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.

277232 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. appLock = 0;
  13907. MessageManager::broadcastMessage (getApplicationName() + "/" + commandLineParameters);
  13908. delete appInstance;
  13909. appInstance = 0;
  13910. DBG ("Another instance is running - quitting...");
  13911. return false;
  13912. }
  13913. }
  13914. #endif
  13915. // let the app do its setting-up..
  13916. initialise (commandLineParameters);
  13917. // register for broadcast new app messages
  13918. MessageManager::getInstance()->registerBroadcastListener (this);
  13919. stillInitialising = false;
  13920. return true;
  13921. }
  13922. int JUCEApplication::shutdownAppAndClearUp()
  13923. {
  13924. jassert (appInstance != 0);
  13925. ScopedPointer<JUCEApplication> app (appInstance);
  13926. int returnValue = 0;
  13927. MessageManager::getInstance()->deregisterBroadcastListener (static_cast <JUCEApplication*> (app));
  13928. static bool reentrancyCheck = false;
  13929. if (! reentrancyCheck)
  13930. {
  13931. reentrancyCheck = true;
  13932. JUCE_TRY
  13933. {
  13934. // give the app a chance to clean up..
  13935. app->shutdown();
  13936. }
  13937. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  13938. catch (const std::exception& e)
  13939. {
  13940. app->unhandledException (&e, __FILE__, __LINE__);
  13941. }
  13942. catch (...)
  13943. {
  13944. app->unhandledException (0, __FILE__, __LINE__);
  13945. }
  13946. #endif
  13947. JUCE_TRY
  13948. {
  13949. shutdownJuce_GUI();
  13950. returnValue = app->getApplicationReturnValue();
  13951. appInstance = 0;
  13952. app = 0;
  13953. }
  13954. JUCE_CATCH_ALL_ASSERT
  13955. reentrancyCheck = false;
  13956. }
  13957. return returnValue;
  13958. }
  13959. #if JUCE_IPHONE
  13960. extern int juce_IPhoneMain (int argc, const char* argv[], JUCEApplication* app);
  13961. #endif
  13962. #if ! JUCE_WINDOWS
  13963. extern const char* juce_Argv0;
  13964. #endif
  13965. int JUCEApplication::main (int argc, const char* argv[], JUCEApplication* const newApp)
  13966. {
  13967. #if ! JUCE_WINDOWS
  13968. juce_Argv0 = argv[0];
  13969. #endif
  13970. #if JUCE_IPHONE
  13971. const ScopedAutoReleasePool pool;
  13972. return juce_IPhoneMain (argc, argv, newApp);
  13973. #else
  13974. #if JUCE_MAC
  13975. const ScopedAutoReleasePool pool;
  13976. #endif
  13977. String cmd;
  13978. for (int i = 1; i < argc; ++i)
  13979. cmd << argv[i] << ' ';
  13980. return JUCEApplication::main (cmd, newApp);
  13981. #endif
  13982. }
  13983. void JUCEApplication::actionListenerCallback (const String& message)
  13984. {
  13985. if (message.startsWith (getApplicationName() + "/"))
  13986. anotherInstanceStarted (message.substring (getApplicationName().length() + 1));
  13987. }
  13988. static bool juceInitialisedGUI = false;
  13989. void JUCE_PUBLIC_FUNCTION initialiseJuce_GUI()
  13990. {
  13991. if (! juceInitialisedGUI)
  13992. {
  13993. #if JUCE_MAC || JUCE_IPHONE
  13994. const ScopedAutoReleasePool pool;
  13995. #endif
  13996. juceInitialisedGUI = true;
  13997. initialiseJuce_NonGUI();
  13998. MessageManager::getInstance();
  13999. LookAndFeel::setDefaultLookAndFeel (0);
  14000. juce_setCurrentThreadName ("Juce Message Thread");
  14001. #if JUCE_WINDOWS && JUCE_DEBUG
  14002. // This section is just for catching people who mess up their project settings and
  14003. // turn RTTI off..
  14004. try
  14005. {
  14006. TextButton tb (String::empty);
  14007. Component* c = &tb;
  14008. // Got an exception here? Then TURN ON RTTI in your compiler settings!!
  14009. c = dynamic_cast <Button*> (c);
  14010. }
  14011. catch (...)
  14012. {
  14013. // Ended up here? If so, TURN ON RTTI in your compiler settings!! And if you
  14014. // got as far as this catch statement, then why haven't you got exception catching
  14015. // turned on in the debugger???
  14016. jassertfalse;
  14017. }
  14018. #endif
  14019. }
  14020. }
  14021. void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI()
  14022. {
  14023. if (juceInitialisedGUI)
  14024. {
  14025. #if JUCE_MAC
  14026. const ScopedAutoReleasePool pool;
  14027. #endif
  14028. {
  14029. DeletedAtShutdown::deleteAll();
  14030. LookAndFeel::clearDefaultLookAndFeel();
  14031. }
  14032. delete MessageManager::getInstance();
  14033. shutdownJuce_NonGUI();
  14034. juceInitialisedGUI = false;
  14035. }
  14036. }
  14037. END_JUCE_NAMESPACE
  14038. /*** End of inlined file: juce_Application.cpp ***/
  14039. /*** Start of inlined file: juce_ApplicationCommandInfo.cpp ***/
  14040. BEGIN_JUCE_NAMESPACE
  14041. ApplicationCommandInfo::ApplicationCommandInfo (const CommandID commandID_) throw()
  14042. : commandID (commandID_),
  14043. flags (0)
  14044. {
  14045. }
  14046. void ApplicationCommandInfo::setInfo (const String& shortName_,
  14047. const String& description_,
  14048. const String& categoryName_,
  14049. const int flags_) throw()
  14050. {
  14051. shortName = shortName_;
  14052. description = description_;
  14053. categoryName = categoryName_;
  14054. flags = flags_;
  14055. }
  14056. void ApplicationCommandInfo::setActive (const bool b) throw()
  14057. {
  14058. if (b)
  14059. flags &= ~isDisabled;
  14060. else
  14061. flags |= isDisabled;
  14062. }
  14063. void ApplicationCommandInfo::setTicked (const bool b) throw()
  14064. {
  14065. if (b)
  14066. flags |= isTicked;
  14067. else
  14068. flags &= ~isTicked;
  14069. }
  14070. void ApplicationCommandInfo::addDefaultKeypress (const int keyCode, const ModifierKeys& modifiers) throw()
  14071. {
  14072. defaultKeypresses.add (KeyPress (keyCode, modifiers, 0));
  14073. }
  14074. END_JUCE_NAMESPACE
  14075. /*** End of inlined file: juce_ApplicationCommandInfo.cpp ***/
  14076. /*** Start of inlined file: juce_ApplicationCommandManager.cpp ***/
  14077. BEGIN_JUCE_NAMESPACE
  14078. ApplicationCommandManager::ApplicationCommandManager()
  14079. : firstTarget (0)
  14080. {
  14081. keyMappings = new KeyPressMappingSet (this);
  14082. Desktop::getInstance().addFocusChangeListener (this);
  14083. }
  14084. ApplicationCommandManager::~ApplicationCommandManager()
  14085. {
  14086. Desktop::getInstance().removeFocusChangeListener (this);
  14087. keyMappings = 0;
  14088. }
  14089. void ApplicationCommandManager::clearCommands()
  14090. {
  14091. commands.clear();
  14092. keyMappings->clearAllKeyPresses();
  14093. triggerAsyncUpdate();
  14094. }
  14095. void ApplicationCommandManager::registerCommand (const ApplicationCommandInfo& newCommand)
  14096. {
  14097. // zero isn't a valid command ID!
  14098. jassert (newCommand.commandID != 0);
  14099. // the name isn't optional!
  14100. jassert (newCommand.shortName.isNotEmpty());
  14101. if (getCommandForID (newCommand.commandID) == 0)
  14102. {
  14103. ApplicationCommandInfo* const newInfo = new ApplicationCommandInfo (newCommand);
  14104. newInfo->flags &= ~ApplicationCommandInfo::isTicked;
  14105. commands.add (newInfo);
  14106. keyMappings->resetToDefaultMapping (newCommand.commandID);
  14107. triggerAsyncUpdate();
  14108. }
  14109. else
  14110. {
  14111. // trying to re-register the same command with different parameters?
  14112. jassert (newCommand.shortName == getCommandForID (newCommand.commandID)->shortName
  14113. && (newCommand.description == getCommandForID (newCommand.commandID)->description || newCommand.description.isEmpty())
  14114. && newCommand.categoryName == getCommandForID (newCommand.commandID)->categoryName
  14115. && newCommand.defaultKeypresses == getCommandForID (newCommand.commandID)->defaultKeypresses
  14116. && (newCommand.flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor))
  14117. == (getCommandForID (newCommand.commandID)->flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor)));
  14118. }
  14119. }
  14120. void ApplicationCommandManager::registerAllCommandsForTarget (ApplicationCommandTarget* target)
  14121. {
  14122. if (target != 0)
  14123. {
  14124. Array <CommandID> commandIDs;
  14125. target->getAllCommands (commandIDs);
  14126. for (int i = 0; i < commandIDs.size(); ++i)
  14127. {
  14128. ApplicationCommandInfo info (commandIDs.getUnchecked(i));
  14129. target->getCommandInfo (info.commandID, info);
  14130. registerCommand (info);
  14131. }
  14132. }
  14133. }
  14134. void ApplicationCommandManager::removeCommand (const CommandID commandID)
  14135. {
  14136. for (int i = commands.size(); --i >= 0;)
  14137. {
  14138. if (commands.getUnchecked (i)->commandID == commandID)
  14139. {
  14140. commands.remove (i);
  14141. triggerAsyncUpdate();
  14142. const Array <KeyPress> keys (keyMappings->getKeyPressesAssignedToCommand (commandID));
  14143. for (int j = keys.size(); --j >= 0;)
  14144. keyMappings->removeKeyPress (keys.getReference (j));
  14145. }
  14146. }
  14147. }
  14148. void ApplicationCommandManager::commandStatusChanged()
  14149. {
  14150. triggerAsyncUpdate();
  14151. }
  14152. const ApplicationCommandInfo* ApplicationCommandManager::getCommandForID (const CommandID commandID) const throw()
  14153. {
  14154. for (int i = commands.size(); --i >= 0;)
  14155. if (commands.getUnchecked(i)->commandID == commandID)
  14156. return commands.getUnchecked(i);
  14157. return 0;
  14158. }
  14159. const String ApplicationCommandManager::getNameOfCommand (const CommandID commandID) const throw()
  14160. {
  14161. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  14162. return (ci != 0) ? ci->shortName : String::empty;
  14163. }
  14164. const String ApplicationCommandManager::getDescriptionOfCommand (const CommandID commandID) const throw()
  14165. {
  14166. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  14167. return (ci != 0) ? (ci->description.isNotEmpty() ? ci->description : ci->shortName)
  14168. : String::empty;
  14169. }
  14170. const StringArray ApplicationCommandManager::getCommandCategories() const throw()
  14171. {
  14172. StringArray s;
  14173. for (int i = 0; i < commands.size(); ++i)
  14174. s.addIfNotAlreadyThere (commands.getUnchecked(i)->categoryName, false);
  14175. return s;
  14176. }
  14177. const Array <CommandID> ApplicationCommandManager::getCommandsInCategory (const String& categoryName) const throw()
  14178. {
  14179. Array <CommandID> results;
  14180. for (int i = 0; i < commands.size(); ++i)
  14181. if (commands.getUnchecked(i)->categoryName == categoryName)
  14182. results.add (commands.getUnchecked(i)->commandID);
  14183. return results;
  14184. }
  14185. bool ApplicationCommandManager::invokeDirectly (const CommandID commandID, const bool asynchronously)
  14186. {
  14187. ApplicationCommandTarget::InvocationInfo info (commandID);
  14188. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  14189. return invoke (info, asynchronously);
  14190. }
  14191. bool ApplicationCommandManager::invoke (const ApplicationCommandTarget::InvocationInfo& info_, const bool asynchronously)
  14192. {
  14193. // This call isn't thread-safe for use from a non-UI thread without locking the message
  14194. // manager first..
  14195. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  14196. ApplicationCommandTarget* const target = getFirstCommandTarget (info_.commandID);
  14197. if (target == 0)
  14198. return false;
  14199. ApplicationCommandInfo commandInfo (0);
  14200. target->getCommandInfo (info_.commandID, commandInfo);
  14201. ApplicationCommandTarget::InvocationInfo info (info_);
  14202. info.commandFlags = commandInfo.flags;
  14203. sendListenerInvokeCallback (info);
  14204. const bool ok = target->invoke (info, asynchronously);
  14205. commandStatusChanged();
  14206. return ok;
  14207. }
  14208. ApplicationCommandTarget* ApplicationCommandManager::getFirstCommandTarget (const CommandID)
  14209. {
  14210. return firstTarget != 0 ? firstTarget
  14211. : findDefaultComponentTarget();
  14212. }
  14213. void ApplicationCommandManager::setFirstCommandTarget (ApplicationCommandTarget* const newTarget) throw()
  14214. {
  14215. firstTarget = newTarget;
  14216. }
  14217. ApplicationCommandTarget* ApplicationCommandManager::getTargetForCommand (const CommandID commandID,
  14218. ApplicationCommandInfo& upToDateInfo)
  14219. {
  14220. ApplicationCommandTarget* target = getFirstCommandTarget (commandID);
  14221. if (target == 0)
  14222. target = JUCEApplication::getInstance();
  14223. if (target != 0)
  14224. target = target->getTargetForCommand (commandID);
  14225. if (target != 0)
  14226. target->getCommandInfo (commandID, upToDateInfo);
  14227. return target;
  14228. }
  14229. ApplicationCommandTarget* ApplicationCommandManager::findTargetForComponent (Component* c)
  14230. {
  14231. ApplicationCommandTarget* target = dynamic_cast <ApplicationCommandTarget*> (c);
  14232. if (target == 0 && c != 0)
  14233. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  14234. target = c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  14235. return target;
  14236. }
  14237. ApplicationCommandTarget* ApplicationCommandManager::findDefaultComponentTarget()
  14238. {
  14239. Component* c = Component::getCurrentlyFocusedComponent();
  14240. if (c == 0)
  14241. {
  14242. TopLevelWindow* const activeWindow = TopLevelWindow::getActiveTopLevelWindow();
  14243. if (activeWindow != 0)
  14244. {
  14245. c = activeWindow->getPeer()->getLastFocusedSubcomponent();
  14246. if (c == 0)
  14247. c = activeWindow;
  14248. }
  14249. }
  14250. if (c == 0 && Process::isForegroundProcess())
  14251. {
  14252. // getting a bit desperate now - try all desktop comps..
  14253. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  14254. {
  14255. ApplicationCommandTarget* const target
  14256. = findTargetForComponent (Desktop::getInstance().getComponent (i)
  14257. ->getPeer()->getLastFocusedSubcomponent());
  14258. if (target != 0)
  14259. return target;
  14260. }
  14261. }
  14262. if (c != 0)
  14263. {
  14264. ResizableWindow* const resizableWindow = dynamic_cast <ResizableWindow*> (c);
  14265. // if we're focused on a ResizableWindow, chances are that it's the content
  14266. // component that really should get the event. And if not, the event will
  14267. // still be passed up to the top level window anyway, so let's send it to the
  14268. // content comp.
  14269. if (resizableWindow != 0 && resizableWindow->getContentComponent() != 0)
  14270. c = resizableWindow->getContentComponent();
  14271. ApplicationCommandTarget* const target = findTargetForComponent (c);
  14272. if (target != 0)
  14273. return target;
  14274. }
  14275. return JUCEApplication::getInstance();
  14276. }
  14277. void ApplicationCommandManager::addListener (ApplicationCommandManagerListener* const listener) throw()
  14278. {
  14279. listeners.add (listener);
  14280. }
  14281. void ApplicationCommandManager::removeListener (ApplicationCommandManagerListener* const listener) throw()
  14282. {
  14283. listeners.remove (listener);
  14284. }
  14285. void ApplicationCommandManager::sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info)
  14286. {
  14287. listeners.call (&ApplicationCommandManagerListener::applicationCommandInvoked, info);
  14288. }
  14289. void ApplicationCommandManager::handleAsyncUpdate()
  14290. {
  14291. listeners.call (&ApplicationCommandManagerListener::applicationCommandListChanged);
  14292. }
  14293. void ApplicationCommandManager::globalFocusChanged (Component*)
  14294. {
  14295. commandStatusChanged();
  14296. }
  14297. END_JUCE_NAMESPACE
  14298. /*** End of inlined file: juce_ApplicationCommandManager.cpp ***/
  14299. /*** Start of inlined file: juce_ApplicationCommandTarget.cpp ***/
  14300. BEGIN_JUCE_NAMESPACE
  14301. ApplicationCommandTarget::ApplicationCommandTarget()
  14302. {
  14303. }
  14304. ApplicationCommandTarget::~ApplicationCommandTarget()
  14305. {
  14306. messageInvoker = 0;
  14307. }
  14308. bool ApplicationCommandTarget::tryToInvoke (const InvocationInfo& info, const bool async)
  14309. {
  14310. if (isCommandActive (info.commandID))
  14311. {
  14312. if (async)
  14313. {
  14314. if (messageInvoker == 0)
  14315. messageInvoker = new CommandTargetMessageInvoker (this);
  14316. messageInvoker->postMessage (new Message (0, 0, 0, new ApplicationCommandTarget::InvocationInfo (info)));
  14317. return true;
  14318. }
  14319. else
  14320. {
  14321. const bool success = perform (info);
  14322. jassert (success); // hmm - your target should have been able to perform this command. If it can't
  14323. // do it at the moment for some reason, it should clear the 'isActive' flag when it
  14324. // returns the command's info.
  14325. return success;
  14326. }
  14327. }
  14328. return false;
  14329. }
  14330. ApplicationCommandTarget* ApplicationCommandTarget::findFirstTargetParentComponent()
  14331. {
  14332. Component* c = dynamic_cast <Component*> (this);
  14333. if (c != 0)
  14334. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  14335. return c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  14336. return 0;
  14337. }
  14338. ApplicationCommandTarget* ApplicationCommandTarget::getTargetForCommand (const CommandID commandID)
  14339. {
  14340. ApplicationCommandTarget* target = this;
  14341. int depth = 0;
  14342. while (target != 0)
  14343. {
  14344. Array <CommandID> commandIDs;
  14345. target->getAllCommands (commandIDs);
  14346. if (commandIDs.contains (commandID))
  14347. return target;
  14348. target = target->getNextCommandTarget();
  14349. ++depth;
  14350. jassert (depth < 100); // could be a recursive command chain??
  14351. jassert (target != this); // definitely a recursive command chain!
  14352. if (depth > 100 || target == this)
  14353. break;
  14354. }
  14355. if (target == 0)
  14356. {
  14357. target = JUCEApplication::getInstance();
  14358. if (target != 0)
  14359. {
  14360. Array <CommandID> commandIDs;
  14361. target->getAllCommands (commandIDs);
  14362. if (commandIDs.contains (commandID))
  14363. return target;
  14364. }
  14365. }
  14366. return 0;
  14367. }
  14368. bool ApplicationCommandTarget::isCommandActive (const CommandID commandID)
  14369. {
  14370. ApplicationCommandInfo info (commandID);
  14371. info.flags = ApplicationCommandInfo::isDisabled;
  14372. getCommandInfo (commandID, info);
  14373. return (info.flags & ApplicationCommandInfo::isDisabled) == 0;
  14374. }
  14375. bool ApplicationCommandTarget::invoke (const InvocationInfo& info, const bool async)
  14376. {
  14377. ApplicationCommandTarget* target = this;
  14378. int depth = 0;
  14379. while (target != 0)
  14380. {
  14381. if (target->tryToInvoke (info, async))
  14382. return true;
  14383. target = target->getNextCommandTarget();
  14384. ++depth;
  14385. jassert (depth < 100); // could be a recursive command chain??
  14386. jassert (target != this); // definitely a recursive command chain!
  14387. if (depth > 100 || target == this)
  14388. break;
  14389. }
  14390. if (target == 0)
  14391. {
  14392. target = JUCEApplication::getInstance();
  14393. if (target != 0)
  14394. return target->tryToInvoke (info, async);
  14395. }
  14396. return false;
  14397. }
  14398. bool ApplicationCommandTarget::invokeDirectly (const CommandID commandID, const bool asynchronously)
  14399. {
  14400. ApplicationCommandTarget::InvocationInfo info (commandID);
  14401. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  14402. return invoke (info, asynchronously);
  14403. }
  14404. ApplicationCommandTarget::InvocationInfo::InvocationInfo (const CommandID commandID_) throw()
  14405. : commandID (commandID_),
  14406. commandFlags (0),
  14407. invocationMethod (direct),
  14408. originatingComponent (0),
  14409. isKeyDown (false),
  14410. millisecsSinceKeyPressed (0)
  14411. {
  14412. }
  14413. ApplicationCommandTarget::CommandTargetMessageInvoker::CommandTargetMessageInvoker (ApplicationCommandTarget* const owner_)
  14414. : owner (owner_)
  14415. {
  14416. }
  14417. ApplicationCommandTarget::CommandTargetMessageInvoker::~CommandTargetMessageInvoker()
  14418. {
  14419. }
  14420. void ApplicationCommandTarget::CommandTargetMessageInvoker::handleMessage (const Message& message)
  14421. {
  14422. const ScopedPointer <InvocationInfo> info (static_cast <InvocationInfo*> (message.pointerParameter));
  14423. owner->tryToInvoke (*info, false);
  14424. }
  14425. END_JUCE_NAMESPACE
  14426. /*** End of inlined file: juce_ApplicationCommandTarget.cpp ***/
  14427. /*** Start of inlined file: juce_ApplicationProperties.cpp ***/
  14428. BEGIN_JUCE_NAMESPACE
  14429. juce_ImplementSingleton (ApplicationProperties)
  14430. ApplicationProperties::ApplicationProperties() throw()
  14431. : msBeforeSaving (3000),
  14432. options (PropertiesFile::storeAsBinary),
  14433. commonSettingsAreReadOnly (0)
  14434. {
  14435. }
  14436. ApplicationProperties::~ApplicationProperties()
  14437. {
  14438. closeFiles();
  14439. clearSingletonInstance();
  14440. }
  14441. void ApplicationProperties::setStorageParameters (const String& applicationName,
  14442. const String& fileNameSuffix,
  14443. const String& folderName_,
  14444. const int millisecondsBeforeSaving,
  14445. const int propertiesFileOptions) throw()
  14446. {
  14447. appName = applicationName;
  14448. fileSuffix = fileNameSuffix;
  14449. folderName = folderName_;
  14450. msBeforeSaving = millisecondsBeforeSaving;
  14451. options = propertiesFileOptions;
  14452. }
  14453. bool ApplicationProperties::testWriteAccess (const bool testUserSettings,
  14454. const bool testCommonSettings,
  14455. const bool showWarningDialogOnFailure)
  14456. {
  14457. const bool userOk = (! testUserSettings) || getUserSettings()->save();
  14458. const bool commonOk = (! testCommonSettings) || getCommonSettings (false)->save();
  14459. if (! (userOk && commonOk))
  14460. {
  14461. if (showWarningDialogOnFailure)
  14462. {
  14463. String filenames;
  14464. if (userProps != 0 && ! userOk)
  14465. filenames << '\n' << userProps->getFile().getFullPathName();
  14466. if (commonProps != 0 && ! commonOk)
  14467. filenames << '\n' << commonProps->getFile().getFullPathName();
  14468. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  14469. appName + TRANS(" - Unable to save settings"),
  14470. TRANS("An error occurred when trying to save the application's settings file...\n\nIn order to save and restore its settings, ")
  14471. + appName + TRANS(" needs to be able to write to the following files:\n")
  14472. + filenames
  14473. + TRANS("\n\nMake sure that these files aren't read-only, and that the disk isn't full."));
  14474. }
  14475. return false;
  14476. }
  14477. return true;
  14478. }
  14479. void ApplicationProperties::openFiles() throw()
  14480. {
  14481. // You need to call setStorageParameters() before trying to get hold of the
  14482. // properties!
  14483. jassert (appName.isNotEmpty());
  14484. if (appName.isNotEmpty())
  14485. {
  14486. if (userProps == 0)
  14487. userProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  14488. false, msBeforeSaving, options);
  14489. if (commonProps == 0)
  14490. commonProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  14491. true, msBeforeSaving, options);
  14492. userProps->setFallbackPropertySet (commonProps);
  14493. }
  14494. }
  14495. PropertiesFile* ApplicationProperties::getUserSettings() throw()
  14496. {
  14497. if (userProps == 0)
  14498. openFiles();
  14499. return userProps;
  14500. }
  14501. PropertiesFile* ApplicationProperties::getCommonSettings (const bool returnUserPropsIfReadOnly) throw()
  14502. {
  14503. if (commonProps == 0)
  14504. openFiles();
  14505. if (returnUserPropsIfReadOnly)
  14506. {
  14507. if (commonSettingsAreReadOnly == 0)
  14508. commonSettingsAreReadOnly = commonProps->save() ? -1 : 1;
  14509. if (commonSettingsAreReadOnly > 0)
  14510. return userProps;
  14511. }
  14512. return commonProps;
  14513. }
  14514. bool ApplicationProperties::saveIfNeeded()
  14515. {
  14516. return (userProps == 0 || userProps->saveIfNeeded())
  14517. && (commonProps == 0 || commonProps->saveIfNeeded());
  14518. }
  14519. void ApplicationProperties::closeFiles()
  14520. {
  14521. userProps = 0;
  14522. commonProps = 0;
  14523. }
  14524. END_JUCE_NAMESPACE
  14525. /*** End of inlined file: juce_ApplicationProperties.cpp ***/
  14526. /*** Start of inlined file: juce_PropertiesFile.cpp ***/
  14527. BEGIN_JUCE_NAMESPACE
  14528. namespace PropertyFileConstants
  14529. {
  14530. static const int magicNumber = (int) ByteOrder::littleEndianInt ("PROP");
  14531. static const int magicNumberCompressed = (int) ByteOrder::littleEndianInt ("CPRP");
  14532. static const char* const fileTag = "PROPERTIES";
  14533. static const char* const valueTag = "VALUE";
  14534. static const char* const nameAttribute = "name";
  14535. static const char* const valueAttribute = "val";
  14536. }
  14537. PropertiesFile::PropertiesFile (const File& f, const int millisecondsBeforeSaving,
  14538. const int options_, InterProcessLock* const processLock_)
  14539. : PropertySet (ignoreCaseOfKeyNames),
  14540. file (f),
  14541. timerInterval (millisecondsBeforeSaving),
  14542. options (options_),
  14543. loadedOk (false),
  14544. needsWriting (false),
  14545. processLock (processLock_)
  14546. {
  14547. // You need to correctly specify just one storage format for the file
  14548. jassert ((options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsBinary
  14549. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsCompressedBinary
  14550. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsXML);
  14551. ProcessScopedLock pl (createProcessLock());
  14552. if (pl != 0 && ! pl->isLocked())
  14553. return; // locking failure..
  14554. ScopedPointer<InputStream> fileStream (f.createInputStream());
  14555. if (fileStream != 0)
  14556. {
  14557. int magicNumber = fileStream->readInt();
  14558. if (magicNumber == PropertyFileConstants::magicNumberCompressed)
  14559. {
  14560. fileStream = new GZIPDecompressorInputStream (new SubregionStream (fileStream.release(), 4, -1, true), true);
  14561. magicNumber = PropertyFileConstants::magicNumber;
  14562. }
  14563. if (magicNumber == PropertyFileConstants::magicNumber)
  14564. {
  14565. loadedOk = true;
  14566. BufferedInputStream in (fileStream.release(), 2048, true);
  14567. int numValues = in.readInt();
  14568. while (--numValues >= 0 && ! in.isExhausted())
  14569. {
  14570. const String key (in.readString());
  14571. const String value (in.readString());
  14572. jassert (key.isNotEmpty());
  14573. if (key.isNotEmpty())
  14574. getAllProperties().set (key, value);
  14575. }
  14576. }
  14577. else
  14578. {
  14579. // Not a binary props file - let's see if it's XML..
  14580. fileStream = 0;
  14581. XmlDocument parser (f);
  14582. ScopedPointer<XmlElement> doc (parser.getDocumentElement (true));
  14583. if (doc != 0 && doc->hasTagName (PropertyFileConstants::fileTag))
  14584. {
  14585. doc = parser.getDocumentElement();
  14586. if (doc != 0)
  14587. {
  14588. loadedOk = true;
  14589. forEachXmlChildElementWithTagName (*doc, e, PropertyFileConstants::valueTag)
  14590. {
  14591. const String name (e->getStringAttribute (PropertyFileConstants::nameAttribute));
  14592. if (name.isNotEmpty())
  14593. {
  14594. getAllProperties().set (name,
  14595. e->getFirstChildElement() != 0
  14596. ? e->getFirstChildElement()->createDocument (String::empty, true)
  14597. : e->getStringAttribute (PropertyFileConstants::valueAttribute));
  14598. }
  14599. }
  14600. }
  14601. else
  14602. {
  14603. // must be a pretty broken XML file we're trying to parse here,
  14604. // or a sign that this object needs an InterProcessLock,
  14605. // or just a failure reading the file. This last reason is why
  14606. // we don't jassertfalse here.
  14607. }
  14608. }
  14609. }
  14610. }
  14611. else
  14612. {
  14613. loadedOk = ! f.exists();
  14614. }
  14615. }
  14616. PropertiesFile::~PropertiesFile()
  14617. {
  14618. if (! saveIfNeeded())
  14619. jassertfalse;
  14620. }
  14621. InterProcessLock::ScopedLockType* PropertiesFile::createProcessLock() const
  14622. {
  14623. return processLock != 0 ? new InterProcessLock::ScopedLockType (*processLock) : 0;
  14624. }
  14625. bool PropertiesFile::saveIfNeeded()
  14626. {
  14627. const ScopedLock sl (getLock());
  14628. return (! needsWriting) || save();
  14629. }
  14630. bool PropertiesFile::needsToBeSaved() const
  14631. {
  14632. const ScopedLock sl (getLock());
  14633. return needsWriting;
  14634. }
  14635. void PropertiesFile::setNeedsToBeSaved (const bool needsToBeSaved_)
  14636. {
  14637. const ScopedLock sl (getLock());
  14638. needsWriting = needsToBeSaved_;
  14639. }
  14640. bool PropertiesFile::save()
  14641. {
  14642. const ScopedLock sl (getLock());
  14643. stopTimer();
  14644. if (file == File::nonexistent
  14645. || file.isDirectory()
  14646. || ! file.getParentDirectory().createDirectory())
  14647. return false;
  14648. if ((options & storeAsXML) != 0)
  14649. {
  14650. XmlElement doc (PropertyFileConstants::fileTag);
  14651. for (int i = 0; i < getAllProperties().size(); ++i)
  14652. {
  14653. XmlElement* const e = doc.createNewChildElement (PropertyFileConstants::valueTag);
  14654. e->setAttribute (PropertyFileConstants::nameAttribute, getAllProperties().getAllKeys() [i]);
  14655. // if the value seems to contain xml, store it as such..
  14656. XmlDocument xmlContent (getAllProperties().getAllValues() [i]);
  14657. XmlElement* const childElement = xmlContent.getDocumentElement();
  14658. if (childElement != 0)
  14659. e->addChildElement (childElement);
  14660. else
  14661. e->setAttribute (PropertyFileConstants::valueAttribute,
  14662. getAllProperties().getAllValues() [i]);
  14663. }
  14664. ProcessScopedLock pl (createProcessLock());
  14665. if (pl != 0 && ! pl->isLocked())
  14666. return false; // locking failure..
  14667. if (doc.writeToFile (file, String::empty))
  14668. {
  14669. needsWriting = false;
  14670. return true;
  14671. }
  14672. }
  14673. else
  14674. {
  14675. ProcessScopedLock pl (createProcessLock());
  14676. if (pl != 0 && ! pl->isLocked())
  14677. return false; // locking failure..
  14678. TemporaryFile tempFile (file);
  14679. ScopedPointer <OutputStream> out (tempFile.getFile().createOutputStream());
  14680. if (out != 0)
  14681. {
  14682. if ((options & storeAsCompressedBinary) != 0)
  14683. {
  14684. out->writeInt (PropertyFileConstants::magicNumberCompressed);
  14685. out->flush();
  14686. out = new GZIPCompressorOutputStream (out.release(), 9, true);
  14687. }
  14688. else
  14689. {
  14690. // have you set up the storage option flags correctly?
  14691. jassert ((options & storeAsBinary) != 0);
  14692. out->writeInt (PropertyFileConstants::magicNumber);
  14693. }
  14694. const int numProperties = getAllProperties().size();
  14695. out->writeInt (numProperties);
  14696. for (int i = 0; i < numProperties; ++i)
  14697. {
  14698. out->writeString (getAllProperties().getAllKeys() [i]);
  14699. out->writeString (getAllProperties().getAllValues() [i]);
  14700. }
  14701. out = 0;
  14702. if (tempFile.overwriteTargetFileWithTemporary())
  14703. {
  14704. needsWriting = false;
  14705. return true;
  14706. }
  14707. }
  14708. }
  14709. return false;
  14710. }
  14711. void PropertiesFile::timerCallback()
  14712. {
  14713. saveIfNeeded();
  14714. }
  14715. void PropertiesFile::propertyChanged()
  14716. {
  14717. sendChangeMessage (this);
  14718. needsWriting = true;
  14719. if (timerInterval > 0)
  14720. startTimer (timerInterval);
  14721. else if (timerInterval == 0)
  14722. saveIfNeeded();
  14723. }
  14724. const File PropertiesFile::getDefaultAppSettingsFile (const String& applicationName,
  14725. const String& fileNameSuffix,
  14726. const String& folderName,
  14727. const bool commonToAllUsers)
  14728. {
  14729. // mustn't have illegal characters in this name..
  14730. jassert (applicationName == File::createLegalFileName (applicationName));
  14731. #if JUCE_MAC || JUCE_IPHONE
  14732. File dir (commonToAllUsers ? "/Library/Preferences"
  14733. : "~/Library/Preferences");
  14734. if (folderName.isNotEmpty())
  14735. dir = dir.getChildFile (folderName);
  14736. #endif
  14737. #ifdef JUCE_LINUX
  14738. const File dir ((commonToAllUsers ? "/var/" : "~/")
  14739. + (folderName.isNotEmpty() ? folderName
  14740. : ("." + applicationName)));
  14741. #endif
  14742. #if JUCE_WINDOWS
  14743. File dir (File::getSpecialLocation (commonToAllUsers ? File::commonApplicationDataDirectory
  14744. : File::userApplicationDataDirectory));
  14745. if (dir == File::nonexistent)
  14746. return File::nonexistent;
  14747. dir = dir.getChildFile (folderName.isNotEmpty() ? folderName
  14748. : applicationName);
  14749. #endif
  14750. return dir.getChildFile (applicationName)
  14751. .withFileExtension (fileNameSuffix);
  14752. }
  14753. PropertiesFile* PropertiesFile::createDefaultAppPropertiesFile (const String& applicationName,
  14754. const String& fileNameSuffix,
  14755. const String& folderName,
  14756. const bool commonToAllUsers,
  14757. const int millisecondsBeforeSaving,
  14758. const int propertiesFileOptions,
  14759. InterProcessLock* processLock_)
  14760. {
  14761. const File file (getDefaultAppSettingsFile (applicationName,
  14762. fileNameSuffix,
  14763. folderName,
  14764. commonToAllUsers));
  14765. jassert (file != File::nonexistent);
  14766. if (file == File::nonexistent)
  14767. return 0;
  14768. return new PropertiesFile (file, millisecondsBeforeSaving, propertiesFileOptions,processLock_);
  14769. }
  14770. END_JUCE_NAMESPACE
  14771. /*** End of inlined file: juce_PropertiesFile.cpp ***/
  14772. /*** Start of inlined file: juce_FileBasedDocument.cpp ***/
  14773. BEGIN_JUCE_NAMESPACE
  14774. FileBasedDocument::FileBasedDocument (const String& fileExtension_,
  14775. const String& fileWildcard_,
  14776. const String& openFileDialogTitle_,
  14777. const String& saveFileDialogTitle_)
  14778. : changedSinceSave (false),
  14779. fileExtension (fileExtension_),
  14780. fileWildcard (fileWildcard_),
  14781. openFileDialogTitle (openFileDialogTitle_),
  14782. saveFileDialogTitle (saveFileDialogTitle_)
  14783. {
  14784. }
  14785. FileBasedDocument::~FileBasedDocument()
  14786. {
  14787. }
  14788. void FileBasedDocument::setChangedFlag (const bool hasChanged)
  14789. {
  14790. if (changedSinceSave != hasChanged)
  14791. {
  14792. changedSinceSave = hasChanged;
  14793. sendChangeMessage (this);
  14794. }
  14795. }
  14796. void FileBasedDocument::changed()
  14797. {
  14798. changedSinceSave = true;
  14799. sendChangeMessage (this);
  14800. }
  14801. void FileBasedDocument::setFile (const File& newFile)
  14802. {
  14803. if (documentFile != newFile)
  14804. {
  14805. documentFile = newFile;
  14806. changed();
  14807. }
  14808. }
  14809. bool FileBasedDocument::loadFrom (const File& newFile,
  14810. const bool showMessageOnFailure)
  14811. {
  14812. MouseCursor::showWaitCursor();
  14813. const File oldFile (documentFile);
  14814. documentFile = newFile;
  14815. String error;
  14816. if (newFile.existsAsFile())
  14817. {
  14818. error = loadDocument (newFile);
  14819. if (error.isEmpty())
  14820. {
  14821. setChangedFlag (false);
  14822. MouseCursor::hideWaitCursor();
  14823. setLastDocumentOpened (newFile);
  14824. return true;
  14825. }
  14826. }
  14827. else
  14828. {
  14829. error = "The file doesn't exist";
  14830. }
  14831. documentFile = oldFile;
  14832. MouseCursor::hideWaitCursor();
  14833. if (showMessageOnFailure)
  14834. {
  14835. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  14836. TRANS("Failed to open file..."),
  14837. TRANS("There was an error while trying to load the file:\n\n")
  14838. + newFile.getFullPathName()
  14839. + "\n\n"
  14840. + error);
  14841. }
  14842. return false;
  14843. }
  14844. bool FileBasedDocument::loadFromUserSpecifiedFile (const bool showMessageOnFailure)
  14845. {
  14846. FileChooser fc (openFileDialogTitle,
  14847. getLastDocumentOpened(),
  14848. fileWildcard);
  14849. if (fc.browseForFileToOpen())
  14850. return loadFrom (fc.getResult(), showMessageOnFailure);
  14851. return false;
  14852. }
  14853. FileBasedDocument::SaveResult FileBasedDocument::save (const bool askUserForFileIfNotSpecified,
  14854. const bool showMessageOnFailure)
  14855. {
  14856. return saveAs (documentFile,
  14857. false,
  14858. askUserForFileIfNotSpecified,
  14859. showMessageOnFailure);
  14860. }
  14861. FileBasedDocument::SaveResult FileBasedDocument::saveAs (const File& newFile,
  14862. const bool warnAboutOverwritingExistingFiles,
  14863. const bool askUserForFileIfNotSpecified,
  14864. const bool showMessageOnFailure)
  14865. {
  14866. if (newFile == File::nonexistent)
  14867. {
  14868. if (askUserForFileIfNotSpecified)
  14869. {
  14870. return saveAsInteractive (true);
  14871. }
  14872. else
  14873. {
  14874. // can't save to an unspecified file
  14875. jassertfalse;
  14876. return failedToWriteToFile;
  14877. }
  14878. }
  14879. if (warnAboutOverwritingExistingFiles && newFile.exists())
  14880. {
  14881. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  14882. TRANS("File already exists"),
  14883. TRANS("There's already a file called:\n\n")
  14884. + newFile.getFullPathName()
  14885. + TRANS("\n\nAre you sure you want to overwrite it?"),
  14886. TRANS("overwrite"),
  14887. TRANS("cancel")))
  14888. {
  14889. return userCancelledSave;
  14890. }
  14891. }
  14892. MouseCursor::showWaitCursor();
  14893. const File oldFile (documentFile);
  14894. documentFile = newFile;
  14895. String error (saveDocument (newFile));
  14896. if (error.isEmpty())
  14897. {
  14898. setChangedFlag (false);
  14899. MouseCursor::hideWaitCursor();
  14900. return savedOk;
  14901. }
  14902. documentFile = oldFile;
  14903. MouseCursor::hideWaitCursor();
  14904. if (showMessageOnFailure)
  14905. {
  14906. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  14907. TRANS("Error writing to file..."),
  14908. TRANS("An error occurred while trying to save \"")
  14909. + getDocumentTitle()
  14910. + TRANS("\" to the file:\n\n")
  14911. + newFile.getFullPathName()
  14912. + "\n\n"
  14913. + error);
  14914. }
  14915. return failedToWriteToFile;
  14916. }
  14917. FileBasedDocument::SaveResult FileBasedDocument::saveIfNeededAndUserAgrees()
  14918. {
  14919. if (! hasChangedSinceSaved())
  14920. return savedOk;
  14921. const int r = AlertWindow::showYesNoCancelBox (AlertWindow::QuestionIcon,
  14922. TRANS("Closing document..."),
  14923. TRANS("Do you want to save the changes to \"")
  14924. + getDocumentTitle() + "\"?",
  14925. TRANS("save"),
  14926. TRANS("discard changes"),
  14927. TRANS("cancel"));
  14928. if (r == 1)
  14929. {
  14930. // save changes
  14931. return save (true, true);
  14932. }
  14933. else if (r == 2)
  14934. {
  14935. // discard changes
  14936. return savedOk;
  14937. }
  14938. return userCancelledSave;
  14939. }
  14940. FileBasedDocument::SaveResult FileBasedDocument::saveAsInteractive (const bool warnAboutOverwritingExistingFiles)
  14941. {
  14942. File f;
  14943. if (documentFile.existsAsFile())
  14944. f = documentFile;
  14945. else
  14946. f = getLastDocumentOpened();
  14947. String legalFilename (File::createLegalFileName (getDocumentTitle()));
  14948. if (legalFilename.isEmpty())
  14949. legalFilename = "unnamed";
  14950. if (f.existsAsFile() || f.getParentDirectory().isDirectory())
  14951. f = f.getSiblingFile (legalFilename);
  14952. else
  14953. f = File::getSpecialLocation (File::userDocumentsDirectory).getChildFile (legalFilename);
  14954. f = f.withFileExtension (fileExtension)
  14955. .getNonexistentSibling (true);
  14956. FileChooser fc (saveFileDialogTitle, f, fileWildcard);
  14957. if (fc.browseForFileToSave (warnAboutOverwritingExistingFiles))
  14958. {
  14959. setLastDocumentOpened (fc.getResult());
  14960. File chosen (fc.getResult());
  14961. if (chosen.getFileExtension().isEmpty())
  14962. {
  14963. chosen = chosen.withFileExtension (fileExtension);
  14964. if (chosen.exists())
  14965. {
  14966. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  14967. TRANS("File already exists"),
  14968. TRANS("There's already a file called:")
  14969. + "\n\n" + chosen.getFullPathName()
  14970. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  14971. TRANS("overwrite"),
  14972. TRANS("cancel")))
  14973. {
  14974. return userCancelledSave;
  14975. }
  14976. }
  14977. }
  14978. return saveAs (chosen, false, false, true);
  14979. }
  14980. return userCancelledSave;
  14981. }
  14982. END_JUCE_NAMESPACE
  14983. /*** End of inlined file: juce_FileBasedDocument.cpp ***/
  14984. /*** Start of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  14985. BEGIN_JUCE_NAMESPACE
  14986. RecentlyOpenedFilesList::RecentlyOpenedFilesList()
  14987. : maxNumberOfItems (10)
  14988. {
  14989. }
  14990. RecentlyOpenedFilesList::~RecentlyOpenedFilesList()
  14991. {
  14992. }
  14993. void RecentlyOpenedFilesList::setMaxNumberOfItems (const int newMaxNumber)
  14994. {
  14995. maxNumberOfItems = jmax (1, newMaxNumber);
  14996. while (getNumFiles() > maxNumberOfItems)
  14997. files.remove (getNumFiles() - 1);
  14998. }
  14999. int RecentlyOpenedFilesList::getNumFiles() const
  15000. {
  15001. return files.size();
  15002. }
  15003. const File RecentlyOpenedFilesList::getFile (const int index) const
  15004. {
  15005. return File (files [index]);
  15006. }
  15007. void RecentlyOpenedFilesList::clear()
  15008. {
  15009. files.clear();
  15010. }
  15011. void RecentlyOpenedFilesList::addFile (const File& file)
  15012. {
  15013. const String path (file.getFullPathName());
  15014. files.removeString (path, true);
  15015. files.insert (0, path);
  15016. setMaxNumberOfItems (maxNumberOfItems);
  15017. }
  15018. void RecentlyOpenedFilesList::removeNonExistentFiles()
  15019. {
  15020. for (int i = getNumFiles(); --i >= 0;)
  15021. if (! getFile(i).exists())
  15022. files.remove (i);
  15023. }
  15024. int RecentlyOpenedFilesList::createPopupMenuItems (PopupMenu& menuToAddTo,
  15025. const int baseItemId,
  15026. const bool showFullPaths,
  15027. const bool dontAddNonExistentFiles,
  15028. const File** filesToAvoid)
  15029. {
  15030. int num = 0;
  15031. for (int i = 0; i < getNumFiles(); ++i)
  15032. {
  15033. const File f (getFile(i));
  15034. if ((! dontAddNonExistentFiles) || f.exists())
  15035. {
  15036. bool needsAvoiding = false;
  15037. if (filesToAvoid != 0)
  15038. {
  15039. const File** avoid = filesToAvoid;
  15040. while (*avoid != 0)
  15041. {
  15042. if (f == **avoid)
  15043. {
  15044. needsAvoiding = true;
  15045. break;
  15046. }
  15047. ++avoid;
  15048. }
  15049. }
  15050. if (! needsAvoiding)
  15051. {
  15052. menuToAddTo.addItem (baseItemId + i,
  15053. showFullPaths ? f.getFullPathName()
  15054. : f.getFileName());
  15055. ++num;
  15056. }
  15057. }
  15058. }
  15059. return num;
  15060. }
  15061. const String RecentlyOpenedFilesList::toString() const
  15062. {
  15063. return files.joinIntoString ("\n");
  15064. }
  15065. void RecentlyOpenedFilesList::restoreFromString (const String& stringifiedVersion)
  15066. {
  15067. clear();
  15068. files.addLines (stringifiedVersion);
  15069. setMaxNumberOfItems (maxNumberOfItems);
  15070. }
  15071. END_JUCE_NAMESPACE
  15072. /*** End of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  15073. /*** Start of inlined file: juce_UndoManager.cpp ***/
  15074. BEGIN_JUCE_NAMESPACE
  15075. UndoManager::UndoManager (const int maxNumberOfUnitsToKeep,
  15076. const int minimumTransactions)
  15077. : totalUnitsStored (0),
  15078. nextIndex (0),
  15079. newTransaction (true),
  15080. reentrancyCheck (false)
  15081. {
  15082. setMaxNumberOfStoredUnits (maxNumberOfUnitsToKeep,
  15083. minimumTransactions);
  15084. }
  15085. UndoManager::~UndoManager()
  15086. {
  15087. clearUndoHistory();
  15088. }
  15089. void UndoManager::clearUndoHistory()
  15090. {
  15091. transactions.clear();
  15092. transactionNames.clear();
  15093. totalUnitsStored = 0;
  15094. nextIndex = 0;
  15095. sendChangeMessage (this);
  15096. }
  15097. int UndoManager::getNumberOfUnitsTakenUpByStoredCommands() const
  15098. {
  15099. return totalUnitsStored;
  15100. }
  15101. void UndoManager::setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  15102. const int minimumTransactions)
  15103. {
  15104. maxNumUnitsToKeep = jmax (1, maxNumberOfUnitsToKeep);
  15105. minimumTransactionsToKeep = jmax (1, minimumTransactions);
  15106. }
  15107. bool UndoManager::perform (UndoableAction* const command_, const String& actionName)
  15108. {
  15109. if (command_ != 0)
  15110. {
  15111. ScopedPointer<UndoableAction> command (command_);
  15112. if (actionName.isNotEmpty())
  15113. currentTransactionName = actionName;
  15114. if (reentrancyCheck)
  15115. {
  15116. jassertfalse; // don't call perform() recursively from the UndoableAction::perform() or
  15117. // undo() methods, or else these actions won't actually get done.
  15118. return false;
  15119. }
  15120. else if (command->perform())
  15121. {
  15122. OwnedArray<UndoableAction>* commandSet = transactions [nextIndex - 1];
  15123. if (commandSet != 0 && ! newTransaction)
  15124. {
  15125. UndoableAction* lastAction = commandSet->getLast();
  15126. if (lastAction != 0)
  15127. {
  15128. UndoableAction* coalescedAction = lastAction->createCoalescedAction (command);
  15129. if (coalescedAction != 0)
  15130. {
  15131. command = coalescedAction;
  15132. totalUnitsStored -= lastAction->getSizeInUnits();
  15133. commandSet->removeLast();
  15134. }
  15135. }
  15136. }
  15137. else
  15138. {
  15139. commandSet = new OwnedArray<UndoableAction>();
  15140. transactions.insert (nextIndex, commandSet);
  15141. transactionNames.insert (nextIndex, currentTransactionName);
  15142. ++nextIndex;
  15143. }
  15144. totalUnitsStored += command->getSizeInUnits();
  15145. commandSet->add (command.release());
  15146. newTransaction = false;
  15147. while (nextIndex < transactions.size())
  15148. {
  15149. const OwnedArray <UndoableAction>* const lastSet = transactions.getLast();
  15150. for (int i = lastSet->size(); --i >= 0;)
  15151. totalUnitsStored -= lastSet->getUnchecked (i)->getSizeInUnits();
  15152. transactions.removeLast();
  15153. transactionNames.remove (transactionNames.size() - 1);
  15154. }
  15155. while (nextIndex > 0
  15156. && totalUnitsStored > maxNumUnitsToKeep
  15157. && transactions.size() > minimumTransactionsToKeep)
  15158. {
  15159. const OwnedArray <UndoableAction>* const firstSet = transactions.getFirst();
  15160. for (int i = firstSet->size(); --i >= 0;)
  15161. totalUnitsStored -= firstSet->getUnchecked (i)->getSizeInUnits();
  15162. jassert (totalUnitsStored >= 0); // something fishy going on if this fails!
  15163. transactions.remove (0);
  15164. transactionNames.remove (0);
  15165. --nextIndex;
  15166. }
  15167. sendChangeMessage (this);
  15168. return true;
  15169. }
  15170. }
  15171. return false;
  15172. }
  15173. void UndoManager::beginNewTransaction (const String& actionName)
  15174. {
  15175. newTransaction = true;
  15176. currentTransactionName = actionName;
  15177. }
  15178. void UndoManager::setCurrentTransactionName (const String& newName)
  15179. {
  15180. currentTransactionName = newName;
  15181. }
  15182. bool UndoManager::canUndo() const
  15183. {
  15184. return nextIndex > 0;
  15185. }
  15186. bool UndoManager::canRedo() const
  15187. {
  15188. return nextIndex < transactions.size();
  15189. }
  15190. const String UndoManager::getUndoDescription() const
  15191. {
  15192. return transactionNames [nextIndex - 1];
  15193. }
  15194. const String UndoManager::getRedoDescription() const
  15195. {
  15196. return transactionNames [nextIndex];
  15197. }
  15198. bool UndoManager::undo()
  15199. {
  15200. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex - 1];
  15201. if (commandSet == 0)
  15202. return false;
  15203. reentrancyCheck = true;
  15204. bool failed = false;
  15205. for (int i = commandSet->size(); --i >= 0;)
  15206. {
  15207. if (! commandSet->getUnchecked(i)->undo())
  15208. {
  15209. jassertfalse;
  15210. failed = true;
  15211. break;
  15212. }
  15213. }
  15214. reentrancyCheck = false;
  15215. if (failed)
  15216. clearUndoHistory();
  15217. else
  15218. --nextIndex;
  15219. beginNewTransaction();
  15220. sendChangeMessage (this);
  15221. return true;
  15222. }
  15223. bool UndoManager::redo()
  15224. {
  15225. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex];
  15226. if (commandSet == 0)
  15227. return false;
  15228. reentrancyCheck = true;
  15229. bool failed = false;
  15230. for (int i = 0; i < commandSet->size(); ++i)
  15231. {
  15232. if (! commandSet->getUnchecked(i)->perform())
  15233. {
  15234. jassertfalse;
  15235. failed = true;
  15236. break;
  15237. }
  15238. }
  15239. reentrancyCheck = false;
  15240. if (failed)
  15241. clearUndoHistory();
  15242. else
  15243. ++nextIndex;
  15244. beginNewTransaction();
  15245. sendChangeMessage (this);
  15246. return true;
  15247. }
  15248. bool UndoManager::undoCurrentTransactionOnly()
  15249. {
  15250. return newTransaction ? false : undo();
  15251. }
  15252. void UndoManager::getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const
  15253. {
  15254. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  15255. if (commandSet != 0 && ! newTransaction)
  15256. {
  15257. for (int i = 0; i < commandSet->size(); ++i)
  15258. actionsFound.add (commandSet->getUnchecked(i));
  15259. }
  15260. }
  15261. int UndoManager::getNumActionsInCurrentTransaction() const
  15262. {
  15263. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  15264. if (commandSet != 0 && ! newTransaction)
  15265. return commandSet->size();
  15266. return 0;
  15267. }
  15268. END_JUCE_NAMESPACE
  15269. /*** End of inlined file: juce_UndoManager.cpp ***/
  15270. /*** Start of inlined file: juce_AiffAudioFormat.cpp ***/
  15271. BEGIN_JUCE_NAMESPACE
  15272. static const char* const aiffFormatName = "AIFF file";
  15273. static const char* const aiffExtensions[] = { ".aiff", ".aif", 0 };
  15274. class AiffAudioFormatReader : public AudioFormatReader
  15275. {
  15276. public:
  15277. int bytesPerFrame;
  15278. int64 dataChunkStart;
  15279. bool littleEndian;
  15280. AiffAudioFormatReader (InputStream* in)
  15281. : AudioFormatReader (in, TRANS (aiffFormatName))
  15282. {
  15283. if (input->readInt() == chunkName ("FORM"))
  15284. {
  15285. const int len = input->readIntBigEndian();
  15286. const int64 end = input->getPosition() + len;
  15287. const int nextType = input->readInt();
  15288. if (nextType == chunkName ("AIFF") || nextType == chunkName ("AIFC"))
  15289. {
  15290. bool hasGotVer = false;
  15291. bool hasGotData = false;
  15292. bool hasGotType = false;
  15293. while (input->getPosition() < end)
  15294. {
  15295. const int type = input->readInt();
  15296. const uint32 length = (uint32) input->readIntBigEndian();
  15297. const int64 chunkEnd = input->getPosition() + length;
  15298. if (type == chunkName ("FVER"))
  15299. {
  15300. hasGotVer = true;
  15301. const int ver = input->readIntBigEndian();
  15302. if (ver != 0 && ver != (int)0xa2805140)
  15303. break;
  15304. }
  15305. else if (type == chunkName ("COMM"))
  15306. {
  15307. hasGotType = true;
  15308. numChannels = (unsigned int)input->readShortBigEndian();
  15309. lengthInSamples = input->readIntBigEndian();
  15310. bitsPerSample = input->readShortBigEndian();
  15311. bytesPerFrame = (numChannels * bitsPerSample) >> 3;
  15312. unsigned char sampleRateBytes[10];
  15313. input->read (sampleRateBytes, 10);
  15314. const int byte0 = sampleRateBytes[0];
  15315. if ((byte0 & 0x80) != 0
  15316. || byte0 <= 0x3F || byte0 > 0x40
  15317. || (byte0 == 0x40 && sampleRateBytes[1] > 0x1C))
  15318. break;
  15319. unsigned int sampRate = ByteOrder::bigEndianInt (sampleRateBytes + 2);
  15320. sampRate >>= (16414 - ByteOrder::bigEndianShort (sampleRateBytes));
  15321. sampleRate = (int) sampRate;
  15322. if (length <= 18)
  15323. {
  15324. // some types don't have a chunk large enough to include a compression
  15325. // type, so assume it's just big-endian pcm
  15326. littleEndian = false;
  15327. }
  15328. else
  15329. {
  15330. const int compType = input->readInt();
  15331. if (compType == chunkName ("NONE") || compType == chunkName ("twos"))
  15332. {
  15333. littleEndian = false;
  15334. }
  15335. else if (compType == chunkName ("sowt"))
  15336. {
  15337. littleEndian = true;
  15338. }
  15339. else
  15340. {
  15341. sampleRate = 0;
  15342. break;
  15343. }
  15344. }
  15345. }
  15346. else if (type == chunkName ("SSND"))
  15347. {
  15348. hasGotData = true;
  15349. const int offset = input->readIntBigEndian();
  15350. dataChunkStart = input->getPosition() + 4 + offset;
  15351. lengthInSamples = (bytesPerFrame > 0) ? jmin (lengthInSamples, (int64) (length / bytesPerFrame)) : 0;
  15352. }
  15353. else if ((hasGotVer && hasGotData && hasGotType)
  15354. || chunkEnd < input->getPosition()
  15355. || input->isExhausted())
  15356. {
  15357. break;
  15358. }
  15359. input->setPosition (chunkEnd);
  15360. }
  15361. }
  15362. }
  15363. }
  15364. ~AiffAudioFormatReader()
  15365. {
  15366. }
  15367. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  15368. int64 startSampleInFile, int numSamples)
  15369. {
  15370. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  15371. if (samplesAvailable < numSamples)
  15372. {
  15373. for (int i = numDestChannels; --i >= 0;)
  15374. if (destSamples[i] != 0)
  15375. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  15376. numSamples = (int) samplesAvailable;
  15377. }
  15378. if (numSamples <= 0)
  15379. return true;
  15380. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  15381. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  15382. char tempBuffer [tempBufSize];
  15383. while (numSamples > 0)
  15384. {
  15385. int* left = destSamples[0];
  15386. if (left != 0)
  15387. left += startOffsetInDestBuffer;
  15388. int* right = numDestChannels > 1 ? destSamples[1] : 0;
  15389. if (right != 0)
  15390. right += startOffsetInDestBuffer;
  15391. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  15392. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  15393. if (bytesRead < numThisTime * bytesPerFrame)
  15394. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  15395. if (bitsPerSample == 16)
  15396. {
  15397. if (littleEndian)
  15398. {
  15399. const short* src = reinterpret_cast <const short*> (tempBuffer);
  15400. if (numChannels > 1)
  15401. {
  15402. if (left == 0)
  15403. {
  15404. for (int i = numThisTime; --i >= 0;)
  15405. {
  15406. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15407. ++src;
  15408. }
  15409. }
  15410. else if (right == 0)
  15411. {
  15412. for (int i = numThisTime; --i >= 0;)
  15413. {
  15414. ++src;
  15415. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15416. }
  15417. }
  15418. else
  15419. {
  15420. for (int i = numThisTime; --i >= 0;)
  15421. {
  15422. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15423. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15424. }
  15425. }
  15426. }
  15427. else
  15428. {
  15429. for (int i = numThisTime; --i >= 0;)
  15430. {
  15431. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15432. }
  15433. }
  15434. }
  15435. else
  15436. {
  15437. const char* src = tempBuffer;
  15438. if (numChannels > 1)
  15439. {
  15440. if (left == 0)
  15441. {
  15442. for (int i = numThisTime; --i >= 0;)
  15443. {
  15444. *right++ = ByteOrder::bigEndianShort (src) << 16;
  15445. src += 4;
  15446. }
  15447. }
  15448. else if (right == 0)
  15449. {
  15450. for (int i = numThisTime; --i >= 0;)
  15451. {
  15452. src += 2;
  15453. *left++ = ByteOrder::bigEndianShort (src) << 16;
  15454. src += 2;
  15455. }
  15456. }
  15457. else
  15458. {
  15459. for (int i = numThisTime; --i >= 0;)
  15460. {
  15461. *left++ = ByteOrder::bigEndianShort (src) << 16;
  15462. src += 2;
  15463. *right++ = ByteOrder::bigEndianShort (src) << 16;
  15464. src += 2;
  15465. }
  15466. }
  15467. }
  15468. else
  15469. {
  15470. for (int i = numThisTime; --i >= 0;)
  15471. {
  15472. *left++ = ByteOrder::bigEndianShort (src) << 16;
  15473. src += 2;
  15474. }
  15475. }
  15476. }
  15477. }
  15478. else if (bitsPerSample == 24)
  15479. {
  15480. const char* src = (const char*)tempBuffer;
  15481. if (littleEndian)
  15482. {
  15483. if (numChannels > 1)
  15484. {
  15485. if (left == 0)
  15486. {
  15487. for (int i = numThisTime; --i >= 0;)
  15488. {
  15489. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  15490. src += 6;
  15491. }
  15492. }
  15493. else if (right == 0)
  15494. {
  15495. for (int i = numThisTime; --i >= 0;)
  15496. {
  15497. src += 3;
  15498. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  15499. src += 3;
  15500. }
  15501. }
  15502. else
  15503. {
  15504. for (int i = numThisTime; --i >= 0;)
  15505. {
  15506. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  15507. src += 3;
  15508. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  15509. src += 3;
  15510. }
  15511. }
  15512. }
  15513. else
  15514. {
  15515. for (int i = numThisTime; --i >= 0;)
  15516. {
  15517. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  15518. src += 3;
  15519. }
  15520. }
  15521. }
  15522. else
  15523. {
  15524. if (numChannels > 1)
  15525. {
  15526. if (left == 0)
  15527. {
  15528. for (int i = numThisTime; --i >= 0;)
  15529. {
  15530. *right++ = ByteOrder::bigEndian24Bit (src) << 8;
  15531. src += 6;
  15532. }
  15533. }
  15534. else if (right == 0)
  15535. {
  15536. for (int i = numThisTime; --i >= 0;)
  15537. {
  15538. src += 3;
  15539. *left++ = ByteOrder::bigEndian24Bit (src) << 8;
  15540. src += 3;
  15541. }
  15542. }
  15543. else
  15544. {
  15545. for (int i = numThisTime; --i >= 0;)
  15546. {
  15547. *left++ = ByteOrder::bigEndian24Bit (src) << 8;
  15548. src += 3;
  15549. *right++ = ByteOrder::bigEndian24Bit (src) << 8;
  15550. src += 3;
  15551. }
  15552. }
  15553. }
  15554. else
  15555. {
  15556. for (int i = numThisTime; --i >= 0;)
  15557. {
  15558. *left++ = ByteOrder::bigEndian24Bit (src) << 8;
  15559. src += 3;
  15560. }
  15561. }
  15562. }
  15563. }
  15564. else if (bitsPerSample == 32)
  15565. {
  15566. const unsigned int* src = reinterpret_cast <const unsigned int*> (tempBuffer);
  15567. unsigned int* l = reinterpret_cast <unsigned int*> (left);
  15568. unsigned int* r = reinterpret_cast <unsigned int*> (right);
  15569. if (littleEndian)
  15570. {
  15571. if (numChannels > 1)
  15572. {
  15573. if (l == 0)
  15574. {
  15575. for (int i = numThisTime; --i >= 0;)
  15576. {
  15577. ++src;
  15578. *r++ = ByteOrder::swapIfBigEndian (*src++);
  15579. }
  15580. }
  15581. else if (r == 0)
  15582. {
  15583. for (int i = numThisTime; --i >= 0;)
  15584. {
  15585. *l++ = ByteOrder::swapIfBigEndian (*src++);
  15586. ++src;
  15587. }
  15588. }
  15589. else
  15590. {
  15591. for (int i = numThisTime; --i >= 0;)
  15592. {
  15593. *l++ = ByteOrder::swapIfBigEndian (*src++);
  15594. *r++ = ByteOrder::swapIfBigEndian (*src++);
  15595. }
  15596. }
  15597. }
  15598. else
  15599. {
  15600. for (int i = numThisTime; --i >= 0;)
  15601. {
  15602. *l++ = ByteOrder::swapIfBigEndian (*src++);
  15603. }
  15604. }
  15605. }
  15606. else
  15607. {
  15608. if (numChannels > 1)
  15609. {
  15610. if (l == 0)
  15611. {
  15612. for (int i = numThisTime; --i >= 0;)
  15613. {
  15614. ++src;
  15615. *r++ = ByteOrder::swapIfLittleEndian (*src++);
  15616. }
  15617. }
  15618. else if (r == 0)
  15619. {
  15620. for (int i = numThisTime; --i >= 0;)
  15621. {
  15622. *l++ = ByteOrder::swapIfLittleEndian (*src++);
  15623. ++src;
  15624. }
  15625. }
  15626. else
  15627. {
  15628. for (int i = numThisTime; --i >= 0;)
  15629. {
  15630. *l++ = ByteOrder::swapIfLittleEndian (*src++);
  15631. *r++ = ByteOrder::swapIfLittleEndian (*src++);
  15632. }
  15633. }
  15634. }
  15635. else
  15636. {
  15637. for (int i = numThisTime; --i >= 0;)
  15638. {
  15639. *l++ = ByteOrder::swapIfLittleEndian (*src++);
  15640. }
  15641. }
  15642. }
  15643. left = reinterpret_cast <int*> (l);
  15644. right = reinterpret_cast <int*> (r);
  15645. }
  15646. else if (bitsPerSample == 8)
  15647. {
  15648. const char* src = tempBuffer;
  15649. if (numChannels > 1)
  15650. {
  15651. if (left == 0)
  15652. {
  15653. for (int i = numThisTime; --i >= 0;)
  15654. {
  15655. *right++ = ((int) *src++) << 24;
  15656. ++src;
  15657. }
  15658. }
  15659. else if (right == 0)
  15660. {
  15661. for (int i = numThisTime; --i >= 0;)
  15662. {
  15663. ++src;
  15664. *left++ = ((int) *src++) << 24;
  15665. }
  15666. }
  15667. else
  15668. {
  15669. for (int i = numThisTime; --i >= 0;)
  15670. {
  15671. *left++ = ((int) *src++) << 24;
  15672. *right++ = ((int) *src++) << 24;
  15673. }
  15674. }
  15675. }
  15676. else
  15677. {
  15678. for (int i = numThisTime; --i >= 0;)
  15679. {
  15680. *left++ = ((int) *src++) << 24;
  15681. }
  15682. }
  15683. }
  15684. startOffsetInDestBuffer += numThisTime;
  15685. numSamples -= numThisTime;
  15686. }
  15687. if (numSamples > 0)
  15688. {
  15689. for (int i = numDestChannels; --i >= 0;)
  15690. if (destSamples[i] != 0)
  15691. zeromem (destSamples[i] + startOffsetInDestBuffer,
  15692. sizeof (int) * numSamples);
  15693. }
  15694. return true;
  15695. }
  15696. juce_UseDebuggingNewOperator
  15697. private:
  15698. AiffAudioFormatReader (const AiffAudioFormatReader&);
  15699. AiffAudioFormatReader& operator= (const AiffAudioFormatReader&);
  15700. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  15701. };
  15702. class AiffAudioFormatWriter : public AudioFormatWriter
  15703. {
  15704. MemoryBlock tempBlock;
  15705. uint32 lengthInSamples, bytesWritten;
  15706. int64 headerPosition;
  15707. bool writeFailed;
  15708. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  15709. AiffAudioFormatWriter (const AiffAudioFormatWriter&);
  15710. AiffAudioFormatWriter& operator= (const AiffAudioFormatWriter&);
  15711. void writeHeader()
  15712. {
  15713. const bool couldSeekOk = output->setPosition (headerPosition);
  15714. (void) couldSeekOk;
  15715. // if this fails, you've given it an output stream that can't seek! It needs
  15716. // to be able to seek back to write the header
  15717. jassert (couldSeekOk);
  15718. const int headerLen = 54;
  15719. int audioBytes = lengthInSamples * ((bitsPerSample * numChannels) / 8);
  15720. audioBytes += (audioBytes & 1);
  15721. output->writeInt (chunkName ("FORM"));
  15722. output->writeIntBigEndian (headerLen + audioBytes - 8);
  15723. output->writeInt (chunkName ("AIFF"));
  15724. output->writeInt (chunkName ("COMM"));
  15725. output->writeIntBigEndian (18);
  15726. output->writeShortBigEndian ((short) numChannels);
  15727. output->writeIntBigEndian (lengthInSamples);
  15728. output->writeShortBigEndian ((short) bitsPerSample);
  15729. uint8 sampleRateBytes[10];
  15730. zeromem (sampleRateBytes, 10);
  15731. if (sampleRate <= 1)
  15732. {
  15733. sampleRateBytes[0] = 0x3f;
  15734. sampleRateBytes[1] = 0xff;
  15735. sampleRateBytes[2] = 0x80;
  15736. }
  15737. else
  15738. {
  15739. int mask = 0x40000000;
  15740. sampleRateBytes[0] = 0x40;
  15741. if (sampleRate >= mask)
  15742. {
  15743. jassertfalse;
  15744. sampleRateBytes[1] = 0x1d;
  15745. }
  15746. else
  15747. {
  15748. int n = (int) sampleRate;
  15749. int i;
  15750. for (i = 0; i <= 32 ; ++i)
  15751. {
  15752. if ((n & mask) != 0)
  15753. break;
  15754. mask >>= 1;
  15755. }
  15756. n = n << (i + 1);
  15757. sampleRateBytes[1] = (uint8) (29 - i);
  15758. sampleRateBytes[2] = (uint8) ((n >> 24) & 0xff);
  15759. sampleRateBytes[3] = (uint8) ((n >> 16) & 0xff);
  15760. sampleRateBytes[4] = (uint8) ((n >> 8) & 0xff);
  15761. sampleRateBytes[5] = (uint8) (n & 0xff);
  15762. }
  15763. }
  15764. output->write (sampleRateBytes, 10);
  15765. output->writeInt (chunkName ("SSND"));
  15766. output->writeIntBigEndian (audioBytes + 8);
  15767. output->writeInt (0);
  15768. output->writeInt (0);
  15769. jassert (output->getPosition() == headerLen);
  15770. }
  15771. public:
  15772. AiffAudioFormatWriter (OutputStream* out,
  15773. const double sampleRate_,
  15774. const unsigned int chans,
  15775. const int bits)
  15776. : AudioFormatWriter (out,
  15777. TRANS (aiffFormatName),
  15778. sampleRate_,
  15779. chans,
  15780. bits),
  15781. lengthInSamples (0),
  15782. bytesWritten (0),
  15783. writeFailed (false)
  15784. {
  15785. headerPosition = out->getPosition();
  15786. writeHeader();
  15787. }
  15788. ~AiffAudioFormatWriter()
  15789. {
  15790. if ((bytesWritten & 1) != 0)
  15791. output->writeByte (0);
  15792. writeHeader();
  15793. }
  15794. bool write (const int** data, int numSamples)
  15795. {
  15796. if (writeFailed)
  15797. return false;
  15798. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  15799. tempBlock.ensureSize (bytes, false);
  15800. char* buffer = static_cast <char*> (tempBlock.getData());
  15801. const int* left = data[0];
  15802. const int* right = data[1];
  15803. if (right == 0)
  15804. right = left;
  15805. if (bitsPerSample == 16)
  15806. {
  15807. short* b = reinterpret_cast <short*> (buffer);
  15808. if (numChannels > 1)
  15809. {
  15810. for (int i = numSamples; --i >= 0;)
  15811. {
  15812. *b++ = (short) ByteOrder::swapIfLittleEndian ((uint16) (*left++ >> 16));
  15813. *b++ = (short) ByteOrder::swapIfLittleEndian ((uint16) (*right++ >> 16));
  15814. }
  15815. }
  15816. else
  15817. {
  15818. for (int i = numSamples; --i >= 0;)
  15819. {
  15820. *b++ = (short) ByteOrder::swapIfLittleEndian ((uint16) (*left++ >> 16));
  15821. }
  15822. }
  15823. }
  15824. else if (bitsPerSample == 24)
  15825. {
  15826. char* b = buffer;
  15827. if (numChannels > 1)
  15828. {
  15829. for (int i = numSamples; --i >= 0;)
  15830. {
  15831. ByteOrder::bigEndian24BitToChars (*left++ >> 8, b);
  15832. b += 3;
  15833. ByteOrder::bigEndian24BitToChars (*right++ >> 8, b);
  15834. b += 3;
  15835. }
  15836. }
  15837. else
  15838. {
  15839. for (int i = numSamples; --i >= 0;)
  15840. {
  15841. ByteOrder::bigEndian24BitToChars (*left++ >> 8, b);
  15842. b += 3;
  15843. }
  15844. }
  15845. }
  15846. else if (bitsPerSample == 32)
  15847. {
  15848. uint32* b = reinterpret_cast <uint32*> (buffer);
  15849. if (numChannels > 1)
  15850. {
  15851. for (int i = numSamples; --i >= 0;)
  15852. {
  15853. *b++ = ByteOrder::swapIfLittleEndian ((uint32) *left++);
  15854. *b++ = ByteOrder::swapIfLittleEndian ((uint32) *right++);
  15855. }
  15856. }
  15857. else
  15858. {
  15859. for (int i = numSamples; --i >= 0;)
  15860. {
  15861. *b++ = ByteOrder::swapIfLittleEndian ((uint32) *left++);
  15862. }
  15863. }
  15864. }
  15865. else if (bitsPerSample == 8)
  15866. {
  15867. char* b = buffer;
  15868. if (numChannels > 1)
  15869. {
  15870. for (int i = numSamples; --i >= 0;)
  15871. {
  15872. *b++ = (char) (*left++ >> 24);
  15873. *b++ = (char) (*right++ >> 24);
  15874. }
  15875. }
  15876. else
  15877. {
  15878. for (int i = numSamples; --i >= 0;)
  15879. {
  15880. *b++ = (char) (*left++ >> 24);
  15881. }
  15882. }
  15883. }
  15884. if (bytesWritten + bytes >= (uint32) 0xfff00000
  15885. || ! output->write (buffer, bytes))
  15886. {
  15887. // failed to write to disk, so let's try writing the header.
  15888. // If it's just run out of disk space, then if it does manage
  15889. // to write the header, we'll still have a useable file..
  15890. writeHeader();
  15891. writeFailed = true;
  15892. return false;
  15893. }
  15894. else
  15895. {
  15896. bytesWritten += bytes;
  15897. lengthInSamples += numSamples;
  15898. return true;
  15899. }
  15900. }
  15901. juce_UseDebuggingNewOperator
  15902. };
  15903. AiffAudioFormat::AiffAudioFormat()
  15904. : AudioFormat (TRANS (aiffFormatName), StringArray (aiffExtensions))
  15905. {
  15906. }
  15907. AiffAudioFormat::~AiffAudioFormat()
  15908. {
  15909. }
  15910. const Array <int> AiffAudioFormat::getPossibleSampleRates()
  15911. {
  15912. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  15913. return Array <int> (rates);
  15914. }
  15915. const Array <int> AiffAudioFormat::getPossibleBitDepths()
  15916. {
  15917. const int depths[] = { 8, 16, 24, 0 };
  15918. return Array <int> (depths);
  15919. }
  15920. bool AiffAudioFormat::canDoStereo()
  15921. {
  15922. return true;
  15923. }
  15924. bool AiffAudioFormat::canDoMono()
  15925. {
  15926. return true;
  15927. }
  15928. #if JUCE_MAC
  15929. bool AiffAudioFormat::canHandleFile (const File& f)
  15930. {
  15931. if (AudioFormat::canHandleFile (f))
  15932. return true;
  15933. const OSType type = PlatformUtilities::getTypeOfFile (f.getFullPathName());
  15934. return type == 'AIFF' || type == 'AIFC'
  15935. || type == 'aiff' || type == 'aifc';
  15936. }
  15937. #endif
  15938. AudioFormatReader* AiffAudioFormat::createReaderFor (InputStream* sourceStream,
  15939. const bool deleteStreamIfOpeningFails)
  15940. {
  15941. ScopedPointer <AiffAudioFormatReader> w (new AiffAudioFormatReader (sourceStream));
  15942. if (w->sampleRate != 0)
  15943. return w.release();
  15944. if (! deleteStreamIfOpeningFails)
  15945. w->input = 0;
  15946. return 0;
  15947. }
  15948. AudioFormatWriter* AiffAudioFormat::createWriterFor (OutputStream* out,
  15949. double sampleRate,
  15950. unsigned int chans,
  15951. int bitsPerSample,
  15952. const StringPairArray& /*metadataValues*/,
  15953. int /*qualityOptionIndex*/)
  15954. {
  15955. if (getPossibleBitDepths().contains (bitsPerSample))
  15956. {
  15957. return new AiffAudioFormatWriter (out,
  15958. sampleRate,
  15959. chans,
  15960. bitsPerSample);
  15961. }
  15962. return 0;
  15963. }
  15964. END_JUCE_NAMESPACE
  15965. /*** End of inlined file: juce_AiffAudioFormat.cpp ***/
  15966. /*** Start of inlined file: juce_AudioFormat.cpp ***/
  15967. BEGIN_JUCE_NAMESPACE
  15968. AudioFormatReader::AudioFormatReader (InputStream* const in,
  15969. const String& formatName_)
  15970. : sampleRate (0),
  15971. bitsPerSample (0),
  15972. lengthInSamples (0),
  15973. numChannels (0),
  15974. usesFloatingPointData (false),
  15975. input (in),
  15976. formatName (formatName_)
  15977. {
  15978. }
  15979. AudioFormatReader::~AudioFormatReader()
  15980. {
  15981. delete input;
  15982. }
  15983. bool AudioFormatReader::read (int** destSamples,
  15984. int numDestChannels,
  15985. int64 startSampleInSource,
  15986. int numSamplesToRead,
  15987. const bool fillLeftoverChannelsWithCopies)
  15988. {
  15989. jassert (numDestChannels > 0); // you have to actually give this some channels to work with!
  15990. int startOffsetInDestBuffer = 0;
  15991. if (startSampleInSource < 0)
  15992. {
  15993. const int silence = (int) jmin (-startSampleInSource, (int64) numSamplesToRead);
  15994. for (int i = numDestChannels; --i >= 0;)
  15995. if (destSamples[i] != 0)
  15996. zeromem (destSamples[i], sizeof (int) * silence);
  15997. startOffsetInDestBuffer += silence;
  15998. numSamplesToRead -= silence;
  15999. startSampleInSource = 0;
  16000. }
  16001. if (numSamplesToRead <= 0)
  16002. return true;
  16003. if (! readSamples (destSamples, jmin ((int) numChannels, numDestChannels), startOffsetInDestBuffer,
  16004. startSampleInSource, numSamplesToRead))
  16005. return false;
  16006. if (numDestChannels > (int) numChannels)
  16007. {
  16008. if (fillLeftoverChannelsWithCopies)
  16009. {
  16010. int* lastFullChannel = destSamples[0];
  16011. for (int i = numDestChannels; --i > 0;)
  16012. {
  16013. if (destSamples[i] != 0)
  16014. {
  16015. lastFullChannel = destSamples[i];
  16016. break;
  16017. }
  16018. }
  16019. if (lastFullChannel != 0)
  16020. for (int i = numChannels; i < numDestChannels; ++i)
  16021. if (destSamples[i] != 0)
  16022. memcpy (destSamples[i], lastFullChannel, sizeof (int) * numSamplesToRead);
  16023. }
  16024. else
  16025. {
  16026. for (int i = numChannels; i < numDestChannels; ++i)
  16027. if (destSamples[i] != 0)
  16028. zeromem (destSamples[i], sizeof (int) * numSamplesToRead);
  16029. }
  16030. }
  16031. return true;
  16032. }
  16033. static void findAudioBufferMaxMin (const float* const buffer, const int num, float& maxVal, float& minVal) throw()
  16034. {
  16035. float mn = buffer[0];
  16036. float mx = mn;
  16037. for (int i = 1; i < num; ++i)
  16038. {
  16039. const float s = buffer[i];
  16040. if (s > mx) mx = s;
  16041. if (s < mn) mn = s;
  16042. }
  16043. maxVal = mx;
  16044. minVal = mn;
  16045. }
  16046. void AudioFormatReader::readMaxLevels (int64 startSampleInFile,
  16047. int64 numSamples,
  16048. float& lowestLeft, float& highestLeft,
  16049. float& lowestRight, float& highestRight)
  16050. {
  16051. if (numSamples <= 0)
  16052. {
  16053. lowestLeft = 0;
  16054. lowestRight = 0;
  16055. highestLeft = 0;
  16056. highestRight = 0;
  16057. return;
  16058. }
  16059. const int bufferSize = (int) jmin (numSamples, (int64) 4096);
  16060. MemoryBlock tempSpace (bufferSize * sizeof (int) * 2 + 64);
  16061. int* tempBuffer[3];
  16062. tempBuffer[0] = (int*) tempSpace.getData();
  16063. tempBuffer[1] = ((int*) tempSpace.getData()) + bufferSize;
  16064. tempBuffer[2] = 0;
  16065. if (usesFloatingPointData)
  16066. {
  16067. float lmin = 1.0e6f;
  16068. float lmax = -lmin;
  16069. float rmin = lmin;
  16070. float rmax = lmax;
  16071. while (numSamples > 0)
  16072. {
  16073. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  16074. read ((int**) tempBuffer, 2, startSampleInFile, numToDo, false);
  16075. numSamples -= numToDo;
  16076. startSampleInFile += numToDo;
  16077. float bufmin, bufmax;
  16078. findAudioBufferMaxMin ((float*) tempBuffer[0], numToDo, bufmax, bufmin);
  16079. lmin = jmin (lmin, bufmin);
  16080. lmax = jmax (lmax, bufmax);
  16081. if (numChannels > 1)
  16082. {
  16083. findAudioBufferMaxMin ((float*) tempBuffer[1], numToDo, bufmax, bufmin);
  16084. rmin = jmin (rmin, bufmin);
  16085. rmax = jmax (rmax, bufmax);
  16086. }
  16087. }
  16088. if (numChannels <= 1)
  16089. {
  16090. rmax = lmax;
  16091. rmin = lmin;
  16092. }
  16093. lowestLeft = lmin;
  16094. highestLeft = lmax;
  16095. lowestRight = rmin;
  16096. highestRight = rmax;
  16097. }
  16098. else
  16099. {
  16100. int lmax = std::numeric_limits<int>::min();
  16101. int lmin = std::numeric_limits<int>::max();
  16102. int rmax = std::numeric_limits<int>::min();
  16103. int rmin = std::numeric_limits<int>::max();
  16104. while (numSamples > 0)
  16105. {
  16106. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  16107. read ((int**) tempBuffer, 2, startSampleInFile, numToDo, false);
  16108. numSamples -= numToDo;
  16109. startSampleInFile += numToDo;
  16110. for (int j = numChannels; --j >= 0;)
  16111. {
  16112. int bufMax = std::numeric_limits<int>::min();
  16113. int bufMin = std::numeric_limits<int>::max();
  16114. const int* const b = tempBuffer[j];
  16115. for (int i = 0; i < numToDo; ++i)
  16116. {
  16117. const int samp = b[i];
  16118. if (samp < bufMin)
  16119. bufMin = samp;
  16120. if (samp > bufMax)
  16121. bufMax = samp;
  16122. }
  16123. if (j == 0)
  16124. {
  16125. lmax = jmax (lmax, bufMax);
  16126. lmin = jmin (lmin, bufMin);
  16127. }
  16128. else
  16129. {
  16130. rmax = jmax (rmax, bufMax);
  16131. rmin = jmin (rmin, bufMin);
  16132. }
  16133. }
  16134. }
  16135. if (numChannels <= 1)
  16136. {
  16137. rmax = lmax;
  16138. rmin = lmin;
  16139. }
  16140. lowestLeft = lmin / (float) std::numeric_limits<int>::max();
  16141. highestLeft = lmax / (float) std::numeric_limits<int>::max();
  16142. lowestRight = rmin / (float) std::numeric_limits<int>::max();
  16143. highestRight = rmax / (float) std::numeric_limits<int>::max();
  16144. }
  16145. }
  16146. int64 AudioFormatReader::searchForLevel (int64 startSample,
  16147. int64 numSamplesToSearch,
  16148. const double magnitudeRangeMinimum,
  16149. const double magnitudeRangeMaximum,
  16150. const int minimumConsecutiveSamples)
  16151. {
  16152. if (numSamplesToSearch == 0)
  16153. return -1;
  16154. const int bufferSize = 4096;
  16155. MemoryBlock tempSpace (bufferSize * sizeof (int) * 2 + 64);
  16156. int* tempBuffer[3];
  16157. tempBuffer[0] = (int*) tempSpace.getData();
  16158. tempBuffer[1] = ((int*) tempSpace.getData()) + bufferSize;
  16159. tempBuffer[2] = 0;
  16160. int consecutive = 0;
  16161. int64 firstMatchPos = -1;
  16162. jassert (magnitudeRangeMaximum > magnitudeRangeMinimum);
  16163. const double doubleMin = jlimit (0.0, (double) std::numeric_limits<int>::max(), magnitudeRangeMinimum * std::numeric_limits<int>::max());
  16164. const double doubleMax = jlimit (doubleMin, (double) std::numeric_limits<int>::max(), magnitudeRangeMaximum * std::numeric_limits<int>::max());
  16165. const int intMagnitudeRangeMinimum = roundToInt (doubleMin);
  16166. const int intMagnitudeRangeMaximum = roundToInt (doubleMax);
  16167. while (numSamplesToSearch != 0)
  16168. {
  16169. const int numThisTime = (int) jmin (abs64 (numSamplesToSearch), (int64) bufferSize);
  16170. int64 bufferStart = startSample;
  16171. if (numSamplesToSearch < 0)
  16172. bufferStart -= numThisTime;
  16173. if (bufferStart >= (int) lengthInSamples)
  16174. break;
  16175. read ((int**) tempBuffer, 2, bufferStart, numThisTime, false);
  16176. int num = numThisTime;
  16177. while (--num >= 0)
  16178. {
  16179. if (numSamplesToSearch < 0)
  16180. --startSample;
  16181. bool matches = false;
  16182. const int index = (int) (startSample - bufferStart);
  16183. if (usesFloatingPointData)
  16184. {
  16185. const float sample1 = std::abs (((float*) tempBuffer[0]) [index]);
  16186. if (sample1 >= magnitudeRangeMinimum
  16187. && sample1 <= magnitudeRangeMaximum)
  16188. {
  16189. matches = true;
  16190. }
  16191. else if (numChannels > 1)
  16192. {
  16193. const float sample2 = std::abs (((float*) tempBuffer[1]) [index]);
  16194. matches = (sample2 >= magnitudeRangeMinimum
  16195. && sample2 <= magnitudeRangeMaximum);
  16196. }
  16197. }
  16198. else
  16199. {
  16200. const int sample1 = abs (tempBuffer[0] [index]);
  16201. if (sample1 >= intMagnitudeRangeMinimum
  16202. && sample1 <= intMagnitudeRangeMaximum)
  16203. {
  16204. matches = true;
  16205. }
  16206. else if (numChannels > 1)
  16207. {
  16208. const int sample2 = abs (tempBuffer[1][index]);
  16209. matches = (sample2 >= intMagnitudeRangeMinimum
  16210. && sample2 <= intMagnitudeRangeMaximum);
  16211. }
  16212. }
  16213. if (matches)
  16214. {
  16215. if (firstMatchPos < 0)
  16216. firstMatchPos = startSample;
  16217. if (++consecutive >= minimumConsecutiveSamples)
  16218. {
  16219. if (firstMatchPos < 0 || firstMatchPos >= lengthInSamples)
  16220. return -1;
  16221. return firstMatchPos;
  16222. }
  16223. }
  16224. else
  16225. {
  16226. consecutive = 0;
  16227. firstMatchPos = -1;
  16228. }
  16229. if (numSamplesToSearch > 0)
  16230. ++startSample;
  16231. }
  16232. if (numSamplesToSearch > 0)
  16233. numSamplesToSearch -= numThisTime;
  16234. else
  16235. numSamplesToSearch += numThisTime;
  16236. }
  16237. return -1;
  16238. }
  16239. AudioFormatWriter::AudioFormatWriter (OutputStream* const out,
  16240. const String& formatName_,
  16241. const double rate,
  16242. const unsigned int numChannels_,
  16243. const unsigned int bitsPerSample_)
  16244. : sampleRate (rate),
  16245. numChannels (numChannels_),
  16246. bitsPerSample (bitsPerSample_),
  16247. usesFloatingPointData (false),
  16248. output (out),
  16249. formatName (formatName_)
  16250. {
  16251. }
  16252. AudioFormatWriter::~AudioFormatWriter()
  16253. {
  16254. delete output;
  16255. }
  16256. bool AudioFormatWriter::writeFromAudioReader (AudioFormatReader& reader,
  16257. int64 startSample,
  16258. int64 numSamplesToRead)
  16259. {
  16260. const int bufferSize = 16384;
  16261. AudioSampleBuffer tempBuffer (numChannels, bufferSize);
  16262. int* buffers [128];
  16263. zerostruct (buffers);
  16264. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  16265. buffers[i] = (int*) tempBuffer.getSampleData (i, 0);
  16266. if (numSamplesToRead < 0)
  16267. numSamplesToRead = reader.lengthInSamples;
  16268. while (numSamplesToRead > 0)
  16269. {
  16270. const int numToDo = (int) jmin (numSamplesToRead, (int64) bufferSize);
  16271. if (! reader.read (buffers, numChannels, startSample, numToDo, false))
  16272. return false;
  16273. if (reader.usesFloatingPointData != isFloatingPoint())
  16274. {
  16275. int** bufferChan = buffers;
  16276. while (*bufferChan != 0)
  16277. {
  16278. int* b = *bufferChan++;
  16279. if (isFloatingPoint())
  16280. {
  16281. // int -> float
  16282. const double factor = 1.0 / std::numeric_limits<int>::max();
  16283. for (int i = 0; i < numToDo; ++i)
  16284. ((float*) b)[i] = (float) (factor * b[i]);
  16285. }
  16286. else
  16287. {
  16288. // float -> int
  16289. for (int i = 0; i < numToDo; ++i)
  16290. {
  16291. const double samp = *(const float*) b;
  16292. if (samp <= -1.0)
  16293. *b++ = std::numeric_limits<int>::min();
  16294. else if (samp >= 1.0)
  16295. *b++ = std::numeric_limits<int>::max();
  16296. else
  16297. *b++ = roundToInt (std::numeric_limits<int>::max() * samp);
  16298. }
  16299. }
  16300. }
  16301. }
  16302. if (! write ((const int**) buffers, numToDo))
  16303. return false;
  16304. numSamplesToRead -= numToDo;
  16305. startSample += numToDo;
  16306. }
  16307. return true;
  16308. }
  16309. bool AudioFormatWriter::writeFromAudioSource (AudioSource& source,
  16310. int numSamplesToRead,
  16311. const int samplesPerBlock)
  16312. {
  16313. AudioSampleBuffer tempBuffer (getNumChannels(), samplesPerBlock);
  16314. int* buffers [128];
  16315. zerostruct (buffers);
  16316. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  16317. buffers[i] = (int*) tempBuffer.getSampleData (i, 0);
  16318. while (numSamplesToRead > 0)
  16319. {
  16320. const int numToDo = jmin (numSamplesToRead, samplesPerBlock);
  16321. AudioSourceChannelInfo info;
  16322. info.buffer = &tempBuffer;
  16323. info.startSample = 0;
  16324. info.numSamples = numToDo;
  16325. info.clearActiveBufferRegion();
  16326. source.getNextAudioBlock (info);
  16327. if (! isFloatingPoint())
  16328. {
  16329. int** bufferChan = buffers;
  16330. while (*bufferChan != 0)
  16331. {
  16332. int* b = *bufferChan++;
  16333. // float -> int
  16334. for (int j = numToDo; --j >= 0;)
  16335. {
  16336. const double samp = *(const float*) b;
  16337. if (samp <= -1.0)
  16338. *b++ = std::numeric_limits<int>::min();
  16339. else if (samp >= 1.0)
  16340. *b++ = std::numeric_limits<int>::max();
  16341. else
  16342. *b++ = roundToInt (std::numeric_limits<int>::max() * samp);
  16343. }
  16344. }
  16345. }
  16346. if (! write ((const int**) buffers, numToDo))
  16347. return false;
  16348. numSamplesToRead -= numToDo;
  16349. }
  16350. return true;
  16351. }
  16352. AudioFormat::AudioFormat (const String& name,
  16353. const StringArray& extensions)
  16354. : formatName (name),
  16355. fileExtensions (extensions)
  16356. {
  16357. }
  16358. AudioFormat::~AudioFormat()
  16359. {
  16360. }
  16361. const String& AudioFormat::getFormatName() const
  16362. {
  16363. return formatName;
  16364. }
  16365. const StringArray& AudioFormat::getFileExtensions() const
  16366. {
  16367. return fileExtensions;
  16368. }
  16369. bool AudioFormat::canHandleFile (const File& f)
  16370. {
  16371. for (int i = 0; i < fileExtensions.size(); ++i)
  16372. if (f.hasFileExtension (fileExtensions[i]))
  16373. return true;
  16374. return false;
  16375. }
  16376. bool AudioFormat::isCompressed()
  16377. {
  16378. return false;
  16379. }
  16380. const StringArray AudioFormat::getQualityOptions()
  16381. {
  16382. return StringArray();
  16383. }
  16384. END_JUCE_NAMESPACE
  16385. /*** End of inlined file: juce_AudioFormat.cpp ***/
  16386. /*** Start of inlined file: juce_AudioFormatManager.cpp ***/
  16387. BEGIN_JUCE_NAMESPACE
  16388. AudioFormatManager::AudioFormatManager()
  16389. : defaultFormatIndex (0)
  16390. {
  16391. }
  16392. AudioFormatManager::~AudioFormatManager()
  16393. {
  16394. clearFormats();
  16395. clearSingletonInstance();
  16396. }
  16397. juce_ImplementSingleton (AudioFormatManager);
  16398. void AudioFormatManager::registerFormat (AudioFormat* newFormat,
  16399. const bool makeThisTheDefaultFormat)
  16400. {
  16401. jassert (newFormat != 0);
  16402. if (newFormat != 0)
  16403. {
  16404. #if JUCE_DEBUG
  16405. for (int i = getNumKnownFormats(); --i >= 0;)
  16406. {
  16407. if (getKnownFormat (i)->getFormatName() == newFormat->getFormatName())
  16408. {
  16409. jassertfalse; // trying to add the same format twice!
  16410. }
  16411. }
  16412. #endif
  16413. if (makeThisTheDefaultFormat)
  16414. defaultFormatIndex = getNumKnownFormats();
  16415. knownFormats.add (newFormat);
  16416. }
  16417. }
  16418. void AudioFormatManager::registerBasicFormats()
  16419. {
  16420. #if JUCE_MAC
  16421. registerFormat (new AiffAudioFormat(), true);
  16422. registerFormat (new WavAudioFormat(), false);
  16423. #else
  16424. registerFormat (new WavAudioFormat(), true);
  16425. registerFormat (new AiffAudioFormat(), false);
  16426. #endif
  16427. #if JUCE_USE_FLAC
  16428. registerFormat (new FlacAudioFormat(), false);
  16429. #endif
  16430. #if JUCE_USE_OGGVORBIS
  16431. registerFormat (new OggVorbisAudioFormat(), false);
  16432. #endif
  16433. }
  16434. void AudioFormatManager::clearFormats()
  16435. {
  16436. knownFormats.clear();
  16437. defaultFormatIndex = 0;
  16438. }
  16439. int AudioFormatManager::getNumKnownFormats() const
  16440. {
  16441. return knownFormats.size();
  16442. }
  16443. AudioFormat* AudioFormatManager::getKnownFormat (const int index) const
  16444. {
  16445. return knownFormats [index];
  16446. }
  16447. AudioFormat* AudioFormatManager::getDefaultFormat() const
  16448. {
  16449. return getKnownFormat (defaultFormatIndex);
  16450. }
  16451. AudioFormat* AudioFormatManager::findFormatForFileExtension (const String& fileExtension) const
  16452. {
  16453. String e (fileExtension);
  16454. if (! e.startsWithChar ('.'))
  16455. e = "." + e;
  16456. for (int i = 0; i < getNumKnownFormats(); ++i)
  16457. if (getKnownFormat(i)->getFileExtensions().contains (e, true))
  16458. return getKnownFormat(i);
  16459. return 0;
  16460. }
  16461. const String AudioFormatManager::getWildcardForAllFormats() const
  16462. {
  16463. StringArray allExtensions;
  16464. int i;
  16465. for (i = 0; i < getNumKnownFormats(); ++i)
  16466. allExtensions.addArray (getKnownFormat (i)->getFileExtensions());
  16467. allExtensions.trim();
  16468. allExtensions.removeEmptyStrings();
  16469. String s;
  16470. for (i = 0; i < allExtensions.size(); ++i)
  16471. {
  16472. s << '*';
  16473. if (! allExtensions[i].startsWithChar ('.'))
  16474. s << '.';
  16475. s << allExtensions[i];
  16476. if (i < allExtensions.size() - 1)
  16477. s << ';';
  16478. }
  16479. return s;
  16480. }
  16481. AudioFormatReader* AudioFormatManager::createReaderFor (const File& file)
  16482. {
  16483. // you need to actually register some formats before the manager can
  16484. // use them to open a file!
  16485. jassert (getNumKnownFormats() > 0);
  16486. for (int i = 0; i < getNumKnownFormats(); ++i)
  16487. {
  16488. AudioFormat* const af = getKnownFormat(i);
  16489. if (af->canHandleFile (file))
  16490. {
  16491. InputStream* const in = file.createInputStream();
  16492. if (in != 0)
  16493. {
  16494. AudioFormatReader* const r = af->createReaderFor (in, true);
  16495. if (r != 0)
  16496. return r;
  16497. }
  16498. }
  16499. }
  16500. return 0;
  16501. }
  16502. AudioFormatReader* AudioFormatManager::createReaderFor (InputStream* audioFileStream)
  16503. {
  16504. // you need to actually register some formats before the manager can
  16505. // use them to open a file!
  16506. jassert (getNumKnownFormats() > 0);
  16507. ScopedPointer <InputStream> in (audioFileStream);
  16508. if (in != 0)
  16509. {
  16510. const int64 originalStreamPos = in->getPosition();
  16511. for (int i = 0; i < getNumKnownFormats(); ++i)
  16512. {
  16513. AudioFormatReader* const r = getKnownFormat(i)->createReaderFor (in, false);
  16514. if (r != 0)
  16515. {
  16516. in.release();
  16517. return r;
  16518. }
  16519. in->setPosition (originalStreamPos);
  16520. // the stream that is passed-in must be capable of being repositioned so
  16521. // that all the formats can have a go at opening it.
  16522. jassert (in->getPosition() == originalStreamPos);
  16523. }
  16524. }
  16525. return 0;
  16526. }
  16527. END_JUCE_NAMESPACE
  16528. /*** End of inlined file: juce_AudioFormatManager.cpp ***/
  16529. /*** Start of inlined file: juce_AudioSubsectionReader.cpp ***/
  16530. BEGIN_JUCE_NAMESPACE
  16531. AudioSubsectionReader::AudioSubsectionReader (AudioFormatReader* const source_,
  16532. const int64 startSample_,
  16533. const int64 length_,
  16534. const bool deleteSourceWhenDeleted_)
  16535. : AudioFormatReader (0, source_->getFormatName()),
  16536. source (source_),
  16537. startSample (startSample_),
  16538. deleteSourceWhenDeleted (deleteSourceWhenDeleted_)
  16539. {
  16540. length = jmin (jmax ((int64) 0, source->lengthInSamples - startSample), length_);
  16541. sampleRate = source->sampleRate;
  16542. bitsPerSample = source->bitsPerSample;
  16543. lengthInSamples = length;
  16544. numChannels = source->numChannels;
  16545. usesFloatingPointData = source->usesFloatingPointData;
  16546. }
  16547. AudioSubsectionReader::~AudioSubsectionReader()
  16548. {
  16549. if (deleteSourceWhenDeleted)
  16550. delete source;
  16551. }
  16552. bool AudioSubsectionReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  16553. int64 startSampleInFile, int numSamples)
  16554. {
  16555. if (startSampleInFile + numSamples > length)
  16556. {
  16557. for (int i = numDestChannels; --i >= 0;)
  16558. if (destSamples[i] != 0)
  16559. zeromem (destSamples[i], sizeof (int) * numSamples);
  16560. numSamples = jmin (numSamples, (int) (length - startSampleInFile));
  16561. if (numSamples <= 0)
  16562. return true;
  16563. }
  16564. return source->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer,
  16565. startSampleInFile + startSample, numSamples);
  16566. }
  16567. void AudioSubsectionReader::readMaxLevels (int64 startSampleInFile,
  16568. int64 numSamples,
  16569. float& lowestLeft,
  16570. float& highestLeft,
  16571. float& lowestRight,
  16572. float& highestRight)
  16573. {
  16574. startSampleInFile = jmax ((int64) 0, startSampleInFile);
  16575. numSamples = jmax ((int64) 0, jmin (numSamples, length - startSampleInFile));
  16576. source->readMaxLevels (startSampleInFile + startSample,
  16577. numSamples,
  16578. lowestLeft,
  16579. highestLeft,
  16580. lowestRight,
  16581. highestRight);
  16582. }
  16583. END_JUCE_NAMESPACE
  16584. /*** End of inlined file: juce_AudioSubsectionReader.cpp ***/
  16585. /*** Start of inlined file: juce_AudioThumbnail.cpp ***/
  16586. BEGIN_JUCE_NAMESPACE
  16587. const int timeBeforeDeletingReader = 2000;
  16588. struct AudioThumbnailDataFormat
  16589. {
  16590. char thumbnailMagic[4];
  16591. int samplesPerThumbSample;
  16592. int64 totalSamples; // source samples
  16593. int64 numFinishedSamples; // source samples
  16594. int numThumbnailSamples;
  16595. int numChannels;
  16596. int sampleRate;
  16597. char future[16];
  16598. char data[1];
  16599. void swapEndiannessIfNeeded() throw()
  16600. {
  16601. #if JUCE_BIG_ENDIAN
  16602. flip (samplesPerThumbSample);
  16603. flip (totalSamples);
  16604. flip (numFinishedSamples);
  16605. flip (numThumbnailSamples);
  16606. flip (numChannels);
  16607. flip (sampleRate);
  16608. #endif
  16609. }
  16610. private:
  16611. #if JUCE_BIG_ENDIAN
  16612. static void flip (int& n) { n = (int) ByteOrder::swap ((uint32) n); }
  16613. static void flip (int64& n) { n = (int64) ByteOrder::swap ((uint64) n); }
  16614. #endif
  16615. };
  16616. AudioThumbnail::AudioThumbnail (const int orginalSamplesPerThumbnailSample_,
  16617. AudioFormatManager& formatManagerToUse_,
  16618. AudioThumbnailCache& cacheToUse)
  16619. : formatManagerToUse (formatManagerToUse_),
  16620. cache (cacheToUse),
  16621. orginalSamplesPerThumbnailSample (orginalSamplesPerThumbnailSample_)
  16622. {
  16623. clear();
  16624. }
  16625. AudioThumbnail::~AudioThumbnail()
  16626. {
  16627. cache.removeThumbnail (this);
  16628. const ScopedLock sl (readerLock);
  16629. reader = 0;
  16630. }
  16631. void AudioThumbnail::setSource (InputSource* const newSource)
  16632. {
  16633. cache.removeThumbnail (this);
  16634. timerCallback(); // stops the timer and deletes the reader
  16635. source = newSource;
  16636. clear();
  16637. if (newSource != 0
  16638. && ! (cache.loadThumb (*this, newSource->hashCode())
  16639. && isFullyLoaded()))
  16640. {
  16641. {
  16642. const ScopedLock sl (readerLock);
  16643. reader = createReader();
  16644. }
  16645. if (reader != 0)
  16646. {
  16647. initialiseFromAudioFile (*reader);
  16648. cache.addThumbnail (this);
  16649. }
  16650. }
  16651. sendChangeMessage (this);
  16652. }
  16653. bool AudioThumbnail::useTimeSlice()
  16654. {
  16655. const ScopedLock sl (readerLock);
  16656. if (isFullyLoaded())
  16657. {
  16658. if (reader != 0)
  16659. startTimer (timeBeforeDeletingReader);
  16660. cache.removeThumbnail (this);
  16661. return false;
  16662. }
  16663. if (reader == 0)
  16664. reader = createReader();
  16665. if (reader != 0)
  16666. {
  16667. readNextBlockFromAudioFile (*reader);
  16668. stopTimer();
  16669. sendChangeMessage (this);
  16670. const bool justFinished = isFullyLoaded();
  16671. if (justFinished)
  16672. cache.storeThumb (*this, source->hashCode());
  16673. return ! justFinished;
  16674. }
  16675. return false;
  16676. }
  16677. AudioFormatReader* AudioThumbnail::createReader() const
  16678. {
  16679. if (source != 0)
  16680. {
  16681. InputStream* const audioFileStream = source->createInputStream();
  16682. if (audioFileStream != 0)
  16683. return formatManagerToUse.createReaderFor (audioFileStream);
  16684. }
  16685. return 0;
  16686. }
  16687. void AudioThumbnail::timerCallback()
  16688. {
  16689. stopTimer();
  16690. const ScopedLock sl (readerLock);
  16691. reader = 0;
  16692. }
  16693. void AudioThumbnail::clear()
  16694. {
  16695. data.setSize (sizeof (AudioThumbnailDataFormat) + 3);
  16696. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16697. d->thumbnailMagic[0] = 'j';
  16698. d->thumbnailMagic[1] = 'a';
  16699. d->thumbnailMagic[2] = 't';
  16700. d->thumbnailMagic[3] = 'm';
  16701. d->samplesPerThumbSample = orginalSamplesPerThumbnailSample;
  16702. d->totalSamples = 0;
  16703. d->numFinishedSamples = 0;
  16704. d->numThumbnailSamples = 0;
  16705. d->numChannels = 0;
  16706. d->sampleRate = 0;
  16707. numSamplesCached = 0;
  16708. cacheNeedsRefilling = true;
  16709. }
  16710. void AudioThumbnail::loadFrom (InputStream& input)
  16711. {
  16712. const ScopedLock sl (readerLock);
  16713. data.setSize (0);
  16714. input.readIntoMemoryBlock (data);
  16715. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16716. d->swapEndiannessIfNeeded();
  16717. if (! (d->thumbnailMagic[0] == 'j'
  16718. && d->thumbnailMagic[1] == 'a'
  16719. && d->thumbnailMagic[2] == 't'
  16720. && d->thumbnailMagic[3] == 'm'))
  16721. {
  16722. clear();
  16723. }
  16724. numSamplesCached = 0;
  16725. cacheNeedsRefilling = true;
  16726. }
  16727. void AudioThumbnail::saveTo (OutputStream& output) const
  16728. {
  16729. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16730. d->swapEndiannessIfNeeded();
  16731. output.write (data.getData(), (int) data.getSize());
  16732. d->swapEndiannessIfNeeded();
  16733. }
  16734. bool AudioThumbnail::initialiseFromAudioFile (AudioFormatReader& fileReader)
  16735. {
  16736. AudioThumbnailDataFormat* d = (AudioThumbnailDataFormat*) data.getData();
  16737. d->totalSamples = fileReader.lengthInSamples;
  16738. d->numChannels = jmin ((uint32) 2, fileReader.numChannels);
  16739. d->numFinishedSamples = 0;
  16740. d->sampleRate = roundToInt (fileReader.sampleRate);
  16741. d->numThumbnailSamples = (int) (d->totalSamples / d->samplesPerThumbSample) + 1;
  16742. data.setSize (sizeof (AudioThumbnailDataFormat) + 3 + d->numThumbnailSamples * d->numChannels * 2);
  16743. d = (AudioThumbnailDataFormat*) data.getData();
  16744. zeromem (&(d->data[0]), d->numThumbnailSamples * d->numChannels * 2);
  16745. return d->totalSamples > 0;
  16746. }
  16747. bool AudioThumbnail::readNextBlockFromAudioFile (AudioFormatReader& fileReader)
  16748. {
  16749. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16750. if (d->numFinishedSamples < d->totalSamples)
  16751. {
  16752. const int numToDo = (int) jmin ((int64) 65536, d->totalSamples - d->numFinishedSamples);
  16753. generateSection (fileReader,
  16754. d->numFinishedSamples,
  16755. numToDo);
  16756. d->numFinishedSamples += numToDo;
  16757. }
  16758. cacheNeedsRefilling = true;
  16759. return (d->numFinishedSamples < d->totalSamples);
  16760. }
  16761. int AudioThumbnail::getNumChannels() const throw()
  16762. {
  16763. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16764. jassert (d != 0);
  16765. return d->numChannels;
  16766. }
  16767. double AudioThumbnail::getTotalLength() const throw()
  16768. {
  16769. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16770. jassert (d != 0);
  16771. if (d->sampleRate > 0)
  16772. return d->totalSamples / (double)d->sampleRate;
  16773. else
  16774. return 0.0;
  16775. }
  16776. void AudioThumbnail::generateSection (AudioFormatReader& fileReader,
  16777. int64 startSample,
  16778. int numSamples)
  16779. {
  16780. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16781. jassert (d != 0);
  16782. int firstDataPos = (int) (startSample / d->samplesPerThumbSample);
  16783. int lastDataPos = (int) ((startSample + numSamples) / d->samplesPerThumbSample);
  16784. char* l = getChannelData (0);
  16785. char* r = getChannelData (1);
  16786. for (int i = firstDataPos; i < lastDataPos; ++i)
  16787. {
  16788. const int sourceStart = i * d->samplesPerThumbSample;
  16789. const int sourceEnd = sourceStart + d->samplesPerThumbSample;
  16790. float lowestLeft, highestLeft, lowestRight, highestRight;
  16791. fileReader.readMaxLevels (sourceStart,
  16792. sourceEnd - sourceStart,
  16793. lowestLeft,
  16794. highestLeft,
  16795. lowestRight,
  16796. highestRight);
  16797. int n = i * 2;
  16798. if (r != 0)
  16799. {
  16800. l [n] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  16801. r [n++] = (char) jlimit (-128.0f, 127.0f, lowestRight * 127.0f);
  16802. l [n] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  16803. r [n++] = (char) jlimit (-128.0f, 127.0f, highestRight * 127.0f);
  16804. }
  16805. else
  16806. {
  16807. l [n++] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  16808. l [n++] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  16809. }
  16810. }
  16811. }
  16812. char* AudioThumbnail::getChannelData (int channel) const
  16813. {
  16814. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16815. jassert (d != 0);
  16816. if (channel >= 0 && channel < d->numChannels)
  16817. return d->data + (channel * 2 * d->numThumbnailSamples);
  16818. return 0;
  16819. }
  16820. bool AudioThumbnail::isFullyLoaded() const throw()
  16821. {
  16822. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16823. jassert (d != 0);
  16824. return d->numFinishedSamples >= d->totalSamples;
  16825. }
  16826. void AudioThumbnail::refillCache (const int numSamples,
  16827. double startTime,
  16828. const double timePerPixel)
  16829. {
  16830. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16831. jassert (d != 0);
  16832. if (numSamples <= 0
  16833. || timePerPixel <= 0.0
  16834. || d->sampleRate <= 0)
  16835. {
  16836. numSamplesCached = 0;
  16837. cacheNeedsRefilling = true;
  16838. return;
  16839. }
  16840. if (numSamples == numSamplesCached
  16841. && numChannelsCached == d->numChannels
  16842. && startTime == cachedStart
  16843. && timePerPixel == cachedTimePerPixel
  16844. && ! cacheNeedsRefilling)
  16845. {
  16846. return;
  16847. }
  16848. numSamplesCached = numSamples;
  16849. numChannelsCached = d->numChannels;
  16850. cachedStart = startTime;
  16851. cachedTimePerPixel = timePerPixel;
  16852. cachedLevels.ensureSize (2 * numChannelsCached * numSamples);
  16853. const bool needExtraDetail = (timePerPixel * d->sampleRate <= d->samplesPerThumbSample);
  16854. const ScopedLock sl (readerLock);
  16855. cacheNeedsRefilling = false;
  16856. if (needExtraDetail && reader == 0)
  16857. reader = createReader();
  16858. if (reader != 0 && timePerPixel * d->sampleRate <= d->samplesPerThumbSample)
  16859. {
  16860. startTimer (timeBeforeDeletingReader);
  16861. char* cacheData = static_cast <char*> (cachedLevels.getData());
  16862. int sample = roundToInt (startTime * d->sampleRate);
  16863. for (int i = numSamples; --i >= 0;)
  16864. {
  16865. const int nextSample = roundToInt ((startTime + timePerPixel) * d->sampleRate);
  16866. if (sample >= 0)
  16867. {
  16868. if (sample >= reader->lengthInSamples)
  16869. break;
  16870. float lmin, lmax, rmin, rmax;
  16871. reader->readMaxLevels (sample,
  16872. jmax (1, nextSample - sample),
  16873. lmin, lmax, rmin, rmax);
  16874. cacheData[0] = (char) jlimit (-128, 127, roundFloatToInt (lmin * 127.0f));
  16875. cacheData[1] = (char) jlimit (-128, 127, roundFloatToInt (lmax * 127.0f));
  16876. if (numChannelsCached > 1)
  16877. {
  16878. cacheData[2] = (char) jlimit (-128, 127, roundFloatToInt (rmin * 127.0f));
  16879. cacheData[3] = (char) jlimit (-128, 127, roundFloatToInt (rmax * 127.0f));
  16880. }
  16881. cacheData += 2 * numChannelsCached;
  16882. }
  16883. startTime += timePerPixel;
  16884. sample = nextSample;
  16885. }
  16886. }
  16887. else
  16888. {
  16889. for (int channelNum = 0; channelNum < numChannelsCached; ++channelNum)
  16890. {
  16891. char* const channelData = getChannelData (channelNum);
  16892. char* cacheData = static_cast <char*> (cachedLevels.getData()) + channelNum * 2;
  16893. const double timeToThumbSampleFactor = d->sampleRate / (double) d->samplesPerThumbSample;
  16894. startTime = cachedStart;
  16895. int sample = roundToInt (startTime * timeToThumbSampleFactor);
  16896. const int numFinished = (int) (d->numFinishedSamples / d->samplesPerThumbSample);
  16897. for (int i = numSamples; --i >= 0;)
  16898. {
  16899. const int nextSample = roundToInt ((startTime + timePerPixel) * timeToThumbSampleFactor);
  16900. if (sample >= 0 && channelData != 0)
  16901. {
  16902. char mx = -128;
  16903. char mn = 127;
  16904. while (sample <= nextSample)
  16905. {
  16906. if (sample >= numFinished)
  16907. break;
  16908. const int n = sample << 1;
  16909. const char sampMin = channelData [n];
  16910. const char sampMax = channelData [n + 1];
  16911. if (sampMin < mn)
  16912. mn = sampMin;
  16913. if (sampMax > mx)
  16914. mx = sampMax;
  16915. ++sample;
  16916. }
  16917. if (mn <= mx)
  16918. {
  16919. cacheData[0] = mn;
  16920. cacheData[1] = mx;
  16921. }
  16922. else
  16923. {
  16924. cacheData[0] = 1;
  16925. cacheData[1] = 0;
  16926. }
  16927. }
  16928. else
  16929. {
  16930. cacheData[0] = 1;
  16931. cacheData[1] = 0;
  16932. }
  16933. cacheData += numChannelsCached * 2;
  16934. startTime += timePerPixel;
  16935. sample = nextSample;
  16936. }
  16937. }
  16938. }
  16939. }
  16940. void AudioThumbnail::drawChannel (Graphics& g,
  16941. int x, int y, int w, int h,
  16942. double startTime,
  16943. double endTime,
  16944. int channelNum,
  16945. const float verticalZoomFactor)
  16946. {
  16947. refillCache (w, startTime, (endTime - startTime) / w);
  16948. if (numSamplesCached >= w
  16949. && channelNum >= 0
  16950. && channelNum < numChannelsCached)
  16951. {
  16952. const float topY = (float) y;
  16953. const float bottomY = topY + h;
  16954. const float midY = topY + h * 0.5f;
  16955. const float vscale = verticalZoomFactor * h / 256.0f;
  16956. const Rectangle<int> clip (g.getClipBounds());
  16957. const int skipLeft = jlimit (0, w, clip.getX() - x);
  16958. w -= skipLeft;
  16959. x += skipLeft;
  16960. const char* cacheData = static_cast <const char*> (cachedLevels.getData())
  16961. + (channelNum << 1)
  16962. + skipLeft * (numChannelsCached << 1);
  16963. while (--w >= 0)
  16964. {
  16965. const char mn = cacheData[0];
  16966. const char mx = cacheData[1];
  16967. cacheData += numChannelsCached << 1;
  16968. if (mn <= mx) // if the wrong way round, signifies that the sample's not yet known
  16969. g.drawLine ((float) x, jmax (midY - mx * vscale - 0.3f, topY),
  16970. (float) x, jmin (midY - mn * vscale + 0.3f, bottomY));
  16971. ++x;
  16972. if (x >= clip.getRight())
  16973. break;
  16974. }
  16975. }
  16976. }
  16977. END_JUCE_NAMESPACE
  16978. /*** End of inlined file: juce_AudioThumbnail.cpp ***/
  16979. /*** Start of inlined file: juce_AudioThumbnailCache.cpp ***/
  16980. BEGIN_JUCE_NAMESPACE
  16981. struct ThumbnailCacheEntry
  16982. {
  16983. int64 hash;
  16984. uint32 lastUsed;
  16985. MemoryBlock data;
  16986. juce_UseDebuggingNewOperator
  16987. };
  16988. AudioThumbnailCache::AudioThumbnailCache (const int maxNumThumbsToStore_)
  16989. : TimeSliceThread ("thumb cache"),
  16990. maxNumThumbsToStore (maxNumThumbsToStore_)
  16991. {
  16992. startThread (2);
  16993. }
  16994. AudioThumbnailCache::~AudioThumbnailCache()
  16995. {
  16996. }
  16997. bool AudioThumbnailCache::loadThumb (AudioThumbnail& thumb, const int64 hashCode)
  16998. {
  16999. for (int i = thumbs.size(); --i >= 0;)
  17000. {
  17001. if (thumbs[i]->hash == hashCode)
  17002. {
  17003. MemoryInputStream in (thumbs[i]->data, false);
  17004. thumb.loadFrom (in);
  17005. thumbs[i]->lastUsed = Time::getMillisecondCounter();
  17006. return true;
  17007. }
  17008. }
  17009. return false;
  17010. }
  17011. void AudioThumbnailCache::storeThumb (const AudioThumbnail& thumb,
  17012. const int64 hashCode)
  17013. {
  17014. MemoryOutputStream out;
  17015. thumb.saveTo (out);
  17016. ThumbnailCacheEntry* te = 0;
  17017. for (int i = thumbs.size(); --i >= 0;)
  17018. {
  17019. if (thumbs[i]->hash == hashCode)
  17020. {
  17021. te = thumbs[i];
  17022. break;
  17023. }
  17024. }
  17025. if (te == 0)
  17026. {
  17027. te = new ThumbnailCacheEntry();
  17028. te->hash = hashCode;
  17029. if (thumbs.size() < maxNumThumbsToStore)
  17030. {
  17031. thumbs.add (te);
  17032. }
  17033. else
  17034. {
  17035. int oldest = 0;
  17036. unsigned int oldestTime = Time::getMillisecondCounter() + 1;
  17037. int i;
  17038. for (i = thumbs.size(); --i >= 0;)
  17039. if (thumbs[i]->lastUsed < oldestTime)
  17040. oldest = i;
  17041. thumbs.set (i, te);
  17042. }
  17043. }
  17044. te->lastUsed = Time::getMillisecondCounter();
  17045. te->data.setSize (0);
  17046. te->data.append (out.getData(), out.getDataSize());
  17047. }
  17048. void AudioThumbnailCache::clear()
  17049. {
  17050. thumbs.clear();
  17051. }
  17052. void AudioThumbnailCache::addThumbnail (AudioThumbnail* const thumb)
  17053. {
  17054. addTimeSliceClient (thumb);
  17055. }
  17056. void AudioThumbnailCache::removeThumbnail (AudioThumbnail* const thumb)
  17057. {
  17058. removeTimeSliceClient (thumb);
  17059. }
  17060. END_JUCE_NAMESPACE
  17061. /*** End of inlined file: juce_AudioThumbnailCache.cpp ***/
  17062. /*** Start of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  17063. #if JUCE_QUICKTIME && ! (JUCE_64BIT || JUCE_IPHONE)
  17064. #if ! JUCE_WINDOWS
  17065. #include <QuickTime/Movies.h>
  17066. #include <QuickTime/QTML.h>
  17067. #include <QuickTime/QuickTimeComponents.h>
  17068. #include <QuickTime/MediaHandlers.h>
  17069. #include <QuickTime/ImageCodec.h>
  17070. #else
  17071. #if JUCE_MSVC
  17072. #pragma warning (push)
  17073. #pragma warning (disable : 4100)
  17074. #endif
  17075. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  17076. add its header directory to your include path.
  17077. Alternatively, if you don't need any QuickTime services, just turn off the JUC_QUICKTIME
  17078. flag in juce_Config.h
  17079. */
  17080. #include <Movies.h>
  17081. #include <QTML.h>
  17082. #include <QuickTimeComponents.h>
  17083. #include <MediaHandlers.h>
  17084. #include <ImageCodec.h>
  17085. #if JUCE_MSVC
  17086. #pragma warning (pop)
  17087. #endif
  17088. #endif
  17089. BEGIN_JUCE_NAMESPACE
  17090. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  17091. static const char* const quickTimeFormatName = "QuickTime file";
  17092. static const char* const quickTimeExtensions[] = { ".mov", ".mp3", ".mp4", 0 };
  17093. class QTAudioReader : public AudioFormatReader
  17094. {
  17095. public:
  17096. QTAudioReader (InputStream* const input_, const int trackNum_)
  17097. : AudioFormatReader (input_, TRANS (quickTimeFormatName)),
  17098. ok (false),
  17099. movie (0),
  17100. trackNum (trackNum_),
  17101. lastSampleRead (0),
  17102. lastThreadId (0),
  17103. extractor (0),
  17104. dataHandle (0)
  17105. {
  17106. bufferList.calloc (256, 1);
  17107. #if JUCE_WINDOWS
  17108. if (InitializeQTML (0) != noErr)
  17109. return;
  17110. #endif
  17111. if (EnterMovies() != noErr)
  17112. return;
  17113. bool opened = juce_OpenQuickTimeMovieFromStream (input_, movie, dataHandle);
  17114. if (! opened)
  17115. return;
  17116. {
  17117. const int numTracks = GetMovieTrackCount (movie);
  17118. int trackCount = 0;
  17119. for (int i = 1; i <= numTracks; ++i)
  17120. {
  17121. track = GetMovieIndTrack (movie, i);
  17122. media = GetTrackMedia (track);
  17123. OSType mediaType;
  17124. GetMediaHandlerDescription (media, &mediaType, 0, 0);
  17125. if (mediaType == SoundMediaType
  17126. && trackCount++ == trackNum_)
  17127. {
  17128. ok = true;
  17129. break;
  17130. }
  17131. }
  17132. }
  17133. if (! ok)
  17134. return;
  17135. ok = false;
  17136. lengthInSamples = GetMediaDecodeDuration (media);
  17137. usesFloatingPointData = false;
  17138. samplesPerFrame = (int) (GetMediaDecodeDuration (media) / GetMediaSampleCount (media));
  17139. trackUnitsPerFrame = GetMovieTimeScale (movie) * samplesPerFrame
  17140. / GetMediaTimeScale (media);
  17141. OSStatus err = MovieAudioExtractionBegin (movie, 0, &extractor);
  17142. unsigned long output_layout_size;
  17143. err = MovieAudioExtractionGetPropertyInfo (extractor,
  17144. kQTPropertyClass_MovieAudioExtraction_Audio,
  17145. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  17146. 0, &output_layout_size, 0);
  17147. if (err != noErr)
  17148. return;
  17149. HeapBlock <AudioChannelLayout> qt_audio_channel_layout;
  17150. qt_audio_channel_layout.calloc (output_layout_size, 1);
  17151. err = MovieAudioExtractionGetProperty (extractor,
  17152. kQTPropertyClass_MovieAudioExtraction_Audio,
  17153. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  17154. output_layout_size, qt_audio_channel_layout, 0);
  17155. qt_audio_channel_layout[0].mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  17156. err = MovieAudioExtractionSetProperty (extractor,
  17157. kQTPropertyClass_MovieAudioExtraction_Audio,
  17158. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  17159. output_layout_size,
  17160. qt_audio_channel_layout);
  17161. err = MovieAudioExtractionGetProperty (extractor,
  17162. kQTPropertyClass_MovieAudioExtraction_Audio,
  17163. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  17164. sizeof (inputStreamDesc),
  17165. &inputStreamDesc, 0);
  17166. if (err != noErr)
  17167. return;
  17168. inputStreamDesc.mFormatFlags = kAudioFormatFlagIsSignedInteger
  17169. | kAudioFormatFlagIsPacked
  17170. | kAudioFormatFlagsNativeEndian;
  17171. inputStreamDesc.mBitsPerChannel = sizeof (SInt16) * 8;
  17172. inputStreamDesc.mChannelsPerFrame = jmin ((UInt32) 2, inputStreamDesc.mChannelsPerFrame);
  17173. inputStreamDesc.mBytesPerFrame = sizeof (SInt16) * inputStreamDesc.mChannelsPerFrame;
  17174. inputStreamDesc.mBytesPerPacket = inputStreamDesc.mBytesPerFrame;
  17175. err = MovieAudioExtractionSetProperty (extractor,
  17176. kQTPropertyClass_MovieAudioExtraction_Audio,
  17177. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  17178. sizeof (inputStreamDesc),
  17179. &inputStreamDesc);
  17180. if (err != noErr)
  17181. return;
  17182. Boolean allChannelsDiscrete = false;
  17183. err = MovieAudioExtractionSetProperty (extractor,
  17184. kQTPropertyClass_MovieAudioExtraction_Movie,
  17185. kQTMovieAudioExtractionMoviePropertyID_AllChannelsDiscrete,
  17186. sizeof (allChannelsDiscrete),
  17187. &allChannelsDiscrete);
  17188. if (err != noErr)
  17189. return;
  17190. bufferList->mNumberBuffers = 1;
  17191. bufferList->mBuffers[0].mNumberChannels = inputStreamDesc.mChannelsPerFrame;
  17192. bufferList->mBuffers[0].mDataByteSize = (UInt32) (samplesPerFrame * inputStreamDesc.mBytesPerFrame) + 16;
  17193. dataBuffer.malloc (bufferList->mBuffers[0].mDataByteSize);
  17194. bufferList->mBuffers[0].mData = dataBuffer;
  17195. sampleRate = inputStreamDesc.mSampleRate;
  17196. bitsPerSample = 16;
  17197. numChannels = inputStreamDesc.mChannelsPerFrame;
  17198. detachThread();
  17199. ok = true;
  17200. }
  17201. ~QTAudioReader()
  17202. {
  17203. if (dataHandle != 0)
  17204. DisposeHandle (dataHandle);
  17205. if (extractor != 0)
  17206. {
  17207. MovieAudioExtractionEnd (extractor);
  17208. extractor = 0;
  17209. }
  17210. checkThreadIsAttached();
  17211. DisposeMovie (movie);
  17212. #if JUCE_MAC
  17213. ExitMoviesOnThread ();
  17214. #endif
  17215. }
  17216. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  17217. int64 startSampleInFile, int numSamples)
  17218. {
  17219. checkThreadIsAttached();
  17220. while (numSamples > 0)
  17221. {
  17222. if (! loadFrame ((int) startSampleInFile))
  17223. return false;
  17224. const int numToDo = jmin (numSamples, samplesPerFrame);
  17225. for (int j = numDestChannels; --j >= 0;)
  17226. {
  17227. if (destSamples[j] != 0)
  17228. {
  17229. const short* const src = ((const short*) bufferList->mBuffers[0].mData) + j;
  17230. for (int i = 0; i < numToDo; ++i)
  17231. destSamples[j][startOffsetInDestBuffer + i] = src [i << 1] << 16;
  17232. }
  17233. }
  17234. startOffsetInDestBuffer += numToDo;
  17235. startSampleInFile += numToDo;
  17236. numSamples -= numToDo;
  17237. }
  17238. detachThread();
  17239. return true;
  17240. }
  17241. bool loadFrame (const int sampleNum)
  17242. {
  17243. if (lastSampleRead != sampleNum)
  17244. {
  17245. TimeRecord time;
  17246. time.scale = (TimeScale) inputStreamDesc.mSampleRate;
  17247. time.base = 0;
  17248. time.value.hi = 0;
  17249. time.value.lo = (UInt32) sampleNum;
  17250. OSStatus err = MovieAudioExtractionSetProperty (extractor,
  17251. kQTPropertyClass_MovieAudioExtraction_Movie,
  17252. kQTMovieAudioExtractionMoviePropertyID_CurrentTime,
  17253. sizeof (time), &time);
  17254. if (err != noErr)
  17255. return false;
  17256. }
  17257. bufferList->mBuffers[0].mDataByteSize = inputStreamDesc.mBytesPerFrame * samplesPerFrame;
  17258. UInt32 outFlags = 0;
  17259. UInt32 actualNumSamples = samplesPerFrame;
  17260. OSStatus err = MovieAudioExtractionFillBuffer (extractor, &actualNumSamples,
  17261. bufferList, &outFlags);
  17262. lastSampleRead = sampleNum + samplesPerFrame;
  17263. return err == noErr;
  17264. }
  17265. juce_UseDebuggingNewOperator
  17266. bool ok;
  17267. private:
  17268. Movie movie;
  17269. Media media;
  17270. Track track;
  17271. const int trackNum;
  17272. double trackUnitsPerFrame;
  17273. int samplesPerFrame;
  17274. int lastSampleRead;
  17275. Thread::ThreadID lastThreadId;
  17276. MovieAudioExtractionRef extractor;
  17277. AudioStreamBasicDescription inputStreamDesc;
  17278. HeapBlock <AudioBufferList> bufferList;
  17279. HeapBlock <char> dataBuffer;
  17280. Handle dataHandle;
  17281. void checkThreadIsAttached()
  17282. {
  17283. #if JUCE_MAC
  17284. if (Thread::getCurrentThreadId() != lastThreadId)
  17285. EnterMoviesOnThread (0);
  17286. AttachMovieToCurrentThread (movie);
  17287. #endif
  17288. }
  17289. void detachThread()
  17290. {
  17291. #if JUCE_MAC
  17292. DetachMovieFromCurrentThread (movie);
  17293. #endif
  17294. }
  17295. QTAudioReader (const QTAudioReader&);
  17296. QTAudioReader& operator= (const QTAudioReader&);
  17297. };
  17298. QuickTimeAudioFormat::QuickTimeAudioFormat()
  17299. : AudioFormat (TRANS (quickTimeFormatName), StringArray (quickTimeExtensions))
  17300. {
  17301. }
  17302. QuickTimeAudioFormat::~QuickTimeAudioFormat()
  17303. {
  17304. }
  17305. const Array <int> QuickTimeAudioFormat::getPossibleSampleRates()
  17306. {
  17307. return Array<int>();
  17308. }
  17309. const Array <int> QuickTimeAudioFormat::getPossibleBitDepths()
  17310. {
  17311. return Array<int>();
  17312. }
  17313. bool QuickTimeAudioFormat::canDoStereo()
  17314. {
  17315. return true;
  17316. }
  17317. bool QuickTimeAudioFormat::canDoMono()
  17318. {
  17319. return true;
  17320. }
  17321. AudioFormatReader* QuickTimeAudioFormat::createReaderFor (InputStream* sourceStream,
  17322. const bool deleteStreamIfOpeningFails)
  17323. {
  17324. ScopedPointer <QTAudioReader> r (new QTAudioReader (sourceStream, 0));
  17325. if (r->ok)
  17326. return r.release();
  17327. if (! deleteStreamIfOpeningFails)
  17328. r->input = 0;
  17329. return 0;
  17330. }
  17331. AudioFormatWriter* QuickTimeAudioFormat::createWriterFor (OutputStream* /*streamToWriteTo*/,
  17332. double /*sampleRateToUse*/,
  17333. unsigned int /*numberOfChannels*/,
  17334. int /*bitsPerSample*/,
  17335. const StringPairArray& /*metadataValues*/,
  17336. int /*qualityOptionIndex*/)
  17337. {
  17338. jassertfalse; // not yet implemented!
  17339. return 0;
  17340. }
  17341. END_JUCE_NAMESPACE
  17342. #endif
  17343. /*** End of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  17344. /*** Start of inlined file: juce_WavAudioFormat.cpp ***/
  17345. BEGIN_JUCE_NAMESPACE
  17346. static const char* const wavFormatName = "WAV file";
  17347. static const char* const wavExtensions[] = { ".wav", ".bwf", 0 };
  17348. const char* const WavAudioFormat::bwavDescription = "bwav description";
  17349. const char* const WavAudioFormat::bwavOriginator = "bwav originator";
  17350. const char* const WavAudioFormat::bwavOriginatorRef = "bwav originator ref";
  17351. const char* const WavAudioFormat::bwavOriginationDate = "bwav origination date";
  17352. const char* const WavAudioFormat::bwavOriginationTime = "bwav origination time";
  17353. const char* const WavAudioFormat::bwavTimeReference = "bwav time reference";
  17354. const char* const WavAudioFormat::bwavCodingHistory = "bwav coding history";
  17355. const StringPairArray WavAudioFormat::createBWAVMetadata (const String& description,
  17356. const String& originator,
  17357. const String& originatorRef,
  17358. const Time& date,
  17359. const int64 timeReferenceSamples,
  17360. const String& codingHistory)
  17361. {
  17362. StringPairArray m;
  17363. m.set (bwavDescription, description);
  17364. m.set (bwavOriginator, originator);
  17365. m.set (bwavOriginatorRef, originatorRef);
  17366. m.set (bwavOriginationDate, date.formatted ("%Y-%m-%d"));
  17367. m.set (bwavOriginationTime, date.formatted ("%H:%M:%S"));
  17368. m.set (bwavTimeReference, String (timeReferenceSamples));
  17369. m.set (bwavCodingHistory, codingHistory);
  17370. return m;
  17371. }
  17372. #if JUCE_MSVC
  17373. #pragma pack (push, 1)
  17374. #define PACKED
  17375. #elif JUCE_GCC
  17376. #define PACKED __attribute__((packed))
  17377. #else
  17378. #define PACKED
  17379. #endif
  17380. struct BWAVChunk
  17381. {
  17382. char description [256];
  17383. char originator [32];
  17384. char originatorRef [32];
  17385. char originationDate [10];
  17386. char originationTime [8];
  17387. uint32 timeRefLow;
  17388. uint32 timeRefHigh;
  17389. uint16 version;
  17390. uint8 umid[64];
  17391. uint8 reserved[190];
  17392. char codingHistory[1];
  17393. void copyTo (StringPairArray& values) const
  17394. {
  17395. values.set (WavAudioFormat::bwavDescription, String::fromUTF8 (description, 256));
  17396. values.set (WavAudioFormat::bwavOriginator, String::fromUTF8 (originator, 32));
  17397. values.set (WavAudioFormat::bwavOriginatorRef, String::fromUTF8 (originatorRef, 32));
  17398. values.set (WavAudioFormat::bwavOriginationDate, String::fromUTF8 (originationDate, 10));
  17399. values.set (WavAudioFormat::bwavOriginationTime, String::fromUTF8 (originationTime, 8));
  17400. const uint32 timeLow = ByteOrder::swapIfBigEndian (timeRefLow);
  17401. const uint32 timeHigh = ByteOrder::swapIfBigEndian (timeRefHigh);
  17402. const int64 time = (((int64)timeHigh) << 32) + timeLow;
  17403. values.set (WavAudioFormat::bwavTimeReference, String (time));
  17404. values.set (WavAudioFormat::bwavCodingHistory, String::fromUTF8 (codingHistory));
  17405. }
  17406. static MemoryBlock createFrom (const StringPairArray& values)
  17407. {
  17408. const size_t sizeNeeded = sizeof (BWAVChunk) + values [WavAudioFormat::bwavCodingHistory].getNumBytesAsUTF8();
  17409. MemoryBlock data ((sizeNeeded + 3) & ~3);
  17410. data.fillWith (0);
  17411. BWAVChunk* b = (BWAVChunk*) data.getData();
  17412. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  17413. // as they get called in the right order..
  17414. values [WavAudioFormat::bwavDescription].copyToUTF8 (b->description, 257);
  17415. values [WavAudioFormat::bwavOriginator].copyToUTF8 (b->originator, 33);
  17416. values [WavAudioFormat::bwavOriginatorRef].copyToUTF8 (b->originatorRef, 33);
  17417. values [WavAudioFormat::bwavOriginationDate].copyToUTF8 (b->originationDate, 11);
  17418. values [WavAudioFormat::bwavOriginationTime].copyToUTF8 (b->originationTime, 9);
  17419. const int64 time = values [WavAudioFormat::bwavTimeReference].getLargeIntValue();
  17420. b->timeRefLow = ByteOrder::swapIfBigEndian ((uint32) (time & 0xffffffff));
  17421. b->timeRefHigh = ByteOrder::swapIfBigEndian ((uint32) (time >> 32));
  17422. values [WavAudioFormat::bwavCodingHistory].copyToUTF8 (b->codingHistory, 0x7fffffff);
  17423. if (b->description[0] != 0
  17424. || b->originator[0] != 0
  17425. || b->originationDate[0] != 0
  17426. || b->originationTime[0] != 0
  17427. || b->codingHistory[0] != 0
  17428. || time != 0)
  17429. {
  17430. return data;
  17431. }
  17432. return MemoryBlock();
  17433. }
  17434. } PACKED;
  17435. struct SMPLChunk
  17436. {
  17437. struct SampleLoop
  17438. {
  17439. uint32 identifier;
  17440. uint32 type;
  17441. uint32 start;
  17442. uint32 end;
  17443. uint32 fraction;
  17444. uint32 playCount;
  17445. } PACKED;
  17446. uint32 manufacturer;
  17447. uint32 product;
  17448. uint32 samplePeriod;
  17449. uint32 midiUnityNote;
  17450. uint32 midiPitchFraction;
  17451. uint32 smpteFormat;
  17452. uint32 smpteOffset;
  17453. uint32 numSampleLoops;
  17454. uint32 samplerData;
  17455. SampleLoop loops[1];
  17456. void copyTo (StringPairArray& values, const int totalSize) const
  17457. {
  17458. values.set ("Manufacturer", String (ByteOrder::swapIfBigEndian (manufacturer)));
  17459. values.set ("Product", String (ByteOrder::swapIfBigEndian (product)));
  17460. values.set ("SamplePeriod", String (ByteOrder::swapIfBigEndian (samplePeriod)));
  17461. values.set ("MidiUnityNote", String (ByteOrder::swapIfBigEndian (midiUnityNote)));
  17462. values.set ("MidiPitchFraction", String (ByteOrder::swapIfBigEndian (midiPitchFraction)));
  17463. values.set ("SmpteFormat", String (ByteOrder::swapIfBigEndian (smpteFormat)));
  17464. values.set ("SmpteOffset", String (ByteOrder::swapIfBigEndian (smpteOffset)));
  17465. values.set ("NumSampleLoops", String (ByteOrder::swapIfBigEndian (numSampleLoops)));
  17466. values.set ("SamplerData", String (ByteOrder::swapIfBigEndian (samplerData)));
  17467. for (uint32 i = 0; i < numSampleLoops; ++i)
  17468. {
  17469. if ((uint8*) (loops + (i + 1)) > ((uint8*) this) + totalSize)
  17470. break;
  17471. const String prefix ("Loop" + String(i));
  17472. values.set (prefix + "Identifier", String (ByteOrder::swapIfBigEndian (loops[i].identifier)));
  17473. values.set (prefix + "Type", String (ByteOrder::swapIfBigEndian (loops[i].type)));
  17474. values.set (prefix + "Start", String (ByteOrder::swapIfBigEndian (loops[i].start)));
  17475. values.set (prefix + "End", String (ByteOrder::swapIfBigEndian (loops[i].end)));
  17476. values.set (prefix + "Fraction", String (ByteOrder::swapIfBigEndian (loops[i].fraction)));
  17477. values.set (prefix + "PlayCount", String (ByteOrder::swapIfBigEndian (loops[i].playCount)));
  17478. }
  17479. }
  17480. static MemoryBlock createFrom (const StringPairArray& values)
  17481. {
  17482. const int numLoops = jmin (64, values.getValue ("NumSampleLoops", "0").getIntValue());
  17483. if (numLoops <= 0)
  17484. return MemoryBlock();
  17485. const size_t sizeNeeded = sizeof (SMPLChunk) + (numLoops - 1) * sizeof (SampleLoop);
  17486. MemoryBlock data ((sizeNeeded + 3) & ~3);
  17487. data.fillWith (0);
  17488. SMPLChunk* s = (SMPLChunk*) data.getData();
  17489. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  17490. // as they get called in the right order..
  17491. s->manufacturer = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Manufacturer", "0").getIntValue());
  17492. s->product = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Product", "0").getIntValue());
  17493. s->samplePeriod = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplePeriod", "0").getIntValue());
  17494. s->midiUnityNote = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiUnityNote", "60").getIntValue());
  17495. s->midiPitchFraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiPitchFraction", "0").getIntValue());
  17496. s->smpteFormat = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteFormat", "0").getIntValue());
  17497. s->smpteOffset = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteOffset", "0").getIntValue());
  17498. s->numSampleLoops = ByteOrder::swapIfBigEndian ((uint32) numLoops);
  17499. s->samplerData = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplerData", "0").getIntValue());
  17500. for (int i = 0; i < numLoops; ++i)
  17501. {
  17502. const String prefix ("Loop" + String(i));
  17503. s->loops[i].identifier = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Identifier", "0").getIntValue());
  17504. s->loops[i].type = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Type", "0").getIntValue());
  17505. s->loops[i].start = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Start", "0").getIntValue());
  17506. s->loops[i].end = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "End", "0").getIntValue());
  17507. s->loops[i].fraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Fraction", "0").getIntValue());
  17508. s->loops[i].playCount = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "PlayCount", "0").getIntValue());
  17509. }
  17510. return data;
  17511. }
  17512. } PACKED;
  17513. struct ExtensibleWavSubFormat
  17514. {
  17515. uint32 data1;
  17516. uint16 data2;
  17517. uint16 data3;
  17518. uint8 data4[8];
  17519. } PACKED;
  17520. #if JUCE_MSVC
  17521. #pragma pack (pop)
  17522. #endif
  17523. #undef PACKED
  17524. class WavAudioFormatReader : public AudioFormatReader
  17525. {
  17526. int bytesPerFrame;
  17527. int64 dataChunkStart, dataLength;
  17528. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  17529. WavAudioFormatReader (const WavAudioFormatReader&);
  17530. WavAudioFormatReader& operator= (const WavAudioFormatReader&);
  17531. public:
  17532. int64 bwavChunkStart, bwavSize;
  17533. WavAudioFormatReader (InputStream* const in)
  17534. : AudioFormatReader (in, TRANS (wavFormatName)),
  17535. dataLength (0),
  17536. bwavChunkStart (0),
  17537. bwavSize (0)
  17538. {
  17539. if (input->readInt() == chunkName ("RIFF"))
  17540. {
  17541. const uint32 len = (uint32) input->readInt();
  17542. const int64 end = input->getPosition() + len;
  17543. bool hasGotType = false;
  17544. bool hasGotData = false;
  17545. if (input->readInt() == chunkName ("WAVE"))
  17546. {
  17547. while (input->getPosition() < end
  17548. && ! input->isExhausted())
  17549. {
  17550. const int chunkType = input->readInt();
  17551. uint32 length = (uint32) input->readInt();
  17552. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  17553. if (chunkType == chunkName ("fmt "))
  17554. {
  17555. // read the format chunk
  17556. const unsigned short format = input->readShort();
  17557. const short numChans = input->readShort();
  17558. sampleRate = input->readInt();
  17559. const int bytesPerSec = input->readInt();
  17560. numChannels = numChans;
  17561. bytesPerFrame = bytesPerSec / (int)sampleRate;
  17562. bitsPerSample = 8 * bytesPerFrame / numChans;
  17563. if (format == 3)
  17564. {
  17565. usesFloatingPointData = true;
  17566. }
  17567. else if (format == 0xfffe /*WAVE_FORMAT_EXTENSIBLE*/)
  17568. {
  17569. if (length < 40) // too short
  17570. {
  17571. bytesPerFrame = 0;
  17572. }
  17573. else
  17574. {
  17575. input->skipNextBytes (12); // skip over blockAlign, bitsPerSample and speakerPosition mask
  17576. ExtensibleWavSubFormat subFormat;
  17577. subFormat.data1 = input->readInt();
  17578. subFormat.data2 = input->readShort();
  17579. subFormat.data3 = input->readShort();
  17580. input->read (subFormat.data4, sizeof (subFormat.data4));
  17581. const ExtensibleWavSubFormat pcmFormat
  17582. = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  17583. if (memcmp (&subFormat, &pcmFormat, sizeof (subFormat)) != 0)
  17584. {
  17585. const ExtensibleWavSubFormat ambisonicFormat
  17586. = { 0x00000001, 0x0721, 0x11d3, { 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00 } };
  17587. if (memcmp (&subFormat, &ambisonicFormat, sizeof (subFormat)) != 0)
  17588. bytesPerFrame = 0;
  17589. }
  17590. }
  17591. }
  17592. else if (format != 1)
  17593. {
  17594. bytesPerFrame = 0;
  17595. }
  17596. hasGotType = true;
  17597. }
  17598. else if (chunkType == chunkName ("data"))
  17599. {
  17600. // get the data chunk's position
  17601. dataLength = length;
  17602. dataChunkStart = input->getPosition();
  17603. lengthInSamples = (bytesPerFrame > 0) ? (dataLength / bytesPerFrame) : 0;
  17604. hasGotData = true;
  17605. }
  17606. else if (chunkType == chunkName ("bext"))
  17607. {
  17608. bwavChunkStart = input->getPosition();
  17609. bwavSize = length;
  17610. // Broadcast-wav extension chunk..
  17611. HeapBlock <BWAVChunk> bwav;
  17612. bwav.calloc (jmax ((size_t) length + 1, sizeof (BWAVChunk)), 1);
  17613. input->read (bwav, length);
  17614. bwav->copyTo (metadataValues);
  17615. }
  17616. else if (chunkType == chunkName ("smpl"))
  17617. {
  17618. HeapBlock <SMPLChunk> smpl;
  17619. smpl.calloc (jmax ((size_t) length + 1, sizeof (SMPLChunk)), 1);
  17620. input->read (smpl, length);
  17621. smpl->copyTo (metadataValues, length);
  17622. }
  17623. else if (chunkEnd <= input->getPosition())
  17624. {
  17625. break;
  17626. }
  17627. input->setPosition (chunkEnd);
  17628. }
  17629. }
  17630. }
  17631. }
  17632. ~WavAudioFormatReader()
  17633. {
  17634. }
  17635. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  17636. int64 startSampleInFile, int numSamples)
  17637. {
  17638. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  17639. if (samplesAvailable < numSamples)
  17640. {
  17641. for (int i = numDestChannels; --i >= 0;)
  17642. if (destSamples[i] != 0)
  17643. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  17644. numSamples = (int) samplesAvailable;
  17645. }
  17646. if (numSamples <= 0)
  17647. return true;
  17648. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  17649. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  17650. char tempBuffer [tempBufSize];
  17651. while (numSamples > 0)
  17652. {
  17653. int* left = destSamples[0];
  17654. if (left != 0)
  17655. left += startOffsetInDestBuffer;
  17656. int* right = numDestChannels > 1 ? destSamples[1] : 0;
  17657. if (right != 0)
  17658. right += startOffsetInDestBuffer;
  17659. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  17660. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  17661. if (bytesRead < numThisTime * bytesPerFrame)
  17662. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  17663. if (bitsPerSample == 16)
  17664. {
  17665. const short* src = reinterpret_cast <const short*> (tempBuffer);
  17666. if (numChannels > 1)
  17667. {
  17668. if (left == 0)
  17669. {
  17670. for (int i = numThisTime; --i >= 0;)
  17671. {
  17672. ++src;
  17673. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17674. }
  17675. }
  17676. else if (right == 0)
  17677. {
  17678. for (int i = numThisTime; --i >= 0;)
  17679. {
  17680. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17681. ++src;
  17682. }
  17683. }
  17684. else
  17685. {
  17686. for (int i = numThisTime; --i >= 0;)
  17687. {
  17688. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17689. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17690. }
  17691. }
  17692. }
  17693. else
  17694. {
  17695. for (int i = numThisTime; --i >= 0;)
  17696. {
  17697. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17698. }
  17699. }
  17700. }
  17701. else if (bitsPerSample == 24)
  17702. {
  17703. const char* src = tempBuffer;
  17704. if (numChannels > 1)
  17705. {
  17706. if (left == 0)
  17707. {
  17708. for (int i = numThisTime; --i >= 0;)
  17709. {
  17710. src += 3;
  17711. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  17712. src += 3;
  17713. }
  17714. }
  17715. else if (right == 0)
  17716. {
  17717. for (int i = numThisTime; --i >= 0;)
  17718. {
  17719. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  17720. src += 6;
  17721. }
  17722. }
  17723. else
  17724. {
  17725. for (int i = 0; i < numThisTime; ++i)
  17726. {
  17727. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  17728. src += 3;
  17729. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  17730. src += 3;
  17731. }
  17732. }
  17733. }
  17734. else
  17735. {
  17736. for (int i = 0; i < numThisTime; ++i)
  17737. {
  17738. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  17739. src += 3;
  17740. }
  17741. }
  17742. }
  17743. else if (bitsPerSample == 32)
  17744. {
  17745. const unsigned int* src = (const unsigned int*) tempBuffer;
  17746. unsigned int* l = (unsigned int*) left;
  17747. unsigned int* r = (unsigned int*) right;
  17748. if (numChannels > 1)
  17749. {
  17750. if (l == 0)
  17751. {
  17752. for (int i = numThisTime; --i >= 0;)
  17753. {
  17754. ++src;
  17755. *r++ = ByteOrder::swapIfBigEndian (*src++);
  17756. }
  17757. }
  17758. else if (r == 0)
  17759. {
  17760. for (int i = numThisTime; --i >= 0;)
  17761. {
  17762. *l++ = ByteOrder::swapIfBigEndian (*src++);
  17763. ++src;
  17764. }
  17765. }
  17766. else
  17767. {
  17768. for (int i = numThisTime; --i >= 0;)
  17769. {
  17770. *l++ = ByteOrder::swapIfBigEndian (*src++);
  17771. *r++ = ByteOrder::swapIfBigEndian (*src++);
  17772. }
  17773. }
  17774. }
  17775. else
  17776. {
  17777. for (int i = numThisTime; --i >= 0;)
  17778. {
  17779. *l++ = ByteOrder::swapIfBigEndian (*src++);
  17780. }
  17781. }
  17782. left = (int*)l;
  17783. right = (int*)r;
  17784. }
  17785. else if (bitsPerSample == 8)
  17786. {
  17787. const unsigned char* src = (const unsigned char*) tempBuffer;
  17788. if (numChannels > 1)
  17789. {
  17790. if (left == 0)
  17791. {
  17792. for (int i = numThisTime; --i >= 0;)
  17793. {
  17794. ++src;
  17795. *right++ = ((int) *src++ - 128) << 24;
  17796. }
  17797. }
  17798. else if (right == 0)
  17799. {
  17800. for (int i = numThisTime; --i >= 0;)
  17801. {
  17802. *left++ = ((int) *src++ - 128) << 24;
  17803. ++src;
  17804. }
  17805. }
  17806. else
  17807. {
  17808. for (int i = numThisTime; --i >= 0;)
  17809. {
  17810. *left++ = ((int) *src++ - 128) << 24;
  17811. *right++ = ((int) *src++ - 128) << 24;
  17812. }
  17813. }
  17814. }
  17815. else
  17816. {
  17817. for (int i = numThisTime; --i >= 0;)
  17818. {
  17819. *left++ = ((int)*src++ - 128) << 24;
  17820. }
  17821. }
  17822. }
  17823. startOffsetInDestBuffer += numThisTime;
  17824. numSamples -= numThisTime;
  17825. }
  17826. if (numSamples > 0)
  17827. {
  17828. for (int i = numDestChannels; --i >= 0;)
  17829. if (destSamples[i] != 0)
  17830. zeromem (destSamples[i] + startOffsetInDestBuffer,
  17831. sizeof (int) * numSamples);
  17832. }
  17833. return true;
  17834. }
  17835. juce_UseDebuggingNewOperator
  17836. };
  17837. class WavAudioFormatWriter : public AudioFormatWriter
  17838. {
  17839. MemoryBlock tempBlock, bwavChunk, smplChunk;
  17840. uint32 lengthInSamples, bytesWritten;
  17841. int64 headerPosition;
  17842. bool writeFailed;
  17843. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  17844. WavAudioFormatWriter (const WavAudioFormatWriter&);
  17845. WavAudioFormatWriter& operator= (const WavAudioFormatWriter&);
  17846. void writeHeader()
  17847. {
  17848. const bool seekedOk = output->setPosition (headerPosition);
  17849. (void) seekedOk;
  17850. // if this fails, you've given it an output stream that can't seek! It needs
  17851. // to be able to seek back to write the header
  17852. jassert (seekedOk);
  17853. const int bytesPerFrame = numChannels * bitsPerSample / 8;
  17854. output->writeInt (chunkName ("RIFF"));
  17855. output->writeInt ((int) (lengthInSamples * bytesPerFrame
  17856. + ((bwavChunk.getSize() > 0) ? (44 + bwavChunk.getSize()) : 36)));
  17857. output->writeInt (chunkName ("WAVE"));
  17858. output->writeInt (chunkName ("fmt "));
  17859. output->writeInt (16);
  17860. output->writeShort ((bitsPerSample < 32) ? (short) 1 /*WAVE_FORMAT_PCM*/
  17861. : (short) 3 /*WAVE_FORMAT_IEEE_FLOAT*/);
  17862. output->writeShort ((short) numChannels);
  17863. output->writeInt ((int) sampleRate);
  17864. output->writeInt (bytesPerFrame * (int) sampleRate);
  17865. output->writeShort ((short) bytesPerFrame);
  17866. output->writeShort ((short) bitsPerSample);
  17867. if (bwavChunk.getSize() > 0)
  17868. {
  17869. output->writeInt (chunkName ("bext"));
  17870. output->writeInt ((int) bwavChunk.getSize());
  17871. output->write (bwavChunk.getData(), (int) bwavChunk.getSize());
  17872. }
  17873. if (smplChunk.getSize() > 0)
  17874. {
  17875. output->writeInt (chunkName ("smpl"));
  17876. output->writeInt ((int) smplChunk.getSize());
  17877. output->write (smplChunk.getData(), (int) smplChunk.getSize());
  17878. }
  17879. output->writeInt (chunkName ("data"));
  17880. output->writeInt (lengthInSamples * bytesPerFrame);
  17881. usesFloatingPointData = (bitsPerSample == 32);
  17882. }
  17883. public:
  17884. WavAudioFormatWriter (OutputStream* const out,
  17885. const double sampleRate_,
  17886. const unsigned int numChannels_,
  17887. const int bits,
  17888. const StringPairArray& metadataValues)
  17889. : AudioFormatWriter (out,
  17890. TRANS (wavFormatName),
  17891. sampleRate_,
  17892. numChannels_,
  17893. bits),
  17894. lengthInSamples (0),
  17895. bytesWritten (0),
  17896. writeFailed (false)
  17897. {
  17898. if (metadataValues.size() > 0)
  17899. {
  17900. bwavChunk = BWAVChunk::createFrom (metadataValues);
  17901. smplChunk = SMPLChunk::createFrom (metadataValues);
  17902. }
  17903. headerPosition = out->getPosition();
  17904. writeHeader();
  17905. }
  17906. ~WavAudioFormatWriter()
  17907. {
  17908. writeHeader();
  17909. }
  17910. bool write (const int** data, int numSamples)
  17911. {
  17912. if (writeFailed)
  17913. return false;
  17914. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  17915. tempBlock.ensureSize (bytes, false);
  17916. char* buffer = static_cast <char*> (tempBlock.getData());
  17917. const int* left = data[0];
  17918. const int* right = data[1];
  17919. if (right == 0)
  17920. right = left;
  17921. if (bitsPerSample == 16)
  17922. {
  17923. short* b = (short*) buffer;
  17924. if (numChannels > 1)
  17925. {
  17926. for (int i = numSamples; --i >= 0;)
  17927. {
  17928. *b++ = (short) ByteOrder::swapIfBigEndian ((unsigned short) (*left++ >> 16));
  17929. *b++ = (short) ByteOrder::swapIfBigEndian ((unsigned short) (*right++ >> 16));
  17930. }
  17931. }
  17932. else
  17933. {
  17934. for (int i = numSamples; --i >= 0;)
  17935. {
  17936. *b++ = (short) ByteOrder::swapIfBigEndian ((unsigned short) (*left++ >> 16));
  17937. }
  17938. }
  17939. }
  17940. else if (bitsPerSample == 24)
  17941. {
  17942. char* b = buffer;
  17943. if (numChannels > 1)
  17944. {
  17945. for (int i = numSamples; --i >= 0;)
  17946. {
  17947. ByteOrder::littleEndian24BitToChars ((*left++) >> 8, b);
  17948. b += 3;
  17949. ByteOrder::littleEndian24BitToChars ((*right++) >> 8, b);
  17950. b += 3;
  17951. }
  17952. }
  17953. else
  17954. {
  17955. for (int i = numSamples; --i >= 0;)
  17956. {
  17957. ByteOrder::littleEndian24BitToChars ((*left++) >> 8, b);
  17958. b += 3;
  17959. }
  17960. }
  17961. }
  17962. else if (bitsPerSample == 32)
  17963. {
  17964. unsigned int* b = (unsigned int*) buffer;
  17965. if (numChannels > 1)
  17966. {
  17967. for (int i = numSamples; --i >= 0;)
  17968. {
  17969. *b++ = ByteOrder::swapIfBigEndian ((unsigned int) *left++);
  17970. *b++ = ByteOrder::swapIfBigEndian ((unsigned int) *right++);
  17971. }
  17972. }
  17973. else
  17974. {
  17975. for (int i = numSamples; --i >= 0;)
  17976. {
  17977. *b++ = ByteOrder::swapIfBigEndian ((unsigned int) *left++);
  17978. }
  17979. }
  17980. }
  17981. else if (bitsPerSample == 8)
  17982. {
  17983. unsigned char* b = (unsigned char*) buffer;
  17984. if (numChannels > 1)
  17985. {
  17986. for (int i = numSamples; --i >= 0;)
  17987. {
  17988. *b++ = (unsigned char) (128 + (*left++ >> 24));
  17989. *b++ = (unsigned char) (128 + (*right++ >> 24));
  17990. }
  17991. }
  17992. else
  17993. {
  17994. for (int i = numSamples; --i >= 0;)
  17995. {
  17996. *b++ = (unsigned char) (128 + (*left++ >> 24));
  17997. }
  17998. }
  17999. }
  18000. if (bytesWritten + bytes >= (uint32) 0xfff00000
  18001. || ! output->write (buffer, bytes))
  18002. {
  18003. // failed to write to disk, so let's try writing the header.
  18004. // If it's just run out of disk space, then if it does manage
  18005. // to write the header, we'll still have a useable file..
  18006. writeHeader();
  18007. writeFailed = true;
  18008. return false;
  18009. }
  18010. else
  18011. {
  18012. bytesWritten += bytes;
  18013. lengthInSamples += numSamples;
  18014. return true;
  18015. }
  18016. }
  18017. juce_UseDebuggingNewOperator
  18018. };
  18019. WavAudioFormat::WavAudioFormat()
  18020. : AudioFormat (TRANS (wavFormatName), StringArray (wavExtensions))
  18021. {
  18022. }
  18023. WavAudioFormat::~WavAudioFormat()
  18024. {
  18025. }
  18026. const Array <int> WavAudioFormat::getPossibleSampleRates()
  18027. {
  18028. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  18029. return Array <int> (rates);
  18030. }
  18031. const Array <int> WavAudioFormat::getPossibleBitDepths()
  18032. {
  18033. const int depths[] = { 8, 16, 24, 32, 0 };
  18034. return Array <int> (depths);
  18035. }
  18036. bool WavAudioFormat::canDoStereo()
  18037. {
  18038. return true;
  18039. }
  18040. bool WavAudioFormat::canDoMono()
  18041. {
  18042. return true;
  18043. }
  18044. AudioFormatReader* WavAudioFormat::createReaderFor (InputStream* sourceStream,
  18045. const bool deleteStreamIfOpeningFails)
  18046. {
  18047. ScopedPointer <WavAudioFormatReader> r (new WavAudioFormatReader (sourceStream));
  18048. if (r->sampleRate != 0)
  18049. return r.release();
  18050. if (! deleteStreamIfOpeningFails)
  18051. r->input = 0;
  18052. return 0;
  18053. }
  18054. AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out,
  18055. double sampleRate,
  18056. unsigned int numChannels,
  18057. int bitsPerSample,
  18058. const StringPairArray& metadataValues,
  18059. int /*qualityOptionIndex*/)
  18060. {
  18061. if (getPossibleBitDepths().contains (bitsPerSample))
  18062. {
  18063. return new WavAudioFormatWriter (out,
  18064. sampleRate,
  18065. numChannels,
  18066. bitsPerSample,
  18067. metadataValues);
  18068. }
  18069. return 0;
  18070. }
  18071. static bool juce_slowCopyOfWavFileWithNewMetadata (const File& file, const StringPairArray& metadata)
  18072. {
  18073. TemporaryFile tempFile (file);
  18074. WavAudioFormat wav;
  18075. ScopedPointer <AudioFormatReader> reader (wav.createReaderFor (file.createInputStream(), true));
  18076. if (reader != 0)
  18077. {
  18078. ScopedPointer <OutputStream> outStream (tempFile.getFile().createOutputStream());
  18079. if (outStream != 0)
  18080. {
  18081. ScopedPointer <AudioFormatWriter> writer (wav.createWriterFor (outStream, reader->sampleRate,
  18082. reader->numChannels, reader->bitsPerSample,
  18083. metadata, 0));
  18084. if (writer != 0)
  18085. {
  18086. outStream.release();
  18087. bool ok = writer->writeFromAudioReader (*reader, 0, -1);
  18088. writer = 0;
  18089. reader = 0;
  18090. return ok && tempFile.overwriteTargetFileWithTemporary();
  18091. }
  18092. }
  18093. }
  18094. return false;
  18095. }
  18096. bool WavAudioFormat::replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata)
  18097. {
  18098. ScopedPointer <WavAudioFormatReader> reader ((WavAudioFormatReader*) createReaderFor (wavFile.createInputStream(), true));
  18099. if (reader != 0)
  18100. {
  18101. const int64 bwavPos = reader->bwavChunkStart;
  18102. const int64 bwavSize = reader->bwavSize;
  18103. reader = 0;
  18104. if (bwavSize > 0)
  18105. {
  18106. MemoryBlock chunk = BWAVChunk::createFrom (newMetadata);
  18107. if (chunk.getSize() <= (size_t) bwavSize)
  18108. {
  18109. // the new one will fit in the space available, so write it directly..
  18110. const int64 oldSize = wavFile.getSize();
  18111. {
  18112. ScopedPointer <FileOutputStream> out (wavFile.createOutputStream());
  18113. out->setPosition (bwavPos);
  18114. out->write (chunk.getData(), (int) chunk.getSize());
  18115. out->setPosition (oldSize);
  18116. }
  18117. jassert (wavFile.getSize() == oldSize);
  18118. return true;
  18119. }
  18120. }
  18121. }
  18122. return juce_slowCopyOfWavFileWithNewMetadata (wavFile, newMetadata);
  18123. }
  18124. END_JUCE_NAMESPACE
  18125. /*** End of inlined file: juce_WavAudioFormat.cpp ***/
  18126. /*** Start of inlined file: juce_AudioFormatReaderSource.cpp ***/
  18127. BEGIN_JUCE_NAMESPACE
  18128. AudioFormatReaderSource::AudioFormatReaderSource (AudioFormatReader* const reader_,
  18129. const bool deleteReaderWhenThisIsDeleted)
  18130. : reader (reader_),
  18131. deleteReader (deleteReaderWhenThisIsDeleted),
  18132. nextPlayPos (0),
  18133. looping (false)
  18134. {
  18135. jassert (reader != 0);
  18136. }
  18137. AudioFormatReaderSource::~AudioFormatReaderSource()
  18138. {
  18139. releaseResources();
  18140. if (deleteReader)
  18141. delete reader;
  18142. }
  18143. void AudioFormatReaderSource::setNextReadPosition (int newPosition)
  18144. {
  18145. nextPlayPos = newPosition;
  18146. }
  18147. void AudioFormatReaderSource::setLooping (const bool shouldLoop) throw()
  18148. {
  18149. looping = shouldLoop;
  18150. }
  18151. int AudioFormatReaderSource::getNextReadPosition() const
  18152. {
  18153. return (looping) ? (nextPlayPos % (int) reader->lengthInSamples)
  18154. : nextPlayPos;
  18155. }
  18156. int AudioFormatReaderSource::getTotalLength() const
  18157. {
  18158. return (int) reader->lengthInSamples;
  18159. }
  18160. void AudioFormatReaderSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  18161. double /*sampleRate*/)
  18162. {
  18163. }
  18164. void AudioFormatReaderSource::releaseResources()
  18165. {
  18166. }
  18167. void AudioFormatReaderSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18168. {
  18169. if (info.numSamples > 0)
  18170. {
  18171. const int start = nextPlayPos;
  18172. if (looping)
  18173. {
  18174. const int newStart = start % (int) reader->lengthInSamples;
  18175. const int newEnd = (start + info.numSamples) % (int) reader->lengthInSamples;
  18176. if (newEnd > newStart)
  18177. {
  18178. info.buffer->readFromAudioReader (reader,
  18179. info.startSample,
  18180. newEnd - newStart,
  18181. newStart,
  18182. true, true);
  18183. }
  18184. else
  18185. {
  18186. const int endSamps = (int) reader->lengthInSamples - newStart;
  18187. info.buffer->readFromAudioReader (reader,
  18188. info.startSample,
  18189. endSamps,
  18190. newStart,
  18191. true, true);
  18192. info.buffer->readFromAudioReader (reader,
  18193. info.startSample + endSamps,
  18194. newEnd,
  18195. 0,
  18196. true, true);
  18197. }
  18198. nextPlayPos = newEnd;
  18199. }
  18200. else
  18201. {
  18202. info.buffer->readFromAudioReader (reader,
  18203. info.startSample,
  18204. info.numSamples,
  18205. start,
  18206. true, true);
  18207. nextPlayPos += info.numSamples;
  18208. }
  18209. }
  18210. }
  18211. END_JUCE_NAMESPACE
  18212. /*** End of inlined file: juce_AudioFormatReaderSource.cpp ***/
  18213. /*** Start of inlined file: juce_AudioSourcePlayer.cpp ***/
  18214. BEGIN_JUCE_NAMESPACE
  18215. AudioSourcePlayer::AudioSourcePlayer()
  18216. : source (0),
  18217. sampleRate (0),
  18218. bufferSize (0),
  18219. tempBuffer (2, 8),
  18220. lastGain (1.0f),
  18221. gain (1.0f)
  18222. {
  18223. }
  18224. AudioSourcePlayer::~AudioSourcePlayer()
  18225. {
  18226. setSource (0);
  18227. }
  18228. void AudioSourcePlayer::setSource (AudioSource* newSource)
  18229. {
  18230. if (source != newSource)
  18231. {
  18232. AudioSource* const oldSource = source;
  18233. if (newSource != 0 && bufferSize > 0 && sampleRate > 0)
  18234. newSource->prepareToPlay (bufferSize, sampleRate);
  18235. {
  18236. const ScopedLock sl (readLock);
  18237. source = newSource;
  18238. }
  18239. if (oldSource != 0)
  18240. oldSource->releaseResources();
  18241. }
  18242. }
  18243. void AudioSourcePlayer::setGain (const float newGain) throw()
  18244. {
  18245. gain = newGain;
  18246. }
  18247. void AudioSourcePlayer::audioDeviceIOCallback (const float** inputChannelData,
  18248. int totalNumInputChannels,
  18249. float** outputChannelData,
  18250. int totalNumOutputChannels,
  18251. int numSamples)
  18252. {
  18253. // these should have been prepared by audioDeviceAboutToStart()...
  18254. jassert (sampleRate > 0 && bufferSize > 0);
  18255. const ScopedLock sl (readLock);
  18256. if (source != 0)
  18257. {
  18258. AudioSourceChannelInfo info;
  18259. int i, numActiveChans = 0, numInputs = 0, numOutputs = 0;
  18260. // messy stuff needed to compact the channels down into an array
  18261. // of non-zero pointers..
  18262. for (i = 0; i < totalNumInputChannels; ++i)
  18263. {
  18264. if (inputChannelData[i] != 0)
  18265. {
  18266. inputChans [numInputs++] = inputChannelData[i];
  18267. if (numInputs >= numElementsInArray (inputChans))
  18268. break;
  18269. }
  18270. }
  18271. for (i = 0; i < totalNumOutputChannels; ++i)
  18272. {
  18273. if (outputChannelData[i] != 0)
  18274. {
  18275. outputChans [numOutputs++] = outputChannelData[i];
  18276. if (numOutputs >= numElementsInArray (outputChans))
  18277. break;
  18278. }
  18279. }
  18280. if (numInputs > numOutputs)
  18281. {
  18282. // if there aren't enough output channels for the number of
  18283. // inputs, we need to create some temporary extra ones (can't
  18284. // use the input data in case it gets written to)
  18285. tempBuffer.setSize (numInputs - numOutputs, numSamples,
  18286. false, false, true);
  18287. for (i = 0; i < numOutputs; ++i)
  18288. {
  18289. channels[numActiveChans] = outputChans[i];
  18290. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  18291. ++numActiveChans;
  18292. }
  18293. for (i = numOutputs; i < numInputs; ++i)
  18294. {
  18295. channels[numActiveChans] = tempBuffer.getSampleData (i - numOutputs, 0);
  18296. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  18297. ++numActiveChans;
  18298. }
  18299. }
  18300. else
  18301. {
  18302. for (i = 0; i < numInputs; ++i)
  18303. {
  18304. channels[numActiveChans] = outputChans[i];
  18305. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  18306. ++numActiveChans;
  18307. }
  18308. for (i = numInputs; i < numOutputs; ++i)
  18309. {
  18310. channels[numActiveChans] = outputChans[i];
  18311. zeromem (channels[numActiveChans], sizeof (float) * numSamples);
  18312. ++numActiveChans;
  18313. }
  18314. }
  18315. AudioSampleBuffer buffer (channels, numActiveChans, numSamples);
  18316. info.buffer = &buffer;
  18317. info.startSample = 0;
  18318. info.numSamples = numSamples;
  18319. source->getNextAudioBlock (info);
  18320. for (i = info.buffer->getNumChannels(); --i >= 0;)
  18321. info.buffer->applyGainRamp (i, info.startSample, info.numSamples, lastGain, gain);
  18322. lastGain = gain;
  18323. }
  18324. else
  18325. {
  18326. for (int i = 0; i < totalNumOutputChannels; ++i)
  18327. if (outputChannelData[i] != 0)
  18328. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  18329. }
  18330. }
  18331. void AudioSourcePlayer::audioDeviceAboutToStart (AudioIODevice* device)
  18332. {
  18333. sampleRate = device->getCurrentSampleRate();
  18334. bufferSize = device->getCurrentBufferSizeSamples();
  18335. zeromem (channels, sizeof (channels));
  18336. if (source != 0)
  18337. source->prepareToPlay (bufferSize, sampleRate);
  18338. }
  18339. void AudioSourcePlayer::audioDeviceStopped()
  18340. {
  18341. if (source != 0)
  18342. source->releaseResources();
  18343. sampleRate = 0.0;
  18344. bufferSize = 0;
  18345. tempBuffer.setSize (2, 8);
  18346. }
  18347. END_JUCE_NAMESPACE
  18348. /*** End of inlined file: juce_AudioSourcePlayer.cpp ***/
  18349. /*** Start of inlined file: juce_AudioTransportSource.cpp ***/
  18350. BEGIN_JUCE_NAMESPACE
  18351. AudioTransportSource::AudioTransportSource()
  18352. : source (0),
  18353. resamplerSource (0),
  18354. bufferingSource (0),
  18355. positionableSource (0),
  18356. masterSource (0),
  18357. gain (1.0f),
  18358. lastGain (1.0f),
  18359. playing (false),
  18360. stopped (true),
  18361. sampleRate (44100.0),
  18362. sourceSampleRate (0.0),
  18363. blockSize (128),
  18364. readAheadBufferSize (0),
  18365. isPrepared (false),
  18366. inputStreamEOF (false)
  18367. {
  18368. }
  18369. AudioTransportSource::~AudioTransportSource()
  18370. {
  18371. setSource (0);
  18372. releaseResources();
  18373. }
  18374. void AudioTransportSource::setSource (PositionableAudioSource* const newSource,
  18375. int readAheadBufferSize_,
  18376. double sourceSampleRateToCorrectFor)
  18377. {
  18378. if (source == newSource)
  18379. {
  18380. if (source == 0)
  18381. return;
  18382. setSource (0, 0, 0); // deselect and reselect to avoid releasing resources wrongly
  18383. }
  18384. readAheadBufferSize = readAheadBufferSize_;
  18385. sourceSampleRate = sourceSampleRateToCorrectFor;
  18386. ResamplingAudioSource* newResamplerSource = 0;
  18387. BufferingAudioSource* newBufferingSource = 0;
  18388. PositionableAudioSource* newPositionableSource = 0;
  18389. AudioSource* newMasterSource = 0;
  18390. ScopedPointer <ResamplingAudioSource> oldResamplerSource (resamplerSource);
  18391. ScopedPointer <BufferingAudioSource> oldBufferingSource (bufferingSource);
  18392. AudioSource* oldMasterSource = masterSource;
  18393. if (newSource != 0)
  18394. {
  18395. newPositionableSource = newSource;
  18396. if (readAheadBufferSize_ > 0)
  18397. newPositionableSource = newBufferingSource
  18398. = new BufferingAudioSource (newPositionableSource, false, readAheadBufferSize_);
  18399. newPositionableSource->setNextReadPosition (0);
  18400. if (sourceSampleRateToCorrectFor != 0)
  18401. newMasterSource = newResamplerSource
  18402. = new ResamplingAudioSource (newPositionableSource, false);
  18403. else
  18404. newMasterSource = newPositionableSource;
  18405. if (isPrepared)
  18406. {
  18407. if (newResamplerSource != 0 && sourceSampleRate > 0 && sampleRate > 0)
  18408. newResamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  18409. newMasterSource->prepareToPlay (blockSize, sampleRate);
  18410. }
  18411. }
  18412. {
  18413. const ScopedLock sl (callbackLock);
  18414. source = newSource;
  18415. resamplerSource = newResamplerSource;
  18416. bufferingSource = newBufferingSource;
  18417. masterSource = newMasterSource;
  18418. positionableSource = newPositionableSource;
  18419. playing = false;
  18420. }
  18421. if (oldMasterSource != 0)
  18422. oldMasterSource->releaseResources();
  18423. }
  18424. void AudioTransportSource::start()
  18425. {
  18426. if ((! playing) && masterSource != 0)
  18427. {
  18428. {
  18429. const ScopedLock sl (callbackLock);
  18430. playing = true;
  18431. stopped = false;
  18432. inputStreamEOF = false;
  18433. }
  18434. sendChangeMessage (this);
  18435. }
  18436. }
  18437. void AudioTransportSource::stop()
  18438. {
  18439. if (playing)
  18440. {
  18441. {
  18442. const ScopedLock sl (callbackLock);
  18443. playing = false;
  18444. }
  18445. int n = 500;
  18446. while (--n >= 0 && ! stopped)
  18447. Thread::sleep (2);
  18448. sendChangeMessage (this);
  18449. }
  18450. }
  18451. void AudioTransportSource::setPosition (double newPosition)
  18452. {
  18453. if (sampleRate > 0.0)
  18454. setNextReadPosition (roundToInt (newPosition * sampleRate));
  18455. }
  18456. double AudioTransportSource::getCurrentPosition() const
  18457. {
  18458. if (sampleRate > 0.0)
  18459. return getNextReadPosition() / sampleRate;
  18460. else
  18461. return 0.0;
  18462. }
  18463. void AudioTransportSource::setNextReadPosition (int newPosition)
  18464. {
  18465. if (positionableSource != 0)
  18466. {
  18467. if (sampleRate > 0 && sourceSampleRate > 0)
  18468. newPosition = roundToInt (newPosition * sourceSampleRate / sampleRate);
  18469. positionableSource->setNextReadPosition (newPosition);
  18470. }
  18471. }
  18472. int AudioTransportSource::getNextReadPosition() const
  18473. {
  18474. if (positionableSource != 0)
  18475. {
  18476. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  18477. return roundToInt (positionableSource->getNextReadPosition() * ratio);
  18478. }
  18479. return 0;
  18480. }
  18481. int AudioTransportSource::getTotalLength() const
  18482. {
  18483. const ScopedLock sl (callbackLock);
  18484. if (positionableSource != 0)
  18485. {
  18486. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  18487. return roundToInt (positionableSource->getTotalLength() * ratio);
  18488. }
  18489. return 0;
  18490. }
  18491. bool AudioTransportSource::isLooping() const
  18492. {
  18493. const ScopedLock sl (callbackLock);
  18494. return positionableSource != 0
  18495. && positionableSource->isLooping();
  18496. }
  18497. void AudioTransportSource::setGain (const float newGain) throw()
  18498. {
  18499. gain = newGain;
  18500. }
  18501. void AudioTransportSource::prepareToPlay (int samplesPerBlockExpected,
  18502. double sampleRate_)
  18503. {
  18504. const ScopedLock sl (callbackLock);
  18505. sampleRate = sampleRate_;
  18506. blockSize = samplesPerBlockExpected;
  18507. if (masterSource != 0)
  18508. masterSource->prepareToPlay (samplesPerBlockExpected, sampleRate);
  18509. if (resamplerSource != 0 && sourceSampleRate != 0)
  18510. resamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  18511. isPrepared = true;
  18512. }
  18513. void AudioTransportSource::releaseResources()
  18514. {
  18515. const ScopedLock sl (callbackLock);
  18516. if (masterSource != 0)
  18517. masterSource->releaseResources();
  18518. isPrepared = false;
  18519. }
  18520. void AudioTransportSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18521. {
  18522. const ScopedLock sl (callbackLock);
  18523. inputStreamEOF = false;
  18524. if (masterSource != 0 && ! stopped)
  18525. {
  18526. masterSource->getNextAudioBlock (info);
  18527. if (! playing)
  18528. {
  18529. // just stopped playing, so fade out the last block..
  18530. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  18531. info.buffer->applyGainRamp (i, info.startSample, jmin (256, info.numSamples), 1.0f, 0.0f);
  18532. if (info.numSamples > 256)
  18533. info.buffer->clear (info.startSample + 256, info.numSamples - 256);
  18534. }
  18535. if (positionableSource->getNextReadPosition() > positionableSource->getTotalLength() + 1
  18536. && ! positionableSource->isLooping())
  18537. {
  18538. playing = false;
  18539. inputStreamEOF = true;
  18540. sendChangeMessage (this);
  18541. }
  18542. stopped = ! playing;
  18543. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  18544. {
  18545. info.buffer->applyGainRamp (i, info.startSample, info.numSamples,
  18546. lastGain, gain);
  18547. }
  18548. }
  18549. else
  18550. {
  18551. info.clearActiveBufferRegion();
  18552. stopped = true;
  18553. }
  18554. lastGain = gain;
  18555. }
  18556. END_JUCE_NAMESPACE
  18557. /*** End of inlined file: juce_AudioTransportSource.cpp ***/
  18558. /*** Start of inlined file: juce_BufferingAudioSource.cpp ***/
  18559. BEGIN_JUCE_NAMESPACE
  18560. class SharedBufferingAudioSourceThread : public DeletedAtShutdown,
  18561. public Thread,
  18562. private Timer
  18563. {
  18564. public:
  18565. SharedBufferingAudioSourceThread()
  18566. : Thread ("Audio Buffer")
  18567. {
  18568. }
  18569. ~SharedBufferingAudioSourceThread()
  18570. {
  18571. stopThread (10000);
  18572. clearSingletonInstance();
  18573. }
  18574. juce_DeclareSingleton (SharedBufferingAudioSourceThread, false)
  18575. void addSource (BufferingAudioSource* source)
  18576. {
  18577. const ScopedLock sl (lock);
  18578. if (! sources.contains (source))
  18579. {
  18580. sources.add (source);
  18581. startThread();
  18582. stopTimer();
  18583. }
  18584. notify();
  18585. }
  18586. void removeSource (BufferingAudioSource* source)
  18587. {
  18588. const ScopedLock sl (lock);
  18589. sources.removeValue (source);
  18590. if (sources.size() == 0)
  18591. startTimer (5000);
  18592. }
  18593. private:
  18594. Array <BufferingAudioSource*> sources;
  18595. CriticalSection lock;
  18596. void run()
  18597. {
  18598. while (! threadShouldExit())
  18599. {
  18600. bool busy = false;
  18601. for (int i = sources.size(); --i >= 0;)
  18602. {
  18603. if (threadShouldExit())
  18604. return;
  18605. const ScopedLock sl (lock);
  18606. BufferingAudioSource* const b = sources[i];
  18607. if (b != 0 && b->readNextBufferChunk())
  18608. busy = true;
  18609. }
  18610. if (! busy)
  18611. wait (500);
  18612. }
  18613. }
  18614. void timerCallback()
  18615. {
  18616. stopTimer();
  18617. if (sources.size() == 0)
  18618. deleteInstance();
  18619. }
  18620. SharedBufferingAudioSourceThread (const SharedBufferingAudioSourceThread&);
  18621. SharedBufferingAudioSourceThread& operator= (const SharedBufferingAudioSourceThread&);
  18622. };
  18623. juce_ImplementSingleton (SharedBufferingAudioSourceThread)
  18624. BufferingAudioSource::BufferingAudioSource (PositionableAudioSource* source_,
  18625. const bool deleteSourceWhenDeleted_,
  18626. int numberOfSamplesToBuffer_)
  18627. : source (source_),
  18628. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  18629. numberOfSamplesToBuffer (jmax (1024, numberOfSamplesToBuffer_)),
  18630. buffer (2, 0),
  18631. bufferValidStart (0),
  18632. bufferValidEnd (0),
  18633. nextPlayPos (0),
  18634. wasSourceLooping (false)
  18635. {
  18636. jassert (source_ != 0);
  18637. jassert (numberOfSamplesToBuffer_ > 1024); // not much point using this class if you're
  18638. // not using a larger buffer..
  18639. }
  18640. BufferingAudioSource::~BufferingAudioSource()
  18641. {
  18642. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  18643. if (thread != 0)
  18644. thread->removeSource (this);
  18645. if (deleteSourceWhenDeleted)
  18646. delete source;
  18647. }
  18648. void BufferingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate_)
  18649. {
  18650. source->prepareToPlay (samplesPerBlockExpected, sampleRate_);
  18651. sampleRate = sampleRate_;
  18652. buffer.setSize (2, jmax (samplesPerBlockExpected * 2, numberOfSamplesToBuffer));
  18653. buffer.clear();
  18654. bufferValidStart = 0;
  18655. bufferValidEnd = 0;
  18656. SharedBufferingAudioSourceThread::getInstance()->addSource (this);
  18657. while (bufferValidEnd - bufferValidStart < jmin (((int) sampleRate_) / 4,
  18658. buffer.getNumSamples() / 2))
  18659. {
  18660. SharedBufferingAudioSourceThread::getInstance()->notify();
  18661. Thread::sleep (5);
  18662. }
  18663. }
  18664. void BufferingAudioSource::releaseResources()
  18665. {
  18666. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  18667. if (thread != 0)
  18668. thread->removeSource (this);
  18669. buffer.setSize (2, 0);
  18670. source->releaseResources();
  18671. }
  18672. void BufferingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18673. {
  18674. const ScopedLock sl (bufferStartPosLock);
  18675. const int validStart = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos) - nextPlayPos;
  18676. const int validEnd = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos + info.numSamples) - nextPlayPos;
  18677. if (validStart == validEnd)
  18678. {
  18679. // total cache miss
  18680. info.clearActiveBufferRegion();
  18681. }
  18682. else
  18683. {
  18684. if (validStart > 0)
  18685. info.buffer->clear (info.startSample, validStart); // partial cache miss at start
  18686. if (validEnd < info.numSamples)
  18687. info.buffer->clear (info.startSample + validEnd,
  18688. info.numSamples - validEnd); // partial cache miss at end
  18689. if (validStart < validEnd)
  18690. {
  18691. for (int chan = jmin (2, info.buffer->getNumChannels()); --chan >= 0;)
  18692. {
  18693. const int startBufferIndex = (validStart + nextPlayPos) % buffer.getNumSamples();
  18694. const int endBufferIndex = (validEnd + nextPlayPos) % buffer.getNumSamples();
  18695. if (startBufferIndex < endBufferIndex)
  18696. {
  18697. info.buffer->copyFrom (chan, info.startSample + validStart,
  18698. buffer,
  18699. chan, startBufferIndex,
  18700. validEnd - validStart);
  18701. }
  18702. else
  18703. {
  18704. const int initialSize = buffer.getNumSamples() - startBufferIndex;
  18705. info.buffer->copyFrom (chan, info.startSample + validStart,
  18706. buffer,
  18707. chan, startBufferIndex,
  18708. initialSize);
  18709. info.buffer->copyFrom (chan, info.startSample + validStart + initialSize,
  18710. buffer,
  18711. chan, 0,
  18712. (validEnd - validStart) - initialSize);
  18713. }
  18714. }
  18715. }
  18716. nextPlayPos += info.numSamples;
  18717. if (source->isLooping() && nextPlayPos > 0)
  18718. nextPlayPos %= source->getTotalLength();
  18719. }
  18720. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  18721. if (thread != 0)
  18722. thread->notify();
  18723. }
  18724. int BufferingAudioSource::getNextReadPosition() const
  18725. {
  18726. return (source->isLooping() && nextPlayPos > 0)
  18727. ? nextPlayPos % source->getTotalLength()
  18728. : nextPlayPos;
  18729. }
  18730. void BufferingAudioSource::setNextReadPosition (int newPosition)
  18731. {
  18732. const ScopedLock sl (bufferStartPosLock);
  18733. nextPlayPos = newPosition;
  18734. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  18735. if (thread != 0)
  18736. thread->notify();
  18737. }
  18738. bool BufferingAudioSource::readNextBufferChunk()
  18739. {
  18740. int newBVS, newBVE, sectionToReadStart, sectionToReadEnd;
  18741. {
  18742. const ScopedLock sl (bufferStartPosLock);
  18743. if (wasSourceLooping != isLooping())
  18744. {
  18745. wasSourceLooping = isLooping();
  18746. bufferValidStart = 0;
  18747. bufferValidEnd = 0;
  18748. }
  18749. newBVS = jmax (0, nextPlayPos);
  18750. newBVE = newBVS + buffer.getNumSamples() - 4;
  18751. sectionToReadStart = 0;
  18752. sectionToReadEnd = 0;
  18753. const int maxChunkSize = 2048;
  18754. if (newBVS < bufferValidStart || newBVS >= bufferValidEnd)
  18755. {
  18756. newBVE = jmin (newBVE, newBVS + maxChunkSize);
  18757. sectionToReadStart = newBVS;
  18758. sectionToReadEnd = newBVE;
  18759. bufferValidStart = 0;
  18760. bufferValidEnd = 0;
  18761. }
  18762. else if (abs (newBVS - bufferValidStart) > 512
  18763. || abs (newBVE - bufferValidEnd) > 512)
  18764. {
  18765. newBVE = jmin (newBVE, bufferValidEnd + maxChunkSize);
  18766. sectionToReadStart = bufferValidEnd;
  18767. sectionToReadEnd = newBVE;
  18768. bufferValidStart = newBVS;
  18769. bufferValidEnd = jmin (bufferValidEnd, newBVE);
  18770. }
  18771. }
  18772. if (sectionToReadStart != sectionToReadEnd)
  18773. {
  18774. const int bufferIndexStart = sectionToReadStart % buffer.getNumSamples();
  18775. const int bufferIndexEnd = sectionToReadEnd % buffer.getNumSamples();
  18776. if (bufferIndexStart < bufferIndexEnd)
  18777. {
  18778. readBufferSection (sectionToReadStart,
  18779. sectionToReadEnd - sectionToReadStart,
  18780. bufferIndexStart);
  18781. }
  18782. else
  18783. {
  18784. const int initialSize = buffer.getNumSamples() - bufferIndexStart;
  18785. readBufferSection (sectionToReadStart,
  18786. initialSize,
  18787. bufferIndexStart);
  18788. readBufferSection (sectionToReadStart + initialSize,
  18789. (sectionToReadEnd - sectionToReadStart) - initialSize,
  18790. 0);
  18791. }
  18792. const ScopedLock sl2 (bufferStartPosLock);
  18793. bufferValidStart = newBVS;
  18794. bufferValidEnd = newBVE;
  18795. return true;
  18796. }
  18797. else
  18798. {
  18799. return false;
  18800. }
  18801. }
  18802. void BufferingAudioSource::readBufferSection (int start, int length, int bufferOffset)
  18803. {
  18804. if (source->getNextReadPosition() != start)
  18805. source->setNextReadPosition (start);
  18806. AudioSourceChannelInfo info;
  18807. info.buffer = &buffer;
  18808. info.startSample = bufferOffset;
  18809. info.numSamples = length;
  18810. source->getNextAudioBlock (info);
  18811. }
  18812. END_JUCE_NAMESPACE
  18813. /*** End of inlined file: juce_BufferingAudioSource.cpp ***/
  18814. /*** Start of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  18815. BEGIN_JUCE_NAMESPACE
  18816. ChannelRemappingAudioSource::ChannelRemappingAudioSource (AudioSource* const source_,
  18817. const bool deleteSourceWhenDeleted_)
  18818. : requiredNumberOfChannels (2),
  18819. source (source_),
  18820. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  18821. buffer (2, 16)
  18822. {
  18823. remappedInfo.buffer = &buffer;
  18824. remappedInfo.startSample = 0;
  18825. }
  18826. ChannelRemappingAudioSource::~ChannelRemappingAudioSource()
  18827. {
  18828. if (deleteSourceWhenDeleted)
  18829. delete source;
  18830. }
  18831. void ChannelRemappingAudioSource::setNumberOfChannelsToProduce (const int requiredNumberOfChannels_) throw()
  18832. {
  18833. const ScopedLock sl (lock);
  18834. requiredNumberOfChannels = requiredNumberOfChannels_;
  18835. }
  18836. void ChannelRemappingAudioSource::clearAllMappings() throw()
  18837. {
  18838. const ScopedLock sl (lock);
  18839. remappedInputs.clear();
  18840. remappedOutputs.clear();
  18841. }
  18842. void ChannelRemappingAudioSource::setInputChannelMapping (const int destIndex, const int sourceIndex) throw()
  18843. {
  18844. const ScopedLock sl (lock);
  18845. while (remappedInputs.size() < destIndex)
  18846. remappedInputs.add (-1);
  18847. remappedInputs.set (destIndex, sourceIndex);
  18848. }
  18849. void ChannelRemappingAudioSource::setOutputChannelMapping (const int sourceIndex, const int destIndex) throw()
  18850. {
  18851. const ScopedLock sl (lock);
  18852. while (remappedOutputs.size() < sourceIndex)
  18853. remappedOutputs.add (-1);
  18854. remappedOutputs.set (sourceIndex, destIndex);
  18855. }
  18856. int ChannelRemappingAudioSource::getRemappedInputChannel (const int inputChannelIndex) const throw()
  18857. {
  18858. const ScopedLock sl (lock);
  18859. if (inputChannelIndex >= 0 && inputChannelIndex < remappedInputs.size())
  18860. return remappedInputs.getUnchecked (inputChannelIndex);
  18861. return -1;
  18862. }
  18863. int ChannelRemappingAudioSource::getRemappedOutputChannel (const int outputChannelIndex) const throw()
  18864. {
  18865. const ScopedLock sl (lock);
  18866. if (outputChannelIndex >= 0 && outputChannelIndex < remappedOutputs.size())
  18867. return remappedOutputs .getUnchecked (outputChannelIndex);
  18868. return -1;
  18869. }
  18870. void ChannelRemappingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  18871. {
  18872. source->prepareToPlay (samplesPerBlockExpected, sampleRate);
  18873. }
  18874. void ChannelRemappingAudioSource::releaseResources()
  18875. {
  18876. source->releaseResources();
  18877. }
  18878. void ChannelRemappingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  18879. {
  18880. const ScopedLock sl (lock);
  18881. buffer.setSize (requiredNumberOfChannels, bufferToFill.numSamples, false, false, true);
  18882. const int numChans = bufferToFill.buffer->getNumChannels();
  18883. int i;
  18884. for (i = 0; i < buffer.getNumChannels(); ++i)
  18885. {
  18886. const int remappedChan = getRemappedInputChannel (i);
  18887. if (remappedChan >= 0 && remappedChan < numChans)
  18888. {
  18889. buffer.copyFrom (i, 0, *bufferToFill.buffer,
  18890. remappedChan,
  18891. bufferToFill.startSample,
  18892. bufferToFill.numSamples);
  18893. }
  18894. else
  18895. {
  18896. buffer.clear (i, 0, bufferToFill.numSamples);
  18897. }
  18898. }
  18899. remappedInfo.numSamples = bufferToFill.numSamples;
  18900. source->getNextAudioBlock (remappedInfo);
  18901. bufferToFill.clearActiveBufferRegion();
  18902. for (i = 0; i < requiredNumberOfChannels; ++i)
  18903. {
  18904. const int remappedChan = getRemappedOutputChannel (i);
  18905. if (remappedChan >= 0 && remappedChan < numChans)
  18906. {
  18907. bufferToFill.buffer->addFrom (remappedChan, bufferToFill.startSample,
  18908. buffer, i, 0, bufferToFill.numSamples);
  18909. }
  18910. }
  18911. }
  18912. XmlElement* ChannelRemappingAudioSource::createXml() const throw()
  18913. {
  18914. XmlElement* e = new XmlElement ("MAPPINGS");
  18915. String ins, outs;
  18916. int i;
  18917. const ScopedLock sl (lock);
  18918. for (i = 0; i < remappedInputs.size(); ++i)
  18919. ins << remappedInputs.getUnchecked(i) << ' ';
  18920. for (i = 0; i < remappedOutputs.size(); ++i)
  18921. outs << remappedOutputs.getUnchecked(i) << ' ';
  18922. e->setAttribute ("inputs", ins.trimEnd());
  18923. e->setAttribute ("outputs", outs.trimEnd());
  18924. return e;
  18925. }
  18926. void ChannelRemappingAudioSource::restoreFromXml (const XmlElement& e) throw()
  18927. {
  18928. if (e.hasTagName ("MAPPINGS"))
  18929. {
  18930. const ScopedLock sl (lock);
  18931. clearAllMappings();
  18932. StringArray ins, outs;
  18933. ins.addTokens (e.getStringAttribute ("inputs"), false);
  18934. outs.addTokens (e.getStringAttribute ("outputs"), false);
  18935. int i;
  18936. for (i = 0; i < ins.size(); ++i)
  18937. remappedInputs.add (ins[i].getIntValue());
  18938. for (i = 0; i < outs.size(); ++i)
  18939. remappedOutputs.add (outs[i].getIntValue());
  18940. }
  18941. }
  18942. END_JUCE_NAMESPACE
  18943. /*** End of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  18944. /*** Start of inlined file: juce_IIRFilterAudioSource.cpp ***/
  18945. BEGIN_JUCE_NAMESPACE
  18946. IIRFilterAudioSource::IIRFilterAudioSource (AudioSource* const inputSource,
  18947. const bool deleteInputWhenDeleted_)
  18948. : input (inputSource),
  18949. deleteInputWhenDeleted (deleteInputWhenDeleted_)
  18950. {
  18951. jassert (inputSource != 0);
  18952. for (int i = 2; --i >= 0;)
  18953. iirFilters.add (new IIRFilter());
  18954. }
  18955. IIRFilterAudioSource::~IIRFilterAudioSource()
  18956. {
  18957. if (deleteInputWhenDeleted)
  18958. delete input;
  18959. }
  18960. void IIRFilterAudioSource::setFilterParameters (const IIRFilter& newSettings)
  18961. {
  18962. for (int i = iirFilters.size(); --i >= 0;)
  18963. iirFilters.getUnchecked(i)->copyCoefficientsFrom (newSettings);
  18964. }
  18965. void IIRFilterAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  18966. {
  18967. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  18968. for (int i = iirFilters.size(); --i >= 0;)
  18969. iirFilters.getUnchecked(i)->reset();
  18970. }
  18971. void IIRFilterAudioSource::releaseResources()
  18972. {
  18973. input->releaseResources();
  18974. }
  18975. void IIRFilterAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  18976. {
  18977. input->getNextAudioBlock (bufferToFill);
  18978. const int numChannels = bufferToFill.buffer->getNumChannels();
  18979. while (numChannels > iirFilters.size())
  18980. iirFilters.add (new IIRFilter (*iirFilters.getUnchecked (0)));
  18981. for (int i = 0; i < numChannels; ++i)
  18982. iirFilters.getUnchecked(i)
  18983. ->processSamples (bufferToFill.buffer->getSampleData (i, bufferToFill.startSample),
  18984. bufferToFill.numSamples);
  18985. }
  18986. END_JUCE_NAMESPACE
  18987. /*** End of inlined file: juce_IIRFilterAudioSource.cpp ***/
  18988. /*** Start of inlined file: juce_MixerAudioSource.cpp ***/
  18989. BEGIN_JUCE_NAMESPACE
  18990. MixerAudioSource::MixerAudioSource()
  18991. : tempBuffer (2, 0),
  18992. currentSampleRate (0.0),
  18993. bufferSizeExpected (0)
  18994. {
  18995. }
  18996. MixerAudioSource::~MixerAudioSource()
  18997. {
  18998. removeAllInputs();
  18999. }
  19000. void MixerAudioSource::addInputSource (AudioSource* input, const bool deleteWhenRemoved)
  19001. {
  19002. if (input != 0 && ! inputs.contains (input))
  19003. {
  19004. double localRate;
  19005. int localBufferSize;
  19006. {
  19007. const ScopedLock sl (lock);
  19008. localRate = currentSampleRate;
  19009. localBufferSize = bufferSizeExpected;
  19010. }
  19011. if (localRate != 0.0)
  19012. input->prepareToPlay (localBufferSize, localRate);
  19013. const ScopedLock sl (lock);
  19014. inputsToDelete.setBit (inputs.size(), deleteWhenRemoved);
  19015. inputs.add (input);
  19016. }
  19017. }
  19018. void MixerAudioSource::removeInputSource (AudioSource* input, const bool deleteInput)
  19019. {
  19020. if (input != 0)
  19021. {
  19022. int index;
  19023. {
  19024. const ScopedLock sl (lock);
  19025. index = inputs.indexOf (input);
  19026. if (index >= 0)
  19027. {
  19028. inputsToDelete.shiftBits (index, 1);
  19029. inputs.remove (index);
  19030. }
  19031. }
  19032. if (index >= 0)
  19033. {
  19034. input->releaseResources();
  19035. if (deleteInput)
  19036. delete input;
  19037. }
  19038. }
  19039. }
  19040. void MixerAudioSource::removeAllInputs()
  19041. {
  19042. OwnedArray<AudioSource> toDelete;
  19043. {
  19044. const ScopedLock sl (lock);
  19045. for (int i = inputs.size(); --i >= 0;)
  19046. if (inputsToDelete[i])
  19047. toDelete.add (inputs.getUnchecked(i));
  19048. }
  19049. }
  19050. void MixerAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19051. {
  19052. tempBuffer.setSize (2, samplesPerBlockExpected);
  19053. const ScopedLock sl (lock);
  19054. currentSampleRate = sampleRate;
  19055. bufferSizeExpected = samplesPerBlockExpected;
  19056. for (int i = inputs.size(); --i >= 0;)
  19057. inputs.getUnchecked(i)->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19058. }
  19059. void MixerAudioSource::releaseResources()
  19060. {
  19061. const ScopedLock sl (lock);
  19062. for (int i = inputs.size(); --i >= 0;)
  19063. inputs.getUnchecked(i)->releaseResources();
  19064. tempBuffer.setSize (2, 0);
  19065. currentSampleRate = 0;
  19066. bufferSizeExpected = 0;
  19067. }
  19068. void MixerAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19069. {
  19070. const ScopedLock sl (lock);
  19071. if (inputs.size() > 0)
  19072. {
  19073. inputs.getUnchecked(0)->getNextAudioBlock (info);
  19074. if (inputs.size() > 1)
  19075. {
  19076. tempBuffer.setSize (jmax (1, info.buffer->getNumChannels()),
  19077. info.buffer->getNumSamples());
  19078. AudioSourceChannelInfo info2;
  19079. info2.buffer = &tempBuffer;
  19080. info2.numSamples = info.numSamples;
  19081. info2.startSample = 0;
  19082. for (int i = 1; i < inputs.size(); ++i)
  19083. {
  19084. inputs.getUnchecked(i)->getNextAudioBlock (info2);
  19085. for (int chan = 0; chan < info.buffer->getNumChannels(); ++chan)
  19086. info.buffer->addFrom (chan, info.startSample, tempBuffer, chan, 0, info.numSamples);
  19087. }
  19088. }
  19089. }
  19090. else
  19091. {
  19092. info.clearActiveBufferRegion();
  19093. }
  19094. }
  19095. END_JUCE_NAMESPACE
  19096. /*** End of inlined file: juce_MixerAudioSource.cpp ***/
  19097. /*** Start of inlined file: juce_ResamplingAudioSource.cpp ***/
  19098. BEGIN_JUCE_NAMESPACE
  19099. ResamplingAudioSource::ResamplingAudioSource (AudioSource* const inputSource,
  19100. const bool deleteInputWhenDeleted_)
  19101. : input (inputSource),
  19102. deleteInputWhenDeleted (deleteInputWhenDeleted_),
  19103. ratio (1.0),
  19104. lastRatio (1.0),
  19105. buffer (2, 0),
  19106. sampsInBuffer (0)
  19107. {
  19108. jassert (input != 0);
  19109. }
  19110. ResamplingAudioSource::~ResamplingAudioSource()
  19111. {
  19112. if (deleteInputWhenDeleted)
  19113. delete input;
  19114. }
  19115. void ResamplingAudioSource::setResamplingRatio (const double samplesInPerOutputSample)
  19116. {
  19117. jassert (samplesInPerOutputSample > 0);
  19118. const ScopedLock sl (ratioLock);
  19119. ratio = jmax (0.0, samplesInPerOutputSample);
  19120. }
  19121. void ResamplingAudioSource::prepareToPlay (int samplesPerBlockExpected,
  19122. double sampleRate)
  19123. {
  19124. const ScopedLock sl (ratioLock);
  19125. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19126. buffer.setSize (2, roundToInt (samplesPerBlockExpected * ratio) + 32);
  19127. buffer.clear();
  19128. sampsInBuffer = 0;
  19129. bufferPos = 0;
  19130. subSampleOffset = 0.0;
  19131. createLowPass (ratio);
  19132. resetFilters();
  19133. }
  19134. void ResamplingAudioSource::releaseResources()
  19135. {
  19136. input->releaseResources();
  19137. buffer.setSize (2, 0);
  19138. }
  19139. void ResamplingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19140. {
  19141. const ScopedLock sl (ratioLock);
  19142. if (lastRatio != ratio)
  19143. {
  19144. createLowPass (ratio);
  19145. lastRatio = ratio;
  19146. }
  19147. const int sampsNeeded = roundToInt (info.numSamples * ratio) + 2;
  19148. int bufferSize = buffer.getNumSamples();
  19149. if (bufferSize < sampsNeeded + 8)
  19150. {
  19151. bufferPos %= bufferSize;
  19152. bufferSize = sampsNeeded + 32;
  19153. buffer.setSize (buffer.getNumChannels(), bufferSize, true, true);
  19154. }
  19155. bufferPos %= bufferSize;
  19156. int endOfBufferPos = bufferPos + sampsInBuffer;
  19157. while (sampsNeeded > sampsInBuffer)
  19158. {
  19159. endOfBufferPos %= bufferSize;
  19160. int numToDo = jmin (sampsNeeded - sampsInBuffer,
  19161. bufferSize - endOfBufferPos);
  19162. AudioSourceChannelInfo readInfo;
  19163. readInfo.buffer = &buffer;
  19164. readInfo.numSamples = numToDo;
  19165. readInfo.startSample = endOfBufferPos;
  19166. input->getNextAudioBlock (readInfo);
  19167. if (ratio > 1.0001)
  19168. {
  19169. // for down-sampling, pre-apply the filter..
  19170. for (int i = jmin (2, info.buffer->getNumChannels()); --i >= 0;)
  19171. applyFilter (buffer.getSampleData (i, endOfBufferPos), numToDo, filterStates[i]);
  19172. }
  19173. sampsInBuffer += numToDo;
  19174. endOfBufferPos += numToDo;
  19175. }
  19176. float* dl = info.buffer->getSampleData (0, info.startSample);
  19177. float* dr = (info.buffer->getNumChannels() > 1) ? info.buffer->getSampleData (1, info.startSample) : 0;
  19178. const float* const bl = buffer.getSampleData (0, 0);
  19179. const float* const br = buffer.getSampleData (1, 0);
  19180. int nextPos = (bufferPos + 1) % bufferSize;
  19181. for (int m = info.numSamples; --m >= 0;)
  19182. {
  19183. const float alpha = (float) subSampleOffset;
  19184. const float invAlpha = 1.0f - alpha;
  19185. *dl++ = bl [bufferPos] * invAlpha + bl [nextPos] * alpha;
  19186. if (dr != 0)
  19187. *dr++ = br [bufferPos] * invAlpha + br [nextPos] * alpha;
  19188. subSampleOffset += ratio;
  19189. jassert (sampsInBuffer > 0);
  19190. while (subSampleOffset >= 1.0)
  19191. {
  19192. if (++bufferPos >= bufferSize)
  19193. bufferPos = 0;
  19194. --sampsInBuffer;
  19195. nextPos = (bufferPos + 1) % bufferSize;
  19196. subSampleOffset -= 1.0;
  19197. }
  19198. }
  19199. if (ratio < 0.9999)
  19200. {
  19201. // for up-sampling, apply the filter after transposing..
  19202. for (int i = jmin (2, info.buffer->getNumChannels()); --i >= 0;)
  19203. applyFilter (info.buffer->getSampleData (i, info.startSample), info.numSamples, filterStates[i]);
  19204. }
  19205. else if (ratio <= 1.0001)
  19206. {
  19207. // if the filter's not currently being applied, keep it stoked with the last couple of samples to avoid discontinuities
  19208. for (int i = jmin (2, info.buffer->getNumChannels()); --i >= 0;)
  19209. {
  19210. const float* const endOfBuffer = info.buffer->getSampleData (i, info.startSample + info.numSamples - 1);
  19211. FilterState& fs = filterStates[i];
  19212. if (info.numSamples > 1)
  19213. {
  19214. fs.y2 = fs.x2 = *(endOfBuffer - 1);
  19215. }
  19216. else
  19217. {
  19218. fs.y2 = fs.y1;
  19219. fs.x2 = fs.x1;
  19220. }
  19221. fs.y1 = fs.x1 = *endOfBuffer;
  19222. }
  19223. }
  19224. jassert (sampsInBuffer >= 0);
  19225. }
  19226. void ResamplingAudioSource::createLowPass (const double frequencyRatio)
  19227. {
  19228. const double proportionalRate = (frequencyRatio > 1.0) ? 0.5 / frequencyRatio
  19229. : 0.5 * frequencyRatio;
  19230. const double n = 1.0 / tan (double_Pi * jmax (0.001, proportionalRate));
  19231. const double nSquared = n * n;
  19232. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  19233. setFilterCoefficients (c1,
  19234. c1 * 2.0f,
  19235. c1,
  19236. 1.0,
  19237. c1 * 2.0 * (1.0 - nSquared),
  19238. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  19239. }
  19240. void ResamplingAudioSource::setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6)
  19241. {
  19242. const double a = 1.0 / c4;
  19243. c1 *= a;
  19244. c2 *= a;
  19245. c3 *= a;
  19246. c5 *= a;
  19247. c6 *= a;
  19248. coefficients[0] = c1;
  19249. coefficients[1] = c2;
  19250. coefficients[2] = c3;
  19251. coefficients[3] = c4;
  19252. coefficients[4] = c5;
  19253. coefficients[5] = c6;
  19254. }
  19255. void ResamplingAudioSource::resetFilters()
  19256. {
  19257. zeromem (filterStates, sizeof (filterStates));
  19258. }
  19259. void ResamplingAudioSource::applyFilter (float* samples, int num, FilterState& fs)
  19260. {
  19261. while (--num >= 0)
  19262. {
  19263. const double in = *samples;
  19264. double out = coefficients[0] * in
  19265. + coefficients[1] * fs.x1
  19266. + coefficients[2] * fs.x2
  19267. - coefficients[4] * fs.y1
  19268. - coefficients[5] * fs.y2;
  19269. #if JUCE_INTEL
  19270. if (! (out < -1.0e-8 || out > 1.0e-8))
  19271. out = 0;
  19272. #endif
  19273. fs.x2 = fs.x1;
  19274. fs.x1 = in;
  19275. fs.y2 = fs.y1;
  19276. fs.y1 = out;
  19277. *samples++ = (float) out;
  19278. }
  19279. }
  19280. END_JUCE_NAMESPACE
  19281. /*** End of inlined file: juce_ResamplingAudioSource.cpp ***/
  19282. /*** Start of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  19283. BEGIN_JUCE_NAMESPACE
  19284. ToneGeneratorAudioSource::ToneGeneratorAudioSource()
  19285. : frequency (1000.0),
  19286. sampleRate (44100.0),
  19287. currentPhase (0.0),
  19288. phasePerSample (0.0),
  19289. amplitude (0.5f)
  19290. {
  19291. }
  19292. ToneGeneratorAudioSource::~ToneGeneratorAudioSource()
  19293. {
  19294. }
  19295. void ToneGeneratorAudioSource::setAmplitude (const float newAmplitude)
  19296. {
  19297. amplitude = newAmplitude;
  19298. }
  19299. void ToneGeneratorAudioSource::setFrequency (const double newFrequencyHz)
  19300. {
  19301. frequency = newFrequencyHz;
  19302. phasePerSample = 0.0;
  19303. }
  19304. void ToneGeneratorAudioSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  19305. double sampleRate_)
  19306. {
  19307. currentPhase = 0.0;
  19308. phasePerSample = 0.0;
  19309. sampleRate = sampleRate_;
  19310. }
  19311. void ToneGeneratorAudioSource::releaseResources()
  19312. {
  19313. }
  19314. void ToneGeneratorAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19315. {
  19316. if (phasePerSample == 0.0)
  19317. phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  19318. for (int i = 0; i < info.numSamples; ++i)
  19319. {
  19320. const float sample = amplitude * (float) std::sin (currentPhase);
  19321. currentPhase += phasePerSample;
  19322. for (int j = info.buffer->getNumChannels(); --j >= 0;)
  19323. *info.buffer->getSampleData (j, info.startSample + i) = sample;
  19324. }
  19325. }
  19326. END_JUCE_NAMESPACE
  19327. /*** End of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  19328. /*** Start of inlined file: juce_AudioDeviceManager.cpp ***/
  19329. BEGIN_JUCE_NAMESPACE
  19330. AudioDeviceManager::AudioDeviceSetup::AudioDeviceSetup()
  19331. : sampleRate (0),
  19332. bufferSize (0),
  19333. useDefaultInputChannels (true),
  19334. useDefaultOutputChannels (true)
  19335. {
  19336. }
  19337. bool AudioDeviceManager::AudioDeviceSetup::operator== (const AudioDeviceManager::AudioDeviceSetup& other) const
  19338. {
  19339. return outputDeviceName == other.outputDeviceName
  19340. && inputDeviceName == other.inputDeviceName
  19341. && sampleRate == other.sampleRate
  19342. && bufferSize == other.bufferSize
  19343. && inputChannels == other.inputChannels
  19344. && useDefaultInputChannels == other.useDefaultInputChannels
  19345. && outputChannels == other.outputChannels
  19346. && useDefaultOutputChannels == other.useDefaultOutputChannels;
  19347. }
  19348. AudioDeviceManager::AudioDeviceManager()
  19349. : currentAudioDevice (0),
  19350. numInputChansNeeded (0),
  19351. numOutputChansNeeded (2),
  19352. listNeedsScanning (true),
  19353. useInputNames (false),
  19354. inputLevelMeasurementEnabledCount (0),
  19355. inputLevel (0),
  19356. tempBuffer (2, 2),
  19357. defaultMidiOutput (0),
  19358. cpuUsageMs (0),
  19359. timeToCpuScale (0)
  19360. {
  19361. callbackHandler.owner = this;
  19362. }
  19363. AudioDeviceManager::~AudioDeviceManager()
  19364. {
  19365. currentAudioDevice = 0;
  19366. defaultMidiOutput = 0;
  19367. }
  19368. void AudioDeviceManager::createDeviceTypesIfNeeded()
  19369. {
  19370. if (availableDeviceTypes.size() == 0)
  19371. {
  19372. createAudioDeviceTypes (availableDeviceTypes);
  19373. while (lastDeviceTypeConfigs.size() < availableDeviceTypes.size())
  19374. lastDeviceTypeConfigs.add (new AudioDeviceSetup());
  19375. if (availableDeviceTypes.size() > 0)
  19376. currentDeviceType = availableDeviceTypes.getUnchecked(0)->getTypeName();
  19377. }
  19378. }
  19379. const OwnedArray <AudioIODeviceType>& AudioDeviceManager::getAvailableDeviceTypes()
  19380. {
  19381. scanDevicesIfNeeded();
  19382. return availableDeviceTypes;
  19383. }
  19384. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio();
  19385. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio();
  19386. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI();
  19387. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound();
  19388. AudioIODeviceType* juce_createAudioIODeviceType_ASIO();
  19389. AudioIODeviceType* juce_createAudioIODeviceType_ALSA();
  19390. AudioIODeviceType* juce_createAudioIODeviceType_JACK();
  19391. void AudioDeviceManager::createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& list)
  19392. {
  19393. (void) list; // (to avoid 'unused param' warnings)
  19394. #if JUCE_WINDOWS
  19395. #if JUCE_WASAPI
  19396. if (SystemStats::getOperatingSystemType() >= SystemStats::WinVista)
  19397. list.add (juce_createAudioIODeviceType_WASAPI());
  19398. #endif
  19399. #if JUCE_DIRECTSOUND
  19400. list.add (juce_createAudioIODeviceType_DirectSound());
  19401. #endif
  19402. #if JUCE_ASIO
  19403. list.add (juce_createAudioIODeviceType_ASIO());
  19404. #endif
  19405. #endif
  19406. #if JUCE_MAC
  19407. list.add (juce_createAudioIODeviceType_CoreAudio());
  19408. #endif
  19409. #if JUCE_IPHONE
  19410. list.add (juce_createAudioIODeviceType_iPhoneAudio());
  19411. #endif
  19412. #if JUCE_LINUX && JUCE_ALSA
  19413. list.add (juce_createAudioIODeviceType_ALSA());
  19414. #endif
  19415. #if JUCE_LINUX && JUCE_JACK
  19416. list.add (juce_createAudioIODeviceType_JACK());
  19417. #endif
  19418. }
  19419. const String AudioDeviceManager::initialise (const int numInputChannelsNeeded,
  19420. const int numOutputChannelsNeeded,
  19421. const XmlElement* const e,
  19422. const bool selectDefaultDeviceOnFailure,
  19423. const String& preferredDefaultDeviceName,
  19424. const AudioDeviceSetup* preferredSetupOptions)
  19425. {
  19426. scanDevicesIfNeeded();
  19427. numInputChansNeeded = numInputChannelsNeeded;
  19428. numOutputChansNeeded = numOutputChannelsNeeded;
  19429. if (e != 0 && e->hasTagName ("DEVICESETUP"))
  19430. {
  19431. lastExplicitSettings = new XmlElement (*e);
  19432. String error;
  19433. AudioDeviceSetup setup;
  19434. if (preferredSetupOptions != 0)
  19435. setup = *preferredSetupOptions;
  19436. if (e->getStringAttribute ("audioDeviceName").isNotEmpty())
  19437. {
  19438. setup.inputDeviceName = setup.outputDeviceName
  19439. = e->getStringAttribute ("audioDeviceName");
  19440. }
  19441. else
  19442. {
  19443. setup.inputDeviceName = e->getStringAttribute ("audioInputDeviceName");
  19444. setup.outputDeviceName = e->getStringAttribute ("audioOutputDeviceName");
  19445. }
  19446. currentDeviceType = e->getStringAttribute ("deviceType");
  19447. if (currentDeviceType.isEmpty())
  19448. {
  19449. AudioIODeviceType* const type = findType (setup.inputDeviceName, setup.outputDeviceName);
  19450. if (type != 0)
  19451. currentDeviceType = type->getTypeName();
  19452. else if (availableDeviceTypes.size() > 0)
  19453. currentDeviceType = availableDeviceTypes[0]->getTypeName();
  19454. }
  19455. setup.bufferSize = e->getIntAttribute ("audioDeviceBufferSize");
  19456. setup.sampleRate = e->getDoubleAttribute ("audioDeviceRate");
  19457. setup.inputChannels.parseString (e->getStringAttribute ("audioDeviceInChans", "11"), 2);
  19458. setup.outputChannels.parseString (e->getStringAttribute ("audioDeviceOutChans", "11"), 2);
  19459. setup.useDefaultInputChannels = ! e->hasAttribute ("audioDeviceInChans");
  19460. setup.useDefaultOutputChannels = ! e->hasAttribute ("audioDeviceOutChans");
  19461. error = setAudioDeviceSetup (setup, true);
  19462. midiInsFromXml.clear();
  19463. forEachXmlChildElementWithTagName (*e, c, "MIDIINPUT")
  19464. midiInsFromXml.add (c->getStringAttribute ("name"));
  19465. const StringArray allMidiIns (MidiInput::getDevices());
  19466. for (int i = allMidiIns.size(); --i >= 0;)
  19467. setMidiInputEnabled (allMidiIns[i], midiInsFromXml.contains (allMidiIns[i]));
  19468. if (error.isNotEmpty() && selectDefaultDeviceOnFailure)
  19469. error = initialise (numInputChannelsNeeded, numOutputChannelsNeeded, 0,
  19470. false, preferredDefaultDeviceName);
  19471. setDefaultMidiOutput (e->getStringAttribute ("defaultMidiOutput"));
  19472. return error;
  19473. }
  19474. else
  19475. {
  19476. AudioDeviceSetup setup;
  19477. if (preferredSetupOptions != 0)
  19478. {
  19479. setup = *preferredSetupOptions;
  19480. }
  19481. else if (preferredDefaultDeviceName.isNotEmpty())
  19482. {
  19483. for (int j = availableDeviceTypes.size(); --j >= 0;)
  19484. {
  19485. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(j);
  19486. StringArray outs (type->getDeviceNames (false));
  19487. int i;
  19488. for (i = 0; i < outs.size(); ++i)
  19489. {
  19490. if (outs[i].matchesWildcard (preferredDefaultDeviceName, true))
  19491. {
  19492. setup.outputDeviceName = outs[i];
  19493. break;
  19494. }
  19495. }
  19496. StringArray ins (type->getDeviceNames (true));
  19497. for (i = 0; i < ins.size(); ++i)
  19498. {
  19499. if (ins[i].matchesWildcard (preferredDefaultDeviceName, true))
  19500. {
  19501. setup.inputDeviceName = ins[i];
  19502. break;
  19503. }
  19504. }
  19505. }
  19506. }
  19507. insertDefaultDeviceNames (setup);
  19508. return setAudioDeviceSetup (setup, false);
  19509. }
  19510. }
  19511. void AudioDeviceManager::insertDefaultDeviceNames (AudioDeviceSetup& setup) const
  19512. {
  19513. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  19514. if (type != 0)
  19515. {
  19516. if (setup.outputDeviceName.isEmpty())
  19517. setup.outputDeviceName = type->getDeviceNames (false) [type->getDefaultDeviceIndex (false)];
  19518. if (setup.inputDeviceName.isEmpty())
  19519. setup.inputDeviceName = type->getDeviceNames (true) [type->getDefaultDeviceIndex (true)];
  19520. }
  19521. }
  19522. XmlElement* AudioDeviceManager::createStateXml() const
  19523. {
  19524. return lastExplicitSettings != 0 ? new XmlElement (*lastExplicitSettings) : 0;
  19525. }
  19526. void AudioDeviceManager::scanDevicesIfNeeded()
  19527. {
  19528. if (listNeedsScanning)
  19529. {
  19530. listNeedsScanning = false;
  19531. createDeviceTypesIfNeeded();
  19532. for (int i = availableDeviceTypes.size(); --i >= 0;)
  19533. availableDeviceTypes.getUnchecked(i)->scanForDevices();
  19534. }
  19535. }
  19536. AudioIODeviceType* AudioDeviceManager::findType (const String& inputName, const String& outputName)
  19537. {
  19538. scanDevicesIfNeeded();
  19539. for (int i = availableDeviceTypes.size(); --i >= 0;)
  19540. {
  19541. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(i);
  19542. if ((inputName.isNotEmpty() && type->getDeviceNames (true).contains (inputName, true))
  19543. || (outputName.isNotEmpty() && type->getDeviceNames (false).contains (outputName, true)))
  19544. {
  19545. return type;
  19546. }
  19547. }
  19548. return 0;
  19549. }
  19550. void AudioDeviceManager::getAudioDeviceSetup (AudioDeviceSetup& setup)
  19551. {
  19552. setup = currentSetup;
  19553. }
  19554. void AudioDeviceManager::deleteCurrentDevice()
  19555. {
  19556. currentAudioDevice = 0;
  19557. currentSetup.inputDeviceName = String::empty;
  19558. currentSetup.outputDeviceName = String::empty;
  19559. }
  19560. void AudioDeviceManager::setCurrentAudioDeviceType (const String& type,
  19561. const bool treatAsChosenDevice)
  19562. {
  19563. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  19564. {
  19565. if (availableDeviceTypes.getUnchecked(i)->getTypeName() == type
  19566. && currentDeviceType != type)
  19567. {
  19568. currentDeviceType = type;
  19569. AudioDeviceSetup s (*lastDeviceTypeConfigs.getUnchecked(i));
  19570. insertDefaultDeviceNames (s);
  19571. setAudioDeviceSetup (s, treatAsChosenDevice);
  19572. sendChangeMessage (this);
  19573. break;
  19574. }
  19575. }
  19576. }
  19577. AudioIODeviceType* AudioDeviceManager::getCurrentDeviceTypeObject() const
  19578. {
  19579. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  19580. if (availableDeviceTypes[i]->getTypeName() == currentDeviceType)
  19581. return availableDeviceTypes[i];
  19582. return availableDeviceTypes[0];
  19583. }
  19584. const String AudioDeviceManager::setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  19585. const bool treatAsChosenDevice)
  19586. {
  19587. jassert (&newSetup != &currentSetup); // this will have no effect
  19588. if (newSetup == currentSetup && currentAudioDevice != 0)
  19589. return String::empty;
  19590. if (! (newSetup == currentSetup))
  19591. sendChangeMessage (this);
  19592. stopDevice();
  19593. const String newInputDeviceName (numInputChansNeeded == 0 ? String::empty : newSetup.inputDeviceName);
  19594. const String newOutputDeviceName (numOutputChansNeeded == 0 ? String::empty : newSetup.outputDeviceName);
  19595. String error;
  19596. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  19597. if (type == 0 || (newInputDeviceName.isEmpty() && newOutputDeviceName.isEmpty()))
  19598. {
  19599. deleteCurrentDevice();
  19600. if (treatAsChosenDevice)
  19601. updateXml();
  19602. return String::empty;
  19603. }
  19604. if (currentSetup.inputDeviceName != newInputDeviceName
  19605. || currentSetup.outputDeviceName != newOutputDeviceName
  19606. || currentAudioDevice == 0)
  19607. {
  19608. deleteCurrentDevice();
  19609. scanDevicesIfNeeded();
  19610. if (newOutputDeviceName.isNotEmpty()
  19611. && ! type->getDeviceNames (false).contains (newOutputDeviceName))
  19612. {
  19613. return "No such device: " + newOutputDeviceName;
  19614. }
  19615. if (newInputDeviceName.isNotEmpty()
  19616. && ! type->getDeviceNames (true).contains (newInputDeviceName))
  19617. {
  19618. return "No such device: " + newInputDeviceName;
  19619. }
  19620. currentAudioDevice = type->createDevice (newOutputDeviceName, newInputDeviceName);
  19621. if (currentAudioDevice == 0)
  19622. 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!";
  19623. else
  19624. error = currentAudioDevice->getLastError();
  19625. if (error.isNotEmpty())
  19626. {
  19627. deleteCurrentDevice();
  19628. return error;
  19629. }
  19630. if (newSetup.useDefaultInputChannels)
  19631. {
  19632. inputChannels.clear();
  19633. inputChannels.setRange (0, numInputChansNeeded, true);
  19634. }
  19635. if (newSetup.useDefaultOutputChannels)
  19636. {
  19637. outputChannels.clear();
  19638. outputChannels.setRange (0, numOutputChansNeeded, true);
  19639. }
  19640. if (newInputDeviceName.isEmpty())
  19641. inputChannels.clear();
  19642. if (newOutputDeviceName.isEmpty())
  19643. outputChannels.clear();
  19644. }
  19645. if (! newSetup.useDefaultInputChannels)
  19646. inputChannels = newSetup.inputChannels;
  19647. if (! newSetup.useDefaultOutputChannels)
  19648. outputChannels = newSetup.outputChannels;
  19649. currentSetup = newSetup;
  19650. currentSetup.sampleRate = chooseBestSampleRate (newSetup.sampleRate);
  19651. error = currentAudioDevice->open (inputChannels,
  19652. outputChannels,
  19653. currentSetup.sampleRate,
  19654. currentSetup.bufferSize);
  19655. if (error.isEmpty())
  19656. {
  19657. currentDeviceType = currentAudioDevice->getTypeName();
  19658. currentAudioDevice->start (&callbackHandler);
  19659. currentSetup.sampleRate = currentAudioDevice->getCurrentSampleRate();
  19660. currentSetup.bufferSize = currentAudioDevice->getCurrentBufferSizeSamples();
  19661. currentSetup.inputChannels = currentAudioDevice->getActiveInputChannels();
  19662. currentSetup.outputChannels = currentAudioDevice->getActiveOutputChannels();
  19663. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  19664. if (availableDeviceTypes.getUnchecked (i)->getTypeName() == currentDeviceType)
  19665. *(lastDeviceTypeConfigs.getUnchecked (i)) = currentSetup;
  19666. if (treatAsChosenDevice)
  19667. updateXml();
  19668. }
  19669. else
  19670. {
  19671. deleteCurrentDevice();
  19672. }
  19673. return error;
  19674. }
  19675. double AudioDeviceManager::chooseBestSampleRate (double rate) const
  19676. {
  19677. jassert (currentAudioDevice != 0);
  19678. if (rate > 0)
  19679. {
  19680. bool ok = false;
  19681. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  19682. {
  19683. const double sr = currentAudioDevice->getSampleRate (i);
  19684. if (sr == rate)
  19685. ok = true;
  19686. }
  19687. if (! ok)
  19688. rate = 0;
  19689. }
  19690. if (rate == 0)
  19691. {
  19692. double lowestAbove44 = 0.0;
  19693. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  19694. {
  19695. const double sr = currentAudioDevice->getSampleRate (i);
  19696. if (sr >= 44100.0 && (lowestAbove44 == 0 || sr < lowestAbove44))
  19697. lowestAbove44 = sr;
  19698. }
  19699. if (lowestAbove44 == 0.0)
  19700. rate = currentAudioDevice->getSampleRate (0);
  19701. else
  19702. rate = lowestAbove44;
  19703. }
  19704. return rate;
  19705. }
  19706. void AudioDeviceManager::stopDevice()
  19707. {
  19708. if (currentAudioDevice != 0)
  19709. currentAudioDevice->stop();
  19710. testSound = 0;
  19711. }
  19712. void AudioDeviceManager::closeAudioDevice()
  19713. {
  19714. stopDevice();
  19715. currentAudioDevice = 0;
  19716. }
  19717. void AudioDeviceManager::restartLastAudioDevice()
  19718. {
  19719. if (currentAudioDevice == 0)
  19720. {
  19721. if (currentSetup.inputDeviceName.isEmpty()
  19722. && currentSetup.outputDeviceName.isEmpty())
  19723. {
  19724. // This method will only reload the last device that was running
  19725. // before closeAudioDevice() was called - you need to actually open
  19726. // one first, with setAudioDevice().
  19727. jassertfalse;
  19728. return;
  19729. }
  19730. AudioDeviceSetup s (currentSetup);
  19731. setAudioDeviceSetup (s, false);
  19732. }
  19733. }
  19734. void AudioDeviceManager::updateXml()
  19735. {
  19736. lastExplicitSettings = new XmlElement ("DEVICESETUP");
  19737. lastExplicitSettings->setAttribute ("deviceType", currentDeviceType);
  19738. lastExplicitSettings->setAttribute ("audioOutputDeviceName", currentSetup.outputDeviceName);
  19739. lastExplicitSettings->setAttribute ("audioInputDeviceName", currentSetup.inputDeviceName);
  19740. if (currentAudioDevice != 0)
  19741. {
  19742. lastExplicitSettings->setAttribute ("audioDeviceRate", currentAudioDevice->getCurrentSampleRate());
  19743. if (currentAudioDevice->getDefaultBufferSize() != currentAudioDevice->getCurrentBufferSizeSamples())
  19744. lastExplicitSettings->setAttribute ("audioDeviceBufferSize", currentAudioDevice->getCurrentBufferSizeSamples());
  19745. if (! currentSetup.useDefaultInputChannels)
  19746. lastExplicitSettings->setAttribute ("audioDeviceInChans", currentSetup.inputChannels.toString (2));
  19747. if (! currentSetup.useDefaultOutputChannels)
  19748. lastExplicitSettings->setAttribute ("audioDeviceOutChans", currentSetup.outputChannels.toString (2));
  19749. }
  19750. for (int i = 0; i < enabledMidiInputs.size(); ++i)
  19751. {
  19752. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  19753. m->setAttribute ("name", enabledMidiInputs[i]->getName());
  19754. }
  19755. if (midiInsFromXml.size() > 0)
  19756. {
  19757. // Add any midi devices that have been enabled before, but which aren't currently
  19758. // open because the device has been disconnected.
  19759. const StringArray availableMidiDevices (MidiInput::getDevices());
  19760. for (int i = 0; i < midiInsFromXml.size(); ++i)
  19761. {
  19762. if (! availableMidiDevices.contains (midiInsFromXml[i], true))
  19763. {
  19764. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  19765. m->setAttribute ("name", midiInsFromXml[i]);
  19766. }
  19767. }
  19768. }
  19769. if (defaultMidiOutputName.isNotEmpty())
  19770. lastExplicitSettings->setAttribute ("defaultMidiOutput", defaultMidiOutputName);
  19771. }
  19772. void AudioDeviceManager::addAudioCallback (AudioIODeviceCallback* newCallback)
  19773. {
  19774. {
  19775. const ScopedLock sl (audioCallbackLock);
  19776. if (callbacks.contains (newCallback))
  19777. return;
  19778. }
  19779. if (currentAudioDevice != 0 && newCallback != 0)
  19780. newCallback->audioDeviceAboutToStart (currentAudioDevice);
  19781. const ScopedLock sl (audioCallbackLock);
  19782. callbacks.add (newCallback);
  19783. }
  19784. void AudioDeviceManager::removeAudioCallback (AudioIODeviceCallback* callback)
  19785. {
  19786. if (callback != 0)
  19787. {
  19788. bool needsDeinitialising = currentAudioDevice != 0;
  19789. {
  19790. const ScopedLock sl (audioCallbackLock);
  19791. needsDeinitialising = needsDeinitialising && callbacks.contains (callback);
  19792. callbacks.removeValue (callback);
  19793. }
  19794. if (needsDeinitialising)
  19795. callback->audioDeviceStopped();
  19796. }
  19797. }
  19798. void AudioDeviceManager::audioDeviceIOCallbackInt (const float** inputChannelData,
  19799. int numInputChannels,
  19800. float** outputChannelData,
  19801. int numOutputChannels,
  19802. int numSamples)
  19803. {
  19804. const ScopedLock sl (audioCallbackLock);
  19805. if (inputLevelMeasurementEnabledCount > 0)
  19806. {
  19807. for (int j = 0; j < numSamples; ++j)
  19808. {
  19809. float s = 0;
  19810. for (int i = 0; i < numInputChannels; ++i)
  19811. s += std::abs (inputChannelData[i][j]);
  19812. s /= numInputChannels;
  19813. const double decayFactor = 0.99992;
  19814. if (s > inputLevel)
  19815. inputLevel = s;
  19816. else if (inputLevel > 0.001f)
  19817. inputLevel *= decayFactor;
  19818. else
  19819. inputLevel = 0;
  19820. }
  19821. }
  19822. if (callbacks.size() > 0)
  19823. {
  19824. const double callbackStartTime = Time::getMillisecondCounterHiRes();
  19825. tempBuffer.setSize (jmax (1, numOutputChannels), jmax (1, numSamples), false, false, true);
  19826. callbacks.getUnchecked(0)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  19827. outputChannelData, numOutputChannels, numSamples);
  19828. float** const tempChans = tempBuffer.getArrayOfChannels();
  19829. for (int i = callbacks.size(); --i > 0;)
  19830. {
  19831. callbacks.getUnchecked(i)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  19832. tempChans, numOutputChannels, numSamples);
  19833. for (int chan = 0; chan < numOutputChannels; ++chan)
  19834. {
  19835. const float* const src = tempChans [chan];
  19836. float* const dst = outputChannelData [chan];
  19837. if (src != 0 && dst != 0)
  19838. for (int j = 0; j < numSamples; ++j)
  19839. dst[j] += src[j];
  19840. }
  19841. }
  19842. const double msTaken = Time::getMillisecondCounterHiRes() - callbackStartTime;
  19843. const double filterAmount = 0.2;
  19844. cpuUsageMs += filterAmount * (msTaken - cpuUsageMs);
  19845. }
  19846. else
  19847. {
  19848. for (int i = 0; i < numOutputChannels; ++i)
  19849. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  19850. }
  19851. if (testSound != 0)
  19852. {
  19853. const int numSamps = jmin (numSamples, testSound->getNumSamples() - testSoundPosition);
  19854. const float* const src = testSound->getSampleData (0, testSoundPosition);
  19855. for (int i = 0; i < numOutputChannels; ++i)
  19856. for (int j = 0; j < numSamps; ++j)
  19857. outputChannelData [i][j] += src[j];
  19858. testSoundPosition += numSamps;
  19859. if (testSoundPosition >= testSound->getNumSamples())
  19860. testSound = 0;
  19861. }
  19862. }
  19863. void AudioDeviceManager::audioDeviceAboutToStartInt (AudioIODevice* const device)
  19864. {
  19865. cpuUsageMs = 0;
  19866. const double sampleRate = device->getCurrentSampleRate();
  19867. const int blockSize = device->getCurrentBufferSizeSamples();
  19868. if (sampleRate > 0.0 && blockSize > 0)
  19869. {
  19870. const double msPerBlock = 1000.0 * blockSize / sampleRate;
  19871. timeToCpuScale = (msPerBlock > 0.0) ? (1.0 / msPerBlock) : 0.0;
  19872. }
  19873. {
  19874. const ScopedLock sl (audioCallbackLock);
  19875. for (int i = callbacks.size(); --i >= 0;)
  19876. callbacks.getUnchecked(i)->audioDeviceAboutToStart (device);
  19877. }
  19878. sendChangeMessage (this);
  19879. }
  19880. void AudioDeviceManager::audioDeviceStoppedInt()
  19881. {
  19882. cpuUsageMs = 0;
  19883. timeToCpuScale = 0;
  19884. sendChangeMessage (this);
  19885. const ScopedLock sl (audioCallbackLock);
  19886. for (int i = callbacks.size(); --i >= 0;)
  19887. callbacks.getUnchecked(i)->audioDeviceStopped();
  19888. }
  19889. double AudioDeviceManager::getCpuUsage() const
  19890. {
  19891. return jlimit (0.0, 1.0, timeToCpuScale * cpuUsageMs);
  19892. }
  19893. void AudioDeviceManager::setMidiInputEnabled (const String& name,
  19894. const bool enabled)
  19895. {
  19896. if (enabled != isMidiInputEnabled (name))
  19897. {
  19898. if (enabled)
  19899. {
  19900. const int index = MidiInput::getDevices().indexOf (name);
  19901. if (index >= 0)
  19902. {
  19903. MidiInput* const min = MidiInput::openDevice (index, &callbackHandler);
  19904. if (min != 0)
  19905. {
  19906. enabledMidiInputs.add (min);
  19907. min->start();
  19908. }
  19909. }
  19910. }
  19911. else
  19912. {
  19913. for (int i = enabledMidiInputs.size(); --i >= 0;)
  19914. if (enabledMidiInputs[i]->getName() == name)
  19915. enabledMidiInputs.remove (i);
  19916. }
  19917. updateXml();
  19918. sendChangeMessage (this);
  19919. }
  19920. }
  19921. bool AudioDeviceManager::isMidiInputEnabled (const String& name) const
  19922. {
  19923. for (int i = enabledMidiInputs.size(); --i >= 0;)
  19924. if (enabledMidiInputs[i]->getName() == name)
  19925. return true;
  19926. return false;
  19927. }
  19928. void AudioDeviceManager::addMidiInputCallback (const String& name,
  19929. MidiInputCallback* callback)
  19930. {
  19931. removeMidiInputCallback (name, callback);
  19932. if (name.isEmpty())
  19933. {
  19934. midiCallbacks.add (callback);
  19935. midiCallbackDevices.add (0);
  19936. }
  19937. else
  19938. {
  19939. for (int i = enabledMidiInputs.size(); --i >= 0;)
  19940. {
  19941. if (enabledMidiInputs[i]->getName() == name)
  19942. {
  19943. const ScopedLock sl (midiCallbackLock);
  19944. midiCallbacks.add (callback);
  19945. midiCallbackDevices.add (enabledMidiInputs[i]);
  19946. break;
  19947. }
  19948. }
  19949. }
  19950. }
  19951. void AudioDeviceManager::removeMidiInputCallback (const String& name,
  19952. MidiInputCallback* /*callback*/)
  19953. {
  19954. const ScopedLock sl (midiCallbackLock);
  19955. for (int i = midiCallbacks.size(); --i >= 0;)
  19956. {
  19957. String devName;
  19958. if (midiCallbackDevices.getUnchecked(i) != 0)
  19959. devName = midiCallbackDevices.getUnchecked(i)->getName();
  19960. if (devName == name)
  19961. {
  19962. midiCallbacks.remove (i);
  19963. midiCallbackDevices.remove (i);
  19964. }
  19965. }
  19966. }
  19967. void AudioDeviceManager::handleIncomingMidiMessageInt (MidiInput* source,
  19968. const MidiMessage& message)
  19969. {
  19970. if (! message.isActiveSense())
  19971. {
  19972. const bool isDefaultSource = (source == 0 || source == enabledMidiInputs.getFirst());
  19973. const ScopedLock sl (midiCallbackLock);
  19974. for (int i = midiCallbackDevices.size(); --i >= 0;)
  19975. {
  19976. MidiInput* const md = midiCallbackDevices.getUnchecked(i);
  19977. if (md == source || (md == 0 && isDefaultSource))
  19978. midiCallbacks.getUnchecked(i)->handleIncomingMidiMessage (source, message);
  19979. }
  19980. }
  19981. }
  19982. void AudioDeviceManager::setDefaultMidiOutput (const String& deviceName)
  19983. {
  19984. if (defaultMidiOutputName != deviceName)
  19985. {
  19986. SortedSet <AudioIODeviceCallback*> oldCallbacks;
  19987. {
  19988. const ScopedLock sl (audioCallbackLock);
  19989. oldCallbacks = callbacks;
  19990. callbacks.clear();
  19991. }
  19992. if (currentAudioDevice != 0)
  19993. for (int i = oldCallbacks.size(); --i >= 0;)
  19994. oldCallbacks.getUnchecked(i)->audioDeviceStopped();
  19995. defaultMidiOutput = 0;
  19996. defaultMidiOutputName = deviceName;
  19997. if (deviceName.isNotEmpty())
  19998. defaultMidiOutput = MidiOutput::openDevice (MidiOutput::getDevices().indexOf (deviceName));
  19999. if (currentAudioDevice != 0)
  20000. for (int i = oldCallbacks.size(); --i >= 0;)
  20001. oldCallbacks.getUnchecked(i)->audioDeviceAboutToStart (currentAudioDevice);
  20002. {
  20003. const ScopedLock sl (audioCallbackLock);
  20004. callbacks = oldCallbacks;
  20005. }
  20006. updateXml();
  20007. sendChangeMessage (this);
  20008. }
  20009. }
  20010. void AudioDeviceManager::CallbackHandler::audioDeviceIOCallback (const float** inputChannelData,
  20011. int numInputChannels,
  20012. float** outputChannelData,
  20013. int numOutputChannels,
  20014. int numSamples)
  20015. {
  20016. owner->audioDeviceIOCallbackInt (inputChannelData, numInputChannels, outputChannelData, numOutputChannels, numSamples);
  20017. }
  20018. void AudioDeviceManager::CallbackHandler::audioDeviceAboutToStart (AudioIODevice* device)
  20019. {
  20020. owner->audioDeviceAboutToStartInt (device);
  20021. }
  20022. void AudioDeviceManager::CallbackHandler::audioDeviceStopped()
  20023. {
  20024. owner->audioDeviceStoppedInt();
  20025. }
  20026. void AudioDeviceManager::CallbackHandler::handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message)
  20027. {
  20028. owner->handleIncomingMidiMessageInt (source, message);
  20029. }
  20030. void AudioDeviceManager::playTestSound()
  20031. {
  20032. { // cunningly nested to swap, unlock and delete in that order.
  20033. ScopedPointer <AudioSampleBuffer> oldSound;
  20034. {
  20035. const ScopedLock sl (audioCallbackLock);
  20036. oldSound = testSound;
  20037. }
  20038. }
  20039. testSoundPosition = 0;
  20040. if (currentAudioDevice != 0)
  20041. {
  20042. const double sampleRate = currentAudioDevice->getCurrentSampleRate();
  20043. const int soundLength = (int) sampleRate;
  20044. AudioSampleBuffer* const newSound = new AudioSampleBuffer (1, soundLength);
  20045. float* samples = newSound->getSampleData (0);
  20046. const double frequency = MidiMessage::getMidiNoteInHertz (80);
  20047. const float amplitude = 0.5f;
  20048. const double phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  20049. for (int i = 0; i < soundLength; ++i)
  20050. samples[i] = amplitude * (float) std::sin (i * phasePerSample);
  20051. newSound->applyGainRamp (0, 0, soundLength / 10, 0.0f, 1.0f);
  20052. newSound->applyGainRamp (0, soundLength - soundLength / 4, soundLength / 4, 1.0f, 0.0f);
  20053. const ScopedLock sl (audioCallbackLock);
  20054. testSound = newSound;
  20055. }
  20056. }
  20057. void AudioDeviceManager::enableInputLevelMeasurement (const bool enableMeasurement)
  20058. {
  20059. const ScopedLock sl (audioCallbackLock);
  20060. if (enableMeasurement)
  20061. ++inputLevelMeasurementEnabledCount;
  20062. else
  20063. --inputLevelMeasurementEnabledCount;
  20064. inputLevel = 0;
  20065. }
  20066. double AudioDeviceManager::getCurrentInputLevel() const
  20067. {
  20068. jassert (inputLevelMeasurementEnabledCount > 0); // you need to call enableInputLevelMeasurement() before using this!
  20069. return inputLevel;
  20070. }
  20071. END_JUCE_NAMESPACE
  20072. /*** End of inlined file: juce_AudioDeviceManager.cpp ***/
  20073. /*** Start of inlined file: juce_AudioIODevice.cpp ***/
  20074. BEGIN_JUCE_NAMESPACE
  20075. AudioIODevice::AudioIODevice (const String& deviceName, const String& typeName_)
  20076. : name (deviceName),
  20077. typeName (typeName_)
  20078. {
  20079. }
  20080. AudioIODevice::~AudioIODevice()
  20081. {
  20082. }
  20083. bool AudioIODevice::hasControlPanel() const
  20084. {
  20085. return false;
  20086. }
  20087. bool AudioIODevice::showControlPanel()
  20088. {
  20089. jassertfalse; // this should only be called for devices which return true from
  20090. // their hasControlPanel() method.
  20091. return false;
  20092. }
  20093. END_JUCE_NAMESPACE
  20094. /*** End of inlined file: juce_AudioIODevice.cpp ***/
  20095. /*** Start of inlined file: juce_AudioIODeviceType.cpp ***/
  20096. BEGIN_JUCE_NAMESPACE
  20097. AudioIODeviceType::AudioIODeviceType (const String& name)
  20098. : typeName (name)
  20099. {
  20100. }
  20101. AudioIODeviceType::~AudioIODeviceType()
  20102. {
  20103. }
  20104. END_JUCE_NAMESPACE
  20105. /*** End of inlined file: juce_AudioIODeviceType.cpp ***/
  20106. /*** Start of inlined file: juce_MidiOutput.cpp ***/
  20107. BEGIN_JUCE_NAMESPACE
  20108. MidiOutput::MidiOutput()
  20109. : Thread ("midi out"),
  20110. internal (0),
  20111. firstMessage (0)
  20112. {
  20113. }
  20114. MidiOutput::PendingMessage::PendingMessage (const uint8* const data, const int len,
  20115. const double sampleNumber)
  20116. : message (data, len, sampleNumber)
  20117. {
  20118. }
  20119. void MidiOutput::sendBlockOfMessages (const MidiBuffer& buffer,
  20120. const double millisecondCounterToStartAt,
  20121. double samplesPerSecondForBuffer)
  20122. {
  20123. // You've got to call startBackgroundThread() for this to actually work..
  20124. jassert (isThreadRunning());
  20125. // this needs to be a value in the future - RTFM for this method!
  20126. jassert (millisecondCounterToStartAt > 0);
  20127. const double timeScaleFactor = 1000.0 / samplesPerSecondForBuffer;
  20128. MidiBuffer::Iterator i (buffer);
  20129. const uint8* data;
  20130. int len, time;
  20131. while (i.getNextEvent (data, len, time))
  20132. {
  20133. const double eventTime = millisecondCounterToStartAt + timeScaleFactor * time;
  20134. PendingMessage* const m
  20135. = new PendingMessage (data, len, eventTime);
  20136. const ScopedLock sl (lock);
  20137. if (firstMessage == 0 || firstMessage->message.getTimeStamp() > eventTime)
  20138. {
  20139. m->next = firstMessage;
  20140. firstMessage = m;
  20141. }
  20142. else
  20143. {
  20144. PendingMessage* mm = firstMessage;
  20145. while (mm->next != 0 && mm->next->message.getTimeStamp() <= eventTime)
  20146. mm = mm->next;
  20147. m->next = mm->next;
  20148. mm->next = m;
  20149. }
  20150. }
  20151. notify();
  20152. }
  20153. void MidiOutput::clearAllPendingMessages()
  20154. {
  20155. const ScopedLock sl (lock);
  20156. while (firstMessage != 0)
  20157. {
  20158. PendingMessage* const m = firstMessage;
  20159. firstMessage = firstMessage->next;
  20160. delete m;
  20161. }
  20162. }
  20163. void MidiOutput::startBackgroundThread()
  20164. {
  20165. startThread (9);
  20166. }
  20167. void MidiOutput::stopBackgroundThread()
  20168. {
  20169. stopThread (5000);
  20170. }
  20171. void MidiOutput::run()
  20172. {
  20173. while (! threadShouldExit())
  20174. {
  20175. uint32 now = Time::getMillisecondCounter();
  20176. uint32 eventTime = 0;
  20177. uint32 timeToWait = 500;
  20178. PendingMessage* message;
  20179. {
  20180. const ScopedLock sl (lock);
  20181. message = firstMessage;
  20182. if (message != 0)
  20183. {
  20184. eventTime = roundToInt (message->message.getTimeStamp());
  20185. if (eventTime > now + 20)
  20186. {
  20187. timeToWait = eventTime - (now + 20);
  20188. message = 0;
  20189. }
  20190. else
  20191. {
  20192. firstMessage = message->next;
  20193. }
  20194. }
  20195. }
  20196. if (message != 0)
  20197. {
  20198. if (eventTime > now)
  20199. {
  20200. Time::waitForMillisecondCounter (eventTime);
  20201. if (threadShouldExit())
  20202. break;
  20203. }
  20204. if (eventTime > now - 200)
  20205. sendMessageNow (message->message);
  20206. delete message;
  20207. }
  20208. else
  20209. {
  20210. jassert (timeToWait < 1000 * 30);
  20211. wait (timeToWait);
  20212. }
  20213. }
  20214. clearAllPendingMessages();
  20215. }
  20216. END_JUCE_NAMESPACE
  20217. /*** End of inlined file: juce_MidiOutput.cpp ***/
  20218. /*** Start of inlined file: juce_AudioDataConverters.cpp ***/
  20219. BEGIN_JUCE_NAMESPACE
  20220. void AudioDataConverters::convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20221. {
  20222. const double maxVal = (double) 0x7fff;
  20223. char* intData = static_cast <char*> (dest);
  20224. if (dest != (void*) source || destBytesPerSample <= 4)
  20225. {
  20226. for (int i = 0; i < numSamples; ++i)
  20227. {
  20228. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20229. intData += destBytesPerSample;
  20230. }
  20231. }
  20232. else
  20233. {
  20234. intData += destBytesPerSample * numSamples;
  20235. for (int i = numSamples; --i >= 0;)
  20236. {
  20237. intData -= destBytesPerSample;
  20238. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20239. }
  20240. }
  20241. }
  20242. void AudioDataConverters::convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20243. {
  20244. const double maxVal = (double) 0x7fff;
  20245. char* intData = static_cast <char*> (dest);
  20246. if (dest != (void*) source || destBytesPerSample <= 4)
  20247. {
  20248. for (int i = 0; i < numSamples; ++i)
  20249. {
  20250. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20251. intData += destBytesPerSample;
  20252. }
  20253. }
  20254. else
  20255. {
  20256. intData += destBytesPerSample * numSamples;
  20257. for (int i = numSamples; --i >= 0;)
  20258. {
  20259. intData -= destBytesPerSample;
  20260. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20261. }
  20262. }
  20263. }
  20264. void AudioDataConverters::convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20265. {
  20266. const double maxVal = (double) 0x7fffff;
  20267. char* intData = static_cast <char*> (dest);
  20268. if (dest != (void*) source || destBytesPerSample <= 4)
  20269. {
  20270. for (int i = 0; i < numSamples; ++i)
  20271. {
  20272. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20273. intData += destBytesPerSample;
  20274. }
  20275. }
  20276. else
  20277. {
  20278. intData += destBytesPerSample * numSamples;
  20279. for (int i = numSamples; --i >= 0;)
  20280. {
  20281. intData -= destBytesPerSample;
  20282. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20283. }
  20284. }
  20285. }
  20286. void AudioDataConverters::convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20287. {
  20288. const double maxVal = (double) 0x7fffff;
  20289. char* intData = static_cast <char*> (dest);
  20290. if (dest != (void*) source || destBytesPerSample <= 4)
  20291. {
  20292. for (int i = 0; i < numSamples; ++i)
  20293. {
  20294. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20295. intData += destBytesPerSample;
  20296. }
  20297. }
  20298. else
  20299. {
  20300. intData += destBytesPerSample * numSamples;
  20301. for (int i = numSamples; --i >= 0;)
  20302. {
  20303. intData -= destBytesPerSample;
  20304. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20305. }
  20306. }
  20307. }
  20308. void AudioDataConverters::convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20309. {
  20310. const double maxVal = (double) 0x7fffffff;
  20311. char* intData = static_cast <char*> (dest);
  20312. if (dest != (void*) source || destBytesPerSample <= 4)
  20313. {
  20314. for (int i = 0; i < numSamples; ++i)
  20315. {
  20316. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20317. intData += destBytesPerSample;
  20318. }
  20319. }
  20320. else
  20321. {
  20322. intData += destBytesPerSample * numSamples;
  20323. for (int i = numSamples; --i >= 0;)
  20324. {
  20325. intData -= destBytesPerSample;
  20326. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20327. }
  20328. }
  20329. }
  20330. void AudioDataConverters::convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20331. {
  20332. const double maxVal = (double) 0x7fffffff;
  20333. char* intData = static_cast <char*> (dest);
  20334. if (dest != (void*) source || destBytesPerSample <= 4)
  20335. {
  20336. for (int i = 0; i < numSamples; ++i)
  20337. {
  20338. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20339. intData += destBytesPerSample;
  20340. }
  20341. }
  20342. else
  20343. {
  20344. intData += destBytesPerSample * numSamples;
  20345. for (int i = numSamples; --i >= 0;)
  20346. {
  20347. intData -= destBytesPerSample;
  20348. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20349. }
  20350. }
  20351. }
  20352. void AudioDataConverters::convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20353. {
  20354. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  20355. char* d = static_cast <char*> (dest);
  20356. for (int i = 0; i < numSamples; ++i)
  20357. {
  20358. *(float*) d = source[i];
  20359. #if JUCE_BIG_ENDIAN
  20360. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  20361. #endif
  20362. d += destBytesPerSample;
  20363. }
  20364. }
  20365. void AudioDataConverters::convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20366. {
  20367. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  20368. char* d = static_cast <char*> (dest);
  20369. for (int i = 0; i < numSamples; ++i)
  20370. {
  20371. *(float*) d = source[i];
  20372. #if JUCE_LITTLE_ENDIAN
  20373. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  20374. #endif
  20375. d += destBytesPerSample;
  20376. }
  20377. }
  20378. void AudioDataConverters::convertInt16LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20379. {
  20380. const float scale = 1.0f / 0x7fff;
  20381. const char* intData = static_cast <const char*> (source);
  20382. if (source != (void*) dest || srcBytesPerSample >= 4)
  20383. {
  20384. for (int i = 0; i < numSamples; ++i)
  20385. {
  20386. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  20387. intData += srcBytesPerSample;
  20388. }
  20389. }
  20390. else
  20391. {
  20392. intData += srcBytesPerSample * numSamples;
  20393. for (int i = numSamples; --i >= 0;)
  20394. {
  20395. intData -= srcBytesPerSample;
  20396. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  20397. }
  20398. }
  20399. }
  20400. void AudioDataConverters::convertInt16BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20401. {
  20402. const float scale = 1.0f / 0x7fff;
  20403. const char* intData = static_cast <const char*> (source);
  20404. if (source != (void*) dest || srcBytesPerSample >= 4)
  20405. {
  20406. for (int i = 0; i < numSamples; ++i)
  20407. {
  20408. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  20409. intData += srcBytesPerSample;
  20410. }
  20411. }
  20412. else
  20413. {
  20414. intData += srcBytesPerSample * numSamples;
  20415. for (int i = numSamples; --i >= 0;)
  20416. {
  20417. intData -= srcBytesPerSample;
  20418. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  20419. }
  20420. }
  20421. }
  20422. void AudioDataConverters::convertInt24LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20423. {
  20424. const float scale = 1.0f / 0x7fffff;
  20425. const char* intData = static_cast <const char*> (source);
  20426. if (source != (void*) dest || srcBytesPerSample >= 4)
  20427. {
  20428. for (int i = 0; i < numSamples; ++i)
  20429. {
  20430. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  20431. intData += srcBytesPerSample;
  20432. }
  20433. }
  20434. else
  20435. {
  20436. intData += srcBytesPerSample * numSamples;
  20437. for (int i = numSamples; --i >= 0;)
  20438. {
  20439. intData -= srcBytesPerSample;
  20440. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  20441. }
  20442. }
  20443. }
  20444. void AudioDataConverters::convertInt24BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20445. {
  20446. const float scale = 1.0f / 0x7fffff;
  20447. const char* intData = static_cast <const char*> (source);
  20448. if (source != (void*) dest || srcBytesPerSample >= 4)
  20449. {
  20450. for (int i = 0; i < numSamples; ++i)
  20451. {
  20452. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  20453. intData += srcBytesPerSample;
  20454. }
  20455. }
  20456. else
  20457. {
  20458. intData += srcBytesPerSample * numSamples;
  20459. for (int i = numSamples; --i >= 0;)
  20460. {
  20461. intData -= srcBytesPerSample;
  20462. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  20463. }
  20464. }
  20465. }
  20466. void AudioDataConverters::convertInt32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20467. {
  20468. const float scale = 1.0f / 0x7fffffff;
  20469. const char* intData = static_cast <const char*> (source);
  20470. if (source != (void*) dest || srcBytesPerSample >= 4)
  20471. {
  20472. for (int i = 0; i < numSamples; ++i)
  20473. {
  20474. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  20475. intData += srcBytesPerSample;
  20476. }
  20477. }
  20478. else
  20479. {
  20480. intData += srcBytesPerSample * numSamples;
  20481. for (int i = numSamples; --i >= 0;)
  20482. {
  20483. intData -= srcBytesPerSample;
  20484. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  20485. }
  20486. }
  20487. }
  20488. void AudioDataConverters::convertInt32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20489. {
  20490. const float scale = 1.0f / 0x7fffffff;
  20491. const char* intData = static_cast <const char*> (source);
  20492. if (source != (void*) dest || srcBytesPerSample >= 4)
  20493. {
  20494. for (int i = 0; i < numSamples; ++i)
  20495. {
  20496. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  20497. intData += srcBytesPerSample;
  20498. }
  20499. }
  20500. else
  20501. {
  20502. intData += srcBytesPerSample * numSamples;
  20503. for (int i = numSamples; --i >= 0;)
  20504. {
  20505. intData -= srcBytesPerSample;
  20506. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  20507. }
  20508. }
  20509. }
  20510. void AudioDataConverters::convertFloat32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20511. {
  20512. const char* s = static_cast <const char*> (source);
  20513. for (int i = 0; i < numSamples; ++i)
  20514. {
  20515. dest[i] = *(float*)s;
  20516. #if JUCE_BIG_ENDIAN
  20517. uint32* const d = (uint32*) (dest + i);
  20518. *d = ByteOrder::swap (*d);
  20519. #endif
  20520. s += srcBytesPerSample;
  20521. }
  20522. }
  20523. void AudioDataConverters::convertFloat32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20524. {
  20525. const char* s = static_cast <const char*> (source);
  20526. for (int i = 0; i < numSamples; ++i)
  20527. {
  20528. dest[i] = *(float*)s;
  20529. #if JUCE_LITTLE_ENDIAN
  20530. uint32* const d = (uint32*) (dest + i);
  20531. *d = ByteOrder::swap (*d);
  20532. #endif
  20533. s += srcBytesPerSample;
  20534. }
  20535. }
  20536. void AudioDataConverters::convertFloatToFormat (const DataFormat destFormat,
  20537. const float* const source,
  20538. void* const dest,
  20539. const int numSamples)
  20540. {
  20541. switch (destFormat)
  20542. {
  20543. case int16LE:
  20544. convertFloatToInt16LE (source, dest, numSamples);
  20545. break;
  20546. case int16BE:
  20547. convertFloatToInt16BE (source, dest, numSamples);
  20548. break;
  20549. case int24LE:
  20550. convertFloatToInt24LE (source, dest, numSamples);
  20551. break;
  20552. case int24BE:
  20553. convertFloatToInt24BE (source, dest, numSamples);
  20554. break;
  20555. case int32LE:
  20556. convertFloatToInt32LE (source, dest, numSamples);
  20557. break;
  20558. case int32BE:
  20559. convertFloatToInt32BE (source, dest, numSamples);
  20560. break;
  20561. case float32LE:
  20562. convertFloatToFloat32LE (source, dest, numSamples);
  20563. break;
  20564. case float32BE:
  20565. convertFloatToFloat32BE (source, dest, numSamples);
  20566. break;
  20567. default:
  20568. jassertfalse;
  20569. break;
  20570. }
  20571. }
  20572. void AudioDataConverters::convertFormatToFloat (const DataFormat sourceFormat,
  20573. const void* const source,
  20574. float* const dest,
  20575. const int numSamples)
  20576. {
  20577. switch (sourceFormat)
  20578. {
  20579. case int16LE:
  20580. convertInt16LEToFloat (source, dest, numSamples);
  20581. break;
  20582. case int16BE:
  20583. convertInt16BEToFloat (source, dest, numSamples);
  20584. break;
  20585. case int24LE:
  20586. convertInt24LEToFloat (source, dest, numSamples);
  20587. break;
  20588. case int24BE:
  20589. convertInt24BEToFloat (source, dest, numSamples);
  20590. break;
  20591. case int32LE:
  20592. convertInt32LEToFloat (source, dest, numSamples);
  20593. break;
  20594. case int32BE:
  20595. convertInt32BEToFloat (source, dest, numSamples);
  20596. break;
  20597. case float32LE:
  20598. convertFloat32LEToFloat (source, dest, numSamples);
  20599. break;
  20600. case float32BE:
  20601. convertFloat32BEToFloat (source, dest, numSamples);
  20602. break;
  20603. default:
  20604. jassertfalse;
  20605. break;
  20606. }
  20607. }
  20608. void AudioDataConverters::interleaveSamples (const float** const source,
  20609. float* const dest,
  20610. const int numSamples,
  20611. const int numChannels)
  20612. {
  20613. for (int chan = 0; chan < numChannels; ++chan)
  20614. {
  20615. int i = chan;
  20616. const float* src = source [chan];
  20617. for (int j = 0; j < numSamples; ++j)
  20618. {
  20619. dest [i] = src [j];
  20620. i += numChannels;
  20621. }
  20622. }
  20623. }
  20624. void AudioDataConverters::deinterleaveSamples (const float* const source,
  20625. float** const dest,
  20626. const int numSamples,
  20627. const int numChannels)
  20628. {
  20629. for (int chan = 0; chan < numChannels; ++chan)
  20630. {
  20631. int i = chan;
  20632. float* dst = dest [chan];
  20633. for (int j = 0; j < numSamples; ++j)
  20634. {
  20635. dst [j] = source [i];
  20636. i += numChannels;
  20637. }
  20638. }
  20639. }
  20640. END_JUCE_NAMESPACE
  20641. /*** End of inlined file: juce_AudioDataConverters.cpp ***/
  20642. /*** Start of inlined file: juce_AudioSampleBuffer.cpp ***/
  20643. BEGIN_JUCE_NAMESPACE
  20644. AudioSampleBuffer::AudioSampleBuffer (const int numChannels_,
  20645. const int numSamples) throw()
  20646. : numChannels (numChannels_),
  20647. size (numSamples)
  20648. {
  20649. jassert (numSamples >= 0);
  20650. jassert (numChannels_ > 0);
  20651. allocateData();
  20652. }
  20653. AudioSampleBuffer::AudioSampleBuffer (const AudioSampleBuffer& other) throw()
  20654. : numChannels (other.numChannels),
  20655. size (other.size)
  20656. {
  20657. allocateData();
  20658. const size_t numBytes = size * sizeof (float);
  20659. for (int i = 0; i < numChannels; ++i)
  20660. memcpy (channels[i], other.channels[i], numBytes);
  20661. }
  20662. void AudioSampleBuffer::allocateData()
  20663. {
  20664. const size_t channelListSize = (numChannels + 1) * sizeof (float*);
  20665. allocatedBytes = (int) (numChannels * size * sizeof (float) + channelListSize + 32);
  20666. allocatedData.malloc (allocatedBytes);
  20667. channels = reinterpret_cast <float**> (allocatedData.getData());
  20668. float* chan = (float*) (allocatedData + channelListSize);
  20669. for (int i = 0; i < numChannels; ++i)
  20670. {
  20671. channels[i] = chan;
  20672. chan += size;
  20673. }
  20674. channels [numChannels] = 0;
  20675. }
  20676. AudioSampleBuffer::AudioSampleBuffer (float** dataToReferTo,
  20677. const int numChannels_,
  20678. const int numSamples) throw()
  20679. : numChannels (numChannels_),
  20680. size (numSamples),
  20681. allocatedBytes (0)
  20682. {
  20683. jassert (numChannels_ > 0);
  20684. allocateChannels (dataToReferTo);
  20685. }
  20686. void AudioSampleBuffer::setDataToReferTo (float** dataToReferTo,
  20687. const int newNumChannels,
  20688. const int newNumSamples) throw()
  20689. {
  20690. jassert (newNumChannels > 0);
  20691. allocatedBytes = 0;
  20692. allocatedData.free();
  20693. numChannels = newNumChannels;
  20694. size = newNumSamples;
  20695. allocateChannels (dataToReferTo);
  20696. }
  20697. void AudioSampleBuffer::allocateChannels (float** const dataToReferTo)
  20698. {
  20699. // (try to avoid doing a malloc here, as that'll blow up things like Pro-Tools)
  20700. if (numChannels < numElementsInArray (preallocatedChannelSpace))
  20701. {
  20702. channels = static_cast <float**> (preallocatedChannelSpace);
  20703. }
  20704. else
  20705. {
  20706. allocatedData.malloc (numChannels + 1, sizeof (float*));
  20707. channels = reinterpret_cast <float**> (allocatedData.getData());
  20708. }
  20709. for (int i = 0; i < numChannels; ++i)
  20710. {
  20711. // you have to pass in the same number of valid pointers as numChannels
  20712. jassert (dataToReferTo[i] != 0);
  20713. channels[i] = dataToReferTo[i];
  20714. }
  20715. channels [numChannels] = 0;
  20716. }
  20717. AudioSampleBuffer& AudioSampleBuffer::operator= (const AudioSampleBuffer& other) throw()
  20718. {
  20719. if (this != &other)
  20720. {
  20721. setSize (other.getNumChannels(), other.getNumSamples(), false, false, false);
  20722. const size_t numBytes = size * sizeof (float);
  20723. for (int i = 0; i < numChannels; ++i)
  20724. memcpy (channels[i], other.channels[i], numBytes);
  20725. }
  20726. return *this;
  20727. }
  20728. AudioSampleBuffer::~AudioSampleBuffer() throw()
  20729. {
  20730. }
  20731. void AudioSampleBuffer::setSize (const int newNumChannels,
  20732. const int newNumSamples,
  20733. const bool keepExistingContent,
  20734. const bool clearExtraSpace,
  20735. const bool avoidReallocating) throw()
  20736. {
  20737. jassert (newNumChannels > 0);
  20738. if (newNumSamples != size || newNumChannels != numChannels)
  20739. {
  20740. const size_t channelListSize = (newNumChannels + 1) * sizeof (float*);
  20741. const size_t newTotalBytes = (newNumChannels * newNumSamples * sizeof (float)) + channelListSize + 32;
  20742. if (keepExistingContent)
  20743. {
  20744. HeapBlock <char> newData;
  20745. newData.allocate (newTotalBytes, clearExtraSpace);
  20746. const int numChansToCopy = jmin (numChannels, newNumChannels);
  20747. const size_t numBytesToCopy = sizeof (float) * jmin (newNumSamples, size);
  20748. float** const newChannels = reinterpret_cast <float**> (newData.getData());
  20749. float* newChan = reinterpret_cast <float*> (newData + channelListSize);
  20750. for (int i = 0; i < numChansToCopy; ++i)
  20751. {
  20752. memcpy (newChan, channels[i], numBytesToCopy);
  20753. newChannels[i] = newChan;
  20754. newChan += newNumSamples;
  20755. }
  20756. allocatedData.swapWith (newData);
  20757. allocatedBytes = (int) newTotalBytes;
  20758. channels = newChannels;
  20759. }
  20760. else
  20761. {
  20762. if (avoidReallocating && allocatedBytes >= newTotalBytes)
  20763. {
  20764. if (clearExtraSpace)
  20765. zeromem (allocatedData, newTotalBytes);
  20766. }
  20767. else
  20768. {
  20769. allocatedBytes = newTotalBytes;
  20770. allocatedData.allocate (newTotalBytes, clearExtraSpace);
  20771. channels = reinterpret_cast <float**> (allocatedData.getData());
  20772. }
  20773. float* chan = reinterpret_cast <float*> (allocatedData + channelListSize);
  20774. for (int i = 0; i < newNumChannels; ++i)
  20775. {
  20776. channels[i] = chan;
  20777. chan += newNumSamples;
  20778. }
  20779. }
  20780. channels [newNumChannels] = 0;
  20781. size = newNumSamples;
  20782. numChannels = newNumChannels;
  20783. }
  20784. }
  20785. void AudioSampleBuffer::clear() throw()
  20786. {
  20787. for (int i = 0; i < numChannels; ++i)
  20788. zeromem (channels[i], size * sizeof (float));
  20789. }
  20790. void AudioSampleBuffer::clear (const int startSample,
  20791. const int numSamples) throw()
  20792. {
  20793. jassert (startSample >= 0 && startSample + numSamples <= size);
  20794. for (int i = 0; i < numChannels; ++i)
  20795. zeromem (channels [i] + startSample, numSamples * sizeof (float));
  20796. }
  20797. void AudioSampleBuffer::clear (const int channel,
  20798. const int startSample,
  20799. const int numSamples) throw()
  20800. {
  20801. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20802. jassert (startSample >= 0 && startSample + numSamples <= size);
  20803. zeromem (channels [channel] + startSample, numSamples * sizeof (float));
  20804. }
  20805. void AudioSampleBuffer::applyGain (const int channel,
  20806. const int startSample,
  20807. int numSamples,
  20808. const float gain) throw()
  20809. {
  20810. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20811. jassert (startSample >= 0 && startSample + numSamples <= size);
  20812. if (gain != 1.0f)
  20813. {
  20814. float* d = channels [channel] + startSample;
  20815. if (gain == 0.0f)
  20816. {
  20817. zeromem (d, sizeof (float) * numSamples);
  20818. }
  20819. else
  20820. {
  20821. while (--numSamples >= 0)
  20822. *d++ *= gain;
  20823. }
  20824. }
  20825. }
  20826. void AudioSampleBuffer::applyGainRamp (const int channel,
  20827. const int startSample,
  20828. int numSamples,
  20829. float startGain,
  20830. float endGain) throw()
  20831. {
  20832. if (startGain == endGain)
  20833. {
  20834. applyGain (channel, startSample, numSamples, startGain);
  20835. }
  20836. else
  20837. {
  20838. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20839. jassert (startSample >= 0 && startSample + numSamples <= size);
  20840. const float increment = (endGain - startGain) / numSamples;
  20841. float* d = channels [channel] + startSample;
  20842. while (--numSamples >= 0)
  20843. {
  20844. *d++ *= startGain;
  20845. startGain += increment;
  20846. }
  20847. }
  20848. }
  20849. void AudioSampleBuffer::applyGain (const int startSample,
  20850. const int numSamples,
  20851. const float gain) throw()
  20852. {
  20853. for (int i = 0; i < numChannels; ++i)
  20854. applyGain (i, startSample, numSamples, gain);
  20855. }
  20856. void AudioSampleBuffer::addFrom (const int destChannel,
  20857. const int destStartSample,
  20858. const AudioSampleBuffer& source,
  20859. const int sourceChannel,
  20860. const int sourceStartSample,
  20861. int numSamples,
  20862. const float gain) throw()
  20863. {
  20864. jassert (&source != this || sourceChannel != destChannel);
  20865. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20866. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20867. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  20868. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  20869. if (gain != 0.0f && numSamples > 0)
  20870. {
  20871. float* d = channels [destChannel] + destStartSample;
  20872. const float* s = source.channels [sourceChannel] + sourceStartSample;
  20873. if (gain != 1.0f)
  20874. {
  20875. while (--numSamples >= 0)
  20876. *d++ += gain * *s++;
  20877. }
  20878. else
  20879. {
  20880. while (--numSamples >= 0)
  20881. *d++ += *s++;
  20882. }
  20883. }
  20884. }
  20885. void AudioSampleBuffer::addFrom (const int destChannel,
  20886. const int destStartSample,
  20887. const float* source,
  20888. int numSamples,
  20889. const float gain) throw()
  20890. {
  20891. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20892. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20893. jassert (source != 0);
  20894. if (gain != 0.0f && numSamples > 0)
  20895. {
  20896. float* d = channels [destChannel] + destStartSample;
  20897. if (gain != 1.0f)
  20898. {
  20899. while (--numSamples >= 0)
  20900. *d++ += gain * *source++;
  20901. }
  20902. else
  20903. {
  20904. while (--numSamples >= 0)
  20905. *d++ += *source++;
  20906. }
  20907. }
  20908. }
  20909. void AudioSampleBuffer::addFromWithRamp (const int destChannel,
  20910. const int destStartSample,
  20911. const float* source,
  20912. int numSamples,
  20913. float startGain,
  20914. const float endGain) throw()
  20915. {
  20916. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20917. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20918. jassert (source != 0);
  20919. if (startGain == endGain)
  20920. {
  20921. addFrom (destChannel,
  20922. destStartSample,
  20923. source,
  20924. numSamples,
  20925. startGain);
  20926. }
  20927. else
  20928. {
  20929. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  20930. {
  20931. const float increment = (endGain - startGain) / numSamples;
  20932. float* d = channels [destChannel] + destStartSample;
  20933. while (--numSamples >= 0)
  20934. {
  20935. *d++ += startGain * *source++;
  20936. startGain += increment;
  20937. }
  20938. }
  20939. }
  20940. }
  20941. void AudioSampleBuffer::copyFrom (const int destChannel,
  20942. const int destStartSample,
  20943. const AudioSampleBuffer& source,
  20944. const int sourceChannel,
  20945. const int sourceStartSample,
  20946. int numSamples) throw()
  20947. {
  20948. jassert (&source != this || sourceChannel != destChannel);
  20949. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20950. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20951. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  20952. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  20953. if (numSamples > 0)
  20954. {
  20955. memcpy (channels [destChannel] + destStartSample,
  20956. source.channels [sourceChannel] + sourceStartSample,
  20957. sizeof (float) * numSamples);
  20958. }
  20959. }
  20960. void AudioSampleBuffer::copyFrom (const int destChannel,
  20961. const int destStartSample,
  20962. const float* source,
  20963. int numSamples) throw()
  20964. {
  20965. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20966. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20967. jassert (source != 0);
  20968. if (numSamples > 0)
  20969. {
  20970. memcpy (channels [destChannel] + destStartSample,
  20971. source,
  20972. sizeof (float) * numSamples);
  20973. }
  20974. }
  20975. void AudioSampleBuffer::copyFrom (const int destChannel,
  20976. const int destStartSample,
  20977. const float* source,
  20978. int numSamples,
  20979. const float gain) throw()
  20980. {
  20981. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20982. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20983. jassert (source != 0);
  20984. if (numSamples > 0)
  20985. {
  20986. float* d = channels [destChannel] + destStartSample;
  20987. if (gain != 1.0f)
  20988. {
  20989. if (gain == 0)
  20990. {
  20991. zeromem (d, sizeof (float) * numSamples);
  20992. }
  20993. else
  20994. {
  20995. while (--numSamples >= 0)
  20996. *d++ = gain * *source++;
  20997. }
  20998. }
  20999. else
  21000. {
  21001. memcpy (d, source, sizeof (float) * numSamples);
  21002. }
  21003. }
  21004. }
  21005. void AudioSampleBuffer::copyFromWithRamp (const int destChannel,
  21006. const int destStartSample,
  21007. const float* source,
  21008. int numSamples,
  21009. float startGain,
  21010. float endGain) throw()
  21011. {
  21012. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21013. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21014. jassert (source != 0);
  21015. if (startGain == endGain)
  21016. {
  21017. copyFrom (destChannel,
  21018. destStartSample,
  21019. source,
  21020. numSamples,
  21021. startGain);
  21022. }
  21023. else
  21024. {
  21025. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  21026. {
  21027. const float increment = (endGain - startGain) / numSamples;
  21028. float* d = channels [destChannel] + destStartSample;
  21029. while (--numSamples >= 0)
  21030. {
  21031. *d++ = startGain * *source++;
  21032. startGain += increment;
  21033. }
  21034. }
  21035. }
  21036. }
  21037. void AudioSampleBuffer::findMinMax (const int channel,
  21038. const int startSample,
  21039. int numSamples,
  21040. float& minVal,
  21041. float& maxVal) const throw()
  21042. {
  21043. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21044. jassert (startSample >= 0 && startSample + numSamples <= size);
  21045. if (numSamples <= 0)
  21046. {
  21047. minVal = 0.0f;
  21048. maxVal = 0.0f;
  21049. }
  21050. else
  21051. {
  21052. const float* d = channels [channel] + startSample;
  21053. float mn = *d++;
  21054. float mx = mn;
  21055. while (--numSamples > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  21056. {
  21057. const float samp = *d++;
  21058. if (samp > mx)
  21059. mx = samp;
  21060. if (samp < mn)
  21061. mn = samp;
  21062. }
  21063. maxVal = mx;
  21064. minVal = mn;
  21065. }
  21066. }
  21067. float AudioSampleBuffer::getMagnitude (const int channel,
  21068. const int startSample,
  21069. const int numSamples) const throw()
  21070. {
  21071. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21072. jassert (startSample >= 0 && startSample + numSamples <= size);
  21073. float mn, mx;
  21074. findMinMax (channel, startSample, numSamples, mn, mx);
  21075. return jmax (mn, -mn, mx, -mx);
  21076. }
  21077. float AudioSampleBuffer::getMagnitude (const int startSample,
  21078. const int numSamples) const throw()
  21079. {
  21080. float mag = 0.0f;
  21081. for (int i = 0; i < numChannels; ++i)
  21082. mag = jmax (mag, getMagnitude (i, startSample, numSamples));
  21083. return mag;
  21084. }
  21085. float AudioSampleBuffer::getRMSLevel (const int channel,
  21086. const int startSample,
  21087. const int numSamples) const throw()
  21088. {
  21089. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21090. jassert (startSample >= 0 && startSample + numSamples <= size);
  21091. if (numSamples <= 0 || channel < 0 || channel >= numChannels)
  21092. return 0.0f;
  21093. const float* const data = channels [channel] + startSample;
  21094. double sum = 0.0;
  21095. for (int i = 0; i < numSamples; ++i)
  21096. {
  21097. const float sample = data [i];
  21098. sum += sample * sample;
  21099. }
  21100. return (float) std::sqrt (sum / numSamples);
  21101. }
  21102. void AudioSampleBuffer::readFromAudioReader (AudioFormatReader* reader,
  21103. const int startSample,
  21104. const int numSamples,
  21105. const int readerStartSample,
  21106. const bool useLeftChan,
  21107. const bool useRightChan) throw()
  21108. {
  21109. jassert (reader != 0);
  21110. jassert (startSample >= 0 && startSample + numSamples <= size);
  21111. if (numSamples > 0)
  21112. {
  21113. int* chans[3];
  21114. if (useLeftChan == useRightChan)
  21115. {
  21116. chans[0] = (int*) getSampleData (0, startSample);
  21117. chans[1] = (reader->numChannels > 1 && getNumChannels() > 1) ? (int*) getSampleData (1, startSample) : 0;
  21118. }
  21119. else if (useLeftChan || (reader->numChannels == 1))
  21120. {
  21121. chans[0] = (int*) getSampleData (0, startSample);
  21122. chans[1] = 0;
  21123. }
  21124. else if (useRightChan)
  21125. {
  21126. chans[0] = 0;
  21127. chans[1] = (int*) getSampleData (0, startSample);
  21128. }
  21129. chans[2] = 0;
  21130. reader->read (chans, 2, readerStartSample, numSamples, true);
  21131. if (! reader->usesFloatingPointData)
  21132. {
  21133. for (int j = 0; j < 2; ++j)
  21134. {
  21135. float* const d = reinterpret_cast <float*> (chans[j]);
  21136. if (d != 0)
  21137. {
  21138. const float multiplier = 1.0f / 0x7fffffff;
  21139. for (int i = 0; i < numSamples; ++i)
  21140. d[i] = *(int*)(d + i) * multiplier;
  21141. }
  21142. }
  21143. }
  21144. if (numChannels > 1 && (chans[0] == 0 || chans[1] == 0))
  21145. {
  21146. // if this is a stereo buffer and the source was mono, dupe the first channel..
  21147. memcpy (getSampleData (1, startSample),
  21148. getSampleData (0, startSample),
  21149. sizeof (float) * numSamples);
  21150. }
  21151. }
  21152. }
  21153. void AudioSampleBuffer::writeToAudioWriter (AudioFormatWriter* writer,
  21154. const int startSample,
  21155. const int numSamples) const throw()
  21156. {
  21157. jassert (startSample >= 0 && startSample + numSamples <= size);
  21158. if (numSamples > 0)
  21159. {
  21160. int* chans [3];
  21161. if (writer->isFloatingPoint())
  21162. {
  21163. chans[0] = (int*) getSampleData (0, startSample);
  21164. if (numChannels > 1)
  21165. chans[1] = (int*) getSampleData (1, startSample);
  21166. else
  21167. chans[1] = 0;
  21168. chans[2] = 0;
  21169. writer->write ((const int**) chans, numSamples);
  21170. }
  21171. else
  21172. {
  21173. HeapBlock <int> tempBuffer (numSamples * 2);
  21174. chans[0] = tempBuffer;
  21175. if (numChannels > 1)
  21176. chans[1] = chans[0] + numSamples;
  21177. else
  21178. chans[1] = 0;
  21179. chans[2] = 0;
  21180. for (int j = 0; j < 2; ++j)
  21181. {
  21182. int* const dest = chans[j];
  21183. if (dest != 0)
  21184. {
  21185. const float* const src = channels [j] + startSample;
  21186. for (int i = 0; i < numSamples; ++i)
  21187. {
  21188. const double samp = src[i];
  21189. if (samp <= -1.0)
  21190. dest[i] = std::numeric_limits<int>::min();
  21191. else if (samp >= 1.0)
  21192. dest[i] = std::numeric_limits<int>::max();
  21193. else
  21194. dest[i] = roundToInt (std::numeric_limits<int>::max() * samp);
  21195. }
  21196. }
  21197. }
  21198. writer->write ((const int**) chans, numSamples);
  21199. }
  21200. }
  21201. }
  21202. END_JUCE_NAMESPACE
  21203. /*** End of inlined file: juce_AudioSampleBuffer.cpp ***/
  21204. /*** Start of inlined file: juce_IIRFilter.cpp ***/
  21205. BEGIN_JUCE_NAMESPACE
  21206. IIRFilter::IIRFilter()
  21207. : active (false)
  21208. {
  21209. reset();
  21210. }
  21211. IIRFilter::IIRFilter (const IIRFilter& other)
  21212. : active (other.active)
  21213. {
  21214. const ScopedLock sl (other.processLock);
  21215. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  21216. reset();
  21217. }
  21218. IIRFilter::~IIRFilter()
  21219. {
  21220. }
  21221. void IIRFilter::reset() throw()
  21222. {
  21223. const ScopedLock sl (processLock);
  21224. x1 = 0;
  21225. x2 = 0;
  21226. y1 = 0;
  21227. y2 = 0;
  21228. }
  21229. float IIRFilter::processSingleSampleRaw (const float in) throw()
  21230. {
  21231. float out = coefficients[0] * in
  21232. + coefficients[1] * x1
  21233. + coefficients[2] * x2
  21234. - coefficients[4] * y1
  21235. - coefficients[5] * y2;
  21236. #if JUCE_INTEL
  21237. if (! (out < -1.0e-8 || out > 1.0e-8))
  21238. out = 0;
  21239. #endif
  21240. x2 = x1;
  21241. x1 = in;
  21242. y2 = y1;
  21243. y1 = out;
  21244. return out;
  21245. }
  21246. void IIRFilter::processSamples (float* const samples,
  21247. const int numSamples) throw()
  21248. {
  21249. const ScopedLock sl (processLock);
  21250. if (active)
  21251. {
  21252. for (int i = 0; i < numSamples; ++i)
  21253. {
  21254. const float in = samples[i];
  21255. float out = coefficients[0] * in
  21256. + coefficients[1] * x1
  21257. + coefficients[2] * x2
  21258. - coefficients[4] * y1
  21259. - coefficients[5] * y2;
  21260. #if JUCE_INTEL
  21261. if (! (out < -1.0e-8 || out > 1.0e-8))
  21262. out = 0;
  21263. #endif
  21264. x2 = x1;
  21265. x1 = in;
  21266. y2 = y1;
  21267. y1 = out;
  21268. samples[i] = out;
  21269. }
  21270. }
  21271. }
  21272. void IIRFilter::makeLowPass (const double sampleRate,
  21273. const double frequency) throw()
  21274. {
  21275. jassert (sampleRate > 0);
  21276. const double n = 1.0 / tan (double_Pi * frequency / sampleRate);
  21277. const double nSquared = n * n;
  21278. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  21279. setCoefficients (c1,
  21280. c1 * 2.0f,
  21281. c1,
  21282. 1.0,
  21283. c1 * 2.0 * (1.0 - nSquared),
  21284. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  21285. }
  21286. void IIRFilter::makeHighPass (const double sampleRate,
  21287. const double frequency) throw()
  21288. {
  21289. const double n = tan (double_Pi * frequency / sampleRate);
  21290. const double nSquared = n * n;
  21291. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  21292. setCoefficients (c1,
  21293. c1 * -2.0f,
  21294. c1,
  21295. 1.0,
  21296. c1 * 2.0 * (nSquared - 1.0),
  21297. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  21298. }
  21299. void IIRFilter::makeLowShelf (const double sampleRate,
  21300. const double cutOffFrequency,
  21301. const double Q,
  21302. const float gainFactor) throw()
  21303. {
  21304. jassert (sampleRate > 0);
  21305. jassert (Q > 0);
  21306. const double A = jmax (0.0f, gainFactor);
  21307. const double aminus1 = A - 1.0;
  21308. const double aplus1 = A + 1.0;
  21309. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  21310. const double coso = std::cos (omega);
  21311. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  21312. const double aminus1TimesCoso = aminus1 * coso;
  21313. setCoefficients (A * (aplus1 - aminus1TimesCoso + beta),
  21314. A * 2.0 * (aminus1 - aplus1 * coso),
  21315. A * (aplus1 - aminus1TimesCoso - beta),
  21316. aplus1 + aminus1TimesCoso + beta,
  21317. -2.0 * (aminus1 + aplus1 * coso),
  21318. aplus1 + aminus1TimesCoso - beta);
  21319. }
  21320. void IIRFilter::makeHighShelf (const double sampleRate,
  21321. const double cutOffFrequency,
  21322. const double Q,
  21323. const float gainFactor) throw()
  21324. {
  21325. jassert (sampleRate > 0);
  21326. jassert (Q > 0);
  21327. const double A = jmax (0.0f, gainFactor);
  21328. const double aminus1 = A - 1.0;
  21329. const double aplus1 = A + 1.0;
  21330. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  21331. const double coso = std::cos (omega);
  21332. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  21333. const double aminus1TimesCoso = aminus1 * coso;
  21334. setCoefficients (A * (aplus1 + aminus1TimesCoso + beta),
  21335. A * -2.0 * (aminus1 + aplus1 * coso),
  21336. A * (aplus1 + aminus1TimesCoso - beta),
  21337. aplus1 - aminus1TimesCoso + beta,
  21338. 2.0 * (aminus1 - aplus1 * coso),
  21339. aplus1 - aminus1TimesCoso - beta);
  21340. }
  21341. void IIRFilter::makeBandPass (const double sampleRate,
  21342. const double centreFrequency,
  21343. const double Q,
  21344. const float gainFactor) throw()
  21345. {
  21346. jassert (sampleRate > 0);
  21347. jassert (Q > 0);
  21348. const double A = jmax (0.0f, gainFactor);
  21349. const double omega = (double_Pi * 2.0 * jmax (centreFrequency, 2.0)) / sampleRate;
  21350. const double alpha = 0.5 * std::sin (omega) / Q;
  21351. const double c2 = -2.0 * std::cos (omega);
  21352. const double alphaTimesA = alpha * A;
  21353. const double alphaOverA = alpha / A;
  21354. setCoefficients (1.0 + alphaTimesA,
  21355. c2,
  21356. 1.0 - alphaTimesA,
  21357. 1.0 + alphaOverA,
  21358. c2,
  21359. 1.0 - alphaOverA);
  21360. }
  21361. void IIRFilter::makeInactive() throw()
  21362. {
  21363. const ScopedLock sl (processLock);
  21364. active = false;
  21365. }
  21366. void IIRFilter::copyCoefficientsFrom (const IIRFilter& other) throw()
  21367. {
  21368. const ScopedLock sl (processLock);
  21369. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  21370. active = other.active;
  21371. }
  21372. void IIRFilter::setCoefficients (double c1,
  21373. double c2,
  21374. double c3,
  21375. double c4,
  21376. double c5,
  21377. double c6) throw()
  21378. {
  21379. const double a = 1.0 / c4;
  21380. c1 *= a;
  21381. c2 *= a;
  21382. c3 *= a;
  21383. c5 *= a;
  21384. c6 *= a;
  21385. const ScopedLock sl (processLock);
  21386. coefficients[0] = (float) c1;
  21387. coefficients[1] = (float) c2;
  21388. coefficients[2] = (float) c3;
  21389. coefficients[3] = (float) c4;
  21390. coefficients[4] = (float) c5;
  21391. coefficients[5] = (float) c6;
  21392. active = true;
  21393. }
  21394. END_JUCE_NAMESPACE
  21395. /*** End of inlined file: juce_IIRFilter.cpp ***/
  21396. /*** Start of inlined file: juce_MidiBuffer.cpp ***/
  21397. BEGIN_JUCE_NAMESPACE
  21398. MidiBuffer::MidiBuffer() throw()
  21399. : bytesUsed (0)
  21400. {
  21401. }
  21402. MidiBuffer::MidiBuffer (const MidiMessage& message) throw()
  21403. : bytesUsed (0)
  21404. {
  21405. addEvent (message, 0);
  21406. }
  21407. MidiBuffer::MidiBuffer (const MidiBuffer& other) throw()
  21408. : data (other.data),
  21409. bytesUsed (other.bytesUsed)
  21410. {
  21411. }
  21412. MidiBuffer& MidiBuffer::operator= (const MidiBuffer& other) throw()
  21413. {
  21414. bytesUsed = other.bytesUsed;
  21415. data = other.data;
  21416. return *this;
  21417. }
  21418. void MidiBuffer::swapWith (MidiBuffer& other)
  21419. {
  21420. data.swapWith (other.data);
  21421. swapVariables <int> (bytesUsed, other.bytesUsed);
  21422. }
  21423. MidiBuffer::~MidiBuffer() throw()
  21424. {
  21425. }
  21426. inline uint8* MidiBuffer::getData() const throw()
  21427. {
  21428. return static_cast <uint8*> (data.getData());
  21429. }
  21430. inline int MidiBuffer::getEventTime (const void* const d) throw()
  21431. {
  21432. return *static_cast <const int*> (d);
  21433. }
  21434. inline uint16 MidiBuffer::getEventDataSize (const void* const d) throw()
  21435. {
  21436. return *reinterpret_cast <const uint16*> (static_cast <const char*> (d) + sizeof (int));
  21437. }
  21438. inline uint16 MidiBuffer::getEventTotalSize (const void* const d) throw()
  21439. {
  21440. return getEventDataSize (d) + sizeof (int) + sizeof (uint16);
  21441. }
  21442. void MidiBuffer::clear() throw()
  21443. {
  21444. bytesUsed = 0;
  21445. }
  21446. void MidiBuffer::clear (const int startSample,
  21447. const int numSamples) throw()
  21448. {
  21449. uint8* const start = findEventAfter (getData(), startSample - 1);
  21450. uint8* const end = findEventAfter (start, startSample + numSamples - 1);
  21451. if (end > start)
  21452. {
  21453. const int bytesToMove = bytesUsed - (int) (end - getData());
  21454. if (bytesToMove > 0)
  21455. memmove (start, end, bytesToMove);
  21456. bytesUsed -= (int) (end - start);
  21457. }
  21458. }
  21459. void MidiBuffer::addEvent (const MidiMessage& m,
  21460. const int sampleNumber) throw()
  21461. {
  21462. addEvent (m.getRawData(), m.getRawDataSize(), sampleNumber);
  21463. }
  21464. static int findActualEventLength (const uint8* const data,
  21465. const int maxBytes) throw()
  21466. {
  21467. unsigned int byte = (unsigned int) *data;
  21468. int size = 0;
  21469. if (byte == 0xf0 || byte == 0xf7)
  21470. {
  21471. const uint8* d = data + 1;
  21472. while (d < data + maxBytes)
  21473. if (*d++ == 0xf7)
  21474. break;
  21475. size = (int) (d - data);
  21476. }
  21477. else if (byte == 0xff)
  21478. {
  21479. int n;
  21480. const int bytesLeft = MidiMessage::readVariableLengthVal (data + 1, n);
  21481. size = jmin (maxBytes, n + 2 + bytesLeft);
  21482. }
  21483. else if (byte >= 0x80)
  21484. {
  21485. size = jmin (maxBytes, MidiMessage::getMessageLengthFromFirstByte ((uint8) byte));
  21486. }
  21487. return size;
  21488. }
  21489. void MidiBuffer::addEvent (const uint8* const newData,
  21490. const int maxBytes,
  21491. const int sampleNumber) throw()
  21492. {
  21493. const int numBytes = findActualEventLength (newData, maxBytes);
  21494. if (numBytes > 0)
  21495. {
  21496. int spaceNeeded = bytesUsed + numBytes + sizeof (int) + sizeof (uint16);
  21497. data.ensureSize ((spaceNeeded + spaceNeeded / 2 + 8) & ~7);
  21498. uint8* d = findEventAfter (getData(), sampleNumber);
  21499. const int bytesToMove = bytesUsed - (int) (d - getData());
  21500. if (bytesToMove > 0)
  21501. memmove (d + numBytes + sizeof (int) + sizeof (uint16), d, bytesToMove);
  21502. *reinterpret_cast <int*> (d) = sampleNumber;
  21503. d += sizeof (int);
  21504. *reinterpret_cast <uint16*> (d) = (uint16) numBytes;
  21505. d += sizeof (uint16);
  21506. memcpy (d, newData, numBytes);
  21507. bytesUsed += numBytes + sizeof (int) + sizeof (uint16);
  21508. }
  21509. }
  21510. void MidiBuffer::addEvents (const MidiBuffer& otherBuffer,
  21511. const int startSample,
  21512. const int numSamples,
  21513. const int sampleDeltaToAdd) throw()
  21514. {
  21515. Iterator i (otherBuffer);
  21516. i.setNextSamplePosition (startSample);
  21517. const uint8* eventData;
  21518. int eventSize, position;
  21519. while (i.getNextEvent (eventData, eventSize, position)
  21520. && (position < startSample + numSamples || numSamples < 0))
  21521. {
  21522. addEvent (eventData, eventSize, position + sampleDeltaToAdd);
  21523. }
  21524. }
  21525. void MidiBuffer::ensureSize (size_t minimumNumBytes)
  21526. {
  21527. data.ensureSize (minimumNumBytes);
  21528. }
  21529. bool MidiBuffer::isEmpty() const throw()
  21530. {
  21531. return bytesUsed == 0;
  21532. }
  21533. int MidiBuffer::getNumEvents() const throw()
  21534. {
  21535. int n = 0;
  21536. const uint8* d = getData();
  21537. const uint8* const end = d + bytesUsed;
  21538. while (d < end)
  21539. {
  21540. d += getEventTotalSize (d);
  21541. ++n;
  21542. }
  21543. return n;
  21544. }
  21545. int MidiBuffer::getFirstEventTime() const throw()
  21546. {
  21547. return bytesUsed > 0 ? getEventTime (data.getData()) : 0;
  21548. }
  21549. int MidiBuffer::getLastEventTime() const throw()
  21550. {
  21551. if (bytesUsed == 0)
  21552. return 0;
  21553. const uint8* d = getData();
  21554. const uint8* const endData = d + bytesUsed;
  21555. for (;;)
  21556. {
  21557. const uint8* const nextOne = d + getEventTotalSize (d);
  21558. if (nextOne >= endData)
  21559. return getEventTime (d);
  21560. d = nextOne;
  21561. }
  21562. }
  21563. uint8* MidiBuffer::findEventAfter (uint8* d, const int samplePosition) const throw()
  21564. {
  21565. const uint8* const endData = getData() + bytesUsed;
  21566. while (d < endData && getEventTime (d) <= samplePosition)
  21567. d += getEventTotalSize (d);
  21568. return d;
  21569. }
  21570. MidiBuffer::Iterator::Iterator (const MidiBuffer& buffer_) throw()
  21571. : buffer (buffer_),
  21572. data (buffer_.getData())
  21573. {
  21574. }
  21575. MidiBuffer::Iterator::~Iterator() throw()
  21576. {
  21577. }
  21578. void MidiBuffer::Iterator::setNextSamplePosition (const int samplePosition) throw()
  21579. {
  21580. data = buffer.getData();
  21581. const uint8* dataEnd = data + buffer.bytesUsed;
  21582. while (data < dataEnd && getEventTime (data) < samplePosition)
  21583. data += getEventTotalSize (data);
  21584. }
  21585. bool MidiBuffer::Iterator::getNextEvent (const uint8* &midiData, int& numBytes, int& samplePosition) throw()
  21586. {
  21587. if (data >= buffer.getData() + buffer.bytesUsed)
  21588. return false;
  21589. samplePosition = getEventTime (data);
  21590. numBytes = getEventDataSize (data);
  21591. data += sizeof (int) + sizeof (uint16);
  21592. midiData = data;
  21593. data += numBytes;
  21594. return true;
  21595. }
  21596. bool MidiBuffer::Iterator::getNextEvent (MidiMessage& result, int& samplePosition) throw()
  21597. {
  21598. if (data >= buffer.getData() + buffer.bytesUsed)
  21599. return false;
  21600. samplePosition = getEventTime (data);
  21601. const int numBytes = getEventDataSize (data);
  21602. data += sizeof (int) + sizeof (uint16);
  21603. result = MidiMessage (data, numBytes, samplePosition);
  21604. data += numBytes;
  21605. return true;
  21606. }
  21607. END_JUCE_NAMESPACE
  21608. /*** End of inlined file: juce_MidiBuffer.cpp ***/
  21609. /*** Start of inlined file: juce_MidiFile.cpp ***/
  21610. BEGIN_JUCE_NAMESPACE
  21611. namespace MidiFileHelpers
  21612. {
  21613. static void writeVariableLengthInt (OutputStream& out, unsigned int v)
  21614. {
  21615. unsigned int buffer = v & 0x7F;
  21616. while ((v >>= 7) != 0)
  21617. {
  21618. buffer <<= 8;
  21619. buffer |= ((v & 0x7F) | 0x80);
  21620. }
  21621. for (;;)
  21622. {
  21623. out.writeByte ((char) buffer);
  21624. if (buffer & 0x80)
  21625. buffer >>= 8;
  21626. else
  21627. break;
  21628. }
  21629. }
  21630. static bool parseMidiHeader (const uint8* &data, short& timeFormat, short& fileType, short& numberOfTracks) throw()
  21631. {
  21632. unsigned int ch = (int) ByteOrder::bigEndianInt (data);
  21633. data += 4;
  21634. if (ch != ByteOrder::bigEndianInt ("MThd"))
  21635. {
  21636. bool ok = false;
  21637. if (ch == ByteOrder::bigEndianInt ("RIFF"))
  21638. {
  21639. for (int i = 0; i < 8; ++i)
  21640. {
  21641. ch = ByteOrder::bigEndianInt (data);
  21642. data += 4;
  21643. if (ch == ByteOrder::bigEndianInt ("MThd"))
  21644. {
  21645. ok = true;
  21646. break;
  21647. }
  21648. }
  21649. }
  21650. if (! ok)
  21651. return false;
  21652. }
  21653. unsigned int bytesRemaining = ByteOrder::bigEndianInt (data);
  21654. data += 4;
  21655. fileType = (short) ByteOrder::bigEndianShort (data);
  21656. data += 2;
  21657. numberOfTracks = (short) ByteOrder::bigEndianShort (data);
  21658. data += 2;
  21659. timeFormat = (short) ByteOrder::bigEndianShort (data);
  21660. data += 2;
  21661. bytesRemaining -= 6;
  21662. data += bytesRemaining;
  21663. return true;
  21664. }
  21665. static double convertTicksToSeconds (const double time,
  21666. const MidiMessageSequence& tempoEvents,
  21667. const int timeFormat)
  21668. {
  21669. if (timeFormat > 0)
  21670. {
  21671. int numer = 4, denom = 4;
  21672. double tempoTime = 0.0, correctedTempoTime = 0.0;
  21673. const double tickLen = 1.0 / (timeFormat & 0x7fff);
  21674. double secsPerTick = 0.5 * tickLen;
  21675. const int numEvents = tempoEvents.getNumEvents();
  21676. for (int i = 0; i < numEvents; ++i)
  21677. {
  21678. const MidiMessage& m = tempoEvents.getEventPointer(i)->message;
  21679. if (time <= m.getTimeStamp())
  21680. break;
  21681. if (timeFormat > 0)
  21682. {
  21683. correctedTempoTime = correctedTempoTime
  21684. + (m.getTimeStamp() - tempoTime) * secsPerTick;
  21685. }
  21686. else
  21687. {
  21688. correctedTempoTime = tickLen * m.getTimeStamp() / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  21689. }
  21690. tempoTime = m.getTimeStamp();
  21691. if (m.isTempoMetaEvent())
  21692. secsPerTick = tickLen * m.getTempoSecondsPerQuarterNote();
  21693. else if (m.isTimeSignatureMetaEvent())
  21694. m.getTimeSignatureInfo (numer, denom);
  21695. while (i + 1 < numEvents)
  21696. {
  21697. const MidiMessage& m2 = tempoEvents.getEventPointer(i + 1)->message;
  21698. if (m2.getTimeStamp() == tempoTime)
  21699. {
  21700. ++i;
  21701. if (m2.isTempoMetaEvent())
  21702. secsPerTick = tickLen * m2.getTempoSecondsPerQuarterNote();
  21703. else if (m2.isTimeSignatureMetaEvent())
  21704. m2.getTimeSignatureInfo (numer, denom);
  21705. }
  21706. else
  21707. {
  21708. break;
  21709. }
  21710. }
  21711. }
  21712. return correctedTempoTime + (time - tempoTime) * secsPerTick;
  21713. }
  21714. else
  21715. {
  21716. return time / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  21717. }
  21718. }
  21719. }
  21720. MidiFile::MidiFile()
  21721. : timeFormat ((short) (unsigned short) 0xe728)
  21722. {
  21723. }
  21724. MidiFile::~MidiFile()
  21725. {
  21726. clear();
  21727. }
  21728. void MidiFile::clear()
  21729. {
  21730. tracks.clear();
  21731. }
  21732. int MidiFile::getNumTracks() const throw()
  21733. {
  21734. return tracks.size();
  21735. }
  21736. const MidiMessageSequence* MidiFile::getTrack (const int index) const throw()
  21737. {
  21738. return tracks [index];
  21739. }
  21740. void MidiFile::addTrack (const MidiMessageSequence& trackSequence)
  21741. {
  21742. tracks.add (new MidiMessageSequence (trackSequence));
  21743. }
  21744. short MidiFile::getTimeFormat() const throw()
  21745. {
  21746. return timeFormat;
  21747. }
  21748. void MidiFile::setTicksPerQuarterNote (const int ticks) throw()
  21749. {
  21750. timeFormat = (short) ticks;
  21751. }
  21752. void MidiFile::setSmpteTimeFormat (const int framesPerSecond,
  21753. const int subframeResolution) throw()
  21754. {
  21755. timeFormat = (short) (((-framesPerSecond) << 8) | subframeResolution);
  21756. }
  21757. void MidiFile::findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const
  21758. {
  21759. for (int i = tracks.size(); --i >= 0;)
  21760. {
  21761. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  21762. for (int j = 0; j < numEvents; ++j)
  21763. {
  21764. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  21765. if (m.isTempoMetaEvent())
  21766. tempoChangeEvents.addEvent (m);
  21767. }
  21768. }
  21769. }
  21770. void MidiFile::findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const
  21771. {
  21772. for (int i = tracks.size(); --i >= 0;)
  21773. {
  21774. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  21775. for (int j = 0; j < numEvents; ++j)
  21776. {
  21777. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  21778. if (m.isTimeSignatureMetaEvent())
  21779. timeSigEvents.addEvent (m);
  21780. }
  21781. }
  21782. }
  21783. double MidiFile::getLastTimestamp() const
  21784. {
  21785. double t = 0.0;
  21786. for (int i = tracks.size(); --i >= 0;)
  21787. t = jmax (t, tracks.getUnchecked(i)->getEndTime());
  21788. return t;
  21789. }
  21790. bool MidiFile::readFrom (InputStream& sourceStream)
  21791. {
  21792. clear();
  21793. MemoryBlock data;
  21794. const int maxSensibleMidiFileSize = 2 * 1024 * 1024;
  21795. // (put a sanity-check on the file size, as midi files are generally small)
  21796. if (sourceStream.readIntoMemoryBlock (data, maxSensibleMidiFileSize))
  21797. {
  21798. size_t size = data.getSize();
  21799. const uint8* d = static_cast <const uint8*> (data.getData());
  21800. short fileType, expectedTracks;
  21801. if (size > 16 && MidiFileHelpers::parseMidiHeader (d, timeFormat, fileType, expectedTracks))
  21802. {
  21803. size -= (int) (d - static_cast <const uint8*> (data.getData()));
  21804. int track = 0;
  21805. while (size > 0 && track < expectedTracks)
  21806. {
  21807. const int chunkType = (int) ByteOrder::bigEndianInt (d);
  21808. d += 4;
  21809. const int chunkSize = (int) ByteOrder::bigEndianInt (d);
  21810. d += 4;
  21811. if (chunkSize <= 0)
  21812. break;
  21813. if (size < 0)
  21814. return false;
  21815. if (chunkType == (int) ByteOrder::bigEndianInt ("MTrk"))
  21816. {
  21817. readNextTrack (d, chunkSize);
  21818. }
  21819. size -= chunkSize + 8;
  21820. d += chunkSize;
  21821. ++track;
  21822. }
  21823. return true;
  21824. }
  21825. }
  21826. return false;
  21827. }
  21828. // a comparator that puts all the note-offs before note-ons that have the same time
  21829. int MidiFile::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  21830. const MidiMessageSequence::MidiEventHolder* const second)
  21831. {
  21832. const double diff = (first->message.getTimeStamp() - second->message.getTimeStamp());
  21833. if (diff == 0)
  21834. {
  21835. if (first->message.isNoteOff() && second->message.isNoteOn())
  21836. return -1;
  21837. else if (first->message.isNoteOn() && second->message.isNoteOff())
  21838. return 1;
  21839. else
  21840. return 0;
  21841. }
  21842. else
  21843. {
  21844. return (diff > 0) ? 1 : -1;
  21845. }
  21846. }
  21847. void MidiFile::readNextTrack (const uint8* data, int size)
  21848. {
  21849. double time = 0;
  21850. char lastStatusByte = 0;
  21851. MidiMessageSequence result;
  21852. while (size > 0)
  21853. {
  21854. int bytesUsed;
  21855. const int delay = MidiMessage::readVariableLengthVal (data, bytesUsed);
  21856. data += bytesUsed;
  21857. size -= bytesUsed;
  21858. time += delay;
  21859. int messSize = 0;
  21860. const MidiMessage mm (data, size, messSize, lastStatusByte, time);
  21861. if (messSize <= 0)
  21862. break;
  21863. size -= messSize;
  21864. data += messSize;
  21865. result.addEvent (mm);
  21866. const char firstByte = *(mm.getRawData());
  21867. if ((firstByte & 0xf0) != 0xf0)
  21868. lastStatusByte = firstByte;
  21869. }
  21870. // use a sort that puts all the note-offs before note-ons that have the same time
  21871. result.list.sort (*this, true);
  21872. result.updateMatchedPairs();
  21873. addTrack (result);
  21874. }
  21875. void MidiFile::convertTimestampTicksToSeconds()
  21876. {
  21877. MidiMessageSequence tempoEvents;
  21878. findAllTempoEvents (tempoEvents);
  21879. findAllTimeSigEvents (tempoEvents);
  21880. for (int i = 0; i < tracks.size(); ++i)
  21881. {
  21882. MidiMessageSequence& ms = *tracks.getUnchecked(i);
  21883. for (int j = ms.getNumEvents(); --j >= 0;)
  21884. {
  21885. MidiMessage& m = ms.getEventPointer(j)->message;
  21886. m.setTimeStamp (MidiFileHelpers::convertTicksToSeconds (m.getTimeStamp(),
  21887. tempoEvents,
  21888. timeFormat));
  21889. }
  21890. }
  21891. }
  21892. bool MidiFile::writeTo (OutputStream& out)
  21893. {
  21894. out.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MThd"));
  21895. out.writeIntBigEndian (6);
  21896. out.writeShortBigEndian (1); // type
  21897. out.writeShortBigEndian ((short) tracks.size());
  21898. out.writeShortBigEndian (timeFormat);
  21899. for (int i = 0; i < tracks.size(); ++i)
  21900. writeTrack (out, i);
  21901. out.flush();
  21902. return true;
  21903. }
  21904. void MidiFile::writeTrack (OutputStream& mainOut,
  21905. const int trackNum)
  21906. {
  21907. MemoryOutputStream out;
  21908. const MidiMessageSequence& ms = *tracks[trackNum];
  21909. int lastTick = 0;
  21910. char lastStatusByte = 0;
  21911. for (int i = 0; i < ms.getNumEvents(); ++i)
  21912. {
  21913. const MidiMessage& mm = ms.getEventPointer(i)->message;
  21914. const int tick = roundToInt (mm.getTimeStamp());
  21915. const int delta = jmax (0, tick - lastTick);
  21916. MidiFileHelpers::writeVariableLengthInt (out, delta);
  21917. lastTick = tick;
  21918. const char statusByte = *(mm.getRawData());
  21919. if ((statusByte == lastStatusByte)
  21920. && ((statusByte & 0xf0) != 0xf0)
  21921. && i > 0
  21922. && mm.getRawDataSize() > 1)
  21923. {
  21924. out.write (mm.getRawData() + 1, mm.getRawDataSize() - 1);
  21925. }
  21926. else
  21927. {
  21928. out.write (mm.getRawData(), mm.getRawDataSize());
  21929. }
  21930. lastStatusByte = statusByte;
  21931. }
  21932. out.writeByte (0);
  21933. const MidiMessage m (MidiMessage::endOfTrack());
  21934. out.write (m.getRawData(),
  21935. m.getRawDataSize());
  21936. mainOut.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MTrk"));
  21937. mainOut.writeIntBigEndian ((int) out.getDataSize());
  21938. mainOut.write (out.getData(), (int) out.getDataSize());
  21939. }
  21940. END_JUCE_NAMESPACE
  21941. /*** End of inlined file: juce_MidiFile.cpp ***/
  21942. /*** Start of inlined file: juce_MidiKeyboardState.cpp ***/
  21943. BEGIN_JUCE_NAMESPACE
  21944. MidiKeyboardState::MidiKeyboardState()
  21945. {
  21946. zerostruct (noteStates);
  21947. }
  21948. MidiKeyboardState::~MidiKeyboardState()
  21949. {
  21950. }
  21951. void MidiKeyboardState::reset()
  21952. {
  21953. const ScopedLock sl (lock);
  21954. zerostruct (noteStates);
  21955. eventsToAdd.clear();
  21956. }
  21957. bool MidiKeyboardState::isNoteOn (const int midiChannel, const int n) const throw()
  21958. {
  21959. jassert (midiChannel >= 0 && midiChannel <= 16);
  21960. return ((unsigned int) n) < 128
  21961. && (noteStates[n] & (1 << (midiChannel - 1))) != 0;
  21962. }
  21963. bool MidiKeyboardState::isNoteOnForChannels (const int midiChannelMask, const int n) const throw()
  21964. {
  21965. return ((unsigned int) n) < 128
  21966. && (noteStates[n] & midiChannelMask) != 0;
  21967. }
  21968. void MidiKeyboardState::noteOn (const int midiChannel, const int midiNoteNumber, const float velocity)
  21969. {
  21970. jassert (midiChannel >= 0 && midiChannel <= 16);
  21971. jassert (((unsigned int) midiNoteNumber) < 128);
  21972. const ScopedLock sl (lock);
  21973. if (((unsigned int) midiNoteNumber) < 128)
  21974. {
  21975. const int timeNow = (int) Time::getMillisecondCounter();
  21976. eventsToAdd.addEvent (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity), timeNow);
  21977. eventsToAdd.clear (0, timeNow - 500);
  21978. noteOnInternal (midiChannel, midiNoteNumber, velocity);
  21979. }
  21980. }
  21981. void MidiKeyboardState::noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity)
  21982. {
  21983. if (((unsigned int) midiNoteNumber) < 128)
  21984. {
  21985. noteStates [midiNoteNumber] |= (1 << (midiChannel - 1));
  21986. for (int i = listeners.size(); --i >= 0;)
  21987. listeners.getUnchecked(i)->handleNoteOn (this, midiChannel, midiNoteNumber, velocity);
  21988. }
  21989. }
  21990. void MidiKeyboardState::noteOff (const int midiChannel, const int midiNoteNumber)
  21991. {
  21992. const ScopedLock sl (lock);
  21993. if (isNoteOn (midiChannel, midiNoteNumber))
  21994. {
  21995. const int timeNow = (int) Time::getMillisecondCounter();
  21996. eventsToAdd.addEvent (MidiMessage::noteOff (midiChannel, midiNoteNumber), timeNow);
  21997. eventsToAdd.clear (0, timeNow - 500);
  21998. noteOffInternal (midiChannel, midiNoteNumber);
  21999. }
  22000. }
  22001. void MidiKeyboardState::noteOffInternal (const int midiChannel, const int midiNoteNumber)
  22002. {
  22003. if (isNoteOn (midiChannel, midiNoteNumber))
  22004. {
  22005. noteStates [midiNoteNumber] &= ~(1 << (midiChannel - 1));
  22006. for (int i = listeners.size(); --i >= 0;)
  22007. listeners.getUnchecked(i)->handleNoteOff (this, midiChannel, midiNoteNumber);
  22008. }
  22009. }
  22010. void MidiKeyboardState::allNotesOff (const int midiChannel)
  22011. {
  22012. const ScopedLock sl (lock);
  22013. if (midiChannel <= 0)
  22014. {
  22015. for (int i = 1; i <= 16; ++i)
  22016. allNotesOff (i);
  22017. }
  22018. else
  22019. {
  22020. for (int i = 0; i < 128; ++i)
  22021. noteOff (midiChannel, i);
  22022. }
  22023. }
  22024. void MidiKeyboardState::processNextMidiEvent (const MidiMessage& message)
  22025. {
  22026. if (message.isNoteOn())
  22027. {
  22028. noteOnInternal (message.getChannel(), message.getNoteNumber(), message.getFloatVelocity());
  22029. }
  22030. else if (message.isNoteOff())
  22031. {
  22032. noteOffInternal (message.getChannel(), message.getNoteNumber());
  22033. }
  22034. else if (message.isAllNotesOff())
  22035. {
  22036. for (int i = 0; i < 128; ++i)
  22037. noteOffInternal (message.getChannel(), i);
  22038. }
  22039. }
  22040. void MidiKeyboardState::processNextMidiBuffer (MidiBuffer& buffer,
  22041. const int startSample,
  22042. const int numSamples,
  22043. const bool injectIndirectEvents)
  22044. {
  22045. MidiBuffer::Iterator i (buffer);
  22046. MidiMessage message (0xf4, 0.0);
  22047. int time;
  22048. const ScopedLock sl (lock);
  22049. while (i.getNextEvent (message, time))
  22050. processNextMidiEvent (message);
  22051. if (injectIndirectEvents)
  22052. {
  22053. MidiBuffer::Iterator i2 (eventsToAdd);
  22054. const int firstEventToAdd = eventsToAdd.getFirstEventTime();
  22055. const double scaleFactor = numSamples / (double) (eventsToAdd.getLastEventTime() + 1 - firstEventToAdd);
  22056. while (i2.getNextEvent (message, time))
  22057. {
  22058. const int pos = jlimit (0, numSamples - 1, roundToInt ((time - firstEventToAdd) * scaleFactor));
  22059. buffer.addEvent (message, startSample + pos);
  22060. }
  22061. }
  22062. eventsToAdd.clear();
  22063. }
  22064. void MidiKeyboardState::addListener (MidiKeyboardStateListener* const listener) throw()
  22065. {
  22066. const ScopedLock sl (lock);
  22067. listeners.addIfNotAlreadyThere (listener);
  22068. }
  22069. void MidiKeyboardState::removeListener (MidiKeyboardStateListener* const listener) throw()
  22070. {
  22071. const ScopedLock sl (lock);
  22072. listeners.removeValue (listener);
  22073. }
  22074. END_JUCE_NAMESPACE
  22075. /*** End of inlined file: juce_MidiKeyboardState.cpp ***/
  22076. /*** Start of inlined file: juce_MidiMessage.cpp ***/
  22077. BEGIN_JUCE_NAMESPACE
  22078. int MidiMessage::readVariableLengthVal (const uint8* data,
  22079. int& numBytesUsed) throw()
  22080. {
  22081. numBytesUsed = 0;
  22082. int v = 0;
  22083. int i;
  22084. do
  22085. {
  22086. i = (int) *data++;
  22087. if (++numBytesUsed > 6)
  22088. break;
  22089. v = (v << 7) + (i & 0x7f);
  22090. } while (i & 0x80);
  22091. return v;
  22092. }
  22093. int MidiMessage::getMessageLengthFromFirstByte (const uint8 firstByte) throw()
  22094. {
  22095. // this method only works for valid starting bytes of a short midi message
  22096. jassert (firstByte >= 0x80
  22097. && firstByte != 0xf0
  22098. && firstByte != 0xf7);
  22099. static const char messageLengths[] =
  22100. {
  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. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22105. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  22106. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  22107. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22108. 1, 2, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
  22109. };
  22110. return messageLengths [firstByte & 0x7f];
  22111. }
  22112. MidiMessage::MidiMessage (const void* const d, const int dataSize, const double t)
  22113. : timeStamp (t),
  22114. size (dataSize)
  22115. {
  22116. jassert (dataSize > 0);
  22117. if (dataSize <= 4)
  22118. data = static_cast<uint8*> (preallocatedData.asBytes);
  22119. else
  22120. data = new uint8 [dataSize];
  22121. memcpy (data, d, dataSize);
  22122. // check that the length matches the data..
  22123. jassert (size > 3 || data[0] >= 0xf0 || getMessageLengthFromFirstByte (data[0]) == size);
  22124. }
  22125. MidiMessage::MidiMessage (const int byte1, const double t) throw()
  22126. : timeStamp (t),
  22127. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22128. size (1)
  22129. {
  22130. data[0] = (uint8) byte1;
  22131. // check that the length matches the data..
  22132. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 1);
  22133. }
  22134. MidiMessage::MidiMessage (const int byte1, const int byte2, const double t) throw()
  22135. : timeStamp (t),
  22136. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22137. size (2)
  22138. {
  22139. data[0] = (uint8) byte1;
  22140. data[1] = (uint8) byte2;
  22141. // check that the length matches the data..
  22142. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 2);
  22143. }
  22144. MidiMessage::MidiMessage (const int byte1, const int byte2, const int byte3, const double t) throw()
  22145. : timeStamp (t),
  22146. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22147. size (3)
  22148. {
  22149. data[0] = (uint8) byte1;
  22150. data[1] = (uint8) byte2;
  22151. data[2] = (uint8) byte3;
  22152. // check that the length matches the data..
  22153. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 3);
  22154. }
  22155. MidiMessage::MidiMessage (const MidiMessage& other)
  22156. : timeStamp (other.timeStamp),
  22157. size (other.size)
  22158. {
  22159. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  22160. {
  22161. data = new uint8 [size];
  22162. memcpy (data, other.data, size);
  22163. }
  22164. else
  22165. {
  22166. data = static_cast<uint8*> (preallocatedData.asBytes);
  22167. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  22168. }
  22169. }
  22170. MidiMessage::MidiMessage (const MidiMessage& other, const double newTimeStamp)
  22171. : timeStamp (newTimeStamp),
  22172. size (other.size)
  22173. {
  22174. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  22175. {
  22176. data = new uint8 [size];
  22177. memcpy (data, other.data, size);
  22178. }
  22179. else
  22180. {
  22181. data = static_cast<uint8*> (preallocatedData.asBytes);
  22182. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  22183. }
  22184. }
  22185. MidiMessage::MidiMessage (const void* src_, int sz, int& numBytesUsed, const uint8 lastStatusByte, double t)
  22186. : timeStamp (t),
  22187. data (static_cast<uint8*> (preallocatedData.asBytes))
  22188. {
  22189. const uint8* src = static_cast <const uint8*> (src_);
  22190. unsigned int byte = (unsigned int) *src;
  22191. if (byte < 0x80)
  22192. {
  22193. byte = (unsigned int) (uint8) lastStatusByte;
  22194. numBytesUsed = -1;
  22195. }
  22196. else
  22197. {
  22198. numBytesUsed = 0;
  22199. --sz;
  22200. ++src;
  22201. }
  22202. if (byte >= 0x80)
  22203. {
  22204. if (byte == 0xf0)
  22205. {
  22206. const uint8* d = src;
  22207. while (d < src + sz)
  22208. {
  22209. if (*d >= 0x80) // stop if we hit a status byte, and don't include it in this message
  22210. {
  22211. if (*d == 0xf7) // include an 0xf7 if we hit one
  22212. ++d;
  22213. break;
  22214. }
  22215. ++d;
  22216. }
  22217. size = 1 + (int) (d - src);
  22218. data = new uint8 [size];
  22219. *data = (uint8) byte;
  22220. memcpy (data + 1, src, size - 1);
  22221. }
  22222. else if (byte == 0xff)
  22223. {
  22224. int n;
  22225. const int bytesLeft = readVariableLengthVal (src + 1, n);
  22226. size = jmin (sz + 1, n + 2 + bytesLeft);
  22227. data = new uint8 [size];
  22228. *data = (uint8) byte;
  22229. memcpy (data + 1, src, size - 1);
  22230. }
  22231. else
  22232. {
  22233. preallocatedData.asInt32 = 0;
  22234. size = getMessageLengthFromFirstByte ((uint8) byte);
  22235. data[0] = (uint8) byte;
  22236. if (size > 1)
  22237. {
  22238. data[1] = src[0];
  22239. if (size > 2)
  22240. data[2] = src[1];
  22241. }
  22242. }
  22243. numBytesUsed += size;
  22244. }
  22245. else
  22246. {
  22247. preallocatedData.asInt32 = 0;
  22248. size = 0;
  22249. }
  22250. }
  22251. MidiMessage& MidiMessage::operator= (const MidiMessage& other)
  22252. {
  22253. if (this != &other)
  22254. {
  22255. timeStamp = other.timeStamp;
  22256. size = other.size;
  22257. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  22258. delete[] data;
  22259. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  22260. {
  22261. data = new uint8 [size];
  22262. memcpy (data, other.data, size);
  22263. }
  22264. else
  22265. {
  22266. data = static_cast<uint8*> (preallocatedData.asBytes);
  22267. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  22268. }
  22269. }
  22270. return *this;
  22271. }
  22272. MidiMessage::~MidiMessage()
  22273. {
  22274. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  22275. delete[] data;
  22276. }
  22277. int MidiMessage::getChannel() const throw()
  22278. {
  22279. if ((data[0] & 0xf0) != 0xf0)
  22280. return (data[0] & 0xf) + 1;
  22281. else
  22282. return 0;
  22283. }
  22284. bool MidiMessage::isForChannel (const int channel) const throw()
  22285. {
  22286. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22287. return ((data[0] & 0xf) == channel - 1)
  22288. && ((data[0] & 0xf0) != 0xf0);
  22289. }
  22290. void MidiMessage::setChannel (const int channel) throw()
  22291. {
  22292. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22293. if ((data[0] & 0xf0) != (uint8) 0xf0)
  22294. data[0] = (uint8) ((data[0] & (uint8)0xf0)
  22295. | (uint8)(channel - 1));
  22296. }
  22297. bool MidiMessage::isNoteOn (const bool returnTrueForVelocity0) const throw()
  22298. {
  22299. return ((data[0] & 0xf0) == 0x90)
  22300. && (returnTrueForVelocity0 || data[2] != 0);
  22301. }
  22302. bool MidiMessage::isNoteOff (const bool returnTrueForNoteOnVelocity0) const throw()
  22303. {
  22304. return ((data[0] & 0xf0) == 0x80)
  22305. || (returnTrueForNoteOnVelocity0 && (data[2] == 0) && ((data[0] & 0xf0) == 0x90));
  22306. }
  22307. bool MidiMessage::isNoteOnOrOff() const throw()
  22308. {
  22309. const int d = data[0] & 0xf0;
  22310. return (d == 0x90) || (d == 0x80);
  22311. }
  22312. int MidiMessage::getNoteNumber() const throw()
  22313. {
  22314. return data[1];
  22315. }
  22316. void MidiMessage::setNoteNumber (const int newNoteNumber) throw()
  22317. {
  22318. if (isNoteOnOrOff())
  22319. data[1] = (uint8) jlimit (0, 127, newNoteNumber);
  22320. }
  22321. uint8 MidiMessage::getVelocity() const throw()
  22322. {
  22323. if (isNoteOnOrOff())
  22324. return data[2];
  22325. else
  22326. return 0;
  22327. }
  22328. float MidiMessage::getFloatVelocity() const throw()
  22329. {
  22330. return getVelocity() * (1.0f / 127.0f);
  22331. }
  22332. void MidiMessage::setVelocity (const float newVelocity) throw()
  22333. {
  22334. if (isNoteOnOrOff())
  22335. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (newVelocity * 127.0f));
  22336. }
  22337. void MidiMessage::multiplyVelocity (const float scaleFactor) throw()
  22338. {
  22339. if (isNoteOnOrOff())
  22340. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (scaleFactor * data[2]));
  22341. }
  22342. bool MidiMessage::isAftertouch() const throw()
  22343. {
  22344. return (data[0] & 0xf0) == 0xa0;
  22345. }
  22346. int MidiMessage::getAfterTouchValue() const throw()
  22347. {
  22348. return data[2];
  22349. }
  22350. const MidiMessage MidiMessage::aftertouchChange (const int channel,
  22351. const int noteNum,
  22352. const int aftertouchValue) throw()
  22353. {
  22354. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22355. jassert (((unsigned int) noteNum) <= 127);
  22356. jassert (((unsigned int) aftertouchValue) <= 127);
  22357. return MidiMessage (0xa0 | jlimit (0, 15, channel - 1),
  22358. noteNum & 0x7f,
  22359. aftertouchValue & 0x7f);
  22360. }
  22361. bool MidiMessage::isChannelPressure() const throw()
  22362. {
  22363. return (data[0] & 0xf0) == 0xd0;
  22364. }
  22365. int MidiMessage::getChannelPressureValue() const throw()
  22366. {
  22367. jassert (isChannelPressure());
  22368. return data[1];
  22369. }
  22370. const MidiMessage MidiMessage::channelPressureChange (const int channel,
  22371. const int pressure) throw()
  22372. {
  22373. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22374. jassert (((unsigned int) pressure) <= 127);
  22375. return MidiMessage (0xd0 | jlimit (0, 15, channel - 1),
  22376. pressure & 0x7f);
  22377. }
  22378. bool MidiMessage::isProgramChange() const throw()
  22379. {
  22380. return (data[0] & 0xf0) == 0xc0;
  22381. }
  22382. int MidiMessage::getProgramChangeNumber() const throw()
  22383. {
  22384. return data[1];
  22385. }
  22386. const MidiMessage MidiMessage::programChange (const int channel,
  22387. const int programNumber) throw()
  22388. {
  22389. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22390. return MidiMessage (0xc0 | jlimit (0, 15, channel - 1),
  22391. programNumber & 0x7f);
  22392. }
  22393. bool MidiMessage::isPitchWheel() const throw()
  22394. {
  22395. return (data[0] & 0xf0) == 0xe0;
  22396. }
  22397. int MidiMessage::getPitchWheelValue() const throw()
  22398. {
  22399. return data[1] | (data[2] << 7);
  22400. }
  22401. const MidiMessage MidiMessage::pitchWheel (const int channel,
  22402. const int position) throw()
  22403. {
  22404. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22405. jassert (((unsigned int) position) <= 0x3fff);
  22406. return MidiMessage (0xe0 | jlimit (0, 15, channel - 1),
  22407. position & 127,
  22408. (position >> 7) & 127);
  22409. }
  22410. bool MidiMessage::isController() const throw()
  22411. {
  22412. return (data[0] & 0xf0) == 0xb0;
  22413. }
  22414. int MidiMessage::getControllerNumber() const throw()
  22415. {
  22416. jassert (isController());
  22417. return data[1];
  22418. }
  22419. int MidiMessage::getControllerValue() const throw()
  22420. {
  22421. jassert (isController());
  22422. return data[2];
  22423. }
  22424. const MidiMessage MidiMessage::controllerEvent (const int channel,
  22425. const int controllerType,
  22426. const int value) throw()
  22427. {
  22428. // the channel must be between 1 and 16 inclusive
  22429. jassert (channel > 0 && channel <= 16);
  22430. return MidiMessage (0xb0 | jlimit (0, 15, channel - 1),
  22431. controllerType & 127,
  22432. value & 127);
  22433. }
  22434. const MidiMessage MidiMessage::noteOn (const int channel,
  22435. const int noteNumber,
  22436. const float velocity) throw()
  22437. {
  22438. return noteOn (channel, noteNumber, (uint8)(velocity * 127.0f));
  22439. }
  22440. const MidiMessage MidiMessage::noteOn (const int channel,
  22441. const int noteNumber,
  22442. const uint8 velocity) throw()
  22443. {
  22444. jassert (channel > 0 && channel <= 16);
  22445. jassert (((unsigned int) noteNumber) <= 127);
  22446. return MidiMessage (0x90 | jlimit (0, 15, channel - 1),
  22447. noteNumber & 127,
  22448. jlimit (0, 127, roundToInt (velocity)));
  22449. }
  22450. const MidiMessage MidiMessage::noteOff (const int channel,
  22451. const int noteNumber) throw()
  22452. {
  22453. jassert (channel > 0 && channel <= 16);
  22454. jassert (((unsigned int) noteNumber) <= 127);
  22455. return MidiMessage (0x80 | jlimit (0, 15, channel - 1), noteNumber & 127, 0);
  22456. }
  22457. const MidiMessage MidiMessage::allNotesOff (const int channel) throw()
  22458. {
  22459. jassert (channel > 0 && channel <= 16);
  22460. return controllerEvent (channel, 123, 0);
  22461. }
  22462. bool MidiMessage::isAllNotesOff() const throw()
  22463. {
  22464. return (data[0] & 0xf0) == 0xb0
  22465. && data[1] == 123;
  22466. }
  22467. const MidiMessage MidiMessage::allSoundOff (const int channel) throw()
  22468. {
  22469. return controllerEvent (channel, 120, 0);
  22470. }
  22471. bool MidiMessage::isAllSoundOff() const throw()
  22472. {
  22473. return (data[0] & 0xf0) == 0xb0
  22474. && data[1] == 120;
  22475. }
  22476. const MidiMessage MidiMessage::allControllersOff (const int channel) throw()
  22477. {
  22478. return controllerEvent (channel, 121, 0);
  22479. }
  22480. const MidiMessage MidiMessage::masterVolume (const float volume)
  22481. {
  22482. const int vol = jlimit (0, 0x3fff, roundToInt (volume * 0x4000));
  22483. uint8 buf[8];
  22484. buf[0] = 0xf0;
  22485. buf[1] = 0x7f;
  22486. buf[2] = 0x7f;
  22487. buf[3] = 0x04;
  22488. buf[4] = 0x01;
  22489. buf[5] = (uint8) (vol & 0x7f);
  22490. buf[6] = (uint8) (vol >> 7);
  22491. buf[7] = 0xf7;
  22492. return MidiMessage (buf, 8);
  22493. }
  22494. bool MidiMessage::isSysEx() const throw()
  22495. {
  22496. return *data == 0xf0;
  22497. }
  22498. const MidiMessage MidiMessage::createSysExMessage (const uint8* sysexData, const int dataSize)
  22499. {
  22500. MemoryBlock mm (dataSize + 2);
  22501. uint8* const m = static_cast <uint8*> (mm.getData());
  22502. m[0] = 0xf0;
  22503. memcpy (m + 1, sysexData, dataSize);
  22504. m[dataSize + 1] = 0xf7;
  22505. return MidiMessage (m, dataSize + 2);
  22506. }
  22507. const uint8* MidiMessage::getSysExData() const throw()
  22508. {
  22509. return (isSysEx()) ? getRawData() + 1 : 0;
  22510. }
  22511. int MidiMessage::getSysExDataSize() const throw()
  22512. {
  22513. return (isSysEx()) ? size - 2 : 0;
  22514. }
  22515. bool MidiMessage::isMetaEvent() const throw()
  22516. {
  22517. return *data == 0xff;
  22518. }
  22519. bool MidiMessage::isActiveSense() const throw()
  22520. {
  22521. return *data == 0xfe;
  22522. }
  22523. int MidiMessage::getMetaEventType() const throw()
  22524. {
  22525. if (*data != 0xff)
  22526. return -1;
  22527. else
  22528. return data[1];
  22529. }
  22530. int MidiMessage::getMetaEventLength() const throw()
  22531. {
  22532. if (*data == 0xff)
  22533. {
  22534. int n;
  22535. return jmin (size - 2, readVariableLengthVal (data + 2, n));
  22536. }
  22537. return 0;
  22538. }
  22539. const uint8* MidiMessage::getMetaEventData() const throw()
  22540. {
  22541. int n;
  22542. const uint8* d = data + 2;
  22543. readVariableLengthVal (d, n);
  22544. return d + n;
  22545. }
  22546. bool MidiMessage::isTrackMetaEvent() const throw()
  22547. {
  22548. return getMetaEventType() == 0;
  22549. }
  22550. bool MidiMessage::isEndOfTrackMetaEvent() const throw()
  22551. {
  22552. return getMetaEventType() == 47;
  22553. }
  22554. bool MidiMessage::isTextMetaEvent() const throw()
  22555. {
  22556. const int t = getMetaEventType();
  22557. return t > 0 && t < 16;
  22558. }
  22559. const String MidiMessage::getTextFromTextMetaEvent() const
  22560. {
  22561. return String (reinterpret_cast <const char*> (getMetaEventData()), getMetaEventLength());
  22562. }
  22563. bool MidiMessage::isTrackNameEvent() const throw()
  22564. {
  22565. return (data[1] == 3)
  22566. && (*data == 0xff);
  22567. }
  22568. bool MidiMessage::isTempoMetaEvent() const throw()
  22569. {
  22570. return (data[1] == 81)
  22571. && (*data == 0xff);
  22572. }
  22573. bool MidiMessage::isMidiChannelMetaEvent() const throw()
  22574. {
  22575. return (data[1] == 0x20)
  22576. && (*data == 0xff)
  22577. && (data[2] == 1);
  22578. }
  22579. int MidiMessage::getMidiChannelMetaEventChannel() const throw()
  22580. {
  22581. return data[3] + 1;
  22582. }
  22583. double MidiMessage::getTempoSecondsPerQuarterNote() const throw()
  22584. {
  22585. if (! isTempoMetaEvent())
  22586. return 0.0;
  22587. const uint8* const d = getMetaEventData();
  22588. return (((unsigned int) d[0] << 16)
  22589. | ((unsigned int) d[1] << 8)
  22590. | d[2])
  22591. / 1000000.0;
  22592. }
  22593. double MidiMessage::getTempoMetaEventTickLength (const short timeFormat) const throw()
  22594. {
  22595. if (timeFormat > 0)
  22596. {
  22597. if (! isTempoMetaEvent())
  22598. return 0.5 / timeFormat;
  22599. return getTempoSecondsPerQuarterNote() / timeFormat;
  22600. }
  22601. else
  22602. {
  22603. const int frameCode = (-timeFormat) >> 8;
  22604. double framesPerSecond;
  22605. switch (frameCode)
  22606. {
  22607. case 24: framesPerSecond = 24.0; break;
  22608. case 25: framesPerSecond = 25.0; break;
  22609. case 29: framesPerSecond = 29.97; break;
  22610. case 30: framesPerSecond = 30.0; break;
  22611. default: framesPerSecond = 30.0; break;
  22612. }
  22613. return (1.0 / framesPerSecond) / (timeFormat & 0xff);
  22614. }
  22615. }
  22616. const MidiMessage MidiMessage::tempoMetaEvent (int microsecondsPerQuarterNote) throw()
  22617. {
  22618. uint8 d[8];
  22619. d[0] = 0xff;
  22620. d[1] = 81;
  22621. d[2] = 3;
  22622. d[3] = (uint8) (microsecondsPerQuarterNote >> 16);
  22623. d[4] = (uint8) ((microsecondsPerQuarterNote >> 8) & 0xff);
  22624. d[5] = (uint8) (microsecondsPerQuarterNote & 0xff);
  22625. return MidiMessage (d, 6, 0.0);
  22626. }
  22627. bool MidiMessage::isTimeSignatureMetaEvent() const throw()
  22628. {
  22629. return (data[1] == 0x58)
  22630. && (*data == (uint8) 0xff);
  22631. }
  22632. void MidiMessage::getTimeSignatureInfo (int& numerator, int& denominator) const throw()
  22633. {
  22634. if (isTimeSignatureMetaEvent())
  22635. {
  22636. const uint8* const d = getMetaEventData();
  22637. numerator = d[0];
  22638. denominator = 1 << d[1];
  22639. }
  22640. else
  22641. {
  22642. numerator = 4;
  22643. denominator = 4;
  22644. }
  22645. }
  22646. const MidiMessage MidiMessage::timeSignatureMetaEvent (const int numerator, const int denominator)
  22647. {
  22648. uint8 d[8];
  22649. d[0] = 0xff;
  22650. d[1] = 0x58;
  22651. d[2] = 0x04;
  22652. d[3] = (uint8) numerator;
  22653. int n = 1;
  22654. int powerOfTwo = 0;
  22655. while (n < denominator)
  22656. {
  22657. n <<= 1;
  22658. ++powerOfTwo;
  22659. }
  22660. d[4] = (uint8) powerOfTwo;
  22661. d[5] = 0x01;
  22662. d[6] = 96;
  22663. return MidiMessage (d, 7, 0.0);
  22664. }
  22665. const MidiMessage MidiMessage::midiChannelMetaEvent (const int channel) throw()
  22666. {
  22667. uint8 d[8];
  22668. d[0] = 0xff;
  22669. d[1] = 0x20;
  22670. d[2] = 0x01;
  22671. d[3] = (uint8) jlimit (0, 0xff, channel - 1);
  22672. return MidiMessage (d, 4, 0.0);
  22673. }
  22674. bool MidiMessage::isKeySignatureMetaEvent() const throw()
  22675. {
  22676. return getMetaEventType() == 89;
  22677. }
  22678. int MidiMessage::getKeySignatureNumberOfSharpsOrFlats() const throw()
  22679. {
  22680. return (int) *getMetaEventData();
  22681. }
  22682. const MidiMessage MidiMessage::endOfTrack() throw()
  22683. {
  22684. return MidiMessage (0xff, 0x2f, 0, 0.0);
  22685. }
  22686. bool MidiMessage::isSongPositionPointer() const throw()
  22687. {
  22688. return *data == 0xf2;
  22689. }
  22690. int MidiMessage::getSongPositionPointerMidiBeat() const throw()
  22691. {
  22692. return data[1] | (data[2] << 7);
  22693. }
  22694. const MidiMessage MidiMessage::songPositionPointer (const int positionInMidiBeats) throw()
  22695. {
  22696. return MidiMessage (0xf2,
  22697. positionInMidiBeats & 127,
  22698. (positionInMidiBeats >> 7) & 127);
  22699. }
  22700. bool MidiMessage::isMidiStart() const throw()
  22701. {
  22702. return *data == 0xfa;
  22703. }
  22704. const MidiMessage MidiMessage::midiStart() throw()
  22705. {
  22706. return MidiMessage (0xfa);
  22707. }
  22708. bool MidiMessage::isMidiContinue() const throw()
  22709. {
  22710. return *data == 0xfb;
  22711. }
  22712. const MidiMessage MidiMessage::midiContinue() throw()
  22713. {
  22714. return MidiMessage (0xfb);
  22715. }
  22716. bool MidiMessage::isMidiStop() const throw()
  22717. {
  22718. return *data == 0xfc;
  22719. }
  22720. const MidiMessage MidiMessage::midiStop() throw()
  22721. {
  22722. return MidiMessage (0xfc);
  22723. }
  22724. bool MidiMessage::isMidiClock() const throw()
  22725. {
  22726. return *data == 0xf8;
  22727. }
  22728. const MidiMessage MidiMessage::midiClock() throw()
  22729. {
  22730. return MidiMessage (0xf8);
  22731. }
  22732. bool MidiMessage::isQuarterFrame() const throw()
  22733. {
  22734. return *data == 0xf1;
  22735. }
  22736. int MidiMessage::getQuarterFrameSequenceNumber() const throw()
  22737. {
  22738. return ((int) data[1]) >> 4;
  22739. }
  22740. int MidiMessage::getQuarterFrameValue() const throw()
  22741. {
  22742. return ((int) data[1]) & 0x0f;
  22743. }
  22744. const MidiMessage MidiMessage::quarterFrame (const int sequenceNumber,
  22745. const int value) throw()
  22746. {
  22747. return MidiMessage (0xf1, (sequenceNumber << 4) | value);
  22748. }
  22749. bool MidiMessage::isFullFrame() const throw()
  22750. {
  22751. return data[0] == 0xf0
  22752. && data[1] == 0x7f
  22753. && size >= 10
  22754. && data[3] == 0x01
  22755. && data[4] == 0x01;
  22756. }
  22757. void MidiMessage::getFullFrameParameters (int& hours,
  22758. int& minutes,
  22759. int& seconds,
  22760. int& frames,
  22761. MidiMessage::SmpteTimecodeType& timecodeType) const throw()
  22762. {
  22763. jassert (isFullFrame());
  22764. timecodeType = (SmpteTimecodeType) (data[5] >> 5);
  22765. hours = data[5] & 0x1f;
  22766. minutes = data[6];
  22767. seconds = data[7];
  22768. frames = data[8];
  22769. }
  22770. const MidiMessage MidiMessage::fullFrame (const int hours,
  22771. const int minutes,
  22772. const int seconds,
  22773. const int frames,
  22774. MidiMessage::SmpteTimecodeType timecodeType)
  22775. {
  22776. uint8 d[10];
  22777. d[0] = 0xf0;
  22778. d[1] = 0x7f;
  22779. d[2] = 0x7f;
  22780. d[3] = 0x01;
  22781. d[4] = 0x01;
  22782. d[5] = (uint8) ((hours & 0x01f) | (timecodeType << 5));
  22783. d[6] = (uint8) minutes;
  22784. d[7] = (uint8) seconds;
  22785. d[8] = (uint8) frames;
  22786. d[9] = 0xf7;
  22787. return MidiMessage (d, 10, 0.0);
  22788. }
  22789. bool MidiMessage::isMidiMachineControlMessage() const throw()
  22790. {
  22791. return data[0] == 0xf0
  22792. && data[1] == 0x7f
  22793. && data[3] == 0x06
  22794. && size > 5;
  22795. }
  22796. MidiMessage::MidiMachineControlCommand MidiMessage::getMidiMachineControlCommand() const throw()
  22797. {
  22798. jassert (isMidiMachineControlMessage());
  22799. return (MidiMachineControlCommand) data[4];
  22800. }
  22801. const MidiMessage MidiMessage::midiMachineControlCommand (MidiMessage::MidiMachineControlCommand command)
  22802. {
  22803. uint8 d[6];
  22804. d[0] = 0xf0;
  22805. d[1] = 0x7f;
  22806. d[2] = 0x00;
  22807. d[3] = 0x06;
  22808. d[4] = (uint8) command;
  22809. d[5] = 0xf7;
  22810. return MidiMessage (d, 6, 0.0);
  22811. }
  22812. bool MidiMessage::isMidiMachineControlGoto (int& hours,
  22813. int& minutes,
  22814. int& seconds,
  22815. int& frames) const throw()
  22816. {
  22817. if (size >= 12
  22818. && data[0] == 0xf0
  22819. && data[1] == 0x7f
  22820. && data[3] == 0x06
  22821. && data[4] == 0x44
  22822. && data[5] == 0x06
  22823. && data[6] == 0x01)
  22824. {
  22825. hours = data[7] % 24; // (that some machines send out hours > 24)
  22826. minutes = data[8];
  22827. seconds = data[9];
  22828. frames = data[10];
  22829. return true;
  22830. }
  22831. return false;
  22832. }
  22833. const MidiMessage MidiMessage::midiMachineControlGoto (int hours,
  22834. int minutes,
  22835. int seconds,
  22836. int frames)
  22837. {
  22838. uint8 d[12];
  22839. d[0] = 0xf0;
  22840. d[1] = 0x7f;
  22841. d[2] = 0x00;
  22842. d[3] = 0x06;
  22843. d[4] = 0x44;
  22844. d[5] = 0x06;
  22845. d[6] = 0x01;
  22846. d[7] = (uint8) hours;
  22847. d[8] = (uint8) minutes;
  22848. d[9] = (uint8) seconds;
  22849. d[10] = (uint8) frames;
  22850. d[11] = 0xf7;
  22851. return MidiMessage (d, 12, 0.0);
  22852. }
  22853. const String MidiMessage::getMidiNoteName (int note,
  22854. bool useSharps,
  22855. bool includeOctaveNumber,
  22856. int octaveNumForMiddleC) throw()
  22857. {
  22858. static const char* const sharpNoteNames[] = { "C", "C#", "D", "D#", "E",
  22859. "F", "F#", "G", "G#", "A",
  22860. "A#", "B" };
  22861. static const char* const flatNoteNames[] = { "C", "Db", "D", "Eb", "E",
  22862. "F", "Gb", "G", "Ab", "A",
  22863. "Bb", "B" };
  22864. if (((unsigned int) note) < 128)
  22865. {
  22866. const String s ((useSharps) ? sharpNoteNames [note % 12]
  22867. : flatNoteNames [note % 12]);
  22868. if (includeOctaveNumber)
  22869. return s + String (note / 12 + (octaveNumForMiddleC - 5));
  22870. else
  22871. return s;
  22872. }
  22873. return String::empty;
  22874. }
  22875. const double MidiMessage::getMidiNoteInHertz (int noteNumber) throw()
  22876. {
  22877. noteNumber -= 12 * 6 + 9; // now 0 = A440
  22878. return 440.0 * pow (2.0, noteNumber / 12.0);
  22879. }
  22880. const String MidiMessage::getGMInstrumentName (int n) throw()
  22881. {
  22882. const char *names[] =
  22883. {
  22884. "Acoustic Grand Piano", "Bright Acoustic Piano", "Electric Grand Piano", "Honky-tonk Piano",
  22885. "Electric Piano 1", "Electric Piano 2", "Harpsichord", "Clavinet", "Celesta", "Glockenspiel",
  22886. "Music Box", "Vibraphone", "Marimba", "Xylophone", "Tubular Bells", "Dulcimer", "Drawbar Organ",
  22887. "Percussive Organ", "Rock Organ", "Church Organ", "Reed Organ", "Accordion", "Harmonica",
  22888. "Tango Accordion", "Acoustic Guitar (nylon)", "Acoustic Guitar (steel)", "Electric Guitar (jazz)",
  22889. "Electric Guitar (clean)", "Electric Guitar (mute)", "Overdriven Guitar", "Distortion Guitar",
  22890. "Guitar Harmonics", "Acoustic Bass", "Electric Bass (finger)", "Electric Bass (pick)",
  22891. "Fretless Bass", "Slap Bass 1", "Slap Bass 2", "Synth Bass 1", "Synth Bass 2", "Violin",
  22892. "Viola", "Cello", "Contrabass", "Tremolo Strings", "Pizzicato Strings", "Orchestral Harp",
  22893. "Timpani", "String Ensemble 1", "String Ensemble 2", "SynthStrings 1", "SynthStrings 2",
  22894. "Choir Aahs", "Voice Oohs", "Synth Voice", "Orchestra Hit", "Trumpet", "Trombone", "Tuba",
  22895. "Muted Trumpet", "French Horn", "Brass Section", "SynthBrass 1", "SynthBrass 2", "Soprano Sax",
  22896. "Alto Sax", "Tenor Sax", "Baritone Sax", "Oboe", "English Horn", "Bassoon", "Clarinet",
  22897. "Piccolo", "Flute", "Recorder", "Pan Flute", "Blown Bottle", "Shakuhachi", "Whistle",
  22898. "Ocarina", "Lead 1 (square)", "Lead 2 (sawtooth)", "Lead 3 (calliope)", "Lead 4 (chiff)",
  22899. "Lead 5 (charang)", "Lead 6 (voice)", "Lead 7 (fifths)", "Lead 8 (bass+lead)", "Pad 1 (new age)",
  22900. "Pad 2 (warm)", "Pad 3 (polysynth)", "Pad 4 (choir)", "Pad 5 (bowed)", "Pad 6 (metallic)",
  22901. "Pad 7 (halo)", "Pad 8 (sweep)", "FX 1 (rain)", "FX 2 (soundtrack)", "FX 3 (crystal)",
  22902. "FX 4 (atmosphere)", "FX 5 (brightness)", "FX 6 (goblins)", "FX 7 (echoes)", "FX 8 (sci-fi)",
  22903. "Sitar", "Banjo", "Shamisen", "Koto", "Kalimba", "Bag pipe", "Fiddle", "Shanai", "Tinkle Bell",
  22904. "Agogo", "Steel Drums", "Woodblock", "Taiko Drum", "Melodic Tom", "Synth Drum", "Reverse Cymbal",
  22905. "Guitar Fret Noise", "Breath Noise", "Seashore", "Bird Tweet", "Telephone Ring", "Helicopter",
  22906. "Applause", "Gunshot"
  22907. };
  22908. return (((unsigned int) n) < 128) ? names[n]
  22909. : (const char*)0;
  22910. }
  22911. const String MidiMessage::getGMInstrumentBankName (int n) throw()
  22912. {
  22913. const char* names[] =
  22914. {
  22915. "Piano", "Chromatic Percussion", "Organ", "Guitar",
  22916. "Bass", "Strings", "Ensemble", "Brass",
  22917. "Reed", "Pipe", "Synth Lead", "Synth Pad",
  22918. "Synth Effects", "Ethnic", "Percussive", "Sound Effects"
  22919. };
  22920. return (((unsigned int) n) <= 15) ? names[n]
  22921. : (const char*)0;
  22922. }
  22923. const String MidiMessage::getRhythmInstrumentName (int n) throw()
  22924. {
  22925. const char* names[] =
  22926. {
  22927. "Acoustic Bass Drum", "Bass Drum 1", "Side Stick", "Acoustic Snare",
  22928. "Hand Clap", "Electric Snare", "Low Floor Tom", "Closed Hi-Hat", "High Floor Tom",
  22929. "Pedal Hi-Hat", "Low Tom", "Open Hi-Hat", "Low-Mid Tom", "Hi-Mid Tom", "Crash Cymbal 1",
  22930. "High Tom", "Ride Cymbal 1", "Chinese Cymbal", "Ride Bell", "Tambourine", "Splash Cymbal",
  22931. "Cowbell", "Crash Cymbal 2", "Vibraslap", "Ride Cymbal 2", "Hi Bongo", "Low Bongo",
  22932. "Mute Hi Conga", "Open Hi Conga", "Low Conga", "High Timbale", "Low Timbale", "High Agogo",
  22933. "Low Agogo", "Cabasa", "Maracas", "Short Whistle", "Long Whistle", "Short Guiro",
  22934. "Long Guiro", "Claves", "Hi Wood Block", "Low Wood Block", "Mute Cuica", "Open Cuica",
  22935. "Mute Triangle", "Open Triangle"
  22936. };
  22937. return (n >= 35 && n <= 81) ? names [n - 35]
  22938. : (const char*)0;
  22939. }
  22940. const String MidiMessage::getControllerName (int n) throw()
  22941. {
  22942. const char* names[] =
  22943. {
  22944. "Bank Select", "Modulation Wheel (coarse)", "Breath controller (coarse)",
  22945. 0, "Foot Pedal (coarse)", "Portamento Time (coarse)",
  22946. "Data Entry (coarse)", "Volume (coarse)", "Balance (coarse)",
  22947. 0, "Pan position (coarse)", "Expression (coarse)", "Effect Control 1 (coarse)",
  22948. "Effect Control 2 (coarse)", 0, 0, "General Purpose Slider 1", "General Purpose Slider 2",
  22949. "General Purpose Slider 3", "General Purpose Slider 4", 0, 0, 0, 0, 0, 0, 0, 0,
  22950. 0, 0, 0, 0, "Bank Select (fine)", "Modulation Wheel (fine)", "Breath controller (fine)",
  22951. 0, "Foot Pedal (fine)", "Portamento Time (fine)", "Data Entry (fine)", "Volume (fine)",
  22952. "Balance (fine)", 0, "Pan position (fine)", "Expression (fine)", "Effect Control 1 (fine)",
  22953. "Effect Control 2 (fine)", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  22954. "Hold Pedal (on/off)", "Portamento (on/off)", "Sustenuto Pedal (on/off)", "Soft Pedal (on/off)",
  22955. "Legato Pedal (on/off)", "Hold 2 Pedal (on/off)", "Sound Variation", "Sound Timbre",
  22956. "Sound Release Time", "Sound Attack Time", "Sound Brightness", "Sound Control 6",
  22957. "Sound Control 7", "Sound Control 8", "Sound Control 9", "Sound Control 10",
  22958. "General Purpose Button 1 (on/off)", "General Purpose Button 2 (on/off)",
  22959. "General Purpose Button 3 (on/off)", "General Purpose Button 4 (on/off)",
  22960. 0, 0, 0, 0, 0, 0, 0, "Reverb Level", "Tremolo Level", "Chorus Level", "Celeste Level",
  22961. "Phaser Level", "Data Button increment", "Data Button decrement", "Non-registered Parameter (fine)",
  22962. "Non-registered Parameter (coarse)", "Registered Parameter (fine)", "Registered Parameter (coarse)",
  22963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "All Sound Off", "All Controllers Off",
  22964. "Local Keyboard (on/off)", "All Notes Off", "Omni Mode Off", "Omni Mode On", "Mono Operation",
  22965. "Poly Operation"
  22966. };
  22967. return (((unsigned int) n) < 128) ? names[n]
  22968. : (const char*)0;
  22969. }
  22970. END_JUCE_NAMESPACE
  22971. /*** End of inlined file: juce_MidiMessage.cpp ***/
  22972. /*** Start of inlined file: juce_MidiMessageCollector.cpp ***/
  22973. BEGIN_JUCE_NAMESPACE
  22974. MidiMessageCollector::MidiMessageCollector()
  22975. : lastCallbackTime (0),
  22976. sampleRate (44100.0001)
  22977. {
  22978. }
  22979. MidiMessageCollector::~MidiMessageCollector()
  22980. {
  22981. }
  22982. void MidiMessageCollector::reset (const double sampleRate_)
  22983. {
  22984. jassert (sampleRate_ > 0);
  22985. const ScopedLock sl (midiCallbackLock);
  22986. sampleRate = sampleRate_;
  22987. incomingMessages.clear();
  22988. lastCallbackTime = Time::getMillisecondCounterHiRes();
  22989. }
  22990. void MidiMessageCollector::addMessageToQueue (const MidiMessage& message)
  22991. {
  22992. // you need to call reset() to set the correct sample rate before using this object
  22993. jassert (sampleRate != 44100.0001);
  22994. // the messages that come in here need to be time-stamped correctly - see MidiInput
  22995. // for details of what the number should be.
  22996. jassert (message.getTimeStamp() != 0);
  22997. const ScopedLock sl (midiCallbackLock);
  22998. const int sampleNumber
  22999. = (int) ((message.getTimeStamp() - 0.001 * lastCallbackTime) * sampleRate);
  23000. incomingMessages.addEvent (message, sampleNumber);
  23001. // if the messages don't get used for over a second, we'd better
  23002. // get rid of any old ones to avoid the queue getting too big
  23003. if (sampleNumber > sampleRate)
  23004. incomingMessages.clear (0, sampleNumber - (int) sampleRate);
  23005. }
  23006. void MidiMessageCollector::removeNextBlockOfMessages (MidiBuffer& destBuffer,
  23007. const int numSamples)
  23008. {
  23009. // you need to call reset() to set the correct sample rate before using this object
  23010. jassert (sampleRate != 44100.0001);
  23011. const double timeNow = Time::getMillisecondCounterHiRes();
  23012. const double msElapsed = timeNow - lastCallbackTime;
  23013. const ScopedLock sl (midiCallbackLock);
  23014. lastCallbackTime = timeNow;
  23015. if (! incomingMessages.isEmpty())
  23016. {
  23017. int numSourceSamples = jmax (1, roundToInt (msElapsed * 0.001 * sampleRate));
  23018. int startSample = 0;
  23019. int scale = 1 << 16;
  23020. const uint8* midiData;
  23021. int numBytes, samplePosition;
  23022. MidiBuffer::Iterator iter (incomingMessages);
  23023. if (numSourceSamples > numSamples)
  23024. {
  23025. // if our list of events is longer than the buffer we're being
  23026. // asked for, scale them down to squeeze them all in..
  23027. const int maxBlockLengthToUse = numSamples << 5;
  23028. if (numSourceSamples > maxBlockLengthToUse)
  23029. {
  23030. startSample = numSourceSamples - maxBlockLengthToUse;
  23031. numSourceSamples = maxBlockLengthToUse;
  23032. iter.setNextSamplePosition (startSample);
  23033. }
  23034. scale = (numSamples << 10) / numSourceSamples;
  23035. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  23036. {
  23037. samplePosition = ((samplePosition - startSample) * scale) >> 10;
  23038. destBuffer.addEvent (midiData, numBytes,
  23039. jlimit (0, numSamples - 1, samplePosition));
  23040. }
  23041. }
  23042. else
  23043. {
  23044. // if our event list is shorter than the number we need, put them
  23045. // towards the end of the buffer
  23046. startSample = numSamples - numSourceSamples;
  23047. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  23048. {
  23049. destBuffer.addEvent (midiData, numBytes,
  23050. jlimit (0, numSamples - 1, samplePosition + startSample));
  23051. }
  23052. }
  23053. incomingMessages.clear();
  23054. }
  23055. }
  23056. void MidiMessageCollector::handleNoteOn (MidiKeyboardState*, int midiChannel, int midiNoteNumber, float velocity)
  23057. {
  23058. MidiMessage m (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity));
  23059. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  23060. addMessageToQueue (m);
  23061. }
  23062. void MidiMessageCollector::handleNoteOff (MidiKeyboardState*, int midiChannel, int midiNoteNumber)
  23063. {
  23064. MidiMessage m (MidiMessage::noteOff (midiChannel, midiNoteNumber));
  23065. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  23066. addMessageToQueue (m);
  23067. }
  23068. void MidiMessageCollector::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  23069. {
  23070. addMessageToQueue (message);
  23071. }
  23072. END_JUCE_NAMESPACE
  23073. /*** End of inlined file: juce_MidiMessageCollector.cpp ***/
  23074. /*** Start of inlined file: juce_MidiMessageSequence.cpp ***/
  23075. BEGIN_JUCE_NAMESPACE
  23076. MidiMessageSequence::MidiMessageSequence()
  23077. {
  23078. }
  23079. MidiMessageSequence::MidiMessageSequence (const MidiMessageSequence& other)
  23080. {
  23081. list.ensureStorageAllocated (other.list.size());
  23082. for (int i = 0; i < other.list.size(); ++i)
  23083. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  23084. }
  23085. MidiMessageSequence& MidiMessageSequence::operator= (const MidiMessageSequence& other)
  23086. {
  23087. MidiMessageSequence otherCopy (other);
  23088. swapWith (otherCopy);
  23089. return *this;
  23090. }
  23091. void MidiMessageSequence::swapWith (MidiMessageSequence& other) throw()
  23092. {
  23093. list.swapWithArray (other.list);
  23094. }
  23095. MidiMessageSequence::~MidiMessageSequence()
  23096. {
  23097. }
  23098. void MidiMessageSequence::clear()
  23099. {
  23100. list.clear();
  23101. }
  23102. int MidiMessageSequence::getNumEvents() const
  23103. {
  23104. return list.size();
  23105. }
  23106. MidiMessageSequence::MidiEventHolder* MidiMessageSequence::getEventPointer (const int index) const
  23107. {
  23108. return list [index];
  23109. }
  23110. double MidiMessageSequence::getTimeOfMatchingKeyUp (const int index) const
  23111. {
  23112. const MidiEventHolder* const meh = list [index];
  23113. if (meh != 0 && meh->noteOffObject != 0)
  23114. return meh->noteOffObject->message.getTimeStamp();
  23115. else
  23116. return 0.0;
  23117. }
  23118. int MidiMessageSequence::getIndexOfMatchingKeyUp (const int index) const
  23119. {
  23120. const MidiEventHolder* const meh = list [index];
  23121. return (meh != 0) ? list.indexOf (meh->noteOffObject) : -1;
  23122. }
  23123. int MidiMessageSequence::getIndexOf (MidiEventHolder* const event) const
  23124. {
  23125. return list.indexOf (event);
  23126. }
  23127. int MidiMessageSequence::getNextIndexAtTime (const double timeStamp) const
  23128. {
  23129. const int numEvents = list.size();
  23130. int i;
  23131. for (i = 0; i < numEvents; ++i)
  23132. if (list.getUnchecked(i)->message.getTimeStamp() >= timeStamp)
  23133. break;
  23134. return i;
  23135. }
  23136. double MidiMessageSequence::getStartTime() const
  23137. {
  23138. if (list.size() > 0)
  23139. return list.getUnchecked(0)->message.getTimeStamp();
  23140. else
  23141. return 0;
  23142. }
  23143. double MidiMessageSequence::getEndTime() const
  23144. {
  23145. if (list.size() > 0)
  23146. return list.getLast()->message.getTimeStamp();
  23147. else
  23148. return 0;
  23149. }
  23150. double MidiMessageSequence::getEventTime (const int index) const
  23151. {
  23152. if (((unsigned int) index) < (unsigned int) list.size())
  23153. return list.getUnchecked (index)->message.getTimeStamp();
  23154. return 0.0;
  23155. }
  23156. void MidiMessageSequence::addEvent (const MidiMessage& newMessage,
  23157. double timeAdjustment)
  23158. {
  23159. MidiEventHolder* const newOne = new MidiEventHolder (newMessage);
  23160. timeAdjustment += newMessage.getTimeStamp();
  23161. newOne->message.setTimeStamp (timeAdjustment);
  23162. int i;
  23163. for (i = list.size(); --i >= 0;)
  23164. if (list.getUnchecked(i)->message.getTimeStamp() <= timeAdjustment)
  23165. break;
  23166. list.insert (i + 1, newOne);
  23167. }
  23168. void MidiMessageSequence::deleteEvent (const int index,
  23169. const bool deleteMatchingNoteUp)
  23170. {
  23171. if (((unsigned int) index) < (unsigned int) list.size())
  23172. {
  23173. if (deleteMatchingNoteUp)
  23174. deleteEvent (getIndexOfMatchingKeyUp (index), false);
  23175. list.remove (index);
  23176. }
  23177. }
  23178. void MidiMessageSequence::addSequence (const MidiMessageSequence& other,
  23179. double timeAdjustment,
  23180. double firstAllowableTime,
  23181. double endOfAllowableDestTimes)
  23182. {
  23183. firstAllowableTime -= timeAdjustment;
  23184. endOfAllowableDestTimes -= timeAdjustment;
  23185. for (int i = 0; i < other.list.size(); ++i)
  23186. {
  23187. const MidiMessage& m = other.list.getUnchecked(i)->message;
  23188. const double t = m.getTimeStamp();
  23189. if (t >= firstAllowableTime && t < endOfAllowableDestTimes)
  23190. {
  23191. MidiEventHolder* const newOne = new MidiEventHolder (m);
  23192. newOne->message.setTimeStamp (timeAdjustment + t);
  23193. list.add (newOne);
  23194. }
  23195. }
  23196. sort();
  23197. }
  23198. int MidiMessageSequence::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  23199. const MidiMessageSequence::MidiEventHolder* const second) throw()
  23200. {
  23201. const double diff = first->message.getTimeStamp()
  23202. - second->message.getTimeStamp();
  23203. return (diff > 0) - (diff < 0);
  23204. }
  23205. void MidiMessageSequence::sort()
  23206. {
  23207. list.sort (*this, true);
  23208. }
  23209. void MidiMessageSequence::updateMatchedPairs()
  23210. {
  23211. for (int i = 0; i < list.size(); ++i)
  23212. {
  23213. const MidiMessage& m1 = list.getUnchecked(i)->message;
  23214. if (m1.isNoteOn())
  23215. {
  23216. list.getUnchecked(i)->noteOffObject = 0;
  23217. const int note = m1.getNoteNumber();
  23218. const int chan = m1.getChannel();
  23219. const int len = list.size();
  23220. for (int j = i + 1; j < len; ++j)
  23221. {
  23222. const MidiMessage& m = list.getUnchecked(j)->message;
  23223. if (m.getNoteNumber() == note && m.getChannel() == chan)
  23224. {
  23225. if (m.isNoteOff())
  23226. {
  23227. list.getUnchecked(i)->noteOffObject = list[j];
  23228. break;
  23229. }
  23230. else if (m.isNoteOn())
  23231. {
  23232. list.insert (j, new MidiEventHolder (MidiMessage::noteOff (chan, note)));
  23233. list.getUnchecked(j)->message.setTimeStamp (m.getTimeStamp());
  23234. list.getUnchecked(i)->noteOffObject = list[j];
  23235. break;
  23236. }
  23237. }
  23238. }
  23239. }
  23240. }
  23241. }
  23242. void MidiMessageSequence::addTimeToMessages (const double delta)
  23243. {
  23244. for (int i = list.size(); --i >= 0;)
  23245. list.getUnchecked (i)->message.setTimeStamp (list.getUnchecked (i)->message.getTimeStamp()
  23246. + delta);
  23247. }
  23248. void MidiMessageSequence::extractMidiChannelMessages (const int channelNumberToExtract,
  23249. MidiMessageSequence& destSequence,
  23250. const bool alsoIncludeMetaEvents) const
  23251. {
  23252. for (int i = 0; i < list.size(); ++i)
  23253. {
  23254. const MidiMessage& mm = list.getUnchecked(i)->message;
  23255. if (mm.isForChannel (channelNumberToExtract)
  23256. || (alsoIncludeMetaEvents && mm.isMetaEvent()))
  23257. {
  23258. destSequence.addEvent (mm);
  23259. }
  23260. }
  23261. }
  23262. void MidiMessageSequence::extractSysExMessages (MidiMessageSequence& destSequence) const
  23263. {
  23264. for (int i = 0; i < list.size(); ++i)
  23265. {
  23266. const MidiMessage& mm = list.getUnchecked(i)->message;
  23267. if (mm.isSysEx())
  23268. destSequence.addEvent (mm);
  23269. }
  23270. }
  23271. void MidiMessageSequence::deleteMidiChannelMessages (const int channelNumberToRemove)
  23272. {
  23273. for (int i = list.size(); --i >= 0;)
  23274. if (list.getUnchecked(i)->message.isForChannel (channelNumberToRemove))
  23275. list.remove(i);
  23276. }
  23277. void MidiMessageSequence::deleteSysExMessages()
  23278. {
  23279. for (int i = list.size(); --i >= 0;)
  23280. if (list.getUnchecked(i)->message.isSysEx())
  23281. list.remove(i);
  23282. }
  23283. void MidiMessageSequence::createControllerUpdatesForTime (const int channelNumber,
  23284. const double time,
  23285. OwnedArray<MidiMessage>& dest)
  23286. {
  23287. bool doneProg = false;
  23288. bool donePitchWheel = false;
  23289. Array <int> doneControllers;
  23290. doneControllers.ensureStorageAllocated (32);
  23291. for (int i = list.size(); --i >= 0;)
  23292. {
  23293. const MidiMessage& mm = list.getUnchecked(i)->message;
  23294. if (mm.isForChannel (channelNumber)
  23295. && mm.getTimeStamp() <= time)
  23296. {
  23297. if (mm.isProgramChange())
  23298. {
  23299. if (! doneProg)
  23300. {
  23301. dest.add (new MidiMessage (mm, 0.0));
  23302. doneProg = true;
  23303. }
  23304. }
  23305. else if (mm.isController())
  23306. {
  23307. if (! doneControllers.contains (mm.getControllerNumber()))
  23308. {
  23309. dest.add (new MidiMessage (mm, 0.0));
  23310. doneControllers.add (mm.getControllerNumber());
  23311. }
  23312. }
  23313. else if (mm.isPitchWheel())
  23314. {
  23315. if (! donePitchWheel)
  23316. {
  23317. dest.add (new MidiMessage (mm, 0.0));
  23318. donePitchWheel = true;
  23319. }
  23320. }
  23321. }
  23322. }
  23323. }
  23324. MidiMessageSequence::MidiEventHolder::MidiEventHolder (const MidiMessage& message_)
  23325. : message (message_),
  23326. noteOffObject (0)
  23327. {
  23328. }
  23329. MidiMessageSequence::MidiEventHolder::~MidiEventHolder()
  23330. {
  23331. }
  23332. END_JUCE_NAMESPACE
  23333. /*** End of inlined file: juce_MidiMessageSequence.cpp ***/
  23334. /*** Start of inlined file: juce_AudioPluginFormat.cpp ***/
  23335. BEGIN_JUCE_NAMESPACE
  23336. AudioPluginFormat::AudioPluginFormat() throw()
  23337. {
  23338. }
  23339. AudioPluginFormat::~AudioPluginFormat()
  23340. {
  23341. }
  23342. END_JUCE_NAMESPACE
  23343. /*** End of inlined file: juce_AudioPluginFormat.cpp ***/
  23344. /*** Start of inlined file: juce_AudioPluginFormatManager.cpp ***/
  23345. BEGIN_JUCE_NAMESPACE
  23346. AudioPluginFormatManager::AudioPluginFormatManager() throw()
  23347. {
  23348. }
  23349. AudioPluginFormatManager::~AudioPluginFormatManager() throw()
  23350. {
  23351. clearSingletonInstance();
  23352. }
  23353. juce_ImplementSingleton_SingleThreaded (AudioPluginFormatManager);
  23354. void AudioPluginFormatManager::addDefaultFormats()
  23355. {
  23356. #if JUCE_DEBUG
  23357. // you should only call this method once!
  23358. for (int i = formats.size(); --i >= 0;)
  23359. {
  23360. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  23361. jassert (dynamic_cast <VSTPluginFormat*> (formats[i]) == 0);
  23362. #endif
  23363. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  23364. jassert (dynamic_cast <AudioUnitPluginFormat*> (formats[i]) == 0);
  23365. #endif
  23366. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  23367. jassert (dynamic_cast <DirectXPluginFormat*> (formats[i]) == 0);
  23368. #endif
  23369. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  23370. jassert (dynamic_cast <LADSPAPluginFormat*> (formats[i]) == 0);
  23371. #endif
  23372. }
  23373. #endif
  23374. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  23375. formats.add (new AudioUnitPluginFormat());
  23376. #endif
  23377. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  23378. formats.add (new VSTPluginFormat());
  23379. #endif
  23380. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  23381. formats.add (new DirectXPluginFormat());
  23382. #endif
  23383. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  23384. formats.add (new LADSPAPluginFormat());
  23385. #endif
  23386. }
  23387. int AudioPluginFormatManager::getNumFormats() throw()
  23388. {
  23389. return formats.size();
  23390. }
  23391. AudioPluginFormat* AudioPluginFormatManager::getFormat (const int index) throw()
  23392. {
  23393. return formats [index];
  23394. }
  23395. void AudioPluginFormatManager::addFormat (AudioPluginFormat* const format) throw()
  23396. {
  23397. formats.add (format);
  23398. }
  23399. AudioPluginInstance* AudioPluginFormatManager::createPluginInstance (const PluginDescription& description,
  23400. String& errorMessage) const
  23401. {
  23402. AudioPluginInstance* result = 0;
  23403. for (int i = 0; i < formats.size(); ++i)
  23404. {
  23405. result = formats.getUnchecked(i)->createInstanceFromDescription (description);
  23406. if (result != 0)
  23407. break;
  23408. }
  23409. if (result == 0)
  23410. {
  23411. if (! doesPluginStillExist (description))
  23412. errorMessage = TRANS ("This plug-in file no longer exists");
  23413. else
  23414. errorMessage = TRANS ("This plug-in failed to load correctly");
  23415. }
  23416. return result;
  23417. }
  23418. bool AudioPluginFormatManager::doesPluginStillExist (const PluginDescription& description) const
  23419. {
  23420. for (int i = 0; i < formats.size(); ++i)
  23421. if (formats.getUnchecked(i)->getName() == description.pluginFormatName)
  23422. return formats.getUnchecked(i)->doesPluginStillExist (description);
  23423. return false;
  23424. }
  23425. END_JUCE_NAMESPACE
  23426. /*** End of inlined file: juce_AudioPluginFormatManager.cpp ***/
  23427. /*** Start of inlined file: juce_AudioPluginInstance.cpp ***/
  23428. #define JUCE_PLUGIN_HOST 1
  23429. BEGIN_JUCE_NAMESPACE
  23430. AudioPluginInstance::AudioPluginInstance()
  23431. {
  23432. }
  23433. AudioPluginInstance::~AudioPluginInstance()
  23434. {
  23435. }
  23436. END_JUCE_NAMESPACE
  23437. /*** End of inlined file: juce_AudioPluginInstance.cpp ***/
  23438. /*** Start of inlined file: juce_KnownPluginList.cpp ***/
  23439. BEGIN_JUCE_NAMESPACE
  23440. KnownPluginList::KnownPluginList()
  23441. {
  23442. }
  23443. KnownPluginList::~KnownPluginList()
  23444. {
  23445. }
  23446. void KnownPluginList::clear()
  23447. {
  23448. if (types.size() > 0)
  23449. {
  23450. types.clear();
  23451. sendChangeMessage (this);
  23452. }
  23453. }
  23454. PluginDescription* KnownPluginList::getTypeForFile (const String& fileOrIdentifier) const throw()
  23455. {
  23456. for (int i = 0; i < types.size(); ++i)
  23457. if (types.getUnchecked(i)->fileOrIdentifier == fileOrIdentifier)
  23458. return types.getUnchecked(i);
  23459. return 0;
  23460. }
  23461. PluginDescription* KnownPluginList::getTypeForIdentifierString (const String& identifierString) const throw()
  23462. {
  23463. for (int i = 0; i < types.size(); ++i)
  23464. if (types.getUnchecked(i)->createIdentifierString() == identifierString)
  23465. return types.getUnchecked(i);
  23466. return 0;
  23467. }
  23468. bool KnownPluginList::addType (const PluginDescription& type)
  23469. {
  23470. for (int i = types.size(); --i >= 0;)
  23471. {
  23472. if (types.getUnchecked(i)->isDuplicateOf (type))
  23473. {
  23474. // strange - found a duplicate plugin with different info..
  23475. jassert (types.getUnchecked(i)->name == type.name);
  23476. jassert (types.getUnchecked(i)->isInstrument == type.isInstrument);
  23477. *types.getUnchecked(i) = type;
  23478. return false;
  23479. }
  23480. }
  23481. types.add (new PluginDescription (type));
  23482. sendChangeMessage (this);
  23483. return true;
  23484. }
  23485. void KnownPluginList::removeType (const int index) throw()
  23486. {
  23487. types.remove (index);
  23488. sendChangeMessage (this);
  23489. }
  23490. static Time getFileModTime (const String& fileOrIdentifier) throw()
  23491. {
  23492. if (fileOrIdentifier.startsWithChar ('/')
  23493. || fileOrIdentifier[1] == ':')
  23494. {
  23495. return File (fileOrIdentifier).getLastModificationTime();
  23496. }
  23497. return Time (0);
  23498. }
  23499. static bool timesAreDifferent (const Time& t1, const Time& t2) throw()
  23500. {
  23501. return t1 != t2 || t1 == Time (0);
  23502. }
  23503. bool KnownPluginList::isListingUpToDate (const String& fileOrIdentifier) const throw()
  23504. {
  23505. if (getTypeForFile (fileOrIdentifier) == 0)
  23506. return false;
  23507. for (int i = types.size(); --i >= 0;)
  23508. {
  23509. const PluginDescription* const d = types.getUnchecked(i);
  23510. if (d->fileOrIdentifier == fileOrIdentifier
  23511. && timesAreDifferent (d->lastFileModTime, getFileModTime (fileOrIdentifier)))
  23512. {
  23513. return false;
  23514. }
  23515. }
  23516. return true;
  23517. }
  23518. bool KnownPluginList::scanAndAddFile (const String& fileOrIdentifier,
  23519. const bool dontRescanIfAlreadyInList,
  23520. OwnedArray <PluginDescription>& typesFound,
  23521. AudioPluginFormat& format)
  23522. {
  23523. bool addedOne = false;
  23524. if (dontRescanIfAlreadyInList
  23525. && getTypeForFile (fileOrIdentifier) != 0)
  23526. {
  23527. bool needsRescanning = false;
  23528. for (int i = types.size(); --i >= 0;)
  23529. {
  23530. const PluginDescription* const d = types.getUnchecked(i);
  23531. if (d->fileOrIdentifier == fileOrIdentifier)
  23532. {
  23533. if (timesAreDifferent (d->lastFileModTime, getFileModTime (fileOrIdentifier)))
  23534. needsRescanning = true;
  23535. else
  23536. typesFound.add (new PluginDescription (*d));
  23537. }
  23538. }
  23539. if (! needsRescanning)
  23540. return false;
  23541. }
  23542. OwnedArray <PluginDescription> found;
  23543. format.findAllTypesForFile (found, fileOrIdentifier);
  23544. for (int i = 0; i < found.size(); ++i)
  23545. {
  23546. PluginDescription* const desc = found.getUnchecked(i);
  23547. jassert (desc != 0);
  23548. if (addType (*desc))
  23549. addedOne = true;
  23550. typesFound.add (new PluginDescription (*desc));
  23551. }
  23552. return addedOne;
  23553. }
  23554. void KnownPluginList::scanAndAddDragAndDroppedFiles (const StringArray& files,
  23555. OwnedArray <PluginDescription>& typesFound)
  23556. {
  23557. for (int i = 0; i < files.size(); ++i)
  23558. {
  23559. bool loaded = false;
  23560. for (int j = 0; j < AudioPluginFormatManager::getInstance()->getNumFormats(); ++j)
  23561. {
  23562. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (j);
  23563. if (scanAndAddFile (files[i], true, typesFound, *format))
  23564. loaded = true;
  23565. }
  23566. if (! loaded)
  23567. {
  23568. const File f (files[i]);
  23569. if (f.isDirectory())
  23570. {
  23571. StringArray s;
  23572. {
  23573. Array<File> subFiles;
  23574. f.findChildFiles (subFiles, File::findFilesAndDirectories, false);
  23575. for (int j = 0; j < subFiles.size(); ++j)
  23576. s.add (subFiles.getReference(j).getFullPathName());
  23577. }
  23578. scanAndAddDragAndDroppedFiles (s, typesFound);
  23579. }
  23580. }
  23581. }
  23582. }
  23583. class PluginSorter
  23584. {
  23585. public:
  23586. KnownPluginList::SortMethod method;
  23587. PluginSorter() throw() {}
  23588. int compareElements (const PluginDescription* const first,
  23589. const PluginDescription* const second) const throw()
  23590. {
  23591. int diff = 0;
  23592. if (method == KnownPluginList::sortByCategory)
  23593. diff = first->category.compareLexicographically (second->category);
  23594. else if (method == KnownPluginList::sortByManufacturer)
  23595. diff = first->manufacturerName.compareLexicographically (second->manufacturerName);
  23596. else if (method == KnownPluginList::sortByFileSystemLocation)
  23597. diff = first->fileOrIdentifier.replaceCharacter ('\\', '/')
  23598. .upToLastOccurrenceOf ("/", false, false)
  23599. .compare (second->fileOrIdentifier.replaceCharacter ('\\', '/')
  23600. .upToLastOccurrenceOf ("/", false, false));
  23601. if (diff == 0)
  23602. diff = first->name.compareLexicographically (second->name);
  23603. return diff;
  23604. }
  23605. };
  23606. void KnownPluginList::sort (const SortMethod method)
  23607. {
  23608. if (method != defaultOrder)
  23609. {
  23610. PluginSorter sorter;
  23611. sorter.method = method;
  23612. types.sort (sorter, true);
  23613. sendChangeMessage (this);
  23614. }
  23615. }
  23616. XmlElement* KnownPluginList::createXml() const
  23617. {
  23618. XmlElement* const e = new XmlElement ("KNOWNPLUGINS");
  23619. for (int i = 0; i < types.size(); ++i)
  23620. e->addChildElement (types.getUnchecked(i)->createXml());
  23621. return e;
  23622. }
  23623. void KnownPluginList::recreateFromXml (const XmlElement& xml)
  23624. {
  23625. clear();
  23626. if (xml.hasTagName ("KNOWNPLUGINS"))
  23627. {
  23628. forEachXmlChildElement (xml, e)
  23629. {
  23630. PluginDescription info;
  23631. if (info.loadFromXml (*e))
  23632. addType (info);
  23633. }
  23634. }
  23635. }
  23636. const int menuIdBase = 0x324503f4;
  23637. // This is used to turn a bunch of paths into a nested menu structure.
  23638. struct PluginFilesystemTree
  23639. {
  23640. private:
  23641. String folder;
  23642. OwnedArray <PluginFilesystemTree> subFolders;
  23643. Array <PluginDescription*> plugins;
  23644. void addPlugin (PluginDescription* const pd, const String& path)
  23645. {
  23646. if (path.isEmpty())
  23647. {
  23648. plugins.add (pd);
  23649. }
  23650. else
  23651. {
  23652. const String firstSubFolder (path.upToFirstOccurrenceOf ("/", false, false));
  23653. const String remainingPath (path.fromFirstOccurrenceOf ("/", false, false));
  23654. for (int i = subFolders.size(); --i >= 0;)
  23655. {
  23656. if (subFolders.getUnchecked(i)->folder.equalsIgnoreCase (firstSubFolder))
  23657. {
  23658. subFolders.getUnchecked(i)->addPlugin (pd, remainingPath);
  23659. return;
  23660. }
  23661. }
  23662. PluginFilesystemTree* const newFolder = new PluginFilesystemTree();
  23663. newFolder->folder = firstSubFolder;
  23664. subFolders.add (newFolder);
  23665. newFolder->addPlugin (pd, remainingPath);
  23666. }
  23667. }
  23668. // removes any deeply nested folders that don't contain any actual plugins
  23669. void optimise()
  23670. {
  23671. for (int i = subFolders.size(); --i >= 0;)
  23672. {
  23673. PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  23674. sub->optimise();
  23675. if (sub->plugins.size() == 0)
  23676. {
  23677. for (int j = 0; j < sub->subFolders.size(); ++j)
  23678. subFolders.add (sub->subFolders.getUnchecked(j));
  23679. sub->subFolders.clear (false);
  23680. subFolders.remove (i);
  23681. }
  23682. }
  23683. }
  23684. public:
  23685. void buildTree (const Array <PluginDescription*>& allPlugins)
  23686. {
  23687. for (int i = 0; i < allPlugins.size(); ++i)
  23688. {
  23689. String path (allPlugins.getUnchecked(i)
  23690. ->fileOrIdentifier.replaceCharacter ('\\', '/')
  23691. .upToLastOccurrenceOf ("/", false, false));
  23692. if (path.substring (1, 2) == ":")
  23693. path = path.substring (2);
  23694. addPlugin (allPlugins.getUnchecked(i), path);
  23695. }
  23696. optimise();
  23697. }
  23698. void addToMenu (PopupMenu& m, const OwnedArray <PluginDescription>& allPlugins) const
  23699. {
  23700. int i;
  23701. for (i = 0; i < subFolders.size(); ++i)
  23702. {
  23703. const PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  23704. PopupMenu subMenu;
  23705. sub->addToMenu (subMenu, allPlugins);
  23706. #if JUCE_MAC
  23707. // avoid the special AU formatting nonsense on Mac..
  23708. m.addSubMenu (sub->folder.fromFirstOccurrenceOf (":", false, false), subMenu);
  23709. #else
  23710. m.addSubMenu (sub->folder, subMenu);
  23711. #endif
  23712. }
  23713. for (i = 0; i < plugins.size(); ++i)
  23714. {
  23715. PluginDescription* const plugin = plugins.getUnchecked(i);
  23716. m.addItem (allPlugins.indexOf (plugin) + menuIdBase,
  23717. plugin->name, true, false);
  23718. }
  23719. }
  23720. };
  23721. void KnownPluginList::addToMenu (PopupMenu& menu, const SortMethod sortMethod) const
  23722. {
  23723. Array <PluginDescription*> sorted;
  23724. {
  23725. PluginSorter sorter;
  23726. sorter.method = sortMethod;
  23727. for (int i = 0; i < types.size(); ++i)
  23728. sorted.addSorted (sorter, types.getUnchecked(i));
  23729. }
  23730. if (sortMethod == sortByCategory
  23731. || sortMethod == sortByManufacturer)
  23732. {
  23733. String lastSubMenuName;
  23734. PopupMenu sub;
  23735. for (int i = 0; i < sorted.size(); ++i)
  23736. {
  23737. const PluginDescription* const pd = sorted.getUnchecked(i);
  23738. String thisSubMenuName (sortMethod == sortByCategory ? pd->category
  23739. : pd->manufacturerName);
  23740. if (! thisSubMenuName.containsNonWhitespaceChars())
  23741. thisSubMenuName = "Other";
  23742. if (thisSubMenuName != lastSubMenuName)
  23743. {
  23744. if (sub.getNumItems() > 0)
  23745. {
  23746. menu.addSubMenu (lastSubMenuName, sub);
  23747. sub.clear();
  23748. }
  23749. lastSubMenuName = thisSubMenuName;
  23750. }
  23751. sub.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  23752. }
  23753. if (sub.getNumItems() > 0)
  23754. menu.addSubMenu (lastSubMenuName, sub);
  23755. }
  23756. else if (sortMethod == sortByFileSystemLocation)
  23757. {
  23758. PluginFilesystemTree root;
  23759. root.buildTree (sorted);
  23760. root.addToMenu (menu, types);
  23761. }
  23762. else
  23763. {
  23764. for (int i = 0; i < sorted.size(); ++i)
  23765. {
  23766. const PluginDescription* const pd = sorted.getUnchecked(i);
  23767. menu.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  23768. }
  23769. }
  23770. }
  23771. int KnownPluginList::getIndexChosenByMenu (const int menuResultCode) const
  23772. {
  23773. const int i = menuResultCode - menuIdBase;
  23774. return (((unsigned int) i) < (unsigned int) types.size()) ? i : -1;
  23775. }
  23776. END_JUCE_NAMESPACE
  23777. /*** End of inlined file: juce_KnownPluginList.cpp ***/
  23778. /*** Start of inlined file: juce_PluginDescription.cpp ***/
  23779. BEGIN_JUCE_NAMESPACE
  23780. PluginDescription::PluginDescription() throw()
  23781. : uid (0),
  23782. isInstrument (false),
  23783. numInputChannels (0),
  23784. numOutputChannels (0)
  23785. {
  23786. }
  23787. PluginDescription::~PluginDescription() throw()
  23788. {
  23789. }
  23790. PluginDescription::PluginDescription (const PluginDescription& other) throw()
  23791. : name (other.name),
  23792. pluginFormatName (other.pluginFormatName),
  23793. category (other.category),
  23794. manufacturerName (other.manufacturerName),
  23795. version (other.version),
  23796. fileOrIdentifier (other.fileOrIdentifier),
  23797. lastFileModTime (other.lastFileModTime),
  23798. uid (other.uid),
  23799. isInstrument (other.isInstrument),
  23800. numInputChannels (other.numInputChannels),
  23801. numOutputChannels (other.numOutputChannels)
  23802. {
  23803. }
  23804. PluginDescription& PluginDescription::operator= (const PluginDescription& other) throw()
  23805. {
  23806. name = other.name;
  23807. pluginFormatName = other.pluginFormatName;
  23808. category = other.category;
  23809. manufacturerName = other.manufacturerName;
  23810. version = other.version;
  23811. fileOrIdentifier = other.fileOrIdentifier;
  23812. uid = other.uid;
  23813. isInstrument = other.isInstrument;
  23814. lastFileModTime = other.lastFileModTime;
  23815. numInputChannels = other.numInputChannels;
  23816. numOutputChannels = other.numOutputChannels;
  23817. return *this;
  23818. }
  23819. bool PluginDescription::isDuplicateOf (const PluginDescription& other) const
  23820. {
  23821. return fileOrIdentifier == other.fileOrIdentifier
  23822. && uid == other.uid;
  23823. }
  23824. const String PluginDescription::createIdentifierString() const throw()
  23825. {
  23826. return pluginFormatName
  23827. + "-" + name
  23828. + "-" + String::toHexString (fileOrIdentifier.hashCode())
  23829. + "-" + String::toHexString (uid);
  23830. }
  23831. XmlElement* PluginDescription::createXml() const
  23832. {
  23833. XmlElement* const e = new XmlElement ("PLUGIN");
  23834. e->setAttribute ("name", name);
  23835. e->setAttribute ("format", pluginFormatName);
  23836. e->setAttribute ("category", category);
  23837. e->setAttribute ("manufacturer", manufacturerName);
  23838. e->setAttribute ("version", version);
  23839. e->setAttribute ("file", fileOrIdentifier);
  23840. e->setAttribute ("uid", String::toHexString (uid));
  23841. e->setAttribute ("isInstrument", isInstrument);
  23842. e->setAttribute ("fileTime", String::toHexString (lastFileModTime.toMilliseconds()));
  23843. e->setAttribute ("numInputs", numInputChannels);
  23844. e->setAttribute ("numOutputs", numOutputChannels);
  23845. return e;
  23846. }
  23847. bool PluginDescription::loadFromXml (const XmlElement& xml)
  23848. {
  23849. if (xml.hasTagName ("PLUGIN"))
  23850. {
  23851. name = xml.getStringAttribute ("name");
  23852. pluginFormatName = xml.getStringAttribute ("format");
  23853. category = xml.getStringAttribute ("category");
  23854. manufacturerName = xml.getStringAttribute ("manufacturer");
  23855. version = xml.getStringAttribute ("version");
  23856. fileOrIdentifier = xml.getStringAttribute ("file");
  23857. uid = xml.getStringAttribute ("uid").getHexValue32();
  23858. isInstrument = xml.getBoolAttribute ("isInstrument", false);
  23859. lastFileModTime = Time (xml.getStringAttribute ("fileTime").getHexValue64());
  23860. numInputChannels = xml.getIntAttribute ("numInputs");
  23861. numOutputChannels = xml.getIntAttribute ("numOutputs");
  23862. return true;
  23863. }
  23864. return false;
  23865. }
  23866. END_JUCE_NAMESPACE
  23867. /*** End of inlined file: juce_PluginDescription.cpp ***/
  23868. /*** Start of inlined file: juce_PluginDirectoryScanner.cpp ***/
  23869. BEGIN_JUCE_NAMESPACE
  23870. PluginDirectoryScanner::PluginDirectoryScanner (KnownPluginList& listToAddTo,
  23871. AudioPluginFormat& formatToLookFor,
  23872. FileSearchPath directoriesToSearch,
  23873. const bool recursive,
  23874. const File& deadMansPedalFile_)
  23875. : list (listToAddTo),
  23876. format (formatToLookFor),
  23877. deadMansPedalFile (deadMansPedalFile_),
  23878. nextIndex (0),
  23879. progress (0)
  23880. {
  23881. directoriesToSearch.removeRedundantPaths();
  23882. filesOrIdentifiersToScan = format.searchPathsForPlugins (directoriesToSearch, recursive);
  23883. // If any plugins have crashed recently when being loaded, move them to the
  23884. // end of the list to give the others a chance to load correctly..
  23885. const StringArray crashedPlugins (getDeadMansPedalFile());
  23886. for (int i = 0; i < crashedPlugins.size(); ++i)
  23887. {
  23888. const String f = crashedPlugins[i];
  23889. for (int j = filesOrIdentifiersToScan.size(); --j >= 0;)
  23890. if (f == filesOrIdentifiersToScan[j])
  23891. filesOrIdentifiersToScan.move (j, -1);
  23892. }
  23893. }
  23894. PluginDirectoryScanner::~PluginDirectoryScanner()
  23895. {
  23896. }
  23897. const String PluginDirectoryScanner::getNextPluginFileThatWillBeScanned() const throw()
  23898. {
  23899. return format.getNameOfPluginFromIdentifier (filesOrIdentifiersToScan [nextIndex]);
  23900. }
  23901. bool PluginDirectoryScanner::scanNextFile (const bool dontRescanIfAlreadyInList)
  23902. {
  23903. String file (filesOrIdentifiersToScan [nextIndex]);
  23904. if (file.isNotEmpty())
  23905. {
  23906. if (! list.isListingUpToDate (file))
  23907. {
  23908. OwnedArray <PluginDescription> typesFound;
  23909. // Add this plugin to the end of the dead-man's pedal list in case it crashes...
  23910. StringArray crashedPlugins (getDeadMansPedalFile());
  23911. crashedPlugins.removeString (file);
  23912. crashedPlugins.add (file);
  23913. setDeadMansPedalFile (crashedPlugins);
  23914. list.scanAndAddFile (file,
  23915. dontRescanIfAlreadyInList,
  23916. typesFound,
  23917. format);
  23918. // Managed to load without crashing, so remove it from the dead-man's-pedal..
  23919. crashedPlugins.removeString (file);
  23920. setDeadMansPedalFile (crashedPlugins);
  23921. if (typesFound.size() == 0)
  23922. failedFiles.add (file);
  23923. }
  23924. ++nextIndex;
  23925. progress = nextIndex / (float) filesOrIdentifiersToScan.size();
  23926. }
  23927. return nextIndex < filesOrIdentifiersToScan.size();
  23928. }
  23929. const StringArray PluginDirectoryScanner::getDeadMansPedalFile() throw()
  23930. {
  23931. StringArray lines;
  23932. if (deadMansPedalFile != File::nonexistent)
  23933. {
  23934. lines.addLines (deadMansPedalFile.loadFileAsString());
  23935. lines.removeEmptyStrings();
  23936. }
  23937. return lines;
  23938. }
  23939. void PluginDirectoryScanner::setDeadMansPedalFile (const StringArray& newContents) throw()
  23940. {
  23941. if (deadMansPedalFile != File::nonexistent)
  23942. deadMansPedalFile.replaceWithText (newContents.joinIntoString ("\n"), true, true);
  23943. }
  23944. END_JUCE_NAMESPACE
  23945. /*** End of inlined file: juce_PluginDirectoryScanner.cpp ***/
  23946. /*** Start of inlined file: juce_PluginListComponent.cpp ***/
  23947. BEGIN_JUCE_NAMESPACE
  23948. PluginListComponent::PluginListComponent (KnownPluginList& listToEdit,
  23949. const File& deadMansPedalFile_,
  23950. PropertiesFile* const propertiesToUse_)
  23951. : list (listToEdit),
  23952. deadMansPedalFile (deadMansPedalFile_),
  23953. propertiesToUse (propertiesToUse_)
  23954. {
  23955. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  23956. addAndMakeVisible (optionsButton = new TextButton ("Options..."));
  23957. optionsButton->addButtonListener (this);
  23958. optionsButton->setTriggeredOnMouseDown (true);
  23959. setSize (400, 600);
  23960. list.addChangeListener (this);
  23961. }
  23962. PluginListComponent::~PluginListComponent()
  23963. {
  23964. list.removeChangeListener (this);
  23965. deleteAllChildren();
  23966. }
  23967. void PluginListComponent::resized()
  23968. {
  23969. listBox->setBounds (0, 0, getWidth(), getHeight() - 30);
  23970. optionsButton->changeWidthToFitText (24);
  23971. optionsButton->setTopLeftPosition (8, getHeight() - 28);
  23972. }
  23973. void PluginListComponent::changeListenerCallback (void*)
  23974. {
  23975. listBox->updateContent();
  23976. listBox->repaint();
  23977. }
  23978. int PluginListComponent::getNumRows()
  23979. {
  23980. return list.getNumTypes();
  23981. }
  23982. void PluginListComponent::paintListBoxItem (int row,
  23983. Graphics& g,
  23984. int width, int height,
  23985. bool rowIsSelected)
  23986. {
  23987. if (rowIsSelected)
  23988. g.fillAll (findColour (TextEditor::highlightColourId));
  23989. const PluginDescription* const pd = list.getType (row);
  23990. if (pd != 0)
  23991. {
  23992. GlyphArrangement ga;
  23993. ga.addCurtailedLineOfText (Font (height * 0.7f, Font::bold), pd->name, 8.0f, height * 0.8f, width - 10.0f, true);
  23994. g.setColour (Colours::black);
  23995. ga.draw (g);
  23996. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  23997. String desc;
  23998. desc << pd->pluginFormatName
  23999. << (pd->isInstrument ? " instrument" : " effect")
  24000. << " - "
  24001. << pd->numInputChannels << (pd->numInputChannels == 1 ? " in" : " ins")
  24002. << " / "
  24003. << pd->numOutputChannels << (pd->numOutputChannels == 1 ? " out" : " outs");
  24004. if (pd->manufacturerName.isNotEmpty())
  24005. desc << " - " << pd->manufacturerName;
  24006. if (pd->version.isNotEmpty())
  24007. desc << " - " << pd->version;
  24008. if (pd->category.isNotEmpty())
  24009. desc << " - category: '" << pd->category << '\'';
  24010. g.setColour (Colours::grey);
  24011. ga.clear();
  24012. ga.addCurtailedLineOfText (Font (height * 0.6f), desc, bb.getRight() + 10.0f, height * 0.8f, width - bb.getRight() - 12.0f, true);
  24013. ga.draw (g);
  24014. }
  24015. }
  24016. void PluginListComponent::deleteKeyPressed (int lastRowSelected)
  24017. {
  24018. list.removeType (lastRowSelected);
  24019. }
  24020. void PluginListComponent::buttonClicked (Button* b)
  24021. {
  24022. if (optionsButton == b)
  24023. {
  24024. PopupMenu menu;
  24025. menu.addItem (1, TRANS("Clear list"));
  24026. menu.addItem (5, TRANS("Remove selected plugin from list"), listBox->getNumSelectedRows() > 0);
  24027. menu.addItem (6, TRANS("Show folder containing selected plugin"), listBox->getNumSelectedRows() > 0);
  24028. menu.addItem (7, TRANS("Remove any plugins whose files no longer exist"));
  24029. menu.addSeparator();
  24030. menu.addItem (2, TRANS("Sort alphabetically"));
  24031. menu.addItem (3, TRANS("Sort by category"));
  24032. menu.addItem (4, TRANS("Sort by manufacturer"));
  24033. menu.addSeparator();
  24034. for (int i = 0; i < AudioPluginFormatManager::getInstance()->getNumFormats(); ++i)
  24035. {
  24036. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (i);
  24037. if (format->getDefaultLocationsToSearch().getNumPaths() > 0)
  24038. menu.addItem (10 + i, "Scan for new or updated " + format->getName() + " plugins...");
  24039. }
  24040. const int r = menu.showAt (optionsButton);
  24041. if (r == 1)
  24042. {
  24043. list.clear();
  24044. }
  24045. else if (r == 2)
  24046. {
  24047. list.sort (KnownPluginList::sortAlphabetically);
  24048. }
  24049. else if (r == 3)
  24050. {
  24051. list.sort (KnownPluginList::sortByCategory);
  24052. }
  24053. else if (r == 4)
  24054. {
  24055. list.sort (KnownPluginList::sortByManufacturer);
  24056. }
  24057. else if (r == 5)
  24058. {
  24059. const SparseSet <int> selected (listBox->getSelectedRows());
  24060. for (int i = list.getNumTypes(); --i >= 0;)
  24061. if (selected.contains (i))
  24062. list.removeType (i);
  24063. }
  24064. else if (r == 6)
  24065. {
  24066. const PluginDescription* const desc = list.getType (listBox->getSelectedRow());
  24067. if (desc != 0)
  24068. {
  24069. if (File (desc->fileOrIdentifier).existsAsFile())
  24070. File (desc->fileOrIdentifier).getParentDirectory().startAsProcess();
  24071. }
  24072. }
  24073. else if (r == 7)
  24074. {
  24075. for (int i = list.getNumTypes(); --i >= 0;)
  24076. {
  24077. if (! AudioPluginFormatManager::getInstance()->doesPluginStillExist (*list.getType (i)))
  24078. {
  24079. list.removeType (i);
  24080. }
  24081. }
  24082. }
  24083. else if (r != 0)
  24084. {
  24085. typeToScan = r - 10;
  24086. startTimer (1);
  24087. }
  24088. }
  24089. }
  24090. void PluginListComponent::timerCallback()
  24091. {
  24092. stopTimer();
  24093. scanFor (AudioPluginFormatManager::getInstance()->getFormat (typeToScan));
  24094. }
  24095. bool PluginListComponent::isInterestedInFileDrag (const StringArray& /*files*/)
  24096. {
  24097. return true;
  24098. }
  24099. void PluginListComponent::filesDropped (const StringArray& files, int, int)
  24100. {
  24101. OwnedArray <PluginDescription> typesFound;
  24102. list.scanAndAddDragAndDroppedFiles (files, typesFound);
  24103. }
  24104. void PluginListComponent::scanFor (AudioPluginFormat* format)
  24105. {
  24106. if (format == 0)
  24107. return;
  24108. FileSearchPath path (format->getDefaultLocationsToSearch());
  24109. if (propertiesToUse != 0)
  24110. path = propertiesToUse->getValue ("lastPluginScanPath_" + format->getName(), path.toString());
  24111. {
  24112. AlertWindow aw (TRANS("Select folders to scan..."), String::empty, AlertWindow::NoIcon);
  24113. FileSearchPathListComponent pathList;
  24114. pathList.setSize (500, 300);
  24115. pathList.setPath (path);
  24116. aw.addCustomComponent (&pathList);
  24117. aw.addButton (TRANS("Scan"), 1, KeyPress::returnKey);
  24118. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  24119. if (aw.runModalLoop() == 0)
  24120. return;
  24121. path = pathList.getPath();
  24122. }
  24123. if (propertiesToUse != 0)
  24124. {
  24125. propertiesToUse->setValue ("lastPluginScanPath_" + format->getName(), path.toString());
  24126. propertiesToUse->saveIfNeeded();
  24127. }
  24128. double progress = 0.0;
  24129. AlertWindow aw (TRANS("Scanning for plugins..."),
  24130. TRANS("Searching for all possible plugin files..."), AlertWindow::NoIcon);
  24131. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  24132. aw.addProgressBarComponent (progress);
  24133. aw.enterModalState();
  24134. MessageManager::getInstance()->runDispatchLoopUntil (300);
  24135. PluginDirectoryScanner scanner (list, *format, path, true, deadMansPedalFile);
  24136. for (;;)
  24137. {
  24138. aw.setMessage (TRANS("Testing:\n\n")
  24139. + scanner.getNextPluginFileThatWillBeScanned());
  24140. MessageManager::getInstance()->runDispatchLoopUntil (20);
  24141. if (! scanner.scanNextFile (true))
  24142. break;
  24143. if (! aw.isCurrentlyModal())
  24144. break;
  24145. progress = scanner.getProgress();
  24146. }
  24147. if (scanner.getFailedFiles().size() > 0)
  24148. {
  24149. StringArray shortNames;
  24150. for (int i = 0; i < scanner.getFailedFiles().size(); ++i)
  24151. shortNames.add (File (scanner.getFailedFiles()[i]).getFileName());
  24152. AlertWindow::showMessageBox (AlertWindow::InfoIcon,
  24153. TRANS("Scan complete"),
  24154. TRANS("Note that the following files appeared to be plugin files, but failed to load correctly:\n\n")
  24155. + shortNames.joinIntoString (", "));
  24156. }
  24157. }
  24158. END_JUCE_NAMESPACE
  24159. /*** End of inlined file: juce_PluginListComponent.cpp ***/
  24160. /*** Start of inlined file: juce_AudioUnitPluginFormat.mm ***/
  24161. #if JUCE_PLUGINHOST_AU && ! (JUCE_LINUX || JUCE_WINDOWS)
  24162. #include <AudioUnit/AudioUnit.h>
  24163. #include <AudioUnit/AUCocoaUIView.h>
  24164. #include <CoreAudioKit/AUGenericView.h>
  24165. #if JUCE_SUPPORT_CARBON
  24166. #include <AudioToolbox/AudioUnitUtilities.h>
  24167. #include <AudioUnit/AudioUnitCarbonView.h>
  24168. #endif
  24169. BEGIN_JUCE_NAMESPACE
  24170. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  24171. #endif
  24172. #if JUCE_MAC
  24173. // Change this to disable logging of various activities
  24174. #ifndef AU_LOGGING
  24175. #define AU_LOGGING 1
  24176. #endif
  24177. #if AU_LOGGING
  24178. #define log(a) Logger::writeToLog(a);
  24179. #else
  24180. #define log(a)
  24181. #endif
  24182. namespace AudioUnitFormatHelpers
  24183. {
  24184. static int insideCallback = 0;
  24185. static const String osTypeToString (OSType type)
  24186. {
  24187. char s[4];
  24188. s[0] = (char) (((uint32) type) >> 24);
  24189. s[1] = (char) (((uint32) type) >> 16);
  24190. s[2] = (char) (((uint32) type) >> 8);
  24191. s[3] = (char) ((uint32) type);
  24192. return String (s, 4);
  24193. }
  24194. static OSType stringToOSType (const String& s1)
  24195. {
  24196. const String s (s1 + " ");
  24197. return (((OSType) (unsigned char) s[0]) << 24)
  24198. | (((OSType) (unsigned char) s[1]) << 16)
  24199. | (((OSType) (unsigned char) s[2]) << 8)
  24200. | ((OSType) (unsigned char) s[3]);
  24201. }
  24202. static const char* auIdentifierPrefix = "AudioUnit:";
  24203. static const String createAUPluginIdentifier (const ComponentDescription& desc)
  24204. {
  24205. jassert (osTypeToString ('abcd') == "abcd"); // agh, must have got the endianness wrong..
  24206. jassert (stringToOSType ("abcd") == (OSType) 'abcd'); // ditto
  24207. String s (auIdentifierPrefix);
  24208. if (desc.componentType == kAudioUnitType_MusicDevice)
  24209. s << "Synths/";
  24210. else if (desc.componentType == kAudioUnitType_MusicEffect
  24211. || desc.componentType == kAudioUnitType_Effect)
  24212. s << "Effects/";
  24213. else if (desc.componentType == kAudioUnitType_Generator)
  24214. s << "Generators/";
  24215. else if (desc.componentType == kAudioUnitType_Panner)
  24216. s << "Panners/";
  24217. s << osTypeToString (desc.componentType) << ","
  24218. << osTypeToString (desc.componentSubType) << ","
  24219. << osTypeToString (desc.componentManufacturer);
  24220. return s;
  24221. }
  24222. static void getAUDetails (ComponentRecord* comp, String& name, String& manufacturer)
  24223. {
  24224. Handle componentNameHandle = NewHandle (sizeof (void*));
  24225. Handle componentInfoHandle = NewHandle (sizeof (void*));
  24226. if (componentNameHandle != 0 && componentInfoHandle != 0)
  24227. {
  24228. ComponentDescription desc;
  24229. if (GetComponentInfo (comp, &desc, componentNameHandle, componentInfoHandle, 0) == noErr)
  24230. {
  24231. ConstStr255Param nameString = (ConstStr255Param) (*componentNameHandle);
  24232. ConstStr255Param infoString = (ConstStr255Param) (*componentInfoHandle);
  24233. if (nameString != 0 && nameString[0] != 0)
  24234. {
  24235. const String all ((const char*) nameString + 1, nameString[0]);
  24236. DBG ("name: "+ all);
  24237. manufacturer = all.upToFirstOccurrenceOf (":", false, false).trim();
  24238. name = all.fromFirstOccurrenceOf (":", false, false).trim();
  24239. }
  24240. if (infoString != 0 && infoString[0] != 0)
  24241. {
  24242. DBG ("info: " + String ((const char*) infoString + 1, infoString[0]));
  24243. }
  24244. if (name.isEmpty())
  24245. name = "<Unknown>";
  24246. }
  24247. DisposeHandle (componentNameHandle);
  24248. DisposeHandle (componentInfoHandle);
  24249. }
  24250. }
  24251. static bool getComponentDescFromIdentifier (const String& fileOrIdentifier, ComponentDescription& desc,
  24252. String& name, String& version, String& manufacturer)
  24253. {
  24254. zerostruct (desc);
  24255. if (fileOrIdentifier.startsWithIgnoreCase (auIdentifierPrefix))
  24256. {
  24257. String s (fileOrIdentifier.substring (jmax (fileOrIdentifier.lastIndexOfChar (':'),
  24258. fileOrIdentifier.lastIndexOfChar ('/')) + 1));
  24259. StringArray tokens;
  24260. tokens.addTokens (s, ",", String::empty);
  24261. tokens.trim();
  24262. tokens.removeEmptyStrings();
  24263. if (tokens.size() == 3)
  24264. {
  24265. desc.componentType = stringToOSType (tokens[0]);
  24266. desc.componentSubType = stringToOSType (tokens[1]);
  24267. desc.componentManufacturer = stringToOSType (tokens[2]);
  24268. ComponentRecord* comp = FindNextComponent (0, &desc);
  24269. if (comp != 0)
  24270. {
  24271. getAUDetails (comp, name, manufacturer);
  24272. return true;
  24273. }
  24274. }
  24275. }
  24276. return false;
  24277. }
  24278. }
  24279. class AudioUnitPluginWindowCarbon;
  24280. class AudioUnitPluginWindowCocoa;
  24281. class AudioUnitPluginInstance : public AudioPluginInstance
  24282. {
  24283. public:
  24284. ~AudioUnitPluginInstance();
  24285. // AudioPluginInstance methods:
  24286. void fillInPluginDescription (PluginDescription& desc) const
  24287. {
  24288. desc.name = pluginName;
  24289. desc.fileOrIdentifier = AudioUnitFormatHelpers::createAUPluginIdentifier (componentDesc);
  24290. desc.uid = ((int) componentDesc.componentType)
  24291. ^ ((int) componentDesc.componentSubType)
  24292. ^ ((int) componentDesc.componentManufacturer);
  24293. desc.lastFileModTime = 0;
  24294. desc.pluginFormatName = "AudioUnit";
  24295. desc.category = getCategory();
  24296. desc.manufacturerName = manufacturer;
  24297. desc.version = version;
  24298. desc.numInputChannels = getNumInputChannels();
  24299. desc.numOutputChannels = getNumOutputChannels();
  24300. desc.isInstrument = (componentDesc.componentType == kAudioUnitType_MusicDevice);
  24301. }
  24302. const String getName() const { return pluginName; }
  24303. bool acceptsMidi() const { return wantsMidiMessages; }
  24304. bool producesMidi() const { return false; }
  24305. // AudioProcessor methods:
  24306. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  24307. void releaseResources();
  24308. void processBlock (AudioSampleBuffer& buffer,
  24309. MidiBuffer& midiMessages);
  24310. AudioProcessorEditor* createEditor();
  24311. const String getInputChannelName (const int index) const;
  24312. bool isInputChannelStereoPair (int index) const;
  24313. const String getOutputChannelName (const int index) const;
  24314. bool isOutputChannelStereoPair (int index) const;
  24315. int getNumParameters();
  24316. float getParameter (int index);
  24317. void setParameter (int index, float newValue);
  24318. const String getParameterName (int index);
  24319. const String getParameterText (int index);
  24320. bool isParameterAutomatable (int index) const;
  24321. int getNumPrograms();
  24322. int getCurrentProgram();
  24323. void setCurrentProgram (int index);
  24324. const String getProgramName (int index);
  24325. void changeProgramName (int index, const String& newName);
  24326. void getStateInformation (MemoryBlock& destData);
  24327. void getCurrentProgramStateInformation (MemoryBlock& destData);
  24328. void setStateInformation (const void* data, int sizeInBytes);
  24329. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  24330. juce_UseDebuggingNewOperator
  24331. private:
  24332. friend class AudioUnitPluginWindowCarbon;
  24333. friend class AudioUnitPluginWindowCocoa;
  24334. friend class AudioUnitPluginFormat;
  24335. ComponentDescription componentDesc;
  24336. String pluginName, manufacturer, version;
  24337. String fileOrIdentifier;
  24338. CriticalSection lock;
  24339. bool initialised, wantsMidiMessages, wasPlaying;
  24340. HeapBlock <AudioBufferList> outputBufferList;
  24341. AudioTimeStamp timeStamp;
  24342. AudioSampleBuffer* currentBuffer;
  24343. AudioUnit audioUnit;
  24344. Array <int> parameterIds;
  24345. bool getComponentDescFromFile (const String& fileOrIdentifier);
  24346. void initialise();
  24347. OSStatus renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  24348. const AudioTimeStamp* inTimeStamp,
  24349. UInt32 inBusNumber,
  24350. UInt32 inNumberFrames,
  24351. AudioBufferList* ioData) const;
  24352. static OSStatus renderGetInputCallback (void* inRefCon,
  24353. AudioUnitRenderActionFlags* ioActionFlags,
  24354. const AudioTimeStamp* inTimeStamp,
  24355. UInt32 inBusNumber,
  24356. UInt32 inNumberFrames,
  24357. AudioBufferList* ioData)
  24358. {
  24359. return ((AudioUnitPluginInstance*) inRefCon)
  24360. ->renderGetInput (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  24361. }
  24362. OSStatus getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const;
  24363. OSStatus getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat, Float32* outTimeSig_Numerator,
  24364. UInt32* outTimeSig_Denominator, Float64* outCurrentMeasureDownBeat) const;
  24365. OSStatus getTransportState (Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  24366. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  24367. Float64* outCycleStartBeat, Float64* outCycleEndBeat);
  24368. static OSStatus getBeatAndTempoCallback (void* inHostUserData, Float64* outCurrentBeat, Float64* outCurrentTempo)
  24369. {
  24370. return ((AudioUnitPluginInstance*) inHostUserData)->getBeatAndTempo (outCurrentBeat, outCurrentTempo);
  24371. }
  24372. static OSStatus getMusicalTimeLocationCallback (void* inHostUserData, UInt32* outDeltaSampleOffsetToNextBeat,
  24373. Float32* outTimeSig_Numerator, UInt32* outTimeSig_Denominator,
  24374. Float64* outCurrentMeasureDownBeat)
  24375. {
  24376. return ((AudioUnitPluginInstance*) inHostUserData)
  24377. ->getMusicalTimeLocation (outDeltaSampleOffsetToNextBeat, outTimeSig_Numerator,
  24378. outTimeSig_Denominator, outCurrentMeasureDownBeat);
  24379. }
  24380. static OSStatus getTransportStateCallback (void* inHostUserData, Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  24381. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  24382. Float64* outCycleStartBeat, Float64* outCycleEndBeat)
  24383. {
  24384. return ((AudioUnitPluginInstance*) inHostUserData)
  24385. ->getTransportState (outIsPlaying, outTransportStateChanged,
  24386. outCurrentSampleInTimeLine, outIsCycling,
  24387. outCycleStartBeat, outCycleEndBeat);
  24388. }
  24389. void getNumChannels (int& numIns, int& numOuts)
  24390. {
  24391. numIns = 0;
  24392. numOuts = 0;
  24393. AUChannelInfo supportedChannels [128];
  24394. UInt32 supportedChannelsSize = sizeof (supportedChannels);
  24395. if (AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SupportedNumChannels, kAudioUnitScope_Global,
  24396. 0, supportedChannels, &supportedChannelsSize) == noErr
  24397. && supportedChannelsSize > 0)
  24398. {
  24399. for (int i = 0; i < supportedChannelsSize / sizeof (AUChannelInfo); ++i)
  24400. {
  24401. numIns = jmax (numIns, (int) supportedChannels[i].inChannels);
  24402. numOuts = jmax (numOuts, (int) supportedChannels[i].outChannels);
  24403. }
  24404. }
  24405. else
  24406. {
  24407. // (this really means the plugin will take any number of ins/outs as long
  24408. // as they are the same)
  24409. numIns = numOuts = 2;
  24410. }
  24411. }
  24412. const String getCategory() const;
  24413. AudioUnitPluginInstance (const String& fileOrIdentifier);
  24414. };
  24415. AudioUnitPluginInstance::AudioUnitPluginInstance (const String& fileOrIdentifier)
  24416. : fileOrIdentifier (fileOrIdentifier),
  24417. initialised (false),
  24418. wantsMidiMessages (false),
  24419. audioUnit (0),
  24420. currentBuffer (0)
  24421. {
  24422. using namespace AudioUnitFormatHelpers;
  24423. try
  24424. {
  24425. ++insideCallback;
  24426. log ("Opening AU: " + fileOrIdentifier);
  24427. if (getComponentDescFromFile (fileOrIdentifier))
  24428. {
  24429. ComponentRecord* const comp = FindNextComponent (0, &componentDesc);
  24430. if (comp != 0)
  24431. {
  24432. audioUnit = (AudioUnit) OpenComponent (comp);
  24433. wantsMidiMessages = componentDesc.componentType == kAudioUnitType_MusicDevice
  24434. || componentDesc.componentType == kAudioUnitType_MusicEffect;
  24435. }
  24436. }
  24437. --insideCallback;
  24438. }
  24439. catch (...)
  24440. {
  24441. --insideCallback;
  24442. }
  24443. }
  24444. AudioUnitPluginInstance::~AudioUnitPluginInstance()
  24445. {
  24446. const ScopedLock sl (lock);
  24447. jassert (AudioUnitFormatHelpers::insideCallback == 0);
  24448. if (audioUnit != 0)
  24449. {
  24450. AudioUnitUninitialize (audioUnit);
  24451. CloseComponent (audioUnit);
  24452. audioUnit = 0;
  24453. }
  24454. }
  24455. bool AudioUnitPluginInstance::getComponentDescFromFile (const String& fileOrIdentifier)
  24456. {
  24457. zerostruct (componentDesc);
  24458. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, componentDesc, pluginName, version, manufacturer))
  24459. return true;
  24460. const File file (fileOrIdentifier);
  24461. if (! file.hasFileExtension (".component"))
  24462. return false;
  24463. const char* const utf8 = fileOrIdentifier.toUTF8();
  24464. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  24465. strlen (utf8), file.isDirectory());
  24466. if (url != 0)
  24467. {
  24468. CFBundleRef bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  24469. CFRelease (url);
  24470. if (bundleRef != 0)
  24471. {
  24472. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  24473. if (name != 0 && CFGetTypeID (name) == CFStringGetTypeID())
  24474. pluginName = PlatformUtilities::cfStringToJuceString ((CFStringRef) name);
  24475. if (pluginName.isEmpty())
  24476. pluginName = file.getFileNameWithoutExtension();
  24477. CFTypeRef versionString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleVersion"));
  24478. if (versionString != 0 && CFGetTypeID (versionString) == CFStringGetTypeID())
  24479. version = PlatformUtilities::cfStringToJuceString ((CFStringRef) versionString);
  24480. CFTypeRef manuString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleGetInfoString"));
  24481. if (manuString != 0 && CFGetTypeID (manuString) == CFStringGetTypeID())
  24482. manufacturer = PlatformUtilities::cfStringToJuceString ((CFStringRef) manuString);
  24483. short resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  24484. UseResFile (resFileId);
  24485. for (int i = 1; i <= Count1Resources ('thng'); ++i)
  24486. {
  24487. Handle h = Get1IndResource ('thng', i);
  24488. if (h != 0)
  24489. {
  24490. HLock (h);
  24491. const uint32* const types = (const uint32*) *h;
  24492. if (types[0] == kAudioUnitType_MusicDevice
  24493. || types[0] == kAudioUnitType_MusicEffect
  24494. || types[0] == kAudioUnitType_Effect
  24495. || types[0] == kAudioUnitType_Generator
  24496. || types[0] == kAudioUnitType_Panner)
  24497. {
  24498. componentDesc.componentType = types[0];
  24499. componentDesc.componentSubType = types[1];
  24500. componentDesc.componentManufacturer = types[2];
  24501. break;
  24502. }
  24503. HUnlock (h);
  24504. ReleaseResource (h);
  24505. }
  24506. }
  24507. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  24508. CFRelease (bundleRef);
  24509. }
  24510. }
  24511. return componentDesc.componentType != 0 && componentDesc.componentSubType != 0;
  24512. }
  24513. void AudioUnitPluginInstance::initialise()
  24514. {
  24515. if (initialised || audioUnit == 0)
  24516. return;
  24517. log ("Initialising AU: " + pluginName);
  24518. parameterIds.clear();
  24519. {
  24520. UInt32 paramListSize = 0;
  24521. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  24522. 0, 0, &paramListSize);
  24523. if (paramListSize > 0)
  24524. {
  24525. parameterIds.insertMultiple (0, 0, paramListSize / sizeof (int));
  24526. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  24527. 0, &parameterIds.getReference(0), &paramListSize);
  24528. }
  24529. }
  24530. {
  24531. AURenderCallbackStruct info;
  24532. zerostruct (info);
  24533. info.inputProcRefCon = this;
  24534. info.inputProc = renderGetInputCallback;
  24535. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
  24536. 0, &info, sizeof (info));
  24537. }
  24538. {
  24539. HostCallbackInfo info;
  24540. zerostruct (info);
  24541. info.hostUserData = this;
  24542. info.beatAndTempoProc = getBeatAndTempoCallback;
  24543. info.musicalTimeLocationProc = getMusicalTimeLocationCallback;
  24544. info.transportStateProc = getTransportStateCallback;
  24545. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_HostCallbacks, kAudioUnitScope_Global,
  24546. 0, &info, sizeof (info));
  24547. }
  24548. int numIns, numOuts;
  24549. getNumChannels (numIns, numOuts);
  24550. setPlayConfigDetails (numIns, numOuts, 0, 0);
  24551. initialised = AudioUnitInitialize (audioUnit) == noErr;
  24552. setLatencySamples (0);
  24553. }
  24554. void AudioUnitPluginInstance::prepareToPlay (double sampleRate_,
  24555. int samplesPerBlockExpected)
  24556. {
  24557. if (audioUnit != 0)
  24558. {
  24559. Float64 sampleRateIn = 0, sampleRateOut = 0;
  24560. UInt32 sampleRateSize = sizeof (sampleRateIn);
  24561. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sampleRateIn, &sampleRateSize);
  24562. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sampleRateOut, &sampleRateSize);
  24563. if (sampleRateIn != sampleRate_ || sampleRateOut != sampleRate_)
  24564. {
  24565. if (initialised)
  24566. {
  24567. AudioUnitUninitialize (audioUnit);
  24568. initialised = false;
  24569. }
  24570. Float64 sr = sampleRate_;
  24571. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sr, sizeof (Float64));
  24572. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sr, sizeof (Float64));
  24573. }
  24574. }
  24575. initialise();
  24576. if (initialised)
  24577. {
  24578. int numIns, numOuts;
  24579. getNumChannels (numIns, numOuts);
  24580. setPlayConfigDetails (numIns, numOuts, sampleRate_, samplesPerBlockExpected);
  24581. Float64 latencySecs = 0.0;
  24582. UInt32 latencySize = sizeof (latencySecs);
  24583. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_Latency, kAudioUnitScope_Global,
  24584. 0, &latencySecs, &latencySize);
  24585. setLatencySamples (roundToInt (latencySecs * sampleRate_));
  24586. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  24587. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  24588. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  24589. AudioStreamBasicDescription stream;
  24590. zerostruct (stream);
  24591. stream.mSampleRate = sampleRate_;
  24592. stream.mFormatID = kAudioFormatLinearPCM;
  24593. stream.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved;
  24594. stream.mFramesPerPacket = 1;
  24595. stream.mBytesPerPacket = 4;
  24596. stream.mBytesPerFrame = 4;
  24597. stream.mBitsPerChannel = 32;
  24598. stream.mChannelsPerFrame = numIns;
  24599. OSStatus err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input,
  24600. 0, &stream, sizeof (stream));
  24601. stream.mChannelsPerFrame = numOuts;
  24602. err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output,
  24603. 0, &stream, sizeof (stream));
  24604. outputBufferList.calloc (sizeof (AudioBufferList) + sizeof (AudioBuffer) * (numOuts + 1), 1);
  24605. outputBufferList->mNumberBuffers = numOuts;
  24606. for (int i = numOuts; --i >= 0;)
  24607. outputBufferList->mBuffers[i].mNumberChannels = 1;
  24608. zerostruct (timeStamp);
  24609. timeStamp.mSampleTime = 0;
  24610. timeStamp.mHostTime = AudioGetCurrentHostTime();
  24611. timeStamp.mFlags = kAudioTimeStampSampleTimeValid | kAudioTimeStampHostTimeValid;
  24612. currentBuffer = 0;
  24613. wasPlaying = false;
  24614. }
  24615. }
  24616. void AudioUnitPluginInstance::releaseResources()
  24617. {
  24618. if (initialised)
  24619. {
  24620. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  24621. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  24622. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  24623. outputBufferList.free();
  24624. currentBuffer = 0;
  24625. }
  24626. }
  24627. OSStatus AudioUnitPluginInstance::renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  24628. const AudioTimeStamp* inTimeStamp,
  24629. UInt32 inBusNumber,
  24630. UInt32 inNumberFrames,
  24631. AudioBufferList* ioData) const
  24632. {
  24633. if (inBusNumber == 0
  24634. && currentBuffer != 0)
  24635. {
  24636. jassert (inNumberFrames == currentBuffer->getNumSamples()); // if this ever happens, might need to add extra handling
  24637. for (int i = 0; i < ioData->mNumberBuffers; ++i)
  24638. {
  24639. if (i < currentBuffer->getNumChannels())
  24640. {
  24641. memcpy (ioData->mBuffers[i].mData,
  24642. currentBuffer->getSampleData (i, 0),
  24643. sizeof (float) * inNumberFrames);
  24644. }
  24645. else
  24646. {
  24647. zeromem (ioData->mBuffers[i].mData, sizeof (float) * inNumberFrames);
  24648. }
  24649. }
  24650. }
  24651. return noErr;
  24652. }
  24653. void AudioUnitPluginInstance::processBlock (AudioSampleBuffer& buffer,
  24654. MidiBuffer& midiMessages)
  24655. {
  24656. const int numSamples = buffer.getNumSamples();
  24657. if (initialised)
  24658. {
  24659. AudioUnitRenderActionFlags flags = 0;
  24660. timeStamp.mHostTime = AudioGetCurrentHostTime();
  24661. for (int i = getNumOutputChannels(); --i >= 0;)
  24662. {
  24663. outputBufferList->mBuffers[i].mDataByteSize = sizeof (float) * numSamples;
  24664. outputBufferList->mBuffers[i].mData = buffer.getSampleData (i, 0);
  24665. }
  24666. currentBuffer = &buffer;
  24667. if (wantsMidiMessages)
  24668. {
  24669. const uint8* midiEventData;
  24670. int midiEventSize, midiEventPosition;
  24671. MidiBuffer::Iterator i (midiMessages);
  24672. while (i.getNextEvent (midiEventData, midiEventSize, midiEventPosition))
  24673. {
  24674. if (midiEventSize <= 3)
  24675. MusicDeviceMIDIEvent (audioUnit,
  24676. midiEventData[0], midiEventData[1], midiEventData[2],
  24677. midiEventPosition);
  24678. else
  24679. MusicDeviceSysEx (audioUnit, midiEventData, midiEventSize);
  24680. }
  24681. midiMessages.clear();
  24682. }
  24683. AudioUnitRender (audioUnit, &flags, &timeStamp,
  24684. 0, numSamples, outputBufferList);
  24685. timeStamp.mSampleTime += numSamples;
  24686. }
  24687. else
  24688. {
  24689. // Not initialised, so just bypass..
  24690. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  24691. buffer.clear (i, 0, buffer.getNumSamples());
  24692. }
  24693. }
  24694. OSStatus AudioUnitPluginInstance::getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const
  24695. {
  24696. AudioPlayHead* const ph = getPlayHead();
  24697. AudioPlayHead::CurrentPositionInfo result;
  24698. if (ph != 0 && ph->getCurrentPosition (result))
  24699. {
  24700. if (outCurrentBeat != 0)
  24701. *outCurrentBeat = result.ppqPosition;
  24702. if (outCurrentTempo != 0)
  24703. *outCurrentTempo = result.bpm;
  24704. }
  24705. else
  24706. {
  24707. if (outCurrentBeat != 0)
  24708. *outCurrentBeat = 0;
  24709. if (outCurrentTempo != 0)
  24710. *outCurrentTempo = 120.0;
  24711. }
  24712. return noErr;
  24713. }
  24714. OSStatus AudioUnitPluginInstance::getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat,
  24715. Float32* outTimeSig_Numerator,
  24716. UInt32* outTimeSig_Denominator,
  24717. Float64* outCurrentMeasureDownBeat) const
  24718. {
  24719. AudioPlayHead* const ph = getPlayHead();
  24720. AudioPlayHead::CurrentPositionInfo result;
  24721. if (ph != 0 && ph->getCurrentPosition (result))
  24722. {
  24723. if (outTimeSig_Numerator != 0)
  24724. *outTimeSig_Numerator = result.timeSigNumerator;
  24725. if (outTimeSig_Denominator != 0)
  24726. *outTimeSig_Denominator = result.timeSigDenominator;
  24727. if (outDeltaSampleOffsetToNextBeat != 0)
  24728. *outDeltaSampleOffsetToNextBeat = 0; //xxx
  24729. if (outCurrentMeasureDownBeat != 0)
  24730. *outCurrentMeasureDownBeat = result.ppqPositionOfLastBarStart; //xxx wrong
  24731. }
  24732. else
  24733. {
  24734. if (outDeltaSampleOffsetToNextBeat != 0)
  24735. *outDeltaSampleOffsetToNextBeat = 0;
  24736. if (outTimeSig_Numerator != 0)
  24737. *outTimeSig_Numerator = 4;
  24738. if (outTimeSig_Denominator != 0)
  24739. *outTimeSig_Denominator = 4;
  24740. if (outCurrentMeasureDownBeat != 0)
  24741. *outCurrentMeasureDownBeat = 0;
  24742. }
  24743. return noErr;
  24744. }
  24745. OSStatus AudioUnitPluginInstance::getTransportState (Boolean* outIsPlaying,
  24746. Boolean* outTransportStateChanged,
  24747. Float64* outCurrentSampleInTimeLine,
  24748. Boolean* outIsCycling,
  24749. Float64* outCycleStartBeat,
  24750. Float64* outCycleEndBeat)
  24751. {
  24752. AudioPlayHead* const ph = getPlayHead();
  24753. AudioPlayHead::CurrentPositionInfo result;
  24754. if (ph != 0 && ph->getCurrentPosition (result))
  24755. {
  24756. if (outIsPlaying != 0)
  24757. *outIsPlaying = result.isPlaying;
  24758. if (outTransportStateChanged != 0)
  24759. {
  24760. *outTransportStateChanged = result.isPlaying != wasPlaying;
  24761. wasPlaying = result.isPlaying;
  24762. }
  24763. if (outCurrentSampleInTimeLine != 0)
  24764. *outCurrentSampleInTimeLine = roundToInt (result.timeInSeconds * getSampleRate());
  24765. if (outIsCycling != 0)
  24766. *outIsCycling = false;
  24767. if (outCycleStartBeat != 0)
  24768. *outCycleStartBeat = 0;
  24769. if (outCycleEndBeat != 0)
  24770. *outCycleEndBeat = 0;
  24771. }
  24772. else
  24773. {
  24774. if (outIsPlaying != 0)
  24775. *outIsPlaying = false;
  24776. if (outTransportStateChanged != 0)
  24777. *outTransportStateChanged = false;
  24778. if (outCurrentSampleInTimeLine != 0)
  24779. *outCurrentSampleInTimeLine = 0;
  24780. if (outIsCycling != 0)
  24781. *outIsCycling = false;
  24782. if (outCycleStartBeat != 0)
  24783. *outCycleStartBeat = 0;
  24784. if (outCycleEndBeat != 0)
  24785. *outCycleEndBeat = 0;
  24786. }
  24787. return noErr;
  24788. }
  24789. class AudioUnitPluginWindowCocoa : public AudioProcessorEditor
  24790. {
  24791. public:
  24792. AudioUnitPluginWindowCocoa (AudioUnitPluginInstance& plugin_, const bool createGenericViewIfNeeded)
  24793. : AudioProcessorEditor (&plugin_),
  24794. plugin (plugin_),
  24795. wrapper (0)
  24796. {
  24797. addAndMakeVisible (wrapper = new NSViewComponent());
  24798. setOpaque (true);
  24799. setVisible (true);
  24800. setSize (100, 100);
  24801. createView (createGenericViewIfNeeded);
  24802. }
  24803. ~AudioUnitPluginWindowCocoa()
  24804. {
  24805. const bool wasValid = isValid();
  24806. wrapper->setView (0);
  24807. if (wasValid)
  24808. plugin.editorBeingDeleted (this);
  24809. delete wrapper;
  24810. }
  24811. bool isValid() const { return wrapper->getView() != 0; }
  24812. void paint (Graphics& g)
  24813. {
  24814. g.fillAll (Colours::white);
  24815. }
  24816. void resized()
  24817. {
  24818. wrapper->setSize (getWidth(), getHeight());
  24819. }
  24820. private:
  24821. AudioUnitPluginInstance& plugin;
  24822. NSViewComponent* wrapper;
  24823. bool createView (const bool createGenericViewIfNeeded)
  24824. {
  24825. NSView* pluginView = 0;
  24826. UInt32 dataSize = 0;
  24827. Boolean isWritable = false;
  24828. if (AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  24829. 0, &dataSize, &isWritable) == noErr
  24830. && dataSize != 0
  24831. && AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  24832. 0, &dataSize, &isWritable) == noErr)
  24833. {
  24834. HeapBlock <AudioUnitCocoaViewInfo> info;
  24835. info.calloc (dataSize, 1);
  24836. if (AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  24837. 0, info, &dataSize) == noErr)
  24838. {
  24839. NSString* viewClassName = (NSString*) (info->mCocoaAUViewClass[0]);
  24840. NSString* path = (NSString*) CFURLCopyPath (info->mCocoaAUViewBundleLocation);
  24841. NSBundle* viewBundle = [NSBundle bundleWithPath: [path autorelease]];
  24842. Class viewClass = [viewBundle classNamed: viewClassName];
  24843. if ([viewClass conformsToProtocol: @protocol (AUCocoaUIBase)]
  24844. && [viewClass instancesRespondToSelector: @selector (interfaceVersion)]
  24845. && [viewClass instancesRespondToSelector: @selector (uiViewForAudioUnit: withSize:)])
  24846. {
  24847. id factory = [[[viewClass alloc] init] autorelease];
  24848. pluginView = [factory uiViewForAudioUnit: plugin.audioUnit
  24849. withSize: NSMakeSize (getWidth(), getHeight())];
  24850. }
  24851. for (int i = (dataSize - sizeof (CFURLRef)) / sizeof (CFStringRef); --i >= 0;)
  24852. {
  24853. CFRelease (info->mCocoaAUViewClass[i]);
  24854. CFRelease (info->mCocoaAUViewBundleLocation);
  24855. }
  24856. }
  24857. }
  24858. if (createGenericViewIfNeeded && (pluginView == 0))
  24859. pluginView = [[AUGenericView alloc] initWithAudioUnit: plugin.audioUnit];
  24860. wrapper->setView (pluginView);
  24861. if (pluginView != 0)
  24862. setSize ([pluginView frame].size.width,
  24863. [pluginView frame].size.height);
  24864. return pluginView != 0;
  24865. }
  24866. };
  24867. #if JUCE_SUPPORT_CARBON
  24868. class AudioUnitPluginWindowCarbon : public AudioProcessorEditor
  24869. {
  24870. public:
  24871. AudioUnitPluginWindowCarbon (AudioUnitPluginInstance& plugin_)
  24872. : AudioProcessorEditor (&plugin_),
  24873. plugin (plugin_),
  24874. viewComponent (0)
  24875. {
  24876. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  24877. setOpaque (true);
  24878. setVisible (true);
  24879. setSize (400, 300);
  24880. ComponentDescription viewList [16];
  24881. UInt32 viewListSize = sizeof (viewList);
  24882. AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global,
  24883. 0, &viewList, &viewListSize);
  24884. componentRecord = FindNextComponent (0, &viewList[0]);
  24885. }
  24886. ~AudioUnitPluginWindowCarbon()
  24887. {
  24888. innerWrapper = 0;
  24889. if (isValid())
  24890. plugin.editorBeingDeleted (this);
  24891. }
  24892. bool isValid() const throw() { return componentRecord != 0; }
  24893. void paint (Graphics& g)
  24894. {
  24895. g.fillAll (Colours::black);
  24896. }
  24897. void resized()
  24898. {
  24899. innerWrapper->setSize (getWidth(), getHeight());
  24900. }
  24901. bool keyStateChanged (bool)
  24902. {
  24903. return false;
  24904. }
  24905. bool keyPressed (const KeyPress&)
  24906. {
  24907. return false;
  24908. }
  24909. AudioUnit getAudioUnit() const { return plugin.audioUnit; }
  24910. AudioUnitCarbonView getViewComponent()
  24911. {
  24912. if (viewComponent == 0 && componentRecord != 0)
  24913. viewComponent = (AudioUnitCarbonView) OpenComponent (componentRecord);
  24914. return viewComponent;
  24915. }
  24916. void closeViewComponent()
  24917. {
  24918. if (viewComponent != 0)
  24919. {
  24920. CloseComponent (viewComponent);
  24921. viewComponent = 0;
  24922. }
  24923. }
  24924. juce_UseDebuggingNewOperator
  24925. private:
  24926. AudioUnitPluginInstance& plugin;
  24927. ComponentRecord* componentRecord;
  24928. AudioUnitCarbonView viewComponent;
  24929. class InnerWrapperComponent : public CarbonViewWrapperComponent
  24930. {
  24931. public:
  24932. InnerWrapperComponent (AudioUnitPluginWindowCarbon* const owner_)
  24933. : owner (owner_)
  24934. {
  24935. }
  24936. ~InnerWrapperComponent()
  24937. {
  24938. deleteWindow();
  24939. }
  24940. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  24941. {
  24942. log ("Opening AU GUI: " + owner->plugin.getName());
  24943. AudioUnitCarbonView viewComponent = owner->getViewComponent();
  24944. if (viewComponent == 0)
  24945. return 0;
  24946. Float32Point pos = { 0, 0 };
  24947. Float32Point size = { 250, 200 };
  24948. HIViewRef pluginView = 0;
  24949. AudioUnitCarbonViewCreate (viewComponent,
  24950. owner->getAudioUnit(),
  24951. windowRef,
  24952. rootView,
  24953. &pos,
  24954. &size,
  24955. (ControlRef*) &pluginView);
  24956. return pluginView;
  24957. }
  24958. void removeView (HIViewRef)
  24959. {
  24960. log ("Closing AU GUI: " + owner->plugin.getName());
  24961. owner->closeViewComponent();
  24962. }
  24963. private:
  24964. AudioUnitPluginWindowCarbon* const owner;
  24965. };
  24966. friend class InnerWrapperComponent;
  24967. ScopedPointer<InnerWrapperComponent> innerWrapper;
  24968. };
  24969. #endif
  24970. AudioProcessorEditor* AudioUnitPluginInstance::createEditor()
  24971. {
  24972. ScopedPointer<AudioProcessorEditor> w (new AudioUnitPluginWindowCocoa (*this, false));
  24973. if (! static_cast <AudioUnitPluginWindowCocoa*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  24974. w = 0;
  24975. #if JUCE_SUPPORT_CARBON
  24976. if (w == 0)
  24977. {
  24978. w = new AudioUnitPluginWindowCarbon (*this);
  24979. if (! static_cast <AudioUnitPluginWindowCarbon*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  24980. w = 0;
  24981. }
  24982. #endif
  24983. if (w == 0)
  24984. w = new AudioUnitPluginWindowCocoa (*this, true); // use AUGenericView as a fallback
  24985. return w.release();
  24986. }
  24987. const String AudioUnitPluginInstance::getCategory() const
  24988. {
  24989. const char* result = 0;
  24990. switch (componentDesc.componentType)
  24991. {
  24992. case kAudioUnitType_Effect:
  24993. case kAudioUnitType_MusicEffect:
  24994. result = "Effect";
  24995. break;
  24996. case kAudioUnitType_MusicDevice:
  24997. result = "Synth";
  24998. break;
  24999. case kAudioUnitType_Generator:
  25000. result = "Generator";
  25001. break;
  25002. case kAudioUnitType_Panner:
  25003. result = "Panner";
  25004. break;
  25005. default:
  25006. break;
  25007. }
  25008. return result;
  25009. }
  25010. int AudioUnitPluginInstance::getNumParameters()
  25011. {
  25012. return parameterIds.size();
  25013. }
  25014. float AudioUnitPluginInstance::getParameter (int index)
  25015. {
  25016. const ScopedLock sl (lock);
  25017. Float32 value = 0.0f;
  25018. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  25019. {
  25020. AudioUnitGetParameter (audioUnit,
  25021. (UInt32) parameterIds.getUnchecked (index),
  25022. kAudioUnitScope_Global, 0,
  25023. &value);
  25024. }
  25025. return value;
  25026. }
  25027. void AudioUnitPluginInstance::setParameter (int index, float newValue)
  25028. {
  25029. const ScopedLock sl (lock);
  25030. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  25031. {
  25032. AudioUnitSetParameter (audioUnit,
  25033. (UInt32) parameterIds.getUnchecked (index),
  25034. kAudioUnitScope_Global, 0,
  25035. newValue, 0);
  25036. }
  25037. }
  25038. const String AudioUnitPluginInstance::getParameterName (int index)
  25039. {
  25040. AudioUnitParameterInfo info;
  25041. zerostruct (info);
  25042. UInt32 sz = sizeof (info);
  25043. String name;
  25044. if (AudioUnitGetProperty (audioUnit,
  25045. kAudioUnitProperty_ParameterInfo,
  25046. kAudioUnitScope_Global,
  25047. parameterIds [index], &info, &sz) == noErr)
  25048. {
  25049. if ((info.flags & kAudioUnitParameterFlag_HasCFNameString) != 0)
  25050. name = PlatformUtilities::cfStringToJuceString (info.cfNameString);
  25051. else
  25052. name = String (info.name, sizeof (info.name));
  25053. }
  25054. return name;
  25055. }
  25056. const String AudioUnitPluginInstance::getParameterText (int index)
  25057. {
  25058. return String (getParameter (index));
  25059. }
  25060. bool AudioUnitPluginInstance::isParameterAutomatable (int index) const
  25061. {
  25062. AudioUnitParameterInfo info;
  25063. UInt32 sz = sizeof (info);
  25064. if (AudioUnitGetProperty (audioUnit,
  25065. kAudioUnitProperty_ParameterInfo,
  25066. kAudioUnitScope_Global,
  25067. parameterIds [index], &info, &sz) == noErr)
  25068. {
  25069. return (info.flags & kAudioUnitParameterFlag_NonRealTime) == 0;
  25070. }
  25071. return true;
  25072. }
  25073. int AudioUnitPluginInstance::getNumPrograms()
  25074. {
  25075. CFArrayRef presets;
  25076. UInt32 sz = sizeof (CFArrayRef);
  25077. int num = 0;
  25078. if (AudioUnitGetProperty (audioUnit,
  25079. kAudioUnitProperty_FactoryPresets,
  25080. kAudioUnitScope_Global,
  25081. 0, &presets, &sz) == noErr)
  25082. {
  25083. num = (int) CFArrayGetCount (presets);
  25084. CFRelease (presets);
  25085. }
  25086. return num;
  25087. }
  25088. int AudioUnitPluginInstance::getCurrentProgram()
  25089. {
  25090. AUPreset current;
  25091. current.presetNumber = 0;
  25092. UInt32 sz = sizeof (AUPreset);
  25093. AudioUnitGetProperty (audioUnit,
  25094. kAudioUnitProperty_FactoryPresets,
  25095. kAudioUnitScope_Global,
  25096. 0, &current, &sz);
  25097. return current.presetNumber;
  25098. }
  25099. void AudioUnitPluginInstance::setCurrentProgram (int newIndex)
  25100. {
  25101. AUPreset current;
  25102. current.presetNumber = newIndex;
  25103. current.presetName = 0;
  25104. AudioUnitSetProperty (audioUnit,
  25105. kAudioUnitProperty_FactoryPresets,
  25106. kAudioUnitScope_Global,
  25107. 0, &current, sizeof (AUPreset));
  25108. }
  25109. const String AudioUnitPluginInstance::getProgramName (int index)
  25110. {
  25111. String s;
  25112. CFArrayRef presets;
  25113. UInt32 sz = sizeof (CFArrayRef);
  25114. if (AudioUnitGetProperty (audioUnit,
  25115. kAudioUnitProperty_FactoryPresets,
  25116. kAudioUnitScope_Global,
  25117. 0, &presets, &sz) == noErr)
  25118. {
  25119. for (CFIndex i = 0; i < CFArrayGetCount (presets); ++i)
  25120. {
  25121. const AUPreset* p = (const AUPreset*) CFArrayGetValueAtIndex (presets, i);
  25122. if (p != 0 && p->presetNumber == index)
  25123. {
  25124. s = PlatformUtilities::cfStringToJuceString (p->presetName);
  25125. break;
  25126. }
  25127. }
  25128. CFRelease (presets);
  25129. }
  25130. return s;
  25131. }
  25132. void AudioUnitPluginInstance::changeProgramName (int index, const String& newName)
  25133. {
  25134. jassertfalse; // xxx not implemented!
  25135. }
  25136. const String AudioUnitPluginInstance::getInputChannelName (const int index) const
  25137. {
  25138. if (((unsigned int) index) < (unsigned int) getNumInputChannels())
  25139. return "Input " + String (index + 1);
  25140. return String::empty;
  25141. }
  25142. bool AudioUnitPluginInstance::isInputChannelStereoPair (int index) const
  25143. {
  25144. if (((unsigned int) index) >= (unsigned int) getNumInputChannels())
  25145. return false;
  25146. return true;
  25147. }
  25148. const String AudioUnitPluginInstance::getOutputChannelName (const int index) const
  25149. {
  25150. if (((unsigned int) index) < (unsigned int) getNumOutputChannels())
  25151. return "Output " + String (index + 1);
  25152. return String::empty;
  25153. }
  25154. bool AudioUnitPluginInstance::isOutputChannelStereoPair (int index) const
  25155. {
  25156. if (((unsigned int) index) >= (unsigned int) getNumOutputChannels())
  25157. return false;
  25158. return true;
  25159. }
  25160. void AudioUnitPluginInstance::getStateInformation (MemoryBlock& destData)
  25161. {
  25162. getCurrentProgramStateInformation (destData);
  25163. }
  25164. void AudioUnitPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  25165. {
  25166. CFPropertyListRef propertyList = 0;
  25167. UInt32 sz = sizeof (CFPropertyListRef);
  25168. if (AudioUnitGetProperty (audioUnit,
  25169. kAudioUnitProperty_ClassInfo,
  25170. kAudioUnitScope_Global,
  25171. 0, &propertyList, &sz) == noErr)
  25172. {
  25173. CFWriteStreamRef stream = CFWriteStreamCreateWithAllocatedBuffers (kCFAllocatorDefault, kCFAllocatorDefault);
  25174. CFWriteStreamOpen (stream);
  25175. CFIndex bytesWritten = CFPropertyListWriteToStream (propertyList, stream, kCFPropertyListBinaryFormat_v1_0, 0);
  25176. CFWriteStreamClose (stream);
  25177. CFDataRef data = (CFDataRef) CFWriteStreamCopyProperty (stream, kCFStreamPropertyDataWritten);
  25178. destData.setSize (bytesWritten);
  25179. destData.copyFrom (CFDataGetBytePtr (data), 0, destData.getSize());
  25180. CFRelease (data);
  25181. CFRelease (stream);
  25182. CFRelease (propertyList);
  25183. }
  25184. }
  25185. void AudioUnitPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  25186. {
  25187. setCurrentProgramStateInformation (data, sizeInBytes);
  25188. }
  25189. void AudioUnitPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  25190. {
  25191. CFReadStreamRef stream = CFReadStreamCreateWithBytesNoCopy (kCFAllocatorDefault,
  25192. (const UInt8*) data,
  25193. sizeInBytes,
  25194. kCFAllocatorNull);
  25195. CFReadStreamOpen (stream);
  25196. CFPropertyListFormat format = kCFPropertyListBinaryFormat_v1_0;
  25197. CFPropertyListRef propertyList = CFPropertyListCreateFromStream (kCFAllocatorDefault,
  25198. stream,
  25199. 0,
  25200. kCFPropertyListImmutable,
  25201. &format,
  25202. 0);
  25203. CFRelease (stream);
  25204. if (propertyList != 0)
  25205. AudioUnitSetProperty (audioUnit,
  25206. kAudioUnitProperty_ClassInfo,
  25207. kAudioUnitScope_Global,
  25208. 0, &propertyList, sizeof (propertyList));
  25209. }
  25210. AudioUnitPluginFormat::AudioUnitPluginFormat()
  25211. {
  25212. }
  25213. AudioUnitPluginFormat::~AudioUnitPluginFormat()
  25214. {
  25215. }
  25216. void AudioUnitPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  25217. const String& fileOrIdentifier)
  25218. {
  25219. if (! fileMightContainThisPluginType (fileOrIdentifier))
  25220. return;
  25221. PluginDescription desc;
  25222. desc.fileOrIdentifier = fileOrIdentifier;
  25223. desc.uid = 0;
  25224. try
  25225. {
  25226. ScopedPointer <AudioPluginInstance> createdInstance (createInstanceFromDescription (desc));
  25227. AudioUnitPluginInstance* const auInstance = dynamic_cast <AudioUnitPluginInstance*> ((AudioPluginInstance*) createdInstance);
  25228. if (auInstance != 0)
  25229. {
  25230. auInstance->fillInPluginDescription (desc);
  25231. results.add (new PluginDescription (desc));
  25232. }
  25233. }
  25234. catch (...)
  25235. {
  25236. // crashed while loading...
  25237. }
  25238. }
  25239. AudioPluginInstance* AudioUnitPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  25240. {
  25241. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  25242. {
  25243. ScopedPointer <AudioUnitPluginInstance> result (new AudioUnitPluginInstance (desc.fileOrIdentifier));
  25244. if (result->audioUnit != 0)
  25245. {
  25246. result->initialise();
  25247. return result.release();
  25248. }
  25249. }
  25250. return 0;
  25251. }
  25252. const StringArray AudioUnitPluginFormat::searchPathsForPlugins (const FileSearchPath& /*directoriesToSearch*/,
  25253. const bool /*recursive*/)
  25254. {
  25255. StringArray result;
  25256. ComponentRecord* comp = 0;
  25257. ComponentDescription desc;
  25258. zerostruct (desc);
  25259. for (;;)
  25260. {
  25261. zerostruct (desc);
  25262. comp = FindNextComponent (comp, &desc);
  25263. if (comp == 0)
  25264. break;
  25265. GetComponentInfo (comp, &desc, 0, 0, 0);
  25266. if (desc.componentType == kAudioUnitType_MusicDevice
  25267. || desc.componentType == kAudioUnitType_MusicEffect
  25268. || desc.componentType == kAudioUnitType_Effect
  25269. || desc.componentType == kAudioUnitType_Generator
  25270. || desc.componentType == kAudioUnitType_Panner)
  25271. {
  25272. const String s (AudioUnitFormatHelpers::createAUPluginIdentifier (desc));
  25273. DBG (s);
  25274. result.add (s);
  25275. }
  25276. }
  25277. return result;
  25278. }
  25279. bool AudioUnitPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  25280. {
  25281. ComponentDescription desc;
  25282. String name, version, manufacturer;
  25283. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer))
  25284. return FindNextComponent (0, &desc) != 0;
  25285. const File f (fileOrIdentifier);
  25286. return f.hasFileExtension (".component")
  25287. && f.isDirectory();
  25288. }
  25289. const String AudioUnitPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  25290. {
  25291. ComponentDescription desc;
  25292. String name, version, manufacturer;
  25293. AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer);
  25294. if (name.isEmpty())
  25295. name = fileOrIdentifier;
  25296. return name;
  25297. }
  25298. bool AudioUnitPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  25299. {
  25300. if (desc.fileOrIdentifier.startsWithIgnoreCase (AudioUnitFormatHelpers::auIdentifierPrefix))
  25301. return fileMightContainThisPluginType (desc.fileOrIdentifier);
  25302. else
  25303. return File (desc.fileOrIdentifier).exists();
  25304. }
  25305. const FileSearchPath AudioUnitPluginFormat::getDefaultLocationsToSearch()
  25306. {
  25307. return FileSearchPath ("/(Default AudioUnit locations)");
  25308. }
  25309. #endif
  25310. END_JUCE_NAMESPACE
  25311. #undef log
  25312. #endif
  25313. /*** End of inlined file: juce_AudioUnitPluginFormat.mm ***/
  25314. /*** Start of inlined file: juce_VSTPluginFormat.mm ***/
  25315. // This file just wraps juce_VSTPluginFormat.cpp in an objective-C wrapper
  25316. #define JUCE_MAC_VST_INCLUDED 1
  25317. /*** Start of inlined file: juce_VSTPluginFormat.cpp ***/
  25318. #if JUCE_PLUGINHOST_VST && (JUCE_MAC_VST_INCLUDED || ! JUCE_MAC)
  25319. #if JUCE_WINDOWS
  25320. #undef _WIN32_WINNT
  25321. #define _WIN32_WINNT 0x500
  25322. #undef STRICT
  25323. #define STRICT
  25324. #include <windows.h>
  25325. #include <float.h>
  25326. #pragma warning (disable : 4312 4355)
  25327. #elif JUCE_LINUX
  25328. #include <float.h>
  25329. #include <sys/time.h>
  25330. #include <X11/Xlib.h>
  25331. #include <X11/Xutil.h>
  25332. #include <X11/Xatom.h>
  25333. #undef Font
  25334. #undef KeyPress
  25335. #undef Drawable
  25336. #undef Time
  25337. #else
  25338. #include <Cocoa/Cocoa.h>
  25339. #include <Carbon/Carbon.h>
  25340. #endif
  25341. #if ! (JUCE_MAC && JUCE_64BIT)
  25342. BEGIN_JUCE_NAMESPACE
  25343. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  25344. #endif
  25345. #undef PRAGMA_ALIGN_SUPPORTED
  25346. #define VST_FORCE_DEPRECATED 0
  25347. #if JUCE_MSVC
  25348. #pragma warning (push)
  25349. #pragma warning (disable: 4996)
  25350. #endif
  25351. /* Obviously you're going to need the Steinberg vstsdk2.4 folder in
  25352. your include path if you want to add VST support.
  25353. If you're not interested in VSTs, you can disable them by changing the
  25354. JUCE_PLUGINHOST_VST flag in juce_Config.h
  25355. */
  25356. #include "pluginterfaces/vst2.x/aeffectx.h"
  25357. #if JUCE_MSVC
  25358. #pragma warning (pop)
  25359. #endif
  25360. #if JUCE_LINUX
  25361. #define Font JUCE_NAMESPACE::Font
  25362. #define KeyPress JUCE_NAMESPACE::KeyPress
  25363. #define Drawable JUCE_NAMESPACE::Drawable
  25364. #define Time JUCE_NAMESPACE::Time
  25365. #endif
  25366. /*** Start of inlined file: juce_VSTMidiEventList.h ***/
  25367. #ifdef __aeffect__
  25368. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  25369. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  25370. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  25371. events to the list.
  25372. This is used by both the VST hosting code and the plugin wrapper.
  25373. */
  25374. class VSTMidiEventList
  25375. {
  25376. public:
  25377. VSTMidiEventList()
  25378. : numEventsUsed (0), numEventsAllocated (0)
  25379. {
  25380. }
  25381. ~VSTMidiEventList()
  25382. {
  25383. freeEvents();
  25384. }
  25385. void clear()
  25386. {
  25387. numEventsUsed = 0;
  25388. if (events != 0)
  25389. events->numEvents = 0;
  25390. }
  25391. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  25392. {
  25393. ensureSize (numEventsUsed + 1);
  25394. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  25395. events->numEvents = ++numEventsUsed;
  25396. if (numBytes <= 4)
  25397. {
  25398. if (e->type == kVstSysExType)
  25399. {
  25400. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  25401. e->type = kVstMidiType;
  25402. e->byteSize = sizeof (VstMidiEvent);
  25403. e->noteLength = 0;
  25404. e->noteOffset = 0;
  25405. e->detune = 0;
  25406. e->noteOffVelocity = 0;
  25407. }
  25408. e->deltaFrames = frameOffset;
  25409. memcpy (e->midiData, midiData, numBytes);
  25410. }
  25411. else
  25412. {
  25413. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  25414. if (se->type == kVstSysExType)
  25415. se->sysexDump = (char*) juce_realloc (se->sysexDump, numBytes);
  25416. else
  25417. se->sysexDump = (char*) juce_malloc (numBytes);
  25418. memcpy (se->sysexDump, midiData, numBytes);
  25419. se->type = kVstSysExType;
  25420. se->byteSize = sizeof (VstMidiSysexEvent);
  25421. se->deltaFrames = frameOffset;
  25422. se->flags = 0;
  25423. se->dumpBytes = numBytes;
  25424. se->resvd1 = 0;
  25425. se->resvd2 = 0;
  25426. }
  25427. }
  25428. // Handy method to pull the events out of an event buffer supplied by the host
  25429. // or plugin.
  25430. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  25431. {
  25432. for (int i = 0; i < events->numEvents; ++i)
  25433. {
  25434. const VstEvent* const e = events->events[i];
  25435. if (e != 0)
  25436. {
  25437. if (e->type == kVstMidiType)
  25438. {
  25439. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  25440. 4, e->deltaFrames);
  25441. }
  25442. else if (e->type == kVstSysExType)
  25443. {
  25444. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  25445. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  25446. e->deltaFrames);
  25447. }
  25448. }
  25449. }
  25450. }
  25451. void ensureSize (int numEventsNeeded)
  25452. {
  25453. if (numEventsNeeded > numEventsAllocated)
  25454. {
  25455. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  25456. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  25457. if (events == 0)
  25458. events.calloc (size, 1);
  25459. else
  25460. events.realloc (size, 1);
  25461. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  25462. {
  25463. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  25464. (int) sizeof (VstMidiSysexEvent)));
  25465. e->type = kVstMidiType;
  25466. e->byteSize = sizeof (VstMidiEvent);
  25467. events->events[i] = (VstEvent*) e;
  25468. }
  25469. numEventsAllocated = numEventsNeeded;
  25470. }
  25471. }
  25472. void freeEvents()
  25473. {
  25474. if (events != 0)
  25475. {
  25476. for (int i = numEventsAllocated; --i >= 0;)
  25477. {
  25478. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  25479. if (e->type == kVstSysExType)
  25480. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  25481. juce_free (e);
  25482. }
  25483. events.free();
  25484. numEventsUsed = 0;
  25485. numEventsAllocated = 0;
  25486. }
  25487. }
  25488. HeapBlock <VstEvents> events;
  25489. private:
  25490. int numEventsUsed, numEventsAllocated;
  25491. };
  25492. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  25493. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  25494. /*** End of inlined file: juce_VSTMidiEventList.h ***/
  25495. #if ! JUCE_WINDOWS
  25496. static void _fpreset() {}
  25497. static void _clearfp() {}
  25498. #endif
  25499. extern void juce_callAnyTimersSynchronously();
  25500. const int fxbVersionNum = 1;
  25501. struct fxProgram
  25502. {
  25503. long chunkMagic; // 'CcnK'
  25504. long byteSize; // of this chunk, excl. magic + byteSize
  25505. long fxMagic; // 'FxCk'
  25506. long version;
  25507. long fxID; // fx unique id
  25508. long fxVersion;
  25509. long numParams;
  25510. char prgName[28];
  25511. float params[1]; // variable no. of parameters
  25512. };
  25513. struct fxSet
  25514. {
  25515. long chunkMagic; // 'CcnK'
  25516. long byteSize; // of this chunk, excl. magic + byteSize
  25517. long fxMagic; // 'FxBk'
  25518. long version;
  25519. long fxID; // fx unique id
  25520. long fxVersion;
  25521. long numPrograms;
  25522. char future[128];
  25523. fxProgram programs[1]; // variable no. of programs
  25524. };
  25525. struct fxChunkSet
  25526. {
  25527. long chunkMagic; // 'CcnK'
  25528. long byteSize; // of this chunk, excl. magic + byteSize
  25529. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  25530. long version;
  25531. long fxID; // fx unique id
  25532. long fxVersion;
  25533. long numPrograms;
  25534. char future[128];
  25535. long chunkSize;
  25536. char chunk[8]; // variable
  25537. };
  25538. struct fxProgramSet
  25539. {
  25540. long chunkMagic; // 'CcnK'
  25541. long byteSize; // of this chunk, excl. magic + byteSize
  25542. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  25543. long version;
  25544. long fxID; // fx unique id
  25545. long fxVersion;
  25546. long numPrograms;
  25547. char name[28];
  25548. long chunkSize;
  25549. char chunk[8]; // variable
  25550. };
  25551. static long vst_swap (const long x) throw()
  25552. {
  25553. #ifdef JUCE_LITTLE_ENDIAN
  25554. return (long) ByteOrder::swap ((uint32) x);
  25555. #else
  25556. return x;
  25557. #endif
  25558. }
  25559. static float vst_swapFloat (const float x) throw()
  25560. {
  25561. #ifdef JUCE_LITTLE_ENDIAN
  25562. union { uint32 asInt; float asFloat; } n;
  25563. n.asFloat = x;
  25564. n.asInt = ByteOrder::swap (n.asInt);
  25565. return n.asFloat;
  25566. #else
  25567. return x;
  25568. #endif
  25569. }
  25570. typedef AEffect* (*MainCall) (audioMasterCallback);
  25571. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt);
  25572. static int shellUIDToCreate = 0;
  25573. static int insideVSTCallback = 0;
  25574. class VSTPluginWindow;
  25575. // Change this to disable logging of various VST activities
  25576. #ifndef VST_LOGGING
  25577. #define VST_LOGGING 1
  25578. #endif
  25579. #if VST_LOGGING
  25580. #define log(a) Logger::writeToLog(a);
  25581. #else
  25582. #define log(a)
  25583. #endif
  25584. #if JUCE_MAC && JUCE_PPC
  25585. static void* NewCFMFromMachO (void* const machofp) throw()
  25586. {
  25587. void* result = juce_malloc (8);
  25588. ((void**) result)[0] = machofp;
  25589. ((void**) result)[1] = result;
  25590. return result;
  25591. }
  25592. #endif
  25593. #if JUCE_LINUX
  25594. extern Display* display;
  25595. extern XContext windowHandleXContext;
  25596. typedef void (*EventProcPtr) (XEvent* ev);
  25597. static bool xErrorTriggered;
  25598. static int temporaryErrorHandler (Display*, XErrorEvent*)
  25599. {
  25600. xErrorTriggered = true;
  25601. return 0;
  25602. }
  25603. static int getPropertyFromXWindow (Window handle, Atom atom)
  25604. {
  25605. XErrorHandler oldErrorHandler = XSetErrorHandler (temporaryErrorHandler);
  25606. xErrorTriggered = false;
  25607. int userSize;
  25608. unsigned long bytes, userCount;
  25609. unsigned char* data;
  25610. Atom userType;
  25611. XGetWindowProperty (display, handle, atom, 0, 1, false, AnyPropertyType,
  25612. &userType, &userSize, &userCount, &bytes, &data);
  25613. XSetErrorHandler (oldErrorHandler);
  25614. return (userCount == 1 && ! xErrorTriggered) ? *(int*) data
  25615. : 0;
  25616. }
  25617. static Window getChildWindow (Window windowToCheck)
  25618. {
  25619. Window rootWindow, parentWindow;
  25620. Window* childWindows;
  25621. unsigned int numChildren;
  25622. XQueryTree (display,
  25623. windowToCheck,
  25624. &rootWindow,
  25625. &parentWindow,
  25626. &childWindows,
  25627. &numChildren);
  25628. if (numChildren > 0)
  25629. return childWindows [0];
  25630. return 0;
  25631. }
  25632. static void translateJuceToXButtonModifiers (const MouseEvent& e, XEvent& ev) throw()
  25633. {
  25634. if (e.mods.isLeftButtonDown())
  25635. {
  25636. ev.xbutton.button = Button1;
  25637. ev.xbutton.state |= Button1Mask;
  25638. }
  25639. else if (e.mods.isRightButtonDown())
  25640. {
  25641. ev.xbutton.button = Button3;
  25642. ev.xbutton.state |= Button3Mask;
  25643. }
  25644. else if (e.mods.isMiddleButtonDown())
  25645. {
  25646. ev.xbutton.button = Button2;
  25647. ev.xbutton.state |= Button2Mask;
  25648. }
  25649. }
  25650. static void translateJuceToXMotionModifiers (const MouseEvent& e, XEvent& ev) throw()
  25651. {
  25652. if (e.mods.isLeftButtonDown())
  25653. ev.xmotion.state |= Button1Mask;
  25654. else if (e.mods.isRightButtonDown())
  25655. ev.xmotion.state |= Button3Mask;
  25656. else if (e.mods.isMiddleButtonDown())
  25657. ev.xmotion.state |= Button2Mask;
  25658. }
  25659. static void translateJuceToXCrossingModifiers (const MouseEvent& e, XEvent& ev) throw()
  25660. {
  25661. if (e.mods.isLeftButtonDown())
  25662. ev.xcrossing.state |= Button1Mask;
  25663. else if (e.mods.isRightButtonDown())
  25664. ev.xcrossing.state |= Button3Mask;
  25665. else if (e.mods.isMiddleButtonDown())
  25666. ev.xcrossing.state |= Button2Mask;
  25667. }
  25668. static void translateJuceToXMouseWheelModifiers (const MouseEvent& e, const float increment, XEvent& ev) throw()
  25669. {
  25670. if (increment < 0)
  25671. {
  25672. ev.xbutton.button = Button5;
  25673. ev.xbutton.state |= Button5Mask;
  25674. }
  25675. else if (increment > 0)
  25676. {
  25677. ev.xbutton.button = Button4;
  25678. ev.xbutton.state |= Button4Mask;
  25679. }
  25680. }
  25681. #endif
  25682. class ModuleHandle : public ReferenceCountedObject
  25683. {
  25684. public:
  25685. File file;
  25686. MainCall moduleMain;
  25687. String pluginName;
  25688. static Array <ModuleHandle*>& getActiveModules()
  25689. {
  25690. static Array <ModuleHandle*> activeModules;
  25691. return activeModules;
  25692. }
  25693. static ModuleHandle* findOrCreateModule (const File& file)
  25694. {
  25695. for (int i = getActiveModules().size(); --i >= 0;)
  25696. {
  25697. ModuleHandle* const module = getActiveModules().getUnchecked(i);
  25698. if (module->file == file)
  25699. return module;
  25700. }
  25701. _fpreset(); // (doesn't do any harm)
  25702. ++insideVSTCallback;
  25703. shellUIDToCreate = 0;
  25704. log ("Attempting to load VST: " + file.getFullPathName());
  25705. ScopedPointer <ModuleHandle> m (new ModuleHandle (file));
  25706. if (! m->open())
  25707. m = 0;
  25708. --insideVSTCallback;
  25709. _fpreset(); // (doesn't do any harm)
  25710. return m.release();
  25711. }
  25712. ModuleHandle (const File& file_)
  25713. : file (file_),
  25714. moduleMain (0),
  25715. #if JUCE_WINDOWS || JUCE_LINUX
  25716. hModule (0)
  25717. #elif JUCE_MAC
  25718. fragId (0),
  25719. resHandle (0),
  25720. bundleRef (0),
  25721. resFileId (0)
  25722. #endif
  25723. {
  25724. getActiveModules().add (this);
  25725. #if JUCE_WINDOWS || JUCE_LINUX
  25726. fullParentDirectoryPathName = file_.getParentDirectory().getFullPathName();
  25727. #elif JUCE_MAC
  25728. FSRef ref;
  25729. PlatformUtilities::makeFSRefFromPath (&ref, file_.getParentDirectory().getFullPathName());
  25730. FSGetCatalogInfo (&ref, kFSCatInfoNone, 0, 0, &parentDirFSSpec, 0);
  25731. #endif
  25732. }
  25733. ~ModuleHandle()
  25734. {
  25735. getActiveModules().removeValue (this);
  25736. close();
  25737. }
  25738. juce_UseDebuggingNewOperator
  25739. #if JUCE_WINDOWS || JUCE_LINUX
  25740. void* hModule;
  25741. String fullParentDirectoryPathName;
  25742. bool open()
  25743. {
  25744. #if JUCE_WINDOWS
  25745. static bool timePeriodSet = false;
  25746. if (! timePeriodSet)
  25747. {
  25748. timePeriodSet = true;
  25749. timeBeginPeriod (2);
  25750. }
  25751. #endif
  25752. pluginName = file.getFileNameWithoutExtension();
  25753. hModule = PlatformUtilities::loadDynamicLibrary (file.getFullPathName());
  25754. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "VSTPluginMain");
  25755. if (moduleMain == 0)
  25756. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "main");
  25757. return moduleMain != 0;
  25758. }
  25759. void close()
  25760. {
  25761. _fpreset(); // (doesn't do any harm)
  25762. PlatformUtilities::freeDynamicLibrary (hModule);
  25763. }
  25764. void closeEffect (AEffect* eff)
  25765. {
  25766. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  25767. }
  25768. #else
  25769. CFragConnectionID fragId;
  25770. Handle resHandle;
  25771. CFBundleRef bundleRef;
  25772. FSSpec parentDirFSSpec;
  25773. short resFileId;
  25774. bool open()
  25775. {
  25776. bool ok = false;
  25777. const String filename (file.getFullPathName());
  25778. if (file.hasFileExtension (".vst"))
  25779. {
  25780. const char* const utf8 = filename.toUTF8();
  25781. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  25782. strlen (utf8), file.isDirectory());
  25783. if (url != 0)
  25784. {
  25785. bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  25786. CFRelease (url);
  25787. if (bundleRef != 0)
  25788. {
  25789. if (CFBundleLoadExecutable (bundleRef))
  25790. {
  25791. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("main_macho"));
  25792. if (moduleMain == 0)
  25793. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("VSTPluginMain"));
  25794. if (moduleMain != 0)
  25795. {
  25796. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  25797. if (name != 0)
  25798. {
  25799. if (CFGetTypeID (name) == CFStringGetTypeID())
  25800. {
  25801. char buffer[1024];
  25802. if (CFStringGetCString ((CFStringRef) name, buffer, sizeof (buffer), CFStringGetSystemEncoding()))
  25803. pluginName = buffer;
  25804. }
  25805. }
  25806. if (pluginName.isEmpty())
  25807. pluginName = file.getFileNameWithoutExtension();
  25808. resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  25809. ok = true;
  25810. }
  25811. }
  25812. if (! ok)
  25813. {
  25814. CFBundleUnloadExecutable (bundleRef);
  25815. CFRelease (bundleRef);
  25816. bundleRef = 0;
  25817. }
  25818. }
  25819. }
  25820. }
  25821. #if JUCE_PPC
  25822. else
  25823. {
  25824. FSRef fn;
  25825. if (FSPathMakeRef ((UInt8*) filename.toUTF8(), &fn, 0) == noErr)
  25826. {
  25827. resFileId = FSOpenResFile (&fn, fsRdPerm);
  25828. if (resFileId != -1)
  25829. {
  25830. const int numEffs = Count1Resources ('aEff');
  25831. for (int i = 0; i < numEffs; ++i)
  25832. {
  25833. resHandle = Get1IndResource ('aEff', i + 1);
  25834. if (resHandle != 0)
  25835. {
  25836. OSType type;
  25837. Str255 name;
  25838. SInt16 id;
  25839. GetResInfo (resHandle, &id, &type, name);
  25840. pluginName = String ((const char*) name + 1, name[0]);
  25841. DetachResource (resHandle);
  25842. HLock (resHandle);
  25843. Ptr ptr;
  25844. Str255 errorText;
  25845. OSErr err = GetMemFragment (*resHandle, GetHandleSize (resHandle),
  25846. name, kPrivateCFragCopy,
  25847. &fragId, &ptr, errorText);
  25848. if (err == noErr)
  25849. {
  25850. moduleMain = (MainCall) newMachOFromCFM (ptr);
  25851. ok = true;
  25852. }
  25853. else
  25854. {
  25855. HUnlock (resHandle);
  25856. }
  25857. break;
  25858. }
  25859. }
  25860. if (! ok)
  25861. CloseResFile (resFileId);
  25862. }
  25863. }
  25864. }
  25865. #endif
  25866. return ok;
  25867. }
  25868. void close()
  25869. {
  25870. #if JUCE_PPC
  25871. if (fragId != 0)
  25872. {
  25873. if (moduleMain != 0)
  25874. disposeMachOFromCFM ((void*) moduleMain);
  25875. CloseConnection (&fragId);
  25876. HUnlock (resHandle);
  25877. if (resFileId != 0)
  25878. CloseResFile (resFileId);
  25879. }
  25880. else
  25881. #endif
  25882. if (bundleRef != 0)
  25883. {
  25884. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  25885. if (CFGetRetainCount (bundleRef) == 1)
  25886. CFBundleUnloadExecutable (bundleRef);
  25887. if (CFGetRetainCount (bundleRef) > 0)
  25888. CFRelease (bundleRef);
  25889. }
  25890. }
  25891. void closeEffect (AEffect* eff)
  25892. {
  25893. #if JUCE_PPC
  25894. if (fragId != 0)
  25895. {
  25896. Array<void*> thingsToDelete;
  25897. thingsToDelete.add ((void*) eff->dispatcher);
  25898. thingsToDelete.add ((void*) eff->process);
  25899. thingsToDelete.add ((void*) eff->setParameter);
  25900. thingsToDelete.add ((void*) eff->getParameter);
  25901. thingsToDelete.add ((void*) eff->processReplacing);
  25902. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  25903. for (int i = thingsToDelete.size(); --i >= 0;)
  25904. disposeMachOFromCFM (thingsToDelete[i]);
  25905. }
  25906. else
  25907. #endif
  25908. {
  25909. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  25910. }
  25911. }
  25912. #if JUCE_PPC
  25913. static void* newMachOFromCFM (void* cfmfp)
  25914. {
  25915. if (cfmfp == 0)
  25916. return 0;
  25917. UInt32* const mfp = new UInt32[6];
  25918. mfp[0] = 0x3d800000 | ((UInt32) cfmfp >> 16);
  25919. mfp[1] = 0x618c0000 | ((UInt32) cfmfp & 0xffff);
  25920. mfp[2] = 0x800c0000;
  25921. mfp[3] = 0x804c0004;
  25922. mfp[4] = 0x7c0903a6;
  25923. mfp[5] = 0x4e800420;
  25924. MakeDataExecutable (mfp, sizeof (UInt32) * 6);
  25925. return mfp;
  25926. }
  25927. static void disposeMachOFromCFM (void* ptr)
  25928. {
  25929. delete[] static_cast <UInt32*> (ptr);
  25930. }
  25931. void coerceAEffectFunctionCalls (AEffect* eff)
  25932. {
  25933. if (fragId != 0)
  25934. {
  25935. eff->dispatcher = (AEffectDispatcherProc) newMachOFromCFM ((void*) eff->dispatcher);
  25936. eff->process = (AEffectProcessProc) newMachOFromCFM ((void*) eff->process);
  25937. eff->setParameter = (AEffectSetParameterProc) newMachOFromCFM ((void*) eff->setParameter);
  25938. eff->getParameter = (AEffectGetParameterProc) newMachOFromCFM ((void*) eff->getParameter);
  25939. eff->processReplacing = (AEffectProcessProc) newMachOFromCFM ((void*) eff->processReplacing);
  25940. }
  25941. }
  25942. #endif
  25943. #endif
  25944. };
  25945. /**
  25946. An instance of a plugin, created by a VSTPluginFormat.
  25947. */
  25948. class VSTPluginInstance : public AudioPluginInstance,
  25949. private Timer,
  25950. private AsyncUpdater
  25951. {
  25952. public:
  25953. ~VSTPluginInstance();
  25954. // AudioPluginInstance methods:
  25955. void fillInPluginDescription (PluginDescription& desc) const
  25956. {
  25957. desc.name = name;
  25958. desc.fileOrIdentifier = module->file.getFullPathName();
  25959. desc.uid = getUID();
  25960. desc.lastFileModTime = module->file.getLastModificationTime();
  25961. desc.pluginFormatName = "VST";
  25962. desc.category = getCategory();
  25963. {
  25964. char buffer [kVstMaxVendorStrLen + 8];
  25965. zerostruct (buffer);
  25966. dispatch (effGetVendorString, 0, 0, buffer, 0);
  25967. desc.manufacturerName = buffer;
  25968. }
  25969. desc.version = getVersion();
  25970. desc.numInputChannels = getNumInputChannels();
  25971. desc.numOutputChannels = getNumOutputChannels();
  25972. desc.isInstrument = (effect != 0 && (effect->flags & effFlagsIsSynth) != 0);
  25973. }
  25974. const String getName() const { return name; }
  25975. int getUID() const throw();
  25976. bool acceptsMidi() const { return wantsMidiMessages; }
  25977. bool producesMidi() const { return dispatch (effCanDo, 0, 0, (void*) "sendVstMidiEvent", 0) > 0; }
  25978. // AudioProcessor methods:
  25979. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  25980. void releaseResources();
  25981. void processBlock (AudioSampleBuffer& buffer,
  25982. MidiBuffer& midiMessages);
  25983. AudioProcessorEditor* createEditor();
  25984. const String getInputChannelName (const int index) const;
  25985. bool isInputChannelStereoPair (int index) const;
  25986. const String getOutputChannelName (const int index) const;
  25987. bool isOutputChannelStereoPair (int index) const;
  25988. int getNumParameters() { return effect != 0 ? effect->numParams : 0; }
  25989. float getParameter (int index);
  25990. void setParameter (int index, float newValue);
  25991. const String getParameterName (int index);
  25992. const String getParameterText (int index);
  25993. bool isParameterAutomatable (int index) const;
  25994. int getNumPrograms() { return effect != 0 ? effect->numPrograms : 0; }
  25995. int getCurrentProgram() { return dispatch (effGetProgram, 0, 0, 0, 0); }
  25996. void setCurrentProgram (int index);
  25997. const String getProgramName (int index);
  25998. void changeProgramName (int index, const String& newName);
  25999. void getStateInformation (MemoryBlock& destData);
  26000. void getCurrentProgramStateInformation (MemoryBlock& destData);
  26001. void setStateInformation (const void* data, int sizeInBytes);
  26002. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  26003. void timerCallback();
  26004. void handleAsyncUpdate();
  26005. VstIntPtr handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt);
  26006. juce_UseDebuggingNewOperator
  26007. private:
  26008. friend class VSTPluginWindow;
  26009. friend class VSTPluginFormat;
  26010. AEffect* effect;
  26011. String name;
  26012. CriticalSection lock;
  26013. bool wantsMidiMessages, initialised, isPowerOn;
  26014. mutable StringArray programNames;
  26015. AudioSampleBuffer tempBuffer;
  26016. CriticalSection midiInLock;
  26017. MidiBuffer incomingMidi;
  26018. VSTMidiEventList midiEventsToSend;
  26019. VstTimeInfo vstHostTime;
  26020. HeapBlock <float*> channels;
  26021. ReferenceCountedObjectPtr <ModuleHandle> module;
  26022. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const;
  26023. bool restoreProgramSettings (const fxProgram* const prog);
  26024. const String getCurrentProgramName();
  26025. void setParamsInProgramBlock (fxProgram* const prog) throw();
  26026. void updateStoredProgramNames();
  26027. void initialise();
  26028. void handleMidiFromPlugin (const VstEvents* const events);
  26029. void createTempParameterStore (MemoryBlock& dest);
  26030. void restoreFromTempParameterStore (const MemoryBlock& mb);
  26031. const String getParameterLabel (int index) const;
  26032. bool usesChunks() const throw() { return effect != 0 && (effect->flags & effFlagsProgramChunks) != 0; }
  26033. void getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const;
  26034. void setChunkData (const char* data, int size, bool isPreset);
  26035. bool loadFromFXBFile (const void* data, int numBytes);
  26036. bool saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB);
  26037. int getVersionNumber() const throw() { return effect != 0 ? effect->version : 0; }
  26038. const String getVersion() const throw();
  26039. const String getCategory() const throw();
  26040. bool hasEditor() const throw() { return effect != 0 && (effect->flags & effFlagsHasEditor) != 0; }
  26041. void setPower (const bool on);
  26042. VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module);
  26043. };
  26044. VSTPluginInstance::VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module_)
  26045. : effect (0),
  26046. wantsMidiMessages (false),
  26047. initialised (false),
  26048. isPowerOn (false),
  26049. tempBuffer (1, 1),
  26050. module (module_)
  26051. {
  26052. try
  26053. {
  26054. _fpreset();
  26055. ++insideVSTCallback;
  26056. name = module->pluginName;
  26057. log ("Creating VST instance: " + name);
  26058. #if JUCE_MAC
  26059. if (module->resFileId != 0)
  26060. UseResFile (module->resFileId);
  26061. #if JUCE_PPC
  26062. if (module->fragId != 0)
  26063. {
  26064. static void* audioMasterCoerced = 0;
  26065. if (audioMasterCoerced == 0)
  26066. audioMasterCoerced = NewCFMFromMachO ((void*) &audioMaster);
  26067. effect = module->moduleMain ((audioMasterCallback) audioMasterCoerced);
  26068. }
  26069. else
  26070. #endif
  26071. #endif
  26072. {
  26073. effect = module->moduleMain (&audioMaster);
  26074. }
  26075. --insideVSTCallback;
  26076. if (effect != 0 && effect->magic == kEffectMagic)
  26077. {
  26078. #if JUCE_PPC
  26079. module->coerceAEffectFunctionCalls (effect);
  26080. #endif
  26081. jassert (effect->resvd2 == 0);
  26082. jassert (effect->object != 0);
  26083. _fpreset(); // some dodgy plugs fuck around with this
  26084. }
  26085. else
  26086. {
  26087. effect = 0;
  26088. }
  26089. }
  26090. catch (...)
  26091. {
  26092. --insideVSTCallback;
  26093. }
  26094. }
  26095. VSTPluginInstance::~VSTPluginInstance()
  26096. {
  26097. {
  26098. const ScopedLock sl (lock);
  26099. jassert (insideVSTCallback == 0);
  26100. if (effect != 0 && effect->magic == kEffectMagic)
  26101. {
  26102. try
  26103. {
  26104. #if JUCE_MAC
  26105. if (module->resFileId != 0)
  26106. UseResFile (module->resFileId);
  26107. #endif
  26108. // Must delete any editors before deleting the plugin instance!
  26109. jassert (getActiveEditor() == 0);
  26110. _fpreset(); // some dodgy plugs fuck around with this
  26111. module->closeEffect (effect);
  26112. }
  26113. catch (...)
  26114. {}
  26115. }
  26116. module = 0;
  26117. effect = 0;
  26118. }
  26119. }
  26120. void VSTPluginInstance::initialise()
  26121. {
  26122. if (initialised || effect == 0)
  26123. return;
  26124. log ("Initialising VST: " + module->pluginName);
  26125. initialised = true;
  26126. dispatch (effIdentify, 0, 0, 0, 0);
  26127. // this code would ask the plugin for its name, but so few plugins
  26128. // actually bother implementing this correctly, that it's better to
  26129. // just ignore it and use the file name instead.
  26130. /* {
  26131. char buffer [256];
  26132. zerostruct (buffer);
  26133. dispatch (effGetEffectName, 0, 0, buffer, 0);
  26134. name = String (buffer).trim();
  26135. if (name.isEmpty())
  26136. name = module->pluginName;
  26137. }
  26138. */
  26139. if (getSampleRate() > 0)
  26140. dispatch (effSetSampleRate, 0, 0, 0, (float) getSampleRate());
  26141. if (getBlockSize() > 0)
  26142. dispatch (effSetBlockSize, 0, jmax (32, getBlockSize()), 0, 0);
  26143. dispatch (effOpen, 0, 0, 0, 0);
  26144. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  26145. getSampleRate(), getBlockSize());
  26146. if (getNumPrograms() > 1)
  26147. setCurrentProgram (0);
  26148. else
  26149. dispatch (effSetProgram, 0, 0, 0, 0);
  26150. int i;
  26151. for (i = effect->numInputs; --i >= 0;)
  26152. dispatch (effConnectInput, i, 1, 0, 0);
  26153. for (i = effect->numOutputs; --i >= 0;)
  26154. dispatch (effConnectOutput, i, 1, 0, 0);
  26155. updateStoredProgramNames();
  26156. wantsMidiMessages = dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0;
  26157. setLatencySamples (effect->initialDelay);
  26158. }
  26159. void VSTPluginInstance::prepareToPlay (double sampleRate_,
  26160. int samplesPerBlockExpected)
  26161. {
  26162. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  26163. sampleRate_, samplesPerBlockExpected);
  26164. setLatencySamples (effect->initialDelay);
  26165. channels.calloc (jmax (16, getNumOutputChannels(), getNumInputChannels()) + 2);
  26166. vstHostTime.tempo = 120.0;
  26167. vstHostTime.timeSigNumerator = 4;
  26168. vstHostTime.timeSigDenominator = 4;
  26169. vstHostTime.sampleRate = sampleRate_;
  26170. vstHostTime.samplePos = 0;
  26171. vstHostTime.flags = kVstNanosValid; /*| kVstTransportPlaying | kVstTempoValid | kVstTimeSigValid*/;
  26172. initialise();
  26173. if (initialised)
  26174. {
  26175. wantsMidiMessages = wantsMidiMessages
  26176. || (dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0);
  26177. if (wantsMidiMessages)
  26178. midiEventsToSend.ensureSize (256);
  26179. else
  26180. midiEventsToSend.freeEvents();
  26181. incomingMidi.clear();
  26182. dispatch (effSetSampleRate, 0, 0, 0, (float) sampleRate_);
  26183. dispatch (effSetBlockSize, 0, jmax (16, samplesPerBlockExpected), 0, 0);
  26184. tempBuffer.setSize (jmax (1, effect->numOutputs), samplesPerBlockExpected);
  26185. if (! isPowerOn)
  26186. setPower (true);
  26187. // dodgy hack to force some plugins to initialise the sample rate..
  26188. if ((! hasEditor()) && getNumParameters() > 0)
  26189. {
  26190. const float old = getParameter (0);
  26191. setParameter (0, (old < 0.5f) ? 1.0f : 0.0f);
  26192. setParameter (0, old);
  26193. }
  26194. dispatch (effStartProcess, 0, 0, 0, 0);
  26195. }
  26196. }
  26197. void VSTPluginInstance::releaseResources()
  26198. {
  26199. if (initialised)
  26200. {
  26201. dispatch (effStopProcess, 0, 0, 0, 0);
  26202. setPower (false);
  26203. }
  26204. tempBuffer.setSize (1, 1);
  26205. incomingMidi.clear();
  26206. midiEventsToSend.freeEvents();
  26207. channels.free();
  26208. }
  26209. void VSTPluginInstance::processBlock (AudioSampleBuffer& buffer,
  26210. MidiBuffer& midiMessages)
  26211. {
  26212. const int numSamples = buffer.getNumSamples();
  26213. if (initialised)
  26214. {
  26215. AudioPlayHead* playHead = getPlayHead();
  26216. if (playHead != 0)
  26217. {
  26218. AudioPlayHead::CurrentPositionInfo position;
  26219. playHead->getCurrentPosition (position);
  26220. vstHostTime.tempo = position.bpm;
  26221. vstHostTime.timeSigNumerator = position.timeSigNumerator;
  26222. vstHostTime.timeSigDenominator = position.timeSigDenominator;
  26223. vstHostTime.ppqPos = position.ppqPosition;
  26224. vstHostTime.barStartPos = position.ppqPositionOfLastBarStart;
  26225. vstHostTime.flags |= kVstTempoValid | kVstTimeSigValid | kVstPpqPosValid | kVstBarsValid;
  26226. if (position.isPlaying)
  26227. vstHostTime.flags |= kVstTransportPlaying;
  26228. else
  26229. vstHostTime.flags &= ~kVstTransportPlaying;
  26230. }
  26231. #if JUCE_WINDOWS
  26232. vstHostTime.nanoSeconds = timeGetTime() * 1000000.0;
  26233. #elif JUCE_LINUX
  26234. timeval micro;
  26235. gettimeofday (&micro, 0);
  26236. vstHostTime.nanoSeconds = micro.tv_usec * 1000.0;
  26237. #elif JUCE_MAC
  26238. UnsignedWide micro;
  26239. Microseconds (&micro);
  26240. vstHostTime.nanoSeconds = micro.lo * 1000.0;
  26241. #endif
  26242. if (wantsMidiMessages)
  26243. {
  26244. midiEventsToSend.clear();
  26245. midiEventsToSend.ensureSize (1);
  26246. MidiBuffer::Iterator iter (midiMessages);
  26247. const uint8* midiData;
  26248. int numBytesOfMidiData, samplePosition;
  26249. while (iter.getNextEvent (midiData, numBytesOfMidiData, samplePosition))
  26250. {
  26251. midiEventsToSend.addEvent (midiData, numBytesOfMidiData,
  26252. jlimit (0, numSamples - 1, samplePosition));
  26253. }
  26254. try
  26255. {
  26256. effect->dispatcher (effect, effProcessEvents, 0, 0, midiEventsToSend.events, 0);
  26257. }
  26258. catch (...)
  26259. {}
  26260. }
  26261. int i;
  26262. const int maxChans = jmax (effect->numInputs, effect->numOutputs);
  26263. for (i = 0; i < maxChans; ++i)
  26264. channels[i] = buffer.getSampleData (i);
  26265. channels [maxChans] = 0;
  26266. _clearfp();
  26267. if ((effect->flags & effFlagsCanReplacing) != 0)
  26268. {
  26269. try
  26270. {
  26271. effect->processReplacing (effect, channels, channels, numSamples);
  26272. }
  26273. catch (...)
  26274. {}
  26275. }
  26276. else
  26277. {
  26278. tempBuffer.setSize (effect->numOutputs, numSamples);
  26279. tempBuffer.clear();
  26280. float* outs [64];
  26281. for (i = effect->numOutputs; --i >= 0;)
  26282. outs[i] = tempBuffer.getSampleData (i);
  26283. outs [effect->numOutputs] = 0;
  26284. try
  26285. {
  26286. effect->process (effect, channels, outs, numSamples);
  26287. }
  26288. catch (...)
  26289. {}
  26290. for (i = effect->numOutputs; --i >= 0;)
  26291. buffer.copyFrom (i, 0, outs[i], numSamples);
  26292. }
  26293. }
  26294. else
  26295. {
  26296. // Not initialised, so just bypass..
  26297. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  26298. buffer.clear (i, 0, buffer.getNumSamples());
  26299. }
  26300. {
  26301. // copy any incoming midi..
  26302. const ScopedLock sl (midiInLock);
  26303. midiMessages.swapWith (incomingMidi);
  26304. incomingMidi.clear();
  26305. }
  26306. }
  26307. void VSTPluginInstance::handleMidiFromPlugin (const VstEvents* const events)
  26308. {
  26309. if (events != 0)
  26310. {
  26311. const ScopedLock sl (midiInLock);
  26312. VSTMidiEventList::addEventsToMidiBuffer (events, incomingMidi);
  26313. }
  26314. }
  26315. static Array <VSTPluginWindow*> activeVSTWindows;
  26316. class VSTPluginWindow : public AudioProcessorEditor,
  26317. #if ! JUCE_MAC
  26318. public ComponentMovementWatcher,
  26319. #endif
  26320. public Timer
  26321. {
  26322. public:
  26323. VSTPluginWindow (VSTPluginInstance& plugin_)
  26324. : AudioProcessorEditor (&plugin_),
  26325. #if ! JUCE_MAC
  26326. ComponentMovementWatcher (this),
  26327. #endif
  26328. plugin (plugin_),
  26329. isOpen (false),
  26330. wasShowing (false),
  26331. pluginRefusesToResize (false),
  26332. pluginWantsKeys (false),
  26333. alreadyInside (false),
  26334. recursiveResize (false)
  26335. {
  26336. #if JUCE_WINDOWS
  26337. sizeCheckCount = 0;
  26338. pluginHWND = 0;
  26339. #elif JUCE_LINUX
  26340. pluginWindow = None;
  26341. pluginProc = None;
  26342. #else
  26343. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  26344. #endif
  26345. activeVSTWindows.add (this);
  26346. setSize (1, 1);
  26347. setOpaque (true);
  26348. setVisible (true);
  26349. }
  26350. ~VSTPluginWindow()
  26351. {
  26352. #if JUCE_MAC
  26353. innerWrapper = 0;
  26354. #else
  26355. closePluginWindow();
  26356. #endif
  26357. activeVSTWindows.removeValue (this);
  26358. plugin.editorBeingDeleted (this);
  26359. }
  26360. #if ! JUCE_MAC
  26361. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  26362. {
  26363. if (recursiveResize)
  26364. return;
  26365. Component* const topComp = getTopLevelComponent();
  26366. if (topComp->getPeer() != 0)
  26367. {
  26368. const Point<int> pos (relativePositionToOtherComponent (topComp, Point<int>()));
  26369. recursiveResize = true;
  26370. #if JUCE_WINDOWS
  26371. if (pluginHWND != 0)
  26372. MoveWindow (pluginHWND, pos.getX(), pos.getY(), getWidth(), getHeight(), TRUE);
  26373. #elif JUCE_LINUX
  26374. if (pluginWindow != 0)
  26375. {
  26376. XResizeWindow (display, pluginWindow, getWidth(), getHeight());
  26377. XMoveWindow (display, pluginWindow, pos.getX(), pos.getY());
  26378. XMapRaised (display, pluginWindow);
  26379. }
  26380. #endif
  26381. recursiveResize = false;
  26382. }
  26383. }
  26384. void componentVisibilityChanged (Component&)
  26385. {
  26386. const bool isShowingNow = isShowing();
  26387. if (wasShowing != isShowingNow)
  26388. {
  26389. wasShowing = isShowingNow;
  26390. if (isShowingNow)
  26391. openPluginWindow();
  26392. else
  26393. closePluginWindow();
  26394. }
  26395. componentMovedOrResized (true, true);
  26396. }
  26397. void componentPeerChanged()
  26398. {
  26399. closePluginWindow();
  26400. openPluginWindow();
  26401. }
  26402. #endif
  26403. bool keyStateChanged (bool)
  26404. {
  26405. return pluginWantsKeys;
  26406. }
  26407. bool keyPressed (const KeyPress&)
  26408. {
  26409. return pluginWantsKeys;
  26410. }
  26411. #if JUCE_MAC
  26412. void paint (Graphics& g)
  26413. {
  26414. g.fillAll (Colours::black);
  26415. }
  26416. #else
  26417. void paint (Graphics& g)
  26418. {
  26419. if (isOpen)
  26420. {
  26421. ComponentPeer* const peer = getPeer();
  26422. if (peer != 0)
  26423. {
  26424. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  26425. peer->addMaskedRegion (pos.getX(), pos.getY(), getWidth(), getHeight());
  26426. #if JUCE_LINUX
  26427. if (pluginWindow != 0)
  26428. {
  26429. const Rectangle<int> clip (g.getClipBounds());
  26430. XEvent ev;
  26431. zerostruct (ev);
  26432. ev.xexpose.type = Expose;
  26433. ev.xexpose.display = display;
  26434. ev.xexpose.window = pluginWindow;
  26435. ev.xexpose.x = clip.getX();
  26436. ev.xexpose.y = clip.getY();
  26437. ev.xexpose.width = clip.getWidth();
  26438. ev.xexpose.height = clip.getHeight();
  26439. sendEventToChild (&ev);
  26440. }
  26441. #endif
  26442. }
  26443. }
  26444. else
  26445. {
  26446. g.fillAll (Colours::black);
  26447. }
  26448. }
  26449. #endif
  26450. void timerCallback()
  26451. {
  26452. #if JUCE_WINDOWS
  26453. if (--sizeCheckCount <= 0)
  26454. {
  26455. sizeCheckCount = 10;
  26456. checkPluginWindowSize();
  26457. }
  26458. #endif
  26459. try
  26460. {
  26461. static bool reentrant = false;
  26462. if (! reentrant)
  26463. {
  26464. reentrant = true;
  26465. plugin.dispatch (effEditIdle, 0, 0, 0, 0);
  26466. reentrant = false;
  26467. }
  26468. }
  26469. catch (...)
  26470. {}
  26471. }
  26472. void mouseDown (const MouseEvent& e)
  26473. {
  26474. #if JUCE_LINUX
  26475. if (pluginWindow == 0)
  26476. return;
  26477. toFront (true);
  26478. XEvent ev;
  26479. zerostruct (ev);
  26480. ev.xbutton.display = display;
  26481. ev.xbutton.type = ButtonPress;
  26482. ev.xbutton.window = pluginWindow;
  26483. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  26484. ev.xbutton.time = CurrentTime;
  26485. ev.xbutton.x = e.x;
  26486. ev.xbutton.y = e.y;
  26487. ev.xbutton.x_root = e.getScreenX();
  26488. ev.xbutton.y_root = e.getScreenY();
  26489. translateJuceToXButtonModifiers (e, ev);
  26490. sendEventToChild (&ev);
  26491. #elif JUCE_WINDOWS
  26492. (void) e;
  26493. toFront (true);
  26494. #endif
  26495. }
  26496. void broughtToFront()
  26497. {
  26498. activeVSTWindows.removeValue (this);
  26499. activeVSTWindows.add (this);
  26500. #if JUCE_MAC
  26501. dispatch (effEditTop, 0, 0, 0, 0);
  26502. #endif
  26503. }
  26504. juce_UseDebuggingNewOperator
  26505. private:
  26506. VSTPluginInstance& plugin;
  26507. bool isOpen, wasShowing, recursiveResize;
  26508. bool pluginWantsKeys, pluginRefusesToResize, alreadyInside;
  26509. #if JUCE_WINDOWS
  26510. HWND pluginHWND;
  26511. void* originalWndProc;
  26512. int sizeCheckCount;
  26513. #elif JUCE_LINUX
  26514. Window pluginWindow;
  26515. EventProcPtr pluginProc;
  26516. #endif
  26517. #if JUCE_MAC
  26518. void openPluginWindow (WindowRef parentWindow)
  26519. {
  26520. if (isOpen || parentWindow == 0)
  26521. return;
  26522. isOpen = true;
  26523. ERect* rect = 0;
  26524. dispatch (effEditGetRect, 0, 0, &rect, 0);
  26525. dispatch (effEditOpen, 0, 0, parentWindow, 0);
  26526. // do this before and after like in the steinberg example
  26527. dispatch (effEditGetRect, 0, 0, &rect, 0);
  26528. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  26529. // Install keyboard hooks
  26530. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  26531. // double-check it's not too tiny
  26532. int w = 250, h = 150;
  26533. if (rect != 0)
  26534. {
  26535. w = rect->right - rect->left;
  26536. h = rect->bottom - rect->top;
  26537. if (w == 0 || h == 0)
  26538. {
  26539. w = 250;
  26540. h = 150;
  26541. }
  26542. }
  26543. w = jmax (w, 32);
  26544. h = jmax (h, 32);
  26545. setSize (w, h);
  26546. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  26547. repaint();
  26548. }
  26549. #else
  26550. void openPluginWindow()
  26551. {
  26552. if (isOpen || getWindowHandle() == 0)
  26553. return;
  26554. log ("Opening VST UI: " + plugin.name);
  26555. isOpen = true;
  26556. ERect* rect = 0;
  26557. dispatch (effEditGetRect, 0, 0, &rect, 0);
  26558. dispatch (effEditOpen, 0, 0, getWindowHandle(), 0);
  26559. // do this before and after like in the steinberg example
  26560. dispatch (effEditGetRect, 0, 0, &rect, 0);
  26561. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  26562. // Install keyboard hooks
  26563. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  26564. #if JUCE_WINDOWS
  26565. originalWndProc = 0;
  26566. pluginHWND = GetWindow ((HWND) getWindowHandle(), GW_CHILD);
  26567. if (pluginHWND == 0)
  26568. {
  26569. isOpen = false;
  26570. setSize (300, 150);
  26571. return;
  26572. }
  26573. #pragma warning (push)
  26574. #pragma warning (disable: 4244)
  26575. originalWndProc = (void*) GetWindowLongPtr (pluginHWND, GWL_WNDPROC);
  26576. if (! pluginWantsKeys)
  26577. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) vstHookWndProc);
  26578. #pragma warning (pop)
  26579. int w, h;
  26580. RECT r;
  26581. GetWindowRect (pluginHWND, &r);
  26582. w = r.right - r.left;
  26583. h = r.bottom - r.top;
  26584. if (rect != 0)
  26585. {
  26586. const int rw = rect->right - rect->left;
  26587. const int rh = rect->bottom - rect->top;
  26588. if ((rw > 50 && rh > 50 && rw < 2000 && rh < 2000 && rw != w && rh != h)
  26589. || ((w == 0 && rw > 0) || (h == 0 && rh > 0)))
  26590. {
  26591. // very dodgy logic to decide which size is right.
  26592. if (abs (rw - w) > 350 || abs (rh - h) > 350)
  26593. {
  26594. SetWindowPos (pluginHWND, 0,
  26595. 0, 0, rw, rh,
  26596. SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  26597. GetWindowRect (pluginHWND, &r);
  26598. w = r.right - r.left;
  26599. h = r.bottom - r.top;
  26600. pluginRefusesToResize = (w != rw) || (h != rh);
  26601. w = rw;
  26602. h = rh;
  26603. }
  26604. }
  26605. }
  26606. #elif JUCE_LINUX
  26607. pluginWindow = getChildWindow ((Window) getWindowHandle());
  26608. if (pluginWindow != 0)
  26609. pluginProc = (EventProcPtr) getPropertyFromXWindow (pluginWindow,
  26610. XInternAtom (display, "_XEventProc", False));
  26611. int w = 250, h = 150;
  26612. if (rect != 0)
  26613. {
  26614. w = rect->right - rect->left;
  26615. h = rect->bottom - rect->top;
  26616. if (w == 0 || h == 0)
  26617. {
  26618. w = 250;
  26619. h = 150;
  26620. }
  26621. }
  26622. if (pluginWindow != 0)
  26623. XMapRaised (display, pluginWindow);
  26624. #endif
  26625. // double-check it's not too tiny
  26626. w = jmax (w, 32);
  26627. h = jmax (h, 32);
  26628. setSize (w, h);
  26629. #if JUCE_WINDOWS
  26630. checkPluginWindowSize();
  26631. #endif
  26632. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  26633. repaint();
  26634. }
  26635. #endif
  26636. #if ! JUCE_MAC
  26637. void closePluginWindow()
  26638. {
  26639. if (isOpen)
  26640. {
  26641. log ("Closing VST UI: " + plugin.getName());
  26642. isOpen = false;
  26643. dispatch (effEditClose, 0, 0, 0, 0);
  26644. #if JUCE_WINDOWS
  26645. #pragma warning (push)
  26646. #pragma warning (disable: 4244)
  26647. if (pluginHWND != 0 && IsWindow (pluginHWND))
  26648. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) originalWndProc);
  26649. #pragma warning (pop)
  26650. stopTimer();
  26651. if (pluginHWND != 0 && IsWindow (pluginHWND))
  26652. DestroyWindow (pluginHWND);
  26653. pluginHWND = 0;
  26654. #elif JUCE_LINUX
  26655. stopTimer();
  26656. pluginWindow = 0;
  26657. pluginProc = 0;
  26658. #endif
  26659. }
  26660. }
  26661. #endif
  26662. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt)
  26663. {
  26664. return plugin.dispatch (opcode, index, value, ptr, opt);
  26665. }
  26666. #if JUCE_WINDOWS
  26667. void checkPluginWindowSize() throw()
  26668. {
  26669. RECT r;
  26670. GetWindowRect (pluginHWND, &r);
  26671. const int w = r.right - r.left;
  26672. const int h = r.bottom - r.top;
  26673. if (isShowing() && w > 0 && h > 0
  26674. && (w != getWidth() || h != getHeight())
  26675. && ! pluginRefusesToResize)
  26676. {
  26677. setSize (w, h);
  26678. sizeCheckCount = 0;
  26679. }
  26680. }
  26681. // hooks to get keyboard events from VST windows..
  26682. static LRESULT CALLBACK vstHookWndProc (HWND hW, UINT message, WPARAM wParam, LPARAM lParam)
  26683. {
  26684. for (int i = activeVSTWindows.size(); --i >= 0;)
  26685. {
  26686. const VSTPluginWindow* const w = (const VSTPluginWindow*) activeVSTWindows.getUnchecked (i);
  26687. if (w->pluginHWND == hW)
  26688. {
  26689. if (message == WM_CHAR
  26690. || message == WM_KEYDOWN
  26691. || message == WM_SYSKEYDOWN
  26692. || message == WM_KEYUP
  26693. || message == WM_SYSKEYUP
  26694. || message == WM_APPCOMMAND)
  26695. {
  26696. SendMessage ((HWND) w->getTopLevelComponent()->getWindowHandle(),
  26697. message, wParam, lParam);
  26698. }
  26699. return CallWindowProc ((WNDPROC) (w->originalWndProc),
  26700. (HWND) w->pluginHWND,
  26701. message,
  26702. wParam,
  26703. lParam);
  26704. }
  26705. }
  26706. return DefWindowProc (hW, message, wParam, lParam);
  26707. }
  26708. #endif
  26709. #if JUCE_LINUX
  26710. // overload mouse/keyboard events to forward them to the plugin's inner window..
  26711. void sendEventToChild (XEvent* event)
  26712. {
  26713. if (pluginProc != 0)
  26714. {
  26715. // if the plugin publishes an event procedure, pass the event directly..
  26716. pluginProc (event);
  26717. }
  26718. else if (pluginWindow != 0)
  26719. {
  26720. // if the plugin has a window, then send the event to the window so that
  26721. // its message thread will pick it up..
  26722. XSendEvent (display, pluginWindow, False, 0L, event);
  26723. XFlush (display);
  26724. }
  26725. }
  26726. void mouseEnter (const MouseEvent& e)
  26727. {
  26728. if (pluginWindow != 0)
  26729. {
  26730. XEvent ev;
  26731. zerostruct (ev);
  26732. ev.xcrossing.display = display;
  26733. ev.xcrossing.type = EnterNotify;
  26734. ev.xcrossing.window = pluginWindow;
  26735. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  26736. ev.xcrossing.time = CurrentTime;
  26737. ev.xcrossing.x = e.x;
  26738. ev.xcrossing.y = e.y;
  26739. ev.xcrossing.x_root = e.getScreenX();
  26740. ev.xcrossing.y_root = e.getScreenY();
  26741. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  26742. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  26743. translateJuceToXCrossingModifiers (e, ev);
  26744. sendEventToChild (&ev);
  26745. }
  26746. }
  26747. void mouseExit (const MouseEvent& e)
  26748. {
  26749. if (pluginWindow != 0)
  26750. {
  26751. XEvent ev;
  26752. zerostruct (ev);
  26753. ev.xcrossing.display = display;
  26754. ev.xcrossing.type = LeaveNotify;
  26755. ev.xcrossing.window = pluginWindow;
  26756. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  26757. ev.xcrossing.time = CurrentTime;
  26758. ev.xcrossing.x = e.x;
  26759. ev.xcrossing.y = e.y;
  26760. ev.xcrossing.x_root = e.getScreenX();
  26761. ev.xcrossing.y_root = e.getScreenY();
  26762. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  26763. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  26764. ev.xcrossing.focus = hasKeyboardFocus (true); // TODO - yes ?
  26765. translateJuceToXCrossingModifiers (e, ev);
  26766. sendEventToChild (&ev);
  26767. }
  26768. }
  26769. void mouseMove (const MouseEvent& e)
  26770. {
  26771. if (pluginWindow != 0)
  26772. {
  26773. XEvent ev;
  26774. zerostruct (ev);
  26775. ev.xmotion.display = display;
  26776. ev.xmotion.type = MotionNotify;
  26777. ev.xmotion.window = pluginWindow;
  26778. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  26779. ev.xmotion.time = CurrentTime;
  26780. ev.xmotion.is_hint = NotifyNormal;
  26781. ev.xmotion.x = e.x;
  26782. ev.xmotion.y = e.y;
  26783. ev.xmotion.x_root = e.getScreenX();
  26784. ev.xmotion.y_root = e.getScreenY();
  26785. sendEventToChild (&ev);
  26786. }
  26787. }
  26788. void mouseDrag (const MouseEvent& e)
  26789. {
  26790. if (pluginWindow != 0)
  26791. {
  26792. XEvent ev;
  26793. zerostruct (ev);
  26794. ev.xmotion.display = display;
  26795. ev.xmotion.type = MotionNotify;
  26796. ev.xmotion.window = pluginWindow;
  26797. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  26798. ev.xmotion.time = CurrentTime;
  26799. ev.xmotion.x = e.x ;
  26800. ev.xmotion.y = e.y;
  26801. ev.xmotion.x_root = e.getScreenX();
  26802. ev.xmotion.y_root = e.getScreenY();
  26803. ev.xmotion.is_hint = NotifyNormal;
  26804. translateJuceToXMotionModifiers (e, ev);
  26805. sendEventToChild (&ev);
  26806. }
  26807. }
  26808. void mouseUp (const MouseEvent& e)
  26809. {
  26810. if (pluginWindow != 0)
  26811. {
  26812. XEvent ev;
  26813. zerostruct (ev);
  26814. ev.xbutton.display = display;
  26815. ev.xbutton.type = ButtonRelease;
  26816. ev.xbutton.window = pluginWindow;
  26817. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  26818. ev.xbutton.time = CurrentTime;
  26819. ev.xbutton.x = e.x;
  26820. ev.xbutton.y = e.y;
  26821. ev.xbutton.x_root = e.getScreenX();
  26822. ev.xbutton.y_root = e.getScreenY();
  26823. translateJuceToXButtonModifiers (e, ev);
  26824. sendEventToChild (&ev);
  26825. }
  26826. }
  26827. void mouseWheelMove (const MouseEvent& e,
  26828. float incrementX,
  26829. float incrementY)
  26830. {
  26831. if (pluginWindow != 0)
  26832. {
  26833. XEvent ev;
  26834. zerostruct (ev);
  26835. ev.xbutton.display = display;
  26836. ev.xbutton.type = ButtonPress;
  26837. ev.xbutton.window = pluginWindow;
  26838. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  26839. ev.xbutton.time = CurrentTime;
  26840. ev.xbutton.x = e.x;
  26841. ev.xbutton.y = e.y;
  26842. ev.xbutton.x_root = e.getScreenX();
  26843. ev.xbutton.y_root = e.getScreenY();
  26844. translateJuceToXMouseWheelModifiers (e, incrementY, ev);
  26845. sendEventToChild (&ev);
  26846. // TODO - put a usleep here ?
  26847. ev.xbutton.type = ButtonRelease;
  26848. sendEventToChild (&ev);
  26849. }
  26850. }
  26851. #endif
  26852. #if JUCE_MAC
  26853. #if ! JUCE_SUPPORT_CARBON
  26854. #error "To build VSTs, you need to enable the JUCE_SUPPORT_CARBON flag in your config!"
  26855. #endif
  26856. class InnerWrapperComponent : public CarbonViewWrapperComponent
  26857. {
  26858. public:
  26859. InnerWrapperComponent (VSTPluginWindow* const owner_)
  26860. : owner (owner_),
  26861. alreadyInside (false)
  26862. {
  26863. }
  26864. ~InnerWrapperComponent()
  26865. {
  26866. deleteWindow();
  26867. }
  26868. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  26869. {
  26870. owner->openPluginWindow (windowRef);
  26871. return 0;
  26872. }
  26873. void removeView (HIViewRef)
  26874. {
  26875. owner->dispatch (effEditClose, 0, 0, 0, 0);
  26876. owner->dispatch (effEditSleep, 0, 0, 0, 0);
  26877. }
  26878. bool getEmbeddedViewSize (int& w, int& h)
  26879. {
  26880. ERect* rect = 0;
  26881. owner->dispatch (effEditGetRect, 0, 0, &rect, 0);
  26882. w = rect->right - rect->left;
  26883. h = rect->bottom - rect->top;
  26884. return true;
  26885. }
  26886. void mouseDown (int x, int y)
  26887. {
  26888. if (! alreadyInside)
  26889. {
  26890. alreadyInside = true;
  26891. getTopLevelComponent()->toFront (true);
  26892. owner->dispatch (effEditMouse, x, y, 0, 0);
  26893. alreadyInside = false;
  26894. }
  26895. else
  26896. {
  26897. PostEvent (::mouseDown, 0);
  26898. }
  26899. }
  26900. void paint()
  26901. {
  26902. ComponentPeer* const peer = getPeer();
  26903. if (peer != 0)
  26904. {
  26905. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  26906. ERect r;
  26907. r.left = pos.getX();
  26908. r.right = r.left + getWidth();
  26909. r.top = pos.getY();
  26910. r.bottom = r.top + getHeight();
  26911. owner->dispatch (effEditDraw, 0, 0, &r, 0);
  26912. }
  26913. }
  26914. private:
  26915. VSTPluginWindow* const owner;
  26916. bool alreadyInside;
  26917. };
  26918. friend class InnerWrapperComponent;
  26919. ScopedPointer <InnerWrapperComponent> innerWrapper;
  26920. void resized()
  26921. {
  26922. innerWrapper->setSize (getWidth(), getHeight());
  26923. }
  26924. #endif
  26925. };
  26926. AudioProcessorEditor* VSTPluginInstance::createEditor()
  26927. {
  26928. if (hasEditor())
  26929. return new VSTPluginWindow (*this);
  26930. return 0;
  26931. }
  26932. void VSTPluginInstance::handleAsyncUpdate()
  26933. {
  26934. // indicates that something about the plugin has changed..
  26935. updateHostDisplay();
  26936. }
  26937. bool VSTPluginInstance::restoreProgramSettings (const fxProgram* const prog)
  26938. {
  26939. if (vst_swap (prog->chunkMagic) == 'CcnK' && vst_swap (prog->fxMagic) == 'FxCk')
  26940. {
  26941. changeProgramName (getCurrentProgram(), prog->prgName);
  26942. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  26943. setParameter (i, vst_swapFloat (prog->params[i]));
  26944. return true;
  26945. }
  26946. return false;
  26947. }
  26948. bool VSTPluginInstance::loadFromFXBFile (const void* const data,
  26949. const int dataSize)
  26950. {
  26951. if (dataSize < 28)
  26952. return false;
  26953. const fxSet* const set = (const fxSet*) data;
  26954. if ((vst_swap (set->chunkMagic) != 'CcnK' && vst_swap (set->chunkMagic) != 'KncC')
  26955. || vst_swap (set->version) > fxbVersionNum)
  26956. return false;
  26957. if (vst_swap (set->fxMagic) == 'FxBk')
  26958. {
  26959. // bank of programs
  26960. if (vst_swap (set->numPrograms) >= 0)
  26961. {
  26962. const int oldProg = getCurrentProgram();
  26963. const int numParams = vst_swap (((const fxProgram*) (set->programs))->numParams);
  26964. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  26965. for (int i = 0; i < vst_swap (set->numPrograms); ++i)
  26966. {
  26967. if (i != oldProg)
  26968. {
  26969. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + i * progLen);
  26970. if (((const char*) prog) - ((const char*) set) >= dataSize)
  26971. return false;
  26972. if (vst_swap (set->numPrograms) > 0)
  26973. setCurrentProgram (i);
  26974. if (! restoreProgramSettings (prog))
  26975. return false;
  26976. }
  26977. }
  26978. if (vst_swap (set->numPrograms) > 0)
  26979. setCurrentProgram (oldProg);
  26980. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + oldProg * progLen);
  26981. if (((const char*) prog) - ((const char*) set) >= dataSize)
  26982. return false;
  26983. if (! restoreProgramSettings (prog))
  26984. return false;
  26985. }
  26986. }
  26987. else if (vst_swap (set->fxMagic) == 'FxCk')
  26988. {
  26989. // single program
  26990. const fxProgram* const prog = (const fxProgram*) data;
  26991. if (vst_swap (prog->chunkMagic) != 'CcnK')
  26992. return false;
  26993. changeProgramName (getCurrentProgram(), prog->prgName);
  26994. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  26995. setParameter (i, vst_swapFloat (prog->params[i]));
  26996. }
  26997. else if (vst_swap (set->fxMagic) == 'FBCh' || vst_swap (set->fxMagic) == 'hCBF')
  26998. {
  26999. // non-preset chunk
  27000. const fxChunkSet* const cset = (const fxChunkSet*) data;
  27001. if (vst_swap (cset->chunkSize) + sizeof (fxChunkSet) - 8 > (unsigned int) dataSize)
  27002. return false;
  27003. setChunkData (cset->chunk, vst_swap (cset->chunkSize), false);
  27004. }
  27005. else if (vst_swap (set->fxMagic) == 'FPCh' || vst_swap (set->fxMagic) == 'hCPF')
  27006. {
  27007. // preset chunk
  27008. const fxProgramSet* const cset = (const fxProgramSet*) data;
  27009. if (vst_swap (cset->chunkSize) + sizeof (fxProgramSet) - 8 > (unsigned int) dataSize)
  27010. return false;
  27011. setChunkData (cset->chunk, vst_swap (cset->chunkSize), true);
  27012. changeProgramName (getCurrentProgram(), cset->name);
  27013. }
  27014. else
  27015. {
  27016. return false;
  27017. }
  27018. return true;
  27019. }
  27020. void VSTPluginInstance::setParamsInProgramBlock (fxProgram* const prog) throw()
  27021. {
  27022. const int numParams = getNumParameters();
  27023. prog->chunkMagic = vst_swap ('CcnK');
  27024. prog->byteSize = 0;
  27025. prog->fxMagic = vst_swap ('FxCk');
  27026. prog->version = vst_swap (fxbVersionNum);
  27027. prog->fxID = vst_swap (getUID());
  27028. prog->fxVersion = vst_swap (getVersionNumber());
  27029. prog->numParams = vst_swap (numParams);
  27030. getCurrentProgramName().copyToCString (prog->prgName, sizeof (prog->prgName) - 1);
  27031. for (int i = 0; i < numParams; ++i)
  27032. prog->params[i] = vst_swapFloat (getParameter (i));
  27033. }
  27034. bool VSTPluginInstance::saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB)
  27035. {
  27036. const int numPrograms = getNumPrograms();
  27037. const int numParams = getNumParameters();
  27038. if (usesChunks())
  27039. {
  27040. if (isFXB)
  27041. {
  27042. MemoryBlock chunk;
  27043. getChunkData (chunk, false, maxSizeMB);
  27044. const size_t totalLen = sizeof (fxChunkSet) + chunk.getSize() - 8;
  27045. dest.setSize (totalLen, true);
  27046. fxChunkSet* const set = (fxChunkSet*) dest.getData();
  27047. set->chunkMagic = vst_swap ('CcnK');
  27048. set->byteSize = 0;
  27049. set->fxMagic = vst_swap ('FBCh');
  27050. set->version = vst_swap (fxbVersionNum);
  27051. set->fxID = vst_swap (getUID());
  27052. set->fxVersion = vst_swap (getVersionNumber());
  27053. set->numPrograms = vst_swap (numPrograms);
  27054. set->chunkSize = vst_swap ((long) chunk.getSize());
  27055. chunk.copyTo (set->chunk, 0, chunk.getSize());
  27056. }
  27057. else
  27058. {
  27059. MemoryBlock chunk;
  27060. getChunkData (chunk, true, maxSizeMB);
  27061. const size_t totalLen = sizeof (fxProgramSet) + chunk.getSize() - 8;
  27062. dest.setSize (totalLen, true);
  27063. fxProgramSet* const set = (fxProgramSet*) dest.getData();
  27064. set->chunkMagic = vst_swap ('CcnK');
  27065. set->byteSize = 0;
  27066. set->fxMagic = vst_swap ('FPCh');
  27067. set->version = vst_swap (fxbVersionNum);
  27068. set->fxID = vst_swap (getUID());
  27069. set->fxVersion = vst_swap (getVersionNumber());
  27070. set->numPrograms = vst_swap (numPrograms);
  27071. set->chunkSize = vst_swap ((long) chunk.getSize());
  27072. getCurrentProgramName().copyToCString (set->name, sizeof (set->name) - 1);
  27073. chunk.copyTo (set->chunk, 0, chunk.getSize());
  27074. }
  27075. }
  27076. else
  27077. {
  27078. if (isFXB)
  27079. {
  27080. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27081. const int len = (sizeof (fxSet) - sizeof (fxProgram)) + progLen * jmax (1, numPrograms);
  27082. dest.setSize (len, true);
  27083. fxSet* const set = (fxSet*) dest.getData();
  27084. set->chunkMagic = vst_swap ('CcnK');
  27085. set->byteSize = 0;
  27086. set->fxMagic = vst_swap ('FxBk');
  27087. set->version = vst_swap (fxbVersionNum);
  27088. set->fxID = vst_swap (getUID());
  27089. set->fxVersion = vst_swap (getVersionNumber());
  27090. set->numPrograms = vst_swap (numPrograms);
  27091. const int oldProgram = getCurrentProgram();
  27092. MemoryBlock oldSettings;
  27093. createTempParameterStore (oldSettings);
  27094. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + oldProgram * progLen));
  27095. for (int i = 0; i < numPrograms; ++i)
  27096. {
  27097. if (i != oldProgram)
  27098. {
  27099. setCurrentProgram (i);
  27100. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + i * progLen));
  27101. }
  27102. }
  27103. setCurrentProgram (oldProgram);
  27104. restoreFromTempParameterStore (oldSettings);
  27105. }
  27106. else
  27107. {
  27108. const int totalLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27109. dest.setSize (totalLen, true);
  27110. setParamsInProgramBlock ((fxProgram*) dest.getData());
  27111. }
  27112. }
  27113. return true;
  27114. }
  27115. void VSTPluginInstance::getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const
  27116. {
  27117. if (usesChunks())
  27118. {
  27119. void* data = 0;
  27120. const int bytes = dispatch (effGetChunk, isPreset ? 1 : 0, 0, &data, 0.0f);
  27121. if (data != 0 && bytes <= maxSizeMB * 1024 * 1024)
  27122. {
  27123. mb.setSize (bytes);
  27124. mb.copyFrom (data, 0, bytes);
  27125. }
  27126. }
  27127. }
  27128. void VSTPluginInstance::setChunkData (const char* data, int size, bool isPreset)
  27129. {
  27130. if (size > 0 && usesChunks())
  27131. {
  27132. dispatch (effSetChunk, isPreset ? 1 : 0, size, (void*) data, 0.0f);
  27133. if (! isPreset)
  27134. updateStoredProgramNames();
  27135. }
  27136. }
  27137. void VSTPluginInstance::timerCallback()
  27138. {
  27139. if (dispatch (effIdle, 0, 0, 0, 0) == 0)
  27140. stopTimer();
  27141. }
  27142. int VSTPluginInstance::dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const
  27143. {
  27144. const ScopedLock sl (lock);
  27145. ++insideVSTCallback;
  27146. int result = 0;
  27147. try
  27148. {
  27149. if (effect != 0)
  27150. {
  27151. #if JUCE_MAC
  27152. if (module->resFileId != 0)
  27153. UseResFile (module->resFileId);
  27154. CGrafPtr oldPort;
  27155. if (getActiveEditor() != 0)
  27156. {
  27157. const Point<int> pos (getActiveEditor()->relativePositionToOtherComponent (getActiveEditor()->getTopLevelComponent(), Point<int>()));
  27158. GetPort (&oldPort);
  27159. SetPortWindowPort ((WindowRef) getActiveEditor()->getWindowHandle());
  27160. SetOrigin (-pos.getX(), -pos.getY());
  27161. }
  27162. #endif
  27163. result = effect->dispatcher (effect, opcode, index, value, ptr, opt);
  27164. #if JUCE_MAC
  27165. if (getActiveEditor() != 0)
  27166. SetPort (oldPort);
  27167. module->resFileId = CurResFile();
  27168. #endif
  27169. --insideVSTCallback;
  27170. return result;
  27171. }
  27172. }
  27173. catch (...)
  27174. {
  27175. }
  27176. --insideVSTCallback;
  27177. return result;
  27178. }
  27179. // handles non plugin-specific callbacks..
  27180. static const int defaultVSTSampleRateValue = 16384;
  27181. static const int defaultVSTBlockSizeValue = 512;
  27182. static VstIntPtr handleGeneralCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  27183. {
  27184. (void) index;
  27185. (void) value;
  27186. (void) opt;
  27187. switch (opcode)
  27188. {
  27189. case audioMasterCanDo:
  27190. {
  27191. static const char* canDos[] = { "supplyIdle",
  27192. "sendVstEvents",
  27193. "sendVstMidiEvent",
  27194. "sendVstTimeInfo",
  27195. "receiveVstEvents",
  27196. "receiveVstMidiEvent",
  27197. "supportShell",
  27198. "shellCategory" };
  27199. for (int i = 0; i < numElementsInArray (canDos); ++i)
  27200. if (strcmp (canDos[i], (const char*) ptr) == 0)
  27201. return 1;
  27202. return 0;
  27203. }
  27204. case audioMasterVersion:
  27205. return 0x2400;
  27206. case audioMasterCurrentId:
  27207. return shellUIDToCreate;
  27208. case audioMasterGetNumAutomatableParameters:
  27209. return 0;
  27210. case audioMasterGetAutomationState:
  27211. return 1;
  27212. case audioMasterGetVendorVersion:
  27213. return 0x0101;
  27214. case audioMasterGetVendorString:
  27215. case audioMasterGetProductString:
  27216. {
  27217. String hostName ("Juce VST Host");
  27218. if (JUCEApplication::getInstance() != 0)
  27219. hostName = JUCEApplication::getInstance()->getApplicationName();
  27220. hostName.copyToCString ((char*) ptr, jmin (kVstMaxVendorStrLen, kVstMaxProductStrLen) - 1);
  27221. }
  27222. break;
  27223. case audioMasterGetSampleRate:
  27224. return (VstIntPtr) defaultVSTSampleRateValue;
  27225. case audioMasterGetBlockSize:
  27226. return (VstIntPtr) defaultVSTBlockSizeValue;
  27227. case audioMasterSetOutputSampleRate:
  27228. return 0;
  27229. default:
  27230. DBG ("*** Unhandled VST Callback: " + String ((int) opcode));
  27231. break;
  27232. }
  27233. return 0;
  27234. }
  27235. // handles callbacks for a specific plugin
  27236. VstIntPtr VSTPluginInstance::handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  27237. {
  27238. switch (opcode)
  27239. {
  27240. case audioMasterAutomate:
  27241. sendParamChangeMessageToListeners (index, opt);
  27242. break;
  27243. case audioMasterProcessEvents:
  27244. handleMidiFromPlugin ((const VstEvents*) ptr);
  27245. break;
  27246. case audioMasterGetTime:
  27247. #if JUCE_MSVC
  27248. #pragma warning (push)
  27249. #pragma warning (disable: 4311)
  27250. #endif
  27251. return (VstIntPtr) &vstHostTime;
  27252. #if JUCE_MSVC
  27253. #pragma warning (pop)
  27254. #endif
  27255. break;
  27256. case audioMasterIdle:
  27257. if (insideVSTCallback == 0 && MessageManager::getInstance()->isThisTheMessageThread())
  27258. {
  27259. ++insideVSTCallback;
  27260. #if JUCE_MAC
  27261. if (getActiveEditor() != 0)
  27262. dispatch (effEditIdle, 0, 0, 0, 0);
  27263. #endif
  27264. juce_callAnyTimersSynchronously();
  27265. handleUpdateNowIfNeeded();
  27266. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  27267. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  27268. --insideVSTCallback;
  27269. }
  27270. break;
  27271. case audioMasterUpdateDisplay:
  27272. triggerAsyncUpdate();
  27273. break;
  27274. case audioMasterTempoAt:
  27275. // returns (10000 * bpm)
  27276. break;
  27277. case audioMasterNeedIdle:
  27278. startTimer (50);
  27279. break;
  27280. case audioMasterSizeWindow:
  27281. if (getActiveEditor() != 0)
  27282. getActiveEditor()->setSize (index, value);
  27283. return 1;
  27284. case audioMasterGetSampleRate:
  27285. return (VstIntPtr) (getSampleRate() > 0 ? getSampleRate() : defaultVSTSampleRateValue);
  27286. case audioMasterGetBlockSize:
  27287. return (VstIntPtr) (getBlockSize() > 0 ? getBlockSize() : defaultVSTBlockSizeValue);
  27288. case audioMasterWantMidi:
  27289. wantsMidiMessages = true;
  27290. break;
  27291. case audioMasterGetDirectory:
  27292. #if JUCE_MAC
  27293. return (VstIntPtr) (void*) &module->parentDirFSSpec;
  27294. #else
  27295. return (VstIntPtr) (pointer_sized_uint) module->fullParentDirectoryPathName.toUTF8();
  27296. #endif
  27297. case audioMasterGetAutomationState:
  27298. // returns 0: not supported, 1: off, 2:read, 3:write, 4:read/write
  27299. break;
  27300. // none of these are handled (yet)..
  27301. case audioMasterBeginEdit:
  27302. case audioMasterEndEdit:
  27303. case audioMasterSetTime:
  27304. case audioMasterPinConnected:
  27305. case audioMasterGetParameterQuantization:
  27306. case audioMasterIOChanged:
  27307. case audioMasterGetInputLatency:
  27308. case audioMasterGetOutputLatency:
  27309. case audioMasterGetPreviousPlug:
  27310. case audioMasterGetNextPlug:
  27311. case audioMasterWillReplaceOrAccumulate:
  27312. case audioMasterGetCurrentProcessLevel:
  27313. case audioMasterOfflineStart:
  27314. case audioMasterOfflineRead:
  27315. case audioMasterOfflineWrite:
  27316. case audioMasterOfflineGetCurrentPass:
  27317. case audioMasterOfflineGetCurrentMetaPass:
  27318. case audioMasterVendorSpecific:
  27319. case audioMasterSetIcon:
  27320. case audioMasterGetLanguage:
  27321. case audioMasterOpenWindow:
  27322. case audioMasterCloseWindow:
  27323. break;
  27324. default:
  27325. return handleGeneralCallback (opcode, index, value, ptr, opt);
  27326. }
  27327. return 0;
  27328. }
  27329. // entry point for all callbacks from the plugin
  27330. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt)
  27331. {
  27332. try
  27333. {
  27334. if (effect != 0 && effect->resvd2 != 0)
  27335. {
  27336. return ((VSTPluginInstance*)(effect->resvd2))
  27337. ->handleCallback (opcode, index, value, ptr, opt);
  27338. }
  27339. return handleGeneralCallback (opcode, index, value, ptr, opt);
  27340. }
  27341. catch (...)
  27342. {
  27343. return 0;
  27344. }
  27345. }
  27346. const String VSTPluginInstance::getVersion() const throw()
  27347. {
  27348. unsigned int v = dispatch (effGetVendorVersion, 0, 0, 0, 0);
  27349. String s;
  27350. if (v == 0 || v == -1)
  27351. v = getVersionNumber();
  27352. if (v != 0)
  27353. {
  27354. int versionBits[4];
  27355. int n = 0;
  27356. while (v != 0)
  27357. {
  27358. versionBits [n++] = (v & 0xff);
  27359. v >>= 8;
  27360. }
  27361. s << 'V';
  27362. while (n > 0)
  27363. {
  27364. s << versionBits [--n];
  27365. if (n > 0)
  27366. s << '.';
  27367. }
  27368. }
  27369. return s;
  27370. }
  27371. int VSTPluginInstance::getUID() const throw()
  27372. {
  27373. int uid = effect != 0 ? effect->uniqueID : 0;
  27374. if (uid == 0)
  27375. uid = module->file.hashCode();
  27376. return uid;
  27377. }
  27378. const String VSTPluginInstance::getCategory() const throw()
  27379. {
  27380. const char* result = 0;
  27381. switch (dispatch (effGetPlugCategory, 0, 0, 0, 0))
  27382. {
  27383. case kPlugCategEffect:
  27384. result = "Effect";
  27385. break;
  27386. case kPlugCategSynth:
  27387. result = "Synth";
  27388. break;
  27389. case kPlugCategAnalysis:
  27390. result = "Anaylsis";
  27391. break;
  27392. case kPlugCategMastering:
  27393. result = "Mastering";
  27394. break;
  27395. case kPlugCategSpacializer:
  27396. result = "Spacial";
  27397. break;
  27398. case kPlugCategRoomFx:
  27399. result = "Reverb";
  27400. break;
  27401. case kPlugSurroundFx:
  27402. result = "Surround";
  27403. break;
  27404. case kPlugCategRestoration:
  27405. result = "Restoration";
  27406. break;
  27407. case kPlugCategGenerator:
  27408. result = "Tone generation";
  27409. break;
  27410. default:
  27411. break;
  27412. }
  27413. return result;
  27414. }
  27415. float VSTPluginInstance::getParameter (int index)
  27416. {
  27417. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  27418. {
  27419. try
  27420. {
  27421. const ScopedLock sl (lock);
  27422. return effect->getParameter (effect, index);
  27423. }
  27424. catch (...)
  27425. {
  27426. }
  27427. }
  27428. return 0.0f;
  27429. }
  27430. void VSTPluginInstance::setParameter (int index, float newValue)
  27431. {
  27432. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  27433. {
  27434. try
  27435. {
  27436. const ScopedLock sl (lock);
  27437. if (effect->getParameter (effect, index) != newValue)
  27438. effect->setParameter (effect, index, newValue);
  27439. }
  27440. catch (...)
  27441. {
  27442. }
  27443. }
  27444. }
  27445. const String VSTPluginInstance::getParameterName (int index)
  27446. {
  27447. if (effect != 0)
  27448. {
  27449. jassert (index >= 0 && index < effect->numParams);
  27450. char nm [256];
  27451. zerostruct (nm);
  27452. dispatch (effGetParamName, index, 0, nm, 0);
  27453. return String (nm).trim();
  27454. }
  27455. return String::empty;
  27456. }
  27457. const String VSTPluginInstance::getParameterLabel (int index) const
  27458. {
  27459. if (effect != 0)
  27460. {
  27461. jassert (index >= 0 && index < effect->numParams);
  27462. char nm [256];
  27463. zerostruct (nm);
  27464. dispatch (effGetParamLabel, index, 0, nm, 0);
  27465. return String (nm).trim();
  27466. }
  27467. return String::empty;
  27468. }
  27469. const String VSTPluginInstance::getParameterText (int index)
  27470. {
  27471. if (effect != 0)
  27472. {
  27473. jassert (index >= 0 && index < effect->numParams);
  27474. char nm [256];
  27475. zerostruct (nm);
  27476. dispatch (effGetParamDisplay, index, 0, nm, 0);
  27477. return String (nm).trim();
  27478. }
  27479. return String::empty;
  27480. }
  27481. bool VSTPluginInstance::isParameterAutomatable (int index) const
  27482. {
  27483. if (effect != 0)
  27484. {
  27485. jassert (index >= 0 && index < effect->numParams);
  27486. return dispatch (effCanBeAutomated, index, 0, 0, 0) != 0;
  27487. }
  27488. return false;
  27489. }
  27490. void VSTPluginInstance::createTempParameterStore (MemoryBlock& dest)
  27491. {
  27492. dest.setSize (64 + 4 * getNumParameters());
  27493. dest.fillWith (0);
  27494. getCurrentProgramName().copyToCString ((char*) dest.getData(), 63);
  27495. float* const p = (float*) (((char*) dest.getData()) + 64);
  27496. for (int i = 0; i < getNumParameters(); ++i)
  27497. p[i] = getParameter(i);
  27498. }
  27499. void VSTPluginInstance::restoreFromTempParameterStore (const MemoryBlock& m)
  27500. {
  27501. changeProgramName (getCurrentProgram(), (const char*) m.getData());
  27502. float* p = (float*) (((char*) m.getData()) + 64);
  27503. for (int i = 0; i < getNumParameters(); ++i)
  27504. setParameter (i, p[i]);
  27505. }
  27506. void VSTPluginInstance::setCurrentProgram (int newIndex)
  27507. {
  27508. if (getNumPrograms() > 0 && newIndex != getCurrentProgram())
  27509. dispatch (effSetProgram, 0, jlimit (0, getNumPrograms() - 1, newIndex), 0, 0);
  27510. }
  27511. const String VSTPluginInstance::getProgramName (int index)
  27512. {
  27513. if (index == getCurrentProgram())
  27514. {
  27515. return getCurrentProgramName();
  27516. }
  27517. else if (effect != 0)
  27518. {
  27519. char nm [256];
  27520. zerostruct (nm);
  27521. if (dispatch (effGetProgramNameIndexed,
  27522. jlimit (0, getNumPrograms(), index),
  27523. -1, nm, 0) != 0)
  27524. {
  27525. return String (nm).trim();
  27526. }
  27527. }
  27528. return programNames [index];
  27529. }
  27530. void VSTPluginInstance::changeProgramName (int index, const String& newName)
  27531. {
  27532. if (index == getCurrentProgram())
  27533. {
  27534. if (getNumPrograms() > 0 && newName != getCurrentProgramName())
  27535. dispatch (effSetProgramName, 0, 0, (void*) newName.substring (0, 24).toCString(), 0.0f);
  27536. }
  27537. else
  27538. {
  27539. jassertfalse; // xxx not implemented!
  27540. }
  27541. }
  27542. void VSTPluginInstance::updateStoredProgramNames()
  27543. {
  27544. if (effect != 0 && getNumPrograms() > 0)
  27545. {
  27546. char nm [256];
  27547. zerostruct (nm);
  27548. // only do this if the plugin can't use indexed names..
  27549. if (dispatch (effGetProgramNameIndexed, 0, -1, nm, 0) == 0)
  27550. {
  27551. const int oldProgram = getCurrentProgram();
  27552. MemoryBlock oldSettings;
  27553. createTempParameterStore (oldSettings);
  27554. for (int i = 0; i < getNumPrograms(); ++i)
  27555. {
  27556. setCurrentProgram (i);
  27557. getCurrentProgramName(); // (this updates the list)
  27558. }
  27559. setCurrentProgram (oldProgram);
  27560. restoreFromTempParameterStore (oldSettings);
  27561. }
  27562. }
  27563. }
  27564. const String VSTPluginInstance::getCurrentProgramName()
  27565. {
  27566. if (effect != 0)
  27567. {
  27568. char nm [256];
  27569. zerostruct (nm);
  27570. dispatch (effGetProgramName, 0, 0, nm, 0);
  27571. const int index = getCurrentProgram();
  27572. if (programNames[index].isEmpty())
  27573. {
  27574. while (programNames.size() < index)
  27575. programNames.add (String::empty);
  27576. programNames.set (index, String (nm).trim());
  27577. }
  27578. return String (nm).trim();
  27579. }
  27580. return String::empty;
  27581. }
  27582. const String VSTPluginInstance::getInputChannelName (const int index) const
  27583. {
  27584. if (index >= 0 && index < getNumInputChannels())
  27585. {
  27586. VstPinProperties pinProps;
  27587. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  27588. return String (pinProps.label, sizeof (pinProps.label));
  27589. }
  27590. return String::empty;
  27591. }
  27592. bool VSTPluginInstance::isInputChannelStereoPair (int index) const
  27593. {
  27594. if (index < 0 || index >= getNumInputChannels())
  27595. return false;
  27596. VstPinProperties pinProps;
  27597. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  27598. return (pinProps.flags & kVstPinIsStereo) != 0;
  27599. return true;
  27600. }
  27601. const String VSTPluginInstance::getOutputChannelName (const int index) const
  27602. {
  27603. if (index >= 0 && index < getNumOutputChannels())
  27604. {
  27605. VstPinProperties pinProps;
  27606. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  27607. return String (pinProps.label, sizeof (pinProps.label));
  27608. }
  27609. return String::empty;
  27610. }
  27611. bool VSTPluginInstance::isOutputChannelStereoPair (int index) const
  27612. {
  27613. if (index < 0 || index >= getNumOutputChannels())
  27614. return false;
  27615. VstPinProperties pinProps;
  27616. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  27617. return (pinProps.flags & kVstPinIsStereo) != 0;
  27618. return true;
  27619. }
  27620. void VSTPluginInstance::setPower (const bool on)
  27621. {
  27622. dispatch (effMainsChanged, 0, on ? 1 : 0, 0, 0);
  27623. isPowerOn = on;
  27624. }
  27625. const int defaultMaxSizeMB = 64;
  27626. void VSTPluginInstance::getStateInformation (MemoryBlock& destData)
  27627. {
  27628. saveToFXBFile (destData, true, defaultMaxSizeMB);
  27629. }
  27630. void VSTPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  27631. {
  27632. saveToFXBFile (destData, false, defaultMaxSizeMB);
  27633. }
  27634. void VSTPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  27635. {
  27636. loadFromFXBFile (data, sizeInBytes);
  27637. }
  27638. void VSTPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  27639. {
  27640. loadFromFXBFile (data, sizeInBytes);
  27641. }
  27642. VSTPluginFormat::VSTPluginFormat()
  27643. {
  27644. }
  27645. VSTPluginFormat::~VSTPluginFormat()
  27646. {
  27647. }
  27648. void VSTPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  27649. const String& fileOrIdentifier)
  27650. {
  27651. if (! fileMightContainThisPluginType (fileOrIdentifier))
  27652. return;
  27653. PluginDescription desc;
  27654. desc.fileOrIdentifier = fileOrIdentifier;
  27655. desc.uid = 0;
  27656. ScopedPointer <VSTPluginInstance> instance (dynamic_cast <VSTPluginInstance*> (createInstanceFromDescription (desc)));
  27657. if (instance == 0)
  27658. return;
  27659. try
  27660. {
  27661. #if JUCE_MAC
  27662. if (instance->module->resFileId != 0)
  27663. UseResFile (instance->module->resFileId);
  27664. #endif
  27665. instance->fillInPluginDescription (desc);
  27666. VstPlugCategory category = (VstPlugCategory) instance->dispatch (effGetPlugCategory, 0, 0, 0, 0);
  27667. if (category != kPlugCategShell)
  27668. {
  27669. // Normal plugin...
  27670. results.add (new PluginDescription (desc));
  27671. ++insideVSTCallback;
  27672. instance->dispatch (effOpen, 0, 0, 0, 0);
  27673. --insideVSTCallback;
  27674. }
  27675. else
  27676. {
  27677. // It's a shell plugin, so iterate all the subtypes...
  27678. char shellEffectName [64];
  27679. for (;;)
  27680. {
  27681. zerostruct (shellEffectName);
  27682. const int uid = instance->dispatch (effShellGetNextPlugin, 0, 0, shellEffectName, 0);
  27683. if (uid == 0)
  27684. {
  27685. break;
  27686. }
  27687. else
  27688. {
  27689. desc.uid = uid;
  27690. desc.name = shellEffectName;
  27691. bool alreadyThere = false;
  27692. for (int i = results.size(); --i >= 0;)
  27693. {
  27694. PluginDescription* const d = results.getUnchecked(i);
  27695. if (d->isDuplicateOf (desc))
  27696. {
  27697. alreadyThere = true;
  27698. break;
  27699. }
  27700. }
  27701. if (! alreadyThere)
  27702. results.add (new PluginDescription (desc));
  27703. }
  27704. }
  27705. }
  27706. }
  27707. catch (...)
  27708. {
  27709. // crashed while loading...
  27710. }
  27711. }
  27712. AudioPluginInstance* VSTPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  27713. {
  27714. ScopedPointer <VSTPluginInstance> result;
  27715. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  27716. {
  27717. File file (desc.fileOrIdentifier);
  27718. const File previousWorkingDirectory (File::getCurrentWorkingDirectory());
  27719. file.getParentDirectory().setAsCurrentWorkingDirectory();
  27720. const ReferenceCountedObjectPtr <ModuleHandle> module (ModuleHandle::findOrCreateModule (file));
  27721. if (module != 0)
  27722. {
  27723. shellUIDToCreate = desc.uid;
  27724. result = new VSTPluginInstance (module);
  27725. if (result->effect != 0)
  27726. {
  27727. result->effect->resvd2 = (VstIntPtr) (pointer_sized_int) (VSTPluginInstance*) result;
  27728. result->initialise();
  27729. }
  27730. else
  27731. {
  27732. result = 0;
  27733. }
  27734. }
  27735. previousWorkingDirectory.setAsCurrentWorkingDirectory();
  27736. }
  27737. return result.release();
  27738. }
  27739. bool VSTPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  27740. {
  27741. const File f (fileOrIdentifier);
  27742. #if JUCE_MAC
  27743. if (f.isDirectory() && f.hasFileExtension (".vst"))
  27744. return true;
  27745. #if JUCE_PPC
  27746. FSRef fileRef;
  27747. if (PlatformUtilities::makeFSRefFromPath (&fileRef, f.getFullPathName()))
  27748. {
  27749. const short resFileId = FSOpenResFile (&fileRef, fsRdPerm);
  27750. if (resFileId != -1)
  27751. {
  27752. const int numEffects = Count1Resources ('aEff');
  27753. CloseResFile (resFileId);
  27754. if (numEffects > 0)
  27755. return true;
  27756. }
  27757. }
  27758. #endif
  27759. return false;
  27760. #elif JUCE_WINDOWS
  27761. return f.existsAsFile()
  27762. && f.hasFileExtension (".dll");
  27763. #elif JUCE_LINUX
  27764. return f.existsAsFile()
  27765. && f.hasFileExtension (".so");
  27766. #endif
  27767. }
  27768. const String VSTPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  27769. {
  27770. return fileOrIdentifier;
  27771. }
  27772. bool VSTPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  27773. {
  27774. return File (desc.fileOrIdentifier).exists();
  27775. }
  27776. const StringArray VSTPluginFormat::searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive)
  27777. {
  27778. StringArray results;
  27779. for (int j = 0; j < directoriesToSearch.getNumPaths(); ++j)
  27780. recursiveFileSearch (results, directoriesToSearch [j], recursive);
  27781. return results;
  27782. }
  27783. void VSTPluginFormat::recursiveFileSearch (StringArray& results, const File& dir, const bool recursive)
  27784. {
  27785. // avoid allowing the dir iterator to be recursive, because we want to avoid letting it delve inside
  27786. // .component or .vst directories.
  27787. DirectoryIterator iter (dir, false, "*", File::findFilesAndDirectories);
  27788. while (iter.next())
  27789. {
  27790. const File f (iter.getFile());
  27791. bool isPlugin = false;
  27792. if (fileMightContainThisPluginType (f.getFullPathName()))
  27793. {
  27794. isPlugin = true;
  27795. results.add (f.getFullPathName());
  27796. }
  27797. if (recursive && (! isPlugin) && f.isDirectory())
  27798. recursiveFileSearch (results, f, true);
  27799. }
  27800. }
  27801. const FileSearchPath VSTPluginFormat::getDefaultLocationsToSearch()
  27802. {
  27803. #if JUCE_MAC
  27804. return FileSearchPath ("~/Library/Audio/Plug-Ins/VST;/Library/Audio/Plug-Ins/VST");
  27805. #elif JUCE_WINDOWS
  27806. const String programFiles (File::getSpecialLocation (File::globalApplicationsDirectory).getFullPathName());
  27807. return FileSearchPath (programFiles + "\\Steinberg\\VstPlugins");
  27808. #elif JUCE_LINUX
  27809. return FileSearchPath ("/usr/lib/vst");
  27810. #endif
  27811. }
  27812. END_JUCE_NAMESPACE
  27813. #endif
  27814. #undef log
  27815. #endif
  27816. /*** End of inlined file: juce_VSTPluginFormat.cpp ***/
  27817. /*** End of inlined file: juce_VSTPluginFormat.mm ***/
  27818. /*** Start of inlined file: juce_AudioProcessor.cpp ***/
  27819. BEGIN_JUCE_NAMESPACE
  27820. AudioProcessor::AudioProcessor()
  27821. : playHead (0),
  27822. activeEditor (0),
  27823. sampleRate (0),
  27824. blockSize (0),
  27825. numInputChannels (0),
  27826. numOutputChannels (0),
  27827. latencySamples (0),
  27828. suspended (false),
  27829. nonRealtime (false)
  27830. {
  27831. }
  27832. AudioProcessor::~AudioProcessor()
  27833. {
  27834. // ooh, nasty - the editor should have been deleted before the filter
  27835. // that it refers to is deleted..
  27836. jassert (activeEditor == 0);
  27837. #if JUCE_DEBUG
  27838. // This will fail if you've called beginParameterChangeGesture() for one
  27839. // or more parameters without having made a corresponding call to endParameterChangeGesture...
  27840. jassert (changingParams.countNumberOfSetBits() == 0);
  27841. #endif
  27842. }
  27843. void AudioProcessor::setPlayHead (AudioPlayHead* const newPlayHead) throw()
  27844. {
  27845. playHead = newPlayHead;
  27846. }
  27847. void AudioProcessor::addListener (AudioProcessorListener* const newListener) throw()
  27848. {
  27849. const ScopedLock sl (listenerLock);
  27850. listeners.addIfNotAlreadyThere (newListener);
  27851. }
  27852. void AudioProcessor::removeListener (AudioProcessorListener* const listenerToRemove) throw()
  27853. {
  27854. const ScopedLock sl (listenerLock);
  27855. listeners.removeValue (listenerToRemove);
  27856. }
  27857. void AudioProcessor::setPlayConfigDetails (const int numIns,
  27858. const int numOuts,
  27859. const double sampleRate_,
  27860. const int blockSize_) throw()
  27861. {
  27862. numInputChannels = numIns;
  27863. numOutputChannels = numOuts;
  27864. sampleRate = sampleRate_;
  27865. blockSize = blockSize_;
  27866. }
  27867. void AudioProcessor::setNonRealtime (const bool nonRealtime_) throw()
  27868. {
  27869. nonRealtime = nonRealtime_;
  27870. }
  27871. void AudioProcessor::setLatencySamples (const int newLatency)
  27872. {
  27873. if (latencySamples != newLatency)
  27874. {
  27875. latencySamples = newLatency;
  27876. updateHostDisplay();
  27877. }
  27878. }
  27879. void AudioProcessor::setParameterNotifyingHost (const int parameterIndex,
  27880. const float newValue)
  27881. {
  27882. setParameter (parameterIndex, newValue);
  27883. sendParamChangeMessageToListeners (parameterIndex, newValue);
  27884. }
  27885. void AudioProcessor::sendParamChangeMessageToListeners (const int parameterIndex, const float newValue)
  27886. {
  27887. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  27888. for (int i = listeners.size(); --i >= 0;)
  27889. {
  27890. AudioProcessorListener* l;
  27891. {
  27892. const ScopedLock sl (listenerLock);
  27893. l = listeners [i];
  27894. }
  27895. if (l != 0)
  27896. l->audioProcessorParameterChanged (this, parameterIndex, newValue);
  27897. }
  27898. }
  27899. void AudioProcessor::beginParameterChangeGesture (int parameterIndex)
  27900. {
  27901. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  27902. #if JUCE_DEBUG
  27903. // This means you've called beginParameterChangeGesture twice in succession without a matching
  27904. // call to endParameterChangeGesture. That might be fine in most hosts, but better to avoid doing it.
  27905. jassert (! changingParams [parameterIndex]);
  27906. changingParams.setBit (parameterIndex);
  27907. #endif
  27908. for (int i = listeners.size(); --i >= 0;)
  27909. {
  27910. AudioProcessorListener* l;
  27911. {
  27912. const ScopedLock sl (listenerLock);
  27913. l = listeners [i];
  27914. }
  27915. if (l != 0)
  27916. l->audioProcessorParameterChangeGestureBegin (this, parameterIndex);
  27917. }
  27918. }
  27919. void AudioProcessor::endParameterChangeGesture (int parameterIndex)
  27920. {
  27921. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  27922. #if JUCE_DEBUG
  27923. // This means you've called endParameterChangeGesture without having previously called
  27924. // endParameterChangeGesture. That might be fine in most hosts, but better to keep the
  27925. // calls matched correctly.
  27926. jassert (changingParams [parameterIndex]);
  27927. changingParams.clearBit (parameterIndex);
  27928. #endif
  27929. for (int i = listeners.size(); --i >= 0;)
  27930. {
  27931. AudioProcessorListener* l;
  27932. {
  27933. const ScopedLock sl (listenerLock);
  27934. l = listeners [i];
  27935. }
  27936. if (l != 0)
  27937. l->audioProcessorParameterChangeGestureEnd (this, parameterIndex);
  27938. }
  27939. }
  27940. void AudioProcessor::updateHostDisplay()
  27941. {
  27942. for (int i = listeners.size(); --i >= 0;)
  27943. {
  27944. AudioProcessorListener* l;
  27945. {
  27946. const ScopedLock sl (listenerLock);
  27947. l = listeners [i];
  27948. }
  27949. if (l != 0)
  27950. l->audioProcessorChanged (this);
  27951. }
  27952. }
  27953. bool AudioProcessor::isParameterAutomatable (int /*parameterIndex*/) const
  27954. {
  27955. return true;
  27956. }
  27957. bool AudioProcessor::isMetaParameter (int /*parameterIndex*/) const
  27958. {
  27959. return false;
  27960. }
  27961. void AudioProcessor::suspendProcessing (const bool shouldBeSuspended)
  27962. {
  27963. const ScopedLock sl (callbackLock);
  27964. suspended = shouldBeSuspended;
  27965. }
  27966. void AudioProcessor::reset()
  27967. {
  27968. }
  27969. void AudioProcessor::editorBeingDeleted (AudioProcessorEditor* const editor) throw()
  27970. {
  27971. const ScopedLock sl (callbackLock);
  27972. jassert (activeEditor == editor);
  27973. if (activeEditor == editor)
  27974. activeEditor = 0;
  27975. }
  27976. AudioProcessorEditor* AudioProcessor::createEditorIfNeeded()
  27977. {
  27978. if (activeEditor != 0)
  27979. return activeEditor;
  27980. AudioProcessorEditor* const ed = createEditor();
  27981. if (ed != 0)
  27982. {
  27983. // you must give your editor comp a size before returning it..
  27984. jassert (ed->getWidth() > 0 && ed->getHeight() > 0);
  27985. const ScopedLock sl (callbackLock);
  27986. activeEditor = ed;
  27987. }
  27988. return ed;
  27989. }
  27990. void AudioProcessor::getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData)
  27991. {
  27992. getStateInformation (destData);
  27993. }
  27994. void AudioProcessor::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  27995. {
  27996. setStateInformation (data, sizeInBytes);
  27997. }
  27998. // magic number to identify memory blocks that we've stored as XML
  27999. const uint32 magicXmlNumber = 0x21324356;
  28000. void AudioProcessor::copyXmlToBinary (const XmlElement& xml,
  28001. JUCE_NAMESPACE::MemoryBlock& destData)
  28002. {
  28003. const String xmlString (xml.createDocument (String::empty, true, false));
  28004. const int stringLength = xmlString.getNumBytesAsUTF8();
  28005. destData.setSize (stringLength + 10);
  28006. char* const d = (char*) destData.getData();
  28007. *(uint32*) d = ByteOrder::swapIfBigEndian ((const uint32) magicXmlNumber);
  28008. *(uint32*) (d + 4) = ByteOrder::swapIfBigEndian ((const uint32) stringLength);
  28009. xmlString.copyToUTF8 (d + 8, stringLength + 1);
  28010. }
  28011. XmlElement* AudioProcessor::getXmlFromBinary (const void* data,
  28012. const int sizeInBytes)
  28013. {
  28014. if (sizeInBytes > 8
  28015. && ByteOrder::littleEndianInt (data) == magicXmlNumber)
  28016. {
  28017. const int stringLength = (int) ByteOrder::littleEndianInt (((const char*) data) + 4);
  28018. if (stringLength > 0)
  28019. {
  28020. XmlDocument doc (String::fromUTF8 (((const char*) data) + 8,
  28021. jmin ((sizeInBytes - 8), stringLength)));
  28022. return doc.getDocumentElement();
  28023. }
  28024. }
  28025. return 0;
  28026. }
  28027. void AudioProcessorListener::audioProcessorParameterChangeGestureBegin (AudioProcessor*, int)
  28028. {
  28029. }
  28030. void AudioProcessorListener::audioProcessorParameterChangeGestureEnd (AudioProcessor*, int)
  28031. {
  28032. }
  28033. bool AudioPlayHead::CurrentPositionInfo::operator== (const CurrentPositionInfo& other) const throw()
  28034. {
  28035. return timeInSeconds == other.timeInSeconds
  28036. && ppqPosition == other.ppqPosition
  28037. && editOriginTime == other.editOriginTime
  28038. && ppqPositionOfLastBarStart == other.ppqPositionOfLastBarStart
  28039. && frameRate == other.frameRate
  28040. && isPlaying == other.isPlaying
  28041. && isRecording == other.isRecording
  28042. && bpm == other.bpm
  28043. && timeSigNumerator == other.timeSigNumerator
  28044. && timeSigDenominator == other.timeSigDenominator;
  28045. }
  28046. bool AudioPlayHead::CurrentPositionInfo::operator!= (const CurrentPositionInfo& other) const throw()
  28047. {
  28048. return ! operator== (other);
  28049. }
  28050. void AudioPlayHead::CurrentPositionInfo::resetToDefault()
  28051. {
  28052. zerostruct (*this);
  28053. timeSigNumerator = 4;
  28054. timeSigDenominator = 4;
  28055. bpm = 120;
  28056. }
  28057. END_JUCE_NAMESPACE
  28058. /*** End of inlined file: juce_AudioProcessor.cpp ***/
  28059. /*** Start of inlined file: juce_AudioProcessorEditor.cpp ***/
  28060. BEGIN_JUCE_NAMESPACE
  28061. AudioProcessorEditor::AudioProcessorEditor (AudioProcessor* const owner_)
  28062. : owner (owner_)
  28063. {
  28064. // the filter must be valid..
  28065. jassert (owner != 0);
  28066. }
  28067. AudioProcessorEditor::~AudioProcessorEditor()
  28068. {
  28069. // if this fails, then the wrapper hasn't called editorBeingDeleted() on the
  28070. // filter for some reason..
  28071. jassert (owner->getActiveEditor() != this);
  28072. }
  28073. END_JUCE_NAMESPACE
  28074. /*** End of inlined file: juce_AudioProcessorEditor.cpp ***/
  28075. /*** Start of inlined file: juce_AudioProcessorGraph.cpp ***/
  28076. BEGIN_JUCE_NAMESPACE
  28077. const int AudioProcessorGraph::midiChannelIndex = 0x1000;
  28078. AudioProcessorGraph::Node::Node (const uint32 id_, AudioProcessor* const processor_)
  28079. : id (id_),
  28080. processor (processor_),
  28081. isPrepared (false)
  28082. {
  28083. jassert (processor_ != 0);
  28084. }
  28085. AudioProcessorGraph::Node::~Node()
  28086. {
  28087. delete processor;
  28088. }
  28089. void AudioProcessorGraph::Node::prepare (const double sampleRate, const int blockSize,
  28090. AudioProcessorGraph* const graph)
  28091. {
  28092. if (! isPrepared)
  28093. {
  28094. isPrepared = true;
  28095. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28096. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (processor);
  28097. if (ioProc != 0)
  28098. ioProc->setParentGraph (graph);
  28099. processor->setPlayConfigDetails (processor->getNumInputChannels(),
  28100. processor->getNumOutputChannels(),
  28101. sampleRate, blockSize);
  28102. processor->prepareToPlay (sampleRate, blockSize);
  28103. }
  28104. }
  28105. void AudioProcessorGraph::Node::unprepare()
  28106. {
  28107. if (isPrepared)
  28108. {
  28109. isPrepared = false;
  28110. processor->releaseResources();
  28111. }
  28112. }
  28113. AudioProcessorGraph::AudioProcessorGraph()
  28114. : lastNodeId (0),
  28115. renderingBuffers (1, 1),
  28116. currentAudioOutputBuffer (1, 1)
  28117. {
  28118. }
  28119. AudioProcessorGraph::~AudioProcessorGraph()
  28120. {
  28121. clearRenderingSequence();
  28122. clear();
  28123. }
  28124. const String AudioProcessorGraph::getName() const
  28125. {
  28126. return "Audio Graph";
  28127. }
  28128. void AudioProcessorGraph::clear()
  28129. {
  28130. nodes.clear();
  28131. connections.clear();
  28132. triggerAsyncUpdate();
  28133. }
  28134. AudioProcessorGraph::Node* AudioProcessorGraph::getNodeForId (const uint32 nodeId) const
  28135. {
  28136. for (int i = nodes.size(); --i >= 0;)
  28137. if (nodes.getUnchecked(i)->id == nodeId)
  28138. return nodes.getUnchecked(i);
  28139. return 0;
  28140. }
  28141. AudioProcessorGraph::Node* AudioProcessorGraph::addNode (AudioProcessor* const newProcessor,
  28142. uint32 nodeId)
  28143. {
  28144. if (newProcessor == 0)
  28145. {
  28146. jassertfalse;
  28147. return 0;
  28148. }
  28149. if (nodeId == 0)
  28150. {
  28151. nodeId = ++lastNodeId;
  28152. }
  28153. else
  28154. {
  28155. // you can't add a node with an id that already exists in the graph..
  28156. jassert (getNodeForId (nodeId) == 0);
  28157. removeNode (nodeId);
  28158. }
  28159. lastNodeId = nodeId;
  28160. Node* const n = new Node (nodeId, newProcessor);
  28161. nodes.add (n);
  28162. triggerAsyncUpdate();
  28163. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28164. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (n->processor);
  28165. if (ioProc != 0)
  28166. ioProc->setParentGraph (this);
  28167. return n;
  28168. }
  28169. bool AudioProcessorGraph::removeNode (const uint32 nodeId)
  28170. {
  28171. disconnectNode (nodeId);
  28172. for (int i = nodes.size(); --i >= 0;)
  28173. {
  28174. if (nodes.getUnchecked(i)->id == nodeId)
  28175. {
  28176. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28177. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (nodes.getUnchecked(i)->processor);
  28178. if (ioProc != 0)
  28179. ioProc->setParentGraph (0);
  28180. nodes.remove (i);
  28181. triggerAsyncUpdate();
  28182. return true;
  28183. }
  28184. }
  28185. return false;
  28186. }
  28187. const AudioProcessorGraph::Connection* AudioProcessorGraph::getConnectionBetween (const uint32 sourceNodeId,
  28188. const int sourceChannelIndex,
  28189. const uint32 destNodeId,
  28190. const int destChannelIndex) const
  28191. {
  28192. for (int i = connections.size(); --i >= 0;)
  28193. {
  28194. const Connection* const c = connections.getUnchecked(i);
  28195. if (c->sourceNodeId == sourceNodeId
  28196. && c->destNodeId == destNodeId
  28197. && c->sourceChannelIndex == sourceChannelIndex
  28198. && c->destChannelIndex == destChannelIndex)
  28199. {
  28200. return c;
  28201. }
  28202. }
  28203. return 0;
  28204. }
  28205. bool AudioProcessorGraph::isConnected (const uint32 possibleSourceNodeId,
  28206. const uint32 possibleDestNodeId) const
  28207. {
  28208. for (int i = connections.size(); --i >= 0;)
  28209. {
  28210. const Connection* const c = connections.getUnchecked(i);
  28211. if (c->sourceNodeId == possibleSourceNodeId
  28212. && c->destNodeId == possibleDestNodeId)
  28213. {
  28214. return true;
  28215. }
  28216. }
  28217. return false;
  28218. }
  28219. bool AudioProcessorGraph::canConnect (const uint32 sourceNodeId,
  28220. const int sourceChannelIndex,
  28221. const uint32 destNodeId,
  28222. const int destChannelIndex) const
  28223. {
  28224. if (sourceChannelIndex < 0
  28225. || destChannelIndex < 0
  28226. || sourceNodeId == destNodeId
  28227. || (destChannelIndex == midiChannelIndex) != (sourceChannelIndex == midiChannelIndex))
  28228. return false;
  28229. const Node* const source = getNodeForId (sourceNodeId);
  28230. if (source == 0
  28231. || (sourceChannelIndex != midiChannelIndex && sourceChannelIndex >= source->processor->getNumOutputChannels())
  28232. || (sourceChannelIndex == midiChannelIndex && ! source->processor->producesMidi()))
  28233. return false;
  28234. const Node* const dest = getNodeForId (destNodeId);
  28235. if (dest == 0
  28236. || (destChannelIndex != midiChannelIndex && destChannelIndex >= dest->processor->getNumInputChannels())
  28237. || (destChannelIndex == midiChannelIndex && ! dest->processor->acceptsMidi()))
  28238. return false;
  28239. return getConnectionBetween (sourceNodeId, sourceChannelIndex,
  28240. destNodeId, destChannelIndex) == 0;
  28241. }
  28242. bool AudioProcessorGraph::addConnection (const uint32 sourceNodeId,
  28243. const int sourceChannelIndex,
  28244. const uint32 destNodeId,
  28245. const int destChannelIndex)
  28246. {
  28247. if (! canConnect (sourceNodeId, sourceChannelIndex, destNodeId, destChannelIndex))
  28248. return false;
  28249. Connection* const c = new Connection();
  28250. c->sourceNodeId = sourceNodeId;
  28251. c->sourceChannelIndex = sourceChannelIndex;
  28252. c->destNodeId = destNodeId;
  28253. c->destChannelIndex = destChannelIndex;
  28254. connections.add (c);
  28255. triggerAsyncUpdate();
  28256. return true;
  28257. }
  28258. void AudioProcessorGraph::removeConnection (const int index)
  28259. {
  28260. connections.remove (index);
  28261. triggerAsyncUpdate();
  28262. }
  28263. bool AudioProcessorGraph::removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  28264. const uint32 destNodeId, const int destChannelIndex)
  28265. {
  28266. bool doneAnything = false;
  28267. for (int i = connections.size(); --i >= 0;)
  28268. {
  28269. const Connection* const c = connections.getUnchecked(i);
  28270. if (c->sourceNodeId == sourceNodeId
  28271. && c->destNodeId == destNodeId
  28272. && c->sourceChannelIndex == sourceChannelIndex
  28273. && c->destChannelIndex == destChannelIndex)
  28274. {
  28275. removeConnection (i);
  28276. doneAnything = true;
  28277. triggerAsyncUpdate();
  28278. }
  28279. }
  28280. return doneAnything;
  28281. }
  28282. bool AudioProcessorGraph::disconnectNode (const uint32 nodeId)
  28283. {
  28284. bool doneAnything = false;
  28285. for (int i = connections.size(); --i >= 0;)
  28286. {
  28287. const Connection* const c = connections.getUnchecked(i);
  28288. if (c->sourceNodeId == nodeId || c->destNodeId == nodeId)
  28289. {
  28290. removeConnection (i);
  28291. doneAnything = true;
  28292. triggerAsyncUpdate();
  28293. }
  28294. }
  28295. return doneAnything;
  28296. }
  28297. bool AudioProcessorGraph::removeIllegalConnections()
  28298. {
  28299. bool doneAnything = false;
  28300. for (int i = connections.size(); --i >= 0;)
  28301. {
  28302. const Connection* const c = connections.getUnchecked(i);
  28303. const Node* const source = getNodeForId (c->sourceNodeId);
  28304. const Node* const dest = getNodeForId (c->destNodeId);
  28305. if (source == 0 || dest == 0
  28306. || (c->sourceChannelIndex != midiChannelIndex
  28307. && (((unsigned int) c->sourceChannelIndex) >= (unsigned int) source->processor->getNumOutputChannels()))
  28308. || (c->sourceChannelIndex == midiChannelIndex
  28309. && ! source->processor->producesMidi())
  28310. || (c->destChannelIndex != midiChannelIndex
  28311. && (((unsigned int) c->destChannelIndex) >= (unsigned int) dest->processor->getNumInputChannels()))
  28312. || (c->destChannelIndex == midiChannelIndex
  28313. && ! dest->processor->acceptsMidi()))
  28314. {
  28315. removeConnection (i);
  28316. doneAnything = true;
  28317. triggerAsyncUpdate();
  28318. }
  28319. }
  28320. return doneAnything;
  28321. }
  28322. namespace GraphRenderingOps
  28323. {
  28324. class AudioGraphRenderingOp
  28325. {
  28326. public:
  28327. AudioGraphRenderingOp() {}
  28328. virtual ~AudioGraphRenderingOp() {}
  28329. virtual void perform (AudioSampleBuffer& sharedBufferChans,
  28330. const OwnedArray <MidiBuffer>& sharedMidiBuffers,
  28331. const int numSamples) = 0;
  28332. juce_UseDebuggingNewOperator
  28333. };
  28334. class ClearChannelOp : public AudioGraphRenderingOp
  28335. {
  28336. public:
  28337. ClearChannelOp (const int channelNum_)
  28338. : channelNum (channelNum_)
  28339. {}
  28340. ~ClearChannelOp() {}
  28341. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  28342. {
  28343. sharedBufferChans.clear (channelNum, 0, numSamples);
  28344. }
  28345. private:
  28346. const int channelNum;
  28347. ClearChannelOp (const ClearChannelOp&);
  28348. ClearChannelOp& operator= (const ClearChannelOp&);
  28349. };
  28350. class CopyChannelOp : public AudioGraphRenderingOp
  28351. {
  28352. public:
  28353. CopyChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  28354. : srcChannelNum (srcChannelNum_),
  28355. dstChannelNum (dstChannelNum_)
  28356. {}
  28357. ~CopyChannelOp() {}
  28358. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  28359. {
  28360. sharedBufferChans.copyFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  28361. }
  28362. private:
  28363. const int srcChannelNum, dstChannelNum;
  28364. CopyChannelOp (const CopyChannelOp&);
  28365. CopyChannelOp& operator= (const CopyChannelOp&);
  28366. };
  28367. class AddChannelOp : public AudioGraphRenderingOp
  28368. {
  28369. public:
  28370. AddChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  28371. : srcChannelNum (srcChannelNum_),
  28372. dstChannelNum (dstChannelNum_)
  28373. {}
  28374. ~AddChannelOp() {}
  28375. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  28376. {
  28377. sharedBufferChans.addFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  28378. }
  28379. private:
  28380. const int srcChannelNum, dstChannelNum;
  28381. AddChannelOp (const AddChannelOp&);
  28382. AddChannelOp& operator= (const AddChannelOp&);
  28383. };
  28384. class ClearMidiBufferOp : public AudioGraphRenderingOp
  28385. {
  28386. public:
  28387. ClearMidiBufferOp (const int bufferNum_)
  28388. : bufferNum (bufferNum_)
  28389. {}
  28390. ~ClearMidiBufferOp() {}
  28391. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  28392. {
  28393. sharedMidiBuffers.getUnchecked (bufferNum)->clear();
  28394. }
  28395. private:
  28396. const int bufferNum;
  28397. ClearMidiBufferOp (const ClearMidiBufferOp&);
  28398. ClearMidiBufferOp& operator= (const ClearMidiBufferOp&);
  28399. };
  28400. class CopyMidiBufferOp : public AudioGraphRenderingOp
  28401. {
  28402. public:
  28403. CopyMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  28404. : srcBufferNum (srcBufferNum_),
  28405. dstBufferNum (dstBufferNum_)
  28406. {}
  28407. ~CopyMidiBufferOp() {}
  28408. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  28409. {
  28410. *sharedMidiBuffers.getUnchecked (dstBufferNum) = *sharedMidiBuffers.getUnchecked (srcBufferNum);
  28411. }
  28412. private:
  28413. const int srcBufferNum, dstBufferNum;
  28414. CopyMidiBufferOp (const CopyMidiBufferOp&);
  28415. CopyMidiBufferOp& operator= (const CopyMidiBufferOp&);
  28416. };
  28417. class AddMidiBufferOp : public AudioGraphRenderingOp
  28418. {
  28419. public:
  28420. AddMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  28421. : srcBufferNum (srcBufferNum_),
  28422. dstBufferNum (dstBufferNum_)
  28423. {}
  28424. ~AddMidiBufferOp() {}
  28425. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  28426. {
  28427. sharedMidiBuffers.getUnchecked (dstBufferNum)
  28428. ->addEvents (*sharedMidiBuffers.getUnchecked (srcBufferNum), 0, numSamples, 0);
  28429. }
  28430. private:
  28431. const int srcBufferNum, dstBufferNum;
  28432. AddMidiBufferOp (const AddMidiBufferOp&);
  28433. AddMidiBufferOp& operator= (const AddMidiBufferOp&);
  28434. };
  28435. class ProcessBufferOp : public AudioGraphRenderingOp
  28436. {
  28437. public:
  28438. ProcessBufferOp (const AudioProcessorGraph::Node::Ptr& node_,
  28439. const Array <int>& audioChannelsToUse_,
  28440. const int totalChans_,
  28441. const int midiBufferToUse_)
  28442. : node (node_),
  28443. processor (node_->processor),
  28444. audioChannelsToUse (audioChannelsToUse_),
  28445. totalChans (jmax (1, totalChans_)),
  28446. midiBufferToUse (midiBufferToUse_)
  28447. {
  28448. channels.calloc (totalChans);
  28449. while (audioChannelsToUse.size() < totalChans)
  28450. audioChannelsToUse.add (0);
  28451. }
  28452. ~ProcessBufferOp()
  28453. {
  28454. }
  28455. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  28456. {
  28457. for (int i = totalChans; --i >= 0;)
  28458. channels[i] = sharedBufferChans.getSampleData (audioChannelsToUse.getUnchecked (i), 0);
  28459. AudioSampleBuffer buffer (channels, totalChans, numSamples);
  28460. processor->processBlock (buffer, *sharedMidiBuffers.getUnchecked (midiBufferToUse));
  28461. }
  28462. const AudioProcessorGraph::Node::Ptr node;
  28463. AudioProcessor* const processor;
  28464. private:
  28465. Array <int> audioChannelsToUse;
  28466. HeapBlock <float*> channels;
  28467. int totalChans;
  28468. int midiBufferToUse;
  28469. ProcessBufferOp (const ProcessBufferOp&);
  28470. ProcessBufferOp& operator= (const ProcessBufferOp&);
  28471. };
  28472. /** Used to calculate the correct sequence of rendering ops needed, based on
  28473. the best re-use of shared buffers at each stage.
  28474. */
  28475. class RenderingOpSequenceCalculator
  28476. {
  28477. public:
  28478. RenderingOpSequenceCalculator (AudioProcessorGraph& graph_,
  28479. const Array<void*>& orderedNodes_,
  28480. Array<void*>& renderingOps)
  28481. : graph (graph_),
  28482. orderedNodes (orderedNodes_)
  28483. {
  28484. nodeIds.add (-2); // first buffer is read-only zeros
  28485. channels.add (0);
  28486. midiNodeIds.add (-2);
  28487. for (int i = 0; i < orderedNodes.size(); ++i)
  28488. {
  28489. createRenderingOpsForNode ((AudioProcessorGraph::Node*) orderedNodes.getUnchecked(i),
  28490. renderingOps, i);
  28491. markAnyUnusedBuffersAsFree (i);
  28492. }
  28493. }
  28494. int getNumBuffersNeeded() const { return nodeIds.size(); }
  28495. int getNumMidiBuffersNeeded() const { return midiNodeIds.size(); }
  28496. juce_UseDebuggingNewOperator
  28497. private:
  28498. AudioProcessorGraph& graph;
  28499. const Array<void*>& orderedNodes;
  28500. Array <int> nodeIds, channels, midiNodeIds;
  28501. void createRenderingOpsForNode (AudioProcessorGraph::Node* const node,
  28502. Array<void*>& renderingOps,
  28503. const int ourRenderingIndex)
  28504. {
  28505. const int numIns = node->processor->getNumInputChannels();
  28506. const int numOuts = node->processor->getNumOutputChannels();
  28507. const int totalChans = jmax (numIns, numOuts);
  28508. Array <int> audioChannelsToUse;
  28509. int midiBufferToUse = -1;
  28510. for (int inputChan = 0; inputChan < numIns; ++inputChan)
  28511. {
  28512. // get a list of all the inputs to this node
  28513. Array <int> sourceNodes, sourceOutputChans;
  28514. for (int i = graph.getNumConnections(); --i >= 0;)
  28515. {
  28516. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  28517. if (c->destNodeId == node->id && c->destChannelIndex == inputChan)
  28518. {
  28519. sourceNodes.add (c->sourceNodeId);
  28520. sourceOutputChans.add (c->sourceChannelIndex);
  28521. }
  28522. }
  28523. int bufIndex = -1;
  28524. if (sourceNodes.size() == 0)
  28525. {
  28526. // unconnected input channel
  28527. if (inputChan >= numOuts)
  28528. {
  28529. bufIndex = getReadOnlyEmptyBuffer();
  28530. jassert (bufIndex >= 0);
  28531. }
  28532. else
  28533. {
  28534. bufIndex = getFreeBuffer (false);
  28535. renderingOps.add (new ClearChannelOp (bufIndex));
  28536. }
  28537. }
  28538. else if (sourceNodes.size() == 1)
  28539. {
  28540. // channel with a straightforward single input..
  28541. const int srcNode = sourceNodes.getUnchecked(0);
  28542. const int srcChan = sourceOutputChans.getUnchecked(0);
  28543. bufIndex = getBufferContaining (srcNode, srcChan);
  28544. if (bufIndex < 0)
  28545. {
  28546. // if not found, this is probably a feedback loop
  28547. bufIndex = getReadOnlyEmptyBuffer();
  28548. jassert (bufIndex >= 0);
  28549. }
  28550. if (inputChan < numOuts
  28551. && isBufferNeededLater (ourRenderingIndex,
  28552. inputChan,
  28553. srcNode, srcChan))
  28554. {
  28555. // can't mess up this channel because it's needed later by another node, so we
  28556. // need to use a copy of it..
  28557. const int newFreeBuffer = getFreeBuffer (false);
  28558. renderingOps.add (new CopyChannelOp (bufIndex, newFreeBuffer));
  28559. bufIndex = newFreeBuffer;
  28560. }
  28561. }
  28562. else
  28563. {
  28564. // channel with a mix of several inputs..
  28565. // try to find a re-usable channel from our inputs..
  28566. int reusableInputIndex = -1;
  28567. for (int i = 0; i < sourceNodes.size(); ++i)
  28568. {
  28569. const int sourceBufIndex = getBufferContaining (sourceNodes.getUnchecked(i),
  28570. sourceOutputChans.getUnchecked(i));
  28571. if (sourceBufIndex >= 0
  28572. && ! isBufferNeededLater (ourRenderingIndex,
  28573. inputChan,
  28574. sourceNodes.getUnchecked(i),
  28575. sourceOutputChans.getUnchecked(i)))
  28576. {
  28577. // we've found one of our input chans that can be re-used..
  28578. reusableInputIndex = i;
  28579. bufIndex = sourceBufIndex;
  28580. break;
  28581. }
  28582. }
  28583. if (reusableInputIndex < 0)
  28584. {
  28585. // can't re-use any of our input chans, so get a new one and copy everything into it..
  28586. bufIndex = getFreeBuffer (false);
  28587. jassert (bufIndex != 0);
  28588. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked (0),
  28589. sourceOutputChans.getUnchecked (0));
  28590. if (srcIndex < 0)
  28591. {
  28592. // if not found, this is probably a feedback loop
  28593. renderingOps.add (new ClearChannelOp (bufIndex));
  28594. }
  28595. else
  28596. {
  28597. renderingOps.add (new CopyChannelOp (srcIndex, bufIndex));
  28598. }
  28599. reusableInputIndex = 0;
  28600. }
  28601. for (int j = 0; j < sourceNodes.size(); ++j)
  28602. {
  28603. if (j != reusableInputIndex)
  28604. {
  28605. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked(j),
  28606. sourceOutputChans.getUnchecked(j));
  28607. if (srcIndex >= 0)
  28608. renderingOps.add (new AddChannelOp (srcIndex, bufIndex));
  28609. }
  28610. }
  28611. }
  28612. jassert (bufIndex >= 0);
  28613. audioChannelsToUse.add (bufIndex);
  28614. if (inputChan < numOuts)
  28615. markBufferAsContaining (bufIndex, node->id, inputChan);
  28616. }
  28617. for (int outputChan = numIns; outputChan < numOuts; ++outputChan)
  28618. {
  28619. const int bufIndex = getFreeBuffer (false);
  28620. jassert (bufIndex != 0);
  28621. audioChannelsToUse.add (bufIndex);
  28622. markBufferAsContaining (bufIndex, node->id, outputChan);
  28623. }
  28624. // Now the same thing for midi..
  28625. Array <int> midiSourceNodes;
  28626. for (int i = graph.getNumConnections(); --i >= 0;)
  28627. {
  28628. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  28629. if (c->destNodeId == node->id && c->destChannelIndex == AudioProcessorGraph::midiChannelIndex)
  28630. midiSourceNodes.add (c->sourceNodeId);
  28631. }
  28632. if (midiSourceNodes.size() == 0)
  28633. {
  28634. // No midi inputs..
  28635. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  28636. if (node->processor->acceptsMidi() || node->processor->producesMidi())
  28637. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  28638. }
  28639. else if (midiSourceNodes.size() == 1)
  28640. {
  28641. // One midi input..
  28642. midiBufferToUse = getBufferContaining (midiSourceNodes.getUnchecked(0),
  28643. AudioProcessorGraph::midiChannelIndex);
  28644. if (midiBufferToUse >= 0)
  28645. {
  28646. if (isBufferNeededLater (ourRenderingIndex,
  28647. AudioProcessorGraph::midiChannelIndex,
  28648. midiSourceNodes.getUnchecked(0),
  28649. AudioProcessorGraph::midiChannelIndex))
  28650. {
  28651. // can't mess up this channel because it's needed later by another node, so we
  28652. // need to use a copy of it..
  28653. const int newFreeBuffer = getFreeBuffer (true);
  28654. renderingOps.add (new CopyMidiBufferOp (midiBufferToUse, newFreeBuffer));
  28655. midiBufferToUse = newFreeBuffer;
  28656. }
  28657. }
  28658. else
  28659. {
  28660. // probably a feedback loop, so just use an empty one..
  28661. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  28662. }
  28663. }
  28664. else
  28665. {
  28666. // More than one midi input being mixed..
  28667. int reusableInputIndex = -1;
  28668. for (int i = 0; i < midiSourceNodes.size(); ++i)
  28669. {
  28670. const int sourceBufIndex = getBufferContaining (midiSourceNodes.getUnchecked(i),
  28671. AudioProcessorGraph::midiChannelIndex);
  28672. if (sourceBufIndex >= 0
  28673. && ! isBufferNeededLater (ourRenderingIndex,
  28674. AudioProcessorGraph::midiChannelIndex,
  28675. midiSourceNodes.getUnchecked(i),
  28676. AudioProcessorGraph::midiChannelIndex))
  28677. {
  28678. // we've found one of our input buffers that can be re-used..
  28679. reusableInputIndex = i;
  28680. midiBufferToUse = sourceBufIndex;
  28681. break;
  28682. }
  28683. }
  28684. if (reusableInputIndex < 0)
  28685. {
  28686. // can't re-use any of our input buffers, so get a new one and copy everything into it..
  28687. midiBufferToUse = getFreeBuffer (true);
  28688. jassert (midiBufferToUse >= 0);
  28689. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(0),
  28690. AudioProcessorGraph::midiChannelIndex);
  28691. if (srcIndex >= 0)
  28692. renderingOps.add (new CopyMidiBufferOp (srcIndex, midiBufferToUse));
  28693. else
  28694. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  28695. reusableInputIndex = 0;
  28696. }
  28697. for (int j = 0; j < midiSourceNodes.size(); ++j)
  28698. {
  28699. if (j != reusableInputIndex)
  28700. {
  28701. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(j),
  28702. AudioProcessorGraph::midiChannelIndex);
  28703. if (srcIndex >= 0)
  28704. renderingOps.add (new AddMidiBufferOp (srcIndex, midiBufferToUse));
  28705. }
  28706. }
  28707. }
  28708. if (node->processor->producesMidi())
  28709. markBufferAsContaining (midiBufferToUse, node->id,
  28710. AudioProcessorGraph::midiChannelIndex);
  28711. renderingOps.add (new ProcessBufferOp (node, audioChannelsToUse,
  28712. totalChans, midiBufferToUse));
  28713. }
  28714. int getFreeBuffer (const bool forMidi)
  28715. {
  28716. if (forMidi)
  28717. {
  28718. for (int i = 1; i < midiNodeIds.size(); ++i)
  28719. if (midiNodeIds.getUnchecked(i) < 0)
  28720. return i;
  28721. midiNodeIds.add (-1);
  28722. return midiNodeIds.size() - 1;
  28723. }
  28724. else
  28725. {
  28726. for (int i = 1; i < nodeIds.size(); ++i)
  28727. if (nodeIds.getUnchecked(i) < 0)
  28728. return i;
  28729. nodeIds.add (-1);
  28730. channels.add (0);
  28731. return nodeIds.size() - 1;
  28732. }
  28733. }
  28734. int getReadOnlyEmptyBuffer() const
  28735. {
  28736. return 0;
  28737. }
  28738. int getBufferContaining (const int nodeId, const int outputChannel) const
  28739. {
  28740. if (outputChannel == AudioProcessorGraph::midiChannelIndex)
  28741. {
  28742. for (int i = midiNodeIds.size(); --i >= 0;)
  28743. if (midiNodeIds.getUnchecked(i) == nodeId)
  28744. return i;
  28745. }
  28746. else
  28747. {
  28748. for (int i = nodeIds.size(); --i >= 0;)
  28749. if (nodeIds.getUnchecked(i) == nodeId
  28750. && channels.getUnchecked(i) == outputChannel)
  28751. return i;
  28752. }
  28753. return -1;
  28754. }
  28755. void markAnyUnusedBuffersAsFree (const int stepIndex)
  28756. {
  28757. int i;
  28758. for (i = 0; i < nodeIds.size(); ++i)
  28759. {
  28760. if (nodeIds.getUnchecked(i) >= 0
  28761. && ! isBufferNeededLater (stepIndex, -1,
  28762. nodeIds.getUnchecked(i),
  28763. channels.getUnchecked(i)))
  28764. {
  28765. nodeIds.set (i, -1);
  28766. }
  28767. }
  28768. for (i = 0; i < midiNodeIds.size(); ++i)
  28769. {
  28770. if (midiNodeIds.getUnchecked(i) >= 0
  28771. && ! isBufferNeededLater (stepIndex, -1,
  28772. midiNodeIds.getUnchecked(i),
  28773. AudioProcessorGraph::midiChannelIndex))
  28774. {
  28775. midiNodeIds.set (i, -1);
  28776. }
  28777. }
  28778. }
  28779. bool isBufferNeededLater (int stepIndexToSearchFrom,
  28780. int inputChannelOfIndexToIgnore,
  28781. const int nodeId,
  28782. const int outputChanIndex) const
  28783. {
  28784. while (stepIndexToSearchFrom < orderedNodes.size())
  28785. {
  28786. const AudioProcessorGraph::Node* const node = (const AudioProcessorGraph::Node*) orderedNodes.getUnchecked (stepIndexToSearchFrom);
  28787. if (outputChanIndex == AudioProcessorGraph::midiChannelIndex)
  28788. {
  28789. if (inputChannelOfIndexToIgnore != AudioProcessorGraph::midiChannelIndex
  28790. && graph.getConnectionBetween (nodeId, AudioProcessorGraph::midiChannelIndex,
  28791. node->id, AudioProcessorGraph::midiChannelIndex) != 0)
  28792. return true;
  28793. }
  28794. else
  28795. {
  28796. for (int i = 0; i < node->processor->getNumInputChannels(); ++i)
  28797. if (i != inputChannelOfIndexToIgnore
  28798. && graph.getConnectionBetween (nodeId, outputChanIndex,
  28799. node->id, i) != 0)
  28800. return true;
  28801. }
  28802. inputChannelOfIndexToIgnore = -1;
  28803. ++stepIndexToSearchFrom;
  28804. }
  28805. return false;
  28806. }
  28807. void markBufferAsContaining (int bufferNum, int nodeId, int outputIndex)
  28808. {
  28809. if (outputIndex == AudioProcessorGraph::midiChannelIndex)
  28810. {
  28811. jassert (bufferNum > 0 && bufferNum < midiNodeIds.size());
  28812. midiNodeIds.set (bufferNum, nodeId);
  28813. }
  28814. else
  28815. {
  28816. jassert (bufferNum >= 0 && bufferNum < nodeIds.size());
  28817. nodeIds.set (bufferNum, nodeId);
  28818. channels.set (bufferNum, outputIndex);
  28819. }
  28820. }
  28821. RenderingOpSequenceCalculator (const RenderingOpSequenceCalculator&);
  28822. RenderingOpSequenceCalculator& operator= (const RenderingOpSequenceCalculator&);
  28823. };
  28824. }
  28825. void AudioProcessorGraph::clearRenderingSequence()
  28826. {
  28827. const ScopedLock sl (renderLock);
  28828. for (int i = renderingOps.size(); --i >= 0;)
  28829. {
  28830. GraphRenderingOps::AudioGraphRenderingOp* const r
  28831. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  28832. renderingOps.remove (i);
  28833. delete r;
  28834. }
  28835. }
  28836. bool AudioProcessorGraph::isAnInputTo (const uint32 possibleInputId,
  28837. const uint32 possibleDestinationId,
  28838. const int recursionCheck) const
  28839. {
  28840. if (recursionCheck > 0)
  28841. {
  28842. for (int i = connections.size(); --i >= 0;)
  28843. {
  28844. const AudioProcessorGraph::Connection* const c = connections.getUnchecked (i);
  28845. if (c->destNodeId == possibleDestinationId
  28846. && (c->sourceNodeId == possibleInputId
  28847. || isAnInputTo (possibleInputId, c->sourceNodeId, recursionCheck - 1)))
  28848. return true;
  28849. }
  28850. }
  28851. return false;
  28852. }
  28853. void AudioProcessorGraph::buildRenderingSequence()
  28854. {
  28855. Array<void*> newRenderingOps;
  28856. int numRenderingBuffersNeeded = 2;
  28857. int numMidiBuffersNeeded = 1;
  28858. {
  28859. MessageManagerLock mml;
  28860. Array<void*> orderedNodes;
  28861. int i;
  28862. for (i = 0; i < nodes.size(); ++i)
  28863. {
  28864. Node* const node = nodes.getUnchecked(i);
  28865. node->prepare (getSampleRate(), getBlockSize(), this);
  28866. int j = 0;
  28867. for (; j < orderedNodes.size(); ++j)
  28868. if (isAnInputTo (node->id,
  28869. ((Node*) orderedNodes.getUnchecked (j))->id,
  28870. nodes.size() + 1))
  28871. break;
  28872. orderedNodes.insert (j, node);
  28873. }
  28874. GraphRenderingOps::RenderingOpSequenceCalculator calculator (*this, orderedNodes, newRenderingOps);
  28875. numRenderingBuffersNeeded = calculator.getNumBuffersNeeded();
  28876. numMidiBuffersNeeded = calculator.getNumMidiBuffersNeeded();
  28877. }
  28878. Array<void*> oldRenderingOps (renderingOps);
  28879. {
  28880. // swap over to the new rendering sequence..
  28881. const ScopedLock sl (renderLock);
  28882. renderingBuffers.setSize (numRenderingBuffersNeeded, getBlockSize());
  28883. renderingBuffers.clear();
  28884. for (int i = midiBuffers.size(); --i >= 0;)
  28885. midiBuffers.getUnchecked(i)->clear();
  28886. while (midiBuffers.size() < numMidiBuffersNeeded)
  28887. midiBuffers.add (new MidiBuffer());
  28888. renderingOps = newRenderingOps;
  28889. }
  28890. for (int i = oldRenderingOps.size(); --i >= 0;)
  28891. delete (GraphRenderingOps::AudioGraphRenderingOp*) oldRenderingOps.getUnchecked(i);
  28892. }
  28893. void AudioProcessorGraph::handleAsyncUpdate()
  28894. {
  28895. buildRenderingSequence();
  28896. }
  28897. void AudioProcessorGraph::prepareToPlay (double /*sampleRate*/, int estimatedSamplesPerBlock)
  28898. {
  28899. currentAudioInputBuffer = 0;
  28900. currentAudioOutputBuffer.setSize (jmax (1, getNumOutputChannels()), estimatedSamplesPerBlock);
  28901. currentMidiInputBuffer = 0;
  28902. currentMidiOutputBuffer.clear();
  28903. clearRenderingSequence();
  28904. buildRenderingSequence();
  28905. }
  28906. void AudioProcessorGraph::releaseResources()
  28907. {
  28908. for (int i = 0; i < nodes.size(); ++i)
  28909. nodes.getUnchecked(i)->unprepare();
  28910. renderingBuffers.setSize (1, 1);
  28911. midiBuffers.clear();
  28912. currentAudioInputBuffer = 0;
  28913. currentAudioOutputBuffer.setSize (1, 1);
  28914. currentMidiInputBuffer = 0;
  28915. currentMidiOutputBuffer.clear();
  28916. }
  28917. void AudioProcessorGraph::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages)
  28918. {
  28919. const int numSamples = buffer.getNumSamples();
  28920. const ScopedLock sl (renderLock);
  28921. currentAudioInputBuffer = &buffer;
  28922. currentAudioOutputBuffer.setSize (jmax (1, buffer.getNumChannels()), numSamples);
  28923. currentAudioOutputBuffer.clear();
  28924. currentMidiInputBuffer = &midiMessages;
  28925. currentMidiOutputBuffer.clear();
  28926. int i;
  28927. for (i = 0; i < renderingOps.size(); ++i)
  28928. {
  28929. GraphRenderingOps::AudioGraphRenderingOp* const op
  28930. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  28931. op->perform (renderingBuffers, midiBuffers, numSamples);
  28932. }
  28933. for (i = 0; i < buffer.getNumChannels(); ++i)
  28934. buffer.copyFrom (i, 0, currentAudioOutputBuffer, i, 0, numSamples);
  28935. midiMessages.clear();
  28936. midiMessages.addEvents (currentMidiOutputBuffer, 0, buffer.getNumSamples(), 0);
  28937. }
  28938. const String AudioProcessorGraph::getInputChannelName (const int channelIndex) const
  28939. {
  28940. return "Input " + String (channelIndex + 1);
  28941. }
  28942. const String AudioProcessorGraph::getOutputChannelName (const int channelIndex) const
  28943. {
  28944. return "Output " + String (channelIndex + 1);
  28945. }
  28946. bool AudioProcessorGraph::isInputChannelStereoPair (int /*index*/) const
  28947. {
  28948. return true;
  28949. }
  28950. bool AudioProcessorGraph::isOutputChannelStereoPair (int /*index*/) const
  28951. {
  28952. return true;
  28953. }
  28954. bool AudioProcessorGraph::acceptsMidi() const
  28955. {
  28956. return true;
  28957. }
  28958. bool AudioProcessorGraph::producesMidi() const
  28959. {
  28960. return true;
  28961. }
  28962. void AudioProcessorGraph::getStateInformation (JUCE_NAMESPACE::MemoryBlock& /*destData*/)
  28963. {
  28964. }
  28965. void AudioProcessorGraph::setStateInformation (const void* /*data*/, int /*sizeInBytes*/)
  28966. {
  28967. }
  28968. AudioProcessorGraph::AudioGraphIOProcessor::AudioGraphIOProcessor (const IODeviceType type_)
  28969. : type (type_),
  28970. graph (0)
  28971. {
  28972. }
  28973. AudioProcessorGraph::AudioGraphIOProcessor::~AudioGraphIOProcessor()
  28974. {
  28975. }
  28976. const String AudioProcessorGraph::AudioGraphIOProcessor::getName() const
  28977. {
  28978. switch (type)
  28979. {
  28980. case audioOutputNode:
  28981. return "Audio Output";
  28982. case audioInputNode:
  28983. return "Audio Input";
  28984. case midiOutputNode:
  28985. return "Midi Output";
  28986. case midiInputNode:
  28987. return "Midi Input";
  28988. default:
  28989. break;
  28990. }
  28991. return String::empty;
  28992. }
  28993. void AudioProcessorGraph::AudioGraphIOProcessor::fillInPluginDescription (PluginDescription& d) const
  28994. {
  28995. d.name = getName();
  28996. d.uid = d.name.hashCode();
  28997. d.category = "I/O devices";
  28998. d.pluginFormatName = "Internal";
  28999. d.manufacturerName = "Raw Material Software";
  29000. d.version = "1.0";
  29001. d.isInstrument = false;
  29002. d.numInputChannels = getNumInputChannels();
  29003. if (type == audioOutputNode && graph != 0)
  29004. d.numInputChannels = graph->getNumInputChannels();
  29005. d.numOutputChannels = getNumOutputChannels();
  29006. if (type == audioInputNode && graph != 0)
  29007. d.numOutputChannels = graph->getNumOutputChannels();
  29008. }
  29009. void AudioProcessorGraph::AudioGraphIOProcessor::prepareToPlay (double, int)
  29010. {
  29011. jassert (graph != 0);
  29012. }
  29013. void AudioProcessorGraph::AudioGraphIOProcessor::releaseResources()
  29014. {
  29015. }
  29016. void AudioProcessorGraph::AudioGraphIOProcessor::processBlock (AudioSampleBuffer& buffer,
  29017. MidiBuffer& midiMessages)
  29018. {
  29019. jassert (graph != 0);
  29020. switch (type)
  29021. {
  29022. case audioOutputNode:
  29023. {
  29024. for (int i = jmin (graph->currentAudioOutputBuffer.getNumChannels(),
  29025. buffer.getNumChannels()); --i >= 0;)
  29026. {
  29027. graph->currentAudioOutputBuffer.addFrom (i, 0, buffer, i, 0, buffer.getNumSamples());
  29028. }
  29029. break;
  29030. }
  29031. case audioInputNode:
  29032. {
  29033. for (int i = jmin (graph->currentAudioInputBuffer->getNumChannels(),
  29034. buffer.getNumChannels()); --i >= 0;)
  29035. {
  29036. buffer.copyFrom (i, 0, *graph->currentAudioInputBuffer, i, 0, buffer.getNumSamples());
  29037. }
  29038. break;
  29039. }
  29040. case midiOutputNode:
  29041. graph->currentMidiOutputBuffer.addEvents (midiMessages, 0, buffer.getNumSamples(), 0);
  29042. break;
  29043. case midiInputNode:
  29044. midiMessages.addEvents (*graph->currentMidiInputBuffer, 0, buffer.getNumSamples(), 0);
  29045. break;
  29046. default:
  29047. break;
  29048. }
  29049. }
  29050. bool AudioProcessorGraph::AudioGraphIOProcessor::acceptsMidi() const
  29051. {
  29052. return type == midiOutputNode;
  29053. }
  29054. bool AudioProcessorGraph::AudioGraphIOProcessor::producesMidi() const
  29055. {
  29056. return type == midiInputNode;
  29057. }
  29058. const String AudioProcessorGraph::AudioGraphIOProcessor::getInputChannelName (const int channelIndex) const
  29059. {
  29060. switch (type)
  29061. {
  29062. case audioOutputNode:
  29063. return "Output " + String (channelIndex + 1);
  29064. case midiOutputNode:
  29065. return "Midi Output";
  29066. default:
  29067. break;
  29068. }
  29069. return String::empty;
  29070. }
  29071. const String AudioProcessorGraph::AudioGraphIOProcessor::getOutputChannelName (const int channelIndex) const
  29072. {
  29073. switch (type)
  29074. {
  29075. case audioInputNode:
  29076. return "Input " + String (channelIndex + 1);
  29077. case midiInputNode:
  29078. return "Midi Input";
  29079. default:
  29080. break;
  29081. }
  29082. return String::empty;
  29083. }
  29084. bool AudioProcessorGraph::AudioGraphIOProcessor::isInputChannelStereoPair (int /*index*/) const
  29085. {
  29086. return type == audioInputNode || type == audioOutputNode;
  29087. }
  29088. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutputChannelStereoPair (int index) const
  29089. {
  29090. return isInputChannelStereoPair (index);
  29091. }
  29092. bool AudioProcessorGraph::AudioGraphIOProcessor::isInput() const
  29093. {
  29094. return type == audioInputNode || type == midiInputNode;
  29095. }
  29096. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutput() const
  29097. {
  29098. return type == audioOutputNode || type == midiOutputNode;
  29099. }
  29100. AudioProcessorEditor* AudioProcessorGraph::AudioGraphIOProcessor::createEditor()
  29101. {
  29102. return 0;
  29103. }
  29104. int AudioProcessorGraph::AudioGraphIOProcessor::getNumParameters() { return 0; }
  29105. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterName (int) { return String::empty; }
  29106. float AudioProcessorGraph::AudioGraphIOProcessor::getParameter (int) { return 0.0f; }
  29107. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterText (int) { return String::empty; }
  29108. void AudioProcessorGraph::AudioGraphIOProcessor::setParameter (int, float) { }
  29109. int AudioProcessorGraph::AudioGraphIOProcessor::getNumPrograms() { return 0; }
  29110. int AudioProcessorGraph::AudioGraphIOProcessor::getCurrentProgram() { return 0; }
  29111. void AudioProcessorGraph::AudioGraphIOProcessor::setCurrentProgram (int) { }
  29112. const String AudioProcessorGraph::AudioGraphIOProcessor::getProgramName (int) { return String::empty; }
  29113. void AudioProcessorGraph::AudioGraphIOProcessor::changeProgramName (int, const String&) { }
  29114. void AudioProcessorGraph::AudioGraphIOProcessor::getStateInformation (JUCE_NAMESPACE::MemoryBlock&)
  29115. {
  29116. }
  29117. void AudioProcessorGraph::AudioGraphIOProcessor::setStateInformation (const void*, int)
  29118. {
  29119. }
  29120. void AudioProcessorGraph::AudioGraphIOProcessor::setParentGraph (AudioProcessorGraph* const newGraph)
  29121. {
  29122. graph = newGraph;
  29123. if (graph != 0)
  29124. {
  29125. setPlayConfigDetails (type == audioOutputNode ? graph->getNumOutputChannels() : 0,
  29126. type == audioInputNode ? graph->getNumInputChannels() : 0,
  29127. getSampleRate(),
  29128. getBlockSize());
  29129. updateHostDisplay();
  29130. }
  29131. }
  29132. END_JUCE_NAMESPACE
  29133. /*** End of inlined file: juce_AudioProcessorGraph.cpp ***/
  29134. /*** Start of inlined file: juce_AudioProcessorPlayer.cpp ***/
  29135. BEGIN_JUCE_NAMESPACE
  29136. AudioProcessorPlayer::AudioProcessorPlayer()
  29137. : processor (0),
  29138. sampleRate (0),
  29139. blockSize (0),
  29140. isPrepared (false),
  29141. numInputChans (0),
  29142. numOutputChans (0),
  29143. tempBuffer (1, 1)
  29144. {
  29145. }
  29146. AudioProcessorPlayer::~AudioProcessorPlayer()
  29147. {
  29148. setProcessor (0);
  29149. }
  29150. void AudioProcessorPlayer::setProcessor (AudioProcessor* const processorToPlay)
  29151. {
  29152. if (processor != processorToPlay)
  29153. {
  29154. if (processorToPlay != 0 && sampleRate > 0 && blockSize > 0)
  29155. {
  29156. processorToPlay->setPlayConfigDetails (numInputChans, numOutputChans,
  29157. sampleRate, blockSize);
  29158. processorToPlay->prepareToPlay (sampleRate, blockSize);
  29159. }
  29160. AudioProcessor* oldOne;
  29161. {
  29162. const ScopedLock sl (lock);
  29163. oldOne = isPrepared ? processor : 0;
  29164. processor = processorToPlay;
  29165. isPrepared = true;
  29166. }
  29167. if (oldOne != 0)
  29168. oldOne->releaseResources();
  29169. }
  29170. }
  29171. void AudioProcessorPlayer::audioDeviceIOCallback (const float** const inputChannelData,
  29172. const int numInputChannels,
  29173. float** const outputChannelData,
  29174. const int numOutputChannels,
  29175. const int numSamples)
  29176. {
  29177. // these should have been prepared by audioDeviceAboutToStart()...
  29178. jassert (sampleRate > 0 && blockSize > 0);
  29179. incomingMidi.clear();
  29180. messageCollector.removeNextBlockOfMessages (incomingMidi, numSamples);
  29181. int i, totalNumChans = 0;
  29182. if (numInputChannels > numOutputChannels)
  29183. {
  29184. // if there aren't enough output channels for the number of
  29185. // inputs, we need to create some temporary extra ones (can't
  29186. // use the input data in case it gets written to)
  29187. tempBuffer.setSize (numInputChannels - numOutputChannels, numSamples,
  29188. false, false, true);
  29189. for (i = 0; i < numOutputChannels; ++i)
  29190. {
  29191. channels[totalNumChans] = outputChannelData[i];
  29192. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29193. ++totalNumChans;
  29194. }
  29195. for (i = numOutputChannels; i < numInputChannels; ++i)
  29196. {
  29197. channels[totalNumChans] = tempBuffer.getSampleData (i - numOutputChannels, 0);
  29198. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29199. ++totalNumChans;
  29200. }
  29201. }
  29202. else
  29203. {
  29204. for (i = 0; i < numInputChannels; ++i)
  29205. {
  29206. channels[totalNumChans] = outputChannelData[i];
  29207. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29208. ++totalNumChans;
  29209. }
  29210. for (i = numInputChannels; i < numOutputChannels; ++i)
  29211. {
  29212. channels[totalNumChans] = outputChannelData[i];
  29213. zeromem (channels[totalNumChans], sizeof (float) * numSamples);
  29214. ++totalNumChans;
  29215. }
  29216. }
  29217. AudioSampleBuffer buffer (channels, totalNumChans, numSamples);
  29218. const ScopedLock sl (lock);
  29219. if (processor != 0)
  29220. {
  29221. const ScopedLock sl (processor->getCallbackLock());
  29222. if (processor->isSuspended())
  29223. {
  29224. for (i = 0; i < numOutputChannels; ++i)
  29225. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  29226. }
  29227. else
  29228. {
  29229. processor->processBlock (buffer, incomingMidi);
  29230. }
  29231. }
  29232. }
  29233. void AudioProcessorPlayer::audioDeviceAboutToStart (AudioIODevice* device)
  29234. {
  29235. const ScopedLock sl (lock);
  29236. sampleRate = device->getCurrentSampleRate();
  29237. blockSize = device->getCurrentBufferSizeSamples();
  29238. numInputChans = device->getActiveInputChannels().countNumberOfSetBits();
  29239. numOutputChans = device->getActiveOutputChannels().countNumberOfSetBits();
  29240. messageCollector.reset (sampleRate);
  29241. zeromem (channels, sizeof (channels));
  29242. if (processor != 0)
  29243. {
  29244. if (isPrepared)
  29245. processor->releaseResources();
  29246. AudioProcessor* const oldProcessor = processor;
  29247. setProcessor (0);
  29248. setProcessor (oldProcessor);
  29249. }
  29250. }
  29251. void AudioProcessorPlayer::audioDeviceStopped()
  29252. {
  29253. const ScopedLock sl (lock);
  29254. if (processor != 0 && isPrepared)
  29255. processor->releaseResources();
  29256. sampleRate = 0.0;
  29257. blockSize = 0;
  29258. isPrepared = false;
  29259. tempBuffer.setSize (1, 1);
  29260. }
  29261. void AudioProcessorPlayer::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  29262. {
  29263. messageCollector.addMessageToQueue (message);
  29264. }
  29265. END_JUCE_NAMESPACE
  29266. /*** End of inlined file: juce_AudioProcessorPlayer.cpp ***/
  29267. /*** Start of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  29268. BEGIN_JUCE_NAMESPACE
  29269. class ProcessorParameterPropertyComp : public PropertyComponent,
  29270. public AudioProcessorListener,
  29271. public AsyncUpdater
  29272. {
  29273. public:
  29274. ProcessorParameterPropertyComp (const String& name,
  29275. AudioProcessor* const owner_,
  29276. const int index_)
  29277. : PropertyComponent (name),
  29278. owner (owner_),
  29279. index (index_)
  29280. {
  29281. addAndMakeVisible (slider = new ParamSlider (owner_, index_));
  29282. owner_->addListener (this);
  29283. }
  29284. ~ProcessorParameterPropertyComp()
  29285. {
  29286. owner->removeListener (this);
  29287. deleteAllChildren();
  29288. }
  29289. void refresh()
  29290. {
  29291. slider->setValue (owner->getParameter (index), false);
  29292. }
  29293. void audioProcessorChanged (AudioProcessor*) {}
  29294. void audioProcessorParameterChanged (AudioProcessor*, int parameterIndex, float)
  29295. {
  29296. if (parameterIndex == index)
  29297. triggerAsyncUpdate();
  29298. }
  29299. void handleAsyncUpdate()
  29300. {
  29301. refresh();
  29302. }
  29303. juce_UseDebuggingNewOperator
  29304. private:
  29305. AudioProcessor* const owner;
  29306. const int index;
  29307. Slider* slider;
  29308. class ParamSlider : public Slider
  29309. {
  29310. public:
  29311. ParamSlider (AudioProcessor* const owner_, const int index_)
  29312. : Slider (String::empty),
  29313. owner (owner_),
  29314. index (index_)
  29315. {
  29316. setRange (0.0, 1.0, 0.0);
  29317. setSliderStyle (Slider::LinearBar);
  29318. setTextBoxIsEditable (false);
  29319. setScrollWheelEnabled (false);
  29320. }
  29321. ~ParamSlider()
  29322. {
  29323. }
  29324. void valueChanged()
  29325. {
  29326. const float newVal = (float) getValue();
  29327. if (owner->getParameter (index) != newVal)
  29328. owner->setParameter (index, newVal);
  29329. }
  29330. const String getTextFromValue (double /*value*/)
  29331. {
  29332. return owner->getParameterText (index);
  29333. }
  29334. juce_UseDebuggingNewOperator
  29335. private:
  29336. AudioProcessor* const owner;
  29337. const int index;
  29338. ParamSlider (const ParamSlider&);
  29339. ParamSlider& operator= (const ParamSlider&);
  29340. };
  29341. ProcessorParameterPropertyComp (const ProcessorParameterPropertyComp&);
  29342. ProcessorParameterPropertyComp& operator= (const ProcessorParameterPropertyComp&);
  29343. };
  29344. GenericAudioProcessorEditor::GenericAudioProcessorEditor (AudioProcessor* const owner_)
  29345. : AudioProcessorEditor (owner_)
  29346. {
  29347. setOpaque (true);
  29348. addAndMakeVisible (panel = new PropertyPanel());
  29349. Array <PropertyComponent*> params;
  29350. const int numParams = owner_->getNumParameters();
  29351. int totalHeight = 0;
  29352. for (int i = 0; i < numParams; ++i)
  29353. {
  29354. String name (owner_->getParameterName (i));
  29355. if (name.trim().isEmpty())
  29356. name = "Unnamed";
  29357. ProcessorParameterPropertyComp* const pc = new ProcessorParameterPropertyComp (name, owner_, i);
  29358. params.add (pc);
  29359. totalHeight += pc->getPreferredHeight();
  29360. }
  29361. panel->addProperties (params);
  29362. setSize (400, jlimit (25, 400, totalHeight));
  29363. }
  29364. GenericAudioProcessorEditor::~GenericAudioProcessorEditor()
  29365. {
  29366. deleteAllChildren();
  29367. }
  29368. void GenericAudioProcessorEditor::paint (Graphics& g)
  29369. {
  29370. g.fillAll (Colours::white);
  29371. }
  29372. void GenericAudioProcessorEditor::resized()
  29373. {
  29374. panel->setSize (getWidth(), getHeight());
  29375. }
  29376. END_JUCE_NAMESPACE
  29377. /*** End of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  29378. /*** Start of inlined file: juce_Sampler.cpp ***/
  29379. BEGIN_JUCE_NAMESPACE
  29380. SamplerSound::SamplerSound (const String& name_,
  29381. AudioFormatReader& source,
  29382. const BigInteger& midiNotes_,
  29383. const int midiNoteForNormalPitch,
  29384. const double attackTimeSecs,
  29385. const double releaseTimeSecs,
  29386. const double maxSampleLengthSeconds)
  29387. : name (name_),
  29388. midiNotes (midiNotes_),
  29389. midiRootNote (midiNoteForNormalPitch)
  29390. {
  29391. sourceSampleRate = source.sampleRate;
  29392. if (sourceSampleRate <= 0 || source.lengthInSamples <= 0)
  29393. {
  29394. length = 0;
  29395. attackSamples = 0;
  29396. releaseSamples = 0;
  29397. }
  29398. else
  29399. {
  29400. length = jmin ((int) source.lengthInSamples,
  29401. (int) (maxSampleLengthSeconds * sourceSampleRate));
  29402. data = new AudioSampleBuffer (jmin (2, (int) source.numChannels), length + 4);
  29403. data->readFromAudioReader (&source, 0, length + 4, 0, true, true);
  29404. attackSamples = roundToInt (attackTimeSecs * sourceSampleRate);
  29405. releaseSamples = roundToInt (releaseTimeSecs * sourceSampleRate);
  29406. }
  29407. }
  29408. SamplerSound::~SamplerSound()
  29409. {
  29410. }
  29411. bool SamplerSound::appliesToNote (const int midiNoteNumber)
  29412. {
  29413. return midiNotes [midiNoteNumber];
  29414. }
  29415. bool SamplerSound::appliesToChannel (const int /*midiChannel*/)
  29416. {
  29417. return true;
  29418. }
  29419. SamplerVoice::SamplerVoice()
  29420. : pitchRatio (0.0),
  29421. sourceSamplePosition (0.0),
  29422. lgain (0.0f),
  29423. rgain (0.0f),
  29424. isInAttack (false),
  29425. isInRelease (false)
  29426. {
  29427. }
  29428. SamplerVoice::~SamplerVoice()
  29429. {
  29430. }
  29431. bool SamplerVoice::canPlaySound (SynthesiserSound* sound)
  29432. {
  29433. return dynamic_cast <const SamplerSound*> (sound) != 0;
  29434. }
  29435. void SamplerVoice::startNote (const int midiNoteNumber,
  29436. const float velocity,
  29437. SynthesiserSound* s,
  29438. const int /*currentPitchWheelPosition*/)
  29439. {
  29440. const SamplerSound* const sound = dynamic_cast <const SamplerSound*> (s);
  29441. jassert (sound != 0); // this object can only play SamplerSounds!
  29442. if (sound != 0)
  29443. {
  29444. const double targetFreq = MidiMessage::getMidiNoteInHertz (midiNoteNumber);
  29445. const double naturalFreq = MidiMessage::getMidiNoteInHertz (sound->midiRootNote);
  29446. pitchRatio = (targetFreq * sound->sourceSampleRate) / (naturalFreq * getSampleRate());
  29447. sourceSamplePosition = 0.0;
  29448. lgain = velocity;
  29449. rgain = velocity;
  29450. isInAttack = (sound->attackSamples > 0);
  29451. isInRelease = false;
  29452. if (isInAttack)
  29453. {
  29454. attackReleaseLevel = 0.0f;
  29455. attackDelta = (float) (pitchRatio / sound->attackSamples);
  29456. }
  29457. else
  29458. {
  29459. attackReleaseLevel = 1.0f;
  29460. attackDelta = 0.0f;
  29461. }
  29462. if (sound->releaseSamples > 0)
  29463. {
  29464. releaseDelta = (float) (-pitchRatio / sound->releaseSamples);
  29465. }
  29466. else
  29467. {
  29468. releaseDelta = 0.0f;
  29469. }
  29470. }
  29471. }
  29472. void SamplerVoice::stopNote (const bool allowTailOff)
  29473. {
  29474. if (allowTailOff)
  29475. {
  29476. isInAttack = false;
  29477. isInRelease = true;
  29478. }
  29479. else
  29480. {
  29481. clearCurrentNote();
  29482. }
  29483. }
  29484. void SamplerVoice::pitchWheelMoved (const int /*newValue*/)
  29485. {
  29486. }
  29487. void SamplerVoice::controllerMoved (const int /*controllerNumber*/,
  29488. const int /*newValue*/)
  29489. {
  29490. }
  29491. void SamplerVoice::renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples)
  29492. {
  29493. const SamplerSound* const playingSound = static_cast <SamplerSound*> (getCurrentlyPlayingSound().getObject());
  29494. if (playingSound != 0)
  29495. {
  29496. const float* const inL = playingSound->data->getSampleData (0, 0);
  29497. const float* const inR = playingSound->data->getNumChannels() > 1
  29498. ? playingSound->data->getSampleData (1, 0) : 0;
  29499. float* outL = outputBuffer.getSampleData (0, startSample);
  29500. float* outR = outputBuffer.getNumChannels() > 1 ? outputBuffer.getSampleData (1, startSample) : 0;
  29501. while (--numSamples >= 0)
  29502. {
  29503. const int pos = (int) sourceSamplePosition;
  29504. const float alpha = (float) (sourceSamplePosition - pos);
  29505. const float invAlpha = 1.0f - alpha;
  29506. // just using a very simple linear interpolation here..
  29507. float l = (inL [pos] * invAlpha + inL [pos + 1] * alpha);
  29508. float r = (inR != 0) ? (inR [pos] * invAlpha + inR [pos + 1] * alpha)
  29509. : l;
  29510. l *= lgain;
  29511. r *= rgain;
  29512. if (isInAttack)
  29513. {
  29514. l *= attackReleaseLevel;
  29515. r *= attackReleaseLevel;
  29516. attackReleaseLevel += attackDelta;
  29517. if (attackReleaseLevel >= 1.0f)
  29518. {
  29519. attackReleaseLevel = 1.0f;
  29520. isInAttack = false;
  29521. }
  29522. }
  29523. else if (isInRelease)
  29524. {
  29525. l *= attackReleaseLevel;
  29526. r *= attackReleaseLevel;
  29527. attackReleaseLevel += releaseDelta;
  29528. if (attackReleaseLevel <= 0.0f)
  29529. {
  29530. stopNote (false);
  29531. break;
  29532. }
  29533. }
  29534. if (outR != 0)
  29535. {
  29536. *outL++ += l;
  29537. *outR++ += r;
  29538. }
  29539. else
  29540. {
  29541. *outL++ += (l + r) * 0.5f;
  29542. }
  29543. sourceSamplePosition += pitchRatio;
  29544. if (sourceSamplePosition > playingSound->length)
  29545. {
  29546. stopNote (false);
  29547. break;
  29548. }
  29549. }
  29550. }
  29551. }
  29552. END_JUCE_NAMESPACE
  29553. /*** End of inlined file: juce_Sampler.cpp ***/
  29554. /*** Start of inlined file: juce_Synthesiser.cpp ***/
  29555. BEGIN_JUCE_NAMESPACE
  29556. SynthesiserSound::SynthesiserSound()
  29557. {
  29558. }
  29559. SynthesiserSound::~SynthesiserSound()
  29560. {
  29561. }
  29562. SynthesiserVoice::SynthesiserVoice()
  29563. : currentSampleRate (44100.0),
  29564. currentlyPlayingNote (-1),
  29565. noteOnTime (0),
  29566. currentlyPlayingSound (0)
  29567. {
  29568. }
  29569. SynthesiserVoice::~SynthesiserVoice()
  29570. {
  29571. }
  29572. bool SynthesiserVoice::isPlayingChannel (const int midiChannel) const
  29573. {
  29574. return currentlyPlayingSound != 0
  29575. && currentlyPlayingSound->appliesToChannel (midiChannel);
  29576. }
  29577. void SynthesiserVoice::setCurrentPlaybackSampleRate (const double newRate)
  29578. {
  29579. currentSampleRate = newRate;
  29580. }
  29581. void SynthesiserVoice::clearCurrentNote()
  29582. {
  29583. currentlyPlayingNote = -1;
  29584. currentlyPlayingSound = 0;
  29585. }
  29586. Synthesiser::Synthesiser()
  29587. : sampleRate (0),
  29588. lastNoteOnCounter (0),
  29589. shouldStealNotes (true)
  29590. {
  29591. for (int i = 0; i < numElementsInArray (lastPitchWheelValues); ++i)
  29592. lastPitchWheelValues[i] = 0x2000;
  29593. }
  29594. Synthesiser::~Synthesiser()
  29595. {
  29596. }
  29597. SynthesiserVoice* Synthesiser::getVoice (const int index) const
  29598. {
  29599. const ScopedLock sl (lock);
  29600. return voices [index];
  29601. }
  29602. void Synthesiser::clearVoices()
  29603. {
  29604. const ScopedLock sl (lock);
  29605. voices.clear();
  29606. }
  29607. void Synthesiser::addVoice (SynthesiserVoice* const newVoice)
  29608. {
  29609. const ScopedLock sl (lock);
  29610. voices.add (newVoice);
  29611. }
  29612. void Synthesiser::removeVoice (const int index)
  29613. {
  29614. const ScopedLock sl (lock);
  29615. voices.remove (index);
  29616. }
  29617. void Synthesiser::clearSounds()
  29618. {
  29619. const ScopedLock sl (lock);
  29620. sounds.clear();
  29621. }
  29622. void Synthesiser::addSound (const SynthesiserSound::Ptr& newSound)
  29623. {
  29624. const ScopedLock sl (lock);
  29625. sounds.add (newSound);
  29626. }
  29627. void Synthesiser::removeSound (const int index)
  29628. {
  29629. const ScopedLock sl (lock);
  29630. sounds.remove (index);
  29631. }
  29632. void Synthesiser::setNoteStealingEnabled (const bool shouldStealNotes_)
  29633. {
  29634. shouldStealNotes = shouldStealNotes_;
  29635. }
  29636. void Synthesiser::setCurrentPlaybackSampleRate (const double newRate)
  29637. {
  29638. if (sampleRate != newRate)
  29639. {
  29640. const ScopedLock sl (lock);
  29641. allNotesOff (0, false);
  29642. sampleRate = newRate;
  29643. for (int i = voices.size(); --i >= 0;)
  29644. voices.getUnchecked (i)->setCurrentPlaybackSampleRate (newRate);
  29645. }
  29646. }
  29647. void Synthesiser::renderNextBlock (AudioSampleBuffer& outputBuffer,
  29648. const MidiBuffer& midiData,
  29649. int startSample,
  29650. int numSamples)
  29651. {
  29652. // must set the sample rate before using this!
  29653. jassert (sampleRate != 0);
  29654. const ScopedLock sl (lock);
  29655. MidiBuffer::Iterator midiIterator (midiData);
  29656. midiIterator.setNextSamplePosition (startSample);
  29657. MidiMessage m (0xf4, 0.0);
  29658. while (numSamples > 0)
  29659. {
  29660. int midiEventPos;
  29661. const bool useEvent = midiIterator.getNextEvent (m, midiEventPos)
  29662. && midiEventPos < startSample + numSamples;
  29663. const int numThisTime = useEvent ? midiEventPos - startSample
  29664. : numSamples;
  29665. if (numThisTime > 0)
  29666. {
  29667. for (int i = voices.size(); --i >= 0;)
  29668. voices.getUnchecked (i)->renderNextBlock (outputBuffer, startSample, numThisTime);
  29669. }
  29670. if (useEvent)
  29671. {
  29672. if (m.isNoteOn())
  29673. {
  29674. const int channel = m.getChannel();
  29675. noteOn (channel,
  29676. m.getNoteNumber(),
  29677. m.getFloatVelocity());
  29678. }
  29679. else if (m.isNoteOff())
  29680. {
  29681. noteOff (m.getChannel(),
  29682. m.getNoteNumber(),
  29683. true);
  29684. }
  29685. else if (m.isAllNotesOff() || m.isAllSoundOff())
  29686. {
  29687. allNotesOff (m.getChannel(), true);
  29688. }
  29689. else if (m.isPitchWheel())
  29690. {
  29691. const int channel = m.getChannel();
  29692. const int wheelPos = m.getPitchWheelValue();
  29693. lastPitchWheelValues [channel - 1] = wheelPos;
  29694. handlePitchWheel (channel, wheelPos);
  29695. }
  29696. else if (m.isController())
  29697. {
  29698. handleController (m.getChannel(),
  29699. m.getControllerNumber(),
  29700. m.getControllerValue());
  29701. }
  29702. }
  29703. startSample += numThisTime;
  29704. numSamples -= numThisTime;
  29705. }
  29706. }
  29707. void Synthesiser::noteOn (const int midiChannel,
  29708. const int midiNoteNumber,
  29709. const float velocity)
  29710. {
  29711. const ScopedLock sl (lock);
  29712. for (int i = sounds.size(); --i >= 0;)
  29713. {
  29714. SynthesiserSound* const sound = sounds.getUnchecked(i);
  29715. if (sound->appliesToNote (midiNoteNumber)
  29716. && sound->appliesToChannel (midiChannel))
  29717. {
  29718. startVoice (findFreeVoice (sound, shouldStealNotes),
  29719. sound, midiChannel, midiNoteNumber, velocity);
  29720. }
  29721. }
  29722. }
  29723. void Synthesiser::startVoice (SynthesiserVoice* const voice,
  29724. SynthesiserSound* const sound,
  29725. const int midiChannel,
  29726. const int midiNoteNumber,
  29727. const float velocity)
  29728. {
  29729. if (voice != 0 && sound != 0)
  29730. {
  29731. if (voice->currentlyPlayingSound != 0)
  29732. voice->stopNote (false);
  29733. voice->startNote (midiNoteNumber,
  29734. velocity,
  29735. sound,
  29736. lastPitchWheelValues [midiChannel - 1]);
  29737. voice->currentlyPlayingNote = midiNoteNumber;
  29738. voice->noteOnTime = ++lastNoteOnCounter;
  29739. voice->currentlyPlayingSound = sound;
  29740. }
  29741. }
  29742. void Synthesiser::noteOff (const int midiChannel,
  29743. const int midiNoteNumber,
  29744. const bool allowTailOff)
  29745. {
  29746. const ScopedLock sl (lock);
  29747. for (int i = voices.size(); --i >= 0;)
  29748. {
  29749. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29750. if (voice->getCurrentlyPlayingNote() == midiNoteNumber)
  29751. {
  29752. SynthesiserSound* const sound = voice->getCurrentlyPlayingSound();
  29753. if (sound != 0
  29754. && sound->appliesToNote (midiNoteNumber)
  29755. && sound->appliesToChannel (midiChannel))
  29756. {
  29757. voice->stopNote (allowTailOff);
  29758. // the subclass MUST call clearCurrentNote() if it's not tailing off! RTFM for stopNote()!
  29759. jassert (allowTailOff || (voice->getCurrentlyPlayingNote() < 0 && voice->getCurrentlyPlayingSound() == 0));
  29760. }
  29761. }
  29762. }
  29763. }
  29764. void Synthesiser::allNotesOff (const int midiChannel,
  29765. const bool allowTailOff)
  29766. {
  29767. const ScopedLock sl (lock);
  29768. for (int i = voices.size(); --i >= 0;)
  29769. {
  29770. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29771. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  29772. voice->stopNote (allowTailOff);
  29773. }
  29774. }
  29775. void Synthesiser::handlePitchWheel (const int midiChannel,
  29776. const int wheelValue)
  29777. {
  29778. const ScopedLock sl (lock);
  29779. for (int i = voices.size(); --i >= 0;)
  29780. {
  29781. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29782. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  29783. {
  29784. voice->pitchWheelMoved (wheelValue);
  29785. }
  29786. }
  29787. }
  29788. void Synthesiser::handleController (const int midiChannel,
  29789. const int controllerNumber,
  29790. const int controllerValue)
  29791. {
  29792. const ScopedLock sl (lock);
  29793. for (int i = voices.size(); --i >= 0;)
  29794. {
  29795. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29796. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  29797. voice->controllerMoved (controllerNumber, controllerValue);
  29798. }
  29799. }
  29800. SynthesiserVoice* Synthesiser::findFreeVoice (SynthesiserSound* soundToPlay,
  29801. const bool stealIfNoneAvailable) const
  29802. {
  29803. const ScopedLock sl (lock);
  29804. for (int i = voices.size(); --i >= 0;)
  29805. if (voices.getUnchecked (i)->getCurrentlyPlayingNote() < 0
  29806. && voices.getUnchecked (i)->canPlaySound (soundToPlay))
  29807. return voices.getUnchecked (i);
  29808. if (stealIfNoneAvailable)
  29809. {
  29810. // currently this just steals the one that's been playing the longest, but could be made a bit smarter..
  29811. SynthesiserVoice* oldest = 0;
  29812. for (int i = voices.size(); --i >= 0;)
  29813. {
  29814. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29815. if (voice->canPlaySound (soundToPlay)
  29816. && (oldest == 0 || oldest->noteOnTime > voice->noteOnTime))
  29817. oldest = voice;
  29818. }
  29819. jassert (oldest != 0);
  29820. return oldest;
  29821. }
  29822. return 0;
  29823. }
  29824. END_JUCE_NAMESPACE
  29825. /*** End of inlined file: juce_Synthesiser.cpp ***/
  29826. /*** Start of inlined file: juce_ActionBroadcaster.cpp ***/
  29827. BEGIN_JUCE_NAMESPACE
  29828. ActionBroadcaster::ActionBroadcaster() throw()
  29829. {
  29830. // are you trying to create this object before or after juce has been intialised??
  29831. jassert (MessageManager::instance != 0);
  29832. }
  29833. ActionBroadcaster::~ActionBroadcaster()
  29834. {
  29835. // all event-based objects must be deleted BEFORE juce is shut down!
  29836. jassert (MessageManager::instance != 0);
  29837. }
  29838. void ActionBroadcaster::addActionListener (ActionListener* const listener)
  29839. {
  29840. actionListenerList.addActionListener (listener);
  29841. }
  29842. void ActionBroadcaster::removeActionListener (ActionListener* const listener)
  29843. {
  29844. jassert (actionListenerList.isValidMessageListener());
  29845. if (actionListenerList.isValidMessageListener())
  29846. actionListenerList.removeActionListener (listener);
  29847. }
  29848. void ActionBroadcaster::removeAllActionListeners()
  29849. {
  29850. actionListenerList.removeAllActionListeners();
  29851. }
  29852. void ActionBroadcaster::sendActionMessage (const String& message) const
  29853. {
  29854. actionListenerList.sendActionMessage (message);
  29855. }
  29856. END_JUCE_NAMESPACE
  29857. /*** End of inlined file: juce_ActionBroadcaster.cpp ***/
  29858. /*** Start of inlined file: juce_ActionListenerList.cpp ***/
  29859. BEGIN_JUCE_NAMESPACE
  29860. // special message of our own with a string in it
  29861. class ActionMessage : public Message
  29862. {
  29863. public:
  29864. const String message;
  29865. ActionMessage (const String& messageText,
  29866. void* const listener_) throw()
  29867. : message (messageText)
  29868. {
  29869. pointerParameter = listener_;
  29870. }
  29871. ~ActionMessage() throw()
  29872. {
  29873. }
  29874. private:
  29875. ActionMessage (const ActionMessage&);
  29876. ActionMessage& operator= (const ActionMessage&);
  29877. };
  29878. ActionListenerList::ActionListenerList() throw()
  29879. {
  29880. }
  29881. ActionListenerList::~ActionListenerList() throw()
  29882. {
  29883. }
  29884. void ActionListenerList::addActionListener (ActionListener* const listener) throw()
  29885. {
  29886. const ScopedLock sl (actionListenerLock_);
  29887. jassert (listener != 0);
  29888. jassert (! actionListeners_.contains (listener)); // trying to add a listener to the list twice!
  29889. if (listener != 0)
  29890. actionListeners_.add (listener);
  29891. }
  29892. void ActionListenerList::removeActionListener (ActionListener* const listener) throw()
  29893. {
  29894. const ScopedLock sl (actionListenerLock_);
  29895. jassert (actionListeners_.contains (listener)); // trying to remove a listener that isn't on the list!
  29896. actionListeners_.removeValue (listener);
  29897. }
  29898. void ActionListenerList::removeAllActionListeners() throw()
  29899. {
  29900. const ScopedLock sl (actionListenerLock_);
  29901. actionListeners_.clear();
  29902. }
  29903. void ActionListenerList::sendActionMessage (const String& message) const
  29904. {
  29905. const ScopedLock sl (actionListenerLock_);
  29906. for (int i = actionListeners_.size(); --i >= 0;)
  29907. postMessage (new ActionMessage (message, static_cast <ActionListener*> (actionListeners_.getUnchecked(i))));
  29908. }
  29909. void ActionListenerList::handleMessage (const Message& message)
  29910. {
  29911. const ActionMessage& am = (const ActionMessage&) message;
  29912. if (actionListeners_.contains (am.pointerParameter))
  29913. static_cast <ActionListener*> (am.pointerParameter)->actionListenerCallback (am.message);
  29914. }
  29915. END_JUCE_NAMESPACE
  29916. /*** End of inlined file: juce_ActionListenerList.cpp ***/
  29917. /*** Start of inlined file: juce_AsyncUpdater.cpp ***/
  29918. BEGIN_JUCE_NAMESPACE
  29919. AsyncUpdater::AsyncUpdater() throw()
  29920. : asyncMessagePending (false)
  29921. {
  29922. internalAsyncHandler.owner = this;
  29923. }
  29924. AsyncUpdater::~AsyncUpdater()
  29925. {
  29926. }
  29927. void AsyncUpdater::triggerAsyncUpdate() throw()
  29928. {
  29929. if (! asyncMessagePending)
  29930. {
  29931. asyncMessagePending = true;
  29932. internalAsyncHandler.postMessage (new Message());
  29933. }
  29934. }
  29935. void AsyncUpdater::cancelPendingUpdate() throw()
  29936. {
  29937. asyncMessagePending = false;
  29938. }
  29939. void AsyncUpdater::handleUpdateNowIfNeeded()
  29940. {
  29941. if (asyncMessagePending)
  29942. {
  29943. asyncMessagePending = false;
  29944. handleAsyncUpdate();
  29945. }
  29946. }
  29947. void AsyncUpdater::AsyncUpdaterInternal::handleMessage (const Message&)
  29948. {
  29949. owner->handleUpdateNowIfNeeded();
  29950. }
  29951. END_JUCE_NAMESPACE
  29952. /*** End of inlined file: juce_AsyncUpdater.cpp ***/
  29953. /*** Start of inlined file: juce_ChangeBroadcaster.cpp ***/
  29954. BEGIN_JUCE_NAMESPACE
  29955. ChangeBroadcaster::ChangeBroadcaster() throw()
  29956. {
  29957. // are you trying to create this object before or after juce has been intialised??
  29958. jassert (MessageManager::instance != 0);
  29959. }
  29960. ChangeBroadcaster::~ChangeBroadcaster()
  29961. {
  29962. // all event-based objects must be deleted BEFORE juce is shut down!
  29963. jassert (MessageManager::instance != 0);
  29964. }
  29965. void ChangeBroadcaster::addChangeListener (ChangeListener* const listener) throw()
  29966. {
  29967. changeListenerList.addChangeListener (listener);
  29968. }
  29969. void ChangeBroadcaster::removeChangeListener (ChangeListener* const listener) throw()
  29970. {
  29971. jassert (changeListenerList.isValidMessageListener());
  29972. if (changeListenerList.isValidMessageListener())
  29973. changeListenerList.removeChangeListener (listener);
  29974. }
  29975. void ChangeBroadcaster::removeAllChangeListeners() throw()
  29976. {
  29977. changeListenerList.removeAllChangeListeners();
  29978. }
  29979. void ChangeBroadcaster::sendChangeMessage (void* objectThatHasChanged) throw()
  29980. {
  29981. changeListenerList.sendChangeMessage (objectThatHasChanged);
  29982. }
  29983. void ChangeBroadcaster::sendSynchronousChangeMessage (void* objectThatHasChanged)
  29984. {
  29985. changeListenerList.sendSynchronousChangeMessage (objectThatHasChanged);
  29986. }
  29987. void ChangeBroadcaster::dispatchPendingMessages()
  29988. {
  29989. changeListenerList.dispatchPendingMessages();
  29990. }
  29991. END_JUCE_NAMESPACE
  29992. /*** End of inlined file: juce_ChangeBroadcaster.cpp ***/
  29993. /*** Start of inlined file: juce_ChangeListenerList.cpp ***/
  29994. BEGIN_JUCE_NAMESPACE
  29995. ChangeListenerList::ChangeListenerList() throw()
  29996. : lastChangedObject (0),
  29997. messagePending (false)
  29998. {
  29999. }
  30000. ChangeListenerList::~ChangeListenerList() throw()
  30001. {
  30002. }
  30003. void ChangeListenerList::addChangeListener (ChangeListener* const listener) throw()
  30004. {
  30005. const ScopedLock sl (lock);
  30006. jassert (listener != 0);
  30007. if (listener != 0)
  30008. listeners.add (listener);
  30009. }
  30010. void ChangeListenerList::removeChangeListener (ChangeListener* const listener) throw()
  30011. {
  30012. const ScopedLock sl (lock);
  30013. listeners.removeValue (listener);
  30014. }
  30015. void ChangeListenerList::removeAllChangeListeners() throw()
  30016. {
  30017. const ScopedLock sl (lock);
  30018. listeners.clear();
  30019. }
  30020. void ChangeListenerList::sendChangeMessage (void* const objectThatHasChanged) throw()
  30021. {
  30022. const ScopedLock sl (lock);
  30023. if ((! messagePending) && (listeners.size() > 0))
  30024. {
  30025. lastChangedObject = objectThatHasChanged;
  30026. postMessage (new Message (0, 0, 0, objectThatHasChanged));
  30027. messagePending = true;
  30028. }
  30029. }
  30030. void ChangeListenerList::handleMessage (const Message& message)
  30031. {
  30032. sendSynchronousChangeMessage (message.pointerParameter);
  30033. }
  30034. void ChangeListenerList::sendSynchronousChangeMessage (void* const objectThatHasChanged)
  30035. {
  30036. const ScopedLock sl (lock);
  30037. messagePending = false;
  30038. for (int i = listeners.size(); --i >= 0;)
  30039. {
  30040. ChangeListener* const l = static_cast <ChangeListener*> (listeners.getUnchecked (i));
  30041. {
  30042. const ScopedUnlock tempUnlocker (lock);
  30043. l->changeListenerCallback (objectThatHasChanged);
  30044. }
  30045. i = jmin (i, listeners.size());
  30046. }
  30047. }
  30048. void ChangeListenerList::dispatchPendingMessages()
  30049. {
  30050. if (messagePending)
  30051. sendSynchronousChangeMessage (lastChangedObject);
  30052. }
  30053. END_JUCE_NAMESPACE
  30054. /*** End of inlined file: juce_ChangeListenerList.cpp ***/
  30055. /*** Start of inlined file: juce_InterprocessConnection.cpp ***/
  30056. BEGIN_JUCE_NAMESPACE
  30057. InterprocessConnection::InterprocessConnection (const bool callbacksOnMessageThread,
  30058. const uint32 magicMessageHeaderNumber)
  30059. : Thread ("Juce IPC connection"),
  30060. callbackConnectionState (false),
  30061. useMessageThread (callbacksOnMessageThread),
  30062. magicMessageHeader (magicMessageHeaderNumber),
  30063. pipeReceiveMessageTimeout (-1)
  30064. {
  30065. }
  30066. InterprocessConnection::~InterprocessConnection()
  30067. {
  30068. callbackConnectionState = false;
  30069. disconnect();
  30070. }
  30071. bool InterprocessConnection::connectToSocket (const String& hostName,
  30072. const int portNumber,
  30073. const int timeOutMillisecs)
  30074. {
  30075. disconnect();
  30076. const ScopedLock sl (pipeAndSocketLock);
  30077. socket = new StreamingSocket();
  30078. if (socket->connect (hostName, portNumber, timeOutMillisecs))
  30079. {
  30080. connectionMadeInt();
  30081. startThread();
  30082. return true;
  30083. }
  30084. else
  30085. {
  30086. socket = 0;
  30087. return false;
  30088. }
  30089. }
  30090. bool InterprocessConnection::connectToPipe (const String& pipeName,
  30091. const int pipeReceiveMessageTimeoutMs)
  30092. {
  30093. disconnect();
  30094. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  30095. if (newPipe->openExisting (pipeName))
  30096. {
  30097. const ScopedLock sl (pipeAndSocketLock);
  30098. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  30099. initialiseWithPipe (newPipe.release());
  30100. return true;
  30101. }
  30102. return false;
  30103. }
  30104. bool InterprocessConnection::createPipe (const String& pipeName,
  30105. const int pipeReceiveMessageTimeoutMs)
  30106. {
  30107. disconnect();
  30108. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  30109. if (newPipe->createNewPipe (pipeName))
  30110. {
  30111. const ScopedLock sl (pipeAndSocketLock);
  30112. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  30113. initialiseWithPipe (newPipe.release());
  30114. return true;
  30115. }
  30116. return false;
  30117. }
  30118. void InterprocessConnection::disconnect()
  30119. {
  30120. if (socket != 0)
  30121. socket->close();
  30122. if (pipe != 0)
  30123. {
  30124. pipe->cancelPendingReads();
  30125. pipe->close();
  30126. }
  30127. stopThread (4000);
  30128. {
  30129. const ScopedLock sl (pipeAndSocketLock);
  30130. socket = 0;
  30131. pipe = 0;
  30132. }
  30133. connectionLostInt();
  30134. }
  30135. bool InterprocessConnection::isConnected() const
  30136. {
  30137. const ScopedLock sl (pipeAndSocketLock);
  30138. return ((socket != 0 && socket->isConnected())
  30139. || (pipe != 0 && pipe->isOpen()))
  30140. && isThreadRunning();
  30141. }
  30142. const String InterprocessConnection::getConnectedHostName() const
  30143. {
  30144. if (pipe != 0)
  30145. {
  30146. return "localhost";
  30147. }
  30148. else if (socket != 0)
  30149. {
  30150. if (! socket->isLocal())
  30151. return socket->getHostName();
  30152. return "localhost";
  30153. }
  30154. return String::empty;
  30155. }
  30156. bool InterprocessConnection::sendMessage (const MemoryBlock& message)
  30157. {
  30158. uint32 messageHeader[2];
  30159. messageHeader [0] = ByteOrder::swapIfBigEndian (magicMessageHeader);
  30160. messageHeader [1] = ByteOrder::swapIfBigEndian ((uint32) message.getSize());
  30161. MemoryBlock messageData (sizeof (messageHeader) + message.getSize());
  30162. messageData.copyFrom (messageHeader, 0, sizeof (messageHeader));
  30163. messageData.copyFrom (message.getData(), sizeof (messageHeader), message.getSize());
  30164. size_t bytesWritten = 0;
  30165. const ScopedLock sl (pipeAndSocketLock);
  30166. if (socket != 0)
  30167. {
  30168. bytesWritten = socket->write (messageData.getData(), (int) messageData.getSize());
  30169. }
  30170. else if (pipe != 0)
  30171. {
  30172. bytesWritten = pipe->write (messageData.getData(), (int) messageData.getSize());
  30173. }
  30174. if (bytesWritten < 0)
  30175. {
  30176. // error..
  30177. return false;
  30178. }
  30179. return (bytesWritten == messageData.getSize());
  30180. }
  30181. void InterprocessConnection::initialiseWithSocket (StreamingSocket* const socket_)
  30182. {
  30183. jassert (socket == 0);
  30184. socket = socket_;
  30185. connectionMadeInt();
  30186. startThread();
  30187. }
  30188. void InterprocessConnection::initialiseWithPipe (NamedPipe* const pipe_)
  30189. {
  30190. jassert (pipe == 0);
  30191. pipe = pipe_;
  30192. connectionMadeInt();
  30193. startThread();
  30194. }
  30195. const int messageMagicNumber = 0xb734128b;
  30196. void InterprocessConnection::handleMessage (const Message& message)
  30197. {
  30198. if (message.intParameter1 == messageMagicNumber)
  30199. {
  30200. switch (message.intParameter2)
  30201. {
  30202. case 0:
  30203. {
  30204. ScopedPointer <MemoryBlock> data (static_cast <MemoryBlock*> (message.pointerParameter));
  30205. messageReceived (*data);
  30206. break;
  30207. }
  30208. case 1:
  30209. connectionMade();
  30210. break;
  30211. case 2:
  30212. connectionLost();
  30213. break;
  30214. }
  30215. }
  30216. }
  30217. void InterprocessConnection::connectionMadeInt()
  30218. {
  30219. if (! callbackConnectionState)
  30220. {
  30221. callbackConnectionState = true;
  30222. if (useMessageThread)
  30223. postMessage (new Message (messageMagicNumber, 1, 0, 0));
  30224. else
  30225. connectionMade();
  30226. }
  30227. }
  30228. void InterprocessConnection::connectionLostInt()
  30229. {
  30230. if (callbackConnectionState)
  30231. {
  30232. callbackConnectionState = false;
  30233. if (useMessageThread)
  30234. postMessage (new Message (messageMagicNumber, 2, 0, 0));
  30235. else
  30236. connectionLost();
  30237. }
  30238. }
  30239. void InterprocessConnection::deliverDataInt (const MemoryBlock& data)
  30240. {
  30241. jassert (callbackConnectionState);
  30242. if (useMessageThread)
  30243. postMessage (new Message (messageMagicNumber, 0, 0, new MemoryBlock (data)));
  30244. else
  30245. messageReceived (data);
  30246. }
  30247. bool InterprocessConnection::readNextMessageInt()
  30248. {
  30249. const int maximumMessageSize = 1024 * 1024 * 10; // sanity check
  30250. uint32 messageHeader[2];
  30251. const int bytes = (socket != 0) ? socket->read (messageHeader, sizeof (messageHeader), true)
  30252. : pipe->read (messageHeader, sizeof (messageHeader), pipeReceiveMessageTimeout);
  30253. if (bytes == sizeof (messageHeader)
  30254. && ByteOrder::swapIfBigEndian (messageHeader[0]) == magicMessageHeader)
  30255. {
  30256. int bytesInMessage = (int) ByteOrder::swapIfBigEndian (messageHeader[1]);
  30257. if (bytesInMessage > 0 && bytesInMessage < maximumMessageSize)
  30258. {
  30259. MemoryBlock messageData (bytesInMessage, true);
  30260. int bytesRead = 0;
  30261. while (bytesInMessage > 0)
  30262. {
  30263. if (threadShouldExit())
  30264. return false;
  30265. const int numThisTime = jmin (bytesInMessage, 65536);
  30266. const int bytesIn = (socket != 0) ? socket->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, true)
  30267. : pipe->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, pipeReceiveMessageTimeout);
  30268. if (bytesIn <= 0)
  30269. break;
  30270. bytesRead += bytesIn;
  30271. bytesInMessage -= bytesIn;
  30272. }
  30273. if (bytesRead >= 0)
  30274. deliverDataInt (messageData);
  30275. }
  30276. }
  30277. else if (bytes < 0)
  30278. {
  30279. {
  30280. const ScopedLock sl (pipeAndSocketLock);
  30281. socket = 0;
  30282. }
  30283. connectionLostInt();
  30284. return false;
  30285. }
  30286. return true;
  30287. }
  30288. void InterprocessConnection::run()
  30289. {
  30290. while (! threadShouldExit())
  30291. {
  30292. if (socket != 0)
  30293. {
  30294. const int ready = socket->waitUntilReady (true, 0);
  30295. if (ready < 0)
  30296. {
  30297. {
  30298. const ScopedLock sl (pipeAndSocketLock);
  30299. socket = 0;
  30300. }
  30301. connectionLostInt();
  30302. break;
  30303. }
  30304. else if (ready > 0)
  30305. {
  30306. if (! readNextMessageInt())
  30307. break;
  30308. }
  30309. else
  30310. {
  30311. Thread::sleep (2);
  30312. }
  30313. }
  30314. else if (pipe != 0)
  30315. {
  30316. if (! pipe->isOpen())
  30317. {
  30318. {
  30319. const ScopedLock sl (pipeAndSocketLock);
  30320. pipe = 0;
  30321. }
  30322. connectionLostInt();
  30323. break;
  30324. }
  30325. else
  30326. {
  30327. if (! readNextMessageInt())
  30328. break;
  30329. }
  30330. }
  30331. else
  30332. {
  30333. break;
  30334. }
  30335. }
  30336. }
  30337. END_JUCE_NAMESPACE
  30338. /*** End of inlined file: juce_InterprocessConnection.cpp ***/
  30339. /*** Start of inlined file: juce_InterprocessConnectionServer.cpp ***/
  30340. BEGIN_JUCE_NAMESPACE
  30341. InterprocessConnectionServer::InterprocessConnectionServer()
  30342. : Thread ("Juce IPC server")
  30343. {
  30344. }
  30345. InterprocessConnectionServer::~InterprocessConnectionServer()
  30346. {
  30347. stop();
  30348. }
  30349. bool InterprocessConnectionServer::beginWaitingForSocket (const int portNumber)
  30350. {
  30351. stop();
  30352. socket = new StreamingSocket();
  30353. if (socket->createListener (portNumber))
  30354. {
  30355. startThread();
  30356. return true;
  30357. }
  30358. socket = 0;
  30359. return false;
  30360. }
  30361. void InterprocessConnectionServer::stop()
  30362. {
  30363. signalThreadShouldExit();
  30364. if (socket != 0)
  30365. socket->close();
  30366. stopThread (4000);
  30367. socket = 0;
  30368. }
  30369. void InterprocessConnectionServer::run()
  30370. {
  30371. while ((! threadShouldExit()) && socket != 0)
  30372. {
  30373. ScopedPointer <StreamingSocket> clientSocket (socket->waitForNextConnection());
  30374. if (clientSocket != 0)
  30375. {
  30376. InterprocessConnection* newConnection = createConnectionObject();
  30377. if (newConnection != 0)
  30378. newConnection->initialiseWithSocket (clientSocket.release());
  30379. }
  30380. }
  30381. }
  30382. END_JUCE_NAMESPACE
  30383. /*** End of inlined file: juce_InterprocessConnectionServer.cpp ***/
  30384. /*** Start of inlined file: juce_Message.cpp ***/
  30385. BEGIN_JUCE_NAMESPACE
  30386. Message::Message() throw()
  30387. : intParameter1 (0),
  30388. intParameter2 (0),
  30389. intParameter3 (0),
  30390. pointerParameter (0)
  30391. {
  30392. }
  30393. Message::Message (const int intParameter1_,
  30394. const int intParameter2_,
  30395. const int intParameter3_,
  30396. void* const pointerParameter_) throw()
  30397. : intParameter1 (intParameter1_),
  30398. intParameter2 (intParameter2_),
  30399. intParameter3 (intParameter3_),
  30400. pointerParameter (pointerParameter_)
  30401. {
  30402. }
  30403. Message::~Message() throw()
  30404. {
  30405. }
  30406. END_JUCE_NAMESPACE
  30407. /*** End of inlined file: juce_Message.cpp ***/
  30408. /*** Start of inlined file: juce_MessageListener.cpp ***/
  30409. BEGIN_JUCE_NAMESPACE
  30410. MessageListener::MessageListener() throw()
  30411. {
  30412. // are you trying to create a messagelistener before or after juce has been intialised??
  30413. jassert (MessageManager::instance != 0);
  30414. if (MessageManager::instance != 0)
  30415. MessageManager::instance->messageListeners.add (this);
  30416. }
  30417. MessageListener::~MessageListener()
  30418. {
  30419. if (MessageManager::instance != 0)
  30420. MessageManager::instance->messageListeners.removeValue (this);
  30421. }
  30422. void MessageListener::postMessage (Message* const message) const throw()
  30423. {
  30424. message->messageRecipient = const_cast <MessageListener*> (this);
  30425. if (MessageManager::instance == 0)
  30426. MessageManager::getInstance();
  30427. MessageManager::instance->postMessageToQueue (message);
  30428. }
  30429. bool MessageListener::isValidMessageListener() const throw()
  30430. {
  30431. return (MessageManager::instance != 0)
  30432. && MessageManager::instance->messageListeners.contains (this);
  30433. }
  30434. END_JUCE_NAMESPACE
  30435. /*** End of inlined file: juce_MessageListener.cpp ***/
  30436. /*** Start of inlined file: juce_MessageManager.cpp ***/
  30437. BEGIN_JUCE_NAMESPACE
  30438. // platform-specific functions..
  30439. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  30440. bool juce_postMessageToSystemQueue (Message* message);
  30441. MessageManager* MessageManager::instance = 0;
  30442. static const int quitMessageId = 0xfffff321;
  30443. MessageManager::MessageManager() throw()
  30444. : quitMessagePosted (false),
  30445. quitMessageReceived (false),
  30446. threadWithLock (0)
  30447. {
  30448. messageThreadId = Thread::getCurrentThreadId();
  30449. }
  30450. MessageManager::~MessageManager() throw()
  30451. {
  30452. broadcastListeners = 0;
  30453. doPlatformSpecificShutdown();
  30454. jassert (instance == this);
  30455. instance = 0; // do this last in case this instance is still needed by doPlatformSpecificShutdown()
  30456. }
  30457. MessageManager* MessageManager::getInstance() throw()
  30458. {
  30459. if (instance == 0)
  30460. {
  30461. instance = new MessageManager();
  30462. doPlatformSpecificInitialisation();
  30463. }
  30464. return instance;
  30465. }
  30466. void MessageManager::postMessageToQueue (Message* const message)
  30467. {
  30468. if (quitMessagePosted || ! juce_postMessageToSystemQueue (message))
  30469. delete message;
  30470. }
  30471. CallbackMessage::CallbackMessage() throw() {}
  30472. CallbackMessage::~CallbackMessage() throw() {}
  30473. void CallbackMessage::post()
  30474. {
  30475. if (MessageManager::instance != 0)
  30476. MessageManager::instance->postCallbackMessage (this);
  30477. }
  30478. void MessageManager::postCallbackMessage (Message* const message)
  30479. {
  30480. message->messageRecipient = 0;
  30481. postMessageToQueue (message);
  30482. }
  30483. // not for public use..
  30484. void MessageManager::deliverMessage (Message* const message)
  30485. {
  30486. const ScopedPointer <Message> messageDeleter (message);
  30487. MessageListener* const recipient = message->messageRecipient;
  30488. JUCE_TRY
  30489. {
  30490. if (messageListeners.contains (recipient))
  30491. {
  30492. recipient->handleMessage (*message);
  30493. }
  30494. else if (recipient == 0)
  30495. {
  30496. if (message->intParameter1 == quitMessageId)
  30497. {
  30498. quitMessageReceived = true;
  30499. }
  30500. else
  30501. {
  30502. CallbackMessage* const cm = dynamic_cast <CallbackMessage*> (message);
  30503. if (cm != 0)
  30504. cm->messageCallback();
  30505. }
  30506. }
  30507. }
  30508. JUCE_CATCH_EXCEPTION
  30509. }
  30510. #if ! (JUCE_MAC || JUCE_IPHONE)
  30511. void MessageManager::runDispatchLoop()
  30512. {
  30513. jassert (isThisTheMessageThread()); // must only be called by the message thread
  30514. runDispatchLoopUntil (-1);
  30515. }
  30516. void MessageManager::stopDispatchLoop()
  30517. {
  30518. Message* const m = new Message (quitMessageId, 0, 0, 0);
  30519. m->messageRecipient = 0;
  30520. postMessageToQueue (m);
  30521. quitMessagePosted = true;
  30522. }
  30523. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  30524. {
  30525. jassert (isThisTheMessageThread()); // must only be called by the message thread
  30526. const int64 endTime = Time::currentTimeMillis() + millisecondsToRunFor;
  30527. while ((millisecondsToRunFor < 0 || endTime > Time::currentTimeMillis())
  30528. && ! quitMessageReceived)
  30529. {
  30530. JUCE_TRY
  30531. {
  30532. if (! juce_dispatchNextMessageOnSystemQueue (millisecondsToRunFor >= 0))
  30533. {
  30534. const int msToWait = (int) (endTime - Time::currentTimeMillis());
  30535. if (msToWait > 0)
  30536. Thread::sleep (jmin (5, msToWait));
  30537. }
  30538. }
  30539. JUCE_CATCH_EXCEPTION
  30540. }
  30541. return ! quitMessageReceived;
  30542. }
  30543. #endif
  30544. void MessageManager::deliverBroadcastMessage (const String& value)
  30545. {
  30546. if (broadcastListeners != 0)
  30547. broadcastListeners->sendActionMessage (value);
  30548. }
  30549. void MessageManager::registerBroadcastListener (ActionListener* const listener) throw()
  30550. {
  30551. if (broadcastListeners == 0)
  30552. broadcastListeners = new ActionListenerList();
  30553. broadcastListeners->addActionListener (listener);
  30554. }
  30555. void MessageManager::deregisterBroadcastListener (ActionListener* const listener) throw()
  30556. {
  30557. if (broadcastListeners != 0)
  30558. broadcastListeners->removeActionListener (listener);
  30559. }
  30560. bool MessageManager::isThisTheMessageThread() const throw()
  30561. {
  30562. return Thread::getCurrentThreadId() == messageThreadId;
  30563. }
  30564. void MessageManager::setCurrentThreadAsMessageThread()
  30565. {
  30566. if (messageThreadId != Thread::getCurrentThreadId())
  30567. {
  30568. messageThreadId = Thread::getCurrentThreadId();
  30569. // This is needed on windows to make sure the message window is created by this thread
  30570. doPlatformSpecificShutdown();
  30571. doPlatformSpecificInitialisation();
  30572. }
  30573. }
  30574. bool MessageManager::currentThreadHasLockedMessageManager() const throw()
  30575. {
  30576. const Thread::ThreadID thisThread = Thread::getCurrentThreadId();
  30577. return thisThread == messageThreadId || thisThread == threadWithLock;
  30578. }
  30579. /* The only safe way to lock the message thread while another thread does
  30580. some work is by posting a special message, whose purpose is to tie up the event
  30581. loop until the other thread has finished its business.
  30582. Any other approach can get horribly deadlocked if the OS uses its own hidden locks which
  30583. get locked before making an event callback, because if the same OS lock gets indirectly
  30584. accessed from another thread inside a MM lock, you're screwed. (this is exactly what happens
  30585. in Cocoa).
  30586. */
  30587. class MessageManagerLock::SharedEvents : public ReferenceCountedObject
  30588. {
  30589. public:
  30590. SharedEvents() {}
  30591. ~SharedEvents() {}
  30592. /* This class just holds a couple of events to communicate between the BlockingMessage
  30593. and the MessageManagerLock. Because both of these objects may be deleted at any time,
  30594. this shared data must be kept in a separate, ref-counted container. */
  30595. WaitableEvent lockedEvent, releaseEvent;
  30596. private:
  30597. SharedEvents (const SharedEvents&);
  30598. SharedEvents& operator= (const SharedEvents&);
  30599. };
  30600. class MessageManagerLock::BlockingMessage : public CallbackMessage
  30601. {
  30602. public:
  30603. BlockingMessage (MessageManagerLock::SharedEvents* const events_) : events (events_) {}
  30604. ~BlockingMessage() throw() {}
  30605. void messageCallback()
  30606. {
  30607. events->lockedEvent.signal();
  30608. events->releaseEvent.wait();
  30609. }
  30610. juce_UseDebuggingNewOperator
  30611. private:
  30612. ReferenceCountedObjectPtr <MessageManagerLock::SharedEvents> events;
  30613. BlockingMessage (const BlockingMessage&);
  30614. BlockingMessage& operator= (const BlockingMessage&);
  30615. };
  30616. MessageManagerLock::MessageManagerLock (Thread* const threadToCheck) throw()
  30617. : sharedEvents (0),
  30618. locked (false)
  30619. {
  30620. init (threadToCheck, 0);
  30621. }
  30622. MessageManagerLock::MessageManagerLock (ThreadPoolJob* const jobToCheckForExitSignal) throw()
  30623. : sharedEvents (0),
  30624. locked (false)
  30625. {
  30626. init (0, jobToCheckForExitSignal);
  30627. }
  30628. void MessageManagerLock::init (Thread* const threadToCheck, ThreadPoolJob* const job) throw()
  30629. {
  30630. if (MessageManager::instance != 0)
  30631. {
  30632. if (MessageManager::instance->currentThreadHasLockedMessageManager())
  30633. {
  30634. locked = true; // either we're on the message thread, or this is a re-entrant call.
  30635. }
  30636. else
  30637. {
  30638. if (threadToCheck == 0 && job == 0)
  30639. {
  30640. MessageManager::instance->lockingLock.enter();
  30641. }
  30642. else
  30643. {
  30644. while (! MessageManager::instance->lockingLock.tryEnter())
  30645. {
  30646. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  30647. || (job != 0 && job->shouldExit()))
  30648. return;
  30649. Thread::sleep (1);
  30650. }
  30651. }
  30652. sharedEvents = new SharedEvents();
  30653. sharedEvents->incReferenceCount();
  30654. (new BlockingMessage (sharedEvents))->post();
  30655. while (! sharedEvents->lockedEvent.wait (50))
  30656. {
  30657. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  30658. || (job != 0 && job->shouldExit()))
  30659. {
  30660. sharedEvents->releaseEvent.signal();
  30661. sharedEvents->decReferenceCount();
  30662. sharedEvents = 0;
  30663. MessageManager::instance->lockingLock.exit();
  30664. return;
  30665. }
  30666. }
  30667. jassert (MessageManager::instance->threadWithLock == 0);
  30668. MessageManager::instance->threadWithLock = Thread::getCurrentThreadId();
  30669. locked = true;
  30670. }
  30671. }
  30672. }
  30673. MessageManagerLock::~MessageManagerLock() throw()
  30674. {
  30675. if (sharedEvents != 0)
  30676. {
  30677. jassert (MessageManager::instance == 0 || MessageManager::instance->currentThreadHasLockedMessageManager());
  30678. sharedEvents->releaseEvent.signal();
  30679. sharedEvents->decReferenceCount();
  30680. if (MessageManager::instance != 0)
  30681. {
  30682. MessageManager::instance->threadWithLock = 0;
  30683. MessageManager::instance->lockingLock.exit();
  30684. }
  30685. }
  30686. }
  30687. END_JUCE_NAMESPACE
  30688. /*** End of inlined file: juce_MessageManager.cpp ***/
  30689. /*** Start of inlined file: juce_MultiTimer.cpp ***/
  30690. BEGIN_JUCE_NAMESPACE
  30691. class MultiTimer::MultiTimerCallback : public Timer
  30692. {
  30693. public:
  30694. MultiTimerCallback (const int timerId_, MultiTimer& owner_)
  30695. : timerId (timerId_),
  30696. owner (owner_)
  30697. {
  30698. }
  30699. ~MultiTimerCallback()
  30700. {
  30701. }
  30702. void timerCallback()
  30703. {
  30704. owner.timerCallback (timerId);
  30705. }
  30706. const int timerId;
  30707. private:
  30708. MultiTimer& owner;
  30709. };
  30710. MultiTimer::MultiTimer() throw()
  30711. {
  30712. }
  30713. MultiTimer::MultiTimer (const MultiTimer&) throw()
  30714. {
  30715. }
  30716. MultiTimer::~MultiTimer()
  30717. {
  30718. const ScopedLock sl (timerListLock);
  30719. timers.clear();
  30720. }
  30721. void MultiTimer::startTimer (const int timerId, const int intervalInMilliseconds) throw()
  30722. {
  30723. const ScopedLock sl (timerListLock);
  30724. for (int i = timers.size(); --i >= 0;)
  30725. {
  30726. MultiTimerCallback* const t = timers.getUnchecked(i);
  30727. if (t->timerId == timerId)
  30728. {
  30729. t->startTimer (intervalInMilliseconds);
  30730. return;
  30731. }
  30732. }
  30733. MultiTimerCallback* const newTimer = new MultiTimerCallback (timerId, *this);
  30734. timers.add (newTimer);
  30735. newTimer->startTimer (intervalInMilliseconds);
  30736. }
  30737. void MultiTimer::stopTimer (const int timerId) throw()
  30738. {
  30739. const ScopedLock sl (timerListLock);
  30740. for (int i = timers.size(); --i >= 0;)
  30741. {
  30742. MultiTimerCallback* const t = timers.getUnchecked(i);
  30743. if (t->timerId == timerId)
  30744. t->stopTimer();
  30745. }
  30746. }
  30747. bool MultiTimer::isTimerRunning (const int timerId) const throw()
  30748. {
  30749. const ScopedLock sl (timerListLock);
  30750. for (int i = timers.size(); --i >= 0;)
  30751. {
  30752. const MultiTimerCallback* const t = timers.getUnchecked(i);
  30753. if (t->timerId == timerId)
  30754. return t->isTimerRunning();
  30755. }
  30756. return false;
  30757. }
  30758. int MultiTimer::getTimerInterval (const int timerId) const throw()
  30759. {
  30760. const ScopedLock sl (timerListLock);
  30761. for (int i = timers.size(); --i >= 0;)
  30762. {
  30763. const MultiTimerCallback* const t = timers.getUnchecked(i);
  30764. if (t->timerId == timerId)
  30765. return t->getTimerInterval();
  30766. }
  30767. return 0;
  30768. }
  30769. END_JUCE_NAMESPACE
  30770. /*** End of inlined file: juce_MultiTimer.cpp ***/
  30771. /*** Start of inlined file: juce_Timer.cpp ***/
  30772. BEGIN_JUCE_NAMESPACE
  30773. class InternalTimerThread : private Thread,
  30774. private MessageListener,
  30775. private DeletedAtShutdown,
  30776. private AsyncUpdater
  30777. {
  30778. public:
  30779. InternalTimerThread()
  30780. : Thread ("Juce Timer"),
  30781. firstTimer (0),
  30782. callbackNeeded (0)
  30783. {
  30784. triggerAsyncUpdate();
  30785. }
  30786. ~InternalTimerThread() throw()
  30787. {
  30788. stopThread (4000);
  30789. jassert (instance == this || instance == 0);
  30790. if (instance == this)
  30791. instance = 0;
  30792. }
  30793. void run()
  30794. {
  30795. uint32 lastTime = Time::getMillisecondCounter();
  30796. while (! threadShouldExit())
  30797. {
  30798. const uint32 now = Time::getMillisecondCounter();
  30799. if (now <= lastTime)
  30800. {
  30801. wait (2);
  30802. continue;
  30803. }
  30804. const int elapsed = now - lastTime;
  30805. lastTime = now;
  30806. int timeUntilFirstTimer = 1000;
  30807. {
  30808. const ScopedLock sl (lock);
  30809. decrementAllCounters (elapsed);
  30810. if (firstTimer != 0)
  30811. timeUntilFirstTimer = firstTimer->countdownMs;
  30812. }
  30813. if (timeUntilFirstTimer <= 0)
  30814. {
  30815. /* If we managed to set the atomic boolean to true then send a message, this is needed
  30816. as a memory barrier so the message won't be sent before callbackNeeded is set to true,
  30817. but if it fails it means the message-thread changed the value from under us so at least
  30818. some processing is happenening and we can just loop around and try again
  30819. */
  30820. if (callbackNeeded.compareAndSetBool (1, 0))
  30821. {
  30822. postMessage (new Message());
  30823. /* Sometimes our message can get discarded by the OS (e.g. when running as an RTAS
  30824. when the app has a modal loop), so this is how long to wait before assuming the
  30825. message has been lost and trying again.
  30826. */
  30827. const uint32 messageDeliveryTimeout = now + 2000;
  30828. while (callbackNeeded.get() != 0)
  30829. {
  30830. wait (4);
  30831. if (threadShouldExit())
  30832. return;
  30833. if (Time::getMillisecondCounter() > messageDeliveryTimeout)
  30834. break;
  30835. }
  30836. }
  30837. }
  30838. else
  30839. {
  30840. // don't wait for too long because running this loop also helps keep the
  30841. // Time::getApproximateMillisecondTimer value stay up-to-date
  30842. wait (jlimit (1, 50, timeUntilFirstTimer));
  30843. }
  30844. }
  30845. }
  30846. void callTimers()
  30847. {
  30848. const ScopedLock sl (lock);
  30849. while (firstTimer != 0 && firstTimer->countdownMs <= 0)
  30850. {
  30851. Timer* const t = firstTimer;
  30852. t->countdownMs = t->periodMs;
  30853. removeTimer (t);
  30854. addTimer (t);
  30855. const ScopedUnlock ul (lock);
  30856. JUCE_TRY
  30857. {
  30858. t->timerCallback();
  30859. }
  30860. JUCE_CATCH_EXCEPTION
  30861. }
  30862. /* This is needed as a memory barrier to make sure all processing of current timers is done
  30863. before the boolean is set. This set should never fail since if it was false in the first place,
  30864. we wouldn't get a message (so it can't be changed from false to true from under us), and if we
  30865. get a message then the value is true and the other thread can only set it to true again and
  30866. we will get another callback to set it to false.
  30867. */
  30868. callbackNeeded.set (0);
  30869. }
  30870. void handleMessage (const Message&)
  30871. {
  30872. callTimers();
  30873. }
  30874. void callTimersSynchronously()
  30875. {
  30876. if (! isThreadRunning())
  30877. {
  30878. // (This is relied on by some plugins in cases where the MM has
  30879. // had to restart and the async callback never started)
  30880. cancelPendingUpdate();
  30881. triggerAsyncUpdate();
  30882. }
  30883. callTimers();
  30884. }
  30885. static void callAnyTimersSynchronously()
  30886. {
  30887. if (InternalTimerThread::instance != 0)
  30888. InternalTimerThread::instance->callTimersSynchronously();
  30889. }
  30890. static inline void add (Timer* const tim) throw()
  30891. {
  30892. if (instance == 0)
  30893. instance = new InternalTimerThread();
  30894. const ScopedLock sl (instance->lock);
  30895. instance->addTimer (tim);
  30896. }
  30897. static inline void remove (Timer* const tim) throw()
  30898. {
  30899. if (instance != 0)
  30900. {
  30901. const ScopedLock sl (instance->lock);
  30902. instance->removeTimer (tim);
  30903. }
  30904. }
  30905. static inline void resetCounter (Timer* const tim,
  30906. const int newCounter) throw()
  30907. {
  30908. if (instance != 0)
  30909. {
  30910. tim->countdownMs = newCounter;
  30911. tim->periodMs = newCounter;
  30912. if ((tim->next != 0 && tim->next->countdownMs < tim->countdownMs)
  30913. || (tim->previous != 0 && tim->previous->countdownMs > tim->countdownMs))
  30914. {
  30915. const ScopedLock sl (instance->lock);
  30916. instance->removeTimer (tim);
  30917. instance->addTimer (tim);
  30918. }
  30919. }
  30920. }
  30921. private:
  30922. friend class Timer;
  30923. static InternalTimerThread* instance;
  30924. static CriticalSection lock;
  30925. Timer* volatile firstTimer;
  30926. Atomic <int> callbackNeeded;
  30927. void addTimer (Timer* const t) throw()
  30928. {
  30929. #if JUCE_DEBUG
  30930. Timer* tt = firstTimer;
  30931. while (tt != 0)
  30932. {
  30933. // trying to add a timer that's already here - shouldn't get to this point,
  30934. // so if you get this assertion, let me know!
  30935. jassert (tt != t);
  30936. tt = tt->next;
  30937. }
  30938. jassert (t->previous == 0 && t->next == 0);
  30939. #endif
  30940. Timer* i = firstTimer;
  30941. if (i == 0 || i->countdownMs > t->countdownMs)
  30942. {
  30943. t->next = firstTimer;
  30944. firstTimer = t;
  30945. }
  30946. else
  30947. {
  30948. while (i->next != 0 && i->next->countdownMs <= t->countdownMs)
  30949. i = i->next;
  30950. jassert (i != 0);
  30951. t->next = i->next;
  30952. t->previous = i;
  30953. i->next = t;
  30954. }
  30955. if (t->next != 0)
  30956. t->next->previous = t;
  30957. jassert ((t->next == 0 || t->next->countdownMs >= t->countdownMs)
  30958. && (t->previous == 0 || t->previous->countdownMs <= t->countdownMs));
  30959. notify();
  30960. }
  30961. void removeTimer (Timer* const t) throw()
  30962. {
  30963. #if JUCE_DEBUG
  30964. Timer* tt = firstTimer;
  30965. bool found = false;
  30966. while (tt != 0)
  30967. {
  30968. if (tt == t)
  30969. {
  30970. found = true;
  30971. break;
  30972. }
  30973. tt = tt->next;
  30974. }
  30975. // trying to remove a timer that's not here - shouldn't get to this point,
  30976. // so if you get this assertion, let me know!
  30977. jassert (found);
  30978. #endif
  30979. if (t->previous != 0)
  30980. {
  30981. jassert (firstTimer != t);
  30982. t->previous->next = t->next;
  30983. }
  30984. else
  30985. {
  30986. jassert (firstTimer == t);
  30987. firstTimer = t->next;
  30988. }
  30989. if (t->next != 0)
  30990. t->next->previous = t->previous;
  30991. t->next = 0;
  30992. t->previous = 0;
  30993. }
  30994. void decrementAllCounters (const int numMillisecs) const
  30995. {
  30996. Timer* t = firstTimer;
  30997. while (t != 0)
  30998. {
  30999. t->countdownMs -= numMillisecs;
  31000. t = t->next;
  31001. }
  31002. }
  31003. void handleAsyncUpdate()
  31004. {
  31005. startThread (7);
  31006. }
  31007. InternalTimerThread (const InternalTimerThread&);
  31008. InternalTimerThread& operator= (const InternalTimerThread&);
  31009. };
  31010. InternalTimerThread* InternalTimerThread::instance = 0;
  31011. CriticalSection InternalTimerThread::lock;
  31012. void juce_callAnyTimersSynchronously()
  31013. {
  31014. InternalTimerThread::callAnyTimersSynchronously();
  31015. }
  31016. #if JUCE_DEBUG
  31017. static SortedSet <Timer*> activeTimers;
  31018. #endif
  31019. Timer::Timer() throw()
  31020. : countdownMs (0),
  31021. periodMs (0),
  31022. previous (0),
  31023. next (0)
  31024. {
  31025. #if JUCE_DEBUG
  31026. activeTimers.add (this);
  31027. #endif
  31028. }
  31029. Timer::Timer (const Timer&) throw()
  31030. : countdownMs (0),
  31031. periodMs (0),
  31032. previous (0),
  31033. next (0)
  31034. {
  31035. #if JUCE_DEBUG
  31036. activeTimers.add (this);
  31037. #endif
  31038. }
  31039. Timer::~Timer()
  31040. {
  31041. stopTimer();
  31042. #if JUCE_DEBUG
  31043. activeTimers.removeValue (this);
  31044. #endif
  31045. }
  31046. void Timer::startTimer (const int interval) throw()
  31047. {
  31048. const ScopedLock sl (InternalTimerThread::lock);
  31049. #if JUCE_DEBUG
  31050. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31051. jassert (activeTimers.contains (this));
  31052. #endif
  31053. if (periodMs == 0)
  31054. {
  31055. countdownMs = interval;
  31056. periodMs = jmax (1, interval);
  31057. InternalTimerThread::add (this);
  31058. }
  31059. else
  31060. {
  31061. InternalTimerThread::resetCounter (this, interval);
  31062. }
  31063. }
  31064. void Timer::stopTimer() throw()
  31065. {
  31066. const ScopedLock sl (InternalTimerThread::lock);
  31067. #if JUCE_DEBUG
  31068. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31069. jassert (activeTimers.contains (this));
  31070. #endif
  31071. if (periodMs > 0)
  31072. {
  31073. InternalTimerThread::remove (this);
  31074. periodMs = 0;
  31075. }
  31076. }
  31077. END_JUCE_NAMESPACE
  31078. /*** End of inlined file: juce_Timer.cpp ***/
  31079. #endif
  31080. #if JUCE_BUILD_GUI
  31081. /*** Start of inlined file: juce_Component.cpp ***/
  31082. BEGIN_JUCE_NAMESPACE
  31083. #define checkMessageManagerIsLocked jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  31084. enum ComponentMessageNumbers
  31085. {
  31086. customCommandMessage = 0x7fff0001,
  31087. exitModalStateMessage = 0x7fff0002
  31088. };
  31089. static uint32 nextComponentUID = 0;
  31090. Component* Component::currentlyFocusedComponent = 0;
  31091. Component::Component()
  31092. : parentComponent_ (0),
  31093. componentUID (++nextComponentUID),
  31094. numDeepMouseListeners (0),
  31095. lookAndFeel_ (0),
  31096. effect_ (0),
  31097. bufferedImage_ (0),
  31098. mouseListeners_ (0),
  31099. keyListeners_ (0),
  31100. componentFlags_ (0)
  31101. {
  31102. }
  31103. Component::Component (const String& name)
  31104. : componentName_ (name),
  31105. parentComponent_ (0),
  31106. componentUID (++nextComponentUID),
  31107. numDeepMouseListeners (0),
  31108. lookAndFeel_ (0),
  31109. effect_ (0),
  31110. bufferedImage_ (0),
  31111. mouseListeners_ (0),
  31112. keyListeners_ (0),
  31113. componentFlags_ (0)
  31114. {
  31115. }
  31116. Component::~Component()
  31117. {
  31118. componentListeners.call (&ComponentListener::componentBeingDeleted, *this);
  31119. if (parentComponent_ != 0)
  31120. {
  31121. parentComponent_->removeChildComponent (this);
  31122. }
  31123. else if ((currentlyFocusedComponent == this)
  31124. || isParentOf (currentlyFocusedComponent))
  31125. {
  31126. giveAwayFocus();
  31127. }
  31128. if (flags.hasHeavyweightPeerFlag)
  31129. removeFromDesktop();
  31130. for (int i = childComponentList_.size(); --i >= 0;)
  31131. childComponentList_.getUnchecked(i)->parentComponent_ = 0;
  31132. delete mouseListeners_;
  31133. delete keyListeners_;
  31134. }
  31135. void Component::setName (const String& name)
  31136. {
  31137. // if component methods are being called from threads other than the message
  31138. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31139. checkMessageManagerIsLocked
  31140. if (componentName_ != name)
  31141. {
  31142. componentName_ = name;
  31143. if (flags.hasHeavyweightPeerFlag)
  31144. {
  31145. ComponentPeer* const peer = getPeer();
  31146. jassert (peer != 0);
  31147. if (peer != 0)
  31148. peer->setTitle (name);
  31149. }
  31150. BailOutChecker checker (this);
  31151. componentListeners.callChecked (checker, &ComponentListener::componentNameChanged, *this);
  31152. }
  31153. }
  31154. void Component::setVisible (bool shouldBeVisible)
  31155. {
  31156. if (flags.visibleFlag != shouldBeVisible)
  31157. {
  31158. // if component methods are being called from threads other than the message
  31159. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31160. checkMessageManagerIsLocked
  31161. SafePointer<Component> safePointer (this);
  31162. flags.visibleFlag = shouldBeVisible;
  31163. internalRepaint (0, 0, getWidth(), getHeight());
  31164. sendFakeMouseMove();
  31165. if (! shouldBeVisible)
  31166. {
  31167. if (currentlyFocusedComponent == this
  31168. || isParentOf (currentlyFocusedComponent))
  31169. {
  31170. if (parentComponent_ != 0)
  31171. parentComponent_->grabKeyboardFocus();
  31172. else
  31173. giveAwayFocus();
  31174. }
  31175. }
  31176. if (safePointer != 0)
  31177. {
  31178. sendVisibilityChangeMessage();
  31179. if (safePointer != 0 && flags.hasHeavyweightPeerFlag)
  31180. {
  31181. ComponentPeer* const peer = getPeer();
  31182. jassert (peer != 0);
  31183. if (peer != 0)
  31184. {
  31185. peer->setVisible (shouldBeVisible);
  31186. internalHierarchyChanged();
  31187. }
  31188. }
  31189. }
  31190. }
  31191. }
  31192. void Component::visibilityChanged()
  31193. {
  31194. }
  31195. void Component::sendVisibilityChangeMessage()
  31196. {
  31197. BailOutChecker checker (this);
  31198. visibilityChanged();
  31199. if (! checker.shouldBailOut())
  31200. componentListeners.callChecked (checker, &ComponentListener::componentVisibilityChanged, *this);
  31201. }
  31202. bool Component::isShowing() const
  31203. {
  31204. if (flags.visibleFlag)
  31205. {
  31206. if (parentComponent_ != 0)
  31207. {
  31208. return parentComponent_->isShowing();
  31209. }
  31210. else
  31211. {
  31212. const ComponentPeer* const peer = getPeer();
  31213. return peer != 0 && ! peer->isMinimised();
  31214. }
  31215. }
  31216. return false;
  31217. }
  31218. class FadeOutProxyComponent : public Component,
  31219. public Timer
  31220. {
  31221. public:
  31222. FadeOutProxyComponent (Component* comp,
  31223. const int fadeLengthMs,
  31224. const int deltaXToMove,
  31225. const int deltaYToMove,
  31226. const float scaleFactorAtEnd)
  31227. : lastTime (0),
  31228. alpha (1.0f),
  31229. scale (1.0f)
  31230. {
  31231. image = comp->createComponentSnapshot (comp->getLocalBounds());
  31232. setBounds (comp->getBounds());
  31233. comp->getParentComponent()->addAndMakeVisible (this);
  31234. toBehind (comp);
  31235. alphaChangePerMs = -1.0f / (float)fadeLengthMs;
  31236. centreX = comp->getX() + comp->getWidth() * 0.5f;
  31237. xChangePerMs = deltaXToMove / (float)fadeLengthMs;
  31238. centreY = comp->getY() + comp->getHeight() * 0.5f;
  31239. yChangePerMs = deltaYToMove / (float)fadeLengthMs;
  31240. scaleChangePerMs = (scaleFactorAtEnd - 1.0f) / (float)fadeLengthMs;
  31241. setInterceptsMouseClicks (false, false);
  31242. // 30 fps is enough for a fade, but we need a higher rate if it's moving as well..
  31243. startTimer (1000 / ((deltaXToMove == 0 && deltaYToMove == 0) ? 30 : 50));
  31244. }
  31245. ~FadeOutProxyComponent()
  31246. {
  31247. }
  31248. void paint (Graphics& g)
  31249. {
  31250. g.setOpacity (alpha);
  31251. g.drawImage (image,
  31252. 0, 0, getWidth(), getHeight(),
  31253. 0, 0, image.getWidth(), image.getHeight());
  31254. }
  31255. void timerCallback()
  31256. {
  31257. const uint32 now = Time::getMillisecondCounter();
  31258. if (lastTime == 0)
  31259. lastTime = now;
  31260. const int msPassed = (now > lastTime) ? now - lastTime : 0;
  31261. lastTime = now;
  31262. alpha += alphaChangePerMs * msPassed;
  31263. if (alpha > 0)
  31264. {
  31265. if (xChangePerMs != 0.0f || yChangePerMs != 0.0f || scaleChangePerMs != 0.0f)
  31266. {
  31267. centreX += xChangePerMs * msPassed;
  31268. centreY += yChangePerMs * msPassed;
  31269. scale += scaleChangePerMs * msPassed;
  31270. const int w = roundToInt (image.getWidth() * scale);
  31271. const int h = roundToInt (image.getHeight() * scale);
  31272. setBounds (roundToInt (centreX) - w / 2,
  31273. roundToInt (centreY) - h / 2,
  31274. w, h);
  31275. }
  31276. repaint();
  31277. }
  31278. else
  31279. {
  31280. delete this;
  31281. }
  31282. }
  31283. juce_UseDebuggingNewOperator
  31284. private:
  31285. Image image;
  31286. uint32 lastTime;
  31287. float alpha, alphaChangePerMs;
  31288. float centreX, xChangePerMs;
  31289. float centreY, yChangePerMs;
  31290. float scale, scaleChangePerMs;
  31291. FadeOutProxyComponent (const FadeOutProxyComponent&);
  31292. FadeOutProxyComponent& operator= (const FadeOutProxyComponent&);
  31293. };
  31294. void Component::fadeOutComponent (const int millisecondsToFade,
  31295. const int deltaXToMove,
  31296. const int deltaYToMove,
  31297. const float scaleFactorAtEnd)
  31298. {
  31299. //xxx won't work for comps without parents
  31300. if (isShowing() && millisecondsToFade > 0)
  31301. new FadeOutProxyComponent (this, millisecondsToFade,
  31302. deltaXToMove, deltaYToMove, scaleFactorAtEnd);
  31303. setVisible (false);
  31304. }
  31305. bool Component::isValidComponent() const
  31306. {
  31307. return (this != 0) && isValidMessageListener();
  31308. }
  31309. void* Component::getWindowHandle() const
  31310. {
  31311. const ComponentPeer* const peer = getPeer();
  31312. if (peer != 0)
  31313. return peer->getNativeHandle();
  31314. return 0;
  31315. }
  31316. void Component::addToDesktop (int styleWanted, void* nativeWindowToAttachTo)
  31317. {
  31318. // if component methods are being called from threads other than the message
  31319. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31320. checkMessageManagerIsLocked
  31321. if (isOpaque())
  31322. styleWanted &= ~ComponentPeer::windowIsSemiTransparent;
  31323. else
  31324. styleWanted |= ComponentPeer::windowIsSemiTransparent;
  31325. int currentStyleFlags = 0;
  31326. // don't use getPeer(), so that we only get the peer that's specifically
  31327. // for this comp, and not for one of its parents.
  31328. ComponentPeer* peer = ComponentPeer::getPeerFor (this);
  31329. if (peer != 0)
  31330. currentStyleFlags = peer->getStyleFlags();
  31331. if (styleWanted != currentStyleFlags || ! flags.hasHeavyweightPeerFlag)
  31332. {
  31333. SafePointer<Component> safePointer (this);
  31334. #if JUCE_LINUX
  31335. // it's wise to give the component a non-zero size before
  31336. // putting it on the desktop, as X windows get confused by this, and
  31337. // a (1, 1) minimum size is enforced here.
  31338. setSize (jmax (1, getWidth()),
  31339. jmax (1, getHeight()));
  31340. #endif
  31341. const Point<int> topLeft (relativePositionToGlobal (Point<int> (0, 0)));
  31342. bool wasFullscreen = false;
  31343. bool wasMinimised = false;
  31344. ComponentBoundsConstrainer* currentConstainer = 0;
  31345. Rectangle<int> oldNonFullScreenBounds;
  31346. if (peer != 0)
  31347. {
  31348. wasFullscreen = peer->isFullScreen();
  31349. wasMinimised = peer->isMinimised();
  31350. currentConstainer = peer->getConstrainer();
  31351. oldNonFullScreenBounds = peer->getNonFullScreenBounds();
  31352. removeFromDesktop();
  31353. setTopLeftPosition (topLeft.getX(), topLeft.getY());
  31354. }
  31355. if (parentComponent_ != 0)
  31356. parentComponent_->removeChildComponent (this);
  31357. if (safePointer != 0)
  31358. {
  31359. flags.hasHeavyweightPeerFlag = true;
  31360. peer = createNewPeer (styleWanted, nativeWindowToAttachTo);
  31361. Desktop::getInstance().addDesktopComponent (this);
  31362. bounds_.setPosition (topLeft);
  31363. peer->setBounds (topLeft.getX(), topLeft.getY(), getWidth(), getHeight(), false);
  31364. peer->setVisible (isVisible());
  31365. if (wasFullscreen)
  31366. {
  31367. peer->setFullScreen (true);
  31368. peer->setNonFullScreenBounds (oldNonFullScreenBounds);
  31369. }
  31370. if (wasMinimised)
  31371. peer->setMinimised (true);
  31372. if (isAlwaysOnTop())
  31373. peer->setAlwaysOnTop (true);
  31374. peer->setConstrainer (currentConstainer);
  31375. repaint();
  31376. }
  31377. internalHierarchyChanged();
  31378. }
  31379. }
  31380. void Component::removeFromDesktop()
  31381. {
  31382. // if component methods are being called from threads other than the message
  31383. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31384. checkMessageManagerIsLocked
  31385. if (flags.hasHeavyweightPeerFlag)
  31386. {
  31387. ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  31388. flags.hasHeavyweightPeerFlag = false;
  31389. jassert (peer != 0);
  31390. delete peer;
  31391. Desktop::getInstance().removeDesktopComponent (this);
  31392. }
  31393. }
  31394. bool Component::isOnDesktop() const throw()
  31395. {
  31396. return flags.hasHeavyweightPeerFlag;
  31397. }
  31398. void Component::userTriedToCloseWindow()
  31399. {
  31400. /* This means that the user's trying to get rid of your window with the 'close window' system
  31401. menu option (on windows) or possibly the task manager - you should really handle this
  31402. and delete or hide your component in an appropriate way.
  31403. If you want to ignore the event and don't want to trigger this assertion, just override
  31404. this method and do nothing.
  31405. */
  31406. jassertfalse;
  31407. }
  31408. void Component::minimisationStateChanged (bool)
  31409. {
  31410. }
  31411. void Component::setOpaque (const bool shouldBeOpaque)
  31412. {
  31413. if (shouldBeOpaque != flags.opaqueFlag)
  31414. {
  31415. flags.opaqueFlag = shouldBeOpaque;
  31416. if (flags.hasHeavyweightPeerFlag)
  31417. {
  31418. const ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  31419. if (peer != 0)
  31420. {
  31421. // to make it recreate the heavyweight window
  31422. addToDesktop (peer->getStyleFlags());
  31423. }
  31424. }
  31425. repaint();
  31426. }
  31427. }
  31428. bool Component::isOpaque() const throw()
  31429. {
  31430. return flags.opaqueFlag;
  31431. }
  31432. void Component::setBufferedToImage (const bool shouldBeBuffered)
  31433. {
  31434. if (shouldBeBuffered != flags.bufferToImageFlag)
  31435. {
  31436. bufferedImage_ = Image();
  31437. flags.bufferToImageFlag = shouldBeBuffered;
  31438. }
  31439. }
  31440. void Component::toFront (const bool setAsForeground)
  31441. {
  31442. // if component methods are being called from threads other than the message
  31443. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31444. checkMessageManagerIsLocked
  31445. if (flags.hasHeavyweightPeerFlag)
  31446. {
  31447. ComponentPeer* const peer = getPeer();
  31448. if (peer != 0)
  31449. {
  31450. peer->toFront (setAsForeground);
  31451. if (setAsForeground && ! hasKeyboardFocus (true))
  31452. grabKeyboardFocus();
  31453. }
  31454. }
  31455. else if (parentComponent_ != 0)
  31456. {
  31457. Array<Component*>& childList = parentComponent_->childComponentList_;
  31458. if (childList.getLast() != this)
  31459. {
  31460. const int index = childList.indexOf (this);
  31461. if (index >= 0)
  31462. {
  31463. int insertIndex = -1;
  31464. if (! flags.alwaysOnTopFlag)
  31465. {
  31466. insertIndex = childList.size() - 1;
  31467. while (insertIndex > 0 && childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  31468. --insertIndex;
  31469. }
  31470. if (index != insertIndex)
  31471. {
  31472. childList.move (index, insertIndex);
  31473. sendFakeMouseMove();
  31474. repaintParent();
  31475. }
  31476. }
  31477. }
  31478. if (setAsForeground)
  31479. {
  31480. internalBroughtToFront();
  31481. grabKeyboardFocus();
  31482. }
  31483. }
  31484. }
  31485. void Component::toBehind (Component* const other)
  31486. {
  31487. if (other != 0 && other != this)
  31488. {
  31489. // the two components must belong to the same parent..
  31490. jassert (parentComponent_ == other->parentComponent_);
  31491. if (parentComponent_ != 0)
  31492. {
  31493. Array<Component*>& childList = parentComponent_->childComponentList_;
  31494. const int index = childList.indexOf (this);
  31495. if (index >= 0 && childList [index + 1] != other)
  31496. {
  31497. int otherIndex = childList.indexOf (other);
  31498. if (otherIndex >= 0)
  31499. {
  31500. if (index < otherIndex)
  31501. --otherIndex;
  31502. childList.move (index, otherIndex);
  31503. sendFakeMouseMove();
  31504. repaintParent();
  31505. }
  31506. }
  31507. }
  31508. else if (isOnDesktop())
  31509. {
  31510. jassert (other->isOnDesktop());
  31511. if (other->isOnDesktop())
  31512. {
  31513. ComponentPeer* const us = getPeer();
  31514. ComponentPeer* const them = other->getPeer();
  31515. jassert (us != 0 && them != 0);
  31516. if (us != 0 && them != 0)
  31517. us->toBehind (them);
  31518. }
  31519. }
  31520. }
  31521. }
  31522. void Component::toBack()
  31523. {
  31524. Array<Component*>& childList = parentComponent_->childComponentList_;
  31525. if (isOnDesktop())
  31526. {
  31527. jassertfalse; //xxx need to add this to native window
  31528. }
  31529. else if (parentComponent_ != 0 && childList.getFirst() != this)
  31530. {
  31531. const int index = childList.indexOf (this);
  31532. if (index > 0)
  31533. {
  31534. int insertIndex = 0;
  31535. if (flags.alwaysOnTopFlag)
  31536. {
  31537. while (insertIndex < childList.size()
  31538. && ! childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  31539. {
  31540. ++insertIndex;
  31541. }
  31542. }
  31543. if (index != insertIndex)
  31544. {
  31545. childList.move (index, insertIndex);
  31546. sendFakeMouseMove();
  31547. repaintParent();
  31548. }
  31549. }
  31550. }
  31551. }
  31552. void Component::setAlwaysOnTop (const bool shouldStayOnTop)
  31553. {
  31554. if (shouldStayOnTop != flags.alwaysOnTopFlag)
  31555. {
  31556. flags.alwaysOnTopFlag = shouldStayOnTop;
  31557. if (isOnDesktop())
  31558. {
  31559. ComponentPeer* const peer = getPeer();
  31560. jassert (peer != 0);
  31561. if (peer != 0)
  31562. {
  31563. if (! peer->setAlwaysOnTop (shouldStayOnTop))
  31564. {
  31565. // some kinds of peer can't change their always-on-top status, so
  31566. // for these, we'll need to create a new window
  31567. const int oldFlags = peer->getStyleFlags();
  31568. removeFromDesktop();
  31569. addToDesktop (oldFlags);
  31570. }
  31571. }
  31572. }
  31573. if (shouldStayOnTop)
  31574. toFront (false);
  31575. internalHierarchyChanged();
  31576. }
  31577. }
  31578. bool Component::isAlwaysOnTop() const throw()
  31579. {
  31580. return flags.alwaysOnTopFlag;
  31581. }
  31582. int Component::proportionOfWidth (const float proportion) const throw()
  31583. {
  31584. return roundToInt (proportion * bounds_.getWidth());
  31585. }
  31586. int Component::proportionOfHeight (const float proportion) const throw()
  31587. {
  31588. return roundToInt (proportion * bounds_.getHeight());
  31589. }
  31590. int Component::getParentWidth() const throw()
  31591. {
  31592. return (parentComponent_ != 0) ? parentComponent_->getWidth()
  31593. : getParentMonitorArea().getWidth();
  31594. }
  31595. int Component::getParentHeight() const throw()
  31596. {
  31597. return (parentComponent_ != 0) ? parentComponent_->getHeight()
  31598. : getParentMonitorArea().getHeight();
  31599. }
  31600. int Component::getScreenX() const
  31601. {
  31602. return getScreenPosition().getX();
  31603. }
  31604. int Component::getScreenY() const
  31605. {
  31606. return getScreenPosition().getY();
  31607. }
  31608. const Point<int> Component::getScreenPosition() const
  31609. {
  31610. return (parentComponent_ != 0) ? parentComponent_->getScreenPosition() + getPosition()
  31611. : (flags.hasHeavyweightPeerFlag ? getPeer()->getScreenPosition()
  31612. : getPosition());
  31613. }
  31614. const Rectangle<int> Component::getScreenBounds() const
  31615. {
  31616. return bounds_.withPosition (getScreenPosition());
  31617. }
  31618. const Point<int> Component::relativePositionToGlobal (const Point<int>& relativePosition) const
  31619. {
  31620. const Component* c = this;
  31621. Point<int> p (relativePosition);
  31622. do
  31623. {
  31624. if (c->flags.hasHeavyweightPeerFlag)
  31625. return c->getPeer()->relativePositionToGlobal (p);
  31626. p += c->getPosition();
  31627. c = c->parentComponent_;
  31628. }
  31629. while (c != 0);
  31630. return p;
  31631. }
  31632. const Point<int> Component::globalPositionToRelative (const Point<int>& screenPosition) const
  31633. {
  31634. if (flags.hasHeavyweightPeerFlag)
  31635. {
  31636. return getPeer()->globalPositionToRelative (screenPosition);
  31637. }
  31638. else
  31639. {
  31640. if (parentComponent_ != 0)
  31641. return parentComponent_->globalPositionToRelative (screenPosition) - getPosition();
  31642. return screenPosition - getPosition();
  31643. }
  31644. }
  31645. const Point<int> Component::relativePositionToOtherComponent (const Component* const targetComponent, const Point<int>& positionRelativeToThis) const
  31646. {
  31647. Point<int> p (positionRelativeToThis);
  31648. if (targetComponent != 0)
  31649. {
  31650. const Component* c = this;
  31651. do
  31652. {
  31653. if (c == targetComponent)
  31654. return p;
  31655. if (c->flags.hasHeavyweightPeerFlag)
  31656. {
  31657. p = c->getPeer()->relativePositionToGlobal (p);
  31658. break;
  31659. }
  31660. p += c->getPosition();
  31661. c = c->parentComponent_;
  31662. }
  31663. while (c != 0);
  31664. p = targetComponent->globalPositionToRelative (p);
  31665. }
  31666. return p;
  31667. }
  31668. void Component::setBounds (int x, int y, int w, int h)
  31669. {
  31670. // if component methods are being called from threads other than the message
  31671. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31672. checkMessageManagerIsLocked
  31673. if (w < 0) w = 0;
  31674. if (h < 0) h = 0;
  31675. const bool wasResized = (getWidth() != w || getHeight() != h);
  31676. const bool wasMoved = (getX() != x || getY() != y);
  31677. #if JUCE_DEBUG
  31678. // It's a very bad idea to try to resize a window during its paint() method!
  31679. jassert (! (flags.isInsidePaintCall && wasResized && isOnDesktop()));
  31680. #endif
  31681. if (wasMoved || wasResized)
  31682. {
  31683. if (flags.visibleFlag)
  31684. {
  31685. // send a fake mouse move to trigger enter/exit messages if needed..
  31686. sendFakeMouseMove();
  31687. if (! flags.hasHeavyweightPeerFlag)
  31688. repaintParent();
  31689. }
  31690. bounds_.setBounds (x, y, w, h);
  31691. if (wasResized)
  31692. repaint();
  31693. else if (! flags.hasHeavyweightPeerFlag)
  31694. repaintParent();
  31695. if (flags.hasHeavyweightPeerFlag)
  31696. {
  31697. ComponentPeer* const peer = getPeer();
  31698. if (peer != 0)
  31699. {
  31700. if (wasMoved && wasResized)
  31701. peer->setBounds (getX(), getY(), getWidth(), getHeight(), false);
  31702. else if (wasMoved)
  31703. peer->setPosition (getX(), getY());
  31704. else if (wasResized)
  31705. peer->setSize (getWidth(), getHeight());
  31706. }
  31707. }
  31708. sendMovedResizedMessages (wasMoved, wasResized);
  31709. }
  31710. }
  31711. void Component::sendMovedResizedMessages (const bool wasMoved, const bool wasResized)
  31712. {
  31713. JUCE_TRY
  31714. {
  31715. if (wasMoved)
  31716. moved();
  31717. if (wasResized)
  31718. {
  31719. resized();
  31720. for (int i = childComponentList_.size(); --i >= 0;)
  31721. {
  31722. childComponentList_.getUnchecked(i)->parentSizeChanged();
  31723. i = jmin (i, childComponentList_.size());
  31724. }
  31725. }
  31726. BailOutChecker checker (this);
  31727. if (parentComponent_ != 0)
  31728. parentComponent_->childBoundsChanged (this);
  31729. if (! checker.shouldBailOut())
  31730. componentListeners.callChecked (checker, &ComponentListener::componentMovedOrResized,
  31731. *this, wasMoved, wasResized);
  31732. }
  31733. JUCE_CATCH_EXCEPTION
  31734. }
  31735. void Component::setSize (const int w, const int h)
  31736. {
  31737. setBounds (getX(), getY(), w, h);
  31738. }
  31739. void Component::setTopLeftPosition (const int x, const int y)
  31740. {
  31741. setBounds (x, y, getWidth(), getHeight());
  31742. }
  31743. void Component::setTopRightPosition (const int x, const int y)
  31744. {
  31745. setTopLeftPosition (x - getWidth(), y);
  31746. }
  31747. void Component::setBounds (const Rectangle<int>& r)
  31748. {
  31749. setBounds (r.getX(),
  31750. r.getY(),
  31751. r.getWidth(),
  31752. r.getHeight());
  31753. }
  31754. void Component::setBoundsRelative (const float x, const float y,
  31755. const float w, const float h)
  31756. {
  31757. const int pw = getParentWidth();
  31758. const int ph = getParentHeight();
  31759. setBounds (roundToInt (x * pw),
  31760. roundToInt (y * ph),
  31761. roundToInt (w * pw),
  31762. roundToInt (h * ph));
  31763. }
  31764. void Component::setCentrePosition (const int x, const int y)
  31765. {
  31766. setTopLeftPosition (x - getWidth() / 2,
  31767. y - getHeight() / 2);
  31768. }
  31769. void Component::setCentreRelative (const float x, const float y)
  31770. {
  31771. setCentrePosition (roundToInt (getParentWidth() * x),
  31772. roundToInt (getParentHeight() * y));
  31773. }
  31774. void Component::centreWithSize (const int width, const int height)
  31775. {
  31776. setBounds ((getParentWidth() - width) / 2,
  31777. (getParentHeight() - height) / 2,
  31778. width,
  31779. height);
  31780. }
  31781. void Component::setBoundsInset (const BorderSize& borders)
  31782. {
  31783. setBounds (borders.getLeft(),
  31784. borders.getTop(),
  31785. getParentWidth() - (borders.getLeftAndRight()),
  31786. getParentHeight() - (borders.getTopAndBottom()));
  31787. }
  31788. void Component::setBoundsToFit (int x, int y, int width, int height,
  31789. const Justification& justification,
  31790. const bool onlyReduceInSize)
  31791. {
  31792. // it's no good calling this method unless both the component and
  31793. // target rectangle have a finite size.
  31794. jassert (getWidth() > 0 && getHeight() > 0 && width > 0 && height > 0);
  31795. if (getWidth() > 0 && getHeight() > 0
  31796. && width > 0 && height > 0)
  31797. {
  31798. int newW, newH;
  31799. if (onlyReduceInSize && getWidth() <= width && getHeight() <= height)
  31800. {
  31801. newW = getWidth();
  31802. newH = getHeight();
  31803. }
  31804. else
  31805. {
  31806. const double imageRatio = getHeight() / (double) getWidth();
  31807. const double targetRatio = height / (double) width;
  31808. if (imageRatio <= targetRatio)
  31809. {
  31810. newW = width;
  31811. newH = jmin (height, roundToInt (newW * imageRatio));
  31812. }
  31813. else
  31814. {
  31815. newH = height;
  31816. newW = jmin (width, roundToInt (newH / imageRatio));
  31817. }
  31818. }
  31819. if (newW > 0 && newH > 0)
  31820. {
  31821. int newX, newY;
  31822. justification.applyToRectangle (newX, newY, newW, newH,
  31823. x, y, width, height);
  31824. setBounds (newX, newY, newW, newH);
  31825. }
  31826. }
  31827. }
  31828. bool Component::hitTest (int x, int y)
  31829. {
  31830. if (! flags.ignoresMouseClicksFlag)
  31831. return true;
  31832. if (flags.allowChildMouseClicksFlag)
  31833. {
  31834. for (int i = getNumChildComponents(); --i >= 0;)
  31835. {
  31836. Component* const c = getChildComponent (i);
  31837. if (c->isVisible()
  31838. && c->bounds_.contains (x, y)
  31839. && c->hitTest (x - c->getX(),
  31840. y - c->getY()))
  31841. {
  31842. return true;
  31843. }
  31844. }
  31845. }
  31846. return false;
  31847. }
  31848. void Component::setInterceptsMouseClicks (const bool allowClicks,
  31849. const bool allowClicksOnChildComponents) throw()
  31850. {
  31851. flags.ignoresMouseClicksFlag = ! allowClicks;
  31852. flags.allowChildMouseClicksFlag = allowClicksOnChildComponents;
  31853. }
  31854. void Component::getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  31855. bool& allowsClicksOnChildComponents) const throw()
  31856. {
  31857. allowsClicksOnThisComponent = ! flags.ignoresMouseClicksFlag;
  31858. allowsClicksOnChildComponents = flags.allowChildMouseClicksFlag;
  31859. }
  31860. bool Component::contains (const int x, const int y)
  31861. {
  31862. if (((unsigned int) x) < (unsigned int) getWidth()
  31863. && ((unsigned int) y) < (unsigned int) getHeight()
  31864. && hitTest (x, y))
  31865. {
  31866. if (parentComponent_ != 0)
  31867. {
  31868. return parentComponent_->contains (x + getX(),
  31869. y + getY());
  31870. }
  31871. else if (flags.hasHeavyweightPeerFlag)
  31872. {
  31873. const ComponentPeer* const peer = getPeer();
  31874. if (peer != 0)
  31875. return peer->contains (Point<int> (x, y), true);
  31876. }
  31877. }
  31878. return false;
  31879. }
  31880. bool Component::reallyContains (int x, int y, const bool returnTrueIfWithinAChild)
  31881. {
  31882. if (! contains (x, y))
  31883. return false;
  31884. Component* p = this;
  31885. while (p->parentComponent_ != 0)
  31886. {
  31887. x += p->getX();
  31888. y += p->getY();
  31889. p = p->parentComponent_;
  31890. }
  31891. const Component* const c = p->getComponentAt (x, y);
  31892. return (c == this) || (returnTrueIfWithinAChild && isParentOf (c));
  31893. }
  31894. Component* Component::getComponentAt (const Point<int>& position)
  31895. {
  31896. return getComponentAt (position.getX(), position.getY());
  31897. }
  31898. Component* Component::getComponentAt (const int x, const int y)
  31899. {
  31900. if (flags.visibleFlag
  31901. && ((unsigned int) x) < (unsigned int) getWidth()
  31902. && ((unsigned int) y) < (unsigned int) getHeight()
  31903. && hitTest (x, y))
  31904. {
  31905. for (int i = childComponentList_.size(); --i >= 0;)
  31906. {
  31907. Component* const child = childComponentList_.getUnchecked(i);
  31908. Component* const c = child->getComponentAt (x - child->getX(),
  31909. y - child->getY());
  31910. if (c != 0)
  31911. return c;
  31912. }
  31913. return this;
  31914. }
  31915. return 0;
  31916. }
  31917. void Component::addChildComponent (Component* const child, int zOrder)
  31918. {
  31919. // if component methods are being called from threads other than the message
  31920. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31921. checkMessageManagerIsLocked
  31922. if (child != 0 && child->parentComponent_ != this)
  31923. {
  31924. if (child->parentComponent_ != 0)
  31925. child->parentComponent_->removeChildComponent (child);
  31926. else
  31927. child->removeFromDesktop();
  31928. child->parentComponent_ = this;
  31929. if (child->isVisible())
  31930. child->repaintParent();
  31931. if (! child->isAlwaysOnTop())
  31932. {
  31933. if (zOrder < 0 || zOrder > childComponentList_.size())
  31934. zOrder = childComponentList_.size();
  31935. while (zOrder > 0)
  31936. {
  31937. if (! childComponentList_.getUnchecked (zOrder - 1)->isAlwaysOnTop())
  31938. break;
  31939. --zOrder;
  31940. }
  31941. }
  31942. childComponentList_.insert (zOrder, child);
  31943. child->internalHierarchyChanged();
  31944. internalChildrenChanged();
  31945. }
  31946. }
  31947. void Component::addAndMakeVisible (Component* const child, int zOrder)
  31948. {
  31949. if (child != 0)
  31950. {
  31951. child->setVisible (true);
  31952. addChildComponent (child, zOrder);
  31953. }
  31954. }
  31955. void Component::removeChildComponent (Component* const child)
  31956. {
  31957. removeChildComponent (childComponentList_.indexOf (child));
  31958. }
  31959. Component* Component::removeChildComponent (const int index)
  31960. {
  31961. // if component methods are being called from threads other than the message
  31962. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31963. checkMessageManagerIsLocked
  31964. Component* const child = childComponentList_ [index];
  31965. if (child != 0)
  31966. {
  31967. sendFakeMouseMove();
  31968. child->repaintParent();
  31969. childComponentList_.remove (index);
  31970. child->parentComponent_ = 0;
  31971. JUCE_TRY
  31972. {
  31973. if ((currentlyFocusedComponent == child)
  31974. || child->isParentOf (currentlyFocusedComponent))
  31975. {
  31976. // get rid first to force the grabKeyboardFocus to change to us.
  31977. giveAwayFocus();
  31978. grabKeyboardFocus();
  31979. }
  31980. }
  31981. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  31982. catch (const std::exception& e)
  31983. {
  31984. currentlyFocusedComponent = 0;
  31985. Desktop::getInstance().triggerFocusCallback();
  31986. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  31987. }
  31988. catch (...)
  31989. {
  31990. currentlyFocusedComponent = 0;
  31991. Desktop::getInstance().triggerFocusCallback();
  31992. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  31993. }
  31994. #endif
  31995. child->internalHierarchyChanged();
  31996. internalChildrenChanged();
  31997. }
  31998. return child;
  31999. }
  32000. void Component::removeAllChildren()
  32001. {
  32002. while (childComponentList_.size() > 0)
  32003. removeChildComponent (childComponentList_.size() - 1);
  32004. }
  32005. void Component::deleteAllChildren()
  32006. {
  32007. while (childComponentList_.size() > 0)
  32008. delete (removeChildComponent (childComponentList_.size() - 1));
  32009. }
  32010. int Component::getNumChildComponents() const throw()
  32011. {
  32012. return childComponentList_.size();
  32013. }
  32014. Component* Component::getChildComponent (const int index) const throw()
  32015. {
  32016. return childComponentList_ [index];
  32017. }
  32018. int Component::getIndexOfChildComponent (const Component* const child) const throw()
  32019. {
  32020. return childComponentList_.indexOf (const_cast <Component*> (child));
  32021. }
  32022. Component* Component::getTopLevelComponent() const throw()
  32023. {
  32024. const Component* comp = this;
  32025. while (comp->parentComponent_ != 0)
  32026. comp = comp->parentComponent_;
  32027. return const_cast <Component*> (comp);
  32028. }
  32029. bool Component::isParentOf (const Component* possibleChild) const throw()
  32030. {
  32031. if (! possibleChild->isValidComponent())
  32032. {
  32033. jassert (possibleChild == 0);
  32034. return false;
  32035. }
  32036. while (possibleChild != 0)
  32037. {
  32038. possibleChild = possibleChild->parentComponent_;
  32039. if (possibleChild == this)
  32040. return true;
  32041. }
  32042. return false;
  32043. }
  32044. void Component::parentHierarchyChanged()
  32045. {
  32046. }
  32047. void Component::childrenChanged()
  32048. {
  32049. }
  32050. void Component::internalChildrenChanged()
  32051. {
  32052. if (componentListeners.isEmpty())
  32053. {
  32054. childrenChanged();
  32055. }
  32056. else
  32057. {
  32058. BailOutChecker checker (this);
  32059. childrenChanged();
  32060. if (! checker.shouldBailOut())
  32061. componentListeners.callChecked (checker, &ComponentListener::componentChildrenChanged, *this);
  32062. }
  32063. }
  32064. void Component::internalHierarchyChanged()
  32065. {
  32066. BailOutChecker checker (this);
  32067. parentHierarchyChanged();
  32068. if (checker.shouldBailOut())
  32069. return;
  32070. componentListeners.callChecked (checker, &ComponentListener::componentParentHierarchyChanged, *this);
  32071. if (checker.shouldBailOut())
  32072. return;
  32073. for (int i = childComponentList_.size(); --i >= 0;)
  32074. {
  32075. childComponentList_.getUnchecked (i)->internalHierarchyChanged();
  32076. if (checker.shouldBailOut())
  32077. {
  32078. // you really shouldn't delete the parent component during a callback telling you
  32079. // that it's changed..
  32080. jassertfalse;
  32081. return;
  32082. }
  32083. i = jmin (i, childComponentList_.size());
  32084. }
  32085. }
  32086. void* Component::runModalLoopCallback (void* userData)
  32087. {
  32088. return (void*) (pointer_sized_int) static_cast <Component*> (userData)->runModalLoop();
  32089. }
  32090. int Component::runModalLoop()
  32091. {
  32092. if (! MessageManager::getInstance()->isThisTheMessageThread())
  32093. {
  32094. // use a callback so this can be called from non-gui threads
  32095. return (int) (pointer_sized_int) MessageManager::getInstance()
  32096. ->callFunctionOnMessageThread (&runModalLoopCallback, this);
  32097. }
  32098. if (! isCurrentlyModal())
  32099. enterModalState (true);
  32100. return ModalComponentManager::getInstance()->runEventLoopForCurrentComponent();
  32101. }
  32102. void Component::enterModalState (const bool takeKeyboardFocus_, ModalComponentManager::Callback* const callback)
  32103. {
  32104. // if component methods are being called from threads other than the message
  32105. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32106. checkMessageManagerIsLocked
  32107. // Check for an attempt to make a component modal when it already is!
  32108. // This can cause nasty problems..
  32109. jassert (! flags.currentlyModalFlag);
  32110. if (! isCurrentlyModal())
  32111. {
  32112. ModalComponentManager::getInstance()->startModal (this, callback);
  32113. flags.currentlyModalFlag = true;
  32114. setVisible (true);
  32115. if (takeKeyboardFocus_)
  32116. grabKeyboardFocus();
  32117. }
  32118. }
  32119. void Component::exitModalState (const int returnValue)
  32120. {
  32121. if (isCurrentlyModal())
  32122. {
  32123. if (MessageManager::getInstance()->isThisTheMessageThread())
  32124. {
  32125. ModalComponentManager::getInstance()->endModal (this, returnValue);
  32126. flags.currentlyModalFlag = false;
  32127. bringModalComponentToFront();
  32128. }
  32129. else
  32130. {
  32131. postMessage (new Message (exitModalStateMessage, returnValue, 0, 0));
  32132. }
  32133. }
  32134. }
  32135. bool Component::isCurrentlyModal() const throw()
  32136. {
  32137. return flags.currentlyModalFlag
  32138. && getCurrentlyModalComponent() == this;
  32139. }
  32140. bool Component::isCurrentlyBlockedByAnotherModalComponent() const
  32141. {
  32142. Component* const mc = getCurrentlyModalComponent();
  32143. return mc != 0
  32144. && mc != this
  32145. && (! mc->isParentOf (this))
  32146. && ! mc->canModalEventBeSentToComponent (this);
  32147. }
  32148. int JUCE_CALLTYPE Component::getNumCurrentlyModalComponents() throw()
  32149. {
  32150. return ModalComponentManager::getInstance()->getNumModalComponents();
  32151. }
  32152. Component* JUCE_CALLTYPE Component::getCurrentlyModalComponent (int index) throw()
  32153. {
  32154. return ModalComponentManager::getInstance()->getModalComponent (index);
  32155. }
  32156. void Component::bringModalComponentToFront()
  32157. {
  32158. ComponentPeer* lastOne = 0;
  32159. for (int i = 0; i < getNumCurrentlyModalComponents(); ++i)
  32160. {
  32161. Component* const c = getCurrentlyModalComponent (i);
  32162. if (c == 0)
  32163. break;
  32164. ComponentPeer* peer = c->getPeer();
  32165. if (peer != 0 && peer != lastOne)
  32166. {
  32167. if (lastOne == 0)
  32168. {
  32169. peer->toFront (true);
  32170. peer->grabFocus();
  32171. }
  32172. else
  32173. peer->toBehind (lastOne);
  32174. lastOne = peer;
  32175. }
  32176. }
  32177. }
  32178. void Component::setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw()
  32179. {
  32180. flags.bringToFrontOnClickFlag = shouldBeBroughtToFront;
  32181. }
  32182. bool Component::isBroughtToFrontOnMouseClick() const throw()
  32183. {
  32184. return flags.bringToFrontOnClickFlag;
  32185. }
  32186. void Component::setMouseCursor (const MouseCursor& cursor)
  32187. {
  32188. if (cursor_ != cursor)
  32189. {
  32190. cursor_ = cursor;
  32191. if (flags.visibleFlag)
  32192. updateMouseCursor();
  32193. }
  32194. }
  32195. const MouseCursor Component::getMouseCursor()
  32196. {
  32197. return cursor_;
  32198. }
  32199. void Component::updateMouseCursor() const
  32200. {
  32201. sendFakeMouseMove();
  32202. }
  32203. void Component::setRepaintsOnMouseActivity (const bool shouldRepaint) throw()
  32204. {
  32205. flags.repaintOnMouseActivityFlag = shouldRepaint;
  32206. }
  32207. void Component::repaintParent()
  32208. {
  32209. if (flags.visibleFlag)
  32210. internalRepaint (0, 0, getWidth(), getHeight());
  32211. }
  32212. void Component::repaint()
  32213. {
  32214. repaint (0, 0, getWidth(), getHeight());
  32215. }
  32216. void Component::repaint (const int x, const int y,
  32217. const int w, const int h)
  32218. {
  32219. bufferedImage_ = Image();
  32220. if (flags.visibleFlag)
  32221. internalRepaint (x, y, w, h);
  32222. }
  32223. void Component::repaint (const Rectangle<int>& area)
  32224. {
  32225. repaint (area.getX(), area.getY(), area.getWidth(), area.getHeight());
  32226. }
  32227. void Component::internalRepaint (int x, int y, int w, int h)
  32228. {
  32229. // if component methods are being called from threads other than the message
  32230. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32231. checkMessageManagerIsLocked
  32232. if (x < 0)
  32233. {
  32234. w += x;
  32235. x = 0;
  32236. }
  32237. if (x + w > getWidth())
  32238. w = getWidth() - x;
  32239. if (w > 0)
  32240. {
  32241. if (y < 0)
  32242. {
  32243. h += y;
  32244. y = 0;
  32245. }
  32246. if (y + h > getHeight())
  32247. h = getHeight() - y;
  32248. if (h > 0)
  32249. {
  32250. if (parentComponent_ != 0)
  32251. {
  32252. x += getX();
  32253. y += getY();
  32254. if (parentComponent_->flags.visibleFlag)
  32255. parentComponent_->internalRepaint (x, y, w, h);
  32256. }
  32257. else if (flags.hasHeavyweightPeerFlag)
  32258. {
  32259. ComponentPeer* const peer = getPeer();
  32260. if (peer != 0)
  32261. peer->repaint (Rectangle<int> (x, y, w, h));
  32262. }
  32263. }
  32264. }
  32265. }
  32266. void Component::renderComponent (Graphics& g)
  32267. {
  32268. const Rectangle<int> clipBounds (g.getClipBounds());
  32269. g.saveState();
  32270. clipObscuredRegions (g, clipBounds, 0, 0);
  32271. if (! g.isClipEmpty())
  32272. {
  32273. if (flags.bufferToImageFlag)
  32274. {
  32275. if (bufferedImage_.isNull())
  32276. {
  32277. bufferedImage_ = Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  32278. getWidth(), getHeight(), ! flags.opaqueFlag, Image::NativeImage);
  32279. Graphics imG (bufferedImage_);
  32280. paint (imG);
  32281. }
  32282. g.setColour (Colours::black);
  32283. g.drawImageAt (bufferedImage_, 0, 0);
  32284. }
  32285. else
  32286. {
  32287. paint (g);
  32288. }
  32289. }
  32290. g.restoreState();
  32291. for (int i = 0; i < childComponentList_.size(); ++i)
  32292. {
  32293. Component* const child = childComponentList_.getUnchecked (i);
  32294. if (child->isVisible() && clipBounds.intersects (child->getBounds()))
  32295. {
  32296. g.saveState();
  32297. if (g.reduceClipRegion (child->getX(), child->getY(),
  32298. child->getWidth(), child->getHeight()))
  32299. {
  32300. for (int j = i + 1; j < childComponentList_.size(); ++j)
  32301. {
  32302. const Component* const sibling = childComponentList_.getUnchecked (j);
  32303. if (sibling->flags.opaqueFlag && sibling->isVisible())
  32304. g.excludeClipRegion (sibling->getBounds());
  32305. }
  32306. if (! g.isClipEmpty())
  32307. {
  32308. g.setOrigin (child->getX(), child->getY());
  32309. child->paintEntireComponent (g);
  32310. }
  32311. }
  32312. g.restoreState();
  32313. }
  32314. }
  32315. g.saveState();
  32316. paintOverChildren (g);
  32317. g.restoreState();
  32318. }
  32319. void Component::paintEntireComponent (Graphics& g)
  32320. {
  32321. jassert (! g.isClipEmpty());
  32322. #if JUCE_DEBUG
  32323. flags.isInsidePaintCall = true;
  32324. #endif
  32325. if (effect_ != 0)
  32326. {
  32327. Image effectImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  32328. getWidth(), getHeight(),
  32329. ! flags.opaqueFlag, Image::NativeImage);
  32330. {
  32331. Graphics g2 (effectImage);
  32332. renderComponent (g2);
  32333. }
  32334. effect_->applyEffect (effectImage, g);
  32335. }
  32336. else
  32337. {
  32338. renderComponent (g);
  32339. }
  32340. #if JUCE_DEBUG
  32341. flags.isInsidePaintCall = false;
  32342. #endif
  32343. }
  32344. const Image Component::createComponentSnapshot (const Rectangle<int>& areaToGrab,
  32345. const bool clipImageToComponentBounds)
  32346. {
  32347. Rectangle<int> r (areaToGrab);
  32348. if (clipImageToComponentBounds)
  32349. r = r.getIntersection (getLocalBounds());
  32350. Image componentImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  32351. jmax (1, r.getWidth()),
  32352. jmax (1, r.getHeight()),
  32353. true);
  32354. Graphics imageContext (componentImage);
  32355. imageContext.setOrigin (-r.getX(), -r.getY());
  32356. paintEntireComponent (imageContext);
  32357. return componentImage;
  32358. }
  32359. void Component::setComponentEffect (ImageEffectFilter* const effect)
  32360. {
  32361. if (effect_ != effect)
  32362. {
  32363. effect_ = effect;
  32364. repaint();
  32365. }
  32366. }
  32367. LookAndFeel& Component::getLookAndFeel() const throw()
  32368. {
  32369. const Component* c = this;
  32370. do
  32371. {
  32372. if (c->lookAndFeel_ != 0)
  32373. return *(c->lookAndFeel_);
  32374. c = c->parentComponent_;
  32375. }
  32376. while (c != 0);
  32377. return LookAndFeel::getDefaultLookAndFeel();
  32378. }
  32379. void Component::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  32380. {
  32381. if (lookAndFeel_ != newLookAndFeel)
  32382. {
  32383. lookAndFeel_ = newLookAndFeel;
  32384. sendLookAndFeelChange();
  32385. }
  32386. }
  32387. void Component::lookAndFeelChanged()
  32388. {
  32389. }
  32390. void Component::sendLookAndFeelChange()
  32391. {
  32392. repaint();
  32393. lookAndFeelChanged();
  32394. // (it's not a great idea to do anything that would delete this component
  32395. // during the lookAndFeelChanged() callback)
  32396. jassert (isValidComponent());
  32397. SafePointer<Component> safePointer (this);
  32398. for (int i = childComponentList_.size(); --i >= 0;)
  32399. {
  32400. childComponentList_.getUnchecked (i)->sendLookAndFeelChange();
  32401. if (safePointer == 0)
  32402. return;
  32403. i = jmin (i, childComponentList_.size());
  32404. }
  32405. }
  32406. static const Identifier getColourPropertyId (const int colourId)
  32407. {
  32408. String s;
  32409. s.preallocateStorage (18);
  32410. s << "jcclr_" << String::toHexString (colourId);
  32411. return s;
  32412. }
  32413. const Colour Component::findColour (const int colourId, const bool inheritFromParent) const
  32414. {
  32415. var* v = properties.getItem (getColourPropertyId (colourId));
  32416. if (v != 0)
  32417. return Colour ((int) *v);
  32418. if (inheritFromParent && parentComponent_ != 0)
  32419. return parentComponent_->findColour (colourId, true);
  32420. return getLookAndFeel().findColour (colourId);
  32421. }
  32422. bool Component::isColourSpecified (const int colourId) const
  32423. {
  32424. return properties.contains (getColourPropertyId (colourId));
  32425. }
  32426. void Component::removeColour (const int colourId)
  32427. {
  32428. if (properties.remove (getColourPropertyId (colourId)))
  32429. colourChanged();
  32430. }
  32431. void Component::setColour (const int colourId, const Colour& colour)
  32432. {
  32433. if (properties.set (getColourPropertyId (colourId), (int) colour.getARGB()))
  32434. colourChanged();
  32435. }
  32436. void Component::copyAllExplicitColoursTo (Component& target) const
  32437. {
  32438. bool changed = false;
  32439. for (int i = properties.size(); --i >= 0;)
  32440. {
  32441. const Identifier name (properties.getName(i));
  32442. if (name.toString().startsWith ("jcclr_"))
  32443. if (target.properties.set (name, properties [name]))
  32444. changed = true;
  32445. }
  32446. if (changed)
  32447. target.colourChanged();
  32448. }
  32449. void Component::colourChanged()
  32450. {
  32451. }
  32452. const Rectangle<int> Component::getLocalBounds() const throw()
  32453. {
  32454. return Rectangle<int> (0, 0, getWidth(), getHeight());
  32455. }
  32456. const Rectangle<int> Component::getUnclippedArea() const
  32457. {
  32458. int x = 0, y = 0, w = getWidth(), h = getHeight();
  32459. Component* p = parentComponent_;
  32460. int px = getX();
  32461. int py = getY();
  32462. while (p != 0)
  32463. {
  32464. if (! Rectangle<int>::intersectRectangles (x, y, w, h, -px, -py, p->getWidth(), p->getHeight()))
  32465. return Rectangle<int>();
  32466. px += p->getX();
  32467. py += p->getY();
  32468. p = p->parentComponent_;
  32469. }
  32470. return Rectangle<int> (x, y, w, h);
  32471. }
  32472. void Component::clipObscuredRegions (Graphics& g, const Rectangle<int>& clipRect,
  32473. const int deltaX, const int deltaY) const
  32474. {
  32475. for (int i = childComponentList_.size(); --i >= 0;)
  32476. {
  32477. const Component* const c = childComponentList_.getUnchecked(i);
  32478. if (c->isVisible())
  32479. {
  32480. const Rectangle<int> newClip (clipRect.getIntersection (c->bounds_));
  32481. if (! newClip.isEmpty())
  32482. {
  32483. if (c->isOpaque())
  32484. {
  32485. g.excludeClipRegion (newClip.translated (deltaX, deltaY));
  32486. }
  32487. else
  32488. {
  32489. c->clipObscuredRegions (g, newClip.translated (-c->getX(), -c->getY()),
  32490. c->getX() + deltaX,
  32491. c->getY() + deltaY);
  32492. }
  32493. }
  32494. }
  32495. }
  32496. }
  32497. void Component::getVisibleArea (RectangleList& result, const bool includeSiblings) const
  32498. {
  32499. result.clear();
  32500. const Rectangle<int> unclipped (getUnclippedArea());
  32501. if (! unclipped.isEmpty())
  32502. {
  32503. result.add (unclipped);
  32504. if (includeSiblings)
  32505. {
  32506. const Component* const c = getTopLevelComponent();
  32507. c->subtractObscuredRegions (result, c->relativePositionToOtherComponent (this, Point<int>()),
  32508. c->getLocalBounds(), this);
  32509. }
  32510. subtractObscuredRegions (result, Point<int>(), unclipped, 0);
  32511. result.consolidate();
  32512. }
  32513. }
  32514. void Component::subtractObscuredRegions (RectangleList& result,
  32515. const Point<int>& delta,
  32516. const Rectangle<int>& clipRect,
  32517. const Component* const compToAvoid) const
  32518. {
  32519. for (int i = childComponentList_.size(); --i >= 0;)
  32520. {
  32521. const Component* const c = childComponentList_.getUnchecked(i);
  32522. if (c != compToAvoid && c->isVisible())
  32523. {
  32524. if (c->isOpaque())
  32525. {
  32526. Rectangle<int> childBounds (c->bounds_.getIntersection (clipRect));
  32527. childBounds.translate (delta.getX(), delta.getY());
  32528. result.subtract (childBounds);
  32529. }
  32530. else
  32531. {
  32532. Rectangle<int> newClip (clipRect.getIntersection (c->bounds_));
  32533. newClip.translate (-c->getX(), -c->getY());
  32534. c->subtractObscuredRegions (result, c->getPosition() + delta,
  32535. newClip, compToAvoid);
  32536. }
  32537. }
  32538. }
  32539. }
  32540. void Component::mouseEnter (const MouseEvent&)
  32541. {
  32542. // base class does nothing
  32543. }
  32544. void Component::mouseExit (const MouseEvent&)
  32545. {
  32546. // base class does nothing
  32547. }
  32548. void Component::mouseDown (const MouseEvent&)
  32549. {
  32550. // base class does nothing
  32551. }
  32552. void Component::mouseUp (const MouseEvent&)
  32553. {
  32554. // base class does nothing
  32555. }
  32556. void Component::mouseDrag (const MouseEvent&)
  32557. {
  32558. // base class does nothing
  32559. }
  32560. void Component::mouseMove (const MouseEvent&)
  32561. {
  32562. // base class does nothing
  32563. }
  32564. void Component::mouseDoubleClick (const MouseEvent&)
  32565. {
  32566. // base class does nothing
  32567. }
  32568. void Component::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  32569. {
  32570. // the base class just passes this event up to its parent..
  32571. if (parentComponent_ != 0)
  32572. parentComponent_->mouseWheelMove (e.getEventRelativeTo (parentComponent_),
  32573. wheelIncrementX, wheelIncrementY);
  32574. }
  32575. void Component::resized()
  32576. {
  32577. // base class does nothing
  32578. }
  32579. void Component::moved()
  32580. {
  32581. // base class does nothing
  32582. }
  32583. void Component::childBoundsChanged (Component*)
  32584. {
  32585. // base class does nothing
  32586. }
  32587. void Component::parentSizeChanged()
  32588. {
  32589. // base class does nothing
  32590. }
  32591. void Component::addComponentListener (ComponentListener* const newListener)
  32592. {
  32593. jassert (isValidComponent());
  32594. componentListeners.add (newListener);
  32595. }
  32596. void Component::removeComponentListener (ComponentListener* const listenerToRemove)
  32597. {
  32598. jassert (isValidComponent());
  32599. componentListeners.remove (listenerToRemove);
  32600. }
  32601. void Component::inputAttemptWhenModal()
  32602. {
  32603. bringModalComponentToFront();
  32604. getLookAndFeel().playAlertSound();
  32605. }
  32606. bool Component::canModalEventBeSentToComponent (const Component*)
  32607. {
  32608. return false;
  32609. }
  32610. void Component::internalModalInputAttempt()
  32611. {
  32612. Component* const current = getCurrentlyModalComponent();
  32613. if (current != 0)
  32614. current->inputAttemptWhenModal();
  32615. }
  32616. void Component::paint (Graphics&)
  32617. {
  32618. // all painting is done in the subclasses
  32619. jassert (! isOpaque()); // if your component's opaque, you've gotta paint it!
  32620. }
  32621. void Component::paintOverChildren (Graphics&)
  32622. {
  32623. // all painting is done in the subclasses
  32624. }
  32625. void Component::handleMessage (const Message& message)
  32626. {
  32627. if (message.intParameter1 == exitModalStateMessage)
  32628. {
  32629. exitModalState (message.intParameter2);
  32630. }
  32631. else if (message.intParameter1 == customCommandMessage)
  32632. {
  32633. handleCommandMessage (message.intParameter2);
  32634. }
  32635. }
  32636. void Component::postCommandMessage (const int commandId)
  32637. {
  32638. postMessage (new Message (customCommandMessage, commandId, 0, 0));
  32639. }
  32640. void Component::handleCommandMessage (int)
  32641. {
  32642. // used by subclasses
  32643. }
  32644. void Component::addMouseListener (MouseListener* const newListener,
  32645. const bool wantsEventsForAllNestedChildComponents)
  32646. {
  32647. // if component methods are being called from threads other than the message
  32648. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32649. checkMessageManagerIsLocked
  32650. if (mouseListeners_ == 0)
  32651. mouseListeners_ = new Array<MouseListener*>();
  32652. if (! mouseListeners_->contains (newListener))
  32653. {
  32654. if (wantsEventsForAllNestedChildComponents)
  32655. {
  32656. mouseListeners_->insert (0, newListener);
  32657. ++numDeepMouseListeners;
  32658. }
  32659. else
  32660. {
  32661. mouseListeners_->add (newListener);
  32662. }
  32663. }
  32664. }
  32665. void Component::removeMouseListener (MouseListener* const listenerToRemove)
  32666. {
  32667. // if component methods are being called from threads other than the message
  32668. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32669. checkMessageManagerIsLocked
  32670. if (mouseListeners_ != 0)
  32671. {
  32672. const int index = mouseListeners_->indexOf (listenerToRemove);
  32673. if (index >= 0)
  32674. {
  32675. if (index < numDeepMouseListeners)
  32676. --numDeepMouseListeners;
  32677. mouseListeners_->remove (index);
  32678. }
  32679. }
  32680. }
  32681. void Component::internalMouseEnter (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  32682. {
  32683. if (isCurrentlyBlockedByAnotherModalComponent())
  32684. {
  32685. // if something else is modal, always just show a normal mouse cursor
  32686. source.showMouseCursor (MouseCursor::NormalCursor);
  32687. return;
  32688. }
  32689. if (! flags.mouseInsideFlag)
  32690. {
  32691. flags.mouseInsideFlag = true;
  32692. flags.mouseOverFlag = true;
  32693. flags.draggingFlag = false;
  32694. BailOutChecker checker (this);
  32695. if (flags.repaintOnMouseActivityFlag)
  32696. repaint();
  32697. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  32698. this, this, time, relativePos,
  32699. time, 0, false);
  32700. mouseEnter (me);
  32701. if (checker.shouldBailOut())
  32702. return;
  32703. Desktop::getInstance().resetTimer();
  32704. Desktop::getInstance().mouseListeners.callChecked (checker, &MouseListener::mouseEnter, me);
  32705. if (checker.shouldBailOut())
  32706. return;
  32707. if (mouseListeners_ != 0)
  32708. {
  32709. for (int i = mouseListeners_->size(); --i >= 0;)
  32710. {
  32711. mouseListeners_->getUnchecked(i)->mouseEnter (me);
  32712. if (checker.shouldBailOut())
  32713. return;
  32714. i = jmin (i, mouseListeners_->size());
  32715. }
  32716. }
  32717. Component* p = parentComponent_;
  32718. while (p != 0)
  32719. {
  32720. if (p->numDeepMouseListeners > 0)
  32721. {
  32722. BailOutChecker checker2 (this, p);
  32723. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32724. {
  32725. p->mouseListeners_->getUnchecked(i)->mouseEnter (me);
  32726. if (checker2.shouldBailOut())
  32727. return;
  32728. i = jmin (i, p->numDeepMouseListeners);
  32729. }
  32730. }
  32731. p = p->parentComponent_;
  32732. }
  32733. }
  32734. }
  32735. void Component::internalMouseExit (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  32736. {
  32737. BailOutChecker checker (this);
  32738. if (flags.draggingFlag)
  32739. {
  32740. internalMouseUp (source, relativePos, time, source.getCurrentModifiers().getRawFlags());
  32741. if (checker.shouldBailOut())
  32742. return;
  32743. }
  32744. if (flags.mouseInsideFlag || flags.mouseOverFlag)
  32745. {
  32746. flags.mouseInsideFlag = false;
  32747. flags.mouseOverFlag = false;
  32748. flags.draggingFlag = false;
  32749. if (flags.repaintOnMouseActivityFlag)
  32750. repaint();
  32751. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  32752. this, this, time, relativePos,
  32753. time, 0, false);
  32754. mouseExit (me);
  32755. if (checker.shouldBailOut())
  32756. return;
  32757. Desktop::getInstance().resetTimer();
  32758. Desktop::getInstance().mouseListeners.callChecked (checker, &MouseListener::mouseExit, me);
  32759. if (checker.shouldBailOut())
  32760. return;
  32761. if (mouseListeners_ != 0)
  32762. {
  32763. for (int i = mouseListeners_->size(); --i >= 0;)
  32764. {
  32765. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseExit (me);
  32766. if (checker.shouldBailOut())
  32767. return;
  32768. i = jmin (i, mouseListeners_->size());
  32769. }
  32770. }
  32771. Component* p = parentComponent_;
  32772. while (p != 0)
  32773. {
  32774. if (p->numDeepMouseListeners > 0)
  32775. {
  32776. BailOutChecker checker2 (this, p);
  32777. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32778. {
  32779. p->mouseListeners_->getUnchecked (i)->mouseExit (me);
  32780. if (checker2.shouldBailOut())
  32781. return;
  32782. i = jmin (i, p->numDeepMouseListeners);
  32783. }
  32784. }
  32785. p = p->parentComponent_;
  32786. }
  32787. }
  32788. }
  32789. class InternalDragRepeater : public Timer
  32790. {
  32791. public:
  32792. InternalDragRepeater()
  32793. {}
  32794. ~InternalDragRepeater()
  32795. {
  32796. clearSingletonInstance();
  32797. }
  32798. juce_DeclareSingleton_SingleThreaded_Minimal (InternalDragRepeater)
  32799. void timerCallback()
  32800. {
  32801. Desktop& desktop = Desktop::getInstance();
  32802. int numMiceDown = 0;
  32803. for (int i = desktop.getNumMouseSources(); --i >= 0;)
  32804. {
  32805. MouseInputSource* const source = desktop.getMouseSource(i);
  32806. if (source->isDragging())
  32807. {
  32808. source->triggerFakeMove();
  32809. ++numMiceDown;
  32810. }
  32811. }
  32812. if (numMiceDown == 0)
  32813. deleteInstance();
  32814. }
  32815. juce_UseDebuggingNewOperator
  32816. private:
  32817. InternalDragRepeater (const InternalDragRepeater&);
  32818. InternalDragRepeater& operator= (const InternalDragRepeater&);
  32819. };
  32820. juce_ImplementSingleton_SingleThreaded (InternalDragRepeater)
  32821. void Component::beginDragAutoRepeat (const int interval)
  32822. {
  32823. if (interval > 0)
  32824. {
  32825. if (InternalDragRepeater::getInstance()->getTimerInterval() != interval)
  32826. InternalDragRepeater::getInstance()->startTimer (interval);
  32827. }
  32828. else
  32829. {
  32830. InternalDragRepeater::deleteInstance();
  32831. }
  32832. }
  32833. void Component::internalMouseDown (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  32834. {
  32835. Desktop& desktop = Desktop::getInstance();
  32836. BailOutChecker checker (this);
  32837. if (isCurrentlyBlockedByAnotherModalComponent())
  32838. {
  32839. internalModalInputAttempt();
  32840. if (checker.shouldBailOut())
  32841. return;
  32842. // If processing the input attempt has exited the modal loop, we'll allow the event
  32843. // to be delivered..
  32844. if (isCurrentlyBlockedByAnotherModalComponent())
  32845. {
  32846. // allow blocked mouse-events to go to global listeners..
  32847. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  32848. this, this, time, relativePos, time,
  32849. source.getNumberOfMultipleClicks(), false);
  32850. desktop.resetTimer();
  32851. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  32852. return;
  32853. }
  32854. }
  32855. {
  32856. Component* c = this;
  32857. while (c != 0)
  32858. {
  32859. if (c->isBroughtToFrontOnMouseClick())
  32860. {
  32861. c->toFront (true);
  32862. if (checker.shouldBailOut())
  32863. return;
  32864. }
  32865. c = c->parentComponent_;
  32866. }
  32867. }
  32868. if (! flags.dontFocusOnMouseClickFlag)
  32869. {
  32870. grabFocusInternal (focusChangedByMouseClick);
  32871. if (checker.shouldBailOut())
  32872. return;
  32873. }
  32874. flags.draggingFlag = true;
  32875. flags.mouseOverFlag = true;
  32876. if (flags.repaintOnMouseActivityFlag)
  32877. repaint();
  32878. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  32879. this, this, time, relativePos, time,
  32880. source.getNumberOfMultipleClicks(), false);
  32881. mouseDown (me);
  32882. if (checker.shouldBailOut())
  32883. return;
  32884. desktop.resetTimer();
  32885. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  32886. if (checker.shouldBailOut())
  32887. return;
  32888. if (mouseListeners_ != 0)
  32889. {
  32890. for (int i = mouseListeners_->size(); --i >= 0;)
  32891. {
  32892. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDown (me);
  32893. if (checker.shouldBailOut())
  32894. return;
  32895. i = jmin (i, mouseListeners_->size());
  32896. }
  32897. }
  32898. Component* p = parentComponent_;
  32899. while (p != 0)
  32900. {
  32901. if (p->numDeepMouseListeners > 0)
  32902. {
  32903. BailOutChecker checker2 (this, p);
  32904. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32905. {
  32906. p->mouseListeners_->getUnchecked (i)->mouseDown (me);
  32907. if (checker2.shouldBailOut())
  32908. return;
  32909. i = jmin (i, p->numDeepMouseListeners);
  32910. }
  32911. }
  32912. p = p->parentComponent_;
  32913. }
  32914. }
  32915. void Component::internalMouseUp (MouseInputSource& source, const Point<int>& relativePos, const Time& time, const ModifierKeys& oldModifiers)
  32916. {
  32917. if (flags.draggingFlag)
  32918. {
  32919. Desktop& desktop = Desktop::getInstance();
  32920. flags.draggingFlag = false;
  32921. BailOutChecker checker (this);
  32922. if (flags.repaintOnMouseActivityFlag)
  32923. repaint();
  32924. const MouseEvent me (source, relativePos,
  32925. oldModifiers, this, this, time,
  32926. globalPositionToRelative (source.getLastMouseDownPosition()),
  32927. source.getLastMouseDownTime(),
  32928. source.getNumberOfMultipleClicks(),
  32929. source.hasMouseMovedSignificantlySincePressed());
  32930. mouseUp (me);
  32931. if (checker.shouldBailOut())
  32932. return;
  32933. desktop.resetTimer();
  32934. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseUp, me);
  32935. if (checker.shouldBailOut())
  32936. return;
  32937. if (mouseListeners_ != 0)
  32938. {
  32939. for (int i = mouseListeners_->size(); --i >= 0;)
  32940. {
  32941. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseUp (me);
  32942. if (checker.shouldBailOut())
  32943. return;
  32944. i = jmin (i, mouseListeners_->size());
  32945. }
  32946. }
  32947. {
  32948. Component* p = parentComponent_;
  32949. while (p != 0)
  32950. {
  32951. if (p->numDeepMouseListeners > 0)
  32952. {
  32953. BailOutChecker checker2 (this, p);
  32954. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32955. {
  32956. p->mouseListeners_->getUnchecked (i)->mouseUp (me);
  32957. if (checker2.shouldBailOut())
  32958. return;
  32959. i = jmin (i, p->numDeepMouseListeners);
  32960. }
  32961. }
  32962. p = p->parentComponent_;
  32963. }
  32964. }
  32965. // check for double-click
  32966. if (me.getNumberOfClicks() >= 2)
  32967. {
  32968. const int numListeners = (mouseListeners_ != 0) ? mouseListeners_->size() : 0;
  32969. mouseDoubleClick (me);
  32970. if (checker.shouldBailOut())
  32971. return;
  32972. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDoubleClick, me);
  32973. if (checker.shouldBailOut())
  32974. return;
  32975. for (int i = numListeners; --i >= 0;)
  32976. {
  32977. if (checker.shouldBailOut())
  32978. return;
  32979. MouseListener* const ml = (MouseListener*)((*mouseListeners_)[i]);
  32980. if (ml != 0)
  32981. ml->mouseDoubleClick (me);
  32982. }
  32983. if (checker.shouldBailOut())
  32984. return;
  32985. Component* p = parentComponent_;
  32986. while (p != 0)
  32987. {
  32988. if (p->numDeepMouseListeners > 0)
  32989. {
  32990. BailOutChecker checker2 (this, p);
  32991. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32992. {
  32993. p->mouseListeners_->getUnchecked (i)->mouseDoubleClick (me);
  32994. if (checker2.shouldBailOut())
  32995. return;
  32996. i = jmin (i, p->numDeepMouseListeners);
  32997. }
  32998. }
  32999. p = p->parentComponent_;
  33000. }
  33001. }
  33002. }
  33003. }
  33004. void Component::internalMouseDrag (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33005. {
  33006. if (flags.draggingFlag)
  33007. {
  33008. Desktop& desktop = Desktop::getInstance();
  33009. flags.mouseOverFlag = reallyContains (relativePos.getX(), relativePos.getY(), false);
  33010. BailOutChecker checker (this);
  33011. const MouseEvent me (source, relativePos,
  33012. source.getCurrentModifiers(), this, this, time,
  33013. globalPositionToRelative (source.getLastMouseDownPosition()),
  33014. source.getLastMouseDownTime(),
  33015. source.getNumberOfMultipleClicks(),
  33016. source.hasMouseMovedSignificantlySincePressed());
  33017. mouseDrag (me);
  33018. if (checker.shouldBailOut())
  33019. return;
  33020. desktop.resetTimer();
  33021. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  33022. if (checker.shouldBailOut())
  33023. return;
  33024. if (mouseListeners_ != 0)
  33025. {
  33026. for (int i = mouseListeners_->size(); --i >= 0;)
  33027. {
  33028. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDrag (me);
  33029. if (checker.shouldBailOut())
  33030. return;
  33031. i = jmin (i, mouseListeners_->size());
  33032. }
  33033. }
  33034. Component* p = parentComponent_;
  33035. while (p != 0)
  33036. {
  33037. if (p->numDeepMouseListeners > 0)
  33038. {
  33039. BailOutChecker checker2 (this, p);
  33040. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33041. {
  33042. p->mouseListeners_->getUnchecked (i)->mouseDrag (me);
  33043. if (checker2.shouldBailOut())
  33044. return;
  33045. i = jmin (i, p->numDeepMouseListeners);
  33046. }
  33047. }
  33048. p = p->parentComponent_;
  33049. }
  33050. }
  33051. }
  33052. void Component::internalMouseMove (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33053. {
  33054. Desktop& desktop = Desktop::getInstance();
  33055. BailOutChecker checker (this);
  33056. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33057. this, this, time, relativePos,
  33058. time, 0, false);
  33059. if (isCurrentlyBlockedByAnotherModalComponent())
  33060. {
  33061. // allow blocked mouse-events to go to global listeners..
  33062. desktop.sendMouseMove();
  33063. }
  33064. else
  33065. {
  33066. flags.mouseOverFlag = true;
  33067. mouseMove (me);
  33068. if (checker.shouldBailOut())
  33069. return;
  33070. desktop.resetTimer();
  33071. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  33072. if (checker.shouldBailOut())
  33073. return;
  33074. if (mouseListeners_ != 0)
  33075. {
  33076. for (int i = mouseListeners_->size(); --i >= 0;)
  33077. {
  33078. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseMove (me);
  33079. if (checker.shouldBailOut())
  33080. return;
  33081. i = jmin (i, mouseListeners_->size());
  33082. }
  33083. }
  33084. Component* p = parentComponent_;
  33085. while (p != 0)
  33086. {
  33087. if (p->numDeepMouseListeners > 0)
  33088. {
  33089. BailOutChecker checker2 (this, p);
  33090. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33091. {
  33092. p->mouseListeners_->getUnchecked (i)->mouseMove (me);
  33093. if (checker2.shouldBailOut())
  33094. return;
  33095. i = jmin (i, p->numDeepMouseListeners);
  33096. }
  33097. }
  33098. p = p->parentComponent_;
  33099. }
  33100. }
  33101. }
  33102. void Component::internalMouseWheel (MouseInputSource& source, const Point<int>& relativePos,
  33103. const Time& time, const float amountX, const float amountY)
  33104. {
  33105. Desktop& desktop = Desktop::getInstance();
  33106. BailOutChecker checker (this);
  33107. const float wheelIncrementX = amountX * (1.0f / 256.0f);
  33108. const float wheelIncrementY = amountY * (1.0f / 256.0f);
  33109. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33110. this, this, time, relativePos, time, 0, false);
  33111. if (isCurrentlyBlockedByAnotherModalComponent())
  33112. {
  33113. // allow blocked mouse-events to go to global listeners..
  33114. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33115. }
  33116. else
  33117. {
  33118. mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33119. if (checker.shouldBailOut())
  33120. return;
  33121. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33122. if (checker.shouldBailOut())
  33123. return;
  33124. if (mouseListeners_ != 0)
  33125. {
  33126. for (int i = mouseListeners_->size(); --i >= 0;)
  33127. {
  33128. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33129. if (checker.shouldBailOut())
  33130. return;
  33131. i = jmin (i, mouseListeners_->size());
  33132. }
  33133. }
  33134. Component* p = parentComponent_;
  33135. while (p != 0)
  33136. {
  33137. if (p->numDeepMouseListeners > 0)
  33138. {
  33139. BailOutChecker checker2 (this, p);
  33140. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33141. {
  33142. p->mouseListeners_->getUnchecked (i)->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33143. if (checker2.shouldBailOut())
  33144. return;
  33145. i = jmin (i, p->numDeepMouseListeners);
  33146. }
  33147. }
  33148. p = p->parentComponent_;
  33149. }
  33150. }
  33151. }
  33152. void Component::sendFakeMouseMove() const
  33153. {
  33154. Desktop::getInstance().getMainMouseSource().triggerFakeMove();
  33155. }
  33156. void Component::broughtToFront()
  33157. {
  33158. }
  33159. void Component::internalBroughtToFront()
  33160. {
  33161. if (! isValidComponent())
  33162. return;
  33163. if (flags.hasHeavyweightPeerFlag)
  33164. Desktop::getInstance().componentBroughtToFront (this);
  33165. BailOutChecker checker (this);
  33166. broughtToFront();
  33167. if (checker.shouldBailOut())
  33168. return;
  33169. componentListeners.callChecked (checker, &ComponentListener::componentBroughtToFront, *this);
  33170. if (checker.shouldBailOut())
  33171. return;
  33172. // When brought to the front and there's a modal component blocking this one,
  33173. // we need to bring the modal one to the front instead..
  33174. Component* const cm = getCurrentlyModalComponent();
  33175. if (cm != 0 && cm->getTopLevelComponent() != getTopLevelComponent())
  33176. bringModalComponentToFront();
  33177. }
  33178. void Component::focusGained (FocusChangeType)
  33179. {
  33180. // base class does nothing
  33181. }
  33182. void Component::internalFocusGain (const FocusChangeType cause)
  33183. {
  33184. SafePointer<Component> safePointer (this);
  33185. focusGained (cause);
  33186. if (safePointer != 0)
  33187. internalChildFocusChange (cause);
  33188. }
  33189. void Component::focusLost (FocusChangeType)
  33190. {
  33191. // base class does nothing
  33192. }
  33193. void Component::internalFocusLoss (const FocusChangeType cause)
  33194. {
  33195. SafePointer<Component> safePointer (this);
  33196. focusLost (focusChangedDirectly);
  33197. if (safePointer != 0)
  33198. internalChildFocusChange (cause);
  33199. }
  33200. void Component::focusOfChildComponentChanged (FocusChangeType /*cause*/)
  33201. {
  33202. // base class does nothing
  33203. }
  33204. void Component::internalChildFocusChange (FocusChangeType cause)
  33205. {
  33206. const bool childIsNowFocused = hasKeyboardFocus (true);
  33207. if (flags.childCompFocusedFlag != childIsNowFocused)
  33208. {
  33209. flags.childCompFocusedFlag = childIsNowFocused;
  33210. SafePointer<Component> safePointer (this);
  33211. focusOfChildComponentChanged (cause);
  33212. if (safePointer == 0)
  33213. return;
  33214. }
  33215. if (parentComponent_ != 0)
  33216. parentComponent_->internalChildFocusChange (cause);
  33217. }
  33218. bool Component::isEnabled() const throw()
  33219. {
  33220. return (! flags.isDisabledFlag)
  33221. && (parentComponent_ == 0 || parentComponent_->isEnabled());
  33222. }
  33223. void Component::setEnabled (const bool shouldBeEnabled)
  33224. {
  33225. if (flags.isDisabledFlag == shouldBeEnabled)
  33226. {
  33227. flags.isDisabledFlag = ! shouldBeEnabled;
  33228. // if any parent components are disabled, setting our flag won't make a difference,
  33229. // so no need to send a change message
  33230. if (parentComponent_ == 0 || parentComponent_->isEnabled())
  33231. sendEnablementChangeMessage();
  33232. }
  33233. }
  33234. void Component::sendEnablementChangeMessage()
  33235. {
  33236. SafePointer<Component> safePointer (this);
  33237. enablementChanged();
  33238. if (safePointer == 0)
  33239. return;
  33240. for (int i = getNumChildComponents(); --i >= 0;)
  33241. {
  33242. Component* const c = getChildComponent (i);
  33243. if (c != 0)
  33244. {
  33245. c->sendEnablementChangeMessage();
  33246. if (safePointer == 0)
  33247. return;
  33248. }
  33249. }
  33250. }
  33251. void Component::enablementChanged()
  33252. {
  33253. }
  33254. void Component::setWantsKeyboardFocus (const bool wantsFocus) throw()
  33255. {
  33256. flags.wantsFocusFlag = wantsFocus;
  33257. }
  33258. void Component::setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus)
  33259. {
  33260. flags.dontFocusOnMouseClickFlag = ! shouldGrabFocus;
  33261. }
  33262. bool Component::getMouseClickGrabsKeyboardFocus() const throw()
  33263. {
  33264. return ! flags.dontFocusOnMouseClickFlag;
  33265. }
  33266. bool Component::getWantsKeyboardFocus() const throw()
  33267. {
  33268. return flags.wantsFocusFlag && ! flags.isDisabledFlag;
  33269. }
  33270. void Component::setFocusContainer (const bool shouldBeFocusContainer) throw()
  33271. {
  33272. flags.isFocusContainerFlag = shouldBeFocusContainer;
  33273. }
  33274. bool Component::isFocusContainer() const throw()
  33275. {
  33276. return flags.isFocusContainerFlag;
  33277. }
  33278. static const Identifier juce_explicitFocusOrderId ("_jexfo");
  33279. int Component::getExplicitFocusOrder() const
  33280. {
  33281. return properties [juce_explicitFocusOrderId];
  33282. }
  33283. void Component::setExplicitFocusOrder (const int newFocusOrderIndex)
  33284. {
  33285. properties.set (juce_explicitFocusOrderId, newFocusOrderIndex);
  33286. }
  33287. KeyboardFocusTraverser* Component::createFocusTraverser()
  33288. {
  33289. if (flags.isFocusContainerFlag || parentComponent_ == 0)
  33290. return new KeyboardFocusTraverser();
  33291. return parentComponent_->createFocusTraverser();
  33292. }
  33293. void Component::takeKeyboardFocus (const FocusChangeType cause)
  33294. {
  33295. // give the focus to this component
  33296. if (currentlyFocusedComponent != this)
  33297. {
  33298. JUCE_TRY
  33299. {
  33300. // get the focus onto our desktop window
  33301. ComponentPeer* const peer = getPeer();
  33302. if (peer != 0)
  33303. {
  33304. SafePointer<Component> safePointer (this);
  33305. peer->grabFocus();
  33306. if (peer->isFocused() && currentlyFocusedComponent != this)
  33307. {
  33308. Component* const componentLosingFocus = currentlyFocusedComponent;
  33309. currentlyFocusedComponent = this;
  33310. Desktop::getInstance().triggerFocusCallback();
  33311. // call this after setting currentlyFocusedComponent so that the one that's
  33312. // losing it has a chance to see where focus is going
  33313. if (componentLosingFocus->isValidComponent())
  33314. componentLosingFocus->internalFocusLoss (cause);
  33315. if (currentlyFocusedComponent == this)
  33316. {
  33317. focusGained (cause);
  33318. if (safePointer != 0)
  33319. internalChildFocusChange (cause);
  33320. }
  33321. }
  33322. }
  33323. }
  33324. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  33325. catch (const std::exception& e)
  33326. {
  33327. currentlyFocusedComponent = 0;
  33328. Desktop::getInstance().triggerFocusCallback();
  33329. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  33330. }
  33331. catch (...)
  33332. {
  33333. currentlyFocusedComponent = 0;
  33334. Desktop::getInstance().triggerFocusCallback();
  33335. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  33336. }
  33337. #endif
  33338. }
  33339. }
  33340. void Component::grabFocusInternal (const FocusChangeType cause, const bool canTryParent)
  33341. {
  33342. if (isShowing())
  33343. {
  33344. if (flags.wantsFocusFlag && (isEnabled() || parentComponent_ == 0))
  33345. {
  33346. takeKeyboardFocus (cause);
  33347. }
  33348. else
  33349. {
  33350. if (isParentOf (currentlyFocusedComponent)
  33351. && currentlyFocusedComponent->isShowing())
  33352. {
  33353. // do nothing if the focused component is actually a child of ours..
  33354. }
  33355. else
  33356. {
  33357. // find the default child component..
  33358. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  33359. if (traverser != 0)
  33360. {
  33361. Component* const defaultComp = traverser->getDefaultComponent (this);
  33362. traverser = 0;
  33363. if (defaultComp != 0)
  33364. {
  33365. defaultComp->grabFocusInternal (cause, false);
  33366. return;
  33367. }
  33368. }
  33369. if (canTryParent && parentComponent_ != 0)
  33370. {
  33371. // if no children want it and we're allowed to try our parent comp,
  33372. // then pass up to parent, which will try our siblings.
  33373. parentComponent_->grabFocusInternal (cause, true);
  33374. }
  33375. }
  33376. }
  33377. }
  33378. }
  33379. void Component::grabKeyboardFocus()
  33380. {
  33381. // if component methods are being called from threads other than the message
  33382. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33383. checkMessageManagerIsLocked
  33384. grabFocusInternal (focusChangedDirectly);
  33385. }
  33386. void Component::moveKeyboardFocusToSibling (const bool moveToNext)
  33387. {
  33388. // if component methods are being called from threads other than the message
  33389. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33390. checkMessageManagerIsLocked
  33391. if (parentComponent_ != 0)
  33392. {
  33393. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  33394. if (traverser != 0)
  33395. {
  33396. Component* const nextComp = moveToNext ? traverser->getNextComponent (this)
  33397. : traverser->getPreviousComponent (this);
  33398. traverser = 0;
  33399. if (nextComp != 0)
  33400. {
  33401. if (nextComp->isCurrentlyBlockedByAnotherModalComponent())
  33402. {
  33403. SafePointer<Component> nextCompPointer (nextComp);
  33404. internalModalInputAttempt();
  33405. if (nextCompPointer == 0 || nextComp->isCurrentlyBlockedByAnotherModalComponent())
  33406. return;
  33407. }
  33408. nextComp->grabFocusInternal (focusChangedByTabKey);
  33409. return;
  33410. }
  33411. }
  33412. parentComponent_->moveKeyboardFocusToSibling (moveToNext);
  33413. }
  33414. }
  33415. bool Component::hasKeyboardFocus (const bool trueIfChildIsFocused) const
  33416. {
  33417. return (currentlyFocusedComponent == this)
  33418. || (trueIfChildIsFocused && isParentOf (currentlyFocusedComponent));
  33419. }
  33420. Component* JUCE_CALLTYPE Component::getCurrentlyFocusedComponent() throw()
  33421. {
  33422. return currentlyFocusedComponent;
  33423. }
  33424. void Component::giveAwayFocus()
  33425. {
  33426. // use a copy so we can clear the value before the call
  33427. Component* const componentLosingFocus = currentlyFocusedComponent;
  33428. currentlyFocusedComponent = 0;
  33429. Desktop::getInstance().triggerFocusCallback();
  33430. if (componentLosingFocus->isValidComponent())
  33431. componentLosingFocus->internalFocusLoss (focusChangedDirectly);
  33432. }
  33433. bool Component::isMouseOver() const throw()
  33434. {
  33435. return flags.mouseOverFlag;
  33436. }
  33437. bool Component::isMouseButtonDown() const throw()
  33438. {
  33439. return flags.draggingFlag;
  33440. }
  33441. bool Component::isMouseOverOrDragging() const throw()
  33442. {
  33443. return flags.mouseOverFlag || flags.draggingFlag;
  33444. }
  33445. bool JUCE_CALLTYPE Component::isMouseButtonDownAnywhere() throw()
  33446. {
  33447. return ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown();
  33448. }
  33449. const Point<int> Component::getMouseXYRelative() const
  33450. {
  33451. return globalPositionToRelative (Desktop::getMousePosition());
  33452. }
  33453. const Rectangle<int> Component::getParentMonitorArea() const
  33454. {
  33455. return Desktop::getInstance()
  33456. .getMonitorAreaContaining (relativePositionToGlobal (Point<int> (getWidth() / 2,
  33457. getHeight() / 2)));
  33458. }
  33459. void Component::addKeyListener (KeyListener* const newListener)
  33460. {
  33461. if (keyListeners_ == 0)
  33462. keyListeners_ = new Array <KeyListener*>();
  33463. keyListeners_->addIfNotAlreadyThere (newListener);
  33464. }
  33465. void Component::removeKeyListener (KeyListener* const listenerToRemove)
  33466. {
  33467. if (keyListeners_ != 0)
  33468. keyListeners_->removeValue (listenerToRemove);
  33469. }
  33470. bool Component::keyPressed (const KeyPress&)
  33471. {
  33472. return false;
  33473. }
  33474. bool Component::keyStateChanged (const bool /*isKeyDown*/)
  33475. {
  33476. return false;
  33477. }
  33478. void Component::modifierKeysChanged (const ModifierKeys& modifiers)
  33479. {
  33480. if (parentComponent_ != 0)
  33481. parentComponent_->modifierKeysChanged (modifiers);
  33482. }
  33483. void Component::internalModifierKeysChanged()
  33484. {
  33485. sendFakeMouseMove();
  33486. modifierKeysChanged (ModifierKeys::getCurrentModifiers());
  33487. }
  33488. ComponentPeer* Component::getPeer() const
  33489. {
  33490. if (flags.hasHeavyweightPeerFlag)
  33491. return ComponentPeer::getPeerFor (this);
  33492. else if (parentComponent_ != 0)
  33493. return parentComponent_->getPeer();
  33494. else
  33495. return 0;
  33496. }
  33497. Component::BailOutChecker::BailOutChecker (Component* const component1, Component* const component2_)
  33498. : safePointer1 (component1), safePointer2 (component2_), component2 (component2_)
  33499. {
  33500. jassert (component1 != 0);
  33501. }
  33502. bool Component::BailOutChecker::shouldBailOut() const throw()
  33503. {
  33504. return safePointer1 == 0 || safePointer2.getComponent() != component2;
  33505. }
  33506. END_JUCE_NAMESPACE
  33507. /*** End of inlined file: juce_Component.cpp ***/
  33508. /*** Start of inlined file: juce_ComponentListener.cpp ***/
  33509. BEGIN_JUCE_NAMESPACE
  33510. void ComponentListener::componentMovedOrResized (Component&, bool, bool) {}
  33511. void ComponentListener::componentBroughtToFront (Component&) {}
  33512. void ComponentListener::componentVisibilityChanged (Component&) {}
  33513. void ComponentListener::componentChildrenChanged (Component&) {}
  33514. void ComponentListener::componentParentHierarchyChanged (Component&) {}
  33515. void ComponentListener::componentNameChanged (Component&) {}
  33516. void ComponentListener::componentBeingDeleted (Component&) {}
  33517. END_JUCE_NAMESPACE
  33518. /*** End of inlined file: juce_ComponentListener.cpp ***/
  33519. /*** Start of inlined file: juce_Desktop.cpp ***/
  33520. BEGIN_JUCE_NAMESPACE
  33521. Desktop::Desktop()
  33522. : mouseClickCounter (0),
  33523. kioskModeComponent (0)
  33524. {
  33525. createMouseInputSources();
  33526. refreshMonitorSizes();
  33527. }
  33528. Desktop::~Desktop()
  33529. {
  33530. jassert (instance == this);
  33531. instance = 0;
  33532. // doh! If you don't delete all your windows before exiting, you're going to
  33533. // be leaking memory!
  33534. jassert (desktopComponents.size() == 0);
  33535. }
  33536. Desktop& JUCE_CALLTYPE Desktop::getInstance()
  33537. {
  33538. if (instance == 0)
  33539. instance = new Desktop();
  33540. return *instance;
  33541. }
  33542. Desktop* Desktop::instance = 0;
  33543. extern void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords,
  33544. const bool clipToWorkArea);
  33545. void Desktop::refreshMonitorSizes()
  33546. {
  33547. const Array <Rectangle<int> > oldClipped (monitorCoordsClipped);
  33548. const Array <Rectangle<int> > oldUnclipped (monitorCoordsUnclipped);
  33549. monitorCoordsClipped.clear();
  33550. monitorCoordsUnclipped.clear();
  33551. juce_updateMultiMonitorInfo (monitorCoordsClipped, true);
  33552. juce_updateMultiMonitorInfo (monitorCoordsUnclipped, false);
  33553. jassert (monitorCoordsClipped.size() == monitorCoordsUnclipped.size());
  33554. if (oldClipped != monitorCoordsClipped
  33555. || oldUnclipped != monitorCoordsUnclipped)
  33556. {
  33557. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  33558. {
  33559. ComponentPeer* const p = ComponentPeer::getPeer (i);
  33560. if (p != 0)
  33561. p->handleScreenSizeChange();
  33562. }
  33563. }
  33564. }
  33565. int Desktop::getNumDisplayMonitors() const throw()
  33566. {
  33567. return monitorCoordsClipped.size();
  33568. }
  33569. const Rectangle<int> Desktop::getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw()
  33570. {
  33571. return clippedToWorkArea ? monitorCoordsClipped [index]
  33572. : monitorCoordsUnclipped [index];
  33573. }
  33574. const RectangleList Desktop::getAllMonitorDisplayAreas (const bool clippedToWorkArea) const throw()
  33575. {
  33576. RectangleList rl;
  33577. for (int i = 0; i < getNumDisplayMonitors(); ++i)
  33578. rl.addWithoutMerging (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  33579. return rl;
  33580. }
  33581. const Rectangle<int> Desktop::getMainMonitorArea (const bool clippedToWorkArea) const throw()
  33582. {
  33583. return getDisplayMonitorCoordinates (0, clippedToWorkArea);
  33584. }
  33585. const Rectangle<int> Desktop::getMonitorAreaContaining (const Point<int>& position, const bool clippedToWorkArea) const
  33586. {
  33587. Rectangle<int> best (getMainMonitorArea (clippedToWorkArea));
  33588. double bestDistance = 1.0e10;
  33589. for (int i = getNumDisplayMonitors(); --i >= 0;)
  33590. {
  33591. const Rectangle<int> rect (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  33592. if (rect.contains (position))
  33593. return rect;
  33594. const double distance = rect.getCentre().getDistanceFrom (position);
  33595. if (distance < bestDistance)
  33596. {
  33597. bestDistance = distance;
  33598. best = rect;
  33599. }
  33600. }
  33601. return best;
  33602. }
  33603. int Desktop::getNumComponents() const throw()
  33604. {
  33605. return desktopComponents.size();
  33606. }
  33607. Component* Desktop::getComponent (const int index) const throw()
  33608. {
  33609. return desktopComponents [index];
  33610. }
  33611. Component* Desktop::findComponentAt (const Point<int>& screenPosition) const
  33612. {
  33613. for (int i = desktopComponents.size(); --i >= 0;)
  33614. {
  33615. Component* const c = desktopComponents.getUnchecked(i);
  33616. const Point<int> relative (c->globalPositionToRelative (screenPosition));
  33617. if (c->contains (relative.getX(), relative.getY()))
  33618. return c->getComponentAt (relative.getX(), relative.getY());
  33619. }
  33620. return 0;
  33621. }
  33622. void Desktop::addDesktopComponent (Component* const c)
  33623. {
  33624. jassert (c != 0);
  33625. jassert (! desktopComponents.contains (c));
  33626. desktopComponents.addIfNotAlreadyThere (c);
  33627. }
  33628. void Desktop::removeDesktopComponent (Component* const c)
  33629. {
  33630. desktopComponents.removeValue (c);
  33631. }
  33632. void Desktop::componentBroughtToFront (Component* const c)
  33633. {
  33634. const int index = desktopComponents.indexOf (c);
  33635. jassert (index >= 0);
  33636. if (index >= 0)
  33637. {
  33638. int newIndex = -1;
  33639. if (! c->isAlwaysOnTop())
  33640. {
  33641. newIndex = desktopComponents.size();
  33642. while (newIndex > 0 && desktopComponents.getUnchecked (newIndex - 1)->isAlwaysOnTop())
  33643. --newIndex;
  33644. --newIndex;
  33645. }
  33646. desktopComponents.move (index, newIndex);
  33647. }
  33648. }
  33649. const Point<int> Desktop::getLastMouseDownPosition() throw()
  33650. {
  33651. return getInstance().getMainMouseSource().getLastMouseDownPosition();
  33652. }
  33653. int Desktop::getMouseButtonClickCounter() throw()
  33654. {
  33655. return getInstance().mouseClickCounter;
  33656. }
  33657. void Desktop::incrementMouseClickCounter() throw()
  33658. {
  33659. ++mouseClickCounter;
  33660. }
  33661. int Desktop::getNumDraggingMouseSources() const throw()
  33662. {
  33663. int num = 0;
  33664. for (int i = mouseSources.size(); --i >= 0;)
  33665. if (mouseSources.getUnchecked(i)->isDragging())
  33666. ++num;
  33667. return num;
  33668. }
  33669. MouseInputSource* Desktop::getDraggingMouseSource (int index) const throw()
  33670. {
  33671. int num = 0;
  33672. for (int i = mouseSources.size(); --i >= 0;)
  33673. {
  33674. MouseInputSource* const mi = mouseSources.getUnchecked(i);
  33675. if (mi->isDragging())
  33676. {
  33677. if (index == num)
  33678. return mi;
  33679. ++num;
  33680. }
  33681. }
  33682. return 0;
  33683. }
  33684. void Desktop::addFocusChangeListener (FocusChangeListener* const listener)
  33685. {
  33686. focusListeners.add (listener);
  33687. }
  33688. void Desktop::removeFocusChangeListener (FocusChangeListener* const listener)
  33689. {
  33690. focusListeners.remove (listener);
  33691. }
  33692. void Desktop::triggerFocusCallback()
  33693. {
  33694. triggerAsyncUpdate();
  33695. }
  33696. void Desktop::handleAsyncUpdate()
  33697. {
  33698. Component* currentFocus = Component::getCurrentlyFocusedComponent();
  33699. focusListeners.call (&FocusChangeListener::globalFocusChanged, currentFocus);
  33700. }
  33701. void Desktop::addGlobalMouseListener (MouseListener* const listener)
  33702. {
  33703. mouseListeners.add (listener);
  33704. resetTimer();
  33705. }
  33706. void Desktop::removeGlobalMouseListener (MouseListener* const listener)
  33707. {
  33708. mouseListeners.remove (listener);
  33709. resetTimer();
  33710. }
  33711. void Desktop::timerCallback()
  33712. {
  33713. if (lastFakeMouseMove != getMousePosition())
  33714. sendMouseMove();
  33715. }
  33716. void Desktop::sendMouseMove()
  33717. {
  33718. if (! mouseListeners.isEmpty())
  33719. {
  33720. startTimer (20);
  33721. lastFakeMouseMove = getMousePosition();
  33722. Component* const target = findComponentAt (lastFakeMouseMove);
  33723. if (target != 0)
  33724. {
  33725. Component::BailOutChecker checker (target);
  33726. const Point<int> pos (target->globalPositionToRelative (lastFakeMouseMove));
  33727. const Time now (Time::getCurrentTime());
  33728. const MouseEvent me (getMainMouseSource(), pos, ModifierKeys::getCurrentModifiers(),
  33729. target, target, now, pos, now, 0, false);
  33730. if (me.mods.isAnyMouseButtonDown())
  33731. mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  33732. else
  33733. mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  33734. }
  33735. }
  33736. }
  33737. void Desktop::resetTimer()
  33738. {
  33739. if (mouseListeners.size() == 0)
  33740. stopTimer();
  33741. else
  33742. startTimer (100);
  33743. lastFakeMouseMove = getMousePosition();
  33744. }
  33745. extern void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars);
  33746. void Desktop::setKioskModeComponent (Component* componentToUse, const bool allowMenusAndBars)
  33747. {
  33748. if (kioskModeComponent != componentToUse)
  33749. {
  33750. // agh! Don't delete a component without first stopping it being the kiosk comp
  33751. jassert (kioskModeComponent == 0 || kioskModeComponent->isValidComponent());
  33752. // agh! Don't remove a component from the desktop if it's the kiosk comp!
  33753. jassert (kioskModeComponent == 0 || kioskModeComponent->isOnDesktop());
  33754. if (kioskModeComponent->isValidComponent())
  33755. {
  33756. juce_setKioskComponent (kioskModeComponent, false, allowMenusAndBars);
  33757. kioskModeComponent->setBounds (kioskComponentOriginalBounds);
  33758. }
  33759. kioskModeComponent = componentToUse;
  33760. if (kioskModeComponent != 0)
  33761. {
  33762. jassert (kioskModeComponent->isValidComponent());
  33763. // Only components that are already on the desktop can be put into kiosk mode!
  33764. jassert (kioskModeComponent->isOnDesktop());
  33765. kioskComponentOriginalBounds = kioskModeComponent->getBounds();
  33766. juce_setKioskComponent (kioskModeComponent, true, allowMenusAndBars);
  33767. }
  33768. }
  33769. }
  33770. END_JUCE_NAMESPACE
  33771. /*** End of inlined file: juce_Desktop.cpp ***/
  33772. /*** Start of inlined file: juce_ModalComponentManager.cpp ***/
  33773. BEGIN_JUCE_NAMESPACE
  33774. class ModalComponentManager::ModalItem : public ComponentListener
  33775. {
  33776. public:
  33777. ModalItem (Component* const comp, Callback* const callback)
  33778. : component (comp), returnValue (0), isActive (true), isDeleted (false)
  33779. {
  33780. if (callback != 0)
  33781. callbacks.add (callback);
  33782. jassert (comp != 0);
  33783. component->addComponentListener (this);
  33784. }
  33785. ~ModalItem()
  33786. {
  33787. if (! isDeleted)
  33788. component->removeComponentListener (this);
  33789. }
  33790. void componentBeingDeleted (Component&)
  33791. {
  33792. isDeleted = true;
  33793. cancel();
  33794. }
  33795. void componentVisibilityChanged (Component&)
  33796. {
  33797. if (! component->isShowing())
  33798. cancel();
  33799. }
  33800. void componentParentHierarchyChanged (Component&)
  33801. {
  33802. if (! component->isShowing())
  33803. cancel();
  33804. }
  33805. void cancel()
  33806. {
  33807. if (isActive)
  33808. {
  33809. isActive = false;
  33810. ModalComponentManager::getInstance()->triggerAsyncUpdate();
  33811. }
  33812. }
  33813. Component* component;
  33814. OwnedArray<Callback> callbacks;
  33815. int returnValue;
  33816. bool isActive, isDeleted;
  33817. private:
  33818. ModalItem (const ModalItem&);
  33819. ModalItem& operator= (const ModalItem&);
  33820. };
  33821. ModalComponentManager::ModalComponentManager()
  33822. {
  33823. }
  33824. ModalComponentManager::~ModalComponentManager()
  33825. {
  33826. clearSingletonInstance();
  33827. }
  33828. juce_ImplementSingleton_SingleThreaded (ModalComponentManager);
  33829. void ModalComponentManager::startModal (Component* component, Callback* callback)
  33830. {
  33831. if (component != 0)
  33832. stack.add (new ModalItem (component, callback));
  33833. }
  33834. void ModalComponentManager::attachCallback (Component* component, Callback* callback)
  33835. {
  33836. if (callback != 0)
  33837. {
  33838. ScopedPointer<Callback> callbackDeleter (callback);
  33839. for (int i = stack.size(); --i >= 0;)
  33840. {
  33841. ModalItem* const item = stack.getUnchecked(i);
  33842. if (item->component == component)
  33843. {
  33844. item->callbacks.add (callback);
  33845. callbackDeleter.release();
  33846. break;
  33847. }
  33848. }
  33849. }
  33850. }
  33851. void ModalComponentManager::endModal (Component* component)
  33852. {
  33853. for (int i = stack.size(); --i >= 0;)
  33854. {
  33855. ModalItem* const item = stack.getUnchecked(i);
  33856. if (item->component == component)
  33857. item->cancel();
  33858. }
  33859. }
  33860. void ModalComponentManager::endModal (Component* component, int returnValue)
  33861. {
  33862. for (int i = stack.size(); --i >= 0;)
  33863. {
  33864. ModalItem* const item = stack.getUnchecked(i);
  33865. if (item->component == component)
  33866. {
  33867. item->returnValue = returnValue;
  33868. item->cancel();
  33869. }
  33870. }
  33871. }
  33872. int ModalComponentManager::getNumModalComponents() const
  33873. {
  33874. int n = 0;
  33875. for (int i = 0; i < stack.size(); ++i)
  33876. if (stack.getUnchecked(i)->isActive)
  33877. ++n;
  33878. return n;
  33879. }
  33880. Component* ModalComponentManager::getModalComponent (const int index) const
  33881. {
  33882. int n = 0;
  33883. for (int i = stack.size(); --i >= 0;)
  33884. {
  33885. const ModalItem* const item = stack.getUnchecked(i);
  33886. if (item->isActive)
  33887. if (n++ == index)
  33888. return item->component;
  33889. }
  33890. return 0;
  33891. }
  33892. bool ModalComponentManager::isModal (Component* const comp) const
  33893. {
  33894. for (int i = stack.size(); --i >= 0;)
  33895. {
  33896. const ModalItem* const item = stack.getUnchecked(i);
  33897. if (item->isActive && item->component == comp)
  33898. return true;
  33899. }
  33900. return false;
  33901. }
  33902. bool ModalComponentManager::isFrontModalComponent (Component* const comp) const
  33903. {
  33904. return comp == getModalComponent (0);
  33905. }
  33906. void ModalComponentManager::handleAsyncUpdate()
  33907. {
  33908. for (int i = stack.size(); --i >= 0;)
  33909. {
  33910. const ModalItem* const item = stack.getUnchecked(i);
  33911. if (! item->isActive)
  33912. {
  33913. for (int j = item->callbacks.size(); --j >= 0;)
  33914. item->callbacks.getUnchecked(j)->modalStateFinished (item->returnValue);
  33915. stack.remove (i);
  33916. }
  33917. }
  33918. }
  33919. class ModalComponentManager::ReturnValueRetriever : public ModalComponentManager::Callback
  33920. {
  33921. public:
  33922. ReturnValueRetriever (int& value_, bool& finished_) : value (value_), finished (finished_) {}
  33923. ~ReturnValueRetriever() {}
  33924. void modalStateFinished (int returnValue)
  33925. {
  33926. finished = true;
  33927. value = returnValue;
  33928. }
  33929. private:
  33930. int& value;
  33931. bool& finished;
  33932. ReturnValueRetriever (const ReturnValueRetriever&);
  33933. ReturnValueRetriever& operator= (const ReturnValueRetriever&);
  33934. };
  33935. int ModalComponentManager::runEventLoopForCurrentComponent()
  33936. {
  33937. // This can only be run from the message thread!
  33938. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  33939. Component* currentlyModal = getModalComponent (0);
  33940. if (currentlyModal == 0)
  33941. return 0;
  33942. Component::SafePointer<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  33943. int returnValue = 0;
  33944. bool finished = false;
  33945. attachCallback (currentlyModal, new ReturnValueRetriever (returnValue, finished));
  33946. JUCE_TRY
  33947. {
  33948. while (! finished)
  33949. {
  33950. if (! MessageManager::getInstance()->runDispatchLoopUntil (20))
  33951. break;
  33952. }
  33953. }
  33954. JUCE_CATCH_EXCEPTION
  33955. if (prevFocused != 0)
  33956. prevFocused->grabKeyboardFocus();
  33957. return returnValue;
  33958. }
  33959. END_JUCE_NAMESPACE
  33960. /*** End of inlined file: juce_ModalComponentManager.cpp ***/
  33961. /*** Start of inlined file: juce_ArrowButton.cpp ***/
  33962. BEGIN_JUCE_NAMESPACE
  33963. ArrowButton::ArrowButton (const String& name,
  33964. float arrowDirectionInRadians,
  33965. const Colour& arrowColour)
  33966. : Button (name),
  33967. colour (arrowColour)
  33968. {
  33969. path.lineTo (0.0f, 1.0f);
  33970. path.lineTo (1.0f, 0.5f);
  33971. path.closeSubPath();
  33972. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * arrowDirectionInRadians,
  33973. 0.5f, 0.5f));
  33974. setComponentEffect (&shadow);
  33975. buttonStateChanged();
  33976. }
  33977. ArrowButton::~ArrowButton()
  33978. {
  33979. }
  33980. void ArrowButton::paintButton (Graphics& g,
  33981. bool /*isMouseOverButton*/,
  33982. bool /*isButtonDown*/)
  33983. {
  33984. g.setColour (colour);
  33985. g.fillPath (path, path.getTransformToScaleToFit ((float) offset,
  33986. (float) offset,
  33987. (float) (getWidth() - 3),
  33988. (float) (getHeight() - 3),
  33989. false));
  33990. }
  33991. void ArrowButton::buttonStateChanged()
  33992. {
  33993. offset = (isDown()) ? 1 : 0;
  33994. shadow.setShadowProperties ((isDown()) ? 1.2f : 3.0f,
  33995. 0.3f, -1, 0);
  33996. }
  33997. END_JUCE_NAMESPACE
  33998. /*** End of inlined file: juce_ArrowButton.cpp ***/
  33999. /*** Start of inlined file: juce_Button.cpp ***/
  34000. BEGIN_JUCE_NAMESPACE
  34001. class Button::RepeatTimer : public Timer
  34002. {
  34003. public:
  34004. RepeatTimer (Button& owner_) : owner (owner_) {}
  34005. void timerCallback() { owner.repeatTimerCallback(); }
  34006. juce_UseDebuggingNewOperator
  34007. private:
  34008. Button& owner;
  34009. RepeatTimer (const RepeatTimer&);
  34010. RepeatTimer& operator= (const RepeatTimer&);
  34011. };
  34012. Button::Button (const String& name)
  34013. : Component (name),
  34014. text (name),
  34015. buttonPressTime (0),
  34016. lastTimeCallbackTime (0),
  34017. commandManagerToUse (0),
  34018. autoRepeatDelay (-1),
  34019. autoRepeatSpeed (0),
  34020. autoRepeatMinimumDelay (-1),
  34021. radioGroupId (0),
  34022. commandID (0),
  34023. connectedEdgeFlags (0),
  34024. buttonState (buttonNormal),
  34025. lastToggleState (false),
  34026. clickTogglesState (false),
  34027. needsToRelease (false),
  34028. needsRepainting (false),
  34029. isKeyDown (false),
  34030. triggerOnMouseDown (false),
  34031. generateTooltip (false)
  34032. {
  34033. setWantsKeyboardFocus (true);
  34034. isOn.addListener (this);
  34035. }
  34036. Button::~Button()
  34037. {
  34038. isOn.removeListener (this);
  34039. if (commandManagerToUse != 0)
  34040. commandManagerToUse->removeListener (this);
  34041. repeatTimer = 0;
  34042. clearShortcuts();
  34043. }
  34044. void Button::setButtonText (const String& newText)
  34045. {
  34046. if (text != newText)
  34047. {
  34048. text = newText;
  34049. repaint();
  34050. }
  34051. }
  34052. void Button::setTooltip (const String& newTooltip)
  34053. {
  34054. SettableTooltipClient::setTooltip (newTooltip);
  34055. generateTooltip = false;
  34056. }
  34057. const String Button::getTooltip()
  34058. {
  34059. if (generateTooltip && commandManagerToUse != 0 && commandID != 0)
  34060. {
  34061. String tt (commandManagerToUse->getDescriptionOfCommand (commandID));
  34062. Array <KeyPress> keyPresses (commandManagerToUse->getKeyMappings()->getKeyPressesAssignedToCommand (commandID));
  34063. for (int i = 0; i < keyPresses.size(); ++i)
  34064. {
  34065. const String key (keyPresses.getReference(i).getTextDescription());
  34066. tt << " [";
  34067. if (key.length() == 1)
  34068. tt << TRANS("shortcut") << ": '" << key << "']";
  34069. else
  34070. tt << key << ']';
  34071. }
  34072. return tt;
  34073. }
  34074. return SettableTooltipClient::getTooltip();
  34075. }
  34076. void Button::setConnectedEdges (const int connectedEdgeFlags_)
  34077. {
  34078. if (connectedEdgeFlags != connectedEdgeFlags_)
  34079. {
  34080. connectedEdgeFlags = connectedEdgeFlags_;
  34081. repaint();
  34082. }
  34083. }
  34084. void Button::setToggleState (const bool shouldBeOn,
  34085. const bool sendChangeNotification)
  34086. {
  34087. if (shouldBeOn != lastToggleState)
  34088. {
  34089. if (isOn != shouldBeOn) // this test means that if the value is void rather than explicitly set to
  34090. isOn = shouldBeOn; // false, it won't be changed unless the required value is true.
  34091. lastToggleState = shouldBeOn;
  34092. repaint();
  34093. if (sendChangeNotification)
  34094. {
  34095. Component::SafePointer<Component> deletionWatcher (this);
  34096. sendClickMessage (ModifierKeys());
  34097. if (deletionWatcher == 0)
  34098. return;
  34099. }
  34100. if (lastToggleState)
  34101. turnOffOtherButtonsInGroup (sendChangeNotification);
  34102. }
  34103. }
  34104. void Button::setClickingTogglesState (const bool shouldToggle) throw()
  34105. {
  34106. clickTogglesState = shouldToggle;
  34107. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  34108. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  34109. // it is that this button represents, and the button will update its state to reflect this
  34110. // in the applicationCommandListChanged() method.
  34111. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  34112. }
  34113. bool Button::getClickingTogglesState() const throw()
  34114. {
  34115. return clickTogglesState;
  34116. }
  34117. void Button::valueChanged (Value& value)
  34118. {
  34119. if (value.refersToSameSourceAs (isOn))
  34120. setToggleState (isOn.getValue(), true);
  34121. }
  34122. void Button::setRadioGroupId (const int newGroupId)
  34123. {
  34124. if (radioGroupId != newGroupId)
  34125. {
  34126. radioGroupId = newGroupId;
  34127. if (lastToggleState)
  34128. turnOffOtherButtonsInGroup (true);
  34129. }
  34130. }
  34131. void Button::turnOffOtherButtonsInGroup (const bool sendChangeNotification)
  34132. {
  34133. Component* const p = getParentComponent();
  34134. if (p != 0 && radioGroupId != 0)
  34135. {
  34136. Component::SafePointer<Component> deletionWatcher (this);
  34137. for (int i = p->getNumChildComponents(); --i >= 0;)
  34138. {
  34139. Component* const c = p->getChildComponent (i);
  34140. if (c != this)
  34141. {
  34142. Button* const b = dynamic_cast <Button*> (c);
  34143. if (b != 0 && b->getRadioGroupId() == radioGroupId)
  34144. {
  34145. b->setToggleState (false, sendChangeNotification);
  34146. if (deletionWatcher == 0)
  34147. return;
  34148. }
  34149. }
  34150. }
  34151. }
  34152. }
  34153. void Button::enablementChanged()
  34154. {
  34155. updateState (0);
  34156. repaint();
  34157. }
  34158. Button::ButtonState Button::updateState (const MouseEvent* const e)
  34159. {
  34160. ButtonState state = buttonNormal;
  34161. if (isEnabled() && isVisible() && ! isCurrentlyBlockedByAnotherModalComponent())
  34162. {
  34163. Point<int> mousePos;
  34164. if (e == 0)
  34165. mousePos = getMouseXYRelative();
  34166. else
  34167. mousePos = e->getEventRelativeTo (this).getPosition();
  34168. const bool over = reallyContains (mousePos.getX(), mousePos.getY(), true);
  34169. const bool down = isMouseButtonDown();
  34170. if ((down && (over || (triggerOnMouseDown && buttonState == buttonDown))) || isKeyDown)
  34171. state = buttonDown;
  34172. else if (over)
  34173. state = buttonOver;
  34174. }
  34175. setState (state);
  34176. return state;
  34177. }
  34178. void Button::setState (const ButtonState newState)
  34179. {
  34180. if (buttonState != newState)
  34181. {
  34182. buttonState = newState;
  34183. repaint();
  34184. if (buttonState == buttonDown)
  34185. {
  34186. buttonPressTime = Time::getApproximateMillisecondCounter();
  34187. lastTimeCallbackTime = buttonPressTime;
  34188. }
  34189. sendStateMessage();
  34190. }
  34191. }
  34192. bool Button::isDown() const throw()
  34193. {
  34194. return buttonState == buttonDown;
  34195. }
  34196. bool Button::isOver() const throw()
  34197. {
  34198. return buttonState != buttonNormal;
  34199. }
  34200. void Button::buttonStateChanged()
  34201. {
  34202. }
  34203. uint32 Button::getMillisecondsSinceButtonDown() const throw()
  34204. {
  34205. const uint32 now = Time::getApproximateMillisecondCounter();
  34206. return now > buttonPressTime ? now - buttonPressTime : 0;
  34207. }
  34208. void Button::setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw()
  34209. {
  34210. triggerOnMouseDown = isTriggeredOnMouseDown;
  34211. }
  34212. void Button::clicked()
  34213. {
  34214. }
  34215. void Button::clicked (const ModifierKeys& /*modifiers*/)
  34216. {
  34217. clicked();
  34218. }
  34219. static const int clickMessageId = 0x2f3f4f99;
  34220. void Button::triggerClick()
  34221. {
  34222. postCommandMessage (clickMessageId);
  34223. }
  34224. void Button::internalClickCallback (const ModifierKeys& modifiers)
  34225. {
  34226. if (clickTogglesState)
  34227. setToggleState ((radioGroupId != 0) || ! lastToggleState, false);
  34228. sendClickMessage (modifiers);
  34229. }
  34230. void Button::flashButtonState()
  34231. {
  34232. if (isEnabled())
  34233. {
  34234. needsToRelease = true;
  34235. setState (buttonDown);
  34236. getRepeatTimer().startTimer (100);
  34237. }
  34238. }
  34239. void Button::handleCommandMessage (int commandId)
  34240. {
  34241. if (commandId == clickMessageId)
  34242. {
  34243. if (isEnabled())
  34244. {
  34245. flashButtonState();
  34246. internalClickCallback (ModifierKeys::getCurrentModifiers());
  34247. }
  34248. }
  34249. else
  34250. {
  34251. Component::handleCommandMessage (commandId);
  34252. }
  34253. }
  34254. void Button::addButtonListener (ButtonListener* const newListener)
  34255. {
  34256. buttonListeners.add (newListener);
  34257. }
  34258. void Button::removeButtonListener (ButtonListener* const listener)
  34259. {
  34260. buttonListeners.remove (listener);
  34261. }
  34262. void Button::sendClickMessage (const ModifierKeys& modifiers)
  34263. {
  34264. Component::BailOutChecker checker (this);
  34265. if (commandManagerToUse != 0 && commandID != 0)
  34266. {
  34267. ApplicationCommandTarget::InvocationInfo info (commandID);
  34268. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromButton;
  34269. info.originatingComponent = this;
  34270. commandManagerToUse->invoke (info, true);
  34271. }
  34272. clicked (modifiers);
  34273. if (! checker.shouldBailOut())
  34274. buttonListeners.callChecked (checker, &ButtonListener::buttonClicked, this);
  34275. }
  34276. void Button::sendStateMessage()
  34277. {
  34278. Component::BailOutChecker checker (this);
  34279. buttonStateChanged();
  34280. if (! checker.shouldBailOut())
  34281. buttonListeners.callChecked (checker, &ButtonListener::buttonStateChanged, this);
  34282. }
  34283. void Button::paint (Graphics& g)
  34284. {
  34285. if (needsToRelease && isEnabled())
  34286. {
  34287. needsToRelease = false;
  34288. needsRepainting = true;
  34289. }
  34290. paintButton (g, isOver(), isDown());
  34291. }
  34292. void Button::mouseEnter (const MouseEvent& e)
  34293. {
  34294. updateState (&e);
  34295. }
  34296. void Button::mouseExit (const MouseEvent& e)
  34297. {
  34298. updateState (&e);
  34299. }
  34300. void Button::mouseDown (const MouseEvent& e)
  34301. {
  34302. updateState (&e);
  34303. if (isDown())
  34304. {
  34305. if (autoRepeatDelay >= 0)
  34306. getRepeatTimer().startTimer (autoRepeatDelay);
  34307. if (triggerOnMouseDown)
  34308. internalClickCallback (e.mods);
  34309. }
  34310. }
  34311. void Button::mouseUp (const MouseEvent& e)
  34312. {
  34313. const bool wasDown = isDown();
  34314. updateState (&e);
  34315. if (wasDown && isOver() && ! triggerOnMouseDown)
  34316. internalClickCallback (e.mods);
  34317. }
  34318. void Button::mouseDrag (const MouseEvent& e)
  34319. {
  34320. const ButtonState oldState = buttonState;
  34321. updateState (&e);
  34322. if (autoRepeatDelay >= 0 && buttonState != oldState && isDown())
  34323. getRepeatTimer().startTimer (autoRepeatSpeed);
  34324. }
  34325. void Button::focusGained (FocusChangeType)
  34326. {
  34327. updateState (0);
  34328. repaint();
  34329. }
  34330. void Button::focusLost (FocusChangeType)
  34331. {
  34332. updateState (0);
  34333. repaint();
  34334. }
  34335. void Button::setVisible (bool shouldBeVisible)
  34336. {
  34337. if (shouldBeVisible != isVisible())
  34338. {
  34339. Component::setVisible (shouldBeVisible);
  34340. if (! shouldBeVisible)
  34341. needsToRelease = false;
  34342. updateState (0);
  34343. }
  34344. else
  34345. {
  34346. Component::setVisible (shouldBeVisible);
  34347. }
  34348. }
  34349. void Button::parentHierarchyChanged()
  34350. {
  34351. Component* const newKeySource = (shortcuts.size() == 0) ? 0 : getTopLevelComponent();
  34352. if (newKeySource != keySource.getComponent())
  34353. {
  34354. if (keySource != 0)
  34355. keySource->removeKeyListener (this);
  34356. keySource = newKeySource;
  34357. if (keySource != 0)
  34358. keySource->addKeyListener (this);
  34359. }
  34360. }
  34361. void Button::setCommandToTrigger (ApplicationCommandManager* const commandManagerToUse_,
  34362. const int commandID_,
  34363. const bool generateTooltip_)
  34364. {
  34365. commandID = commandID_;
  34366. generateTooltip = generateTooltip_;
  34367. if (commandManagerToUse != commandManagerToUse_)
  34368. {
  34369. if (commandManagerToUse != 0)
  34370. commandManagerToUse->removeListener (this);
  34371. commandManagerToUse = commandManagerToUse_;
  34372. if (commandManagerToUse != 0)
  34373. commandManagerToUse->addListener (this);
  34374. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  34375. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  34376. // it is that this button represents, and the button will update its state to reflect this
  34377. // in the applicationCommandListChanged() method.
  34378. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  34379. }
  34380. if (commandManagerToUse != 0)
  34381. applicationCommandListChanged();
  34382. else
  34383. setEnabled (true);
  34384. }
  34385. void Button::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  34386. {
  34387. if (info.commandID == commandID
  34388. && (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) == 0)
  34389. {
  34390. flashButtonState();
  34391. }
  34392. }
  34393. void Button::applicationCommandListChanged()
  34394. {
  34395. if (commandManagerToUse != 0)
  34396. {
  34397. ApplicationCommandInfo info (0);
  34398. ApplicationCommandTarget* const target = commandManagerToUse->getTargetForCommand (commandID, info);
  34399. setEnabled (target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0);
  34400. if (target != 0)
  34401. setToggleState ((info.flags & ApplicationCommandInfo::isTicked) != 0, false);
  34402. }
  34403. }
  34404. void Button::addShortcut (const KeyPress& key)
  34405. {
  34406. if (key.isValid())
  34407. {
  34408. jassert (! isRegisteredForShortcut (key)); // already registered!
  34409. shortcuts.add (key);
  34410. parentHierarchyChanged();
  34411. }
  34412. }
  34413. void Button::clearShortcuts()
  34414. {
  34415. shortcuts.clear();
  34416. parentHierarchyChanged();
  34417. }
  34418. bool Button::isShortcutPressed() const
  34419. {
  34420. if (! isCurrentlyBlockedByAnotherModalComponent())
  34421. {
  34422. for (int i = shortcuts.size(); --i >= 0;)
  34423. if (shortcuts.getReference(i).isCurrentlyDown())
  34424. return true;
  34425. }
  34426. return false;
  34427. }
  34428. bool Button::isRegisteredForShortcut (const KeyPress& key) const
  34429. {
  34430. for (int i = shortcuts.size(); --i >= 0;)
  34431. if (key == shortcuts.getReference(i))
  34432. return true;
  34433. return false;
  34434. }
  34435. bool Button::keyStateChanged (const bool, Component*)
  34436. {
  34437. if (! isEnabled())
  34438. return false;
  34439. const bool wasDown = isKeyDown;
  34440. isKeyDown = isShortcutPressed();
  34441. if (autoRepeatDelay >= 0 && (isKeyDown && ! wasDown))
  34442. getRepeatTimer().startTimer (autoRepeatDelay);
  34443. updateState (0);
  34444. if (isEnabled() && wasDown && ! isKeyDown)
  34445. {
  34446. internalClickCallback (ModifierKeys::getCurrentModifiers());
  34447. // (return immediately - this button may now have been deleted)
  34448. return true;
  34449. }
  34450. return wasDown || isKeyDown;
  34451. }
  34452. bool Button::keyPressed (const KeyPress&, Component*)
  34453. {
  34454. // returning true will avoid forwarding events for keys that we're using as shortcuts
  34455. return isShortcutPressed();
  34456. }
  34457. bool Button::keyPressed (const KeyPress& key)
  34458. {
  34459. if (isEnabled() && key.isKeyCode (KeyPress::returnKey))
  34460. {
  34461. triggerClick();
  34462. return true;
  34463. }
  34464. return false;
  34465. }
  34466. void Button::setRepeatSpeed (const int initialDelayMillisecs,
  34467. const int repeatMillisecs,
  34468. const int minimumDelayInMillisecs) throw()
  34469. {
  34470. autoRepeatDelay = initialDelayMillisecs;
  34471. autoRepeatSpeed = repeatMillisecs;
  34472. autoRepeatMinimumDelay = jmin (autoRepeatSpeed, minimumDelayInMillisecs);
  34473. }
  34474. void Button::repeatTimerCallback()
  34475. {
  34476. if (needsRepainting)
  34477. {
  34478. getRepeatTimer().stopTimer();
  34479. updateState (0);
  34480. needsRepainting = false;
  34481. }
  34482. else if (autoRepeatSpeed > 0 && (isKeyDown || (updateState (0) == buttonDown)))
  34483. {
  34484. int repeatSpeed = autoRepeatSpeed;
  34485. if (autoRepeatMinimumDelay >= 0)
  34486. {
  34487. double timeHeldDown = jmin (1.0, getMillisecondsSinceButtonDown() / 4000.0);
  34488. timeHeldDown *= timeHeldDown;
  34489. repeatSpeed = repeatSpeed + (int) (timeHeldDown * (autoRepeatMinimumDelay - repeatSpeed));
  34490. }
  34491. repeatSpeed = jmax (1, repeatSpeed);
  34492. getRepeatTimer().startTimer (repeatSpeed);
  34493. const uint32 now = Time::getApproximateMillisecondCounter();
  34494. const int numTimesToCallback = (now > lastTimeCallbackTime) ? jmax (1, (int) (now - lastTimeCallbackTime) / repeatSpeed) : 1;
  34495. lastTimeCallbackTime = now;
  34496. Component::SafePointer<Component> deletionWatcher (this);
  34497. for (int i = numTimesToCallback; --i >= 0;)
  34498. {
  34499. internalClickCallback (ModifierKeys::getCurrentModifiers());
  34500. if (deletionWatcher == 0 || ! isDown())
  34501. return;
  34502. }
  34503. }
  34504. else if (! needsToRelease)
  34505. {
  34506. getRepeatTimer().stopTimer();
  34507. }
  34508. }
  34509. Button::RepeatTimer& Button::getRepeatTimer()
  34510. {
  34511. if (repeatTimer == 0)
  34512. repeatTimer = new RepeatTimer (*this);
  34513. return *repeatTimer;
  34514. }
  34515. END_JUCE_NAMESPACE
  34516. /*** End of inlined file: juce_Button.cpp ***/
  34517. /*** Start of inlined file: juce_DrawableButton.cpp ***/
  34518. BEGIN_JUCE_NAMESPACE
  34519. DrawableButton::DrawableButton (const String& name,
  34520. const DrawableButton::ButtonStyle buttonStyle)
  34521. : Button (name),
  34522. style (buttonStyle),
  34523. edgeIndent (3)
  34524. {
  34525. if (buttonStyle == ImageOnButtonBackground)
  34526. {
  34527. backgroundOff = Colour (0xffbbbbff);
  34528. backgroundOn = Colour (0xff3333ff);
  34529. }
  34530. else
  34531. {
  34532. backgroundOff = Colours::transparentBlack;
  34533. backgroundOn = Colour (0xaabbbbff);
  34534. }
  34535. }
  34536. DrawableButton::~DrawableButton()
  34537. {
  34538. deleteImages();
  34539. }
  34540. void DrawableButton::deleteImages()
  34541. {
  34542. }
  34543. void DrawableButton::setImages (const Drawable* normal,
  34544. const Drawable* over,
  34545. const Drawable* down,
  34546. const Drawable* disabled,
  34547. const Drawable* normalOn,
  34548. const Drawable* overOn,
  34549. const Drawable* downOn,
  34550. const Drawable* disabledOn)
  34551. {
  34552. deleteImages();
  34553. jassert (normal != 0); // you really need to give it at least a normal image..
  34554. if (normal != 0)
  34555. normalImage = normal->createCopy();
  34556. if (over != 0)
  34557. overImage = over->createCopy();
  34558. if (down != 0)
  34559. downImage = down->createCopy();
  34560. if (disabled != 0)
  34561. disabledImage = disabled->createCopy();
  34562. if (normalOn != 0)
  34563. normalImageOn = normalOn->createCopy();
  34564. if (overOn != 0)
  34565. overImageOn = overOn->createCopy();
  34566. if (downOn != 0)
  34567. downImageOn = downOn->createCopy();
  34568. if (disabledOn != 0)
  34569. disabledImageOn = disabledOn->createCopy();
  34570. repaint();
  34571. }
  34572. void DrawableButton::setButtonStyle (const DrawableButton::ButtonStyle newStyle)
  34573. {
  34574. if (style != newStyle)
  34575. {
  34576. style = newStyle;
  34577. repaint();
  34578. }
  34579. }
  34580. void DrawableButton::setBackgroundColours (const Colour& toggledOffColour,
  34581. const Colour& toggledOnColour)
  34582. {
  34583. if (backgroundOff != toggledOffColour
  34584. || backgroundOn != toggledOnColour)
  34585. {
  34586. backgroundOff = toggledOffColour;
  34587. backgroundOn = toggledOnColour;
  34588. repaint();
  34589. }
  34590. }
  34591. const Colour& DrawableButton::getBackgroundColour() const throw()
  34592. {
  34593. return getToggleState() ? backgroundOn
  34594. : backgroundOff;
  34595. }
  34596. void DrawableButton::setEdgeIndent (const int numPixelsIndent)
  34597. {
  34598. edgeIndent = numPixelsIndent;
  34599. repaint();
  34600. }
  34601. void DrawableButton::paintButton (Graphics& g,
  34602. bool isMouseOverButton,
  34603. bool isButtonDown)
  34604. {
  34605. Rectangle<int> imageSpace;
  34606. if (style == ImageOnButtonBackground)
  34607. {
  34608. const int insetX = getWidth() / 4;
  34609. const int insetY = getHeight() / 4;
  34610. imageSpace.setBounds (insetX, insetY, getWidth() - insetX * 2, getHeight() - insetY * 2);
  34611. getLookAndFeel().drawButtonBackground (g, *this,
  34612. getBackgroundColour(),
  34613. isMouseOverButton,
  34614. isButtonDown);
  34615. }
  34616. else
  34617. {
  34618. g.fillAll (getBackgroundColour());
  34619. const int textH = (style == ImageAboveTextLabel)
  34620. ? jmin (16, proportionOfHeight (0.25f))
  34621. : 0;
  34622. const int indentX = jmin (edgeIndent, proportionOfWidth (0.3f));
  34623. const int indentY = jmin (edgeIndent, proportionOfHeight (0.3f));
  34624. imageSpace.setBounds (indentX, indentY,
  34625. getWidth() - indentX * 2,
  34626. getHeight() - indentY * 2 - textH);
  34627. if (textH > 0)
  34628. {
  34629. g.setFont ((float) textH);
  34630. g.setColour (Colours::black.withAlpha (isEnabled() ? 1.0f : 0.4f));
  34631. g.drawFittedText (getButtonText(),
  34632. 2, getHeight() - textH - 1,
  34633. getWidth() - 4, textH,
  34634. Justification::centred, 1);
  34635. }
  34636. }
  34637. g.setImageResamplingQuality (Graphics::mediumResamplingQuality);
  34638. g.setOpacity (1.0f);
  34639. const Drawable* imageToDraw = 0;
  34640. if (isEnabled())
  34641. {
  34642. imageToDraw = getCurrentImage();
  34643. }
  34644. else
  34645. {
  34646. imageToDraw = getToggleState() ? disabledImageOn
  34647. : disabledImage;
  34648. if (imageToDraw == 0)
  34649. {
  34650. g.setOpacity (0.4f);
  34651. imageToDraw = getNormalImage();
  34652. }
  34653. }
  34654. if (imageToDraw != 0)
  34655. {
  34656. if (style == ImageRaw)
  34657. {
  34658. imageToDraw->draw (g, 1.0f);
  34659. }
  34660. else
  34661. {
  34662. imageToDraw->drawWithin (g,
  34663. imageSpace.getX(),
  34664. imageSpace.getY(),
  34665. imageSpace.getWidth(),
  34666. imageSpace.getHeight(),
  34667. RectanglePlacement::centred,
  34668. 1.0f);
  34669. }
  34670. }
  34671. }
  34672. const Drawable* DrawableButton::getCurrentImage() const throw()
  34673. {
  34674. if (isDown())
  34675. return getDownImage();
  34676. if (isOver())
  34677. return getOverImage();
  34678. return getNormalImage();
  34679. }
  34680. const Drawable* DrawableButton::getNormalImage() const throw()
  34681. {
  34682. return (getToggleState() && normalImageOn != 0) ? normalImageOn
  34683. : normalImage;
  34684. }
  34685. const Drawable* DrawableButton::getOverImage() const throw()
  34686. {
  34687. const Drawable* d = normalImage;
  34688. if (getToggleState())
  34689. {
  34690. if (overImageOn != 0)
  34691. d = overImageOn;
  34692. else if (normalImageOn != 0)
  34693. d = normalImageOn;
  34694. else if (overImage != 0)
  34695. d = overImage;
  34696. }
  34697. else
  34698. {
  34699. if (overImage != 0)
  34700. d = overImage;
  34701. }
  34702. return d;
  34703. }
  34704. const Drawable* DrawableButton::getDownImage() const throw()
  34705. {
  34706. const Drawable* d = normalImage;
  34707. if (getToggleState())
  34708. {
  34709. if (downImageOn != 0)
  34710. d = downImageOn;
  34711. else if (overImageOn != 0)
  34712. d = overImageOn;
  34713. else if (normalImageOn != 0)
  34714. d = normalImageOn;
  34715. else if (downImage != 0)
  34716. d = downImage;
  34717. else
  34718. d = getOverImage();
  34719. }
  34720. else
  34721. {
  34722. if (downImage != 0)
  34723. d = downImage;
  34724. else
  34725. d = getOverImage();
  34726. }
  34727. return d;
  34728. }
  34729. END_JUCE_NAMESPACE
  34730. /*** End of inlined file: juce_DrawableButton.cpp ***/
  34731. /*** Start of inlined file: juce_HyperlinkButton.cpp ***/
  34732. BEGIN_JUCE_NAMESPACE
  34733. HyperlinkButton::HyperlinkButton (const String& linkText,
  34734. const URL& linkURL)
  34735. : Button (linkText),
  34736. url (linkURL),
  34737. font (14.0f, Font::underlined),
  34738. resizeFont (true),
  34739. justification (Justification::centred)
  34740. {
  34741. setMouseCursor (MouseCursor::PointingHandCursor);
  34742. setTooltip (linkURL.toString (false));
  34743. }
  34744. HyperlinkButton::~HyperlinkButton()
  34745. {
  34746. }
  34747. void HyperlinkButton::setFont (const Font& newFont,
  34748. const bool resizeToMatchComponentHeight,
  34749. const Justification& justificationType)
  34750. {
  34751. font = newFont;
  34752. resizeFont = resizeToMatchComponentHeight;
  34753. justification = justificationType;
  34754. repaint();
  34755. }
  34756. void HyperlinkButton::setURL (const URL& newURL) throw()
  34757. {
  34758. url = newURL;
  34759. setTooltip (newURL.toString (false));
  34760. }
  34761. const Font HyperlinkButton::getFontToUse() const
  34762. {
  34763. Font f (font);
  34764. if (resizeFont)
  34765. f.setHeight (getHeight() * 0.7f);
  34766. return f;
  34767. }
  34768. void HyperlinkButton::changeWidthToFitText()
  34769. {
  34770. setSize (getFontToUse().getStringWidth (getName()) + 6, getHeight());
  34771. }
  34772. void HyperlinkButton::colourChanged()
  34773. {
  34774. repaint();
  34775. }
  34776. void HyperlinkButton::clicked()
  34777. {
  34778. if (url.isWellFormed())
  34779. url.launchInDefaultBrowser();
  34780. }
  34781. void HyperlinkButton::paintButton (Graphics& g,
  34782. bool isMouseOverButton,
  34783. bool isButtonDown)
  34784. {
  34785. const Colour textColour (findColour (textColourId));
  34786. if (isEnabled())
  34787. g.setColour ((isMouseOverButton) ? textColour.darker ((isButtonDown) ? 1.3f : 0.4f)
  34788. : textColour);
  34789. else
  34790. g.setColour (textColour.withMultipliedAlpha (0.4f));
  34791. g.setFont (getFontToUse());
  34792. g.drawText (getButtonText(),
  34793. 2, 0, getWidth() - 2, getHeight(),
  34794. justification.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  34795. true);
  34796. }
  34797. END_JUCE_NAMESPACE
  34798. /*** End of inlined file: juce_HyperlinkButton.cpp ***/
  34799. /*** Start of inlined file: juce_ImageButton.cpp ***/
  34800. BEGIN_JUCE_NAMESPACE
  34801. ImageButton::ImageButton (const String& text_)
  34802. : Button (text_),
  34803. scaleImageToFit (true),
  34804. preserveProportions (true),
  34805. alphaThreshold (0),
  34806. imageX (0),
  34807. imageY (0),
  34808. imageW (0),
  34809. imageH (0),
  34810. normalImage (0),
  34811. overImage (0),
  34812. downImage (0)
  34813. {
  34814. }
  34815. ImageButton::~ImageButton()
  34816. {
  34817. }
  34818. void ImageButton::setImages (const bool resizeButtonNowToFitThisImage,
  34819. const bool rescaleImagesWhenButtonSizeChanges,
  34820. const bool preserveImageProportions,
  34821. const Image& normalImage_,
  34822. const float imageOpacityWhenNormal,
  34823. const Colour& overlayColourWhenNormal,
  34824. const Image& overImage_,
  34825. const float imageOpacityWhenOver,
  34826. const Colour& overlayColourWhenOver,
  34827. const Image& downImage_,
  34828. const float imageOpacityWhenDown,
  34829. const Colour& overlayColourWhenDown,
  34830. const float hitTestAlphaThreshold)
  34831. {
  34832. normalImage = normalImage_;
  34833. overImage = overImage_;
  34834. downImage = downImage_;
  34835. if (resizeButtonNowToFitThisImage && normalImage.isValid())
  34836. {
  34837. imageW = normalImage.getWidth();
  34838. imageH = normalImage.getHeight();
  34839. setSize (imageW, imageH);
  34840. }
  34841. scaleImageToFit = rescaleImagesWhenButtonSizeChanges;
  34842. preserveProportions = preserveImageProportions;
  34843. normalOpacity = imageOpacityWhenNormal;
  34844. normalOverlay = overlayColourWhenNormal;
  34845. overOpacity = imageOpacityWhenOver;
  34846. overOverlay = overlayColourWhenOver;
  34847. downOpacity = imageOpacityWhenDown;
  34848. downOverlay = overlayColourWhenDown;
  34849. alphaThreshold = (unsigned char) jlimit (0, 0xff, roundToInt (255.0f * hitTestAlphaThreshold));
  34850. repaint();
  34851. }
  34852. const Image ImageButton::getCurrentImage() const
  34853. {
  34854. if (isDown() || getToggleState())
  34855. return getDownImage();
  34856. if (isOver())
  34857. return getOverImage();
  34858. return getNormalImage();
  34859. }
  34860. const Image ImageButton::getNormalImage() const
  34861. {
  34862. return normalImage;
  34863. }
  34864. const Image ImageButton::getOverImage() const
  34865. {
  34866. return overImage.isValid() ? overImage
  34867. : normalImage;
  34868. }
  34869. const Image ImageButton::getDownImage() const
  34870. {
  34871. return downImage.isValid() ? downImage
  34872. : getOverImage();
  34873. }
  34874. void ImageButton::paintButton (Graphics& g,
  34875. bool isMouseOverButton,
  34876. bool isButtonDown)
  34877. {
  34878. if (! isEnabled())
  34879. {
  34880. isMouseOverButton = false;
  34881. isButtonDown = false;
  34882. }
  34883. Image im (getCurrentImage());
  34884. if (im.isValid())
  34885. {
  34886. const int iw = im.getWidth();
  34887. const int ih = im.getHeight();
  34888. imageW = getWidth();
  34889. imageH = getHeight();
  34890. imageX = (imageW - iw) >> 1;
  34891. imageY = (imageH - ih) >> 1;
  34892. if (scaleImageToFit)
  34893. {
  34894. if (preserveProportions)
  34895. {
  34896. int newW, newH;
  34897. const float imRatio = ih / (float)iw;
  34898. const float destRatio = imageH / (float)imageW;
  34899. if (imRatio > destRatio)
  34900. {
  34901. newW = roundToInt (imageH / imRatio);
  34902. newH = imageH;
  34903. }
  34904. else
  34905. {
  34906. newW = imageW;
  34907. newH = roundToInt (imageW * imRatio);
  34908. }
  34909. imageX = (imageW - newW) / 2;
  34910. imageY = (imageH - newH) / 2;
  34911. imageW = newW;
  34912. imageH = newH;
  34913. }
  34914. else
  34915. {
  34916. imageX = 0;
  34917. imageY = 0;
  34918. }
  34919. }
  34920. if (! scaleImageToFit)
  34921. {
  34922. imageW = iw;
  34923. imageH = ih;
  34924. }
  34925. getLookAndFeel().drawImageButton (g, &im, imageX, imageY, imageW, imageH,
  34926. isButtonDown ? downOverlay
  34927. : (isMouseOverButton ? overOverlay
  34928. : normalOverlay),
  34929. isButtonDown ? downOpacity
  34930. : (isMouseOverButton ? overOpacity
  34931. : normalOpacity),
  34932. *this);
  34933. }
  34934. }
  34935. bool ImageButton::hitTest (int x, int y)
  34936. {
  34937. if (alphaThreshold == 0)
  34938. return true;
  34939. Image im (getCurrentImage());
  34940. return im.isNull() || (imageW > 0 && imageH > 0
  34941. && alphaThreshold < im.getPixelAt (((x - imageX) * im.getWidth()) / imageW,
  34942. ((y - imageY) * im.getHeight()) / imageH).getAlpha());
  34943. }
  34944. END_JUCE_NAMESPACE
  34945. /*** End of inlined file: juce_ImageButton.cpp ***/
  34946. /*** Start of inlined file: juce_ShapeButton.cpp ***/
  34947. BEGIN_JUCE_NAMESPACE
  34948. ShapeButton::ShapeButton (const String& text_,
  34949. const Colour& normalColour_,
  34950. const Colour& overColour_,
  34951. const Colour& downColour_)
  34952. : Button (text_),
  34953. normalColour (normalColour_),
  34954. overColour (overColour_),
  34955. downColour (downColour_),
  34956. maintainShapeProportions (false),
  34957. outlineWidth (0.0f)
  34958. {
  34959. }
  34960. ShapeButton::~ShapeButton()
  34961. {
  34962. }
  34963. void ShapeButton::setColours (const Colour& newNormalColour,
  34964. const Colour& newOverColour,
  34965. const Colour& newDownColour)
  34966. {
  34967. normalColour = newNormalColour;
  34968. overColour = newOverColour;
  34969. downColour = newDownColour;
  34970. }
  34971. void ShapeButton::setOutline (const Colour& newOutlineColour,
  34972. const float newOutlineWidth)
  34973. {
  34974. outlineColour = newOutlineColour;
  34975. outlineWidth = newOutlineWidth;
  34976. }
  34977. void ShapeButton::setShape (const Path& newShape,
  34978. const bool resizeNowToFitThisShape,
  34979. const bool maintainShapeProportions_,
  34980. const bool hasShadow)
  34981. {
  34982. shape = newShape;
  34983. maintainShapeProportions = maintainShapeProportions_;
  34984. shadow.setShadowProperties (3.0f, 0.5f, 0, 0);
  34985. setComponentEffect ((hasShadow) ? &shadow : 0);
  34986. if (resizeNowToFitThisShape)
  34987. {
  34988. Rectangle<float> bounds (shape.getBounds());
  34989. if (hasShadow)
  34990. bounds.expand (4.0f, 4.0f);
  34991. shape.applyTransform (AffineTransform::translation (-bounds.getX(), -bounds.getY()));
  34992. setSize (1 + (int) (bounds.getWidth() + outlineWidth),
  34993. 1 + (int) (bounds.getHeight() + outlineWidth));
  34994. }
  34995. }
  34996. void ShapeButton::paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  34997. {
  34998. if (! isEnabled())
  34999. {
  35000. isMouseOverButton = false;
  35001. isButtonDown = false;
  35002. }
  35003. g.setColour ((isButtonDown) ? downColour
  35004. : (isMouseOverButton) ? overColour
  35005. : normalColour);
  35006. int w = getWidth();
  35007. int h = getHeight();
  35008. if (getComponentEffect() != 0)
  35009. {
  35010. w -= 4;
  35011. h -= 4;
  35012. }
  35013. const float offset = (outlineWidth * 0.5f) + (isButtonDown ? 1.5f : 0.0f);
  35014. const AffineTransform trans (shape.getTransformToScaleToFit (offset, offset,
  35015. w - offset - outlineWidth,
  35016. h - offset - outlineWidth,
  35017. maintainShapeProportions));
  35018. g.fillPath (shape, trans);
  35019. if (outlineWidth > 0.0f)
  35020. {
  35021. g.setColour (outlineColour);
  35022. g.strokePath (shape, PathStrokeType (outlineWidth), trans);
  35023. }
  35024. }
  35025. END_JUCE_NAMESPACE
  35026. /*** End of inlined file: juce_ShapeButton.cpp ***/
  35027. /*** Start of inlined file: juce_TextButton.cpp ***/
  35028. BEGIN_JUCE_NAMESPACE
  35029. TextButton::TextButton (const String& name,
  35030. const String& toolTip)
  35031. : Button (name)
  35032. {
  35033. setTooltip (toolTip);
  35034. }
  35035. TextButton::~TextButton()
  35036. {
  35037. }
  35038. void TextButton::paintButton (Graphics& g,
  35039. bool isMouseOverButton,
  35040. bool isButtonDown)
  35041. {
  35042. getLookAndFeel().drawButtonBackground (g, *this,
  35043. findColour (getToggleState() ? buttonOnColourId
  35044. : buttonColourId),
  35045. isMouseOverButton,
  35046. isButtonDown);
  35047. getLookAndFeel().drawButtonText (g, *this,
  35048. isMouseOverButton,
  35049. isButtonDown);
  35050. }
  35051. void TextButton::colourChanged()
  35052. {
  35053. repaint();
  35054. }
  35055. const Font TextButton::getFont()
  35056. {
  35057. return Font (jmin (15.0f, getHeight() * 0.6f));
  35058. }
  35059. void TextButton::changeWidthToFitText (const int newHeight)
  35060. {
  35061. if (newHeight >= 0)
  35062. setSize (jmax (1, getWidth()), newHeight);
  35063. setSize (getFont().getStringWidth (getButtonText()) + getHeight(),
  35064. getHeight());
  35065. }
  35066. END_JUCE_NAMESPACE
  35067. /*** End of inlined file: juce_TextButton.cpp ***/
  35068. /*** Start of inlined file: juce_ToggleButton.cpp ***/
  35069. BEGIN_JUCE_NAMESPACE
  35070. ToggleButton::ToggleButton (const String& buttonText)
  35071. : Button (buttonText)
  35072. {
  35073. setClickingTogglesState (true);
  35074. }
  35075. ToggleButton::~ToggleButton()
  35076. {
  35077. }
  35078. void ToggleButton::paintButton (Graphics& g,
  35079. bool isMouseOverButton,
  35080. bool isButtonDown)
  35081. {
  35082. getLookAndFeel().drawToggleButton (g, *this,
  35083. isMouseOverButton,
  35084. isButtonDown);
  35085. }
  35086. void ToggleButton::changeWidthToFitText()
  35087. {
  35088. getLookAndFeel().changeToggleButtonWidthToFitText (*this);
  35089. }
  35090. void ToggleButton::colourChanged()
  35091. {
  35092. repaint();
  35093. }
  35094. END_JUCE_NAMESPACE
  35095. /*** End of inlined file: juce_ToggleButton.cpp ***/
  35096. /*** Start of inlined file: juce_ToolbarButton.cpp ***/
  35097. BEGIN_JUCE_NAMESPACE
  35098. ToolbarButton::ToolbarButton (const int itemId_,
  35099. const String& buttonText,
  35100. Drawable* const normalImage_,
  35101. Drawable* const toggledOnImage_)
  35102. : ToolbarItemComponent (itemId_, buttonText, true),
  35103. normalImage (normalImage_),
  35104. toggledOnImage (toggledOnImage_)
  35105. {
  35106. jassert (normalImage_ != 0);
  35107. }
  35108. ToolbarButton::~ToolbarButton()
  35109. {
  35110. }
  35111. bool ToolbarButton::getToolbarItemSizes (int toolbarDepth,
  35112. bool /*isToolbarVertical*/,
  35113. int& preferredSize,
  35114. int& minSize, int& maxSize)
  35115. {
  35116. preferredSize = minSize = maxSize = toolbarDepth;
  35117. return true;
  35118. }
  35119. void ToolbarButton::paintButtonArea (Graphics& g,
  35120. int width, int height,
  35121. bool /*isMouseOver*/,
  35122. bool /*isMouseDown*/)
  35123. {
  35124. Drawable* d = normalImage;
  35125. if (getToggleState() && toggledOnImage != 0)
  35126. d = toggledOnImage;
  35127. if (! isEnabled())
  35128. {
  35129. Image im (Image::ARGB, width, height, true);
  35130. {
  35131. Graphics g2 (im);
  35132. d->drawWithin (g2, 0, 0, width, height, RectanglePlacement::centred, 1.0f);
  35133. }
  35134. im.desaturate();
  35135. g.drawImageAt (im, 0, 0);
  35136. }
  35137. else
  35138. {
  35139. d->drawWithin (g, 0, 0, width, height, RectanglePlacement::centred, 1.0f);
  35140. }
  35141. }
  35142. void ToolbarButton::contentAreaChanged (const Rectangle<int>&)
  35143. {
  35144. }
  35145. END_JUCE_NAMESPACE
  35146. /*** End of inlined file: juce_ToolbarButton.cpp ***/
  35147. /*** Start of inlined file: juce_CodeDocument.cpp ***/
  35148. BEGIN_JUCE_NAMESPACE
  35149. class CodeDocumentLine
  35150. {
  35151. public:
  35152. CodeDocumentLine (const juce_wchar* const line_,
  35153. const int lineLength_,
  35154. const int numNewLineChars,
  35155. const int lineStartInFile_)
  35156. : line (line_, lineLength_),
  35157. lineStartInFile (lineStartInFile_),
  35158. lineLength (lineLength_),
  35159. lineLengthWithoutNewLines (lineLength_ - numNewLineChars)
  35160. {
  35161. }
  35162. ~CodeDocumentLine()
  35163. {
  35164. }
  35165. static void createLines (Array <CodeDocumentLine*>& newLines, const String& text)
  35166. {
  35167. const juce_wchar* const t = text;
  35168. int pos = 0;
  35169. while (t [pos] != 0)
  35170. {
  35171. const int startOfLine = pos;
  35172. int numNewLineChars = 0;
  35173. while (t[pos] != 0)
  35174. {
  35175. if (t[pos] == '\r')
  35176. {
  35177. ++numNewLineChars;
  35178. ++pos;
  35179. if (t[pos] == '\n')
  35180. {
  35181. ++numNewLineChars;
  35182. ++pos;
  35183. }
  35184. break;
  35185. }
  35186. if (t[pos] == '\n')
  35187. {
  35188. ++numNewLineChars;
  35189. ++pos;
  35190. break;
  35191. }
  35192. ++pos;
  35193. }
  35194. newLines.add (new CodeDocumentLine (t + startOfLine, pos - startOfLine,
  35195. numNewLineChars, startOfLine));
  35196. }
  35197. jassert (pos == text.length());
  35198. }
  35199. bool endsWithLineBreak() const throw()
  35200. {
  35201. return lineLengthWithoutNewLines != lineLength;
  35202. }
  35203. void updateLength() throw()
  35204. {
  35205. lineLengthWithoutNewLines = lineLength = line.length();
  35206. while (lineLengthWithoutNewLines > 0
  35207. && (line [lineLengthWithoutNewLines - 1] == '\n'
  35208. || line [lineLengthWithoutNewLines - 1] == '\r'))
  35209. {
  35210. --lineLengthWithoutNewLines;
  35211. }
  35212. }
  35213. String line;
  35214. int lineStartInFile, lineLength, lineLengthWithoutNewLines;
  35215. };
  35216. CodeDocument::Iterator::Iterator (CodeDocument* const document_)
  35217. : document (document_),
  35218. currentLine (document_->lines[0]),
  35219. line (0),
  35220. position (0)
  35221. {
  35222. }
  35223. CodeDocument::Iterator::Iterator (const CodeDocument::Iterator& other)
  35224. : document (other.document),
  35225. currentLine (other.currentLine),
  35226. line (other.line),
  35227. position (other.position)
  35228. {
  35229. }
  35230. CodeDocument::Iterator& CodeDocument::Iterator::operator= (const CodeDocument::Iterator& other) throw()
  35231. {
  35232. document = other.document;
  35233. currentLine = other.currentLine;
  35234. line = other.line;
  35235. position = other.position;
  35236. return *this;
  35237. }
  35238. CodeDocument::Iterator::~Iterator() throw()
  35239. {
  35240. }
  35241. juce_wchar CodeDocument::Iterator::nextChar()
  35242. {
  35243. if (currentLine == 0)
  35244. return 0;
  35245. jassert (currentLine == document->lines.getUnchecked (line));
  35246. const juce_wchar result = currentLine->line [position - currentLine->lineStartInFile];
  35247. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  35248. {
  35249. ++line;
  35250. currentLine = document->lines [line];
  35251. }
  35252. return result;
  35253. }
  35254. void CodeDocument::Iterator::skip()
  35255. {
  35256. if (currentLine != 0)
  35257. {
  35258. jassert (currentLine == document->lines.getUnchecked (line));
  35259. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  35260. {
  35261. ++line;
  35262. currentLine = document->lines [line];
  35263. }
  35264. }
  35265. }
  35266. void CodeDocument::Iterator::skipToEndOfLine()
  35267. {
  35268. if (currentLine != 0)
  35269. {
  35270. jassert (currentLine == document->lines.getUnchecked (line));
  35271. ++line;
  35272. currentLine = document->lines [line];
  35273. if (currentLine != 0)
  35274. position = currentLine->lineStartInFile;
  35275. else
  35276. position = document->getNumCharacters();
  35277. }
  35278. }
  35279. juce_wchar CodeDocument::Iterator::peekNextChar() const
  35280. {
  35281. if (currentLine == 0)
  35282. return 0;
  35283. jassert (currentLine == document->lines.getUnchecked (line));
  35284. return const_cast <const String&> (currentLine->line) [position - currentLine->lineStartInFile];
  35285. }
  35286. void CodeDocument::Iterator::skipWhitespace()
  35287. {
  35288. while (CharacterFunctions::isWhitespace (peekNextChar()))
  35289. skip();
  35290. }
  35291. bool CodeDocument::Iterator::isEOF() const throw()
  35292. {
  35293. return currentLine == 0;
  35294. }
  35295. CodeDocument::Position::Position() throw()
  35296. : owner (0), characterPos (0), line (0),
  35297. indexInLine (0), positionMaintained (false)
  35298. {
  35299. }
  35300. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  35301. const int line_, const int indexInLine_) throw()
  35302. : owner (const_cast <CodeDocument*> (ownerDocument)),
  35303. characterPos (0), line (line_),
  35304. indexInLine (indexInLine_), positionMaintained (false)
  35305. {
  35306. setLineAndIndex (line_, indexInLine_);
  35307. }
  35308. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  35309. const int characterPos_) throw()
  35310. : owner (const_cast <CodeDocument*> (ownerDocument)),
  35311. positionMaintained (false)
  35312. {
  35313. setPosition (characterPos_);
  35314. }
  35315. CodeDocument::Position::Position (const Position& other) throw()
  35316. : owner (other.owner), characterPos (other.characterPos), line (other.line),
  35317. indexInLine (other.indexInLine), positionMaintained (false)
  35318. {
  35319. jassert (*this == other);
  35320. }
  35321. CodeDocument::Position::~Position() throw()
  35322. {
  35323. setPositionMaintained (false);
  35324. }
  35325. CodeDocument::Position& CodeDocument::Position::operator= (const Position& other) throw()
  35326. {
  35327. if (this != &other)
  35328. {
  35329. const bool wasPositionMaintained = positionMaintained;
  35330. if (owner != other.owner)
  35331. setPositionMaintained (false);
  35332. owner = other.owner;
  35333. line = other.line;
  35334. indexInLine = other.indexInLine;
  35335. characterPos = other.characterPos;
  35336. setPositionMaintained (wasPositionMaintained);
  35337. jassert (*this == other);
  35338. }
  35339. return *this;
  35340. }
  35341. bool CodeDocument::Position::operator== (const Position& other) const throw()
  35342. {
  35343. jassert ((characterPos == other.characterPos)
  35344. == (line == other.line && indexInLine == other.indexInLine));
  35345. return characterPos == other.characterPos
  35346. && line == other.line
  35347. && indexInLine == other.indexInLine
  35348. && owner == other.owner;
  35349. }
  35350. bool CodeDocument::Position::operator!= (const Position& other) const throw()
  35351. {
  35352. return ! operator== (other);
  35353. }
  35354. void CodeDocument::Position::setLineAndIndex (const int newLine, const int newIndexInLine) throw()
  35355. {
  35356. jassert (owner != 0);
  35357. if (owner->lines.size() == 0)
  35358. {
  35359. line = 0;
  35360. indexInLine = 0;
  35361. characterPos = 0;
  35362. }
  35363. else
  35364. {
  35365. if (newLine >= owner->lines.size())
  35366. {
  35367. line = owner->lines.size() - 1;
  35368. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  35369. jassert (l != 0);
  35370. indexInLine = l->lineLengthWithoutNewLines;
  35371. characterPos = l->lineStartInFile + indexInLine;
  35372. }
  35373. else
  35374. {
  35375. line = jmax (0, newLine);
  35376. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  35377. jassert (l != 0);
  35378. if (l->lineLengthWithoutNewLines > 0)
  35379. indexInLine = jlimit (0, l->lineLengthWithoutNewLines, newIndexInLine);
  35380. else
  35381. indexInLine = 0;
  35382. characterPos = l->lineStartInFile + indexInLine;
  35383. }
  35384. }
  35385. }
  35386. void CodeDocument::Position::setPosition (const int newPosition) throw()
  35387. {
  35388. jassert (owner != 0);
  35389. line = 0;
  35390. indexInLine = 0;
  35391. characterPos = 0;
  35392. if (newPosition > 0)
  35393. {
  35394. int lineStart = 0;
  35395. int lineEnd = owner->lines.size();
  35396. for (;;)
  35397. {
  35398. if (lineEnd - lineStart < 4)
  35399. {
  35400. for (int i = lineStart; i < lineEnd; ++i)
  35401. {
  35402. CodeDocumentLine* const l = owner->lines.getUnchecked (i);
  35403. int index = newPosition - l->lineStartInFile;
  35404. if (index >= 0 && (index < l->lineLength || i == lineEnd - 1))
  35405. {
  35406. line = i;
  35407. indexInLine = jmin (l->lineLengthWithoutNewLines, index);
  35408. characterPos = l->lineStartInFile + indexInLine;
  35409. }
  35410. }
  35411. break;
  35412. }
  35413. else
  35414. {
  35415. const int midIndex = (lineStart + lineEnd + 1) / 2;
  35416. CodeDocumentLine* const mid = owner->lines.getUnchecked (midIndex);
  35417. if (newPosition >= mid->lineStartInFile)
  35418. lineStart = midIndex;
  35419. else
  35420. lineEnd = midIndex;
  35421. }
  35422. }
  35423. }
  35424. }
  35425. void CodeDocument::Position::moveBy (int characterDelta) throw()
  35426. {
  35427. jassert (owner != 0);
  35428. if (characterDelta == 1)
  35429. {
  35430. setPosition (getPosition());
  35431. // If moving right, make sure we don't get stuck between the \r and \n characters..
  35432. if (line < owner->lines.size())
  35433. {
  35434. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  35435. if (indexInLine + characterDelta < l->lineLength
  35436. && indexInLine + characterDelta >= l->lineLengthWithoutNewLines + 1)
  35437. ++characterDelta;
  35438. }
  35439. }
  35440. setPosition (characterPos + characterDelta);
  35441. }
  35442. const CodeDocument::Position CodeDocument::Position::movedBy (const int characterDelta) const throw()
  35443. {
  35444. CodeDocument::Position p (*this);
  35445. p.moveBy (characterDelta);
  35446. return p;
  35447. }
  35448. const CodeDocument::Position CodeDocument::Position::movedByLines (const int deltaLines) const throw()
  35449. {
  35450. CodeDocument::Position p (*this);
  35451. p.setLineAndIndex (getLineNumber() + deltaLines, getIndexInLine());
  35452. return p;
  35453. }
  35454. const juce_wchar CodeDocument::Position::getCharacter() const throw()
  35455. {
  35456. const CodeDocumentLine* const l = owner->lines [line];
  35457. return l == 0 ? 0 : l->line [getIndexInLine()];
  35458. }
  35459. const String CodeDocument::Position::getLineText() const throw()
  35460. {
  35461. const CodeDocumentLine* const l = owner->lines [line];
  35462. return l == 0 ? String::empty : l->line;
  35463. }
  35464. void CodeDocument::Position::setPositionMaintained (const bool isMaintained) throw()
  35465. {
  35466. if (isMaintained != positionMaintained)
  35467. {
  35468. positionMaintained = isMaintained;
  35469. if (owner != 0)
  35470. {
  35471. if (isMaintained)
  35472. {
  35473. jassert (! owner->positionsToMaintain.contains (this));
  35474. owner->positionsToMaintain.add (this);
  35475. }
  35476. else
  35477. {
  35478. // If this happens, you may have deleted the document while there are Position objects that are still using it...
  35479. jassert (owner->positionsToMaintain.contains (this));
  35480. owner->positionsToMaintain.removeValue (this);
  35481. }
  35482. }
  35483. }
  35484. }
  35485. CodeDocument::CodeDocument()
  35486. : undoManager (std::numeric_limits<int>::max(), 10000),
  35487. currentActionIndex (0),
  35488. indexOfSavedState (-1),
  35489. maximumLineLength (-1),
  35490. newLineChars ("\r\n")
  35491. {
  35492. }
  35493. CodeDocument::~CodeDocument()
  35494. {
  35495. }
  35496. const String CodeDocument::getAllContent() const throw()
  35497. {
  35498. return getTextBetween (Position (this, 0),
  35499. Position (this, lines.size(), 0));
  35500. }
  35501. const String CodeDocument::getTextBetween (const Position& start, const Position& end) const throw()
  35502. {
  35503. if (end.getPosition() <= start.getPosition())
  35504. return String::empty;
  35505. const int startLine = start.getLineNumber();
  35506. const int endLine = end.getLineNumber();
  35507. if (startLine == endLine)
  35508. {
  35509. CodeDocumentLine* const line = lines [startLine];
  35510. return (line == 0) ? String::empty : line->line.substring (start.getIndexInLine(), end.getIndexInLine());
  35511. }
  35512. String result;
  35513. result.preallocateStorage (end.getPosition() - start.getPosition() + 4);
  35514. String::Concatenator concatenator (result);
  35515. const int maxLine = jmin (lines.size() - 1, endLine);
  35516. for (int i = jmax (0, startLine); i <= maxLine; ++i)
  35517. {
  35518. const CodeDocumentLine* line = lines.getUnchecked(i);
  35519. int len = line->lineLength;
  35520. if (i == startLine)
  35521. {
  35522. const int index = start.getIndexInLine();
  35523. concatenator.append (line->line.substring (index, len));
  35524. }
  35525. else if (i == endLine)
  35526. {
  35527. len = end.getIndexInLine();
  35528. concatenator.append (line->line.substring (0, len));
  35529. }
  35530. else
  35531. {
  35532. concatenator.append (line->line);
  35533. }
  35534. }
  35535. return result;
  35536. }
  35537. int CodeDocument::getNumCharacters() const throw()
  35538. {
  35539. const CodeDocumentLine* const lastLine = lines.getLast();
  35540. return (lastLine == 0) ? 0 : lastLine->lineStartInFile + lastLine->lineLength;
  35541. }
  35542. const String CodeDocument::getLine (const int lineIndex) const throw()
  35543. {
  35544. const CodeDocumentLine* const line = lines [lineIndex];
  35545. return (line == 0) ? String::empty : line->line;
  35546. }
  35547. int CodeDocument::getMaximumLineLength() throw()
  35548. {
  35549. if (maximumLineLength < 0)
  35550. {
  35551. maximumLineLength = 0;
  35552. for (int i = lines.size(); --i >= 0;)
  35553. maximumLineLength = jmax (maximumLineLength, lines.getUnchecked(i)->lineLength);
  35554. }
  35555. return maximumLineLength;
  35556. }
  35557. void CodeDocument::deleteSection (const Position& startPosition, const Position& endPosition)
  35558. {
  35559. remove (startPosition.getPosition(), endPosition.getPosition(), true);
  35560. }
  35561. void CodeDocument::insertText (const Position& position, const String& text)
  35562. {
  35563. insert (text, position.getPosition(), true);
  35564. }
  35565. void CodeDocument::replaceAllContent (const String& newContent)
  35566. {
  35567. remove (0, getNumCharacters(), true);
  35568. insert (newContent, 0, true);
  35569. }
  35570. bool CodeDocument::loadFromStream (InputStream& stream)
  35571. {
  35572. replaceAllContent (stream.readEntireStreamAsString());
  35573. setSavePoint();
  35574. clearUndoHistory();
  35575. return true;
  35576. }
  35577. bool CodeDocument::writeToStream (OutputStream& stream)
  35578. {
  35579. for (int i = 0; i < lines.size(); ++i)
  35580. {
  35581. String temp (lines.getUnchecked(i)->line); // use a copy to avoid bloating the memory footprint of the stored string.
  35582. const char* utf8 = temp.toUTF8();
  35583. if (! stream.write (utf8, (int) strlen (utf8)))
  35584. return false;
  35585. }
  35586. return true;
  35587. }
  35588. void CodeDocument::setNewLineCharacters (const String& newLine) throw()
  35589. {
  35590. jassert (newLine == "\r\n" || newLine == "\n" || newLine == "\r");
  35591. newLineChars = newLine;
  35592. }
  35593. void CodeDocument::newTransaction()
  35594. {
  35595. undoManager.beginNewTransaction (String::empty);
  35596. }
  35597. void CodeDocument::undo()
  35598. {
  35599. newTransaction();
  35600. undoManager.undo();
  35601. }
  35602. void CodeDocument::redo()
  35603. {
  35604. undoManager.redo();
  35605. }
  35606. void CodeDocument::clearUndoHistory()
  35607. {
  35608. undoManager.clearUndoHistory();
  35609. }
  35610. void CodeDocument::setSavePoint() throw()
  35611. {
  35612. indexOfSavedState = currentActionIndex;
  35613. }
  35614. bool CodeDocument::hasChangedSinceSavePoint() const throw()
  35615. {
  35616. return currentActionIndex != indexOfSavedState;
  35617. }
  35618. static int getCodeCharacterCategory (const juce_wchar character) throw()
  35619. {
  35620. return (CharacterFunctions::isLetterOrDigit (character) || character == '_')
  35621. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  35622. }
  35623. const CodeDocument::Position CodeDocument::findWordBreakAfter (const Position& position) const throw()
  35624. {
  35625. Position p (position);
  35626. const int maxDistance = 256;
  35627. int i = 0;
  35628. while (i < maxDistance
  35629. && CharacterFunctions::isWhitespace (p.getCharacter())
  35630. && (i == 0 || (p.getCharacter() != '\n'
  35631. && p.getCharacter() != '\r')))
  35632. {
  35633. ++i;
  35634. p.moveBy (1);
  35635. }
  35636. if (i == 0)
  35637. {
  35638. const int type = getCodeCharacterCategory (p.getCharacter());
  35639. while (i < maxDistance && type == getCodeCharacterCategory (p.getCharacter()))
  35640. {
  35641. ++i;
  35642. p.moveBy (1);
  35643. }
  35644. while (i < maxDistance
  35645. && CharacterFunctions::isWhitespace (p.getCharacter())
  35646. && (i == 0 || (p.getCharacter() != '\n'
  35647. && p.getCharacter() != '\r')))
  35648. {
  35649. ++i;
  35650. p.moveBy (1);
  35651. }
  35652. }
  35653. return p;
  35654. }
  35655. const CodeDocument::Position CodeDocument::findWordBreakBefore (const Position& position) const throw()
  35656. {
  35657. Position p (position);
  35658. const int maxDistance = 256;
  35659. int i = 0;
  35660. bool stoppedAtLineStart = false;
  35661. while (i < maxDistance)
  35662. {
  35663. const juce_wchar c = p.movedBy (-1).getCharacter();
  35664. if (c == '\r' || c == '\n')
  35665. {
  35666. stoppedAtLineStart = true;
  35667. if (i > 0)
  35668. break;
  35669. }
  35670. if (! CharacterFunctions::isWhitespace (c))
  35671. break;
  35672. p.moveBy (-1);
  35673. ++i;
  35674. }
  35675. if (i < maxDistance && ! stoppedAtLineStart)
  35676. {
  35677. const int type = getCodeCharacterCategory (p.movedBy (-1).getCharacter());
  35678. while (i < maxDistance && type == getCodeCharacterCategory (p.movedBy (-1).getCharacter()))
  35679. {
  35680. p.moveBy (-1);
  35681. ++i;
  35682. }
  35683. }
  35684. return p;
  35685. }
  35686. void CodeDocument::checkLastLineStatus()
  35687. {
  35688. while (lines.size() > 0
  35689. && lines.getLast()->lineLength == 0
  35690. && (lines.size() == 1 || ! lines.getUnchecked (lines.size() - 2)->endsWithLineBreak()))
  35691. {
  35692. // remove any empty lines at the end if the preceding line doesn't end in a newline.
  35693. lines.removeLast();
  35694. }
  35695. const CodeDocumentLine* const lastLine = lines.getLast();
  35696. if (lastLine != 0 && lastLine->endsWithLineBreak())
  35697. {
  35698. // check that there's an empty line at the end if the preceding one ends in a newline..
  35699. lines.add (new CodeDocumentLine (String::empty, 0, 0, lastLine->lineStartInFile + lastLine->lineLength));
  35700. }
  35701. }
  35702. void CodeDocument::addListener (CodeDocument::Listener* const listener) throw()
  35703. {
  35704. listeners.add (listener);
  35705. }
  35706. void CodeDocument::removeListener (CodeDocument::Listener* const listener) throw()
  35707. {
  35708. listeners.remove (listener);
  35709. }
  35710. void CodeDocument::sendListenerChangeMessage (const int startLine, const int endLine)
  35711. {
  35712. Position startPos (this, startLine, 0);
  35713. Position endPos (this, endLine, 0);
  35714. listeners.call (&Listener::codeDocumentChanged, startPos, endPos);
  35715. }
  35716. class CodeDocumentInsertAction : public UndoableAction
  35717. {
  35718. CodeDocument& owner;
  35719. const String text;
  35720. int insertPos;
  35721. CodeDocumentInsertAction (const CodeDocumentInsertAction&);
  35722. CodeDocumentInsertAction& operator= (const CodeDocumentInsertAction&);
  35723. public:
  35724. CodeDocumentInsertAction (CodeDocument& owner_, const String& text_, const int insertPos_) throw()
  35725. : owner (owner_),
  35726. text (text_),
  35727. insertPos (insertPos_)
  35728. {
  35729. }
  35730. ~CodeDocumentInsertAction() {}
  35731. bool perform()
  35732. {
  35733. owner.currentActionIndex++;
  35734. owner.insert (text, insertPos, false);
  35735. return true;
  35736. }
  35737. bool undo()
  35738. {
  35739. owner.currentActionIndex--;
  35740. owner.remove (insertPos, insertPos + text.length(), false);
  35741. return true;
  35742. }
  35743. int getSizeInUnits() { return text.length() + 32; }
  35744. };
  35745. void CodeDocument::insert (const String& text, const int insertPos, const bool undoable)
  35746. {
  35747. if (text.isEmpty())
  35748. return;
  35749. if (undoable)
  35750. {
  35751. undoManager.perform (new CodeDocumentInsertAction (*this, text, insertPos));
  35752. }
  35753. else
  35754. {
  35755. Position pos (this, insertPos);
  35756. const int firstAffectedLine = pos.getLineNumber();
  35757. int lastAffectedLine = firstAffectedLine + 1;
  35758. CodeDocumentLine* const firstLine = lines [firstAffectedLine];
  35759. String textInsideOriginalLine (text);
  35760. if (firstLine != 0)
  35761. {
  35762. const int index = pos.getIndexInLine();
  35763. textInsideOriginalLine = firstLine->line.substring (0, index)
  35764. + textInsideOriginalLine
  35765. + firstLine->line.substring (index);
  35766. }
  35767. maximumLineLength = -1;
  35768. Array <CodeDocumentLine*> newLines;
  35769. CodeDocumentLine::createLines (newLines, textInsideOriginalLine);
  35770. jassert (newLines.size() > 0);
  35771. CodeDocumentLine* const newFirstLine = newLines.getUnchecked (0);
  35772. newFirstLine->lineStartInFile = firstLine != 0 ? firstLine->lineStartInFile : 0;
  35773. lines.set (firstAffectedLine, newFirstLine);
  35774. if (newLines.size() > 1)
  35775. {
  35776. for (int i = 1; i < newLines.size(); ++i)
  35777. {
  35778. CodeDocumentLine* const l = newLines.getUnchecked (i);
  35779. lines.insert (firstAffectedLine + i, l);
  35780. }
  35781. lastAffectedLine = lines.size();
  35782. }
  35783. int i, lineStart = newFirstLine->lineStartInFile;
  35784. for (i = firstAffectedLine; i < lines.size(); ++i)
  35785. {
  35786. CodeDocumentLine* const l = lines.getUnchecked (i);
  35787. l->lineStartInFile = lineStart;
  35788. lineStart += l->lineLength;
  35789. }
  35790. checkLastLineStatus();
  35791. const int newTextLength = text.length();
  35792. for (i = 0; i < positionsToMaintain.size(); ++i)
  35793. {
  35794. CodeDocument::Position* const p = positionsToMaintain.getUnchecked(i);
  35795. if (p->getPosition() >= insertPos)
  35796. p->setPosition (p->getPosition() + newTextLength);
  35797. }
  35798. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  35799. }
  35800. }
  35801. class CodeDocumentDeleteAction : public UndoableAction
  35802. {
  35803. CodeDocument& owner;
  35804. int startPos, endPos;
  35805. String removedText;
  35806. CodeDocumentDeleteAction (const CodeDocumentDeleteAction&);
  35807. CodeDocumentDeleteAction& operator= (const CodeDocumentDeleteAction&);
  35808. public:
  35809. CodeDocumentDeleteAction (CodeDocument& owner_, const int startPos_, const int endPos_) throw()
  35810. : owner (owner_),
  35811. startPos (startPos_),
  35812. endPos (endPos_)
  35813. {
  35814. removedText = owner.getTextBetween (CodeDocument::Position (&owner, startPos),
  35815. CodeDocument::Position (&owner, endPos));
  35816. }
  35817. ~CodeDocumentDeleteAction() {}
  35818. bool perform()
  35819. {
  35820. owner.currentActionIndex++;
  35821. owner.remove (startPos, endPos, false);
  35822. return true;
  35823. }
  35824. bool undo()
  35825. {
  35826. owner.currentActionIndex--;
  35827. owner.insert (removedText, startPos, false);
  35828. return true;
  35829. }
  35830. int getSizeInUnits() { return removedText.length() + 32; }
  35831. };
  35832. void CodeDocument::remove (const int startPos, const int endPos, const bool undoable)
  35833. {
  35834. if (endPos <= startPos)
  35835. return;
  35836. if (undoable)
  35837. {
  35838. undoManager.perform (new CodeDocumentDeleteAction (*this, startPos, endPos));
  35839. }
  35840. else
  35841. {
  35842. Position startPosition (this, startPos);
  35843. Position endPosition (this, endPos);
  35844. maximumLineLength = -1;
  35845. const int firstAffectedLine = startPosition.getLineNumber();
  35846. const int endLine = endPosition.getLineNumber();
  35847. int lastAffectedLine = firstAffectedLine + 1;
  35848. CodeDocumentLine* const firstLine = lines.getUnchecked (firstAffectedLine);
  35849. if (firstAffectedLine == endLine)
  35850. {
  35851. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  35852. + firstLine->line.substring (endPosition.getIndexInLine());
  35853. firstLine->updateLength();
  35854. }
  35855. else
  35856. {
  35857. lastAffectedLine = lines.size();
  35858. CodeDocumentLine* const lastLine = lines.getUnchecked (endLine);
  35859. jassert (lastLine != 0);
  35860. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  35861. + lastLine->line.substring (endPosition.getIndexInLine());
  35862. firstLine->updateLength();
  35863. int numLinesToRemove = endLine - firstAffectedLine;
  35864. lines.removeRange (firstAffectedLine + 1, numLinesToRemove);
  35865. }
  35866. int i;
  35867. for (i = firstAffectedLine + 1; i < lines.size(); ++i)
  35868. {
  35869. CodeDocumentLine* const l = lines.getUnchecked (i);
  35870. const CodeDocumentLine* const previousLine = lines.getUnchecked (i - 1);
  35871. l->lineStartInFile = previousLine->lineStartInFile + previousLine->lineLength;
  35872. }
  35873. checkLastLineStatus();
  35874. const int totalChars = getNumCharacters();
  35875. for (i = 0; i < positionsToMaintain.size(); ++i)
  35876. {
  35877. CodeDocument::Position* p = positionsToMaintain.getUnchecked(i);
  35878. if (p->getPosition() > startPosition.getPosition())
  35879. p->setPosition (jmax (startPos, p->getPosition() + startPos - endPos));
  35880. if (p->getPosition() > totalChars)
  35881. p->setPosition (totalChars);
  35882. }
  35883. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  35884. }
  35885. }
  35886. END_JUCE_NAMESPACE
  35887. /*** End of inlined file: juce_CodeDocument.cpp ***/
  35888. /*** Start of inlined file: juce_CodeEditorComponent.cpp ***/
  35889. BEGIN_JUCE_NAMESPACE
  35890. class CodeEditorComponent::CaretComponent : public Component,
  35891. public Timer
  35892. {
  35893. public:
  35894. CaretComponent (CodeEditorComponent& owner_)
  35895. : owner (owner_)
  35896. {
  35897. setAlwaysOnTop (true);
  35898. setInterceptsMouseClicks (false, false);
  35899. }
  35900. ~CaretComponent()
  35901. {
  35902. }
  35903. void paint (Graphics& g)
  35904. {
  35905. g.fillAll (findColour (CodeEditorComponent::caretColourId));
  35906. }
  35907. void timerCallback()
  35908. {
  35909. setVisible (shouldBeShown() && ! isVisible());
  35910. }
  35911. void updatePosition()
  35912. {
  35913. startTimer (400);
  35914. setVisible (shouldBeShown());
  35915. setBounds (owner.getCharacterBounds (owner.getCaretPos()).withWidth (2));
  35916. }
  35917. private:
  35918. CodeEditorComponent& owner;
  35919. CaretComponent (const CaretComponent&);
  35920. CaretComponent& operator= (const CaretComponent&);
  35921. bool shouldBeShown() const { return owner.hasKeyboardFocus (true); }
  35922. };
  35923. class CodeEditorComponent::CodeEditorLine
  35924. {
  35925. public:
  35926. CodeEditorLine() throw()
  35927. : highlightColumnStart (0), highlightColumnEnd (0)
  35928. {
  35929. }
  35930. ~CodeEditorLine() throw()
  35931. {
  35932. }
  35933. bool update (CodeDocument& document, int lineNum,
  35934. CodeDocument::Iterator& source,
  35935. CodeTokeniser* analyser, const int spacesPerTab,
  35936. const CodeDocument::Position& selectionStart,
  35937. const CodeDocument::Position& selectionEnd)
  35938. {
  35939. Array <SyntaxToken> newTokens;
  35940. newTokens.ensureStorageAllocated (8);
  35941. if (analyser == 0)
  35942. {
  35943. newTokens.add (SyntaxToken (document.getLine (lineNum), -1));
  35944. }
  35945. else if (lineNum < document.getNumLines())
  35946. {
  35947. const CodeDocument::Position pos (&document, lineNum, 0);
  35948. createTokens (pos.getPosition(), pos.getLineText(),
  35949. source, analyser, newTokens);
  35950. }
  35951. replaceTabsWithSpaces (newTokens, spacesPerTab);
  35952. int newHighlightStart = 0;
  35953. int newHighlightEnd = 0;
  35954. if (selectionStart.getLineNumber() <= lineNum && selectionEnd.getLineNumber() >= lineNum)
  35955. {
  35956. const String line (document.getLine (lineNum));
  35957. CodeDocument::Position lineStart (&document, lineNum, 0), lineEnd (&document, lineNum + 1, 0);
  35958. newHighlightStart = indexToColumn (jmax (0, selectionStart.getPosition() - lineStart.getPosition()),
  35959. line, spacesPerTab);
  35960. newHighlightEnd = indexToColumn (jmin (lineEnd.getPosition() - lineStart.getPosition(), selectionEnd.getPosition() - lineStart.getPosition()),
  35961. line, spacesPerTab);
  35962. }
  35963. if (newHighlightStart != highlightColumnStart || newHighlightEnd != highlightColumnEnd)
  35964. {
  35965. highlightColumnStart = newHighlightStart;
  35966. highlightColumnEnd = newHighlightEnd;
  35967. }
  35968. else
  35969. {
  35970. if (tokens.size() == newTokens.size())
  35971. {
  35972. bool allTheSame = true;
  35973. for (int i = newTokens.size(); --i >= 0;)
  35974. {
  35975. if (tokens.getReference(i) != newTokens.getReference(i))
  35976. {
  35977. allTheSame = false;
  35978. break;
  35979. }
  35980. }
  35981. if (allTheSame)
  35982. return false;
  35983. }
  35984. }
  35985. tokens.swapWithArray (newTokens);
  35986. return true;
  35987. }
  35988. void draw (CodeEditorComponent& owner, Graphics& g, const Font& font,
  35989. float x, const int y, const int baselineOffset, const int lineHeight,
  35990. const Colour& highlightColour) const throw()
  35991. {
  35992. if (highlightColumnStart < highlightColumnEnd)
  35993. {
  35994. g.setColour (highlightColour);
  35995. g.fillRect (roundToInt (x + highlightColumnStart * owner.getCharWidth()), y,
  35996. roundToInt ((highlightColumnEnd - highlightColumnStart) * owner.getCharWidth()), lineHeight);
  35997. }
  35998. int lastType = std::numeric_limits<int>::min();
  35999. for (int i = 0; i < tokens.size(); ++i)
  36000. {
  36001. SyntaxToken& token = tokens.getReference(i);
  36002. if (lastType != token.tokenType)
  36003. {
  36004. lastType = token.tokenType;
  36005. g.setColour (owner.getColourForTokenType (lastType));
  36006. }
  36007. g.drawSingleLineText (token.text, roundToInt (x), y + baselineOffset);
  36008. if (i < tokens.size() - 1)
  36009. {
  36010. if (token.width < 0)
  36011. token.width = font.getStringWidthFloat (token.text);
  36012. x += token.width;
  36013. }
  36014. }
  36015. }
  36016. private:
  36017. struct SyntaxToken
  36018. {
  36019. String text;
  36020. int tokenType;
  36021. float width;
  36022. SyntaxToken (const String& text_, const int type) throw()
  36023. : text (text_), tokenType (type), width (-1.0f)
  36024. {
  36025. }
  36026. bool operator!= (const SyntaxToken& other) const throw()
  36027. {
  36028. return text != other.text || tokenType != other.tokenType;
  36029. }
  36030. };
  36031. Array <SyntaxToken> tokens;
  36032. int highlightColumnStart, highlightColumnEnd;
  36033. static void createTokens (int startPosition, const String& lineText,
  36034. CodeDocument::Iterator& source,
  36035. CodeTokeniser* analyser,
  36036. Array <SyntaxToken>& newTokens)
  36037. {
  36038. CodeDocument::Iterator lastIterator (source);
  36039. const int lineLength = lineText.length();
  36040. for (;;)
  36041. {
  36042. int tokenType = analyser->readNextToken (source);
  36043. int tokenStart = lastIterator.getPosition();
  36044. int tokenEnd = source.getPosition();
  36045. if (tokenEnd <= tokenStart)
  36046. break;
  36047. tokenEnd -= startPosition;
  36048. if (tokenEnd > 0)
  36049. {
  36050. tokenStart -= startPosition;
  36051. newTokens.add (SyntaxToken (lineText.substring (jmax (0, tokenStart), tokenEnd),
  36052. tokenType));
  36053. if (tokenEnd >= lineLength)
  36054. break;
  36055. }
  36056. lastIterator = source;
  36057. }
  36058. source = lastIterator;
  36059. }
  36060. static void replaceTabsWithSpaces (Array <SyntaxToken>& tokens, const int spacesPerTab) throw()
  36061. {
  36062. int x = 0;
  36063. for (int i = 0; i < tokens.size(); ++i)
  36064. {
  36065. SyntaxToken& t = tokens.getReference(i);
  36066. for (;;)
  36067. {
  36068. int tabPos = t.text.indexOfChar ('\t');
  36069. if (tabPos < 0)
  36070. break;
  36071. const int spacesNeeded = spacesPerTab - ((tabPos + x) % spacesPerTab);
  36072. t.text = t.text.replaceSection (tabPos, 1, String::repeatedString (" ", spacesNeeded));
  36073. }
  36074. x += t.text.length();
  36075. }
  36076. }
  36077. int indexToColumn (int index, const String& line, int spacesPerTab) const throw()
  36078. {
  36079. jassert (index <= line.length());
  36080. int col = 0;
  36081. for (int i = 0; i < index; ++i)
  36082. {
  36083. if (line[i] != '\t')
  36084. ++col;
  36085. else
  36086. col += spacesPerTab - (col % spacesPerTab);
  36087. }
  36088. return col;
  36089. }
  36090. };
  36091. CodeEditorComponent::CodeEditorComponent (CodeDocument& document_,
  36092. CodeTokeniser* const codeTokeniser_)
  36093. : document (document_),
  36094. firstLineOnScreen (0),
  36095. gutter (5),
  36096. spacesPerTab (4),
  36097. lineHeight (0),
  36098. linesOnScreen (0),
  36099. columnsOnScreen (0),
  36100. scrollbarThickness (16),
  36101. columnToTryToMaintain (-1),
  36102. useSpacesForTabs (false),
  36103. xOffset (0),
  36104. codeTokeniser (codeTokeniser_)
  36105. {
  36106. caretPos = CodeDocument::Position (&document_, 0, 0);
  36107. caretPos.setPositionMaintained (true);
  36108. selectionStart = CodeDocument::Position (&document_, 0, 0);
  36109. selectionStart.setPositionMaintained (true);
  36110. selectionEnd = CodeDocument::Position (&document_, 0, 0);
  36111. selectionEnd.setPositionMaintained (true);
  36112. setOpaque (true);
  36113. setMouseCursor (MouseCursor (MouseCursor::IBeamCursor));
  36114. setWantsKeyboardFocus (true);
  36115. addAndMakeVisible (verticalScrollBar = new ScrollBar (true));
  36116. verticalScrollBar->setSingleStepSize (1.0);
  36117. addAndMakeVisible (horizontalScrollBar = new ScrollBar (false));
  36118. horizontalScrollBar->setSingleStepSize (1.0);
  36119. addAndMakeVisible (caret = new CaretComponent (*this));
  36120. Font f (12.0f);
  36121. f.setTypefaceName (Font::getDefaultMonospacedFontName());
  36122. setFont (f);
  36123. resetToDefaultColours();
  36124. verticalScrollBar->addListener (this);
  36125. horizontalScrollBar->addListener (this);
  36126. document.addListener (this);
  36127. }
  36128. CodeEditorComponent::~CodeEditorComponent()
  36129. {
  36130. document.removeListener (this);
  36131. deleteAllChildren();
  36132. }
  36133. void CodeEditorComponent::loadContent (const String& newContent)
  36134. {
  36135. clearCachedIterators (0);
  36136. document.replaceAllContent (newContent);
  36137. document.clearUndoHistory();
  36138. document.setSavePoint();
  36139. caretPos.setPosition (0);
  36140. selectionStart.setPosition (0);
  36141. selectionEnd.setPosition (0);
  36142. scrollToLine (0);
  36143. }
  36144. bool CodeEditorComponent::isTextInputActive() const
  36145. {
  36146. return true;
  36147. }
  36148. void CodeEditorComponent::codeDocumentChanged (const CodeDocument::Position& affectedTextStart,
  36149. const CodeDocument::Position& affectedTextEnd)
  36150. {
  36151. clearCachedIterators (affectedTextStart.getLineNumber());
  36152. triggerAsyncUpdate();
  36153. caret->updatePosition();
  36154. columnToTryToMaintain = -1;
  36155. if (affectedTextEnd.getPosition() >= selectionStart.getPosition()
  36156. && affectedTextStart.getPosition() <= selectionEnd.getPosition())
  36157. deselectAll();
  36158. if (caretPos.getPosition() > affectedTextEnd.getPosition()
  36159. || caretPos.getPosition() < affectedTextStart.getPosition())
  36160. moveCaretTo (affectedTextStart, false);
  36161. updateScrollBars();
  36162. }
  36163. void CodeEditorComponent::resized()
  36164. {
  36165. linesOnScreen = (getHeight() - scrollbarThickness) / lineHeight;
  36166. columnsOnScreen = (int) ((getWidth() - scrollbarThickness) / charWidth);
  36167. lines.clear();
  36168. rebuildLineTokens();
  36169. caret->updatePosition();
  36170. verticalScrollBar->setBounds (getWidth() - scrollbarThickness, 0, scrollbarThickness, getHeight() - scrollbarThickness);
  36171. horizontalScrollBar->setBounds (gutter, getHeight() - scrollbarThickness, getWidth() - scrollbarThickness - gutter, scrollbarThickness);
  36172. updateScrollBars();
  36173. }
  36174. void CodeEditorComponent::paint (Graphics& g)
  36175. {
  36176. handleUpdateNowIfNeeded();
  36177. g.fillAll (findColour (CodeEditorComponent::backgroundColourId));
  36178. g.reduceClipRegion (gutter, 0, verticalScrollBar->getX() - gutter, horizontalScrollBar->getY());
  36179. g.setFont (font);
  36180. const int baselineOffset = (int) font.getAscent();
  36181. const Colour defaultColour (findColour (CodeEditorComponent::defaultTextColourId));
  36182. const Colour highlightColour (findColour (CodeEditorComponent::highlightColourId));
  36183. const Rectangle<int> clip (g.getClipBounds());
  36184. const int firstLineToDraw = jmax (0, clip.getY() / lineHeight);
  36185. const int lastLineToDraw = jmin (lines.size(), clip.getBottom() / lineHeight + 1);
  36186. for (int j = firstLineToDraw; j < lastLineToDraw; ++j)
  36187. {
  36188. lines.getUnchecked(j)->draw (*this, g, font,
  36189. (float) (gutter - xOffset * charWidth),
  36190. lineHeight * j, baselineOffset, lineHeight,
  36191. highlightColour);
  36192. }
  36193. }
  36194. void CodeEditorComponent::setScrollbarThickness (const int thickness) throw()
  36195. {
  36196. if (scrollbarThickness != thickness)
  36197. {
  36198. scrollbarThickness = thickness;
  36199. resized();
  36200. }
  36201. }
  36202. void CodeEditorComponent::handleAsyncUpdate()
  36203. {
  36204. rebuildLineTokens();
  36205. }
  36206. void CodeEditorComponent::rebuildLineTokens()
  36207. {
  36208. cancelPendingUpdate();
  36209. const int numNeeded = linesOnScreen + 1;
  36210. int minLineToRepaint = numNeeded;
  36211. int maxLineToRepaint = 0;
  36212. if (numNeeded != lines.size())
  36213. {
  36214. lines.clear();
  36215. for (int i = numNeeded; --i >= 0;)
  36216. lines.add (new CodeEditorLine());
  36217. minLineToRepaint = 0;
  36218. maxLineToRepaint = numNeeded;
  36219. }
  36220. jassert (numNeeded == lines.size());
  36221. CodeDocument::Iterator source (&document);
  36222. getIteratorForPosition (CodeDocument::Position (&document, firstLineOnScreen, 0).getPosition(), source);
  36223. for (int i = 0; i < numNeeded; ++i)
  36224. {
  36225. CodeEditorLine* const line = lines.getUnchecked(i);
  36226. if (line->update (document, firstLineOnScreen + i, source, codeTokeniser, spacesPerTab,
  36227. selectionStart, selectionEnd))
  36228. {
  36229. minLineToRepaint = jmin (minLineToRepaint, i);
  36230. maxLineToRepaint = jmax (maxLineToRepaint, i);
  36231. }
  36232. }
  36233. if (minLineToRepaint <= maxLineToRepaint)
  36234. {
  36235. repaint (gutter, lineHeight * minLineToRepaint - 1,
  36236. verticalScrollBar->getX() - gutter,
  36237. lineHeight * (1 + maxLineToRepaint - minLineToRepaint) + 2);
  36238. }
  36239. }
  36240. void CodeEditorComponent::moveCaretTo (const CodeDocument::Position& newPos, const bool highlighting)
  36241. {
  36242. caretPos = newPos;
  36243. columnToTryToMaintain = -1;
  36244. if (highlighting)
  36245. {
  36246. if (dragType == notDragging)
  36247. {
  36248. if (abs (caretPos.getPosition() - selectionStart.getPosition())
  36249. < abs (caretPos.getPosition() - selectionEnd.getPosition()))
  36250. dragType = draggingSelectionStart;
  36251. else
  36252. dragType = draggingSelectionEnd;
  36253. }
  36254. if (dragType == draggingSelectionStart)
  36255. {
  36256. selectionStart = caretPos;
  36257. if (selectionEnd.getPosition() < selectionStart.getPosition())
  36258. {
  36259. const CodeDocument::Position temp (selectionStart);
  36260. selectionStart = selectionEnd;
  36261. selectionEnd = temp;
  36262. dragType = draggingSelectionEnd;
  36263. }
  36264. }
  36265. else
  36266. {
  36267. selectionEnd = caretPos;
  36268. if (selectionEnd.getPosition() < selectionStart.getPosition())
  36269. {
  36270. const CodeDocument::Position temp (selectionStart);
  36271. selectionStart = selectionEnd;
  36272. selectionEnd = temp;
  36273. dragType = draggingSelectionStart;
  36274. }
  36275. }
  36276. triggerAsyncUpdate();
  36277. }
  36278. else
  36279. {
  36280. deselectAll();
  36281. }
  36282. caret->updatePosition();
  36283. scrollToKeepCaretOnScreen();
  36284. updateScrollBars();
  36285. }
  36286. void CodeEditorComponent::deselectAll()
  36287. {
  36288. if (selectionStart != selectionEnd)
  36289. triggerAsyncUpdate();
  36290. selectionStart = caretPos;
  36291. selectionEnd = caretPos;
  36292. }
  36293. void CodeEditorComponent::updateScrollBars()
  36294. {
  36295. verticalScrollBar->setRangeLimits (0, jmax (document.getNumLines(), firstLineOnScreen + linesOnScreen));
  36296. verticalScrollBar->setCurrentRange (firstLineOnScreen, linesOnScreen);
  36297. horizontalScrollBar->setRangeLimits (0, jmax ((double) document.getMaximumLineLength(), xOffset + columnsOnScreen));
  36298. horizontalScrollBar->setCurrentRange (xOffset, columnsOnScreen);
  36299. }
  36300. void CodeEditorComponent::scrollToLineInternal (int newFirstLineOnScreen)
  36301. {
  36302. newFirstLineOnScreen = jlimit (0, jmax (0, document.getNumLines() - 1),
  36303. newFirstLineOnScreen);
  36304. if (newFirstLineOnScreen != firstLineOnScreen)
  36305. {
  36306. firstLineOnScreen = newFirstLineOnScreen;
  36307. caret->updatePosition();
  36308. updateCachedIterators (firstLineOnScreen);
  36309. triggerAsyncUpdate();
  36310. }
  36311. }
  36312. void CodeEditorComponent::scrollToColumnInternal (double column)
  36313. {
  36314. const double newOffset = jlimit (0.0, document.getMaximumLineLength() + 3.0, column);
  36315. if (xOffset != newOffset)
  36316. {
  36317. xOffset = newOffset;
  36318. caret->updatePosition();
  36319. repaint();
  36320. }
  36321. }
  36322. void CodeEditorComponent::scrollToLine (int newFirstLineOnScreen)
  36323. {
  36324. scrollToLineInternal (newFirstLineOnScreen);
  36325. updateScrollBars();
  36326. }
  36327. void CodeEditorComponent::scrollToColumn (int newFirstColumnOnScreen)
  36328. {
  36329. scrollToColumnInternal (newFirstColumnOnScreen);
  36330. updateScrollBars();
  36331. }
  36332. void CodeEditorComponent::scrollBy (int deltaLines)
  36333. {
  36334. scrollToLine (firstLineOnScreen + deltaLines);
  36335. }
  36336. void CodeEditorComponent::scrollToKeepCaretOnScreen()
  36337. {
  36338. if (caretPos.getLineNumber() < firstLineOnScreen)
  36339. scrollBy (caretPos.getLineNumber() - firstLineOnScreen);
  36340. else if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  36341. scrollBy (caretPos.getLineNumber() - (firstLineOnScreen + linesOnScreen - 1));
  36342. const int column = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  36343. if (column >= xOffset + columnsOnScreen - 1)
  36344. scrollToColumn (column + 1 - columnsOnScreen);
  36345. else if (column < xOffset)
  36346. scrollToColumn (column);
  36347. }
  36348. const Rectangle<int> CodeEditorComponent::getCharacterBounds (const CodeDocument::Position& pos) const throw()
  36349. {
  36350. return Rectangle<int> (roundToInt ((gutter - xOffset * charWidth) + indexToColumn (pos.getLineNumber(), pos.getIndexInLine()) * charWidth),
  36351. (pos.getLineNumber() - firstLineOnScreen) * lineHeight,
  36352. roundToInt (charWidth),
  36353. lineHeight);
  36354. }
  36355. const CodeDocument::Position CodeEditorComponent::getPositionAt (int x, int y)
  36356. {
  36357. const int line = y / lineHeight + firstLineOnScreen;
  36358. const int column = roundToInt ((x - (gutter - xOffset * charWidth)) / charWidth);
  36359. const int index = columnToIndex (line, column);
  36360. return CodeDocument::Position (&document, line, index);
  36361. }
  36362. void CodeEditorComponent::insertTextAtCaret (const String& newText)
  36363. {
  36364. document.deleteSection (selectionStart, selectionEnd);
  36365. if (newText.isNotEmpty())
  36366. document.insertText (caretPos, newText);
  36367. scrollToKeepCaretOnScreen();
  36368. }
  36369. void CodeEditorComponent::insertTabAtCaret()
  36370. {
  36371. if (CharacterFunctions::isWhitespace (caretPos.getCharacter())
  36372. && caretPos.getLineNumber() == caretPos.movedBy (1).getLineNumber())
  36373. {
  36374. moveCaretTo (document.findWordBreakAfter (caretPos), false);
  36375. }
  36376. if (useSpacesForTabs)
  36377. {
  36378. const int caretCol = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  36379. const int spacesNeeded = spacesPerTab - (caretCol % spacesPerTab);
  36380. insertTextAtCaret (String::repeatedString (" ", spacesNeeded));
  36381. }
  36382. else
  36383. {
  36384. insertTextAtCaret ("\t");
  36385. }
  36386. }
  36387. void CodeEditorComponent::cut()
  36388. {
  36389. insertTextAtCaret (String::empty);
  36390. }
  36391. void CodeEditorComponent::copy()
  36392. {
  36393. newTransaction();
  36394. const String selection (document.getTextBetween (selectionStart, selectionEnd));
  36395. if (selection.isNotEmpty())
  36396. SystemClipboard::copyTextToClipboard (selection);
  36397. }
  36398. void CodeEditorComponent::copyThenCut()
  36399. {
  36400. copy();
  36401. cut();
  36402. newTransaction();
  36403. }
  36404. void CodeEditorComponent::paste()
  36405. {
  36406. newTransaction();
  36407. const String clip (SystemClipboard::getTextFromClipboard());
  36408. if (clip.isNotEmpty())
  36409. insertTextAtCaret (clip);
  36410. newTransaction();
  36411. }
  36412. void CodeEditorComponent::cursorLeft (const bool moveInWholeWordSteps, const bool selecting)
  36413. {
  36414. newTransaction();
  36415. if (moveInWholeWordSteps)
  36416. moveCaretTo (document.findWordBreakBefore (caretPos), selecting);
  36417. else
  36418. moveCaretTo (caretPos.movedBy (-1), selecting);
  36419. }
  36420. void CodeEditorComponent::cursorRight (const bool moveInWholeWordSteps, const bool selecting)
  36421. {
  36422. newTransaction();
  36423. if (moveInWholeWordSteps)
  36424. moveCaretTo (document.findWordBreakAfter (caretPos), selecting);
  36425. else
  36426. moveCaretTo (caretPos.movedBy (1), selecting);
  36427. }
  36428. void CodeEditorComponent::moveLineDelta (const int delta, const bool selecting)
  36429. {
  36430. CodeDocument::Position pos (caretPos);
  36431. const int newLineNum = pos.getLineNumber() + delta;
  36432. if (columnToTryToMaintain < 0)
  36433. columnToTryToMaintain = indexToColumn (pos.getLineNumber(), pos.getIndexInLine());
  36434. pos.setLineAndIndex (newLineNum, columnToIndex (newLineNum, columnToTryToMaintain));
  36435. const int colToMaintain = columnToTryToMaintain;
  36436. moveCaretTo (pos, selecting);
  36437. columnToTryToMaintain = colToMaintain;
  36438. }
  36439. void CodeEditorComponent::cursorDown (const bool selecting)
  36440. {
  36441. newTransaction();
  36442. if (caretPos.getLineNumber() == document.getNumLines() - 1)
  36443. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  36444. else
  36445. moveLineDelta (1, selecting);
  36446. }
  36447. void CodeEditorComponent::cursorUp (const bool selecting)
  36448. {
  36449. newTransaction();
  36450. if (caretPos.getLineNumber() == 0)
  36451. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  36452. else
  36453. moveLineDelta (-1, selecting);
  36454. }
  36455. void CodeEditorComponent::pageDown (const bool selecting)
  36456. {
  36457. newTransaction();
  36458. scrollBy (jlimit (0, linesOnScreen, 1 + document.getNumLines() - firstLineOnScreen - linesOnScreen));
  36459. moveLineDelta (linesOnScreen, selecting);
  36460. }
  36461. void CodeEditorComponent::pageUp (const bool selecting)
  36462. {
  36463. newTransaction();
  36464. scrollBy (-linesOnScreen);
  36465. moveLineDelta (-linesOnScreen, selecting);
  36466. }
  36467. void CodeEditorComponent::scrollUp()
  36468. {
  36469. newTransaction();
  36470. scrollBy (1);
  36471. if (caretPos.getLineNumber() < firstLineOnScreen)
  36472. moveLineDelta (1, false);
  36473. }
  36474. void CodeEditorComponent::scrollDown()
  36475. {
  36476. newTransaction();
  36477. scrollBy (-1);
  36478. if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  36479. moveLineDelta (-1, false);
  36480. }
  36481. void CodeEditorComponent::goToStartOfDocument (const bool selecting)
  36482. {
  36483. newTransaction();
  36484. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  36485. }
  36486. static int findFirstNonWhitespaceChar (const String& line) throw()
  36487. {
  36488. const int len = line.length();
  36489. for (int i = 0; i < len; ++i)
  36490. if (! CharacterFunctions::isWhitespace (line [i]))
  36491. return i;
  36492. return 0;
  36493. }
  36494. void CodeEditorComponent::goToStartOfLine (const bool selecting)
  36495. {
  36496. newTransaction();
  36497. int index = findFirstNonWhitespaceChar (caretPos.getLineText());
  36498. if (index >= caretPos.getIndexInLine() && caretPos.getIndexInLine() > 0)
  36499. index = 0;
  36500. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), index), selecting);
  36501. }
  36502. void CodeEditorComponent::goToEndOfDocument (const bool selecting)
  36503. {
  36504. newTransaction();
  36505. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  36506. }
  36507. void CodeEditorComponent::goToEndOfLine (const bool selecting)
  36508. {
  36509. newTransaction();
  36510. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), std::numeric_limits<int>::max()), selecting);
  36511. }
  36512. void CodeEditorComponent::backspace (const bool moveInWholeWordSteps)
  36513. {
  36514. if (moveInWholeWordSteps)
  36515. {
  36516. cut(); // in case something is already highlighted
  36517. moveCaretTo (document.findWordBreakBefore (caretPos), true);
  36518. }
  36519. else
  36520. {
  36521. if (selectionStart == selectionEnd)
  36522. selectionStart.moveBy (-1);
  36523. }
  36524. cut();
  36525. }
  36526. void CodeEditorComponent::deleteForward (const bool moveInWholeWordSteps)
  36527. {
  36528. if (moveInWholeWordSteps)
  36529. {
  36530. cut(); // in case something is already highlighted
  36531. moveCaretTo (document.findWordBreakAfter (caretPos), true);
  36532. }
  36533. else
  36534. {
  36535. if (selectionStart == selectionEnd)
  36536. selectionEnd.moveBy (1);
  36537. else
  36538. newTransaction();
  36539. }
  36540. cut();
  36541. }
  36542. void CodeEditorComponent::selectAll()
  36543. {
  36544. newTransaction();
  36545. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), false);
  36546. moveCaretTo (CodeDocument::Position (&document, 0, 0), true);
  36547. }
  36548. void CodeEditorComponent::undo()
  36549. {
  36550. document.undo();
  36551. scrollToKeepCaretOnScreen();
  36552. }
  36553. void CodeEditorComponent::redo()
  36554. {
  36555. document.redo();
  36556. scrollToKeepCaretOnScreen();
  36557. }
  36558. void CodeEditorComponent::newTransaction()
  36559. {
  36560. document.newTransaction();
  36561. startTimer (600);
  36562. }
  36563. void CodeEditorComponent::timerCallback()
  36564. {
  36565. newTransaction();
  36566. }
  36567. const Range<int> CodeEditorComponent::getHighlightedRegion() const
  36568. {
  36569. return Range<int> (selectionStart.getPosition(), selectionEnd.getPosition());
  36570. }
  36571. void CodeEditorComponent::setHighlightedRegion (const Range<int>& newRange)
  36572. {
  36573. moveCaretTo (CodeDocument::Position (&document, newRange.getStart()), false);
  36574. moveCaretTo (CodeDocument::Position (&document, newRange.getEnd()), true);
  36575. }
  36576. const String CodeEditorComponent::getTextInRange (const Range<int>& range) const
  36577. {
  36578. return document.getTextBetween (CodeDocument::Position (&document, range.getStart()),
  36579. CodeDocument::Position (&document, range.getEnd()));
  36580. }
  36581. bool CodeEditorComponent::keyPressed (const KeyPress& key)
  36582. {
  36583. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  36584. const bool shiftDown = key.getModifiers().isShiftDown();
  36585. if (key.isKeyCode (KeyPress::leftKey))
  36586. {
  36587. cursorLeft (moveInWholeWordSteps, shiftDown);
  36588. }
  36589. else if (key.isKeyCode (KeyPress::rightKey))
  36590. {
  36591. cursorRight (moveInWholeWordSteps, shiftDown);
  36592. }
  36593. else if (key.isKeyCode (KeyPress::upKey))
  36594. {
  36595. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  36596. scrollDown();
  36597. #if JUCE_MAC
  36598. else if (key.getModifiers().isCommandDown())
  36599. goToStartOfDocument (shiftDown);
  36600. #endif
  36601. else
  36602. cursorUp (shiftDown);
  36603. }
  36604. else if (key.isKeyCode (KeyPress::downKey))
  36605. {
  36606. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  36607. scrollUp();
  36608. #if JUCE_MAC
  36609. else if (key.getModifiers().isCommandDown())
  36610. goToEndOfDocument (shiftDown);
  36611. #endif
  36612. else
  36613. cursorDown (shiftDown);
  36614. }
  36615. else if (key.isKeyCode (KeyPress::pageDownKey))
  36616. {
  36617. pageDown (shiftDown);
  36618. }
  36619. else if (key.isKeyCode (KeyPress::pageUpKey))
  36620. {
  36621. pageUp (shiftDown);
  36622. }
  36623. else if (key.isKeyCode (KeyPress::homeKey))
  36624. {
  36625. if (moveInWholeWordSteps)
  36626. goToStartOfDocument (shiftDown);
  36627. else
  36628. goToStartOfLine (shiftDown);
  36629. }
  36630. else if (key.isKeyCode (KeyPress::endKey))
  36631. {
  36632. if (moveInWholeWordSteps)
  36633. goToEndOfDocument (shiftDown);
  36634. else
  36635. goToEndOfLine (shiftDown);
  36636. }
  36637. else if (key.isKeyCode (KeyPress::backspaceKey))
  36638. {
  36639. backspace (moveInWholeWordSteps);
  36640. }
  36641. else if (key.isKeyCode (KeyPress::deleteKey))
  36642. {
  36643. deleteForward (moveInWholeWordSteps);
  36644. }
  36645. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0))
  36646. {
  36647. copy();
  36648. }
  36649. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  36650. {
  36651. copyThenCut();
  36652. }
  36653. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0))
  36654. {
  36655. paste();
  36656. }
  36657. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  36658. {
  36659. undo();
  36660. }
  36661. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0)
  36662. || key == KeyPress ('z', ModifierKeys::commandModifier | ModifierKeys::shiftModifier, 0))
  36663. {
  36664. redo();
  36665. }
  36666. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  36667. {
  36668. selectAll();
  36669. }
  36670. else if (key == KeyPress::tabKey || key.getTextCharacter() == '\t')
  36671. {
  36672. insertTabAtCaret();
  36673. }
  36674. else if (key == KeyPress::returnKey)
  36675. {
  36676. newTransaction();
  36677. insertTextAtCaret (document.getNewLineCharacters());
  36678. }
  36679. else if (key.isKeyCode (KeyPress::escapeKey))
  36680. {
  36681. newTransaction();
  36682. }
  36683. else if (key.getTextCharacter() >= ' ')
  36684. {
  36685. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  36686. }
  36687. else
  36688. {
  36689. return false;
  36690. }
  36691. return true;
  36692. }
  36693. void CodeEditorComponent::mouseDown (const MouseEvent& e)
  36694. {
  36695. newTransaction();
  36696. dragType = notDragging;
  36697. if (! e.mods.isPopupMenu())
  36698. {
  36699. beginDragAutoRepeat (100);
  36700. moveCaretTo (getPositionAt (e.x, e.y), e.mods.isShiftDown());
  36701. }
  36702. else
  36703. {
  36704. /*PopupMenu m;
  36705. addPopupMenuItems (m, &e);
  36706. const int result = m.show();
  36707. if (result != 0)
  36708. performPopupMenuAction (result);
  36709. */
  36710. }
  36711. }
  36712. void CodeEditorComponent::mouseDrag (const MouseEvent& e)
  36713. {
  36714. if (! e.mods.isPopupMenu())
  36715. moveCaretTo (getPositionAt (e.x, e.y), true);
  36716. }
  36717. void CodeEditorComponent::mouseUp (const MouseEvent&)
  36718. {
  36719. newTransaction();
  36720. beginDragAutoRepeat (0);
  36721. dragType = notDragging;
  36722. }
  36723. void CodeEditorComponent::mouseDoubleClick (const MouseEvent& e)
  36724. {
  36725. CodeDocument::Position tokenStart (getPositionAt (e.x, e.y));
  36726. CodeDocument::Position tokenEnd (tokenStart);
  36727. if (e.getNumberOfClicks() > 2)
  36728. {
  36729. tokenStart.setLineAndIndex (tokenStart.getLineNumber(), 0);
  36730. tokenEnd.setLineAndIndex (tokenStart.getLineNumber() + 1, 0);
  36731. }
  36732. else
  36733. {
  36734. while (CharacterFunctions::isLetterOrDigit (tokenEnd.getCharacter()))
  36735. tokenEnd.moveBy (1);
  36736. tokenStart = tokenEnd;
  36737. while (tokenStart.getIndexInLine() > 0
  36738. && CharacterFunctions::isLetterOrDigit (tokenStart.movedBy (-1).getCharacter()))
  36739. tokenStart.moveBy (-1);
  36740. }
  36741. moveCaretTo (tokenEnd, false);
  36742. moveCaretTo (tokenStart, true);
  36743. }
  36744. void CodeEditorComponent::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  36745. {
  36746. if ((verticalScrollBar->isVisible() && wheelIncrementY != 0)
  36747. || (horizontalScrollBar->isVisible() && wheelIncrementX != 0))
  36748. {
  36749. verticalScrollBar->mouseWheelMove (e, 0, wheelIncrementY);
  36750. horizontalScrollBar->mouseWheelMove (e, wheelIncrementX, 0);
  36751. }
  36752. else
  36753. {
  36754. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  36755. }
  36756. }
  36757. void CodeEditorComponent::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  36758. {
  36759. if (scrollBarThatHasMoved == verticalScrollBar)
  36760. scrollToLineInternal ((int) newRangeStart);
  36761. else
  36762. scrollToColumnInternal (newRangeStart);
  36763. }
  36764. void CodeEditorComponent::focusGained (FocusChangeType)
  36765. {
  36766. caret->updatePosition();
  36767. }
  36768. void CodeEditorComponent::focusLost (FocusChangeType)
  36769. {
  36770. caret->updatePosition();
  36771. }
  36772. void CodeEditorComponent::setTabSize (const int numSpaces, const bool insertSpaces) throw()
  36773. {
  36774. useSpacesForTabs = insertSpaces;
  36775. if (spacesPerTab != numSpaces)
  36776. {
  36777. spacesPerTab = numSpaces;
  36778. triggerAsyncUpdate();
  36779. }
  36780. }
  36781. int CodeEditorComponent::indexToColumn (int lineNum, int index) const throw()
  36782. {
  36783. const String line (document.getLine (lineNum));
  36784. jassert (index <= line.length());
  36785. int col = 0;
  36786. for (int i = 0; i < index; ++i)
  36787. {
  36788. if (line[i] != '\t')
  36789. ++col;
  36790. else
  36791. col += getTabSize() - (col % getTabSize());
  36792. }
  36793. return col;
  36794. }
  36795. int CodeEditorComponent::columnToIndex (int lineNum, int column) const throw()
  36796. {
  36797. const String line (document.getLine (lineNum));
  36798. const int lineLength = line.length();
  36799. int i, col = 0;
  36800. for (i = 0; i < lineLength; ++i)
  36801. {
  36802. if (line[i] != '\t')
  36803. ++col;
  36804. else
  36805. col += getTabSize() - (col % getTabSize());
  36806. if (col > column)
  36807. break;
  36808. }
  36809. return i;
  36810. }
  36811. void CodeEditorComponent::setFont (const Font& newFont)
  36812. {
  36813. font = newFont;
  36814. charWidth = font.getStringWidthFloat ("0");
  36815. lineHeight = roundToInt (font.getHeight());
  36816. resized();
  36817. }
  36818. void CodeEditorComponent::resetToDefaultColours()
  36819. {
  36820. coloursForTokenCategories.clear();
  36821. if (codeTokeniser != 0)
  36822. {
  36823. for (int i = codeTokeniser->getTokenTypes().size(); --i >= 0;)
  36824. setColourForTokenType (i, codeTokeniser->getDefaultColour (i));
  36825. }
  36826. }
  36827. void CodeEditorComponent::setColourForTokenType (const int tokenType, const Colour& colour)
  36828. {
  36829. jassert (tokenType < 256);
  36830. while (coloursForTokenCategories.size() < tokenType)
  36831. coloursForTokenCategories.add (Colours::black);
  36832. coloursForTokenCategories.set (tokenType, colour);
  36833. repaint();
  36834. }
  36835. const Colour CodeEditorComponent::getColourForTokenType (const int tokenType) const throw()
  36836. {
  36837. if (((unsigned int) tokenType) >= (unsigned int) coloursForTokenCategories.size())
  36838. return findColour (CodeEditorComponent::defaultTextColourId);
  36839. return coloursForTokenCategories.getReference (tokenType);
  36840. }
  36841. void CodeEditorComponent::clearCachedIterators (const int firstLineToBeInvalid) throw()
  36842. {
  36843. int i;
  36844. for (i = cachedIterators.size(); --i >= 0;)
  36845. if (cachedIterators.getUnchecked (i)->getLine() < firstLineToBeInvalid)
  36846. break;
  36847. cachedIterators.removeRange (jmax (0, i - 1), cachedIterators.size());
  36848. }
  36849. void CodeEditorComponent::updateCachedIterators (int maxLineNum)
  36850. {
  36851. const int maxNumCachedPositions = 5000;
  36852. const int linesBetweenCachedSources = jmax (10, document.getNumLines() / maxNumCachedPositions);
  36853. if (cachedIterators.size() == 0)
  36854. cachedIterators.add (new CodeDocument::Iterator (&document));
  36855. if (codeTokeniser == 0)
  36856. return;
  36857. for (;;)
  36858. {
  36859. CodeDocument::Iterator* last = cachedIterators.getLast();
  36860. if (last->getLine() >= maxLineNum)
  36861. break;
  36862. CodeDocument::Iterator* t = new CodeDocument::Iterator (*last);
  36863. cachedIterators.add (t);
  36864. const int targetLine = last->getLine() + linesBetweenCachedSources;
  36865. for (;;)
  36866. {
  36867. codeTokeniser->readNextToken (*t);
  36868. if (t->getLine() >= targetLine)
  36869. break;
  36870. if (t->isEOF())
  36871. return;
  36872. }
  36873. }
  36874. }
  36875. void CodeEditorComponent::getIteratorForPosition (int position, CodeDocument::Iterator& source)
  36876. {
  36877. if (codeTokeniser == 0)
  36878. return;
  36879. for (int i = cachedIterators.size(); --i >= 0;)
  36880. {
  36881. CodeDocument::Iterator* t = cachedIterators.getUnchecked (i);
  36882. if (t->getPosition() <= position)
  36883. {
  36884. source = *t;
  36885. break;
  36886. }
  36887. }
  36888. while (source.getPosition() < position)
  36889. {
  36890. const CodeDocument::Iterator original (source);
  36891. codeTokeniser->readNextToken (source);
  36892. if (source.getPosition() > position || source.isEOF())
  36893. {
  36894. source = original;
  36895. break;
  36896. }
  36897. }
  36898. }
  36899. END_JUCE_NAMESPACE
  36900. /*** End of inlined file: juce_CodeEditorComponent.cpp ***/
  36901. /*** Start of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  36902. BEGIN_JUCE_NAMESPACE
  36903. CPlusPlusCodeTokeniser::CPlusPlusCodeTokeniser()
  36904. {
  36905. }
  36906. CPlusPlusCodeTokeniser::~CPlusPlusCodeTokeniser()
  36907. {
  36908. }
  36909. namespace CppTokeniser
  36910. {
  36911. static bool isIdentifierStart (const juce_wchar c) throw()
  36912. {
  36913. return CharacterFunctions::isLetter (c)
  36914. || c == '_' || c == '@';
  36915. }
  36916. static bool isIdentifierBody (const juce_wchar c) throw()
  36917. {
  36918. return CharacterFunctions::isLetterOrDigit (c)
  36919. || c == '_' || c == '@';
  36920. }
  36921. static bool isReservedKeyword (const juce_wchar* const token, const int tokenLength) throw()
  36922. {
  36923. static const juce_wchar* const keywords2Char[] =
  36924. { JUCE_T("if"), JUCE_T("do"), JUCE_T("or"), JUCE_T("id"), 0 };
  36925. static const juce_wchar* const keywords3Char[] =
  36926. { 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 };
  36927. static const juce_wchar* const keywords4Char[] =
  36928. { JUCE_T("bool"), JUCE_T("void"), JUCE_T("this"), JUCE_T("true"), JUCE_T("long"), JUCE_T("else"), JUCE_T("char"),
  36929. JUCE_T("enum"), JUCE_T("case"), JUCE_T("goto"), JUCE_T("auto"), 0 };
  36930. static const juce_wchar* const keywords5Char[] =
  36931. { JUCE_T("while"), JUCE_T("bitor"), JUCE_T("break"), JUCE_T("catch"), JUCE_T("class"), JUCE_T("compl"), JUCE_T("const"), JUCE_T("false"),
  36932. JUCE_T("float"), JUCE_T("short"), JUCE_T("throw"), JUCE_T("union"), JUCE_T("using"), JUCE_T("or_eq"), 0 };
  36933. static const juce_wchar* const keywords6Char[] =
  36934. { JUCE_T("return"), JUCE_T("struct"), JUCE_T("and_eq"), JUCE_T("bitand"), JUCE_T("delete"), JUCE_T("double"), JUCE_T("extern"),
  36935. JUCE_T("friend"), JUCE_T("inline"), JUCE_T("not_eq"), JUCE_T("public"), JUCE_T("sizeof"), JUCE_T("static"), JUCE_T("signed"),
  36936. JUCE_T("switch"), JUCE_T("typeid"), JUCE_T("wchar_t"), JUCE_T("xor_eq"), 0};
  36937. static const juce_wchar* const keywordsOther[] =
  36938. { JUCE_T("const_cast"), JUCE_T("continue"), JUCE_T("default"), JUCE_T("explicit"), JUCE_T("mutable"), JUCE_T("namespace"),
  36939. JUCE_T("operator"), JUCE_T("private"), JUCE_T("protected"), JUCE_T("register"), JUCE_T("reinterpret_cast"), JUCE_T("static_cast"),
  36940. JUCE_T("template"), JUCE_T("typedef"), JUCE_T("typename"), JUCE_T("unsigned"), JUCE_T("virtual"), JUCE_T("volatile"),
  36941. JUCE_T("@implementation"), JUCE_T("@interface"), JUCE_T("@end"), JUCE_T("@synthesize"), JUCE_T("@dynamic"), JUCE_T("@public"),
  36942. JUCE_T("@private"), JUCE_T("@property"), JUCE_T("@protected"), JUCE_T("@class"), 0 };
  36943. const juce_wchar* const* k;
  36944. switch (tokenLength)
  36945. {
  36946. case 2: k = keywords2Char; break;
  36947. case 3: k = keywords3Char; break;
  36948. case 4: k = keywords4Char; break;
  36949. case 5: k = keywords5Char; break;
  36950. case 6: k = keywords6Char; break;
  36951. default:
  36952. if (tokenLength < 2 || tokenLength > 16)
  36953. return false;
  36954. k = keywordsOther;
  36955. break;
  36956. }
  36957. int i = 0;
  36958. while (k[i] != 0)
  36959. {
  36960. if (k[i][0] == token[0] && CharacterFunctions::compare (k[i], token) == 0)
  36961. return true;
  36962. ++i;
  36963. }
  36964. return false;
  36965. }
  36966. static int parseIdentifier (CodeDocument::Iterator& source) throw()
  36967. {
  36968. int tokenLength = 0;
  36969. juce_wchar possibleIdentifier [19];
  36970. while (isIdentifierBody (source.peekNextChar()))
  36971. {
  36972. const juce_wchar c = source.nextChar();
  36973. if (tokenLength < numElementsInArray (possibleIdentifier) - 1)
  36974. possibleIdentifier [tokenLength] = c;
  36975. ++tokenLength;
  36976. }
  36977. if (tokenLength > 1 && tokenLength <= 16)
  36978. {
  36979. possibleIdentifier [tokenLength] = 0;
  36980. if (isReservedKeyword (possibleIdentifier, tokenLength))
  36981. return CPlusPlusCodeTokeniser::tokenType_builtInKeyword;
  36982. }
  36983. return CPlusPlusCodeTokeniser::tokenType_identifier;
  36984. }
  36985. static bool skipNumberSuffix (CodeDocument::Iterator& source)
  36986. {
  36987. const juce_wchar c = source.peekNextChar();
  36988. if (c == 'l' || c == 'L' || c == 'u' || c == 'U')
  36989. source.skip();
  36990. if (CharacterFunctions::isLetterOrDigit (source.peekNextChar()))
  36991. return false;
  36992. return true;
  36993. }
  36994. static bool isHexDigit (const juce_wchar c) throw()
  36995. {
  36996. return (c >= '0' && c <= '9')
  36997. || (c >= 'a' && c <= 'f')
  36998. || (c >= 'A' && c <= 'F');
  36999. }
  37000. static bool parseHexLiteral (CodeDocument::Iterator& source) throw()
  37001. {
  37002. if (source.nextChar() != '0')
  37003. return false;
  37004. juce_wchar c = source.nextChar();
  37005. if (c != 'x' && c != 'X')
  37006. return false;
  37007. int numDigits = 0;
  37008. while (isHexDigit (source.peekNextChar()))
  37009. {
  37010. ++numDigits;
  37011. source.skip();
  37012. }
  37013. if (numDigits == 0)
  37014. return false;
  37015. return skipNumberSuffix (source);
  37016. }
  37017. static bool isOctalDigit (const juce_wchar c) throw()
  37018. {
  37019. return c >= '0' && c <= '7';
  37020. }
  37021. static bool parseOctalLiteral (CodeDocument::Iterator& source) throw()
  37022. {
  37023. if (source.nextChar() != '0')
  37024. return false;
  37025. if (! isOctalDigit (source.nextChar()))
  37026. return false;
  37027. while (isOctalDigit (source.peekNextChar()))
  37028. source.skip();
  37029. return skipNumberSuffix (source);
  37030. }
  37031. static bool isDecimalDigit (const juce_wchar c) throw()
  37032. {
  37033. return c >= '0' && c <= '9';
  37034. }
  37035. static bool parseDecimalLiteral (CodeDocument::Iterator& source) throw()
  37036. {
  37037. int numChars = 0;
  37038. while (isDecimalDigit (source.peekNextChar()))
  37039. {
  37040. ++numChars;
  37041. source.skip();
  37042. }
  37043. if (numChars == 0)
  37044. return false;
  37045. return skipNumberSuffix (source);
  37046. }
  37047. static bool parseFloatLiteral (CodeDocument::Iterator& source) throw()
  37048. {
  37049. int numDigits = 0;
  37050. while (isDecimalDigit (source.peekNextChar()))
  37051. {
  37052. source.skip();
  37053. ++numDigits;
  37054. }
  37055. const bool hasPoint = (source.peekNextChar() == '.');
  37056. if (hasPoint)
  37057. {
  37058. source.skip();
  37059. while (isDecimalDigit (source.peekNextChar()))
  37060. {
  37061. source.skip();
  37062. ++numDigits;
  37063. }
  37064. }
  37065. if (numDigits == 0)
  37066. return false;
  37067. juce_wchar c = source.peekNextChar();
  37068. const bool hasExponent = (c == 'e' || c == 'E');
  37069. if (hasExponent)
  37070. {
  37071. source.skip();
  37072. c = source.peekNextChar();
  37073. if (c == '+' || c == '-')
  37074. source.skip();
  37075. int numExpDigits = 0;
  37076. while (isDecimalDigit (source.peekNextChar()))
  37077. {
  37078. source.skip();
  37079. ++numExpDigits;
  37080. }
  37081. if (numExpDigits == 0)
  37082. return false;
  37083. }
  37084. c = source.peekNextChar();
  37085. if (c == 'f' || c == 'F')
  37086. source.skip();
  37087. else if (! (hasExponent || hasPoint))
  37088. return false;
  37089. return true;
  37090. }
  37091. static int parseNumber (CodeDocument::Iterator& source)
  37092. {
  37093. const CodeDocument::Iterator original (source);
  37094. if (parseFloatLiteral (source))
  37095. return CPlusPlusCodeTokeniser::tokenType_floatLiteral;
  37096. source = original;
  37097. if (parseHexLiteral (source))
  37098. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37099. source = original;
  37100. if (parseOctalLiteral (source))
  37101. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37102. source = original;
  37103. if (parseDecimalLiteral (source))
  37104. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37105. source = original;
  37106. source.skip();
  37107. return CPlusPlusCodeTokeniser::tokenType_error;
  37108. }
  37109. static void skipQuotedString (CodeDocument::Iterator& source) throw()
  37110. {
  37111. const juce_wchar quote = source.nextChar();
  37112. for (;;)
  37113. {
  37114. const juce_wchar c = source.nextChar();
  37115. if (c == quote || c == 0)
  37116. break;
  37117. if (c == '\\')
  37118. source.skip();
  37119. }
  37120. }
  37121. static void skipComment (CodeDocument::Iterator& source) throw()
  37122. {
  37123. bool lastWasStar = false;
  37124. for (;;)
  37125. {
  37126. const juce_wchar c = source.nextChar();
  37127. if (c == 0 || (c == '/' && lastWasStar))
  37128. break;
  37129. lastWasStar = (c == '*');
  37130. }
  37131. }
  37132. }
  37133. int CPlusPlusCodeTokeniser::readNextToken (CodeDocument::Iterator& source)
  37134. {
  37135. int result = tokenType_error;
  37136. source.skipWhitespace();
  37137. juce_wchar firstChar = source.peekNextChar();
  37138. switch (firstChar)
  37139. {
  37140. case 0:
  37141. source.skip();
  37142. break;
  37143. case '0':
  37144. case '1':
  37145. case '2':
  37146. case '3':
  37147. case '4':
  37148. case '5':
  37149. case '6':
  37150. case '7':
  37151. case '8':
  37152. case '9':
  37153. result = CppTokeniser::parseNumber (source);
  37154. break;
  37155. case '.':
  37156. result = CppTokeniser::parseNumber (source);
  37157. if (result == tokenType_error)
  37158. result = tokenType_punctuation;
  37159. break;
  37160. case ',':
  37161. case ';':
  37162. case ':':
  37163. source.skip();
  37164. result = tokenType_punctuation;
  37165. break;
  37166. case '(':
  37167. case ')':
  37168. case '{':
  37169. case '}':
  37170. case '[':
  37171. case ']':
  37172. source.skip();
  37173. result = tokenType_bracket;
  37174. break;
  37175. case '"':
  37176. case '\'':
  37177. CppTokeniser::skipQuotedString (source);
  37178. result = tokenType_stringLiteral;
  37179. break;
  37180. case '+':
  37181. result = tokenType_operator;
  37182. source.skip();
  37183. if (source.peekNextChar() == '+')
  37184. source.skip();
  37185. else if (source.peekNextChar() == '=')
  37186. source.skip();
  37187. break;
  37188. case '-':
  37189. source.skip();
  37190. result = CppTokeniser::parseNumber (source);
  37191. if (result == tokenType_error)
  37192. {
  37193. result = tokenType_operator;
  37194. if (source.peekNextChar() == '-')
  37195. source.skip();
  37196. else if (source.peekNextChar() == '=')
  37197. source.skip();
  37198. }
  37199. break;
  37200. case '*':
  37201. case '%':
  37202. case '=':
  37203. case '!':
  37204. result = tokenType_operator;
  37205. source.skip();
  37206. if (source.peekNextChar() == '=')
  37207. source.skip();
  37208. break;
  37209. case '/':
  37210. result = tokenType_operator;
  37211. source.skip();
  37212. if (source.peekNextChar() == '=')
  37213. {
  37214. source.skip();
  37215. }
  37216. else if (source.peekNextChar() == '/')
  37217. {
  37218. result = tokenType_comment;
  37219. source.skipToEndOfLine();
  37220. }
  37221. else if (source.peekNextChar() == '*')
  37222. {
  37223. source.skip();
  37224. result = tokenType_comment;
  37225. CppTokeniser::skipComment (source);
  37226. }
  37227. break;
  37228. case '?':
  37229. case '~':
  37230. source.skip();
  37231. result = tokenType_operator;
  37232. break;
  37233. case '<':
  37234. source.skip();
  37235. result = tokenType_operator;
  37236. if (source.peekNextChar() == '=')
  37237. {
  37238. source.skip();
  37239. }
  37240. else if (source.peekNextChar() == '<')
  37241. {
  37242. source.skip();
  37243. if (source.peekNextChar() == '=')
  37244. source.skip();
  37245. }
  37246. break;
  37247. case '>':
  37248. source.skip();
  37249. result = tokenType_operator;
  37250. if (source.peekNextChar() == '=')
  37251. {
  37252. source.skip();
  37253. }
  37254. else if (source.peekNextChar() == '<')
  37255. {
  37256. source.skip();
  37257. if (source.peekNextChar() == '=')
  37258. source.skip();
  37259. }
  37260. break;
  37261. case '|':
  37262. source.skip();
  37263. result = tokenType_operator;
  37264. if (source.peekNextChar() == '=')
  37265. {
  37266. source.skip();
  37267. }
  37268. else if (source.peekNextChar() == '|')
  37269. {
  37270. source.skip();
  37271. if (source.peekNextChar() == '=')
  37272. source.skip();
  37273. }
  37274. break;
  37275. case '&':
  37276. source.skip();
  37277. result = tokenType_operator;
  37278. if (source.peekNextChar() == '=')
  37279. {
  37280. source.skip();
  37281. }
  37282. else if (source.peekNextChar() == '&')
  37283. {
  37284. source.skip();
  37285. if (source.peekNextChar() == '=')
  37286. source.skip();
  37287. }
  37288. break;
  37289. case '^':
  37290. source.skip();
  37291. result = tokenType_operator;
  37292. if (source.peekNextChar() == '=')
  37293. {
  37294. source.skip();
  37295. }
  37296. else if (source.peekNextChar() == '^')
  37297. {
  37298. source.skip();
  37299. if (source.peekNextChar() == '=')
  37300. source.skip();
  37301. }
  37302. break;
  37303. case '#':
  37304. result = tokenType_preprocessor;
  37305. source.skipToEndOfLine();
  37306. break;
  37307. default:
  37308. if (CppTokeniser::isIdentifierStart (firstChar))
  37309. result = CppTokeniser::parseIdentifier (source);
  37310. else
  37311. source.skip();
  37312. break;
  37313. }
  37314. return result;
  37315. }
  37316. const StringArray CPlusPlusCodeTokeniser::getTokenTypes()
  37317. {
  37318. const char* const types[] =
  37319. {
  37320. "Error",
  37321. "Comment",
  37322. "C++ keyword",
  37323. "Identifier",
  37324. "Integer literal",
  37325. "Float literal",
  37326. "String literal",
  37327. "Operator",
  37328. "Bracket",
  37329. "Punctuation",
  37330. "Preprocessor line",
  37331. 0
  37332. };
  37333. return StringArray (types);
  37334. }
  37335. const Colour CPlusPlusCodeTokeniser::getDefaultColour (const int tokenType)
  37336. {
  37337. const uint32 colours[] =
  37338. {
  37339. 0xffcc0000, // error
  37340. 0xff00aa00, // comment
  37341. 0xff0000cc, // keyword
  37342. 0xff000000, // identifier
  37343. 0xff880000, // int literal
  37344. 0xff885500, // float literal
  37345. 0xff990099, // string literal
  37346. 0xff225500, // operator
  37347. 0xff000055, // bracket
  37348. 0xff004400, // punctuation
  37349. 0xff660000 // preprocessor
  37350. };
  37351. if (tokenType >= 0 && tokenType < numElementsInArray (colours))
  37352. return Colour (colours [tokenType]);
  37353. return Colours::black;
  37354. }
  37355. bool CPlusPlusCodeTokeniser::isReservedKeyword (const String& token) throw()
  37356. {
  37357. return CppTokeniser::isReservedKeyword (token, token.length());
  37358. }
  37359. END_JUCE_NAMESPACE
  37360. /*** End of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  37361. /*** Start of inlined file: juce_ComboBox.cpp ***/
  37362. BEGIN_JUCE_NAMESPACE
  37363. ComboBox::ComboBox (const String& name)
  37364. : Component (name),
  37365. lastCurrentId (0),
  37366. isButtonDown (false),
  37367. separatorPending (false),
  37368. menuActive (false),
  37369. label (0)
  37370. {
  37371. noChoicesMessage = TRANS("(no choices)");
  37372. setRepaintsOnMouseActivity (true);
  37373. lookAndFeelChanged();
  37374. currentId.addListener (this);
  37375. }
  37376. ComboBox::~ComboBox()
  37377. {
  37378. currentId.removeListener (this);
  37379. if (menuActive)
  37380. PopupMenu::dismissAllActiveMenus();
  37381. label = 0;
  37382. deleteAllChildren();
  37383. }
  37384. void ComboBox::setEditableText (const bool isEditable)
  37385. {
  37386. if (label->isEditableOnSingleClick() != isEditable || label->isEditableOnDoubleClick() != isEditable)
  37387. {
  37388. label->setEditable (isEditable, isEditable, false);
  37389. setWantsKeyboardFocus (! isEditable);
  37390. resized();
  37391. }
  37392. }
  37393. bool ComboBox::isTextEditable() const throw()
  37394. {
  37395. return label->isEditable();
  37396. }
  37397. void ComboBox::setJustificationType (const Justification& justification) throw()
  37398. {
  37399. label->setJustificationType (justification);
  37400. }
  37401. const Justification ComboBox::getJustificationType() const throw()
  37402. {
  37403. return label->getJustificationType();
  37404. }
  37405. void ComboBox::setTooltip (const String& newTooltip)
  37406. {
  37407. SettableTooltipClient::setTooltip (newTooltip);
  37408. label->setTooltip (newTooltip);
  37409. }
  37410. void ComboBox::addItem (const String& newItemText,
  37411. const int newItemId) throw()
  37412. {
  37413. // you can't add empty strings to the list..
  37414. jassert (newItemText.isNotEmpty());
  37415. // IDs must be non-zero, as zero is used to indicate a lack of selecion.
  37416. jassert (newItemId != 0);
  37417. // you shouldn't use duplicate item IDs!
  37418. jassert (getItemForId (newItemId) == 0);
  37419. if (newItemText.isNotEmpty() && newItemId != 0)
  37420. {
  37421. if (separatorPending)
  37422. {
  37423. separatorPending = false;
  37424. ItemInfo* const item = new ItemInfo();
  37425. item->itemId = 0;
  37426. item->isEnabled = false;
  37427. item->isHeading = false;
  37428. items.add (item);
  37429. }
  37430. ItemInfo* const item = new ItemInfo();
  37431. item->name = newItemText;
  37432. item->itemId = newItemId;
  37433. item->isEnabled = true;
  37434. item->isHeading = false;
  37435. items.add (item);
  37436. }
  37437. }
  37438. void ComboBox::addSeparator() throw()
  37439. {
  37440. separatorPending = (items.size() > 0);
  37441. }
  37442. void ComboBox::addSectionHeading (const String& headingName) throw()
  37443. {
  37444. // you can't add empty strings to the list..
  37445. jassert (headingName.isNotEmpty());
  37446. if (headingName.isNotEmpty())
  37447. {
  37448. if (separatorPending)
  37449. {
  37450. separatorPending = false;
  37451. ItemInfo* const item = new ItemInfo();
  37452. item->itemId = 0;
  37453. item->isEnabled = false;
  37454. item->isHeading = false;
  37455. items.add (item);
  37456. }
  37457. ItemInfo* const item = new ItemInfo();
  37458. item->name = headingName;
  37459. item->itemId = 0;
  37460. item->isEnabled = true;
  37461. item->isHeading = true;
  37462. items.add (item);
  37463. }
  37464. }
  37465. void ComboBox::setItemEnabled (const int itemId,
  37466. const bool shouldBeEnabled) throw()
  37467. {
  37468. ItemInfo* const item = getItemForId (itemId);
  37469. if (item != 0)
  37470. item->isEnabled = shouldBeEnabled;
  37471. }
  37472. void ComboBox::changeItemText (const int itemId,
  37473. const String& newText) throw()
  37474. {
  37475. ItemInfo* const item = getItemForId (itemId);
  37476. jassert (item != 0);
  37477. if (item != 0)
  37478. item->name = newText;
  37479. }
  37480. void ComboBox::clear (const bool dontSendChangeMessage)
  37481. {
  37482. items.clear();
  37483. separatorPending = false;
  37484. if (! label->isEditable())
  37485. setSelectedItemIndex (-1, dontSendChangeMessage);
  37486. }
  37487. bool ComboBox::ItemInfo::isSeparator() const throw()
  37488. {
  37489. return name.isEmpty();
  37490. }
  37491. bool ComboBox::ItemInfo::isRealItem() const throw()
  37492. {
  37493. return ! (isHeading || name.isEmpty());
  37494. }
  37495. ComboBox::ItemInfo* ComboBox::getItemForId (const int itemId) const throw()
  37496. {
  37497. if (itemId != 0)
  37498. {
  37499. for (int i = items.size(); --i >= 0;)
  37500. if (items.getUnchecked(i)->itemId == itemId)
  37501. return items.getUnchecked(i);
  37502. }
  37503. return 0;
  37504. }
  37505. ComboBox::ItemInfo* ComboBox::getItemForIndex (const int index) const throw()
  37506. {
  37507. int n = 0;
  37508. for (int i = 0; i < items.size(); ++i)
  37509. {
  37510. ItemInfo* const item = items.getUnchecked(i);
  37511. if (item->isRealItem())
  37512. if (n++ == index)
  37513. return item;
  37514. }
  37515. return 0;
  37516. }
  37517. int ComboBox::getNumItems() const throw()
  37518. {
  37519. int n = 0;
  37520. for (int i = items.size(); --i >= 0;)
  37521. if (items.getUnchecked(i)->isRealItem())
  37522. ++n;
  37523. return n;
  37524. }
  37525. const String ComboBox::getItemText (const int index) const throw()
  37526. {
  37527. const ItemInfo* const item = getItemForIndex (index);
  37528. if (item != 0)
  37529. return item->name;
  37530. return String::empty;
  37531. }
  37532. int ComboBox::getItemId (const int index) const throw()
  37533. {
  37534. const ItemInfo* const item = getItemForIndex (index);
  37535. return (item != 0) ? item->itemId : 0;
  37536. }
  37537. int ComboBox::indexOfItemId (const int itemId) const throw()
  37538. {
  37539. int n = 0;
  37540. for (int i = 0; i < items.size(); ++i)
  37541. {
  37542. const ItemInfo* const item = items.getUnchecked(i);
  37543. if (item->isRealItem())
  37544. {
  37545. if (item->itemId == itemId)
  37546. return n;
  37547. ++n;
  37548. }
  37549. }
  37550. return -1;
  37551. }
  37552. int ComboBox::getSelectedItemIndex() const throw()
  37553. {
  37554. int index = indexOfItemId (currentId.getValue());
  37555. if (getText() != getItemText (index))
  37556. index = -1;
  37557. return index;
  37558. }
  37559. void ComboBox::setSelectedItemIndex (const int index,
  37560. const bool dontSendChangeMessage) throw()
  37561. {
  37562. setSelectedId (getItemId (index), dontSendChangeMessage);
  37563. }
  37564. int ComboBox::getSelectedId() const throw()
  37565. {
  37566. const ItemInfo* const item = getItemForId (currentId.getValue());
  37567. return (item != 0 && getText() == item->name)
  37568. ? item->itemId
  37569. : 0;
  37570. }
  37571. void ComboBox::setSelectedId (const int newItemId,
  37572. const bool dontSendChangeMessage) throw()
  37573. {
  37574. const ItemInfo* const item = getItemForId (newItemId);
  37575. const String newItemText (item != 0 ? item->name : String::empty);
  37576. if (lastCurrentId != newItemId || label->getText() != newItemText)
  37577. {
  37578. if (! dontSendChangeMessage)
  37579. triggerAsyncUpdate();
  37580. label->setText (newItemText, false);
  37581. lastCurrentId = newItemId;
  37582. currentId = newItemId;
  37583. repaint(); // for the benefit of the 'none selected' text
  37584. }
  37585. }
  37586. void ComboBox::valueChanged (Value&)
  37587. {
  37588. if (lastCurrentId != (int) currentId.getValue())
  37589. setSelectedId (currentId.getValue(), false);
  37590. }
  37591. const String ComboBox::getText() const throw()
  37592. {
  37593. return label->getText();
  37594. }
  37595. void ComboBox::setText (const String& newText,
  37596. const bool dontSendChangeMessage) throw()
  37597. {
  37598. for (int i = items.size(); --i >= 0;)
  37599. {
  37600. const ItemInfo* const item = items.getUnchecked(i);
  37601. if (item->isRealItem()
  37602. && item->name == newText)
  37603. {
  37604. setSelectedId (item->itemId, dontSendChangeMessage);
  37605. return;
  37606. }
  37607. }
  37608. lastCurrentId = 0;
  37609. currentId = 0;
  37610. if (label->getText() != newText)
  37611. {
  37612. label->setText (newText, false);
  37613. if (! dontSendChangeMessage)
  37614. triggerAsyncUpdate();
  37615. }
  37616. repaint();
  37617. }
  37618. void ComboBox::showEditor()
  37619. {
  37620. jassert (isTextEditable()); // you probably shouldn't do this to a non-editable combo box?
  37621. label->showEditor();
  37622. }
  37623. void ComboBox::setTextWhenNothingSelected (const String& newMessage) throw()
  37624. {
  37625. if (textWhenNothingSelected != newMessage)
  37626. {
  37627. textWhenNothingSelected = newMessage;
  37628. repaint();
  37629. }
  37630. }
  37631. const String ComboBox::getTextWhenNothingSelected() const throw()
  37632. {
  37633. return textWhenNothingSelected;
  37634. }
  37635. void ComboBox::setTextWhenNoChoicesAvailable (const String& newMessage) throw()
  37636. {
  37637. noChoicesMessage = newMessage;
  37638. }
  37639. const String ComboBox::getTextWhenNoChoicesAvailable() const throw()
  37640. {
  37641. return noChoicesMessage;
  37642. }
  37643. void ComboBox::paint (Graphics& g)
  37644. {
  37645. getLookAndFeel().drawComboBox (g,
  37646. getWidth(),
  37647. getHeight(),
  37648. isButtonDown,
  37649. label->getRight(),
  37650. 0,
  37651. getWidth() - label->getRight(),
  37652. getHeight(),
  37653. *this);
  37654. if (textWhenNothingSelected.isNotEmpty()
  37655. && label->getText().isEmpty()
  37656. && ! label->isBeingEdited())
  37657. {
  37658. g.setColour (findColour (textColourId).withMultipliedAlpha (0.5f));
  37659. g.setFont (label->getFont());
  37660. g.drawFittedText (textWhenNothingSelected,
  37661. label->getX() + 2, label->getY() + 1,
  37662. label->getWidth() - 4, label->getHeight() - 2,
  37663. label->getJustificationType(),
  37664. jmax (1, (int) (label->getHeight() / label->getFont().getHeight())));
  37665. }
  37666. }
  37667. void ComboBox::resized()
  37668. {
  37669. if (getHeight() > 0 && getWidth() > 0)
  37670. getLookAndFeel().positionComboBoxText (*this, *label);
  37671. }
  37672. void ComboBox::enablementChanged()
  37673. {
  37674. repaint();
  37675. }
  37676. void ComboBox::lookAndFeelChanged()
  37677. {
  37678. repaint();
  37679. Label* const newLabel = getLookAndFeel().createComboBoxTextBox (*this);
  37680. if (label != 0)
  37681. {
  37682. newLabel->setEditable (label->isEditable());
  37683. newLabel->setJustificationType (label->getJustificationType());
  37684. newLabel->setTooltip (label->getTooltip());
  37685. newLabel->setText (label->getText(), false);
  37686. }
  37687. label = newLabel;
  37688. addAndMakeVisible (newLabel);
  37689. newLabel->addListener (this);
  37690. newLabel->addMouseListener (this, false);
  37691. newLabel->setColour (Label::backgroundColourId, Colours::transparentBlack);
  37692. newLabel->setColour (Label::textColourId, findColour (ComboBox::textColourId));
  37693. newLabel->setColour (TextEditor::textColourId, findColour (ComboBox::textColourId));
  37694. newLabel->setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  37695. newLabel->setColour (TextEditor::highlightColourId, findColour (TextEditor::highlightColourId));
  37696. newLabel->setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  37697. resized();
  37698. }
  37699. void ComboBox::colourChanged()
  37700. {
  37701. lookAndFeelChanged();
  37702. }
  37703. bool ComboBox::keyPressed (const KeyPress& key)
  37704. {
  37705. bool used = false;
  37706. if (key.isKeyCode (KeyPress::upKey)
  37707. || key.isKeyCode (KeyPress::leftKey))
  37708. {
  37709. setSelectedItemIndex (jmax (0, getSelectedItemIndex() - 1));
  37710. used = true;
  37711. }
  37712. else if (key.isKeyCode (KeyPress::downKey)
  37713. || key.isKeyCode (KeyPress::rightKey))
  37714. {
  37715. setSelectedItemIndex (jmin (getSelectedItemIndex() + 1, getNumItems() - 1));
  37716. used = true;
  37717. }
  37718. else if (key.isKeyCode (KeyPress::returnKey))
  37719. {
  37720. showPopup();
  37721. used = true;
  37722. }
  37723. return used;
  37724. }
  37725. bool ComboBox::keyStateChanged (const bool isKeyDown)
  37726. {
  37727. // only forward key events that aren't used by this component
  37728. return isKeyDown
  37729. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  37730. || KeyPress::isKeyCurrentlyDown (KeyPress::leftKey)
  37731. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  37732. || KeyPress::isKeyCurrentlyDown (KeyPress::rightKey));
  37733. }
  37734. void ComboBox::focusGained (FocusChangeType)
  37735. {
  37736. repaint();
  37737. }
  37738. void ComboBox::focusLost (FocusChangeType)
  37739. {
  37740. repaint();
  37741. }
  37742. void ComboBox::labelTextChanged (Label*)
  37743. {
  37744. triggerAsyncUpdate();
  37745. }
  37746. class ComboBox::Callback : public ModalComponentManager::Callback
  37747. {
  37748. public:
  37749. Callback (ComboBox* const box_)
  37750. : box (box_)
  37751. {
  37752. }
  37753. void modalStateFinished (int returnValue)
  37754. {
  37755. if (box != 0)
  37756. {
  37757. box->menuActive = false;
  37758. if (returnValue != 0)
  37759. box->setSelectedId (returnValue);
  37760. }
  37761. }
  37762. private:
  37763. Component::SafePointer<ComboBox> box;
  37764. Callback (const Callback&);
  37765. Callback& operator= (const Callback&);
  37766. };
  37767. void ComboBox::showPopup()
  37768. {
  37769. if (! menuActive)
  37770. {
  37771. const int selectedId = getSelectedId();
  37772. PopupMenu menu;
  37773. menu.setLookAndFeel (&getLookAndFeel());
  37774. for (int i = 0; i < items.size(); ++i)
  37775. {
  37776. const ItemInfo* const item = items.getUnchecked(i);
  37777. if (item->isSeparator())
  37778. menu.addSeparator();
  37779. else if (item->isHeading)
  37780. menu.addSectionHeader (item->name);
  37781. else
  37782. menu.addItem (item->itemId, item->name,
  37783. item->isEnabled, item->itemId == selectedId);
  37784. }
  37785. if (items.size() == 0)
  37786. menu.addItem (1, noChoicesMessage, false);
  37787. menuActive = true;
  37788. menu.showAt (this, selectedId, getWidth(), 1, jlimit (12, 24, getHeight()),
  37789. new Callback (this));
  37790. }
  37791. }
  37792. void ComboBox::mouseDown (const MouseEvent& e)
  37793. {
  37794. beginDragAutoRepeat (300);
  37795. isButtonDown = isEnabled();
  37796. if (isButtonDown
  37797. && (e.eventComponent == this || ! label->isEditable()))
  37798. {
  37799. showPopup();
  37800. }
  37801. }
  37802. void ComboBox::mouseDrag (const MouseEvent& e)
  37803. {
  37804. beginDragAutoRepeat (50);
  37805. if (isButtonDown && ! e.mouseWasClicked())
  37806. showPopup();
  37807. }
  37808. void ComboBox::mouseUp (const MouseEvent& e2)
  37809. {
  37810. if (isButtonDown)
  37811. {
  37812. isButtonDown = false;
  37813. repaint();
  37814. const MouseEvent e (e2.getEventRelativeTo (this));
  37815. if (reallyContains (e.x, e.y, true)
  37816. && (e2.eventComponent == this || ! label->isEditable()))
  37817. {
  37818. showPopup();
  37819. }
  37820. }
  37821. }
  37822. void ComboBox::addListener (ComboBoxListener* const listener) throw()
  37823. {
  37824. listeners.add (listener);
  37825. }
  37826. void ComboBox::removeListener (ComboBoxListener* const listener) throw()
  37827. {
  37828. listeners.remove (listener);
  37829. }
  37830. void ComboBox::handleAsyncUpdate()
  37831. {
  37832. Component::BailOutChecker checker (this);
  37833. listeners.callChecked (checker, &ComboBoxListener::comboBoxChanged, this);
  37834. }
  37835. END_JUCE_NAMESPACE
  37836. /*** End of inlined file: juce_ComboBox.cpp ***/
  37837. /*** Start of inlined file: juce_Label.cpp ***/
  37838. BEGIN_JUCE_NAMESPACE
  37839. Label::Label (const String& componentName,
  37840. const String& labelText)
  37841. : Component (componentName),
  37842. textValue (labelText),
  37843. lastTextValue (labelText),
  37844. font (15.0f),
  37845. justification (Justification::centredLeft),
  37846. ownerComponent (0),
  37847. horizontalBorderSize (5),
  37848. verticalBorderSize (1),
  37849. minimumHorizontalScale (0.7f),
  37850. editSingleClick (false),
  37851. editDoubleClick (false),
  37852. lossOfFocusDiscardsChanges (false)
  37853. {
  37854. setColour (TextEditor::textColourId, Colours::black);
  37855. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  37856. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  37857. textValue.addListener (this);
  37858. }
  37859. Label::~Label()
  37860. {
  37861. textValue.removeListener (this);
  37862. if (ownerComponent != 0)
  37863. ownerComponent->removeComponentListener (this);
  37864. editor = 0;
  37865. }
  37866. void Label::setText (const String& newText,
  37867. const bool broadcastChangeMessage)
  37868. {
  37869. hideEditor (true);
  37870. if (lastTextValue != newText)
  37871. {
  37872. lastTextValue = newText;
  37873. textValue = newText;
  37874. repaint();
  37875. textWasChanged();
  37876. if (ownerComponent != 0)
  37877. componentMovedOrResized (*ownerComponent, true, true);
  37878. if (broadcastChangeMessage)
  37879. callChangeListeners();
  37880. }
  37881. }
  37882. const String Label::getText (const bool returnActiveEditorContents) const throw()
  37883. {
  37884. return (returnActiveEditorContents && isBeingEdited())
  37885. ? editor->getText()
  37886. : textValue.toString();
  37887. }
  37888. void Label::valueChanged (Value&)
  37889. {
  37890. if (lastTextValue != textValue.toString())
  37891. setText (textValue.toString(), true);
  37892. }
  37893. void Label::setFont (const Font& newFont) throw()
  37894. {
  37895. if (font != newFont)
  37896. {
  37897. font = newFont;
  37898. repaint();
  37899. }
  37900. }
  37901. const Font& Label::getFont() const throw()
  37902. {
  37903. return font;
  37904. }
  37905. void Label::setEditable (const bool editOnSingleClick,
  37906. const bool editOnDoubleClick,
  37907. const bool lossOfFocusDiscardsChanges_) throw()
  37908. {
  37909. editSingleClick = editOnSingleClick;
  37910. editDoubleClick = editOnDoubleClick;
  37911. lossOfFocusDiscardsChanges = lossOfFocusDiscardsChanges_;
  37912. setWantsKeyboardFocus (editOnSingleClick || editOnDoubleClick);
  37913. setFocusContainer (editOnSingleClick || editOnDoubleClick);
  37914. }
  37915. void Label::setJustificationType (const Justification& newJustification) throw()
  37916. {
  37917. if (justification != newJustification)
  37918. {
  37919. justification = newJustification;
  37920. repaint();
  37921. }
  37922. }
  37923. void Label::setBorderSize (int h, int v)
  37924. {
  37925. if (horizontalBorderSize != h || verticalBorderSize != v)
  37926. {
  37927. horizontalBorderSize = h;
  37928. verticalBorderSize = v;
  37929. repaint();
  37930. }
  37931. }
  37932. Component* Label::getAttachedComponent() const
  37933. {
  37934. return static_cast<Component*> (ownerComponent);
  37935. }
  37936. void Label::attachToComponent (Component* owner,
  37937. const bool onLeft)
  37938. {
  37939. if (ownerComponent != 0)
  37940. ownerComponent->removeComponentListener (this);
  37941. ownerComponent = owner;
  37942. leftOfOwnerComp = onLeft;
  37943. if (ownerComponent != 0)
  37944. {
  37945. setVisible (owner->isVisible());
  37946. ownerComponent->addComponentListener (this);
  37947. componentParentHierarchyChanged (*ownerComponent);
  37948. componentMovedOrResized (*ownerComponent, true, true);
  37949. }
  37950. }
  37951. void Label::componentMovedOrResized (Component& component, bool /*wasMoved*/, bool /*wasResized*/)
  37952. {
  37953. if (leftOfOwnerComp)
  37954. {
  37955. setSize (jmin (getFont().getStringWidth (textValue.toString()) + 8, component.getX()),
  37956. component.getHeight());
  37957. setTopRightPosition (component.getX(), component.getY());
  37958. }
  37959. else
  37960. {
  37961. setSize (component.getWidth(),
  37962. 8 + roundToInt (getFont().getHeight()));
  37963. setTopLeftPosition (component.getX(), component.getY() - getHeight());
  37964. }
  37965. }
  37966. void Label::componentParentHierarchyChanged (Component& component)
  37967. {
  37968. if (component.getParentComponent() != 0)
  37969. component.getParentComponent()->addChildComponent (this);
  37970. }
  37971. void Label::componentVisibilityChanged (Component& component)
  37972. {
  37973. setVisible (component.isVisible());
  37974. }
  37975. void Label::textWasEdited()
  37976. {
  37977. }
  37978. void Label::textWasChanged()
  37979. {
  37980. }
  37981. void Label::showEditor()
  37982. {
  37983. if (editor == 0)
  37984. {
  37985. addAndMakeVisible (editor = createEditorComponent());
  37986. editor->setText (getText(), false);
  37987. editor->addListener (this);
  37988. editor->grabKeyboardFocus();
  37989. editor->setHighlightedRegion (Range<int> (0, textValue.toString().length()));
  37990. editor->addListener (this);
  37991. resized();
  37992. repaint();
  37993. editorShown (editor);
  37994. enterModalState (false);
  37995. editor->grabKeyboardFocus();
  37996. }
  37997. }
  37998. void Label::editorShown (TextEditor* /*editorComponent*/)
  37999. {
  38000. }
  38001. void Label::editorAboutToBeHidden (TextEditor* /*editorComponent*/)
  38002. {
  38003. }
  38004. bool Label::updateFromTextEditorContents()
  38005. {
  38006. jassert (editor != 0);
  38007. const String newText (editor->getText());
  38008. if (textValue.toString() != newText)
  38009. {
  38010. lastTextValue = newText;
  38011. textValue = newText;
  38012. repaint();
  38013. textWasChanged();
  38014. if (ownerComponent != 0)
  38015. componentMovedOrResized (*ownerComponent, true, true);
  38016. return true;
  38017. }
  38018. return false;
  38019. }
  38020. void Label::hideEditor (const bool discardCurrentEditorContents)
  38021. {
  38022. if (editor != 0)
  38023. {
  38024. Component::SafePointer<Component> deletionChecker (this);
  38025. editorAboutToBeHidden (editor);
  38026. const bool changed = (! discardCurrentEditorContents)
  38027. && updateFromTextEditorContents();
  38028. editor = 0;
  38029. repaint();
  38030. if (changed)
  38031. textWasEdited();
  38032. if (deletionChecker != 0)
  38033. exitModalState (0);
  38034. if (changed && deletionChecker != 0)
  38035. callChangeListeners();
  38036. }
  38037. }
  38038. void Label::inputAttemptWhenModal()
  38039. {
  38040. if (editor != 0)
  38041. {
  38042. if (lossOfFocusDiscardsChanges)
  38043. textEditorEscapeKeyPressed (*editor);
  38044. else
  38045. textEditorReturnKeyPressed (*editor);
  38046. }
  38047. }
  38048. bool Label::isBeingEdited() const throw()
  38049. {
  38050. return editor != 0;
  38051. }
  38052. TextEditor* Label::createEditorComponent()
  38053. {
  38054. TextEditor* const ed = new TextEditor (getName());
  38055. ed->setFont (font);
  38056. // copy these colours from our own settings..
  38057. const int cols[] = { TextEditor::backgroundColourId,
  38058. TextEditor::textColourId,
  38059. TextEditor::highlightColourId,
  38060. TextEditor::highlightedTextColourId,
  38061. TextEditor::caretColourId,
  38062. TextEditor::outlineColourId,
  38063. TextEditor::focusedOutlineColourId,
  38064. TextEditor::shadowColourId };
  38065. for (int i = 0; i < numElementsInArray (cols); ++i)
  38066. ed->setColour (cols[i], findColour (cols[i]));
  38067. return ed;
  38068. }
  38069. void Label::paint (Graphics& g)
  38070. {
  38071. getLookAndFeel().drawLabel (g, *this);
  38072. }
  38073. void Label::mouseUp (const MouseEvent& e)
  38074. {
  38075. if (editSingleClick
  38076. && e.mouseWasClicked()
  38077. && contains (e.x, e.y)
  38078. && ! e.mods.isPopupMenu())
  38079. {
  38080. showEditor();
  38081. }
  38082. }
  38083. void Label::mouseDoubleClick (const MouseEvent& e)
  38084. {
  38085. if (editDoubleClick && ! e.mods.isPopupMenu())
  38086. showEditor();
  38087. }
  38088. void Label::resized()
  38089. {
  38090. if (editor != 0)
  38091. editor->setBoundsInset (BorderSize (0));
  38092. }
  38093. void Label::focusGained (FocusChangeType cause)
  38094. {
  38095. if (editSingleClick && cause == focusChangedByTabKey)
  38096. showEditor();
  38097. }
  38098. void Label::enablementChanged()
  38099. {
  38100. repaint();
  38101. }
  38102. void Label::colourChanged()
  38103. {
  38104. repaint();
  38105. }
  38106. void Label::setMinimumHorizontalScale (const float newScale)
  38107. {
  38108. if (minimumHorizontalScale != newScale)
  38109. {
  38110. minimumHorizontalScale = newScale;
  38111. repaint();
  38112. }
  38113. }
  38114. // We'll use a custom focus traverser here to make sure focus goes from the
  38115. // text editor to another component rather than back to the label itself.
  38116. class LabelKeyboardFocusTraverser : public KeyboardFocusTraverser
  38117. {
  38118. public:
  38119. LabelKeyboardFocusTraverser() {}
  38120. Component* getNextComponent (Component* current)
  38121. {
  38122. return KeyboardFocusTraverser::getNextComponent (dynamic_cast <TextEditor*> (current) != 0
  38123. ? current->getParentComponent() : current);
  38124. }
  38125. Component* getPreviousComponent (Component* current)
  38126. {
  38127. return KeyboardFocusTraverser::getPreviousComponent (dynamic_cast <TextEditor*> (current) != 0
  38128. ? current->getParentComponent() : current);
  38129. }
  38130. };
  38131. KeyboardFocusTraverser* Label::createFocusTraverser()
  38132. {
  38133. return new LabelKeyboardFocusTraverser();
  38134. }
  38135. void Label::addListener (LabelListener* const listener) throw()
  38136. {
  38137. listeners.add (listener);
  38138. }
  38139. void Label::removeListener (LabelListener* const listener) throw()
  38140. {
  38141. listeners.remove (listener);
  38142. }
  38143. void Label::callChangeListeners()
  38144. {
  38145. Component::BailOutChecker checker (this);
  38146. listeners.callChecked (checker, &LabelListener::labelTextChanged, this);
  38147. }
  38148. void Label::textEditorTextChanged (TextEditor& ed)
  38149. {
  38150. if (editor != 0)
  38151. {
  38152. jassert (&ed == editor);
  38153. if (! (hasKeyboardFocus (true) || isCurrentlyBlockedByAnotherModalComponent()))
  38154. {
  38155. if (lossOfFocusDiscardsChanges)
  38156. textEditorEscapeKeyPressed (ed);
  38157. else
  38158. textEditorReturnKeyPressed (ed);
  38159. }
  38160. }
  38161. }
  38162. void Label::textEditorReturnKeyPressed (TextEditor& ed)
  38163. {
  38164. if (editor != 0)
  38165. {
  38166. jassert (&ed == editor);
  38167. (void) ed;
  38168. const bool changed = updateFromTextEditorContents();
  38169. hideEditor (true);
  38170. if (changed)
  38171. {
  38172. Component::SafePointer<Component> deletionChecker (this);
  38173. textWasEdited();
  38174. if (deletionChecker != 0)
  38175. callChangeListeners();
  38176. }
  38177. }
  38178. }
  38179. void Label::textEditorEscapeKeyPressed (TextEditor& ed)
  38180. {
  38181. if (editor != 0)
  38182. {
  38183. jassert (&ed == editor);
  38184. (void) ed;
  38185. editor->setText (textValue.toString(), false);
  38186. hideEditor (true);
  38187. }
  38188. }
  38189. void Label::textEditorFocusLost (TextEditor& ed)
  38190. {
  38191. textEditorTextChanged (ed);
  38192. }
  38193. END_JUCE_NAMESPACE
  38194. /*** End of inlined file: juce_Label.cpp ***/
  38195. /*** Start of inlined file: juce_ListBox.cpp ***/
  38196. BEGIN_JUCE_NAMESPACE
  38197. class ListBoxRowComponent : public Component,
  38198. public TooltipClient
  38199. {
  38200. public:
  38201. ListBoxRowComponent (ListBox& owner_)
  38202. : owner (owner_),
  38203. row (-1),
  38204. selected (false),
  38205. isDragging (false)
  38206. {
  38207. }
  38208. ~ListBoxRowComponent()
  38209. {
  38210. deleteAllChildren();
  38211. }
  38212. void paint (Graphics& g)
  38213. {
  38214. if (owner.getModel() != 0)
  38215. owner.getModel()->paintListBoxItem (row, g, getWidth(), getHeight(), selected);
  38216. }
  38217. void update (const int row_, const bool selected_)
  38218. {
  38219. if (row != row_ || selected != selected_)
  38220. {
  38221. repaint();
  38222. row = row_;
  38223. selected = selected_;
  38224. }
  38225. if (owner.getModel() != 0)
  38226. {
  38227. Component* const customComp = owner.getModel()->refreshComponentForRow (row_, selected_, getChildComponent (0));
  38228. if (customComp != 0)
  38229. {
  38230. addAndMakeVisible (customComp);
  38231. customComp->setBounds (getLocalBounds());
  38232. for (int i = getNumChildComponents(); --i >= 0;)
  38233. if (getChildComponent (i) != customComp)
  38234. delete getChildComponent (i);
  38235. }
  38236. else
  38237. {
  38238. deleteAllChildren();
  38239. }
  38240. }
  38241. }
  38242. void mouseDown (const MouseEvent& e)
  38243. {
  38244. isDragging = false;
  38245. selectRowOnMouseUp = false;
  38246. if (isEnabled())
  38247. {
  38248. if (! selected)
  38249. {
  38250. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  38251. if (owner.getModel() != 0)
  38252. owner.getModel()->listBoxItemClicked (row, e);
  38253. }
  38254. else
  38255. {
  38256. selectRowOnMouseUp = true;
  38257. }
  38258. }
  38259. }
  38260. void mouseUp (const MouseEvent& e)
  38261. {
  38262. if (isEnabled() && selectRowOnMouseUp && ! isDragging)
  38263. {
  38264. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  38265. if (owner.getModel() != 0)
  38266. owner.getModel()->listBoxItemClicked (row, e);
  38267. }
  38268. }
  38269. void mouseDoubleClick (const MouseEvent& e)
  38270. {
  38271. if (owner.getModel() != 0 && isEnabled())
  38272. owner.getModel()->listBoxItemDoubleClicked (row, e);
  38273. }
  38274. void mouseDrag (const MouseEvent& e)
  38275. {
  38276. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  38277. {
  38278. const SparseSet<int> selectedRows (owner.getSelectedRows());
  38279. if (selectedRows.size() > 0)
  38280. {
  38281. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  38282. if (dragDescription.isNotEmpty())
  38283. {
  38284. isDragging = true;
  38285. owner.startDragAndDrop (e, dragDescription);
  38286. }
  38287. }
  38288. }
  38289. }
  38290. void resized()
  38291. {
  38292. if (getNumChildComponents() > 0)
  38293. getChildComponent(0)->setBounds (getLocalBounds());
  38294. }
  38295. const String getTooltip()
  38296. {
  38297. if (owner.getModel() != 0)
  38298. return owner.getModel()->getTooltipForRow (row);
  38299. return String::empty;
  38300. }
  38301. juce_UseDebuggingNewOperator
  38302. bool neededFlag;
  38303. private:
  38304. ListBox& owner;
  38305. int row;
  38306. bool selected, isDragging, selectRowOnMouseUp;
  38307. ListBoxRowComponent (const ListBoxRowComponent&);
  38308. ListBoxRowComponent& operator= (const ListBoxRowComponent&);
  38309. };
  38310. class ListViewport : public Viewport
  38311. {
  38312. public:
  38313. int firstIndex, firstWholeIndex, lastWholeIndex;
  38314. bool hasUpdated;
  38315. ListViewport (ListBox& owner_)
  38316. : owner (owner_)
  38317. {
  38318. setWantsKeyboardFocus (false);
  38319. setViewedComponent (new Component());
  38320. getViewedComponent()->addMouseListener (this, false);
  38321. getViewedComponent()->setWantsKeyboardFocus (false);
  38322. }
  38323. ~ListViewport()
  38324. {
  38325. getViewedComponent()->removeMouseListener (this);
  38326. getViewedComponent()->deleteAllChildren();
  38327. }
  38328. ListBoxRowComponent* getComponentForRow (const int row) const throw()
  38329. {
  38330. return static_cast <ListBoxRowComponent*>
  38331. (getViewedComponent()->getChildComponent (row % jmax (1, getViewedComponent()->getNumChildComponents())));
  38332. }
  38333. int getRowNumberOfComponent (Component* const rowComponent) const throw()
  38334. {
  38335. const int index = getIndexOfChildComponent (rowComponent);
  38336. const int num = getViewedComponent()->getNumChildComponents();
  38337. for (int i = num; --i >= 0;)
  38338. if (((firstIndex + i) % jmax (1, num)) == index)
  38339. return firstIndex + i;
  38340. return -1;
  38341. }
  38342. Component* getComponentForRowIfOnscreen (const int row) const throw()
  38343. {
  38344. return (row >= firstIndex && row < firstIndex + getViewedComponent()->getNumChildComponents())
  38345. ? getComponentForRow (row) : 0;
  38346. }
  38347. void visibleAreaChanged (int, int, int, int)
  38348. {
  38349. updateVisibleArea (true);
  38350. if (owner.getModel() != 0)
  38351. owner.getModel()->listWasScrolled();
  38352. }
  38353. void updateVisibleArea (const bool makeSureItUpdatesContent)
  38354. {
  38355. hasUpdated = false;
  38356. const int newX = getViewedComponent()->getX();
  38357. int newY = getViewedComponent()->getY();
  38358. const int newW = jmax (owner.minimumRowWidth, getMaximumVisibleWidth());
  38359. const int newH = owner.totalItems * owner.getRowHeight();
  38360. if (newY + newH < getMaximumVisibleHeight() && newH > getMaximumVisibleHeight())
  38361. newY = getMaximumVisibleHeight() - newH;
  38362. getViewedComponent()->setBounds (newX, newY, newW, newH);
  38363. if (makeSureItUpdatesContent && ! hasUpdated)
  38364. updateContents();
  38365. }
  38366. void updateContents()
  38367. {
  38368. hasUpdated = true;
  38369. const int rowHeight = owner.getRowHeight();
  38370. if (rowHeight > 0)
  38371. {
  38372. const int y = getViewPositionY();
  38373. const int w = getViewedComponent()->getWidth();
  38374. const int numNeeded = 2 + getMaximumVisibleHeight() / rowHeight;
  38375. while (numNeeded > getViewedComponent()->getNumChildComponents())
  38376. getViewedComponent()->addAndMakeVisible (new ListBoxRowComponent (owner));
  38377. jassert (numNeeded >= 0);
  38378. while (numNeeded < getViewedComponent()->getNumChildComponents())
  38379. {
  38380. Component* const rowToRemove
  38381. = getViewedComponent()->getChildComponent (getViewedComponent()->getNumChildComponents() - 1);
  38382. delete rowToRemove;
  38383. }
  38384. firstIndex = y / rowHeight;
  38385. firstWholeIndex = (y + rowHeight - 1) / rowHeight;
  38386. lastWholeIndex = (y + getMaximumVisibleHeight() - 1) / rowHeight;
  38387. for (int i = 0; i < numNeeded; ++i)
  38388. {
  38389. const int row = i + firstIndex;
  38390. ListBoxRowComponent* const rowComp = getComponentForRow (row);
  38391. if (rowComp != 0)
  38392. {
  38393. rowComp->setBounds (0, row * rowHeight, w, rowHeight);
  38394. rowComp->update (row, owner.isRowSelected (row));
  38395. }
  38396. }
  38397. }
  38398. if (owner.headerComponent != 0)
  38399. owner.headerComponent->setBounds (owner.outlineThickness + getViewedComponent()->getX(),
  38400. owner.outlineThickness,
  38401. jmax (owner.getWidth() - owner.outlineThickness * 2,
  38402. getViewedComponent()->getWidth()),
  38403. owner.headerComponent->getHeight());
  38404. }
  38405. void paint (Graphics& g)
  38406. {
  38407. if (isOpaque())
  38408. g.fillAll (owner.findColour (ListBox::backgroundColourId));
  38409. }
  38410. bool keyPressed (const KeyPress& key)
  38411. {
  38412. if (key.isKeyCode (KeyPress::upKey)
  38413. || key.isKeyCode (KeyPress::downKey)
  38414. || key.isKeyCode (KeyPress::pageUpKey)
  38415. || key.isKeyCode (KeyPress::pageDownKey)
  38416. || key.isKeyCode (KeyPress::homeKey)
  38417. || key.isKeyCode (KeyPress::endKey))
  38418. {
  38419. // we want to avoid these keypresses going to the viewport, and instead allow
  38420. // them to pass up to our listbox..
  38421. return false;
  38422. }
  38423. return Viewport::keyPressed (key);
  38424. }
  38425. juce_UseDebuggingNewOperator
  38426. private:
  38427. ListBox& owner;
  38428. ListViewport (const ListViewport&);
  38429. ListViewport& operator= (const ListViewport&);
  38430. };
  38431. ListBox::ListBox (const String& name, ListBoxModel* const model_)
  38432. : Component (name),
  38433. model (model_),
  38434. totalItems (0),
  38435. rowHeight (22),
  38436. minimumRowWidth (0),
  38437. outlineThickness (0),
  38438. lastRowSelected (-1),
  38439. mouseMoveSelects (false),
  38440. multipleSelection (false),
  38441. hasDoneInitialUpdate (false)
  38442. {
  38443. addAndMakeVisible (viewport = new ListViewport (*this));
  38444. setWantsKeyboardFocus (true);
  38445. colourChanged();
  38446. }
  38447. ListBox::~ListBox()
  38448. {
  38449. headerComponent = 0;
  38450. viewport = 0;
  38451. }
  38452. void ListBox::setModel (ListBoxModel* const newModel)
  38453. {
  38454. if (model != newModel)
  38455. {
  38456. model = newModel;
  38457. updateContent();
  38458. }
  38459. }
  38460. void ListBox::setMultipleSelectionEnabled (bool b)
  38461. {
  38462. multipleSelection = b;
  38463. }
  38464. void ListBox::setMouseMoveSelectsRows (bool b)
  38465. {
  38466. mouseMoveSelects = b;
  38467. if (b)
  38468. addMouseListener (this, true);
  38469. }
  38470. void ListBox::paint (Graphics& g)
  38471. {
  38472. if (! hasDoneInitialUpdate)
  38473. updateContent();
  38474. g.fillAll (findColour (backgroundColourId));
  38475. }
  38476. void ListBox::paintOverChildren (Graphics& g)
  38477. {
  38478. if (outlineThickness > 0)
  38479. {
  38480. g.setColour (findColour (outlineColourId));
  38481. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  38482. }
  38483. }
  38484. void ListBox::resized()
  38485. {
  38486. viewport->setBoundsInset (BorderSize (outlineThickness + ((headerComponent != 0) ? headerComponent->getHeight() : 0),
  38487. outlineThickness,
  38488. outlineThickness,
  38489. outlineThickness));
  38490. viewport->setSingleStepSizes (20, getRowHeight());
  38491. viewport->updateVisibleArea (false);
  38492. }
  38493. void ListBox::visibilityChanged()
  38494. {
  38495. viewport->updateVisibleArea (true);
  38496. }
  38497. Viewport* ListBox::getViewport() const throw()
  38498. {
  38499. return viewport;
  38500. }
  38501. void ListBox::updateContent()
  38502. {
  38503. hasDoneInitialUpdate = true;
  38504. totalItems = (model != 0) ? model->getNumRows() : 0;
  38505. bool selectionChanged = false;
  38506. if (selected [selected.size() - 1] >= totalItems)
  38507. {
  38508. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  38509. lastRowSelected = getSelectedRow (0);
  38510. selectionChanged = true;
  38511. }
  38512. viewport->updateVisibleArea (isVisible());
  38513. viewport->resized();
  38514. if (selectionChanged && model != 0)
  38515. model->selectedRowsChanged (lastRowSelected);
  38516. }
  38517. void ListBox::selectRow (const int row,
  38518. bool dontScroll,
  38519. bool deselectOthersFirst)
  38520. {
  38521. selectRowInternal (row, dontScroll, deselectOthersFirst, false);
  38522. }
  38523. void ListBox::selectRowInternal (const int row,
  38524. bool dontScroll,
  38525. bool deselectOthersFirst,
  38526. bool isMouseClick)
  38527. {
  38528. if (! multipleSelection)
  38529. deselectOthersFirst = true;
  38530. if ((! isRowSelected (row))
  38531. || (deselectOthersFirst && getNumSelectedRows() > 1))
  38532. {
  38533. if (((unsigned int) row) < (unsigned int) totalItems)
  38534. {
  38535. if (deselectOthersFirst)
  38536. selected.clear();
  38537. selected.addRange (Range<int> (row, row + 1));
  38538. if (getHeight() == 0 || getWidth() == 0)
  38539. dontScroll = true;
  38540. viewport->hasUpdated = false;
  38541. if (row < viewport->firstWholeIndex && ! dontScroll)
  38542. {
  38543. viewport->setViewPosition (viewport->getViewPositionX(),
  38544. row * getRowHeight());
  38545. }
  38546. else if (row >= viewport->lastWholeIndex && ! dontScroll)
  38547. {
  38548. const int rowsOnScreen = viewport->lastWholeIndex - viewport->firstWholeIndex;
  38549. if (row >= lastRowSelected + rowsOnScreen
  38550. && rowsOnScreen < totalItems - 1
  38551. && ! isMouseClick)
  38552. {
  38553. viewport->setViewPosition (viewport->getViewPositionX(),
  38554. jlimit (0, jmax (0, totalItems - rowsOnScreen), row)
  38555. * getRowHeight());
  38556. }
  38557. else
  38558. {
  38559. viewport->setViewPosition (viewport->getViewPositionX(),
  38560. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  38561. }
  38562. }
  38563. if (! viewport->hasUpdated)
  38564. viewport->updateContents();
  38565. lastRowSelected = row;
  38566. model->selectedRowsChanged (row);
  38567. }
  38568. else
  38569. {
  38570. if (deselectOthersFirst)
  38571. deselectAllRows();
  38572. }
  38573. }
  38574. }
  38575. void ListBox::deselectRow (const int row)
  38576. {
  38577. if (selected.contains (row))
  38578. {
  38579. selected.removeRange (Range <int> (row, row + 1));
  38580. if (row == lastRowSelected)
  38581. lastRowSelected = getSelectedRow (0);
  38582. viewport->updateContents();
  38583. model->selectedRowsChanged (lastRowSelected);
  38584. }
  38585. }
  38586. void ListBox::setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  38587. const bool sendNotificationEventToModel)
  38588. {
  38589. selected = setOfRowsToBeSelected;
  38590. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  38591. if (! isRowSelected (lastRowSelected))
  38592. lastRowSelected = getSelectedRow (0);
  38593. viewport->updateContents();
  38594. if ((model != 0) && sendNotificationEventToModel)
  38595. model->selectedRowsChanged (lastRowSelected);
  38596. }
  38597. const SparseSet<int> ListBox::getSelectedRows() const
  38598. {
  38599. return selected;
  38600. }
  38601. void ListBox::selectRangeOfRows (int firstRow, int lastRow)
  38602. {
  38603. if (multipleSelection && (firstRow != lastRow))
  38604. {
  38605. const int numRows = totalItems - 1;
  38606. firstRow = jlimit (0, jmax (0, numRows), firstRow);
  38607. lastRow = jlimit (0, jmax (0, numRows), lastRow);
  38608. selected.addRange (Range <int> (jmin (firstRow, lastRow),
  38609. jmax (firstRow, lastRow) + 1));
  38610. selected.removeRange (Range <int> (lastRow, lastRow + 1));
  38611. }
  38612. selectRowInternal (lastRow, false, false, true);
  38613. }
  38614. void ListBox::flipRowSelection (const int row)
  38615. {
  38616. if (isRowSelected (row))
  38617. deselectRow (row);
  38618. else
  38619. selectRowInternal (row, false, false, true);
  38620. }
  38621. void ListBox::deselectAllRows()
  38622. {
  38623. if (! selected.isEmpty())
  38624. {
  38625. selected.clear();
  38626. lastRowSelected = -1;
  38627. viewport->updateContents();
  38628. if (model != 0)
  38629. model->selectedRowsChanged (lastRowSelected);
  38630. }
  38631. }
  38632. void ListBox::selectRowsBasedOnModifierKeys (const int row,
  38633. const ModifierKeys& mods)
  38634. {
  38635. if (multipleSelection && mods.isCommandDown())
  38636. {
  38637. flipRowSelection (row);
  38638. }
  38639. else if (multipleSelection && mods.isShiftDown() && lastRowSelected >= 0)
  38640. {
  38641. selectRangeOfRows (lastRowSelected, row);
  38642. }
  38643. else if ((! mods.isPopupMenu()) || ! isRowSelected (row))
  38644. {
  38645. selectRowInternal (row, false, true, true);
  38646. }
  38647. }
  38648. int ListBox::getNumSelectedRows() const
  38649. {
  38650. return selected.size();
  38651. }
  38652. int ListBox::getSelectedRow (const int index) const
  38653. {
  38654. return (((unsigned int) index) < (unsigned int) selected.size())
  38655. ? selected [index] : -1;
  38656. }
  38657. bool ListBox::isRowSelected (const int row) const
  38658. {
  38659. return selected.contains (row);
  38660. }
  38661. int ListBox::getLastRowSelected() const
  38662. {
  38663. return (isRowSelected (lastRowSelected)) ? lastRowSelected : -1;
  38664. }
  38665. int ListBox::getRowContainingPosition (const int x, const int y) const throw()
  38666. {
  38667. if (((unsigned int) x) < (unsigned int) getWidth())
  38668. {
  38669. const int row = (viewport->getViewPositionY() + y - viewport->getY()) / rowHeight;
  38670. if (((unsigned int) row) < (unsigned int) totalItems)
  38671. return row;
  38672. }
  38673. return -1;
  38674. }
  38675. int ListBox::getInsertionIndexForPosition (const int x, const int y) const throw()
  38676. {
  38677. if (((unsigned int) x) < (unsigned int) getWidth())
  38678. {
  38679. const int row = (viewport->getViewPositionY() + y + rowHeight / 2 - viewport->getY()) / rowHeight;
  38680. return jlimit (0, totalItems, row);
  38681. }
  38682. return -1;
  38683. }
  38684. Component* ListBox::getComponentForRowNumber (const int row) const throw()
  38685. {
  38686. Component* const listRowComp = viewport->getComponentForRowIfOnscreen (row);
  38687. return listRowComp != 0 ? listRowComp->getChildComponent (0) : 0;
  38688. }
  38689. int ListBox::getRowNumberOfComponent (Component* const rowComponent) const throw()
  38690. {
  38691. return viewport->getRowNumberOfComponent (rowComponent);
  38692. }
  38693. const Rectangle<int> ListBox::getRowPosition (const int rowNumber,
  38694. const bool relativeToComponentTopLeft) const throw()
  38695. {
  38696. int y = viewport->getY() + rowHeight * rowNumber;
  38697. if (relativeToComponentTopLeft)
  38698. y -= viewport->getViewPositionY();
  38699. return Rectangle<int> (viewport->getX(), y,
  38700. viewport->getViewedComponent()->getWidth(), rowHeight);
  38701. }
  38702. void ListBox::setVerticalPosition (const double proportion)
  38703. {
  38704. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  38705. viewport->setViewPosition (viewport->getViewPositionX(),
  38706. jmax (0, roundToInt (proportion * offscreen)));
  38707. }
  38708. double ListBox::getVerticalPosition() const
  38709. {
  38710. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  38711. return (offscreen > 0) ? viewport->getViewPositionY() / (double) offscreen
  38712. : 0;
  38713. }
  38714. int ListBox::getVisibleRowWidth() const throw()
  38715. {
  38716. return viewport->getViewWidth();
  38717. }
  38718. void ListBox::scrollToEnsureRowIsOnscreen (const int row)
  38719. {
  38720. if (row < viewport->firstWholeIndex)
  38721. {
  38722. viewport->setViewPosition (viewport->getViewPositionX(),
  38723. row * getRowHeight());
  38724. }
  38725. else if (row >= viewport->lastWholeIndex)
  38726. {
  38727. viewport->setViewPosition (viewport->getViewPositionX(),
  38728. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  38729. }
  38730. }
  38731. bool ListBox::keyPressed (const KeyPress& key)
  38732. {
  38733. const int numVisibleRows = viewport->getHeight() / getRowHeight();
  38734. const bool multiple = multipleSelection
  38735. && (lastRowSelected >= 0)
  38736. && (key.getModifiers().isShiftDown()
  38737. || key.getModifiers().isCtrlDown()
  38738. || key.getModifiers().isCommandDown());
  38739. if (key.isKeyCode (KeyPress::upKey))
  38740. {
  38741. if (multiple)
  38742. selectRangeOfRows (lastRowSelected, lastRowSelected - 1);
  38743. else
  38744. selectRow (jmax (0, lastRowSelected - 1));
  38745. }
  38746. else if (key.isKeyCode (KeyPress::returnKey)
  38747. && isRowSelected (lastRowSelected))
  38748. {
  38749. if (model != 0)
  38750. model->returnKeyPressed (lastRowSelected);
  38751. }
  38752. else if (key.isKeyCode (KeyPress::pageUpKey))
  38753. {
  38754. if (multiple)
  38755. selectRangeOfRows (lastRowSelected, lastRowSelected - numVisibleRows);
  38756. else
  38757. selectRow (jmax (0, jmax (0, lastRowSelected) - numVisibleRows));
  38758. }
  38759. else if (key.isKeyCode (KeyPress::pageDownKey))
  38760. {
  38761. if (multiple)
  38762. selectRangeOfRows (lastRowSelected, lastRowSelected + numVisibleRows);
  38763. else
  38764. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + numVisibleRows));
  38765. }
  38766. else if (key.isKeyCode (KeyPress::homeKey))
  38767. {
  38768. if (multiple && key.getModifiers().isShiftDown())
  38769. selectRangeOfRows (lastRowSelected, 0);
  38770. else
  38771. selectRow (0);
  38772. }
  38773. else if (key.isKeyCode (KeyPress::endKey))
  38774. {
  38775. if (multiple && key.getModifiers().isShiftDown())
  38776. selectRangeOfRows (lastRowSelected, totalItems - 1);
  38777. else
  38778. selectRow (totalItems - 1);
  38779. }
  38780. else if (key.isKeyCode (KeyPress::downKey))
  38781. {
  38782. if (multiple)
  38783. selectRangeOfRows (lastRowSelected, lastRowSelected + 1);
  38784. else
  38785. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + 1));
  38786. }
  38787. else if ((key.isKeyCode (KeyPress::deleteKey) || key.isKeyCode (KeyPress::backspaceKey))
  38788. && isRowSelected (lastRowSelected))
  38789. {
  38790. if (model != 0)
  38791. model->deleteKeyPressed (lastRowSelected);
  38792. }
  38793. else if (multiple && key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  38794. {
  38795. selectRangeOfRows (0, std::numeric_limits<int>::max());
  38796. }
  38797. else
  38798. {
  38799. return false;
  38800. }
  38801. return true;
  38802. }
  38803. bool ListBox::keyStateChanged (const bool isKeyDown)
  38804. {
  38805. return isKeyDown
  38806. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  38807. || KeyPress::isKeyCurrentlyDown (KeyPress::pageUpKey)
  38808. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  38809. || KeyPress::isKeyCurrentlyDown (KeyPress::pageDownKey)
  38810. || KeyPress::isKeyCurrentlyDown (KeyPress::homeKey)
  38811. || KeyPress::isKeyCurrentlyDown (KeyPress::endKey)
  38812. || KeyPress::isKeyCurrentlyDown (KeyPress::returnKey));
  38813. }
  38814. void ListBox::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  38815. {
  38816. getHorizontalScrollBar()->mouseWheelMove (e, wheelIncrementX, 0);
  38817. getVerticalScrollBar()->mouseWheelMove (e, 0, wheelIncrementY);
  38818. }
  38819. void ListBox::mouseMove (const MouseEvent& e)
  38820. {
  38821. if (mouseMoveSelects)
  38822. {
  38823. const MouseEvent e2 (e.getEventRelativeTo (this));
  38824. selectRow (getRowContainingPosition (e2.x, e2.y), true);
  38825. }
  38826. }
  38827. void ListBox::mouseExit (const MouseEvent& e)
  38828. {
  38829. mouseMove (e);
  38830. }
  38831. void ListBox::mouseUp (const MouseEvent& e)
  38832. {
  38833. if (e.mouseWasClicked() && model != 0)
  38834. model->backgroundClicked();
  38835. }
  38836. void ListBox::setRowHeight (const int newHeight)
  38837. {
  38838. rowHeight = jmax (1, newHeight);
  38839. viewport->setSingleStepSizes (20, rowHeight);
  38840. updateContent();
  38841. }
  38842. int ListBox::getNumRowsOnScreen() const throw()
  38843. {
  38844. return viewport->getMaximumVisibleHeight() / rowHeight;
  38845. }
  38846. void ListBox::setMinimumContentWidth (const int newMinimumWidth)
  38847. {
  38848. minimumRowWidth = newMinimumWidth;
  38849. updateContent();
  38850. }
  38851. int ListBox::getVisibleContentWidth() const throw()
  38852. {
  38853. return viewport->getMaximumVisibleWidth();
  38854. }
  38855. ScrollBar* ListBox::getVerticalScrollBar() const throw()
  38856. {
  38857. return viewport->getVerticalScrollBar();
  38858. }
  38859. ScrollBar* ListBox::getHorizontalScrollBar() const throw()
  38860. {
  38861. return viewport->getHorizontalScrollBar();
  38862. }
  38863. void ListBox::colourChanged()
  38864. {
  38865. setOpaque (findColour (backgroundColourId).isOpaque());
  38866. viewport->setOpaque (isOpaque());
  38867. repaint();
  38868. }
  38869. void ListBox::setOutlineThickness (const int outlineThickness_)
  38870. {
  38871. outlineThickness = outlineThickness_;
  38872. resized();
  38873. }
  38874. void ListBox::setHeaderComponent (Component* const newHeaderComponent)
  38875. {
  38876. if (newHeaderComponent != headerComponent)
  38877. {
  38878. headerComponent = newHeaderComponent;
  38879. addAndMakeVisible (newHeaderComponent);
  38880. ListBox::resized();
  38881. }
  38882. }
  38883. void ListBox::repaintRow (const int rowNumber) throw()
  38884. {
  38885. repaint (getRowPosition (rowNumber, true));
  38886. }
  38887. const Image ListBox::createSnapshotOfSelectedRows (int& imageX, int& imageY)
  38888. {
  38889. Rectangle<int> imageArea;
  38890. const int firstRow = getRowContainingPosition (0, 0);
  38891. int i;
  38892. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  38893. {
  38894. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  38895. if (rowComp != 0 && isRowSelected (firstRow + i))
  38896. {
  38897. const Point<int> pos (rowComp->relativePositionToOtherComponent (this, Point<int>()));
  38898. const Rectangle<int> rowRect (pos.getX(), pos.getY(), rowComp->getWidth(), rowComp->getHeight());
  38899. imageArea = imageArea.getUnion (rowRect);
  38900. }
  38901. }
  38902. imageArea = imageArea.getIntersection (getLocalBounds());
  38903. imageX = imageArea.getX();
  38904. imageY = imageArea.getY();
  38905. Image snapshot (Image::ARGB, imageArea.getWidth(), imageArea.getHeight(), true, Image::NativeImage);
  38906. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  38907. {
  38908. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  38909. if (rowComp != 0 && isRowSelected (firstRow + i))
  38910. {
  38911. const Point<int> pos (rowComp->relativePositionToOtherComponent (this, Point<int>()));
  38912. Graphics g (snapshot);
  38913. g.setOrigin (pos.getX() - imageX, pos.getY() - imageY);
  38914. if (g.reduceClipRegion (0, 0, rowComp->getWidth(), rowComp->getHeight()))
  38915. rowComp->paintEntireComponent (g);
  38916. }
  38917. }
  38918. return snapshot;
  38919. }
  38920. void ListBox::startDragAndDrop (const MouseEvent& e, const String& dragDescription)
  38921. {
  38922. DragAndDropContainer* const dragContainer
  38923. = DragAndDropContainer::findParentDragContainerFor (this);
  38924. if (dragContainer != 0)
  38925. {
  38926. int x, y;
  38927. Image dragImage (createSnapshotOfSelectedRows (x, y));
  38928. dragImage.multiplyAllAlphas (0.6f);
  38929. MouseEvent e2 (e.getEventRelativeTo (this));
  38930. const Point<int> p (x - e2.x, y - e2.y);
  38931. dragContainer->startDragging (dragDescription, this, dragImage, true, &p);
  38932. }
  38933. else
  38934. {
  38935. // to be able to do a drag-and-drop operation, the listbox needs to
  38936. // be inside a component which is also a DragAndDropContainer.
  38937. jassertfalse;
  38938. }
  38939. }
  38940. Component* ListBoxModel::refreshComponentForRow (int, bool, Component* existingComponentToUpdate)
  38941. {
  38942. (void) existingComponentToUpdate;
  38943. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  38944. return 0;
  38945. }
  38946. void ListBoxModel::listBoxItemClicked (int, const MouseEvent&)
  38947. {
  38948. }
  38949. void ListBoxModel::listBoxItemDoubleClicked (int, const MouseEvent&)
  38950. {
  38951. }
  38952. void ListBoxModel::backgroundClicked()
  38953. {
  38954. }
  38955. void ListBoxModel::selectedRowsChanged (int)
  38956. {
  38957. }
  38958. void ListBoxModel::deleteKeyPressed (int)
  38959. {
  38960. }
  38961. void ListBoxModel::returnKeyPressed (int)
  38962. {
  38963. }
  38964. void ListBoxModel::listWasScrolled()
  38965. {
  38966. }
  38967. const String ListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  38968. {
  38969. return String::empty;
  38970. }
  38971. const String ListBoxModel::getTooltipForRow (int)
  38972. {
  38973. return String::empty;
  38974. }
  38975. END_JUCE_NAMESPACE
  38976. /*** End of inlined file: juce_ListBox.cpp ***/
  38977. /*** Start of inlined file: juce_ProgressBar.cpp ***/
  38978. BEGIN_JUCE_NAMESPACE
  38979. ProgressBar::ProgressBar (double& progress_)
  38980. : progress (progress_),
  38981. displayPercentage (true),
  38982. lastCallbackTime (0)
  38983. {
  38984. currentValue = jlimit (0.0, 1.0, progress);
  38985. }
  38986. ProgressBar::~ProgressBar()
  38987. {
  38988. }
  38989. void ProgressBar::setPercentageDisplay (const bool shouldDisplayPercentage)
  38990. {
  38991. displayPercentage = shouldDisplayPercentage;
  38992. repaint();
  38993. }
  38994. void ProgressBar::setTextToDisplay (const String& text)
  38995. {
  38996. displayPercentage = false;
  38997. displayedMessage = text;
  38998. }
  38999. void ProgressBar::lookAndFeelChanged()
  39000. {
  39001. setOpaque (findColour (backgroundColourId).isOpaque());
  39002. }
  39003. void ProgressBar::colourChanged()
  39004. {
  39005. lookAndFeelChanged();
  39006. }
  39007. void ProgressBar::paint (Graphics& g)
  39008. {
  39009. String text;
  39010. if (displayPercentage)
  39011. {
  39012. if (currentValue >= 0 && currentValue <= 1.0)
  39013. text << roundToInt (currentValue * 100.0) << '%';
  39014. }
  39015. else
  39016. {
  39017. text = displayedMessage;
  39018. }
  39019. getLookAndFeel().drawProgressBar (g, *this,
  39020. getWidth(), getHeight(),
  39021. currentValue, text);
  39022. }
  39023. void ProgressBar::visibilityChanged()
  39024. {
  39025. if (isVisible())
  39026. startTimer (30);
  39027. else
  39028. stopTimer();
  39029. }
  39030. void ProgressBar::timerCallback()
  39031. {
  39032. double newProgress = progress;
  39033. const uint32 now = Time::getMillisecondCounter();
  39034. const int timeSinceLastCallback = (int) (now - lastCallbackTime);
  39035. lastCallbackTime = now;
  39036. if (currentValue != newProgress
  39037. || newProgress < 0 || newProgress >= 1.0
  39038. || currentMessage != displayedMessage)
  39039. {
  39040. if (currentValue < newProgress
  39041. && newProgress >= 0 && newProgress < 1.0
  39042. && currentValue >= 0 && currentValue < 1.0)
  39043. {
  39044. newProgress = jmin (currentValue + 0.0008 * timeSinceLastCallback,
  39045. newProgress);
  39046. }
  39047. currentValue = newProgress;
  39048. currentMessage = displayedMessage;
  39049. repaint();
  39050. }
  39051. }
  39052. END_JUCE_NAMESPACE
  39053. /*** End of inlined file: juce_ProgressBar.cpp ***/
  39054. /*** Start of inlined file: juce_Slider.cpp ***/
  39055. BEGIN_JUCE_NAMESPACE
  39056. class SliderPopupDisplayComponent : public BubbleComponent
  39057. {
  39058. public:
  39059. SliderPopupDisplayComponent (Slider* const owner_)
  39060. : owner (owner_),
  39061. font (15.0f, Font::bold)
  39062. {
  39063. setAlwaysOnTop (true);
  39064. }
  39065. ~SliderPopupDisplayComponent()
  39066. {
  39067. }
  39068. void paintContent (Graphics& g, int w, int h)
  39069. {
  39070. g.setFont (font);
  39071. g.setColour (Colours::black);
  39072. g.drawFittedText (text, 0, 0, w, h, Justification::centred, 1);
  39073. }
  39074. void getContentSize (int& w, int& h)
  39075. {
  39076. w = font.getStringWidth (text) + 18;
  39077. h = (int) (font.getHeight() * 1.6f);
  39078. }
  39079. void updatePosition (const String& newText)
  39080. {
  39081. if (text != newText)
  39082. {
  39083. text = newText;
  39084. repaint();
  39085. }
  39086. BubbleComponent::setPosition (owner);
  39087. }
  39088. juce_UseDebuggingNewOperator
  39089. private:
  39090. Slider* owner;
  39091. Font font;
  39092. String text;
  39093. SliderPopupDisplayComponent (const SliderPopupDisplayComponent&);
  39094. SliderPopupDisplayComponent& operator= (const SliderPopupDisplayComponent&);
  39095. };
  39096. Slider::Slider (const String& name)
  39097. : Component (name),
  39098. lastCurrentValue (0),
  39099. lastValueMin (0),
  39100. lastValueMax (0),
  39101. minimum (0),
  39102. maximum (10),
  39103. interval (0),
  39104. skewFactor (1.0),
  39105. velocityModeSensitivity (1.0),
  39106. velocityModeOffset (0.0),
  39107. velocityModeThreshold (1),
  39108. rotaryStart (float_Pi * 1.2f),
  39109. rotaryEnd (float_Pi * 2.8f),
  39110. numDecimalPlaces (7),
  39111. sliderRegionStart (0),
  39112. sliderRegionSize (1),
  39113. sliderBeingDragged (-1),
  39114. pixelsForFullDragExtent (250),
  39115. style (LinearHorizontal),
  39116. textBoxPos (TextBoxLeft),
  39117. textBoxWidth (80),
  39118. textBoxHeight (20),
  39119. incDecButtonMode (incDecButtonsNotDraggable),
  39120. editableText (true),
  39121. doubleClickToValue (false),
  39122. isVelocityBased (false),
  39123. userKeyOverridesVelocity (true),
  39124. rotaryStop (true),
  39125. incDecButtonsSideBySide (false),
  39126. sendChangeOnlyOnRelease (false),
  39127. popupDisplayEnabled (false),
  39128. menuEnabled (false),
  39129. menuShown (false),
  39130. scrollWheelEnabled (true),
  39131. snapsToMousePos (true),
  39132. valueBox (0),
  39133. incButton (0),
  39134. decButton (0),
  39135. popupDisplay (0),
  39136. parentForPopupDisplay (0)
  39137. {
  39138. setWantsKeyboardFocus (false);
  39139. setRepaintsOnMouseActivity (true);
  39140. lookAndFeelChanged();
  39141. updateText();
  39142. currentValue.addListener (this);
  39143. valueMin.addListener (this);
  39144. valueMax.addListener (this);
  39145. }
  39146. Slider::~Slider()
  39147. {
  39148. currentValue.removeListener (this);
  39149. valueMin.removeListener (this);
  39150. valueMax.removeListener (this);
  39151. popupDisplay = 0;
  39152. deleteAllChildren();
  39153. }
  39154. void Slider::handleAsyncUpdate()
  39155. {
  39156. cancelPendingUpdate();
  39157. Component::BailOutChecker checker (this);
  39158. listeners.callChecked (checker, &SliderListener::sliderValueChanged, this);
  39159. }
  39160. void Slider::sendDragStart()
  39161. {
  39162. startedDragging();
  39163. Component::BailOutChecker checker (this);
  39164. listeners.callChecked (checker, &SliderListener::sliderDragStarted, this);
  39165. }
  39166. void Slider::sendDragEnd()
  39167. {
  39168. stoppedDragging();
  39169. sliderBeingDragged = -1;
  39170. Component::BailOutChecker checker (this);
  39171. listeners.callChecked (checker, &SliderListener::sliderDragEnded, this);
  39172. }
  39173. void Slider::addListener (SliderListener* const listener)
  39174. {
  39175. listeners.add (listener);
  39176. }
  39177. void Slider::removeListener (SliderListener* const listener)
  39178. {
  39179. listeners.remove (listener);
  39180. }
  39181. void Slider::setSliderStyle (const SliderStyle newStyle)
  39182. {
  39183. if (style != newStyle)
  39184. {
  39185. style = newStyle;
  39186. repaint();
  39187. lookAndFeelChanged();
  39188. }
  39189. }
  39190. void Slider::setRotaryParameters (const float startAngleRadians,
  39191. const float endAngleRadians,
  39192. const bool stopAtEnd)
  39193. {
  39194. // make sure the values are sensible..
  39195. jassert (rotaryStart >= 0 && rotaryEnd >= 0);
  39196. jassert (rotaryStart < float_Pi * 4.0f && rotaryEnd < float_Pi * 4.0f);
  39197. jassert (rotaryStart < rotaryEnd);
  39198. rotaryStart = startAngleRadians;
  39199. rotaryEnd = endAngleRadians;
  39200. rotaryStop = stopAtEnd;
  39201. }
  39202. void Slider::setVelocityBasedMode (const bool velBased)
  39203. {
  39204. isVelocityBased = velBased;
  39205. }
  39206. void Slider::setVelocityModeParameters (const double sensitivity,
  39207. const int threshold,
  39208. const double offset,
  39209. const bool userCanPressKeyToSwapMode)
  39210. {
  39211. jassert (threshold >= 0);
  39212. jassert (sensitivity > 0);
  39213. jassert (offset >= 0);
  39214. velocityModeSensitivity = sensitivity;
  39215. velocityModeOffset = offset;
  39216. velocityModeThreshold = threshold;
  39217. userKeyOverridesVelocity = userCanPressKeyToSwapMode;
  39218. }
  39219. void Slider::setSkewFactor (const double factor)
  39220. {
  39221. skewFactor = factor;
  39222. }
  39223. void Slider::setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint)
  39224. {
  39225. if (maximum > minimum)
  39226. skewFactor = log (0.5) / log ((sliderValueToShowAtMidPoint - minimum)
  39227. / (maximum - minimum));
  39228. }
  39229. void Slider::setMouseDragSensitivity (const int distanceForFullScaleDrag)
  39230. {
  39231. jassert (distanceForFullScaleDrag > 0);
  39232. pixelsForFullDragExtent = distanceForFullScaleDrag;
  39233. }
  39234. void Slider::setIncDecButtonsMode (const IncDecButtonMode mode)
  39235. {
  39236. if (incDecButtonMode != mode)
  39237. {
  39238. incDecButtonMode = mode;
  39239. lookAndFeelChanged();
  39240. }
  39241. }
  39242. void Slider::setTextBoxStyle (const TextEntryBoxPosition newPosition,
  39243. const bool isReadOnly,
  39244. const int textEntryBoxWidth,
  39245. const int textEntryBoxHeight)
  39246. {
  39247. if (textBoxPos != newPosition
  39248. || editableText != (! isReadOnly)
  39249. || textBoxWidth != textEntryBoxWidth
  39250. || textBoxHeight != textEntryBoxHeight)
  39251. {
  39252. textBoxPos = newPosition;
  39253. editableText = ! isReadOnly;
  39254. textBoxWidth = textEntryBoxWidth;
  39255. textBoxHeight = textEntryBoxHeight;
  39256. repaint();
  39257. lookAndFeelChanged();
  39258. }
  39259. }
  39260. void Slider::setTextBoxIsEditable (const bool shouldBeEditable)
  39261. {
  39262. editableText = shouldBeEditable;
  39263. if (valueBox != 0)
  39264. valueBox->setEditable (shouldBeEditable && isEnabled());
  39265. }
  39266. void Slider::showTextBox()
  39267. {
  39268. jassert (editableText); // this should probably be avoided in read-only sliders.
  39269. if (valueBox != 0)
  39270. valueBox->showEditor();
  39271. }
  39272. void Slider::hideTextBox (const bool discardCurrentEditorContents)
  39273. {
  39274. if (valueBox != 0)
  39275. {
  39276. valueBox->hideEditor (discardCurrentEditorContents);
  39277. if (discardCurrentEditorContents)
  39278. updateText();
  39279. }
  39280. }
  39281. void Slider::setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease)
  39282. {
  39283. sendChangeOnlyOnRelease = onlyNotifyOnRelease;
  39284. }
  39285. void Slider::setSliderSnapsToMousePosition (const bool shouldSnapToMouse)
  39286. {
  39287. snapsToMousePos = shouldSnapToMouse;
  39288. }
  39289. void Slider::setPopupDisplayEnabled (const bool enabled,
  39290. Component* const parentComponentToUse)
  39291. {
  39292. popupDisplayEnabled = enabled;
  39293. parentForPopupDisplay = parentComponentToUse;
  39294. }
  39295. void Slider::colourChanged()
  39296. {
  39297. lookAndFeelChanged();
  39298. }
  39299. void Slider::lookAndFeelChanged()
  39300. {
  39301. const String previousTextBoxContent (valueBox != 0 ? valueBox->getText()
  39302. : getTextFromValue (currentValue.getValue()));
  39303. deleteAllChildren();
  39304. valueBox = 0;
  39305. LookAndFeel& lf = getLookAndFeel();
  39306. if (textBoxPos != NoTextBox)
  39307. {
  39308. addAndMakeVisible (valueBox = getLookAndFeel().createSliderTextBox (*this));
  39309. valueBox->setWantsKeyboardFocus (false);
  39310. valueBox->setText (previousTextBoxContent, false);
  39311. valueBox->setEditable (editableText && isEnabled());
  39312. valueBox->addListener (this);
  39313. if (style == LinearBar)
  39314. valueBox->addMouseListener (this, false);
  39315. valueBox->setTooltip (getTooltip());
  39316. }
  39317. if (style == IncDecButtons)
  39318. {
  39319. addAndMakeVisible (incButton = lf.createSliderButton (true));
  39320. incButton->addButtonListener (this);
  39321. addAndMakeVisible (decButton = lf.createSliderButton (false));
  39322. decButton->addButtonListener (this);
  39323. if (incDecButtonMode != incDecButtonsNotDraggable)
  39324. {
  39325. incButton->addMouseListener (this, false);
  39326. decButton->addMouseListener (this, false);
  39327. }
  39328. else
  39329. {
  39330. incButton->setRepeatSpeed (300, 100, 20);
  39331. incButton->addMouseListener (decButton, false);
  39332. decButton->setRepeatSpeed (300, 100, 20);
  39333. decButton->addMouseListener (incButton, false);
  39334. }
  39335. incButton->setTooltip (getTooltip());
  39336. decButton->setTooltip (getTooltip());
  39337. }
  39338. setComponentEffect (lf.getSliderEffect());
  39339. resized();
  39340. repaint();
  39341. }
  39342. void Slider::setRange (const double newMin,
  39343. const double newMax,
  39344. const double newInt)
  39345. {
  39346. if (minimum != newMin
  39347. || maximum != newMax
  39348. || interval != newInt)
  39349. {
  39350. minimum = newMin;
  39351. maximum = newMax;
  39352. interval = newInt;
  39353. // figure out the number of DPs needed to display all values at this
  39354. // interval setting.
  39355. numDecimalPlaces = 7;
  39356. if (newInt != 0)
  39357. {
  39358. int v = abs ((int) (newInt * 10000000));
  39359. while ((v % 10) == 0)
  39360. {
  39361. --numDecimalPlaces;
  39362. v /= 10;
  39363. }
  39364. }
  39365. // keep the current values inside the new range..
  39366. if (style != TwoValueHorizontal && style != TwoValueVertical)
  39367. {
  39368. setValue (getValue(), false, false);
  39369. }
  39370. else
  39371. {
  39372. setMinValue (getMinValue(), false, false);
  39373. setMaxValue (getMaxValue(), false, false);
  39374. }
  39375. updateText();
  39376. }
  39377. }
  39378. void Slider::triggerChangeMessage (const bool synchronous)
  39379. {
  39380. if (synchronous)
  39381. handleAsyncUpdate();
  39382. else
  39383. triggerAsyncUpdate();
  39384. valueChanged();
  39385. }
  39386. void Slider::valueChanged (Value& value)
  39387. {
  39388. if (value.refersToSameSourceAs (currentValue))
  39389. {
  39390. if (style != TwoValueHorizontal && style != TwoValueVertical)
  39391. setValue (currentValue.getValue(), false, false);
  39392. }
  39393. else if (value.refersToSameSourceAs (valueMin))
  39394. setMinValue (valueMin.getValue(), false, false, true);
  39395. else if (value.refersToSameSourceAs (valueMax))
  39396. setMaxValue (valueMax.getValue(), false, false, true);
  39397. }
  39398. double Slider::getValue() const
  39399. {
  39400. // for a two-value style slider, you should use the getMinValue() and getMaxValue()
  39401. // methods to get the two values.
  39402. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  39403. return currentValue.getValue();
  39404. }
  39405. void Slider::setValue (double newValue,
  39406. const bool sendUpdateMessage,
  39407. const bool sendMessageSynchronously)
  39408. {
  39409. // for a two-value style slider, you should use the setMinValue() and setMaxValue()
  39410. // methods to set the two values.
  39411. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  39412. newValue = constrainedValue (newValue);
  39413. if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  39414. {
  39415. jassert ((double) valueMin.getValue() <= (double) valueMax.getValue());
  39416. newValue = jlimit ((double) valueMin.getValue(),
  39417. (double) valueMax.getValue(),
  39418. newValue);
  39419. }
  39420. if (newValue != lastCurrentValue)
  39421. {
  39422. if (valueBox != 0)
  39423. valueBox->hideEditor (true);
  39424. lastCurrentValue = newValue;
  39425. currentValue = newValue;
  39426. updateText();
  39427. repaint();
  39428. if (popupDisplay != 0)
  39429. {
  39430. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  39431. ->updatePosition (getTextFromValue (newValue));
  39432. popupDisplay->repaint();
  39433. }
  39434. if (sendUpdateMessage)
  39435. triggerChangeMessage (sendMessageSynchronously);
  39436. }
  39437. }
  39438. double Slider::getMinValue() const
  39439. {
  39440. // The minimum value only applies to sliders that are in two- or three-value mode.
  39441. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39442. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39443. return valueMin.getValue();
  39444. }
  39445. double Slider::getMaxValue() const
  39446. {
  39447. // The maximum value only applies to sliders that are in two- or three-value mode.
  39448. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39449. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39450. return valueMax.getValue();
  39451. }
  39452. void Slider::setMinValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  39453. {
  39454. // The minimum value only applies to sliders that are in two- or three-value mode.
  39455. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39456. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39457. newValue = constrainedValue (newValue);
  39458. if (style == TwoValueHorizontal || style == TwoValueVertical)
  39459. {
  39460. if (allowNudgingOfOtherValues && newValue > (double) valueMax.getValue())
  39461. setMaxValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39462. newValue = jmin ((double) valueMax.getValue(), newValue);
  39463. }
  39464. else
  39465. {
  39466. if (allowNudgingOfOtherValues && newValue > lastCurrentValue)
  39467. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39468. newValue = jmin (lastCurrentValue, newValue);
  39469. }
  39470. if (lastValueMin != newValue)
  39471. {
  39472. lastValueMin = newValue;
  39473. valueMin = newValue;
  39474. repaint();
  39475. if (popupDisplay != 0)
  39476. {
  39477. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  39478. ->updatePosition (getTextFromValue (newValue));
  39479. popupDisplay->repaint();
  39480. }
  39481. if (sendUpdateMessage)
  39482. triggerChangeMessage (sendMessageSynchronously);
  39483. }
  39484. }
  39485. void Slider::setMaxValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  39486. {
  39487. // The maximum value only applies to sliders that are in two- or three-value mode.
  39488. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39489. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39490. newValue = constrainedValue (newValue);
  39491. if (style == TwoValueHorizontal || style == TwoValueVertical)
  39492. {
  39493. if (allowNudgingOfOtherValues && newValue < (double) valueMin.getValue())
  39494. setMinValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39495. newValue = jmax ((double) valueMin.getValue(), newValue);
  39496. }
  39497. else
  39498. {
  39499. if (allowNudgingOfOtherValues && newValue < lastCurrentValue)
  39500. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39501. newValue = jmax (lastCurrentValue, newValue);
  39502. }
  39503. if (lastValueMax != newValue)
  39504. {
  39505. lastValueMax = newValue;
  39506. valueMax = newValue;
  39507. repaint();
  39508. if (popupDisplay != 0)
  39509. {
  39510. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  39511. ->updatePosition (getTextFromValue (valueMax.getValue()));
  39512. popupDisplay->repaint();
  39513. }
  39514. if (sendUpdateMessage)
  39515. triggerChangeMessage (sendMessageSynchronously);
  39516. }
  39517. }
  39518. void Slider::setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  39519. const double valueToSetOnDoubleClick)
  39520. {
  39521. doubleClickToValue = isDoubleClickEnabled;
  39522. doubleClickReturnValue = valueToSetOnDoubleClick;
  39523. }
  39524. double Slider::getDoubleClickReturnValue (bool& isEnabled_) const
  39525. {
  39526. isEnabled_ = doubleClickToValue;
  39527. return doubleClickReturnValue;
  39528. }
  39529. void Slider::updateText()
  39530. {
  39531. if (valueBox != 0)
  39532. valueBox->setText (getTextFromValue (currentValue.getValue()), false);
  39533. }
  39534. void Slider::setTextValueSuffix (const String& suffix)
  39535. {
  39536. if (textSuffix != suffix)
  39537. {
  39538. textSuffix = suffix;
  39539. updateText();
  39540. }
  39541. }
  39542. const String Slider::getTextValueSuffix() const
  39543. {
  39544. return textSuffix;
  39545. }
  39546. const String Slider::getTextFromValue (double v)
  39547. {
  39548. if (getNumDecimalPlacesToDisplay() > 0)
  39549. return String (v, getNumDecimalPlacesToDisplay()) + getTextValueSuffix();
  39550. else
  39551. return String (roundToInt (v)) + getTextValueSuffix();
  39552. }
  39553. double Slider::getValueFromText (const String& text)
  39554. {
  39555. String t (text.trimStart());
  39556. if (t.endsWith (textSuffix))
  39557. t = t.substring (0, t.length() - textSuffix.length());
  39558. while (t.startsWithChar ('+'))
  39559. t = t.substring (1).trimStart();
  39560. return t.initialSectionContainingOnly ("0123456789.,-")
  39561. .getDoubleValue();
  39562. }
  39563. double Slider::proportionOfLengthToValue (double proportion)
  39564. {
  39565. if (skewFactor != 1.0 && proportion > 0.0)
  39566. proportion = exp (log (proportion) / skewFactor);
  39567. return minimum + (maximum - minimum) * proportion;
  39568. }
  39569. double Slider::valueToProportionOfLength (double value)
  39570. {
  39571. const double n = (value - minimum) / (maximum - minimum);
  39572. return skewFactor == 1.0 ? n : pow (n, skewFactor);
  39573. }
  39574. double Slider::snapValue (double attemptedValue, const bool)
  39575. {
  39576. return attemptedValue;
  39577. }
  39578. void Slider::startedDragging()
  39579. {
  39580. }
  39581. void Slider::stoppedDragging()
  39582. {
  39583. }
  39584. void Slider::valueChanged()
  39585. {
  39586. }
  39587. void Slider::enablementChanged()
  39588. {
  39589. repaint();
  39590. }
  39591. void Slider::setPopupMenuEnabled (const bool menuEnabled_)
  39592. {
  39593. menuEnabled = menuEnabled_;
  39594. }
  39595. void Slider::setScrollWheelEnabled (const bool enabled)
  39596. {
  39597. scrollWheelEnabled = enabled;
  39598. }
  39599. void Slider::labelTextChanged (Label* label)
  39600. {
  39601. const double newValue = snapValue (getValueFromText (label->getText()), false);
  39602. if (newValue != (double) currentValue.getValue())
  39603. {
  39604. sendDragStart();
  39605. setValue (newValue, true, true);
  39606. sendDragEnd();
  39607. }
  39608. updateText(); // force a clean-up of the text, needed in case setValue() hasn't done this.
  39609. }
  39610. void Slider::buttonClicked (Button* button)
  39611. {
  39612. if (style == IncDecButtons)
  39613. {
  39614. sendDragStart();
  39615. if (button == incButton)
  39616. setValue (snapValue (getValue() + interval, false), true, true);
  39617. else if (button == decButton)
  39618. setValue (snapValue (getValue() - interval, false), true, true);
  39619. sendDragEnd();
  39620. }
  39621. }
  39622. double Slider::constrainedValue (double value) const
  39623. {
  39624. if (interval > 0)
  39625. value = minimum + interval * std::floor ((value - minimum) / interval + 0.5);
  39626. if (value <= minimum || maximum <= minimum)
  39627. value = minimum;
  39628. else if (value >= maximum)
  39629. value = maximum;
  39630. return value;
  39631. }
  39632. float Slider::getLinearSliderPos (const double value)
  39633. {
  39634. double sliderPosProportional;
  39635. if (maximum > minimum)
  39636. {
  39637. if (value < minimum)
  39638. {
  39639. sliderPosProportional = 0.0;
  39640. }
  39641. else if (value > maximum)
  39642. {
  39643. sliderPosProportional = 1.0;
  39644. }
  39645. else
  39646. {
  39647. sliderPosProportional = valueToProportionOfLength (value);
  39648. jassert (sliderPosProportional >= 0 && sliderPosProportional <= 1.0);
  39649. }
  39650. }
  39651. else
  39652. {
  39653. sliderPosProportional = 0.5;
  39654. }
  39655. if (isVertical() || style == IncDecButtons)
  39656. sliderPosProportional = 1.0 - sliderPosProportional;
  39657. return (float) (sliderRegionStart + sliderPosProportional * sliderRegionSize);
  39658. }
  39659. bool Slider::isHorizontal() const
  39660. {
  39661. return style == LinearHorizontal
  39662. || style == LinearBar
  39663. || style == TwoValueHorizontal
  39664. || style == ThreeValueHorizontal;
  39665. }
  39666. bool Slider::isVertical() const
  39667. {
  39668. return style == LinearVertical
  39669. || style == TwoValueVertical
  39670. || style == ThreeValueVertical;
  39671. }
  39672. bool Slider::incDecDragDirectionIsHorizontal() const
  39673. {
  39674. return incDecButtonMode == incDecButtonsDraggable_Horizontal
  39675. || (incDecButtonMode == incDecButtonsDraggable_AutoDirection && incDecButtonsSideBySide);
  39676. }
  39677. float Slider::getPositionOfValue (const double value)
  39678. {
  39679. if (isHorizontal() || isVertical())
  39680. {
  39681. return getLinearSliderPos (value);
  39682. }
  39683. else
  39684. {
  39685. jassertfalse; // not a valid call on a slider that doesn't work linearly!
  39686. return 0.0f;
  39687. }
  39688. }
  39689. void Slider::paint (Graphics& g)
  39690. {
  39691. if (style != IncDecButtons)
  39692. {
  39693. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  39694. {
  39695. const float sliderPos = (float) valueToProportionOfLength (lastCurrentValue);
  39696. jassert (sliderPos >= 0 && sliderPos <= 1.0f);
  39697. getLookAndFeel().drawRotarySlider (g,
  39698. sliderRect.getX(),
  39699. sliderRect.getY(),
  39700. sliderRect.getWidth(),
  39701. sliderRect.getHeight(),
  39702. sliderPos,
  39703. rotaryStart, rotaryEnd,
  39704. *this);
  39705. }
  39706. else
  39707. {
  39708. getLookAndFeel().drawLinearSlider (g,
  39709. sliderRect.getX(),
  39710. sliderRect.getY(),
  39711. sliderRect.getWidth(),
  39712. sliderRect.getHeight(),
  39713. getLinearSliderPos (lastCurrentValue),
  39714. getLinearSliderPos (lastValueMin),
  39715. getLinearSliderPos (lastValueMax),
  39716. style,
  39717. *this);
  39718. }
  39719. if (style == LinearBar && valueBox == 0)
  39720. {
  39721. g.setColour (findColour (Slider::textBoxOutlineColourId));
  39722. g.drawRect (0, 0, getWidth(), getHeight(), 1);
  39723. }
  39724. }
  39725. }
  39726. void Slider::resized()
  39727. {
  39728. int minXSpace = 0;
  39729. int minYSpace = 0;
  39730. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  39731. minXSpace = 30;
  39732. else
  39733. minYSpace = 15;
  39734. const int tbw = jmax (0, jmin (textBoxWidth, getWidth() - minXSpace));
  39735. const int tbh = jmax (0, jmin (textBoxHeight, getHeight() - minYSpace));
  39736. if (style == LinearBar)
  39737. {
  39738. if (valueBox != 0)
  39739. valueBox->setBounds (getLocalBounds());
  39740. }
  39741. else
  39742. {
  39743. if (textBoxPos == NoTextBox)
  39744. {
  39745. sliderRect = getLocalBounds();
  39746. }
  39747. else if (textBoxPos == TextBoxLeft)
  39748. {
  39749. valueBox->setBounds (0, (getHeight() - tbh) / 2, tbw, tbh);
  39750. sliderRect.setBounds (tbw, 0, getWidth() - tbw, getHeight());
  39751. }
  39752. else if (textBoxPos == TextBoxRight)
  39753. {
  39754. valueBox->setBounds (getWidth() - tbw, (getHeight() - tbh) / 2, tbw, tbh);
  39755. sliderRect.setBounds (0, 0, getWidth() - tbw, getHeight());
  39756. }
  39757. else if (textBoxPos == TextBoxAbove)
  39758. {
  39759. valueBox->setBounds ((getWidth() - tbw) / 2, 0, tbw, tbh);
  39760. sliderRect.setBounds (0, tbh, getWidth(), getHeight() - tbh);
  39761. }
  39762. else if (textBoxPos == TextBoxBelow)
  39763. {
  39764. valueBox->setBounds ((getWidth() - tbw) / 2, getHeight() - tbh, tbw, tbh);
  39765. sliderRect.setBounds (0, 0, getWidth(), getHeight() - tbh);
  39766. }
  39767. }
  39768. const int indent = getLookAndFeel().getSliderThumbRadius (*this);
  39769. if (style == LinearBar)
  39770. {
  39771. const int barIndent = 1;
  39772. sliderRegionStart = barIndent;
  39773. sliderRegionSize = getWidth() - barIndent * 2;
  39774. sliderRect.setBounds (sliderRegionStart, barIndent,
  39775. sliderRegionSize, getHeight() - barIndent * 2);
  39776. }
  39777. else if (isHorizontal())
  39778. {
  39779. sliderRegionStart = sliderRect.getX() + indent;
  39780. sliderRegionSize = jmax (1, sliderRect.getWidth() - indent * 2);
  39781. sliderRect.setBounds (sliderRegionStart, sliderRect.getY(),
  39782. sliderRegionSize, sliderRect.getHeight());
  39783. }
  39784. else if (isVertical())
  39785. {
  39786. sliderRegionStart = sliderRect.getY() + indent;
  39787. sliderRegionSize = jmax (1, sliderRect.getHeight() - indent * 2);
  39788. sliderRect.setBounds (sliderRect.getX(), sliderRegionStart,
  39789. sliderRect.getWidth(), sliderRegionSize);
  39790. }
  39791. else
  39792. {
  39793. sliderRegionStart = 0;
  39794. sliderRegionSize = 100;
  39795. }
  39796. if (style == IncDecButtons)
  39797. {
  39798. Rectangle<int> buttonRect (sliderRect);
  39799. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  39800. buttonRect.expand (-2, 0);
  39801. else
  39802. buttonRect.expand (0, -2);
  39803. incDecButtonsSideBySide = buttonRect.getWidth() > buttonRect.getHeight();
  39804. if (incDecButtonsSideBySide)
  39805. {
  39806. decButton->setBounds (buttonRect.getX(),
  39807. buttonRect.getY(),
  39808. buttonRect.getWidth() / 2,
  39809. buttonRect.getHeight());
  39810. decButton->setConnectedEdges (Button::ConnectedOnRight);
  39811. incButton->setBounds (buttonRect.getCentreX(),
  39812. buttonRect.getY(),
  39813. buttonRect.getWidth() / 2,
  39814. buttonRect.getHeight());
  39815. incButton->setConnectedEdges (Button::ConnectedOnLeft);
  39816. }
  39817. else
  39818. {
  39819. incButton->setBounds (buttonRect.getX(),
  39820. buttonRect.getY(),
  39821. buttonRect.getWidth(),
  39822. buttonRect.getHeight() / 2);
  39823. incButton->setConnectedEdges (Button::ConnectedOnBottom);
  39824. decButton->setBounds (buttonRect.getX(),
  39825. buttonRect.getCentreY(),
  39826. buttonRect.getWidth(),
  39827. buttonRect.getHeight() / 2);
  39828. decButton->setConnectedEdges (Button::ConnectedOnTop);
  39829. }
  39830. }
  39831. }
  39832. void Slider::focusOfChildComponentChanged (FocusChangeType)
  39833. {
  39834. repaint();
  39835. }
  39836. void Slider::mouseDown (const MouseEvent& e)
  39837. {
  39838. mouseWasHidden = false;
  39839. incDecDragged = false;
  39840. mouseXWhenLastDragged = e.x;
  39841. mouseYWhenLastDragged = e.y;
  39842. mouseDragStartX = e.getMouseDownX();
  39843. mouseDragStartY = e.getMouseDownY();
  39844. if (isEnabled())
  39845. {
  39846. if (e.mods.isPopupMenu() && menuEnabled)
  39847. {
  39848. menuShown = true;
  39849. PopupMenu m;
  39850. m.setLookAndFeel (&getLookAndFeel());
  39851. m.addItem (1, TRANS ("velocity-sensitive mode"), true, isVelocityBased);
  39852. m.addSeparator();
  39853. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  39854. {
  39855. PopupMenu rotaryMenu;
  39856. rotaryMenu.addItem (2, TRANS ("use circular dragging"), true, style == Rotary);
  39857. rotaryMenu.addItem (3, TRANS ("use left-right dragging"), true, style == RotaryHorizontalDrag);
  39858. rotaryMenu.addItem (4, TRANS ("use up-down dragging"), true, style == RotaryVerticalDrag);
  39859. m.addSubMenu (TRANS ("rotary mode"), rotaryMenu);
  39860. }
  39861. const int r = m.show();
  39862. if (r == 1)
  39863. {
  39864. setVelocityBasedMode (! isVelocityBased);
  39865. }
  39866. else if (r == 2)
  39867. {
  39868. setSliderStyle (Rotary);
  39869. }
  39870. else if (r == 3)
  39871. {
  39872. setSliderStyle (RotaryHorizontalDrag);
  39873. }
  39874. else if (r == 4)
  39875. {
  39876. setSliderStyle (RotaryVerticalDrag);
  39877. }
  39878. }
  39879. else if (maximum > minimum)
  39880. {
  39881. menuShown = false;
  39882. if (valueBox != 0)
  39883. valueBox->hideEditor (true);
  39884. sliderBeingDragged = 0;
  39885. if (style == TwoValueHorizontal
  39886. || style == TwoValueVertical
  39887. || style == ThreeValueHorizontal
  39888. || style == ThreeValueVertical)
  39889. {
  39890. const float mousePos = (float) (isVertical() ? e.y : e.x);
  39891. const float normalPosDistance = std::abs (getLinearSliderPos (currentValue.getValue()) - mousePos);
  39892. const float minPosDistance = std::abs (getLinearSliderPos (valueMin.getValue()) - 0.1f - mousePos);
  39893. const float maxPosDistance = std::abs (getLinearSliderPos (valueMax.getValue()) + 0.1f - mousePos);
  39894. if (style == TwoValueHorizontal || style == TwoValueVertical)
  39895. {
  39896. if (maxPosDistance <= minPosDistance)
  39897. sliderBeingDragged = 2;
  39898. else
  39899. sliderBeingDragged = 1;
  39900. }
  39901. else if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  39902. {
  39903. if (normalPosDistance >= minPosDistance && maxPosDistance >= minPosDistance)
  39904. sliderBeingDragged = 1;
  39905. else if (normalPosDistance >= maxPosDistance)
  39906. sliderBeingDragged = 2;
  39907. }
  39908. }
  39909. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  39910. lastAngle = rotaryStart + (rotaryEnd - rotaryStart)
  39911. * valueToProportionOfLength (currentValue.getValue());
  39912. valueWhenLastDragged = ((sliderBeingDragged == 2) ? valueMax
  39913. : ((sliderBeingDragged == 1) ? valueMin
  39914. : currentValue)).getValue();
  39915. valueOnMouseDown = valueWhenLastDragged;
  39916. if (popupDisplayEnabled)
  39917. {
  39918. SliderPopupDisplayComponent* const popup = new SliderPopupDisplayComponent (this);
  39919. popupDisplay = popup;
  39920. if (parentForPopupDisplay != 0)
  39921. {
  39922. parentForPopupDisplay->addChildComponent (popup);
  39923. }
  39924. else
  39925. {
  39926. popup->addToDesktop (0);
  39927. }
  39928. popup->setVisible (true);
  39929. }
  39930. sendDragStart();
  39931. mouseDrag (e);
  39932. }
  39933. }
  39934. }
  39935. void Slider::mouseUp (const MouseEvent&)
  39936. {
  39937. if (isEnabled()
  39938. && (! menuShown)
  39939. && (maximum > minimum)
  39940. && (style != IncDecButtons || incDecDragged))
  39941. {
  39942. restoreMouseIfHidden();
  39943. if (sendChangeOnlyOnRelease && valueOnMouseDown != (double) currentValue.getValue())
  39944. triggerChangeMessage (false);
  39945. sendDragEnd();
  39946. popupDisplay = 0;
  39947. if (style == IncDecButtons)
  39948. {
  39949. incButton->setState (Button::buttonNormal);
  39950. decButton->setState (Button::buttonNormal);
  39951. }
  39952. }
  39953. }
  39954. void Slider::restoreMouseIfHidden()
  39955. {
  39956. if (mouseWasHidden)
  39957. {
  39958. mouseWasHidden = false;
  39959. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  39960. Desktop::getInstance().getMouseSource(i)->enableUnboundedMouseMovement (false);
  39961. const double pos = (sliderBeingDragged == 2) ? getMaxValue()
  39962. : ((sliderBeingDragged == 1) ? getMinValue()
  39963. : (double) currentValue.getValue());
  39964. Point<int> mousePos;
  39965. if (style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  39966. {
  39967. mousePos = Desktop::getLastMouseDownPosition();
  39968. if (style == RotaryHorizontalDrag)
  39969. {
  39970. const double posDiff = valueToProportionOfLength (pos) - valueToProportionOfLength (valueOnMouseDown);
  39971. mousePos += Point<int> (roundToInt (pixelsForFullDragExtent * posDiff), 0);
  39972. }
  39973. else
  39974. {
  39975. const double posDiff = valueToProportionOfLength (valueOnMouseDown) - valueToProportionOfLength (pos);
  39976. mousePos += Point<int> (0, roundToInt (pixelsForFullDragExtent * posDiff));
  39977. }
  39978. }
  39979. else
  39980. {
  39981. const int pixelPos = (int) getLinearSliderPos (pos);
  39982. mousePos = relativePositionToGlobal (Point<int> (isHorizontal() ? pixelPos : (getWidth() / 2),
  39983. isVertical() ? pixelPos : (getHeight() / 2)));
  39984. }
  39985. Desktop::setMousePosition (mousePos);
  39986. }
  39987. }
  39988. void Slider::modifierKeysChanged (const ModifierKeys& modifiers)
  39989. {
  39990. if (isEnabled()
  39991. && style != IncDecButtons
  39992. && style != Rotary
  39993. && isVelocityBased == modifiers.isAnyModifierKeyDown())
  39994. {
  39995. restoreMouseIfHidden();
  39996. }
  39997. }
  39998. static double smallestAngleBetween (double a1, double a2)
  39999. {
  40000. return jmin (std::abs (a1 - a2),
  40001. std::abs (a1 + double_Pi * 2.0 - a2),
  40002. std::abs (a2 + double_Pi * 2.0 - a1));
  40003. }
  40004. void Slider::mouseDrag (const MouseEvent& e)
  40005. {
  40006. if (isEnabled()
  40007. && (! menuShown)
  40008. && (maximum > minimum))
  40009. {
  40010. if (style == Rotary)
  40011. {
  40012. int dx = e.x - sliderRect.getCentreX();
  40013. int dy = e.y - sliderRect.getCentreY();
  40014. if (dx * dx + dy * dy > 25)
  40015. {
  40016. double angle = std::atan2 ((double) dx, (double) -dy);
  40017. while (angle < 0.0)
  40018. angle += double_Pi * 2.0;
  40019. if (rotaryStop && ! e.mouseWasClicked())
  40020. {
  40021. if (std::abs (angle - lastAngle) > double_Pi)
  40022. {
  40023. if (angle >= lastAngle)
  40024. angle -= double_Pi * 2.0;
  40025. else
  40026. angle += double_Pi * 2.0;
  40027. }
  40028. if (angle >= lastAngle)
  40029. angle = jmin (angle, (double) jmax (rotaryStart, rotaryEnd));
  40030. else
  40031. angle = jmax (angle, (double) jmin (rotaryStart, rotaryEnd));
  40032. }
  40033. else
  40034. {
  40035. while (angle < rotaryStart)
  40036. angle += double_Pi * 2.0;
  40037. if (angle > rotaryEnd)
  40038. {
  40039. if (smallestAngleBetween (angle, rotaryStart) <= smallestAngleBetween (angle, rotaryEnd))
  40040. angle = rotaryStart;
  40041. else
  40042. angle = rotaryEnd;
  40043. }
  40044. }
  40045. const double proportion = (angle - rotaryStart) / (rotaryEnd - rotaryStart);
  40046. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, proportion));
  40047. lastAngle = angle;
  40048. }
  40049. }
  40050. else
  40051. {
  40052. if (style == LinearBar && e.mouseWasClicked()
  40053. && valueBox != 0 && valueBox->isEditable())
  40054. return;
  40055. if (style == IncDecButtons && ! incDecDragged)
  40056. {
  40057. if (e.getDistanceFromDragStart() < 10 || e.mouseWasClicked())
  40058. return;
  40059. incDecDragged = true;
  40060. mouseDragStartX = e.x;
  40061. mouseDragStartY = e.y;
  40062. }
  40063. if ((isVelocityBased == (userKeyOverridesVelocity ? e.mods.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::commandModifier | ModifierKeys::altModifier)
  40064. : false))
  40065. || ((maximum - minimum) / sliderRegionSize < interval))
  40066. {
  40067. const int mousePos = (isHorizontal() || style == RotaryHorizontalDrag) ? e.x : e.y;
  40068. double scaledMousePos = (mousePos - sliderRegionStart) / (double) sliderRegionSize;
  40069. if (style == RotaryHorizontalDrag
  40070. || style == RotaryVerticalDrag
  40071. || style == IncDecButtons
  40072. || ((style == LinearHorizontal || style == LinearVertical || style == LinearBar)
  40073. && ! snapsToMousePos))
  40074. {
  40075. const int mouseDiff = (style == RotaryHorizontalDrag
  40076. || style == LinearHorizontal
  40077. || style == LinearBar
  40078. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  40079. ? e.x - mouseDragStartX
  40080. : mouseDragStartY - e.y;
  40081. double newPos = valueToProportionOfLength (valueOnMouseDown)
  40082. + mouseDiff * (1.0 / pixelsForFullDragExtent);
  40083. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, newPos));
  40084. if (style == IncDecButtons)
  40085. {
  40086. incButton->setState (mouseDiff < 0 ? Button::buttonNormal : Button::buttonDown);
  40087. decButton->setState (mouseDiff > 0 ? Button::buttonNormal : Button::buttonDown);
  40088. }
  40089. }
  40090. else
  40091. {
  40092. if (isVertical())
  40093. scaledMousePos = 1.0 - scaledMousePos;
  40094. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, scaledMousePos));
  40095. }
  40096. }
  40097. else
  40098. {
  40099. const int mouseDiff = (isHorizontal() || style == RotaryHorizontalDrag
  40100. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  40101. ? e.x - mouseXWhenLastDragged
  40102. : e.y - mouseYWhenLastDragged;
  40103. const double maxSpeed = jmax (200, sliderRegionSize);
  40104. double speed = jlimit (0.0, maxSpeed, (double) abs (mouseDiff));
  40105. if (speed != 0)
  40106. {
  40107. speed = 0.2 * velocityModeSensitivity
  40108. * (1.0 + std::sin (double_Pi * (1.5 + jmin (0.5, velocityModeOffset
  40109. + jmax (0.0, (double) (speed - velocityModeThreshold))
  40110. / maxSpeed))));
  40111. if (mouseDiff < 0)
  40112. speed = -speed;
  40113. if (isVertical() || style == RotaryVerticalDrag
  40114. || (style == IncDecButtons && ! incDecDragDirectionIsHorizontal()))
  40115. speed = -speed;
  40116. const double currentPos = valueToProportionOfLength (valueWhenLastDragged);
  40117. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + speed));
  40118. e.source.enableUnboundedMouseMovement (true, false);
  40119. mouseWasHidden = true;
  40120. }
  40121. }
  40122. }
  40123. valueWhenLastDragged = jlimit (minimum, maximum, valueWhenLastDragged);
  40124. if (sliderBeingDragged == 0)
  40125. {
  40126. setValue (snapValue (valueWhenLastDragged, true),
  40127. ! sendChangeOnlyOnRelease, true);
  40128. }
  40129. else if (sliderBeingDragged == 1)
  40130. {
  40131. setMinValue (snapValue (valueWhenLastDragged, true),
  40132. ! sendChangeOnlyOnRelease, false, true);
  40133. if (e.mods.isShiftDown())
  40134. setMaxValue (getMinValue() + minMaxDiff, false, false, true);
  40135. else
  40136. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40137. }
  40138. else
  40139. {
  40140. jassert (sliderBeingDragged == 2);
  40141. setMaxValue (snapValue (valueWhenLastDragged, true),
  40142. ! sendChangeOnlyOnRelease, false, true);
  40143. if (e.mods.isShiftDown())
  40144. setMinValue (getMaxValue() - minMaxDiff, false, false, true);
  40145. else
  40146. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40147. }
  40148. mouseXWhenLastDragged = e.x;
  40149. mouseYWhenLastDragged = e.y;
  40150. }
  40151. }
  40152. void Slider::mouseDoubleClick (const MouseEvent&)
  40153. {
  40154. if (doubleClickToValue
  40155. && isEnabled()
  40156. && style != IncDecButtons
  40157. && minimum <= doubleClickReturnValue
  40158. && maximum >= doubleClickReturnValue)
  40159. {
  40160. sendDragStart();
  40161. setValue (doubleClickReturnValue, true, true);
  40162. sendDragEnd();
  40163. }
  40164. }
  40165. void Slider::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  40166. {
  40167. if (scrollWheelEnabled && isEnabled()
  40168. && style != TwoValueHorizontal
  40169. && style != TwoValueVertical)
  40170. {
  40171. if (maximum > minimum && ! e.mods.isAnyMouseButtonDown())
  40172. {
  40173. if (valueBox != 0)
  40174. valueBox->hideEditor (false);
  40175. const double value = (double) currentValue.getValue();
  40176. const double proportionDelta = (wheelIncrementX != 0 ? -wheelIncrementX : wheelIncrementY) * 0.15f;
  40177. const double currentPos = valueToProportionOfLength (value);
  40178. const double newValue = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + proportionDelta));
  40179. double delta = (newValue != value)
  40180. ? jmax (std::abs (newValue - value), interval) : 0;
  40181. if (value > newValue)
  40182. delta = -delta;
  40183. sendDragStart();
  40184. setValue (snapValue (value + delta, false), true, true);
  40185. sendDragEnd();
  40186. }
  40187. }
  40188. else
  40189. {
  40190. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  40191. }
  40192. }
  40193. void SliderListener::sliderDragStarted (Slider*)
  40194. {
  40195. }
  40196. void SliderListener::sliderDragEnded (Slider*)
  40197. {
  40198. }
  40199. END_JUCE_NAMESPACE
  40200. /*** End of inlined file: juce_Slider.cpp ***/
  40201. /*** Start of inlined file: juce_TableHeaderComponent.cpp ***/
  40202. BEGIN_JUCE_NAMESPACE
  40203. class DragOverlayComp : public Component
  40204. {
  40205. public:
  40206. DragOverlayComp (const Image& image_)
  40207. : image (image_)
  40208. {
  40209. image.duplicateIfShared();
  40210. image.multiplyAllAlphas (0.8f);
  40211. setAlwaysOnTop (true);
  40212. }
  40213. ~DragOverlayComp()
  40214. {
  40215. }
  40216. void paint (Graphics& g)
  40217. {
  40218. g.drawImageAt (image, 0, 0);
  40219. }
  40220. private:
  40221. Image image;
  40222. DragOverlayComp (const DragOverlayComp&);
  40223. DragOverlayComp& operator= (const DragOverlayComp&);
  40224. };
  40225. TableHeaderComponent::TableHeaderComponent()
  40226. : columnsChanged (false),
  40227. columnsResized (false),
  40228. sortChanged (false),
  40229. menuActive (true),
  40230. stretchToFit (false),
  40231. columnIdBeingResized (0),
  40232. columnIdBeingDragged (0),
  40233. columnIdUnderMouse (0),
  40234. lastDeliberateWidth (0)
  40235. {
  40236. }
  40237. TableHeaderComponent::~TableHeaderComponent()
  40238. {
  40239. dragOverlayComp = 0;
  40240. }
  40241. void TableHeaderComponent::setPopupMenuActive (const bool hasMenu)
  40242. {
  40243. menuActive = hasMenu;
  40244. }
  40245. bool TableHeaderComponent::isPopupMenuActive() const { return menuActive; }
  40246. int TableHeaderComponent::getNumColumns (const bool onlyCountVisibleColumns) const
  40247. {
  40248. if (onlyCountVisibleColumns)
  40249. {
  40250. int num = 0;
  40251. for (int i = columns.size(); --i >= 0;)
  40252. if (columns.getUnchecked(i)->isVisible())
  40253. ++num;
  40254. return num;
  40255. }
  40256. else
  40257. {
  40258. return columns.size();
  40259. }
  40260. }
  40261. const String TableHeaderComponent::getColumnName (const int columnId) const
  40262. {
  40263. const ColumnInfo* const ci = getInfoForId (columnId);
  40264. return ci != 0 ? ci->name : String::empty;
  40265. }
  40266. void TableHeaderComponent::setColumnName (const int columnId, const String& newName)
  40267. {
  40268. ColumnInfo* const ci = getInfoForId (columnId);
  40269. if (ci != 0 && ci->name != newName)
  40270. {
  40271. ci->name = newName;
  40272. sendColumnsChanged();
  40273. }
  40274. }
  40275. void TableHeaderComponent::addColumn (const String& columnName,
  40276. const int columnId,
  40277. const int width,
  40278. const int minimumWidth,
  40279. const int maximumWidth,
  40280. const int propertyFlags,
  40281. const int insertIndex)
  40282. {
  40283. // can't have a duplicate or null ID!
  40284. jassert (columnId != 0 && getIndexOfColumnId (columnId, false) < 0);
  40285. jassert (width > 0);
  40286. ColumnInfo* const ci = new ColumnInfo();
  40287. ci->name = columnName;
  40288. ci->id = columnId;
  40289. ci->width = width;
  40290. ci->lastDeliberateWidth = width;
  40291. ci->minimumWidth = minimumWidth;
  40292. ci->maximumWidth = maximumWidth;
  40293. if (ci->maximumWidth < 0)
  40294. ci->maximumWidth = std::numeric_limits<int>::max();
  40295. jassert (ci->maximumWidth >= ci->minimumWidth);
  40296. ci->propertyFlags = propertyFlags;
  40297. columns.insert (insertIndex, ci);
  40298. sendColumnsChanged();
  40299. }
  40300. void TableHeaderComponent::removeColumn (const int columnIdToRemove)
  40301. {
  40302. const int index = getIndexOfColumnId (columnIdToRemove, false);
  40303. if (index >= 0)
  40304. {
  40305. columns.remove (index);
  40306. sortChanged = true;
  40307. sendColumnsChanged();
  40308. }
  40309. }
  40310. void TableHeaderComponent::removeAllColumns()
  40311. {
  40312. if (columns.size() > 0)
  40313. {
  40314. columns.clear();
  40315. sendColumnsChanged();
  40316. }
  40317. }
  40318. void TableHeaderComponent::moveColumn (const int columnId, int newIndex)
  40319. {
  40320. const int currentIndex = getIndexOfColumnId (columnId, false);
  40321. newIndex = visibleIndexToTotalIndex (newIndex);
  40322. if (columns [currentIndex] != 0 && currentIndex != newIndex)
  40323. {
  40324. columns.move (currentIndex, newIndex);
  40325. sendColumnsChanged();
  40326. }
  40327. }
  40328. int TableHeaderComponent::getColumnWidth (const int columnId) const
  40329. {
  40330. const ColumnInfo* const ci = getInfoForId (columnId);
  40331. return ci != 0 ? ci->width : 0;
  40332. }
  40333. void TableHeaderComponent::setColumnWidth (const int columnId, const int newWidth)
  40334. {
  40335. ColumnInfo* const ci = getInfoForId (columnId);
  40336. if (ci != 0 && ci->width != newWidth)
  40337. {
  40338. const int numColumns = getNumColumns (true);
  40339. ci->lastDeliberateWidth = ci->width
  40340. = jlimit (ci->minimumWidth, ci->maximumWidth, newWidth);
  40341. if (stretchToFit)
  40342. {
  40343. const int index = getIndexOfColumnId (columnId, true) + 1;
  40344. if (((unsigned int) index) < (unsigned int) numColumns)
  40345. {
  40346. const int x = getColumnPosition (index).getX();
  40347. if (lastDeliberateWidth == 0)
  40348. lastDeliberateWidth = getTotalWidth();
  40349. resizeColumnsToFit (visibleIndexToTotalIndex (index), lastDeliberateWidth - x);
  40350. }
  40351. }
  40352. repaint();
  40353. columnsResized = true;
  40354. triggerAsyncUpdate();
  40355. }
  40356. }
  40357. int TableHeaderComponent::getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const
  40358. {
  40359. int n = 0;
  40360. for (int i = 0; i < columns.size(); ++i)
  40361. {
  40362. if ((! onlyCountVisibleColumns) || columns.getUnchecked(i)->isVisible())
  40363. {
  40364. if (columns.getUnchecked(i)->id == columnId)
  40365. return n;
  40366. ++n;
  40367. }
  40368. }
  40369. return -1;
  40370. }
  40371. int TableHeaderComponent::getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const
  40372. {
  40373. if (onlyCountVisibleColumns)
  40374. index = visibleIndexToTotalIndex (index);
  40375. const ColumnInfo* const ci = columns [index];
  40376. return (ci != 0) ? ci->id : 0;
  40377. }
  40378. const Rectangle<int> TableHeaderComponent::getColumnPosition (const int index) const
  40379. {
  40380. int x = 0, width = 0, n = 0;
  40381. for (int i = 0; i < columns.size(); ++i)
  40382. {
  40383. x += width;
  40384. if (columns.getUnchecked(i)->isVisible())
  40385. {
  40386. width = columns.getUnchecked(i)->width;
  40387. if (n++ == index)
  40388. break;
  40389. }
  40390. else
  40391. {
  40392. width = 0;
  40393. }
  40394. }
  40395. return Rectangle<int> (x, 0, width, getHeight());
  40396. }
  40397. int TableHeaderComponent::getColumnIdAtX (const int xToFind) const
  40398. {
  40399. if (xToFind >= 0)
  40400. {
  40401. int x = 0;
  40402. for (int i = 0; i < columns.size(); ++i)
  40403. {
  40404. const ColumnInfo* const ci = columns.getUnchecked(i);
  40405. if (ci->isVisible())
  40406. {
  40407. x += ci->width;
  40408. if (xToFind < x)
  40409. return ci->id;
  40410. }
  40411. }
  40412. }
  40413. return 0;
  40414. }
  40415. int TableHeaderComponent::getTotalWidth() const
  40416. {
  40417. int w = 0;
  40418. for (int i = columns.size(); --i >= 0;)
  40419. if (columns.getUnchecked(i)->isVisible())
  40420. w += columns.getUnchecked(i)->width;
  40421. return w;
  40422. }
  40423. void TableHeaderComponent::setStretchToFitActive (const bool shouldStretchToFit)
  40424. {
  40425. stretchToFit = shouldStretchToFit;
  40426. lastDeliberateWidth = getTotalWidth();
  40427. resized();
  40428. }
  40429. bool TableHeaderComponent::isStretchToFitActive() const
  40430. {
  40431. return stretchToFit;
  40432. }
  40433. void TableHeaderComponent::resizeAllColumnsToFit (int targetTotalWidth)
  40434. {
  40435. if (stretchToFit && getWidth() > 0
  40436. && columnIdBeingResized == 0 && columnIdBeingDragged == 0)
  40437. {
  40438. lastDeliberateWidth = targetTotalWidth;
  40439. resizeColumnsToFit (0, targetTotalWidth);
  40440. }
  40441. }
  40442. void TableHeaderComponent::resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth)
  40443. {
  40444. targetTotalWidth = jmax (targetTotalWidth, 0);
  40445. StretchableObjectResizer sor;
  40446. int i;
  40447. for (i = firstColumnIndex; i < columns.size(); ++i)
  40448. {
  40449. ColumnInfo* const ci = columns.getUnchecked(i);
  40450. if (ci->isVisible())
  40451. sor.addItem (ci->lastDeliberateWidth, ci->minimumWidth, ci->maximumWidth);
  40452. }
  40453. sor.resizeToFit (targetTotalWidth);
  40454. int visIndex = 0;
  40455. for (i = firstColumnIndex; i < columns.size(); ++i)
  40456. {
  40457. ColumnInfo* const ci = columns.getUnchecked(i);
  40458. if (ci->isVisible())
  40459. {
  40460. const int newWidth = jlimit (ci->minimumWidth, ci->maximumWidth,
  40461. (int) std::floor (sor.getItemSize (visIndex++)));
  40462. if (newWidth != ci->width)
  40463. {
  40464. ci->width = newWidth;
  40465. repaint();
  40466. columnsResized = true;
  40467. triggerAsyncUpdate();
  40468. }
  40469. }
  40470. }
  40471. }
  40472. void TableHeaderComponent::setColumnVisible (const int columnId, const bool shouldBeVisible)
  40473. {
  40474. ColumnInfo* const ci = getInfoForId (columnId);
  40475. if (ci != 0 && shouldBeVisible != ci->isVisible())
  40476. {
  40477. if (shouldBeVisible)
  40478. ci->propertyFlags |= visible;
  40479. else
  40480. ci->propertyFlags &= ~visible;
  40481. sendColumnsChanged();
  40482. resized();
  40483. }
  40484. }
  40485. bool TableHeaderComponent::isColumnVisible (const int columnId) const
  40486. {
  40487. const ColumnInfo* const ci = getInfoForId (columnId);
  40488. return ci != 0 && ci->isVisible();
  40489. }
  40490. void TableHeaderComponent::setSortColumnId (const int columnId, const bool sortForwards)
  40491. {
  40492. if (getSortColumnId() != columnId || isSortedForwards() != sortForwards)
  40493. {
  40494. for (int i = columns.size(); --i >= 0;)
  40495. columns.getUnchecked(i)->propertyFlags &= ~(sortedForwards | sortedBackwards);
  40496. ColumnInfo* const ci = getInfoForId (columnId);
  40497. if (ci != 0)
  40498. ci->propertyFlags |= (sortForwards ? sortedForwards : sortedBackwards);
  40499. reSortTable();
  40500. }
  40501. }
  40502. int TableHeaderComponent::getSortColumnId() const
  40503. {
  40504. for (int i = columns.size(); --i >= 0;)
  40505. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  40506. return columns.getUnchecked(i)->id;
  40507. return 0;
  40508. }
  40509. bool TableHeaderComponent::isSortedForwards() const
  40510. {
  40511. for (int i = columns.size(); --i >= 0;)
  40512. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  40513. return (columns.getUnchecked(i)->propertyFlags & sortedForwards) != 0;
  40514. return true;
  40515. }
  40516. void TableHeaderComponent::reSortTable()
  40517. {
  40518. sortChanged = true;
  40519. repaint();
  40520. triggerAsyncUpdate();
  40521. }
  40522. const String TableHeaderComponent::toString() const
  40523. {
  40524. String s;
  40525. XmlElement doc ("TABLELAYOUT");
  40526. doc.setAttribute ("sortedCol", getSortColumnId());
  40527. doc.setAttribute ("sortForwards", isSortedForwards());
  40528. for (int i = 0; i < columns.size(); ++i)
  40529. {
  40530. const ColumnInfo* const ci = columns.getUnchecked (i);
  40531. XmlElement* const e = doc.createNewChildElement ("COLUMN");
  40532. e->setAttribute ("id", ci->id);
  40533. e->setAttribute ("visible", ci->isVisible());
  40534. e->setAttribute ("width", ci->width);
  40535. }
  40536. return doc.createDocument (String::empty, true, false);
  40537. }
  40538. void TableHeaderComponent::restoreFromString (const String& storedVersion)
  40539. {
  40540. XmlDocument doc (storedVersion);
  40541. ScopedPointer <XmlElement> storedXml (doc.getDocumentElement());
  40542. int index = 0;
  40543. if (storedXml != 0 && storedXml->hasTagName ("TABLELAYOUT"))
  40544. {
  40545. forEachXmlChildElement (*storedXml, col)
  40546. {
  40547. const int tabId = col->getIntAttribute ("id");
  40548. ColumnInfo* const ci = getInfoForId (tabId);
  40549. if (ci != 0)
  40550. {
  40551. columns.move (columns.indexOf (ci), index);
  40552. ci->width = col->getIntAttribute ("width");
  40553. setColumnVisible (tabId, col->getBoolAttribute ("visible"));
  40554. }
  40555. ++index;
  40556. }
  40557. columnsResized = true;
  40558. sendColumnsChanged();
  40559. setSortColumnId (storedXml->getIntAttribute ("sortedCol"),
  40560. storedXml->getBoolAttribute ("sortForwards", true));
  40561. }
  40562. }
  40563. void TableHeaderComponent::addListener (TableHeaderListener* const newListener)
  40564. {
  40565. listeners.addIfNotAlreadyThere (newListener);
  40566. }
  40567. void TableHeaderComponent::removeListener (TableHeaderListener* const listenerToRemove)
  40568. {
  40569. listeners.removeValue (listenerToRemove);
  40570. }
  40571. void TableHeaderComponent::columnClicked (int columnId, const ModifierKeys& mods)
  40572. {
  40573. const ColumnInfo* const ci = getInfoForId (columnId);
  40574. if (ci != 0 && (ci->propertyFlags & sortable) != 0 && ! mods.isPopupMenu())
  40575. setSortColumnId (columnId, (ci->propertyFlags & sortedForwards) == 0);
  40576. }
  40577. void TableHeaderComponent::addMenuItems (PopupMenu& menu, const int /*columnIdClicked*/)
  40578. {
  40579. for (int i = 0; i < columns.size(); ++i)
  40580. {
  40581. const ColumnInfo* const ci = columns.getUnchecked(i);
  40582. if ((ci->propertyFlags & appearsOnColumnMenu) != 0)
  40583. menu.addItem (ci->id, ci->name,
  40584. (ci->propertyFlags & (sortedForwards | sortedBackwards)) == 0,
  40585. isColumnVisible (ci->id));
  40586. }
  40587. }
  40588. void TableHeaderComponent::reactToMenuItem (const int menuReturnId, const int /*columnIdClicked*/)
  40589. {
  40590. if (getIndexOfColumnId (menuReturnId, false) >= 0)
  40591. setColumnVisible (menuReturnId, ! isColumnVisible (menuReturnId));
  40592. }
  40593. void TableHeaderComponent::paint (Graphics& g)
  40594. {
  40595. LookAndFeel& lf = getLookAndFeel();
  40596. lf.drawTableHeaderBackground (g, *this);
  40597. const Rectangle<int> clip (g.getClipBounds());
  40598. int x = 0;
  40599. for (int i = 0; i < columns.size(); ++i)
  40600. {
  40601. const ColumnInfo* const ci = columns.getUnchecked(i);
  40602. if (ci->isVisible())
  40603. {
  40604. if (x + ci->width > clip.getX()
  40605. && (ci->id != columnIdBeingDragged
  40606. || dragOverlayComp == 0
  40607. || ! dragOverlayComp->isVisible()))
  40608. {
  40609. g.saveState();
  40610. g.setOrigin (x, 0);
  40611. g.reduceClipRegion (0, 0, ci->width, getHeight());
  40612. lf.drawTableHeaderColumn (g, ci->name, ci->id, ci->width, getHeight(),
  40613. ci->id == columnIdUnderMouse,
  40614. ci->id == columnIdUnderMouse && isMouseButtonDown(),
  40615. ci->propertyFlags);
  40616. g.restoreState();
  40617. }
  40618. x += ci->width;
  40619. if (x >= clip.getRight())
  40620. break;
  40621. }
  40622. }
  40623. }
  40624. void TableHeaderComponent::resized()
  40625. {
  40626. }
  40627. void TableHeaderComponent::mouseMove (const MouseEvent& e)
  40628. {
  40629. updateColumnUnderMouse (e.x, e.y);
  40630. }
  40631. void TableHeaderComponent::mouseEnter (const MouseEvent& e)
  40632. {
  40633. updateColumnUnderMouse (e.x, e.y);
  40634. }
  40635. void TableHeaderComponent::mouseExit (const MouseEvent& e)
  40636. {
  40637. updateColumnUnderMouse (e.x, e.y);
  40638. }
  40639. void TableHeaderComponent::mouseDown (const MouseEvent& e)
  40640. {
  40641. repaint();
  40642. columnIdBeingResized = 0;
  40643. columnIdBeingDragged = 0;
  40644. if (columnIdUnderMouse != 0)
  40645. {
  40646. draggingColumnOffset = e.x - getColumnPosition (getIndexOfColumnId (columnIdUnderMouse, true)).getX();
  40647. if (e.mods.isPopupMenu())
  40648. columnClicked (columnIdUnderMouse, e.mods);
  40649. }
  40650. if (menuActive && e.mods.isPopupMenu())
  40651. showColumnChooserMenu (columnIdUnderMouse);
  40652. }
  40653. void TableHeaderComponent::mouseDrag (const MouseEvent& e)
  40654. {
  40655. if (columnIdBeingResized == 0
  40656. && columnIdBeingDragged == 0
  40657. && ! (e.mouseWasClicked() || e.mods.isPopupMenu()))
  40658. {
  40659. dragOverlayComp = 0;
  40660. columnIdBeingResized = getResizeDraggerAt (e.getMouseDownX());
  40661. if (columnIdBeingResized != 0)
  40662. {
  40663. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  40664. initialColumnWidth = ci->width;
  40665. }
  40666. else
  40667. {
  40668. beginDrag (e);
  40669. }
  40670. }
  40671. if (columnIdBeingResized != 0)
  40672. {
  40673. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  40674. if (ci != 0)
  40675. {
  40676. int w = jlimit (ci->minimumWidth, ci->maximumWidth,
  40677. initialColumnWidth + e.getDistanceFromDragStartX());
  40678. if (stretchToFit)
  40679. {
  40680. // prevent us dragging a column too far right if we're in stretch-to-fit mode
  40681. int minWidthOnRight = 0;
  40682. for (int i = getIndexOfColumnId (columnIdBeingResized, false) + 1; i < columns.size(); ++i)
  40683. if (columns.getUnchecked (i)->isVisible())
  40684. minWidthOnRight += columns.getUnchecked (i)->minimumWidth;
  40685. const Rectangle<int> currentPos (getColumnPosition (getIndexOfColumnId (columnIdBeingResized, true)));
  40686. w = jmax (ci->minimumWidth, jmin (w, getWidth() - minWidthOnRight - currentPos.getX()));
  40687. }
  40688. setColumnWidth (columnIdBeingResized, w);
  40689. }
  40690. }
  40691. else if (columnIdBeingDragged != 0)
  40692. {
  40693. if (e.y >= -50 && e.y < getHeight() + 50)
  40694. {
  40695. if (dragOverlayComp != 0)
  40696. {
  40697. dragOverlayComp->setVisible (true);
  40698. dragOverlayComp->setBounds (jlimit (0,
  40699. jmax (0, getTotalWidth() - dragOverlayComp->getWidth()),
  40700. e.x - draggingColumnOffset),
  40701. 0,
  40702. dragOverlayComp->getWidth(),
  40703. getHeight());
  40704. for (int i = columns.size(); --i >= 0;)
  40705. {
  40706. const int currentIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  40707. int newIndex = currentIndex;
  40708. if (newIndex > 0)
  40709. {
  40710. // if the previous column isn't draggable, we can't move our column
  40711. // past it, because that'd change the undraggable column's position..
  40712. const ColumnInfo* const previous = columns.getUnchecked (newIndex - 1);
  40713. if ((previous->propertyFlags & draggable) != 0)
  40714. {
  40715. const int leftOfPrevious = getColumnPosition (newIndex - 1).getX();
  40716. const int rightOfCurrent = getColumnPosition (newIndex).getRight();
  40717. if (abs (dragOverlayComp->getX() - leftOfPrevious)
  40718. < abs (dragOverlayComp->getRight() - rightOfCurrent))
  40719. {
  40720. --newIndex;
  40721. }
  40722. }
  40723. }
  40724. if (newIndex < columns.size() - 1)
  40725. {
  40726. // if the next column isn't draggable, we can't move our column
  40727. // past it, because that'd change the undraggable column's position..
  40728. const ColumnInfo* const nextCol = columns.getUnchecked (newIndex + 1);
  40729. if ((nextCol->propertyFlags & draggable) != 0)
  40730. {
  40731. const int leftOfCurrent = getColumnPosition (newIndex).getX();
  40732. const int rightOfNext = getColumnPosition (newIndex + 1).getRight();
  40733. if (abs (dragOverlayComp->getX() - leftOfCurrent)
  40734. > abs (dragOverlayComp->getRight() - rightOfNext))
  40735. {
  40736. ++newIndex;
  40737. }
  40738. }
  40739. }
  40740. if (newIndex != currentIndex)
  40741. moveColumn (columnIdBeingDragged, newIndex);
  40742. else
  40743. break;
  40744. }
  40745. }
  40746. }
  40747. else
  40748. {
  40749. endDrag (draggingColumnOriginalIndex);
  40750. }
  40751. }
  40752. }
  40753. void TableHeaderComponent::beginDrag (const MouseEvent& e)
  40754. {
  40755. if (columnIdBeingDragged == 0)
  40756. {
  40757. columnIdBeingDragged = getColumnIdAtX (e.getMouseDownX());
  40758. const ColumnInfo* const ci = getInfoForId (columnIdBeingDragged);
  40759. if (ci == 0 || (ci->propertyFlags & draggable) == 0)
  40760. {
  40761. columnIdBeingDragged = 0;
  40762. }
  40763. else
  40764. {
  40765. draggingColumnOriginalIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  40766. const Rectangle<int> columnRect (getColumnPosition (draggingColumnOriginalIndex));
  40767. const int temp = columnIdBeingDragged;
  40768. columnIdBeingDragged = 0;
  40769. addAndMakeVisible (dragOverlayComp = new DragOverlayComp (createComponentSnapshot (columnRect, false)));
  40770. columnIdBeingDragged = temp;
  40771. dragOverlayComp->setBounds (columnRect);
  40772. for (int i = listeners.size(); --i >= 0;)
  40773. {
  40774. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, columnIdBeingDragged);
  40775. i = jmin (i, listeners.size() - 1);
  40776. }
  40777. }
  40778. }
  40779. }
  40780. void TableHeaderComponent::endDrag (const int finalIndex)
  40781. {
  40782. if (columnIdBeingDragged != 0)
  40783. {
  40784. moveColumn (columnIdBeingDragged, finalIndex);
  40785. columnIdBeingDragged = 0;
  40786. repaint();
  40787. for (int i = listeners.size(); --i >= 0;)
  40788. {
  40789. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, 0);
  40790. i = jmin (i, listeners.size() - 1);
  40791. }
  40792. }
  40793. }
  40794. void TableHeaderComponent::mouseUp (const MouseEvent& e)
  40795. {
  40796. mouseDrag (e);
  40797. for (int i = columns.size(); --i >= 0;)
  40798. if (columns.getUnchecked (i)->isVisible())
  40799. columns.getUnchecked (i)->lastDeliberateWidth = columns.getUnchecked (i)->width;
  40800. columnIdBeingResized = 0;
  40801. repaint();
  40802. endDrag (getIndexOfColumnId (columnIdBeingDragged, true));
  40803. updateColumnUnderMouse (e.x, e.y);
  40804. if (columnIdUnderMouse != 0 && e.mouseWasClicked() && ! e.mods.isPopupMenu())
  40805. columnClicked (columnIdUnderMouse, e.mods);
  40806. dragOverlayComp = 0;
  40807. }
  40808. const MouseCursor TableHeaderComponent::getMouseCursor()
  40809. {
  40810. if (columnIdBeingResized != 0 || (getResizeDraggerAt (getMouseXYRelative().getX()) != 0 && ! isMouseButtonDown()))
  40811. return MouseCursor (MouseCursor::LeftRightResizeCursor);
  40812. return Component::getMouseCursor();
  40813. }
  40814. bool TableHeaderComponent::ColumnInfo::isVisible() const
  40815. {
  40816. return (propertyFlags & TableHeaderComponent::visible) != 0;
  40817. }
  40818. TableHeaderComponent::ColumnInfo* TableHeaderComponent::getInfoForId (const int id) const
  40819. {
  40820. for (int i = columns.size(); --i >= 0;)
  40821. if (columns.getUnchecked(i)->id == id)
  40822. return columns.getUnchecked(i);
  40823. return 0;
  40824. }
  40825. int TableHeaderComponent::visibleIndexToTotalIndex (const int visibleIndex) const
  40826. {
  40827. int n = 0;
  40828. for (int i = 0; i < columns.size(); ++i)
  40829. {
  40830. if (columns.getUnchecked(i)->isVisible())
  40831. {
  40832. if (n == visibleIndex)
  40833. return i;
  40834. ++n;
  40835. }
  40836. }
  40837. return -1;
  40838. }
  40839. void TableHeaderComponent::sendColumnsChanged()
  40840. {
  40841. if (stretchToFit && lastDeliberateWidth > 0)
  40842. resizeAllColumnsToFit (lastDeliberateWidth);
  40843. repaint();
  40844. columnsChanged = true;
  40845. triggerAsyncUpdate();
  40846. }
  40847. void TableHeaderComponent::handleAsyncUpdate()
  40848. {
  40849. const bool changed = columnsChanged || sortChanged;
  40850. const bool sized = columnsResized || changed;
  40851. const bool sorted = sortChanged;
  40852. columnsChanged = false;
  40853. columnsResized = false;
  40854. sortChanged = false;
  40855. if (sorted)
  40856. {
  40857. for (int i = listeners.size(); --i >= 0;)
  40858. {
  40859. listeners.getUnchecked(i)->tableSortOrderChanged (this);
  40860. i = jmin (i, listeners.size() - 1);
  40861. }
  40862. }
  40863. if (changed)
  40864. {
  40865. for (int i = listeners.size(); --i >= 0;)
  40866. {
  40867. listeners.getUnchecked(i)->tableColumnsChanged (this);
  40868. i = jmin (i, listeners.size() - 1);
  40869. }
  40870. }
  40871. if (sized)
  40872. {
  40873. for (int i = listeners.size(); --i >= 0;)
  40874. {
  40875. listeners.getUnchecked(i)->tableColumnsResized (this);
  40876. i = jmin (i, listeners.size() - 1);
  40877. }
  40878. }
  40879. }
  40880. int TableHeaderComponent::getResizeDraggerAt (const int mouseX) const
  40881. {
  40882. if (((unsigned int) mouseX) < (unsigned int) getWidth())
  40883. {
  40884. const int draggableDistance = 3;
  40885. int x = 0;
  40886. for (int i = 0; i < columns.size(); ++i)
  40887. {
  40888. const ColumnInfo* const ci = columns.getUnchecked(i);
  40889. if (ci->isVisible())
  40890. {
  40891. if (abs (mouseX - (x + ci->width)) <= draggableDistance
  40892. && (ci->propertyFlags & resizable) != 0)
  40893. return ci->id;
  40894. x += ci->width;
  40895. }
  40896. }
  40897. }
  40898. return 0;
  40899. }
  40900. void TableHeaderComponent::updateColumnUnderMouse (int x, int y)
  40901. {
  40902. const int newCol = (reallyContains (x, y, true) && getResizeDraggerAt (x) == 0)
  40903. ? getColumnIdAtX (x) : 0;
  40904. if (newCol != columnIdUnderMouse)
  40905. {
  40906. columnIdUnderMouse = newCol;
  40907. repaint();
  40908. }
  40909. }
  40910. void TableHeaderComponent::showColumnChooserMenu (const int columnIdClicked)
  40911. {
  40912. PopupMenu m;
  40913. addMenuItems (m, columnIdClicked);
  40914. if (m.getNumItems() > 0)
  40915. {
  40916. m.setLookAndFeel (&getLookAndFeel());
  40917. const int result = m.show();
  40918. if (result != 0)
  40919. reactToMenuItem (result, columnIdClicked);
  40920. }
  40921. }
  40922. void TableHeaderListener::tableColumnDraggingChanged (TableHeaderComponent*, int)
  40923. {
  40924. }
  40925. END_JUCE_NAMESPACE
  40926. /*** End of inlined file: juce_TableHeaderComponent.cpp ***/
  40927. /*** Start of inlined file: juce_TableListBox.cpp ***/
  40928. BEGIN_JUCE_NAMESPACE
  40929. static const char* const tableColumnPropertyTag = "_tableColumnID";
  40930. class TableListRowComp : public Component,
  40931. public TooltipClient
  40932. {
  40933. public:
  40934. TableListRowComp (TableListBox& owner_)
  40935. : owner (owner_),
  40936. row (-1),
  40937. isSelected (false)
  40938. {
  40939. }
  40940. ~TableListRowComp()
  40941. {
  40942. deleteAllChildren();
  40943. }
  40944. void paint (Graphics& g)
  40945. {
  40946. TableListBoxModel* const model = owner.getModel();
  40947. if (model != 0)
  40948. {
  40949. const TableHeaderComponent* const header = owner.getHeader();
  40950. model->paintRowBackground (g, row, getWidth(), getHeight(), isSelected);
  40951. const int numColumns = header->getNumColumns (true);
  40952. for (int i = 0; i < numColumns; ++i)
  40953. {
  40954. if (! columnsWithComponents [i])
  40955. {
  40956. const int columnId = header->getColumnIdOfIndex (i, true);
  40957. Rectangle<int> columnRect (header->getColumnPosition (i));
  40958. columnRect.setSize (columnRect.getWidth(), getHeight());
  40959. g.saveState();
  40960. g.reduceClipRegion (columnRect);
  40961. g.setOrigin (columnRect.getX(), 0);
  40962. model->paintCell (g, row, columnId, columnRect.getWidth(), columnRect.getHeight(), isSelected);
  40963. g.restoreState();
  40964. }
  40965. }
  40966. }
  40967. }
  40968. void update (const int newRow, const bool isNowSelected)
  40969. {
  40970. if (newRow != row || isNowSelected != isSelected)
  40971. {
  40972. row = newRow;
  40973. isSelected = isNowSelected;
  40974. repaint();
  40975. }
  40976. if (row < owner.getNumRows())
  40977. {
  40978. jassert (row >= 0);
  40979. const Identifier tagPropertyName ("_tableLastUseNum");
  40980. const int newTag = Random::getSystemRandom().nextInt();
  40981. const TableHeaderComponent* const header = owner.getHeader();
  40982. const int numColumns = header->getNumColumns (true);
  40983. int i;
  40984. columnsWithComponents.clear();
  40985. if (owner.getModel() != 0)
  40986. {
  40987. for (i = 0; i < numColumns; ++i)
  40988. {
  40989. const int columnId = header->getColumnIdOfIndex (i, true);
  40990. Component* const newComp
  40991. = owner.getModel()->refreshComponentForCell (row, columnId, isSelected,
  40992. findChildComponentForColumn (columnId));
  40993. if (newComp != 0)
  40994. {
  40995. addAndMakeVisible (newComp);
  40996. newComp->getProperties().set (tagPropertyName, newTag);
  40997. newComp->getProperties().set (tableColumnPropertyTag, columnId);
  40998. const Rectangle<int> columnRect (header->getColumnPosition (i));
  40999. newComp->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  41000. columnsWithComponents.setBit (i);
  41001. }
  41002. }
  41003. }
  41004. for (i = getNumChildComponents(); --i >= 0;)
  41005. {
  41006. Component* const c = getChildComponent (i);
  41007. if ((int) c->getProperties() [tagPropertyName] != newTag)
  41008. delete c;
  41009. }
  41010. }
  41011. else
  41012. {
  41013. columnsWithComponents.clear();
  41014. deleteAllChildren();
  41015. }
  41016. }
  41017. void resized()
  41018. {
  41019. for (int i = getNumChildComponents(); --i >= 0;)
  41020. {
  41021. Component* const c = getChildComponent (i);
  41022. const int columnId = c->getProperties() [tableColumnPropertyTag];
  41023. if (columnId != 0)
  41024. {
  41025. const Rectangle<int> columnRect (owner.getHeader()->getColumnPosition (owner.getHeader()->getIndexOfColumnId (columnId, true)));
  41026. c->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  41027. }
  41028. }
  41029. }
  41030. void mouseDown (const MouseEvent& e)
  41031. {
  41032. isDragging = false;
  41033. selectRowOnMouseUp = false;
  41034. if (isEnabled())
  41035. {
  41036. if (! isSelected)
  41037. {
  41038. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  41039. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  41040. if (columnId != 0 && owner.getModel() != 0)
  41041. owner.getModel()->cellClicked (row, columnId, e);
  41042. }
  41043. else
  41044. {
  41045. selectRowOnMouseUp = true;
  41046. }
  41047. }
  41048. }
  41049. void mouseDrag (const MouseEvent& e)
  41050. {
  41051. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  41052. {
  41053. const SparseSet<int> selectedRows (owner.getSelectedRows());
  41054. if (selectedRows.size() > 0)
  41055. {
  41056. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  41057. if (dragDescription.isNotEmpty())
  41058. {
  41059. isDragging = true;
  41060. owner.startDragAndDrop (e, dragDescription);
  41061. }
  41062. }
  41063. }
  41064. }
  41065. void mouseUp (const MouseEvent& e)
  41066. {
  41067. if (selectRowOnMouseUp && e.mouseWasClicked() && isEnabled())
  41068. {
  41069. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  41070. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  41071. if (columnId != 0 && owner.getModel() != 0)
  41072. owner.getModel()->cellClicked (row, columnId, e);
  41073. }
  41074. }
  41075. void mouseDoubleClick (const MouseEvent& e)
  41076. {
  41077. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  41078. if (columnId != 0 && owner.getModel() != 0)
  41079. owner.getModel()->cellDoubleClicked (row, columnId, e);
  41080. }
  41081. const String getTooltip()
  41082. {
  41083. const int columnId = owner.getHeader()->getColumnIdAtX (getMouseXYRelative().getX());
  41084. if (columnId != 0 && owner.getModel() != 0)
  41085. return owner.getModel()->getCellTooltip (row, columnId);
  41086. return String::empty;
  41087. }
  41088. juce_UseDebuggingNewOperator
  41089. private:
  41090. TableListBox& owner;
  41091. int row;
  41092. bool isSelected, isDragging, selectRowOnMouseUp;
  41093. BigInteger columnsWithComponents;
  41094. Component* findChildComponentForColumn (const int columnId) const
  41095. {
  41096. for (int i = getNumChildComponents(); --i >= 0;)
  41097. {
  41098. Component* const c = getChildComponent (i);
  41099. if ((int) c->getProperties() [tableColumnPropertyTag] == columnId)
  41100. return c;
  41101. }
  41102. return 0;
  41103. }
  41104. TableListRowComp (const TableListRowComp&);
  41105. TableListRowComp& operator= (const TableListRowComp&);
  41106. };
  41107. class TableListBoxHeader : public TableHeaderComponent
  41108. {
  41109. public:
  41110. TableListBoxHeader (TableListBox& owner_)
  41111. : owner (owner_)
  41112. {
  41113. }
  41114. ~TableListBoxHeader()
  41115. {
  41116. }
  41117. void addMenuItems (PopupMenu& menu, int columnIdClicked)
  41118. {
  41119. if (owner.isAutoSizeMenuOptionShown())
  41120. {
  41121. menu.addItem (0xf836743, TRANS("Auto-size this column"), columnIdClicked != 0);
  41122. menu.addItem (0xf836744, TRANS("Auto-size all columns"), owner.getHeader()->getNumColumns (true) > 0);
  41123. menu.addSeparator();
  41124. }
  41125. TableHeaderComponent::addMenuItems (menu, columnIdClicked);
  41126. }
  41127. void reactToMenuItem (int menuReturnId, int columnIdClicked)
  41128. {
  41129. if (menuReturnId == 0xf836743)
  41130. {
  41131. owner.autoSizeColumn (columnIdClicked);
  41132. }
  41133. else if (menuReturnId == 0xf836744)
  41134. {
  41135. owner.autoSizeAllColumns();
  41136. }
  41137. else
  41138. {
  41139. TableHeaderComponent::reactToMenuItem (menuReturnId, columnIdClicked);
  41140. }
  41141. }
  41142. juce_UseDebuggingNewOperator
  41143. private:
  41144. TableListBox& owner;
  41145. TableListBoxHeader (const TableListBoxHeader&);
  41146. TableListBoxHeader& operator= (const TableListBoxHeader&);
  41147. };
  41148. TableListBox::TableListBox (const String& name, TableListBoxModel* const model_)
  41149. : ListBox (name, 0),
  41150. model (model_),
  41151. autoSizeOptionsShown (true)
  41152. {
  41153. ListBox::model = this;
  41154. header = new TableListBoxHeader (*this);
  41155. header->setSize (100, 28);
  41156. header->addListener (this);
  41157. setHeaderComponent (header);
  41158. }
  41159. TableListBox::~TableListBox()
  41160. {
  41161. deleteAllChildren();
  41162. }
  41163. void TableListBox::setModel (TableListBoxModel* const newModel)
  41164. {
  41165. if (model != newModel)
  41166. {
  41167. model = newModel;
  41168. updateContent();
  41169. }
  41170. }
  41171. int TableListBox::getHeaderHeight() const
  41172. {
  41173. return header->getHeight();
  41174. }
  41175. void TableListBox::setHeaderHeight (const int newHeight)
  41176. {
  41177. header->setSize (header->getWidth(), newHeight);
  41178. resized();
  41179. }
  41180. void TableListBox::autoSizeColumn (const int columnId)
  41181. {
  41182. const int width = model != 0 ? model->getColumnAutoSizeWidth (columnId) : 0;
  41183. if (width > 0)
  41184. header->setColumnWidth (columnId, width);
  41185. }
  41186. void TableListBox::autoSizeAllColumns()
  41187. {
  41188. for (int i = 0; i < header->getNumColumns (true); ++i)
  41189. autoSizeColumn (header->getColumnIdOfIndex (i, true));
  41190. }
  41191. void TableListBox::setAutoSizeMenuOptionShown (const bool shouldBeShown)
  41192. {
  41193. autoSizeOptionsShown = shouldBeShown;
  41194. }
  41195. bool TableListBox::isAutoSizeMenuOptionShown() const
  41196. {
  41197. return autoSizeOptionsShown;
  41198. }
  41199. const Rectangle<int> TableListBox::getCellPosition (const int columnId,
  41200. const int rowNumber,
  41201. const bool relativeToComponentTopLeft) const
  41202. {
  41203. Rectangle<int> headerCell (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  41204. if (relativeToComponentTopLeft)
  41205. headerCell.translate (header->getX(), 0);
  41206. const Rectangle<int> row (getRowPosition (rowNumber, relativeToComponentTopLeft));
  41207. return Rectangle<int> (headerCell.getX(), row.getY(),
  41208. headerCell.getWidth(), row.getHeight());
  41209. }
  41210. void TableListBox::scrollToEnsureColumnIsOnscreen (const int columnId)
  41211. {
  41212. ScrollBar* const scrollbar = getHorizontalScrollBar();
  41213. if (scrollbar != 0)
  41214. {
  41215. const Rectangle<int> pos (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  41216. double x = scrollbar->getCurrentRangeStart();
  41217. const double w = scrollbar->getCurrentRangeSize();
  41218. if (pos.getX() < x)
  41219. x = pos.getX();
  41220. else if (pos.getRight() > x + w)
  41221. x += jmax (0.0, pos.getRight() - (x + w));
  41222. scrollbar->setCurrentRangeStart (x);
  41223. }
  41224. }
  41225. int TableListBox::getNumRows()
  41226. {
  41227. return model != 0 ? model->getNumRows() : 0;
  41228. }
  41229. void TableListBox::paintListBoxItem (int, Graphics&, int, int, bool)
  41230. {
  41231. }
  41232. Component* TableListBox::refreshComponentForRow (int rowNumber, bool isRowSelected_, Component* existingComponentToUpdate)
  41233. {
  41234. if (existingComponentToUpdate == 0)
  41235. existingComponentToUpdate = new TableListRowComp (*this);
  41236. static_cast <TableListRowComp*> (existingComponentToUpdate)->update (rowNumber, isRowSelected_);
  41237. return existingComponentToUpdate;
  41238. }
  41239. void TableListBox::selectedRowsChanged (int row)
  41240. {
  41241. if (model != 0)
  41242. model->selectedRowsChanged (row);
  41243. }
  41244. void TableListBox::deleteKeyPressed (int row)
  41245. {
  41246. if (model != 0)
  41247. model->deleteKeyPressed (row);
  41248. }
  41249. void TableListBox::returnKeyPressed (int row)
  41250. {
  41251. if (model != 0)
  41252. model->returnKeyPressed (row);
  41253. }
  41254. void TableListBox::backgroundClicked()
  41255. {
  41256. if (model != 0)
  41257. model->backgroundClicked();
  41258. }
  41259. void TableListBox::listWasScrolled()
  41260. {
  41261. if (model != 0)
  41262. model->listWasScrolled();
  41263. }
  41264. void TableListBox::tableColumnsChanged (TableHeaderComponent*)
  41265. {
  41266. setMinimumContentWidth (header->getTotalWidth());
  41267. repaint();
  41268. updateColumnComponents();
  41269. }
  41270. void TableListBox::tableColumnsResized (TableHeaderComponent*)
  41271. {
  41272. setMinimumContentWidth (header->getTotalWidth());
  41273. repaint();
  41274. updateColumnComponents();
  41275. }
  41276. void TableListBox::tableSortOrderChanged (TableHeaderComponent*)
  41277. {
  41278. if (model != 0)
  41279. model->sortOrderChanged (header->getSortColumnId(),
  41280. header->isSortedForwards());
  41281. }
  41282. void TableListBox::tableColumnDraggingChanged (TableHeaderComponent*, int columnIdNowBeingDragged_)
  41283. {
  41284. columnIdNowBeingDragged = columnIdNowBeingDragged_;
  41285. repaint();
  41286. }
  41287. void TableListBox::resized()
  41288. {
  41289. ListBox::resized();
  41290. header->resizeAllColumnsToFit (getVisibleContentWidth());
  41291. setMinimumContentWidth (header->getTotalWidth());
  41292. }
  41293. void TableListBox::updateColumnComponents() const
  41294. {
  41295. const int firstRow = getRowContainingPosition (0, 0);
  41296. for (int i = firstRow + getNumRowsOnScreen() + 2; --i >= firstRow;)
  41297. {
  41298. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (i));
  41299. if (rowComp != 0)
  41300. rowComp->resized();
  41301. }
  41302. }
  41303. void TableListBoxModel::cellClicked (int, int, const MouseEvent&)
  41304. {
  41305. }
  41306. void TableListBoxModel::cellDoubleClicked (int, int, const MouseEvent&)
  41307. {
  41308. }
  41309. void TableListBoxModel::backgroundClicked()
  41310. {
  41311. }
  41312. void TableListBoxModel::sortOrderChanged (int, const bool)
  41313. {
  41314. }
  41315. int TableListBoxModel::getColumnAutoSizeWidth (int)
  41316. {
  41317. return 0;
  41318. }
  41319. void TableListBoxModel::selectedRowsChanged (int)
  41320. {
  41321. }
  41322. void TableListBoxModel::deleteKeyPressed (int)
  41323. {
  41324. }
  41325. void TableListBoxModel::returnKeyPressed (int)
  41326. {
  41327. }
  41328. void TableListBoxModel::listWasScrolled()
  41329. {
  41330. }
  41331. const String TableListBoxModel::getCellTooltip (int /*rowNumber*/, int /*columnId*/)
  41332. {
  41333. return String::empty;
  41334. }
  41335. const String TableListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  41336. {
  41337. return String::empty;
  41338. }
  41339. Component* TableListBoxModel::refreshComponentForCell (int, int, bool, Component* existingComponentToUpdate)
  41340. {
  41341. (void) existingComponentToUpdate;
  41342. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  41343. return 0;
  41344. }
  41345. END_JUCE_NAMESPACE
  41346. /*** End of inlined file: juce_TableListBox.cpp ***/
  41347. /*** Start of inlined file: juce_TextEditor.cpp ***/
  41348. BEGIN_JUCE_NAMESPACE
  41349. // a word or space that can't be broken down any further
  41350. struct TextAtom
  41351. {
  41352. String atomText;
  41353. float width;
  41354. uint16 numChars;
  41355. bool isWhitespace() const { return CharacterFunctions::isWhitespace (atomText[0]); }
  41356. bool isNewLine() const { return atomText[0] == '\r' || atomText[0] == '\n'; }
  41357. const String getText (const juce_wchar passwordCharacter) const
  41358. {
  41359. if (passwordCharacter == 0)
  41360. return atomText;
  41361. else
  41362. return String::repeatedString (String::charToString (passwordCharacter),
  41363. atomText.length());
  41364. }
  41365. const String getTrimmedText (const juce_wchar passwordCharacter) const
  41366. {
  41367. if (passwordCharacter == 0)
  41368. return atomText.substring (0, numChars);
  41369. else if (isNewLine())
  41370. return String::empty;
  41371. else
  41372. return String::repeatedString (String::charToString (passwordCharacter), numChars);
  41373. }
  41374. };
  41375. // a run of text with a single font and colour
  41376. class TextEditor::UniformTextSection
  41377. {
  41378. public:
  41379. UniformTextSection (const String& text,
  41380. const Font& font_,
  41381. const Colour& colour_,
  41382. const juce_wchar passwordCharacter)
  41383. : font (font_),
  41384. colour (colour_)
  41385. {
  41386. initialiseAtoms (text, passwordCharacter);
  41387. }
  41388. UniformTextSection (const UniformTextSection& other)
  41389. : font (other.font),
  41390. colour (other.colour)
  41391. {
  41392. atoms.ensureStorageAllocated (other.atoms.size());
  41393. for (int i = 0; i < other.atoms.size(); ++i)
  41394. atoms.add (new TextAtom (*other.atoms.getUnchecked(i)));
  41395. }
  41396. ~UniformTextSection()
  41397. {
  41398. // (no need to delete the atoms, as they're explicitly deleted by the caller)
  41399. }
  41400. void clear()
  41401. {
  41402. for (int i = atoms.size(); --i >= 0;)
  41403. delete getAtom(i);
  41404. atoms.clear();
  41405. }
  41406. int getNumAtoms() const
  41407. {
  41408. return atoms.size();
  41409. }
  41410. TextAtom* getAtom (const int index) const throw()
  41411. {
  41412. return atoms.getUnchecked (index);
  41413. }
  41414. void append (const UniformTextSection& other, const juce_wchar passwordCharacter)
  41415. {
  41416. if (other.atoms.size() > 0)
  41417. {
  41418. TextAtom* const lastAtom = atoms.getLast();
  41419. int i = 0;
  41420. if (lastAtom != 0)
  41421. {
  41422. if (! CharacterFunctions::isWhitespace (lastAtom->atomText.getLastCharacter()))
  41423. {
  41424. TextAtom* const first = other.getAtom(0);
  41425. if (! CharacterFunctions::isWhitespace (first->atomText[0]))
  41426. {
  41427. lastAtom->atomText += first->atomText;
  41428. lastAtom->numChars = (uint16) (lastAtom->numChars + first->numChars);
  41429. lastAtom->width = font.getStringWidthFloat (lastAtom->getText (passwordCharacter));
  41430. delete first;
  41431. ++i;
  41432. }
  41433. }
  41434. }
  41435. atoms.ensureStorageAllocated (atoms.size() + other.atoms.size() - i);
  41436. while (i < other.atoms.size())
  41437. {
  41438. atoms.add (other.getAtom(i));
  41439. ++i;
  41440. }
  41441. }
  41442. }
  41443. UniformTextSection* split (const int indexToBreakAt,
  41444. const juce_wchar passwordCharacter)
  41445. {
  41446. UniformTextSection* const section2 = new UniformTextSection (String::empty,
  41447. font, colour,
  41448. passwordCharacter);
  41449. int index = 0;
  41450. for (int i = 0; i < atoms.size(); ++i)
  41451. {
  41452. TextAtom* const atom = getAtom(i);
  41453. const int nextIndex = index + atom->numChars;
  41454. if (index == indexToBreakAt)
  41455. {
  41456. int j;
  41457. for (j = i; j < atoms.size(); ++j)
  41458. section2->atoms.add (getAtom (j));
  41459. for (j = atoms.size(); --j >= i;)
  41460. atoms.remove (j);
  41461. break;
  41462. }
  41463. else if (indexToBreakAt >= index && indexToBreakAt < nextIndex)
  41464. {
  41465. TextAtom* const secondAtom = new TextAtom();
  41466. secondAtom->atomText = atom->atomText.substring (indexToBreakAt - index);
  41467. secondAtom->width = font.getStringWidthFloat (secondAtom->getText (passwordCharacter));
  41468. secondAtom->numChars = (uint16) secondAtom->atomText.length();
  41469. section2->atoms.add (secondAtom);
  41470. atom->atomText = atom->atomText.substring (0, indexToBreakAt - index);
  41471. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  41472. atom->numChars = (uint16) (indexToBreakAt - index);
  41473. int j;
  41474. for (j = i + 1; j < atoms.size(); ++j)
  41475. section2->atoms.add (getAtom (j));
  41476. for (j = atoms.size(); --j > i;)
  41477. atoms.remove (j);
  41478. break;
  41479. }
  41480. index = nextIndex;
  41481. }
  41482. return section2;
  41483. }
  41484. void appendAllText (String::Concatenator& concatenator) const
  41485. {
  41486. for (int i = 0; i < atoms.size(); ++i)
  41487. concatenator.append (getAtom(i)->atomText);
  41488. }
  41489. void appendSubstring (String::Concatenator& concatenator,
  41490. const Range<int>& range) const
  41491. {
  41492. int index = 0;
  41493. for (int i = 0; i < atoms.size(); ++i)
  41494. {
  41495. const TextAtom* const atom = getAtom (i);
  41496. const int nextIndex = index + atom->numChars;
  41497. if (range.getStart() < nextIndex)
  41498. {
  41499. if (range.getEnd() <= index)
  41500. break;
  41501. const Range<int> r ((range - index).getIntersectionWith (Range<int> (0, (int) atom->numChars)));
  41502. if (! r.isEmpty())
  41503. concatenator.append (atom->atomText.substring (r.getStart(), r.getEnd()));
  41504. }
  41505. index = nextIndex;
  41506. }
  41507. }
  41508. int getTotalLength() const
  41509. {
  41510. int total = 0;
  41511. for (int i = atoms.size(); --i >= 0;)
  41512. total += getAtom(i)->numChars;
  41513. return total;
  41514. }
  41515. void setFont (const Font& newFont,
  41516. const juce_wchar passwordCharacter)
  41517. {
  41518. if (font != newFont)
  41519. {
  41520. font = newFont;
  41521. for (int i = atoms.size(); --i >= 0;)
  41522. {
  41523. TextAtom* const atom = atoms.getUnchecked(i);
  41524. atom->width = newFont.getStringWidthFloat (atom->getText (passwordCharacter));
  41525. }
  41526. }
  41527. }
  41528. juce_UseDebuggingNewOperator
  41529. Font font;
  41530. Colour colour;
  41531. private:
  41532. Array <TextAtom*> atoms;
  41533. void initialiseAtoms (const String& textToParse,
  41534. const juce_wchar passwordCharacter)
  41535. {
  41536. int i = 0;
  41537. const int len = textToParse.length();
  41538. const juce_wchar* const text = textToParse;
  41539. while (i < len)
  41540. {
  41541. int start = i;
  41542. // create a whitespace atom unless it starts with non-ws
  41543. if (CharacterFunctions::isWhitespace (text[i])
  41544. && text[i] != '\r'
  41545. && text[i] != '\n')
  41546. {
  41547. while (i < len
  41548. && CharacterFunctions::isWhitespace (text[i])
  41549. && text[i] != '\r'
  41550. && text[i] != '\n')
  41551. {
  41552. ++i;
  41553. }
  41554. }
  41555. else
  41556. {
  41557. if (text[i] == '\r')
  41558. {
  41559. ++i;
  41560. if ((i < len) && (text[i] == '\n'))
  41561. {
  41562. ++start;
  41563. ++i;
  41564. }
  41565. }
  41566. else if (text[i] == '\n')
  41567. {
  41568. ++i;
  41569. }
  41570. else
  41571. {
  41572. while ((i < len) && ! CharacterFunctions::isWhitespace (text[i]))
  41573. ++i;
  41574. }
  41575. }
  41576. TextAtom* const atom = new TextAtom();
  41577. atom->atomText = String (text + start, i - start);
  41578. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  41579. atom->numChars = (uint16) (i - start);
  41580. atoms.add (atom);
  41581. }
  41582. }
  41583. UniformTextSection& operator= (const UniformTextSection& other);
  41584. };
  41585. class TextEditor::Iterator
  41586. {
  41587. public:
  41588. Iterator (const Array <UniformTextSection*>& sections_,
  41589. const float wordWrapWidth_,
  41590. const juce_wchar passwordCharacter_)
  41591. : indexInText (0),
  41592. lineY (0),
  41593. lineHeight (0),
  41594. maxDescent (0),
  41595. atomX (0),
  41596. atomRight (0),
  41597. atom (0),
  41598. currentSection (0),
  41599. sections (sections_),
  41600. sectionIndex (0),
  41601. atomIndex (0),
  41602. wordWrapWidth (wordWrapWidth_),
  41603. passwordCharacter (passwordCharacter_)
  41604. {
  41605. jassert (wordWrapWidth_ > 0);
  41606. if (sections.size() > 0)
  41607. {
  41608. currentSection = sections.getUnchecked (sectionIndex);
  41609. if (currentSection != 0)
  41610. beginNewLine();
  41611. }
  41612. }
  41613. Iterator (const Iterator& other)
  41614. : indexInText (other.indexInText),
  41615. lineY (other.lineY),
  41616. lineHeight (other.lineHeight),
  41617. maxDescent (other.maxDescent),
  41618. atomX (other.atomX),
  41619. atomRight (other.atomRight),
  41620. atom (other.atom),
  41621. currentSection (other.currentSection),
  41622. sections (other.sections),
  41623. sectionIndex (other.sectionIndex),
  41624. atomIndex (other.atomIndex),
  41625. wordWrapWidth (other.wordWrapWidth),
  41626. passwordCharacter (other.passwordCharacter),
  41627. tempAtom (other.tempAtom)
  41628. {
  41629. }
  41630. ~Iterator()
  41631. {
  41632. }
  41633. bool next()
  41634. {
  41635. if (atom == &tempAtom)
  41636. {
  41637. const int numRemaining = tempAtom.atomText.length() - tempAtom.numChars;
  41638. if (numRemaining > 0)
  41639. {
  41640. tempAtom.atomText = tempAtom.atomText.substring (tempAtom.numChars);
  41641. atomX = 0;
  41642. if (tempAtom.numChars > 0)
  41643. lineY += lineHeight;
  41644. indexInText += tempAtom.numChars;
  41645. GlyphArrangement g;
  41646. g.addLineOfText (currentSection->font, atom->getText (passwordCharacter), 0.0f, 0.0f);
  41647. int split;
  41648. for (split = 0; split < g.getNumGlyphs(); ++split)
  41649. if (shouldWrap (g.getGlyph (split).getRight()))
  41650. break;
  41651. if (split > 0 && split <= numRemaining)
  41652. {
  41653. tempAtom.numChars = (uint16) split;
  41654. tempAtom.width = g.getGlyph (split - 1).getRight();
  41655. atomRight = atomX + tempAtom.width;
  41656. return true;
  41657. }
  41658. }
  41659. }
  41660. bool forceNewLine = false;
  41661. if (sectionIndex >= sections.size())
  41662. {
  41663. moveToEndOfLastAtom();
  41664. return false;
  41665. }
  41666. else if (atomIndex >= currentSection->getNumAtoms() - 1)
  41667. {
  41668. if (atomIndex >= currentSection->getNumAtoms())
  41669. {
  41670. if (++sectionIndex >= sections.size())
  41671. {
  41672. moveToEndOfLastAtom();
  41673. return false;
  41674. }
  41675. atomIndex = 0;
  41676. currentSection = sections.getUnchecked (sectionIndex);
  41677. }
  41678. else
  41679. {
  41680. const TextAtom* const lastAtom = currentSection->getAtom (atomIndex);
  41681. if (! lastAtom->isWhitespace())
  41682. {
  41683. // handle the case where the last atom in a section is actually part of the same
  41684. // word as the first atom of the next section...
  41685. float right = atomRight + lastAtom->width;
  41686. float lineHeight2 = lineHeight;
  41687. float maxDescent2 = maxDescent;
  41688. for (int section = sectionIndex + 1; section < sections.size(); ++section)
  41689. {
  41690. const UniformTextSection* const s = sections.getUnchecked (section);
  41691. if (s->getNumAtoms() == 0)
  41692. break;
  41693. const TextAtom* const nextAtom = s->getAtom (0);
  41694. if (nextAtom->isWhitespace())
  41695. break;
  41696. right += nextAtom->width;
  41697. lineHeight2 = jmax (lineHeight2, s->font.getHeight());
  41698. maxDescent2 = jmax (maxDescent2, s->font.getDescent());
  41699. if (shouldWrap (right))
  41700. {
  41701. lineHeight = lineHeight2;
  41702. maxDescent = maxDescent2;
  41703. forceNewLine = true;
  41704. break;
  41705. }
  41706. if (s->getNumAtoms() > 1)
  41707. break;
  41708. }
  41709. }
  41710. }
  41711. }
  41712. if (atom != 0)
  41713. {
  41714. atomX = atomRight;
  41715. indexInText += atom->numChars;
  41716. if (atom->isNewLine())
  41717. beginNewLine();
  41718. }
  41719. atom = currentSection->getAtom (atomIndex);
  41720. atomRight = atomX + atom->width;
  41721. ++atomIndex;
  41722. if (shouldWrap (atomRight) || forceNewLine)
  41723. {
  41724. if (atom->isWhitespace())
  41725. {
  41726. // leave whitespace at the end of a line, but truncate it to avoid scrolling
  41727. atomRight = jmin (atomRight, wordWrapWidth);
  41728. }
  41729. else
  41730. {
  41731. atomRight = atom->width;
  41732. if (shouldWrap (atomRight)) // atom too big to fit on a line, so break it up..
  41733. {
  41734. tempAtom = *atom;
  41735. tempAtom.width = 0;
  41736. tempAtom.numChars = 0;
  41737. atom = &tempAtom;
  41738. if (atomX > 0)
  41739. beginNewLine();
  41740. return next();
  41741. }
  41742. beginNewLine();
  41743. return true;
  41744. }
  41745. }
  41746. return true;
  41747. }
  41748. void beginNewLine()
  41749. {
  41750. atomX = 0;
  41751. lineY += lineHeight;
  41752. int tempSectionIndex = sectionIndex;
  41753. int tempAtomIndex = atomIndex;
  41754. const UniformTextSection* section = sections.getUnchecked (tempSectionIndex);
  41755. lineHeight = section->font.getHeight();
  41756. maxDescent = section->font.getDescent();
  41757. float x = (atom != 0) ? atom->width : 0;
  41758. while (! shouldWrap (x))
  41759. {
  41760. if (tempSectionIndex >= sections.size())
  41761. break;
  41762. bool checkSize = false;
  41763. if (tempAtomIndex >= section->getNumAtoms())
  41764. {
  41765. if (++tempSectionIndex >= sections.size())
  41766. break;
  41767. tempAtomIndex = 0;
  41768. section = sections.getUnchecked (tempSectionIndex);
  41769. checkSize = true;
  41770. }
  41771. const TextAtom* const nextAtom = section->getAtom (tempAtomIndex);
  41772. if (nextAtom == 0)
  41773. break;
  41774. x += nextAtom->width;
  41775. if (shouldWrap (x) || nextAtom->isNewLine())
  41776. break;
  41777. if (checkSize)
  41778. {
  41779. lineHeight = jmax (lineHeight, section->font.getHeight());
  41780. maxDescent = jmax (maxDescent, section->font.getDescent());
  41781. }
  41782. ++tempAtomIndex;
  41783. }
  41784. }
  41785. void draw (Graphics& g, const UniformTextSection*& lastSection) const
  41786. {
  41787. if (passwordCharacter != 0 || ! atom->isWhitespace())
  41788. {
  41789. if (lastSection != currentSection)
  41790. {
  41791. lastSection = currentSection;
  41792. g.setColour (currentSection->colour);
  41793. g.setFont (currentSection->font);
  41794. }
  41795. jassert (atom->getTrimmedText (passwordCharacter).isNotEmpty());
  41796. GlyphArrangement ga;
  41797. ga.addLineOfText (currentSection->font,
  41798. atom->getTrimmedText (passwordCharacter),
  41799. atomX,
  41800. (float) roundToInt (lineY + lineHeight - maxDescent));
  41801. ga.draw (g);
  41802. }
  41803. }
  41804. void drawSelection (Graphics& g,
  41805. const Range<int>& selection) const
  41806. {
  41807. const int startX = roundToInt (indexToX (selection.getStart()));
  41808. const int endX = roundToInt (indexToX (selection.getEnd()));
  41809. const int y = roundToInt (lineY);
  41810. const int nextY = roundToInt (lineY + lineHeight);
  41811. g.fillRect (startX, y, endX - startX, nextY - y);
  41812. }
  41813. void drawSelectedText (Graphics& g,
  41814. const Range<int>& selection,
  41815. const Colour& selectedTextColour) const
  41816. {
  41817. if (passwordCharacter != 0 || ! atom->isWhitespace())
  41818. {
  41819. GlyphArrangement ga;
  41820. ga.addLineOfText (currentSection->font,
  41821. atom->getTrimmedText (passwordCharacter),
  41822. atomX,
  41823. (float) roundToInt (lineY + lineHeight - maxDescent));
  41824. if (selection.getEnd() < indexInText + atom->numChars)
  41825. {
  41826. GlyphArrangement ga2 (ga);
  41827. ga2.removeRangeOfGlyphs (0, selection.getEnd() - indexInText);
  41828. ga.removeRangeOfGlyphs (selection.getEnd() - indexInText, -1);
  41829. g.setColour (currentSection->colour);
  41830. ga2.draw (g);
  41831. }
  41832. if (selection.getStart() > indexInText)
  41833. {
  41834. GlyphArrangement ga2 (ga);
  41835. ga2.removeRangeOfGlyphs (selection.getStart() - indexInText, -1);
  41836. ga.removeRangeOfGlyphs (0, selection.getStart() - indexInText);
  41837. g.setColour (currentSection->colour);
  41838. ga2.draw (g);
  41839. }
  41840. g.setColour (selectedTextColour);
  41841. ga.draw (g);
  41842. }
  41843. }
  41844. float indexToX (const int indexToFind) const
  41845. {
  41846. if (indexToFind <= indexInText)
  41847. return atomX;
  41848. if (indexToFind >= indexInText + atom->numChars)
  41849. return atomRight;
  41850. GlyphArrangement g;
  41851. g.addLineOfText (currentSection->font,
  41852. atom->getText (passwordCharacter),
  41853. atomX, 0.0f);
  41854. if (indexToFind - indexInText >= g.getNumGlyphs())
  41855. return atomRight;
  41856. return jmin (atomRight, g.getGlyph (indexToFind - indexInText).getLeft());
  41857. }
  41858. int xToIndex (const float xToFind) const
  41859. {
  41860. if (xToFind <= atomX || atom->isNewLine())
  41861. return indexInText;
  41862. if (xToFind >= atomRight)
  41863. return indexInText + atom->numChars;
  41864. GlyphArrangement g;
  41865. g.addLineOfText (currentSection->font,
  41866. atom->getText (passwordCharacter),
  41867. atomX, 0.0f);
  41868. int j;
  41869. for (j = 0; j < g.getNumGlyphs(); ++j)
  41870. if ((g.getGlyph(j).getLeft() + g.getGlyph(j).getRight()) / 2 > xToFind)
  41871. break;
  41872. return indexInText + j;
  41873. }
  41874. bool getCharPosition (const int index, float& cx, float& cy, float& lineHeight_)
  41875. {
  41876. while (next())
  41877. {
  41878. if (indexInText + atom->numChars > index)
  41879. {
  41880. cx = indexToX (index);
  41881. cy = lineY;
  41882. lineHeight_ = lineHeight;
  41883. return true;
  41884. }
  41885. }
  41886. cx = atomX;
  41887. cy = lineY;
  41888. lineHeight_ = lineHeight;
  41889. return false;
  41890. }
  41891. juce_UseDebuggingNewOperator
  41892. int indexInText;
  41893. float lineY, lineHeight, maxDescent;
  41894. float atomX, atomRight;
  41895. const TextAtom* atom;
  41896. const UniformTextSection* currentSection;
  41897. private:
  41898. const Array <UniformTextSection*>& sections;
  41899. int sectionIndex, atomIndex;
  41900. const float wordWrapWidth;
  41901. const juce_wchar passwordCharacter;
  41902. TextAtom tempAtom;
  41903. Iterator& operator= (const Iterator&);
  41904. void moveToEndOfLastAtom()
  41905. {
  41906. if (atom != 0)
  41907. {
  41908. atomX = atomRight;
  41909. if (atom->isNewLine())
  41910. {
  41911. atomX = 0.0f;
  41912. lineY += lineHeight;
  41913. }
  41914. }
  41915. }
  41916. bool shouldWrap (const float x) const
  41917. {
  41918. return (x - 0.0001f) >= wordWrapWidth;
  41919. }
  41920. };
  41921. class TextEditor::InsertAction : public UndoableAction
  41922. {
  41923. TextEditor& owner;
  41924. const String text;
  41925. const int insertIndex, oldCaretPos, newCaretPos;
  41926. const Font font;
  41927. const Colour colour;
  41928. InsertAction (const InsertAction&);
  41929. InsertAction& operator= (const InsertAction&);
  41930. public:
  41931. InsertAction (TextEditor& owner_,
  41932. const String& text_,
  41933. const int insertIndex_,
  41934. const Font& font_,
  41935. const Colour& colour_,
  41936. const int oldCaretPos_,
  41937. const int newCaretPos_)
  41938. : owner (owner_),
  41939. text (text_),
  41940. insertIndex (insertIndex_),
  41941. oldCaretPos (oldCaretPos_),
  41942. newCaretPos (newCaretPos_),
  41943. font (font_),
  41944. colour (colour_)
  41945. {
  41946. }
  41947. ~InsertAction()
  41948. {
  41949. }
  41950. bool perform()
  41951. {
  41952. owner.insert (text, insertIndex, font, colour, 0, newCaretPos);
  41953. return true;
  41954. }
  41955. bool undo()
  41956. {
  41957. owner.remove (Range<int> (insertIndex, insertIndex + text.length()), 0, oldCaretPos);
  41958. return true;
  41959. }
  41960. int getSizeInUnits()
  41961. {
  41962. return text.length() + 16;
  41963. }
  41964. };
  41965. class TextEditor::RemoveAction : public UndoableAction
  41966. {
  41967. TextEditor& owner;
  41968. const Range<int> range;
  41969. const int oldCaretPos, newCaretPos;
  41970. Array <UniformTextSection*> removedSections;
  41971. RemoveAction (const RemoveAction&);
  41972. RemoveAction& operator= (const RemoveAction&);
  41973. public:
  41974. RemoveAction (TextEditor& owner_,
  41975. const Range<int> range_,
  41976. const int oldCaretPos_,
  41977. const int newCaretPos_,
  41978. const Array <UniformTextSection*>& removedSections_)
  41979. : owner (owner_),
  41980. range (range_),
  41981. oldCaretPos (oldCaretPos_),
  41982. newCaretPos (newCaretPos_),
  41983. removedSections (removedSections_)
  41984. {
  41985. }
  41986. ~RemoveAction()
  41987. {
  41988. for (int i = removedSections.size(); --i >= 0;)
  41989. {
  41990. UniformTextSection* const section = removedSections.getUnchecked (i);
  41991. section->clear();
  41992. delete section;
  41993. }
  41994. }
  41995. bool perform()
  41996. {
  41997. owner.remove (range, 0, newCaretPos);
  41998. return true;
  41999. }
  42000. bool undo()
  42001. {
  42002. owner.reinsert (range.getStart(), removedSections);
  42003. owner.moveCursorTo (oldCaretPos, false);
  42004. return true;
  42005. }
  42006. int getSizeInUnits()
  42007. {
  42008. int n = 0;
  42009. for (int i = removedSections.size(); --i >= 0;)
  42010. n += removedSections.getUnchecked (i)->getTotalLength();
  42011. return n + 16;
  42012. }
  42013. };
  42014. class TextEditor::TextHolderComponent : public Component,
  42015. public Timer,
  42016. public Value::Listener
  42017. {
  42018. public:
  42019. TextHolderComponent (TextEditor& owner_)
  42020. : owner (owner_)
  42021. {
  42022. setWantsKeyboardFocus (false);
  42023. setInterceptsMouseClicks (false, true);
  42024. owner.getTextValue().addListener (this);
  42025. }
  42026. ~TextHolderComponent()
  42027. {
  42028. owner.getTextValue().removeListener (this);
  42029. }
  42030. void paint (Graphics& g)
  42031. {
  42032. owner.drawContent (g);
  42033. }
  42034. void timerCallback()
  42035. {
  42036. owner.timerCallbackInt();
  42037. }
  42038. const MouseCursor getMouseCursor()
  42039. {
  42040. return owner.getMouseCursor();
  42041. }
  42042. void valueChanged (Value&)
  42043. {
  42044. owner.textWasChangedByValue();
  42045. }
  42046. private:
  42047. TextEditor& owner;
  42048. TextHolderComponent (const TextHolderComponent&);
  42049. TextHolderComponent& operator= (const TextHolderComponent&);
  42050. };
  42051. class TextEditorViewport : public Viewport
  42052. {
  42053. public:
  42054. TextEditorViewport (TextEditor* const owner_)
  42055. : owner (owner_), lastWordWrapWidth (0), rentrant (false)
  42056. {
  42057. }
  42058. ~TextEditorViewport()
  42059. {
  42060. }
  42061. void visibleAreaChanged (int, int, int, int)
  42062. {
  42063. if (! rentrant) // it's rare, but possible to get into a feedback loop as the viewport's scrollbars
  42064. // appear and disappear, causing the wrap width to change.
  42065. {
  42066. const float wordWrapWidth = owner->getWordWrapWidth();
  42067. if (wordWrapWidth != lastWordWrapWidth)
  42068. {
  42069. lastWordWrapWidth = wordWrapWidth;
  42070. rentrant = true;
  42071. owner->updateTextHolderSize();
  42072. rentrant = false;
  42073. }
  42074. }
  42075. }
  42076. private:
  42077. TextEditor* const owner;
  42078. float lastWordWrapWidth;
  42079. bool rentrant;
  42080. TextEditorViewport (const TextEditorViewport&);
  42081. TextEditorViewport& operator= (const TextEditorViewport&);
  42082. };
  42083. namespace TextEditorDefs
  42084. {
  42085. const int flashSpeedIntervalMs = 380;
  42086. const int textChangeMessageId = 0x10003001;
  42087. const int returnKeyMessageId = 0x10003002;
  42088. const int escapeKeyMessageId = 0x10003003;
  42089. const int focusLossMessageId = 0x10003004;
  42090. const int maxActionsPerTransaction = 100;
  42091. }
  42092. TextEditor::TextEditor (const String& name,
  42093. const juce_wchar passwordCharacter_)
  42094. : Component (name),
  42095. borderSize (1, 1, 1, 3),
  42096. readOnly (false),
  42097. multiline (false),
  42098. wordWrap (false),
  42099. returnKeyStartsNewLine (false),
  42100. caretVisible (true),
  42101. popupMenuEnabled (true),
  42102. selectAllTextWhenFocused (false),
  42103. scrollbarVisible (true),
  42104. wasFocused (false),
  42105. caretFlashState (true),
  42106. keepCursorOnScreen (true),
  42107. tabKeyUsed (false),
  42108. menuActive (false),
  42109. valueTextNeedsUpdating (false),
  42110. cursorX (0),
  42111. cursorY (0),
  42112. cursorHeight (0),
  42113. maxTextLength (0),
  42114. leftIndent (4),
  42115. topIndent (4),
  42116. lastTransactionTime (0),
  42117. currentFont (14.0f),
  42118. totalNumChars (0),
  42119. caretPosition (0),
  42120. passwordCharacter (passwordCharacter_),
  42121. dragType (notDragging)
  42122. {
  42123. setOpaque (true);
  42124. addAndMakeVisible (viewport = new TextEditorViewport (this));
  42125. viewport->setViewedComponent (textHolder = new TextHolderComponent (*this));
  42126. viewport->setWantsKeyboardFocus (false);
  42127. viewport->setScrollBarsShown (false, false);
  42128. setMouseCursor (MouseCursor::IBeamCursor);
  42129. setWantsKeyboardFocus (true);
  42130. }
  42131. TextEditor::~TextEditor()
  42132. {
  42133. textValue.referTo (Value());
  42134. clearInternal (0);
  42135. viewport = 0;
  42136. textHolder = 0;
  42137. }
  42138. void TextEditor::newTransaction()
  42139. {
  42140. lastTransactionTime = Time::getApproximateMillisecondCounter();
  42141. undoManager.beginNewTransaction();
  42142. }
  42143. void TextEditor::doUndoRedo (const bool isRedo)
  42144. {
  42145. if (! isReadOnly())
  42146. {
  42147. if (isRedo ? undoManager.redo()
  42148. : undoManager.undo())
  42149. {
  42150. scrollToMakeSureCursorIsVisible();
  42151. repaint();
  42152. textChanged();
  42153. }
  42154. }
  42155. }
  42156. void TextEditor::setMultiLine (const bool shouldBeMultiLine,
  42157. const bool shouldWordWrap)
  42158. {
  42159. if (multiline != shouldBeMultiLine
  42160. || wordWrap != (shouldWordWrap && shouldBeMultiLine))
  42161. {
  42162. multiline = shouldBeMultiLine;
  42163. wordWrap = shouldWordWrap && shouldBeMultiLine;
  42164. viewport->setScrollBarsShown (scrollbarVisible && multiline,
  42165. scrollbarVisible && multiline);
  42166. viewport->setViewPosition (0, 0);
  42167. resized();
  42168. scrollToMakeSureCursorIsVisible();
  42169. }
  42170. }
  42171. bool TextEditor::isMultiLine() const
  42172. {
  42173. return multiline;
  42174. }
  42175. void TextEditor::setScrollbarsShown (bool shown)
  42176. {
  42177. if (scrollbarVisible != shown)
  42178. {
  42179. scrollbarVisible = shown;
  42180. shown = shown && isMultiLine();
  42181. viewport->setScrollBarsShown (shown, shown);
  42182. }
  42183. }
  42184. void TextEditor::setReadOnly (const bool shouldBeReadOnly)
  42185. {
  42186. if (readOnly != shouldBeReadOnly)
  42187. {
  42188. readOnly = shouldBeReadOnly;
  42189. enablementChanged();
  42190. }
  42191. }
  42192. bool TextEditor::isReadOnly() const
  42193. {
  42194. return readOnly || ! isEnabled();
  42195. }
  42196. bool TextEditor::isTextInputActive() const
  42197. {
  42198. return ! isReadOnly();
  42199. }
  42200. void TextEditor::setReturnKeyStartsNewLine (const bool shouldStartNewLine)
  42201. {
  42202. returnKeyStartsNewLine = shouldStartNewLine;
  42203. }
  42204. void TextEditor::setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed)
  42205. {
  42206. tabKeyUsed = shouldTabKeyBeUsed;
  42207. }
  42208. void TextEditor::setPopupMenuEnabled (const bool b)
  42209. {
  42210. popupMenuEnabled = b;
  42211. }
  42212. void TextEditor::setSelectAllWhenFocused (const bool b)
  42213. {
  42214. selectAllTextWhenFocused = b;
  42215. }
  42216. const Font TextEditor::getFont() const
  42217. {
  42218. return currentFont;
  42219. }
  42220. void TextEditor::setFont (const Font& newFont)
  42221. {
  42222. currentFont = newFont;
  42223. scrollToMakeSureCursorIsVisible();
  42224. }
  42225. void TextEditor::applyFontToAllText (const Font& newFont)
  42226. {
  42227. currentFont = newFont;
  42228. const Colour overallColour (findColour (textColourId));
  42229. for (int i = sections.size(); --i >= 0;)
  42230. {
  42231. UniformTextSection* const uts = sections.getUnchecked (i);
  42232. uts->setFont (newFont, passwordCharacter);
  42233. uts->colour = overallColour;
  42234. }
  42235. coalesceSimilarSections();
  42236. updateTextHolderSize();
  42237. scrollToMakeSureCursorIsVisible();
  42238. repaint();
  42239. }
  42240. void TextEditor::colourChanged()
  42241. {
  42242. setOpaque (findColour (backgroundColourId).isOpaque());
  42243. repaint();
  42244. }
  42245. void TextEditor::setCaretVisible (const bool shouldCaretBeVisible)
  42246. {
  42247. caretVisible = shouldCaretBeVisible;
  42248. if (shouldCaretBeVisible)
  42249. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42250. setMouseCursor (shouldCaretBeVisible ? MouseCursor::IBeamCursor
  42251. : MouseCursor::NormalCursor);
  42252. }
  42253. void TextEditor::setInputRestrictions (const int maxLen,
  42254. const String& chars)
  42255. {
  42256. maxTextLength = jmax (0, maxLen);
  42257. allowedCharacters = chars;
  42258. }
  42259. void TextEditor::setTextToShowWhenEmpty (const String& text, const Colour& colourToUse)
  42260. {
  42261. textToShowWhenEmpty = text;
  42262. colourForTextWhenEmpty = colourToUse;
  42263. }
  42264. void TextEditor::setPasswordCharacter (const juce_wchar newPasswordCharacter)
  42265. {
  42266. if (passwordCharacter != newPasswordCharacter)
  42267. {
  42268. passwordCharacter = newPasswordCharacter;
  42269. resized();
  42270. repaint();
  42271. }
  42272. }
  42273. void TextEditor::setScrollBarThickness (const int newThicknessPixels)
  42274. {
  42275. viewport->setScrollBarThickness (newThicknessPixels);
  42276. }
  42277. void TextEditor::setScrollBarButtonVisibility (const bool buttonsVisible)
  42278. {
  42279. viewport->setScrollBarButtonVisibility (buttonsVisible);
  42280. }
  42281. void TextEditor::clear()
  42282. {
  42283. clearInternal (0);
  42284. updateTextHolderSize();
  42285. undoManager.clearUndoHistory();
  42286. }
  42287. void TextEditor::setText (const String& newText,
  42288. const bool sendTextChangeMessage)
  42289. {
  42290. const int newLength = newText.length();
  42291. if (newLength != getTotalNumChars() || getText() != newText)
  42292. {
  42293. const int oldCursorPos = caretPosition;
  42294. const bool cursorWasAtEnd = oldCursorPos >= getTotalNumChars();
  42295. clearInternal (0);
  42296. insert (newText, 0, currentFont, findColour (textColourId), 0, caretPosition);
  42297. // if you're adding text with line-feeds to a single-line text editor, it
  42298. // ain't gonna look right!
  42299. jassert (multiline || ! newText.containsAnyOf ("\r\n"));
  42300. if (cursorWasAtEnd && ! isMultiLine())
  42301. moveCursorTo (getTotalNumChars(), false);
  42302. else
  42303. moveCursorTo (oldCursorPos, false);
  42304. if (sendTextChangeMessage)
  42305. textChanged();
  42306. updateTextHolderSize();
  42307. scrollToMakeSureCursorIsVisible();
  42308. undoManager.clearUndoHistory();
  42309. repaint();
  42310. }
  42311. }
  42312. Value& TextEditor::getTextValue()
  42313. {
  42314. if (valueTextNeedsUpdating)
  42315. {
  42316. valueTextNeedsUpdating = false;
  42317. textValue = getText();
  42318. }
  42319. return textValue;
  42320. }
  42321. void TextEditor::textWasChangedByValue()
  42322. {
  42323. if (textValue.getValueSource().getReferenceCount() > 1)
  42324. setText (textValue.getValue());
  42325. }
  42326. void TextEditor::textChanged()
  42327. {
  42328. updateTextHolderSize();
  42329. postCommandMessage (TextEditorDefs::textChangeMessageId);
  42330. if (textValue.getValueSource().getReferenceCount() > 1)
  42331. {
  42332. valueTextNeedsUpdating = false;
  42333. textValue = getText();
  42334. }
  42335. }
  42336. void TextEditor::returnPressed()
  42337. {
  42338. postCommandMessage (TextEditorDefs::returnKeyMessageId);
  42339. }
  42340. void TextEditor::escapePressed()
  42341. {
  42342. postCommandMessage (TextEditorDefs::escapeKeyMessageId);
  42343. }
  42344. void TextEditor::addListener (TextEditorListener* const newListener)
  42345. {
  42346. listeners.add (newListener);
  42347. }
  42348. void TextEditor::removeListener (TextEditorListener* const listenerToRemove)
  42349. {
  42350. listeners.remove (listenerToRemove);
  42351. }
  42352. void TextEditor::timerCallbackInt()
  42353. {
  42354. const bool newState = (! caretFlashState) && ! isCurrentlyBlockedByAnotherModalComponent();
  42355. if (caretFlashState != newState)
  42356. {
  42357. caretFlashState = newState;
  42358. if (caretFlashState)
  42359. wasFocused = true;
  42360. if (caretVisible
  42361. && hasKeyboardFocus (false)
  42362. && ! isReadOnly())
  42363. {
  42364. repaintCaret();
  42365. }
  42366. }
  42367. const unsigned int now = Time::getApproximateMillisecondCounter();
  42368. if (now > lastTransactionTime + 200)
  42369. newTransaction();
  42370. }
  42371. void TextEditor::repaintCaret()
  42372. {
  42373. if (! findColour (caretColourId).isTransparent())
  42374. repaint (borderSize.getLeft() + textHolder->getX() + leftIndent + roundToInt (cursorX) - 1,
  42375. borderSize.getTop() + textHolder->getY() + topIndent + roundToInt (cursorY) - 1,
  42376. 4,
  42377. roundToInt (cursorHeight) + 2);
  42378. }
  42379. void TextEditor::repaintText (const Range<int>& range)
  42380. {
  42381. if (! range.isEmpty())
  42382. {
  42383. float x = 0, y = 0, lh = currentFont.getHeight();
  42384. const float wordWrapWidth = getWordWrapWidth();
  42385. if (wordWrapWidth > 0)
  42386. {
  42387. Iterator i (sections, wordWrapWidth, passwordCharacter);
  42388. i.getCharPosition (range.getStart(), x, y, lh);
  42389. const int y1 = (int) y;
  42390. int y2;
  42391. if (range.getEnd() >= getTotalNumChars())
  42392. {
  42393. y2 = textHolder->getHeight();
  42394. }
  42395. else
  42396. {
  42397. i.getCharPosition (range.getEnd(), x, y, lh);
  42398. y2 = (int) (y + lh * 2.0f);
  42399. }
  42400. textHolder->repaint (0, y1, textHolder->getWidth(), y2 - y1);
  42401. }
  42402. }
  42403. }
  42404. void TextEditor::moveCaret (int newCaretPos)
  42405. {
  42406. if (newCaretPos < 0)
  42407. newCaretPos = 0;
  42408. else if (newCaretPos > getTotalNumChars())
  42409. newCaretPos = getTotalNumChars();
  42410. if (newCaretPos != getCaretPosition())
  42411. {
  42412. repaintCaret();
  42413. caretFlashState = true;
  42414. caretPosition = newCaretPos;
  42415. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42416. scrollToMakeSureCursorIsVisible();
  42417. repaintCaret();
  42418. }
  42419. }
  42420. void TextEditor::setCaretPosition (const int newIndex)
  42421. {
  42422. moveCursorTo (newIndex, false);
  42423. }
  42424. int TextEditor::getCaretPosition() const
  42425. {
  42426. return caretPosition;
  42427. }
  42428. void TextEditor::scrollEditorToPositionCaret (const int desiredCaretX,
  42429. const int desiredCaretY)
  42430. {
  42431. updateCaretPosition();
  42432. int vx = roundToInt (cursorX) - desiredCaretX;
  42433. int vy = roundToInt (cursorY) - desiredCaretY;
  42434. if (desiredCaretX < jmax (1, proportionOfWidth (0.05f)))
  42435. {
  42436. vx += desiredCaretX - proportionOfWidth (0.2f);
  42437. }
  42438. else if (desiredCaretX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  42439. {
  42440. vx += desiredCaretX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  42441. }
  42442. vx = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), vx);
  42443. if (! isMultiLine())
  42444. {
  42445. vy = viewport->getViewPositionY();
  42446. }
  42447. else
  42448. {
  42449. vy = jlimit (0, jmax (0, textHolder->getHeight() - viewport->getMaximumVisibleHeight()), vy);
  42450. const int curH = roundToInt (cursorHeight);
  42451. if (desiredCaretY < 0)
  42452. {
  42453. vy = jmax (0, desiredCaretY + vy);
  42454. }
  42455. else if (desiredCaretY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  42456. {
  42457. vy += desiredCaretY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  42458. }
  42459. }
  42460. viewport->setViewPosition (vx, vy);
  42461. }
  42462. const Rectangle<int> TextEditor::getCaretRectangle()
  42463. {
  42464. updateCaretPosition();
  42465. return Rectangle<int> (roundToInt (cursorX) - viewport->getX(),
  42466. roundToInt (cursorY) - viewport->getY(),
  42467. 1, roundToInt (cursorHeight));
  42468. }
  42469. float TextEditor::getWordWrapWidth() const
  42470. {
  42471. return (wordWrap) ? (float) (viewport->getMaximumVisibleWidth() - leftIndent - leftIndent / 2)
  42472. : 1.0e10f;
  42473. }
  42474. void TextEditor::updateTextHolderSize()
  42475. {
  42476. const float wordWrapWidth = getWordWrapWidth();
  42477. if (wordWrapWidth > 0)
  42478. {
  42479. float maxWidth = 0.0f;
  42480. Iterator i (sections, wordWrapWidth, passwordCharacter);
  42481. while (i.next())
  42482. maxWidth = jmax (maxWidth, i.atomRight);
  42483. const int w = leftIndent + roundToInt (maxWidth);
  42484. const int h = topIndent + roundToInt (jmax (i.lineY + i.lineHeight,
  42485. currentFont.getHeight()));
  42486. textHolder->setSize (w + 1, h + 1);
  42487. }
  42488. }
  42489. int TextEditor::getTextWidth() const
  42490. {
  42491. return textHolder->getWidth();
  42492. }
  42493. int TextEditor::getTextHeight() const
  42494. {
  42495. return textHolder->getHeight();
  42496. }
  42497. void TextEditor::setIndents (const int newLeftIndent,
  42498. const int newTopIndent)
  42499. {
  42500. leftIndent = newLeftIndent;
  42501. topIndent = newTopIndent;
  42502. }
  42503. void TextEditor::setBorder (const BorderSize& border)
  42504. {
  42505. borderSize = border;
  42506. resized();
  42507. }
  42508. const BorderSize TextEditor::getBorder() const
  42509. {
  42510. return borderSize;
  42511. }
  42512. void TextEditor::setScrollToShowCursor (const bool shouldScrollToShowCursor)
  42513. {
  42514. keepCursorOnScreen = shouldScrollToShowCursor;
  42515. }
  42516. void TextEditor::updateCaretPosition()
  42517. {
  42518. cursorHeight = currentFont.getHeight(); // (in case the text is empty and the call below doesn't set this value)
  42519. getCharPosition (caretPosition, cursorX, cursorY, cursorHeight);
  42520. }
  42521. void TextEditor::scrollToMakeSureCursorIsVisible()
  42522. {
  42523. updateCaretPosition();
  42524. if (keepCursorOnScreen)
  42525. {
  42526. int x = viewport->getViewPositionX();
  42527. int y = viewport->getViewPositionY();
  42528. const int relativeCursorX = roundToInt (cursorX) - x;
  42529. const int relativeCursorY = roundToInt (cursorY) - y;
  42530. if (relativeCursorX < jmax (1, proportionOfWidth (0.05f)))
  42531. {
  42532. x += relativeCursorX - proportionOfWidth (0.2f);
  42533. }
  42534. else if (relativeCursorX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  42535. {
  42536. x += relativeCursorX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  42537. }
  42538. x = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), x);
  42539. if (! isMultiLine())
  42540. {
  42541. y = (getHeight() - textHolder->getHeight() - topIndent) / -2;
  42542. }
  42543. else
  42544. {
  42545. const int curH = roundToInt (cursorHeight);
  42546. if (relativeCursorY < 0)
  42547. {
  42548. y = jmax (0, relativeCursorY + y);
  42549. }
  42550. else if (relativeCursorY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  42551. {
  42552. y += relativeCursorY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  42553. }
  42554. }
  42555. viewport->setViewPosition (x, y);
  42556. }
  42557. }
  42558. void TextEditor::moveCursorTo (const int newPosition,
  42559. const bool isSelecting)
  42560. {
  42561. if (isSelecting)
  42562. {
  42563. moveCaret (newPosition);
  42564. const Range<int> oldSelection (selection);
  42565. if (dragType == notDragging)
  42566. {
  42567. if (abs (getCaretPosition() - selection.getStart()) < abs (getCaretPosition() - selection.getEnd()))
  42568. dragType = draggingSelectionStart;
  42569. else
  42570. dragType = draggingSelectionEnd;
  42571. }
  42572. if (dragType == draggingSelectionStart)
  42573. {
  42574. if (getCaretPosition() >= selection.getEnd())
  42575. dragType = draggingSelectionEnd;
  42576. selection = Range<int>::between (getCaretPosition(), selection.getEnd());
  42577. }
  42578. else
  42579. {
  42580. if (getCaretPosition() < selection.getStart())
  42581. dragType = draggingSelectionStart;
  42582. selection = Range<int>::between (getCaretPosition(), selection.getStart());
  42583. }
  42584. repaintText (selection.getUnionWith (oldSelection));
  42585. }
  42586. else
  42587. {
  42588. dragType = notDragging;
  42589. repaintText (selection);
  42590. moveCaret (newPosition);
  42591. selection = Range<int>::emptyRange (getCaretPosition());
  42592. }
  42593. }
  42594. int TextEditor::getTextIndexAt (const int x,
  42595. const int y)
  42596. {
  42597. return indexAtPosition ((float) (x + viewport->getViewPositionX() - leftIndent),
  42598. (float) (y + viewport->getViewPositionY() - topIndent));
  42599. }
  42600. void TextEditor::insertTextAtCaret (const String& newText_)
  42601. {
  42602. String newText (newText_);
  42603. if (allowedCharacters.isNotEmpty())
  42604. newText = newText.retainCharacters (allowedCharacters);
  42605. if ((! returnKeyStartsNewLine) && newText == "\n")
  42606. {
  42607. returnPressed();
  42608. return;
  42609. }
  42610. if (! isMultiLine())
  42611. newText = newText.replaceCharacters ("\r\n", " ");
  42612. else
  42613. newText = newText.replace ("\r\n", "\n");
  42614. const int newCaretPos = selection.getStart() + newText.length();
  42615. const int insertIndex = selection.getStart();
  42616. remove (selection, getUndoManager(),
  42617. newText.isNotEmpty() ? newCaretPos - 1 : newCaretPos);
  42618. if (maxTextLength > 0)
  42619. newText = newText.substring (0, maxTextLength - getTotalNumChars());
  42620. if (newText.isNotEmpty())
  42621. insert (newText,
  42622. insertIndex,
  42623. currentFont,
  42624. findColour (textColourId),
  42625. getUndoManager(),
  42626. newCaretPos);
  42627. textChanged();
  42628. }
  42629. void TextEditor::setHighlightedRegion (const Range<int>& newSelection)
  42630. {
  42631. moveCursorTo (newSelection.getStart(), false);
  42632. moveCursorTo (newSelection.getEnd(), true);
  42633. }
  42634. void TextEditor::copy()
  42635. {
  42636. if (passwordCharacter == 0)
  42637. {
  42638. const String selectedText (getHighlightedText());
  42639. if (selectedText.isNotEmpty())
  42640. SystemClipboard::copyTextToClipboard (selectedText);
  42641. }
  42642. }
  42643. void TextEditor::paste()
  42644. {
  42645. if (! isReadOnly())
  42646. {
  42647. const String clip (SystemClipboard::getTextFromClipboard());
  42648. if (clip.isNotEmpty())
  42649. insertTextAtCaret (clip);
  42650. }
  42651. }
  42652. void TextEditor::cut()
  42653. {
  42654. if (! isReadOnly())
  42655. {
  42656. moveCaret (selection.getEnd());
  42657. insertTextAtCaret (String::empty);
  42658. }
  42659. }
  42660. void TextEditor::drawContent (Graphics& g)
  42661. {
  42662. const float wordWrapWidth = getWordWrapWidth();
  42663. if (wordWrapWidth > 0)
  42664. {
  42665. g.setOrigin (leftIndent, topIndent);
  42666. const Rectangle<int> clip (g.getClipBounds());
  42667. Colour selectedTextColour;
  42668. Iterator i (sections, wordWrapWidth, passwordCharacter);
  42669. while (i.lineY + 200.0 < clip.getY() && i.next())
  42670. {}
  42671. if (! selection.isEmpty())
  42672. {
  42673. g.setColour (findColour (highlightColourId)
  42674. .withMultipliedAlpha (hasKeyboardFocus (true) ? 1.0f : 0.5f));
  42675. selectedTextColour = findColour (highlightedTextColourId);
  42676. Iterator i2 (i);
  42677. while (i2.next() && i2.lineY < clip.getBottom())
  42678. {
  42679. if (i2.lineY + i2.lineHeight >= clip.getY()
  42680. && selection.intersects (Range<int> (i2.indexInText, i2.indexInText + i2.atom->numChars)))
  42681. {
  42682. i2.drawSelection (g, selection);
  42683. }
  42684. }
  42685. }
  42686. const UniformTextSection* lastSection = 0;
  42687. while (i.next() && i.lineY < clip.getBottom())
  42688. {
  42689. if (i.lineY + i.lineHeight >= clip.getY())
  42690. {
  42691. if (selection.intersects (Range<int> (i.indexInText, i.indexInText + i.atom->numChars)))
  42692. {
  42693. i.drawSelectedText (g, selection, selectedTextColour);
  42694. lastSection = 0;
  42695. }
  42696. else
  42697. {
  42698. i.draw (g, lastSection);
  42699. }
  42700. }
  42701. }
  42702. }
  42703. }
  42704. void TextEditor::paint (Graphics& g)
  42705. {
  42706. getLookAndFeel().fillTextEditorBackground (g, getWidth(), getHeight(), *this);
  42707. }
  42708. void TextEditor::paintOverChildren (Graphics& g)
  42709. {
  42710. if (caretFlashState
  42711. && hasKeyboardFocus (false)
  42712. && caretVisible
  42713. && ! isReadOnly())
  42714. {
  42715. g.setColour (findColour (caretColourId));
  42716. g.fillRect (borderSize.getLeft() + textHolder->getX() + leftIndent + cursorX,
  42717. borderSize.getTop() + textHolder->getY() + topIndent + cursorY,
  42718. 2.0f, cursorHeight);
  42719. }
  42720. if (textToShowWhenEmpty.isNotEmpty()
  42721. && (! hasKeyboardFocus (false))
  42722. && getTotalNumChars() == 0)
  42723. {
  42724. g.setColour (colourForTextWhenEmpty);
  42725. g.setFont (getFont());
  42726. if (isMultiLine())
  42727. {
  42728. g.drawText (textToShowWhenEmpty,
  42729. 0, 0, getWidth(), getHeight(),
  42730. Justification::centred, true);
  42731. }
  42732. else
  42733. {
  42734. g.drawText (textToShowWhenEmpty,
  42735. leftIndent, topIndent,
  42736. viewport->getWidth() - leftIndent,
  42737. viewport->getHeight() - topIndent,
  42738. Justification::centredLeft, true);
  42739. }
  42740. }
  42741. getLookAndFeel().drawTextEditorOutline (g, getWidth(), getHeight(), *this);
  42742. }
  42743. class TextEditorMenuPerformer : public ModalComponentManager::Callback
  42744. {
  42745. public:
  42746. TextEditorMenuPerformer (TextEditor* const editor_)
  42747. : editor (editor_)
  42748. {
  42749. }
  42750. void modalStateFinished (int returnValue)
  42751. {
  42752. if (editor != 0 && returnValue != 0)
  42753. editor->performPopupMenuAction (returnValue);
  42754. }
  42755. private:
  42756. Component::SafePointer<TextEditor> editor;
  42757. TextEditorMenuPerformer (const TextEditorMenuPerformer&);
  42758. TextEditorMenuPerformer& operator= (const TextEditorMenuPerformer&);
  42759. };
  42760. void TextEditor::mouseDown (const MouseEvent& e)
  42761. {
  42762. beginDragAutoRepeat (100);
  42763. newTransaction();
  42764. if (wasFocused || ! selectAllTextWhenFocused)
  42765. {
  42766. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  42767. {
  42768. moveCursorTo (getTextIndexAt (e.x, e.y),
  42769. e.mods.isShiftDown());
  42770. }
  42771. else
  42772. {
  42773. PopupMenu m;
  42774. m.setLookAndFeel (&getLookAndFeel());
  42775. addPopupMenuItems (m, &e);
  42776. m.show (0, 0, 0, 0, new TextEditorMenuPerformer (this));
  42777. }
  42778. }
  42779. }
  42780. void TextEditor::mouseDrag (const MouseEvent& e)
  42781. {
  42782. if (wasFocused || ! selectAllTextWhenFocused)
  42783. {
  42784. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  42785. {
  42786. moveCursorTo (getTextIndexAt (e.x, e.y), true);
  42787. }
  42788. }
  42789. }
  42790. void TextEditor::mouseUp (const MouseEvent& e)
  42791. {
  42792. newTransaction();
  42793. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42794. if (wasFocused || ! selectAllTextWhenFocused)
  42795. {
  42796. if (e.mouseWasClicked() && ! (popupMenuEnabled && e.mods.isPopupMenu()))
  42797. {
  42798. moveCaret (getTextIndexAt (e.x, e.y));
  42799. }
  42800. }
  42801. wasFocused = true;
  42802. }
  42803. void TextEditor::mouseDoubleClick (const MouseEvent& e)
  42804. {
  42805. int tokenEnd = getTextIndexAt (e.x, e.y);
  42806. int tokenStart = tokenEnd;
  42807. if (e.getNumberOfClicks() > 3)
  42808. {
  42809. tokenStart = 0;
  42810. tokenEnd = getTotalNumChars();
  42811. }
  42812. else
  42813. {
  42814. const String t (getText());
  42815. const int totalLength = getTotalNumChars();
  42816. while (tokenEnd < totalLength)
  42817. {
  42818. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  42819. if (CharacterFunctions::isLetterOrDigit (t [tokenEnd]) || t [tokenEnd] > 128)
  42820. ++tokenEnd;
  42821. else
  42822. break;
  42823. }
  42824. tokenStart = tokenEnd;
  42825. while (tokenStart > 0)
  42826. {
  42827. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  42828. if (CharacterFunctions::isLetterOrDigit (t [tokenStart - 1]) || t [tokenStart - 1] > 128)
  42829. --tokenStart;
  42830. else
  42831. break;
  42832. }
  42833. if (e.getNumberOfClicks() > 2)
  42834. {
  42835. while (tokenEnd < totalLength)
  42836. {
  42837. if (t [tokenEnd] != '\r' && t [tokenEnd] != '\n')
  42838. ++tokenEnd;
  42839. else
  42840. break;
  42841. }
  42842. while (tokenStart > 0)
  42843. {
  42844. if (t [tokenStart - 1] != '\r' && t [tokenStart - 1] != '\n')
  42845. --tokenStart;
  42846. else
  42847. break;
  42848. }
  42849. }
  42850. }
  42851. moveCursorTo (tokenEnd, false);
  42852. moveCursorTo (tokenStart, true);
  42853. }
  42854. void TextEditor::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  42855. {
  42856. if (! viewport->useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  42857. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  42858. }
  42859. bool TextEditor::keyPressed (const KeyPress& key)
  42860. {
  42861. if (isReadOnly() && key != KeyPress ('c', ModifierKeys::commandModifier, 0))
  42862. return false;
  42863. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  42864. if (key.isKeyCode (KeyPress::leftKey)
  42865. || key.isKeyCode (KeyPress::upKey))
  42866. {
  42867. newTransaction();
  42868. int newPos;
  42869. if (isMultiLine() && key.isKeyCode (KeyPress::upKey))
  42870. newPos = indexAtPosition (cursorX, cursorY - 1);
  42871. else if (moveInWholeWordSteps)
  42872. newPos = findWordBreakBefore (getCaretPosition());
  42873. else
  42874. newPos = getCaretPosition() - 1;
  42875. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  42876. }
  42877. else if (key.isKeyCode (KeyPress::rightKey)
  42878. || key.isKeyCode (KeyPress::downKey))
  42879. {
  42880. newTransaction();
  42881. int newPos;
  42882. if (isMultiLine() && key.isKeyCode (KeyPress::downKey))
  42883. newPos = indexAtPosition (cursorX, cursorY + cursorHeight + 1);
  42884. else if (moveInWholeWordSteps)
  42885. newPos = findWordBreakAfter (getCaretPosition());
  42886. else
  42887. newPos = getCaretPosition() + 1;
  42888. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  42889. }
  42890. else if (key.isKeyCode (KeyPress::pageDownKey) && isMultiLine())
  42891. {
  42892. newTransaction();
  42893. moveCursorTo (indexAtPosition (cursorX, cursorY + cursorHeight + viewport->getViewHeight()),
  42894. key.getModifiers().isShiftDown());
  42895. }
  42896. else if (key.isKeyCode (KeyPress::pageUpKey) && isMultiLine())
  42897. {
  42898. newTransaction();
  42899. moveCursorTo (indexAtPosition (cursorX, cursorY - viewport->getViewHeight()),
  42900. key.getModifiers().isShiftDown());
  42901. }
  42902. else if (key.isKeyCode (KeyPress::homeKey))
  42903. {
  42904. newTransaction();
  42905. if (isMultiLine() && ! moveInWholeWordSteps)
  42906. moveCursorTo (indexAtPosition (0.0f, cursorY),
  42907. key.getModifiers().isShiftDown());
  42908. else
  42909. moveCursorTo (0, key.getModifiers().isShiftDown());
  42910. }
  42911. else if (key.isKeyCode (KeyPress::endKey))
  42912. {
  42913. newTransaction();
  42914. if (isMultiLine() && ! moveInWholeWordSteps)
  42915. moveCursorTo (indexAtPosition ((float) textHolder->getWidth(), cursorY),
  42916. key.getModifiers().isShiftDown());
  42917. else
  42918. moveCursorTo (getTotalNumChars(), key.getModifiers().isShiftDown());
  42919. }
  42920. else if (key.isKeyCode (KeyPress::backspaceKey))
  42921. {
  42922. if (moveInWholeWordSteps)
  42923. {
  42924. moveCursorTo (findWordBreakBefore (getCaretPosition()), true);
  42925. }
  42926. else
  42927. {
  42928. if (selection.isEmpty() && selection.getStart() > 0)
  42929. selection.setStart (selection.getEnd() - 1);
  42930. }
  42931. cut();
  42932. }
  42933. else if (key.isKeyCode (KeyPress::deleteKey))
  42934. {
  42935. if (key.getModifiers().isShiftDown())
  42936. copy();
  42937. if (selection.isEmpty() && selection.getStart() < getTotalNumChars())
  42938. selection.setEnd (selection.getStart() + 1);
  42939. cut();
  42940. }
  42941. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0)
  42942. || key == KeyPress (KeyPress::insertKey, ModifierKeys::ctrlModifier, 0))
  42943. {
  42944. newTransaction();
  42945. copy();
  42946. }
  42947. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  42948. {
  42949. newTransaction();
  42950. copy();
  42951. cut();
  42952. }
  42953. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0)
  42954. || key == KeyPress (KeyPress::insertKey, ModifierKeys::shiftModifier, 0))
  42955. {
  42956. newTransaction();
  42957. paste();
  42958. }
  42959. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  42960. {
  42961. newTransaction();
  42962. doUndoRedo (false);
  42963. }
  42964. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0))
  42965. {
  42966. newTransaction();
  42967. doUndoRedo (true);
  42968. }
  42969. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  42970. {
  42971. newTransaction();
  42972. moveCursorTo (getTotalNumChars(), false);
  42973. moveCursorTo (0, true);
  42974. }
  42975. else if (key == KeyPress::returnKey)
  42976. {
  42977. newTransaction();
  42978. insertTextAtCaret ("\n");
  42979. }
  42980. else if (key.isKeyCode (KeyPress::escapeKey))
  42981. {
  42982. newTransaction();
  42983. moveCursorTo (getCaretPosition(), false);
  42984. escapePressed();
  42985. }
  42986. else if (key.getTextCharacter() >= ' '
  42987. || (tabKeyUsed && (key.getTextCharacter() == '\t')))
  42988. {
  42989. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  42990. lastTransactionTime = Time::getApproximateMillisecondCounter();
  42991. }
  42992. else
  42993. {
  42994. return false;
  42995. }
  42996. return true;
  42997. }
  42998. bool TextEditor::keyStateChanged (const bool isKeyDown)
  42999. {
  43000. if (! isKeyDown)
  43001. return false;
  43002. #if JUCE_WINDOWS
  43003. if (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0).isCurrentlyDown())
  43004. return false; // We need to explicitly allow alt-F4 to pass through on Windows
  43005. #endif
  43006. // (overridden to avoid forwarding key events to the parent)
  43007. return ! ModifierKeys::getCurrentModifiers().isCommandDown();
  43008. }
  43009. const int baseMenuItemID = 0x7fff0000;
  43010. void TextEditor::addPopupMenuItems (PopupMenu& m, const MouseEvent*)
  43011. {
  43012. const bool writable = ! isReadOnly();
  43013. if (passwordCharacter == 0)
  43014. {
  43015. m.addItem (baseMenuItemID + 1, TRANS("cut"), writable);
  43016. m.addItem (baseMenuItemID + 2, TRANS("copy"), ! selection.isEmpty());
  43017. m.addItem (baseMenuItemID + 3, TRANS("paste"), writable);
  43018. }
  43019. m.addItem (baseMenuItemID + 4, TRANS("delete"), writable);
  43020. m.addSeparator();
  43021. m.addItem (baseMenuItemID + 5, TRANS("select all"));
  43022. m.addSeparator();
  43023. if (getUndoManager() != 0)
  43024. {
  43025. m.addItem (baseMenuItemID + 6, TRANS("undo"), undoManager.canUndo());
  43026. m.addItem (baseMenuItemID + 7, TRANS("redo"), undoManager.canRedo());
  43027. }
  43028. }
  43029. void TextEditor::performPopupMenuAction (const int menuItemID)
  43030. {
  43031. switch (menuItemID)
  43032. {
  43033. case baseMenuItemID + 1:
  43034. copy();
  43035. cut();
  43036. break;
  43037. case baseMenuItemID + 2:
  43038. copy();
  43039. break;
  43040. case baseMenuItemID + 3:
  43041. paste();
  43042. break;
  43043. case baseMenuItemID + 4:
  43044. cut();
  43045. break;
  43046. case baseMenuItemID + 5:
  43047. moveCursorTo (getTotalNumChars(), false);
  43048. moveCursorTo (0, true);
  43049. break;
  43050. case baseMenuItemID + 6:
  43051. doUndoRedo (false);
  43052. break;
  43053. case baseMenuItemID + 7:
  43054. doUndoRedo (true);
  43055. break;
  43056. default:
  43057. break;
  43058. }
  43059. }
  43060. void TextEditor::focusGained (FocusChangeType)
  43061. {
  43062. newTransaction();
  43063. caretFlashState = true;
  43064. if (selectAllTextWhenFocused)
  43065. {
  43066. moveCursorTo (0, false);
  43067. moveCursorTo (getTotalNumChars(), true);
  43068. }
  43069. repaint();
  43070. if (caretVisible)
  43071. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43072. ComponentPeer* const peer = getPeer();
  43073. if (peer != 0 && ! isReadOnly())
  43074. peer->textInputRequired (getScreenPosition() - peer->getScreenPosition());
  43075. }
  43076. void TextEditor::focusLost (FocusChangeType)
  43077. {
  43078. newTransaction();
  43079. wasFocused = false;
  43080. textHolder->stopTimer();
  43081. caretFlashState = false;
  43082. postCommandMessage (TextEditorDefs::focusLossMessageId);
  43083. repaint();
  43084. }
  43085. void TextEditor::resized()
  43086. {
  43087. viewport->setBoundsInset (borderSize);
  43088. viewport->setSingleStepSizes (16, roundToInt (currentFont.getHeight()));
  43089. updateTextHolderSize();
  43090. if (! isMultiLine())
  43091. {
  43092. scrollToMakeSureCursorIsVisible();
  43093. }
  43094. else
  43095. {
  43096. updateCaretPosition();
  43097. }
  43098. }
  43099. void TextEditor::handleCommandMessage (const int commandId)
  43100. {
  43101. Component::BailOutChecker checker (this);
  43102. switch (commandId)
  43103. {
  43104. case TextEditorDefs::textChangeMessageId:
  43105. listeners.callChecked (checker, &TextEditorListener::textEditorTextChanged, (TextEditor&) *this);
  43106. break;
  43107. case TextEditorDefs::returnKeyMessageId:
  43108. listeners.callChecked (checker, &TextEditorListener::textEditorReturnKeyPressed, (TextEditor&) *this);
  43109. break;
  43110. case TextEditorDefs::escapeKeyMessageId:
  43111. listeners.callChecked (checker, &TextEditorListener::textEditorEscapeKeyPressed, (TextEditor&) *this);
  43112. break;
  43113. case TextEditorDefs::focusLossMessageId:
  43114. listeners.callChecked (checker, &TextEditorListener::textEditorFocusLost, (TextEditor&) *this);
  43115. break;
  43116. default:
  43117. jassertfalse;
  43118. break;
  43119. }
  43120. }
  43121. void TextEditor::enablementChanged()
  43122. {
  43123. setMouseCursor (isReadOnly() ? MouseCursor::NormalCursor
  43124. : MouseCursor::IBeamCursor);
  43125. repaint();
  43126. }
  43127. UndoManager* TextEditor::getUndoManager() throw()
  43128. {
  43129. return isReadOnly() ? 0 : &undoManager;
  43130. }
  43131. void TextEditor::clearInternal (UndoManager* const um)
  43132. {
  43133. remove (Range<int> (0, getTotalNumChars()), um, caretPosition);
  43134. }
  43135. void TextEditor::insert (const String& text,
  43136. const int insertIndex,
  43137. const Font& font,
  43138. const Colour& colour,
  43139. UndoManager* const um,
  43140. const int caretPositionToMoveTo)
  43141. {
  43142. if (text.isNotEmpty())
  43143. {
  43144. if (um != 0)
  43145. {
  43146. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  43147. newTransaction();
  43148. um->perform (new InsertAction (*this, text, insertIndex, font, colour,
  43149. caretPosition, caretPositionToMoveTo));
  43150. }
  43151. else
  43152. {
  43153. repaintText (Range<int> (insertIndex, getTotalNumChars())); // must do this before and after changing the data, in case
  43154. // a line gets moved due to word wrap
  43155. int index = 0;
  43156. int nextIndex = 0;
  43157. for (int i = 0; i < sections.size(); ++i)
  43158. {
  43159. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  43160. if (insertIndex == index)
  43161. {
  43162. sections.insert (i, new UniformTextSection (text,
  43163. font, colour,
  43164. passwordCharacter));
  43165. break;
  43166. }
  43167. else if (insertIndex > index && insertIndex < nextIndex)
  43168. {
  43169. splitSection (i, insertIndex - index);
  43170. sections.insert (i + 1, new UniformTextSection (text,
  43171. font, colour,
  43172. passwordCharacter));
  43173. break;
  43174. }
  43175. index = nextIndex;
  43176. }
  43177. if (nextIndex == insertIndex)
  43178. sections.add (new UniformTextSection (text,
  43179. font, colour,
  43180. passwordCharacter));
  43181. coalesceSimilarSections();
  43182. totalNumChars = -1;
  43183. valueTextNeedsUpdating = true;
  43184. moveCursorTo (caretPositionToMoveTo, false);
  43185. repaintText (Range<int> (insertIndex, getTotalNumChars()));
  43186. }
  43187. }
  43188. }
  43189. void TextEditor::reinsert (const int insertIndex,
  43190. const Array <UniformTextSection*>& sectionsToInsert)
  43191. {
  43192. int index = 0;
  43193. int nextIndex = 0;
  43194. for (int i = 0; i < sections.size(); ++i)
  43195. {
  43196. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  43197. if (insertIndex == index)
  43198. {
  43199. for (int j = sectionsToInsert.size(); --j >= 0;)
  43200. sections.insert (i, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43201. break;
  43202. }
  43203. else if (insertIndex > index && insertIndex < nextIndex)
  43204. {
  43205. splitSection (i, insertIndex - index);
  43206. for (int j = sectionsToInsert.size(); --j >= 0;)
  43207. sections.insert (i + 1, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43208. break;
  43209. }
  43210. index = nextIndex;
  43211. }
  43212. if (nextIndex == insertIndex)
  43213. {
  43214. for (int j = 0; j < sectionsToInsert.size(); ++j)
  43215. sections.add (new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43216. }
  43217. coalesceSimilarSections();
  43218. totalNumChars = -1;
  43219. valueTextNeedsUpdating = true;
  43220. }
  43221. void TextEditor::remove (const Range<int>& range,
  43222. UndoManager* const um,
  43223. const int caretPositionToMoveTo)
  43224. {
  43225. if (! range.isEmpty())
  43226. {
  43227. int index = 0;
  43228. for (int i = 0; i < sections.size(); ++i)
  43229. {
  43230. const int nextIndex = index + sections.getUnchecked(i)->getTotalLength();
  43231. if (range.getStart() > index && range.getStart() < nextIndex)
  43232. {
  43233. splitSection (i, range.getStart() - index);
  43234. --i;
  43235. }
  43236. else if (range.getEnd() > index && range.getEnd() < nextIndex)
  43237. {
  43238. splitSection (i, range.getEnd() - index);
  43239. --i;
  43240. }
  43241. else
  43242. {
  43243. index = nextIndex;
  43244. if (index > range.getEnd())
  43245. break;
  43246. }
  43247. }
  43248. index = 0;
  43249. if (um != 0)
  43250. {
  43251. Array <UniformTextSection*> removedSections;
  43252. for (int i = 0; i < sections.size(); ++i)
  43253. {
  43254. if (range.getEnd() <= range.getStart())
  43255. break;
  43256. UniformTextSection* const section = sections.getUnchecked (i);
  43257. const int nextIndex = index + section->getTotalLength();
  43258. if (range.getStart() <= index && range.getEnd() >= nextIndex)
  43259. removedSections.add (new UniformTextSection (*section));
  43260. index = nextIndex;
  43261. }
  43262. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  43263. newTransaction();
  43264. um->perform (new RemoveAction (*this, range, caretPosition,
  43265. caretPositionToMoveTo, removedSections));
  43266. }
  43267. else
  43268. {
  43269. Range<int> remainingRange (range);
  43270. for (int i = 0; i < sections.size(); ++i)
  43271. {
  43272. UniformTextSection* const section = sections.getUnchecked (i);
  43273. const int nextIndex = index + section->getTotalLength();
  43274. if (remainingRange.getStart() <= index && remainingRange.getEnd() >= nextIndex)
  43275. {
  43276. sections.remove(i);
  43277. section->clear();
  43278. delete section;
  43279. remainingRange.setEnd (remainingRange.getEnd() - (nextIndex - index));
  43280. if (remainingRange.isEmpty())
  43281. break;
  43282. --i;
  43283. }
  43284. else
  43285. {
  43286. index = nextIndex;
  43287. }
  43288. }
  43289. coalesceSimilarSections();
  43290. totalNumChars = -1;
  43291. valueTextNeedsUpdating = true;
  43292. moveCursorTo (caretPositionToMoveTo, false);
  43293. repaintText (Range<int> (range.getStart(), getTotalNumChars()));
  43294. }
  43295. }
  43296. }
  43297. const String TextEditor::getText() const
  43298. {
  43299. String t;
  43300. t.preallocateStorage (getTotalNumChars());
  43301. String::Concatenator concatenator (t);
  43302. for (int i = 0; i < sections.size(); ++i)
  43303. sections.getUnchecked (i)->appendAllText (concatenator);
  43304. return t;
  43305. }
  43306. const String TextEditor::getTextInRange (const Range<int>& range) const
  43307. {
  43308. String t;
  43309. if (! range.isEmpty())
  43310. {
  43311. t.preallocateStorage (jmin (getTotalNumChars(), range.getLength()));
  43312. String::Concatenator concatenator (t);
  43313. int index = 0;
  43314. for (int i = 0; i < sections.size(); ++i)
  43315. {
  43316. const UniformTextSection* const s = sections.getUnchecked (i);
  43317. const int nextIndex = index + s->getTotalLength();
  43318. if (range.getStart() < nextIndex)
  43319. {
  43320. if (range.getEnd() <= index)
  43321. break;
  43322. s->appendSubstring (concatenator, range - index);
  43323. }
  43324. index = nextIndex;
  43325. }
  43326. }
  43327. return t;
  43328. }
  43329. const String TextEditor::getHighlightedText() const
  43330. {
  43331. return getTextInRange (selection);
  43332. }
  43333. int TextEditor::getTotalNumChars() const
  43334. {
  43335. if (totalNumChars < 0)
  43336. {
  43337. totalNumChars = 0;
  43338. for (int i = sections.size(); --i >= 0;)
  43339. totalNumChars += sections.getUnchecked (i)->getTotalLength();
  43340. }
  43341. return totalNumChars;
  43342. }
  43343. bool TextEditor::isEmpty() const
  43344. {
  43345. return getTotalNumChars() == 0;
  43346. }
  43347. void TextEditor::getCharPosition (const int index, float& cx, float& cy, float& lineHeight) const
  43348. {
  43349. const float wordWrapWidth = getWordWrapWidth();
  43350. if (wordWrapWidth > 0 && sections.size() > 0)
  43351. {
  43352. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43353. i.getCharPosition (index, cx, cy, lineHeight);
  43354. }
  43355. else
  43356. {
  43357. cx = cy = 0;
  43358. lineHeight = currentFont.getHeight();
  43359. }
  43360. }
  43361. int TextEditor::indexAtPosition (const float x, const float y)
  43362. {
  43363. const float wordWrapWidth = getWordWrapWidth();
  43364. if (wordWrapWidth > 0)
  43365. {
  43366. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43367. while (i.next())
  43368. {
  43369. if (i.lineY + i.lineHeight > y)
  43370. {
  43371. if (i.lineY > y)
  43372. return jmax (0, i.indexInText - 1);
  43373. if (i.atomX >= x)
  43374. return i.indexInText;
  43375. if (x < i.atomRight)
  43376. return i.xToIndex (x);
  43377. }
  43378. }
  43379. }
  43380. return getTotalNumChars();
  43381. }
  43382. static int getCharacterCategory (const juce_wchar character)
  43383. {
  43384. return CharacterFunctions::isLetterOrDigit (character)
  43385. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  43386. }
  43387. int TextEditor::findWordBreakAfter (const int position) const
  43388. {
  43389. const String t (getTextInRange (Range<int> (position, position + 512)));
  43390. const int totalLength = t.length();
  43391. int i = 0;
  43392. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  43393. ++i;
  43394. const int type = getCharacterCategory (t[i]);
  43395. while (i < totalLength && type == getCharacterCategory (t[i]))
  43396. ++i;
  43397. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  43398. ++i;
  43399. return position + i;
  43400. }
  43401. int TextEditor::findWordBreakBefore (const int position) const
  43402. {
  43403. if (position <= 0)
  43404. return 0;
  43405. const int startOfBuffer = jmax (0, position - 512);
  43406. const String t (getTextInRange (Range<int> (startOfBuffer, position)));
  43407. int i = position - startOfBuffer;
  43408. while (i > 0 && CharacterFunctions::isWhitespace (t [i - 1]))
  43409. --i;
  43410. if (i > 0)
  43411. {
  43412. const int type = getCharacterCategory (t [i - 1]);
  43413. while (i > 0 && type == getCharacterCategory (t [i - 1]))
  43414. --i;
  43415. }
  43416. jassert (startOfBuffer + i >= 0);
  43417. return startOfBuffer + i;
  43418. }
  43419. void TextEditor::splitSection (const int sectionIndex,
  43420. const int charToSplitAt)
  43421. {
  43422. jassert (sections[sectionIndex] != 0);
  43423. sections.insert (sectionIndex + 1,
  43424. sections.getUnchecked (sectionIndex)->split (charToSplitAt, passwordCharacter));
  43425. }
  43426. void TextEditor::coalesceSimilarSections()
  43427. {
  43428. for (int i = 0; i < sections.size() - 1; ++i)
  43429. {
  43430. UniformTextSection* const s1 = sections.getUnchecked (i);
  43431. UniformTextSection* const s2 = sections.getUnchecked (i + 1);
  43432. if (s1->font == s2->font
  43433. && s1->colour == s2->colour)
  43434. {
  43435. s1->append (*s2, passwordCharacter);
  43436. sections.remove (i + 1);
  43437. delete s2;
  43438. --i;
  43439. }
  43440. }
  43441. }
  43442. END_JUCE_NAMESPACE
  43443. /*** End of inlined file: juce_TextEditor.cpp ***/
  43444. /*** Start of inlined file: juce_Toolbar.cpp ***/
  43445. BEGIN_JUCE_NAMESPACE
  43446. const char* const Toolbar::toolbarDragDescriptor = "_toolbarItem_";
  43447. class ToolbarSpacerComp : public ToolbarItemComponent
  43448. {
  43449. public:
  43450. ToolbarSpacerComp (const int itemId_, const float fixedSize_, const bool drawBar_)
  43451. : ToolbarItemComponent (itemId_, String::empty, false),
  43452. fixedSize (fixedSize_),
  43453. drawBar (drawBar_)
  43454. {
  43455. }
  43456. ~ToolbarSpacerComp()
  43457. {
  43458. }
  43459. bool getToolbarItemSizes (int toolbarThickness, bool /*isToolbarVertical*/,
  43460. int& preferredSize, int& minSize, int& maxSize)
  43461. {
  43462. if (fixedSize <= 0)
  43463. {
  43464. preferredSize = toolbarThickness * 2;
  43465. minSize = 4;
  43466. maxSize = 32768;
  43467. }
  43468. else
  43469. {
  43470. maxSize = roundToInt (toolbarThickness * fixedSize);
  43471. minSize = drawBar ? maxSize : jmin (4, maxSize);
  43472. preferredSize = maxSize;
  43473. if (getEditingMode() == editableOnPalette)
  43474. preferredSize = maxSize = toolbarThickness / (drawBar ? 3 : 2);
  43475. }
  43476. return true;
  43477. }
  43478. void paintButtonArea (Graphics&, int, int, bool, bool)
  43479. {
  43480. }
  43481. void contentAreaChanged (const Rectangle<int>&)
  43482. {
  43483. }
  43484. int getResizeOrder() const throw()
  43485. {
  43486. return fixedSize <= 0 ? 0 : 1;
  43487. }
  43488. void paint (Graphics& g)
  43489. {
  43490. const int w = getWidth();
  43491. const int h = getHeight();
  43492. if (drawBar)
  43493. {
  43494. g.setColour (findColour (Toolbar::separatorColourId, true));
  43495. const float thickness = 0.2f;
  43496. if (isToolbarVertical())
  43497. g.fillRect (w * 0.1f, h * (0.5f - thickness * 0.5f), w * 0.8f, h * thickness);
  43498. else
  43499. g.fillRect (w * (0.5f - thickness * 0.5f), h * 0.1f, w * thickness, h * 0.8f);
  43500. }
  43501. if (getEditingMode() != normalMode && ! drawBar)
  43502. {
  43503. g.setColour (findColour (Toolbar::separatorColourId, true));
  43504. const int indentX = jmin (2, (w - 3) / 2);
  43505. const int indentY = jmin (2, (h - 3) / 2);
  43506. g.drawRect (indentX, indentY, w - indentX * 2, h - indentY * 2, 1);
  43507. if (fixedSize <= 0)
  43508. {
  43509. float x1, y1, x2, y2, x3, y3, x4, y4, hw, hl;
  43510. if (isToolbarVertical())
  43511. {
  43512. x1 = w * 0.5f;
  43513. y1 = h * 0.4f;
  43514. x2 = x1;
  43515. y2 = indentX * 2.0f;
  43516. x3 = x1;
  43517. y3 = h * 0.6f;
  43518. x4 = x1;
  43519. y4 = h - y2;
  43520. hw = w * 0.15f;
  43521. hl = w * 0.2f;
  43522. }
  43523. else
  43524. {
  43525. x1 = w * 0.4f;
  43526. y1 = h * 0.5f;
  43527. x2 = indentX * 2.0f;
  43528. y2 = y1;
  43529. x3 = w * 0.6f;
  43530. y3 = y1;
  43531. x4 = w - x2;
  43532. y4 = y1;
  43533. hw = h * 0.15f;
  43534. hl = h * 0.2f;
  43535. }
  43536. Path p;
  43537. p.addArrow (Line<float> (x1, y1, x2, y2), 1.5f, hw, hl);
  43538. p.addArrow (Line<float> (x3, y3, x4, y4), 1.5f, hw, hl);
  43539. g.fillPath (p);
  43540. }
  43541. }
  43542. }
  43543. juce_UseDebuggingNewOperator
  43544. private:
  43545. const float fixedSize;
  43546. const bool drawBar;
  43547. ToolbarSpacerComp (const ToolbarSpacerComp&);
  43548. ToolbarSpacerComp& operator= (const ToolbarSpacerComp&);
  43549. };
  43550. class MissingItemsComponent : public PopupMenuCustomComponent
  43551. {
  43552. public:
  43553. MissingItemsComponent (Toolbar& owner_, const int height_)
  43554. : PopupMenuCustomComponent (true),
  43555. owner (owner_),
  43556. height (height_)
  43557. {
  43558. for (int i = owner_.items.size(); --i >= 0;)
  43559. {
  43560. ToolbarItemComponent* const tc = owner_.items.getUnchecked(i);
  43561. if (dynamic_cast <ToolbarSpacerComp*> (tc) == 0 && ! tc->isVisible())
  43562. {
  43563. oldIndexes.insert (0, i);
  43564. addAndMakeVisible (tc, 0);
  43565. }
  43566. }
  43567. layout (400);
  43568. }
  43569. ~MissingItemsComponent()
  43570. {
  43571. // deleting the toolbar while its menu it open??
  43572. jassert (owner.isValidComponent());
  43573. for (int i = 0; i < getNumChildComponents(); ++i)
  43574. {
  43575. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  43576. if (tc != 0)
  43577. {
  43578. tc->setVisible (false);
  43579. const int index = oldIndexes.remove (i);
  43580. owner.addChildComponent (tc, index);
  43581. --i;
  43582. }
  43583. }
  43584. owner.resized();
  43585. }
  43586. void layout (const int preferredWidth)
  43587. {
  43588. const int indent = 8;
  43589. int x = indent;
  43590. int y = indent;
  43591. int maxX = 0;
  43592. for (int i = 0; i < getNumChildComponents(); ++i)
  43593. {
  43594. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  43595. if (tc != 0)
  43596. {
  43597. int preferredSize = 1, minSize = 1, maxSize = 1;
  43598. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  43599. {
  43600. if (x + preferredSize > preferredWidth && x > indent)
  43601. {
  43602. x = indent;
  43603. y += height;
  43604. }
  43605. tc->setBounds (x, y, preferredSize, height);
  43606. x += preferredSize;
  43607. maxX = jmax (maxX, x);
  43608. }
  43609. }
  43610. }
  43611. setSize (maxX + 8, y + height + 8);
  43612. }
  43613. void getIdealSize (int& idealWidth, int& idealHeight)
  43614. {
  43615. idealWidth = getWidth();
  43616. idealHeight = getHeight();
  43617. }
  43618. juce_UseDebuggingNewOperator
  43619. private:
  43620. Toolbar& owner;
  43621. const int height;
  43622. Array <int> oldIndexes;
  43623. MissingItemsComponent (const MissingItemsComponent&);
  43624. MissingItemsComponent& operator= (const MissingItemsComponent&);
  43625. };
  43626. Toolbar::Toolbar()
  43627. : vertical (false),
  43628. isEditingActive (false),
  43629. toolbarStyle (Toolbar::iconsOnly)
  43630. {
  43631. addChildComponent (missingItemsButton = getLookAndFeel().createToolbarMissingItemsButton (*this));
  43632. missingItemsButton->setAlwaysOnTop (true);
  43633. missingItemsButton->addButtonListener (this);
  43634. }
  43635. Toolbar::~Toolbar()
  43636. {
  43637. animator.cancelAllAnimations (true);
  43638. deleteAllChildren();
  43639. }
  43640. void Toolbar::setVertical (const bool shouldBeVertical)
  43641. {
  43642. if (vertical != shouldBeVertical)
  43643. {
  43644. vertical = shouldBeVertical;
  43645. resized();
  43646. }
  43647. }
  43648. void Toolbar::clear()
  43649. {
  43650. for (int i = items.size(); --i >= 0;)
  43651. {
  43652. ToolbarItemComponent* const tc = items.getUnchecked(i);
  43653. items.remove (i);
  43654. delete tc;
  43655. }
  43656. resized();
  43657. }
  43658. ToolbarItemComponent* Toolbar::createItem (ToolbarItemFactory& factory, const int itemId)
  43659. {
  43660. if (itemId == ToolbarItemFactory::separatorBarId)
  43661. return new ToolbarSpacerComp (itemId, 0.1f, true);
  43662. else if (itemId == ToolbarItemFactory::spacerId)
  43663. return new ToolbarSpacerComp (itemId, 0.5f, false);
  43664. else if (itemId == ToolbarItemFactory::flexibleSpacerId)
  43665. return new ToolbarSpacerComp (itemId, 0, false);
  43666. return factory.createItem (itemId);
  43667. }
  43668. void Toolbar::addItemInternal (ToolbarItemFactory& factory,
  43669. const int itemId,
  43670. const int insertIndex)
  43671. {
  43672. // An ID can't be zero - this might indicate a mistake somewhere?
  43673. jassert (itemId != 0);
  43674. ToolbarItemComponent* const tc = createItem (factory, itemId);
  43675. if (tc != 0)
  43676. {
  43677. #if JUCE_DEBUG
  43678. Array <int> allowedIds;
  43679. factory.getAllToolbarItemIds (allowedIds);
  43680. // If your factory can create an item for a given ID, it must also return
  43681. // that ID from its getAllToolbarItemIds() method!
  43682. jassert (allowedIds.contains (itemId));
  43683. #endif
  43684. items.insert (insertIndex, tc);
  43685. addAndMakeVisible (tc, insertIndex);
  43686. }
  43687. }
  43688. void Toolbar::addItem (ToolbarItemFactory& factory,
  43689. const int itemId,
  43690. const int insertIndex)
  43691. {
  43692. addItemInternal (factory, itemId, insertIndex);
  43693. resized();
  43694. }
  43695. void Toolbar::addDefaultItems (ToolbarItemFactory& factoryToUse)
  43696. {
  43697. Array <int> ids;
  43698. factoryToUse.getDefaultItemSet (ids);
  43699. clear();
  43700. for (int i = 0; i < ids.size(); ++i)
  43701. addItemInternal (factoryToUse, ids.getUnchecked (i), -1);
  43702. resized();
  43703. }
  43704. void Toolbar::removeToolbarItem (const int itemIndex)
  43705. {
  43706. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  43707. if (tc != 0)
  43708. {
  43709. items.removeValue (tc);
  43710. delete tc;
  43711. resized();
  43712. }
  43713. }
  43714. int Toolbar::getNumItems() const throw()
  43715. {
  43716. return items.size();
  43717. }
  43718. int Toolbar::getItemId (const int itemIndex) const throw()
  43719. {
  43720. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  43721. return tc != 0 ? tc->getItemId() : 0;
  43722. }
  43723. ToolbarItemComponent* Toolbar::getItemComponent (const int itemIndex) const throw()
  43724. {
  43725. return items [itemIndex];
  43726. }
  43727. ToolbarItemComponent* Toolbar::getNextActiveComponent (int index, const int delta) const
  43728. {
  43729. for (;;)
  43730. {
  43731. index += delta;
  43732. ToolbarItemComponent* const tc = getItemComponent (index);
  43733. if (tc == 0)
  43734. break;
  43735. if (tc->isActive)
  43736. return tc;
  43737. }
  43738. return 0;
  43739. }
  43740. void Toolbar::setStyle (const ToolbarItemStyle& newStyle)
  43741. {
  43742. if (toolbarStyle != newStyle)
  43743. {
  43744. toolbarStyle = newStyle;
  43745. updateAllItemPositions (false);
  43746. }
  43747. }
  43748. const String Toolbar::toString() const
  43749. {
  43750. String s ("TB:");
  43751. for (int i = 0; i < getNumItems(); ++i)
  43752. s << getItemId(i) << ' ';
  43753. return s.trimEnd();
  43754. }
  43755. bool Toolbar::restoreFromString (ToolbarItemFactory& factoryToUse,
  43756. const String& savedVersion)
  43757. {
  43758. if (! savedVersion.startsWith ("TB:"))
  43759. return false;
  43760. StringArray tokens;
  43761. tokens.addTokens (savedVersion.substring (3), false);
  43762. clear();
  43763. for (int i = 0; i < tokens.size(); ++i)
  43764. addItemInternal (factoryToUse, tokens[i].getIntValue(), -1);
  43765. resized();
  43766. return true;
  43767. }
  43768. void Toolbar::paint (Graphics& g)
  43769. {
  43770. getLookAndFeel().paintToolbarBackground (g, getWidth(), getHeight(), *this);
  43771. }
  43772. int Toolbar::getThickness() const throw()
  43773. {
  43774. return vertical ? getWidth() : getHeight();
  43775. }
  43776. int Toolbar::getLength() const throw()
  43777. {
  43778. return vertical ? getHeight() : getWidth();
  43779. }
  43780. void Toolbar::setEditingActive (const bool active)
  43781. {
  43782. if (isEditingActive != active)
  43783. {
  43784. isEditingActive = active;
  43785. updateAllItemPositions (false);
  43786. }
  43787. }
  43788. void Toolbar::resized()
  43789. {
  43790. updateAllItemPositions (false);
  43791. }
  43792. void Toolbar::updateAllItemPositions (const bool animate)
  43793. {
  43794. if (getWidth() > 0 && getHeight() > 0)
  43795. {
  43796. StretchableObjectResizer resizer;
  43797. int i;
  43798. for (i = 0; i < items.size(); ++i)
  43799. {
  43800. ToolbarItemComponent* const tc = items.getUnchecked(i);
  43801. tc->setEditingMode (isEditingActive ? ToolbarItemComponent::editableOnToolbar
  43802. : ToolbarItemComponent::normalMode);
  43803. tc->setStyle (toolbarStyle);
  43804. ToolbarSpacerComp* const spacer = dynamic_cast <ToolbarSpacerComp*> (tc);
  43805. int preferredSize = 1, minSize = 1, maxSize = 1;
  43806. if (tc->getToolbarItemSizes (getThickness(), isVertical(),
  43807. preferredSize, minSize, maxSize))
  43808. {
  43809. tc->isActive = true;
  43810. resizer.addItem (preferredSize, minSize, maxSize,
  43811. spacer != 0 ? spacer->getResizeOrder() : 2);
  43812. }
  43813. else
  43814. {
  43815. tc->isActive = false;
  43816. tc->setVisible (false);
  43817. }
  43818. }
  43819. resizer.resizeToFit (getLength());
  43820. int totalLength = 0;
  43821. for (i = 0; i < resizer.getNumItems(); ++i)
  43822. totalLength += (int) resizer.getItemSize (i);
  43823. const bool itemsOffTheEnd = totalLength > getLength();
  43824. const int extrasButtonSize = getThickness() / 2;
  43825. missingItemsButton->setSize (extrasButtonSize, extrasButtonSize);
  43826. missingItemsButton->setVisible (itemsOffTheEnd);
  43827. missingItemsButton->setEnabled (! isEditingActive);
  43828. if (vertical)
  43829. missingItemsButton->setCentrePosition (getWidth() / 2,
  43830. getHeight() - 4 - extrasButtonSize / 2);
  43831. else
  43832. missingItemsButton->setCentrePosition (getWidth() - 4 - extrasButtonSize / 2,
  43833. getHeight() / 2);
  43834. const int maxLength = itemsOffTheEnd ? (vertical ? missingItemsButton->getY()
  43835. : missingItemsButton->getX()) - 4
  43836. : getLength();
  43837. int pos = 0, activeIndex = 0;
  43838. for (i = 0; i < items.size(); ++i)
  43839. {
  43840. ToolbarItemComponent* const tc = items.getUnchecked(i);
  43841. if (tc->isActive)
  43842. {
  43843. const int size = (int) resizer.getItemSize (activeIndex++);
  43844. Rectangle<int> newBounds;
  43845. if (vertical)
  43846. newBounds.setBounds (0, pos, getWidth(), size);
  43847. else
  43848. newBounds.setBounds (pos, 0, size, getHeight());
  43849. if (animate)
  43850. {
  43851. animator.animateComponent (tc, newBounds, 200, 3.0, 0.0);
  43852. }
  43853. else
  43854. {
  43855. animator.cancelAnimation (tc, false);
  43856. tc->setBounds (newBounds);
  43857. }
  43858. pos += size;
  43859. tc->setVisible (pos <= maxLength
  43860. && ((! tc->isBeingDragged)
  43861. || tc->getEditingMode() == ToolbarItemComponent::editableOnPalette));
  43862. }
  43863. }
  43864. }
  43865. }
  43866. void Toolbar::buttonClicked (Button*)
  43867. {
  43868. jassert (missingItemsButton->isShowing());
  43869. if (missingItemsButton->isShowing())
  43870. {
  43871. PopupMenu m;
  43872. m.addCustomItem (1, new MissingItemsComponent (*this, getThickness()));
  43873. m.showAt (missingItemsButton);
  43874. }
  43875. }
  43876. bool Toolbar::isInterestedInDragSource (const String& sourceDescription,
  43877. Component* /*sourceComponent*/)
  43878. {
  43879. return sourceDescription == toolbarDragDescriptor && isEditingActive;
  43880. }
  43881. void Toolbar::itemDragMove (const String&, Component* sourceComponent, int x, int y)
  43882. {
  43883. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  43884. if (tc != 0)
  43885. {
  43886. if (getNumItems() == 0)
  43887. {
  43888. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  43889. {
  43890. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  43891. if (palette != 0)
  43892. palette->replaceComponent (tc);
  43893. }
  43894. else
  43895. {
  43896. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  43897. }
  43898. items.add (tc);
  43899. addChildComponent (tc);
  43900. updateAllItemPositions (false);
  43901. }
  43902. else
  43903. {
  43904. for (int i = getNumItems(); --i >= 0;)
  43905. {
  43906. int currentIndex = getIndexOfChildComponent (tc);
  43907. if (currentIndex < 0)
  43908. {
  43909. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  43910. {
  43911. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  43912. if (palette != 0)
  43913. palette->replaceComponent (tc);
  43914. }
  43915. else
  43916. {
  43917. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  43918. }
  43919. items.add (tc);
  43920. addChildComponent (tc);
  43921. currentIndex = getIndexOfChildComponent (tc);
  43922. updateAllItemPositions (true);
  43923. }
  43924. int newIndex = currentIndex;
  43925. const int dragObjectLeft = vertical ? (y - tc->dragOffsetY) : (x - tc->dragOffsetX);
  43926. const int dragObjectRight = dragObjectLeft + (vertical ? tc->getHeight() : tc->getWidth());
  43927. const Rectangle<int> current (animator.getComponentDestination (getChildComponent (newIndex)));
  43928. ToolbarItemComponent* const prev = getNextActiveComponent (newIndex, -1);
  43929. if (prev != 0)
  43930. {
  43931. const Rectangle<int> previousPos (animator.getComponentDestination (prev));
  43932. if (abs (dragObjectLeft - (vertical ? previousPos.getY() : previousPos.getX())
  43933. < abs (dragObjectRight - (vertical ? current.getBottom() : current.getRight()))))
  43934. {
  43935. newIndex = getIndexOfChildComponent (prev);
  43936. }
  43937. }
  43938. ToolbarItemComponent* const next = getNextActiveComponent (newIndex, 1);
  43939. if (next != 0)
  43940. {
  43941. const Rectangle<int> nextPos (animator.getComponentDestination (next));
  43942. if (abs (dragObjectLeft - (vertical ? current.getY() : current.getX())
  43943. > abs (dragObjectRight - (vertical ? nextPos.getBottom() : nextPos.getRight()))))
  43944. {
  43945. newIndex = getIndexOfChildComponent (next) + 1;
  43946. }
  43947. }
  43948. if (newIndex != currentIndex)
  43949. {
  43950. items.removeValue (tc);
  43951. removeChildComponent (tc);
  43952. addChildComponent (tc, newIndex);
  43953. items.insert (newIndex, tc);
  43954. updateAllItemPositions (true);
  43955. }
  43956. else
  43957. {
  43958. break;
  43959. }
  43960. }
  43961. }
  43962. }
  43963. }
  43964. void Toolbar::itemDragExit (const String&, Component* sourceComponent)
  43965. {
  43966. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  43967. if (tc != 0)
  43968. {
  43969. if (isParentOf (tc))
  43970. {
  43971. items.removeValue (tc);
  43972. removeChildComponent (tc);
  43973. updateAllItemPositions (true);
  43974. }
  43975. }
  43976. }
  43977. void Toolbar::itemDropped (const String&, Component*, int, int)
  43978. {
  43979. }
  43980. void Toolbar::mouseDown (const MouseEvent& e)
  43981. {
  43982. if (e.mods.isPopupMenu())
  43983. {
  43984. }
  43985. }
  43986. class ToolbarCustomisationDialog : public DialogWindow
  43987. {
  43988. public:
  43989. ToolbarCustomisationDialog (ToolbarItemFactory& factory,
  43990. Toolbar* const toolbar_,
  43991. const int optionFlags)
  43992. : DialogWindow (TRANS("Add/remove items from toolbar"), Colours::white, true, true),
  43993. toolbar (toolbar_)
  43994. {
  43995. setContentComponent (new CustomiserPanel (factory, toolbar, optionFlags), true, true);
  43996. setResizable (true, true);
  43997. setResizeLimits (400, 300, 1500, 1000);
  43998. positionNearBar();
  43999. }
  44000. ~ToolbarCustomisationDialog()
  44001. {
  44002. setContentComponent (0, true);
  44003. }
  44004. void closeButtonPressed()
  44005. {
  44006. setVisible (false);
  44007. }
  44008. bool canModalEventBeSentToComponent (const Component* comp)
  44009. {
  44010. return toolbar->isParentOf (comp);
  44011. }
  44012. void positionNearBar()
  44013. {
  44014. const Rectangle<int> screenSize (toolbar->getParentMonitorArea());
  44015. const int tbx = toolbar->getScreenX();
  44016. const int tby = toolbar->getScreenY();
  44017. const int gap = 8;
  44018. int x, y;
  44019. if (toolbar->isVertical())
  44020. {
  44021. y = tby;
  44022. if (tbx > screenSize.getCentreX())
  44023. x = tbx - getWidth() - gap;
  44024. else
  44025. x = tbx + toolbar->getWidth() + gap;
  44026. }
  44027. else
  44028. {
  44029. x = tbx + (toolbar->getWidth() - getWidth()) / 2;
  44030. if (tby > screenSize.getCentreY())
  44031. y = tby - getHeight() - gap;
  44032. else
  44033. y = tby + toolbar->getHeight() + gap;
  44034. }
  44035. setTopLeftPosition (x, y);
  44036. }
  44037. private:
  44038. Toolbar* const toolbar;
  44039. class CustomiserPanel : public Component,
  44040. private ComboBoxListener,
  44041. private ButtonListener
  44042. {
  44043. public:
  44044. CustomiserPanel (ToolbarItemFactory& factory_,
  44045. Toolbar* const toolbar_,
  44046. const int optionFlags)
  44047. : factory (factory_),
  44048. toolbar (toolbar_),
  44049. styleBox (0),
  44050. defaultButton (0)
  44051. {
  44052. addAndMakeVisible (palette = new ToolbarItemPalette (factory, toolbar));
  44053. if ((optionFlags & (Toolbar::allowIconsOnlyChoice
  44054. | Toolbar::allowIconsWithTextChoice
  44055. | Toolbar::allowTextOnlyChoice)) != 0)
  44056. {
  44057. addAndMakeVisible (styleBox = new ComboBox (String::empty));
  44058. styleBox->setEditableText (false);
  44059. if ((optionFlags & Toolbar::allowIconsOnlyChoice) != 0)
  44060. styleBox->addItem (TRANS("Show icons only"), 1);
  44061. if ((optionFlags & Toolbar::allowIconsWithTextChoice) != 0)
  44062. styleBox->addItem (TRANS("Show icons and descriptions"), 2);
  44063. if ((optionFlags & Toolbar::allowTextOnlyChoice) != 0)
  44064. styleBox->addItem (TRANS("Show descriptions only"), 3);
  44065. if (toolbar_->getStyle() == Toolbar::iconsOnly)
  44066. styleBox->setSelectedId (1);
  44067. else if (toolbar_->getStyle() == Toolbar::iconsWithText)
  44068. styleBox->setSelectedId (2);
  44069. else if (toolbar_->getStyle() == Toolbar::textOnly)
  44070. styleBox->setSelectedId (3);
  44071. styleBox->addListener (this);
  44072. }
  44073. if ((optionFlags & Toolbar::showResetToDefaultsButton) != 0)
  44074. {
  44075. addAndMakeVisible (defaultButton = new TextButton (TRANS ("Restore to default set of items")));
  44076. defaultButton->addButtonListener (this);
  44077. }
  44078. addAndMakeVisible (instructions = new Label (String::empty,
  44079. 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.")));
  44080. instructions->setFont (Font (13.0f));
  44081. setSize (500, 300);
  44082. }
  44083. ~CustomiserPanel()
  44084. {
  44085. deleteAllChildren();
  44086. }
  44087. void comboBoxChanged (ComboBox*)
  44088. {
  44089. if (styleBox->getSelectedId() == 1)
  44090. toolbar->setStyle (Toolbar::iconsOnly);
  44091. else if (styleBox->getSelectedId() == 2)
  44092. toolbar->setStyle (Toolbar::iconsWithText);
  44093. else if (styleBox->getSelectedId() == 3)
  44094. toolbar->setStyle (Toolbar::textOnly);
  44095. palette->resized(); // to make it update the styles
  44096. }
  44097. void buttonClicked (Button*)
  44098. {
  44099. toolbar->addDefaultItems (factory);
  44100. }
  44101. void paint (Graphics& g)
  44102. {
  44103. Colour background;
  44104. DialogWindow* const dw = findParentComponentOfClass ((DialogWindow*) 0);
  44105. if (dw != 0)
  44106. background = dw->getBackgroundColour();
  44107. g.setColour (background.contrasting().withAlpha (0.3f));
  44108. g.fillRect (palette->getX(), palette->getBottom() - 1, palette->getWidth(), 1);
  44109. }
  44110. void resized()
  44111. {
  44112. palette->setBounds (0, 0, getWidth(), getHeight() - 120);
  44113. if (styleBox != 0)
  44114. styleBox->setBounds (10, getHeight() - 110, 200, 22);
  44115. if (defaultButton != 0)
  44116. {
  44117. defaultButton->changeWidthToFitText (22);
  44118. defaultButton->setTopLeftPosition (240, getHeight() - 110);
  44119. }
  44120. instructions->setBounds (10, getHeight() - 80, getWidth() - 20, 80);
  44121. }
  44122. private:
  44123. ToolbarItemFactory& factory;
  44124. Toolbar* const toolbar;
  44125. Label* instructions;
  44126. ToolbarItemPalette* palette;
  44127. ComboBox* styleBox;
  44128. TextButton* defaultButton;
  44129. };
  44130. };
  44131. void Toolbar::showCustomisationDialog (ToolbarItemFactory& factory, const int optionFlags)
  44132. {
  44133. setEditingActive (true);
  44134. ToolbarCustomisationDialog dw (factory, this, optionFlags);
  44135. dw.runModalLoop();
  44136. jassert (isValidComponent()); // ? deleting the toolbar while it's being edited?
  44137. setEditingActive (false);
  44138. }
  44139. END_JUCE_NAMESPACE
  44140. /*** End of inlined file: juce_Toolbar.cpp ***/
  44141. /*** Start of inlined file: juce_ToolbarItemComponent.cpp ***/
  44142. BEGIN_JUCE_NAMESPACE
  44143. ToolbarItemFactory::ToolbarItemFactory()
  44144. {
  44145. }
  44146. ToolbarItemFactory::~ToolbarItemFactory()
  44147. {
  44148. }
  44149. class ItemDragAndDropOverlayComponent : public Component
  44150. {
  44151. public:
  44152. ItemDragAndDropOverlayComponent()
  44153. : isDragging (false)
  44154. {
  44155. setAlwaysOnTop (true);
  44156. setRepaintsOnMouseActivity (true);
  44157. setMouseCursor (MouseCursor::DraggingHandCursor);
  44158. }
  44159. ~ItemDragAndDropOverlayComponent()
  44160. {
  44161. }
  44162. void paint (Graphics& g)
  44163. {
  44164. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44165. if (isMouseOverOrDragging()
  44166. && tc != 0
  44167. && tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44168. {
  44169. g.setColour (findColour (Toolbar::editingModeOutlineColourId, true));
  44170. g.drawRect (0, 0, getWidth(), getHeight(),
  44171. jmin (2, (getWidth() - 1) / 2, (getHeight() - 1) / 2));
  44172. }
  44173. }
  44174. void mouseDown (const MouseEvent& e)
  44175. {
  44176. isDragging = false;
  44177. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44178. if (tc != 0)
  44179. {
  44180. tc->dragOffsetX = e.x;
  44181. tc->dragOffsetY = e.y;
  44182. }
  44183. }
  44184. void mouseDrag (const MouseEvent& e)
  44185. {
  44186. if (! (isDragging || e.mouseWasClicked()))
  44187. {
  44188. isDragging = true;
  44189. DragAndDropContainer* const dnd = DragAndDropContainer::findParentDragContainerFor (this);
  44190. if (dnd != 0)
  44191. {
  44192. dnd->startDragging (Toolbar::toolbarDragDescriptor, getParentComponent(), Image(), true);
  44193. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44194. if (tc != 0)
  44195. {
  44196. tc->isBeingDragged = true;
  44197. if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44198. tc->setVisible (false);
  44199. }
  44200. }
  44201. }
  44202. }
  44203. void mouseUp (const MouseEvent&)
  44204. {
  44205. isDragging = false;
  44206. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44207. if (tc != 0)
  44208. {
  44209. tc->isBeingDragged = false;
  44210. Toolbar* const tb = tc->getToolbar();
  44211. if (tb != 0)
  44212. tb->updateAllItemPositions (true);
  44213. else if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44214. delete tc;
  44215. }
  44216. }
  44217. void parentSizeChanged()
  44218. {
  44219. setBounds (0, 0, getParentWidth(), getParentHeight());
  44220. }
  44221. juce_UseDebuggingNewOperator
  44222. private:
  44223. bool isDragging;
  44224. ItemDragAndDropOverlayComponent (const ItemDragAndDropOverlayComponent&);
  44225. ItemDragAndDropOverlayComponent& operator= (const ItemDragAndDropOverlayComponent&);
  44226. };
  44227. ToolbarItemComponent::ToolbarItemComponent (const int itemId_,
  44228. const String& labelText,
  44229. const bool isBeingUsedAsAButton_)
  44230. : Button (labelText),
  44231. itemId (itemId_),
  44232. mode (normalMode),
  44233. toolbarStyle (Toolbar::iconsOnly),
  44234. dragOffsetX (0),
  44235. dragOffsetY (0),
  44236. isActive (true),
  44237. isBeingDragged (false),
  44238. isBeingUsedAsAButton (isBeingUsedAsAButton_)
  44239. {
  44240. // Your item ID can't be 0!
  44241. jassert (itemId_ != 0);
  44242. }
  44243. ToolbarItemComponent::~ToolbarItemComponent()
  44244. {
  44245. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  44246. overlayComp = 0;
  44247. }
  44248. Toolbar* ToolbarItemComponent::getToolbar() const
  44249. {
  44250. return dynamic_cast <Toolbar*> (getParentComponent());
  44251. }
  44252. bool ToolbarItemComponent::isToolbarVertical() const
  44253. {
  44254. const Toolbar* const t = getToolbar();
  44255. return t != 0 && t->isVertical();
  44256. }
  44257. void ToolbarItemComponent::setStyle (const Toolbar::ToolbarItemStyle& newStyle)
  44258. {
  44259. if (toolbarStyle != newStyle)
  44260. {
  44261. toolbarStyle = newStyle;
  44262. repaint();
  44263. resized();
  44264. }
  44265. }
  44266. void ToolbarItemComponent::paintButton (Graphics& g, const bool over, const bool down)
  44267. {
  44268. if (isBeingUsedAsAButton)
  44269. getLookAndFeel().paintToolbarButtonBackground (g, getWidth(), getHeight(),
  44270. over, down, *this);
  44271. if (toolbarStyle != Toolbar::iconsOnly)
  44272. {
  44273. const int indent = contentArea.getX();
  44274. int y = indent;
  44275. int h = getHeight() - indent * 2;
  44276. if (toolbarStyle == Toolbar::iconsWithText)
  44277. {
  44278. y = contentArea.getBottom() + indent / 2;
  44279. h -= contentArea.getHeight();
  44280. }
  44281. getLookAndFeel().paintToolbarButtonLabel (g, indent, y, getWidth() - indent * 2, h,
  44282. getButtonText(), *this);
  44283. }
  44284. if (! contentArea.isEmpty())
  44285. {
  44286. g.saveState();
  44287. g.setOrigin (contentArea.getX(), contentArea.getY());
  44288. g.reduceClipRegion (0, 0, contentArea.getWidth(), contentArea.getHeight());
  44289. paintButtonArea (g, contentArea.getWidth(), contentArea.getHeight(), over, down);
  44290. g.restoreState();
  44291. }
  44292. }
  44293. void ToolbarItemComponent::resized()
  44294. {
  44295. if (toolbarStyle != Toolbar::textOnly)
  44296. {
  44297. const int indent = jmin (proportionOfWidth (0.08f),
  44298. proportionOfHeight (0.08f));
  44299. contentArea = Rectangle<int> (indent, indent,
  44300. getWidth() - indent * 2,
  44301. toolbarStyle == Toolbar::iconsWithText ? proportionOfHeight (0.55f)
  44302. : (getHeight() - indent * 2));
  44303. }
  44304. else
  44305. {
  44306. contentArea = Rectangle<int>();
  44307. }
  44308. contentAreaChanged (contentArea);
  44309. }
  44310. void ToolbarItemComponent::setEditingMode (const ToolbarEditingMode newMode)
  44311. {
  44312. if (mode != newMode)
  44313. {
  44314. mode = newMode;
  44315. repaint();
  44316. if (mode == normalMode)
  44317. {
  44318. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  44319. overlayComp = 0;
  44320. }
  44321. else if (overlayComp == 0)
  44322. {
  44323. addAndMakeVisible (overlayComp = new ItemDragAndDropOverlayComponent());
  44324. overlayComp->parentSizeChanged();
  44325. }
  44326. resized();
  44327. }
  44328. }
  44329. END_JUCE_NAMESPACE
  44330. /*** End of inlined file: juce_ToolbarItemComponent.cpp ***/
  44331. /*** Start of inlined file: juce_ToolbarItemPalette.cpp ***/
  44332. BEGIN_JUCE_NAMESPACE
  44333. ToolbarItemPalette::ToolbarItemPalette (ToolbarItemFactory& factory_,
  44334. Toolbar* const toolbar_)
  44335. : factory (factory_),
  44336. toolbar (toolbar_)
  44337. {
  44338. Component* const itemHolder = new Component();
  44339. Array <int> allIds;
  44340. factory_.getAllToolbarItemIds (allIds);
  44341. for (int i = 0; i < allIds.size(); ++i)
  44342. {
  44343. ToolbarItemComponent* const tc = Toolbar::createItem (factory_, allIds.getUnchecked (i));
  44344. jassert (tc != 0);
  44345. if (tc != 0)
  44346. {
  44347. itemHolder->addAndMakeVisible (tc);
  44348. tc->setEditingMode (ToolbarItemComponent::editableOnPalette);
  44349. }
  44350. }
  44351. viewport = new Viewport();
  44352. viewport->setViewedComponent (itemHolder);
  44353. addAndMakeVisible (viewport);
  44354. }
  44355. ToolbarItemPalette::~ToolbarItemPalette()
  44356. {
  44357. viewport->getViewedComponent()->deleteAllChildren();
  44358. deleteAllChildren();
  44359. }
  44360. void ToolbarItemPalette::resized()
  44361. {
  44362. viewport->setBoundsInset (BorderSize (1));
  44363. Component* const itemHolder = viewport->getViewedComponent();
  44364. const int indent = 8;
  44365. const int preferredWidth = viewport->getWidth() - viewport->getScrollBarThickness() - indent;
  44366. const int height = toolbar->getThickness();
  44367. int x = indent;
  44368. int y = indent;
  44369. int maxX = 0;
  44370. for (int i = 0; i < itemHolder->getNumChildComponents(); ++i)
  44371. {
  44372. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (itemHolder->getChildComponent (i));
  44373. if (tc != 0)
  44374. {
  44375. tc->setStyle (toolbar->getStyle());
  44376. int preferredSize = 1, minSize = 1, maxSize = 1;
  44377. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  44378. {
  44379. if (x + preferredSize > preferredWidth && x > indent)
  44380. {
  44381. x = indent;
  44382. y += height;
  44383. }
  44384. tc->setBounds (x, y, preferredSize, height);
  44385. x += preferredSize + 8;
  44386. maxX = jmax (maxX, x);
  44387. }
  44388. }
  44389. }
  44390. itemHolder->setSize (maxX, y + height + 8);
  44391. }
  44392. void ToolbarItemPalette::replaceComponent (ToolbarItemComponent* const comp)
  44393. {
  44394. ToolbarItemComponent* const tc = Toolbar::createItem (factory, comp->getItemId());
  44395. jassert (tc != 0);
  44396. if (tc != 0)
  44397. {
  44398. tc->setBounds (comp->getBounds());
  44399. tc->setStyle (toolbar->getStyle());
  44400. tc->setEditingMode (comp->getEditingMode());
  44401. viewport->getViewedComponent()->addAndMakeVisible (tc, getIndexOfChildComponent (comp));
  44402. }
  44403. }
  44404. END_JUCE_NAMESPACE
  44405. /*** End of inlined file: juce_ToolbarItemPalette.cpp ***/
  44406. /*** Start of inlined file: juce_TreeView.cpp ***/
  44407. BEGIN_JUCE_NAMESPACE
  44408. class TreeViewContentComponent : public Component,
  44409. public TooltipClient
  44410. {
  44411. public:
  44412. TreeViewContentComponent (TreeView& owner_)
  44413. : owner (owner_),
  44414. buttonUnderMouse (0),
  44415. isDragging (false)
  44416. {
  44417. }
  44418. ~TreeViewContentComponent()
  44419. {
  44420. deleteAllChildren();
  44421. }
  44422. void mouseDown (const MouseEvent& e)
  44423. {
  44424. updateButtonUnderMouse (e);
  44425. isDragging = false;
  44426. needSelectionOnMouseUp = false;
  44427. Rectangle<int> pos;
  44428. TreeViewItem* const item = findItemAt (e.y, pos);
  44429. if (item == 0)
  44430. return;
  44431. // (if the open/close buttons are hidden, we'll treat clicks to the left of the item
  44432. // as selection clicks)
  44433. if (e.x < pos.getX() && owner.openCloseButtonsVisible)
  44434. {
  44435. if (e.x >= pos.getX() - owner.getIndentSize())
  44436. item->setOpen (! item->isOpen());
  44437. // (clicks to the left of an open/close button are ignored)
  44438. }
  44439. else
  44440. {
  44441. // mouse-down inside the body of the item..
  44442. if (! owner.isMultiSelectEnabled())
  44443. item->setSelected (true, true);
  44444. else if (item->isSelected())
  44445. needSelectionOnMouseUp = ! e.mods.isPopupMenu();
  44446. else
  44447. selectBasedOnModifiers (item, e.mods);
  44448. if (e.x >= pos.getX())
  44449. item->itemClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  44450. }
  44451. }
  44452. void mouseUp (const MouseEvent& e)
  44453. {
  44454. updateButtonUnderMouse (e);
  44455. if (needSelectionOnMouseUp && e.mouseWasClicked())
  44456. {
  44457. Rectangle<int> pos;
  44458. TreeViewItem* const item = findItemAt (e.y, pos);
  44459. if (item != 0)
  44460. selectBasedOnModifiers (item, e.mods);
  44461. }
  44462. }
  44463. void mouseDoubleClick (const MouseEvent& e)
  44464. {
  44465. if (e.getNumberOfClicks() != 3) // ignore triple clicks
  44466. {
  44467. Rectangle<int> pos;
  44468. TreeViewItem* const item = findItemAt (e.y, pos);
  44469. if (item != 0 && (e.x >= pos.getX() || ! owner.openCloseButtonsVisible))
  44470. item->itemDoubleClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  44471. }
  44472. }
  44473. void mouseDrag (const MouseEvent& e)
  44474. {
  44475. if (isEnabled()
  44476. && ! (isDragging || e.mouseWasClicked()
  44477. || e.getDistanceFromDragStart() < 5
  44478. || e.mods.isPopupMenu()))
  44479. {
  44480. isDragging = true;
  44481. Rectangle<int> pos;
  44482. TreeViewItem* const item = findItemAt (e.getMouseDownY(), pos);
  44483. if (item != 0 && e.getMouseDownX() >= pos.getX())
  44484. {
  44485. const String dragDescription (item->getDragSourceDescription());
  44486. if (dragDescription.isNotEmpty())
  44487. {
  44488. DragAndDropContainer* const dragContainer
  44489. = DragAndDropContainer::findParentDragContainerFor (this);
  44490. if (dragContainer != 0)
  44491. {
  44492. pos.setSize (pos.getWidth(), item->itemHeight);
  44493. Image dragImage (Component::createComponentSnapshot (pos, true));
  44494. dragImage.multiplyAllAlphas (0.6f);
  44495. Point<int> imageOffset (pos.getPosition() - e.getPosition());
  44496. dragContainer->startDragging (dragDescription, &owner, dragImage, true, &imageOffset);
  44497. }
  44498. else
  44499. {
  44500. // to be able to do a drag-and-drop operation, the treeview needs to
  44501. // be inside a component which is also a DragAndDropContainer.
  44502. jassertfalse;
  44503. }
  44504. }
  44505. }
  44506. }
  44507. }
  44508. void mouseMove (const MouseEvent& e)
  44509. {
  44510. updateButtonUnderMouse (e);
  44511. }
  44512. void mouseExit (const MouseEvent& e)
  44513. {
  44514. updateButtonUnderMouse (e);
  44515. }
  44516. void paint (Graphics& g)
  44517. {
  44518. if (owner.rootItem != 0)
  44519. {
  44520. owner.handleAsyncUpdate();
  44521. if (! owner.rootItemVisible)
  44522. g.setOrigin (0, -owner.rootItem->itemHeight);
  44523. owner.rootItem->paintRecursively (g, getWidth());
  44524. }
  44525. }
  44526. TreeViewItem* findItemAt (int y, Rectangle<int>& itemPosition) const
  44527. {
  44528. if (owner.rootItem != 0)
  44529. {
  44530. owner.handleAsyncUpdate();
  44531. if (! owner.rootItemVisible)
  44532. y += owner.rootItem->itemHeight;
  44533. TreeViewItem* const ti = owner.rootItem->findItemRecursively (y);
  44534. if (ti != 0)
  44535. itemPosition = ti->getItemPosition (false);
  44536. return ti;
  44537. }
  44538. return 0;
  44539. }
  44540. void updateComponents()
  44541. {
  44542. const int visibleTop = -getY();
  44543. const int visibleBottom = visibleTop + getParentHeight();
  44544. BigInteger itemsToKeep;
  44545. {
  44546. TreeViewItem* item = owner.rootItem;
  44547. int y = (item != 0 && ! owner.rootItemVisible) ? -item->itemHeight : 0;
  44548. while (item != 0 && y < visibleBottom)
  44549. {
  44550. y += item->itemHeight;
  44551. if (y >= visibleTop)
  44552. {
  44553. const int index = rowComponentIds.indexOf (item->uid);
  44554. if (index < 0)
  44555. {
  44556. Component* const comp = item->createItemComponent();
  44557. if (comp != 0)
  44558. {
  44559. addAndMakeVisible (comp);
  44560. itemsToKeep.setBit (rowComponentItems.size());
  44561. rowComponentItems.add (item);
  44562. rowComponentIds.add (item->uid);
  44563. rowComponents.add (comp);
  44564. }
  44565. }
  44566. else
  44567. {
  44568. itemsToKeep.setBit (index);
  44569. }
  44570. }
  44571. item = item->getNextVisibleItem (true);
  44572. }
  44573. }
  44574. for (int i = rowComponentItems.size(); --i >= 0;)
  44575. {
  44576. Component* const comp = rowComponents.getUnchecked(i);
  44577. bool keep = false;
  44578. if (isParentOf (comp))
  44579. {
  44580. if (itemsToKeep[i])
  44581. {
  44582. const TreeViewItem* const item = rowComponentItems.getUnchecked(i);
  44583. Rectangle<int> pos (item->getItemPosition (false));
  44584. pos.setSize (pos.getWidth(), item->itemHeight);
  44585. if (pos.getBottom() >= visibleTop && pos.getY() < visibleBottom)
  44586. {
  44587. keep = true;
  44588. comp->setBounds (pos);
  44589. }
  44590. }
  44591. if ((! keep) && isMouseDraggingInChildCompOf (comp))
  44592. {
  44593. keep = true;
  44594. comp->setSize (0, 0);
  44595. }
  44596. }
  44597. if (! keep)
  44598. {
  44599. delete comp;
  44600. rowComponents.remove (i);
  44601. rowComponentIds.remove (i);
  44602. rowComponentItems.remove (i);
  44603. }
  44604. }
  44605. }
  44606. void updateButtonUnderMouse (const MouseEvent& e)
  44607. {
  44608. TreeViewItem* newItem = 0;
  44609. if (owner.openCloseButtonsVisible)
  44610. {
  44611. Rectangle<int> pos;
  44612. TreeViewItem* item = findItemAt (e.y, pos);
  44613. if (item != 0 && e.x < pos.getX() && e.x >= pos.getX() - owner.getIndentSize())
  44614. {
  44615. newItem = item;
  44616. if (! newItem->mightContainSubItems())
  44617. newItem = 0;
  44618. }
  44619. }
  44620. if (buttonUnderMouse != newItem)
  44621. {
  44622. if (buttonUnderMouse != 0 && containsItem (buttonUnderMouse))
  44623. {
  44624. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  44625. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  44626. }
  44627. buttonUnderMouse = newItem;
  44628. if (buttonUnderMouse != 0)
  44629. {
  44630. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  44631. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  44632. }
  44633. }
  44634. }
  44635. bool isMouseOverButton (TreeViewItem* const item) const throw()
  44636. {
  44637. return item == buttonUnderMouse;
  44638. }
  44639. void resized()
  44640. {
  44641. owner.itemsChanged();
  44642. }
  44643. const String getTooltip()
  44644. {
  44645. Rectangle<int> pos;
  44646. TreeViewItem* const item = findItemAt (getMouseXYRelative().getY(), pos);
  44647. if (item != 0)
  44648. return item->getTooltip();
  44649. return owner.getTooltip();
  44650. }
  44651. juce_UseDebuggingNewOperator
  44652. private:
  44653. TreeView& owner;
  44654. Array <TreeViewItem*> rowComponentItems;
  44655. Array <int> rowComponentIds;
  44656. Array <Component*> rowComponents;
  44657. TreeViewItem* buttonUnderMouse;
  44658. bool isDragging, needSelectionOnMouseUp;
  44659. void selectBasedOnModifiers (TreeViewItem* const item, const ModifierKeys& modifiers)
  44660. {
  44661. TreeViewItem* firstSelected = 0;
  44662. if (modifiers.isShiftDown() && ((firstSelected = owner.getSelectedItem (0)) != 0))
  44663. {
  44664. TreeViewItem* const lastSelected = owner.getSelectedItem (owner.getNumSelectedItems() - 1);
  44665. jassert (lastSelected != 0);
  44666. int rowStart = firstSelected->getRowNumberInTree();
  44667. int rowEnd = lastSelected->getRowNumberInTree();
  44668. if (rowStart > rowEnd)
  44669. swapVariables (rowStart, rowEnd);
  44670. int ourRow = item->getRowNumberInTree();
  44671. int otherEnd = ourRow < rowEnd ? rowStart : rowEnd;
  44672. if (ourRow > otherEnd)
  44673. swapVariables (ourRow, otherEnd);
  44674. for (int i = ourRow; i <= otherEnd; ++i)
  44675. owner.getItemOnRow (i)->setSelected (true, false);
  44676. }
  44677. else
  44678. {
  44679. const bool cmd = modifiers.isCommandDown();
  44680. item->setSelected ((! cmd) || ! item->isSelected(), ! cmd);
  44681. }
  44682. }
  44683. bool containsItem (TreeViewItem* const item) const
  44684. {
  44685. for (int i = rowComponentItems.size(); --i >= 0;)
  44686. if (rowComponentItems.getUnchecked(i) == item)
  44687. return true;
  44688. return false;
  44689. }
  44690. static bool isMouseDraggingInChildCompOf (Component* const comp)
  44691. {
  44692. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  44693. {
  44694. MouseInputSource* const source = Desktop::getInstance().getMouseSource(i);
  44695. if (source->isDragging())
  44696. {
  44697. Component* const underMouse = source->getComponentUnderMouse();
  44698. if (underMouse != 0 && (comp == underMouse || comp->isParentOf (underMouse)))
  44699. return true;
  44700. }
  44701. }
  44702. return false;
  44703. }
  44704. TreeViewContentComponent (const TreeViewContentComponent&);
  44705. TreeViewContentComponent& operator= (const TreeViewContentComponent&);
  44706. };
  44707. class TreeView::TreeViewport : public Viewport
  44708. {
  44709. public:
  44710. TreeViewport() throw() : lastX (-1) {}
  44711. ~TreeViewport() throw() {}
  44712. void updateComponents (const bool triggerResize = false)
  44713. {
  44714. TreeViewContentComponent* const tvc = static_cast <TreeViewContentComponent*> (getViewedComponent());
  44715. if (tvc != 0)
  44716. {
  44717. if (triggerResize)
  44718. tvc->resized();
  44719. else
  44720. tvc->updateComponents();
  44721. }
  44722. repaint();
  44723. }
  44724. void visibleAreaChanged (int x, int, int, int)
  44725. {
  44726. const bool hasScrolledSideways = (x != lastX);
  44727. lastX = x;
  44728. updateComponents (hasScrolledSideways);
  44729. }
  44730. juce_UseDebuggingNewOperator
  44731. private:
  44732. int lastX;
  44733. TreeViewport (const TreeViewport&);
  44734. TreeViewport& operator= (const TreeViewport&);
  44735. };
  44736. TreeView::TreeView (const String& componentName)
  44737. : Component (componentName),
  44738. rootItem (0),
  44739. indentSize (24),
  44740. defaultOpenness (false),
  44741. needsRecalculating (true),
  44742. rootItemVisible (true),
  44743. multiSelectEnabled (false),
  44744. openCloseButtonsVisible (true)
  44745. {
  44746. addAndMakeVisible (viewport = new TreeViewport());
  44747. viewport->setViewedComponent (new TreeViewContentComponent (*this));
  44748. viewport->setWantsKeyboardFocus (false);
  44749. setWantsKeyboardFocus (true);
  44750. }
  44751. TreeView::~TreeView()
  44752. {
  44753. if (rootItem != 0)
  44754. rootItem->setOwnerView (0);
  44755. }
  44756. void TreeView::setRootItem (TreeViewItem* const newRootItem)
  44757. {
  44758. if (rootItem != newRootItem)
  44759. {
  44760. if (newRootItem != 0)
  44761. {
  44762. jassert (newRootItem->ownerView == 0); // can't use a tree item in more than one tree at once..
  44763. if (newRootItem->ownerView != 0)
  44764. newRootItem->ownerView->setRootItem (0);
  44765. }
  44766. if (rootItem != 0)
  44767. rootItem->setOwnerView (0);
  44768. rootItem = newRootItem;
  44769. if (newRootItem != 0)
  44770. newRootItem->setOwnerView (this);
  44771. needsRecalculating = true;
  44772. handleAsyncUpdate();
  44773. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  44774. {
  44775. rootItem->setOpen (false); // force a re-open
  44776. rootItem->setOpen (true);
  44777. }
  44778. }
  44779. }
  44780. void TreeView::deleteRootItem()
  44781. {
  44782. const ScopedPointer <TreeViewItem> deleter (rootItem);
  44783. setRootItem (0);
  44784. }
  44785. void TreeView::setRootItemVisible (const bool shouldBeVisible)
  44786. {
  44787. rootItemVisible = shouldBeVisible;
  44788. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  44789. {
  44790. rootItem->setOpen (false); // force a re-open
  44791. rootItem->setOpen (true);
  44792. }
  44793. itemsChanged();
  44794. }
  44795. void TreeView::colourChanged()
  44796. {
  44797. setOpaque (findColour (backgroundColourId).isOpaque());
  44798. repaint();
  44799. }
  44800. void TreeView::setIndentSize (const int newIndentSize)
  44801. {
  44802. if (indentSize != newIndentSize)
  44803. {
  44804. indentSize = newIndentSize;
  44805. resized();
  44806. }
  44807. }
  44808. void TreeView::setDefaultOpenness (const bool isOpenByDefault)
  44809. {
  44810. if (defaultOpenness != isOpenByDefault)
  44811. {
  44812. defaultOpenness = isOpenByDefault;
  44813. itemsChanged();
  44814. }
  44815. }
  44816. void TreeView::setMultiSelectEnabled (const bool canMultiSelect)
  44817. {
  44818. multiSelectEnabled = canMultiSelect;
  44819. }
  44820. void TreeView::setOpenCloseButtonsVisible (const bool shouldBeVisible)
  44821. {
  44822. if (openCloseButtonsVisible != shouldBeVisible)
  44823. {
  44824. openCloseButtonsVisible = shouldBeVisible;
  44825. itemsChanged();
  44826. }
  44827. }
  44828. Viewport* TreeView::getViewport() const throw()
  44829. {
  44830. return viewport;
  44831. }
  44832. void TreeView::clearSelectedItems()
  44833. {
  44834. if (rootItem != 0)
  44835. rootItem->deselectAllRecursively();
  44836. }
  44837. int TreeView::getNumSelectedItems() const throw()
  44838. {
  44839. return (rootItem != 0) ? rootItem->countSelectedItemsRecursively() : 0;
  44840. }
  44841. TreeViewItem* TreeView::getSelectedItem (const int index) const throw()
  44842. {
  44843. return (rootItem != 0) ? rootItem->getSelectedItemWithIndex (index) : 0;
  44844. }
  44845. int TreeView::getNumRowsInTree() const
  44846. {
  44847. if (rootItem != 0)
  44848. return rootItem->getNumRows() - (rootItemVisible ? 0 : 1);
  44849. return 0;
  44850. }
  44851. TreeViewItem* TreeView::getItemOnRow (int index) const
  44852. {
  44853. if (! rootItemVisible)
  44854. ++index;
  44855. if (rootItem != 0 && index >= 0)
  44856. return rootItem->getItemOnRow (index);
  44857. return 0;
  44858. }
  44859. TreeViewItem* TreeView::getItemAt (int y) const throw()
  44860. {
  44861. TreeViewContentComponent* const tc = static_cast <TreeViewContentComponent*> (viewport->getViewedComponent());
  44862. Rectangle<int> pos;
  44863. return tc->findItemAt (relativePositionToOtherComponent (tc, Point<int> (0, y)).getY(), pos);
  44864. }
  44865. TreeViewItem* TreeView::findItemFromIdentifierString (const String& identifierString) const
  44866. {
  44867. if (rootItem == 0)
  44868. return 0;
  44869. return rootItem->findItemFromIdentifierString (identifierString);
  44870. }
  44871. XmlElement* TreeView::getOpennessState (const bool alsoIncludeScrollPosition) const
  44872. {
  44873. XmlElement* e = 0;
  44874. if (rootItem != 0)
  44875. {
  44876. e = rootItem->getOpennessState();
  44877. if (e != 0 && alsoIncludeScrollPosition)
  44878. e->setAttribute ("scrollPos", viewport->getViewPositionY());
  44879. }
  44880. return e;
  44881. }
  44882. void TreeView::restoreOpennessState (const XmlElement& newState)
  44883. {
  44884. if (rootItem != 0)
  44885. {
  44886. rootItem->restoreOpennessState (newState);
  44887. if (newState.hasAttribute ("scrollPos"))
  44888. viewport->setViewPosition (viewport->getViewPositionX(),
  44889. newState.getIntAttribute ("scrollPos"));
  44890. }
  44891. }
  44892. void TreeView::paint (Graphics& g)
  44893. {
  44894. g.fillAll (findColour (backgroundColourId));
  44895. }
  44896. void TreeView::resized()
  44897. {
  44898. viewport->setBounds (getLocalBounds());
  44899. itemsChanged();
  44900. handleAsyncUpdate();
  44901. }
  44902. void TreeView::enablementChanged()
  44903. {
  44904. repaint();
  44905. }
  44906. void TreeView::moveSelectedRow (int delta)
  44907. {
  44908. if (delta == 0)
  44909. return;
  44910. int rowSelected = 0;
  44911. TreeViewItem* const firstSelected = getSelectedItem (0);
  44912. if (firstSelected != 0)
  44913. rowSelected = firstSelected->getRowNumberInTree();
  44914. rowSelected = jlimit (0, getNumRowsInTree() - 1, rowSelected + delta);
  44915. for (;;)
  44916. {
  44917. TreeViewItem* item = getItemOnRow (rowSelected);
  44918. if (item != 0)
  44919. {
  44920. if (! item->canBeSelected())
  44921. {
  44922. // if the row we want to highlight doesn't allow it, try skipping
  44923. // to the next item..
  44924. const int nextRowToTry = jlimit (0, getNumRowsInTree() - 1,
  44925. rowSelected + (delta < 0 ? -1 : 1));
  44926. if (rowSelected != nextRowToTry)
  44927. {
  44928. rowSelected = nextRowToTry;
  44929. continue;
  44930. }
  44931. else
  44932. {
  44933. break;
  44934. }
  44935. }
  44936. item->setSelected (true, true);
  44937. scrollToKeepItemVisible (item);
  44938. }
  44939. break;
  44940. }
  44941. }
  44942. void TreeView::scrollToKeepItemVisible (TreeViewItem* item)
  44943. {
  44944. if (item != 0 && item->ownerView == this)
  44945. {
  44946. handleAsyncUpdate();
  44947. item = item->getDeepestOpenParentItem();
  44948. int y = item->y;
  44949. int viewTop = viewport->getViewPositionY();
  44950. if (y < viewTop)
  44951. {
  44952. viewport->setViewPosition (viewport->getViewPositionX(), y);
  44953. }
  44954. else if (y + item->itemHeight > viewTop + viewport->getViewHeight())
  44955. {
  44956. viewport->setViewPosition (viewport->getViewPositionX(),
  44957. (y + item->itemHeight) - viewport->getViewHeight());
  44958. }
  44959. }
  44960. }
  44961. bool TreeView::keyPressed (const KeyPress& key)
  44962. {
  44963. if (key.isKeyCode (KeyPress::upKey))
  44964. {
  44965. moveSelectedRow (-1);
  44966. }
  44967. else if (key.isKeyCode (KeyPress::downKey))
  44968. {
  44969. moveSelectedRow (1);
  44970. }
  44971. else if (key.isKeyCode (KeyPress::pageDownKey) || key.isKeyCode (KeyPress::pageUpKey))
  44972. {
  44973. if (rootItem != 0)
  44974. {
  44975. int rowsOnScreen = getHeight() / jmax (1, rootItem->itemHeight);
  44976. if (key.isKeyCode (KeyPress::pageUpKey))
  44977. rowsOnScreen = -rowsOnScreen;
  44978. moveSelectedRow (rowsOnScreen);
  44979. }
  44980. }
  44981. else if (key.isKeyCode (KeyPress::homeKey))
  44982. {
  44983. moveSelectedRow (-0x3fffffff);
  44984. }
  44985. else if (key.isKeyCode (KeyPress::endKey))
  44986. {
  44987. moveSelectedRow (0x3fffffff);
  44988. }
  44989. else if (key.isKeyCode (KeyPress::returnKey))
  44990. {
  44991. TreeViewItem* const firstSelected = getSelectedItem (0);
  44992. if (firstSelected != 0)
  44993. firstSelected->setOpen (! firstSelected->isOpen());
  44994. }
  44995. else if (key.isKeyCode (KeyPress::leftKey))
  44996. {
  44997. TreeViewItem* const firstSelected = getSelectedItem (0);
  44998. if (firstSelected != 0)
  44999. {
  45000. if (firstSelected->isOpen())
  45001. {
  45002. firstSelected->setOpen (false);
  45003. }
  45004. else
  45005. {
  45006. TreeViewItem* parent = firstSelected->parentItem;
  45007. if ((! rootItemVisible) && parent == rootItem)
  45008. parent = 0;
  45009. if (parent != 0)
  45010. {
  45011. parent->setSelected (true, true);
  45012. scrollToKeepItemVisible (parent);
  45013. }
  45014. }
  45015. }
  45016. }
  45017. else if (key.isKeyCode (KeyPress::rightKey))
  45018. {
  45019. TreeViewItem* const firstSelected = getSelectedItem (0);
  45020. if (firstSelected != 0)
  45021. {
  45022. if (firstSelected->isOpen() || ! firstSelected->mightContainSubItems())
  45023. moveSelectedRow (1);
  45024. else
  45025. firstSelected->setOpen (true);
  45026. }
  45027. }
  45028. else
  45029. {
  45030. return false;
  45031. }
  45032. return true;
  45033. }
  45034. void TreeView::itemsChanged() throw()
  45035. {
  45036. needsRecalculating = true;
  45037. repaint();
  45038. triggerAsyncUpdate();
  45039. }
  45040. void TreeView::handleAsyncUpdate()
  45041. {
  45042. if (needsRecalculating)
  45043. {
  45044. needsRecalculating = false;
  45045. const ScopedLock sl (nodeAlterationLock);
  45046. if (rootItem != 0)
  45047. rootItem->updatePositions (rootItemVisible ? 0 : -rootItem->itemHeight);
  45048. viewport->updateComponents();
  45049. if (rootItem != 0)
  45050. {
  45051. viewport->getViewedComponent()
  45052. ->setSize (jmax (viewport->getMaximumVisibleWidth(), rootItem->totalWidth),
  45053. rootItem->totalHeight - (rootItemVisible ? 0 : rootItem->itemHeight));
  45054. }
  45055. else
  45056. {
  45057. viewport->getViewedComponent()->setSize (0, 0);
  45058. }
  45059. }
  45060. }
  45061. class TreeView::InsertPointHighlight : public Component
  45062. {
  45063. public:
  45064. InsertPointHighlight()
  45065. : lastItem (0)
  45066. {
  45067. setSize (100, 12);
  45068. setAlwaysOnTop (true);
  45069. setInterceptsMouseClicks (false, false);
  45070. }
  45071. ~InsertPointHighlight() {}
  45072. void setTargetPosition (TreeViewItem* const item, int insertIndex, const int x, const int y, const int width) throw()
  45073. {
  45074. lastItem = item;
  45075. lastIndex = insertIndex;
  45076. const int offset = getHeight() / 2;
  45077. setBounds (x - offset, y - offset, width - (x - offset), getHeight());
  45078. }
  45079. void paint (Graphics& g)
  45080. {
  45081. Path p;
  45082. const float h = (float) getHeight();
  45083. p.addEllipse (2.0f, 2.0f, h - 4.0f, h - 4.0f);
  45084. p.startNewSubPath (h - 2.0f, h / 2.0f);
  45085. p.lineTo ((float) getWidth(), h / 2.0f);
  45086. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  45087. g.strokePath (p, PathStrokeType (2.0f));
  45088. }
  45089. TreeViewItem* lastItem;
  45090. int lastIndex;
  45091. private:
  45092. InsertPointHighlight (const InsertPointHighlight&);
  45093. InsertPointHighlight& operator= (const InsertPointHighlight&);
  45094. };
  45095. class TreeView::TargetGroupHighlight : public Component
  45096. {
  45097. public:
  45098. TargetGroupHighlight()
  45099. {
  45100. setAlwaysOnTop (true);
  45101. setInterceptsMouseClicks (false, false);
  45102. }
  45103. ~TargetGroupHighlight() {}
  45104. void setTargetPosition (TreeViewItem* const item) throw()
  45105. {
  45106. Rectangle<int> r (item->getItemPosition (true));
  45107. r.setHeight (item->getItemHeight());
  45108. setBounds (r);
  45109. }
  45110. void paint (Graphics& g)
  45111. {
  45112. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  45113. g.drawRoundedRectangle (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 3.0f, 2.0f);
  45114. }
  45115. private:
  45116. TargetGroupHighlight (const TargetGroupHighlight&);
  45117. TargetGroupHighlight& operator= (const TargetGroupHighlight&);
  45118. };
  45119. void TreeView::showDragHighlight (TreeViewItem* item, int insertIndex, int x, int y) throw()
  45120. {
  45121. beginDragAutoRepeat (1000 / 30);
  45122. if (dragInsertPointHighlight == 0)
  45123. {
  45124. addAndMakeVisible (dragInsertPointHighlight = new InsertPointHighlight());
  45125. addAndMakeVisible (dragTargetGroupHighlight = new TargetGroupHighlight());
  45126. }
  45127. dragInsertPointHighlight->setTargetPosition (item, insertIndex, x, y, viewport->getViewWidth());
  45128. dragTargetGroupHighlight->setTargetPosition (item);
  45129. }
  45130. void TreeView::hideDragHighlight() throw()
  45131. {
  45132. dragInsertPointHighlight = 0;
  45133. dragTargetGroupHighlight = 0;
  45134. }
  45135. TreeViewItem* TreeView::getInsertPosition (int& x, int& y, int& insertIndex,
  45136. const StringArray& files, const String& sourceDescription,
  45137. Component* sourceComponent) const throw()
  45138. {
  45139. insertIndex = 0;
  45140. TreeViewItem* item = getItemAt (y);
  45141. if (item == 0)
  45142. return 0;
  45143. Rectangle<int> itemPos (item->getItemPosition (true));
  45144. insertIndex = item->getIndexInParent();
  45145. const int oldY = y;
  45146. y = itemPos.getY();
  45147. if (item->getNumSubItems() == 0 || ! item->isOpen())
  45148. {
  45149. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  45150. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45151. {
  45152. // Check if we're trying to drag into an empty group item..
  45153. if (oldY > itemPos.getY() + itemPos.getHeight() / 4
  45154. && oldY < itemPos.getBottom() - itemPos.getHeight() / 4)
  45155. {
  45156. insertIndex = 0;
  45157. x = itemPos.getX() + getIndentSize();
  45158. y = itemPos.getBottom();
  45159. return item;
  45160. }
  45161. }
  45162. }
  45163. if (oldY > itemPos.getCentreY())
  45164. {
  45165. y += item->getItemHeight();
  45166. while (item->isLastOfSiblings() && item->parentItem != 0
  45167. && item->parentItem->parentItem != 0)
  45168. {
  45169. if (x > itemPos.getX())
  45170. break;
  45171. item = item->parentItem;
  45172. itemPos = item->getItemPosition (true);
  45173. insertIndex = item->getIndexInParent();
  45174. }
  45175. ++insertIndex;
  45176. }
  45177. x = itemPos.getX();
  45178. return item->parentItem;
  45179. }
  45180. void TreeView::handleDrag (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  45181. {
  45182. const bool scrolled = viewport->autoScroll (x, y, 20, 10);
  45183. int insertIndex;
  45184. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  45185. if (item != 0)
  45186. {
  45187. if (scrolled || dragInsertPointHighlight == 0
  45188. || dragInsertPointHighlight->lastItem != item
  45189. || dragInsertPointHighlight->lastIndex != insertIndex)
  45190. {
  45191. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  45192. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45193. showDragHighlight (item, insertIndex, x, y);
  45194. else
  45195. hideDragHighlight();
  45196. }
  45197. }
  45198. else
  45199. {
  45200. hideDragHighlight();
  45201. }
  45202. }
  45203. void TreeView::handleDrop (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  45204. {
  45205. hideDragHighlight();
  45206. int insertIndex;
  45207. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  45208. if (item != 0)
  45209. {
  45210. if (files.size() > 0)
  45211. {
  45212. if (item->isInterestedInFileDrag (files))
  45213. item->filesDropped (files, insertIndex);
  45214. }
  45215. else
  45216. {
  45217. if (item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45218. item->itemDropped (sourceDescription, sourceComponent, insertIndex);
  45219. }
  45220. }
  45221. }
  45222. bool TreeView::isInterestedInFileDrag (const StringArray&)
  45223. {
  45224. return true;
  45225. }
  45226. void TreeView::fileDragEnter (const StringArray& files, int x, int y)
  45227. {
  45228. fileDragMove (files, x, y);
  45229. }
  45230. void TreeView::fileDragMove (const StringArray& files, int x, int y)
  45231. {
  45232. handleDrag (files, String::empty, 0, x, y);
  45233. }
  45234. void TreeView::fileDragExit (const StringArray&)
  45235. {
  45236. hideDragHighlight();
  45237. }
  45238. void TreeView::filesDropped (const StringArray& files, int x, int y)
  45239. {
  45240. handleDrop (files, String::empty, 0, x, y);
  45241. }
  45242. bool TreeView::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45243. {
  45244. return true;
  45245. }
  45246. void TreeView::itemDragEnter (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45247. {
  45248. itemDragMove (sourceDescription, sourceComponent, x, y);
  45249. }
  45250. void TreeView::itemDragMove (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45251. {
  45252. handleDrag (StringArray(), sourceDescription, sourceComponent, x, y);
  45253. }
  45254. void TreeView::itemDragExit (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45255. {
  45256. hideDragHighlight();
  45257. }
  45258. void TreeView::itemDropped (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45259. {
  45260. handleDrop (StringArray(), sourceDescription, sourceComponent, x, y);
  45261. }
  45262. enum TreeViewOpenness
  45263. {
  45264. opennessDefault = 0,
  45265. opennessClosed = 1,
  45266. opennessOpen = 2
  45267. };
  45268. TreeViewItem::TreeViewItem()
  45269. : ownerView (0),
  45270. parentItem (0),
  45271. y (0),
  45272. itemHeight (0),
  45273. totalHeight (0),
  45274. selected (false),
  45275. redrawNeeded (true),
  45276. drawLinesInside (true),
  45277. drawsInLeftMargin (false),
  45278. openness (opennessDefault)
  45279. {
  45280. static int nextUID = 0;
  45281. uid = nextUID++;
  45282. }
  45283. TreeViewItem::~TreeViewItem()
  45284. {
  45285. }
  45286. const String TreeViewItem::getUniqueName() const
  45287. {
  45288. return String::empty;
  45289. }
  45290. void TreeViewItem::itemOpennessChanged (bool)
  45291. {
  45292. }
  45293. int TreeViewItem::getNumSubItems() const throw()
  45294. {
  45295. return subItems.size();
  45296. }
  45297. TreeViewItem* TreeViewItem::getSubItem (const int index) const throw()
  45298. {
  45299. return subItems [index];
  45300. }
  45301. void TreeViewItem::clearSubItems()
  45302. {
  45303. if (subItems.size() > 0)
  45304. {
  45305. if (ownerView != 0)
  45306. {
  45307. const ScopedLock sl (ownerView->nodeAlterationLock);
  45308. subItems.clear();
  45309. treeHasChanged();
  45310. }
  45311. else
  45312. {
  45313. subItems.clear();
  45314. }
  45315. }
  45316. }
  45317. void TreeViewItem::addSubItem (TreeViewItem* const newItem, const int insertPosition)
  45318. {
  45319. if (newItem != 0)
  45320. {
  45321. newItem->parentItem = this;
  45322. newItem->setOwnerView (ownerView);
  45323. newItem->y = 0;
  45324. newItem->itemHeight = newItem->getItemHeight();
  45325. newItem->totalHeight = 0;
  45326. newItem->itemWidth = newItem->getItemWidth();
  45327. newItem->totalWidth = 0;
  45328. if (ownerView != 0)
  45329. {
  45330. const ScopedLock sl (ownerView->nodeAlterationLock);
  45331. subItems.insert (insertPosition, newItem);
  45332. treeHasChanged();
  45333. if (newItem->isOpen())
  45334. newItem->itemOpennessChanged (true);
  45335. }
  45336. else
  45337. {
  45338. subItems.insert (insertPosition, newItem);
  45339. if (newItem->isOpen())
  45340. newItem->itemOpennessChanged (true);
  45341. }
  45342. }
  45343. }
  45344. void TreeViewItem::removeSubItem (const int index, const bool deleteItem)
  45345. {
  45346. if (ownerView != 0)
  45347. {
  45348. const ScopedLock sl (ownerView->nodeAlterationLock);
  45349. if (((unsigned int) index) < (unsigned int) subItems.size())
  45350. {
  45351. subItems.remove (index, deleteItem);
  45352. treeHasChanged();
  45353. }
  45354. }
  45355. else
  45356. {
  45357. subItems.remove (index, deleteItem);
  45358. }
  45359. }
  45360. bool TreeViewItem::isOpen() const throw()
  45361. {
  45362. if (openness == opennessDefault)
  45363. return ownerView != 0 && ownerView->defaultOpenness;
  45364. else
  45365. return openness == opennessOpen;
  45366. }
  45367. void TreeViewItem::setOpen (const bool shouldBeOpen)
  45368. {
  45369. if (isOpen() != shouldBeOpen)
  45370. {
  45371. openness = shouldBeOpen ? opennessOpen
  45372. : opennessClosed;
  45373. treeHasChanged();
  45374. itemOpennessChanged (isOpen());
  45375. }
  45376. }
  45377. bool TreeViewItem::isSelected() const throw()
  45378. {
  45379. return selected;
  45380. }
  45381. void TreeViewItem::deselectAllRecursively()
  45382. {
  45383. setSelected (false, false);
  45384. for (int i = 0; i < subItems.size(); ++i)
  45385. subItems.getUnchecked(i)->deselectAllRecursively();
  45386. }
  45387. void TreeViewItem::setSelected (const bool shouldBeSelected,
  45388. const bool deselectOtherItemsFirst)
  45389. {
  45390. if (shouldBeSelected && ! canBeSelected())
  45391. return;
  45392. if (deselectOtherItemsFirst)
  45393. getTopLevelItem()->deselectAllRecursively();
  45394. if (shouldBeSelected != selected)
  45395. {
  45396. selected = shouldBeSelected;
  45397. if (ownerView != 0)
  45398. ownerView->repaint();
  45399. itemSelectionChanged (shouldBeSelected);
  45400. }
  45401. }
  45402. void TreeViewItem::paintItem (Graphics&, int, int)
  45403. {
  45404. }
  45405. void TreeViewItem::paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver)
  45406. {
  45407. ownerView->getLookAndFeel()
  45408. .drawTreeviewPlusMinusBox (g, 0, 0, width, height, ! isOpen(), isMouseOver);
  45409. }
  45410. void TreeViewItem::itemClicked (const MouseEvent&)
  45411. {
  45412. }
  45413. void TreeViewItem::itemDoubleClicked (const MouseEvent&)
  45414. {
  45415. if (mightContainSubItems())
  45416. setOpen (! isOpen());
  45417. }
  45418. void TreeViewItem::itemSelectionChanged (bool)
  45419. {
  45420. }
  45421. const String TreeViewItem::getTooltip()
  45422. {
  45423. return String::empty;
  45424. }
  45425. const String TreeViewItem::getDragSourceDescription()
  45426. {
  45427. return String::empty;
  45428. }
  45429. bool TreeViewItem::isInterestedInFileDrag (const StringArray&)
  45430. {
  45431. return false;
  45432. }
  45433. void TreeViewItem::filesDropped (const StringArray& /*files*/, int /*insertIndex*/)
  45434. {
  45435. }
  45436. bool TreeViewItem::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45437. {
  45438. return false;
  45439. }
  45440. void TreeViewItem::itemDropped (const String& /*sourceDescription*/, Component* /*sourceComponent*/, int /*insertIndex*/)
  45441. {
  45442. }
  45443. const Rectangle<int> TreeViewItem::getItemPosition (const bool relativeToTreeViewTopLeft) const throw()
  45444. {
  45445. const int indentX = getIndentX();
  45446. int width = itemWidth;
  45447. if (ownerView != 0 && width < 0)
  45448. width = ownerView->viewport->getViewWidth() - indentX;
  45449. Rectangle<int> r (indentX, y, jmax (0, width), totalHeight);
  45450. if (relativeToTreeViewTopLeft)
  45451. r -= ownerView->viewport->getViewPosition();
  45452. return r;
  45453. }
  45454. void TreeViewItem::treeHasChanged() const throw()
  45455. {
  45456. if (ownerView != 0)
  45457. ownerView->itemsChanged();
  45458. }
  45459. void TreeViewItem::repaintItem() const
  45460. {
  45461. if (ownerView != 0 && areAllParentsOpen())
  45462. {
  45463. Rectangle<int> r (getItemPosition (true));
  45464. r.setLeft (0);
  45465. ownerView->viewport->repaint (r);
  45466. }
  45467. }
  45468. bool TreeViewItem::areAllParentsOpen() const throw()
  45469. {
  45470. return parentItem == 0
  45471. || (parentItem->isOpen() && parentItem->areAllParentsOpen());
  45472. }
  45473. void TreeViewItem::updatePositions (int newY)
  45474. {
  45475. y = newY;
  45476. itemHeight = getItemHeight();
  45477. totalHeight = itemHeight;
  45478. itemWidth = getItemWidth();
  45479. totalWidth = jmax (itemWidth, 0) + getIndentX();
  45480. if (isOpen())
  45481. {
  45482. newY += totalHeight;
  45483. for (int i = 0; i < subItems.size(); ++i)
  45484. {
  45485. TreeViewItem* const ti = subItems.getUnchecked(i);
  45486. ti->updatePositions (newY);
  45487. newY += ti->totalHeight;
  45488. totalHeight += ti->totalHeight;
  45489. totalWidth = jmax (totalWidth, ti->totalWidth);
  45490. }
  45491. }
  45492. }
  45493. TreeViewItem* TreeViewItem::getDeepestOpenParentItem() throw()
  45494. {
  45495. TreeViewItem* result = this;
  45496. TreeViewItem* item = this;
  45497. while (item->parentItem != 0)
  45498. {
  45499. item = item->parentItem;
  45500. if (! item->isOpen())
  45501. result = item;
  45502. }
  45503. return result;
  45504. }
  45505. void TreeViewItem::setOwnerView (TreeView* const newOwner) throw()
  45506. {
  45507. ownerView = newOwner;
  45508. for (int i = subItems.size(); --i >= 0;)
  45509. subItems.getUnchecked(i)->setOwnerView (newOwner);
  45510. }
  45511. int TreeViewItem::getIndentX() const throw()
  45512. {
  45513. const int indentWidth = ownerView->getIndentSize();
  45514. int x = ownerView->rootItemVisible ? indentWidth : 0;
  45515. if (! ownerView->openCloseButtonsVisible)
  45516. x -= indentWidth;
  45517. TreeViewItem* p = parentItem;
  45518. while (p != 0)
  45519. {
  45520. x += indentWidth;
  45521. p = p->parentItem;
  45522. }
  45523. return x;
  45524. }
  45525. void TreeViewItem::setDrawsInLeftMargin (bool canDrawInLeftMargin) throw()
  45526. {
  45527. drawsInLeftMargin = canDrawInLeftMargin;
  45528. }
  45529. void TreeViewItem::paintRecursively (Graphics& g, int width)
  45530. {
  45531. jassert (ownerView != 0);
  45532. if (ownerView == 0)
  45533. return;
  45534. const int indent = getIndentX();
  45535. const int itemW = itemWidth < 0 ? width - indent : itemWidth;
  45536. g.setColour (ownerView->findColour (TreeView::linesColourId));
  45537. const float halfH = itemHeight * 0.5f;
  45538. int depth = 0;
  45539. TreeViewItem* p = parentItem;
  45540. while (p != 0)
  45541. {
  45542. ++depth;
  45543. p = p->parentItem;
  45544. }
  45545. if (! ownerView->rootItemVisible)
  45546. --depth;
  45547. const int indentWidth = ownerView->getIndentSize();
  45548. if (depth >= 0 && ownerView->openCloseButtonsVisible)
  45549. {
  45550. float x = (depth + 0.5f) * indentWidth;
  45551. if (depth >= 0)
  45552. {
  45553. if (parentItem != 0 && parentItem->drawLinesInside)
  45554. g.drawLine (x, 0, x, isLastOfSiblings() ? halfH : (float) itemHeight);
  45555. if ((parentItem != 0 && parentItem->drawLinesInside)
  45556. || (parentItem == 0 && drawLinesInside))
  45557. g.drawLine (x, halfH, x + indentWidth / 2, halfH);
  45558. }
  45559. p = parentItem;
  45560. int d = depth;
  45561. while (p != 0 && --d >= 0)
  45562. {
  45563. x -= (float) indentWidth;
  45564. if ((p->parentItem == 0 || p->parentItem->drawLinesInside)
  45565. && ! p->isLastOfSiblings())
  45566. {
  45567. g.drawLine (x, 0, x, (float) itemHeight);
  45568. }
  45569. p = p->parentItem;
  45570. }
  45571. if (mightContainSubItems())
  45572. {
  45573. g.saveState();
  45574. g.setOrigin (depth * indentWidth, 0);
  45575. g.reduceClipRegion (0, 0, indentWidth, itemHeight);
  45576. paintOpenCloseButton (g, indentWidth, itemHeight,
  45577. static_cast <TreeViewContentComponent*> (ownerView->viewport->getViewedComponent())
  45578. ->isMouseOverButton (this));
  45579. g.restoreState();
  45580. }
  45581. }
  45582. {
  45583. g.saveState();
  45584. g.setOrigin (indent, 0);
  45585. if (g.reduceClipRegion (drawsInLeftMargin ? -indent : 0, 0,
  45586. drawsInLeftMargin ? itemW + indent : itemW, itemHeight))
  45587. paintItem (g, itemW, itemHeight);
  45588. g.restoreState();
  45589. }
  45590. if (isOpen())
  45591. {
  45592. const Rectangle<int> clip (g.getClipBounds());
  45593. for (int i = 0; i < subItems.size(); ++i)
  45594. {
  45595. TreeViewItem* const ti = subItems.getUnchecked(i);
  45596. const int relY = ti->y - y;
  45597. if (relY >= clip.getBottom())
  45598. break;
  45599. if (relY + ti->totalHeight >= clip.getY())
  45600. {
  45601. g.saveState();
  45602. g.setOrigin (0, relY);
  45603. if (g.reduceClipRegion (0, 0, width, ti->totalHeight))
  45604. ti->paintRecursively (g, width);
  45605. g.restoreState();
  45606. }
  45607. }
  45608. }
  45609. }
  45610. bool TreeViewItem::isLastOfSiblings() const throw()
  45611. {
  45612. return parentItem == 0
  45613. || parentItem->subItems.getLast() == this;
  45614. }
  45615. int TreeViewItem::getIndexInParent() const throw()
  45616. {
  45617. if (parentItem == 0)
  45618. return 0;
  45619. return parentItem->subItems.indexOf (this);
  45620. }
  45621. TreeViewItem* TreeViewItem::getTopLevelItem() throw()
  45622. {
  45623. return (parentItem == 0) ? this
  45624. : parentItem->getTopLevelItem();
  45625. }
  45626. int TreeViewItem::getNumRows() const throw()
  45627. {
  45628. int num = 1;
  45629. if (isOpen())
  45630. {
  45631. for (int i = subItems.size(); --i >= 0;)
  45632. num += subItems.getUnchecked(i)->getNumRows();
  45633. }
  45634. return num;
  45635. }
  45636. TreeViewItem* TreeViewItem::getItemOnRow (int index) throw()
  45637. {
  45638. if (index == 0)
  45639. return this;
  45640. if (index > 0 && isOpen())
  45641. {
  45642. --index;
  45643. for (int i = 0; i < subItems.size(); ++i)
  45644. {
  45645. TreeViewItem* const item = subItems.getUnchecked(i);
  45646. if (index == 0)
  45647. return item;
  45648. const int numRows = item->getNumRows();
  45649. if (numRows > index)
  45650. return item->getItemOnRow (index);
  45651. index -= numRows;
  45652. }
  45653. }
  45654. return 0;
  45655. }
  45656. TreeViewItem* TreeViewItem::findItemRecursively (int targetY) throw()
  45657. {
  45658. if (((unsigned int) targetY) < (unsigned int) totalHeight)
  45659. {
  45660. const int h = itemHeight;
  45661. if (targetY < h)
  45662. return this;
  45663. if (isOpen())
  45664. {
  45665. targetY -= h;
  45666. for (int i = 0; i < subItems.size(); ++i)
  45667. {
  45668. TreeViewItem* const ti = subItems.getUnchecked(i);
  45669. if (targetY < ti->totalHeight)
  45670. return ti->findItemRecursively (targetY);
  45671. targetY -= ti->totalHeight;
  45672. }
  45673. }
  45674. }
  45675. return 0;
  45676. }
  45677. int TreeViewItem::countSelectedItemsRecursively() const throw()
  45678. {
  45679. int total = 0;
  45680. if (isSelected())
  45681. ++total;
  45682. for (int i = subItems.size(); --i >= 0;)
  45683. total += subItems.getUnchecked(i)->countSelectedItemsRecursively();
  45684. return total;
  45685. }
  45686. TreeViewItem* TreeViewItem::getSelectedItemWithIndex (int index) throw()
  45687. {
  45688. if (isSelected())
  45689. {
  45690. if (index == 0)
  45691. return this;
  45692. --index;
  45693. }
  45694. if (index >= 0)
  45695. {
  45696. for (int i = 0; i < subItems.size(); ++i)
  45697. {
  45698. TreeViewItem* const item = subItems.getUnchecked(i);
  45699. TreeViewItem* const found = item->getSelectedItemWithIndex (index);
  45700. if (found != 0)
  45701. return found;
  45702. index -= item->countSelectedItemsRecursively();
  45703. }
  45704. }
  45705. return 0;
  45706. }
  45707. int TreeViewItem::getRowNumberInTree() const throw()
  45708. {
  45709. if (parentItem != 0 && ownerView != 0)
  45710. {
  45711. int n = 1 + parentItem->getRowNumberInTree();
  45712. int ourIndex = parentItem->subItems.indexOf (this);
  45713. jassert (ourIndex >= 0);
  45714. while (--ourIndex >= 0)
  45715. n += parentItem->subItems [ourIndex]->getNumRows();
  45716. if (parentItem->parentItem == 0
  45717. && ! ownerView->rootItemVisible)
  45718. --n;
  45719. return n;
  45720. }
  45721. else
  45722. {
  45723. return 0;
  45724. }
  45725. }
  45726. void TreeViewItem::setLinesDrawnForSubItems (const bool drawLines) throw()
  45727. {
  45728. drawLinesInside = drawLines;
  45729. }
  45730. TreeViewItem* TreeViewItem::getNextVisibleItem (const bool recurse) const throw()
  45731. {
  45732. if (recurse && isOpen() && subItems.size() > 0)
  45733. return subItems [0];
  45734. if (parentItem != 0)
  45735. {
  45736. const int nextIndex = parentItem->subItems.indexOf (this) + 1;
  45737. if (nextIndex >= parentItem->subItems.size())
  45738. return parentItem->getNextVisibleItem (false);
  45739. return parentItem->subItems [nextIndex];
  45740. }
  45741. return 0;
  45742. }
  45743. const String TreeViewItem::getItemIdentifierString() const
  45744. {
  45745. String s;
  45746. if (parentItem != 0)
  45747. s = parentItem->getItemIdentifierString();
  45748. return s + "/" + getUniqueName().replaceCharacter ('/', '\\');
  45749. }
  45750. TreeViewItem* TreeViewItem::findItemFromIdentifierString (const String& identifierString)
  45751. {
  45752. const String thisId (getUniqueName());
  45753. if (thisId == identifierString)
  45754. return this;
  45755. if (identifierString.startsWith (thisId + "/"))
  45756. {
  45757. const String remainingPath (identifierString.substring (thisId.length() + 1));
  45758. bool wasOpen = isOpen();
  45759. setOpen (true);
  45760. for (int i = subItems.size(); --i >= 0;)
  45761. {
  45762. TreeViewItem* item = subItems.getUnchecked(i)->findItemFromIdentifierString (remainingPath);
  45763. if (item != 0)
  45764. return item;
  45765. }
  45766. setOpen (wasOpen);
  45767. }
  45768. return 0;
  45769. }
  45770. void TreeViewItem::restoreOpennessState (const XmlElement& e) throw()
  45771. {
  45772. if (e.hasTagName ("CLOSED"))
  45773. {
  45774. setOpen (false);
  45775. }
  45776. else if (e.hasTagName ("OPEN"))
  45777. {
  45778. setOpen (true);
  45779. forEachXmlChildElement (e, n)
  45780. {
  45781. const String id (n->getStringAttribute ("id"));
  45782. for (int i = 0; i < subItems.size(); ++i)
  45783. {
  45784. TreeViewItem* const ti = subItems.getUnchecked(i);
  45785. if (ti->getUniqueName() == id)
  45786. {
  45787. ti->restoreOpennessState (*n);
  45788. break;
  45789. }
  45790. }
  45791. }
  45792. }
  45793. }
  45794. XmlElement* TreeViewItem::getOpennessState() const throw()
  45795. {
  45796. const String name (getUniqueName());
  45797. if (name.isNotEmpty())
  45798. {
  45799. XmlElement* e;
  45800. if (isOpen())
  45801. {
  45802. e = new XmlElement ("OPEN");
  45803. for (int i = 0; i < subItems.size(); ++i)
  45804. e->addChildElement (subItems.getUnchecked(i)->getOpennessState());
  45805. }
  45806. else
  45807. {
  45808. e = new XmlElement ("CLOSED");
  45809. }
  45810. e->setAttribute ("id", name);
  45811. return e;
  45812. }
  45813. else
  45814. {
  45815. // trying to save the openness for an element that has no name - this won't
  45816. // work because it needs the names to identify what to open.
  45817. jassertfalse;
  45818. }
  45819. return 0;
  45820. }
  45821. END_JUCE_NAMESPACE
  45822. /*** End of inlined file: juce_TreeView.cpp ***/
  45823. /*** Start of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  45824. BEGIN_JUCE_NAMESPACE
  45825. DirectoryContentsDisplayComponent::DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow)
  45826. : fileList (listToShow)
  45827. {
  45828. }
  45829. DirectoryContentsDisplayComponent::~DirectoryContentsDisplayComponent()
  45830. {
  45831. }
  45832. FileBrowserListener::~FileBrowserListener()
  45833. {
  45834. }
  45835. void DirectoryContentsDisplayComponent::addListener (FileBrowserListener* const listener)
  45836. {
  45837. listeners.add (listener);
  45838. }
  45839. void DirectoryContentsDisplayComponent::removeListener (FileBrowserListener* const listener)
  45840. {
  45841. listeners.remove (listener);
  45842. }
  45843. void DirectoryContentsDisplayComponent::sendSelectionChangeMessage()
  45844. {
  45845. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  45846. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  45847. }
  45848. void DirectoryContentsDisplayComponent::sendMouseClickMessage (const File& file, const MouseEvent& e)
  45849. {
  45850. if (fileList.getDirectory().exists())
  45851. {
  45852. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  45853. listeners.callChecked (checker, &FileBrowserListener::fileClicked, file, e);
  45854. }
  45855. }
  45856. void DirectoryContentsDisplayComponent::sendDoubleClickMessage (const File& file)
  45857. {
  45858. if (fileList.getDirectory().exists())
  45859. {
  45860. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  45861. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, file);
  45862. }
  45863. }
  45864. END_JUCE_NAMESPACE
  45865. /*** End of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  45866. /*** Start of inlined file: juce_DirectoryContentsList.cpp ***/
  45867. BEGIN_JUCE_NAMESPACE
  45868. DirectoryContentsList::DirectoryContentsList (const FileFilter* const fileFilter_,
  45869. TimeSliceThread& thread_)
  45870. : fileFilter (fileFilter_),
  45871. thread (thread_),
  45872. fileTypeFlags (File::ignoreHiddenFiles | File::findFiles),
  45873. fileFindHandle (0),
  45874. shouldStop (true)
  45875. {
  45876. }
  45877. DirectoryContentsList::~DirectoryContentsList()
  45878. {
  45879. clear();
  45880. }
  45881. void DirectoryContentsList::setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles)
  45882. {
  45883. setTypeFlags (shouldIgnoreHiddenFiles ? (fileTypeFlags | File::ignoreHiddenFiles)
  45884. : (fileTypeFlags & ~File::ignoreHiddenFiles));
  45885. }
  45886. bool DirectoryContentsList::ignoresHiddenFiles() const
  45887. {
  45888. return (fileTypeFlags & File::ignoreHiddenFiles) != 0;
  45889. }
  45890. const File& DirectoryContentsList::getDirectory() const
  45891. {
  45892. return root;
  45893. }
  45894. void DirectoryContentsList::setDirectory (const File& directory,
  45895. const bool includeDirectories,
  45896. const bool includeFiles)
  45897. {
  45898. jassert (includeDirectories || includeFiles); // you have to speciify at least one of these!
  45899. if (directory != root)
  45900. {
  45901. clear();
  45902. root = directory;
  45903. // (this forces a refresh when setTypeFlags() is called, rather than triggering two refreshes)
  45904. fileTypeFlags &= ~(File::findDirectories | File::findFiles);
  45905. }
  45906. int newFlags = fileTypeFlags;
  45907. if (includeDirectories) newFlags |= File::findDirectories; else newFlags &= ~File::findDirectories;
  45908. if (includeFiles) newFlags |= File::findFiles; else newFlags &= ~File::findFiles;
  45909. setTypeFlags (newFlags);
  45910. }
  45911. void DirectoryContentsList::setTypeFlags (const int newFlags)
  45912. {
  45913. if (fileTypeFlags != newFlags)
  45914. {
  45915. fileTypeFlags = newFlags;
  45916. refresh();
  45917. }
  45918. }
  45919. void DirectoryContentsList::clear()
  45920. {
  45921. shouldStop = true;
  45922. thread.removeTimeSliceClient (this);
  45923. fileFindHandle = 0;
  45924. if (files.size() > 0)
  45925. {
  45926. files.clear();
  45927. changed();
  45928. }
  45929. }
  45930. void DirectoryContentsList::refresh()
  45931. {
  45932. clear();
  45933. if (root.isDirectory())
  45934. {
  45935. fileFindHandle = new DirectoryIterator (root, false, "*", fileTypeFlags);
  45936. shouldStop = false;
  45937. thread.addTimeSliceClient (this);
  45938. }
  45939. }
  45940. int DirectoryContentsList::getNumFiles() const
  45941. {
  45942. return files.size();
  45943. }
  45944. bool DirectoryContentsList::getFileInfo (const int index,
  45945. FileInfo& result) const
  45946. {
  45947. const ScopedLock sl (fileListLock);
  45948. const FileInfo* const info = files [index];
  45949. if (info != 0)
  45950. {
  45951. result = *info;
  45952. return true;
  45953. }
  45954. return false;
  45955. }
  45956. const File DirectoryContentsList::getFile (const int index) const
  45957. {
  45958. const ScopedLock sl (fileListLock);
  45959. const FileInfo* const info = files [index];
  45960. if (info != 0)
  45961. return root.getChildFile (info->filename);
  45962. return File::nonexistent;
  45963. }
  45964. bool DirectoryContentsList::isStillLoading() const
  45965. {
  45966. return fileFindHandle != 0;
  45967. }
  45968. void DirectoryContentsList::changed()
  45969. {
  45970. sendChangeMessage (this);
  45971. }
  45972. bool DirectoryContentsList::useTimeSlice()
  45973. {
  45974. const uint32 startTime = Time::getApproximateMillisecondCounter();
  45975. bool hasChanged = false;
  45976. for (int i = 100; --i >= 0;)
  45977. {
  45978. if (! checkNextFile (hasChanged))
  45979. {
  45980. if (hasChanged)
  45981. changed();
  45982. return false;
  45983. }
  45984. if (shouldStop || (Time::getApproximateMillisecondCounter() > startTime + 150))
  45985. break;
  45986. }
  45987. if (hasChanged)
  45988. changed();
  45989. return true;
  45990. }
  45991. bool DirectoryContentsList::checkNextFile (bool& hasChanged)
  45992. {
  45993. if (fileFindHandle != 0)
  45994. {
  45995. bool fileFoundIsDir, isHidden, isReadOnly;
  45996. int64 fileSize;
  45997. Time modTime, creationTime;
  45998. if (fileFindHandle->next (&fileFoundIsDir, &isHidden, &fileSize,
  45999. &modTime, &creationTime, &isReadOnly))
  46000. {
  46001. if (addFile (fileFindHandle->getFile(), fileFoundIsDir,
  46002. fileSize, modTime, creationTime, isReadOnly))
  46003. {
  46004. hasChanged = true;
  46005. }
  46006. return true;
  46007. }
  46008. else
  46009. {
  46010. fileFindHandle = 0;
  46011. }
  46012. }
  46013. return false;
  46014. }
  46015. int DirectoryContentsList::compareElements (const DirectoryContentsList::FileInfo* const first,
  46016. const DirectoryContentsList::FileInfo* const second)
  46017. {
  46018. #if JUCE_WINDOWS
  46019. if (first->isDirectory != second->isDirectory)
  46020. return first->isDirectory ? -1 : 1;
  46021. #endif
  46022. return first->filename.compareIgnoreCase (second->filename);
  46023. }
  46024. bool DirectoryContentsList::addFile (const File& file,
  46025. const bool isDir,
  46026. const int64 fileSize,
  46027. const Time& modTime,
  46028. const Time& creationTime,
  46029. const bool isReadOnly)
  46030. {
  46031. if (fileFilter == 0
  46032. || ((! isDir) && fileFilter->isFileSuitable (file))
  46033. || (isDir && fileFilter->isDirectorySuitable (file)))
  46034. {
  46035. ScopedPointer <FileInfo> info (new FileInfo());
  46036. info->filename = file.getFileName();
  46037. info->fileSize = fileSize;
  46038. info->modificationTime = modTime;
  46039. info->creationTime = creationTime;
  46040. info->isDirectory = isDir;
  46041. info->isReadOnly = isReadOnly;
  46042. const ScopedLock sl (fileListLock);
  46043. for (int i = files.size(); --i >= 0;)
  46044. if (files.getUnchecked(i)->filename == info->filename)
  46045. return false;
  46046. files.addSorted (*this, info.release());
  46047. return true;
  46048. }
  46049. return false;
  46050. }
  46051. END_JUCE_NAMESPACE
  46052. /*** End of inlined file: juce_DirectoryContentsList.cpp ***/
  46053. /*** Start of inlined file: juce_FileBrowserComponent.cpp ***/
  46054. BEGIN_JUCE_NAMESPACE
  46055. FileBrowserComponent::FileBrowserComponent (int flags_,
  46056. const File& initialFileOrDirectory,
  46057. const FileFilter* fileFilter_,
  46058. FilePreviewComponent* previewComp_)
  46059. : FileFilter (String::empty),
  46060. fileFilter (fileFilter_),
  46061. flags (flags_),
  46062. previewComp (previewComp_),
  46063. thread ("Juce FileBrowser")
  46064. {
  46065. // You need to specify one or other of the open/save flags..
  46066. jassert ((flags & (saveMode | openMode)) != 0);
  46067. jassert ((flags & (saveMode | openMode)) != (saveMode | openMode));
  46068. // You need to specify at least one of these flags..
  46069. jassert ((flags & (canSelectFiles | canSelectDirectories)) != 0);
  46070. String filename;
  46071. if (initialFileOrDirectory == File::nonexistent)
  46072. {
  46073. currentRoot = File::getCurrentWorkingDirectory();
  46074. }
  46075. else if (initialFileOrDirectory.isDirectory())
  46076. {
  46077. currentRoot = initialFileOrDirectory;
  46078. }
  46079. else
  46080. {
  46081. chosenFiles.add (initialFileOrDirectory);
  46082. currentRoot = initialFileOrDirectory.getParentDirectory();
  46083. filename = initialFileOrDirectory.getFileName();
  46084. }
  46085. fileList = new DirectoryContentsList (this, thread);
  46086. if ((flags & useTreeView) != 0)
  46087. {
  46088. FileTreeComponent* const tree = new FileTreeComponent (*fileList);
  46089. if ((flags & canSelectMultipleItems) != 0)
  46090. tree->setMultiSelectEnabled (true);
  46091. addAndMakeVisible (tree);
  46092. fileListComponent = tree;
  46093. }
  46094. else
  46095. {
  46096. FileListComponent* const list = new FileListComponent (*fileList);
  46097. list->setOutlineThickness (1);
  46098. if ((flags & canSelectMultipleItems) != 0)
  46099. list->setMultipleSelectionEnabled (true);
  46100. addAndMakeVisible (list);
  46101. fileListComponent = list;
  46102. }
  46103. fileListComponent->addListener (this);
  46104. addAndMakeVisible (currentPathBox = new ComboBox ("path"));
  46105. currentPathBox->setEditableText (true);
  46106. StringArray rootNames, rootPaths;
  46107. const BigInteger separators (getRoots (rootNames, rootPaths));
  46108. for (int i = 0; i < rootNames.size(); ++i)
  46109. {
  46110. if (separators [i])
  46111. currentPathBox->addSeparator();
  46112. currentPathBox->addItem (rootNames[i], i + 1);
  46113. }
  46114. currentPathBox->addSeparator();
  46115. currentPathBox->addListener (this);
  46116. addAndMakeVisible (filenameBox = new TextEditor());
  46117. filenameBox->setMultiLine (false);
  46118. filenameBox->setSelectAllWhenFocused (true);
  46119. filenameBox->setText (filename, false);
  46120. filenameBox->addListener (this);
  46121. filenameBox->setReadOnly ((flags & (filenameBoxIsReadOnly | canSelectMultipleItems)) != 0);
  46122. Label* label = new Label ("f", TRANS("file:"));
  46123. addAndMakeVisible (label);
  46124. label->attachToComponent (filenameBox, true);
  46125. addAndMakeVisible (goUpButton = getLookAndFeel().createFileBrowserGoUpButton());
  46126. goUpButton->addButtonListener (this);
  46127. goUpButton->setTooltip (TRANS ("go up to parent directory"));
  46128. if (previewComp != 0)
  46129. addAndMakeVisible (previewComp);
  46130. setRoot (currentRoot);
  46131. thread.startThread (4);
  46132. }
  46133. FileBrowserComponent::~FileBrowserComponent()
  46134. {
  46135. if (previewComp != 0)
  46136. removeChildComponent (previewComp);
  46137. deleteAllChildren();
  46138. fileList = 0;
  46139. thread.stopThread (10000);
  46140. }
  46141. void FileBrowserComponent::addListener (FileBrowserListener* const newListener)
  46142. {
  46143. listeners.add (newListener);
  46144. }
  46145. void FileBrowserComponent::removeListener (FileBrowserListener* const listener)
  46146. {
  46147. listeners.remove (listener);
  46148. }
  46149. bool FileBrowserComponent::isSaveMode() const throw()
  46150. {
  46151. return (flags & saveMode) != 0;
  46152. }
  46153. int FileBrowserComponent::getNumSelectedFiles() const throw()
  46154. {
  46155. if (chosenFiles.size() == 0 && currentFileIsValid())
  46156. return 1;
  46157. return chosenFiles.size();
  46158. }
  46159. const File FileBrowserComponent::getSelectedFile (int index) const throw()
  46160. {
  46161. if ((flags & canSelectDirectories) != 0 && filenameBox->getText().isEmpty())
  46162. return currentRoot;
  46163. if (! filenameBox->isReadOnly())
  46164. return currentRoot.getChildFile (filenameBox->getText());
  46165. return chosenFiles[index];
  46166. }
  46167. bool FileBrowserComponent::currentFileIsValid() const
  46168. {
  46169. if (isSaveMode())
  46170. return ! getSelectedFile (0).isDirectory();
  46171. else
  46172. return getSelectedFile (0).exists();
  46173. }
  46174. const File FileBrowserComponent::getHighlightedFile() const throw()
  46175. {
  46176. return fileListComponent->getSelectedFile (0);
  46177. }
  46178. void FileBrowserComponent::deselectAllFiles()
  46179. {
  46180. fileListComponent->deselectAllFiles();
  46181. }
  46182. bool FileBrowserComponent::isFileSuitable (const File& file) const
  46183. {
  46184. return (flags & canSelectFiles) != 0 ? (fileFilter == 0 || fileFilter->isFileSuitable (file))
  46185. : false;
  46186. }
  46187. bool FileBrowserComponent::isDirectorySuitable (const File&) const
  46188. {
  46189. return true;
  46190. }
  46191. bool FileBrowserComponent::isFileOrDirSuitable (const File& f) const
  46192. {
  46193. if (f.isDirectory())
  46194. return (flags & canSelectDirectories) != 0 && (fileFilter == 0 || fileFilter->isDirectorySuitable (f));
  46195. return (flags & canSelectFiles) != 0 && f.exists()
  46196. && (fileFilter == 0 || fileFilter->isFileSuitable (f));
  46197. }
  46198. const File FileBrowserComponent::getRoot() const
  46199. {
  46200. return currentRoot;
  46201. }
  46202. void FileBrowserComponent::setRoot (const File& newRootDirectory)
  46203. {
  46204. if (currentRoot != newRootDirectory)
  46205. {
  46206. fileListComponent->scrollToTop();
  46207. String path (newRootDirectory.getFullPathName());
  46208. if (path.isEmpty())
  46209. path = File::separatorString;
  46210. StringArray rootNames, rootPaths;
  46211. getRoots (rootNames, rootPaths);
  46212. if (! rootPaths.contains (path, true))
  46213. {
  46214. bool alreadyListed = false;
  46215. for (int i = currentPathBox->getNumItems(); --i >= 0;)
  46216. {
  46217. if (currentPathBox->getItemText (i).equalsIgnoreCase (path))
  46218. {
  46219. alreadyListed = true;
  46220. break;
  46221. }
  46222. }
  46223. if (! alreadyListed)
  46224. currentPathBox->addItem (path, currentPathBox->getNumItems() + 2);
  46225. }
  46226. }
  46227. currentRoot = newRootDirectory;
  46228. fileList->setDirectory (currentRoot, true, true);
  46229. String currentRootName (currentRoot.getFullPathName());
  46230. if (currentRootName.isEmpty())
  46231. currentRootName = File::separatorString;
  46232. currentPathBox->setText (currentRootName, true);
  46233. goUpButton->setEnabled (currentRoot.getParentDirectory().isDirectory()
  46234. && currentRoot.getParentDirectory() != currentRoot);
  46235. }
  46236. void FileBrowserComponent::goUp()
  46237. {
  46238. setRoot (getRoot().getParentDirectory());
  46239. }
  46240. void FileBrowserComponent::refresh()
  46241. {
  46242. fileList->refresh();
  46243. }
  46244. const String FileBrowserComponent::getActionVerb() const
  46245. {
  46246. return isSaveMode() ? TRANS("Save") : TRANS("Open");
  46247. }
  46248. FilePreviewComponent* FileBrowserComponent::getPreviewComponent() const throw()
  46249. {
  46250. return previewComp;
  46251. }
  46252. void FileBrowserComponent::resized()
  46253. {
  46254. getLookAndFeel()
  46255. .layoutFileBrowserComponent (*this, fileListComponent,
  46256. previewComp, currentPathBox,
  46257. filenameBox, goUpButton);
  46258. }
  46259. void FileBrowserComponent::sendListenerChangeMessage()
  46260. {
  46261. Component::BailOutChecker checker (this);
  46262. if (previewComp != 0)
  46263. previewComp->selectedFileChanged (getSelectedFile (0));
  46264. // You shouldn't delete the browser when the file gets changed!
  46265. jassert (! checker.shouldBailOut());
  46266. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  46267. }
  46268. void FileBrowserComponent::selectionChanged()
  46269. {
  46270. StringArray newFilenames;
  46271. bool resetChosenFiles = true;
  46272. for (int i = 0; i < fileListComponent->getNumSelectedFiles(); ++i)
  46273. {
  46274. const File f (fileListComponent->getSelectedFile (i));
  46275. if (isFileOrDirSuitable (f))
  46276. {
  46277. if (resetChosenFiles)
  46278. {
  46279. chosenFiles.clear();
  46280. resetChosenFiles = false;
  46281. }
  46282. chosenFiles.add (f);
  46283. newFilenames.add (f.getRelativePathFrom (getRoot()));
  46284. }
  46285. }
  46286. if (newFilenames.size() > 0)
  46287. filenameBox->setText (newFilenames.joinIntoString (", "), false);
  46288. sendListenerChangeMessage();
  46289. }
  46290. void FileBrowserComponent::fileClicked (const File& f, const MouseEvent& e)
  46291. {
  46292. Component::BailOutChecker checker (this);
  46293. listeners.callChecked (checker, &FileBrowserListener::fileClicked, f, e);
  46294. }
  46295. void FileBrowserComponent::fileDoubleClicked (const File& f)
  46296. {
  46297. if (f.isDirectory())
  46298. {
  46299. setRoot (f);
  46300. if ((flags & canSelectDirectories) != 0)
  46301. filenameBox->setText (String::empty);
  46302. }
  46303. else
  46304. {
  46305. Component::BailOutChecker checker (this);
  46306. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, f);
  46307. }
  46308. }
  46309. bool FileBrowserComponent::keyPressed (const KeyPress& key)
  46310. {
  46311. (void) key;
  46312. #if JUCE_LINUX || JUCE_WINDOWS
  46313. if (key.getModifiers().isCommandDown()
  46314. && (key.getKeyCode() == 'H' || key.getKeyCode() == 'h'))
  46315. {
  46316. fileList->setIgnoresHiddenFiles (! fileList->ignoresHiddenFiles());
  46317. fileList->refresh();
  46318. return true;
  46319. }
  46320. #endif
  46321. return false;
  46322. }
  46323. void FileBrowserComponent::textEditorTextChanged (TextEditor&)
  46324. {
  46325. sendListenerChangeMessage();
  46326. }
  46327. void FileBrowserComponent::textEditorReturnKeyPressed (TextEditor&)
  46328. {
  46329. if (filenameBox->getText().containsChar (File::separator))
  46330. {
  46331. const File f (currentRoot.getChildFile (filenameBox->getText()));
  46332. if (f.isDirectory())
  46333. {
  46334. setRoot (f);
  46335. chosenFiles.clear();
  46336. filenameBox->setText (String::empty);
  46337. }
  46338. else
  46339. {
  46340. setRoot (f.getParentDirectory());
  46341. chosenFiles.clear();
  46342. chosenFiles.add (f);
  46343. filenameBox->setText (f.getFileName());
  46344. }
  46345. }
  46346. else
  46347. {
  46348. fileDoubleClicked (getSelectedFile (0));
  46349. }
  46350. }
  46351. void FileBrowserComponent::textEditorEscapeKeyPressed (TextEditor&)
  46352. {
  46353. }
  46354. void FileBrowserComponent::textEditorFocusLost (TextEditor&)
  46355. {
  46356. if (! isSaveMode())
  46357. selectionChanged();
  46358. }
  46359. void FileBrowserComponent::buttonClicked (Button*)
  46360. {
  46361. goUp();
  46362. }
  46363. void FileBrowserComponent::comboBoxChanged (ComboBox*)
  46364. {
  46365. const String newText (currentPathBox->getText().trim().unquoted());
  46366. if (newText.isNotEmpty())
  46367. {
  46368. const int index = currentPathBox->getSelectedId() - 1;
  46369. StringArray rootNames, rootPaths;
  46370. getRoots (rootNames, rootPaths);
  46371. if (rootPaths [index].isNotEmpty())
  46372. {
  46373. setRoot (File (rootPaths [index]));
  46374. }
  46375. else
  46376. {
  46377. File f (newText);
  46378. for (;;)
  46379. {
  46380. if (f.isDirectory())
  46381. {
  46382. setRoot (f);
  46383. break;
  46384. }
  46385. if (f.getParentDirectory() == f)
  46386. break;
  46387. f = f.getParentDirectory();
  46388. }
  46389. }
  46390. }
  46391. }
  46392. const BigInteger FileBrowserComponent::getRoots (StringArray& rootNames, StringArray& rootPaths)
  46393. {
  46394. BigInteger separators;
  46395. #if JUCE_WINDOWS
  46396. Array<File> roots;
  46397. File::findFileSystemRoots (roots);
  46398. rootPaths.clear();
  46399. for (int i = 0; i < roots.size(); ++i)
  46400. {
  46401. const File& drive = roots.getReference(i);
  46402. String name (drive.getFullPathName());
  46403. rootPaths.add (name);
  46404. if (drive.isOnHardDisk())
  46405. {
  46406. String volume (drive.getVolumeLabel());
  46407. if (volume.isEmpty())
  46408. volume = TRANS("Hard Drive");
  46409. name << " [" << drive.getVolumeLabel() << ']';
  46410. }
  46411. else if (drive.isOnCDRomDrive())
  46412. {
  46413. name << TRANS(" [CD/DVD drive]");
  46414. }
  46415. rootNames.add (name);
  46416. }
  46417. separators.setBit (rootPaths.size());
  46418. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  46419. rootNames.add ("Documents");
  46420. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46421. rootNames.add ("Desktop");
  46422. #endif
  46423. #if JUCE_MAC
  46424. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  46425. rootNames.add ("Home folder");
  46426. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  46427. rootNames.add ("Documents");
  46428. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46429. rootNames.add ("Desktop");
  46430. separators.setBit (rootPaths.size());
  46431. Array <File> volumes;
  46432. File vol ("/Volumes");
  46433. vol.findChildFiles (volumes, File::findDirectories, false);
  46434. for (int i = 0; i < volumes.size(); ++i)
  46435. {
  46436. const File& volume = volumes.getReference(i);
  46437. if (volume.isDirectory() && ! volume.getFileName().startsWithChar ('.'))
  46438. {
  46439. rootPaths.add (volume.getFullPathName());
  46440. rootNames.add (volume.getFileName());
  46441. }
  46442. }
  46443. #endif
  46444. #if JUCE_LINUX
  46445. rootPaths.add ("/");
  46446. rootNames.add ("/");
  46447. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  46448. rootNames.add ("Home folder");
  46449. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46450. rootNames.add ("Desktop");
  46451. #endif
  46452. return separators;
  46453. }
  46454. END_JUCE_NAMESPACE
  46455. /*** End of inlined file: juce_FileBrowserComponent.cpp ***/
  46456. /*** Start of inlined file: juce_FileChooser.cpp ***/
  46457. BEGIN_JUCE_NAMESPACE
  46458. FileChooser::FileChooser (const String& chooserBoxTitle,
  46459. const File& currentFileOrDirectory,
  46460. const String& fileFilters,
  46461. const bool useNativeDialogBox_)
  46462. : title (chooserBoxTitle),
  46463. filters (fileFilters),
  46464. startingFile (currentFileOrDirectory),
  46465. useNativeDialogBox (useNativeDialogBox_)
  46466. {
  46467. #if JUCE_LINUX
  46468. useNativeDialogBox = false;
  46469. #endif
  46470. if (! fileFilters.containsNonWhitespaceChars())
  46471. filters = "*";
  46472. }
  46473. FileChooser::~FileChooser()
  46474. {
  46475. }
  46476. bool FileChooser::browseForFileToOpen (FilePreviewComponent* previewComponent)
  46477. {
  46478. return showDialog (false, true, false, false, false, previewComponent);
  46479. }
  46480. bool FileChooser::browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent)
  46481. {
  46482. return showDialog (false, true, false, false, true, previewComponent);
  46483. }
  46484. bool FileChooser::browseForMultipleFilesOrDirectories (FilePreviewComponent* previewComponent)
  46485. {
  46486. return showDialog (true, true, false, false, true, previewComponent);
  46487. }
  46488. bool FileChooser::browseForFileToSave (const bool warnAboutOverwritingExistingFiles)
  46489. {
  46490. return showDialog (false, true, true, warnAboutOverwritingExistingFiles, false, 0);
  46491. }
  46492. bool FileChooser::browseForDirectory()
  46493. {
  46494. return showDialog (true, false, false, false, false, 0);
  46495. }
  46496. const File FileChooser::getResult() const
  46497. {
  46498. // if you've used a multiple-file select, you should use the getResults() method
  46499. // to retrieve all the files that were chosen.
  46500. jassert (results.size() <= 1);
  46501. return results.getFirst();
  46502. }
  46503. const Array<File>& FileChooser::getResults() const
  46504. {
  46505. return results;
  46506. }
  46507. bool FileChooser::showDialog (const bool selectsDirectories,
  46508. const bool selectsFiles,
  46509. const bool isSave,
  46510. const bool warnAboutOverwritingExistingFiles,
  46511. const bool selectMultipleFiles,
  46512. FilePreviewComponent* const previewComponent)
  46513. {
  46514. Component::SafePointer<Component> previouslyFocused (Component::getCurrentlyFocusedComponent());
  46515. results.clear();
  46516. // the preview component needs to be the right size before you pass it in here..
  46517. jassert (previewComponent == 0 || (previewComponent->getWidth() > 10
  46518. && previewComponent->getHeight() > 10));
  46519. #if JUCE_WINDOWS
  46520. if (useNativeDialogBox && ! (selectsFiles && selectsDirectories))
  46521. #elif JUCE_MAC
  46522. if (useNativeDialogBox && (previewComponent == 0))
  46523. #else
  46524. if (false)
  46525. #endif
  46526. {
  46527. showPlatformDialog (results, title, startingFile, filters,
  46528. selectsDirectories, selectsFiles, isSave,
  46529. warnAboutOverwritingExistingFiles,
  46530. selectMultipleFiles,
  46531. previewComponent);
  46532. }
  46533. else
  46534. {
  46535. WildcardFileFilter wildcard (selectsFiles ? filters : String::empty,
  46536. selectsDirectories ? "*" : String::empty,
  46537. String::empty);
  46538. int flags = isSave ? FileBrowserComponent::saveMode
  46539. : FileBrowserComponent::openMode;
  46540. if (selectsFiles)
  46541. flags |= FileBrowserComponent::canSelectFiles;
  46542. if (selectsDirectories)
  46543. {
  46544. flags |= FileBrowserComponent::canSelectDirectories;
  46545. if (! isSave)
  46546. flags |= FileBrowserComponent::filenameBoxIsReadOnly;
  46547. }
  46548. if (selectMultipleFiles)
  46549. flags |= FileBrowserComponent::canSelectMultipleItems;
  46550. FileBrowserComponent browserComponent (flags, startingFile, &wildcard, previewComponent);
  46551. FileChooserDialogBox box (title, String::empty,
  46552. browserComponent,
  46553. warnAboutOverwritingExistingFiles,
  46554. browserComponent.findColour (AlertWindow::backgroundColourId));
  46555. if (box.show())
  46556. {
  46557. for (int i = 0; i < browserComponent.getNumSelectedFiles(); ++i)
  46558. results.add (browserComponent.getSelectedFile (i));
  46559. }
  46560. }
  46561. if (previouslyFocused != 0)
  46562. previouslyFocused->grabKeyboardFocus();
  46563. return results.size() > 0;
  46564. }
  46565. FilePreviewComponent::FilePreviewComponent()
  46566. {
  46567. }
  46568. FilePreviewComponent::~FilePreviewComponent()
  46569. {
  46570. }
  46571. END_JUCE_NAMESPACE
  46572. /*** End of inlined file: juce_FileChooser.cpp ***/
  46573. /*** Start of inlined file: juce_FileChooserDialogBox.cpp ***/
  46574. BEGIN_JUCE_NAMESPACE
  46575. FileChooserDialogBox::FileChooserDialogBox (const String& name,
  46576. const String& instructions,
  46577. FileBrowserComponent& chooserComponent,
  46578. const bool warnAboutOverwritingExistingFiles_,
  46579. const Colour& backgroundColour)
  46580. : ResizableWindow (name, backgroundColour, true),
  46581. warnAboutOverwritingExistingFiles (warnAboutOverwritingExistingFiles_)
  46582. {
  46583. content = new ContentComponent();
  46584. content->setName (name);
  46585. content->instructions = instructions;
  46586. content->chooserComponent = &chooserComponent;
  46587. content->addAndMakeVisible (&chooserComponent);
  46588. content->okButton = new TextButton (chooserComponent.getActionVerb());
  46589. content->addAndMakeVisible (content->okButton);
  46590. content->okButton->addButtonListener (this);
  46591. content->okButton->setEnabled (chooserComponent.currentFileIsValid());
  46592. content->okButton->addShortcut (KeyPress (KeyPress::returnKey, 0, 0));
  46593. content->cancelButton = new TextButton (TRANS("Cancel"));
  46594. content->addAndMakeVisible (content->cancelButton);
  46595. content->cancelButton->addButtonListener (this);
  46596. content->cancelButton->addShortcut (KeyPress (KeyPress::escapeKey, 0, 0));
  46597. setContentComponent (content);
  46598. setResizable (true, true);
  46599. setResizeLimits (300, 300, 1200, 1000);
  46600. content->chooserComponent->addListener (this);
  46601. }
  46602. FileChooserDialogBox::~FileChooserDialogBox()
  46603. {
  46604. content->chooserComponent->removeListener (this);
  46605. }
  46606. bool FileChooserDialogBox::show (int w, int h)
  46607. {
  46608. return showAt (-1, -1, w, h);
  46609. }
  46610. bool FileChooserDialogBox::showAt (int x, int y, int w, int h)
  46611. {
  46612. if (w <= 0)
  46613. {
  46614. Component* const previewComp = content->chooserComponent->getPreviewComponent();
  46615. if (previewComp != 0)
  46616. w = 400 + previewComp->getWidth();
  46617. else
  46618. w = 600;
  46619. }
  46620. if (h <= 0)
  46621. h = 500;
  46622. if (x < 0 || y < 0)
  46623. centreWithSize (w, h);
  46624. else
  46625. setBounds (x, y, w, h);
  46626. const bool ok = (runModalLoop() != 0);
  46627. setVisible (false);
  46628. return ok;
  46629. }
  46630. void FileChooserDialogBox::buttonClicked (Button* button)
  46631. {
  46632. if (button == content->okButton)
  46633. {
  46634. if (warnAboutOverwritingExistingFiles
  46635. && content->chooserComponent->isSaveMode()
  46636. && content->chooserComponent->getSelectedFile(0).exists())
  46637. {
  46638. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  46639. TRANS("File already exists"),
  46640. TRANS("There's already a file called:")
  46641. + "\n\n" + content->chooserComponent->getSelectedFile(0).getFullPathName()
  46642. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  46643. TRANS("overwrite"),
  46644. TRANS("cancel")))
  46645. {
  46646. return;
  46647. }
  46648. }
  46649. exitModalState (1);
  46650. }
  46651. else if (button == content->cancelButton)
  46652. closeButtonPressed();
  46653. }
  46654. void FileChooserDialogBox::closeButtonPressed()
  46655. {
  46656. setVisible (false);
  46657. }
  46658. void FileChooserDialogBox::selectionChanged()
  46659. {
  46660. content->okButton->setEnabled (content->chooserComponent->currentFileIsValid());
  46661. }
  46662. void FileChooserDialogBox::fileClicked (const File&, const MouseEvent&)
  46663. {
  46664. }
  46665. void FileChooserDialogBox::fileDoubleClicked (const File&)
  46666. {
  46667. selectionChanged();
  46668. content->okButton->triggerClick();
  46669. }
  46670. FileChooserDialogBox::ContentComponent::ContentComponent()
  46671. {
  46672. setInterceptsMouseClicks (false, true);
  46673. }
  46674. FileChooserDialogBox::ContentComponent::~ContentComponent()
  46675. {
  46676. delete okButton;
  46677. delete cancelButton;
  46678. }
  46679. void FileChooserDialogBox::ContentComponent::paint (Graphics& g)
  46680. {
  46681. g.setColour (getLookAndFeel().findColour (FileChooserDialogBox::titleTextColourId));
  46682. text.draw (g);
  46683. }
  46684. void FileChooserDialogBox::ContentComponent::resized()
  46685. {
  46686. getLookAndFeel().createFileChooserHeaderText (getName(), instructions, text, getWidth());
  46687. const Rectangle<float> bb (text.getBoundingBox (0, text.getNumGlyphs(), false));
  46688. const int y = roundToInt (bb.getBottom()) + 10;
  46689. const int buttonHeight = 26;
  46690. const int buttonY = getHeight() - buttonHeight - 8;
  46691. chooserComponent->setBounds (0, y, getWidth(), buttonY - y - 20);
  46692. okButton->setBounds (proportionOfWidth (0.25f), buttonY,
  46693. proportionOfWidth (0.2f), buttonHeight);
  46694. cancelButton->setBounds (proportionOfWidth (0.55f), buttonY,
  46695. proportionOfWidth (0.2f), buttonHeight);
  46696. }
  46697. END_JUCE_NAMESPACE
  46698. /*** End of inlined file: juce_FileChooserDialogBox.cpp ***/
  46699. /*** Start of inlined file: juce_FileFilter.cpp ***/
  46700. BEGIN_JUCE_NAMESPACE
  46701. FileFilter::FileFilter (const String& filterDescription)
  46702. : description (filterDescription)
  46703. {
  46704. }
  46705. FileFilter::~FileFilter()
  46706. {
  46707. }
  46708. const String& FileFilter::getDescription() const throw()
  46709. {
  46710. return description;
  46711. }
  46712. END_JUCE_NAMESPACE
  46713. /*** End of inlined file: juce_FileFilter.cpp ***/
  46714. /*** Start of inlined file: juce_FileListComponent.cpp ***/
  46715. BEGIN_JUCE_NAMESPACE
  46716. const Image juce_createIconForFile (const File& file);
  46717. FileListComponent::FileListComponent (DirectoryContentsList& listToShow)
  46718. : ListBox (String::empty, 0),
  46719. DirectoryContentsDisplayComponent (listToShow)
  46720. {
  46721. setModel (this);
  46722. fileList.addChangeListener (this);
  46723. }
  46724. FileListComponent::~FileListComponent()
  46725. {
  46726. fileList.removeChangeListener (this);
  46727. deleteAllChildren();
  46728. }
  46729. int FileListComponent::getNumSelectedFiles() const
  46730. {
  46731. return getNumSelectedRows();
  46732. }
  46733. const File FileListComponent::getSelectedFile (int index) const
  46734. {
  46735. return fileList.getFile (getSelectedRow (index));
  46736. }
  46737. void FileListComponent::deselectAllFiles()
  46738. {
  46739. deselectAllRows();
  46740. }
  46741. void FileListComponent::scrollToTop()
  46742. {
  46743. getVerticalScrollBar()->setCurrentRangeStart (0);
  46744. }
  46745. void FileListComponent::changeListenerCallback (void*)
  46746. {
  46747. updateContent();
  46748. if (lastDirectory != fileList.getDirectory())
  46749. {
  46750. lastDirectory = fileList.getDirectory();
  46751. deselectAllRows();
  46752. }
  46753. }
  46754. class FileListItemComponent : public Component,
  46755. public TimeSliceClient,
  46756. public AsyncUpdater
  46757. {
  46758. public:
  46759. FileListItemComponent (FileListComponent& owner_, TimeSliceThread& thread_)
  46760. : owner (owner_), thread (thread_),
  46761. highlighted (false), index (0), icon (0)
  46762. {
  46763. }
  46764. ~FileListItemComponent()
  46765. {
  46766. thread.removeTimeSliceClient (this);
  46767. clearIcon();
  46768. }
  46769. void paint (Graphics& g)
  46770. {
  46771. getLookAndFeel().drawFileBrowserRow (g, getWidth(), getHeight(),
  46772. file.getFileName(),
  46773. &icon,
  46774. fileSize, modTime,
  46775. isDirectory, highlighted,
  46776. index);
  46777. }
  46778. void mouseDown (const MouseEvent& e)
  46779. {
  46780. owner.selectRowsBasedOnModifierKeys (index, e.mods);
  46781. owner.sendMouseClickMessage (file, e);
  46782. }
  46783. void mouseDoubleClick (const MouseEvent&)
  46784. {
  46785. owner.sendDoubleClickMessage (file);
  46786. }
  46787. void update (const File& root,
  46788. const DirectoryContentsList::FileInfo* const fileInfo,
  46789. const int index_,
  46790. const bool highlighted_)
  46791. {
  46792. thread.removeTimeSliceClient (this);
  46793. if (highlighted_ != highlighted
  46794. || index_ != index)
  46795. {
  46796. index = index_;
  46797. highlighted = highlighted_;
  46798. repaint();
  46799. }
  46800. File newFile;
  46801. String newFileSize;
  46802. String newModTime;
  46803. if (fileInfo != 0)
  46804. {
  46805. newFile = root.getChildFile (fileInfo->filename);
  46806. newFileSize = File::descriptionOfSizeInBytes (fileInfo->fileSize);
  46807. newModTime = fileInfo->modificationTime.formatted ("%d %b '%y %H:%M");
  46808. }
  46809. if (newFile != file
  46810. || fileSize != newFileSize
  46811. || modTime != newModTime)
  46812. {
  46813. file = newFile;
  46814. fileSize = newFileSize;
  46815. modTime = newModTime;
  46816. isDirectory = fileInfo != 0 && fileInfo->isDirectory;
  46817. repaint();
  46818. clearIcon();
  46819. }
  46820. if (file != File::nonexistent && icon.isNull() && ! isDirectory)
  46821. {
  46822. updateIcon (true);
  46823. if (! icon.isValid())
  46824. thread.addTimeSliceClient (this);
  46825. }
  46826. }
  46827. bool useTimeSlice()
  46828. {
  46829. updateIcon (false);
  46830. return false;
  46831. }
  46832. void handleAsyncUpdate()
  46833. {
  46834. repaint();
  46835. }
  46836. juce_UseDebuggingNewOperator
  46837. private:
  46838. FileListComponent& owner;
  46839. TimeSliceThread& thread;
  46840. bool highlighted;
  46841. int index;
  46842. File file;
  46843. String fileSize;
  46844. String modTime;
  46845. Image icon;
  46846. bool isDirectory;
  46847. void clearIcon()
  46848. {
  46849. icon = Image();
  46850. }
  46851. void updateIcon (const bool onlyUpdateIfCached)
  46852. {
  46853. if (icon.isNull())
  46854. {
  46855. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  46856. Image im (ImageCache::getFromHashCode (hashCode));
  46857. if (im.isNull() && ! onlyUpdateIfCached)
  46858. {
  46859. im = juce_createIconForFile (file);
  46860. if (im.isValid())
  46861. ImageCache::addImageToCache (im, hashCode);
  46862. }
  46863. if (im.isValid())
  46864. {
  46865. icon = im;
  46866. triggerAsyncUpdate();
  46867. }
  46868. }
  46869. }
  46870. };
  46871. int FileListComponent::getNumRows()
  46872. {
  46873. return fileList.getNumFiles();
  46874. }
  46875. void FileListComponent::paintListBoxItem (int, Graphics&, int, int, bool)
  46876. {
  46877. }
  46878. Component* FileListComponent::refreshComponentForRow (int row, bool isSelected, Component* existingComponentToUpdate)
  46879. {
  46880. FileListItemComponent* comp = dynamic_cast <FileListItemComponent*> (existingComponentToUpdate);
  46881. if (comp == 0)
  46882. {
  46883. delete existingComponentToUpdate;
  46884. comp = new FileListItemComponent (*this, fileList.getTimeSliceThread());
  46885. }
  46886. DirectoryContentsList::FileInfo fileInfo;
  46887. if (fileList.getFileInfo (row, fileInfo))
  46888. comp->update (fileList.getDirectory(), &fileInfo, row, isSelected);
  46889. else
  46890. comp->update (fileList.getDirectory(), 0, row, isSelected);
  46891. return comp;
  46892. }
  46893. void FileListComponent::selectedRowsChanged (int /*lastRowSelected*/)
  46894. {
  46895. sendSelectionChangeMessage();
  46896. }
  46897. void FileListComponent::deleteKeyPressed (int /*currentSelectedRow*/)
  46898. {
  46899. }
  46900. void FileListComponent::returnKeyPressed (int currentSelectedRow)
  46901. {
  46902. sendDoubleClickMessage (fileList.getFile (currentSelectedRow));
  46903. }
  46904. END_JUCE_NAMESPACE
  46905. /*** End of inlined file: juce_FileListComponent.cpp ***/
  46906. /*** Start of inlined file: juce_FilenameComponent.cpp ***/
  46907. BEGIN_JUCE_NAMESPACE
  46908. FilenameComponent::FilenameComponent (const String& name,
  46909. const File& currentFile,
  46910. const bool canEditFilename,
  46911. const bool isDirectory,
  46912. const bool isForSaving,
  46913. const String& fileBrowserWildcard,
  46914. const String& enforcedSuffix_,
  46915. const String& textWhenNothingSelected)
  46916. : Component (name),
  46917. maxRecentFiles (30),
  46918. isDir (isDirectory),
  46919. isSaving (isForSaving),
  46920. isFileDragOver (false),
  46921. wildcard (fileBrowserWildcard),
  46922. enforcedSuffix (enforcedSuffix_)
  46923. {
  46924. addAndMakeVisible (&filenameBox);
  46925. filenameBox.setEditableText (canEditFilename);
  46926. filenameBox.addListener (this);
  46927. filenameBox.setTextWhenNothingSelected (textWhenNothingSelected);
  46928. filenameBox.setTextWhenNoChoicesAvailable (TRANS("(no recently seleced files)"));
  46929. setBrowseButtonText ("...");
  46930. setCurrentFile (currentFile, true);
  46931. }
  46932. FilenameComponent::~FilenameComponent()
  46933. {
  46934. }
  46935. void FilenameComponent::paintOverChildren (Graphics& g)
  46936. {
  46937. if (isFileDragOver)
  46938. {
  46939. g.setColour (Colours::red.withAlpha (0.2f));
  46940. g.drawRect (0, 0, getWidth(), getHeight(), 3);
  46941. }
  46942. }
  46943. void FilenameComponent::resized()
  46944. {
  46945. getLookAndFeel().layoutFilenameComponent (*this, &filenameBox, browseButton);
  46946. }
  46947. void FilenameComponent::setBrowseButtonText (const String& newBrowseButtonText)
  46948. {
  46949. browseButtonText = newBrowseButtonText;
  46950. lookAndFeelChanged();
  46951. }
  46952. void FilenameComponent::lookAndFeelChanged()
  46953. {
  46954. browseButton = 0;
  46955. addAndMakeVisible (browseButton = getLookAndFeel().createFilenameComponentBrowseButton (browseButtonText));
  46956. browseButton->setConnectedEdges (Button::ConnectedOnLeft);
  46957. resized();
  46958. browseButton->addButtonListener (this);
  46959. }
  46960. void FilenameComponent::setTooltip (const String& newTooltip)
  46961. {
  46962. SettableTooltipClient::setTooltip (newTooltip);
  46963. filenameBox.setTooltip (newTooltip);
  46964. }
  46965. void FilenameComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  46966. {
  46967. defaultBrowseFile = newDefaultDirectory;
  46968. }
  46969. void FilenameComponent::buttonClicked (Button*)
  46970. {
  46971. FileChooser fc (TRANS("Choose a new file"),
  46972. getCurrentFile() == File::nonexistent ? defaultBrowseFile
  46973. : getCurrentFile(),
  46974. wildcard);
  46975. if (isDir ? fc.browseForDirectory()
  46976. : (isSaving ? fc.browseForFileToSave (false)
  46977. : fc.browseForFileToOpen()))
  46978. {
  46979. setCurrentFile (fc.getResult(), true);
  46980. }
  46981. }
  46982. void FilenameComponent::comboBoxChanged (ComboBox*)
  46983. {
  46984. setCurrentFile (getCurrentFile(), true);
  46985. }
  46986. bool FilenameComponent::isInterestedInFileDrag (const StringArray&)
  46987. {
  46988. return true;
  46989. }
  46990. void FilenameComponent::filesDropped (const StringArray& filenames, int, int)
  46991. {
  46992. isFileDragOver = false;
  46993. repaint();
  46994. const File f (filenames[0]);
  46995. if (f.exists() && (f.isDirectory() == isDir))
  46996. setCurrentFile (f, true);
  46997. }
  46998. void FilenameComponent::fileDragEnter (const StringArray&, int, int)
  46999. {
  47000. isFileDragOver = true;
  47001. repaint();
  47002. }
  47003. void FilenameComponent::fileDragExit (const StringArray&)
  47004. {
  47005. isFileDragOver = false;
  47006. repaint();
  47007. }
  47008. const File FilenameComponent::getCurrentFile() const
  47009. {
  47010. File f (filenameBox.getText());
  47011. if (enforcedSuffix.isNotEmpty())
  47012. f = f.withFileExtension (enforcedSuffix);
  47013. return f;
  47014. }
  47015. void FilenameComponent::setCurrentFile (File newFile,
  47016. const bool addToRecentlyUsedList,
  47017. const bool sendChangeNotification)
  47018. {
  47019. if (enforcedSuffix.isNotEmpty())
  47020. newFile = newFile.withFileExtension (enforcedSuffix);
  47021. if (newFile.getFullPathName() != lastFilename)
  47022. {
  47023. lastFilename = newFile.getFullPathName();
  47024. if (addToRecentlyUsedList)
  47025. addRecentlyUsedFile (newFile);
  47026. filenameBox.setText (lastFilename, true);
  47027. if (sendChangeNotification)
  47028. triggerAsyncUpdate();
  47029. }
  47030. }
  47031. void FilenameComponent::setFilenameIsEditable (const bool shouldBeEditable)
  47032. {
  47033. filenameBox.setEditableText (shouldBeEditable);
  47034. }
  47035. const StringArray FilenameComponent::getRecentlyUsedFilenames() const
  47036. {
  47037. StringArray names;
  47038. for (int i = 0; i < filenameBox.getNumItems(); ++i)
  47039. names.add (filenameBox.getItemText (i));
  47040. return names;
  47041. }
  47042. void FilenameComponent::setRecentlyUsedFilenames (const StringArray& filenames)
  47043. {
  47044. if (filenames != getRecentlyUsedFilenames())
  47045. {
  47046. filenameBox.clear();
  47047. for (int i = 0; i < jmin (filenames.size(), maxRecentFiles); ++i)
  47048. filenameBox.addItem (filenames[i], i + 1);
  47049. }
  47050. }
  47051. void FilenameComponent::setMaxNumberOfRecentFiles (const int newMaximum)
  47052. {
  47053. maxRecentFiles = jmax (1, newMaximum);
  47054. setRecentlyUsedFilenames (getRecentlyUsedFilenames());
  47055. }
  47056. void FilenameComponent::addRecentlyUsedFile (const File& file)
  47057. {
  47058. StringArray files (getRecentlyUsedFilenames());
  47059. if (file.getFullPathName().isNotEmpty())
  47060. {
  47061. files.removeString (file.getFullPathName(), true);
  47062. files.insert (0, file.getFullPathName());
  47063. setRecentlyUsedFilenames (files);
  47064. }
  47065. }
  47066. void FilenameComponent::addListener (FilenameComponentListener* const listener)
  47067. {
  47068. listeners.add (listener);
  47069. }
  47070. void FilenameComponent::removeListener (FilenameComponentListener* const listener)
  47071. {
  47072. listeners.remove (listener);
  47073. }
  47074. void FilenameComponent::handleAsyncUpdate()
  47075. {
  47076. Component::BailOutChecker checker (this);
  47077. listeners.callChecked (checker, &FilenameComponentListener::filenameComponentChanged, this);
  47078. }
  47079. END_JUCE_NAMESPACE
  47080. /*** End of inlined file: juce_FilenameComponent.cpp ***/
  47081. /*** Start of inlined file: juce_FileSearchPathListComponent.cpp ***/
  47082. BEGIN_JUCE_NAMESPACE
  47083. FileSearchPathListComponent::FileSearchPathListComponent()
  47084. {
  47085. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  47086. listBox->setColour (ListBox::backgroundColourId, Colours::black.withAlpha (0.02f));
  47087. listBox->setColour (ListBox::outlineColourId, Colours::black.withAlpha (0.1f));
  47088. listBox->setOutlineThickness (1);
  47089. addAndMakeVisible (addButton = new TextButton ("+"));
  47090. addButton->addButtonListener (this);
  47091. addButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  47092. addAndMakeVisible (removeButton = new TextButton ("-"));
  47093. removeButton->addButtonListener (this);
  47094. removeButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  47095. addAndMakeVisible (changeButton = new TextButton (TRANS("change...")));
  47096. changeButton->addButtonListener (this);
  47097. addAndMakeVisible (upButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  47098. upButton->addButtonListener (this);
  47099. {
  47100. Path arrowPath;
  47101. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  47102. DrawablePath arrowImage;
  47103. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  47104. arrowImage.setPath (arrowPath);
  47105. upButton->setImages (&arrowImage);
  47106. }
  47107. addAndMakeVisible (downButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  47108. downButton->addButtonListener (this);
  47109. {
  47110. Path arrowPath;
  47111. arrowPath.addArrow (Line<float> (50.0f, 0.0f, 50.0f, 100.0f), 40.0f, 100.0f, 50.0f);
  47112. DrawablePath arrowImage;
  47113. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  47114. arrowImage.setPath (arrowPath);
  47115. downButton->setImages (&arrowImage);
  47116. }
  47117. updateButtons();
  47118. }
  47119. FileSearchPathListComponent::~FileSearchPathListComponent()
  47120. {
  47121. deleteAllChildren();
  47122. }
  47123. void FileSearchPathListComponent::updateButtons()
  47124. {
  47125. const bool anythingSelected = listBox->getNumSelectedRows() > 0;
  47126. removeButton->setEnabled (anythingSelected);
  47127. changeButton->setEnabled (anythingSelected);
  47128. upButton->setEnabled (anythingSelected);
  47129. downButton->setEnabled (anythingSelected);
  47130. }
  47131. void FileSearchPathListComponent::changed()
  47132. {
  47133. listBox->updateContent();
  47134. listBox->repaint();
  47135. updateButtons();
  47136. }
  47137. void FileSearchPathListComponent::setPath (const FileSearchPath& newPath)
  47138. {
  47139. if (newPath.toString() != path.toString())
  47140. {
  47141. path = newPath;
  47142. changed();
  47143. }
  47144. }
  47145. void FileSearchPathListComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  47146. {
  47147. defaultBrowseTarget = newDefaultDirectory;
  47148. }
  47149. int FileSearchPathListComponent::getNumRows()
  47150. {
  47151. return path.getNumPaths();
  47152. }
  47153. void FileSearchPathListComponent::paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected)
  47154. {
  47155. if (rowIsSelected)
  47156. g.fillAll (findColour (TextEditor::highlightColourId));
  47157. g.setColour (findColour (ListBox::textColourId));
  47158. Font f (height * 0.7f);
  47159. f.setHorizontalScale (0.9f);
  47160. g.setFont (f);
  47161. g.drawText (path [rowNumber].getFullPathName(),
  47162. 4, 0, width - 6, height,
  47163. Justification::centredLeft, true);
  47164. }
  47165. void FileSearchPathListComponent::deleteKeyPressed (int row)
  47166. {
  47167. if (((unsigned int) row) < (unsigned int) path.getNumPaths())
  47168. {
  47169. path.remove (row);
  47170. changed();
  47171. }
  47172. }
  47173. void FileSearchPathListComponent::returnKeyPressed (int row)
  47174. {
  47175. FileChooser chooser (TRANS("Change folder..."), path [row], "*");
  47176. if (chooser.browseForDirectory())
  47177. {
  47178. path.remove (row);
  47179. path.add (chooser.getResult(), row);
  47180. changed();
  47181. }
  47182. }
  47183. void FileSearchPathListComponent::listBoxItemDoubleClicked (int row, const MouseEvent&)
  47184. {
  47185. returnKeyPressed (row);
  47186. }
  47187. void FileSearchPathListComponent::selectedRowsChanged (int)
  47188. {
  47189. updateButtons();
  47190. }
  47191. void FileSearchPathListComponent::paint (Graphics& g)
  47192. {
  47193. g.fillAll (findColour (backgroundColourId));
  47194. }
  47195. void FileSearchPathListComponent::resized()
  47196. {
  47197. const int buttonH = 22;
  47198. const int buttonY = getHeight() - buttonH - 4;
  47199. listBox->setBounds (2, 2, getWidth() - 4, buttonY - 5);
  47200. addButton->setBounds (2, buttonY, buttonH, buttonH);
  47201. removeButton->setBounds (addButton->getRight(), buttonY, buttonH, buttonH);
  47202. changeButton->changeWidthToFitText (buttonH);
  47203. downButton->setSize (buttonH * 2, buttonH);
  47204. upButton->setSize (buttonH * 2, buttonH);
  47205. downButton->setTopRightPosition (getWidth() - 2, buttonY);
  47206. upButton->setTopRightPosition (downButton->getX() - 4, buttonY);
  47207. changeButton->setTopRightPosition (upButton->getX() - 8, buttonY);
  47208. }
  47209. bool FileSearchPathListComponent::isInterestedInFileDrag (const StringArray&)
  47210. {
  47211. return true;
  47212. }
  47213. void FileSearchPathListComponent::filesDropped (const StringArray& filenames, int, int mouseY)
  47214. {
  47215. for (int i = filenames.size(); --i >= 0;)
  47216. {
  47217. const File f (filenames[i]);
  47218. if (f.isDirectory())
  47219. {
  47220. const int row = listBox->getRowContainingPosition (0, mouseY - listBox->getY());
  47221. path.add (f, row);
  47222. changed();
  47223. }
  47224. }
  47225. }
  47226. void FileSearchPathListComponent::buttonClicked (Button* button)
  47227. {
  47228. const int currentRow = listBox->getSelectedRow();
  47229. if (button == removeButton)
  47230. {
  47231. deleteKeyPressed (currentRow);
  47232. }
  47233. else if (button == addButton)
  47234. {
  47235. File start (defaultBrowseTarget);
  47236. if (start == File::nonexistent)
  47237. start = path [0];
  47238. if (start == File::nonexistent)
  47239. start = File::getCurrentWorkingDirectory();
  47240. FileChooser chooser (TRANS("Add a folder..."), start, "*");
  47241. if (chooser.browseForDirectory())
  47242. {
  47243. path.add (chooser.getResult(), currentRow);
  47244. }
  47245. }
  47246. else if (button == changeButton)
  47247. {
  47248. returnKeyPressed (currentRow);
  47249. }
  47250. else if (button == upButton)
  47251. {
  47252. if (currentRow > 0 && currentRow < path.getNumPaths())
  47253. {
  47254. const File f (path[currentRow]);
  47255. path.remove (currentRow);
  47256. path.add (f, currentRow - 1);
  47257. listBox->selectRow (currentRow - 1);
  47258. }
  47259. }
  47260. else if (button == downButton)
  47261. {
  47262. if (currentRow >= 0 && currentRow < path.getNumPaths() - 1)
  47263. {
  47264. const File f (path[currentRow]);
  47265. path.remove (currentRow);
  47266. path.add (f, currentRow + 1);
  47267. listBox->selectRow (currentRow + 1);
  47268. }
  47269. }
  47270. changed();
  47271. }
  47272. END_JUCE_NAMESPACE
  47273. /*** End of inlined file: juce_FileSearchPathListComponent.cpp ***/
  47274. /*** Start of inlined file: juce_FileTreeComponent.cpp ***/
  47275. BEGIN_JUCE_NAMESPACE
  47276. const Image juce_createIconForFile (const File& file);
  47277. class FileListTreeItem : public TreeViewItem,
  47278. public TimeSliceClient,
  47279. public AsyncUpdater,
  47280. public ChangeListener
  47281. {
  47282. public:
  47283. FileListTreeItem (FileTreeComponent& owner_,
  47284. DirectoryContentsList* const parentContentsList_,
  47285. const int indexInContentsList_,
  47286. const File& file_,
  47287. TimeSliceThread& thread_)
  47288. : file (file_),
  47289. owner (owner_),
  47290. parentContentsList (parentContentsList_),
  47291. indexInContentsList (indexInContentsList_),
  47292. subContentsList (0),
  47293. canDeleteSubContentsList (false),
  47294. thread (thread_),
  47295. icon (0)
  47296. {
  47297. DirectoryContentsList::FileInfo fileInfo;
  47298. if (parentContentsList_ != 0
  47299. && parentContentsList_->getFileInfo (indexInContentsList_, fileInfo))
  47300. {
  47301. fileSize = File::descriptionOfSizeInBytes (fileInfo.fileSize);
  47302. modTime = fileInfo.modificationTime.formatted ("%d %b '%y %H:%M");
  47303. isDirectory = fileInfo.isDirectory;
  47304. }
  47305. else
  47306. {
  47307. isDirectory = true;
  47308. }
  47309. }
  47310. ~FileListTreeItem()
  47311. {
  47312. thread.removeTimeSliceClient (this);
  47313. clearSubItems();
  47314. if (canDeleteSubContentsList)
  47315. delete subContentsList;
  47316. }
  47317. bool mightContainSubItems() { return isDirectory; }
  47318. const String getUniqueName() const { return file.getFullPathName(); }
  47319. int getItemHeight() const { return 22; }
  47320. const String getDragSourceDescription() { return owner.getDragAndDropDescription(); }
  47321. void itemOpennessChanged (bool isNowOpen)
  47322. {
  47323. if (isNowOpen)
  47324. {
  47325. clearSubItems();
  47326. isDirectory = file.isDirectory();
  47327. if (isDirectory)
  47328. {
  47329. if (subContentsList == 0)
  47330. {
  47331. jassert (parentContentsList != 0);
  47332. DirectoryContentsList* const l = new DirectoryContentsList (parentContentsList->getFilter(), thread);
  47333. l->setDirectory (file, true, true);
  47334. setSubContentsList (l);
  47335. canDeleteSubContentsList = true;
  47336. }
  47337. changeListenerCallback (0);
  47338. }
  47339. }
  47340. }
  47341. void setSubContentsList (DirectoryContentsList* newList)
  47342. {
  47343. jassert (subContentsList == 0);
  47344. subContentsList = newList;
  47345. newList->addChangeListener (this);
  47346. }
  47347. void changeListenerCallback (void*)
  47348. {
  47349. clearSubItems();
  47350. if (isOpen() && subContentsList != 0)
  47351. {
  47352. for (int i = 0; i < subContentsList->getNumFiles(); ++i)
  47353. {
  47354. FileListTreeItem* const item
  47355. = new FileListTreeItem (owner, subContentsList, i, subContentsList->getFile(i), thread);
  47356. addSubItem (item);
  47357. }
  47358. }
  47359. }
  47360. void paintItem (Graphics& g, int width, int height)
  47361. {
  47362. if (file != File::nonexistent)
  47363. {
  47364. updateIcon (true);
  47365. if (icon.isNull())
  47366. thread.addTimeSliceClient (this);
  47367. }
  47368. owner.getLookAndFeel()
  47369. .drawFileBrowserRow (g, width, height,
  47370. file.getFileName(),
  47371. &icon, fileSize, modTime,
  47372. isDirectory, isSelected(),
  47373. indexInContentsList);
  47374. }
  47375. void itemClicked (const MouseEvent& e)
  47376. {
  47377. owner.sendMouseClickMessage (file, e);
  47378. }
  47379. void itemDoubleClicked (const MouseEvent& e)
  47380. {
  47381. TreeViewItem::itemDoubleClicked (e);
  47382. owner.sendDoubleClickMessage (file);
  47383. }
  47384. void itemSelectionChanged (bool)
  47385. {
  47386. owner.sendSelectionChangeMessage();
  47387. }
  47388. bool useTimeSlice()
  47389. {
  47390. updateIcon (false);
  47391. thread.removeTimeSliceClient (this);
  47392. return false;
  47393. }
  47394. void handleAsyncUpdate()
  47395. {
  47396. owner.repaint();
  47397. }
  47398. const File file;
  47399. juce_UseDebuggingNewOperator
  47400. private:
  47401. FileTreeComponent& owner;
  47402. DirectoryContentsList* parentContentsList;
  47403. int indexInContentsList;
  47404. DirectoryContentsList* subContentsList;
  47405. bool isDirectory, canDeleteSubContentsList;
  47406. TimeSliceThread& thread;
  47407. Image icon;
  47408. String fileSize;
  47409. String modTime;
  47410. void updateIcon (const bool onlyUpdateIfCached)
  47411. {
  47412. if (icon.isNull())
  47413. {
  47414. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  47415. Image im (ImageCache::getFromHashCode (hashCode));
  47416. if (im.isNull() && ! onlyUpdateIfCached)
  47417. {
  47418. im = juce_createIconForFile (file);
  47419. if (im.isValid())
  47420. ImageCache::addImageToCache (im, hashCode);
  47421. }
  47422. if (im.isValid())
  47423. {
  47424. icon = im;
  47425. triggerAsyncUpdate();
  47426. }
  47427. }
  47428. }
  47429. };
  47430. FileTreeComponent::FileTreeComponent (DirectoryContentsList& listToShow)
  47431. : DirectoryContentsDisplayComponent (listToShow)
  47432. {
  47433. FileListTreeItem* const root
  47434. = new FileListTreeItem (*this, 0, 0, listToShow.getDirectory(),
  47435. listToShow.getTimeSliceThread());
  47436. root->setSubContentsList (&listToShow);
  47437. setRootItemVisible (false);
  47438. setRootItem (root);
  47439. }
  47440. FileTreeComponent::~FileTreeComponent()
  47441. {
  47442. deleteRootItem();
  47443. }
  47444. const File FileTreeComponent::getSelectedFile (const int index) const
  47445. {
  47446. const FileListTreeItem* const item = dynamic_cast <const FileListTreeItem*> (getSelectedItem (index));
  47447. return item != 0 ? item->file
  47448. : File::nonexistent;
  47449. }
  47450. void FileTreeComponent::deselectAllFiles()
  47451. {
  47452. clearSelectedItems();
  47453. }
  47454. void FileTreeComponent::scrollToTop()
  47455. {
  47456. getViewport()->getVerticalScrollBar()->setCurrentRangeStart (0);
  47457. }
  47458. void FileTreeComponent::setDragAndDropDescription (const String& description)
  47459. {
  47460. dragAndDropDescription = description;
  47461. }
  47462. END_JUCE_NAMESPACE
  47463. /*** End of inlined file: juce_FileTreeComponent.cpp ***/
  47464. /*** Start of inlined file: juce_ImagePreviewComponent.cpp ***/
  47465. BEGIN_JUCE_NAMESPACE
  47466. ImagePreviewComponent::ImagePreviewComponent()
  47467. {
  47468. }
  47469. ImagePreviewComponent::~ImagePreviewComponent()
  47470. {
  47471. }
  47472. void ImagePreviewComponent::getThumbSize (int& w, int& h) const
  47473. {
  47474. const int availableW = proportionOfWidth (0.97f);
  47475. const int availableH = getHeight() - 13 * 4;
  47476. const double scale = jmin (1.0,
  47477. availableW / (double) w,
  47478. availableH / (double) h);
  47479. w = roundToInt (scale * w);
  47480. h = roundToInt (scale * h);
  47481. }
  47482. void ImagePreviewComponent::selectedFileChanged (const File& file)
  47483. {
  47484. if (fileToLoad != file)
  47485. {
  47486. fileToLoad = file;
  47487. startTimer (100);
  47488. }
  47489. }
  47490. void ImagePreviewComponent::timerCallback()
  47491. {
  47492. stopTimer();
  47493. currentThumbnail = Image();
  47494. currentDetails = String::empty;
  47495. repaint();
  47496. ScopedPointer <FileInputStream> in (fileToLoad.createInputStream());
  47497. if (in != 0)
  47498. {
  47499. ImageFileFormat* const format = ImageFileFormat::findImageFormatForStream (*in);
  47500. if (format != 0)
  47501. {
  47502. currentThumbnail = format->decodeImage (*in);
  47503. if (currentThumbnail.isValid())
  47504. {
  47505. int w = currentThumbnail.getWidth();
  47506. int h = currentThumbnail.getHeight();
  47507. currentDetails
  47508. << fileToLoad.getFileName() << "\n"
  47509. << format->getFormatName() << "\n"
  47510. << w << " x " << h << " pixels\n"
  47511. << File::descriptionOfSizeInBytes (fileToLoad.getSize());
  47512. getThumbSize (w, h);
  47513. currentThumbnail = currentThumbnail.rescaled (w, h);
  47514. }
  47515. }
  47516. }
  47517. }
  47518. void ImagePreviewComponent::paint (Graphics& g)
  47519. {
  47520. if (currentThumbnail.isValid())
  47521. {
  47522. g.setFont (13.0f);
  47523. int w = currentThumbnail.getWidth();
  47524. int h = currentThumbnail.getHeight();
  47525. getThumbSize (w, h);
  47526. const int numLines = 4;
  47527. const int totalH = 13 * numLines + h + 4;
  47528. const int y = (getHeight() - totalH) / 2;
  47529. g.drawImageWithin (currentThumbnail,
  47530. (getWidth() - w) / 2, y, w, h,
  47531. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  47532. false);
  47533. g.drawFittedText (currentDetails,
  47534. 0, y + h + 4, getWidth(), 100,
  47535. Justification::centredTop, numLines);
  47536. }
  47537. }
  47538. END_JUCE_NAMESPACE
  47539. /*** End of inlined file: juce_ImagePreviewComponent.cpp ***/
  47540. /*** Start of inlined file: juce_WildcardFileFilter.cpp ***/
  47541. BEGIN_JUCE_NAMESPACE
  47542. WildcardFileFilter::WildcardFileFilter (const String& fileWildcardPatterns,
  47543. const String& directoryWildcardPatterns,
  47544. const String& description_)
  47545. : FileFilter (description_.isEmpty() ? fileWildcardPatterns
  47546. : (description_ + " (" + fileWildcardPatterns + ")"))
  47547. {
  47548. parse (fileWildcardPatterns, fileWildcards);
  47549. parse (directoryWildcardPatterns, directoryWildcards);
  47550. }
  47551. WildcardFileFilter::~WildcardFileFilter()
  47552. {
  47553. }
  47554. bool WildcardFileFilter::isFileSuitable (const File& file) const
  47555. {
  47556. return match (file, fileWildcards);
  47557. }
  47558. bool WildcardFileFilter::isDirectorySuitable (const File& file) const
  47559. {
  47560. return match (file, directoryWildcards);
  47561. }
  47562. void WildcardFileFilter::parse (const String& pattern, StringArray& result)
  47563. {
  47564. result.addTokens (pattern.toLowerCase(), ";,", "\"'");
  47565. result.trim();
  47566. result.removeEmptyStrings();
  47567. // special case for *.*, because people use it to mean "any file", but it
  47568. // would actually ignore files with no extension.
  47569. for (int i = result.size(); --i >= 0;)
  47570. if (result[i] == "*.*")
  47571. result.set (i, "*");
  47572. }
  47573. bool WildcardFileFilter::match (const File& file, const StringArray& wildcards)
  47574. {
  47575. const String filename (file.getFileName());
  47576. for (int i = wildcards.size(); --i >= 0;)
  47577. if (filename.matchesWildcard (wildcards[i], true))
  47578. return true;
  47579. return false;
  47580. }
  47581. END_JUCE_NAMESPACE
  47582. /*** End of inlined file: juce_WildcardFileFilter.cpp ***/
  47583. /*** Start of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  47584. BEGIN_JUCE_NAMESPACE
  47585. KeyboardFocusTraverser::KeyboardFocusTraverser()
  47586. {
  47587. }
  47588. KeyboardFocusTraverser::~KeyboardFocusTraverser()
  47589. {
  47590. }
  47591. namespace KeyboardFocusHelpers
  47592. {
  47593. // This will sort a set of components, so that they are ordered in terms of
  47594. // left-to-right and then top-to-bottom.
  47595. class ScreenPositionComparator
  47596. {
  47597. public:
  47598. ScreenPositionComparator() {}
  47599. static int compareElements (const Component* const first, const Component* const second)
  47600. {
  47601. int explicitOrder1 = first->getExplicitFocusOrder();
  47602. if (explicitOrder1 <= 0)
  47603. explicitOrder1 = std::numeric_limits<int>::max() / 2;
  47604. int explicitOrder2 = second->getExplicitFocusOrder();
  47605. if (explicitOrder2 <= 0)
  47606. explicitOrder2 = std::numeric_limits<int>::max() / 2;
  47607. if (explicitOrder1 != explicitOrder2)
  47608. return explicitOrder1 - explicitOrder2;
  47609. const int diff = first->getY() - second->getY();
  47610. return (diff == 0) ? first->getX() - second->getX()
  47611. : diff;
  47612. }
  47613. };
  47614. static void findAllFocusableComponents (Component* const parent, Array <Component*>& comps)
  47615. {
  47616. if (parent->getNumChildComponents() > 0)
  47617. {
  47618. Array <Component*> localComps;
  47619. ScreenPositionComparator comparator;
  47620. int i;
  47621. for (i = parent->getNumChildComponents(); --i >= 0;)
  47622. {
  47623. Component* const c = parent->getChildComponent (i);
  47624. if (c->isVisible() && c->isEnabled())
  47625. localComps.addSorted (comparator, c);
  47626. }
  47627. for (i = 0; i < localComps.size(); ++i)
  47628. {
  47629. Component* const c = localComps.getUnchecked (i);
  47630. if (c->getWantsKeyboardFocus())
  47631. comps.add (c);
  47632. if (! c->isFocusContainer())
  47633. findAllFocusableComponents (c, comps);
  47634. }
  47635. }
  47636. }
  47637. }
  47638. static Component* getIncrementedComponent (Component* const current, const int delta)
  47639. {
  47640. Component* focusContainer = current->getParentComponent();
  47641. if (focusContainer != 0)
  47642. {
  47643. while (focusContainer->getParentComponent() != 0 && ! focusContainer->isFocusContainer())
  47644. focusContainer = focusContainer->getParentComponent();
  47645. if (focusContainer != 0)
  47646. {
  47647. Array <Component*> comps;
  47648. KeyboardFocusHelpers::findAllFocusableComponents (focusContainer, comps);
  47649. if (comps.size() > 0)
  47650. {
  47651. const int index = comps.indexOf (current);
  47652. return comps [(index + comps.size() + delta) % comps.size()];
  47653. }
  47654. }
  47655. }
  47656. return 0;
  47657. }
  47658. Component* KeyboardFocusTraverser::getNextComponent (Component* current)
  47659. {
  47660. return getIncrementedComponent (current, 1);
  47661. }
  47662. Component* KeyboardFocusTraverser::getPreviousComponent (Component* current)
  47663. {
  47664. return getIncrementedComponent (current, -1);
  47665. }
  47666. Component* KeyboardFocusTraverser::getDefaultComponent (Component* parentComponent)
  47667. {
  47668. Array <Component*> comps;
  47669. if (parentComponent != 0)
  47670. KeyboardFocusHelpers::findAllFocusableComponents (parentComponent, comps);
  47671. return comps.getFirst();
  47672. }
  47673. END_JUCE_NAMESPACE
  47674. /*** End of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  47675. /*** Start of inlined file: juce_KeyListener.cpp ***/
  47676. BEGIN_JUCE_NAMESPACE
  47677. bool KeyListener::keyStateChanged (const bool, Component*)
  47678. {
  47679. return false;
  47680. }
  47681. END_JUCE_NAMESPACE
  47682. /*** End of inlined file: juce_KeyListener.cpp ***/
  47683. /*** Start of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  47684. BEGIN_JUCE_NAMESPACE
  47685. // N.B. these two includes are put here deliberately to avoid problems with
  47686. // old GCCs failing on long include paths
  47687. const int maxKeys = 3;
  47688. class KeyMappingChangeButton : public Button
  47689. {
  47690. public:
  47691. KeyMappingChangeButton (KeyMappingEditorComponent* const owner_,
  47692. const CommandID commandID_,
  47693. const String& keyName,
  47694. const int keyNum_)
  47695. : Button (keyName),
  47696. owner (owner_),
  47697. commandID (commandID_),
  47698. keyNum (keyNum_)
  47699. {
  47700. setWantsKeyboardFocus (false);
  47701. setTriggeredOnMouseDown (keyNum >= 0);
  47702. if (keyNum_ < 0)
  47703. setTooltip (TRANS("adds a new key-mapping"));
  47704. else
  47705. setTooltip (TRANS("click to change this key-mapping"));
  47706. }
  47707. ~KeyMappingChangeButton()
  47708. {
  47709. }
  47710. void paintButton (Graphics& g, bool /*isOver*/, bool /*isDown*/)
  47711. {
  47712. getLookAndFeel().drawKeymapChangeButton (g, getWidth(), getHeight(), *this,
  47713. keyNum >= 0 ? getName() : String::empty);
  47714. }
  47715. void clicked()
  47716. {
  47717. if (keyNum >= 0)
  47718. {
  47719. // existing key clicked..
  47720. PopupMenu m;
  47721. m.addItem (1, TRANS("change this key-mapping"));
  47722. m.addSeparator();
  47723. m.addItem (2, TRANS("remove this key-mapping"));
  47724. const int res = m.show();
  47725. if (res == 1)
  47726. {
  47727. owner->assignNewKey (commandID, keyNum);
  47728. }
  47729. else if (res == 2)
  47730. {
  47731. owner->getMappings()->removeKeyPress (commandID, keyNum);
  47732. }
  47733. }
  47734. else
  47735. {
  47736. // + button pressed..
  47737. owner->assignNewKey (commandID, -1);
  47738. }
  47739. }
  47740. void fitToContent (const int h) throw()
  47741. {
  47742. if (keyNum < 0)
  47743. {
  47744. setSize (h, h);
  47745. }
  47746. else
  47747. {
  47748. Font f (h * 0.6f);
  47749. setSize (jlimit (h * 4, h * 8, 6 + f.getStringWidth (getName())), h);
  47750. }
  47751. }
  47752. juce_UseDebuggingNewOperator
  47753. private:
  47754. KeyMappingEditorComponent* const owner;
  47755. const CommandID commandID;
  47756. const int keyNum;
  47757. KeyMappingChangeButton (const KeyMappingChangeButton&);
  47758. KeyMappingChangeButton& operator= (const KeyMappingChangeButton&);
  47759. };
  47760. class KeyMappingItemComponent : public Component
  47761. {
  47762. public:
  47763. KeyMappingItemComponent (KeyMappingEditorComponent* const owner_,
  47764. const CommandID commandID_)
  47765. : owner (owner_),
  47766. commandID (commandID_)
  47767. {
  47768. setInterceptsMouseClicks (false, true);
  47769. const bool isReadOnly = owner_->isCommandReadOnly (commandID);
  47770. const Array <KeyPress> keyPresses (owner_->getMappings()->getKeyPressesAssignedToCommand (commandID));
  47771. for (int i = 0; i < jmin (maxKeys, keyPresses.size()); ++i)
  47772. {
  47773. KeyMappingChangeButton* const kb
  47774. = new KeyMappingChangeButton (owner_, commandID,
  47775. owner_->getDescriptionForKeyPress (keyPresses.getReference (i)), i);
  47776. kb->setEnabled (! isReadOnly);
  47777. addAndMakeVisible (kb);
  47778. }
  47779. KeyMappingChangeButton* const kb
  47780. = new KeyMappingChangeButton (owner_, commandID, String::empty, -1);
  47781. addChildComponent (kb);
  47782. kb->setVisible (keyPresses.size() < maxKeys && ! isReadOnly);
  47783. }
  47784. ~KeyMappingItemComponent()
  47785. {
  47786. deleteAllChildren();
  47787. }
  47788. void paint (Graphics& g)
  47789. {
  47790. g.setFont (getHeight() * 0.7f);
  47791. g.setColour (findColour (KeyMappingEditorComponent::textColourId));
  47792. g.drawFittedText (owner->getMappings()->getCommandManager()->getNameOfCommand (commandID),
  47793. 4, 0, jmax (40, getChildComponent (0)->getX() - 5), getHeight(),
  47794. Justification::centredLeft, true);
  47795. }
  47796. void resized()
  47797. {
  47798. int x = getWidth() - 4;
  47799. for (int i = getNumChildComponents(); --i >= 0;)
  47800. {
  47801. KeyMappingChangeButton* const kb = dynamic_cast <KeyMappingChangeButton*> (getChildComponent (i));
  47802. kb->fitToContent (getHeight() - 2);
  47803. kb->setTopRightPosition (x, 1);
  47804. x -= kb->getWidth() + 5;
  47805. }
  47806. }
  47807. juce_UseDebuggingNewOperator
  47808. private:
  47809. KeyMappingEditorComponent* const owner;
  47810. const CommandID commandID;
  47811. KeyMappingItemComponent (const KeyMappingItemComponent&);
  47812. KeyMappingItemComponent& operator= (const KeyMappingItemComponent&);
  47813. };
  47814. class KeyMappingTreeViewItem : public TreeViewItem
  47815. {
  47816. public:
  47817. KeyMappingTreeViewItem (KeyMappingEditorComponent* const owner_,
  47818. const CommandID commandID_)
  47819. : owner (owner_),
  47820. commandID (commandID_)
  47821. {
  47822. }
  47823. ~KeyMappingTreeViewItem()
  47824. {
  47825. }
  47826. const String getUniqueName() const { return String ((int) commandID) + "_id"; }
  47827. bool mightContainSubItems() { return false; }
  47828. int getItemHeight() const { return 20; }
  47829. Component* createItemComponent()
  47830. {
  47831. return new KeyMappingItemComponent (owner, commandID);
  47832. }
  47833. juce_UseDebuggingNewOperator
  47834. private:
  47835. KeyMappingEditorComponent* const owner;
  47836. const CommandID commandID;
  47837. KeyMappingTreeViewItem (const KeyMappingTreeViewItem&);
  47838. KeyMappingTreeViewItem& operator= (const KeyMappingTreeViewItem&);
  47839. };
  47840. class KeyCategoryTreeViewItem : public TreeViewItem
  47841. {
  47842. public:
  47843. KeyCategoryTreeViewItem (KeyMappingEditorComponent* const owner_,
  47844. const String& name)
  47845. : owner (owner_),
  47846. categoryName (name)
  47847. {
  47848. }
  47849. ~KeyCategoryTreeViewItem()
  47850. {
  47851. }
  47852. const String getUniqueName() const { return categoryName + "_cat"; }
  47853. bool mightContainSubItems() { return true; }
  47854. int getItemHeight() const { return 28; }
  47855. void paintItem (Graphics& g, int width, int height)
  47856. {
  47857. g.setFont (height * 0.6f, Font::bold);
  47858. g.setColour (owner->findColour (KeyMappingEditorComponent::textColourId));
  47859. g.drawText (categoryName,
  47860. 2, 0, width - 2, height,
  47861. Justification::centredLeft, true);
  47862. }
  47863. void itemOpennessChanged (bool isNowOpen)
  47864. {
  47865. if (isNowOpen)
  47866. {
  47867. if (getNumSubItems() == 0)
  47868. {
  47869. Array <CommandID> commands (owner->getMappings()->getCommandManager()->getCommandsInCategory (categoryName));
  47870. for (int i = 0; i < commands.size(); ++i)
  47871. {
  47872. if (owner->shouldCommandBeIncluded (commands[i]))
  47873. addSubItem (new KeyMappingTreeViewItem (owner, commands[i]));
  47874. }
  47875. }
  47876. }
  47877. else
  47878. {
  47879. clearSubItems();
  47880. }
  47881. }
  47882. juce_UseDebuggingNewOperator
  47883. private:
  47884. KeyMappingEditorComponent* owner;
  47885. String categoryName;
  47886. KeyCategoryTreeViewItem (const KeyCategoryTreeViewItem&);
  47887. KeyCategoryTreeViewItem& operator= (const KeyCategoryTreeViewItem&);
  47888. };
  47889. KeyMappingEditorComponent::KeyMappingEditorComponent (KeyPressMappingSet* const mappingManager,
  47890. const bool showResetToDefaultButton)
  47891. : mappings (mappingManager)
  47892. {
  47893. jassert (mappingManager != 0); // can't be null!
  47894. mappingManager->addChangeListener (this);
  47895. setLinesDrawnForSubItems (false);
  47896. resetButton = 0;
  47897. if (showResetToDefaultButton)
  47898. {
  47899. addAndMakeVisible (resetButton = new TextButton (TRANS("reset to defaults")));
  47900. resetButton->addButtonListener (this);
  47901. }
  47902. addAndMakeVisible (tree = new TreeView());
  47903. tree->setColour (TreeView::backgroundColourId, findColour (backgroundColourId));
  47904. tree->setRootItemVisible (false);
  47905. tree->setDefaultOpenness (true);
  47906. tree->setRootItem (this);
  47907. }
  47908. KeyMappingEditorComponent::~KeyMappingEditorComponent()
  47909. {
  47910. mappings->removeChangeListener (this);
  47911. deleteAllChildren();
  47912. }
  47913. bool KeyMappingEditorComponent::mightContainSubItems()
  47914. {
  47915. return true;
  47916. }
  47917. const String KeyMappingEditorComponent::getUniqueName() const
  47918. {
  47919. return "keys";
  47920. }
  47921. void KeyMappingEditorComponent::setColours (const Colour& mainBackground,
  47922. const Colour& textColour)
  47923. {
  47924. setColour (backgroundColourId, mainBackground);
  47925. setColour (textColourId, textColour);
  47926. tree->setColour (TreeView::backgroundColourId, mainBackground);
  47927. }
  47928. void KeyMappingEditorComponent::parentHierarchyChanged()
  47929. {
  47930. changeListenerCallback (0);
  47931. }
  47932. void KeyMappingEditorComponent::resized()
  47933. {
  47934. int h = getHeight();
  47935. if (resetButton != 0)
  47936. {
  47937. const int buttonHeight = 20;
  47938. h -= buttonHeight + 8;
  47939. int x = getWidth() - 8;
  47940. resetButton->changeWidthToFitText (buttonHeight);
  47941. resetButton->setTopRightPosition (x, h + 6);
  47942. }
  47943. tree->setBounds (0, 0, getWidth(), h);
  47944. }
  47945. void KeyMappingEditorComponent::buttonClicked (Button* button)
  47946. {
  47947. if (button == resetButton)
  47948. {
  47949. if (AlertWindow::showOkCancelBox (AlertWindow::QuestionIcon,
  47950. TRANS("Reset to defaults"),
  47951. TRANS("Are you sure you want to reset all the key-mappings to their default state?"),
  47952. TRANS("Reset")))
  47953. {
  47954. mappings->resetToDefaultMappings();
  47955. }
  47956. }
  47957. }
  47958. void KeyMappingEditorComponent::changeListenerCallback (void*)
  47959. {
  47960. ScopedPointer <XmlElement> oldOpenness (tree->getOpennessState (true));
  47961. clearSubItems();
  47962. const StringArray categories (mappings->getCommandManager()->getCommandCategories());
  47963. for (int i = 0; i < categories.size(); ++i)
  47964. {
  47965. const Array <CommandID> commands (mappings->getCommandManager()->getCommandsInCategory (categories[i]));
  47966. int count = 0;
  47967. for (int j = 0; j < commands.size(); ++j)
  47968. if (shouldCommandBeIncluded (commands[j]))
  47969. ++count;
  47970. if (count > 0)
  47971. addSubItem (new KeyCategoryTreeViewItem (this, categories[i]));
  47972. }
  47973. if (oldOpenness != 0)
  47974. tree->restoreOpennessState (*oldOpenness);
  47975. }
  47976. class KeyEntryWindow : public AlertWindow
  47977. {
  47978. public:
  47979. KeyEntryWindow (KeyMappingEditorComponent* const owner_)
  47980. : AlertWindow (TRANS("New key-mapping"),
  47981. TRANS("Please press a key combination now..."),
  47982. AlertWindow::NoIcon),
  47983. owner (owner_)
  47984. {
  47985. addButton (TRANS("ok"), 1);
  47986. addButton (TRANS("cancel"), 0);
  47987. // (avoid return + escape keys getting processed by the buttons..)
  47988. for (int i = getNumChildComponents(); --i >= 0;)
  47989. getChildComponent (i)->setWantsKeyboardFocus (false);
  47990. setWantsKeyboardFocus (true);
  47991. grabKeyboardFocus();
  47992. }
  47993. ~KeyEntryWindow()
  47994. {
  47995. }
  47996. bool keyPressed (const KeyPress& key)
  47997. {
  47998. lastPress = key;
  47999. String message (TRANS("Key: ") + owner->getDescriptionForKeyPress (key));
  48000. const CommandID previousCommand = owner->getMappings()->findCommandForKeyPress (key);
  48001. if (previousCommand != 0)
  48002. {
  48003. message << "\n\n"
  48004. << TRANS("(Currently assigned to \"")
  48005. << owner->getMappings()->getCommandManager()->getNameOfCommand (previousCommand)
  48006. << "\")";
  48007. }
  48008. setMessage (message);
  48009. return true;
  48010. }
  48011. bool keyStateChanged (bool)
  48012. {
  48013. return true;
  48014. }
  48015. KeyPress lastPress;
  48016. juce_UseDebuggingNewOperator
  48017. private:
  48018. KeyMappingEditorComponent* owner;
  48019. KeyEntryWindow (const KeyEntryWindow&);
  48020. KeyEntryWindow& operator= (const KeyEntryWindow&);
  48021. };
  48022. void KeyMappingEditorComponent::assignNewKey (const CommandID commandID, const int index)
  48023. {
  48024. KeyEntryWindow entryWindow (this);
  48025. if (entryWindow.runModalLoop() != 0)
  48026. {
  48027. entryWindow.setVisible (false);
  48028. if (entryWindow.lastPress.isValid())
  48029. {
  48030. const CommandID previousCommand = mappings->findCommandForKeyPress (entryWindow.lastPress);
  48031. if (previousCommand != 0)
  48032. {
  48033. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  48034. TRANS("Change key-mapping"),
  48035. TRANS("This key is already assigned to the command \"")
  48036. + mappings->getCommandManager()->getNameOfCommand (previousCommand)
  48037. + TRANS("\"\n\nDo you want to re-assign it to this new command instead?"),
  48038. TRANS("re-assign"),
  48039. TRANS("cancel")))
  48040. {
  48041. return;
  48042. }
  48043. }
  48044. mappings->removeKeyPress (entryWindow.lastPress);
  48045. if (index >= 0)
  48046. mappings->removeKeyPress (commandID, index);
  48047. mappings->addKeyPress (commandID, entryWindow.lastPress, index);
  48048. }
  48049. }
  48050. }
  48051. bool KeyMappingEditorComponent::shouldCommandBeIncluded (const CommandID commandID)
  48052. {
  48053. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  48054. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::hiddenFromKeyEditor) == 0);
  48055. }
  48056. bool KeyMappingEditorComponent::isCommandReadOnly (const CommandID commandID)
  48057. {
  48058. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  48059. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::readOnlyInKeyEditor) != 0);
  48060. }
  48061. const String KeyMappingEditorComponent::getDescriptionForKeyPress (const KeyPress& key)
  48062. {
  48063. return key.getTextDescription();
  48064. }
  48065. END_JUCE_NAMESPACE
  48066. /*** End of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  48067. /*** Start of inlined file: juce_KeyPress.cpp ***/
  48068. BEGIN_JUCE_NAMESPACE
  48069. KeyPress::KeyPress() throw()
  48070. : keyCode (0),
  48071. mods (0),
  48072. textCharacter (0)
  48073. {
  48074. }
  48075. KeyPress::KeyPress (const int keyCode_,
  48076. const ModifierKeys& mods_,
  48077. const juce_wchar textCharacter_) throw()
  48078. : keyCode (keyCode_),
  48079. mods (mods_),
  48080. textCharacter (textCharacter_)
  48081. {
  48082. }
  48083. KeyPress::KeyPress (const int keyCode_) throw()
  48084. : keyCode (keyCode_),
  48085. textCharacter (0)
  48086. {
  48087. }
  48088. KeyPress::KeyPress (const KeyPress& other) throw()
  48089. : keyCode (other.keyCode),
  48090. mods (other.mods),
  48091. textCharacter (other.textCharacter)
  48092. {
  48093. }
  48094. KeyPress& KeyPress::operator= (const KeyPress& other) throw()
  48095. {
  48096. keyCode = other.keyCode;
  48097. mods = other.mods;
  48098. textCharacter = other.textCharacter;
  48099. return *this;
  48100. }
  48101. bool KeyPress::operator== (const KeyPress& other) const throw()
  48102. {
  48103. return mods.getRawFlags() == other.mods.getRawFlags()
  48104. && (textCharacter == other.textCharacter
  48105. || textCharacter == 0
  48106. || other.textCharacter == 0)
  48107. && (keyCode == other.keyCode
  48108. || (keyCode < 256
  48109. && other.keyCode < 256
  48110. && CharacterFunctions::toLowerCase ((juce_wchar) keyCode)
  48111. == CharacterFunctions::toLowerCase ((juce_wchar) other.keyCode)));
  48112. }
  48113. bool KeyPress::operator!= (const KeyPress& other) const throw()
  48114. {
  48115. return ! operator== (other);
  48116. }
  48117. bool KeyPress::isCurrentlyDown() const
  48118. {
  48119. return isKeyCurrentlyDown (keyCode)
  48120. && (ModifierKeys::getCurrentModifiers().getRawFlags() & ModifierKeys::allKeyboardModifiers)
  48121. == (mods.getRawFlags() & ModifierKeys::allKeyboardModifiers);
  48122. }
  48123. namespace KeyPressHelpers
  48124. {
  48125. struct KeyNameAndCode
  48126. {
  48127. const char* name;
  48128. int code;
  48129. };
  48130. static const KeyNameAndCode translations[] =
  48131. {
  48132. { "spacebar", KeyPress::spaceKey },
  48133. { "return", KeyPress::returnKey },
  48134. { "escape", KeyPress::escapeKey },
  48135. { "backspace", KeyPress::backspaceKey },
  48136. { "cursor left", KeyPress::leftKey },
  48137. { "cursor right", KeyPress::rightKey },
  48138. { "cursor up", KeyPress::upKey },
  48139. { "cursor down", KeyPress::downKey },
  48140. { "page up", KeyPress::pageUpKey },
  48141. { "page down", KeyPress::pageDownKey },
  48142. { "home", KeyPress::homeKey },
  48143. { "end", KeyPress::endKey },
  48144. { "delete", KeyPress::deleteKey },
  48145. { "insert", KeyPress::insertKey },
  48146. { "tab", KeyPress::tabKey },
  48147. { "play", KeyPress::playKey },
  48148. { "stop", KeyPress::stopKey },
  48149. { "fast forward", KeyPress::fastForwardKey },
  48150. { "rewind", KeyPress::rewindKey }
  48151. };
  48152. static const String numberPadPrefix() { return "numpad "; }
  48153. }
  48154. const KeyPress KeyPress::createFromDescription (const String& desc)
  48155. {
  48156. int modifiers = 0;
  48157. if (desc.containsWholeWordIgnoreCase ("ctrl")
  48158. || desc.containsWholeWordIgnoreCase ("control")
  48159. || desc.containsWholeWordIgnoreCase ("ctl"))
  48160. modifiers |= ModifierKeys::ctrlModifier;
  48161. if (desc.containsWholeWordIgnoreCase ("shift")
  48162. || desc.containsWholeWordIgnoreCase ("shft"))
  48163. modifiers |= ModifierKeys::shiftModifier;
  48164. if (desc.containsWholeWordIgnoreCase ("alt")
  48165. || desc.containsWholeWordIgnoreCase ("option"))
  48166. modifiers |= ModifierKeys::altModifier;
  48167. if (desc.containsWholeWordIgnoreCase ("command")
  48168. || desc.containsWholeWordIgnoreCase ("cmd"))
  48169. modifiers |= ModifierKeys::commandModifier;
  48170. int key = 0;
  48171. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  48172. {
  48173. if (desc.containsWholeWordIgnoreCase (String (KeyPressHelpers::translations[i].name)))
  48174. {
  48175. key = KeyPressHelpers::translations[i].code;
  48176. break;
  48177. }
  48178. }
  48179. if (key == 0)
  48180. {
  48181. // see if it's a numpad key..
  48182. if (desc.containsIgnoreCase (KeyPressHelpers::numberPadPrefix()))
  48183. {
  48184. const juce_wchar lastChar = desc.trimEnd().getLastCharacter();
  48185. if (lastChar >= '0' && lastChar <= '9')
  48186. key = numberPad0 + lastChar - '0';
  48187. else if (lastChar == '+')
  48188. key = numberPadAdd;
  48189. else if (lastChar == '-')
  48190. key = numberPadSubtract;
  48191. else if (lastChar == '*')
  48192. key = numberPadMultiply;
  48193. else if (lastChar == '/')
  48194. key = numberPadDivide;
  48195. else if (lastChar == '.')
  48196. key = numberPadDecimalPoint;
  48197. else if (lastChar == '=')
  48198. key = numberPadEquals;
  48199. else if (desc.endsWith ("separator"))
  48200. key = numberPadSeparator;
  48201. else if (desc.endsWith ("delete"))
  48202. key = numberPadDelete;
  48203. }
  48204. if (key == 0)
  48205. {
  48206. // see if it's a function key..
  48207. for (int i = 1; i <= 12; ++i)
  48208. if (desc.containsWholeWordIgnoreCase ("f" + String (i)))
  48209. key = F1Key + i - 1;
  48210. if (key == 0)
  48211. {
  48212. // give up and use the hex code..
  48213. const int hexCode = desc.fromFirstOccurrenceOf ("#", false, false)
  48214. .toLowerCase()
  48215. .retainCharacters ("0123456789abcdef")
  48216. .getHexValue32();
  48217. if (hexCode > 0)
  48218. key = hexCode;
  48219. else
  48220. key = CharacterFunctions::toUpperCase (desc.getLastCharacter());
  48221. }
  48222. }
  48223. }
  48224. return KeyPress (key, ModifierKeys (modifiers), 0);
  48225. }
  48226. const String KeyPress::getTextDescription() const
  48227. {
  48228. String desc;
  48229. if (keyCode > 0)
  48230. {
  48231. // some keyboard layouts use a shift-key to get the slash, but in those cases, we
  48232. // want to store it as being a slash, not shift+whatever.
  48233. if (textCharacter == '/')
  48234. return "/";
  48235. if (mods.isCtrlDown())
  48236. desc << "ctrl + ";
  48237. if (mods.isShiftDown())
  48238. desc << "shift + ";
  48239. #if JUCE_MAC
  48240. // only do this on the mac, because on Windows ctrl and command are the same,
  48241. // and this would get confusing
  48242. if (mods.isCommandDown())
  48243. desc << "command + ";
  48244. if (mods.isAltDown())
  48245. desc << "option + ";
  48246. #else
  48247. if (mods.isAltDown())
  48248. desc << "alt + ";
  48249. #endif
  48250. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  48251. if (keyCode == KeyPressHelpers::translations[i].code)
  48252. return desc + KeyPressHelpers::translations[i].name;
  48253. if (keyCode >= F1Key && keyCode <= F16Key)
  48254. desc << 'F' << (1 + keyCode - F1Key);
  48255. else if (keyCode >= numberPad0 && keyCode <= numberPad9)
  48256. desc << KeyPressHelpers::numberPadPrefix() << (keyCode - numberPad0);
  48257. else if (keyCode >= 33 && keyCode < 176)
  48258. desc += CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  48259. else if (keyCode == numberPadAdd)
  48260. desc << KeyPressHelpers::numberPadPrefix() << '+';
  48261. else if (keyCode == numberPadSubtract)
  48262. desc << KeyPressHelpers::numberPadPrefix() << '-';
  48263. else if (keyCode == numberPadMultiply)
  48264. desc << KeyPressHelpers::numberPadPrefix() << '*';
  48265. else if (keyCode == numberPadDivide)
  48266. desc << KeyPressHelpers::numberPadPrefix() << '/';
  48267. else if (keyCode == numberPadSeparator)
  48268. desc << KeyPressHelpers::numberPadPrefix() << "separator";
  48269. else if (keyCode == numberPadDecimalPoint)
  48270. desc << KeyPressHelpers::numberPadPrefix() << '.';
  48271. else if (keyCode == numberPadDelete)
  48272. desc << KeyPressHelpers::numberPadPrefix() << "delete";
  48273. else
  48274. desc << '#' << String::toHexString (keyCode);
  48275. }
  48276. return desc;
  48277. }
  48278. END_JUCE_NAMESPACE
  48279. /*** End of inlined file: juce_KeyPress.cpp ***/
  48280. /*** Start of inlined file: juce_KeyPressMappingSet.cpp ***/
  48281. BEGIN_JUCE_NAMESPACE
  48282. KeyPressMappingSet::KeyPressMappingSet (ApplicationCommandManager* const commandManager_)
  48283. : commandManager (commandManager_)
  48284. {
  48285. // A manager is needed to get the descriptions of commands, and will be called when
  48286. // a command is invoked. So you can't leave this null..
  48287. jassert (commandManager_ != 0);
  48288. Desktop::getInstance().addFocusChangeListener (this);
  48289. }
  48290. KeyPressMappingSet::KeyPressMappingSet (const KeyPressMappingSet& other)
  48291. : commandManager (other.commandManager)
  48292. {
  48293. Desktop::getInstance().addFocusChangeListener (this);
  48294. }
  48295. KeyPressMappingSet::~KeyPressMappingSet()
  48296. {
  48297. Desktop::getInstance().removeFocusChangeListener (this);
  48298. }
  48299. const Array <KeyPress> KeyPressMappingSet::getKeyPressesAssignedToCommand (const CommandID commandID) const
  48300. {
  48301. for (int i = 0; i < mappings.size(); ++i)
  48302. if (mappings.getUnchecked(i)->commandID == commandID)
  48303. return mappings.getUnchecked (i)->keypresses;
  48304. return Array <KeyPress> ();
  48305. }
  48306. void KeyPressMappingSet::addKeyPress (const CommandID commandID,
  48307. const KeyPress& newKeyPress,
  48308. int insertIndex)
  48309. {
  48310. // If you specify an upper-case letter but no shift key, how is the user supposed to press it!?
  48311. // Stick to lower-case letters when defining a keypress, to avoid ambiguity.
  48312. jassert (! (CharacterFunctions::isUpperCase (newKeyPress.getTextCharacter())
  48313. && ! newKeyPress.getModifiers().isShiftDown()));
  48314. if (findCommandForKeyPress (newKeyPress) != commandID)
  48315. {
  48316. removeKeyPress (newKeyPress);
  48317. if (newKeyPress.isValid())
  48318. {
  48319. for (int i = mappings.size(); --i >= 0;)
  48320. {
  48321. if (mappings.getUnchecked(i)->commandID == commandID)
  48322. {
  48323. mappings.getUnchecked(i)->keypresses.insert (insertIndex, newKeyPress);
  48324. sendChangeMessage (this);
  48325. return;
  48326. }
  48327. }
  48328. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48329. if (ci != 0)
  48330. {
  48331. CommandMapping* const cm = new CommandMapping();
  48332. cm->commandID = commandID;
  48333. cm->keypresses.add (newKeyPress);
  48334. cm->wantsKeyUpDownCallbacks = (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) != 0;
  48335. mappings.add (cm);
  48336. sendChangeMessage (this);
  48337. }
  48338. }
  48339. }
  48340. }
  48341. void KeyPressMappingSet::resetToDefaultMappings()
  48342. {
  48343. mappings.clear();
  48344. for (int i = 0; i < commandManager->getNumCommands(); ++i)
  48345. {
  48346. const ApplicationCommandInfo* const ci = commandManager->getCommandForIndex (i);
  48347. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  48348. {
  48349. addKeyPress (ci->commandID,
  48350. ci->defaultKeypresses.getReference (j));
  48351. }
  48352. }
  48353. sendChangeMessage (this);
  48354. }
  48355. void KeyPressMappingSet::resetToDefaultMapping (const CommandID commandID)
  48356. {
  48357. clearAllKeyPresses (commandID);
  48358. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48359. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  48360. {
  48361. addKeyPress (ci->commandID,
  48362. ci->defaultKeypresses.getReference (j));
  48363. }
  48364. }
  48365. void KeyPressMappingSet::clearAllKeyPresses()
  48366. {
  48367. if (mappings.size() > 0)
  48368. {
  48369. sendChangeMessage (this);
  48370. mappings.clear();
  48371. }
  48372. }
  48373. void KeyPressMappingSet::clearAllKeyPresses (const CommandID commandID)
  48374. {
  48375. for (int i = mappings.size(); --i >= 0;)
  48376. {
  48377. if (mappings.getUnchecked(i)->commandID == commandID)
  48378. {
  48379. mappings.remove (i);
  48380. sendChangeMessage (this);
  48381. }
  48382. }
  48383. }
  48384. void KeyPressMappingSet::removeKeyPress (const KeyPress& keypress)
  48385. {
  48386. if (keypress.isValid())
  48387. {
  48388. for (int i = mappings.size(); --i >= 0;)
  48389. {
  48390. CommandMapping* const cm = mappings.getUnchecked(i);
  48391. for (int j = cm->keypresses.size(); --j >= 0;)
  48392. {
  48393. if (keypress == cm->keypresses [j])
  48394. {
  48395. cm->keypresses.remove (j);
  48396. sendChangeMessage (this);
  48397. }
  48398. }
  48399. }
  48400. }
  48401. }
  48402. void KeyPressMappingSet::removeKeyPress (const CommandID commandID, const int keyPressIndex)
  48403. {
  48404. for (int i = mappings.size(); --i >= 0;)
  48405. {
  48406. if (mappings.getUnchecked(i)->commandID == commandID)
  48407. {
  48408. mappings.getUnchecked(i)->keypresses.remove (keyPressIndex);
  48409. sendChangeMessage (this);
  48410. break;
  48411. }
  48412. }
  48413. }
  48414. CommandID KeyPressMappingSet::findCommandForKeyPress (const KeyPress& keyPress) const throw()
  48415. {
  48416. for (int i = 0; i < mappings.size(); ++i)
  48417. if (mappings.getUnchecked(i)->keypresses.contains (keyPress))
  48418. return mappings.getUnchecked(i)->commandID;
  48419. return 0;
  48420. }
  48421. bool KeyPressMappingSet::containsMapping (const CommandID commandID, const KeyPress& keyPress) const throw()
  48422. {
  48423. for (int i = mappings.size(); --i >= 0;)
  48424. if (mappings.getUnchecked(i)->commandID == commandID)
  48425. return mappings.getUnchecked(i)->keypresses.contains (keyPress);
  48426. return false;
  48427. }
  48428. void KeyPressMappingSet::invokeCommand (const CommandID commandID,
  48429. const KeyPress& key,
  48430. const bool isKeyDown,
  48431. const int millisecsSinceKeyPressed,
  48432. Component* const originatingComponent) const
  48433. {
  48434. ApplicationCommandTarget::InvocationInfo info (commandID);
  48435. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromKeyPress;
  48436. info.isKeyDown = isKeyDown;
  48437. info.keyPress = key;
  48438. info.millisecsSinceKeyPressed = millisecsSinceKeyPressed;
  48439. info.originatingComponent = originatingComponent;
  48440. commandManager->invoke (info, false);
  48441. }
  48442. bool KeyPressMappingSet::restoreFromXml (const XmlElement& xmlVersion)
  48443. {
  48444. if (xmlVersion.hasTagName ("KEYMAPPINGS"))
  48445. {
  48446. if (xmlVersion.getBoolAttribute ("basedOnDefaults", true))
  48447. {
  48448. // if the XML was created as a set of differences from the default mappings,
  48449. // (i.e. by calling createXml (true)), then we need to first restore the defaults.
  48450. resetToDefaultMappings();
  48451. }
  48452. else
  48453. {
  48454. // if the XML was created calling createXml (false), then we need to clear all
  48455. // the keys and treat the xml as describing the entire set of mappings.
  48456. clearAllKeyPresses();
  48457. }
  48458. forEachXmlChildElement (xmlVersion, map)
  48459. {
  48460. const CommandID commandId = map->getStringAttribute ("commandId").getHexValue32();
  48461. if (commandId != 0)
  48462. {
  48463. const KeyPress key (KeyPress::createFromDescription (map->getStringAttribute ("key")));
  48464. if (map->hasTagName ("MAPPING"))
  48465. {
  48466. addKeyPress (commandId, key);
  48467. }
  48468. else if (map->hasTagName ("UNMAPPING"))
  48469. {
  48470. if (containsMapping (commandId, key))
  48471. removeKeyPress (key);
  48472. }
  48473. }
  48474. }
  48475. return true;
  48476. }
  48477. return false;
  48478. }
  48479. XmlElement* KeyPressMappingSet::createXml (const bool saveDifferencesFromDefaultSet) const
  48480. {
  48481. ScopedPointer <KeyPressMappingSet> defaultSet;
  48482. if (saveDifferencesFromDefaultSet)
  48483. {
  48484. defaultSet = new KeyPressMappingSet (commandManager);
  48485. defaultSet->resetToDefaultMappings();
  48486. }
  48487. XmlElement* const doc = new XmlElement ("KEYMAPPINGS");
  48488. doc->setAttribute ("basedOnDefaults", saveDifferencesFromDefaultSet);
  48489. int i;
  48490. for (i = 0; i < mappings.size(); ++i)
  48491. {
  48492. const CommandMapping* const cm = mappings.getUnchecked(i);
  48493. for (int j = 0; j < cm->keypresses.size(); ++j)
  48494. {
  48495. if (defaultSet == 0
  48496. || ! defaultSet->containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  48497. {
  48498. XmlElement* const map = doc->createNewChildElement ("MAPPING");
  48499. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  48500. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  48501. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  48502. }
  48503. }
  48504. }
  48505. if (defaultSet != 0)
  48506. {
  48507. for (i = 0; i < defaultSet->mappings.size(); ++i)
  48508. {
  48509. const CommandMapping* const cm = defaultSet->mappings.getUnchecked(i);
  48510. for (int j = 0; j < cm->keypresses.size(); ++j)
  48511. {
  48512. if (! containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  48513. {
  48514. XmlElement* const map = doc->createNewChildElement ("UNMAPPING");
  48515. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  48516. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  48517. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  48518. }
  48519. }
  48520. }
  48521. }
  48522. return doc;
  48523. }
  48524. bool KeyPressMappingSet::keyPressed (const KeyPress& key,
  48525. Component* originatingComponent)
  48526. {
  48527. bool used = false;
  48528. const CommandID commandID = findCommandForKeyPress (key);
  48529. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48530. if (ci != 0
  48531. && (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) == 0)
  48532. {
  48533. ApplicationCommandInfo info (0);
  48534. if (commandManager->getTargetForCommand (commandID, info) != 0
  48535. && (info.flags & ApplicationCommandInfo::isDisabled) == 0)
  48536. {
  48537. invokeCommand (commandID, key, true, 0, originatingComponent);
  48538. used = true;
  48539. }
  48540. else
  48541. {
  48542. if (originatingComponent != 0)
  48543. originatingComponent->getLookAndFeel().playAlertSound();
  48544. }
  48545. }
  48546. return used;
  48547. }
  48548. bool KeyPressMappingSet::keyStateChanged (const bool /*isKeyDown*/, Component* originatingComponent)
  48549. {
  48550. bool used = false;
  48551. const uint32 now = Time::getMillisecondCounter();
  48552. for (int i = mappings.size(); --i >= 0;)
  48553. {
  48554. CommandMapping* const cm = mappings.getUnchecked(i);
  48555. if (cm->wantsKeyUpDownCallbacks)
  48556. {
  48557. for (int j = cm->keypresses.size(); --j >= 0;)
  48558. {
  48559. const KeyPress key (cm->keypresses.getReference (j));
  48560. const bool isDown = key.isCurrentlyDown();
  48561. int keyPressEntryIndex = 0;
  48562. bool wasDown = false;
  48563. for (int k = keysDown.size(); --k >= 0;)
  48564. {
  48565. if (key == keysDown.getUnchecked(k)->key)
  48566. {
  48567. keyPressEntryIndex = k;
  48568. wasDown = true;
  48569. used = true;
  48570. break;
  48571. }
  48572. }
  48573. if (isDown != wasDown)
  48574. {
  48575. int millisecs = 0;
  48576. if (isDown)
  48577. {
  48578. KeyPressTime* const k = new KeyPressTime();
  48579. k->key = key;
  48580. k->timeWhenPressed = now;
  48581. keysDown.add (k);
  48582. }
  48583. else
  48584. {
  48585. const uint32 pressTime = keysDown.getUnchecked (keyPressEntryIndex)->timeWhenPressed;
  48586. if (now > pressTime)
  48587. millisecs = now - pressTime;
  48588. keysDown.remove (keyPressEntryIndex);
  48589. }
  48590. invokeCommand (cm->commandID, key, isDown, millisecs, originatingComponent);
  48591. used = true;
  48592. }
  48593. }
  48594. }
  48595. }
  48596. return used;
  48597. }
  48598. void KeyPressMappingSet::globalFocusChanged (Component* focusedComponent)
  48599. {
  48600. if (focusedComponent != 0)
  48601. focusedComponent->keyStateChanged (false);
  48602. }
  48603. END_JUCE_NAMESPACE
  48604. /*** End of inlined file: juce_KeyPressMappingSet.cpp ***/
  48605. /*** Start of inlined file: juce_ModifierKeys.cpp ***/
  48606. BEGIN_JUCE_NAMESPACE
  48607. ModifierKeys::ModifierKeys (const int flags_) throw()
  48608. : flags (flags_)
  48609. {
  48610. }
  48611. ModifierKeys::ModifierKeys (const ModifierKeys& other) throw()
  48612. : flags (other.flags)
  48613. {
  48614. }
  48615. ModifierKeys& ModifierKeys::operator= (const ModifierKeys& other) throw()
  48616. {
  48617. flags = other.flags;
  48618. return *this;
  48619. }
  48620. ModifierKeys ModifierKeys::currentModifiers;
  48621. const ModifierKeys ModifierKeys::getCurrentModifiers() throw()
  48622. {
  48623. return currentModifiers;
  48624. }
  48625. int ModifierKeys::getNumMouseButtonsDown() const throw()
  48626. {
  48627. int num = 0;
  48628. if (isLeftButtonDown()) ++num;
  48629. if (isRightButtonDown()) ++num;
  48630. if (isMiddleButtonDown()) ++num;
  48631. return num;
  48632. }
  48633. END_JUCE_NAMESPACE
  48634. /*** End of inlined file: juce_ModifierKeys.cpp ***/
  48635. /*** Start of inlined file: juce_ComponentAnimator.cpp ***/
  48636. BEGIN_JUCE_NAMESPACE
  48637. class ComponentAnimator::AnimationTask
  48638. {
  48639. public:
  48640. AnimationTask (Component* const comp)
  48641. : component (comp)
  48642. {
  48643. }
  48644. Component::SafePointer<Component> component;
  48645. Rectangle<int> destination;
  48646. int msElapsed, msTotal;
  48647. double startSpeed, midSpeed, endSpeed, lastProgress;
  48648. double left, top, right, bottom;
  48649. bool useTimeslice (const int elapsed)
  48650. {
  48651. if (component == 0)
  48652. return false;
  48653. msElapsed += elapsed;
  48654. double newProgress = msElapsed / (double) msTotal;
  48655. if (newProgress >= 0 && newProgress < 1.0)
  48656. {
  48657. newProgress = timeToDistance (newProgress);
  48658. const double delta = (newProgress - lastProgress) / (1.0 - lastProgress);
  48659. jassert (newProgress >= lastProgress);
  48660. lastProgress = newProgress;
  48661. left += (destination.getX() - left) * delta;
  48662. top += (destination.getY() - top) * delta;
  48663. right += (destination.getRight() - right) * delta;
  48664. bottom += (destination.getBottom() - bottom) * delta;
  48665. if (delta < 1.0)
  48666. {
  48667. const Rectangle<int> newBounds (roundToInt (left),
  48668. roundToInt (top),
  48669. roundToInt (right - left),
  48670. roundToInt (bottom - top));
  48671. if (newBounds != destination)
  48672. {
  48673. component->setBounds (newBounds);
  48674. return true;
  48675. }
  48676. }
  48677. }
  48678. component->setBounds (destination);
  48679. return false;
  48680. }
  48681. void moveToFinalDestination()
  48682. {
  48683. if (component != 0)
  48684. component->setBounds (destination);
  48685. }
  48686. private:
  48687. inline double timeToDistance (const double time) const
  48688. {
  48689. return (time < 0.5) ? time * (startSpeed + time * (midSpeed - startSpeed))
  48690. : 0.5 * (startSpeed + 0.5 * (midSpeed - startSpeed))
  48691. + (time - 0.5) * (midSpeed + (time - 0.5) * (endSpeed - midSpeed));
  48692. }
  48693. };
  48694. ComponentAnimator::ComponentAnimator()
  48695. : lastTime (0)
  48696. {
  48697. }
  48698. ComponentAnimator::~ComponentAnimator()
  48699. {
  48700. cancelAllAnimations (false);
  48701. jassert (tasks.size() == 0);
  48702. }
  48703. ComponentAnimator::AnimationTask* ComponentAnimator::findTaskFor (Component* const component) const
  48704. {
  48705. for (int i = tasks.size(); --i >= 0;)
  48706. if (component == tasks.getUnchecked(i)->component.getComponent())
  48707. return tasks.getUnchecked(i);
  48708. return 0;
  48709. }
  48710. void ComponentAnimator::animateComponent (Component* const component,
  48711. const Rectangle<int>& finalPosition,
  48712. const int millisecondsToSpendMoving,
  48713. const double startSpeed,
  48714. const double endSpeed)
  48715. {
  48716. if (component != 0)
  48717. {
  48718. AnimationTask* at = findTaskFor (component);
  48719. if (at == 0)
  48720. {
  48721. at = new AnimationTask (component);
  48722. tasks.add (at);
  48723. sendChangeMessage (this);
  48724. }
  48725. at->msElapsed = 0;
  48726. at->lastProgress = 0;
  48727. at->msTotal = jmax (1, millisecondsToSpendMoving);
  48728. at->destination = finalPosition;
  48729. // the speeds must be 0 or greater!
  48730. jassert (startSpeed >= 0 && endSpeed >= 0)
  48731. const double invTotalDistance = 4.0 / (startSpeed + endSpeed + 2.0);
  48732. at->startSpeed = jmax (0.0, startSpeed * invTotalDistance);
  48733. at->midSpeed = invTotalDistance;
  48734. at->endSpeed = jmax (0.0, endSpeed * invTotalDistance);
  48735. at->left = component->getX();
  48736. at->top = component->getY();
  48737. at->right = component->getRight();
  48738. at->bottom = component->getBottom();
  48739. if (! isTimerRunning())
  48740. {
  48741. lastTime = Time::getMillisecondCounter();
  48742. startTimer (1000 / 50);
  48743. }
  48744. }
  48745. }
  48746. void ComponentAnimator::cancelAllAnimations (const bool moveComponentsToTheirFinalPositions)
  48747. {
  48748. for (int i = tasks.size(); --i >= 0;)
  48749. {
  48750. AnimationTask* const at = tasks.getUnchecked(i);
  48751. if (moveComponentsToTheirFinalPositions)
  48752. at->moveToFinalDestination();
  48753. delete at;
  48754. tasks.remove (i);
  48755. sendChangeMessage (this);
  48756. }
  48757. }
  48758. void ComponentAnimator::cancelAnimation (Component* const component,
  48759. const bool moveComponentToItsFinalPosition)
  48760. {
  48761. AnimationTask* const at = findTaskFor (component);
  48762. if (at != 0)
  48763. {
  48764. if (moveComponentToItsFinalPosition)
  48765. at->moveToFinalDestination();
  48766. tasks.removeValue (at);
  48767. delete at;
  48768. sendChangeMessage (this);
  48769. }
  48770. }
  48771. const Rectangle<int> ComponentAnimator::getComponentDestination (Component* const component)
  48772. {
  48773. AnimationTask* const at = findTaskFor (component);
  48774. if (at != 0)
  48775. return at->destination;
  48776. else if (component != 0)
  48777. return component->getBounds();
  48778. return Rectangle<int>();
  48779. }
  48780. bool ComponentAnimator::isAnimating (Component* component) const
  48781. {
  48782. return findTaskFor (component) != 0;
  48783. }
  48784. void ComponentAnimator::timerCallback()
  48785. {
  48786. const uint32 timeNow = Time::getMillisecondCounter();
  48787. if (lastTime == 0 || lastTime == timeNow)
  48788. lastTime = timeNow;
  48789. const int elapsed = timeNow - lastTime;
  48790. for (int i = tasks.size(); --i >= 0;)
  48791. {
  48792. AnimationTask* const at = tasks.getUnchecked(i);
  48793. if (! at->useTimeslice (elapsed))
  48794. {
  48795. tasks.remove (i);
  48796. delete at;
  48797. sendChangeMessage (this);
  48798. }
  48799. }
  48800. lastTime = timeNow;
  48801. if (tasks.size() == 0)
  48802. stopTimer();
  48803. }
  48804. END_JUCE_NAMESPACE
  48805. /*** End of inlined file: juce_ComponentAnimator.cpp ***/
  48806. /*** Start of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  48807. BEGIN_JUCE_NAMESPACE
  48808. ComponentBoundsConstrainer::ComponentBoundsConstrainer() throw()
  48809. : minW (0),
  48810. maxW (0x3fffffff),
  48811. minH (0),
  48812. maxH (0x3fffffff),
  48813. minOffTop (0),
  48814. minOffLeft (0),
  48815. minOffBottom (0),
  48816. minOffRight (0),
  48817. aspectRatio (0.0)
  48818. {
  48819. }
  48820. ComponentBoundsConstrainer::~ComponentBoundsConstrainer()
  48821. {
  48822. }
  48823. void ComponentBoundsConstrainer::setMinimumWidth (const int minimumWidth) throw()
  48824. {
  48825. minW = minimumWidth;
  48826. }
  48827. void ComponentBoundsConstrainer::setMaximumWidth (const int maximumWidth) throw()
  48828. {
  48829. maxW = maximumWidth;
  48830. }
  48831. void ComponentBoundsConstrainer::setMinimumHeight (const int minimumHeight) throw()
  48832. {
  48833. minH = minimumHeight;
  48834. }
  48835. void ComponentBoundsConstrainer::setMaximumHeight (const int maximumHeight) throw()
  48836. {
  48837. maxH = maximumHeight;
  48838. }
  48839. void ComponentBoundsConstrainer::setMinimumSize (const int minimumWidth, const int minimumHeight) throw()
  48840. {
  48841. jassert (maxW >= minimumWidth);
  48842. jassert (maxH >= minimumHeight);
  48843. jassert (minimumWidth > 0 && minimumHeight > 0);
  48844. minW = minimumWidth;
  48845. minH = minimumHeight;
  48846. if (minW > maxW)
  48847. maxW = minW;
  48848. if (minH > maxH)
  48849. maxH = minH;
  48850. }
  48851. void ComponentBoundsConstrainer::setMaximumSize (const int maximumWidth, const int maximumHeight) throw()
  48852. {
  48853. jassert (maximumWidth >= minW);
  48854. jassert (maximumHeight >= minH);
  48855. jassert (maximumWidth > 0 && maximumHeight > 0);
  48856. maxW = jmax (minW, maximumWidth);
  48857. maxH = jmax (minH, maximumHeight);
  48858. }
  48859. void ComponentBoundsConstrainer::setSizeLimits (const int minimumWidth,
  48860. const int minimumHeight,
  48861. const int maximumWidth,
  48862. const int maximumHeight) throw()
  48863. {
  48864. jassert (maximumWidth >= minimumWidth);
  48865. jassert (maximumHeight >= minimumHeight);
  48866. jassert (maximumWidth > 0 && maximumHeight > 0);
  48867. jassert (minimumWidth > 0 && minimumHeight > 0);
  48868. minW = jmax (0, minimumWidth);
  48869. minH = jmax (0, minimumHeight);
  48870. maxW = jmax (minW, maximumWidth);
  48871. maxH = jmax (minH, maximumHeight);
  48872. }
  48873. void ComponentBoundsConstrainer::setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  48874. const int minimumWhenOffTheLeft,
  48875. const int minimumWhenOffTheBottom,
  48876. const int minimumWhenOffTheRight) throw()
  48877. {
  48878. minOffTop = minimumWhenOffTheTop;
  48879. minOffLeft = minimumWhenOffTheLeft;
  48880. minOffBottom = minimumWhenOffTheBottom;
  48881. minOffRight = minimumWhenOffTheRight;
  48882. }
  48883. void ComponentBoundsConstrainer::setFixedAspectRatio (const double widthOverHeight) throw()
  48884. {
  48885. aspectRatio = jmax (0.0, widthOverHeight);
  48886. }
  48887. double ComponentBoundsConstrainer::getFixedAspectRatio() const throw()
  48888. {
  48889. return aspectRatio;
  48890. }
  48891. void ComponentBoundsConstrainer::setBoundsForComponent (Component* const component,
  48892. const Rectangle<int>& targetBounds,
  48893. const bool isStretchingTop,
  48894. const bool isStretchingLeft,
  48895. const bool isStretchingBottom,
  48896. const bool isStretchingRight)
  48897. {
  48898. jassert (component != 0);
  48899. Rectangle<int> limits, bounds (targetBounds);
  48900. BorderSize border;
  48901. Component* const parent = component->getParentComponent();
  48902. if (parent == 0)
  48903. {
  48904. ComponentPeer* peer = component->getPeer();
  48905. if (peer != 0)
  48906. border = peer->getFrameSize();
  48907. limits = Desktop::getInstance().getMonitorAreaContaining (bounds.getCentre());
  48908. }
  48909. else
  48910. {
  48911. limits.setSize (parent->getWidth(), parent->getHeight());
  48912. }
  48913. border.addTo (bounds);
  48914. checkBounds (bounds,
  48915. border.addedTo (component->getBounds()), limits,
  48916. isStretchingTop, isStretchingLeft,
  48917. isStretchingBottom, isStretchingRight);
  48918. border.subtractFrom (bounds);
  48919. applyBoundsToComponent (component, bounds);
  48920. }
  48921. void ComponentBoundsConstrainer::checkComponentBounds (Component* component)
  48922. {
  48923. setBoundsForComponent (component, component->getBounds(),
  48924. false, false, false, false);
  48925. }
  48926. void ComponentBoundsConstrainer::applyBoundsToComponent (Component* component,
  48927. const Rectangle<int>& bounds)
  48928. {
  48929. component->setBounds (bounds);
  48930. }
  48931. void ComponentBoundsConstrainer::resizeStart()
  48932. {
  48933. }
  48934. void ComponentBoundsConstrainer::resizeEnd()
  48935. {
  48936. }
  48937. void ComponentBoundsConstrainer::checkBounds (Rectangle<int>& bounds,
  48938. const Rectangle<int>& old,
  48939. const Rectangle<int>& limits,
  48940. const bool isStretchingTop,
  48941. const bool isStretchingLeft,
  48942. const bool isStretchingBottom,
  48943. const bool isStretchingRight)
  48944. {
  48945. int x = bounds.getX();
  48946. int y = bounds.getY();
  48947. int w = bounds.getWidth();
  48948. int h = bounds.getHeight();
  48949. // constrain the size if it's being stretched..
  48950. if (isStretchingLeft)
  48951. {
  48952. x = jlimit (old.getRight() - maxW, old.getRight() - minW, x);
  48953. w = old.getRight() - x;
  48954. }
  48955. if (isStretchingRight)
  48956. {
  48957. w = jlimit (minW, maxW, w);
  48958. }
  48959. if (isStretchingTop)
  48960. {
  48961. y = jlimit (old.getBottom() - maxH, old.getBottom() - minH, y);
  48962. h = old.getBottom() - y;
  48963. }
  48964. if (isStretchingBottom)
  48965. {
  48966. h = jlimit (minH, maxH, h);
  48967. }
  48968. // constrain the aspect ratio if one has been specified..
  48969. if (aspectRatio > 0.0 && w > 0 && h > 0)
  48970. {
  48971. bool adjustWidth;
  48972. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  48973. {
  48974. adjustWidth = true;
  48975. }
  48976. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  48977. {
  48978. adjustWidth = false;
  48979. }
  48980. else
  48981. {
  48982. const double oldRatio = (old.getHeight() > 0) ? std::abs (old.getWidth() / (double) old.getHeight()) : 0.0;
  48983. const double newRatio = std::abs (w / (double) h);
  48984. adjustWidth = (oldRatio > newRatio);
  48985. }
  48986. if (adjustWidth)
  48987. {
  48988. w = roundToInt (h * aspectRatio);
  48989. if (w > maxW || w < minW)
  48990. {
  48991. w = jlimit (minW, maxW, w);
  48992. h = roundToInt (w / aspectRatio);
  48993. }
  48994. }
  48995. else
  48996. {
  48997. h = roundToInt (w / aspectRatio);
  48998. if (h > maxH || h < minH)
  48999. {
  49000. h = jlimit (minH, maxH, h);
  49001. w = roundToInt (h * aspectRatio);
  49002. }
  49003. }
  49004. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  49005. {
  49006. x = old.getX() + (old.getWidth() - w) / 2;
  49007. }
  49008. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  49009. {
  49010. y = old.getY() + (old.getHeight() - h) / 2;
  49011. }
  49012. else
  49013. {
  49014. if (isStretchingLeft)
  49015. x = old.getRight() - w;
  49016. if (isStretchingTop)
  49017. y = old.getBottom() - h;
  49018. }
  49019. }
  49020. // ...and constrain the position if limits have been set for that.
  49021. if (minOffTop > 0 || minOffLeft > 0 || minOffBottom > 0 || minOffRight > 0)
  49022. {
  49023. if (minOffTop > 0)
  49024. {
  49025. const int limit = limits.getY() + jmin (minOffTop - h, 0);
  49026. if (y < limit)
  49027. {
  49028. if (isStretchingTop)
  49029. h -= (limit - y);
  49030. y = limit;
  49031. }
  49032. }
  49033. if (minOffLeft > 0)
  49034. {
  49035. const int limit = limits.getX() + jmin (minOffLeft - w, 0);
  49036. if (x < limit)
  49037. {
  49038. if (isStretchingLeft)
  49039. w -= (limit - x);
  49040. x = limit;
  49041. }
  49042. }
  49043. if (minOffBottom > 0)
  49044. {
  49045. const int limit = limits.getBottom() - jmin (minOffBottom, h);
  49046. if (y > limit)
  49047. {
  49048. if (isStretchingBottom)
  49049. h += (limit - y);
  49050. else
  49051. y = limit;
  49052. }
  49053. }
  49054. if (minOffRight > 0)
  49055. {
  49056. const int limit = limits.getRight() - jmin (minOffRight, w);
  49057. if (x > limit)
  49058. {
  49059. if (isStretchingRight)
  49060. w += (limit - x);
  49061. else
  49062. x = limit;
  49063. }
  49064. }
  49065. }
  49066. jassert (w >= 0 && h >= 0);
  49067. bounds = Rectangle<int> (x, y, w, h);
  49068. }
  49069. END_JUCE_NAMESPACE
  49070. /*** End of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  49071. /*** Start of inlined file: juce_ComponentMovementWatcher.cpp ***/
  49072. BEGIN_JUCE_NAMESPACE
  49073. ComponentMovementWatcher::ComponentMovementWatcher (Component* const component_)
  49074. : component (component_),
  49075. lastPeer (0),
  49076. reentrant (false)
  49077. {
  49078. jassert (component != 0); // can't use this with a null pointer..
  49079. component->addComponentListener (this);
  49080. registerWithParentComps();
  49081. }
  49082. ComponentMovementWatcher::~ComponentMovementWatcher()
  49083. {
  49084. component->removeComponentListener (this);
  49085. unregister();
  49086. }
  49087. void ComponentMovementWatcher::componentParentHierarchyChanged (Component&)
  49088. {
  49089. // agh! don't delete the target component without deleting this object first!
  49090. jassert (component != 0);
  49091. if (! reentrant)
  49092. {
  49093. reentrant = true;
  49094. ComponentPeer* const peer = component->getPeer();
  49095. if (peer != lastPeer)
  49096. {
  49097. componentPeerChanged();
  49098. if (component == 0)
  49099. return;
  49100. lastPeer = peer;
  49101. }
  49102. unregister();
  49103. registerWithParentComps();
  49104. reentrant = false;
  49105. componentMovedOrResized (*component, true, true);
  49106. }
  49107. }
  49108. void ComponentMovementWatcher::componentMovedOrResized (Component&, bool wasMoved, bool wasResized)
  49109. {
  49110. // agh! don't delete the target component without deleting this object first!
  49111. jassert (component != 0);
  49112. if (wasMoved)
  49113. {
  49114. const Point<int> pos (component->relativePositionToOtherComponent (component->getTopLevelComponent(), Point<int>()));
  49115. wasMoved = lastBounds.getPosition() != pos;
  49116. lastBounds.setPosition (pos);
  49117. }
  49118. wasResized = (lastBounds.getWidth() != component->getWidth() || lastBounds.getHeight() != component->getHeight());
  49119. lastBounds.setSize (component->getWidth(), component->getHeight());
  49120. if (wasMoved || wasResized)
  49121. componentMovedOrResized (wasMoved, wasResized);
  49122. }
  49123. void ComponentMovementWatcher::registerWithParentComps() throw()
  49124. {
  49125. Component* p = component->getParentComponent();
  49126. while (p != 0)
  49127. {
  49128. p->addComponentListener (this);
  49129. registeredParentComps.add (p);
  49130. p = p->getParentComponent();
  49131. }
  49132. }
  49133. void ComponentMovementWatcher::unregister() throw()
  49134. {
  49135. for (int i = registeredParentComps.size(); --i >= 0;)
  49136. registeredParentComps.getUnchecked(i)->removeComponentListener (this);
  49137. registeredParentComps.clear();
  49138. }
  49139. END_JUCE_NAMESPACE
  49140. /*** End of inlined file: juce_ComponentMovementWatcher.cpp ***/
  49141. /*** Start of inlined file: juce_GroupComponent.cpp ***/
  49142. BEGIN_JUCE_NAMESPACE
  49143. GroupComponent::GroupComponent (const String& componentName,
  49144. const String& labelText)
  49145. : Component (componentName),
  49146. text (labelText),
  49147. justification (Justification::left)
  49148. {
  49149. setInterceptsMouseClicks (false, true);
  49150. }
  49151. GroupComponent::~GroupComponent()
  49152. {
  49153. }
  49154. void GroupComponent::setText (const String& newText)
  49155. {
  49156. if (text != newText)
  49157. {
  49158. text = newText;
  49159. repaint();
  49160. }
  49161. }
  49162. const String GroupComponent::getText() const
  49163. {
  49164. return text;
  49165. }
  49166. void GroupComponent::setTextLabelPosition (const Justification& newJustification)
  49167. {
  49168. if (justification != newJustification)
  49169. {
  49170. justification = newJustification;
  49171. repaint();
  49172. }
  49173. }
  49174. void GroupComponent::paint (Graphics& g)
  49175. {
  49176. getLookAndFeel()
  49177. .drawGroupComponentOutline (g, getWidth(), getHeight(),
  49178. text, justification,
  49179. *this);
  49180. }
  49181. void GroupComponent::enablementChanged()
  49182. {
  49183. repaint();
  49184. }
  49185. void GroupComponent::colourChanged()
  49186. {
  49187. repaint();
  49188. }
  49189. END_JUCE_NAMESPACE
  49190. /*** End of inlined file: juce_GroupComponent.cpp ***/
  49191. /*** Start of inlined file: juce_MultiDocumentPanel.cpp ***/
  49192. BEGIN_JUCE_NAMESPACE
  49193. MultiDocumentPanelWindow::MultiDocumentPanelWindow (const Colour& backgroundColour)
  49194. : DocumentWindow (String::empty, backgroundColour,
  49195. DocumentWindow::maximiseButton | DocumentWindow::closeButton, false)
  49196. {
  49197. }
  49198. MultiDocumentPanelWindow::~MultiDocumentPanelWindow()
  49199. {
  49200. }
  49201. void MultiDocumentPanelWindow::maximiseButtonPressed()
  49202. {
  49203. MultiDocumentPanel* const owner = getOwner();
  49204. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  49205. if (owner != 0)
  49206. owner->setLayoutMode (MultiDocumentPanel::MaximisedWindowsWithTabs);
  49207. }
  49208. void MultiDocumentPanelWindow::closeButtonPressed()
  49209. {
  49210. MultiDocumentPanel* const owner = getOwner();
  49211. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  49212. if (owner != 0)
  49213. owner->closeDocument (getContentComponent(), true);
  49214. }
  49215. void MultiDocumentPanelWindow::activeWindowStatusChanged()
  49216. {
  49217. DocumentWindow::activeWindowStatusChanged();
  49218. updateOrder();
  49219. }
  49220. void MultiDocumentPanelWindow::broughtToFront()
  49221. {
  49222. DocumentWindow::broughtToFront();
  49223. updateOrder();
  49224. }
  49225. void MultiDocumentPanelWindow::updateOrder()
  49226. {
  49227. MultiDocumentPanel* const owner = getOwner();
  49228. if (owner != 0)
  49229. owner->updateOrder();
  49230. }
  49231. MultiDocumentPanel* MultiDocumentPanelWindow::getOwner() const throw()
  49232. {
  49233. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  49234. return findParentComponentOfClass ((MultiDocumentPanel*) 0);
  49235. }
  49236. class MDITabbedComponentInternal : public TabbedComponent
  49237. {
  49238. public:
  49239. MDITabbedComponentInternal()
  49240. : TabbedComponent (TabbedButtonBar::TabsAtTop)
  49241. {
  49242. }
  49243. ~MDITabbedComponentInternal()
  49244. {
  49245. }
  49246. void currentTabChanged (int, const String&)
  49247. {
  49248. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  49249. MultiDocumentPanel* const owner = findParentComponentOfClass ((MultiDocumentPanel*) 0);
  49250. if (owner != 0)
  49251. owner->updateOrder();
  49252. }
  49253. };
  49254. MultiDocumentPanel::MultiDocumentPanel()
  49255. : mode (MaximisedWindowsWithTabs),
  49256. tabComponent (0),
  49257. backgroundColour (Colours::lightblue),
  49258. maximumNumDocuments (0),
  49259. numDocsBeforeTabsUsed (0)
  49260. {
  49261. setOpaque (true);
  49262. }
  49263. MultiDocumentPanel::~MultiDocumentPanel()
  49264. {
  49265. closeAllDocuments (false);
  49266. }
  49267. static bool shouldDeleteComp (Component* const c)
  49268. {
  49269. return c->getProperties() ["mdiDocumentDelete_"];
  49270. }
  49271. bool MultiDocumentPanel::closeAllDocuments (const bool checkItsOkToCloseFirst)
  49272. {
  49273. while (components.size() > 0)
  49274. if (! closeDocument (components.getLast(), checkItsOkToCloseFirst))
  49275. return false;
  49276. return true;
  49277. }
  49278. MultiDocumentPanelWindow* MultiDocumentPanel::createNewDocumentWindow()
  49279. {
  49280. return new MultiDocumentPanelWindow (backgroundColour);
  49281. }
  49282. void MultiDocumentPanel::addWindow (Component* component)
  49283. {
  49284. MultiDocumentPanelWindow* const dw = createNewDocumentWindow();
  49285. dw->setResizable (true, false);
  49286. dw->setContentComponent (component, false, true);
  49287. dw->setName (component->getName());
  49288. const var bkg (component->getProperties() ["mdiDocumentBkg_"]);
  49289. dw->setBackgroundColour (bkg.isVoid() ? backgroundColour : Colour ((int) bkg));
  49290. int x = 4;
  49291. Component* const topComp = getChildComponent (getNumChildComponents() - 1);
  49292. if (topComp != 0 && topComp->getX() == x && topComp->getY() == x)
  49293. x += 16;
  49294. dw->setTopLeftPosition (x, x);
  49295. const var pos (component->getProperties() ["mdiDocumentPos_"]);
  49296. if (pos.toString().isNotEmpty())
  49297. dw->restoreWindowStateFromString (pos.toString());
  49298. addAndMakeVisible (dw);
  49299. dw->toFront (true);
  49300. }
  49301. bool MultiDocumentPanel::addDocument (Component* const component,
  49302. const Colour& docColour,
  49303. const bool deleteWhenRemoved)
  49304. {
  49305. // If you try passing a full DocumentWindow or ResizableWindow in here, you'll end up
  49306. // with a frame-within-a-frame! Just pass in the bare content component.
  49307. jassert (dynamic_cast <ResizableWindow*> (component) == 0);
  49308. if (component == 0 || (maximumNumDocuments > 0 && components.size() >= maximumNumDocuments))
  49309. return false;
  49310. components.add (component);
  49311. component->getProperties().set ("mdiDocumentDelete_", deleteWhenRemoved);
  49312. component->getProperties().set ("mdiDocumentBkg_", (int) docColour.getARGB());
  49313. component->addComponentListener (this);
  49314. if (mode == FloatingWindows)
  49315. {
  49316. if (isFullscreenWhenOneDocument())
  49317. {
  49318. if (components.size() == 1)
  49319. {
  49320. addAndMakeVisible (component);
  49321. }
  49322. else
  49323. {
  49324. if (components.size() == 2)
  49325. addWindow (components.getFirst());
  49326. addWindow (component);
  49327. }
  49328. }
  49329. else
  49330. {
  49331. addWindow (component);
  49332. }
  49333. }
  49334. else
  49335. {
  49336. if (tabComponent == 0 && components.size() > numDocsBeforeTabsUsed)
  49337. {
  49338. addAndMakeVisible (tabComponent = new MDITabbedComponentInternal());
  49339. Array <Component*> temp (components);
  49340. for (int i = 0; i < temp.size(); ++i)
  49341. tabComponent->addTab (temp[i]->getName(), docColour, temp[i], false);
  49342. resized();
  49343. }
  49344. else
  49345. {
  49346. if (tabComponent != 0)
  49347. tabComponent->addTab (component->getName(), docColour, component, false);
  49348. else
  49349. addAndMakeVisible (component);
  49350. }
  49351. setActiveDocument (component);
  49352. }
  49353. resized();
  49354. activeDocumentChanged();
  49355. return true;
  49356. }
  49357. bool MultiDocumentPanel::closeDocument (Component* component,
  49358. const bool checkItsOkToCloseFirst)
  49359. {
  49360. if (components.contains (component))
  49361. {
  49362. if (checkItsOkToCloseFirst && ! tryToCloseDocument (component))
  49363. return false;
  49364. component->removeComponentListener (this);
  49365. const bool shouldDelete = shouldDeleteComp (component);
  49366. component->getProperties().remove ("mdiDocumentDelete_");
  49367. component->getProperties().remove ("mdiDocumentBkg_");
  49368. if (mode == FloatingWindows)
  49369. {
  49370. for (int i = getNumChildComponents(); --i >= 0;)
  49371. {
  49372. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49373. if (dw != 0 && dw->getContentComponent() == component)
  49374. {
  49375. dw->setContentComponent (0, false);
  49376. delete dw;
  49377. break;
  49378. }
  49379. }
  49380. if (shouldDelete)
  49381. delete component;
  49382. components.removeValue (component);
  49383. if (isFullscreenWhenOneDocument() && components.size() == 1)
  49384. {
  49385. for (int i = getNumChildComponents(); --i >= 0;)
  49386. {
  49387. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49388. if (dw != 0)
  49389. {
  49390. dw->setContentComponent (0, false);
  49391. delete dw;
  49392. }
  49393. }
  49394. addAndMakeVisible (components.getFirst());
  49395. }
  49396. }
  49397. else
  49398. {
  49399. jassert (components.indexOf (component) >= 0);
  49400. if (tabComponent != 0)
  49401. {
  49402. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  49403. if (tabComponent->getTabContentComponent (i) == component)
  49404. tabComponent->removeTab (i);
  49405. }
  49406. else
  49407. {
  49408. removeChildComponent (component);
  49409. }
  49410. if (shouldDelete)
  49411. delete component;
  49412. if (tabComponent != 0 && tabComponent->getNumTabs() <= numDocsBeforeTabsUsed)
  49413. deleteAndZero (tabComponent);
  49414. components.removeValue (component);
  49415. if (components.size() > 0 && tabComponent == 0)
  49416. addAndMakeVisible (components.getFirst());
  49417. }
  49418. resized();
  49419. activeDocumentChanged();
  49420. }
  49421. else
  49422. {
  49423. jassertfalse;
  49424. }
  49425. return true;
  49426. }
  49427. int MultiDocumentPanel::getNumDocuments() const throw()
  49428. {
  49429. return components.size();
  49430. }
  49431. Component* MultiDocumentPanel::getDocument (const int index) const throw()
  49432. {
  49433. return components [index];
  49434. }
  49435. Component* MultiDocumentPanel::getActiveDocument() const throw()
  49436. {
  49437. if (mode == FloatingWindows)
  49438. {
  49439. for (int i = getNumChildComponents(); --i >= 0;)
  49440. {
  49441. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49442. if (dw != 0 && dw->isActiveWindow())
  49443. return dw->getContentComponent();
  49444. }
  49445. }
  49446. return components.getLast();
  49447. }
  49448. void MultiDocumentPanel::setActiveDocument (Component* component)
  49449. {
  49450. if (mode == FloatingWindows)
  49451. {
  49452. component = getContainerComp (component);
  49453. if (component != 0)
  49454. component->toFront (true);
  49455. }
  49456. else if (tabComponent != 0)
  49457. {
  49458. jassert (components.indexOf (component) >= 0);
  49459. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  49460. {
  49461. if (tabComponent->getTabContentComponent (i) == component)
  49462. {
  49463. tabComponent->setCurrentTabIndex (i);
  49464. break;
  49465. }
  49466. }
  49467. }
  49468. else
  49469. {
  49470. component->grabKeyboardFocus();
  49471. }
  49472. }
  49473. void MultiDocumentPanel::activeDocumentChanged()
  49474. {
  49475. }
  49476. void MultiDocumentPanel::setMaximumNumDocuments (const int newNumber)
  49477. {
  49478. maximumNumDocuments = newNumber;
  49479. }
  49480. void MultiDocumentPanel::useFullscreenWhenOneDocument (const bool shouldUseTabs)
  49481. {
  49482. numDocsBeforeTabsUsed = shouldUseTabs ? 1 : 0;
  49483. }
  49484. bool MultiDocumentPanel::isFullscreenWhenOneDocument() const throw()
  49485. {
  49486. return numDocsBeforeTabsUsed != 0;
  49487. }
  49488. void MultiDocumentPanel::setLayoutMode (const LayoutMode newLayoutMode)
  49489. {
  49490. if (mode != newLayoutMode)
  49491. {
  49492. mode = newLayoutMode;
  49493. if (mode == FloatingWindows)
  49494. {
  49495. deleteAndZero (tabComponent);
  49496. }
  49497. else
  49498. {
  49499. for (int i = getNumChildComponents(); --i >= 0;)
  49500. {
  49501. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49502. if (dw != 0)
  49503. {
  49504. dw->getContentComponent()->getProperties().set ("mdiDocumentPos_", dw->getWindowStateAsString());
  49505. dw->setContentComponent (0, false);
  49506. delete dw;
  49507. }
  49508. }
  49509. }
  49510. resized();
  49511. const Array <Component*> tempComps (components);
  49512. components.clear();
  49513. for (int i = 0; i < tempComps.size(); ++i)
  49514. {
  49515. Component* const c = tempComps.getUnchecked(i);
  49516. addDocument (c,
  49517. Colour ((int) c->getProperties().getWithDefault ("mdiDocumentBkg_", (int) Colours::white.getARGB())),
  49518. shouldDeleteComp (c));
  49519. }
  49520. }
  49521. }
  49522. void MultiDocumentPanel::setBackgroundColour (const Colour& newBackgroundColour)
  49523. {
  49524. if (backgroundColour != newBackgroundColour)
  49525. {
  49526. backgroundColour = newBackgroundColour;
  49527. setOpaque (newBackgroundColour.isOpaque());
  49528. repaint();
  49529. }
  49530. }
  49531. void MultiDocumentPanel::paint (Graphics& g)
  49532. {
  49533. g.fillAll (backgroundColour);
  49534. }
  49535. void MultiDocumentPanel::resized()
  49536. {
  49537. if (mode == MaximisedWindowsWithTabs || components.size() == numDocsBeforeTabsUsed)
  49538. {
  49539. for (int i = getNumChildComponents(); --i >= 0;)
  49540. getChildComponent (i)->setBounds (getLocalBounds());
  49541. }
  49542. setWantsKeyboardFocus (components.size() == 0);
  49543. }
  49544. Component* MultiDocumentPanel::getContainerComp (Component* c) const
  49545. {
  49546. if (mode == FloatingWindows)
  49547. {
  49548. for (int i = 0; i < getNumChildComponents(); ++i)
  49549. {
  49550. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49551. if (dw != 0 && dw->getContentComponent() == c)
  49552. {
  49553. c = dw;
  49554. break;
  49555. }
  49556. }
  49557. }
  49558. return c;
  49559. }
  49560. void MultiDocumentPanel::componentNameChanged (Component&)
  49561. {
  49562. if (mode == FloatingWindows)
  49563. {
  49564. for (int i = 0; i < getNumChildComponents(); ++i)
  49565. {
  49566. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49567. if (dw != 0)
  49568. dw->setName (dw->getContentComponent()->getName());
  49569. }
  49570. }
  49571. else if (tabComponent != 0)
  49572. {
  49573. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  49574. tabComponent->setTabName (i, tabComponent->getTabContentComponent (i)->getName());
  49575. }
  49576. }
  49577. void MultiDocumentPanel::updateOrder()
  49578. {
  49579. const Array <Component*> oldList (components);
  49580. if (mode == FloatingWindows)
  49581. {
  49582. components.clear();
  49583. for (int i = 0; i < getNumChildComponents(); ++i)
  49584. {
  49585. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49586. if (dw != 0)
  49587. components.add (dw->getContentComponent());
  49588. }
  49589. }
  49590. else
  49591. {
  49592. if (tabComponent != 0)
  49593. {
  49594. Component* const current = tabComponent->getCurrentContentComponent();
  49595. if (current != 0)
  49596. {
  49597. components.removeValue (current);
  49598. components.add (current);
  49599. }
  49600. }
  49601. }
  49602. if (components != oldList)
  49603. activeDocumentChanged();
  49604. }
  49605. END_JUCE_NAMESPACE
  49606. /*** End of inlined file: juce_MultiDocumentPanel.cpp ***/
  49607. /*** Start of inlined file: juce_ResizableBorderComponent.cpp ***/
  49608. BEGIN_JUCE_NAMESPACE
  49609. ResizableBorderComponent::Zone::Zone (int zoneFlags) throw()
  49610. : zone (zoneFlags)
  49611. {
  49612. }
  49613. ResizableBorderComponent::Zone::Zone (const ResizableBorderComponent::Zone& other) throw() : zone (other.zone) {}
  49614. ResizableBorderComponent::Zone& ResizableBorderComponent::Zone::operator= (const ResizableBorderComponent::Zone& other) throw() { zone = other.zone; return *this; }
  49615. bool ResizableBorderComponent::Zone::operator== (const ResizableBorderComponent::Zone& other) const throw() { return zone == other.zone; }
  49616. bool ResizableBorderComponent::Zone::operator!= (const ResizableBorderComponent::Zone& other) const throw() { return zone != other.zone; }
  49617. const ResizableBorderComponent::Zone ResizableBorderComponent::Zone::fromPositionOnBorder (const Rectangle<int>& totalSize,
  49618. const BorderSize& border,
  49619. const Point<int>& position)
  49620. {
  49621. int z = 0;
  49622. if (totalSize.contains (position)
  49623. && ! border.subtractedFrom (totalSize).contains (position))
  49624. {
  49625. const int minW = jmax (totalSize.getWidth() / 10, jmin (10, totalSize.getWidth() / 3));
  49626. if (position.getX() < jmax (border.getLeft(), minW))
  49627. z |= left;
  49628. else if (position.getX() >= totalSize.getWidth() - jmax (border.getRight(), minW))
  49629. z |= right;
  49630. const int minH = jmax (totalSize.getHeight() / 10, jmin (10, totalSize.getHeight() / 3));
  49631. if (position.getY() < jmax (border.getTop(), minH))
  49632. z |= top;
  49633. else if (position.getY() >= totalSize.getHeight() - jmax (border.getBottom(), minH))
  49634. z |= bottom;
  49635. }
  49636. return Zone (z);
  49637. }
  49638. const MouseCursor ResizableBorderComponent::Zone::getMouseCursor() const throw()
  49639. {
  49640. MouseCursor::StandardCursorType mc = MouseCursor::NormalCursor;
  49641. switch (zone)
  49642. {
  49643. case (left | top): mc = MouseCursor::TopLeftCornerResizeCursor; break;
  49644. case top: mc = MouseCursor::TopEdgeResizeCursor; break;
  49645. case (right | top): mc = MouseCursor::TopRightCornerResizeCursor; break;
  49646. case left: mc = MouseCursor::LeftEdgeResizeCursor; break;
  49647. case right: mc = MouseCursor::RightEdgeResizeCursor; break;
  49648. case (left | bottom): mc = MouseCursor::BottomLeftCornerResizeCursor; break;
  49649. case bottom: mc = MouseCursor::BottomEdgeResizeCursor; break;
  49650. case (right | bottom): mc = MouseCursor::BottomRightCornerResizeCursor; break;
  49651. default: break;
  49652. }
  49653. return mc;
  49654. }
  49655. const Rectangle<int> ResizableBorderComponent::Zone::resizeRectangleBy (Rectangle<int> b, const Point<int>& offset) const throw()
  49656. {
  49657. if (isDraggingWholeObject())
  49658. return b + offset;
  49659. if (isDraggingLeftEdge())
  49660. b.setLeft (b.getX() + offset.getX());
  49661. if (isDraggingRightEdge())
  49662. b.setWidth (jmax (0, b.getWidth() + offset.getX()));
  49663. if (isDraggingTopEdge())
  49664. b.setTop (b.getY() + offset.getY());
  49665. if (isDraggingBottomEdge())
  49666. b.setHeight (jmax (0, b.getHeight() + offset.getY()));
  49667. return b;
  49668. }
  49669. const Rectangle<float> ResizableBorderComponent::Zone::resizeRectangleBy (Rectangle<float> b, const Point<float>& offset) const throw()
  49670. {
  49671. if (isDraggingWholeObject())
  49672. return b + offset;
  49673. if (isDraggingLeftEdge())
  49674. b.setLeft (b.getX() + offset.getX());
  49675. if (isDraggingRightEdge())
  49676. b.setWidth (jmax (0.0f, b.getWidth() + offset.getX()));
  49677. if (isDraggingTopEdge())
  49678. b.setTop (b.getY() + offset.getY());
  49679. if (isDraggingBottomEdge())
  49680. b.setHeight (jmax (0.0f, b.getHeight() + offset.getY()));
  49681. return b;
  49682. }
  49683. ResizableBorderComponent::ResizableBorderComponent (Component* const componentToResize,
  49684. ComponentBoundsConstrainer* const constrainer_)
  49685. : component (componentToResize),
  49686. constrainer (constrainer_),
  49687. borderSize (5),
  49688. mouseZone (0)
  49689. {
  49690. }
  49691. ResizableBorderComponent::~ResizableBorderComponent()
  49692. {
  49693. }
  49694. void ResizableBorderComponent::paint (Graphics& g)
  49695. {
  49696. getLookAndFeel().drawResizableFrame (g, getWidth(), getHeight(), borderSize);
  49697. }
  49698. void ResizableBorderComponent::mouseEnter (const MouseEvent& e)
  49699. {
  49700. updateMouseZone (e);
  49701. }
  49702. void ResizableBorderComponent::mouseMove (const MouseEvent& e)
  49703. {
  49704. updateMouseZone (e);
  49705. }
  49706. void ResizableBorderComponent::mouseDown (const MouseEvent& e)
  49707. {
  49708. if (component == 0)
  49709. {
  49710. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  49711. return;
  49712. }
  49713. updateMouseZone (e);
  49714. originalBounds = component->getBounds();
  49715. if (constrainer != 0)
  49716. constrainer->resizeStart();
  49717. }
  49718. void ResizableBorderComponent::mouseDrag (const MouseEvent& e)
  49719. {
  49720. if (component == 0)
  49721. {
  49722. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  49723. return;
  49724. }
  49725. const Rectangle<int> bounds (mouseZone.resizeRectangleBy (originalBounds, e.getOffsetFromDragStart()));
  49726. if (constrainer != 0)
  49727. constrainer->setBoundsForComponent (component, bounds,
  49728. mouseZone.isDraggingTopEdge(),
  49729. mouseZone.isDraggingLeftEdge(),
  49730. mouseZone.isDraggingBottomEdge(),
  49731. mouseZone.isDraggingRightEdge());
  49732. else
  49733. component->setBounds (bounds);
  49734. }
  49735. void ResizableBorderComponent::mouseUp (const MouseEvent&)
  49736. {
  49737. if (constrainer != 0)
  49738. constrainer->resizeEnd();
  49739. }
  49740. bool ResizableBorderComponent::hitTest (int x, int y)
  49741. {
  49742. return x < borderSize.getLeft()
  49743. || x >= getWidth() - borderSize.getRight()
  49744. || y < borderSize.getTop()
  49745. || y >= getHeight() - borderSize.getBottom();
  49746. }
  49747. void ResizableBorderComponent::setBorderThickness (const BorderSize& newBorderSize)
  49748. {
  49749. if (borderSize != newBorderSize)
  49750. {
  49751. borderSize = newBorderSize;
  49752. repaint();
  49753. }
  49754. }
  49755. const BorderSize ResizableBorderComponent::getBorderThickness() const
  49756. {
  49757. return borderSize;
  49758. }
  49759. void ResizableBorderComponent::updateMouseZone (const MouseEvent& e)
  49760. {
  49761. Zone newZone (Zone::fromPositionOnBorder (getLocalBounds(), borderSize, e.getPosition()));
  49762. if (mouseZone != newZone)
  49763. {
  49764. mouseZone = newZone;
  49765. setMouseCursor (newZone.getMouseCursor());
  49766. }
  49767. }
  49768. END_JUCE_NAMESPACE
  49769. /*** End of inlined file: juce_ResizableBorderComponent.cpp ***/
  49770. /*** Start of inlined file: juce_ResizableCornerComponent.cpp ***/
  49771. BEGIN_JUCE_NAMESPACE
  49772. ResizableCornerComponent::ResizableCornerComponent (Component* const componentToResize,
  49773. ComponentBoundsConstrainer* const constrainer_)
  49774. : component (componentToResize),
  49775. constrainer (constrainer_)
  49776. {
  49777. setRepaintsOnMouseActivity (true);
  49778. setMouseCursor (MouseCursor::BottomRightCornerResizeCursor);
  49779. }
  49780. ResizableCornerComponent::~ResizableCornerComponent()
  49781. {
  49782. }
  49783. void ResizableCornerComponent::paint (Graphics& g)
  49784. {
  49785. getLookAndFeel()
  49786. .drawCornerResizer (g, getWidth(), getHeight(),
  49787. isMouseOverOrDragging(),
  49788. isMouseButtonDown());
  49789. }
  49790. void ResizableCornerComponent::mouseDown (const MouseEvent&)
  49791. {
  49792. if (component == 0)
  49793. {
  49794. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  49795. return;
  49796. }
  49797. originalBounds = component->getBounds();
  49798. if (constrainer != 0)
  49799. constrainer->resizeStart();
  49800. }
  49801. void ResizableCornerComponent::mouseDrag (const MouseEvent& e)
  49802. {
  49803. if (component == 0)
  49804. {
  49805. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  49806. return;
  49807. }
  49808. Rectangle<int> r (originalBounds.withSize (originalBounds.getWidth() + e.getDistanceFromDragStartX(),
  49809. originalBounds.getHeight() + e.getDistanceFromDragStartY()));
  49810. if (constrainer != 0)
  49811. constrainer->setBoundsForComponent (component, r, false, false, true, true);
  49812. else
  49813. component->setBounds (r);
  49814. }
  49815. void ResizableCornerComponent::mouseUp (const MouseEvent&)
  49816. {
  49817. if (constrainer != 0)
  49818. constrainer->resizeStart();
  49819. }
  49820. bool ResizableCornerComponent::hitTest (int x, int y)
  49821. {
  49822. if (getWidth() <= 0)
  49823. return false;
  49824. const int yAtX = getHeight() - (getHeight() * x / getWidth());
  49825. return y >= yAtX - getHeight() / 4;
  49826. }
  49827. END_JUCE_NAMESPACE
  49828. /*** End of inlined file: juce_ResizableCornerComponent.cpp ***/
  49829. /*** Start of inlined file: juce_ScrollBar.cpp ***/
  49830. BEGIN_JUCE_NAMESPACE
  49831. class ScrollBar::ScrollbarButton : public Button
  49832. {
  49833. public:
  49834. int direction;
  49835. ScrollbarButton (const int direction_, ScrollBar& owner_)
  49836. : Button (String::empty),
  49837. direction (direction_),
  49838. owner (owner_)
  49839. {
  49840. setWantsKeyboardFocus (false);
  49841. }
  49842. ~ScrollbarButton()
  49843. {
  49844. }
  49845. void paintButton (Graphics& g, bool over, bool down)
  49846. {
  49847. getLookAndFeel()
  49848. .drawScrollbarButton (g, owner,
  49849. getWidth(), getHeight(),
  49850. direction,
  49851. owner.isVertical(),
  49852. over, down);
  49853. }
  49854. void clicked()
  49855. {
  49856. owner.moveScrollbarInSteps ((direction == 1 || direction == 2) ? 1 : -1);
  49857. }
  49858. juce_UseDebuggingNewOperator
  49859. private:
  49860. ScrollBar& owner;
  49861. ScrollbarButton (const ScrollbarButton&);
  49862. ScrollbarButton& operator= (const ScrollbarButton&);
  49863. };
  49864. ScrollBar::ScrollBar (const bool vertical_,
  49865. const bool buttonsAreVisible)
  49866. : totalRange (0.0, 1.0),
  49867. visibleRange (0.0, 0.1),
  49868. singleStepSize (0.1),
  49869. thumbAreaStart (0),
  49870. thumbAreaSize (0),
  49871. thumbStart (0),
  49872. thumbSize (0),
  49873. initialDelayInMillisecs (100),
  49874. repeatDelayInMillisecs (50),
  49875. minimumDelayInMillisecs (10),
  49876. vertical (vertical_),
  49877. isDraggingThumb (false),
  49878. autohides (true)
  49879. {
  49880. setButtonVisibility (buttonsAreVisible);
  49881. setRepaintsOnMouseActivity (true);
  49882. setFocusContainer (true);
  49883. }
  49884. ScrollBar::~ScrollBar()
  49885. {
  49886. upButton = 0;
  49887. downButton = 0;
  49888. }
  49889. void ScrollBar::setRangeLimits (const Range<double>& newRangeLimit)
  49890. {
  49891. if (totalRange != newRangeLimit)
  49892. {
  49893. totalRange = newRangeLimit;
  49894. setCurrentRange (visibleRange);
  49895. updateThumbPosition();
  49896. }
  49897. }
  49898. void ScrollBar::setRangeLimits (const double newMinimum, const double newMaximum)
  49899. {
  49900. jassert (newMaximum >= newMinimum); // these can't be the wrong way round!
  49901. setRangeLimits (Range<double> (newMinimum, newMaximum));
  49902. }
  49903. void ScrollBar::setCurrentRange (const Range<double>& newRange)
  49904. {
  49905. const Range<double> constrainedRange (totalRange.constrainRange (newRange));
  49906. if (visibleRange != constrainedRange)
  49907. {
  49908. visibleRange = constrainedRange;
  49909. updateThumbPosition();
  49910. triggerAsyncUpdate();
  49911. }
  49912. }
  49913. void ScrollBar::setCurrentRange (const double newStart, const double newSize)
  49914. {
  49915. setCurrentRange (Range<double> (newStart, newStart + newSize));
  49916. }
  49917. void ScrollBar::setCurrentRangeStart (const double newStart)
  49918. {
  49919. setCurrentRange (visibleRange.movedToStartAt (newStart));
  49920. }
  49921. void ScrollBar::setSingleStepSize (const double newSingleStepSize)
  49922. {
  49923. singleStepSize = newSingleStepSize;
  49924. }
  49925. void ScrollBar::moveScrollbarInSteps (const int howManySteps)
  49926. {
  49927. setCurrentRange (visibleRange + howManySteps * singleStepSize);
  49928. }
  49929. void ScrollBar::moveScrollbarInPages (const int howManyPages)
  49930. {
  49931. setCurrentRange (visibleRange + howManyPages * visibleRange.getLength());
  49932. }
  49933. void ScrollBar::scrollToTop()
  49934. {
  49935. setCurrentRange (visibleRange.movedToStartAt (getMinimumRangeLimit()));
  49936. }
  49937. void ScrollBar::scrollToBottom()
  49938. {
  49939. setCurrentRange (visibleRange.movedToEndAt (getMaximumRangeLimit()));
  49940. }
  49941. void ScrollBar::setButtonRepeatSpeed (const int initialDelayInMillisecs_,
  49942. const int repeatDelayInMillisecs_,
  49943. const int minimumDelayInMillisecs_)
  49944. {
  49945. initialDelayInMillisecs = initialDelayInMillisecs_;
  49946. repeatDelayInMillisecs = repeatDelayInMillisecs_;
  49947. minimumDelayInMillisecs = minimumDelayInMillisecs_;
  49948. if (upButton != 0)
  49949. {
  49950. upButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  49951. downButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  49952. }
  49953. }
  49954. void ScrollBar::addListener (ScrollBarListener* const listener)
  49955. {
  49956. listeners.add (listener);
  49957. }
  49958. void ScrollBar::removeListener (ScrollBarListener* const listener)
  49959. {
  49960. listeners.remove (listener);
  49961. }
  49962. void ScrollBar::handleAsyncUpdate()
  49963. {
  49964. double start = visibleRange.getStart(); // (need to use a temp variable for VC7 compatibility)
  49965. listeners.call (&ScrollBarListener::scrollBarMoved, this, start);
  49966. }
  49967. void ScrollBar::updateThumbPosition()
  49968. {
  49969. int newThumbSize = roundToInt (totalRange.getLength() > 0 ? (visibleRange.getLength() * thumbAreaSize) / totalRange.getLength()
  49970. : thumbAreaSize);
  49971. if (newThumbSize < getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  49972. newThumbSize = jmin (getLookAndFeel().getMinimumScrollbarThumbSize (*this), thumbAreaSize - 1);
  49973. if (newThumbSize > thumbAreaSize)
  49974. newThumbSize = thumbAreaSize;
  49975. int newThumbStart = thumbAreaStart;
  49976. if (totalRange.getLength() > visibleRange.getLength())
  49977. newThumbStart += roundToInt (((visibleRange.getStart() - totalRange.getStart()) * (thumbAreaSize - newThumbSize))
  49978. / (totalRange.getLength() - visibleRange.getLength()));
  49979. setVisible ((! autohides) || (totalRange.getLength() > visibleRange.getLength() && visibleRange.getLength() > 0.0));
  49980. if (thumbStart != newThumbStart || thumbSize != newThumbSize)
  49981. {
  49982. const int repaintStart = jmin (thumbStart, newThumbStart) - 4;
  49983. const int repaintSize = jmax (thumbStart + thumbSize, newThumbStart + newThumbSize) + 8 - repaintStart;
  49984. if (vertical)
  49985. repaint (0, repaintStart, getWidth(), repaintSize);
  49986. else
  49987. repaint (repaintStart, 0, repaintSize, getHeight());
  49988. thumbStart = newThumbStart;
  49989. thumbSize = newThumbSize;
  49990. }
  49991. }
  49992. void ScrollBar::setOrientation (const bool shouldBeVertical)
  49993. {
  49994. if (vertical != shouldBeVertical)
  49995. {
  49996. vertical = shouldBeVertical;
  49997. if (upButton != 0)
  49998. {
  49999. upButton->direction = vertical ? 0 : 3;
  50000. downButton->direction = vertical ? 2 : 1;
  50001. }
  50002. updateThumbPosition();
  50003. }
  50004. }
  50005. void ScrollBar::setButtonVisibility (const bool buttonsAreVisible)
  50006. {
  50007. upButton = 0;
  50008. downButton = 0;
  50009. if (buttonsAreVisible)
  50010. {
  50011. addAndMakeVisible (upButton = new ScrollbarButton (vertical ? 0 : 3, *this));
  50012. addAndMakeVisible (downButton = new ScrollbarButton (vertical ? 2 : 1, *this));
  50013. setButtonRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50014. }
  50015. updateThumbPosition();
  50016. }
  50017. void ScrollBar::setAutoHide (const bool shouldHideWhenFullRange)
  50018. {
  50019. autohides = shouldHideWhenFullRange;
  50020. updateThumbPosition();
  50021. }
  50022. bool ScrollBar::autoHides() const throw()
  50023. {
  50024. return autohides;
  50025. }
  50026. void ScrollBar::paint (Graphics& g)
  50027. {
  50028. if (thumbAreaSize > 0)
  50029. {
  50030. LookAndFeel& lf = getLookAndFeel();
  50031. const int thumb = (thumbAreaSize > lf.getMinimumScrollbarThumbSize (*this))
  50032. ? thumbSize : 0;
  50033. if (vertical)
  50034. {
  50035. lf.drawScrollbar (g, *this,
  50036. 0, thumbAreaStart,
  50037. getWidth(), thumbAreaSize,
  50038. vertical,
  50039. thumbStart, thumb,
  50040. isMouseOver(), isMouseButtonDown());
  50041. }
  50042. else
  50043. {
  50044. lf.drawScrollbar (g, *this,
  50045. thumbAreaStart, 0,
  50046. thumbAreaSize, getHeight(),
  50047. vertical,
  50048. thumbStart, thumb,
  50049. isMouseOver(), isMouseButtonDown());
  50050. }
  50051. }
  50052. }
  50053. void ScrollBar::lookAndFeelChanged()
  50054. {
  50055. setComponentEffect (getLookAndFeel().getScrollbarEffect());
  50056. }
  50057. void ScrollBar::resized()
  50058. {
  50059. const int length = ((vertical) ? getHeight() : getWidth());
  50060. const int buttonSize = (upButton != 0) ? jmin (getLookAndFeel().getScrollbarButtonSize (*this), (length >> 1))
  50061. : 0;
  50062. if (length < 32 + getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50063. {
  50064. thumbAreaStart = length >> 1;
  50065. thumbAreaSize = 0;
  50066. }
  50067. else
  50068. {
  50069. thumbAreaStart = buttonSize;
  50070. thumbAreaSize = length - (buttonSize << 1);
  50071. }
  50072. if (upButton != 0)
  50073. {
  50074. if (vertical)
  50075. {
  50076. upButton->setBounds (0, 0, getWidth(), buttonSize);
  50077. downButton->setBounds (0, thumbAreaStart + thumbAreaSize, getWidth(), buttonSize);
  50078. }
  50079. else
  50080. {
  50081. upButton->setBounds (0, 0, buttonSize, getHeight());
  50082. downButton->setBounds (thumbAreaStart + thumbAreaSize, 0, buttonSize, getHeight());
  50083. }
  50084. }
  50085. updateThumbPosition();
  50086. }
  50087. void ScrollBar::mouseDown (const MouseEvent& e)
  50088. {
  50089. isDraggingThumb = false;
  50090. lastMousePos = vertical ? e.y : e.x;
  50091. dragStartMousePos = lastMousePos;
  50092. dragStartRange = visibleRange.getStart();
  50093. if (dragStartMousePos < thumbStart)
  50094. {
  50095. moveScrollbarInPages (-1);
  50096. startTimer (400);
  50097. }
  50098. else if (dragStartMousePos >= thumbStart + thumbSize)
  50099. {
  50100. moveScrollbarInPages (1);
  50101. startTimer (400);
  50102. }
  50103. else
  50104. {
  50105. isDraggingThumb = (thumbAreaSize > getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50106. && (thumbAreaSize > thumbSize);
  50107. }
  50108. }
  50109. void ScrollBar::mouseDrag (const MouseEvent& e)
  50110. {
  50111. if (isDraggingThumb)
  50112. {
  50113. const int deltaPixels = ((vertical) ? e.y : e.x) - dragStartMousePos;
  50114. setCurrentRangeStart (dragStartRange
  50115. + deltaPixels * (totalRange.getLength() - visibleRange.getLength())
  50116. / (thumbAreaSize - thumbSize));
  50117. }
  50118. else
  50119. {
  50120. lastMousePos = (vertical) ? e.y : e.x;
  50121. }
  50122. }
  50123. void ScrollBar::mouseUp (const MouseEvent&)
  50124. {
  50125. isDraggingThumb = false;
  50126. stopTimer();
  50127. repaint();
  50128. }
  50129. void ScrollBar::mouseWheelMove (const MouseEvent&,
  50130. float wheelIncrementX,
  50131. float wheelIncrementY)
  50132. {
  50133. float increment = vertical ? wheelIncrementY : wheelIncrementX;
  50134. if (increment < 0)
  50135. increment = jmin (increment * 10.0f, -1.0f);
  50136. else if (increment > 0)
  50137. increment = jmax (increment * 10.0f, 1.0f);
  50138. setCurrentRange (visibleRange - singleStepSize * increment);
  50139. }
  50140. void ScrollBar::timerCallback()
  50141. {
  50142. if (isMouseButtonDown())
  50143. {
  50144. startTimer (40);
  50145. if (lastMousePos < thumbStart)
  50146. setCurrentRange (visibleRange - visibleRange.getLength());
  50147. else if (lastMousePos > thumbStart + thumbSize)
  50148. setCurrentRangeStart (visibleRange.getEnd());
  50149. }
  50150. else
  50151. {
  50152. stopTimer();
  50153. }
  50154. }
  50155. bool ScrollBar::keyPressed (const KeyPress& key)
  50156. {
  50157. if (! isVisible())
  50158. return false;
  50159. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  50160. moveScrollbarInSteps (-1);
  50161. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  50162. moveScrollbarInSteps (1);
  50163. else if (key.isKeyCode (KeyPress::pageUpKey))
  50164. moveScrollbarInPages (-1);
  50165. else if (key.isKeyCode (KeyPress::pageDownKey))
  50166. moveScrollbarInPages (1);
  50167. else if (key.isKeyCode (KeyPress::homeKey))
  50168. scrollToTop();
  50169. else if (key.isKeyCode (KeyPress::endKey))
  50170. scrollToBottom();
  50171. else
  50172. return false;
  50173. return true;
  50174. }
  50175. END_JUCE_NAMESPACE
  50176. /*** End of inlined file: juce_ScrollBar.cpp ***/
  50177. /*** Start of inlined file: juce_StretchableLayoutManager.cpp ***/
  50178. BEGIN_JUCE_NAMESPACE
  50179. StretchableLayoutManager::StretchableLayoutManager()
  50180. : totalSize (0)
  50181. {
  50182. }
  50183. StretchableLayoutManager::~StretchableLayoutManager()
  50184. {
  50185. }
  50186. void StretchableLayoutManager::clearAllItems()
  50187. {
  50188. items.clear();
  50189. totalSize = 0;
  50190. }
  50191. void StretchableLayoutManager::setItemLayout (const int itemIndex,
  50192. const double minimumSize,
  50193. const double maximumSize,
  50194. const double preferredSize)
  50195. {
  50196. ItemLayoutProperties* layout = getInfoFor (itemIndex);
  50197. if (layout == 0)
  50198. {
  50199. layout = new ItemLayoutProperties();
  50200. layout->itemIndex = itemIndex;
  50201. int i;
  50202. for (i = 0; i < items.size(); ++i)
  50203. if (items.getUnchecked (i)->itemIndex > itemIndex)
  50204. break;
  50205. items.insert (i, layout);
  50206. }
  50207. layout->minSize = minimumSize;
  50208. layout->maxSize = maximumSize;
  50209. layout->preferredSize = preferredSize;
  50210. layout->currentSize = 0;
  50211. }
  50212. bool StretchableLayoutManager::getItemLayout (const int itemIndex,
  50213. double& minimumSize,
  50214. double& maximumSize,
  50215. double& preferredSize) const
  50216. {
  50217. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50218. if (layout != 0)
  50219. {
  50220. minimumSize = layout->minSize;
  50221. maximumSize = layout->maxSize;
  50222. preferredSize = layout->preferredSize;
  50223. return true;
  50224. }
  50225. return false;
  50226. }
  50227. void StretchableLayoutManager::setTotalSize (const int newTotalSize)
  50228. {
  50229. totalSize = newTotalSize;
  50230. fitComponentsIntoSpace (0, items.size(), totalSize, 0);
  50231. }
  50232. int StretchableLayoutManager::getItemCurrentPosition (const int itemIndex) const
  50233. {
  50234. int pos = 0;
  50235. for (int i = 0; i < itemIndex; ++i)
  50236. {
  50237. const ItemLayoutProperties* const layout = getInfoFor (i);
  50238. if (layout != 0)
  50239. pos += layout->currentSize;
  50240. }
  50241. return pos;
  50242. }
  50243. int StretchableLayoutManager::getItemCurrentAbsoluteSize (const int itemIndex) const
  50244. {
  50245. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50246. if (layout != 0)
  50247. return layout->currentSize;
  50248. return 0;
  50249. }
  50250. double StretchableLayoutManager::getItemCurrentRelativeSize (const int itemIndex) const
  50251. {
  50252. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50253. if (layout != 0)
  50254. return -layout->currentSize / (double) totalSize;
  50255. return 0;
  50256. }
  50257. void StretchableLayoutManager::setItemPosition (const int itemIndex,
  50258. int newPosition)
  50259. {
  50260. for (int i = items.size(); --i >= 0;)
  50261. {
  50262. const ItemLayoutProperties* const layout = items.getUnchecked(i);
  50263. if (layout->itemIndex == itemIndex)
  50264. {
  50265. int realTotalSize = jmax (totalSize, getMinimumSizeOfItems (0, items.size()));
  50266. const int minSizeAfterThisComp = getMinimumSizeOfItems (i, items.size());
  50267. const int maxSizeAfterThisComp = getMaximumSizeOfItems (i + 1, items.size());
  50268. newPosition = jmax (newPosition, totalSize - maxSizeAfterThisComp - layout->currentSize);
  50269. newPosition = jmin (newPosition, realTotalSize - minSizeAfterThisComp);
  50270. int endPos = fitComponentsIntoSpace (0, i, newPosition, 0);
  50271. endPos += layout->currentSize;
  50272. fitComponentsIntoSpace (i + 1, items.size(), totalSize - endPos, endPos);
  50273. updatePrefSizesToMatchCurrentPositions();
  50274. break;
  50275. }
  50276. }
  50277. }
  50278. void StretchableLayoutManager::layOutComponents (Component** const components,
  50279. int numComponents,
  50280. int x, int y, int w, int h,
  50281. const bool vertically,
  50282. const bool resizeOtherDimension)
  50283. {
  50284. setTotalSize (vertically ? h : w);
  50285. int pos = vertically ? y : x;
  50286. for (int i = 0; i < numComponents; ++i)
  50287. {
  50288. const ItemLayoutProperties* const layout = getInfoFor (i);
  50289. if (layout != 0)
  50290. {
  50291. Component* const c = components[i];
  50292. if (c != 0)
  50293. {
  50294. if (i == numComponents - 1)
  50295. {
  50296. // if it's the last item, crop it to exactly fit the available space..
  50297. if (resizeOtherDimension)
  50298. {
  50299. if (vertically)
  50300. c->setBounds (x, pos, w, jmax (layout->currentSize, h - pos));
  50301. else
  50302. c->setBounds (pos, y, jmax (layout->currentSize, w - pos), h);
  50303. }
  50304. else
  50305. {
  50306. if (vertically)
  50307. c->setBounds (c->getX(), pos, c->getWidth(), jmax (layout->currentSize, h - pos));
  50308. else
  50309. c->setBounds (pos, c->getY(), jmax (layout->currentSize, w - pos), c->getHeight());
  50310. }
  50311. }
  50312. else
  50313. {
  50314. if (resizeOtherDimension)
  50315. {
  50316. if (vertically)
  50317. c->setBounds (x, pos, w, layout->currentSize);
  50318. else
  50319. c->setBounds (pos, y, layout->currentSize, h);
  50320. }
  50321. else
  50322. {
  50323. if (vertically)
  50324. c->setBounds (c->getX(), pos, c->getWidth(), layout->currentSize);
  50325. else
  50326. c->setBounds (pos, c->getY(), layout->currentSize, c->getHeight());
  50327. }
  50328. }
  50329. }
  50330. pos += layout->currentSize;
  50331. }
  50332. }
  50333. }
  50334. StretchableLayoutManager::ItemLayoutProperties* StretchableLayoutManager::getInfoFor (const int itemIndex) const
  50335. {
  50336. for (int i = items.size(); --i >= 0;)
  50337. if (items.getUnchecked(i)->itemIndex == itemIndex)
  50338. return items.getUnchecked(i);
  50339. return 0;
  50340. }
  50341. int StretchableLayoutManager::fitComponentsIntoSpace (const int startIndex,
  50342. const int endIndex,
  50343. const int availableSpace,
  50344. int startPos)
  50345. {
  50346. // calculate the total sizes
  50347. int i;
  50348. double totalIdealSize = 0.0;
  50349. int totalMinimums = 0;
  50350. for (i = startIndex; i < endIndex; ++i)
  50351. {
  50352. ItemLayoutProperties* const layout = items.getUnchecked (i);
  50353. layout->currentSize = sizeToRealSize (layout->minSize, totalSize);
  50354. totalMinimums += layout->currentSize;
  50355. totalIdealSize += sizeToRealSize (layout->preferredSize, availableSpace);
  50356. }
  50357. if (totalIdealSize <= 0)
  50358. totalIdealSize = 1.0;
  50359. // now calc the best sizes..
  50360. int extraSpace = availableSpace - totalMinimums;
  50361. while (extraSpace > 0)
  50362. {
  50363. int numWantingMoreSpace = 0;
  50364. int numHavingTakenExtraSpace = 0;
  50365. // first figure out how many comps want a slice of the extra space..
  50366. for (i = startIndex; i < endIndex; ++i)
  50367. {
  50368. ItemLayoutProperties* const layout = items.getUnchecked (i);
  50369. double sizeWanted = sizeToRealSize (layout->preferredSize, availableSpace);
  50370. const int bestSize = jlimit (layout->currentSize,
  50371. jmax (layout->currentSize,
  50372. sizeToRealSize (layout->maxSize, totalSize)),
  50373. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  50374. if (bestSize > layout->currentSize)
  50375. ++numWantingMoreSpace;
  50376. }
  50377. // ..share out the extra space..
  50378. for (i = startIndex; i < endIndex; ++i)
  50379. {
  50380. ItemLayoutProperties* const layout = items.getUnchecked (i);
  50381. double sizeWanted = sizeToRealSize (layout->preferredSize, availableSpace);
  50382. int bestSize = jlimit (layout->currentSize,
  50383. jmax (layout->currentSize, sizeToRealSize (layout->maxSize, totalSize)),
  50384. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  50385. const int extraWanted = bestSize - layout->currentSize;
  50386. if (extraWanted > 0)
  50387. {
  50388. const int extraAllowed = jmin (extraWanted,
  50389. extraSpace / jmax (1, numWantingMoreSpace));
  50390. if (extraAllowed > 0)
  50391. {
  50392. ++numHavingTakenExtraSpace;
  50393. --numWantingMoreSpace;
  50394. layout->currentSize += extraAllowed;
  50395. extraSpace -= extraAllowed;
  50396. }
  50397. }
  50398. }
  50399. if (numHavingTakenExtraSpace <= 0)
  50400. break;
  50401. }
  50402. // ..and calculate the end position
  50403. for (i = startIndex; i < endIndex; ++i)
  50404. {
  50405. ItemLayoutProperties* const layout = items.getUnchecked(i);
  50406. startPos += layout->currentSize;
  50407. }
  50408. return startPos;
  50409. }
  50410. int StretchableLayoutManager::getMinimumSizeOfItems (const int startIndex,
  50411. const int endIndex) const
  50412. {
  50413. int totalMinimums = 0;
  50414. for (int i = startIndex; i < endIndex; ++i)
  50415. totalMinimums += sizeToRealSize (items.getUnchecked (i)->minSize, totalSize);
  50416. return totalMinimums;
  50417. }
  50418. int StretchableLayoutManager::getMaximumSizeOfItems (const int startIndex, const int endIndex) const
  50419. {
  50420. int totalMaximums = 0;
  50421. for (int i = startIndex; i < endIndex; ++i)
  50422. totalMaximums += sizeToRealSize (items.getUnchecked (i)->maxSize, totalSize);
  50423. return totalMaximums;
  50424. }
  50425. void StretchableLayoutManager::updatePrefSizesToMatchCurrentPositions()
  50426. {
  50427. for (int i = 0; i < items.size(); ++i)
  50428. {
  50429. ItemLayoutProperties* const layout = items.getUnchecked (i);
  50430. layout->preferredSize
  50431. = (layout->preferredSize < 0) ? getItemCurrentRelativeSize (i)
  50432. : getItemCurrentAbsoluteSize (i);
  50433. }
  50434. }
  50435. int StretchableLayoutManager::sizeToRealSize (double size, int totalSpace)
  50436. {
  50437. if (size < 0)
  50438. size *= -totalSpace;
  50439. return roundToInt (size);
  50440. }
  50441. END_JUCE_NAMESPACE
  50442. /*** End of inlined file: juce_StretchableLayoutManager.cpp ***/
  50443. /*** Start of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  50444. BEGIN_JUCE_NAMESPACE
  50445. StretchableLayoutResizerBar::StretchableLayoutResizerBar (StretchableLayoutManager* layout_,
  50446. const int itemIndex_,
  50447. const bool isVertical_)
  50448. : layout (layout_),
  50449. itemIndex (itemIndex_),
  50450. isVertical (isVertical_)
  50451. {
  50452. setRepaintsOnMouseActivity (true);
  50453. setMouseCursor (MouseCursor (isVertical_ ? MouseCursor::LeftRightResizeCursor
  50454. : MouseCursor::UpDownResizeCursor));
  50455. }
  50456. StretchableLayoutResizerBar::~StretchableLayoutResizerBar()
  50457. {
  50458. }
  50459. void StretchableLayoutResizerBar::paint (Graphics& g)
  50460. {
  50461. getLookAndFeel().drawStretchableLayoutResizerBar (g,
  50462. getWidth(), getHeight(),
  50463. isVertical,
  50464. isMouseOver(),
  50465. isMouseButtonDown());
  50466. }
  50467. void StretchableLayoutResizerBar::mouseDown (const MouseEvent&)
  50468. {
  50469. mouseDownPos = layout->getItemCurrentPosition (itemIndex);
  50470. }
  50471. void StretchableLayoutResizerBar::mouseDrag (const MouseEvent& e)
  50472. {
  50473. const int desiredPos = mouseDownPos + (isVertical ? e.getDistanceFromDragStartX()
  50474. : e.getDistanceFromDragStartY());
  50475. layout->setItemPosition (itemIndex, desiredPos);
  50476. hasBeenMoved();
  50477. }
  50478. void StretchableLayoutResizerBar::hasBeenMoved()
  50479. {
  50480. if (getParentComponent() != 0)
  50481. getParentComponent()->resized();
  50482. }
  50483. END_JUCE_NAMESPACE
  50484. /*** End of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  50485. /*** Start of inlined file: juce_StretchableObjectResizer.cpp ***/
  50486. BEGIN_JUCE_NAMESPACE
  50487. StretchableObjectResizer::StretchableObjectResizer()
  50488. {
  50489. }
  50490. StretchableObjectResizer::~StretchableObjectResizer()
  50491. {
  50492. }
  50493. void StretchableObjectResizer::addItem (const double size,
  50494. const double minSize, const double maxSize,
  50495. const int order)
  50496. {
  50497. // the order must be >= 0 but less than the maximum integer value.
  50498. jassert (order >= 0 && order < std::numeric_limits<int>::max());
  50499. Item* const item = new Item();
  50500. item->size = size;
  50501. item->minSize = minSize;
  50502. item->maxSize = maxSize;
  50503. item->order = order;
  50504. items.add (item);
  50505. }
  50506. double StretchableObjectResizer::getItemSize (const int index) const throw()
  50507. {
  50508. const Item* const it = items [index];
  50509. return it != 0 ? it->size : 0;
  50510. }
  50511. void StretchableObjectResizer::resizeToFit (const double targetSize)
  50512. {
  50513. int order = 0;
  50514. for (;;)
  50515. {
  50516. double currentSize = 0;
  50517. double minSize = 0;
  50518. double maxSize = 0;
  50519. int nextHighestOrder = std::numeric_limits<int>::max();
  50520. for (int i = 0; i < items.size(); ++i)
  50521. {
  50522. const Item* const it = items.getUnchecked(i);
  50523. currentSize += it->size;
  50524. if (it->order <= order)
  50525. {
  50526. minSize += it->minSize;
  50527. maxSize += it->maxSize;
  50528. }
  50529. else
  50530. {
  50531. minSize += it->size;
  50532. maxSize += it->size;
  50533. nextHighestOrder = jmin (nextHighestOrder, it->order);
  50534. }
  50535. }
  50536. const double thisIterationTarget = jlimit (minSize, maxSize, targetSize);
  50537. if (thisIterationTarget >= currentSize)
  50538. {
  50539. const double availableExtraSpace = maxSize - currentSize;
  50540. const double targetAmountOfExtraSpace = thisIterationTarget - currentSize;
  50541. const double scale = targetAmountOfExtraSpace / availableExtraSpace;
  50542. for (int i = 0; i < items.size(); ++i)
  50543. {
  50544. Item* const it = items.getUnchecked(i);
  50545. if (it->order <= order)
  50546. it->size = jmin (it->maxSize, it->size + (it->maxSize - it->size) * scale);
  50547. }
  50548. }
  50549. else
  50550. {
  50551. const double amountOfSlack = currentSize - minSize;
  50552. const double targetAmountOfSlack = thisIterationTarget - minSize;
  50553. const double scale = targetAmountOfSlack / amountOfSlack;
  50554. for (int i = 0; i < items.size(); ++i)
  50555. {
  50556. Item* const it = items.getUnchecked(i);
  50557. if (it->order <= order)
  50558. it->size = jmax (it->minSize, it->minSize + (it->size - it->minSize) * scale);
  50559. }
  50560. }
  50561. if (nextHighestOrder < std::numeric_limits<int>::max())
  50562. order = nextHighestOrder;
  50563. else
  50564. break;
  50565. }
  50566. }
  50567. END_JUCE_NAMESPACE
  50568. /*** End of inlined file: juce_StretchableObjectResizer.cpp ***/
  50569. /*** Start of inlined file: juce_TabbedButtonBar.cpp ***/
  50570. BEGIN_JUCE_NAMESPACE
  50571. TabBarButton::TabBarButton (const String& name,
  50572. TabbedButtonBar* const owner_,
  50573. const int index)
  50574. : Button (name),
  50575. owner (owner_),
  50576. tabIndex (index),
  50577. overlapPixels (0)
  50578. {
  50579. shadow.setShadowProperties (2.2f, 0.7f, 0, 0);
  50580. setComponentEffect (&shadow);
  50581. setWantsKeyboardFocus (false);
  50582. }
  50583. TabBarButton::~TabBarButton()
  50584. {
  50585. }
  50586. void TabBarButton::paintButton (Graphics& g,
  50587. bool isMouseOverButton,
  50588. bool isButtonDown)
  50589. {
  50590. int x, y, w, h;
  50591. getActiveArea (x, y, w, h);
  50592. g.setOrigin (x, y);
  50593. getLookAndFeel()
  50594. .drawTabButton (g, w, h,
  50595. owner->getTabBackgroundColour (tabIndex),
  50596. tabIndex, getButtonText(), *this,
  50597. owner->getOrientation(),
  50598. isMouseOverButton, isButtonDown,
  50599. getToggleState());
  50600. }
  50601. void TabBarButton::clicked (const ModifierKeys& mods)
  50602. {
  50603. if (mods.isPopupMenu())
  50604. owner->popupMenuClickOnTab (tabIndex, getButtonText());
  50605. else
  50606. owner->setCurrentTabIndex (tabIndex);
  50607. }
  50608. bool TabBarButton::hitTest (int mx, int my)
  50609. {
  50610. int x, y, w, h;
  50611. getActiveArea (x, y, w, h);
  50612. if (owner->getOrientation() == TabbedButtonBar::TabsAtLeft
  50613. || owner->getOrientation() == TabbedButtonBar::TabsAtRight)
  50614. {
  50615. if (((unsigned int) mx) < (unsigned int) getWidth()
  50616. && my >= y + overlapPixels
  50617. && my < y + h - overlapPixels)
  50618. return true;
  50619. }
  50620. else
  50621. {
  50622. if (mx >= x + overlapPixels && mx < x + w - overlapPixels
  50623. && ((unsigned int) my) < (unsigned int) getHeight())
  50624. return true;
  50625. }
  50626. Path p;
  50627. getLookAndFeel()
  50628. .createTabButtonShape (p, w, h, tabIndex, getButtonText(), *this,
  50629. owner->getOrientation(),
  50630. false, false, getToggleState());
  50631. return p.contains ((float) (mx - x),
  50632. (float) (my - y));
  50633. }
  50634. int TabBarButton::getBestTabLength (const int depth)
  50635. {
  50636. return jlimit (depth * 2,
  50637. depth * 7,
  50638. getLookAndFeel().getTabButtonBestWidth (tabIndex, getButtonText(), depth, *this));
  50639. }
  50640. void TabBarButton::getActiveArea (int& x, int& y, int& w, int& h)
  50641. {
  50642. x = 0;
  50643. y = 0;
  50644. int r = getWidth();
  50645. int b = getHeight();
  50646. const int spaceAroundImage = getLookAndFeel().getTabButtonSpaceAroundImage();
  50647. if (owner->getOrientation() != TabbedButtonBar::TabsAtLeft)
  50648. r -= spaceAroundImage;
  50649. if (owner->getOrientation() != TabbedButtonBar::TabsAtRight)
  50650. x += spaceAroundImage;
  50651. if (owner->getOrientation() != TabbedButtonBar::TabsAtBottom)
  50652. y += spaceAroundImage;
  50653. if (owner->getOrientation() != TabbedButtonBar::TabsAtTop)
  50654. b -= spaceAroundImage;
  50655. w = r - x;
  50656. h = b - y;
  50657. }
  50658. class TabAreaBehindFrontButtonComponent : public Component
  50659. {
  50660. public:
  50661. TabAreaBehindFrontButtonComponent (TabbedButtonBar* const owner_)
  50662. : owner (owner_)
  50663. {
  50664. setInterceptsMouseClicks (false, false);
  50665. }
  50666. ~TabAreaBehindFrontButtonComponent()
  50667. {
  50668. }
  50669. void paint (Graphics& g)
  50670. {
  50671. getLookAndFeel()
  50672. .drawTabAreaBehindFrontButton (g, getWidth(), getHeight(),
  50673. *owner, owner->getOrientation());
  50674. }
  50675. void enablementChanged()
  50676. {
  50677. repaint();
  50678. }
  50679. private:
  50680. TabbedButtonBar* const owner;
  50681. TabAreaBehindFrontButtonComponent (const TabAreaBehindFrontButtonComponent&);
  50682. TabAreaBehindFrontButtonComponent& operator= (const TabAreaBehindFrontButtonComponent&);
  50683. };
  50684. TabbedButtonBar::TabbedButtonBar (const Orientation orientation_)
  50685. : orientation (orientation_),
  50686. currentTabIndex (-1)
  50687. {
  50688. setInterceptsMouseClicks (false, true);
  50689. addAndMakeVisible (behindFrontTab = new TabAreaBehindFrontButtonComponent (this));
  50690. setFocusContainer (true);
  50691. }
  50692. TabbedButtonBar::~TabbedButtonBar()
  50693. {
  50694. extraTabsButton = 0;
  50695. deleteAllChildren();
  50696. }
  50697. void TabbedButtonBar::setOrientation (const Orientation newOrientation)
  50698. {
  50699. orientation = newOrientation;
  50700. for (int i = getNumChildComponents(); --i >= 0;)
  50701. getChildComponent (i)->resized();
  50702. resized();
  50703. }
  50704. TabBarButton* TabbedButtonBar::createTabButton (const String& name, const int index)
  50705. {
  50706. return new TabBarButton (name, this, index);
  50707. }
  50708. void TabbedButtonBar::clearTabs()
  50709. {
  50710. tabs.clear();
  50711. tabColours.clear();
  50712. currentTabIndex = -1;
  50713. extraTabsButton = 0;
  50714. removeChildComponent (behindFrontTab);
  50715. deleteAllChildren();
  50716. addChildComponent (behindFrontTab);
  50717. setCurrentTabIndex (-1);
  50718. }
  50719. void TabbedButtonBar::addTab (const String& tabName,
  50720. const Colour& tabBackgroundColour,
  50721. int insertIndex)
  50722. {
  50723. jassert (tabName.isNotEmpty()); // you have to give them all a name..
  50724. if (tabName.isNotEmpty())
  50725. {
  50726. if (((unsigned int) insertIndex) > (unsigned int) tabs.size())
  50727. insertIndex = tabs.size();
  50728. for (int i = tabs.size(); --i >= insertIndex;)
  50729. {
  50730. TabBarButton* const tb = getTabButton (i);
  50731. if (tb != 0)
  50732. tb->tabIndex++;
  50733. }
  50734. tabs.insert (insertIndex, tabName);
  50735. tabColours.insert (insertIndex, tabBackgroundColour);
  50736. TabBarButton* const tb = createTabButton (tabName, insertIndex);
  50737. jassert (tb != 0); // your createTabButton() mustn't return zero!
  50738. addAndMakeVisible (tb, insertIndex);
  50739. resized();
  50740. if (currentTabIndex < 0)
  50741. setCurrentTabIndex (0);
  50742. }
  50743. }
  50744. void TabbedButtonBar::setTabName (const int tabIndex,
  50745. const String& newName)
  50746. {
  50747. if (((unsigned int) tabIndex) < (unsigned int) tabs.size()
  50748. && tabs[tabIndex] != newName)
  50749. {
  50750. tabs.set (tabIndex, newName);
  50751. TabBarButton* const tb = getTabButton (tabIndex);
  50752. if (tb != 0)
  50753. tb->setButtonText (newName);
  50754. resized();
  50755. }
  50756. }
  50757. void TabbedButtonBar::removeTab (const int tabIndex)
  50758. {
  50759. if (((unsigned int) tabIndex) < (unsigned int) tabs.size())
  50760. {
  50761. const int oldTabIndex = currentTabIndex;
  50762. if (currentTabIndex == tabIndex)
  50763. currentTabIndex = -1;
  50764. tabs.remove (tabIndex);
  50765. tabColours.remove (tabIndex);
  50766. delete getTabButton (tabIndex);
  50767. for (int i = tabIndex + 1; i <= tabs.size(); ++i)
  50768. {
  50769. TabBarButton* const tb = getTabButton (i);
  50770. if (tb != 0)
  50771. tb->tabIndex--;
  50772. }
  50773. resized();
  50774. setCurrentTabIndex (jlimit (0, jmax (0, tabs.size() - 1), oldTabIndex));
  50775. }
  50776. }
  50777. void TabbedButtonBar::moveTab (const int currentIndex,
  50778. const int newIndex)
  50779. {
  50780. tabs.move (currentIndex, newIndex);
  50781. tabColours.move (currentIndex, newIndex);
  50782. resized();
  50783. }
  50784. int TabbedButtonBar::getNumTabs() const
  50785. {
  50786. return tabs.size();
  50787. }
  50788. const StringArray TabbedButtonBar::getTabNames() const
  50789. {
  50790. return tabs;
  50791. }
  50792. void TabbedButtonBar::setCurrentTabIndex (int newIndex, const bool sendChangeMessage_)
  50793. {
  50794. if (currentTabIndex != newIndex)
  50795. {
  50796. if (((unsigned int) newIndex) >= (unsigned int) tabs.size())
  50797. newIndex = -1;
  50798. currentTabIndex = newIndex;
  50799. for (int i = 0; i < getNumChildComponents(); ++i)
  50800. {
  50801. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  50802. if (tb != 0)
  50803. tb->setToggleState (tb->tabIndex == newIndex, false);
  50804. }
  50805. resized();
  50806. if (sendChangeMessage_)
  50807. sendChangeMessage (this);
  50808. currentTabChanged (newIndex, newIndex >= 0 ? tabs [newIndex] : String::empty);
  50809. }
  50810. }
  50811. TabBarButton* TabbedButtonBar::getTabButton (const int index) const
  50812. {
  50813. for (int i = getNumChildComponents(); --i >= 0;)
  50814. {
  50815. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  50816. if (tb != 0 && tb->tabIndex == index)
  50817. return tb;
  50818. }
  50819. return 0;
  50820. }
  50821. void TabbedButtonBar::lookAndFeelChanged()
  50822. {
  50823. extraTabsButton = 0;
  50824. resized();
  50825. }
  50826. void TabbedButtonBar::resized()
  50827. {
  50828. const double minimumScale = 0.7;
  50829. int depth = getWidth();
  50830. int length = getHeight();
  50831. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  50832. swapVariables (depth, length);
  50833. const int overlap = getLookAndFeel().getTabButtonOverlap (depth)
  50834. + getLookAndFeel().getTabButtonSpaceAroundImage() * 2;
  50835. int i, totalLength = overlap;
  50836. int numVisibleButtons = tabs.size();
  50837. for (i = 0; i < getNumChildComponents(); ++i)
  50838. {
  50839. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  50840. if (tb != 0)
  50841. {
  50842. totalLength += tb->getBestTabLength (depth) - overlap;
  50843. tb->overlapPixels = overlap / 2;
  50844. }
  50845. }
  50846. double scale = 1.0;
  50847. if (totalLength > length)
  50848. scale = jmax (minimumScale, length / (double) totalLength);
  50849. const bool isTooBig = totalLength * scale > length;
  50850. int tabsButtonPos = 0;
  50851. if (isTooBig)
  50852. {
  50853. if (extraTabsButton == 0)
  50854. {
  50855. addAndMakeVisible (extraTabsButton = getLookAndFeel().createTabBarExtrasButton());
  50856. extraTabsButton->addButtonListener (this);
  50857. extraTabsButton->setAlwaysOnTop (true);
  50858. extraTabsButton->setTriggeredOnMouseDown (true);
  50859. }
  50860. const int buttonSize = jmin (proportionOfWidth (0.7f), proportionOfHeight (0.7f));
  50861. extraTabsButton->setSize (buttonSize, buttonSize);
  50862. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  50863. {
  50864. tabsButtonPos = getWidth() - buttonSize / 2 - 1;
  50865. extraTabsButton->setCentrePosition (tabsButtonPos, getHeight() / 2);
  50866. }
  50867. else
  50868. {
  50869. tabsButtonPos = getHeight() - buttonSize / 2 - 1;
  50870. extraTabsButton->setCentrePosition (getWidth() / 2, tabsButtonPos);
  50871. }
  50872. totalLength = 0;
  50873. for (i = 0; i < tabs.size(); ++i)
  50874. {
  50875. TabBarButton* const tb = getTabButton (i);
  50876. if (tb != 0)
  50877. {
  50878. const int newLength = totalLength + tb->getBestTabLength (depth);
  50879. if (i > 0 && newLength * minimumScale > tabsButtonPos)
  50880. {
  50881. totalLength += overlap;
  50882. break;
  50883. }
  50884. numVisibleButtons = i + 1;
  50885. totalLength = newLength - overlap;
  50886. }
  50887. }
  50888. scale = jmax (minimumScale, tabsButtonPos / (double) totalLength);
  50889. }
  50890. else
  50891. {
  50892. extraTabsButton = 0;
  50893. }
  50894. int pos = 0;
  50895. TabBarButton* frontTab = 0;
  50896. for (i = 0; i < tabs.size(); ++i)
  50897. {
  50898. TabBarButton* const tb = getTabButton (i);
  50899. if (tb != 0)
  50900. {
  50901. const int bestLength = roundToInt (scale * tb->getBestTabLength (depth));
  50902. if (i < numVisibleButtons)
  50903. {
  50904. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  50905. tb->setBounds (pos, 0, bestLength, getHeight());
  50906. else
  50907. tb->setBounds (0, pos, getWidth(), bestLength);
  50908. tb->toBack();
  50909. if (tb->tabIndex == currentTabIndex)
  50910. frontTab = tb;
  50911. tb->setVisible (true);
  50912. }
  50913. else
  50914. {
  50915. tb->setVisible (false);
  50916. }
  50917. pos += bestLength - overlap;
  50918. }
  50919. }
  50920. behindFrontTab->setBounds (getLocalBounds());
  50921. if (frontTab != 0)
  50922. {
  50923. frontTab->toFront (false);
  50924. behindFrontTab->toBehind (frontTab);
  50925. }
  50926. }
  50927. const Colour TabbedButtonBar::getTabBackgroundColour (const int tabIndex)
  50928. {
  50929. return tabColours [tabIndex];
  50930. }
  50931. void TabbedButtonBar::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  50932. {
  50933. if (((unsigned int) tabIndex) < (unsigned int) tabColours.size()
  50934. && tabColours [tabIndex] != newColour)
  50935. {
  50936. tabColours.set (tabIndex, newColour);
  50937. repaint();
  50938. }
  50939. }
  50940. void TabbedButtonBar::buttonClicked (Button* button)
  50941. {
  50942. if (button == extraTabsButton)
  50943. {
  50944. PopupMenu m;
  50945. for (int i = 0; i < tabs.size(); ++i)
  50946. {
  50947. TabBarButton* const tb = getTabButton (i);
  50948. if (tb != 0 && ! tb->isVisible())
  50949. m.addItem (tb->tabIndex + 1, tabs[i], true, i == currentTabIndex);
  50950. }
  50951. const int res = m.showAt (extraTabsButton);
  50952. if (res != 0)
  50953. setCurrentTabIndex (res - 1);
  50954. }
  50955. }
  50956. void TabbedButtonBar::currentTabChanged (const int, const String&)
  50957. {
  50958. }
  50959. void TabbedButtonBar::popupMenuClickOnTab (const int, const String&)
  50960. {
  50961. }
  50962. END_JUCE_NAMESPACE
  50963. /*** End of inlined file: juce_TabbedButtonBar.cpp ***/
  50964. /*** Start of inlined file: juce_TabbedComponent.cpp ***/
  50965. BEGIN_JUCE_NAMESPACE
  50966. class TabCompButtonBar : public TabbedButtonBar
  50967. {
  50968. public:
  50969. TabCompButtonBar (TabbedComponent* const owner_,
  50970. const TabbedButtonBar::Orientation orientation_)
  50971. : TabbedButtonBar (orientation_),
  50972. owner (owner_)
  50973. {
  50974. }
  50975. ~TabCompButtonBar()
  50976. {
  50977. }
  50978. void currentTabChanged (int newCurrentTabIndex, const String& newTabName)
  50979. {
  50980. owner->changeCallback (newCurrentTabIndex, newTabName);
  50981. }
  50982. void popupMenuClickOnTab (int tabIndex, const String& tabName)
  50983. {
  50984. owner->popupMenuClickOnTab (tabIndex, tabName);
  50985. }
  50986. const Colour getTabBackgroundColour (const int tabIndex)
  50987. {
  50988. return owner->tabs->getTabBackgroundColour (tabIndex);
  50989. }
  50990. TabBarButton* createTabButton (const String& tabName, int tabIndex)
  50991. {
  50992. return owner->createTabButton (tabName, tabIndex);
  50993. }
  50994. juce_UseDebuggingNewOperator
  50995. private:
  50996. TabbedComponent* const owner;
  50997. TabCompButtonBar (const TabCompButtonBar&);
  50998. TabCompButtonBar& operator= (const TabCompButtonBar&);
  50999. };
  51000. TabbedComponent::TabbedComponent (const TabbedButtonBar::Orientation orientation)
  51001. : panelComponent (0),
  51002. tabDepth (30),
  51003. outlineThickness (1),
  51004. edgeIndent (0)
  51005. {
  51006. addAndMakeVisible (tabs = new TabCompButtonBar (this, orientation));
  51007. }
  51008. TabbedComponent::~TabbedComponent()
  51009. {
  51010. clearTabs();
  51011. delete tabs;
  51012. }
  51013. void TabbedComponent::setOrientation (const TabbedButtonBar::Orientation orientation)
  51014. {
  51015. tabs->setOrientation (orientation);
  51016. resized();
  51017. }
  51018. TabbedButtonBar::Orientation TabbedComponent::getOrientation() const throw()
  51019. {
  51020. return tabs->getOrientation();
  51021. }
  51022. void TabbedComponent::setTabBarDepth (const int newDepth)
  51023. {
  51024. if (tabDepth != newDepth)
  51025. {
  51026. tabDepth = newDepth;
  51027. resized();
  51028. }
  51029. }
  51030. TabBarButton* TabbedComponent::createTabButton (const String& tabName, const int tabIndex)
  51031. {
  51032. return new TabBarButton (tabName, tabs, tabIndex);
  51033. }
  51034. const Identifier TabbedComponent::deleteComponentId ("deleteByTabComp_");
  51035. void TabbedComponent::clearTabs()
  51036. {
  51037. if (panelComponent != 0)
  51038. {
  51039. panelComponent->setVisible (false);
  51040. removeChildComponent (panelComponent);
  51041. panelComponent = 0;
  51042. }
  51043. tabs->clearTabs();
  51044. for (int i = contentComponents.size(); --i >= 0;)
  51045. {
  51046. Component* const c = contentComponents.getUnchecked(i);
  51047. // be careful not to delete these components until they've been removed from the tab component
  51048. jassert (c == 0 || c->isValidComponent());
  51049. if (c != 0 && (bool) c->getProperties() [deleteComponentId])
  51050. delete c;
  51051. }
  51052. contentComponents.clear();
  51053. }
  51054. void TabbedComponent::addTab (const String& tabName,
  51055. const Colour& tabBackgroundColour,
  51056. Component* const contentComponent,
  51057. const bool deleteComponentWhenNotNeeded,
  51058. const int insertIndex)
  51059. {
  51060. contentComponents.insert (insertIndex, contentComponent);
  51061. if (contentComponent != 0)
  51062. contentComponent->getProperties().set (deleteComponentId, deleteComponentWhenNotNeeded);
  51063. tabs->addTab (tabName, tabBackgroundColour, insertIndex);
  51064. }
  51065. void TabbedComponent::setTabName (const int tabIndex, const String& newName)
  51066. {
  51067. tabs->setTabName (tabIndex, newName);
  51068. }
  51069. void TabbedComponent::removeTab (const int tabIndex)
  51070. {
  51071. Component* const c = contentComponents [tabIndex];
  51072. if (c != 0 && (bool) c->getProperties() [deleteComponentId])
  51073. {
  51074. if (c == panelComponent)
  51075. panelComponent = 0;
  51076. delete c;
  51077. }
  51078. contentComponents.remove (tabIndex);
  51079. tabs->removeTab (tabIndex);
  51080. }
  51081. int TabbedComponent::getNumTabs() const
  51082. {
  51083. return tabs->getNumTabs();
  51084. }
  51085. const StringArray TabbedComponent::getTabNames() const
  51086. {
  51087. return tabs->getTabNames();
  51088. }
  51089. Component* TabbedComponent::getTabContentComponent (const int tabIndex) const throw()
  51090. {
  51091. return contentComponents [tabIndex];
  51092. }
  51093. const Colour TabbedComponent::getTabBackgroundColour (const int tabIndex) const throw()
  51094. {
  51095. return tabs->getTabBackgroundColour (tabIndex);
  51096. }
  51097. void TabbedComponent::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  51098. {
  51099. tabs->setTabBackgroundColour (tabIndex, newColour);
  51100. if (getCurrentTabIndex() == tabIndex)
  51101. repaint();
  51102. }
  51103. void TabbedComponent::setCurrentTabIndex (const int newTabIndex, const bool sendChangeMessage)
  51104. {
  51105. tabs->setCurrentTabIndex (newTabIndex, sendChangeMessage);
  51106. }
  51107. int TabbedComponent::getCurrentTabIndex() const
  51108. {
  51109. return tabs->getCurrentTabIndex();
  51110. }
  51111. const String& TabbedComponent::getCurrentTabName() const
  51112. {
  51113. return tabs->getCurrentTabName();
  51114. }
  51115. void TabbedComponent::setOutline (int thickness)
  51116. {
  51117. outlineThickness = thickness;
  51118. repaint();
  51119. }
  51120. void TabbedComponent::setIndent (const int indentThickness)
  51121. {
  51122. edgeIndent = indentThickness;
  51123. }
  51124. void TabbedComponent::paint (Graphics& g)
  51125. {
  51126. g.fillAll (findColour (backgroundColourId));
  51127. const TabbedButtonBar::Orientation o = getOrientation();
  51128. int x = 0;
  51129. int y = 0;
  51130. int r = getWidth();
  51131. int b = getHeight();
  51132. if (o == TabbedButtonBar::TabsAtTop)
  51133. y += tabDepth;
  51134. else if (o == TabbedButtonBar::TabsAtBottom)
  51135. b -= tabDepth;
  51136. else if (o == TabbedButtonBar::TabsAtLeft)
  51137. x += tabDepth;
  51138. else if (o == TabbedButtonBar::TabsAtRight)
  51139. r -= tabDepth;
  51140. g.reduceClipRegion (x, y, r - x, b - y);
  51141. g.fillAll (tabs->getTabBackgroundColour (getCurrentTabIndex()));
  51142. if (outlineThickness > 0)
  51143. {
  51144. if (o == TabbedButtonBar::TabsAtTop)
  51145. --y;
  51146. else if (o == TabbedButtonBar::TabsAtBottom)
  51147. ++b;
  51148. else if (o == TabbedButtonBar::TabsAtLeft)
  51149. --x;
  51150. else if (o == TabbedButtonBar::TabsAtRight)
  51151. ++r;
  51152. g.setColour (findColour (outlineColourId));
  51153. g.drawRect (x, y, r - x, b - y, outlineThickness);
  51154. }
  51155. }
  51156. void TabbedComponent::resized()
  51157. {
  51158. const TabbedButtonBar::Orientation o = getOrientation();
  51159. const int indent = edgeIndent + outlineThickness;
  51160. BorderSize indents (indent);
  51161. if (o == TabbedButtonBar::TabsAtTop)
  51162. {
  51163. tabs->setBounds (0, 0, getWidth(), tabDepth);
  51164. indents.setTop (tabDepth + edgeIndent);
  51165. }
  51166. else if (o == TabbedButtonBar::TabsAtBottom)
  51167. {
  51168. tabs->setBounds (0, getHeight() - tabDepth, getWidth(), tabDepth);
  51169. indents.setBottom (tabDepth + edgeIndent);
  51170. }
  51171. else if (o == TabbedButtonBar::TabsAtLeft)
  51172. {
  51173. tabs->setBounds (0, 0, tabDepth, getHeight());
  51174. indents.setLeft (tabDepth + edgeIndent);
  51175. }
  51176. else if (o == TabbedButtonBar::TabsAtRight)
  51177. {
  51178. tabs->setBounds (getWidth() - tabDepth, 0, tabDepth, getHeight());
  51179. indents.setRight (tabDepth + edgeIndent);
  51180. }
  51181. const Rectangle<int> bounds (indents.subtractedFrom (getLocalBounds()));
  51182. for (int i = contentComponents.size(); --i >= 0;)
  51183. if (contentComponents.getUnchecked (i) != 0)
  51184. contentComponents.getUnchecked (i)->setBounds (bounds);
  51185. }
  51186. void TabbedComponent::lookAndFeelChanged()
  51187. {
  51188. for (int i = contentComponents.size(); --i >= 0;)
  51189. if (contentComponents.getUnchecked (i) != 0)
  51190. contentComponents.getUnchecked (i)->lookAndFeelChanged();
  51191. }
  51192. void TabbedComponent::changeCallback (const int newCurrentTabIndex,
  51193. const String& newTabName)
  51194. {
  51195. if (panelComponent != 0)
  51196. {
  51197. panelComponent->setVisible (false);
  51198. removeChildComponent (panelComponent);
  51199. panelComponent = 0;
  51200. }
  51201. if (getCurrentTabIndex() >= 0)
  51202. {
  51203. panelComponent = contentComponents [getCurrentTabIndex()];
  51204. if (panelComponent != 0)
  51205. {
  51206. // do these ops as two stages instead of addAndMakeVisible() so that the
  51207. // component has always got a parent when it gets the visibilityChanged() callback
  51208. addChildComponent (panelComponent);
  51209. panelComponent->setVisible (true);
  51210. panelComponent->toFront (true);
  51211. }
  51212. repaint();
  51213. }
  51214. resized();
  51215. currentTabChanged (newCurrentTabIndex, newTabName);
  51216. }
  51217. void TabbedComponent::currentTabChanged (const int, const String&)
  51218. {
  51219. }
  51220. void TabbedComponent::popupMenuClickOnTab (const int, const String&)
  51221. {
  51222. }
  51223. END_JUCE_NAMESPACE
  51224. /*** End of inlined file: juce_TabbedComponent.cpp ***/
  51225. /*** Start of inlined file: juce_Viewport.cpp ***/
  51226. BEGIN_JUCE_NAMESPACE
  51227. Viewport::Viewport (const String& componentName)
  51228. : Component (componentName),
  51229. scrollBarThickness (0),
  51230. singleStepX (16),
  51231. singleStepY (16),
  51232. showHScrollbar (true),
  51233. showVScrollbar (true),
  51234. verticalScrollBar (true),
  51235. horizontalScrollBar (false)
  51236. {
  51237. // content holder is used to clip the contents so they don't overlap the scrollbars
  51238. addAndMakeVisible (&contentHolder);
  51239. contentHolder.setInterceptsMouseClicks (false, true);
  51240. addChildComponent (&verticalScrollBar);
  51241. addChildComponent (&horizontalScrollBar);
  51242. verticalScrollBar.addListener (this);
  51243. horizontalScrollBar.addListener (this);
  51244. setInterceptsMouseClicks (false, true);
  51245. setWantsKeyboardFocus (true);
  51246. }
  51247. Viewport::~Viewport()
  51248. {
  51249. contentHolder.deleteAllChildren();
  51250. }
  51251. void Viewport::visibleAreaChanged (int, int, int, int)
  51252. {
  51253. }
  51254. void Viewport::setViewedComponent (Component* const newViewedComponent)
  51255. {
  51256. if (contentComp.getComponent() != newViewedComponent)
  51257. {
  51258. {
  51259. ScopedPointer<Component> oldCompDeleter (contentComp);
  51260. contentComp = 0;
  51261. }
  51262. contentComp = newViewedComponent;
  51263. if (contentComp != 0)
  51264. {
  51265. contentComp->setTopLeftPosition (0, 0);
  51266. contentHolder.addAndMakeVisible (contentComp);
  51267. contentComp->addComponentListener (this);
  51268. }
  51269. updateVisibleArea();
  51270. }
  51271. }
  51272. int Viewport::getMaximumVisibleWidth() const
  51273. {
  51274. return contentHolder.getWidth();
  51275. }
  51276. int Viewport::getMaximumVisibleHeight() const
  51277. {
  51278. return contentHolder.getHeight();
  51279. }
  51280. void Viewport::setViewPosition (const int xPixelsOffset, const int yPixelsOffset)
  51281. {
  51282. if (contentComp != 0)
  51283. contentComp->setTopLeftPosition (jmax (jmin (0, contentHolder.getWidth() - contentComp->getWidth()), jmin (0, -xPixelsOffset)),
  51284. jmax (jmin (0, contentHolder.getHeight() - contentComp->getHeight()), jmin (0, -yPixelsOffset)));
  51285. }
  51286. void Viewport::setViewPosition (const Point<int>& newPosition)
  51287. {
  51288. setViewPosition (newPosition.getX(), newPosition.getY());
  51289. }
  51290. void Viewport::setViewPositionProportionately (const double x, const double y)
  51291. {
  51292. if (contentComp != 0)
  51293. setViewPosition (jmax (0, roundToInt (x * (contentComp->getWidth() - getWidth()))),
  51294. jmax (0, roundToInt (y * (contentComp->getHeight() - getHeight()))));
  51295. }
  51296. bool Viewport::autoScroll (const int mouseX, const int mouseY, const int activeBorderThickness, const int maximumSpeed)
  51297. {
  51298. if (contentComp != 0)
  51299. {
  51300. int dx = 0, dy = 0;
  51301. if (horizontalScrollBar.isVisible() || contentComp->getX() < 0 || contentComp->getRight() > getWidth())
  51302. {
  51303. if (mouseX < activeBorderThickness)
  51304. dx = activeBorderThickness - mouseX;
  51305. else if (mouseX >= contentHolder.getWidth() - activeBorderThickness)
  51306. dx = (contentHolder.getWidth() - activeBorderThickness) - mouseX;
  51307. if (dx < 0)
  51308. dx = jmax (dx, -maximumSpeed, contentHolder.getWidth() - contentComp->getRight());
  51309. else
  51310. dx = jmin (dx, maximumSpeed, -contentComp->getX());
  51311. }
  51312. if (verticalScrollBar.isVisible() || contentComp->getY() < 0 || contentComp->getBottom() > getHeight())
  51313. {
  51314. if (mouseY < activeBorderThickness)
  51315. dy = activeBorderThickness - mouseY;
  51316. else if (mouseY >= contentHolder.getHeight() - activeBorderThickness)
  51317. dy = (contentHolder.getHeight() - activeBorderThickness) - mouseY;
  51318. if (dy < 0)
  51319. dy = jmax (dy, -maximumSpeed, contentHolder.getHeight() - contentComp->getBottom());
  51320. else
  51321. dy = jmin (dy, maximumSpeed, -contentComp->getY());
  51322. }
  51323. if (dx != 0 || dy != 0)
  51324. {
  51325. contentComp->setTopLeftPosition (contentComp->getX() + dx,
  51326. contentComp->getY() + dy);
  51327. return true;
  51328. }
  51329. }
  51330. return false;
  51331. }
  51332. void Viewport::componentMovedOrResized (Component&, bool, bool)
  51333. {
  51334. updateVisibleArea();
  51335. }
  51336. void Viewport::resized()
  51337. {
  51338. updateVisibleArea();
  51339. }
  51340. void Viewport::updateVisibleArea()
  51341. {
  51342. const int scrollbarWidth = getScrollBarThickness();
  51343. const bool canShowAnyBars = getWidth() > scrollbarWidth && getHeight() > scrollbarWidth;
  51344. const bool canShowHBar = showHScrollbar && canShowAnyBars;
  51345. const bool canShowVBar = showVScrollbar && canShowAnyBars;
  51346. bool hBarVisible = canShowHBar && ! horizontalScrollBar.autoHides();
  51347. bool vBarVisible = canShowVBar && ! verticalScrollBar.autoHides();
  51348. Rectangle<int> contentArea (getLocalBounds());
  51349. if (contentComp != 0 && ! contentArea.contains (contentComp->getBounds()))
  51350. {
  51351. hBarVisible = canShowHBar && (hBarVisible || contentComp->getX() < 0 || contentComp->getRight() > contentArea.getWidth());
  51352. vBarVisible = canShowVBar && (vBarVisible || contentComp->getY() < 0 || contentComp->getBottom() > contentArea.getHeight());
  51353. if (vBarVisible)
  51354. contentArea.setWidth (getWidth() - scrollbarWidth);
  51355. if (hBarVisible)
  51356. contentArea.setHeight (getHeight() - scrollbarWidth);
  51357. if (! contentArea.contains (contentComp->getBounds()))
  51358. {
  51359. hBarVisible = canShowHBar && (hBarVisible || contentComp->getRight() > contentArea.getWidth());
  51360. vBarVisible = canShowVBar && (vBarVisible || contentComp->getBottom() > contentArea.getHeight());
  51361. }
  51362. }
  51363. if (vBarVisible)
  51364. contentArea.setWidth (getWidth() - scrollbarWidth);
  51365. if (hBarVisible)
  51366. contentArea.setHeight (getHeight() - scrollbarWidth);
  51367. contentHolder.setBounds (contentArea);
  51368. Rectangle<int> contentBounds;
  51369. if (contentComp != 0)
  51370. contentBounds = contentComp->getBounds();
  51371. const Point<int> visibleOrigin (-contentBounds.getPosition());
  51372. if (hBarVisible)
  51373. {
  51374. horizontalScrollBar.setBounds (0, contentArea.getHeight(), contentArea.getWidth(), scrollbarWidth);
  51375. horizontalScrollBar.setRangeLimits (0.0, contentBounds.getWidth());
  51376. horizontalScrollBar.setCurrentRange (visibleOrigin.getX(), contentArea.getWidth());
  51377. horizontalScrollBar.setSingleStepSize (singleStepX);
  51378. horizontalScrollBar.cancelPendingUpdate();
  51379. }
  51380. if (vBarVisible)
  51381. {
  51382. verticalScrollBar.setBounds (contentArea.getWidth(), 0, scrollbarWidth, contentArea.getHeight());
  51383. verticalScrollBar.setRangeLimits (0.0, contentBounds.getHeight());
  51384. verticalScrollBar.setCurrentRange (visibleOrigin.getY(), contentArea.getHeight());
  51385. verticalScrollBar.setSingleStepSize (singleStepY);
  51386. verticalScrollBar.cancelPendingUpdate();
  51387. }
  51388. // Force the visibility *after* setting the ranges to avoid flicker caused by edge conditions in the numbers.
  51389. horizontalScrollBar.setVisible (hBarVisible);
  51390. verticalScrollBar.setVisible (vBarVisible);
  51391. const Rectangle<int> visibleArea (visibleOrigin.getX(), visibleOrigin.getY(),
  51392. jmin (contentBounds.getWidth() - visibleOrigin.getX(), contentArea.getWidth()),
  51393. jmin (contentBounds.getHeight() - visibleOrigin.getY(), contentArea.getHeight()));
  51394. if (lastVisibleArea != visibleArea)
  51395. {
  51396. lastVisibleArea = visibleArea;
  51397. visibleAreaChanged (visibleArea.getX(), visibleArea.getY(), visibleArea.getWidth(), visibleArea.getHeight());
  51398. }
  51399. horizontalScrollBar.handleUpdateNowIfNeeded();
  51400. verticalScrollBar.handleUpdateNowIfNeeded();
  51401. }
  51402. void Viewport::setSingleStepSizes (const int stepX, const int stepY)
  51403. {
  51404. if (singleStepX != stepX || singleStepY != stepY)
  51405. {
  51406. singleStepX = stepX;
  51407. singleStepY = stepY;
  51408. updateVisibleArea();
  51409. }
  51410. }
  51411. void Viewport::setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  51412. const bool showHorizontalScrollbarIfNeeded)
  51413. {
  51414. if (showVScrollbar != showVerticalScrollbarIfNeeded
  51415. || showHScrollbar != showHorizontalScrollbarIfNeeded)
  51416. {
  51417. showVScrollbar = showVerticalScrollbarIfNeeded;
  51418. showHScrollbar = showHorizontalScrollbarIfNeeded;
  51419. updateVisibleArea();
  51420. }
  51421. }
  51422. void Viewport::setScrollBarThickness (const int thickness)
  51423. {
  51424. if (scrollBarThickness != thickness)
  51425. {
  51426. scrollBarThickness = thickness;
  51427. updateVisibleArea();
  51428. }
  51429. }
  51430. int Viewport::getScrollBarThickness() const
  51431. {
  51432. return scrollBarThickness > 0 ? scrollBarThickness
  51433. : getLookAndFeel().getDefaultScrollbarWidth();
  51434. }
  51435. void Viewport::setScrollBarButtonVisibility (const bool buttonsVisible)
  51436. {
  51437. verticalScrollBar.setButtonVisibility (buttonsVisible);
  51438. horizontalScrollBar.setButtonVisibility (buttonsVisible);
  51439. }
  51440. void Viewport::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  51441. {
  51442. const int newRangeStartInt = roundToInt (newRangeStart);
  51443. if (scrollBarThatHasMoved == &horizontalScrollBar)
  51444. {
  51445. setViewPosition (newRangeStartInt, getViewPositionY());
  51446. }
  51447. else if (scrollBarThatHasMoved == &verticalScrollBar)
  51448. {
  51449. setViewPosition (getViewPositionX(), newRangeStartInt);
  51450. }
  51451. }
  51452. void Viewport::mouseWheelMove (const MouseEvent& e, const float wheelIncrementX, const float wheelIncrementY)
  51453. {
  51454. if (! useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  51455. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  51456. }
  51457. bool Viewport::useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  51458. {
  51459. if (! (e.mods.isAltDown() || e.mods.isCtrlDown()))
  51460. {
  51461. const bool hasVertBar = verticalScrollBar.isVisible();
  51462. const bool hasHorzBar = horizontalScrollBar.isVisible();
  51463. if (hasHorzBar || hasVertBar)
  51464. {
  51465. if (wheelIncrementX != 0)
  51466. {
  51467. wheelIncrementX *= 14.0f * singleStepX;
  51468. wheelIncrementX = (wheelIncrementX < 0) ? jmin (wheelIncrementX, -1.0f)
  51469. : jmax (wheelIncrementX, 1.0f);
  51470. }
  51471. if (wheelIncrementY != 0)
  51472. {
  51473. wheelIncrementY *= 14.0f * singleStepY;
  51474. wheelIncrementY = (wheelIncrementY < 0) ? jmin (wheelIncrementY, -1.0f)
  51475. : jmax (wheelIncrementY, 1.0f);
  51476. }
  51477. Point<int> pos (getViewPosition());
  51478. if (wheelIncrementX != 0 && wheelIncrementY != 0 && hasHorzBar && hasVertBar)
  51479. {
  51480. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  51481. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  51482. }
  51483. else if (hasHorzBar && (wheelIncrementX != 0 || e.mods.isShiftDown() || ! hasVertBar))
  51484. {
  51485. if (wheelIncrementX == 0 && ! hasVertBar)
  51486. wheelIncrementX = wheelIncrementY;
  51487. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  51488. }
  51489. else if (hasVertBar && wheelIncrementY != 0)
  51490. {
  51491. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  51492. }
  51493. if (pos != getViewPosition())
  51494. {
  51495. setViewPosition (pos);
  51496. return true;
  51497. }
  51498. }
  51499. }
  51500. return false;
  51501. }
  51502. bool Viewport::keyPressed (const KeyPress& key)
  51503. {
  51504. const bool isUpDownKey = key.isKeyCode (KeyPress::upKey)
  51505. || key.isKeyCode (KeyPress::downKey)
  51506. || key.isKeyCode (KeyPress::pageUpKey)
  51507. || key.isKeyCode (KeyPress::pageDownKey)
  51508. || key.isKeyCode (KeyPress::homeKey)
  51509. || key.isKeyCode (KeyPress::endKey);
  51510. if (verticalScrollBar.isVisible() && isUpDownKey)
  51511. return verticalScrollBar.keyPressed (key);
  51512. const bool isLeftRightKey = key.isKeyCode (KeyPress::leftKey)
  51513. || key.isKeyCode (KeyPress::rightKey);
  51514. if (horizontalScrollBar.isVisible() && (isUpDownKey || isLeftRightKey))
  51515. return horizontalScrollBar.keyPressed (key);
  51516. return false;
  51517. }
  51518. END_JUCE_NAMESPACE
  51519. /*** End of inlined file: juce_Viewport.cpp ***/
  51520. /*** Start of inlined file: juce_LookAndFeel.cpp ***/
  51521. BEGIN_JUCE_NAMESPACE
  51522. static const Colour createBaseColour (const Colour& buttonColour,
  51523. const bool hasKeyboardFocus,
  51524. const bool isMouseOverButton,
  51525. const bool isButtonDown) throw()
  51526. {
  51527. const float sat = hasKeyboardFocus ? 1.3f : 0.9f;
  51528. const Colour baseColour (buttonColour.withMultipliedSaturation (sat));
  51529. if (isButtonDown)
  51530. return baseColour.contrasting (0.2f);
  51531. else if (isMouseOverButton)
  51532. return baseColour.contrasting (0.1f);
  51533. return baseColour;
  51534. }
  51535. LookAndFeel::LookAndFeel()
  51536. {
  51537. /* if this fails it means you're trying to create a LookAndFeel object before
  51538. the static Colours have been initialised. That ain't gonna work. It probably
  51539. means that you're using a static LookAndFeel object and that your compiler has
  51540. decided to intialise it before the Colours class.
  51541. */
  51542. jassert (Colours::white == Colour (0xffffffff));
  51543. // set up the standard set of colours..
  51544. const int textButtonColour = 0xffbbbbff;
  51545. const int textHighlightColour = 0x401111ee;
  51546. const int standardOutlineColour = 0xb2808080;
  51547. static const int standardColours[] =
  51548. {
  51549. TextButton::buttonColourId, textButtonColour,
  51550. TextButton::buttonOnColourId, 0xff4444ff,
  51551. TextButton::textColourOnId, 0xff000000,
  51552. TextButton::textColourOffId, 0xff000000,
  51553. ComboBox::buttonColourId, 0xffbbbbff,
  51554. ComboBox::outlineColourId, standardOutlineColour,
  51555. ToggleButton::textColourId, 0xff000000,
  51556. TextEditor::backgroundColourId, 0xffffffff,
  51557. TextEditor::textColourId, 0xff000000,
  51558. TextEditor::highlightColourId, textHighlightColour,
  51559. TextEditor::highlightedTextColourId, 0xff000000,
  51560. TextEditor::caretColourId, 0xff000000,
  51561. TextEditor::outlineColourId, 0x00000000,
  51562. TextEditor::focusedOutlineColourId, textButtonColour,
  51563. TextEditor::shadowColourId, 0x38000000,
  51564. Label::backgroundColourId, 0x00000000,
  51565. Label::textColourId, 0xff000000,
  51566. Label::outlineColourId, 0x00000000,
  51567. ScrollBar::backgroundColourId, 0x00000000,
  51568. ScrollBar::thumbColourId, 0xffffffff,
  51569. ScrollBar::trackColourId, 0xffffffff,
  51570. TreeView::linesColourId, 0x4c000000,
  51571. TreeView::backgroundColourId, 0x00000000,
  51572. TreeView::dragAndDropIndicatorColourId, 0x80ff0000,
  51573. PopupMenu::backgroundColourId, 0xffffffff,
  51574. PopupMenu::textColourId, 0xff000000,
  51575. PopupMenu::headerTextColourId, 0xff000000,
  51576. PopupMenu::highlightedTextColourId, 0xffffffff,
  51577. PopupMenu::highlightedBackgroundColourId, 0x991111aa,
  51578. ComboBox::textColourId, 0xff000000,
  51579. ComboBox::backgroundColourId, 0xffffffff,
  51580. ComboBox::arrowColourId, 0x99000000,
  51581. ListBox::backgroundColourId, 0xffffffff,
  51582. ListBox::outlineColourId, standardOutlineColour,
  51583. ListBox::textColourId, 0xff000000,
  51584. Slider::backgroundColourId, 0x00000000,
  51585. Slider::thumbColourId, textButtonColour,
  51586. Slider::trackColourId, 0x7fffffff,
  51587. Slider::rotarySliderFillColourId, 0x7f0000ff,
  51588. Slider::rotarySliderOutlineColourId, 0x66000000,
  51589. Slider::textBoxTextColourId, 0xff000000,
  51590. Slider::textBoxBackgroundColourId, 0xffffffff,
  51591. Slider::textBoxHighlightColourId, textHighlightColour,
  51592. Slider::textBoxOutlineColourId, standardOutlineColour,
  51593. ResizableWindow::backgroundColourId, 0xff777777,
  51594. //DocumentWindow::textColourId, 0xff000000, // (this is deliberately not set)
  51595. AlertWindow::backgroundColourId, 0xffededed,
  51596. AlertWindow::textColourId, 0xff000000,
  51597. AlertWindow::outlineColourId, 0xff666666,
  51598. ProgressBar::backgroundColourId, 0xffeeeeee,
  51599. ProgressBar::foregroundColourId, 0xffaaaaee,
  51600. TooltipWindow::backgroundColourId, 0xffeeeebb,
  51601. TooltipWindow::textColourId, 0xff000000,
  51602. TooltipWindow::outlineColourId, 0x4c000000,
  51603. TabbedComponent::backgroundColourId, 0x00000000,
  51604. TabbedComponent::outlineColourId, 0xff777777,
  51605. TabbedButtonBar::tabOutlineColourId, 0x80000000,
  51606. TabbedButtonBar::frontOutlineColourId, 0x90000000,
  51607. Toolbar::backgroundColourId, 0xfff6f8f9,
  51608. Toolbar::separatorColourId, 0x4c000000,
  51609. Toolbar::buttonMouseOverBackgroundColourId, 0x4c0000ff,
  51610. Toolbar::buttonMouseDownBackgroundColourId, 0x800000ff,
  51611. Toolbar::labelTextColourId, 0xff000000,
  51612. Toolbar::editingModeOutlineColourId, 0xffff0000,
  51613. HyperlinkButton::textColourId, 0xcc1111ee,
  51614. GroupComponent::outlineColourId, 0x66000000,
  51615. GroupComponent::textColourId, 0xff000000,
  51616. DirectoryContentsDisplayComponent::highlightColourId, textHighlightColour,
  51617. DirectoryContentsDisplayComponent::textColourId, 0xff000000,
  51618. 0x1000440, /*LassoComponent::lassoFillColourId*/ 0x66dddddd,
  51619. 0x1000441, /*LassoComponent::lassoOutlineColourId*/ 0x99111111,
  51620. MidiKeyboardComponent::whiteNoteColourId, 0xffffffff,
  51621. MidiKeyboardComponent::blackNoteColourId, 0xff000000,
  51622. MidiKeyboardComponent::keySeparatorLineColourId, 0x66000000,
  51623. MidiKeyboardComponent::mouseOverKeyOverlayColourId, 0x80ffff00,
  51624. MidiKeyboardComponent::keyDownOverlayColourId, 0xffb6b600,
  51625. MidiKeyboardComponent::textLabelColourId, 0xff000000,
  51626. MidiKeyboardComponent::upDownButtonBackgroundColourId, 0xffd3d3d3,
  51627. MidiKeyboardComponent::upDownButtonArrowColourId, 0xff000000,
  51628. CodeEditorComponent::backgroundColourId, 0xffffffff,
  51629. CodeEditorComponent::caretColourId, 0xff000000,
  51630. CodeEditorComponent::highlightColourId, textHighlightColour,
  51631. CodeEditorComponent::defaultTextColourId, 0xff000000,
  51632. ColourSelector::backgroundColourId, 0xffe5e5e5,
  51633. ColourSelector::labelTextColourId, 0xff000000,
  51634. KeyMappingEditorComponent::backgroundColourId, 0x00000000,
  51635. KeyMappingEditorComponent::textColourId, 0xff000000,
  51636. FileSearchPathListComponent::backgroundColourId, 0xffffffff,
  51637. FileChooserDialogBox::titleTextColourId, 0xff000000,
  51638. };
  51639. for (int i = 0; i < numElementsInArray (standardColours); i += 2)
  51640. setColour (standardColours [i], Colour (standardColours [i + 1]));
  51641. static String defaultSansName, defaultSerifName, defaultFixedName;
  51642. if (defaultSansName.isEmpty())
  51643. Font::getPlatformDefaultFontNames (defaultSansName, defaultSerifName, defaultFixedName);
  51644. defaultSans = defaultSansName;
  51645. defaultSerif = defaultSerifName;
  51646. defaultFixed = defaultFixedName;
  51647. }
  51648. LookAndFeel::~LookAndFeel()
  51649. {
  51650. }
  51651. const Colour LookAndFeel::findColour (const int colourId) const throw()
  51652. {
  51653. const int index = colourIds.indexOf (colourId);
  51654. if (index >= 0)
  51655. return colours [index];
  51656. jassertfalse;
  51657. return Colours::black;
  51658. }
  51659. void LookAndFeel::setColour (const int colourId, const Colour& colour) throw()
  51660. {
  51661. const int index = colourIds.indexOf (colourId);
  51662. if (index >= 0)
  51663. {
  51664. colours.set (index, colour);
  51665. }
  51666. else
  51667. {
  51668. colourIds.add (colourId);
  51669. colours.add (colour);
  51670. }
  51671. }
  51672. bool LookAndFeel::isColourSpecified (const int colourId) const throw()
  51673. {
  51674. return colourIds.contains (colourId);
  51675. }
  51676. static LookAndFeel* defaultLF = 0;
  51677. static LookAndFeel* currentDefaultLF = 0;
  51678. LookAndFeel& LookAndFeel::getDefaultLookAndFeel() throw()
  51679. {
  51680. // if this happens, your app hasn't initialised itself properly.. if you're
  51681. // trying to hack your own main() function, have a look at
  51682. // JUCEApplication::initialiseForGUI()
  51683. jassert (currentDefaultLF != 0);
  51684. return *currentDefaultLF;
  51685. }
  51686. void LookAndFeel::setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw()
  51687. {
  51688. if (newDefaultLookAndFeel == 0)
  51689. {
  51690. if (defaultLF == 0)
  51691. defaultLF = new LookAndFeel();
  51692. newDefaultLookAndFeel = defaultLF;
  51693. }
  51694. currentDefaultLF = newDefaultLookAndFeel;
  51695. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  51696. {
  51697. Component* const c = Desktop::getInstance().getComponent (i);
  51698. if (c != 0)
  51699. c->sendLookAndFeelChange();
  51700. }
  51701. }
  51702. void LookAndFeel::clearDefaultLookAndFeel() throw()
  51703. {
  51704. if (currentDefaultLF == defaultLF)
  51705. currentDefaultLF = 0;
  51706. deleteAndZero (defaultLF);
  51707. }
  51708. const Typeface::Ptr LookAndFeel::getTypefaceForFont (const Font& font)
  51709. {
  51710. String faceName (font.getTypefaceName());
  51711. if (faceName == Font::getDefaultSansSerifFontName())
  51712. faceName = defaultSans;
  51713. else if (faceName == Font::getDefaultSerifFontName())
  51714. faceName = defaultSerif;
  51715. else if (faceName == Font::getDefaultMonospacedFontName())
  51716. faceName = defaultFixed;
  51717. Font f (font);
  51718. f.setTypefaceName (faceName);
  51719. return Typeface::createSystemTypefaceFor (f);
  51720. }
  51721. void LookAndFeel::setDefaultSansSerifTypefaceName (const String& newName)
  51722. {
  51723. defaultSans = newName;
  51724. }
  51725. const MouseCursor LookAndFeel::getMouseCursorFor (Component& component)
  51726. {
  51727. return component.getMouseCursor();
  51728. }
  51729. void LookAndFeel::drawButtonBackground (Graphics& g,
  51730. Button& button,
  51731. const Colour& backgroundColour,
  51732. bool isMouseOverButton,
  51733. bool isButtonDown)
  51734. {
  51735. const int width = button.getWidth();
  51736. const int height = button.getHeight();
  51737. const float outlineThickness = button.isEnabled() ? ((isButtonDown || isMouseOverButton) ? 1.2f : 0.7f) : 0.4f;
  51738. const float halfThickness = outlineThickness * 0.5f;
  51739. const float indentL = button.isConnectedOnLeft() ? 0.1f : halfThickness;
  51740. const float indentR = button.isConnectedOnRight() ? 0.1f : halfThickness;
  51741. const float indentT = button.isConnectedOnTop() ? 0.1f : halfThickness;
  51742. const float indentB = button.isConnectedOnBottom() ? 0.1f : halfThickness;
  51743. const Colour baseColour (createBaseColour (backgroundColour,
  51744. button.hasKeyboardFocus (true),
  51745. isMouseOverButton, isButtonDown)
  51746. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  51747. drawGlassLozenge (g,
  51748. indentL,
  51749. indentT,
  51750. width - indentL - indentR,
  51751. height - indentT - indentB,
  51752. baseColour, outlineThickness, -1.0f,
  51753. button.isConnectedOnLeft(),
  51754. button.isConnectedOnRight(),
  51755. button.isConnectedOnTop(),
  51756. button.isConnectedOnBottom());
  51757. }
  51758. const Font LookAndFeel::getFontForTextButton (TextButton& button)
  51759. {
  51760. return button.getFont();
  51761. }
  51762. void LookAndFeel::drawButtonText (Graphics& g, TextButton& button,
  51763. bool /*isMouseOverButton*/, bool /*isButtonDown*/)
  51764. {
  51765. Font font (getFontForTextButton (button));
  51766. g.setFont (font);
  51767. g.setColour (button.findColour (button.getToggleState() ? TextButton::textColourOnId
  51768. : TextButton::textColourOffId)
  51769. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  51770. const int yIndent = jmin (4, button.proportionOfHeight (0.3f));
  51771. const int cornerSize = jmin (button.getHeight(), button.getWidth()) / 2;
  51772. const int fontHeight = roundToInt (font.getHeight() * 0.6f);
  51773. const int leftIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnLeft() ? 4 : 2));
  51774. const int rightIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnRight() ? 4 : 2));
  51775. g.drawFittedText (button.getButtonText(),
  51776. leftIndent,
  51777. yIndent,
  51778. button.getWidth() - leftIndent - rightIndent,
  51779. button.getHeight() - yIndent * 2,
  51780. Justification::centred, 2);
  51781. }
  51782. void LookAndFeel::drawTickBox (Graphics& g,
  51783. Component& component,
  51784. float x, float y, float w, float h,
  51785. const bool ticked,
  51786. const bool isEnabled,
  51787. const bool isMouseOverButton,
  51788. const bool isButtonDown)
  51789. {
  51790. const float boxSize = w * 0.7f;
  51791. drawGlassSphere (g, x, y + (h - boxSize) * 0.5f, boxSize,
  51792. createBaseColour (component.findColour (TextButton::buttonColourId)
  51793. .withMultipliedAlpha (isEnabled ? 1.0f : 0.5f),
  51794. true,
  51795. isMouseOverButton,
  51796. isButtonDown),
  51797. isEnabled ? ((isButtonDown || isMouseOverButton) ? 1.1f : 0.5f) : 0.3f);
  51798. if (ticked)
  51799. {
  51800. Path tick;
  51801. tick.startNewSubPath (1.5f, 3.0f);
  51802. tick.lineTo (3.0f, 6.0f);
  51803. tick.lineTo (6.0f, 0.0f);
  51804. g.setColour (isEnabled ? Colours::black : Colours::grey);
  51805. const AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  51806. .translated (x, y));
  51807. g.strokePath (tick, PathStrokeType (2.5f), trans);
  51808. }
  51809. }
  51810. void LookAndFeel::drawToggleButton (Graphics& g,
  51811. ToggleButton& button,
  51812. bool isMouseOverButton,
  51813. bool isButtonDown)
  51814. {
  51815. if (button.hasKeyboardFocus (true))
  51816. {
  51817. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  51818. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  51819. }
  51820. float fontSize = jmin (15.0f, button.getHeight() * 0.75f);
  51821. const float tickWidth = fontSize * 1.1f;
  51822. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  51823. tickWidth, tickWidth,
  51824. button.getToggleState(),
  51825. button.isEnabled(),
  51826. isMouseOverButton,
  51827. isButtonDown);
  51828. g.setColour (button.findColour (ToggleButton::textColourId));
  51829. g.setFont (fontSize);
  51830. if (! button.isEnabled())
  51831. g.setOpacity (0.5f);
  51832. const int textX = (int) tickWidth + 5;
  51833. g.drawFittedText (button.getButtonText(),
  51834. textX, 0,
  51835. button.getWidth() - textX - 2, button.getHeight(),
  51836. Justification::centredLeft, 10);
  51837. }
  51838. void LookAndFeel::changeToggleButtonWidthToFitText (ToggleButton& button)
  51839. {
  51840. Font font (jmin (15.0f, button.getHeight() * 0.6f));
  51841. const int tickWidth = jmin (24, button.getHeight());
  51842. button.setSize (font.getStringWidth (button.getButtonText()) + tickWidth + 8,
  51843. button.getHeight());
  51844. }
  51845. AlertWindow* LookAndFeel::createAlertWindow (const String& title,
  51846. const String& message,
  51847. const String& button1,
  51848. const String& button2,
  51849. const String& button3,
  51850. AlertWindow::AlertIconType iconType,
  51851. int numButtons,
  51852. Component* associatedComponent)
  51853. {
  51854. AlertWindow* aw = new AlertWindow (title, message, iconType, associatedComponent);
  51855. if (numButtons == 1)
  51856. {
  51857. aw->addButton (button1, 0,
  51858. KeyPress (KeyPress::escapeKey, 0, 0),
  51859. KeyPress (KeyPress::returnKey, 0, 0));
  51860. }
  51861. else
  51862. {
  51863. const KeyPress button1ShortCut (CharacterFunctions::toLowerCase (button1[0]), 0, 0);
  51864. KeyPress button2ShortCut (CharacterFunctions::toLowerCase (button2[0]), 0, 0);
  51865. if (button1ShortCut == button2ShortCut)
  51866. button2ShortCut = KeyPress();
  51867. if (numButtons == 2)
  51868. {
  51869. aw->addButton (button1, 1, KeyPress (KeyPress::returnKey, 0, 0), button1ShortCut);
  51870. aw->addButton (button2, 0, KeyPress (KeyPress::escapeKey, 0, 0), button2ShortCut);
  51871. }
  51872. else if (numButtons == 3)
  51873. {
  51874. aw->addButton (button1, 1, button1ShortCut);
  51875. aw->addButton (button2, 2, button2ShortCut);
  51876. aw->addButton (button3, 0, KeyPress (KeyPress::escapeKey, 0, 0));
  51877. }
  51878. }
  51879. return aw;
  51880. }
  51881. void LookAndFeel::drawAlertBox (Graphics& g,
  51882. AlertWindow& alert,
  51883. const Rectangle<int>& textArea,
  51884. TextLayout& textLayout)
  51885. {
  51886. g.fillAll (alert.findColour (AlertWindow::backgroundColourId));
  51887. int iconSpaceUsed = 0;
  51888. Justification alignment (Justification::horizontallyCentred);
  51889. const int iconWidth = 80;
  51890. int iconSize = jmin (iconWidth + 50, alert.getHeight() + 20);
  51891. if (alert.containsAnyExtraComponents() || alert.getNumButtons() > 2)
  51892. iconSize = jmin (iconSize, textArea.getHeight() + 50);
  51893. const Rectangle<int> iconRect (iconSize / -10, iconSize / -10,
  51894. iconSize, iconSize);
  51895. if (alert.getAlertType() != AlertWindow::NoIcon)
  51896. {
  51897. Path icon;
  51898. uint32 colour;
  51899. char character;
  51900. if (alert.getAlertType() == AlertWindow::WarningIcon)
  51901. {
  51902. colour = 0x55ff5555;
  51903. character = '!';
  51904. icon.addTriangle (iconRect.getX() + iconRect.getWidth() * 0.5f, (float) iconRect.getY(),
  51905. (float) iconRect.getRight(), (float) iconRect.getBottom(),
  51906. (float) iconRect.getX(), (float) iconRect.getBottom());
  51907. icon = icon.createPathWithRoundedCorners (5.0f);
  51908. }
  51909. else
  51910. {
  51911. colour = alert.getAlertType() == AlertWindow::InfoIcon ? 0x605555ff : 0x40b69900;
  51912. character = alert.getAlertType() == AlertWindow::InfoIcon ? 'i' : '?';
  51913. icon.addEllipse ((float) iconRect.getX(), (float) iconRect.getY(),
  51914. (float) iconRect.getWidth(), (float) iconRect.getHeight());
  51915. }
  51916. GlyphArrangement ga;
  51917. ga.addFittedText (Font (iconRect.getHeight() * 0.9f, Font::bold),
  51918. String::charToString (character),
  51919. (float) iconRect.getX(), (float) iconRect.getY(),
  51920. (float) iconRect.getWidth(), (float) iconRect.getHeight(),
  51921. Justification::centred, false);
  51922. ga.createPath (icon);
  51923. icon.setUsingNonZeroWinding (false);
  51924. g.setColour (Colour (colour));
  51925. g.fillPath (icon);
  51926. iconSpaceUsed = iconWidth;
  51927. alignment = Justification::left;
  51928. }
  51929. g.setColour (alert.findColour (AlertWindow::textColourId));
  51930. textLayout.drawWithin (g,
  51931. textArea.getX() + iconSpaceUsed, textArea.getY(),
  51932. textArea.getWidth() - iconSpaceUsed, textArea.getHeight(),
  51933. alignment.getFlags() | Justification::top);
  51934. g.setColour (alert.findColour (AlertWindow::outlineColourId));
  51935. g.drawRect (0, 0, alert.getWidth(), alert.getHeight());
  51936. }
  51937. int LookAndFeel::getAlertBoxWindowFlags()
  51938. {
  51939. return ComponentPeer::windowAppearsOnTaskbar
  51940. | ComponentPeer::windowHasDropShadow;
  51941. }
  51942. int LookAndFeel::getAlertWindowButtonHeight()
  51943. {
  51944. return 28;
  51945. }
  51946. const Font LookAndFeel::getAlertWindowFont()
  51947. {
  51948. return Font (12.0f);
  51949. }
  51950. void LookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  51951. int width, int height,
  51952. double progress, const String& textToShow)
  51953. {
  51954. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  51955. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  51956. g.fillAll (background);
  51957. if (progress >= 0.0f && progress < 1.0f)
  51958. {
  51959. drawGlassLozenge (g, 1.0f, 1.0f,
  51960. (float) jlimit (0.0, width - 2.0, progress * (width - 2.0)),
  51961. (float) (height - 2),
  51962. foreground,
  51963. 0.5f, 0.0f,
  51964. true, true, true, true);
  51965. }
  51966. else
  51967. {
  51968. // spinning bar..
  51969. g.setColour (foreground);
  51970. const int stripeWidth = height * 2;
  51971. const int position = (Time::getMillisecondCounter() / 15) % stripeWidth;
  51972. Path p;
  51973. for (float x = (float) (- position); x < width + stripeWidth; x += stripeWidth)
  51974. p.addQuadrilateral (x, 0.0f,
  51975. x + stripeWidth * 0.5f, 0.0f,
  51976. x, (float) height,
  51977. x - stripeWidth * 0.5f, (float) height);
  51978. Image im (Image::ARGB, width, height, true);
  51979. {
  51980. Graphics g2 (im);
  51981. drawGlassLozenge (g2, 1.0f, 1.0f,
  51982. (float) (width - 2),
  51983. (float) (height - 2),
  51984. foreground,
  51985. 0.5f, 0.0f,
  51986. true, true, true, true);
  51987. }
  51988. g.setTiledImageFill (im, 0, 0, 0.85f);
  51989. g.fillPath (p);
  51990. }
  51991. if (textToShow.isNotEmpty())
  51992. {
  51993. g.setColour (Colour::contrasting (background, foreground));
  51994. g.setFont (height * 0.6f);
  51995. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  51996. }
  51997. }
  51998. void LookAndFeel::drawSpinningWaitAnimation (Graphics& g, const Colour& colour, int x, int y, int w, int h)
  51999. {
  52000. const float radius = jmin (w, h) * 0.4f;
  52001. const float thickness = radius * 0.15f;
  52002. Path p;
  52003. p.addRoundedRectangle (radius * 0.4f, thickness * -0.5f,
  52004. radius * 0.6f, thickness,
  52005. thickness * 0.5f);
  52006. const float cx = x + w * 0.5f;
  52007. const float cy = y + h * 0.5f;
  52008. const uint32 animationIndex = (Time::getMillisecondCounter() / (1000 / 10)) % 12;
  52009. for (int i = 0; i < 12; ++i)
  52010. {
  52011. const int n = (i + 12 - animationIndex) % 12;
  52012. g.setColour (colour.withMultipliedAlpha ((n + 1) / 12.0f));
  52013. g.fillPath (p, AffineTransform::rotation (i * (float_Pi / 6.0f))
  52014. .translated (cx, cy));
  52015. }
  52016. }
  52017. void LookAndFeel::drawScrollbarButton (Graphics& g,
  52018. ScrollBar& scrollbar,
  52019. int width, int height,
  52020. int buttonDirection,
  52021. bool /*isScrollbarVertical*/,
  52022. bool /*isMouseOverButton*/,
  52023. bool isButtonDown)
  52024. {
  52025. Path p;
  52026. if (buttonDirection == 0)
  52027. p.addTriangle (width * 0.5f, height * 0.2f,
  52028. width * 0.1f, height * 0.7f,
  52029. width * 0.9f, height * 0.7f);
  52030. else if (buttonDirection == 1)
  52031. p.addTriangle (width * 0.8f, height * 0.5f,
  52032. width * 0.3f, height * 0.1f,
  52033. width * 0.3f, height * 0.9f);
  52034. else if (buttonDirection == 2)
  52035. p.addTriangle (width * 0.5f, height * 0.8f,
  52036. width * 0.1f, height * 0.3f,
  52037. width * 0.9f, height * 0.3f);
  52038. else if (buttonDirection == 3)
  52039. p.addTriangle (width * 0.2f, height * 0.5f,
  52040. width * 0.7f, height * 0.1f,
  52041. width * 0.7f, height * 0.9f);
  52042. if (isButtonDown)
  52043. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId).contrasting (0.2f));
  52044. else
  52045. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId));
  52046. g.fillPath (p);
  52047. g.setColour (Colour (0x80000000));
  52048. g.strokePath (p, PathStrokeType (0.5f));
  52049. }
  52050. void LookAndFeel::drawScrollbar (Graphics& g,
  52051. ScrollBar& scrollbar,
  52052. int x, int y,
  52053. int width, int height,
  52054. bool isScrollbarVertical,
  52055. int thumbStartPosition,
  52056. int thumbSize,
  52057. bool /*isMouseOver*/,
  52058. bool /*isMouseDown*/)
  52059. {
  52060. g.fillAll (scrollbar.findColour (ScrollBar::backgroundColourId));
  52061. Path slotPath, thumbPath;
  52062. const float slotIndent = jmin (width, height) > 15 ? 1.0f : 0.0f;
  52063. const float slotIndentx2 = slotIndent * 2.0f;
  52064. const float thumbIndent = slotIndent + 1.0f;
  52065. const float thumbIndentx2 = thumbIndent * 2.0f;
  52066. float gx1 = 0.0f, gy1 = 0.0f, gx2 = 0.0f, gy2 = 0.0f;
  52067. if (isScrollbarVertical)
  52068. {
  52069. slotPath.addRoundedRectangle (x + slotIndent,
  52070. y + slotIndent,
  52071. width - slotIndentx2,
  52072. height - slotIndentx2,
  52073. (width - slotIndentx2) * 0.5f);
  52074. if (thumbSize > 0)
  52075. thumbPath.addRoundedRectangle (x + thumbIndent,
  52076. thumbStartPosition + thumbIndent,
  52077. width - thumbIndentx2,
  52078. thumbSize - thumbIndentx2,
  52079. (width - thumbIndentx2) * 0.5f);
  52080. gx1 = (float) x;
  52081. gx2 = x + width * 0.7f;
  52082. }
  52083. else
  52084. {
  52085. slotPath.addRoundedRectangle (x + slotIndent,
  52086. y + slotIndent,
  52087. width - slotIndentx2,
  52088. height - slotIndentx2,
  52089. (height - slotIndentx2) * 0.5f);
  52090. if (thumbSize > 0)
  52091. thumbPath.addRoundedRectangle (thumbStartPosition + thumbIndent,
  52092. y + thumbIndent,
  52093. thumbSize - thumbIndentx2,
  52094. height - thumbIndentx2,
  52095. (height - thumbIndentx2) * 0.5f);
  52096. gy1 = (float) y;
  52097. gy2 = y + height * 0.7f;
  52098. }
  52099. const Colour thumbColour (scrollbar.findColour (ScrollBar::thumbColourId));
  52100. g.setGradientFill (ColourGradient (thumbColour.overlaidWith (Colour (0x44000000)), gx1, gy1,
  52101. thumbColour.overlaidWith (Colour (0x19000000)), gx2, gy2, false));
  52102. g.fillPath (slotPath);
  52103. if (isScrollbarVertical)
  52104. {
  52105. gx1 = x + width * 0.6f;
  52106. gx2 = (float) x + width;
  52107. }
  52108. else
  52109. {
  52110. gy1 = y + height * 0.6f;
  52111. gy2 = (float) y + height;
  52112. }
  52113. g.setGradientFill (ColourGradient (Colours::transparentBlack,gx1, gy1,
  52114. Colour (0x19000000), gx2, gy2, false));
  52115. g.fillPath (slotPath);
  52116. g.setColour (thumbColour);
  52117. g.fillPath (thumbPath);
  52118. g.setGradientFill (ColourGradient (Colour (0x10000000), gx1, gy1,
  52119. Colours::transparentBlack, gx2, gy2, false));
  52120. g.saveState();
  52121. if (isScrollbarVertical)
  52122. g.reduceClipRegion (x + width / 2, y, width, height);
  52123. else
  52124. g.reduceClipRegion (x, y + height / 2, width, height);
  52125. g.fillPath (thumbPath);
  52126. g.restoreState();
  52127. g.setColour (Colour (0x4c000000));
  52128. g.strokePath (thumbPath, PathStrokeType (0.4f));
  52129. }
  52130. ImageEffectFilter* LookAndFeel::getScrollbarEffect()
  52131. {
  52132. return 0;
  52133. }
  52134. int LookAndFeel::getMinimumScrollbarThumbSize (ScrollBar& scrollbar)
  52135. {
  52136. return jmin (scrollbar.getWidth(), scrollbar.getHeight()) * 2;
  52137. }
  52138. int LookAndFeel::getDefaultScrollbarWidth()
  52139. {
  52140. return 18;
  52141. }
  52142. int LookAndFeel::getScrollbarButtonSize (ScrollBar& scrollbar)
  52143. {
  52144. return 2 + (scrollbar.isVertical() ? scrollbar.getWidth()
  52145. : scrollbar.getHeight());
  52146. }
  52147. const Path LookAndFeel::getTickShape (const float height)
  52148. {
  52149. static const unsigned char tickShapeData[] =
  52150. {
  52151. 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,
  52152. 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,
  52153. 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,
  52154. 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,
  52155. 96,140,68,0,128,188,67,0,224,168,68,0,0,119,67,99,101
  52156. };
  52157. Path p;
  52158. p.loadPathFromData (tickShapeData, sizeof (tickShapeData));
  52159. p.scaleToFit (0, 0, height * 2.0f, height, true);
  52160. return p;
  52161. }
  52162. const Path LookAndFeel::getCrossShape (const float height)
  52163. {
  52164. static const unsigned char crossShapeData[] =
  52165. {
  52166. 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,
  52167. 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,
  52168. 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,
  52169. 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,
  52170. 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,
  52171. 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,
  52172. 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
  52173. };
  52174. Path p;
  52175. p.loadPathFromData (crossShapeData, sizeof (crossShapeData));
  52176. p.scaleToFit (0, 0, height * 2.0f, height, true);
  52177. return p;
  52178. }
  52179. void LookAndFeel::drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool /*isMouseOver*/)
  52180. {
  52181. const int boxSize = ((jmin (16, w, h) << 1) / 3) | 1;
  52182. x += (w - boxSize) >> 1;
  52183. y += (h - boxSize) >> 1;
  52184. w = boxSize;
  52185. h = boxSize;
  52186. g.setColour (Colour (0xe5ffffff));
  52187. g.fillRect (x, y, w, h);
  52188. g.setColour (Colour (0x80000000));
  52189. g.drawRect (x, y, w, h);
  52190. const float size = boxSize / 2 + 1.0f;
  52191. const float centre = (float) (boxSize / 2);
  52192. g.fillRect (x + (w - size) * 0.5f, y + centre, size, 1.0f);
  52193. if (isPlus)
  52194. g.fillRect (x + centre, y + (h - size) * 0.5f, 1.0f, size);
  52195. }
  52196. void LookAndFeel::drawBubble (Graphics& g,
  52197. float tipX, float tipY,
  52198. float boxX, float boxY,
  52199. float boxW, float boxH)
  52200. {
  52201. int side = 0;
  52202. if (tipX < boxX)
  52203. side = 1;
  52204. else if (tipX > boxX + boxW)
  52205. side = 3;
  52206. else if (tipY > boxY + boxH)
  52207. side = 2;
  52208. const float indent = 2.0f;
  52209. Path p;
  52210. p.addBubble (boxX + indent,
  52211. boxY + indent,
  52212. boxW - indent * 2.0f,
  52213. boxH - indent * 2.0f,
  52214. 5.0f,
  52215. tipX, tipY,
  52216. side,
  52217. 0.5f,
  52218. jmin (15.0f, boxW * 0.3f, boxH * 0.3f));
  52219. //xxx need to take comp as param for colour
  52220. g.setColour (findColour (TooltipWindow::backgroundColourId).withAlpha (0.9f));
  52221. g.fillPath (p);
  52222. //xxx as above
  52223. g.setColour (findColour (TooltipWindow::textColourId).withAlpha (0.4f));
  52224. g.strokePath (p, PathStrokeType (1.33f));
  52225. }
  52226. const Font LookAndFeel::getPopupMenuFont()
  52227. {
  52228. return Font (17.0f);
  52229. }
  52230. void LookAndFeel::getIdealPopupMenuItemSize (const String& text,
  52231. const bool isSeparator,
  52232. int standardMenuItemHeight,
  52233. int& idealWidth,
  52234. int& idealHeight)
  52235. {
  52236. if (isSeparator)
  52237. {
  52238. idealWidth = 50;
  52239. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight / 2 : 10;
  52240. }
  52241. else
  52242. {
  52243. Font font (getPopupMenuFont());
  52244. if (standardMenuItemHeight > 0 && font.getHeight() > standardMenuItemHeight / 1.3f)
  52245. font.setHeight (standardMenuItemHeight / 1.3f);
  52246. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight : roundToInt (font.getHeight() * 1.3f);
  52247. idealWidth = font.getStringWidth (text) + idealHeight * 2;
  52248. }
  52249. }
  52250. void LookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  52251. {
  52252. const Colour background (findColour (PopupMenu::backgroundColourId));
  52253. g.fillAll (background);
  52254. g.setColour (background.overlaidWith (Colour (0x2badd8e6)));
  52255. for (int i = 0; i < height; i += 3)
  52256. g.fillRect (0, i, width, 1);
  52257. #if ! JUCE_MAC
  52258. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.6f));
  52259. g.drawRect (0, 0, width, height);
  52260. #endif
  52261. }
  52262. void LookAndFeel::drawPopupMenuUpDownArrow (Graphics& g,
  52263. int width, int height,
  52264. bool isScrollUpArrow)
  52265. {
  52266. const Colour background (findColour (PopupMenu::backgroundColourId));
  52267. g.setGradientFill (ColourGradient (background, 0.0f, height * 0.5f,
  52268. background.withAlpha (0.0f),
  52269. 0.0f, isScrollUpArrow ? ((float) height) : 0.0f,
  52270. false));
  52271. g.fillRect (1, 1, width - 2, height - 2);
  52272. const float hw = width * 0.5f;
  52273. const float arrowW = height * 0.3f;
  52274. const float y1 = height * (isScrollUpArrow ? 0.6f : 0.3f);
  52275. const float y2 = height * (isScrollUpArrow ? 0.3f : 0.6f);
  52276. Path p;
  52277. p.addTriangle (hw - arrowW, y1,
  52278. hw + arrowW, y1,
  52279. hw, y2);
  52280. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.5f));
  52281. g.fillPath (p);
  52282. }
  52283. void LookAndFeel::drawPopupMenuItem (Graphics& g,
  52284. int width, int height,
  52285. const bool isSeparator,
  52286. const bool isActive,
  52287. const bool isHighlighted,
  52288. const bool isTicked,
  52289. const bool hasSubMenu,
  52290. const String& text,
  52291. const String& shortcutKeyText,
  52292. Image* image,
  52293. const Colour* const textColourToUse)
  52294. {
  52295. const float halfH = height * 0.5f;
  52296. if (isSeparator)
  52297. {
  52298. const float separatorIndent = 5.5f;
  52299. g.setColour (Colour (0x33000000));
  52300. g.drawLine (separatorIndent, halfH, width - separatorIndent, halfH);
  52301. g.setColour (Colour (0x66ffffff));
  52302. g.drawLine (separatorIndent, halfH + 1.0f, width - separatorIndent, halfH + 1.0f);
  52303. }
  52304. else
  52305. {
  52306. Colour textColour (findColour (PopupMenu::textColourId));
  52307. if (textColourToUse != 0)
  52308. textColour = *textColourToUse;
  52309. if (isHighlighted)
  52310. {
  52311. g.setColour (findColour (PopupMenu::highlightedBackgroundColourId));
  52312. g.fillRect (1, 1, width - 2, height - 2);
  52313. g.setColour (findColour (PopupMenu::highlightedTextColourId));
  52314. }
  52315. else
  52316. {
  52317. g.setColour (textColour);
  52318. }
  52319. if (! isActive)
  52320. g.setOpacity (0.3f);
  52321. Font font (getPopupMenuFont());
  52322. if (font.getHeight() > height / 1.3f)
  52323. font.setHeight (height / 1.3f);
  52324. g.setFont (font);
  52325. const int leftBorder = (height * 5) / 4;
  52326. const int rightBorder = 4;
  52327. if (image != 0)
  52328. {
  52329. g.drawImageWithin (*image,
  52330. 2, 1, leftBorder - 4, height - 2,
  52331. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, false);
  52332. }
  52333. else if (isTicked)
  52334. {
  52335. const Path tick (getTickShape (1.0f));
  52336. const float th = font.getAscent();
  52337. const float ty = halfH - th * 0.5f;
  52338. g.fillPath (tick, tick.getTransformToScaleToFit (2.0f, ty, (float) (leftBorder - 4),
  52339. th, true));
  52340. }
  52341. g.drawFittedText (text,
  52342. leftBorder, 0,
  52343. width - (leftBorder + rightBorder), height,
  52344. Justification::centredLeft, 1);
  52345. if (shortcutKeyText.isNotEmpty())
  52346. {
  52347. Font f2 (font);
  52348. f2.setHeight (f2.getHeight() * 0.75f);
  52349. f2.setHorizontalScale (0.95f);
  52350. g.setFont (f2);
  52351. g.drawText (shortcutKeyText,
  52352. leftBorder,
  52353. 0,
  52354. width - (leftBorder + rightBorder + 4),
  52355. height,
  52356. Justification::centredRight,
  52357. true);
  52358. }
  52359. if (hasSubMenu)
  52360. {
  52361. const float arrowH = 0.6f * getPopupMenuFont().getAscent();
  52362. const float x = width - height * 0.6f;
  52363. Path p;
  52364. p.addTriangle (x, halfH - arrowH * 0.5f,
  52365. x, halfH + arrowH * 0.5f,
  52366. x + arrowH * 0.6f, halfH);
  52367. g.fillPath (p);
  52368. }
  52369. }
  52370. }
  52371. int LookAndFeel::getMenuWindowFlags()
  52372. {
  52373. return ComponentPeer::windowHasDropShadow;
  52374. }
  52375. void LookAndFeel::drawMenuBarBackground (Graphics& g, int width, int height,
  52376. bool, MenuBarComponent& menuBar)
  52377. {
  52378. const Colour baseColour (createBaseColour (menuBar.findColour (PopupMenu::backgroundColourId), false, false, false));
  52379. if (menuBar.isEnabled())
  52380. {
  52381. drawShinyButtonShape (g,
  52382. -4.0f, 0.0f,
  52383. width + 8.0f, (float) height,
  52384. 0.0f,
  52385. baseColour,
  52386. 0.4f,
  52387. true, true, true, true);
  52388. }
  52389. else
  52390. {
  52391. g.fillAll (baseColour);
  52392. }
  52393. }
  52394. const Font LookAndFeel::getMenuBarFont (MenuBarComponent& menuBar, int /*itemIndex*/, const String& /*itemText*/)
  52395. {
  52396. return Font (menuBar.getHeight() * 0.7f);
  52397. }
  52398. int LookAndFeel::getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText)
  52399. {
  52400. return getMenuBarFont (menuBar, itemIndex, itemText)
  52401. .getStringWidth (itemText) + menuBar.getHeight();
  52402. }
  52403. void LookAndFeel::drawMenuBarItem (Graphics& g,
  52404. int width, int height,
  52405. int itemIndex,
  52406. const String& itemText,
  52407. bool isMouseOverItem,
  52408. bool isMenuOpen,
  52409. bool /*isMouseOverBar*/,
  52410. MenuBarComponent& menuBar)
  52411. {
  52412. if (! menuBar.isEnabled())
  52413. {
  52414. g.setColour (menuBar.findColour (PopupMenu::textColourId)
  52415. .withMultipliedAlpha (0.5f));
  52416. }
  52417. else if (isMenuOpen || isMouseOverItem)
  52418. {
  52419. g.fillAll (menuBar.findColour (PopupMenu::highlightedBackgroundColourId));
  52420. g.setColour (menuBar.findColour (PopupMenu::highlightedTextColourId));
  52421. }
  52422. else
  52423. {
  52424. g.setColour (menuBar.findColour (PopupMenu::textColourId));
  52425. }
  52426. g.setFont (getMenuBarFont (menuBar, itemIndex, itemText));
  52427. g.drawFittedText (itemText, 0, 0, width, height, Justification::centred, 1);
  52428. }
  52429. void LookAndFeel::fillTextEditorBackground (Graphics& g, int /*width*/, int /*height*/,
  52430. TextEditor& textEditor)
  52431. {
  52432. g.fillAll (textEditor.findColour (TextEditor::backgroundColourId));
  52433. }
  52434. void LookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  52435. {
  52436. if (textEditor.isEnabled())
  52437. {
  52438. if (textEditor.hasKeyboardFocus (true) && ! textEditor.isReadOnly())
  52439. {
  52440. const int border = 2;
  52441. g.setColour (textEditor.findColour (TextEditor::focusedOutlineColourId));
  52442. g.drawRect (0, 0, width, height, border);
  52443. g.setOpacity (1.0f);
  52444. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId).withMultipliedAlpha (0.75f));
  52445. g.drawBevel (0, 0, width, height + 2, border + 2, shadowColour, shadowColour);
  52446. }
  52447. else
  52448. {
  52449. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  52450. g.drawRect (0, 0, width, height);
  52451. g.setOpacity (1.0f);
  52452. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId));
  52453. g.drawBevel (0, 0, width, height + 2, 3, shadowColour, shadowColour);
  52454. }
  52455. }
  52456. }
  52457. void LookAndFeel::drawComboBox (Graphics& g, int width, int height,
  52458. const bool isButtonDown,
  52459. int buttonX, int buttonY,
  52460. int buttonW, int buttonH,
  52461. ComboBox& box)
  52462. {
  52463. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  52464. if (box.isEnabled() && box.hasKeyboardFocus (false))
  52465. {
  52466. g.setColour (box.findColour (TextButton::buttonColourId));
  52467. g.drawRect (0, 0, width, height, 2);
  52468. }
  52469. else
  52470. {
  52471. g.setColour (box.findColour (ComboBox::outlineColourId));
  52472. g.drawRect (0, 0, width, height);
  52473. }
  52474. const float outlineThickness = box.isEnabled() ? (isButtonDown ? 1.2f : 0.5f) : 0.3f;
  52475. const Colour baseColour (createBaseColour (box.findColour (ComboBox::buttonColourId),
  52476. box.hasKeyboardFocus (true),
  52477. false, isButtonDown)
  52478. .withMultipliedAlpha (box.isEnabled() ? 1.0f : 0.5f));
  52479. drawGlassLozenge (g,
  52480. buttonX + outlineThickness, buttonY + outlineThickness,
  52481. buttonW - outlineThickness * 2.0f, buttonH - outlineThickness * 2.0f,
  52482. baseColour, outlineThickness, -1.0f,
  52483. true, true, true, true);
  52484. if (box.isEnabled())
  52485. {
  52486. const float arrowX = 0.3f;
  52487. const float arrowH = 0.2f;
  52488. Path p;
  52489. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  52490. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  52491. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  52492. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  52493. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  52494. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  52495. g.setColour (box.findColour (ComboBox::arrowColourId));
  52496. g.fillPath (p);
  52497. }
  52498. }
  52499. const Font LookAndFeel::getComboBoxFont (ComboBox& box)
  52500. {
  52501. return Font (jmin (15.0f, box.getHeight() * 0.85f));
  52502. }
  52503. Label* LookAndFeel::createComboBoxTextBox (ComboBox&)
  52504. {
  52505. return new Label (String::empty, String::empty);
  52506. }
  52507. void LookAndFeel::positionComboBoxText (ComboBox& box, Label& label)
  52508. {
  52509. label.setBounds (1, 1,
  52510. box.getWidth() + 3 - box.getHeight(),
  52511. box.getHeight() - 2);
  52512. label.setFont (getComboBoxFont (box));
  52513. }
  52514. void LookAndFeel::drawLabel (Graphics& g, Label& label)
  52515. {
  52516. g.fillAll (label.findColour (Label::backgroundColourId));
  52517. if (! label.isBeingEdited())
  52518. {
  52519. const float alpha = label.isEnabled() ? 1.0f : 0.5f;
  52520. g.setColour (label.findColour (Label::textColourId).withMultipliedAlpha (alpha));
  52521. g.setFont (label.getFont());
  52522. g.drawFittedText (label.getText(),
  52523. label.getHorizontalBorderSize(),
  52524. label.getVerticalBorderSize(),
  52525. label.getWidth() - 2 * label.getHorizontalBorderSize(),
  52526. label.getHeight() - 2 * label.getVerticalBorderSize(),
  52527. label.getJustificationType(),
  52528. jmax (1, (int) (label.getHeight() / label.getFont().getHeight())),
  52529. label.getMinimumHorizontalScale());
  52530. g.setColour (label.findColour (Label::outlineColourId).withMultipliedAlpha (alpha));
  52531. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  52532. }
  52533. else if (label.isEnabled())
  52534. {
  52535. g.setColour (label.findColour (Label::outlineColourId));
  52536. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  52537. }
  52538. }
  52539. void LookAndFeel::drawLinearSliderBackground (Graphics& g,
  52540. int x, int y,
  52541. int width, int height,
  52542. float /*sliderPos*/,
  52543. float /*minSliderPos*/,
  52544. float /*maxSliderPos*/,
  52545. const Slider::SliderStyle /*style*/,
  52546. Slider& slider)
  52547. {
  52548. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  52549. const Colour trackColour (slider.findColour (Slider::trackColourId));
  52550. const Colour gradCol1 (trackColour.overlaidWith (Colours::black.withAlpha (slider.isEnabled() ? 0.25f : 0.13f)));
  52551. const Colour gradCol2 (trackColour.overlaidWith (Colour (0x14000000)));
  52552. Path indent;
  52553. if (slider.isHorizontal())
  52554. {
  52555. const float iy = y + height * 0.5f - sliderRadius * 0.5f;
  52556. const float ih = sliderRadius;
  52557. g.setGradientFill (ColourGradient (gradCol1, 0.0f, iy,
  52558. gradCol2, 0.0f, iy + ih, false));
  52559. indent.addRoundedRectangle (x - sliderRadius * 0.5f, iy,
  52560. width + sliderRadius, ih,
  52561. 5.0f);
  52562. g.fillPath (indent);
  52563. }
  52564. else
  52565. {
  52566. const float ix = x + width * 0.5f - sliderRadius * 0.5f;
  52567. const float iw = sliderRadius;
  52568. g.setGradientFill (ColourGradient (gradCol1, ix, 0.0f,
  52569. gradCol2, ix + iw, 0.0f, false));
  52570. indent.addRoundedRectangle (ix, y - sliderRadius * 0.5f,
  52571. iw, height + sliderRadius,
  52572. 5.0f);
  52573. g.fillPath (indent);
  52574. }
  52575. g.setColour (Colour (0x4c000000));
  52576. g.strokePath (indent, PathStrokeType (0.5f));
  52577. }
  52578. void LookAndFeel::drawLinearSliderThumb (Graphics& g,
  52579. int x, int y,
  52580. int width, int height,
  52581. float sliderPos,
  52582. float minSliderPos,
  52583. float maxSliderPos,
  52584. const Slider::SliderStyle style,
  52585. Slider& slider)
  52586. {
  52587. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  52588. Colour knobColour (createBaseColour (slider.findColour (Slider::thumbColourId),
  52589. slider.hasKeyboardFocus (false) && slider.isEnabled(),
  52590. slider.isMouseOverOrDragging() && slider.isEnabled(),
  52591. slider.isMouseButtonDown() && slider.isEnabled()));
  52592. const float outlineThickness = slider.isEnabled() ? 0.8f : 0.3f;
  52593. if (style == Slider::LinearHorizontal || style == Slider::LinearVertical)
  52594. {
  52595. float kx, ky;
  52596. if (style == Slider::LinearVertical)
  52597. {
  52598. kx = x + width * 0.5f;
  52599. ky = sliderPos;
  52600. }
  52601. else
  52602. {
  52603. kx = sliderPos;
  52604. ky = y + height * 0.5f;
  52605. }
  52606. drawGlassSphere (g,
  52607. kx - sliderRadius,
  52608. ky - sliderRadius,
  52609. sliderRadius * 2.0f,
  52610. knobColour, outlineThickness);
  52611. }
  52612. else
  52613. {
  52614. if (style == Slider::ThreeValueVertical)
  52615. {
  52616. drawGlassSphere (g, x + width * 0.5f - sliderRadius,
  52617. sliderPos - sliderRadius,
  52618. sliderRadius * 2.0f,
  52619. knobColour, outlineThickness);
  52620. }
  52621. else if (style == Slider::ThreeValueHorizontal)
  52622. {
  52623. drawGlassSphere (g,sliderPos - sliderRadius,
  52624. y + height * 0.5f - sliderRadius,
  52625. sliderRadius * 2.0f,
  52626. knobColour, outlineThickness);
  52627. }
  52628. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  52629. {
  52630. const float sr = jmin (sliderRadius, width * 0.4f);
  52631. drawGlassPointer (g, jmax (0.0f, x + width * 0.5f - sliderRadius * 2.0f),
  52632. minSliderPos - sliderRadius,
  52633. sliderRadius * 2.0f, knobColour, outlineThickness, 1);
  52634. drawGlassPointer (g, jmin (x + width - sliderRadius * 2.0f, x + width * 0.5f), maxSliderPos - sr,
  52635. sliderRadius * 2.0f, knobColour, outlineThickness, 3);
  52636. }
  52637. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  52638. {
  52639. const float sr = jmin (sliderRadius, height * 0.4f);
  52640. drawGlassPointer (g, minSliderPos - sr,
  52641. jmax (0.0f, y + height * 0.5f - sliderRadius * 2.0f),
  52642. sliderRadius * 2.0f, knobColour, outlineThickness, 2);
  52643. drawGlassPointer (g, maxSliderPos - sliderRadius,
  52644. jmin (y + height - sliderRadius * 2.0f, y + height * 0.5f),
  52645. sliderRadius * 2.0f, knobColour, outlineThickness, 4);
  52646. }
  52647. }
  52648. }
  52649. void LookAndFeel::drawLinearSlider (Graphics& g,
  52650. int x, int y,
  52651. int width, int height,
  52652. float sliderPos,
  52653. float minSliderPos,
  52654. float maxSliderPos,
  52655. const Slider::SliderStyle style,
  52656. Slider& slider)
  52657. {
  52658. g.fillAll (slider.findColour (Slider::backgroundColourId));
  52659. if (style == Slider::LinearBar)
  52660. {
  52661. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  52662. Colour baseColour (createBaseColour (slider.findColour (Slider::thumbColourId)
  52663. .withMultipliedSaturation (slider.isEnabled() ? 1.0f : 0.5f),
  52664. false,
  52665. isMouseOver,
  52666. isMouseOver || slider.isMouseButtonDown()));
  52667. drawShinyButtonShape (g,
  52668. (float) x, (float) y, sliderPos - (float) x, (float) height, 0.0f,
  52669. baseColour,
  52670. slider.isEnabled() ? 0.9f : 0.3f,
  52671. true, true, true, true);
  52672. }
  52673. else
  52674. {
  52675. drawLinearSliderBackground (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  52676. drawLinearSliderThumb (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  52677. }
  52678. }
  52679. int LookAndFeel::getSliderThumbRadius (Slider& slider)
  52680. {
  52681. return jmin (7,
  52682. slider.getHeight() / 2,
  52683. slider.getWidth() / 2) + 2;
  52684. }
  52685. void LookAndFeel::drawRotarySlider (Graphics& g,
  52686. int x, int y,
  52687. int width, int height,
  52688. float sliderPos,
  52689. const float rotaryStartAngle,
  52690. const float rotaryEndAngle,
  52691. Slider& slider)
  52692. {
  52693. const float radius = jmin (width / 2, height / 2) - 2.0f;
  52694. const float centreX = x + width * 0.5f;
  52695. const float centreY = y + height * 0.5f;
  52696. const float rx = centreX - radius;
  52697. const float ry = centreY - radius;
  52698. const float rw = radius * 2.0f;
  52699. const float angle = rotaryStartAngle + sliderPos * (rotaryEndAngle - rotaryStartAngle);
  52700. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  52701. if (radius > 12.0f)
  52702. {
  52703. if (slider.isEnabled())
  52704. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  52705. else
  52706. g.setColour (Colour (0x80808080));
  52707. const float thickness = 0.7f;
  52708. {
  52709. Path filledArc;
  52710. filledArc.addPieSegment (rx, ry, rw, rw,
  52711. rotaryStartAngle,
  52712. angle,
  52713. thickness);
  52714. g.fillPath (filledArc);
  52715. }
  52716. if (thickness > 0)
  52717. {
  52718. const float innerRadius = radius * 0.2f;
  52719. Path p;
  52720. p.addTriangle (-innerRadius, 0.0f,
  52721. 0.0f, -radius * thickness * 1.1f,
  52722. innerRadius, 0.0f);
  52723. p.addEllipse (-innerRadius, -innerRadius, innerRadius * 2.0f, innerRadius * 2.0f);
  52724. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  52725. }
  52726. if (slider.isEnabled())
  52727. g.setColour (slider.findColour (Slider::rotarySliderOutlineColourId));
  52728. else
  52729. g.setColour (Colour (0x80808080));
  52730. Path outlineArc;
  52731. outlineArc.addPieSegment (rx, ry, rw, rw, rotaryStartAngle, rotaryEndAngle, thickness);
  52732. outlineArc.closeSubPath();
  52733. g.strokePath (outlineArc, PathStrokeType (slider.isEnabled() ? (isMouseOver ? 2.0f : 1.2f) : 0.3f));
  52734. }
  52735. else
  52736. {
  52737. if (slider.isEnabled())
  52738. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  52739. else
  52740. g.setColour (Colour (0x80808080));
  52741. Path p;
  52742. p.addEllipse (-0.4f * rw, -0.4f * rw, rw * 0.8f, rw * 0.8f);
  52743. PathStrokeType (rw * 0.1f).createStrokedPath (p, p);
  52744. p.addLineSegment (Line<float> (0.0f, 0.0f, 0.0f, -radius), rw * 0.2f);
  52745. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  52746. }
  52747. }
  52748. Button* LookAndFeel::createSliderButton (const bool isIncrement)
  52749. {
  52750. return new TextButton (isIncrement ? "+" : "-", String::empty);
  52751. }
  52752. class SliderLabelComp : public Label
  52753. {
  52754. public:
  52755. SliderLabelComp() : Label (String::empty, String::empty) {}
  52756. ~SliderLabelComp() {}
  52757. void mouseWheelMove (const MouseEvent&, float, float) {}
  52758. };
  52759. Label* LookAndFeel::createSliderTextBox (Slider& slider)
  52760. {
  52761. Label* const l = new SliderLabelComp();
  52762. l->setJustificationType (Justification::centred);
  52763. l->setColour (Label::textColourId, slider.findColour (Slider::textBoxTextColourId));
  52764. l->setColour (Label::backgroundColourId,
  52765. (slider.getSliderStyle() == Slider::LinearBar) ? Colours::transparentBlack
  52766. : slider.findColour (Slider::textBoxBackgroundColourId));
  52767. l->setColour (Label::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  52768. l->setColour (TextEditor::textColourId, slider.findColour (Slider::textBoxTextColourId));
  52769. l->setColour (TextEditor::backgroundColourId,
  52770. slider.findColour (Slider::textBoxBackgroundColourId)
  52771. .withAlpha (slider.getSliderStyle() == Slider::LinearBar ? 0.7f : 1.0f));
  52772. l->setColour (TextEditor::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  52773. return l;
  52774. }
  52775. ImageEffectFilter* LookAndFeel::getSliderEffect()
  52776. {
  52777. return 0;
  52778. }
  52779. static const TextLayout layoutTooltipText (const String& text) throw()
  52780. {
  52781. const float tooltipFontSize = 12.0f;
  52782. const int maxToolTipWidth = 400;
  52783. const Font f (tooltipFontSize, Font::bold);
  52784. TextLayout tl (text, f);
  52785. tl.layout (maxToolTipWidth, Justification::left, true);
  52786. return tl;
  52787. }
  52788. void LookAndFeel::getTooltipSize (const String& tipText, int& width, int& height)
  52789. {
  52790. const TextLayout tl (layoutTooltipText (tipText));
  52791. width = tl.getWidth() + 14;
  52792. height = tl.getHeight() + 6;
  52793. }
  52794. void LookAndFeel::drawTooltip (Graphics& g, const String& text, int width, int height)
  52795. {
  52796. g.fillAll (findColour (TooltipWindow::backgroundColourId));
  52797. const Colour textCol (findColour (TooltipWindow::textColourId));
  52798. #if ! JUCE_MAC // The mac windows already have a non-optional 1 pix outline, so don't double it here..
  52799. g.setColour (findColour (TooltipWindow::outlineColourId));
  52800. g.drawRect (0, 0, width, height, 1);
  52801. #endif
  52802. const TextLayout tl (layoutTooltipText (text));
  52803. g.setColour (findColour (TooltipWindow::textColourId));
  52804. tl.drawWithin (g, 0, 0, width, height, Justification::centred);
  52805. }
  52806. Button* LookAndFeel::createFilenameComponentBrowseButton (const String& text)
  52807. {
  52808. return new TextButton (text, TRANS("click to browse for a different file"));
  52809. }
  52810. void LookAndFeel::layoutFilenameComponent (FilenameComponent& filenameComp,
  52811. ComboBox* filenameBox,
  52812. Button* browseButton)
  52813. {
  52814. browseButton->setSize (80, filenameComp.getHeight());
  52815. TextButton* const tb = dynamic_cast <TextButton*> (browseButton);
  52816. if (tb != 0)
  52817. tb->changeWidthToFitText();
  52818. browseButton->setTopRightPosition (filenameComp.getWidth(), 0);
  52819. filenameBox->setBounds (0, 0, browseButton->getX(), filenameComp.getHeight());
  52820. }
  52821. void LookAndFeel::drawImageButton (Graphics& g, Image* image,
  52822. int imageX, int imageY, int imageW, int imageH,
  52823. const Colour& overlayColour,
  52824. float imageOpacity,
  52825. ImageButton& button)
  52826. {
  52827. if (! button.isEnabled())
  52828. imageOpacity *= 0.3f;
  52829. if (! overlayColour.isOpaque())
  52830. {
  52831. g.setOpacity (imageOpacity);
  52832. g.drawImage (*image, imageX, imageY, imageW, imageH,
  52833. 0, 0, image->getWidth(), image->getHeight(), false);
  52834. }
  52835. if (! overlayColour.isTransparent())
  52836. {
  52837. g.setColour (overlayColour);
  52838. g.drawImage (*image, imageX, imageY, imageW, imageH,
  52839. 0, 0, image->getWidth(), image->getHeight(), true);
  52840. }
  52841. }
  52842. void LookAndFeel::drawCornerResizer (Graphics& g,
  52843. int w, int h,
  52844. bool /*isMouseOver*/,
  52845. bool /*isMouseDragging*/)
  52846. {
  52847. const float lineThickness = jmin (w, h) * 0.075f;
  52848. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  52849. {
  52850. g.setColour (Colours::lightgrey);
  52851. g.drawLine (w * i,
  52852. h + 1.0f,
  52853. w + 1.0f,
  52854. h * i,
  52855. lineThickness);
  52856. g.setColour (Colours::darkgrey);
  52857. g.drawLine (w * i + lineThickness,
  52858. h + 1.0f,
  52859. w + 1.0f,
  52860. h * i + lineThickness,
  52861. lineThickness);
  52862. }
  52863. }
  52864. void LookAndFeel::drawResizableFrame (Graphics&, int /*w*/, int /*h*/,
  52865. const BorderSize& /*borders*/)
  52866. {
  52867. }
  52868. void LookAndFeel::fillResizableWindowBackground (Graphics& g, int /*w*/, int /*h*/,
  52869. const BorderSize& /*border*/, ResizableWindow& window)
  52870. {
  52871. g.fillAll (window.getBackgroundColour());
  52872. }
  52873. void LookAndFeel::drawResizableWindowBorder (Graphics& g, int w, int h,
  52874. const BorderSize& border, ResizableWindow&)
  52875. {
  52876. g.setColour (Colour (0x80000000));
  52877. g.drawRect (0, 0, w, h);
  52878. g.setColour (Colour (0x19000000));
  52879. g.drawRect (border.getLeft() - 1,
  52880. border.getTop() - 1,
  52881. w + 2 - border.getLeftAndRight(),
  52882. h + 2 - border.getTopAndBottom());
  52883. }
  52884. void LookAndFeel::drawDocumentWindowTitleBar (DocumentWindow& window,
  52885. Graphics& g, int w, int h,
  52886. int titleSpaceX, int titleSpaceW,
  52887. const Image* icon,
  52888. bool drawTitleTextOnLeft)
  52889. {
  52890. const bool isActive = window.isActiveWindow();
  52891. g.setGradientFill (ColourGradient (window.getBackgroundColour(),
  52892. 0.0f, 0.0f,
  52893. window.getBackgroundColour().contrasting (isActive ? 0.15f : 0.05f),
  52894. 0.0f, (float) h, false));
  52895. g.fillAll();
  52896. Font font (h * 0.65f, Font::bold);
  52897. g.setFont (font);
  52898. int textW = font.getStringWidth (window.getName());
  52899. int iconW = 0;
  52900. int iconH = 0;
  52901. if (icon != 0)
  52902. {
  52903. iconH = (int) font.getHeight();
  52904. iconW = icon->getWidth() * iconH / icon->getHeight() + 4;
  52905. }
  52906. textW = jmin (titleSpaceW, textW + iconW);
  52907. int textX = drawTitleTextOnLeft ? titleSpaceX
  52908. : jmax (titleSpaceX, (w - textW) / 2);
  52909. if (textX + textW > titleSpaceX + titleSpaceW)
  52910. textX = titleSpaceX + titleSpaceW - textW;
  52911. if (icon != 0)
  52912. {
  52913. g.setOpacity (isActive ? 1.0f : 0.6f);
  52914. g.drawImageWithin (*icon, textX, (h - iconH) / 2, iconW, iconH,
  52915. RectanglePlacement::centred, false);
  52916. textX += iconW;
  52917. textW -= iconW;
  52918. }
  52919. if (window.isColourSpecified (DocumentWindow::textColourId) || isColourSpecified (DocumentWindow::textColourId))
  52920. g.setColour (findColour (DocumentWindow::textColourId));
  52921. else
  52922. g.setColour (window.getBackgroundColour().contrasting (isActive ? 0.7f : 0.4f));
  52923. g.drawText (window.getName(), textX, 0, textW, h, Justification::centredLeft, true);
  52924. }
  52925. class GlassWindowButton : public Button
  52926. {
  52927. public:
  52928. GlassWindowButton (const String& name, const Colour& col,
  52929. const Path& normalShape_,
  52930. const Path& toggledShape_) throw()
  52931. : Button (name),
  52932. colour (col),
  52933. normalShape (normalShape_),
  52934. toggledShape (toggledShape_)
  52935. {
  52936. }
  52937. ~GlassWindowButton()
  52938. {
  52939. }
  52940. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  52941. {
  52942. float alpha = isMouseOverButton ? (isButtonDown ? 1.0f : 0.8f) : 0.55f;
  52943. if (! isEnabled())
  52944. alpha *= 0.5f;
  52945. float x = 0, y = 0, diam;
  52946. if (getWidth() < getHeight())
  52947. {
  52948. diam = (float) getWidth();
  52949. y = (getHeight() - getWidth()) * 0.5f;
  52950. }
  52951. else
  52952. {
  52953. diam = (float) getHeight();
  52954. y = (getWidth() - getHeight()) * 0.5f;
  52955. }
  52956. x += diam * 0.05f;
  52957. y += diam * 0.05f;
  52958. diam *= 0.9f;
  52959. g.setGradientFill (ColourGradient (Colour::greyLevel (0.9f).withAlpha (alpha), 0, y + diam,
  52960. Colour::greyLevel (0.6f).withAlpha (alpha), 0, y, false));
  52961. g.fillEllipse (x, y, diam, diam);
  52962. x += 2.0f;
  52963. y += 2.0f;
  52964. diam -= 4.0f;
  52965. LookAndFeel::drawGlassSphere (g, x, y, diam, colour.withAlpha (alpha), 1.0f);
  52966. Path& p = getToggleState() ? toggledShape : normalShape;
  52967. const AffineTransform t (p.getTransformToScaleToFit (x + diam * 0.3f, y + diam * 0.3f,
  52968. diam * 0.4f, diam * 0.4f, true));
  52969. g.setColour (Colours::black.withAlpha (alpha * 0.6f));
  52970. g.fillPath (p, t);
  52971. }
  52972. juce_UseDebuggingNewOperator
  52973. private:
  52974. Colour colour;
  52975. Path normalShape, toggledShape;
  52976. GlassWindowButton (const GlassWindowButton&);
  52977. GlassWindowButton& operator= (const GlassWindowButton&);
  52978. };
  52979. Button* LookAndFeel::createDocumentWindowButton (int buttonType)
  52980. {
  52981. Path shape;
  52982. const float crossThickness = 0.25f;
  52983. if (buttonType == DocumentWindow::closeButton)
  52984. {
  52985. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), crossThickness * 1.4f);
  52986. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), crossThickness * 1.4f);
  52987. return new GlassWindowButton ("close", Colour (0xffdd1100), shape, shape);
  52988. }
  52989. else if (buttonType == DocumentWindow::minimiseButton)
  52990. {
  52991. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  52992. return new GlassWindowButton ("minimise", Colour (0xffaa8811), shape, shape);
  52993. }
  52994. else if (buttonType == DocumentWindow::maximiseButton)
  52995. {
  52996. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), crossThickness);
  52997. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  52998. Path fullscreenShape;
  52999. fullscreenShape.startNewSubPath (45.0f, 100.0f);
  53000. fullscreenShape.lineTo (0.0f, 100.0f);
  53001. fullscreenShape.lineTo (0.0f, 0.0f);
  53002. fullscreenShape.lineTo (100.0f, 0.0f);
  53003. fullscreenShape.lineTo (100.0f, 45.0f);
  53004. fullscreenShape.addRectangle (45.0f, 45.0f, 100.0f, 100.0f);
  53005. PathStrokeType (30.0f).createStrokedPath (fullscreenShape, fullscreenShape);
  53006. return new GlassWindowButton ("maximise", Colour (0xff119911), shape, fullscreenShape);
  53007. }
  53008. jassertfalse;
  53009. return 0;
  53010. }
  53011. void LookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  53012. int titleBarX,
  53013. int titleBarY,
  53014. int titleBarW,
  53015. int titleBarH,
  53016. Button* minimiseButton,
  53017. Button* maximiseButton,
  53018. Button* closeButton,
  53019. bool positionTitleBarButtonsOnLeft)
  53020. {
  53021. const int buttonW = titleBarH - titleBarH / 8;
  53022. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  53023. : titleBarX + titleBarW - buttonW - buttonW / 4;
  53024. if (closeButton != 0)
  53025. {
  53026. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53027. x += positionTitleBarButtonsOnLeft ? buttonW : -(buttonW + buttonW / 4);
  53028. }
  53029. if (positionTitleBarButtonsOnLeft)
  53030. swapVariables (minimiseButton, maximiseButton);
  53031. if (maximiseButton != 0)
  53032. {
  53033. maximiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53034. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  53035. }
  53036. if (minimiseButton != 0)
  53037. minimiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53038. }
  53039. int LookAndFeel::getDefaultMenuBarHeight()
  53040. {
  53041. return 24;
  53042. }
  53043. DropShadower* LookAndFeel::createDropShadowerForComponent (Component*)
  53044. {
  53045. return new DropShadower (0.4f, 1, 5, 10);
  53046. }
  53047. void LookAndFeel::drawStretchableLayoutResizerBar (Graphics& g,
  53048. int w, int h,
  53049. bool /*isVerticalBar*/,
  53050. bool isMouseOver,
  53051. bool isMouseDragging)
  53052. {
  53053. float alpha = 0.5f;
  53054. if (isMouseOver || isMouseDragging)
  53055. {
  53056. g.fillAll (Colour (0x190000ff));
  53057. alpha = 1.0f;
  53058. }
  53059. const float cx = w * 0.5f;
  53060. const float cy = h * 0.5f;
  53061. const float cr = jmin (w, h) * 0.4f;
  53062. g.setGradientFill (ColourGradient (Colours::white.withAlpha (alpha), cx + cr * 0.1f, cy + cr,
  53063. Colours::black.withAlpha (alpha), cx, cy - cr * 4.0f,
  53064. true));
  53065. g.fillEllipse (cx - cr, cy - cr, cr * 2.0f, cr * 2.0f);
  53066. }
  53067. void LookAndFeel::drawGroupComponentOutline (Graphics& g, int width, int height,
  53068. const String& text,
  53069. const Justification& position,
  53070. GroupComponent& group)
  53071. {
  53072. const float textH = 15.0f;
  53073. const float indent = 3.0f;
  53074. const float textEdgeGap = 4.0f;
  53075. float cs = 5.0f;
  53076. Font f (textH);
  53077. Path p;
  53078. float x = indent;
  53079. float y = f.getAscent() - 3.0f;
  53080. float w = jmax (0.0f, width - x * 2.0f);
  53081. float h = jmax (0.0f, height - y - indent);
  53082. cs = jmin (cs, w * 0.5f, h * 0.5f);
  53083. const float cs2 = 2.0f * cs;
  53084. float textW = text.isEmpty() ? 0 : jlimit (0.0f, jmax (0.0f, w - cs2 - textEdgeGap * 2), f.getStringWidth (text) + textEdgeGap * 2.0f);
  53085. float textX = cs + textEdgeGap;
  53086. if (position.testFlags (Justification::horizontallyCentred))
  53087. textX = cs + (w - cs2 - textW) * 0.5f;
  53088. else if (position.testFlags (Justification::right))
  53089. textX = w - cs - textW - textEdgeGap;
  53090. p.startNewSubPath (x + textX + textW, y);
  53091. p.lineTo (x + w - cs, y);
  53092. p.addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  53093. p.lineTo (x + w, y + h - cs);
  53094. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  53095. p.lineTo (x + cs, y + h);
  53096. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  53097. p.lineTo (x, y + cs);
  53098. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  53099. p.lineTo (x + textX, y);
  53100. const float alpha = group.isEnabled() ? 1.0f : 0.5f;
  53101. g.setColour (group.findColour (GroupComponent::outlineColourId)
  53102. .withMultipliedAlpha (alpha));
  53103. g.strokePath (p, PathStrokeType (2.0f));
  53104. g.setColour (group.findColour (GroupComponent::textColourId)
  53105. .withMultipliedAlpha (alpha));
  53106. g.setFont (f);
  53107. g.drawText (text,
  53108. roundToInt (x + textX), 0,
  53109. roundToInt (textW),
  53110. roundToInt (textH),
  53111. Justification::centred, true);
  53112. }
  53113. int LookAndFeel::getTabButtonOverlap (int tabDepth)
  53114. {
  53115. return 1 + tabDepth / 3;
  53116. }
  53117. int LookAndFeel::getTabButtonSpaceAroundImage()
  53118. {
  53119. return 4;
  53120. }
  53121. void LookAndFeel::createTabButtonShape (Path& p,
  53122. int width, int height,
  53123. int /*tabIndex*/,
  53124. const String& /*text*/,
  53125. Button& /*button*/,
  53126. TabbedButtonBar::Orientation orientation,
  53127. const bool /*isMouseOver*/,
  53128. const bool /*isMouseDown*/,
  53129. const bool /*isFrontTab*/)
  53130. {
  53131. const float w = (float) width;
  53132. const float h = (float) height;
  53133. float length = w;
  53134. float depth = h;
  53135. if (orientation == TabbedButtonBar::TabsAtLeft
  53136. || orientation == TabbedButtonBar::TabsAtRight)
  53137. {
  53138. swapVariables (length, depth);
  53139. }
  53140. const float indent = (float) getTabButtonOverlap ((int) depth);
  53141. const float overhang = 4.0f;
  53142. if (orientation == TabbedButtonBar::TabsAtLeft)
  53143. {
  53144. p.startNewSubPath (w, 0.0f);
  53145. p.lineTo (0.0f, indent);
  53146. p.lineTo (0.0f, h - indent);
  53147. p.lineTo (w, h);
  53148. p.lineTo (w + overhang, h + overhang);
  53149. p.lineTo (w + overhang, -overhang);
  53150. }
  53151. else if (orientation == TabbedButtonBar::TabsAtRight)
  53152. {
  53153. p.startNewSubPath (0.0f, 0.0f);
  53154. p.lineTo (w, indent);
  53155. p.lineTo (w, h - indent);
  53156. p.lineTo (0.0f, h);
  53157. p.lineTo (-overhang, h + overhang);
  53158. p.lineTo (-overhang, -overhang);
  53159. }
  53160. else if (orientation == TabbedButtonBar::TabsAtBottom)
  53161. {
  53162. p.startNewSubPath (0.0f, 0.0f);
  53163. p.lineTo (indent, h);
  53164. p.lineTo (w - indent, h);
  53165. p.lineTo (w, 0.0f);
  53166. p.lineTo (w + overhang, -overhang);
  53167. p.lineTo (-overhang, -overhang);
  53168. }
  53169. else
  53170. {
  53171. p.startNewSubPath (0.0f, h);
  53172. p.lineTo (indent, 0.0f);
  53173. p.lineTo (w - indent, 0.0f);
  53174. p.lineTo (w, h);
  53175. p.lineTo (w + overhang, h + overhang);
  53176. p.lineTo (-overhang, h + overhang);
  53177. }
  53178. p.closeSubPath();
  53179. p = p.createPathWithRoundedCorners (3.0f);
  53180. }
  53181. void LookAndFeel::fillTabButtonShape (Graphics& g,
  53182. const Path& path,
  53183. const Colour& preferredColour,
  53184. int /*tabIndex*/,
  53185. const String& /*text*/,
  53186. Button& button,
  53187. TabbedButtonBar::Orientation /*orientation*/,
  53188. const bool /*isMouseOver*/,
  53189. const bool /*isMouseDown*/,
  53190. const bool isFrontTab)
  53191. {
  53192. g.setColour (isFrontTab ? preferredColour
  53193. : preferredColour.withMultipliedAlpha (0.9f));
  53194. g.fillPath (path);
  53195. g.setColour (button.findColour (isFrontTab ? TabbedButtonBar::frontOutlineColourId
  53196. : TabbedButtonBar::tabOutlineColourId, false)
  53197. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  53198. g.strokePath (path, PathStrokeType (isFrontTab ? 1.0f : 0.5f));
  53199. }
  53200. void LookAndFeel::drawTabButtonText (Graphics& g,
  53201. int x, int y, int w, int h,
  53202. const Colour& preferredBackgroundColour,
  53203. int /*tabIndex*/,
  53204. const String& text,
  53205. Button& button,
  53206. TabbedButtonBar::Orientation orientation,
  53207. const bool isMouseOver,
  53208. const bool isMouseDown,
  53209. const bool isFrontTab)
  53210. {
  53211. int length = w;
  53212. int depth = h;
  53213. if (orientation == TabbedButtonBar::TabsAtLeft
  53214. || orientation == TabbedButtonBar::TabsAtRight)
  53215. {
  53216. swapVariables (length, depth);
  53217. }
  53218. Font font (depth * 0.6f);
  53219. font.setUnderline (button.hasKeyboardFocus (false));
  53220. GlyphArrangement textLayout;
  53221. textLayout.addFittedText (font, text.trim(),
  53222. 0.0f, 0.0f, (float) length, (float) depth,
  53223. Justification::centred,
  53224. jmax (1, depth / 12));
  53225. AffineTransform transform;
  53226. if (orientation == TabbedButtonBar::TabsAtLeft)
  53227. {
  53228. transform = transform.rotated (float_Pi * -0.5f)
  53229. .translated ((float) x, (float) (y + h));
  53230. }
  53231. else if (orientation == TabbedButtonBar::TabsAtRight)
  53232. {
  53233. transform = transform.rotated (float_Pi * 0.5f)
  53234. .translated ((float) (x + w), (float) y);
  53235. }
  53236. else
  53237. {
  53238. transform = transform.translated ((float) x, (float) y);
  53239. }
  53240. if (isFrontTab && (button.isColourSpecified (TabbedButtonBar::frontTextColourId) || isColourSpecified (TabbedButtonBar::frontTextColourId)))
  53241. g.setColour (findColour (TabbedButtonBar::frontTextColourId));
  53242. else if (button.isColourSpecified (TabbedButtonBar::tabTextColourId) || isColourSpecified (TabbedButtonBar::tabTextColourId))
  53243. g.setColour (findColour (TabbedButtonBar::tabTextColourId));
  53244. else
  53245. g.setColour (preferredBackgroundColour.contrasting());
  53246. if (! (isMouseOver || isMouseDown))
  53247. g.setOpacity (0.8f);
  53248. if (! button.isEnabled())
  53249. g.setOpacity (0.3f);
  53250. textLayout.draw (g, transform);
  53251. }
  53252. int LookAndFeel::getTabButtonBestWidth (int /*tabIndex*/,
  53253. const String& text,
  53254. int tabDepth,
  53255. Button&)
  53256. {
  53257. Font f (tabDepth * 0.6f);
  53258. return f.getStringWidth (text.trim()) + getTabButtonOverlap (tabDepth) * 2;
  53259. }
  53260. void LookAndFeel::drawTabButton (Graphics& g,
  53261. int w, int h,
  53262. const Colour& preferredColour,
  53263. int tabIndex,
  53264. const String& text,
  53265. Button& button,
  53266. TabbedButtonBar::Orientation orientation,
  53267. const bool isMouseOver,
  53268. const bool isMouseDown,
  53269. const bool isFrontTab)
  53270. {
  53271. int length = w;
  53272. int depth = h;
  53273. if (orientation == TabbedButtonBar::TabsAtLeft
  53274. || orientation == TabbedButtonBar::TabsAtRight)
  53275. {
  53276. swapVariables (length, depth);
  53277. }
  53278. Path tabShape;
  53279. createTabButtonShape (tabShape, w, h,
  53280. tabIndex, text, button, orientation,
  53281. isMouseOver, isMouseDown, isFrontTab);
  53282. fillTabButtonShape (g, tabShape, preferredColour,
  53283. tabIndex, text, button, orientation,
  53284. isMouseOver, isMouseDown, isFrontTab);
  53285. const int indent = getTabButtonOverlap (depth);
  53286. int x = 0, y = 0;
  53287. if (orientation == TabbedButtonBar::TabsAtLeft
  53288. || orientation == TabbedButtonBar::TabsAtRight)
  53289. {
  53290. y += indent;
  53291. h -= indent * 2;
  53292. }
  53293. else
  53294. {
  53295. x += indent;
  53296. w -= indent * 2;
  53297. }
  53298. drawTabButtonText (g, x, y, w, h, preferredColour,
  53299. tabIndex, text, button, orientation,
  53300. isMouseOver, isMouseDown, isFrontTab);
  53301. }
  53302. void LookAndFeel::drawTabAreaBehindFrontButton (Graphics& g,
  53303. int w, int h,
  53304. TabbedButtonBar& tabBar,
  53305. TabbedButtonBar::Orientation orientation)
  53306. {
  53307. const float shadowSize = 0.2f;
  53308. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  53309. Rectangle<int> shadowRect;
  53310. if (orientation == TabbedButtonBar::TabsAtLeft)
  53311. {
  53312. x1 = (float) w;
  53313. x2 = w * (1.0f - shadowSize);
  53314. shadowRect.setBounds ((int) x2, 0, w - (int) x2, h);
  53315. }
  53316. else if (orientation == TabbedButtonBar::TabsAtRight)
  53317. {
  53318. x2 = w * shadowSize;
  53319. shadowRect.setBounds (0, 0, (int) x2, h);
  53320. }
  53321. else if (orientation == TabbedButtonBar::TabsAtBottom)
  53322. {
  53323. y2 = h * shadowSize;
  53324. shadowRect.setBounds (0, 0, w, (int) y2);
  53325. }
  53326. else
  53327. {
  53328. y1 = (float) h;
  53329. y2 = h * (1.0f - shadowSize);
  53330. shadowRect.setBounds (0, (int) y2, w, h - (int) y2);
  53331. }
  53332. g.setGradientFill (ColourGradient (Colours::black.withAlpha (tabBar.isEnabled() ? 0.3f : 0.15f), x1, y1,
  53333. Colours::transparentBlack, x2, y2, false));
  53334. shadowRect.expand (2, 2);
  53335. g.fillRect (shadowRect);
  53336. g.setColour (Colour (0x80000000));
  53337. if (orientation == TabbedButtonBar::TabsAtLeft)
  53338. {
  53339. g.fillRect (w - 1, 0, 1, h);
  53340. }
  53341. else if (orientation == TabbedButtonBar::TabsAtRight)
  53342. {
  53343. g.fillRect (0, 0, 1, h);
  53344. }
  53345. else if (orientation == TabbedButtonBar::TabsAtBottom)
  53346. {
  53347. g.fillRect (0, 0, w, 1);
  53348. }
  53349. else
  53350. {
  53351. g.fillRect (0, h - 1, w, 1);
  53352. }
  53353. }
  53354. Button* LookAndFeel::createTabBarExtrasButton()
  53355. {
  53356. const float thickness = 7.0f;
  53357. const float indent = 22.0f;
  53358. Path p;
  53359. p.addEllipse (-10.0f, -10.0f, 120.0f, 120.0f);
  53360. DrawablePath ellipse;
  53361. ellipse.setPath (p);
  53362. ellipse.setFill (Colour (0x99ffffff));
  53363. p.clear();
  53364. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  53365. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  53366. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  53367. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  53368. p.setUsingNonZeroWinding (false);
  53369. DrawablePath dp;
  53370. dp.setPath (p);
  53371. dp.setFill (Colour (0x59000000));
  53372. DrawableComposite normalImage;
  53373. normalImage.insertDrawable (ellipse);
  53374. normalImage.insertDrawable (dp);
  53375. dp.setFill (Colour (0xcc000000));
  53376. DrawableComposite overImage;
  53377. overImage.insertDrawable (ellipse);
  53378. overImage.insertDrawable (dp);
  53379. DrawableButton* db = new DrawableButton ("tabs", DrawableButton::ImageFitted);
  53380. db->setImages (&normalImage, &overImage, 0);
  53381. return db;
  53382. }
  53383. void LookAndFeel::drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header)
  53384. {
  53385. g.fillAll (Colours::white);
  53386. const int w = header.getWidth();
  53387. const int h = header.getHeight();
  53388. g.setGradientFill (ColourGradient (Colour (0xffe8ebf9), 0.0f, h * 0.5f,
  53389. Colour (0xfff6f8f9), 0.0f, h - 1.0f,
  53390. false));
  53391. g.fillRect (0, h / 2, w, h);
  53392. g.setColour (Colour (0x33000000));
  53393. g.fillRect (0, h - 1, w, 1);
  53394. for (int i = header.getNumColumns (true); --i >= 0;)
  53395. g.fillRect (header.getColumnPosition (i).getRight() - 1, 0, 1, h - 1);
  53396. }
  53397. void LookAndFeel::drawTableHeaderColumn (Graphics& g, const String& columnName, int /*columnId*/,
  53398. int width, int height,
  53399. bool isMouseOver, bool isMouseDown,
  53400. int columnFlags)
  53401. {
  53402. if (isMouseDown)
  53403. g.fillAll (Colour (0x8899aadd));
  53404. else if (isMouseOver)
  53405. g.fillAll (Colour (0x5599aadd));
  53406. int rightOfText = width - 4;
  53407. if ((columnFlags & (TableHeaderComponent::sortedForwards | TableHeaderComponent::sortedBackwards)) != 0)
  53408. {
  53409. const float top = height * ((columnFlags & TableHeaderComponent::sortedForwards) != 0 ? 0.35f : (1.0f - 0.35f));
  53410. const float bottom = height - top;
  53411. const float w = height * 0.5f;
  53412. const float x = rightOfText - (w * 1.25f);
  53413. rightOfText = (int) x;
  53414. Path sortArrow;
  53415. sortArrow.addTriangle (x, bottom, x + w * 0.5f, top, x + w, bottom);
  53416. g.setColour (Colour (0x99000000));
  53417. g.fillPath (sortArrow);
  53418. }
  53419. g.setColour (Colours::black);
  53420. g.setFont (height * 0.5f, Font::bold);
  53421. const int textX = 4;
  53422. g.drawFittedText (columnName, textX, 0, rightOfText - textX, height, Justification::centredLeft, 1);
  53423. }
  53424. void LookAndFeel::paintToolbarBackground (Graphics& g, int w, int h, Toolbar& toolbar)
  53425. {
  53426. const Colour background (toolbar.findColour (Toolbar::backgroundColourId));
  53427. g.setGradientFill (ColourGradient (background, 0.0f, 0.0f,
  53428. background.darker (0.1f),
  53429. toolbar.isVertical() ? w - 1.0f : 0.0f,
  53430. toolbar.isVertical() ? 0.0f : h - 1.0f,
  53431. false));
  53432. g.fillAll();
  53433. }
  53434. Button* LookAndFeel::createToolbarMissingItemsButton (Toolbar& /*toolbar*/)
  53435. {
  53436. return createTabBarExtrasButton();
  53437. }
  53438. void LookAndFeel::paintToolbarButtonBackground (Graphics& g, int /*width*/, int /*height*/,
  53439. bool isMouseOver, bool isMouseDown,
  53440. ToolbarItemComponent& component)
  53441. {
  53442. if (isMouseDown)
  53443. g.fillAll (component.findColour (Toolbar::buttonMouseDownBackgroundColourId, true));
  53444. else if (isMouseOver)
  53445. g.fillAll (component.findColour (Toolbar::buttonMouseOverBackgroundColourId, true));
  53446. }
  53447. void LookAndFeel::paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  53448. const String& text, ToolbarItemComponent& component)
  53449. {
  53450. g.setColour (component.findColour (Toolbar::labelTextColourId, true)
  53451. .withAlpha (component.isEnabled() ? 1.0f : 0.25f));
  53452. const float fontHeight = jmin (14.0f, height * 0.85f);
  53453. g.setFont (fontHeight);
  53454. g.drawFittedText (text,
  53455. x, y, width, height,
  53456. Justification::centred,
  53457. jmax (1, height / (int) fontHeight));
  53458. }
  53459. void LookAndFeel::drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  53460. bool isOpen, int width, int height)
  53461. {
  53462. const int buttonSize = (height * 3) / 4;
  53463. const int buttonIndent = (height - buttonSize) / 2;
  53464. drawTreeviewPlusMinusBox (g, buttonIndent, buttonIndent, buttonSize, buttonSize, ! isOpen, false);
  53465. const int textX = buttonIndent * 2 + buttonSize + 2;
  53466. g.setColour (Colours::black);
  53467. g.setFont (height * 0.7f, Font::bold);
  53468. g.drawText (name, textX, 0, width - textX - 4, height, Justification::centredLeft, true);
  53469. }
  53470. void LookAndFeel::drawPropertyComponentBackground (Graphics& g, int width, int height,
  53471. PropertyComponent&)
  53472. {
  53473. g.setColour (Colour (0x66ffffff));
  53474. g.fillRect (0, 0, width, height - 1);
  53475. }
  53476. void LookAndFeel::drawPropertyComponentLabel (Graphics& g, int, int height,
  53477. PropertyComponent& component)
  53478. {
  53479. g.setColour (Colours::black);
  53480. if (! component.isEnabled())
  53481. g.setOpacity (0.6f);
  53482. g.setFont (jmin (height, 24) * 0.65f);
  53483. const Rectangle<int> r (getPropertyComponentContentPosition (component));
  53484. g.drawFittedText (component.getName(),
  53485. 3, r.getY(), r.getX() - 5, r.getHeight(),
  53486. Justification::centredLeft, 2);
  53487. }
  53488. const Rectangle<int> LookAndFeel::getPropertyComponentContentPosition (PropertyComponent& component)
  53489. {
  53490. return Rectangle<int> (component.getWidth() / 3, 1,
  53491. component.getWidth() - component.getWidth() / 3 - 1, component.getHeight() - 3);
  53492. }
  53493. void LookAndFeel::drawCallOutBoxBackground (CallOutBox& box, Graphics& g, const Path& path)
  53494. {
  53495. Image content (Image::ARGB, box.getWidth(), box.getHeight(), true);
  53496. {
  53497. Graphics g2 (content);
  53498. g2.setColour (Colour::greyLevel (0.23f).withAlpha (0.9f));
  53499. g2.fillPath (path);
  53500. g2.setColour (Colours::white.withAlpha (0.8f));
  53501. g2.strokePath (path, PathStrokeType (2.0f));
  53502. }
  53503. DropShadowEffect shadow;
  53504. shadow.setShadowProperties (5.0f, 0.4f, 0, 2);
  53505. shadow.applyEffect (content, g);
  53506. }
  53507. void LookAndFeel::createFileChooserHeaderText (const String& title,
  53508. const String& instructions,
  53509. GlyphArrangement& text,
  53510. int width)
  53511. {
  53512. text.clear();
  53513. text.addJustifiedText (Font (17.0f, Font::bold), title,
  53514. 8.0f, 22.0f, width - 16.0f,
  53515. Justification::centred);
  53516. text.addJustifiedText (Font (14.0f), instructions,
  53517. 8.0f, 24.0f + 16.0f, width - 16.0f,
  53518. Justification::centred);
  53519. }
  53520. void LookAndFeel::drawFileBrowserRow (Graphics& g, int width, int height,
  53521. const String& filename, Image* icon,
  53522. const String& fileSizeDescription,
  53523. const String& fileTimeDescription,
  53524. const bool isDirectory,
  53525. const bool isItemSelected,
  53526. const int /*itemIndex*/)
  53527. {
  53528. if (isItemSelected)
  53529. g.fillAll (findColour (DirectoryContentsDisplayComponent::highlightColourId));
  53530. g.setColour (findColour (DirectoryContentsDisplayComponent::textColourId));
  53531. g.setFont (height * 0.7f);
  53532. Image im;
  53533. if (icon != 0)
  53534. im = *icon;
  53535. if (im.isNull())
  53536. im = isDirectory ? getDefaultFolderImage()
  53537. : getDefaultDocumentFileImage();
  53538. const int x = 32;
  53539. if (im.isValid())
  53540. {
  53541. g.drawImageWithin (im, 2, 2, x - 4, height - 4,
  53542. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  53543. false);
  53544. }
  53545. if (width > 450 && ! isDirectory)
  53546. {
  53547. const int sizeX = roundToInt (width * 0.7f);
  53548. const int dateX = roundToInt (width * 0.8f);
  53549. g.drawFittedText (filename,
  53550. x, 0, sizeX - x, height,
  53551. Justification::centredLeft, 1);
  53552. g.setFont (height * 0.5f);
  53553. g.setColour (Colours::darkgrey);
  53554. if (! isDirectory)
  53555. {
  53556. g.drawFittedText (fileSizeDescription,
  53557. sizeX, 0, dateX - sizeX - 8, height,
  53558. Justification::centredRight, 1);
  53559. g.drawFittedText (fileTimeDescription,
  53560. dateX, 0, width - 8 - dateX, height,
  53561. Justification::centredRight, 1);
  53562. }
  53563. }
  53564. else
  53565. {
  53566. g.drawFittedText (filename,
  53567. x, 0, width - x, height,
  53568. Justification::centredLeft, 1);
  53569. }
  53570. }
  53571. Button* LookAndFeel::createFileBrowserGoUpButton()
  53572. {
  53573. DrawableButton* goUpButton = new DrawableButton ("up", DrawableButton::ImageOnButtonBackground);
  53574. Path arrowPath;
  53575. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  53576. DrawablePath arrowImage;
  53577. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  53578. arrowImage.setPath (arrowPath);
  53579. goUpButton->setImages (&arrowImage);
  53580. return goUpButton;
  53581. }
  53582. void LookAndFeel::layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  53583. DirectoryContentsDisplayComponent* fileListComponent,
  53584. FilePreviewComponent* previewComp,
  53585. ComboBox* currentPathBox,
  53586. TextEditor* filenameBox,
  53587. Button* goUpButton)
  53588. {
  53589. const int x = 8;
  53590. int w = browserComp.getWidth() - x - x;
  53591. if (previewComp != 0)
  53592. {
  53593. const int previewWidth = w / 3;
  53594. previewComp->setBounds (x + w - previewWidth, 0, previewWidth, browserComp.getHeight());
  53595. w -= previewWidth + 4;
  53596. }
  53597. int y = 4;
  53598. const int controlsHeight = 22;
  53599. const int bottomSectionHeight = controlsHeight + 8;
  53600. const int upButtonWidth = 50;
  53601. currentPathBox->setBounds (x, y, w - upButtonWidth - 6, controlsHeight);
  53602. goUpButton->setBounds (x + w - upButtonWidth, y, upButtonWidth, controlsHeight);
  53603. y += controlsHeight + 4;
  53604. Component* const listAsComp = dynamic_cast <Component*> (fileListComponent);
  53605. listAsComp->setBounds (x, y, w, browserComp.getHeight() - y - bottomSectionHeight);
  53606. y = listAsComp->getBottom() + 4;
  53607. filenameBox->setBounds (x + 50, y, w - 50, controlsHeight);
  53608. }
  53609. const Image LookAndFeel::getDefaultFolderImage()
  53610. {
  53611. 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,
  53612. 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,
  53613. 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,
  53614. 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,
  53615. 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,
  53616. 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,
  53617. 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,
  53618. 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,
  53619. 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,
  53620. 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,
  53621. 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,
  53622. 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,
  53623. 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,
  53624. 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,
  53625. 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,
  53626. 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,
  53627. 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,
  53628. 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,
  53629. 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,
  53630. 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,
  53631. 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,
  53632. 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,
  53633. 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,
  53634. 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,
  53635. 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,
  53636. 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,
  53637. 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,
  53638. 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,
  53639. 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,
  53640. 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,
  53641. 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,
  53642. 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,
  53643. 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,
  53644. 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,
  53645. 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,
  53646. 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,
  53647. 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,
  53648. 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,
  53649. 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,
  53650. 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,
  53651. 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,
  53652. 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,
  53653. 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,
  53654. 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};
  53655. return ImageCache::getFromMemory (foldericon_png, sizeof (foldericon_png));
  53656. }
  53657. const Image LookAndFeel::getDefaultDocumentFileImage()
  53658. {
  53659. 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,
  53660. 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,
  53661. 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,
  53662. 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,
  53663. 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,
  53664. 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,
  53665. 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,
  53666. 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,
  53667. 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,
  53668. 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,
  53669. 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,
  53670. 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,
  53671. 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,
  53672. 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,
  53673. 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,
  53674. 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,
  53675. 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,
  53676. 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,
  53677. 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,
  53678. 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,
  53679. 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,
  53680. 174,66,96,130,0,0};
  53681. return ImageCache::getFromMemory (fileicon_png, sizeof (fileicon_png));
  53682. }
  53683. void LookAndFeel::playAlertSound()
  53684. {
  53685. PlatformUtilities::beep();
  53686. }
  53687. void LookAndFeel::drawLevelMeter (Graphics& g, int width, int height, float level)
  53688. {
  53689. g.setColour (Colours::white.withAlpha (0.7f));
  53690. g.fillRoundedRectangle (0.0f, 0.0f, (float) width, (float) height, 3.0f);
  53691. g.setColour (Colours::black.withAlpha (0.2f));
  53692. g.drawRoundedRectangle (1.0f, 1.0f, width - 2.0f, height - 2.0f, 3.0f, 1.0f);
  53693. const int totalBlocks = 7;
  53694. const int numBlocks = roundToInt (totalBlocks * level);
  53695. const float w = (width - 6.0f) / (float) totalBlocks;
  53696. for (int i = 0; i < totalBlocks; ++i)
  53697. {
  53698. if (i >= numBlocks)
  53699. g.setColour (Colours::lightblue.withAlpha (0.6f));
  53700. else
  53701. g.setColour (i < totalBlocks - 1 ? Colours::blue.withAlpha (0.5f)
  53702. : Colours::red);
  53703. g.fillRoundedRectangle (3.0f + i * w + w * 0.1f, 3.0f, w * 0.8f, height - 6.0f, w * 0.4f);
  53704. }
  53705. }
  53706. void LookAndFeel::drawKeymapChangeButton (Graphics& g, int width, int height, Button& button, const String& keyDescription)
  53707. {
  53708. const Colour textColour (button.findColour (KeyMappingEditorComponent::textColourId, true));
  53709. if (keyDescription.isNotEmpty())
  53710. {
  53711. if (button.isEnabled())
  53712. {
  53713. const float alpha = button.isDown() ? 0.3f : (button.isOver() ? 0.15f : 0.08f);
  53714. g.fillAll (textColour.withAlpha (alpha));
  53715. g.setOpacity (0.3f);
  53716. g.drawBevel (0, 0, width, height, 2);
  53717. }
  53718. g.setColour (textColour);
  53719. g.setFont (height * 0.6f);
  53720. g.drawFittedText (keyDescription,
  53721. 3, 0, width - 6, height,
  53722. Justification::centred, 1);
  53723. }
  53724. else
  53725. {
  53726. const float thickness = 7.0f;
  53727. const float indent = 22.0f;
  53728. Path p;
  53729. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  53730. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  53731. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  53732. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  53733. p.setUsingNonZeroWinding (false);
  53734. g.setColour (textColour.withAlpha (button.isDown() ? 0.7f : (button.isOver() ? 0.5f : 0.3f)));
  53735. g.fillPath (p, p.getTransformToScaleToFit (2.0f, 2.0f, width - 4.0f, height - 4.0f, true));
  53736. }
  53737. if (button.hasKeyboardFocus (false))
  53738. {
  53739. g.setColour (textColour.withAlpha (0.4f));
  53740. g.drawRect (0, 0, width, height);
  53741. }
  53742. }
  53743. static void createRoundedPath (Path& p,
  53744. const float x, const float y,
  53745. const float w, const float h,
  53746. const float cs,
  53747. const bool curveTopLeft, const bool curveTopRight,
  53748. const bool curveBottomLeft, const bool curveBottomRight) throw()
  53749. {
  53750. const float cs2 = 2.0f * cs;
  53751. if (curveTopLeft)
  53752. {
  53753. p.startNewSubPath (x, y + cs);
  53754. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  53755. }
  53756. else
  53757. {
  53758. p.startNewSubPath (x, y);
  53759. }
  53760. if (curveTopRight)
  53761. {
  53762. p.lineTo (x + w - cs, y);
  53763. p.addArc (x + w - cs2, y, cs2, cs2, 0.0f, float_Pi * 0.5f);
  53764. }
  53765. else
  53766. {
  53767. p.lineTo (x + w, y);
  53768. }
  53769. if (curveBottomRight)
  53770. {
  53771. p.lineTo (x + w, y + h - cs);
  53772. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  53773. }
  53774. else
  53775. {
  53776. p.lineTo (x + w, y + h);
  53777. }
  53778. if (curveBottomLeft)
  53779. {
  53780. p.lineTo (x + cs, y + h);
  53781. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  53782. }
  53783. else
  53784. {
  53785. p.lineTo (x, y + h);
  53786. }
  53787. p.closeSubPath();
  53788. }
  53789. void LookAndFeel::drawShinyButtonShape (Graphics& g,
  53790. float x, float y, float w, float h,
  53791. float maxCornerSize,
  53792. const Colour& baseColour,
  53793. const float strokeWidth,
  53794. const bool flatOnLeft,
  53795. const bool flatOnRight,
  53796. const bool flatOnTop,
  53797. const bool flatOnBottom) throw()
  53798. {
  53799. if (w <= strokeWidth * 1.1f || h <= strokeWidth * 1.1f)
  53800. return;
  53801. const float cs = jmin (maxCornerSize, w * 0.5f, h * 0.5f);
  53802. Path outline;
  53803. createRoundedPath (outline, x, y, w, h, cs,
  53804. ! (flatOnLeft || flatOnTop),
  53805. ! (flatOnRight || flatOnTop),
  53806. ! (flatOnLeft || flatOnBottom),
  53807. ! (flatOnRight || flatOnBottom));
  53808. ColourGradient cg (baseColour, 0.0f, y,
  53809. baseColour.overlaidWith (Colour (0x070000ff)), 0.0f, y + h,
  53810. false);
  53811. cg.addColour (0.5, baseColour.overlaidWith (Colour (0x33ffffff)));
  53812. cg.addColour (0.51, baseColour.overlaidWith (Colour (0x110000ff)));
  53813. g.setGradientFill (cg);
  53814. g.fillPath (outline);
  53815. g.setColour (Colour (0x80000000));
  53816. g.strokePath (outline, PathStrokeType (strokeWidth));
  53817. }
  53818. void LookAndFeel::drawGlassSphere (Graphics& g,
  53819. const float x, const float y,
  53820. const float diameter,
  53821. const Colour& colour,
  53822. const float outlineThickness) throw()
  53823. {
  53824. if (diameter <= outlineThickness)
  53825. return;
  53826. Path p;
  53827. p.addEllipse (x, y, diameter, diameter);
  53828. {
  53829. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  53830. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  53831. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  53832. g.setGradientFill (cg);
  53833. g.fillPath (p);
  53834. }
  53835. g.setGradientFill (ColourGradient (Colours::white, 0, y + diameter * 0.06f,
  53836. Colours::transparentWhite, 0, y + diameter * 0.3f, false));
  53837. g.fillEllipse (x + diameter * 0.2f, y + diameter * 0.05f, diameter * 0.6f, diameter * 0.4f);
  53838. ColourGradient cg (Colours::transparentBlack,
  53839. x + diameter * 0.5f, y + diameter * 0.5f,
  53840. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  53841. x, y + diameter * 0.5f, true);
  53842. cg.addColour (0.7, Colours::transparentBlack);
  53843. cg.addColour (0.8, Colours::black.withAlpha (0.1f * outlineThickness));
  53844. g.setGradientFill (cg);
  53845. g.fillPath (p);
  53846. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  53847. g.drawEllipse (x, y, diameter, diameter, outlineThickness);
  53848. }
  53849. void LookAndFeel::drawGlassPointer (Graphics& g,
  53850. const float x, const float y,
  53851. const float diameter,
  53852. const Colour& colour, const float outlineThickness,
  53853. const int direction) throw()
  53854. {
  53855. if (diameter <= outlineThickness)
  53856. return;
  53857. Path p;
  53858. p.startNewSubPath (x + diameter * 0.5f, y);
  53859. p.lineTo (x + diameter, y + diameter * 0.6f);
  53860. p.lineTo (x + diameter, y + diameter);
  53861. p.lineTo (x, y + diameter);
  53862. p.lineTo (x, y + diameter * 0.6f);
  53863. p.closeSubPath();
  53864. p.applyTransform (AffineTransform::rotation (direction * (float_Pi * 0.5f), x + diameter * 0.5f, y + diameter * 0.5f));
  53865. {
  53866. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  53867. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  53868. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  53869. g.setGradientFill (cg);
  53870. g.fillPath (p);
  53871. }
  53872. ColourGradient cg (Colours::transparentBlack,
  53873. x + diameter * 0.5f, y + diameter * 0.5f,
  53874. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  53875. x - diameter * 0.2f, y + diameter * 0.5f, true);
  53876. cg.addColour (0.5, Colours::transparentBlack);
  53877. cg.addColour (0.7, Colours::black.withAlpha (0.07f * outlineThickness));
  53878. g.setGradientFill (cg);
  53879. g.fillPath (p);
  53880. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  53881. g.strokePath (p, PathStrokeType (outlineThickness));
  53882. }
  53883. void LookAndFeel::drawGlassLozenge (Graphics& g,
  53884. const float x, const float y,
  53885. const float width, const float height,
  53886. const Colour& colour,
  53887. const float outlineThickness,
  53888. const float cornerSize,
  53889. const bool flatOnLeft,
  53890. const bool flatOnRight,
  53891. const bool flatOnTop,
  53892. const bool flatOnBottom) throw()
  53893. {
  53894. if (width <= outlineThickness || height <= outlineThickness)
  53895. return;
  53896. const int intX = (int) x;
  53897. const int intY = (int) y;
  53898. const int intW = (int) width;
  53899. const int intH = (int) height;
  53900. const float cs = cornerSize < 0 ? jmin (width * 0.5f, height * 0.5f) : cornerSize;
  53901. const float edgeBlurRadius = height * 0.75f + (height - cs * 2.0f);
  53902. const int intEdge = (int) edgeBlurRadius;
  53903. Path outline;
  53904. createRoundedPath (outline, x, y, width, height, cs,
  53905. ! (flatOnLeft || flatOnTop),
  53906. ! (flatOnRight || flatOnTop),
  53907. ! (flatOnLeft || flatOnBottom),
  53908. ! (flatOnRight || flatOnBottom));
  53909. {
  53910. ColourGradient cg (colour.darker (0.2f), 0, y,
  53911. colour.darker (0.2f), 0, y + height, false);
  53912. cg.addColour (0.03, colour.withMultipliedAlpha (0.3f));
  53913. cg.addColour (0.4, colour);
  53914. cg.addColour (0.97, colour.withMultipliedAlpha (0.3f));
  53915. g.setGradientFill (cg);
  53916. g.fillPath (outline);
  53917. }
  53918. ColourGradient cg (Colours::transparentBlack, x + edgeBlurRadius, y + height * 0.5f,
  53919. colour.darker (0.2f), x, y + height * 0.5f, true);
  53920. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.5f) / edgeBlurRadius), Colours::transparentBlack);
  53921. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.25f) / edgeBlurRadius), colour.darker (0.2f).withMultipliedAlpha (0.3f));
  53922. if (! (flatOnLeft || flatOnTop || flatOnBottom))
  53923. {
  53924. g.saveState();
  53925. g.setGradientFill (cg);
  53926. g.reduceClipRegion (intX, intY, intEdge, intH);
  53927. g.fillPath (outline);
  53928. g.restoreState();
  53929. }
  53930. if (! (flatOnRight || flatOnTop || flatOnBottom))
  53931. {
  53932. cg.point1.setX (x + width - edgeBlurRadius);
  53933. cg.point2.setX (x + width);
  53934. g.saveState();
  53935. g.setGradientFill (cg);
  53936. g.reduceClipRegion (intX + intW - intEdge, intY, 2 + intEdge, intH);
  53937. g.fillPath (outline);
  53938. g.restoreState();
  53939. }
  53940. {
  53941. const float leftIndent = flatOnLeft ? 0.0f : cs * 0.4f;
  53942. const float rightIndent = flatOnRight ? 0.0f : cs * 0.4f;
  53943. Path highlight;
  53944. createRoundedPath (highlight,
  53945. x + leftIndent,
  53946. y + cs * 0.1f,
  53947. width - (leftIndent + rightIndent),
  53948. height * 0.4f, cs * 0.4f,
  53949. ! (flatOnLeft || flatOnTop),
  53950. ! (flatOnRight || flatOnTop),
  53951. ! (flatOnLeft || flatOnBottom),
  53952. ! (flatOnRight || flatOnBottom));
  53953. g.setGradientFill (ColourGradient (colour.brighter (10.0f), 0, y + height * 0.06f,
  53954. Colours::transparentWhite, 0, y + height * 0.4f, false));
  53955. g.fillPath (highlight);
  53956. }
  53957. g.setColour (colour.darker().withMultipliedAlpha (1.5f));
  53958. g.strokePath (outline, PathStrokeType (outlineThickness));
  53959. }
  53960. END_JUCE_NAMESPACE
  53961. /*** End of inlined file: juce_LookAndFeel.cpp ***/
  53962. /*** Start of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  53963. BEGIN_JUCE_NAMESPACE
  53964. OldSchoolLookAndFeel::OldSchoolLookAndFeel()
  53965. {
  53966. setColour (TextButton::buttonColourId, Colour (0xffbbbbff));
  53967. setColour (ListBox::outlineColourId, findColour (ComboBox::outlineColourId));
  53968. setColour (ScrollBar::thumbColourId, Colour (0xffbbbbdd));
  53969. setColour (ScrollBar::backgroundColourId, Colours::transparentBlack);
  53970. setColour (Slider::thumbColourId, Colours::white);
  53971. setColour (Slider::trackColourId, Colour (0x7f000000));
  53972. setColour (Slider::textBoxOutlineColourId, Colours::grey);
  53973. setColour (ProgressBar::backgroundColourId, Colours::white.withAlpha (0.6f));
  53974. setColour (ProgressBar::foregroundColourId, Colours::green.withAlpha (0.7f));
  53975. setColour (PopupMenu::backgroundColourId, Colour (0xffeef5f8));
  53976. setColour (PopupMenu::highlightedBackgroundColourId, Colour (0xbfa4c2ce));
  53977. setColour (PopupMenu::highlightedTextColourId, Colours::black);
  53978. setColour (TextEditor::focusedOutlineColourId, findColour (TextButton::buttonColourId));
  53979. scrollbarShadow.setShadowProperties (2.2f, 0.5f, 0, 0);
  53980. }
  53981. OldSchoolLookAndFeel::~OldSchoolLookAndFeel()
  53982. {
  53983. }
  53984. void OldSchoolLookAndFeel::drawButtonBackground (Graphics& g,
  53985. Button& button,
  53986. const Colour& backgroundColour,
  53987. bool isMouseOverButton,
  53988. bool isButtonDown)
  53989. {
  53990. const int width = button.getWidth();
  53991. const int height = button.getHeight();
  53992. const float indent = 2.0f;
  53993. const int cornerSize = jmin (roundToInt (width * 0.4f),
  53994. roundToInt (height * 0.4f));
  53995. Path p;
  53996. p.addRoundedRectangle (indent, indent,
  53997. width - indent * 2.0f,
  53998. height - indent * 2.0f,
  53999. (float) cornerSize);
  54000. Colour bc (backgroundColour.withMultipliedSaturation (0.3f));
  54001. if (isMouseOverButton)
  54002. {
  54003. if (isButtonDown)
  54004. bc = bc.brighter();
  54005. else if (bc.getBrightness() > 0.5f)
  54006. bc = bc.darker (0.1f);
  54007. else
  54008. bc = bc.brighter (0.1f);
  54009. }
  54010. g.setColour (bc);
  54011. g.fillPath (p);
  54012. g.setColour (bc.contrasting().withAlpha ((isMouseOverButton) ? 0.6f : 0.4f));
  54013. g.strokePath (p, PathStrokeType ((isMouseOverButton) ? 2.0f : 1.4f));
  54014. }
  54015. void OldSchoolLookAndFeel::drawTickBox (Graphics& g,
  54016. Component& /*component*/,
  54017. float x, float y, float w, float h,
  54018. const bool ticked,
  54019. const bool isEnabled,
  54020. const bool /*isMouseOverButton*/,
  54021. const bool isButtonDown)
  54022. {
  54023. Path box;
  54024. box.addRoundedRectangle (0.0f, 2.0f, 6.0f, 6.0f, 1.0f);
  54025. g.setColour (isEnabled ? Colours::blue.withAlpha (isButtonDown ? 0.3f : 0.1f)
  54026. : Colours::lightgrey.withAlpha (0.1f));
  54027. AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f).translated (x, y));
  54028. g.fillPath (box, trans);
  54029. g.setColour (Colours::black.withAlpha (0.6f));
  54030. g.strokePath (box, PathStrokeType (0.9f), trans);
  54031. if (ticked)
  54032. {
  54033. Path tick;
  54034. tick.startNewSubPath (1.5f, 3.0f);
  54035. tick.lineTo (3.0f, 6.0f);
  54036. tick.lineTo (6.0f, 0.0f);
  54037. g.setColour (isEnabled ? Colours::black : Colours::grey);
  54038. g.strokePath (tick, PathStrokeType (2.5f), trans);
  54039. }
  54040. }
  54041. void OldSchoolLookAndFeel::drawToggleButton (Graphics& g,
  54042. ToggleButton& button,
  54043. bool isMouseOverButton,
  54044. bool isButtonDown)
  54045. {
  54046. if (button.hasKeyboardFocus (true))
  54047. {
  54048. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  54049. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  54050. }
  54051. const int tickWidth = jmin (20, button.getHeight() - 4);
  54052. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  54053. (float) tickWidth, (float) tickWidth,
  54054. button.getToggleState(),
  54055. button.isEnabled(),
  54056. isMouseOverButton,
  54057. isButtonDown);
  54058. g.setColour (button.findColour (ToggleButton::textColourId));
  54059. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  54060. if (! button.isEnabled())
  54061. g.setOpacity (0.5f);
  54062. const int textX = tickWidth + 5;
  54063. g.drawFittedText (button.getButtonText(),
  54064. textX, 4,
  54065. button.getWidth() - textX - 2, button.getHeight() - 8,
  54066. Justification::centredLeft, 10);
  54067. }
  54068. void OldSchoolLookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  54069. int width, int height,
  54070. double progress, const String& textToShow)
  54071. {
  54072. if (progress < 0 || progress >= 1.0)
  54073. {
  54074. LookAndFeel::drawProgressBar (g, progressBar, width, height, progress, textToShow);
  54075. }
  54076. else
  54077. {
  54078. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  54079. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  54080. g.fillAll (background);
  54081. g.setColour (foreground);
  54082. g.fillRect (1, 1,
  54083. jlimit (0, width - 2, roundToInt (progress * (width - 2))),
  54084. height - 2);
  54085. if (textToShow.isNotEmpty())
  54086. {
  54087. g.setColour (Colour::contrasting (background, foreground));
  54088. g.setFont (height * 0.6f);
  54089. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  54090. }
  54091. }
  54092. }
  54093. void OldSchoolLookAndFeel::drawScrollbarButton (Graphics& g,
  54094. ScrollBar& bar,
  54095. int width, int height,
  54096. int buttonDirection,
  54097. bool isScrollbarVertical,
  54098. bool isMouseOverButton,
  54099. bool isButtonDown)
  54100. {
  54101. if (isScrollbarVertical)
  54102. width -= 2;
  54103. else
  54104. height -= 2;
  54105. Path p;
  54106. if (buttonDirection == 0)
  54107. p.addTriangle (width * 0.5f, height * 0.2f,
  54108. width * 0.1f, height * 0.7f,
  54109. width * 0.9f, height * 0.7f);
  54110. else if (buttonDirection == 1)
  54111. p.addTriangle (width * 0.8f, height * 0.5f,
  54112. width * 0.3f, height * 0.1f,
  54113. width * 0.3f, height * 0.9f);
  54114. else if (buttonDirection == 2)
  54115. p.addTriangle (width * 0.5f, height * 0.8f,
  54116. width * 0.1f, height * 0.3f,
  54117. width * 0.9f, height * 0.3f);
  54118. else if (buttonDirection == 3)
  54119. p.addTriangle (width * 0.2f, height * 0.5f,
  54120. width * 0.7f, height * 0.1f,
  54121. width * 0.7f, height * 0.9f);
  54122. if (isButtonDown)
  54123. g.setColour (Colours::white);
  54124. else if (isMouseOverButton)
  54125. g.setColour (Colours::white.withAlpha (0.7f));
  54126. else
  54127. g.setColour (bar.findColour (ScrollBar::thumbColourId).withAlpha (0.5f));
  54128. g.fillPath (p);
  54129. g.setColour (Colours::black.withAlpha (0.5f));
  54130. g.strokePath (p, PathStrokeType (0.5f));
  54131. }
  54132. void OldSchoolLookAndFeel::drawScrollbar (Graphics& g,
  54133. ScrollBar& bar,
  54134. int x, int y,
  54135. int width, int height,
  54136. bool isScrollbarVertical,
  54137. int thumbStartPosition,
  54138. int thumbSize,
  54139. bool isMouseOver,
  54140. bool isMouseDown)
  54141. {
  54142. g.fillAll (bar.findColour (ScrollBar::backgroundColourId));
  54143. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  54144. .withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.15f));
  54145. if (thumbSize > 0.0f)
  54146. {
  54147. Rectangle<int> thumb;
  54148. if (isScrollbarVertical)
  54149. {
  54150. width -= 2;
  54151. g.fillRect (x + roundToInt (width * 0.35f), y,
  54152. roundToInt (width * 0.3f), height);
  54153. thumb.setBounds (x + 1, thumbStartPosition,
  54154. width - 2, thumbSize);
  54155. }
  54156. else
  54157. {
  54158. height -= 2;
  54159. g.fillRect (x, y + roundToInt (height * 0.35f),
  54160. width, roundToInt (height * 0.3f));
  54161. thumb.setBounds (thumbStartPosition, y + 1,
  54162. thumbSize, height - 2);
  54163. }
  54164. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  54165. .withAlpha ((isMouseOver || isMouseDown) ? 0.95f : 0.7f));
  54166. g.fillRect (thumb);
  54167. g.setColour (Colours::black.withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.25f));
  54168. g.drawRect (thumb.getX(), thumb.getY(), thumb.getWidth(), thumb.getHeight());
  54169. if (thumbSize > 16)
  54170. {
  54171. for (int i = 3; --i >= 0;)
  54172. {
  54173. const float linePos = thumbStartPosition + thumbSize / 2 + (i - 1) * 4.0f;
  54174. g.setColour (Colours::black.withAlpha (0.15f));
  54175. if (isScrollbarVertical)
  54176. {
  54177. g.drawLine (x + width * 0.2f, linePos, width * 0.8f, linePos);
  54178. g.setColour (Colours::white.withAlpha (0.15f));
  54179. g.drawLine (width * 0.2f, linePos - 1, width * 0.8f, linePos - 1);
  54180. }
  54181. else
  54182. {
  54183. g.drawLine (linePos, height * 0.2f, linePos, height * 0.8f);
  54184. g.setColour (Colours::white.withAlpha (0.15f));
  54185. g.drawLine (linePos - 1, height * 0.2f, linePos - 1, height * 0.8f);
  54186. }
  54187. }
  54188. }
  54189. }
  54190. }
  54191. ImageEffectFilter* OldSchoolLookAndFeel::getScrollbarEffect()
  54192. {
  54193. return &scrollbarShadow;
  54194. }
  54195. void OldSchoolLookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  54196. {
  54197. g.fillAll (findColour (PopupMenu::backgroundColourId));
  54198. g.setColour (Colours::black.withAlpha (0.6f));
  54199. g.drawRect (0, 0, width, height);
  54200. }
  54201. void OldSchoolLookAndFeel::drawMenuBarBackground (Graphics& g, int /*width*/, int /*height*/,
  54202. bool, MenuBarComponent& menuBar)
  54203. {
  54204. g.fillAll (menuBar.findColour (PopupMenu::backgroundColourId));
  54205. }
  54206. void OldSchoolLookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  54207. {
  54208. if (textEditor.isEnabled())
  54209. {
  54210. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  54211. g.drawRect (0, 0, width, height);
  54212. }
  54213. }
  54214. void OldSchoolLookAndFeel::drawComboBox (Graphics& g, int width, int height,
  54215. const bool isButtonDown,
  54216. int buttonX, int buttonY,
  54217. int buttonW, int buttonH,
  54218. ComboBox& box)
  54219. {
  54220. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  54221. g.setColour (box.findColour ((isButtonDown) ? ComboBox::buttonColourId
  54222. : ComboBox::backgroundColourId));
  54223. g.fillRect (buttonX, buttonY, buttonW, buttonH);
  54224. g.setColour (box.findColour (ComboBox::outlineColourId));
  54225. g.drawRect (0, 0, width, height);
  54226. const float arrowX = 0.2f;
  54227. const float arrowH = 0.3f;
  54228. if (box.isEnabled())
  54229. {
  54230. Path p;
  54231. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  54232. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  54233. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  54234. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  54235. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  54236. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  54237. g.setColour (box.findColour ((isButtonDown) ? ComboBox::backgroundColourId
  54238. : ComboBox::buttonColourId));
  54239. g.fillPath (p);
  54240. }
  54241. }
  54242. const Font OldSchoolLookAndFeel::getComboBoxFont (ComboBox& box)
  54243. {
  54244. Font f (jmin (15.0f, box.getHeight() * 0.85f));
  54245. f.setHorizontalScale (0.9f);
  54246. return f;
  54247. }
  54248. static void drawTriangle (Graphics& g, float x1, float y1, float x2, float y2, float x3, float y3, const Colour& fill, const Colour& outline) throw()
  54249. {
  54250. Path p;
  54251. p.addTriangle (x1, y1, x2, y2, x3, y3);
  54252. g.setColour (fill);
  54253. g.fillPath (p);
  54254. g.setColour (outline);
  54255. g.strokePath (p, PathStrokeType (0.3f));
  54256. }
  54257. void OldSchoolLookAndFeel::drawLinearSlider (Graphics& g,
  54258. int x, int y,
  54259. int w, int h,
  54260. float sliderPos,
  54261. float minSliderPos,
  54262. float maxSliderPos,
  54263. const Slider::SliderStyle style,
  54264. Slider& slider)
  54265. {
  54266. g.fillAll (slider.findColour (Slider::backgroundColourId));
  54267. if (style == Slider::LinearBar)
  54268. {
  54269. g.setColour (slider.findColour (Slider::thumbColourId));
  54270. g.fillRect (x, y, (int) sliderPos - x, h);
  54271. g.setColour (slider.findColour (Slider::textBoxTextColourId).withMultipliedAlpha (0.5f));
  54272. g.drawRect (x, y, (int) sliderPos - x, h);
  54273. }
  54274. else
  54275. {
  54276. g.setColour (slider.findColour (Slider::trackColourId)
  54277. .withMultipliedAlpha (slider.isEnabled() ? 1.0f : 0.3f));
  54278. if (slider.isHorizontal())
  54279. {
  54280. g.fillRect (x, y + roundToInt (h * 0.6f),
  54281. w, roundToInt (h * 0.2f));
  54282. }
  54283. else
  54284. {
  54285. g.fillRect (x + roundToInt (w * 0.5f - jmin (3.0f, w * 0.1f)), y,
  54286. jmin (4, roundToInt (w * 0.2f)), h);
  54287. }
  54288. float alpha = 0.35f;
  54289. if (slider.isEnabled())
  54290. alpha = slider.isMouseOverOrDragging() ? 1.0f : 0.7f;
  54291. const Colour fill (slider.findColour (Slider::thumbColourId).withAlpha (alpha));
  54292. const Colour outline (Colours::black.withAlpha (slider.isEnabled() ? 0.7f : 0.35f));
  54293. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  54294. {
  54295. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), minSliderPos,
  54296. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos - 7.0f,
  54297. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos,
  54298. fill, outline);
  54299. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), maxSliderPos,
  54300. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos,
  54301. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos + 7.0f,
  54302. fill, outline);
  54303. }
  54304. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  54305. {
  54306. drawTriangle (g, minSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  54307. minSliderPos - 7.0f, y + h * 0.9f ,
  54308. minSliderPos, y + h * 0.9f,
  54309. fill, outline);
  54310. drawTriangle (g, maxSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  54311. maxSliderPos, y + h * 0.9f,
  54312. maxSliderPos + 7.0f, y + h * 0.9f,
  54313. fill, outline);
  54314. }
  54315. if (style == Slider::LinearHorizontal || style == Slider::ThreeValueHorizontal)
  54316. {
  54317. drawTriangle (g, sliderPos, y + h * 0.9f,
  54318. sliderPos - 7.0f, y + h * 0.2f,
  54319. sliderPos + 7.0f, y + h * 0.2f,
  54320. fill, outline);
  54321. }
  54322. else if (style == Slider::LinearVertical || style == Slider::ThreeValueVertical)
  54323. {
  54324. drawTriangle (g, x + w * 0.5f - jmin (4.0f, w * 0.3f), sliderPos,
  54325. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos - 7.0f,
  54326. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos + 7.0f,
  54327. fill, outline);
  54328. }
  54329. }
  54330. }
  54331. Button* OldSchoolLookAndFeel::createSliderButton (const bool isIncrement)
  54332. {
  54333. if (isIncrement)
  54334. return new ArrowButton ("u", 0.75f, Colours::white.withAlpha (0.8f));
  54335. else
  54336. return new ArrowButton ("d", 0.25f, Colours::white.withAlpha (0.8f));
  54337. }
  54338. ImageEffectFilter* OldSchoolLookAndFeel::getSliderEffect()
  54339. {
  54340. return &scrollbarShadow;
  54341. }
  54342. int OldSchoolLookAndFeel::getSliderThumbRadius (Slider&)
  54343. {
  54344. return 8;
  54345. }
  54346. void OldSchoolLookAndFeel::drawCornerResizer (Graphics& g,
  54347. int w, int h,
  54348. bool isMouseOver,
  54349. bool isMouseDragging)
  54350. {
  54351. g.setColour ((isMouseOver || isMouseDragging) ? Colours::lightgrey
  54352. : Colours::darkgrey);
  54353. const float lineThickness = jmin (w, h) * 0.1f;
  54354. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  54355. {
  54356. g.drawLine (w * i,
  54357. h + 1.0f,
  54358. w + 1.0f,
  54359. h * i,
  54360. lineThickness);
  54361. }
  54362. }
  54363. Button* OldSchoolLookAndFeel::createDocumentWindowButton (int buttonType)
  54364. {
  54365. Path shape;
  54366. if (buttonType == DocumentWindow::closeButton)
  54367. {
  54368. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), 0.35f);
  54369. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), 0.35f);
  54370. ShapeButton* const b = new ShapeButton ("close",
  54371. Colour (0x7fff3333),
  54372. Colour (0xd7ff3333),
  54373. Colour (0xf7ff3333));
  54374. b->setShape (shape, true, true, true);
  54375. return b;
  54376. }
  54377. else if (buttonType == DocumentWindow::minimiseButton)
  54378. {
  54379. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  54380. DrawableButton* b = new DrawableButton ("minimise", DrawableButton::ImageFitted);
  54381. DrawablePath dp;
  54382. dp.setPath (shape);
  54383. dp.setFill (Colours::black.withAlpha (0.3f));
  54384. b->setImages (&dp);
  54385. return b;
  54386. }
  54387. else if (buttonType == DocumentWindow::maximiseButton)
  54388. {
  54389. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), 0.25f);
  54390. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  54391. DrawableButton* b = new DrawableButton ("maximise", DrawableButton::ImageFitted);
  54392. DrawablePath dp;
  54393. dp.setPath (shape);
  54394. dp.setFill (Colours::black.withAlpha (0.3f));
  54395. b->setImages (&dp);
  54396. return b;
  54397. }
  54398. jassertfalse;
  54399. return 0;
  54400. }
  54401. void OldSchoolLookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  54402. int titleBarX,
  54403. int titleBarY,
  54404. int titleBarW,
  54405. int titleBarH,
  54406. Button* minimiseButton,
  54407. Button* maximiseButton,
  54408. Button* closeButton,
  54409. bool positionTitleBarButtonsOnLeft)
  54410. {
  54411. titleBarY += titleBarH / 8;
  54412. titleBarH -= titleBarH / 4;
  54413. const int buttonW = titleBarH;
  54414. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  54415. : titleBarX + titleBarW - buttonW - 4;
  54416. if (closeButton != 0)
  54417. {
  54418. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  54419. x += positionTitleBarButtonsOnLeft ? buttonW + buttonW / 5
  54420. : -(buttonW + buttonW / 5);
  54421. }
  54422. if (positionTitleBarButtonsOnLeft)
  54423. swapVariables (minimiseButton, maximiseButton);
  54424. if (maximiseButton != 0)
  54425. {
  54426. maximiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  54427. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  54428. }
  54429. if (minimiseButton != 0)
  54430. minimiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  54431. }
  54432. END_JUCE_NAMESPACE
  54433. /*** End of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  54434. /*** Start of inlined file: juce_MenuBarComponent.cpp ***/
  54435. BEGIN_JUCE_NAMESPACE
  54436. MenuBarComponent::MenuBarComponent (MenuBarModel* model_)
  54437. : model (0),
  54438. itemUnderMouse (-1),
  54439. currentPopupIndex (-1),
  54440. topLevelIndexClicked (0),
  54441. lastMouseX (0),
  54442. lastMouseY (0)
  54443. {
  54444. setRepaintsOnMouseActivity (true);
  54445. setWantsKeyboardFocus (false);
  54446. setMouseClickGrabsKeyboardFocus (false);
  54447. setModel (model_);
  54448. }
  54449. MenuBarComponent::~MenuBarComponent()
  54450. {
  54451. setModel (0);
  54452. Desktop::getInstance().removeGlobalMouseListener (this);
  54453. }
  54454. MenuBarModel* MenuBarComponent::getModel() const throw()
  54455. {
  54456. return model;
  54457. }
  54458. void MenuBarComponent::setModel (MenuBarModel* const newModel)
  54459. {
  54460. if (model != newModel)
  54461. {
  54462. if (model != 0)
  54463. model->removeListener (this);
  54464. model = newModel;
  54465. if (model != 0)
  54466. model->addListener (this);
  54467. repaint();
  54468. menuBarItemsChanged (0);
  54469. }
  54470. }
  54471. void MenuBarComponent::paint (Graphics& g)
  54472. {
  54473. const bool isMouseOverBar = currentPopupIndex >= 0 || itemUnderMouse >= 0 || isMouseOver();
  54474. getLookAndFeel().drawMenuBarBackground (g,
  54475. getWidth(),
  54476. getHeight(),
  54477. isMouseOverBar,
  54478. *this);
  54479. if (model != 0)
  54480. {
  54481. for (int i = 0; i < menuNames.size(); ++i)
  54482. {
  54483. g.saveState();
  54484. g.setOrigin (xPositions [i], 0);
  54485. g.reduceClipRegion (0, 0, xPositions[i + 1] - xPositions[i], getHeight());
  54486. getLookAndFeel().drawMenuBarItem (g,
  54487. xPositions[i + 1] - xPositions[i],
  54488. getHeight(),
  54489. i,
  54490. menuNames[i],
  54491. i == itemUnderMouse,
  54492. i == currentPopupIndex,
  54493. isMouseOverBar,
  54494. *this);
  54495. g.restoreState();
  54496. }
  54497. }
  54498. }
  54499. void MenuBarComponent::resized()
  54500. {
  54501. xPositions.clear();
  54502. int x = 2;
  54503. xPositions.add (x);
  54504. for (int i = 0; i < menuNames.size(); ++i)
  54505. {
  54506. x += getLookAndFeel().getMenuBarItemWidth (*this, i, menuNames[i]);
  54507. xPositions.add (x);
  54508. }
  54509. }
  54510. int MenuBarComponent::getItemAt (const int x, const int y)
  54511. {
  54512. for (int i = 0; i < xPositions.size(); ++i)
  54513. if (x >= xPositions[i] && x < xPositions[i + 1])
  54514. return reallyContains (x, y, true) ? i : -1;
  54515. return -1;
  54516. }
  54517. void MenuBarComponent::repaintMenuItem (int index)
  54518. {
  54519. if (((unsigned int) index) < (unsigned int) xPositions.size())
  54520. {
  54521. const int x1 = xPositions [index];
  54522. const int x2 = xPositions [index + 1];
  54523. repaint (x1 - 2, 0, x2 - x1 + 4, getHeight());
  54524. }
  54525. }
  54526. void MenuBarComponent::setItemUnderMouse (const int index)
  54527. {
  54528. if (itemUnderMouse != index)
  54529. {
  54530. repaintMenuItem (itemUnderMouse);
  54531. itemUnderMouse = index;
  54532. repaintMenuItem (itemUnderMouse);
  54533. }
  54534. }
  54535. void MenuBarComponent::setOpenItem (int index)
  54536. {
  54537. if (currentPopupIndex != index)
  54538. {
  54539. repaintMenuItem (currentPopupIndex);
  54540. currentPopupIndex = index;
  54541. repaintMenuItem (currentPopupIndex);
  54542. if (index >= 0)
  54543. Desktop::getInstance().addGlobalMouseListener (this);
  54544. else
  54545. Desktop::getInstance().removeGlobalMouseListener (this);
  54546. }
  54547. }
  54548. void MenuBarComponent::updateItemUnderMouse (int x, int y)
  54549. {
  54550. setItemUnderMouse (getItemAt (x, y));
  54551. }
  54552. class MenuBarComponent::AsyncCallback : public ModalComponentManager::Callback
  54553. {
  54554. public:
  54555. AsyncCallback (MenuBarComponent* const bar_, const int topLevelIndex_)
  54556. : bar (bar_), topLevelIndex (topLevelIndex_)
  54557. {
  54558. }
  54559. ~AsyncCallback() {}
  54560. void modalStateFinished (int returnValue)
  54561. {
  54562. if (bar != 0)
  54563. bar->menuDismissed (topLevelIndex, returnValue);
  54564. }
  54565. private:
  54566. Component::SafePointer<MenuBarComponent> bar;
  54567. const int topLevelIndex;
  54568. AsyncCallback (const AsyncCallback&);
  54569. AsyncCallback& operator= (const AsyncCallback&);
  54570. };
  54571. void MenuBarComponent::showMenu (int index)
  54572. {
  54573. if (index != currentPopupIndex)
  54574. {
  54575. PopupMenu::dismissAllActiveMenus();
  54576. menuBarItemsChanged (0);
  54577. setOpenItem (index);
  54578. setItemUnderMouse (index);
  54579. if (index >= 0)
  54580. {
  54581. PopupMenu m (model->getMenuForIndex (itemUnderMouse,
  54582. menuNames [itemUnderMouse]));
  54583. if (m.lookAndFeel == 0)
  54584. m.setLookAndFeel (&getLookAndFeel());
  54585. const Rectangle<int> itemPos (xPositions [index], 0, xPositions [index + 1] - xPositions [index], getHeight());
  54586. m.showMenu (itemPos + getScreenPosition(),
  54587. 0, itemPos.getWidth(), 0, 0, true, this,
  54588. new AsyncCallback (this, index));
  54589. }
  54590. }
  54591. }
  54592. void MenuBarComponent::menuDismissed (int topLevelIndex, int itemId)
  54593. {
  54594. topLevelIndexClicked = topLevelIndex;
  54595. postCommandMessage (itemId);
  54596. }
  54597. void MenuBarComponent::handleCommandMessage (int commandId)
  54598. {
  54599. const Point<int> mousePos (getMouseXYRelative());
  54600. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  54601. if (! isCurrentlyBlockedByAnotherModalComponent())
  54602. setOpenItem (-1);
  54603. if (commandId != 0 && model != 0)
  54604. model->menuItemSelected (commandId, topLevelIndexClicked);
  54605. }
  54606. void MenuBarComponent::mouseEnter (const MouseEvent& e)
  54607. {
  54608. if (e.eventComponent == this)
  54609. updateItemUnderMouse (e.x, e.y);
  54610. }
  54611. void MenuBarComponent::mouseExit (const MouseEvent& e)
  54612. {
  54613. if (e.eventComponent == this)
  54614. updateItemUnderMouse (e.x, e.y);
  54615. }
  54616. void MenuBarComponent::mouseDown (const MouseEvent& e)
  54617. {
  54618. if (currentPopupIndex < 0)
  54619. {
  54620. const MouseEvent e2 (e.getEventRelativeTo (this));
  54621. updateItemUnderMouse (e2.x, e2.y);
  54622. currentPopupIndex = -2;
  54623. showMenu (itemUnderMouse);
  54624. }
  54625. }
  54626. void MenuBarComponent::mouseDrag (const MouseEvent& e)
  54627. {
  54628. const MouseEvent e2 (e.getEventRelativeTo (this));
  54629. const int item = getItemAt (e2.x, e2.y);
  54630. if (item >= 0)
  54631. showMenu (item);
  54632. }
  54633. void MenuBarComponent::mouseUp (const MouseEvent& e)
  54634. {
  54635. const MouseEvent e2 (e.getEventRelativeTo (this));
  54636. updateItemUnderMouse (e2.x, e2.y);
  54637. if (itemUnderMouse < 0 && getLocalBounds().contains (e2.x, e2.y))
  54638. {
  54639. setOpenItem (-1);
  54640. PopupMenu::dismissAllActiveMenus();
  54641. }
  54642. }
  54643. void MenuBarComponent::mouseMove (const MouseEvent& e)
  54644. {
  54645. const MouseEvent e2 (e.getEventRelativeTo (this));
  54646. if (lastMouseX != e2.x || lastMouseY != e2.y)
  54647. {
  54648. if (currentPopupIndex >= 0)
  54649. {
  54650. const int item = getItemAt (e2.x, e2.y);
  54651. if (item >= 0)
  54652. showMenu (item);
  54653. }
  54654. else
  54655. {
  54656. updateItemUnderMouse (e2.x, e2.y);
  54657. }
  54658. lastMouseX = e2.x;
  54659. lastMouseY = e2.y;
  54660. }
  54661. }
  54662. bool MenuBarComponent::keyPressed (const KeyPress& key)
  54663. {
  54664. bool used = false;
  54665. const int numMenus = menuNames.size();
  54666. const int currentIndex = jlimit (0, menuNames.size() - 1, currentPopupIndex);
  54667. if (key.isKeyCode (KeyPress::leftKey))
  54668. {
  54669. showMenu ((currentIndex + numMenus - 1) % numMenus);
  54670. used = true;
  54671. }
  54672. else if (key.isKeyCode (KeyPress::rightKey))
  54673. {
  54674. showMenu ((currentIndex + 1) % numMenus);
  54675. used = true;
  54676. }
  54677. return used;
  54678. }
  54679. void MenuBarComponent::menuBarItemsChanged (MenuBarModel* /*menuBarModel*/)
  54680. {
  54681. StringArray newNames;
  54682. if (model != 0)
  54683. newNames = model->getMenuBarNames();
  54684. if (newNames != menuNames)
  54685. {
  54686. menuNames = newNames;
  54687. repaint();
  54688. resized();
  54689. }
  54690. }
  54691. void MenuBarComponent::menuCommandInvoked (MenuBarModel* /*menuBarModel*/,
  54692. const ApplicationCommandTarget::InvocationInfo& info)
  54693. {
  54694. if (model == 0 || (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) != 0)
  54695. return;
  54696. for (int i = 0; i < menuNames.size(); ++i)
  54697. {
  54698. const PopupMenu menu (model->getMenuForIndex (i, menuNames [i]));
  54699. if (menu.containsCommandItem (info.commandID))
  54700. {
  54701. setItemUnderMouse (i);
  54702. startTimer (200);
  54703. break;
  54704. }
  54705. }
  54706. }
  54707. void MenuBarComponent::timerCallback()
  54708. {
  54709. stopTimer();
  54710. const Point<int> mousePos (getMouseXYRelative());
  54711. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  54712. }
  54713. END_JUCE_NAMESPACE
  54714. /*** End of inlined file: juce_MenuBarComponent.cpp ***/
  54715. /*** Start of inlined file: juce_MenuBarModel.cpp ***/
  54716. BEGIN_JUCE_NAMESPACE
  54717. MenuBarModel::MenuBarModel() throw()
  54718. : manager (0)
  54719. {
  54720. }
  54721. MenuBarModel::~MenuBarModel()
  54722. {
  54723. setApplicationCommandManagerToWatch (0);
  54724. }
  54725. void MenuBarModel::menuItemsChanged()
  54726. {
  54727. triggerAsyncUpdate();
  54728. }
  54729. void MenuBarModel::setApplicationCommandManagerToWatch (ApplicationCommandManager* const newManager) throw()
  54730. {
  54731. if (manager != newManager)
  54732. {
  54733. if (manager != 0)
  54734. manager->removeListener (this);
  54735. manager = newManager;
  54736. if (manager != 0)
  54737. manager->addListener (this);
  54738. }
  54739. }
  54740. void MenuBarModel::addListener (MenuBarModelListener* const newListener) throw()
  54741. {
  54742. listeners.add (newListener);
  54743. }
  54744. void MenuBarModel::removeListener (MenuBarModelListener* const listenerToRemove) throw()
  54745. {
  54746. // Trying to remove a listener that isn't on the list!
  54747. // If this assertion happens because this object is a dangling pointer, make sure you've not
  54748. // deleted this menu model while it's still being used by something (e.g. by a MenuBarComponent)
  54749. jassert (listeners.contains (listenerToRemove));
  54750. listeners.remove (listenerToRemove);
  54751. }
  54752. void MenuBarModel::handleAsyncUpdate()
  54753. {
  54754. listeners.call (&MenuBarModelListener::menuBarItemsChanged, this);
  54755. }
  54756. void MenuBarModel::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  54757. {
  54758. listeners.call (&MenuBarModelListener::menuCommandInvoked, this, info);
  54759. }
  54760. void MenuBarModel::applicationCommandListChanged()
  54761. {
  54762. menuItemsChanged();
  54763. }
  54764. END_JUCE_NAMESPACE
  54765. /*** End of inlined file: juce_MenuBarModel.cpp ***/
  54766. /*** Start of inlined file: juce_PopupMenu.cpp ***/
  54767. BEGIN_JUCE_NAMESPACE
  54768. class PopupMenu::Item
  54769. {
  54770. public:
  54771. Item()
  54772. : itemId (0), active (true), isSeparator (true), isTicked (false),
  54773. usesColour (false), customComp (0), commandManager (0)
  54774. {
  54775. }
  54776. Item (const int itemId_,
  54777. const String& text_,
  54778. const bool active_,
  54779. const bool isTicked_,
  54780. const Image& im,
  54781. const Colour& textColour_,
  54782. const bool usesColour_,
  54783. PopupMenuCustomComponent* const customComp_,
  54784. const PopupMenu* const subMenu_,
  54785. ApplicationCommandManager* const commandManager_)
  54786. : itemId (itemId_), text (text_), textColour (textColour_),
  54787. active (active_), isSeparator (false), isTicked (isTicked_),
  54788. usesColour (usesColour_), image (im), customComp (customComp_),
  54789. commandManager (commandManager_)
  54790. {
  54791. if (subMenu_ != 0)
  54792. subMenu = new PopupMenu (*subMenu_);
  54793. if (commandManager_ != 0 && itemId_ != 0)
  54794. {
  54795. String shortcutKey;
  54796. Array <KeyPress> keyPresses (commandManager_->getKeyMappings()
  54797. ->getKeyPressesAssignedToCommand (itemId_));
  54798. for (int i = 0; i < keyPresses.size(); ++i)
  54799. {
  54800. const String key (keyPresses.getReference(i).getTextDescription());
  54801. if (shortcutKey.isNotEmpty())
  54802. shortcutKey << ", ";
  54803. if (key.length() == 1)
  54804. shortcutKey << "shortcut: '" << key << '\'';
  54805. else
  54806. shortcutKey << key;
  54807. }
  54808. shortcutKey = shortcutKey.trim();
  54809. if (shortcutKey.isNotEmpty())
  54810. text << "<end>" << shortcutKey;
  54811. }
  54812. }
  54813. Item (const Item& other)
  54814. : itemId (other.itemId),
  54815. text (other.text),
  54816. textColour (other.textColour),
  54817. active (other.active),
  54818. isSeparator (other.isSeparator),
  54819. isTicked (other.isTicked),
  54820. usesColour (other.usesColour),
  54821. image (other.image),
  54822. customComp (other.customComp),
  54823. commandManager (other.commandManager)
  54824. {
  54825. if (other.subMenu != 0)
  54826. subMenu = new PopupMenu (*(other.subMenu));
  54827. }
  54828. ~Item()
  54829. {
  54830. customComp = 0;
  54831. }
  54832. bool canBeTriggered() const throw()
  54833. {
  54834. return active && ! (isSeparator || (subMenu != 0));
  54835. }
  54836. bool hasActiveSubMenu() const throw()
  54837. {
  54838. return active && (subMenu != 0);
  54839. }
  54840. const int itemId;
  54841. String text;
  54842. const Colour textColour;
  54843. const bool active, isSeparator, isTicked, usesColour;
  54844. Image image;
  54845. ReferenceCountedObjectPtr <PopupMenuCustomComponent> customComp;
  54846. ScopedPointer <PopupMenu> subMenu;
  54847. ApplicationCommandManager* const commandManager;
  54848. juce_UseDebuggingNewOperator
  54849. private:
  54850. Item& operator= (const Item&);
  54851. };
  54852. class PopupMenu::ItemComponent : public Component
  54853. {
  54854. public:
  54855. ItemComponent (const PopupMenu::Item& itemInfo_)
  54856. : itemInfo (itemInfo_),
  54857. isHighlighted (false)
  54858. {
  54859. if (itemInfo.customComp != 0)
  54860. addAndMakeVisible (itemInfo.customComp);
  54861. }
  54862. ~ItemComponent()
  54863. {
  54864. if (itemInfo.customComp != 0)
  54865. removeChildComponent (itemInfo.customComp);
  54866. }
  54867. void getIdealSize (int& idealWidth,
  54868. int& idealHeight,
  54869. const int standardItemHeight)
  54870. {
  54871. if (itemInfo.customComp != 0)
  54872. {
  54873. itemInfo.customComp->getIdealSize (idealWidth, idealHeight);
  54874. }
  54875. else
  54876. {
  54877. getLookAndFeel().getIdealPopupMenuItemSize (itemInfo.text,
  54878. itemInfo.isSeparator,
  54879. standardItemHeight,
  54880. idealWidth,
  54881. idealHeight);
  54882. }
  54883. }
  54884. void paint (Graphics& g)
  54885. {
  54886. if (itemInfo.customComp == 0)
  54887. {
  54888. String mainText (itemInfo.text);
  54889. String endText;
  54890. const int endIndex = mainText.indexOf ("<end>");
  54891. if (endIndex >= 0)
  54892. {
  54893. endText = mainText.substring (endIndex + 5).trim();
  54894. mainText = mainText.substring (0, endIndex);
  54895. }
  54896. getLookAndFeel()
  54897. .drawPopupMenuItem (g, getWidth(), getHeight(),
  54898. itemInfo.isSeparator,
  54899. itemInfo.active,
  54900. isHighlighted,
  54901. itemInfo.isTicked,
  54902. itemInfo.subMenu != 0,
  54903. mainText, endText,
  54904. itemInfo.image.isValid() ? &itemInfo.image : 0,
  54905. itemInfo.usesColour ? &(itemInfo.textColour) : 0);
  54906. }
  54907. }
  54908. void resized()
  54909. {
  54910. if (getNumChildComponents() > 0)
  54911. getChildComponent(0)->setBounds (2, 0, getWidth() - 4, getHeight());
  54912. }
  54913. void setHighlighted (bool shouldBeHighlighted)
  54914. {
  54915. shouldBeHighlighted = shouldBeHighlighted && itemInfo.active;
  54916. if (isHighlighted != shouldBeHighlighted)
  54917. {
  54918. isHighlighted = shouldBeHighlighted;
  54919. if (itemInfo.customComp != 0)
  54920. {
  54921. itemInfo.customComp->isHighlighted = shouldBeHighlighted;
  54922. itemInfo.customComp->repaint();
  54923. }
  54924. repaint();
  54925. }
  54926. }
  54927. PopupMenu::Item itemInfo;
  54928. juce_UseDebuggingNewOperator
  54929. private:
  54930. bool isHighlighted;
  54931. ItemComponent (const ItemComponent&);
  54932. ItemComponent& operator= (const ItemComponent&);
  54933. };
  54934. namespace PopupMenuSettings
  54935. {
  54936. static const int scrollZone = 24;
  54937. static const int borderSize = 2;
  54938. static const int timerInterval = 50;
  54939. static const int dismissCommandId = 0x6287345f;
  54940. }
  54941. class PopupMenu::Window : public Component,
  54942. private Timer
  54943. {
  54944. public:
  54945. Window()
  54946. : Component ("menu"),
  54947. owner (0),
  54948. currentChild (0),
  54949. activeSubMenu (0),
  54950. managerOfChosenCommand (0),
  54951. minimumWidth (0),
  54952. maximumNumColumns (7),
  54953. standardItemHeight (0),
  54954. isOver (false),
  54955. hasBeenOver (false),
  54956. isDown (false),
  54957. needsToScroll (false),
  54958. hideOnExit (false),
  54959. disableMouseMoves (false),
  54960. hasAnyJuceCompHadFocus (false),
  54961. numColumns (0),
  54962. contentHeight (0),
  54963. childYOffset (0),
  54964. timeEnteredCurrentChildComp (0),
  54965. scrollAcceleration (1.0)
  54966. {
  54967. menuCreationTime = lastFocused = lastScroll = Time::getMillisecondCounter();
  54968. setWantsKeyboardFocus (true);
  54969. setMouseClickGrabsKeyboardFocus (false);
  54970. setOpaque (true);
  54971. setAlwaysOnTop (true);
  54972. Desktop::getInstance().addGlobalMouseListener (this);
  54973. getActiveWindows().add (this);
  54974. }
  54975. ~Window()
  54976. {
  54977. getActiveWindows().removeValue (this);
  54978. Desktop::getInstance().removeGlobalMouseListener (this);
  54979. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  54980. activeSubMenu = 0;
  54981. deleteAllChildren();
  54982. }
  54983. static Window* create (const PopupMenu& menu,
  54984. const bool dismissOnMouseUp,
  54985. Window* const owner_,
  54986. const Rectangle<int>& target,
  54987. const int minimumWidth,
  54988. const int maximumNumColumns,
  54989. const int standardItemHeight,
  54990. const bool alignToRectangle,
  54991. const int itemIdThatMustBeVisible,
  54992. ApplicationCommandManager** managerOfChosenCommand,
  54993. Component* const componentAttachedTo)
  54994. {
  54995. if (menu.items.size() > 0)
  54996. {
  54997. int totalItems = 0;
  54998. ScopedPointer <Window> mw (new Window());
  54999. mw->setLookAndFeel (menu.lookAndFeel);
  55000. mw->setWantsKeyboardFocus (false);
  55001. mw->minimumWidth = minimumWidth;
  55002. mw->maximumNumColumns = maximumNumColumns;
  55003. mw->standardItemHeight = standardItemHeight;
  55004. mw->dismissOnMouseUp = dismissOnMouseUp;
  55005. for (int i = 0; i < menu.items.size(); ++i)
  55006. {
  55007. PopupMenu::Item* const item = menu.items.getUnchecked(i);
  55008. mw->addItem (*item);
  55009. ++totalItems;
  55010. }
  55011. if (totalItems > 0)
  55012. {
  55013. mw->owner = owner_;
  55014. mw->managerOfChosenCommand = managerOfChosenCommand;
  55015. mw->componentAttachedTo = componentAttachedTo;
  55016. mw->componentAttachedToOriginal = componentAttachedTo;
  55017. mw->calculateWindowPos (target, alignToRectangle);
  55018. mw->setTopLeftPosition (mw->windowPos.getX(),
  55019. mw->windowPos.getY());
  55020. mw->updateYPositions();
  55021. if (itemIdThatMustBeVisible != 0)
  55022. {
  55023. const int y = target.getY() - mw->windowPos.getY();
  55024. mw->ensureItemIsVisible (itemIdThatMustBeVisible,
  55025. (((unsigned int) y) < (unsigned int) mw->windowPos.getHeight()) ? y : -1);
  55026. }
  55027. mw->resizeToBestWindowPos();
  55028. mw->addToDesktop (ComponentPeer::windowIsTemporary
  55029. | mw->getLookAndFeel().getMenuWindowFlags());
  55030. return mw.release();
  55031. }
  55032. }
  55033. return 0;
  55034. }
  55035. void paint (Graphics& g)
  55036. {
  55037. getLookAndFeel().drawPopupMenuBackground (g, getWidth(), getHeight());
  55038. }
  55039. void paintOverChildren (Graphics& g)
  55040. {
  55041. if (isScrolling())
  55042. {
  55043. LookAndFeel& lf = getLookAndFeel();
  55044. if (isScrollZoneActive (false))
  55045. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, true);
  55046. if (isScrollZoneActive (true))
  55047. {
  55048. g.setOrigin (0, getHeight() - PopupMenuSettings::scrollZone);
  55049. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, false);
  55050. }
  55051. }
  55052. }
  55053. bool isScrollZoneActive (bool bottomOne) const
  55054. {
  55055. return isScrolling()
  55056. && (bottomOne
  55057. ? childYOffset < contentHeight - windowPos.getHeight()
  55058. : childYOffset > 0);
  55059. }
  55060. void addItem (const PopupMenu::Item& item)
  55061. {
  55062. PopupMenu::ItemComponent* const mic = new PopupMenu::ItemComponent (item);
  55063. addAndMakeVisible (mic);
  55064. int itemW = 80;
  55065. int itemH = 16;
  55066. mic->getIdealSize (itemW, itemH, standardItemHeight);
  55067. mic->setSize (itemW, jlimit (2, 600, itemH));
  55068. mic->addMouseListener (this, false);
  55069. }
  55070. // hide this and all sub-comps
  55071. void hide (const PopupMenu::Item* const item)
  55072. {
  55073. if (isVisible())
  55074. {
  55075. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55076. activeSubMenu = 0;
  55077. currentChild = 0;
  55078. exitModalState (item != 0 ? item->itemId : 0);
  55079. setVisible (false);
  55080. if (item != 0
  55081. && item->commandManager != 0
  55082. && item->itemId != 0)
  55083. {
  55084. *managerOfChosenCommand = item->commandManager;
  55085. }
  55086. }
  55087. }
  55088. void dismissMenu (const PopupMenu::Item* const item)
  55089. {
  55090. if (owner != 0)
  55091. {
  55092. owner->dismissMenu (item);
  55093. }
  55094. else
  55095. {
  55096. if (item != 0)
  55097. {
  55098. // need a copy of this on the stack as the one passed in will get deleted during this call
  55099. const PopupMenu::Item mi (*item);
  55100. hide (&mi);
  55101. }
  55102. else
  55103. {
  55104. hide (0);
  55105. }
  55106. }
  55107. }
  55108. void mouseMove (const MouseEvent&)
  55109. {
  55110. timerCallback();
  55111. }
  55112. void mouseDown (const MouseEvent&)
  55113. {
  55114. timerCallback();
  55115. }
  55116. void mouseDrag (const MouseEvent&)
  55117. {
  55118. timerCallback();
  55119. }
  55120. void mouseUp (const MouseEvent&)
  55121. {
  55122. timerCallback();
  55123. }
  55124. void mouseWheelMove (const MouseEvent&, float /*amountX*/, float amountY)
  55125. {
  55126. alterChildYPos (roundToInt (-10.0f * amountY * PopupMenuSettings::scrollZone));
  55127. lastMouse = Point<int> (-1, -1);
  55128. }
  55129. bool keyPressed (const KeyPress& key)
  55130. {
  55131. if (key.isKeyCode (KeyPress::downKey))
  55132. {
  55133. selectNextItem (1);
  55134. }
  55135. else if (key.isKeyCode (KeyPress::upKey))
  55136. {
  55137. selectNextItem (-1);
  55138. }
  55139. else if (key.isKeyCode (KeyPress::leftKey))
  55140. {
  55141. if (owner != 0)
  55142. {
  55143. Component::SafePointer<Window> parentWindow (owner);
  55144. PopupMenu::ItemComponent* currentChildOfParent = parentWindow->currentChild;
  55145. hide (0);
  55146. if (parentWindow != 0)
  55147. parentWindow->setCurrentlyHighlightedChild (currentChildOfParent);
  55148. disableTimerUntilMouseMoves();
  55149. }
  55150. else if (componentAttachedTo != 0)
  55151. {
  55152. componentAttachedTo->keyPressed (key);
  55153. }
  55154. }
  55155. else if (key.isKeyCode (KeyPress::rightKey))
  55156. {
  55157. disableTimerUntilMouseMoves();
  55158. if (showSubMenuFor (currentChild))
  55159. {
  55160. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55161. if (activeSubMenu != 0 && activeSubMenu->isVisible())
  55162. activeSubMenu->selectNextItem (1);
  55163. }
  55164. else if (componentAttachedTo != 0)
  55165. {
  55166. componentAttachedTo->keyPressed (key);
  55167. }
  55168. }
  55169. else if (key.isKeyCode (KeyPress::returnKey))
  55170. {
  55171. triggerCurrentlyHighlightedItem();
  55172. }
  55173. else if (key.isKeyCode (KeyPress::escapeKey))
  55174. {
  55175. dismissMenu (0);
  55176. }
  55177. else
  55178. {
  55179. return false;
  55180. }
  55181. return true;
  55182. }
  55183. void inputAttemptWhenModal()
  55184. {
  55185. Component::SafePointer<Component> deletionChecker (this);
  55186. timerCallback();
  55187. if (deletionChecker != 0 && ! isOverAnyMenu())
  55188. {
  55189. if (componentAttachedTo != 0)
  55190. {
  55191. // we want to dismiss the menu, but if we do it synchronously, then
  55192. // the mouse-click will be allowed to pass through. That's good, except
  55193. // when the user clicks on the button that orginally popped the menu up,
  55194. // as they'll expect the menu to go away, and in fact it'll just
  55195. // come back. So only dismiss synchronously if they're not on the original
  55196. // comp that we're attached to.
  55197. const Point<int> mousePos (componentAttachedTo->getMouseXYRelative());
  55198. if (componentAttachedTo->reallyContains (mousePos.getX(), mousePos.getY(), true))
  55199. {
  55200. postCommandMessage (PopupMenuSettings::dismissCommandId); // dismiss asynchrounously
  55201. return;
  55202. }
  55203. }
  55204. dismissMenu (0);
  55205. }
  55206. }
  55207. void handleCommandMessage (int commandId)
  55208. {
  55209. Component::handleCommandMessage (commandId);
  55210. if (commandId == PopupMenuSettings::dismissCommandId)
  55211. dismissMenu (0);
  55212. }
  55213. void timerCallback()
  55214. {
  55215. if (! isVisible())
  55216. return;
  55217. if (componentAttachedTo != componentAttachedToOriginal)
  55218. {
  55219. dismissMenu (0);
  55220. return;
  55221. }
  55222. Window* currentlyModalWindow = dynamic_cast <Window*> (Component::getCurrentlyModalComponent());
  55223. if (currentlyModalWindow != 0 && ! treeContains (currentlyModalWindow))
  55224. return;
  55225. startTimer (PopupMenuSettings::timerInterval); // do this in case it was called from a mouse
  55226. // move rather than a real timer callback
  55227. const Point<int> globalMousePos (Desktop::getMousePosition());
  55228. const Point<int> localMousePos (globalPositionToRelative (globalMousePos));
  55229. const uint32 now = Time::getMillisecondCounter();
  55230. if (now > timeEnteredCurrentChildComp + 100
  55231. && reallyContains (localMousePos.getX(), localMousePos.getY(), true)
  55232. && currentChild->isValidComponent()
  55233. && (! disableMouseMoves)
  55234. && ! (activeSubMenu != 0 && activeSubMenu->isVisible()))
  55235. {
  55236. showSubMenuFor (currentChild);
  55237. }
  55238. if (globalMousePos != lastMouse || now > lastMouseMoveTime + 350)
  55239. {
  55240. highlightItemUnderMouse (globalMousePos, localMousePos);
  55241. }
  55242. bool overScrollArea = false;
  55243. if (isScrolling()
  55244. && (isOver || (isDown && ((unsigned int) localMousePos.getX()) < (unsigned int) getWidth()))
  55245. && ((isScrollZoneActive (false) && localMousePos.getY() < PopupMenuSettings::scrollZone)
  55246. || (isScrollZoneActive (true) && localMousePos.getY() > getHeight() - PopupMenuSettings::scrollZone)))
  55247. {
  55248. if (now > lastScroll + 20)
  55249. {
  55250. scrollAcceleration = jmin (4.0, scrollAcceleration * 1.04);
  55251. int amount = 0;
  55252. for (int i = 0; i < getNumChildComponents() && amount == 0; ++i)
  55253. amount = ((int) scrollAcceleration) * getChildComponent (i)->getHeight();
  55254. alterChildYPos (localMousePos.getY() < PopupMenuSettings::scrollZone ? -amount : amount);
  55255. lastScroll = now;
  55256. }
  55257. overScrollArea = true;
  55258. lastMouse = Point<int> (-1, -1); // trigger a mouse-move
  55259. }
  55260. else
  55261. {
  55262. scrollAcceleration = 1.0;
  55263. }
  55264. const bool wasDown = isDown;
  55265. bool isOverAny = isOverAnyMenu();
  55266. if (hideOnExit && hasBeenOver && (! isOverAny) && activeSubMenu != 0)
  55267. {
  55268. activeSubMenu->updateMouseOverStatus (globalMousePos);
  55269. isOverAny = isOverAnyMenu();
  55270. }
  55271. if (hideOnExit && hasBeenOver && ! isOverAny)
  55272. {
  55273. hide (0);
  55274. }
  55275. else
  55276. {
  55277. isDown = hasBeenOver
  55278. && (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown()
  55279. || ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown());
  55280. bool anyFocused = Process::isForegroundProcess();
  55281. if (anyFocused && Component::getCurrentlyFocusedComponent() == 0)
  55282. {
  55283. // because no component at all may have focus, our test here will
  55284. // only be triggered when something has focus and then loses it.
  55285. anyFocused = ! hasAnyJuceCompHadFocus;
  55286. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  55287. {
  55288. if (ComponentPeer::getPeer (i)->isFocused())
  55289. {
  55290. anyFocused = true;
  55291. hasAnyJuceCompHadFocus = true;
  55292. break;
  55293. }
  55294. }
  55295. }
  55296. if (! anyFocused)
  55297. {
  55298. if (now > lastFocused + 10)
  55299. {
  55300. wasHiddenBecauseOfAppChange() = true;
  55301. dismissMenu (0);
  55302. return; // may have been deleted by the previous call..
  55303. }
  55304. }
  55305. else if (wasDown && now > menuCreationTime + 250
  55306. && ! (isDown || overScrollArea))
  55307. {
  55308. isOver = reallyContains (localMousePos.getX(), localMousePos.getY(), true);
  55309. if (isOver)
  55310. {
  55311. triggerCurrentlyHighlightedItem();
  55312. }
  55313. else if ((hasBeenOver || ! dismissOnMouseUp) && ! isOverAny)
  55314. {
  55315. dismissMenu (0);
  55316. }
  55317. return; // may have been deleted by the previous calls..
  55318. }
  55319. else
  55320. {
  55321. lastFocused = now;
  55322. }
  55323. }
  55324. }
  55325. static Array<Window*>& getActiveWindows()
  55326. {
  55327. static Array<Window*> activeMenuWindows;
  55328. return activeMenuWindows;
  55329. }
  55330. static bool& wasHiddenBecauseOfAppChange() throw()
  55331. {
  55332. static bool b = false;
  55333. return b;
  55334. }
  55335. juce_UseDebuggingNewOperator
  55336. private:
  55337. Window* owner;
  55338. PopupMenu::ItemComponent* currentChild;
  55339. ScopedPointer <Window> activeSubMenu;
  55340. ApplicationCommandManager** managerOfChosenCommand;
  55341. Component::SafePointer<Component> componentAttachedTo;
  55342. Component* componentAttachedToOriginal;
  55343. Rectangle<int> windowPos;
  55344. Point<int> lastMouse;
  55345. int minimumWidth, maximumNumColumns, standardItemHeight;
  55346. bool isOver, hasBeenOver, isDown, needsToScroll;
  55347. bool dismissOnMouseUp, hideOnExit, disableMouseMoves, hasAnyJuceCompHadFocus;
  55348. int numColumns, contentHeight, childYOffset;
  55349. Array <int> columnWidths;
  55350. uint32 menuCreationTime, lastFocused, lastScroll, lastMouseMoveTime, timeEnteredCurrentChildComp;
  55351. double scrollAcceleration;
  55352. bool overlaps (const Rectangle<int>& r) const
  55353. {
  55354. return r.intersects (getBounds())
  55355. || (owner != 0 && owner->overlaps (r));
  55356. }
  55357. bool isOverAnyMenu() const
  55358. {
  55359. return (owner != 0) ? owner->isOverAnyMenu()
  55360. : isOverChildren();
  55361. }
  55362. bool isOverChildren() const
  55363. {
  55364. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55365. return isVisible()
  55366. && (isOver || (activeSubMenu != 0 && activeSubMenu->isOverChildren()));
  55367. }
  55368. void updateMouseOverStatus (const Point<int>& globalMousePos)
  55369. {
  55370. const Point<int> relPos (globalPositionToRelative (globalMousePos));
  55371. isOver = reallyContains (relPos.getX(), relPos.getY(), true);
  55372. if (activeSubMenu != 0)
  55373. activeSubMenu->updateMouseOverStatus (globalMousePos);
  55374. }
  55375. bool treeContains (const Window* const window) const throw()
  55376. {
  55377. const Window* mw = this;
  55378. while (mw->owner != 0)
  55379. mw = mw->owner;
  55380. while (mw != 0)
  55381. {
  55382. if (mw == window)
  55383. return true;
  55384. mw = mw->activeSubMenu;
  55385. }
  55386. return false;
  55387. }
  55388. void calculateWindowPos (const Rectangle<int>& target, const bool alignToRectangle)
  55389. {
  55390. const Rectangle<int> mon (Desktop::getInstance()
  55391. .getMonitorAreaContaining (target.getCentre(),
  55392. #if JUCE_MAC
  55393. true));
  55394. #else
  55395. false)); // on windows, don't stop the menu overlapping the taskbar
  55396. #endif
  55397. int x, y, widthToUse, heightToUse;
  55398. layoutMenuItems (mon.getWidth() - 24, widthToUse, heightToUse);
  55399. if (alignToRectangle)
  55400. {
  55401. x = target.getX();
  55402. const int spaceUnder = mon.getHeight() - (target.getBottom() - mon.getY());
  55403. const int spaceOver = target.getY() - mon.getY();
  55404. if (heightToUse < spaceUnder - 30 || spaceUnder >= spaceOver)
  55405. y = target.getBottom();
  55406. else
  55407. y = target.getY() - heightToUse;
  55408. }
  55409. else
  55410. {
  55411. bool tendTowardsRight = target.getCentreX() < mon.getCentreX();
  55412. if (owner != 0)
  55413. {
  55414. if (owner->owner != 0)
  55415. {
  55416. const bool ownerGoingRight = (owner->getX() + owner->getWidth() / 2
  55417. > owner->owner->getX() + owner->owner->getWidth() / 2);
  55418. if (ownerGoingRight && target.getRight() + widthToUse < mon.getRight() - 4)
  55419. tendTowardsRight = true;
  55420. else if ((! ownerGoingRight) && target.getX() > widthToUse + 4)
  55421. tendTowardsRight = false;
  55422. }
  55423. else if (target.getRight() + widthToUse < mon.getRight() - 32)
  55424. {
  55425. tendTowardsRight = true;
  55426. }
  55427. }
  55428. const int biggestSpace = jmax (mon.getRight() - target.getRight(),
  55429. target.getX() - mon.getX()) - 32;
  55430. if (biggestSpace < widthToUse)
  55431. {
  55432. layoutMenuItems (biggestSpace + target.getWidth() / 3, widthToUse, heightToUse);
  55433. if (numColumns > 1)
  55434. layoutMenuItems (biggestSpace - 4, widthToUse, heightToUse);
  55435. tendTowardsRight = (mon.getRight() - target.getRight()) >= (target.getX() - mon.getX());
  55436. }
  55437. if (tendTowardsRight)
  55438. x = jmin (mon.getRight() - widthToUse - 4, target.getRight());
  55439. else
  55440. x = jmax (mon.getX() + 4, target.getX() - widthToUse);
  55441. y = target.getY();
  55442. if (target.getCentreY() > mon.getCentreY())
  55443. y = jmax (mon.getY(), target.getBottom() - heightToUse);
  55444. }
  55445. x = jmax (mon.getX() + 1, jmin (mon.getRight() - (widthToUse + 6), x));
  55446. y = jmax (mon.getY() + 1, jmin (mon.getBottom() - (heightToUse + 6), y));
  55447. windowPos.setBounds (x, y, widthToUse, heightToUse);
  55448. // sets this flag if it's big enough to obscure any of its parent menus
  55449. hideOnExit = (owner != 0)
  55450. && owner->windowPos.intersects (windowPos.expanded (-4, -4));
  55451. }
  55452. void layoutMenuItems (const int maxMenuW, int& width, int& height)
  55453. {
  55454. numColumns = 0;
  55455. contentHeight = 0;
  55456. const int maxMenuH = getParentHeight() - 24;
  55457. int totalW;
  55458. do
  55459. {
  55460. ++numColumns;
  55461. totalW = workOutBestSize (maxMenuW);
  55462. if (totalW > maxMenuW)
  55463. {
  55464. numColumns = jmax (1, numColumns - 1);
  55465. totalW = workOutBestSize (maxMenuW); // to update col widths
  55466. break;
  55467. }
  55468. else if (totalW > maxMenuW / 2 || contentHeight < maxMenuH)
  55469. {
  55470. break;
  55471. }
  55472. } while (numColumns < maximumNumColumns);
  55473. const int actualH = jmin (contentHeight, maxMenuH);
  55474. needsToScroll = contentHeight > actualH;
  55475. width = updateYPositions();
  55476. height = actualH + PopupMenuSettings::borderSize * 2;
  55477. }
  55478. int workOutBestSize (const int maxMenuW)
  55479. {
  55480. int totalW = 0;
  55481. contentHeight = 0;
  55482. int childNum = 0;
  55483. for (int col = 0; col < numColumns; ++col)
  55484. {
  55485. int i, colW = 50, colH = 0;
  55486. const int numChildren = jmin (getNumChildComponents() - childNum,
  55487. (getNumChildComponents() + numColumns - 1) / numColumns);
  55488. for (i = numChildren; --i >= 0;)
  55489. {
  55490. colW = jmax (colW, getChildComponent (childNum + i)->getWidth());
  55491. colH += getChildComponent (childNum + i)->getHeight();
  55492. }
  55493. colW = jmin (maxMenuW / jmax (1, numColumns - 2), colW + PopupMenuSettings::borderSize * 2);
  55494. columnWidths.set (col, colW);
  55495. totalW += colW;
  55496. contentHeight = jmax (contentHeight, colH);
  55497. childNum += numChildren;
  55498. }
  55499. if (totalW < minimumWidth)
  55500. {
  55501. totalW = minimumWidth;
  55502. for (int col = 0; col < numColumns; ++col)
  55503. columnWidths.set (0, totalW / numColumns);
  55504. }
  55505. return totalW;
  55506. }
  55507. void ensureItemIsVisible (const int itemId, int wantedY)
  55508. {
  55509. jassert (itemId != 0)
  55510. for (int i = getNumChildComponents(); --i >= 0;)
  55511. {
  55512. PopupMenu::ItemComponent* const m = static_cast <PopupMenu::ItemComponent*> (getChildComponent (i));
  55513. if (m != 0
  55514. && m->itemInfo.itemId == itemId
  55515. && windowPos.getHeight() > PopupMenuSettings::scrollZone * 4)
  55516. {
  55517. const int currentY = m->getY();
  55518. if (wantedY > 0 || currentY < 0 || m->getBottom() > windowPos.getHeight())
  55519. {
  55520. if (wantedY < 0)
  55521. wantedY = jlimit (PopupMenuSettings::scrollZone,
  55522. jmax (PopupMenuSettings::scrollZone,
  55523. windowPos.getHeight() - (PopupMenuSettings::scrollZone + m->getHeight())),
  55524. currentY);
  55525. const Rectangle<int> mon (Desktop::getInstance().getMonitorAreaContaining (windowPos.getPosition(), true));
  55526. int deltaY = wantedY - currentY;
  55527. windowPos.setSize (jmin (windowPos.getWidth(), mon.getWidth()),
  55528. jmin (windowPos.getHeight(), mon.getHeight()));
  55529. const int newY = jlimit (mon.getY(),
  55530. mon.getBottom() - windowPos.getHeight(),
  55531. windowPos.getY() + deltaY);
  55532. deltaY -= newY - windowPos.getY();
  55533. childYOffset -= deltaY;
  55534. windowPos.setPosition (windowPos.getX(), newY);
  55535. updateYPositions();
  55536. }
  55537. break;
  55538. }
  55539. }
  55540. }
  55541. void resizeToBestWindowPos()
  55542. {
  55543. Rectangle<int> r (windowPos);
  55544. if (childYOffset < 0)
  55545. {
  55546. r.setBounds (r.getX(), r.getY() - childYOffset,
  55547. r.getWidth(), r.getHeight() + childYOffset);
  55548. }
  55549. else if (childYOffset > 0)
  55550. {
  55551. const int spaceAtBottom = r.getHeight() - (contentHeight - childYOffset);
  55552. if (spaceAtBottom > 0)
  55553. r.setSize (r.getWidth(), r.getHeight() - spaceAtBottom);
  55554. }
  55555. setBounds (r);
  55556. updateYPositions();
  55557. }
  55558. void alterChildYPos (const int delta)
  55559. {
  55560. if (isScrolling())
  55561. {
  55562. childYOffset += delta;
  55563. if (delta < 0)
  55564. {
  55565. childYOffset = jmax (childYOffset, 0);
  55566. }
  55567. else if (delta > 0)
  55568. {
  55569. childYOffset = jmin (childYOffset,
  55570. contentHeight - windowPos.getHeight() + PopupMenuSettings::borderSize);
  55571. }
  55572. updateYPositions();
  55573. }
  55574. else
  55575. {
  55576. childYOffset = 0;
  55577. }
  55578. resizeToBestWindowPos();
  55579. repaint();
  55580. }
  55581. int updateYPositions()
  55582. {
  55583. int x = 0;
  55584. int childNum = 0;
  55585. for (int col = 0; col < numColumns; ++col)
  55586. {
  55587. const int numChildren = jmin (getNumChildComponents() - childNum,
  55588. (getNumChildComponents() + numColumns - 1) / numColumns);
  55589. const int colW = columnWidths [col];
  55590. int y = PopupMenuSettings::borderSize - (childYOffset + (getY() - windowPos.getY()));
  55591. for (int i = 0; i < numChildren; ++i)
  55592. {
  55593. Component* const c = getChildComponent (childNum + i);
  55594. c->setBounds (x, y, colW, c->getHeight());
  55595. y += c->getHeight();
  55596. }
  55597. x += colW;
  55598. childNum += numChildren;
  55599. }
  55600. return x;
  55601. }
  55602. bool isScrolling() const throw()
  55603. {
  55604. return childYOffset != 0 || needsToScroll;
  55605. }
  55606. void setCurrentlyHighlightedChild (PopupMenu::ItemComponent* const child)
  55607. {
  55608. if (currentChild->isValidComponent())
  55609. currentChild->setHighlighted (false);
  55610. currentChild = child;
  55611. if (currentChild != 0)
  55612. {
  55613. currentChild->setHighlighted (true);
  55614. timeEnteredCurrentChildComp = Time::getApproximateMillisecondCounter();
  55615. }
  55616. }
  55617. bool showSubMenuFor (PopupMenu::ItemComponent* const childComp)
  55618. {
  55619. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55620. activeSubMenu = 0;
  55621. if (childComp->isValidComponent() && childComp->itemInfo.hasActiveSubMenu())
  55622. {
  55623. activeSubMenu = Window::create (*(childComp->itemInfo.subMenu),
  55624. dismissOnMouseUp,
  55625. this,
  55626. childComp->getScreenBounds(),
  55627. 0, maximumNumColumns,
  55628. standardItemHeight,
  55629. false, 0, managerOfChosenCommand,
  55630. componentAttachedTo);
  55631. if (activeSubMenu != 0)
  55632. {
  55633. activeSubMenu->setVisible (true);
  55634. activeSubMenu->enterModalState (false);
  55635. activeSubMenu->toFront (false);
  55636. return true;
  55637. }
  55638. }
  55639. return false;
  55640. }
  55641. void highlightItemUnderMouse (const Point<int>& globalMousePos, const Point<int>& localMousePos)
  55642. {
  55643. isOver = reallyContains (localMousePos.getX(), localMousePos.getY(), true);
  55644. if (isOver)
  55645. hasBeenOver = true;
  55646. if (lastMouse.getDistanceFrom (globalMousePos) > 2)
  55647. {
  55648. lastMouseMoveTime = Time::getApproximateMillisecondCounter();
  55649. if (disableMouseMoves && isOver)
  55650. disableMouseMoves = false;
  55651. }
  55652. if (disableMouseMoves || (activeSubMenu != 0 && activeSubMenu->isOverChildren()))
  55653. return;
  55654. bool isMovingTowardsMenu = false;
  55655. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent())
  55656. if (isOver && (activeSubMenu != 0) && globalMousePos != lastMouse)
  55657. {
  55658. // try to intelligently guess whether the user is moving the mouse towards a currently-open
  55659. // submenu. To do this, look at whether the mouse stays inside a triangular region that
  55660. // extends from the last mouse pos to the submenu's rectangle..
  55661. float subX = (float) activeSubMenu->getScreenX();
  55662. if (activeSubMenu->getX() > getX())
  55663. {
  55664. lastMouse -= Point<int> (2, 0); // to enlarge the triangle a bit, in case the mouse only moves a couple of pixels
  55665. }
  55666. else
  55667. {
  55668. lastMouse += Point<int> (2, 0);
  55669. subX += activeSubMenu->getWidth();
  55670. }
  55671. Path areaTowardsSubMenu;
  55672. areaTowardsSubMenu.addTriangle ((float) lastMouse.getX(),
  55673. (float) lastMouse.getY(),
  55674. subX,
  55675. (float) activeSubMenu->getScreenY(),
  55676. subX,
  55677. (float) (activeSubMenu->getScreenY() + activeSubMenu->getHeight()));
  55678. isMovingTowardsMenu = areaTowardsSubMenu.contains ((float) globalMousePos.getX(), (float) globalMousePos.getY());
  55679. }
  55680. lastMouse = globalMousePos;
  55681. if (! isMovingTowardsMenu)
  55682. {
  55683. Component* c = getComponentAt (localMousePos.getX(), localMousePos.getY());
  55684. if (c == this)
  55685. c = 0;
  55686. PopupMenu::ItemComponent* mic = dynamic_cast <PopupMenu::ItemComponent*> (c);
  55687. if (mic == 0 && c != 0)
  55688. mic = c->findParentComponentOfClass ((PopupMenu::ItemComponent*) 0);
  55689. if (mic != currentChild
  55690. && (isOver || (activeSubMenu == 0) || ! activeSubMenu->isVisible()))
  55691. {
  55692. if (isOver && (c != 0) && (activeSubMenu != 0))
  55693. {
  55694. activeSubMenu->hide (0);
  55695. }
  55696. if (! isOver)
  55697. mic = 0;
  55698. setCurrentlyHighlightedChild (mic);
  55699. }
  55700. }
  55701. }
  55702. void triggerCurrentlyHighlightedItem()
  55703. {
  55704. if (currentChild->isValidComponent()
  55705. && currentChild->itemInfo.canBeTriggered()
  55706. && (currentChild->itemInfo.customComp == 0
  55707. || currentChild->itemInfo.customComp->isTriggeredAutomatically))
  55708. {
  55709. dismissMenu (&currentChild->itemInfo);
  55710. }
  55711. }
  55712. void selectNextItem (const int delta)
  55713. {
  55714. disableTimerUntilMouseMoves();
  55715. PopupMenu::ItemComponent* mic = 0;
  55716. bool wasLastOne = (currentChild == 0);
  55717. const int numItems = getNumChildComponents();
  55718. for (int i = 0; i < numItems + 1; ++i)
  55719. {
  55720. int index = (delta > 0) ? i : (numItems - 1 - i);
  55721. index = (index + numItems) % numItems;
  55722. mic = dynamic_cast <PopupMenu::ItemComponent*> (getChildComponent (index));
  55723. if (mic != 0 && (mic->itemInfo.canBeTriggered() || mic->itemInfo.hasActiveSubMenu())
  55724. && wasLastOne)
  55725. break;
  55726. if (mic == currentChild)
  55727. wasLastOne = true;
  55728. }
  55729. setCurrentlyHighlightedChild (mic);
  55730. }
  55731. void disableTimerUntilMouseMoves()
  55732. {
  55733. disableMouseMoves = true;
  55734. if (owner != 0)
  55735. owner->disableTimerUntilMouseMoves();
  55736. }
  55737. Window (const Window&);
  55738. Window& operator= (const Window&);
  55739. };
  55740. PopupMenu::PopupMenu()
  55741. : lookAndFeel (0),
  55742. separatorPending (false)
  55743. {
  55744. }
  55745. PopupMenu::PopupMenu (const PopupMenu& other)
  55746. : lookAndFeel (other.lookAndFeel),
  55747. separatorPending (false)
  55748. {
  55749. items.addCopiesOf (other.items);
  55750. }
  55751. PopupMenu& PopupMenu::operator= (const PopupMenu& other)
  55752. {
  55753. if (this != &other)
  55754. {
  55755. lookAndFeel = other.lookAndFeel;
  55756. clear();
  55757. items.addCopiesOf (other.items);
  55758. }
  55759. return *this;
  55760. }
  55761. PopupMenu::~PopupMenu()
  55762. {
  55763. clear();
  55764. }
  55765. void PopupMenu::clear()
  55766. {
  55767. items.clear();
  55768. separatorPending = false;
  55769. }
  55770. void PopupMenu::addSeparatorIfPending()
  55771. {
  55772. if (separatorPending)
  55773. {
  55774. separatorPending = false;
  55775. if (items.size() > 0)
  55776. items.add (new Item());
  55777. }
  55778. }
  55779. void PopupMenu::addItem (const int itemResultId,
  55780. const String& itemText,
  55781. const bool isActive,
  55782. const bool isTicked,
  55783. const Image& iconToUse)
  55784. {
  55785. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  55786. // didn't pick anything, so you shouldn't use it as the id
  55787. // for an item..
  55788. addSeparatorIfPending();
  55789. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  55790. Colours::black, false, 0, 0, 0));
  55791. }
  55792. void PopupMenu::addCommandItem (ApplicationCommandManager* commandManager,
  55793. const int commandID,
  55794. const String& displayName)
  55795. {
  55796. jassert (commandManager != 0 && commandID != 0);
  55797. const ApplicationCommandInfo* const registeredInfo = commandManager->getCommandForID (commandID);
  55798. if (registeredInfo != 0)
  55799. {
  55800. ApplicationCommandInfo info (*registeredInfo);
  55801. ApplicationCommandTarget* const target = commandManager->getTargetForCommand (commandID, info);
  55802. addSeparatorIfPending();
  55803. items.add (new Item (commandID,
  55804. displayName.isNotEmpty() ? displayName
  55805. : info.shortName,
  55806. target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0,
  55807. (info.flags & ApplicationCommandInfo::isTicked) != 0,
  55808. Image(),
  55809. Colours::black,
  55810. false,
  55811. 0, 0,
  55812. commandManager));
  55813. }
  55814. }
  55815. void PopupMenu::addColouredItem (const int itemResultId,
  55816. const String& itemText,
  55817. const Colour& itemTextColour,
  55818. const bool isActive,
  55819. const bool isTicked,
  55820. const Image& iconToUse)
  55821. {
  55822. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  55823. // didn't pick anything, so you shouldn't use it as the id
  55824. // for an item..
  55825. addSeparatorIfPending();
  55826. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  55827. itemTextColour, true, 0, 0, 0));
  55828. }
  55829. void PopupMenu::addCustomItem (const int itemResultId,
  55830. PopupMenuCustomComponent* const customComponent)
  55831. {
  55832. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  55833. // didn't pick anything, so you shouldn't use it as the id
  55834. // for an item..
  55835. addSeparatorIfPending();
  55836. items.add (new Item (itemResultId, String::empty, true, false, Image(),
  55837. Colours::black, false, customComponent, 0, 0));
  55838. }
  55839. class NormalComponentWrapper : public PopupMenuCustomComponent
  55840. {
  55841. public:
  55842. NormalComponentWrapper (Component* const comp,
  55843. const int w, const int h,
  55844. const bool triggerMenuItemAutomaticallyWhenClicked)
  55845. : PopupMenuCustomComponent (triggerMenuItemAutomaticallyWhenClicked),
  55846. width (w),
  55847. height (h)
  55848. {
  55849. addAndMakeVisible (comp);
  55850. }
  55851. ~NormalComponentWrapper() {}
  55852. void getIdealSize (int& idealWidth, int& idealHeight)
  55853. {
  55854. idealWidth = width;
  55855. idealHeight = height;
  55856. }
  55857. void resized()
  55858. {
  55859. if (getChildComponent(0) != 0)
  55860. getChildComponent(0)->setBounds (getLocalBounds());
  55861. }
  55862. juce_UseDebuggingNewOperator
  55863. private:
  55864. const int width, height;
  55865. NormalComponentWrapper (const NormalComponentWrapper&);
  55866. NormalComponentWrapper& operator= (const NormalComponentWrapper&);
  55867. };
  55868. void PopupMenu::addCustomItem (const int itemResultId,
  55869. Component* customComponent,
  55870. int idealWidth, int idealHeight,
  55871. const bool triggerMenuItemAutomaticallyWhenClicked)
  55872. {
  55873. addCustomItem (itemResultId,
  55874. new NormalComponentWrapper (customComponent,
  55875. idealWidth, idealHeight,
  55876. triggerMenuItemAutomaticallyWhenClicked));
  55877. }
  55878. void PopupMenu::addSubMenu (const String& subMenuName,
  55879. const PopupMenu& subMenu,
  55880. const bool isActive,
  55881. const Image& iconToUse,
  55882. const bool isTicked)
  55883. {
  55884. addSeparatorIfPending();
  55885. items.add (new Item (0, subMenuName, isActive && (subMenu.getNumItems() > 0), isTicked,
  55886. iconToUse, Colours::black, false, 0, &subMenu, 0));
  55887. }
  55888. void PopupMenu::addSeparator()
  55889. {
  55890. separatorPending = true;
  55891. }
  55892. class HeaderItemComponent : public PopupMenuCustomComponent
  55893. {
  55894. public:
  55895. HeaderItemComponent (const String& name)
  55896. : PopupMenuCustomComponent (false)
  55897. {
  55898. setName (name);
  55899. }
  55900. ~HeaderItemComponent()
  55901. {
  55902. }
  55903. void paint (Graphics& g)
  55904. {
  55905. Font f (getLookAndFeel().getPopupMenuFont());
  55906. f.setBold (true);
  55907. g.setFont (f);
  55908. g.setColour (findColour (PopupMenu::headerTextColourId));
  55909. g.drawFittedText (getName(),
  55910. 12, 0, getWidth() - 16, proportionOfHeight (0.8f),
  55911. Justification::bottomLeft, 1);
  55912. }
  55913. void getIdealSize (int& idealWidth,
  55914. int& idealHeight)
  55915. {
  55916. getLookAndFeel().getIdealPopupMenuItemSize (getName(), false, -1, idealWidth, idealHeight);
  55917. idealHeight += idealHeight / 2;
  55918. idealWidth += idealWidth / 4;
  55919. }
  55920. juce_UseDebuggingNewOperator
  55921. };
  55922. void PopupMenu::addSectionHeader (const String& title)
  55923. {
  55924. addCustomItem (0X4734a34f, new HeaderItemComponent (title));
  55925. }
  55926. // This invokes any command manager commands and deletes the menu window when it is dismissed
  55927. class PopupMenuCompletionCallback : public ModalComponentManager::Callback
  55928. {
  55929. public:
  55930. PopupMenuCompletionCallback()
  55931. : managerOfChosenCommand (0)
  55932. {
  55933. }
  55934. ~PopupMenuCompletionCallback() {}
  55935. void modalStateFinished (int result)
  55936. {
  55937. if (managerOfChosenCommand != 0 && result != 0)
  55938. {
  55939. ApplicationCommandTarget::InvocationInfo info (result);
  55940. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  55941. managerOfChosenCommand->invoke (info, true);
  55942. }
  55943. }
  55944. ApplicationCommandManager* managerOfChosenCommand;
  55945. ScopedPointer<Component> component;
  55946. private:
  55947. PopupMenuCompletionCallback (const PopupMenuCompletionCallback&);
  55948. PopupMenuCompletionCallback& operator= (const PopupMenuCompletionCallback&);
  55949. };
  55950. int PopupMenu::showMenu (const Rectangle<int>& target,
  55951. const int itemIdThatMustBeVisible,
  55952. const int minimumWidth,
  55953. const int maximumNumColumns,
  55954. const int standardItemHeight,
  55955. const bool alignToRectangle,
  55956. Component* const componentAttachedTo,
  55957. ModalComponentManager::Callback* userCallback)
  55958. {
  55959. ScopedPointer<ModalComponentManager::Callback> userCallbackDeleter (userCallback);
  55960. Component::SafePointer<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  55961. Component::SafePointer<Component> prevTopLevel ((prevFocused != 0) ? prevFocused->getTopLevelComponent() : 0);
  55962. Window::wasHiddenBecauseOfAppChange() = false;
  55963. PopupMenuCompletionCallback* callback = new PopupMenuCompletionCallback();
  55964. ScopedPointer<PopupMenuCompletionCallback> callbackDeleter (callback);
  55965. callback->component = Window::create (*this, ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown(),
  55966. 0, target, minimumWidth, maximumNumColumns > 0 ? maximumNumColumns : 7,
  55967. standardItemHeight, alignToRectangle, itemIdThatMustBeVisible,
  55968. &callback->managerOfChosenCommand, componentAttachedTo);
  55969. if (callback->component == 0)
  55970. return 0;
  55971. callbackDeleter.release();
  55972. callback->component->enterModalState (false, userCallbackDeleter.release());
  55973. callback->component->toFront (false); // need to do this after making it modal, or it could
  55974. // be stuck behind other comps that are already modal..
  55975. ModalComponentManager::getInstance()->attachCallback (callback->component, callback);
  55976. if (userCallback != 0)
  55977. return 0;
  55978. const int result = callback->component->runModalLoop();
  55979. if (! Window::wasHiddenBecauseOfAppChange())
  55980. {
  55981. if (prevTopLevel != 0)
  55982. prevTopLevel->toFront (true);
  55983. if (prevFocused != 0)
  55984. prevFocused->grabKeyboardFocus();
  55985. }
  55986. return result;
  55987. }
  55988. int PopupMenu::show (const int itemIdThatMustBeVisible,
  55989. const int minimumWidth,
  55990. const int maximumNumColumns,
  55991. const int standardItemHeight,
  55992. ModalComponentManager::Callback* callback)
  55993. {
  55994. const Point<int> mousePos (Desktop::getMousePosition());
  55995. return showAt (mousePos.getX(), mousePos.getY(),
  55996. itemIdThatMustBeVisible,
  55997. minimumWidth,
  55998. maximumNumColumns,
  55999. standardItemHeight,
  56000. callback);
  56001. }
  56002. int PopupMenu::showAt (const int screenX,
  56003. const int screenY,
  56004. const int itemIdThatMustBeVisible,
  56005. const int minimumWidth,
  56006. const int maximumNumColumns,
  56007. const int standardItemHeight,
  56008. ModalComponentManager::Callback* callback)
  56009. {
  56010. return showMenu (Rectangle<int> (screenX, screenY, 1, 1),
  56011. itemIdThatMustBeVisible,
  56012. minimumWidth, maximumNumColumns,
  56013. standardItemHeight,
  56014. false, 0, callback);
  56015. }
  56016. int PopupMenu::showAt (Component* componentToAttachTo,
  56017. const int itemIdThatMustBeVisible,
  56018. const int minimumWidth,
  56019. const int maximumNumColumns,
  56020. const int standardItemHeight,
  56021. ModalComponentManager::Callback* callback)
  56022. {
  56023. if (componentToAttachTo != 0)
  56024. {
  56025. return showMenu (componentToAttachTo->getScreenBounds(),
  56026. itemIdThatMustBeVisible,
  56027. minimumWidth,
  56028. maximumNumColumns,
  56029. standardItemHeight,
  56030. true, componentToAttachTo, callback);
  56031. }
  56032. else
  56033. {
  56034. return show (itemIdThatMustBeVisible,
  56035. minimumWidth,
  56036. maximumNumColumns,
  56037. standardItemHeight,
  56038. callback);
  56039. }
  56040. }
  56041. void JUCE_CALLTYPE PopupMenu::dismissAllActiveMenus()
  56042. {
  56043. for (int i = Window::getActiveWindows().size(); --i >= 0;)
  56044. {
  56045. Window* const pmw = Window::getActiveWindows()[i];
  56046. if (pmw != 0)
  56047. pmw->dismissMenu (0);
  56048. }
  56049. }
  56050. int PopupMenu::getNumItems() const throw()
  56051. {
  56052. int num = 0;
  56053. for (int i = items.size(); --i >= 0;)
  56054. if (! (items.getUnchecked(i))->isSeparator)
  56055. ++num;
  56056. return num;
  56057. }
  56058. bool PopupMenu::containsCommandItem (const int commandID) const
  56059. {
  56060. for (int i = items.size(); --i >= 0;)
  56061. {
  56062. const Item* mi = items.getUnchecked (i);
  56063. if ((mi->itemId == commandID && mi->commandManager != 0)
  56064. || (mi->subMenu != 0 && mi->subMenu->containsCommandItem (commandID)))
  56065. {
  56066. return true;
  56067. }
  56068. }
  56069. return false;
  56070. }
  56071. bool PopupMenu::containsAnyActiveItems() const throw()
  56072. {
  56073. for (int i = items.size(); --i >= 0;)
  56074. {
  56075. const Item* const mi = items.getUnchecked (i);
  56076. if (mi->subMenu != 0)
  56077. {
  56078. if (mi->subMenu->containsAnyActiveItems())
  56079. return true;
  56080. }
  56081. else if (mi->active)
  56082. {
  56083. return true;
  56084. }
  56085. }
  56086. return false;
  56087. }
  56088. void PopupMenu::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  56089. {
  56090. lookAndFeel = newLookAndFeel;
  56091. }
  56092. PopupMenuCustomComponent::PopupMenuCustomComponent (const bool isTriggeredAutomatically_)
  56093. : isHighlighted (false),
  56094. isTriggeredAutomatically (isTriggeredAutomatically_)
  56095. {
  56096. }
  56097. PopupMenuCustomComponent::~PopupMenuCustomComponent()
  56098. {
  56099. }
  56100. void PopupMenuCustomComponent::triggerMenuItem()
  56101. {
  56102. PopupMenu::ItemComponent* const mic = dynamic_cast <PopupMenu::ItemComponent*> (getParentComponent());
  56103. if (mic != 0)
  56104. {
  56105. PopupMenu::Window* const pmw = dynamic_cast <PopupMenu::Window*> (mic->getParentComponent());
  56106. if (pmw != 0)
  56107. {
  56108. pmw->dismissMenu (&mic->itemInfo);
  56109. }
  56110. else
  56111. {
  56112. // something must have gone wrong with the component hierarchy if this happens..
  56113. jassertfalse;
  56114. }
  56115. }
  56116. else
  56117. {
  56118. // why isn't this component inside a menu? Not much point triggering the item if
  56119. // there's no menu.
  56120. jassertfalse;
  56121. }
  56122. }
  56123. PopupMenu::MenuItemIterator::MenuItemIterator (const PopupMenu& menu_)
  56124. : subMenu (0),
  56125. itemId (0),
  56126. isSeparator (false),
  56127. isTicked (false),
  56128. isEnabled (false),
  56129. isCustomComponent (false),
  56130. isSectionHeader (false),
  56131. customColour (0),
  56132. customImage (0),
  56133. menu (menu_),
  56134. index (0)
  56135. {
  56136. }
  56137. PopupMenu::MenuItemIterator::~MenuItemIterator()
  56138. {
  56139. }
  56140. bool PopupMenu::MenuItemIterator::next()
  56141. {
  56142. if (index >= menu.items.size())
  56143. return false;
  56144. const Item* const item = menu.items.getUnchecked (index);
  56145. ++index;
  56146. itemName = item->customComp != 0 ? item->customComp->getName() : item->text;
  56147. subMenu = item->subMenu;
  56148. itemId = item->itemId;
  56149. isSeparator = item->isSeparator;
  56150. isTicked = item->isTicked;
  56151. isEnabled = item->active;
  56152. isSectionHeader = dynamic_cast <HeaderItemComponent*> ((PopupMenuCustomComponent*) item->customComp) != 0;
  56153. isCustomComponent = (! isSectionHeader) && item->customComp != 0;
  56154. customColour = item->usesColour ? &(item->textColour) : 0;
  56155. customImage = item->image;
  56156. commandManager = item->commandManager;
  56157. return true;
  56158. }
  56159. END_JUCE_NAMESPACE
  56160. /*** End of inlined file: juce_PopupMenu.cpp ***/
  56161. /*** Start of inlined file: juce_ComponentDragger.cpp ***/
  56162. BEGIN_JUCE_NAMESPACE
  56163. ComponentDragger::ComponentDragger()
  56164. : constrainer (0)
  56165. {
  56166. }
  56167. ComponentDragger::~ComponentDragger()
  56168. {
  56169. }
  56170. void ComponentDragger::startDraggingComponent (Component* const componentToDrag,
  56171. ComponentBoundsConstrainer* const constrainer_)
  56172. {
  56173. jassert (componentToDrag->isValidComponent());
  56174. if (componentToDrag != 0)
  56175. {
  56176. constrainer = constrainer_;
  56177. originalPos = componentToDrag->relativePositionToGlobal (Point<int>());
  56178. }
  56179. }
  56180. void ComponentDragger::dragComponent (Component* const componentToDrag, const MouseEvent& e)
  56181. {
  56182. jassert (componentToDrag->isValidComponent());
  56183. jassert (e.mods.isAnyMouseButtonDown()); // (the event has to be a drag event..)
  56184. if (componentToDrag != 0)
  56185. {
  56186. Rectangle<int> bounds (componentToDrag->getBounds().withPosition (originalPos));
  56187. const Component* const parentComp = componentToDrag->getParentComponent();
  56188. if (parentComp != 0)
  56189. bounds.setPosition (parentComp->globalPositionToRelative (originalPos));
  56190. bounds.setPosition (bounds.getPosition() + e.getOffsetFromDragStart());
  56191. if (constrainer != 0)
  56192. constrainer->setBoundsForComponent (componentToDrag, bounds, false, false, false, false);
  56193. else
  56194. componentToDrag->setBounds (bounds);
  56195. }
  56196. }
  56197. END_JUCE_NAMESPACE
  56198. /*** End of inlined file: juce_ComponentDragger.cpp ***/
  56199. /*** Start of inlined file: juce_DragAndDropContainer.cpp ***/
  56200. BEGIN_JUCE_NAMESPACE
  56201. bool juce_performDragDropFiles (const StringArray& files, const bool copyFiles, bool& shouldStop);
  56202. bool juce_performDragDropText (const String& text, bool& shouldStop);
  56203. class DragImageComponent : public Component,
  56204. public Timer
  56205. {
  56206. public:
  56207. DragImageComponent (const Image& im,
  56208. const String& desc,
  56209. Component* const sourceComponent,
  56210. Component* const mouseDragSource_,
  56211. DragAndDropContainer* const o,
  56212. const Point<int>& imageOffset_)
  56213. : image (im),
  56214. source (sourceComponent),
  56215. mouseDragSource (mouseDragSource_),
  56216. owner (o),
  56217. dragDesc (desc),
  56218. imageOffset (imageOffset_),
  56219. hasCheckedForExternalDrag (false),
  56220. drawImage (true)
  56221. {
  56222. setSize (im.getWidth(), im.getHeight());
  56223. if (mouseDragSource == 0)
  56224. mouseDragSource = source;
  56225. mouseDragSource->addMouseListener (this, false);
  56226. startTimer (200);
  56227. setInterceptsMouseClicks (false, false);
  56228. setAlwaysOnTop (true);
  56229. }
  56230. ~DragImageComponent()
  56231. {
  56232. if (owner->dragImageComponent == this)
  56233. owner->dragImageComponent.release();
  56234. if (mouseDragSource != 0)
  56235. {
  56236. mouseDragSource->removeMouseListener (this);
  56237. if (getCurrentlyOver() != 0 && getCurrentlyOver()->isInterestedInDragSource (dragDesc, source))
  56238. getCurrentlyOver()->itemDragExit (dragDesc, source);
  56239. }
  56240. }
  56241. void paint (Graphics& g)
  56242. {
  56243. if (isOpaque())
  56244. g.fillAll (Colours::white);
  56245. if (drawImage)
  56246. {
  56247. g.setOpacity (1.0f);
  56248. g.drawImageAt (image, 0, 0);
  56249. }
  56250. }
  56251. DragAndDropTarget* findTarget (const Point<int>& screenPos, Point<int>& relativePos)
  56252. {
  56253. Component* hit = getParentComponent();
  56254. if (hit == 0)
  56255. {
  56256. hit = Desktop::getInstance().findComponentAt (screenPos);
  56257. }
  56258. else
  56259. {
  56260. const Point<int> relPos (hit->globalPositionToRelative (screenPos));
  56261. hit = hit->getComponentAt (relPos.getX(), relPos.getY());
  56262. }
  56263. // (note: use a local copy of the dragDesc member in case the callback runs
  56264. // a modal loop and deletes this object before the method completes)
  56265. const String dragDescLocal (dragDesc);
  56266. while (hit != 0)
  56267. {
  56268. DragAndDropTarget* const ddt = dynamic_cast <DragAndDropTarget*> (hit);
  56269. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  56270. {
  56271. relativePos = hit->globalPositionToRelative (screenPos);
  56272. return ddt;
  56273. }
  56274. hit = hit->getParentComponent();
  56275. }
  56276. return 0;
  56277. }
  56278. void mouseUp (const MouseEvent& e)
  56279. {
  56280. if (e.originalComponent != this)
  56281. {
  56282. if (mouseDragSource != 0)
  56283. mouseDragSource->removeMouseListener (this);
  56284. bool dropAccepted = false;
  56285. DragAndDropTarget* ddt = 0;
  56286. Point<int> relPos;
  56287. if (isVisible())
  56288. {
  56289. setVisible (false);
  56290. ddt = findTarget (e.getScreenPosition(), relPos);
  56291. // fade this component and remove it - it'll be deleted later by the timer callback
  56292. dropAccepted = ddt != 0;
  56293. setVisible (true);
  56294. if (dropAccepted || source == 0)
  56295. {
  56296. fadeOutComponent (120);
  56297. }
  56298. else
  56299. {
  56300. const Point<int> target (source->relativePositionToGlobal (Point<int> (source->getWidth() / 2,
  56301. source->getHeight() / 2)));
  56302. const Point<int> ourCentre (relativePositionToGlobal (Point<int> (getWidth() / 2,
  56303. getHeight() / 2)));
  56304. fadeOutComponent (120,
  56305. target.getX() - ourCentre.getX(),
  56306. target.getY() - ourCentre.getY());
  56307. }
  56308. }
  56309. if (getParentComponent() != 0)
  56310. getParentComponent()->removeChildComponent (this);
  56311. if (dropAccepted && ddt != 0)
  56312. {
  56313. // (note: use a local copy of the dragDesc member in case the callback runs
  56314. // a modal loop and deletes this object before the method completes)
  56315. const String dragDescLocal (dragDesc);
  56316. currentlyOverComp = 0;
  56317. ddt->itemDropped (dragDescLocal, source, relPos.getX(), relPos.getY());
  56318. }
  56319. // careful - this object could now be deleted..
  56320. }
  56321. }
  56322. void updateLocation (const bool canDoExternalDrag, const Point<int>& screenPos)
  56323. {
  56324. // (note: use a local copy of the dragDesc member in case the callback runs
  56325. // a modal loop and deletes this object before it returns)
  56326. const String dragDescLocal (dragDesc);
  56327. Point<int> newPos (screenPos + imageOffset);
  56328. if (getParentComponent() != 0)
  56329. newPos = getParentComponent()->globalPositionToRelative (newPos);
  56330. //if (newX != getX() || newY != getY())
  56331. {
  56332. setTopLeftPosition (newPos.getX(), newPos.getY());
  56333. Point<int> relPos;
  56334. DragAndDropTarget* const ddt = findTarget (screenPos, relPos);
  56335. Component* ddtComp = dynamic_cast <Component*> (ddt);
  56336. drawImage = (ddt == 0) || ddt->shouldDrawDragImageWhenOver();
  56337. if (ddtComp != currentlyOverComp)
  56338. {
  56339. if (currentlyOverComp != 0 && source != 0
  56340. && getCurrentlyOver()->isInterestedInDragSource (dragDescLocal, source))
  56341. {
  56342. getCurrentlyOver()->itemDragExit (dragDescLocal, source);
  56343. }
  56344. currentlyOverComp = ddtComp;
  56345. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  56346. ddt->itemDragEnter (dragDescLocal, source, relPos.getX(), relPos.getY());
  56347. }
  56348. DragAndDropTarget* target = getCurrentlyOver();
  56349. if (target != 0 && target->isInterestedInDragSource (dragDescLocal, source))
  56350. target->itemDragMove (dragDescLocal, source, relPos.getX(), relPos.getY());
  56351. if (getCurrentlyOver() == 0 && canDoExternalDrag && ! hasCheckedForExternalDrag)
  56352. {
  56353. if (Desktop::getInstance().findComponentAt (screenPos) == 0)
  56354. {
  56355. hasCheckedForExternalDrag = true;
  56356. StringArray files;
  56357. bool canMoveFiles = false;
  56358. if (owner->shouldDropFilesWhenDraggedExternally (dragDescLocal, source, files, canMoveFiles)
  56359. && files.size() > 0)
  56360. {
  56361. Component::SafePointer<Component> cdw (this);
  56362. setVisible (false);
  56363. if (ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  56364. DragAndDropContainer::performExternalDragDropOfFiles (files, canMoveFiles);
  56365. if (cdw != 0)
  56366. delete this;
  56367. return;
  56368. }
  56369. }
  56370. }
  56371. }
  56372. }
  56373. void mouseDrag (const MouseEvent& e)
  56374. {
  56375. if (e.originalComponent != this)
  56376. updateLocation (true, e.getScreenPosition());
  56377. }
  56378. void timerCallback()
  56379. {
  56380. if (source == 0)
  56381. {
  56382. delete this;
  56383. }
  56384. else if (! isMouseButtonDownAnywhere())
  56385. {
  56386. if (mouseDragSource != 0)
  56387. mouseDragSource->removeMouseListener (this);
  56388. delete this;
  56389. }
  56390. }
  56391. private:
  56392. Image image;
  56393. Component::SafePointer<Component> source;
  56394. Component::SafePointer<Component> mouseDragSource;
  56395. DragAndDropContainer* const owner;
  56396. Component::SafePointer<Component> currentlyOverComp;
  56397. DragAndDropTarget* getCurrentlyOver()
  56398. {
  56399. return dynamic_cast <DragAndDropTarget*> (static_cast <Component*> (currentlyOverComp));
  56400. }
  56401. String dragDesc;
  56402. const Point<int> imageOffset;
  56403. bool hasCheckedForExternalDrag, drawImage;
  56404. DragImageComponent (const DragImageComponent&);
  56405. DragImageComponent& operator= (const DragImageComponent&);
  56406. };
  56407. DragAndDropContainer::DragAndDropContainer()
  56408. {
  56409. }
  56410. DragAndDropContainer::~DragAndDropContainer()
  56411. {
  56412. dragImageComponent = 0;
  56413. }
  56414. void DragAndDropContainer::startDragging (const String& sourceDescription,
  56415. Component* sourceComponent,
  56416. const Image& dragImage_,
  56417. const bool allowDraggingToExternalWindows,
  56418. const Point<int>* imageOffsetFromMouse)
  56419. {
  56420. Image dragImage (dragImage_);
  56421. if (dragImageComponent == 0)
  56422. {
  56423. Component* const thisComp = dynamic_cast <Component*> (this);
  56424. if (thisComp == 0)
  56425. {
  56426. jassertfalse; // Your DragAndDropContainer needs to be a Component!
  56427. return;
  56428. }
  56429. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource (0);
  56430. if (draggingSource == 0 || ! draggingSource->isDragging())
  56431. {
  56432. jassertfalse; // You must call startDragging() from within a mouseDown or mouseDrag callback!
  56433. return;
  56434. }
  56435. const Point<int> lastMouseDown (Desktop::getLastMouseDownPosition());
  56436. Point<int> imageOffset;
  56437. if (dragImage.isNull())
  56438. {
  56439. dragImage = sourceComponent->createComponentSnapshot (sourceComponent->getLocalBounds())
  56440. .convertedToFormat (Image::ARGB);
  56441. dragImage.multiplyAllAlphas (0.6f);
  56442. const int lo = 150;
  56443. const int hi = 400;
  56444. Point<int> relPos (sourceComponent->globalPositionToRelative (lastMouseDown));
  56445. Point<int> clipped (dragImage.getBounds().getConstrainedPoint (relPos));
  56446. for (int y = dragImage.getHeight(); --y >= 0;)
  56447. {
  56448. const double dy = (y - clipped.getY()) * (y - clipped.getY());
  56449. for (int x = dragImage.getWidth(); --x >= 0;)
  56450. {
  56451. const int dx = x - clipped.getX();
  56452. const int distance = roundToInt (std::sqrt (dx * dx + dy));
  56453. if (distance > lo)
  56454. {
  56455. const float alpha = (distance > hi) ? 0
  56456. : (hi - distance) / (float) (hi - lo)
  56457. + Random::getSystemRandom().nextFloat() * 0.008f;
  56458. dragImage.multiplyAlphaAt (x, y, alpha);
  56459. }
  56460. }
  56461. }
  56462. imageOffset = -clipped;
  56463. }
  56464. else
  56465. {
  56466. if (imageOffsetFromMouse == 0)
  56467. imageOffset = -dragImage.getBounds().getCentre();
  56468. else
  56469. imageOffset = -(dragImage.getBounds().getConstrainedPoint (-*imageOffsetFromMouse));
  56470. }
  56471. dragImageComponent = new DragImageComponent (dragImage, sourceDescription, sourceComponent,
  56472. draggingSource->getComponentUnderMouse(), this, imageOffset);
  56473. currentDragDesc = sourceDescription;
  56474. if (allowDraggingToExternalWindows)
  56475. {
  56476. if (! Desktop::canUseSemiTransparentWindows())
  56477. dragImageComponent->setOpaque (true);
  56478. dragImageComponent->addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  56479. | ComponentPeer::windowIsTemporary
  56480. | ComponentPeer::windowIgnoresKeyPresses);
  56481. }
  56482. else
  56483. thisComp->addChildComponent (dragImageComponent);
  56484. static_cast <DragImageComponent*> (static_cast <Component*> (dragImageComponent))->updateLocation (false, lastMouseDown);
  56485. dragImageComponent->setVisible (true);
  56486. }
  56487. }
  56488. bool DragAndDropContainer::isDragAndDropActive() const
  56489. {
  56490. return dragImageComponent != 0;
  56491. }
  56492. const String DragAndDropContainer::getCurrentDragDescription() const
  56493. {
  56494. return (dragImageComponent != 0) ? currentDragDesc
  56495. : String::empty;
  56496. }
  56497. DragAndDropContainer* DragAndDropContainer::findParentDragContainerFor (Component* c)
  56498. {
  56499. return c == 0 ? 0 : c->findParentComponentOfClass ((DragAndDropContainer*) 0);
  56500. }
  56501. bool DragAndDropContainer::shouldDropFilesWhenDraggedExternally (const String&, Component*, StringArray&, bool&)
  56502. {
  56503. return false;
  56504. }
  56505. void DragAndDropTarget::itemDragEnter (const String&, Component*, int, int)
  56506. {
  56507. }
  56508. void DragAndDropTarget::itemDragMove (const String&, Component*, int, int)
  56509. {
  56510. }
  56511. void DragAndDropTarget::itemDragExit (const String&, Component*)
  56512. {
  56513. }
  56514. bool DragAndDropTarget::shouldDrawDragImageWhenOver()
  56515. {
  56516. return true;
  56517. }
  56518. void FileDragAndDropTarget::fileDragEnter (const StringArray&, int, int)
  56519. {
  56520. }
  56521. void FileDragAndDropTarget::fileDragMove (const StringArray&, int, int)
  56522. {
  56523. }
  56524. void FileDragAndDropTarget::fileDragExit (const StringArray&)
  56525. {
  56526. }
  56527. END_JUCE_NAMESPACE
  56528. /*** End of inlined file: juce_DragAndDropContainer.cpp ***/
  56529. /*** Start of inlined file: juce_MouseCursor.cpp ***/
  56530. BEGIN_JUCE_NAMESPACE
  56531. class MouseCursor::SharedCursorHandle
  56532. {
  56533. public:
  56534. explicit SharedCursorHandle (const MouseCursor::StandardCursorType type)
  56535. : handle (createStandardMouseCursor (type)),
  56536. refCount (1),
  56537. standardType (type),
  56538. isStandard (true)
  56539. {
  56540. }
  56541. SharedCursorHandle (const Image& image, const int hotSpotX, const int hotSpotY)
  56542. : handle (createMouseCursorFromImage (image, hotSpotX, hotSpotY)),
  56543. refCount (1),
  56544. standardType (MouseCursor::NormalCursor),
  56545. isStandard (false)
  56546. {
  56547. }
  56548. static SharedCursorHandle* createStandard (const MouseCursor::StandardCursorType type)
  56549. {
  56550. const ScopedLock sl (getLock());
  56551. for (int i = getCursors().size(); --i >= 0;)
  56552. {
  56553. SharedCursorHandle* const sc = getCursors().getUnchecked(i);
  56554. if (sc->standardType == type)
  56555. return sc->retain();
  56556. }
  56557. SharedCursorHandle* const sc = new SharedCursorHandle (type);
  56558. getCursors().add (sc);
  56559. return sc;
  56560. }
  56561. SharedCursorHandle* retain() throw()
  56562. {
  56563. ++refCount;
  56564. return this;
  56565. }
  56566. void release()
  56567. {
  56568. if (--refCount == 0)
  56569. {
  56570. if (isStandard)
  56571. {
  56572. const ScopedLock sl (getLock());
  56573. getCursors().removeValue (this);
  56574. }
  56575. delete this;
  56576. }
  56577. }
  56578. void* getHandle() const throw() { return handle; }
  56579. juce_UseDebuggingNewOperator
  56580. private:
  56581. void* const handle;
  56582. Atomic <int> refCount;
  56583. const MouseCursor::StandardCursorType standardType;
  56584. const bool isStandard;
  56585. static CriticalSection& getLock()
  56586. {
  56587. static CriticalSection lock;
  56588. return lock;
  56589. }
  56590. static Array <SharedCursorHandle*>& getCursors()
  56591. {
  56592. static Array <SharedCursorHandle*> cursors;
  56593. return cursors;
  56594. }
  56595. ~SharedCursorHandle()
  56596. {
  56597. deleteMouseCursor (handle, isStandard);
  56598. }
  56599. SharedCursorHandle& operator= (const SharedCursorHandle&);
  56600. };
  56601. MouseCursor::MouseCursor()
  56602. : cursorHandle (SharedCursorHandle::createStandard (NormalCursor))
  56603. {
  56604. jassert (cursorHandle != 0);
  56605. }
  56606. MouseCursor::MouseCursor (const StandardCursorType type)
  56607. : cursorHandle (SharedCursorHandle::createStandard (type))
  56608. {
  56609. jassert (cursorHandle != 0);
  56610. }
  56611. MouseCursor::MouseCursor (const Image& image, const int hotSpotX, const int hotSpotY)
  56612. : cursorHandle (new SharedCursorHandle (image, hotSpotX, hotSpotY))
  56613. {
  56614. }
  56615. MouseCursor::MouseCursor (const MouseCursor& other)
  56616. : cursorHandle (other.cursorHandle->retain())
  56617. {
  56618. }
  56619. MouseCursor::~MouseCursor()
  56620. {
  56621. cursorHandle->release();
  56622. }
  56623. MouseCursor& MouseCursor::operator= (const MouseCursor& other)
  56624. {
  56625. other.cursorHandle->retain();
  56626. cursorHandle->release();
  56627. cursorHandle = other.cursorHandle;
  56628. return *this;
  56629. }
  56630. bool MouseCursor::operator== (const MouseCursor& other) const throw()
  56631. {
  56632. return getHandle() == other.getHandle();
  56633. }
  56634. bool MouseCursor::operator!= (const MouseCursor& other) const throw()
  56635. {
  56636. return getHandle() != other.getHandle();
  56637. }
  56638. void* MouseCursor::getHandle() const throw()
  56639. {
  56640. return cursorHandle->getHandle();
  56641. }
  56642. void MouseCursor::showWaitCursor()
  56643. {
  56644. Desktop::getInstance().getMainMouseSource().showMouseCursor (MouseCursor::WaitCursor);
  56645. }
  56646. void MouseCursor::hideWaitCursor()
  56647. {
  56648. Desktop::getInstance().getMainMouseSource().revealCursor();
  56649. }
  56650. END_JUCE_NAMESPACE
  56651. /*** End of inlined file: juce_MouseCursor.cpp ***/
  56652. /*** Start of inlined file: juce_MouseEvent.cpp ***/
  56653. BEGIN_JUCE_NAMESPACE
  56654. MouseEvent::MouseEvent (MouseInputSource& source_,
  56655. const Point<int>& position,
  56656. const ModifierKeys& mods_,
  56657. Component* const eventComponent_,
  56658. Component* const originator,
  56659. const Time& eventTime_,
  56660. const Point<int> mouseDownPos_,
  56661. const Time& mouseDownTime_,
  56662. const int numberOfClicks_,
  56663. const bool mouseWasDragged) throw()
  56664. : x (position.getX()),
  56665. y (position.getY()),
  56666. mods (mods_),
  56667. eventComponent (eventComponent_),
  56668. originalComponent (originator),
  56669. eventTime (eventTime_),
  56670. source (source_),
  56671. mouseDownPos (mouseDownPos_),
  56672. mouseDownTime (mouseDownTime_),
  56673. numberOfClicks (numberOfClicks_),
  56674. wasMovedSinceMouseDown (mouseWasDragged)
  56675. {
  56676. }
  56677. MouseEvent::~MouseEvent() throw()
  56678. {
  56679. }
  56680. const MouseEvent MouseEvent::getEventRelativeTo (Component* const otherComponent) const throw()
  56681. {
  56682. if (otherComponent == 0)
  56683. {
  56684. jassertfalse;
  56685. return *this;
  56686. }
  56687. return MouseEvent (source, eventComponent->relativePositionToOtherComponent (otherComponent, getPosition()),
  56688. mods, otherComponent, originalComponent, eventTime,
  56689. eventComponent->relativePositionToOtherComponent (otherComponent, mouseDownPos),
  56690. mouseDownTime, numberOfClicks, wasMovedSinceMouseDown);
  56691. }
  56692. const MouseEvent MouseEvent::withNewPosition (const Point<int>& newPosition) const throw()
  56693. {
  56694. return MouseEvent (source, newPosition, mods, eventComponent, originalComponent,
  56695. eventTime, mouseDownPos, mouseDownTime,
  56696. numberOfClicks, wasMovedSinceMouseDown);
  56697. }
  56698. bool MouseEvent::mouseWasClicked() const throw()
  56699. {
  56700. return ! wasMovedSinceMouseDown;
  56701. }
  56702. int MouseEvent::getMouseDownX() const throw()
  56703. {
  56704. return mouseDownPos.getX();
  56705. }
  56706. int MouseEvent::getMouseDownY() const throw()
  56707. {
  56708. return mouseDownPos.getY();
  56709. }
  56710. const Point<int> MouseEvent::getMouseDownPosition() const throw()
  56711. {
  56712. return mouseDownPos;
  56713. }
  56714. int MouseEvent::getDistanceFromDragStartX() const throw()
  56715. {
  56716. return x - mouseDownPos.getX();
  56717. }
  56718. int MouseEvent::getDistanceFromDragStartY() const throw()
  56719. {
  56720. return y - mouseDownPos.getY();
  56721. }
  56722. int MouseEvent::getDistanceFromDragStart() const throw()
  56723. {
  56724. return mouseDownPos.getDistanceFrom (getPosition());
  56725. }
  56726. const Point<int> MouseEvent::getOffsetFromDragStart() const throw()
  56727. {
  56728. return getPosition() - mouseDownPos;
  56729. }
  56730. int MouseEvent::getLengthOfMousePress() const throw()
  56731. {
  56732. if (mouseDownTime.toMilliseconds() > 0)
  56733. return jmax (0, (int) (eventTime - mouseDownTime).inMilliseconds());
  56734. return 0;
  56735. }
  56736. const Point<int> MouseEvent::getPosition() const throw()
  56737. {
  56738. return Point<int> (x, y);
  56739. }
  56740. int MouseEvent::getScreenX() const
  56741. {
  56742. return getScreenPosition().getX();
  56743. }
  56744. int MouseEvent::getScreenY() const
  56745. {
  56746. return getScreenPosition().getY();
  56747. }
  56748. const Point<int> MouseEvent::getScreenPosition() const
  56749. {
  56750. return eventComponent->relativePositionToGlobal (Point<int> (x, y));
  56751. }
  56752. int MouseEvent::getMouseDownScreenX() const
  56753. {
  56754. return getMouseDownScreenPosition().getX();
  56755. }
  56756. int MouseEvent::getMouseDownScreenY() const
  56757. {
  56758. return getMouseDownScreenPosition().getY();
  56759. }
  56760. const Point<int> MouseEvent::getMouseDownScreenPosition() const
  56761. {
  56762. return eventComponent->relativePositionToGlobal (mouseDownPos);
  56763. }
  56764. int MouseEvent::doubleClickTimeOutMs = 400;
  56765. void MouseEvent::setDoubleClickTimeout (const int newTime) throw()
  56766. {
  56767. doubleClickTimeOutMs = newTime;
  56768. }
  56769. int MouseEvent::getDoubleClickTimeout() throw()
  56770. {
  56771. return doubleClickTimeOutMs;
  56772. }
  56773. END_JUCE_NAMESPACE
  56774. /*** End of inlined file: juce_MouseEvent.cpp ***/
  56775. /*** Start of inlined file: juce_MouseInputSource.cpp ***/
  56776. BEGIN_JUCE_NAMESPACE
  56777. class MouseInputSourceInternal : public AsyncUpdater
  56778. {
  56779. public:
  56780. MouseInputSourceInternal (MouseInputSource& source_, const int index_, const bool isMouseDevice_)
  56781. : index (index_), isMouseDevice (isMouseDevice_), source (source_), lastPeer (0), lastTime (0),
  56782. isUnboundedMouseModeOn (false), isCursorVisibleUntilOffscreen (false), currentCursorHandle (0),
  56783. mouseEventCounter (0)
  56784. {
  56785. zerostruct (mouseDowns);
  56786. }
  56787. ~MouseInputSourceInternal()
  56788. {
  56789. }
  56790. bool isDragging() const throw()
  56791. {
  56792. return buttonState.isAnyMouseButtonDown();
  56793. }
  56794. Component* getComponentUnderMouse() const
  56795. {
  56796. return static_cast <Component*> (componentUnderMouse);
  56797. }
  56798. const ModifierKeys getCurrentModifiers() const
  56799. {
  56800. return ModifierKeys::getCurrentModifiers().withoutMouseButtons().withFlags (buttonState.getRawFlags());
  56801. }
  56802. ComponentPeer* getPeer()
  56803. {
  56804. if (! ComponentPeer::isValidPeer (lastPeer))
  56805. lastPeer = 0;
  56806. return lastPeer;
  56807. }
  56808. Component* findComponentAt (const Point<int>& screenPos)
  56809. {
  56810. ComponentPeer* const peer = getPeer();
  56811. if (peer != 0)
  56812. {
  56813. Component* const comp = peer->getComponent();
  56814. const Point<int> relativePos (comp->globalPositionToRelative (screenPos));
  56815. // (the contains() call is needed to test for overlapping desktop windows)
  56816. if (comp->contains (relativePos.getX(), relativePos.getY()))
  56817. return comp->getComponentAt (relativePos);
  56818. }
  56819. return 0;
  56820. }
  56821. const Point<int> getScreenPosition() const throw()
  56822. {
  56823. return lastScreenPos + unboundedMouseOffset;
  56824. }
  56825. void sendMouseEnter (Component* const comp, const Point<int>& screenPos, const int64 time)
  56826. {
  56827. //DBG ("Mouse " + String (source.getIndex()) + " enter: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56828. comp->internalMouseEnter (source, comp->globalPositionToRelative (screenPos), time);
  56829. }
  56830. void sendMouseExit (Component* const comp, const Point<int>& screenPos, const int64 time)
  56831. {
  56832. //DBG ("Mouse " + String (source.getIndex()) + " exit: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56833. comp->internalMouseExit (source, comp->globalPositionToRelative (screenPos), time);
  56834. }
  56835. void sendMouseMove (Component* const comp, const Point<int>& screenPos, const int64 time)
  56836. {
  56837. //DBG ("Mouse " + String (source.getIndex()) + " move: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56838. comp->internalMouseMove (source, comp->globalPositionToRelative (screenPos), time);
  56839. }
  56840. void sendMouseDown (Component* const comp, const Point<int>& screenPos, const int64 time)
  56841. {
  56842. //DBG ("Mouse " + String (source.getIndex()) + " down: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56843. comp->internalMouseDown (source, comp->globalPositionToRelative (screenPos), time);
  56844. }
  56845. void sendMouseDrag (Component* const comp, const Point<int>& screenPos, const int64 time)
  56846. {
  56847. //DBG ("Mouse " + String (source.getIndex()) + " drag: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56848. comp->internalMouseDrag (source, comp->globalPositionToRelative (screenPos), time);
  56849. }
  56850. void sendMouseUp (Component* const comp, const Point<int>& screenPos, const int64 time)
  56851. {
  56852. //DBG ("Mouse " + String (source.getIndex()) + " up: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56853. comp->internalMouseUp (source, comp->globalPositionToRelative (screenPos), time, getCurrentModifiers());
  56854. }
  56855. void sendMouseWheel (Component* const comp, const Point<int>& screenPos, const int64 time, float x, float y)
  56856. {
  56857. //DBG ("Mouse " + String (source.getIndex()) + " wheel: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56858. comp->internalMouseWheel (source, comp->globalPositionToRelative (screenPos), time, x, y);
  56859. }
  56860. // (returns true if the button change caused a modal event loop)
  56861. bool setButtons (const Point<int>& screenPos, const int64 time, const ModifierKeys& newButtonState)
  56862. {
  56863. if (buttonState == newButtonState)
  56864. return false;
  56865. setScreenPos (screenPos, time, false);
  56866. // (ignore secondary clicks when there's already a button down)
  56867. if (buttonState.isAnyMouseButtonDown() == newButtonState.isAnyMouseButtonDown())
  56868. {
  56869. buttonState = newButtonState;
  56870. return false;
  56871. }
  56872. const int lastCounter = mouseEventCounter;
  56873. if (buttonState.isAnyMouseButtonDown())
  56874. {
  56875. Component* const current = getComponentUnderMouse();
  56876. if (current != 0)
  56877. sendMouseUp (current, screenPos + unboundedMouseOffset, time);
  56878. enableUnboundedMouseMovement (false, false);
  56879. }
  56880. buttonState = newButtonState;
  56881. if (buttonState.isAnyMouseButtonDown())
  56882. {
  56883. Desktop::getInstance().incrementMouseClickCounter();
  56884. Component* const current = getComponentUnderMouse();
  56885. if (current != 0)
  56886. {
  56887. registerMouseDown (screenPos, time, current);
  56888. sendMouseDown (current, screenPos, time);
  56889. }
  56890. }
  56891. return lastCounter != mouseEventCounter;
  56892. }
  56893. void setComponentUnderMouse (Component* const newComponent, const Point<int>& screenPos, const int64 time)
  56894. {
  56895. Component* current = getComponentUnderMouse();
  56896. if (newComponent != current)
  56897. {
  56898. Component::SafePointer<Component> safeNewComp (newComponent);
  56899. const ModifierKeys originalButtonState (buttonState);
  56900. if (current != 0)
  56901. {
  56902. setButtons (screenPos, time, ModifierKeys());
  56903. sendMouseExit (current, screenPos, time);
  56904. buttonState = originalButtonState;
  56905. }
  56906. componentUnderMouse = safeNewComp;
  56907. current = getComponentUnderMouse();
  56908. if (current != 0)
  56909. sendMouseEnter (current, screenPos, time);
  56910. revealCursor (false);
  56911. setButtons (screenPos, time, originalButtonState);
  56912. }
  56913. }
  56914. void setPeer (ComponentPeer* const newPeer, const Point<int>& screenPos, const int64 time)
  56915. {
  56916. ModifierKeys::updateCurrentModifiers();
  56917. if (newPeer != lastPeer)
  56918. {
  56919. setComponentUnderMouse (0, screenPos, time);
  56920. lastPeer = newPeer;
  56921. setComponentUnderMouse (findComponentAt (screenPos), screenPos, time);
  56922. }
  56923. }
  56924. void setScreenPos (const Point<int>& newScreenPos, const int64 time, const bool forceUpdate)
  56925. {
  56926. if (! isDragging())
  56927. setComponentUnderMouse (findComponentAt (newScreenPos), newScreenPos, time);
  56928. if (newScreenPos != lastScreenPos || forceUpdate)
  56929. {
  56930. cancelPendingUpdate();
  56931. lastScreenPos = newScreenPos;
  56932. Component* const current = getComponentUnderMouse();
  56933. if (current != 0)
  56934. {
  56935. if (isDragging())
  56936. {
  56937. registerMouseDrag (newScreenPos);
  56938. sendMouseDrag (current, newScreenPos + unboundedMouseOffset, time);
  56939. if (isUnboundedMouseModeOn)
  56940. handleUnboundedDrag (current);
  56941. }
  56942. else
  56943. {
  56944. sendMouseMove (current, newScreenPos, time);
  56945. }
  56946. }
  56947. revealCursor (false);
  56948. }
  56949. }
  56950. void handleEvent (ComponentPeer* const newPeer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& newMods)
  56951. {
  56952. jassert (newPeer != 0);
  56953. lastTime = time;
  56954. ++mouseEventCounter;
  56955. const Point<int> screenPos (newPeer->relativePositionToGlobal (positionWithinPeer));
  56956. if (isDragging() && newMods.isAnyMouseButtonDown())
  56957. {
  56958. setScreenPos (screenPos, time, false);
  56959. }
  56960. else
  56961. {
  56962. setPeer (newPeer, screenPos, time);
  56963. ComponentPeer* peer = getPeer();
  56964. if (peer != 0)
  56965. {
  56966. if (setButtons (screenPos, time, newMods))
  56967. return; // some modal events have been dispatched, so the current event is now out-of-date
  56968. peer = getPeer();
  56969. if (peer != 0)
  56970. setScreenPos (screenPos, time, false);
  56971. }
  56972. }
  56973. }
  56974. void handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, int64 time, float x, float y)
  56975. {
  56976. jassert (peer != 0);
  56977. lastTime = time;
  56978. ++mouseEventCounter;
  56979. const Point<int> screenPos (peer->relativePositionToGlobal (positionWithinPeer));
  56980. setPeer (peer, screenPos, time);
  56981. setScreenPos (screenPos, time, false);
  56982. triggerFakeMove();
  56983. if (! isDragging())
  56984. {
  56985. Component* current = getComponentUnderMouse();
  56986. if (current != 0)
  56987. sendMouseWheel (current, screenPos, time, x, y);
  56988. }
  56989. }
  56990. const Time getLastMouseDownTime() const throw()
  56991. {
  56992. return Time (mouseDowns[0].time);
  56993. }
  56994. const Point<int> getLastMouseDownPosition() const throw()
  56995. {
  56996. return mouseDowns[0].position;
  56997. }
  56998. int getNumberOfMultipleClicks() const throw()
  56999. {
  57000. int numClicks = 0;
  57001. if (mouseDowns[0].time != 0)
  57002. {
  57003. if (! mouseMovedSignificantlySincePressed)
  57004. ++numClicks;
  57005. for (int i = 1; i < numElementsInArray (mouseDowns); ++i)
  57006. {
  57007. if (mouseDowns[0].time - mouseDowns[i].time < (int) (MouseEvent::getDoubleClickTimeout() * (1.0 + 0.25 * (i - 1)))
  57008. && abs (mouseDowns[0].position.getX() - mouseDowns[i].position.getX()) < 8
  57009. && abs (mouseDowns[0].position.getY() - mouseDowns[i].position.getY()) < 8)
  57010. {
  57011. ++numClicks;
  57012. }
  57013. else
  57014. {
  57015. break;
  57016. }
  57017. }
  57018. }
  57019. return numClicks;
  57020. }
  57021. bool hasMouseMovedSignificantlySincePressed() const throw()
  57022. {
  57023. return mouseMovedSignificantlySincePressed
  57024. || lastTime > mouseDowns[0].time + 300;
  57025. }
  57026. void triggerFakeMove()
  57027. {
  57028. triggerAsyncUpdate();
  57029. }
  57030. void handleAsyncUpdate()
  57031. {
  57032. if (! isDragging())
  57033. setScreenPos (Desktop::getMousePosition(), jmax (lastTime, Time::currentTimeMillis()), true);
  57034. }
  57035. void enableUnboundedMouseMovement (bool enable, bool keepCursorVisibleUntilOffscreen)
  57036. {
  57037. enable = enable && isDragging();
  57038. isCursorVisibleUntilOffscreen = keepCursorVisibleUntilOffscreen;
  57039. if (enable != isUnboundedMouseModeOn)
  57040. {
  57041. if ((! enable) && ((! isCursorVisibleUntilOffscreen) || ! unboundedMouseOffset.isOrigin()))
  57042. {
  57043. // when released, return the mouse to within the component's bounds
  57044. Component* current = getComponentUnderMouse();
  57045. if (current != 0)
  57046. Desktop::setMousePosition (current->getScreenBounds()
  57047. .getConstrainedPoint (current->getMouseXYRelative()));
  57048. }
  57049. isUnboundedMouseModeOn = enable;
  57050. unboundedMouseOffset = Point<int>();
  57051. revealCursor (true);
  57052. }
  57053. }
  57054. void handleUnboundedDrag (Component* current)
  57055. {
  57056. const Rectangle<int> screenArea (current->getParentMonitorArea().expanded (-2, -2));
  57057. if (! screenArea.contains (lastScreenPos))
  57058. {
  57059. const Point<int> componentCentre (current->getScreenBounds().getCentre());
  57060. unboundedMouseOffset += (lastScreenPos - componentCentre);
  57061. Desktop::setMousePosition (componentCentre);
  57062. }
  57063. else if (isCursorVisibleUntilOffscreen
  57064. && (! unboundedMouseOffset.isOrigin())
  57065. && screenArea.contains (lastScreenPos + unboundedMouseOffset))
  57066. {
  57067. Desktop::setMousePosition (lastScreenPos + unboundedMouseOffset);
  57068. unboundedMouseOffset = Point<int>();
  57069. }
  57070. }
  57071. void showMouseCursor (MouseCursor cursor, bool forcedUpdate)
  57072. {
  57073. if (isUnboundedMouseModeOn && ((! unboundedMouseOffset.isOrigin()) || ! isCursorVisibleUntilOffscreen))
  57074. {
  57075. cursor = MouseCursor::NoCursor;
  57076. forcedUpdate = true;
  57077. }
  57078. if (forcedUpdate || cursor.getHandle() != currentCursorHandle)
  57079. {
  57080. currentCursorHandle = cursor.getHandle();
  57081. cursor.showInWindow (getPeer());
  57082. }
  57083. }
  57084. void hideCursor()
  57085. {
  57086. showMouseCursor (MouseCursor::NoCursor, true);
  57087. }
  57088. void revealCursor (bool forcedUpdate)
  57089. {
  57090. MouseCursor mc (MouseCursor::NormalCursor);
  57091. Component* current = getComponentUnderMouse();
  57092. if (current != 0)
  57093. mc = current->getLookAndFeel().getMouseCursorFor (*current);
  57094. showMouseCursor (mc, forcedUpdate);
  57095. }
  57096. int index;
  57097. bool isMouseDevice;
  57098. Point<int> lastScreenPos;
  57099. ModifierKeys buttonState;
  57100. private:
  57101. MouseInputSource& source;
  57102. Component::SafePointer<Component> componentUnderMouse;
  57103. ComponentPeer* lastPeer;
  57104. Point<int> unboundedMouseOffset;
  57105. bool isUnboundedMouseModeOn, isCursorVisibleUntilOffscreen;
  57106. void* currentCursorHandle;
  57107. int mouseEventCounter;
  57108. struct RecentMouseDown
  57109. {
  57110. Point<int> position;
  57111. int64 time;
  57112. Component* component;
  57113. };
  57114. RecentMouseDown mouseDowns[4];
  57115. bool mouseMovedSignificantlySincePressed;
  57116. int64 lastTime;
  57117. void registerMouseDown (const Point<int>& screenPos, const int64 time, Component* const component) throw()
  57118. {
  57119. for (int i = numElementsInArray (mouseDowns); --i > 0;)
  57120. mouseDowns[i] = mouseDowns[i - 1];
  57121. mouseDowns[0].position = screenPos;
  57122. mouseDowns[0].time = time;
  57123. mouseDowns[0].component = component;
  57124. mouseMovedSignificantlySincePressed = false;
  57125. }
  57126. void registerMouseDrag (const Point<int>& screenPos) throw()
  57127. {
  57128. mouseMovedSignificantlySincePressed = mouseMovedSignificantlySincePressed
  57129. || mouseDowns[0].position.getDistanceFrom (screenPos) >= 4;
  57130. }
  57131. MouseInputSourceInternal (const MouseInputSourceInternal&);
  57132. MouseInputSourceInternal& operator= (const MouseInputSourceInternal&);
  57133. };
  57134. MouseInputSource::MouseInputSource (const int index, const bool isMouseDevice)
  57135. {
  57136. pimpl = new MouseInputSourceInternal (*this, index, isMouseDevice);
  57137. }
  57138. MouseInputSource::~MouseInputSource()
  57139. {
  57140. }
  57141. bool MouseInputSource::isMouse() const { return pimpl->isMouseDevice; }
  57142. bool MouseInputSource::isTouch() const { return ! isMouse(); }
  57143. bool MouseInputSource::canHover() const { return isMouse(); }
  57144. bool MouseInputSource::hasMouseWheel() const { return isMouse(); }
  57145. int MouseInputSource::getIndex() const { return pimpl->index; }
  57146. bool MouseInputSource::isDragging() const { return pimpl->isDragging(); }
  57147. const Point<int> MouseInputSource::getScreenPosition() const { return pimpl->getScreenPosition(); }
  57148. const ModifierKeys MouseInputSource::getCurrentModifiers() const { return pimpl->getCurrentModifiers(); }
  57149. Component* MouseInputSource::getComponentUnderMouse() const { return pimpl->getComponentUnderMouse(); }
  57150. void MouseInputSource::triggerFakeMove() const { pimpl->triggerFakeMove(); }
  57151. int MouseInputSource::getNumberOfMultipleClicks() const throw() { return pimpl->getNumberOfMultipleClicks(); }
  57152. const Time MouseInputSource::getLastMouseDownTime() const throw() { return pimpl->getLastMouseDownTime(); }
  57153. const Point<int> MouseInputSource::getLastMouseDownPosition() const throw() { return pimpl->getLastMouseDownPosition(); }
  57154. bool MouseInputSource::hasMouseMovedSignificantlySincePressed() const throw() { return pimpl->hasMouseMovedSignificantlySincePressed(); }
  57155. bool MouseInputSource::canDoUnboundedMovement() const throw() { return isMouse(); }
  57156. void MouseInputSource::enableUnboundedMouseMovement (bool isEnabled, bool keepCursorVisibleUntilOffscreen) { pimpl->enableUnboundedMouseMovement (isEnabled, keepCursorVisibleUntilOffscreen); }
  57157. bool MouseInputSource::hasMouseCursor() const throw() { return isMouse(); }
  57158. void MouseInputSource::showMouseCursor (const MouseCursor& cursor) { pimpl->showMouseCursor (cursor, false); }
  57159. void MouseInputSource::hideCursor() { pimpl->hideCursor(); }
  57160. void MouseInputSource::revealCursor() { pimpl->revealCursor (false); }
  57161. void MouseInputSource::forceMouseCursorUpdate() { pimpl->revealCursor (true); }
  57162. void MouseInputSource::handleEvent (ComponentPeer* peer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& mods)
  57163. {
  57164. pimpl->handleEvent (peer, positionWithinPeer, time, mods.withOnlyMouseButtons());
  57165. }
  57166. void MouseInputSource::handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  57167. {
  57168. pimpl->handleWheel (peer, positionWithinPeer, time, x, y);
  57169. }
  57170. END_JUCE_NAMESPACE
  57171. /*** End of inlined file: juce_MouseInputSource.cpp ***/
  57172. /*** Start of inlined file: juce_MouseHoverDetector.cpp ***/
  57173. BEGIN_JUCE_NAMESPACE
  57174. MouseHoverDetector::MouseHoverDetector (const int hoverTimeMillisecs_)
  57175. : source (0),
  57176. hoverTimeMillisecs (hoverTimeMillisecs_),
  57177. hasJustHovered (false)
  57178. {
  57179. internalTimer.owner = this;
  57180. }
  57181. MouseHoverDetector::~MouseHoverDetector()
  57182. {
  57183. setHoverComponent (0);
  57184. }
  57185. void MouseHoverDetector::setHoverTimeMillisecs (const int newTimeInMillisecs)
  57186. {
  57187. hoverTimeMillisecs = newTimeInMillisecs;
  57188. }
  57189. void MouseHoverDetector::setHoverComponent (Component* const newSourceComponent)
  57190. {
  57191. if (source != newSourceComponent)
  57192. {
  57193. internalTimer.stopTimer();
  57194. hasJustHovered = false;
  57195. if (source != 0)
  57196. {
  57197. // ! you need to delete the hover detector before deleting its component
  57198. jassert (source->isValidComponent());
  57199. source->removeMouseListener (&internalTimer);
  57200. }
  57201. source = newSourceComponent;
  57202. if (newSourceComponent != 0)
  57203. newSourceComponent->addMouseListener (&internalTimer, false);
  57204. }
  57205. }
  57206. void MouseHoverDetector::hoverTimerCallback()
  57207. {
  57208. internalTimer.stopTimer();
  57209. if (source != 0)
  57210. {
  57211. const Point<int> pos (source->getMouseXYRelative());
  57212. if (source->reallyContains (pos.getX(), pos.getY(), false))
  57213. {
  57214. hasJustHovered = true;
  57215. mouseHovered (pos.getX(), pos.getY());
  57216. }
  57217. }
  57218. }
  57219. void MouseHoverDetector::checkJustHoveredCallback()
  57220. {
  57221. if (hasJustHovered)
  57222. {
  57223. hasJustHovered = false;
  57224. mouseMovedAfterHover();
  57225. }
  57226. }
  57227. void MouseHoverDetector::HoverDetectorInternal::timerCallback()
  57228. {
  57229. owner->hoverTimerCallback();
  57230. }
  57231. void MouseHoverDetector::HoverDetectorInternal::mouseEnter (const MouseEvent&)
  57232. {
  57233. stopTimer();
  57234. owner->checkJustHoveredCallback();
  57235. }
  57236. void MouseHoverDetector::HoverDetectorInternal::mouseExit (const MouseEvent&)
  57237. {
  57238. stopTimer();
  57239. owner->checkJustHoveredCallback();
  57240. }
  57241. void MouseHoverDetector::HoverDetectorInternal::mouseDown (const MouseEvent&)
  57242. {
  57243. stopTimer();
  57244. owner->checkJustHoveredCallback();
  57245. }
  57246. void MouseHoverDetector::HoverDetectorInternal::mouseUp (const MouseEvent&)
  57247. {
  57248. stopTimer();
  57249. owner->checkJustHoveredCallback();
  57250. }
  57251. void MouseHoverDetector::HoverDetectorInternal::mouseMove (const MouseEvent& e)
  57252. {
  57253. if (lastX != e.x || lastY != e.y) // to avoid fake mouse-moves setting it off
  57254. {
  57255. lastX = e.x;
  57256. lastY = e.y;
  57257. if (owner->source != 0)
  57258. startTimer (owner->hoverTimeMillisecs);
  57259. owner->checkJustHoveredCallback();
  57260. }
  57261. }
  57262. void MouseHoverDetector::HoverDetectorInternal::mouseWheelMove (const MouseEvent&, float, float)
  57263. {
  57264. stopTimer();
  57265. owner->checkJustHoveredCallback();
  57266. }
  57267. END_JUCE_NAMESPACE
  57268. /*** End of inlined file: juce_MouseHoverDetector.cpp ***/
  57269. /*** Start of inlined file: juce_MouseListener.cpp ***/
  57270. BEGIN_JUCE_NAMESPACE
  57271. void MouseListener::mouseEnter (const MouseEvent&)
  57272. {
  57273. }
  57274. void MouseListener::mouseExit (const MouseEvent&)
  57275. {
  57276. }
  57277. void MouseListener::mouseDown (const MouseEvent&)
  57278. {
  57279. }
  57280. void MouseListener::mouseUp (const MouseEvent&)
  57281. {
  57282. }
  57283. void MouseListener::mouseDrag (const MouseEvent&)
  57284. {
  57285. }
  57286. void MouseListener::mouseMove (const MouseEvent&)
  57287. {
  57288. }
  57289. void MouseListener::mouseDoubleClick (const MouseEvent&)
  57290. {
  57291. }
  57292. void MouseListener::mouseWheelMove (const MouseEvent&, float, float)
  57293. {
  57294. }
  57295. END_JUCE_NAMESPACE
  57296. /*** End of inlined file: juce_MouseListener.cpp ***/
  57297. /*** Start of inlined file: juce_BooleanPropertyComponent.cpp ***/
  57298. BEGIN_JUCE_NAMESPACE
  57299. BooleanPropertyComponent::BooleanPropertyComponent (const String& name,
  57300. const String& buttonTextWhenTrue,
  57301. const String& buttonTextWhenFalse)
  57302. : PropertyComponent (name),
  57303. onText (buttonTextWhenTrue),
  57304. offText (buttonTextWhenFalse)
  57305. {
  57306. addAndMakeVisible (&button);
  57307. button.setClickingTogglesState (false);
  57308. button.addButtonListener (this);
  57309. }
  57310. BooleanPropertyComponent::BooleanPropertyComponent (const Value& valueToControl,
  57311. const String& name,
  57312. const String& buttonText)
  57313. : PropertyComponent (name),
  57314. onText (buttonText),
  57315. offText (buttonText)
  57316. {
  57317. addAndMakeVisible (&button);
  57318. button.setClickingTogglesState (false);
  57319. button.setButtonText (buttonText);
  57320. button.getToggleStateValue().referTo (valueToControl);
  57321. button.setClickingTogglesState (true);
  57322. }
  57323. BooleanPropertyComponent::~BooleanPropertyComponent()
  57324. {
  57325. }
  57326. void BooleanPropertyComponent::setState (const bool newState)
  57327. {
  57328. button.setToggleState (newState, true);
  57329. }
  57330. bool BooleanPropertyComponent::getState() const
  57331. {
  57332. return button.getToggleState();
  57333. }
  57334. void BooleanPropertyComponent::paint (Graphics& g)
  57335. {
  57336. PropertyComponent::paint (g);
  57337. g.setColour (Colours::white);
  57338. g.fillRect (button.getBounds());
  57339. g.setColour (findColour (ComboBox::outlineColourId));
  57340. g.drawRect (button.getBounds());
  57341. }
  57342. void BooleanPropertyComponent::refresh()
  57343. {
  57344. button.setToggleState (getState(), false);
  57345. button.setButtonText (button.getToggleState() ? onText : offText);
  57346. }
  57347. void BooleanPropertyComponent::buttonClicked (Button*)
  57348. {
  57349. setState (! getState());
  57350. }
  57351. END_JUCE_NAMESPACE
  57352. /*** End of inlined file: juce_BooleanPropertyComponent.cpp ***/
  57353. /*** Start of inlined file: juce_ButtonPropertyComponent.cpp ***/
  57354. BEGIN_JUCE_NAMESPACE
  57355. ButtonPropertyComponent::ButtonPropertyComponent (const String& name,
  57356. const bool triggerOnMouseDown)
  57357. : PropertyComponent (name)
  57358. {
  57359. addAndMakeVisible (&button);
  57360. button.setTriggeredOnMouseDown (triggerOnMouseDown);
  57361. button.addButtonListener (this);
  57362. }
  57363. ButtonPropertyComponent::~ButtonPropertyComponent()
  57364. {
  57365. }
  57366. void ButtonPropertyComponent::refresh()
  57367. {
  57368. button.setButtonText (getButtonText());
  57369. }
  57370. void ButtonPropertyComponent::buttonClicked (Button*)
  57371. {
  57372. buttonClicked();
  57373. }
  57374. END_JUCE_NAMESPACE
  57375. /*** End of inlined file: juce_ButtonPropertyComponent.cpp ***/
  57376. /*** Start of inlined file: juce_ChoicePropertyComponent.cpp ***/
  57377. BEGIN_JUCE_NAMESPACE
  57378. class ChoicePropertyComponent::RemapperValueSource : public Value::ValueSource,
  57379. public Value::Listener
  57380. {
  57381. public:
  57382. RemapperValueSource (const Value& sourceValue_, const Array<var>& mappings_)
  57383. : sourceValue (sourceValue_),
  57384. mappings (mappings_)
  57385. {
  57386. sourceValue.addListener (this);
  57387. }
  57388. ~RemapperValueSource() {}
  57389. const var getValue() const
  57390. {
  57391. return mappings.indexOf (sourceValue.getValue()) + 1;
  57392. }
  57393. void setValue (const var& newValue)
  57394. {
  57395. const var remappedVal (mappings [(int) newValue - 1]);
  57396. if (remappedVal != sourceValue)
  57397. sourceValue = remappedVal;
  57398. }
  57399. void valueChanged (Value&)
  57400. {
  57401. sendChangeMessage (true);
  57402. }
  57403. juce_UseDebuggingNewOperator
  57404. protected:
  57405. Value sourceValue;
  57406. Array<var> mappings;
  57407. RemapperValueSource (const RemapperValueSource&);
  57408. const RemapperValueSource& operator= (const RemapperValueSource&);
  57409. };
  57410. ChoicePropertyComponent::ChoicePropertyComponent (const String& name)
  57411. : PropertyComponent (name),
  57412. isCustomClass (true)
  57413. {
  57414. }
  57415. ChoicePropertyComponent::ChoicePropertyComponent (const Value& valueToControl,
  57416. const String& name,
  57417. const StringArray& choices_,
  57418. const Array <var>& correspondingValues)
  57419. : PropertyComponent (name),
  57420. choices (choices_),
  57421. isCustomClass (false)
  57422. {
  57423. // The array of corresponding values must contain one value for each of the items in
  57424. // the choices array!
  57425. jassert (correspondingValues.size() == choices.size());
  57426. createComboBox();
  57427. comboBox.getSelectedIdAsValue().referTo (Value (new RemapperValueSource (valueToControl, correspondingValues)));
  57428. }
  57429. ChoicePropertyComponent::~ChoicePropertyComponent()
  57430. {
  57431. }
  57432. void ChoicePropertyComponent::createComboBox()
  57433. {
  57434. addAndMakeVisible (&comboBox);
  57435. for (int i = 0; i < choices.size(); ++i)
  57436. {
  57437. if (choices[i].isNotEmpty())
  57438. comboBox.addItem (choices[i], i + 1);
  57439. else
  57440. comboBox.addSeparator();
  57441. }
  57442. comboBox.setEditableText (false);
  57443. }
  57444. void ChoicePropertyComponent::setIndex (const int /*newIndex*/)
  57445. {
  57446. jassertfalse; // you need to override this method in your subclass!
  57447. }
  57448. int ChoicePropertyComponent::getIndex() const
  57449. {
  57450. jassertfalse; // you need to override this method in your subclass!
  57451. return -1;
  57452. }
  57453. const StringArray& ChoicePropertyComponent::getChoices() const
  57454. {
  57455. return choices;
  57456. }
  57457. void ChoicePropertyComponent::refresh()
  57458. {
  57459. if (isCustomClass)
  57460. {
  57461. if (! comboBox.isVisible())
  57462. {
  57463. createComboBox();
  57464. comboBox.addListener (this);
  57465. }
  57466. comboBox.setSelectedId (getIndex() + 1, true);
  57467. }
  57468. }
  57469. void ChoicePropertyComponent::comboBoxChanged (ComboBox*)
  57470. {
  57471. if (isCustomClass)
  57472. {
  57473. const int newIndex = comboBox.getSelectedId() - 1;
  57474. if (newIndex != getIndex())
  57475. setIndex (newIndex);
  57476. }
  57477. }
  57478. END_JUCE_NAMESPACE
  57479. /*** End of inlined file: juce_ChoicePropertyComponent.cpp ***/
  57480. /*** Start of inlined file: juce_PropertyComponent.cpp ***/
  57481. BEGIN_JUCE_NAMESPACE
  57482. PropertyComponent::PropertyComponent (const String& name,
  57483. const int preferredHeight_)
  57484. : Component (name),
  57485. preferredHeight (preferredHeight_)
  57486. {
  57487. jassert (name.isNotEmpty());
  57488. }
  57489. PropertyComponent::~PropertyComponent()
  57490. {
  57491. }
  57492. void PropertyComponent::paint (Graphics& g)
  57493. {
  57494. getLookAndFeel().drawPropertyComponentBackground (g, getWidth(), getHeight(), *this);
  57495. getLookAndFeel().drawPropertyComponentLabel (g, getWidth(), getHeight(), *this);
  57496. }
  57497. void PropertyComponent::resized()
  57498. {
  57499. if (getNumChildComponents() > 0)
  57500. getChildComponent (0)->setBounds (getLookAndFeel().getPropertyComponentContentPosition (*this));
  57501. }
  57502. void PropertyComponent::enablementChanged()
  57503. {
  57504. repaint();
  57505. }
  57506. END_JUCE_NAMESPACE
  57507. /*** End of inlined file: juce_PropertyComponent.cpp ***/
  57508. /*** Start of inlined file: juce_PropertyPanel.cpp ***/
  57509. BEGIN_JUCE_NAMESPACE
  57510. class PropertyPanel::PropertyHolderComponent : public Component
  57511. {
  57512. public:
  57513. PropertyHolderComponent()
  57514. {
  57515. }
  57516. ~PropertyHolderComponent()
  57517. {
  57518. deleteAllChildren();
  57519. }
  57520. void paint (Graphics&)
  57521. {
  57522. }
  57523. void updateLayout (int width);
  57524. void refreshAll() const;
  57525. private:
  57526. PropertyHolderComponent (const PropertyHolderComponent&);
  57527. PropertyHolderComponent& operator= (const PropertyHolderComponent&);
  57528. };
  57529. class PropertySectionComponent : public Component
  57530. {
  57531. public:
  57532. PropertySectionComponent (const String& sectionTitle,
  57533. const Array <PropertyComponent*>& newProperties,
  57534. const bool open)
  57535. : Component (sectionTitle),
  57536. titleHeight (sectionTitle.isNotEmpty() ? 22 : 0),
  57537. isOpen_ (open)
  57538. {
  57539. for (int i = newProperties.size(); --i >= 0;)
  57540. {
  57541. addAndMakeVisible (newProperties.getUnchecked(i));
  57542. newProperties.getUnchecked(i)->refresh();
  57543. }
  57544. }
  57545. ~PropertySectionComponent()
  57546. {
  57547. deleteAllChildren();
  57548. }
  57549. void paint (Graphics& g)
  57550. {
  57551. if (titleHeight > 0)
  57552. getLookAndFeel().drawPropertyPanelSectionHeader (g, getName(), isOpen(), getWidth(), titleHeight);
  57553. }
  57554. void resized()
  57555. {
  57556. int y = titleHeight;
  57557. for (int i = getNumChildComponents(); --i >= 0;)
  57558. {
  57559. PropertyComponent* const pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  57560. if (pec != 0)
  57561. {
  57562. const int prefH = pec->getPreferredHeight();
  57563. pec->setBounds (1, y, getWidth() - 2, prefH);
  57564. y += prefH;
  57565. }
  57566. }
  57567. }
  57568. int getPreferredHeight() const
  57569. {
  57570. int y = titleHeight;
  57571. if (isOpen())
  57572. {
  57573. for (int i = 0; i < getNumChildComponents(); ++i)
  57574. {
  57575. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  57576. if (pec != 0)
  57577. y += pec->getPreferredHeight();
  57578. }
  57579. }
  57580. return y;
  57581. }
  57582. void setOpen (const bool open)
  57583. {
  57584. if (isOpen_ != open)
  57585. {
  57586. isOpen_ = open;
  57587. for (int i = 0; i < getNumChildComponents(); ++i)
  57588. {
  57589. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  57590. if (pec != 0)
  57591. pec->setVisible (open);
  57592. }
  57593. // (unable to use the syntax findParentComponentOfClass <DragAndDropContainer> () because of a VC6 compiler bug)
  57594. PropertyPanel* const pp = findParentComponentOfClass ((PropertyPanel*) 0);
  57595. if (pp != 0)
  57596. pp->resized();
  57597. }
  57598. }
  57599. bool isOpen() const
  57600. {
  57601. return isOpen_;
  57602. }
  57603. void refreshAll() const
  57604. {
  57605. for (int i = 0; i < getNumChildComponents(); ++i)
  57606. {
  57607. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  57608. if (pec != 0)
  57609. pec->refresh();
  57610. }
  57611. }
  57612. void mouseDown (const MouseEvent&)
  57613. {
  57614. }
  57615. void mouseUp (const MouseEvent& e)
  57616. {
  57617. if (e.getMouseDownX() < titleHeight
  57618. && e.x < titleHeight
  57619. && e.y < titleHeight
  57620. && e.getNumberOfClicks() != 2)
  57621. {
  57622. setOpen (! isOpen());
  57623. }
  57624. }
  57625. void mouseDoubleClick (const MouseEvent& e)
  57626. {
  57627. if (e.y < titleHeight)
  57628. setOpen (! isOpen());
  57629. }
  57630. private:
  57631. int titleHeight;
  57632. bool isOpen_;
  57633. PropertySectionComponent (const PropertySectionComponent&);
  57634. PropertySectionComponent& operator= (const PropertySectionComponent&);
  57635. };
  57636. void PropertyPanel::PropertyHolderComponent::updateLayout (const int width)
  57637. {
  57638. int y = 0;
  57639. for (int i = getNumChildComponents(); --i >= 0;)
  57640. {
  57641. PropertySectionComponent* const section
  57642. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  57643. if (section != 0)
  57644. {
  57645. const int prefH = section->getPreferredHeight();
  57646. section->setBounds (0, y, width, prefH);
  57647. y += prefH;
  57648. }
  57649. }
  57650. setSize (width, y);
  57651. repaint();
  57652. }
  57653. void PropertyPanel::PropertyHolderComponent::refreshAll() const
  57654. {
  57655. for (int i = getNumChildComponents(); --i >= 0;)
  57656. {
  57657. PropertySectionComponent* const section
  57658. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  57659. if (section != 0)
  57660. section->refreshAll();
  57661. }
  57662. }
  57663. PropertyPanel::PropertyPanel()
  57664. {
  57665. messageWhenEmpty = TRANS("(nothing selected)");
  57666. addAndMakeVisible (&viewport);
  57667. viewport.setViewedComponent (propertyHolderComponent = new PropertyHolderComponent());
  57668. viewport.setFocusContainer (true);
  57669. }
  57670. PropertyPanel::~PropertyPanel()
  57671. {
  57672. clear();
  57673. }
  57674. void PropertyPanel::paint (Graphics& g)
  57675. {
  57676. if (propertyHolderComponent->getNumChildComponents() == 0)
  57677. {
  57678. g.setColour (Colours::black.withAlpha (0.5f));
  57679. g.setFont (14.0f);
  57680. g.drawText (messageWhenEmpty, 0, 0, getWidth(), 30,
  57681. Justification::centred, true);
  57682. }
  57683. }
  57684. void PropertyPanel::resized()
  57685. {
  57686. viewport.setBounds (getLocalBounds());
  57687. updatePropHolderLayout();
  57688. }
  57689. void PropertyPanel::clear()
  57690. {
  57691. if (propertyHolderComponent->getNumChildComponents() > 0)
  57692. {
  57693. propertyHolderComponent->deleteAllChildren();
  57694. repaint();
  57695. }
  57696. }
  57697. void PropertyPanel::addProperties (const Array <PropertyComponent*>& newProperties)
  57698. {
  57699. if (propertyHolderComponent->getNumChildComponents() == 0)
  57700. repaint();
  57701. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (String::empty,
  57702. newProperties,
  57703. true), 0);
  57704. updatePropHolderLayout();
  57705. }
  57706. void PropertyPanel::addSection (const String& sectionTitle,
  57707. const Array <PropertyComponent*>& newProperties,
  57708. const bool shouldBeOpen)
  57709. {
  57710. jassert (sectionTitle.isNotEmpty());
  57711. if (propertyHolderComponent->getNumChildComponents() == 0)
  57712. repaint();
  57713. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (sectionTitle,
  57714. newProperties,
  57715. shouldBeOpen), 0);
  57716. updatePropHolderLayout();
  57717. }
  57718. void PropertyPanel::updatePropHolderLayout() const
  57719. {
  57720. const int maxWidth = viewport.getMaximumVisibleWidth();
  57721. propertyHolderComponent->updateLayout (maxWidth);
  57722. const int newMaxWidth = viewport.getMaximumVisibleWidth();
  57723. if (maxWidth != newMaxWidth)
  57724. {
  57725. // need to do this twice because of scrollbars changing the size, etc.
  57726. propertyHolderComponent->updateLayout (newMaxWidth);
  57727. }
  57728. }
  57729. void PropertyPanel::refreshAll() const
  57730. {
  57731. propertyHolderComponent->refreshAll();
  57732. }
  57733. const StringArray PropertyPanel::getSectionNames() const
  57734. {
  57735. StringArray s;
  57736. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  57737. {
  57738. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  57739. if (section != 0 && section->getName().isNotEmpty())
  57740. s.add (section->getName());
  57741. }
  57742. return s;
  57743. }
  57744. bool PropertyPanel::isSectionOpen (const int sectionIndex) const
  57745. {
  57746. int index = 0;
  57747. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  57748. {
  57749. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  57750. if (section != 0 && section->getName().isNotEmpty())
  57751. {
  57752. if (index == sectionIndex)
  57753. return section->isOpen();
  57754. ++index;
  57755. }
  57756. }
  57757. return false;
  57758. }
  57759. void PropertyPanel::setSectionOpen (const int sectionIndex, const bool shouldBeOpen)
  57760. {
  57761. int index = 0;
  57762. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  57763. {
  57764. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  57765. if (section != 0 && section->getName().isNotEmpty())
  57766. {
  57767. if (index == sectionIndex)
  57768. {
  57769. section->setOpen (shouldBeOpen);
  57770. break;
  57771. }
  57772. ++index;
  57773. }
  57774. }
  57775. }
  57776. void PropertyPanel::setSectionEnabled (const int sectionIndex, const bool shouldBeEnabled)
  57777. {
  57778. int index = 0;
  57779. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  57780. {
  57781. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  57782. if (section != 0 && section->getName().isNotEmpty())
  57783. {
  57784. if (index == sectionIndex)
  57785. {
  57786. section->setEnabled (shouldBeEnabled);
  57787. break;
  57788. }
  57789. ++index;
  57790. }
  57791. }
  57792. }
  57793. XmlElement* PropertyPanel::getOpennessState() const
  57794. {
  57795. XmlElement* const xml = new XmlElement ("PROPERTYPANELSTATE");
  57796. xml->setAttribute ("scrollPos", viewport.getViewPositionY());
  57797. const StringArray sections (getSectionNames());
  57798. for (int i = 0; i < sections.size(); ++i)
  57799. {
  57800. if (sections[i].isNotEmpty())
  57801. {
  57802. XmlElement* const e = xml->createNewChildElement ("SECTION");
  57803. e->setAttribute ("name", sections[i]);
  57804. e->setAttribute ("open", isSectionOpen (i) ? 1 : 0);
  57805. }
  57806. }
  57807. return xml;
  57808. }
  57809. void PropertyPanel::restoreOpennessState (const XmlElement& xml)
  57810. {
  57811. if (xml.hasTagName ("PROPERTYPANELSTATE"))
  57812. {
  57813. const StringArray sections (getSectionNames());
  57814. forEachXmlChildElementWithTagName (xml, e, "SECTION")
  57815. {
  57816. setSectionOpen (sections.indexOf (e->getStringAttribute ("name")),
  57817. e->getBoolAttribute ("open"));
  57818. }
  57819. viewport.setViewPosition (viewport.getViewPositionX(),
  57820. xml.getIntAttribute ("scrollPos", viewport.getViewPositionY()));
  57821. }
  57822. }
  57823. void PropertyPanel::setMessageWhenEmpty (const String& newMessage)
  57824. {
  57825. if (messageWhenEmpty != newMessage)
  57826. {
  57827. messageWhenEmpty = newMessage;
  57828. repaint();
  57829. }
  57830. }
  57831. const String& PropertyPanel::getMessageWhenEmpty() const
  57832. {
  57833. return messageWhenEmpty;
  57834. }
  57835. END_JUCE_NAMESPACE
  57836. /*** End of inlined file: juce_PropertyPanel.cpp ***/
  57837. /*** Start of inlined file: juce_SliderPropertyComponent.cpp ***/
  57838. BEGIN_JUCE_NAMESPACE
  57839. SliderPropertyComponent::SliderPropertyComponent (const String& name,
  57840. const double rangeMin,
  57841. const double rangeMax,
  57842. const double interval,
  57843. const double skewFactor)
  57844. : PropertyComponent (name)
  57845. {
  57846. addAndMakeVisible (&slider);
  57847. slider.setRange (rangeMin, rangeMax, interval);
  57848. slider.setSkewFactor (skewFactor);
  57849. slider.setSliderStyle (Slider::LinearBar);
  57850. slider.addListener (this);
  57851. }
  57852. SliderPropertyComponent::SliderPropertyComponent (const Value& valueToControl,
  57853. const String& name,
  57854. const double rangeMin,
  57855. const double rangeMax,
  57856. const double interval,
  57857. const double skewFactor)
  57858. : PropertyComponent (name)
  57859. {
  57860. addAndMakeVisible (&slider);
  57861. slider.setRange (rangeMin, rangeMax, interval);
  57862. slider.setSkewFactor (skewFactor);
  57863. slider.setSliderStyle (Slider::LinearBar);
  57864. slider.getValueObject().referTo (valueToControl);
  57865. }
  57866. SliderPropertyComponent::~SliderPropertyComponent()
  57867. {
  57868. }
  57869. void SliderPropertyComponent::setValue (const double /*newValue*/)
  57870. {
  57871. }
  57872. double SliderPropertyComponent::getValue() const
  57873. {
  57874. return slider.getValue();
  57875. }
  57876. void SliderPropertyComponent::refresh()
  57877. {
  57878. slider.setValue (getValue(), false);
  57879. }
  57880. void SliderPropertyComponent::sliderValueChanged (Slider*)
  57881. {
  57882. if (getValue() != slider.getValue())
  57883. setValue (slider.getValue());
  57884. }
  57885. END_JUCE_NAMESPACE
  57886. /*** End of inlined file: juce_SliderPropertyComponent.cpp ***/
  57887. /*** Start of inlined file: juce_TextPropertyComponent.cpp ***/
  57888. BEGIN_JUCE_NAMESPACE
  57889. class TextPropLabel : public Label
  57890. {
  57891. TextPropertyComponent& owner;
  57892. int maxChars;
  57893. bool isMultiline;
  57894. public:
  57895. TextPropLabel (TextPropertyComponent& owner_,
  57896. const int maxChars_, const bool isMultiline_)
  57897. : Label (String::empty, String::empty),
  57898. owner (owner_),
  57899. maxChars (maxChars_),
  57900. isMultiline (isMultiline_)
  57901. {
  57902. setEditable (true, true, false);
  57903. setColour (backgroundColourId, Colours::white);
  57904. setColour (outlineColourId, findColour (ComboBox::outlineColourId));
  57905. }
  57906. ~TextPropLabel()
  57907. {
  57908. }
  57909. TextEditor* createEditorComponent()
  57910. {
  57911. TextEditor* const textEditor = Label::createEditorComponent();
  57912. textEditor->setInputRestrictions (maxChars);
  57913. if (isMultiline)
  57914. {
  57915. textEditor->setMultiLine (true, true);
  57916. textEditor->setReturnKeyStartsNewLine (true);
  57917. }
  57918. return textEditor;
  57919. }
  57920. void textWasEdited()
  57921. {
  57922. owner.textWasEdited();
  57923. }
  57924. };
  57925. TextPropertyComponent::TextPropertyComponent (const String& name,
  57926. const int maxNumChars,
  57927. const bool isMultiLine)
  57928. : PropertyComponent (name)
  57929. {
  57930. createEditor (maxNumChars, isMultiLine);
  57931. }
  57932. TextPropertyComponent::TextPropertyComponent (const Value& valueToControl,
  57933. const String& name,
  57934. const int maxNumChars,
  57935. const bool isMultiLine)
  57936. : PropertyComponent (name)
  57937. {
  57938. createEditor (maxNumChars, isMultiLine);
  57939. textEditor->getTextValue().referTo (valueToControl);
  57940. }
  57941. TextPropertyComponent::~TextPropertyComponent()
  57942. {
  57943. deleteAllChildren();
  57944. }
  57945. void TextPropertyComponent::setText (const String& newText)
  57946. {
  57947. textEditor->setText (newText, true);
  57948. }
  57949. const String TextPropertyComponent::getText() const
  57950. {
  57951. return textEditor->getText();
  57952. }
  57953. void TextPropertyComponent::createEditor (const int maxNumChars, const bool isMultiLine)
  57954. {
  57955. addAndMakeVisible (textEditor = new TextPropLabel (*this, maxNumChars, isMultiLine));
  57956. if (isMultiLine)
  57957. {
  57958. textEditor->setJustificationType (Justification::topLeft);
  57959. preferredHeight = 120;
  57960. }
  57961. }
  57962. void TextPropertyComponent::refresh()
  57963. {
  57964. textEditor->setText (getText(), false);
  57965. }
  57966. void TextPropertyComponent::textWasEdited()
  57967. {
  57968. const String newText (textEditor->getText());
  57969. if (getText() != newText)
  57970. setText (newText);
  57971. }
  57972. END_JUCE_NAMESPACE
  57973. /*** End of inlined file: juce_TextPropertyComponent.cpp ***/
  57974. /*** Start of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  57975. BEGIN_JUCE_NAMESPACE
  57976. class SimpleDeviceManagerInputLevelMeter : public Component,
  57977. public Timer
  57978. {
  57979. public:
  57980. SimpleDeviceManagerInputLevelMeter (AudioDeviceManager* const manager_)
  57981. : manager (manager_),
  57982. level (0)
  57983. {
  57984. startTimer (50);
  57985. manager->enableInputLevelMeasurement (true);
  57986. }
  57987. ~SimpleDeviceManagerInputLevelMeter()
  57988. {
  57989. manager->enableInputLevelMeasurement (false);
  57990. }
  57991. void timerCallback()
  57992. {
  57993. const float newLevel = (float) manager->getCurrentInputLevel();
  57994. if (std::abs (level - newLevel) > 0.005f)
  57995. {
  57996. level = newLevel;
  57997. repaint();
  57998. }
  57999. }
  58000. void paint (Graphics& g)
  58001. {
  58002. getLookAndFeel().drawLevelMeter (g, getWidth(), getHeight(),
  58003. (float) exp (log (level) / 3.0)); // (add a bit of a skew to make the level more obvious)
  58004. }
  58005. private:
  58006. AudioDeviceManager* const manager;
  58007. float level;
  58008. SimpleDeviceManagerInputLevelMeter (const SimpleDeviceManagerInputLevelMeter&);
  58009. SimpleDeviceManagerInputLevelMeter& operator= (const SimpleDeviceManagerInputLevelMeter&);
  58010. };
  58011. class AudioDeviceSelectorComponent::MidiInputSelectorComponentListBox : public ListBox,
  58012. public ListBoxModel
  58013. {
  58014. public:
  58015. MidiInputSelectorComponentListBox (AudioDeviceManager& deviceManager_,
  58016. const String& noItemsMessage_,
  58017. const int minNumber_,
  58018. const int maxNumber_)
  58019. : ListBox (String::empty, 0),
  58020. deviceManager (deviceManager_),
  58021. noItemsMessage (noItemsMessage_),
  58022. minNumber (minNumber_),
  58023. maxNumber (maxNumber_)
  58024. {
  58025. items = MidiInput::getDevices();
  58026. setModel (this);
  58027. setOutlineThickness (1);
  58028. }
  58029. ~MidiInputSelectorComponentListBox()
  58030. {
  58031. }
  58032. int getNumRows()
  58033. {
  58034. return items.size();
  58035. }
  58036. void paintListBoxItem (int row,
  58037. Graphics& g,
  58038. int width, int height,
  58039. bool rowIsSelected)
  58040. {
  58041. if (((unsigned int) row) < (unsigned int) items.size())
  58042. {
  58043. if (rowIsSelected)
  58044. g.fillAll (findColour (TextEditor::highlightColourId)
  58045. .withMultipliedAlpha (0.3f));
  58046. const String item (items [row]);
  58047. bool enabled = deviceManager.isMidiInputEnabled (item);
  58048. const int x = getTickX();
  58049. const float tickW = height * 0.75f;
  58050. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  58051. enabled, true, true, false);
  58052. g.setFont (height * 0.6f);
  58053. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  58054. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  58055. }
  58056. }
  58057. void listBoxItemClicked (int row, const MouseEvent& e)
  58058. {
  58059. selectRow (row);
  58060. if (e.x < getTickX())
  58061. flipEnablement (row);
  58062. }
  58063. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  58064. {
  58065. flipEnablement (row);
  58066. }
  58067. void returnKeyPressed (int row)
  58068. {
  58069. flipEnablement (row);
  58070. }
  58071. void paint (Graphics& g)
  58072. {
  58073. ListBox::paint (g);
  58074. if (items.size() == 0)
  58075. {
  58076. g.setColour (Colours::grey);
  58077. g.setFont (13.0f);
  58078. g.drawText (noItemsMessage,
  58079. 0, 0, getWidth(), getHeight() / 2,
  58080. Justification::centred, true);
  58081. }
  58082. }
  58083. int getBestHeight (const int preferredHeight)
  58084. {
  58085. const int extra = getOutlineThickness() * 2;
  58086. return jmax (getRowHeight() * 2 + extra,
  58087. jmin (getRowHeight() * getNumRows() + extra,
  58088. preferredHeight));
  58089. }
  58090. juce_UseDebuggingNewOperator
  58091. private:
  58092. AudioDeviceManager& deviceManager;
  58093. const String noItemsMessage;
  58094. StringArray items;
  58095. int minNumber, maxNumber;
  58096. void flipEnablement (const int row)
  58097. {
  58098. if (((unsigned int) row) < (unsigned int) items.size())
  58099. {
  58100. const String item (items [row]);
  58101. deviceManager.setMidiInputEnabled (item, ! deviceManager.isMidiInputEnabled (item));
  58102. }
  58103. }
  58104. int getTickX() const
  58105. {
  58106. return getRowHeight() + 5;
  58107. }
  58108. MidiInputSelectorComponentListBox (const MidiInputSelectorComponentListBox&);
  58109. MidiInputSelectorComponentListBox& operator= (const MidiInputSelectorComponentListBox&);
  58110. };
  58111. class AudioDeviceSettingsPanel : public Component,
  58112. public ComboBoxListener,
  58113. public ChangeListener,
  58114. public ButtonListener
  58115. {
  58116. public:
  58117. AudioDeviceSettingsPanel (AudioIODeviceType* type_,
  58118. AudioIODeviceType::DeviceSetupDetails& setup_,
  58119. const bool hideAdvancedOptionsWithButton)
  58120. : type (type_),
  58121. setup (setup_)
  58122. {
  58123. if (hideAdvancedOptionsWithButton)
  58124. {
  58125. addAndMakeVisible (showAdvancedSettingsButton = new TextButton (TRANS("Show advanced settings...")));
  58126. showAdvancedSettingsButton->addButtonListener (this);
  58127. }
  58128. type->scanForDevices();
  58129. setup.manager->addChangeListener (this);
  58130. changeListenerCallback (0);
  58131. }
  58132. ~AudioDeviceSettingsPanel()
  58133. {
  58134. setup.manager->removeChangeListener (this);
  58135. }
  58136. void resized()
  58137. {
  58138. const int lx = proportionOfWidth (0.35f);
  58139. const int w = proportionOfWidth (0.4f);
  58140. const int h = 24;
  58141. const int space = 6;
  58142. const int dh = h + space;
  58143. int y = 0;
  58144. if (outputDeviceDropDown != 0)
  58145. {
  58146. outputDeviceDropDown->setBounds (lx, y, w, h);
  58147. if (testButton != 0)
  58148. testButton->setBounds (proportionOfWidth (0.77f),
  58149. outputDeviceDropDown->getY(),
  58150. proportionOfWidth (0.18f),
  58151. h);
  58152. y += dh;
  58153. }
  58154. if (inputDeviceDropDown != 0)
  58155. {
  58156. inputDeviceDropDown->setBounds (lx, y, w, h);
  58157. inputLevelMeter->setBounds (proportionOfWidth (0.77f),
  58158. inputDeviceDropDown->getY(),
  58159. proportionOfWidth (0.18f),
  58160. h);
  58161. y += dh;
  58162. }
  58163. const int maxBoxHeight = 100;//(getHeight() - y - dh * 2) / numBoxes;
  58164. if (outputChanList != 0)
  58165. {
  58166. const int bh = outputChanList->getBestHeight (maxBoxHeight);
  58167. outputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  58168. y += bh + space;
  58169. }
  58170. if (inputChanList != 0)
  58171. {
  58172. const int bh = inputChanList->getBestHeight (maxBoxHeight);
  58173. inputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  58174. y += bh + space;
  58175. }
  58176. y += space * 2;
  58177. if (showAdvancedSettingsButton != 0)
  58178. {
  58179. showAdvancedSettingsButton->changeWidthToFitText (h);
  58180. showAdvancedSettingsButton->setTopLeftPosition (lx, y);
  58181. }
  58182. if (sampleRateDropDown != 0)
  58183. {
  58184. sampleRateDropDown->setVisible (showAdvancedSettingsButton == 0
  58185. || ! showAdvancedSettingsButton->isVisible());
  58186. sampleRateDropDown->setBounds (lx, y, w, h);
  58187. y += dh;
  58188. }
  58189. if (bufferSizeDropDown != 0)
  58190. {
  58191. bufferSizeDropDown->setVisible (showAdvancedSettingsButton == 0
  58192. || ! showAdvancedSettingsButton->isVisible());
  58193. bufferSizeDropDown->setBounds (lx, y, w, h);
  58194. y += dh;
  58195. }
  58196. if (showUIButton != 0)
  58197. {
  58198. showUIButton->setVisible (showAdvancedSettingsButton == 0
  58199. || ! showAdvancedSettingsButton->isVisible());
  58200. showUIButton->changeWidthToFitText (h);
  58201. showUIButton->setTopLeftPosition (lx, y);
  58202. }
  58203. }
  58204. void comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  58205. {
  58206. if (comboBoxThatHasChanged == 0)
  58207. return;
  58208. AudioDeviceManager::AudioDeviceSetup config;
  58209. setup.manager->getAudioDeviceSetup (config);
  58210. String error;
  58211. if (comboBoxThatHasChanged == outputDeviceDropDown
  58212. || comboBoxThatHasChanged == inputDeviceDropDown)
  58213. {
  58214. if (outputDeviceDropDown != 0)
  58215. config.outputDeviceName = outputDeviceDropDown->getSelectedId() < 0 ? String::empty
  58216. : outputDeviceDropDown->getText();
  58217. if (inputDeviceDropDown != 0)
  58218. config.inputDeviceName = inputDeviceDropDown->getSelectedId() < 0 ? String::empty
  58219. : inputDeviceDropDown->getText();
  58220. if (! type->hasSeparateInputsAndOutputs())
  58221. config.inputDeviceName = config.outputDeviceName;
  58222. if (comboBoxThatHasChanged == inputDeviceDropDown)
  58223. config.useDefaultInputChannels = true;
  58224. else
  58225. config.useDefaultOutputChannels = true;
  58226. error = setup.manager->setAudioDeviceSetup (config, true);
  58227. showCorrectDeviceName (inputDeviceDropDown, true);
  58228. showCorrectDeviceName (outputDeviceDropDown, false);
  58229. updateControlPanelButton();
  58230. resized();
  58231. }
  58232. else if (comboBoxThatHasChanged == sampleRateDropDown)
  58233. {
  58234. if (sampleRateDropDown->getSelectedId() > 0)
  58235. {
  58236. config.sampleRate = sampleRateDropDown->getSelectedId();
  58237. error = setup.manager->setAudioDeviceSetup (config, true);
  58238. }
  58239. }
  58240. else if (comboBoxThatHasChanged == bufferSizeDropDown)
  58241. {
  58242. if (bufferSizeDropDown->getSelectedId() > 0)
  58243. {
  58244. config.bufferSize = bufferSizeDropDown->getSelectedId();
  58245. error = setup.manager->setAudioDeviceSetup (config, true);
  58246. }
  58247. }
  58248. if (error.isNotEmpty())
  58249. {
  58250. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  58251. "Error when trying to open audio device!",
  58252. error);
  58253. }
  58254. }
  58255. void buttonClicked (Button* button)
  58256. {
  58257. if (button == showAdvancedSettingsButton)
  58258. {
  58259. showAdvancedSettingsButton->setVisible (false);
  58260. resized();
  58261. }
  58262. else if (button == showUIButton)
  58263. {
  58264. AudioIODevice* const device = setup.manager->getCurrentAudioDevice();
  58265. if (device != 0 && device->showControlPanel())
  58266. {
  58267. setup.manager->closeAudioDevice();
  58268. setup.manager->restartLastAudioDevice();
  58269. getTopLevelComponent()->toFront (true);
  58270. }
  58271. }
  58272. else if (button == testButton && testButton != 0)
  58273. {
  58274. setup.manager->playTestSound();
  58275. }
  58276. }
  58277. void updateControlPanelButton()
  58278. {
  58279. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58280. showUIButton = 0;
  58281. if (currentDevice != 0 && currentDevice->hasControlPanel())
  58282. {
  58283. addAndMakeVisible (showUIButton = new TextButton (TRANS ("show this device's control panel"),
  58284. TRANS ("opens the device's own control panel")));
  58285. showUIButton->addButtonListener (this);
  58286. }
  58287. resized();
  58288. }
  58289. void changeListenerCallback (void*)
  58290. {
  58291. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58292. if (setup.maxNumOutputChannels > 0 || ! type->hasSeparateInputsAndOutputs())
  58293. {
  58294. if (outputDeviceDropDown == 0)
  58295. {
  58296. outputDeviceDropDown = new ComboBox (String::empty);
  58297. outputDeviceDropDown->addListener (this);
  58298. addAndMakeVisible (outputDeviceDropDown);
  58299. outputDeviceLabel = new Label (String::empty,
  58300. type->hasSeparateInputsAndOutputs() ? TRANS ("output:")
  58301. : TRANS ("device:"));
  58302. outputDeviceLabel->attachToComponent (outputDeviceDropDown, true);
  58303. if (setup.maxNumOutputChannels > 0)
  58304. {
  58305. addAndMakeVisible (testButton = new TextButton (TRANS ("Test")));
  58306. testButton->addButtonListener (this);
  58307. }
  58308. }
  58309. addNamesToDeviceBox (*outputDeviceDropDown, false);
  58310. }
  58311. if (setup.maxNumInputChannels > 0 && type->hasSeparateInputsAndOutputs())
  58312. {
  58313. if (inputDeviceDropDown == 0)
  58314. {
  58315. inputDeviceDropDown = new ComboBox (String::empty);
  58316. inputDeviceDropDown->addListener (this);
  58317. addAndMakeVisible (inputDeviceDropDown);
  58318. inputDeviceLabel = new Label (String::empty, TRANS ("input:"));
  58319. inputDeviceLabel->attachToComponent (inputDeviceDropDown, true);
  58320. addAndMakeVisible (inputLevelMeter
  58321. = new SimpleDeviceManagerInputLevelMeter (setup.manager));
  58322. }
  58323. addNamesToDeviceBox (*inputDeviceDropDown, true);
  58324. }
  58325. updateControlPanelButton();
  58326. showCorrectDeviceName (inputDeviceDropDown, true);
  58327. showCorrectDeviceName (outputDeviceDropDown, false);
  58328. if (currentDevice != 0)
  58329. {
  58330. if (setup.maxNumOutputChannels > 0
  58331. && setup.minNumOutputChannels < setup.manager->getCurrentAudioDevice()->getOutputChannelNames().size())
  58332. {
  58333. if (outputChanList == 0)
  58334. {
  58335. addAndMakeVisible (outputChanList
  58336. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioOutputType,
  58337. TRANS ("(no audio output channels found)")));
  58338. outputChanLabel = new Label (String::empty, TRANS ("active output channels:"));
  58339. outputChanLabel->attachToComponent (outputChanList, true);
  58340. }
  58341. outputChanList->refresh();
  58342. }
  58343. else
  58344. {
  58345. outputChanLabel = 0;
  58346. outputChanList = 0;
  58347. }
  58348. if (setup.maxNumInputChannels > 0
  58349. && setup.minNumInputChannels < setup.manager->getCurrentAudioDevice()->getInputChannelNames().size())
  58350. {
  58351. if (inputChanList == 0)
  58352. {
  58353. addAndMakeVisible (inputChanList
  58354. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioInputType,
  58355. TRANS ("(no audio input channels found)")));
  58356. inputChanLabel = new Label (String::empty, TRANS ("active input channels:"));
  58357. inputChanLabel->attachToComponent (inputChanList, true);
  58358. }
  58359. inputChanList->refresh();
  58360. }
  58361. else
  58362. {
  58363. inputChanLabel = 0;
  58364. inputChanList = 0;
  58365. }
  58366. // sample rate..
  58367. {
  58368. if (sampleRateDropDown == 0)
  58369. {
  58370. addAndMakeVisible (sampleRateDropDown = new ComboBox (String::empty));
  58371. sampleRateDropDown->addListener (this);
  58372. sampleRateLabel = new Label (String::empty, TRANS ("sample rate:"));
  58373. sampleRateLabel->attachToComponent (sampleRateDropDown, true);
  58374. }
  58375. else
  58376. {
  58377. sampleRateDropDown->clear();
  58378. sampleRateDropDown->removeListener (this);
  58379. }
  58380. const int numRates = currentDevice->getNumSampleRates();
  58381. for (int i = 0; i < numRates; ++i)
  58382. {
  58383. const int rate = roundToInt (currentDevice->getSampleRate (i));
  58384. sampleRateDropDown->addItem (String (rate) + " Hz", rate);
  58385. }
  58386. sampleRateDropDown->setSelectedId (roundToInt (currentDevice->getCurrentSampleRate()), true);
  58387. sampleRateDropDown->addListener (this);
  58388. }
  58389. // buffer size
  58390. {
  58391. if (bufferSizeDropDown == 0)
  58392. {
  58393. addAndMakeVisible (bufferSizeDropDown = new ComboBox (String::empty));
  58394. bufferSizeDropDown->addListener (this);
  58395. bufferSizeLabel = new Label (String::empty, TRANS ("audio buffer size:"));
  58396. bufferSizeLabel->attachToComponent (bufferSizeDropDown, true);
  58397. }
  58398. else
  58399. {
  58400. bufferSizeDropDown->clear();
  58401. }
  58402. const int numBufferSizes = currentDevice->getNumBufferSizesAvailable();
  58403. double currentRate = currentDevice->getCurrentSampleRate();
  58404. if (currentRate == 0)
  58405. currentRate = 48000.0;
  58406. for (int i = 0; i < numBufferSizes; ++i)
  58407. {
  58408. const int bs = currentDevice->getBufferSizeSamples (i);
  58409. bufferSizeDropDown->addItem (String (bs)
  58410. + " samples ("
  58411. + String (bs * 1000.0 / currentRate, 1)
  58412. + " ms)",
  58413. bs);
  58414. }
  58415. bufferSizeDropDown->setSelectedId (currentDevice->getCurrentBufferSizeSamples(), true);
  58416. }
  58417. }
  58418. else
  58419. {
  58420. jassert (setup.manager->getCurrentAudioDevice() == 0); // not the correct device type!
  58421. sampleRateLabel = 0;
  58422. bufferSizeLabel = 0;
  58423. sampleRateDropDown = 0;
  58424. bufferSizeDropDown = 0;
  58425. if (outputDeviceDropDown != 0)
  58426. outputDeviceDropDown->setSelectedId (-1, true);
  58427. if (inputDeviceDropDown != 0)
  58428. inputDeviceDropDown->setSelectedId (-1, true);
  58429. }
  58430. resized();
  58431. setSize (getWidth(), getLowestY() + 4);
  58432. }
  58433. private:
  58434. AudioIODeviceType* const type;
  58435. const AudioIODeviceType::DeviceSetupDetails setup;
  58436. ScopedPointer<ComboBox> outputDeviceDropDown, inputDeviceDropDown, sampleRateDropDown, bufferSizeDropDown;
  58437. ScopedPointer<Label> outputDeviceLabel, inputDeviceLabel, sampleRateLabel, bufferSizeLabel, inputChanLabel, outputChanLabel;
  58438. ScopedPointer<TextButton> testButton;
  58439. ScopedPointer<Component> inputLevelMeter;
  58440. ScopedPointer<TextButton> showUIButton, showAdvancedSettingsButton;
  58441. void showCorrectDeviceName (ComboBox* const box, const bool isInput)
  58442. {
  58443. if (box != 0)
  58444. {
  58445. AudioIODevice* const currentDevice = dynamic_cast <AudioIODevice*> (setup.manager->getCurrentAudioDevice());
  58446. const int index = type->getIndexOfDevice (currentDevice, isInput);
  58447. box->setSelectedId (index + 1, true);
  58448. if (testButton != 0 && ! isInput)
  58449. testButton->setEnabled (index >= 0);
  58450. }
  58451. }
  58452. void addNamesToDeviceBox (ComboBox& combo, bool isInputs)
  58453. {
  58454. const StringArray devs (type->getDeviceNames (isInputs));
  58455. combo.clear (true);
  58456. for (int i = 0; i < devs.size(); ++i)
  58457. combo.addItem (devs[i], i + 1);
  58458. combo.addItem (TRANS("<< none >>"), -1);
  58459. combo.setSelectedId (-1, true);
  58460. }
  58461. int getLowestY() const
  58462. {
  58463. int y = 0;
  58464. for (int i = getNumChildComponents(); --i >= 0;)
  58465. y = jmax (y, getChildComponent (i)->getBottom());
  58466. return y;
  58467. }
  58468. public:
  58469. class ChannelSelectorListBox : public ListBox,
  58470. public ListBoxModel
  58471. {
  58472. public:
  58473. enum BoxType
  58474. {
  58475. audioInputType,
  58476. audioOutputType
  58477. };
  58478. ChannelSelectorListBox (const AudioIODeviceType::DeviceSetupDetails& setup_,
  58479. const BoxType type_,
  58480. const String& noItemsMessage_)
  58481. : ListBox (String::empty, 0),
  58482. setup (setup_),
  58483. type (type_),
  58484. noItemsMessage (noItemsMessage_)
  58485. {
  58486. refresh();
  58487. setModel (this);
  58488. setOutlineThickness (1);
  58489. }
  58490. ~ChannelSelectorListBox()
  58491. {
  58492. }
  58493. void refresh()
  58494. {
  58495. items.clear();
  58496. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58497. if (currentDevice != 0)
  58498. {
  58499. if (type == audioInputType)
  58500. items = currentDevice->getInputChannelNames();
  58501. else if (type == audioOutputType)
  58502. items = currentDevice->getOutputChannelNames();
  58503. if (setup.useStereoPairs)
  58504. {
  58505. StringArray pairs;
  58506. for (int i = 0; i < items.size(); i += 2)
  58507. {
  58508. const String name (items[i]);
  58509. const String name2 (items[i + 1]);
  58510. String commonBit;
  58511. for (int j = 0; j < name.length(); ++j)
  58512. if (name.substring (0, j).equalsIgnoreCase (name2.substring (0, j)))
  58513. commonBit = name.substring (0, j);
  58514. // Make sure we only split the name at a space, because otherwise, things
  58515. // like "input 11" + "input 12" would become "input 11 + 2"
  58516. while (commonBit.isNotEmpty() && ! CharacterFunctions::isWhitespace (commonBit.getLastCharacter()))
  58517. commonBit = commonBit.dropLastCharacters (1);
  58518. pairs.add (name.trim() + " + " + name2.substring (commonBit.length()).trim());
  58519. }
  58520. items = pairs;
  58521. }
  58522. }
  58523. updateContent();
  58524. repaint();
  58525. }
  58526. int getNumRows()
  58527. {
  58528. return items.size();
  58529. }
  58530. void paintListBoxItem (int row,
  58531. Graphics& g,
  58532. int width, int height,
  58533. bool rowIsSelected)
  58534. {
  58535. if (((unsigned int) row) < (unsigned int) items.size())
  58536. {
  58537. if (rowIsSelected)
  58538. g.fillAll (findColour (TextEditor::highlightColourId)
  58539. .withMultipliedAlpha (0.3f));
  58540. const String item (items [row]);
  58541. bool enabled = false;
  58542. AudioDeviceManager::AudioDeviceSetup config;
  58543. setup.manager->getAudioDeviceSetup (config);
  58544. if (setup.useStereoPairs)
  58545. {
  58546. if (type == audioInputType)
  58547. enabled = config.inputChannels [row * 2] || config.inputChannels [row * 2 + 1];
  58548. else if (type == audioOutputType)
  58549. enabled = config.outputChannels [row * 2] || config.outputChannels [row * 2 + 1];
  58550. }
  58551. else
  58552. {
  58553. if (type == audioInputType)
  58554. enabled = config.inputChannels [row];
  58555. else if (type == audioOutputType)
  58556. enabled = config.outputChannels [row];
  58557. }
  58558. const int x = getTickX();
  58559. const float tickW = height * 0.75f;
  58560. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  58561. enabled, true, true, false);
  58562. g.setFont (height * 0.6f);
  58563. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  58564. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  58565. }
  58566. }
  58567. void listBoxItemClicked (int row, const MouseEvent& e)
  58568. {
  58569. selectRow (row);
  58570. if (e.x < getTickX())
  58571. flipEnablement (row);
  58572. }
  58573. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  58574. {
  58575. flipEnablement (row);
  58576. }
  58577. void returnKeyPressed (int row)
  58578. {
  58579. flipEnablement (row);
  58580. }
  58581. void paint (Graphics& g)
  58582. {
  58583. ListBox::paint (g);
  58584. if (items.size() == 0)
  58585. {
  58586. g.setColour (Colours::grey);
  58587. g.setFont (13.0f);
  58588. g.drawText (noItemsMessage,
  58589. 0, 0, getWidth(), getHeight() / 2,
  58590. Justification::centred, true);
  58591. }
  58592. }
  58593. int getBestHeight (int maxHeight)
  58594. {
  58595. return getRowHeight() * jlimit (2, jmax (2, maxHeight / getRowHeight()),
  58596. getNumRows())
  58597. + getOutlineThickness() * 2;
  58598. }
  58599. juce_UseDebuggingNewOperator
  58600. private:
  58601. const AudioIODeviceType::DeviceSetupDetails setup;
  58602. const BoxType type;
  58603. const String noItemsMessage;
  58604. StringArray items;
  58605. void flipEnablement (const int row)
  58606. {
  58607. jassert (type == audioInputType || type == audioOutputType);
  58608. if (((unsigned int) row) < (unsigned int) items.size())
  58609. {
  58610. AudioDeviceManager::AudioDeviceSetup config;
  58611. setup.manager->getAudioDeviceSetup (config);
  58612. if (setup.useStereoPairs)
  58613. {
  58614. BigInteger bits;
  58615. BigInteger& original = (type == audioInputType ? config.inputChannels
  58616. : config.outputChannels);
  58617. int i;
  58618. for (i = 0; i < 256; i += 2)
  58619. bits.setBit (i / 2, original [i] || original [i + 1]);
  58620. if (type == audioInputType)
  58621. {
  58622. config.useDefaultInputChannels = false;
  58623. flipBit (bits, row, setup.minNumInputChannels / 2, setup.maxNumInputChannels / 2);
  58624. }
  58625. else
  58626. {
  58627. config.useDefaultOutputChannels = false;
  58628. flipBit (bits, row, setup.minNumOutputChannels / 2, setup.maxNumOutputChannels / 2);
  58629. }
  58630. for (i = 0; i < 256; ++i)
  58631. original.setBit (i, bits [i / 2]);
  58632. }
  58633. else
  58634. {
  58635. if (type == audioInputType)
  58636. {
  58637. config.useDefaultInputChannels = false;
  58638. flipBit (config.inputChannels, row, setup.minNumInputChannels, setup.maxNumInputChannels);
  58639. }
  58640. else
  58641. {
  58642. config.useDefaultOutputChannels = false;
  58643. flipBit (config.outputChannels, row, setup.minNumOutputChannels, setup.maxNumOutputChannels);
  58644. }
  58645. }
  58646. String error (setup.manager->setAudioDeviceSetup (config, true));
  58647. if (! error.isEmpty())
  58648. {
  58649. //xxx
  58650. }
  58651. }
  58652. }
  58653. static void flipBit (BigInteger& chans, int index, int minNumber, int maxNumber)
  58654. {
  58655. const int numActive = chans.countNumberOfSetBits();
  58656. if (chans [index])
  58657. {
  58658. if (numActive > minNumber)
  58659. chans.setBit (index, false);
  58660. }
  58661. else
  58662. {
  58663. if (numActive >= maxNumber)
  58664. {
  58665. const int firstActiveChan = chans.findNextSetBit();
  58666. chans.setBit (index > firstActiveChan
  58667. ? firstActiveChan : chans.getHighestBit(),
  58668. false);
  58669. }
  58670. chans.setBit (index, true);
  58671. }
  58672. }
  58673. int getTickX() const
  58674. {
  58675. return getRowHeight() + 5;
  58676. }
  58677. ChannelSelectorListBox (const ChannelSelectorListBox&);
  58678. ChannelSelectorListBox& operator= (const ChannelSelectorListBox&);
  58679. };
  58680. private:
  58681. ScopedPointer<ChannelSelectorListBox> inputChanList, outputChanList;
  58682. AudioDeviceSettingsPanel (const AudioDeviceSettingsPanel&);
  58683. AudioDeviceSettingsPanel& operator= (const AudioDeviceSettingsPanel&);
  58684. };
  58685. AudioDeviceSelectorComponent::AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager_,
  58686. const int minInputChannels_,
  58687. const int maxInputChannels_,
  58688. const int minOutputChannels_,
  58689. const int maxOutputChannels_,
  58690. const bool showMidiInputOptions,
  58691. const bool showMidiOutputSelector,
  58692. const bool showChannelsAsStereoPairs_,
  58693. const bool hideAdvancedOptionsWithButton_)
  58694. : deviceManager (deviceManager_),
  58695. deviceTypeDropDown (0),
  58696. deviceTypeDropDownLabel (0),
  58697. minOutputChannels (minOutputChannels_),
  58698. maxOutputChannels (maxOutputChannels_),
  58699. minInputChannels (minInputChannels_),
  58700. maxInputChannels (maxInputChannels_),
  58701. showChannelsAsStereoPairs (showChannelsAsStereoPairs_),
  58702. hideAdvancedOptionsWithButton (hideAdvancedOptionsWithButton_)
  58703. {
  58704. jassert (minOutputChannels >= 0 && minOutputChannels <= maxOutputChannels);
  58705. jassert (minInputChannels >= 0 && minInputChannels <= maxInputChannels);
  58706. if (deviceManager_.getAvailableDeviceTypes().size() > 1)
  58707. {
  58708. deviceTypeDropDown = new ComboBox (String::empty);
  58709. for (int i = 0; i < deviceManager_.getAvailableDeviceTypes().size(); ++i)
  58710. {
  58711. deviceTypeDropDown
  58712. ->addItem (deviceManager_.getAvailableDeviceTypes().getUnchecked(i)->getTypeName(),
  58713. i + 1);
  58714. }
  58715. addAndMakeVisible (deviceTypeDropDown);
  58716. deviceTypeDropDown->addListener (this);
  58717. deviceTypeDropDownLabel = new Label (String::empty, TRANS ("audio device type:"));
  58718. deviceTypeDropDownLabel->setJustificationType (Justification::centredRight);
  58719. deviceTypeDropDownLabel->attachToComponent (deviceTypeDropDown, true);
  58720. }
  58721. if (showMidiInputOptions)
  58722. {
  58723. addAndMakeVisible (midiInputsList
  58724. = new MidiInputSelectorComponentListBox (deviceManager,
  58725. TRANS("(no midi inputs available)"),
  58726. 0, 0));
  58727. midiInputsLabel = new Label (String::empty, TRANS ("active midi inputs:"));
  58728. midiInputsLabel->setJustificationType (Justification::topRight);
  58729. midiInputsLabel->attachToComponent (midiInputsList, true);
  58730. }
  58731. else
  58732. {
  58733. midiInputsList = 0;
  58734. midiInputsLabel = 0;
  58735. }
  58736. if (showMidiOutputSelector)
  58737. {
  58738. addAndMakeVisible (midiOutputSelector = new ComboBox (String::empty));
  58739. midiOutputSelector->addListener (this);
  58740. midiOutputLabel = new Label ("lm", TRANS("Midi Output:"));
  58741. midiOutputLabel->attachToComponent (midiOutputSelector, true);
  58742. }
  58743. else
  58744. {
  58745. midiOutputSelector = 0;
  58746. midiOutputLabel = 0;
  58747. }
  58748. deviceManager_.addChangeListener (this);
  58749. changeListenerCallback (0);
  58750. }
  58751. AudioDeviceSelectorComponent::~AudioDeviceSelectorComponent()
  58752. {
  58753. deviceManager.removeChangeListener (this);
  58754. }
  58755. void AudioDeviceSelectorComponent::resized()
  58756. {
  58757. const int lx = proportionOfWidth (0.35f);
  58758. const int w = proportionOfWidth (0.4f);
  58759. const int h = 24;
  58760. const int space = 6;
  58761. const int dh = h + space;
  58762. int y = 15;
  58763. if (deviceTypeDropDown != 0)
  58764. {
  58765. deviceTypeDropDown->setBounds (lx, y, proportionOfWidth (0.3f), h);
  58766. y += dh + space * 2;
  58767. }
  58768. if (audioDeviceSettingsComp != 0)
  58769. {
  58770. audioDeviceSettingsComp->setBounds (0, y, getWidth(), audioDeviceSettingsComp->getHeight());
  58771. y += audioDeviceSettingsComp->getHeight() + space;
  58772. }
  58773. if (midiInputsList != 0)
  58774. {
  58775. const int bh = midiInputsList->getBestHeight (jmin (h * 8, getHeight() - y - space - h));
  58776. midiInputsList->setBounds (lx, y, w, bh);
  58777. y += bh + space;
  58778. }
  58779. if (midiOutputSelector != 0)
  58780. midiOutputSelector->setBounds (lx, y, w, h);
  58781. }
  58782. void AudioDeviceSelectorComponent::childBoundsChanged (Component* child)
  58783. {
  58784. if (child == audioDeviceSettingsComp)
  58785. resized();
  58786. }
  58787. void AudioDeviceSelectorComponent::buttonClicked (Button*)
  58788. {
  58789. AudioIODevice* const device = deviceManager.getCurrentAudioDevice();
  58790. if (device != 0 && device->hasControlPanel())
  58791. {
  58792. if (device->showControlPanel())
  58793. deviceManager.restartLastAudioDevice();
  58794. getTopLevelComponent()->toFront (true);
  58795. }
  58796. }
  58797. void AudioDeviceSelectorComponent::comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  58798. {
  58799. if (comboBoxThatHasChanged == deviceTypeDropDown)
  58800. {
  58801. AudioIODeviceType* const type = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown->getSelectedId() - 1];
  58802. if (type != 0)
  58803. {
  58804. audioDeviceSettingsComp = 0;
  58805. deviceManager.setCurrentAudioDeviceType (type->getTypeName(), true);
  58806. changeListenerCallback (0); // needed in case the type hasn't actally changed
  58807. }
  58808. }
  58809. else if (comboBoxThatHasChanged == midiOutputSelector)
  58810. {
  58811. deviceManager.setDefaultMidiOutput (midiOutputSelector->getText());
  58812. }
  58813. }
  58814. void AudioDeviceSelectorComponent::changeListenerCallback (void*)
  58815. {
  58816. if (deviceTypeDropDown != 0)
  58817. {
  58818. deviceTypeDropDown->setText (deviceManager.getCurrentAudioDeviceType(), false);
  58819. }
  58820. if (audioDeviceSettingsComp == 0
  58821. || audioDeviceSettingsCompType != deviceManager.getCurrentAudioDeviceType())
  58822. {
  58823. audioDeviceSettingsCompType = deviceManager.getCurrentAudioDeviceType();
  58824. audioDeviceSettingsComp = 0;
  58825. AudioIODeviceType* const type
  58826. = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown == 0
  58827. ? 0 : deviceTypeDropDown->getSelectedId() - 1];
  58828. if (type != 0)
  58829. {
  58830. AudioIODeviceType::DeviceSetupDetails details;
  58831. details.manager = &deviceManager;
  58832. details.minNumInputChannels = minInputChannels;
  58833. details.maxNumInputChannels = maxInputChannels;
  58834. details.minNumOutputChannels = minOutputChannels;
  58835. details.maxNumOutputChannels = maxOutputChannels;
  58836. details.useStereoPairs = showChannelsAsStereoPairs;
  58837. audioDeviceSettingsComp = new AudioDeviceSettingsPanel (type, details, hideAdvancedOptionsWithButton);
  58838. if (audioDeviceSettingsComp != 0)
  58839. {
  58840. addAndMakeVisible (audioDeviceSettingsComp);
  58841. audioDeviceSettingsComp->resized();
  58842. }
  58843. }
  58844. }
  58845. if (midiInputsList != 0)
  58846. {
  58847. midiInputsList->updateContent();
  58848. midiInputsList->repaint();
  58849. }
  58850. if (midiOutputSelector != 0)
  58851. {
  58852. midiOutputSelector->clear();
  58853. const StringArray midiOuts (MidiOutput::getDevices());
  58854. midiOutputSelector->addItem (TRANS("<< none >>"), -1);
  58855. midiOutputSelector->addSeparator();
  58856. for (int i = 0; i < midiOuts.size(); ++i)
  58857. midiOutputSelector->addItem (midiOuts[i], i + 1);
  58858. int current = -1;
  58859. if (deviceManager.getDefaultMidiOutput() != 0)
  58860. current = 1 + midiOuts.indexOf (deviceManager.getDefaultMidiOutputName());
  58861. midiOutputSelector->setSelectedId (current, true);
  58862. }
  58863. resized();
  58864. }
  58865. END_JUCE_NAMESPACE
  58866. /*** End of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  58867. /*** Start of inlined file: juce_BubbleComponent.cpp ***/
  58868. BEGIN_JUCE_NAMESPACE
  58869. BubbleComponent::BubbleComponent()
  58870. : side (0),
  58871. allowablePlacements (above | below | left | right),
  58872. arrowTipX (0.0f),
  58873. arrowTipY (0.0f)
  58874. {
  58875. setInterceptsMouseClicks (false, false);
  58876. shadow.setShadowProperties (5.0f, 0.35f, 0, 0);
  58877. setComponentEffect (&shadow);
  58878. }
  58879. BubbleComponent::~BubbleComponent()
  58880. {
  58881. }
  58882. void BubbleComponent::paint (Graphics& g)
  58883. {
  58884. int x = content.getX();
  58885. int y = content.getY();
  58886. int w = content.getWidth();
  58887. int h = content.getHeight();
  58888. int cw, ch;
  58889. getContentSize (cw, ch);
  58890. if (side == 3)
  58891. x += w - cw;
  58892. else if (side != 1)
  58893. x += (w - cw) / 2;
  58894. w = cw;
  58895. if (side == 2)
  58896. y += h - ch;
  58897. else if (side != 0)
  58898. y += (h - ch) / 2;
  58899. h = ch;
  58900. getLookAndFeel().drawBubble (g, arrowTipX, arrowTipY,
  58901. (float) x, (float) y,
  58902. (float) w, (float) h);
  58903. const int cx = x + (w - cw) / 2;
  58904. const int cy = y + (h - ch) / 2;
  58905. const int indent = 3;
  58906. g.setOrigin (cx + indent, cy + indent);
  58907. g.reduceClipRegion (0, 0, cw - indent * 2, ch - indent * 2);
  58908. paintContent (g, cw - indent * 2, ch - indent * 2);
  58909. }
  58910. void BubbleComponent::setAllowedPlacement (const int newPlacement)
  58911. {
  58912. allowablePlacements = newPlacement;
  58913. }
  58914. void BubbleComponent::setPosition (Component* componentToPointTo)
  58915. {
  58916. jassert (componentToPointTo->isValidComponent());
  58917. Point<int> pos;
  58918. if (getParentComponent() != 0)
  58919. pos = componentToPointTo->relativePositionToOtherComponent (getParentComponent(), pos);
  58920. else
  58921. pos = componentToPointTo->relativePositionToGlobal (pos);
  58922. setPosition (Rectangle<int> (pos.getX(), pos.getY(), componentToPointTo->getWidth(), componentToPointTo->getHeight()));
  58923. }
  58924. void BubbleComponent::setPosition (const int arrowTipX_,
  58925. const int arrowTipY_)
  58926. {
  58927. setPosition (Rectangle<int> (arrowTipX_, arrowTipY_, 1, 1));
  58928. }
  58929. void BubbleComponent::setPosition (const Rectangle<int>& rectangleToPointTo)
  58930. {
  58931. Rectangle<int> availableSpace;
  58932. if (getParentComponent() != 0)
  58933. {
  58934. availableSpace.setSize (getParentComponent()->getWidth(),
  58935. getParentComponent()->getHeight());
  58936. }
  58937. else
  58938. {
  58939. availableSpace = getParentMonitorArea();
  58940. }
  58941. int x = 0;
  58942. int y = 0;
  58943. int w = 150;
  58944. int h = 30;
  58945. getContentSize (w, h);
  58946. w += 30;
  58947. h += 30;
  58948. const float edgeIndent = 2.0f;
  58949. const int arrowLength = jmin (10, h / 3, w / 3);
  58950. int spaceAbove = ((allowablePlacements & above) != 0) ? jmax (0, rectangleToPointTo.getY() - availableSpace.getY()) : -1;
  58951. int spaceBelow = ((allowablePlacements & below) != 0) ? jmax (0, availableSpace.getBottom() - rectangleToPointTo.getBottom()) : -1;
  58952. int spaceLeft = ((allowablePlacements & left) != 0) ? jmax (0, rectangleToPointTo.getX() - availableSpace.getX()) : -1;
  58953. int spaceRight = ((allowablePlacements & right) != 0) ? jmax (0, availableSpace.getRight() - rectangleToPointTo.getRight()) : -1;
  58954. // look at whether the component is elongated, and if so, try to position next to its longer dimension.
  58955. if (rectangleToPointTo.getWidth() > rectangleToPointTo.getHeight() * 2
  58956. && (spaceAbove > h + 20 || spaceBelow > h + 20))
  58957. {
  58958. spaceLeft = spaceRight = 0;
  58959. }
  58960. else if (rectangleToPointTo.getWidth() < rectangleToPointTo.getHeight() / 2
  58961. && (spaceLeft > w + 20 || spaceRight > w + 20))
  58962. {
  58963. spaceAbove = spaceBelow = 0;
  58964. }
  58965. if (jmax (spaceAbove, spaceBelow) >= jmax (spaceLeft, spaceRight))
  58966. {
  58967. x = rectangleToPointTo.getX() + (rectangleToPointTo.getWidth() - w) / 2;
  58968. arrowTipX = w * 0.5f;
  58969. content.setSize (w, h - arrowLength);
  58970. if (spaceAbove >= spaceBelow)
  58971. {
  58972. // above
  58973. y = rectangleToPointTo.getY() - h;
  58974. content.setPosition (0, 0);
  58975. arrowTipY = h - edgeIndent;
  58976. side = 2;
  58977. }
  58978. else
  58979. {
  58980. // below
  58981. y = rectangleToPointTo.getBottom();
  58982. content.setPosition (0, arrowLength);
  58983. arrowTipY = edgeIndent;
  58984. side = 0;
  58985. }
  58986. }
  58987. else
  58988. {
  58989. y = rectangleToPointTo.getY() + (rectangleToPointTo.getHeight() - h) / 2;
  58990. arrowTipY = h * 0.5f;
  58991. content.setSize (w - arrowLength, h);
  58992. if (spaceLeft > spaceRight)
  58993. {
  58994. // on the left
  58995. x = rectangleToPointTo.getX() - w;
  58996. content.setPosition (0, 0);
  58997. arrowTipX = w - edgeIndent;
  58998. side = 3;
  58999. }
  59000. else
  59001. {
  59002. // on the right
  59003. x = rectangleToPointTo.getRight();
  59004. content.setPosition (arrowLength, 0);
  59005. arrowTipX = edgeIndent;
  59006. side = 1;
  59007. }
  59008. }
  59009. setBounds (x, y, w, h);
  59010. }
  59011. END_JUCE_NAMESPACE
  59012. /*** End of inlined file: juce_BubbleComponent.cpp ***/
  59013. /*** Start of inlined file: juce_BubbleMessageComponent.cpp ***/
  59014. BEGIN_JUCE_NAMESPACE
  59015. BubbleMessageComponent::BubbleMessageComponent (int fadeOutLengthMs)
  59016. : fadeOutLength (fadeOutLengthMs),
  59017. deleteAfterUse (false)
  59018. {
  59019. }
  59020. BubbleMessageComponent::~BubbleMessageComponent()
  59021. {
  59022. fadeOutComponent (fadeOutLength);
  59023. }
  59024. void BubbleMessageComponent::showAt (int x, int y,
  59025. const String& text,
  59026. const int numMillisecondsBeforeRemoving,
  59027. const bool removeWhenMouseClicked,
  59028. const bool deleteSelfAfterUse)
  59029. {
  59030. textLayout.clear();
  59031. textLayout.setText (text, Font (14.0f));
  59032. textLayout.layout (256, Justification::centredLeft, true);
  59033. setPosition (x, y);
  59034. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  59035. }
  59036. void BubbleMessageComponent::showAt (Component* const component,
  59037. const String& text,
  59038. const int numMillisecondsBeforeRemoving,
  59039. const bool removeWhenMouseClicked,
  59040. const bool deleteSelfAfterUse)
  59041. {
  59042. textLayout.clear();
  59043. textLayout.setText (text, Font (14.0f));
  59044. textLayout.layout (256, Justification::centredLeft, true);
  59045. setPosition (component);
  59046. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  59047. }
  59048. void BubbleMessageComponent::init (const int numMillisecondsBeforeRemoving,
  59049. const bool removeWhenMouseClicked,
  59050. const bool deleteSelfAfterUse)
  59051. {
  59052. setVisible (true);
  59053. deleteAfterUse = deleteSelfAfterUse;
  59054. if (numMillisecondsBeforeRemoving > 0)
  59055. expiryTime = Time::getMillisecondCounter() + numMillisecondsBeforeRemoving;
  59056. else
  59057. expiryTime = 0;
  59058. startTimer (77);
  59059. mouseClickCounter = Desktop::getInstance().getMouseButtonClickCounter();
  59060. if (! (removeWhenMouseClicked && isShowing()))
  59061. mouseClickCounter += 0xfffff;
  59062. repaint();
  59063. }
  59064. void BubbleMessageComponent::getContentSize (int& w, int& h)
  59065. {
  59066. w = textLayout.getWidth() + 16;
  59067. h = textLayout.getHeight() + 16;
  59068. }
  59069. void BubbleMessageComponent::paintContent (Graphics& g, int w, int h)
  59070. {
  59071. g.setColour (findColour (TooltipWindow::textColourId));
  59072. textLayout.drawWithin (g, 0, 0, w, h, Justification::centred);
  59073. }
  59074. void BubbleMessageComponent::timerCallback()
  59075. {
  59076. if (Desktop::getInstance().getMouseButtonClickCounter() > mouseClickCounter)
  59077. {
  59078. stopTimer();
  59079. setVisible (false);
  59080. if (deleteAfterUse)
  59081. delete this;
  59082. }
  59083. else if (expiryTime != 0 && Time::getMillisecondCounter() > expiryTime)
  59084. {
  59085. stopTimer();
  59086. fadeOutComponent (fadeOutLength);
  59087. if (deleteAfterUse)
  59088. delete this;
  59089. }
  59090. }
  59091. END_JUCE_NAMESPACE
  59092. /*** End of inlined file: juce_BubbleMessageComponent.cpp ***/
  59093. /*** Start of inlined file: juce_ColourSelector.cpp ***/
  59094. BEGIN_JUCE_NAMESPACE
  59095. class ColourComponentSlider : public Slider
  59096. {
  59097. public:
  59098. ColourComponentSlider (const String& name)
  59099. : Slider (name)
  59100. {
  59101. setRange (0.0, 255.0, 1.0);
  59102. }
  59103. ~ColourComponentSlider()
  59104. {
  59105. }
  59106. const String getTextFromValue (double value)
  59107. {
  59108. return String::toHexString ((int) value).toUpperCase().paddedLeft ('0', 2);
  59109. }
  59110. double getValueFromText (const String& text)
  59111. {
  59112. return (double) text.getHexValue32();
  59113. }
  59114. private:
  59115. ColourComponentSlider (const ColourComponentSlider&);
  59116. ColourComponentSlider& operator= (const ColourComponentSlider&);
  59117. };
  59118. class ColourSpaceMarker : public Component
  59119. {
  59120. public:
  59121. ColourSpaceMarker()
  59122. {
  59123. setInterceptsMouseClicks (false, false);
  59124. }
  59125. ~ColourSpaceMarker()
  59126. {
  59127. }
  59128. void paint (Graphics& g)
  59129. {
  59130. g.setColour (Colour::greyLevel (0.1f));
  59131. g.drawEllipse (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 1.0f);
  59132. g.setColour (Colour::greyLevel (0.9f));
  59133. g.drawEllipse (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, 1.0f);
  59134. }
  59135. private:
  59136. ColourSpaceMarker (const ColourSpaceMarker&);
  59137. ColourSpaceMarker& operator= (const ColourSpaceMarker&);
  59138. };
  59139. class ColourSelector::ColourSpaceView : public Component
  59140. {
  59141. public:
  59142. ColourSpaceView (ColourSelector* owner_,
  59143. float& h_, float& s_, float& v_,
  59144. const int edgeSize)
  59145. : owner (owner_),
  59146. h (h_), s (s_), v (v_),
  59147. lastHue (0.0f),
  59148. edge (edgeSize)
  59149. {
  59150. addAndMakeVisible (marker = new ColourSpaceMarker());
  59151. setMouseCursor (MouseCursor::CrosshairCursor);
  59152. }
  59153. ~ColourSpaceView()
  59154. {
  59155. deleteAllChildren();
  59156. }
  59157. void paint (Graphics& g)
  59158. {
  59159. if (colours.isNull())
  59160. {
  59161. const int width = getWidth() / 2;
  59162. const int height = getHeight() / 2;
  59163. colours = Image (Image::RGB, width, height, false);
  59164. Image::BitmapData pixels (colours, 0, 0, width, height, true);
  59165. for (int y = 0; y < height; ++y)
  59166. {
  59167. const float val = 1.0f - y / (float) height;
  59168. for (int x = 0; x < width; ++x)
  59169. {
  59170. const float sat = x / (float) width;
  59171. pixels.setPixelColour (x, y, Colour (h, sat, val, 1.0f));
  59172. }
  59173. }
  59174. }
  59175. g.setOpacity (1.0f);
  59176. g.drawImage (colours, edge, edge, getWidth() - edge * 2, getHeight() - edge * 2,
  59177. 0, 0, colours.getWidth(), colours.getHeight());
  59178. }
  59179. void mouseDown (const MouseEvent& e)
  59180. {
  59181. mouseDrag (e);
  59182. }
  59183. void mouseDrag (const MouseEvent& e)
  59184. {
  59185. const float sat = (e.x - edge) / (float) (getWidth() - edge * 2);
  59186. const float val = 1.0f - (e.y - edge) / (float) (getHeight() - edge * 2);
  59187. owner->setSV (sat, val);
  59188. }
  59189. void updateIfNeeded()
  59190. {
  59191. if (lastHue != h)
  59192. {
  59193. lastHue = h;
  59194. colours = Image();
  59195. repaint();
  59196. }
  59197. updateMarker();
  59198. }
  59199. void resized()
  59200. {
  59201. colours = Image();
  59202. updateMarker();
  59203. }
  59204. private:
  59205. ColourSelector* const owner;
  59206. float& h;
  59207. float& s;
  59208. float& v;
  59209. float lastHue;
  59210. ColourSpaceMarker* marker;
  59211. const int edge;
  59212. Image colours;
  59213. void updateMarker() const
  59214. {
  59215. marker->setBounds (roundToInt ((getWidth() - edge * 2) * s),
  59216. roundToInt ((getHeight() - edge * 2) * (1.0f - v)),
  59217. edge * 2, edge * 2);
  59218. }
  59219. ColourSpaceView (const ColourSpaceView&);
  59220. ColourSpaceView& operator= (const ColourSpaceView&);
  59221. };
  59222. class HueSelectorMarker : public Component
  59223. {
  59224. public:
  59225. HueSelectorMarker()
  59226. {
  59227. setInterceptsMouseClicks (false, false);
  59228. }
  59229. ~HueSelectorMarker()
  59230. {
  59231. }
  59232. void paint (Graphics& g)
  59233. {
  59234. Path p;
  59235. p.addTriangle (1.0f, 1.0f,
  59236. getWidth() * 0.3f, getHeight() * 0.5f,
  59237. 1.0f, getHeight() - 1.0f);
  59238. p.addTriangle (getWidth() - 1.0f, 1.0f,
  59239. getWidth() * 0.7f, getHeight() * 0.5f,
  59240. getWidth() - 1.0f, getHeight() - 1.0f);
  59241. g.setColour (Colours::white.withAlpha (0.75f));
  59242. g.fillPath (p);
  59243. g.setColour (Colours::black.withAlpha (0.75f));
  59244. g.strokePath (p, PathStrokeType (1.2f));
  59245. }
  59246. private:
  59247. HueSelectorMarker (const HueSelectorMarker&);
  59248. HueSelectorMarker& operator= (const HueSelectorMarker&);
  59249. };
  59250. class ColourSelector::HueSelectorComp : public Component
  59251. {
  59252. public:
  59253. HueSelectorComp (ColourSelector* owner_,
  59254. float& h_, float& s_, float& v_,
  59255. const int edgeSize)
  59256. : owner (owner_),
  59257. h (h_), s (s_), v (v_),
  59258. lastHue (0.0f),
  59259. edge (edgeSize)
  59260. {
  59261. addAndMakeVisible (marker = new HueSelectorMarker());
  59262. }
  59263. ~HueSelectorComp()
  59264. {
  59265. deleteAllChildren();
  59266. }
  59267. void paint (Graphics& g)
  59268. {
  59269. const float yScale = 1.0f / (getHeight() - edge * 2);
  59270. const Rectangle<int> clip (g.getClipBounds());
  59271. for (int y = jmin (clip.getBottom(), getHeight() - edge); --y >= jmax (edge, clip.getY());)
  59272. {
  59273. g.setColour (Colour ((y - edge) * yScale, 1.0f, 1.0f, 1.0f));
  59274. g.fillRect (edge, y, getWidth() - edge * 2, 1);
  59275. }
  59276. }
  59277. void resized()
  59278. {
  59279. marker->setBounds (0, roundToInt ((getHeight() - edge * 2) * h),
  59280. getWidth(), edge * 2);
  59281. }
  59282. void mouseDown (const MouseEvent& e)
  59283. {
  59284. mouseDrag (e);
  59285. }
  59286. void mouseDrag (const MouseEvent& e)
  59287. {
  59288. const float hue = (e.y - edge) / (float) (getHeight() - edge * 2);
  59289. owner->setHue (hue);
  59290. }
  59291. void updateIfNeeded()
  59292. {
  59293. resized();
  59294. }
  59295. private:
  59296. ColourSelector* const owner;
  59297. float& h;
  59298. float& s;
  59299. float& v;
  59300. float lastHue;
  59301. HueSelectorMarker* marker;
  59302. const int edge;
  59303. HueSelectorComp (const HueSelectorComp&);
  59304. HueSelectorComp& operator= (const HueSelectorComp&);
  59305. };
  59306. class ColourSelector::SwatchComponent : public Component
  59307. {
  59308. public:
  59309. SwatchComponent (ColourSelector* owner_, int index_)
  59310. : owner (owner_),
  59311. index (index_)
  59312. {
  59313. }
  59314. ~SwatchComponent()
  59315. {
  59316. }
  59317. void paint (Graphics& g)
  59318. {
  59319. const Colour colour (owner->getSwatchColour (index));
  59320. g.fillCheckerBoard (0, 0, getWidth(), getHeight(),
  59321. 6, 6,
  59322. Colour (0xffdddddd).overlaidWith (colour),
  59323. Colour (0xffffffff).overlaidWith (colour));
  59324. }
  59325. void mouseDown (const MouseEvent&)
  59326. {
  59327. PopupMenu m;
  59328. m.addItem (1, TRANS("Use this swatch as the current colour"));
  59329. m.addSeparator();
  59330. m.addItem (2, TRANS("Set this swatch to the current colour"));
  59331. const int r = m.showAt (this);
  59332. if (r == 1)
  59333. {
  59334. owner->setCurrentColour (owner->getSwatchColour (index));
  59335. }
  59336. else if (r == 2)
  59337. {
  59338. if (owner->getSwatchColour (index) != owner->getCurrentColour())
  59339. {
  59340. owner->setSwatchColour (index, owner->getCurrentColour());
  59341. repaint();
  59342. }
  59343. }
  59344. }
  59345. private:
  59346. ColourSelector* const owner;
  59347. const int index;
  59348. SwatchComponent (const SwatchComponent&);
  59349. SwatchComponent& operator= (const SwatchComponent&);
  59350. };
  59351. ColourSelector::ColourSelector (const int flags_,
  59352. const int edgeGap_,
  59353. const int gapAroundColourSpaceComponent)
  59354. : colour (Colours::white),
  59355. flags (flags_),
  59356. topSpace (0),
  59357. edgeGap (edgeGap_)
  59358. {
  59359. // not much point having a selector with no components in it!
  59360. jassert ((flags_ & (showColourAtTop | showSliders | showColourspace)) != 0);
  59361. updateHSV();
  59362. if ((flags & showSliders) != 0)
  59363. {
  59364. addAndMakeVisible (sliders[0] = new ColourComponentSlider (TRANS ("red")));
  59365. addAndMakeVisible (sliders[1] = new ColourComponentSlider (TRANS ("green")));
  59366. addAndMakeVisible (sliders[2] = new ColourComponentSlider (TRANS ("blue")));
  59367. addChildComponent (sliders[3] = new ColourComponentSlider (TRANS ("alpha")));
  59368. sliders[3]->setVisible ((flags & showAlphaChannel) != 0);
  59369. for (int i = 4; --i >= 0;)
  59370. sliders[i]->addListener (this);
  59371. }
  59372. else
  59373. {
  59374. zeromem (sliders, sizeof (sliders));
  59375. }
  59376. if ((flags & showColourspace) != 0)
  59377. {
  59378. addAndMakeVisible (colourSpace = new ColourSpaceView (this, h, s, v, gapAroundColourSpaceComponent));
  59379. addAndMakeVisible (hueSelector = new HueSelectorComp (this, h, s, v, gapAroundColourSpaceComponent));
  59380. }
  59381. else
  59382. {
  59383. colourSpace = 0;
  59384. hueSelector = 0;
  59385. }
  59386. update();
  59387. }
  59388. ColourSelector::~ColourSelector()
  59389. {
  59390. dispatchPendingMessages();
  59391. swatchComponents.clear();
  59392. deleteAllChildren();
  59393. }
  59394. const Colour ColourSelector::getCurrentColour() const
  59395. {
  59396. return ((flags & showAlphaChannel) != 0) ? colour
  59397. : colour.withAlpha ((uint8) 0xff);
  59398. }
  59399. void ColourSelector::setCurrentColour (const Colour& c)
  59400. {
  59401. if (c != colour)
  59402. {
  59403. colour = ((flags & showAlphaChannel) != 0) ? c : c.withAlpha ((uint8) 0xff);
  59404. updateHSV();
  59405. update();
  59406. }
  59407. }
  59408. void ColourSelector::setHue (float newH)
  59409. {
  59410. newH = jlimit (0.0f, 1.0f, newH);
  59411. if (h != newH)
  59412. {
  59413. h = newH;
  59414. colour = Colour (h, s, v, colour.getFloatAlpha());
  59415. update();
  59416. }
  59417. }
  59418. void ColourSelector::setSV (float newS, float newV)
  59419. {
  59420. newS = jlimit (0.0f, 1.0f, newS);
  59421. newV = jlimit (0.0f, 1.0f, newV);
  59422. if (s != newS || v != newV)
  59423. {
  59424. s = newS;
  59425. v = newV;
  59426. colour = Colour (h, s, v, colour.getFloatAlpha());
  59427. update();
  59428. }
  59429. }
  59430. void ColourSelector::updateHSV()
  59431. {
  59432. colour.getHSB (h, s, v);
  59433. }
  59434. void ColourSelector::update()
  59435. {
  59436. if (sliders[0] != 0)
  59437. {
  59438. sliders[0]->setValue ((int) colour.getRed());
  59439. sliders[1]->setValue ((int) colour.getGreen());
  59440. sliders[2]->setValue ((int) colour.getBlue());
  59441. sliders[3]->setValue ((int) colour.getAlpha());
  59442. }
  59443. if (colourSpace != 0)
  59444. {
  59445. colourSpace->updateIfNeeded();
  59446. hueSelector->updateIfNeeded();
  59447. }
  59448. if ((flags & showColourAtTop) != 0)
  59449. repaint (0, edgeGap, getWidth(), topSpace - edgeGap);
  59450. sendChangeMessage (this);
  59451. }
  59452. void ColourSelector::paint (Graphics& g)
  59453. {
  59454. g.fillAll (findColour (backgroundColourId));
  59455. if ((flags & showColourAtTop) != 0)
  59456. {
  59457. const Colour currentColour (getCurrentColour());
  59458. g.fillCheckerBoard (edgeGap, edgeGap, getWidth() - edgeGap - edgeGap, topSpace - edgeGap - edgeGap,
  59459. 10, 10,
  59460. Colour (0xffdddddd).overlaidWith (currentColour),
  59461. Colour (0xffffffff).overlaidWith (currentColour));
  59462. g.setColour (Colours::white.overlaidWith (currentColour).contrasting());
  59463. g.setFont (14.0f, true);
  59464. g.drawText (currentColour.toDisplayString ((flags & showAlphaChannel) != 0),
  59465. 0, edgeGap, getWidth(), topSpace - edgeGap * 2,
  59466. Justification::centred, false);
  59467. }
  59468. if ((flags & showSliders) != 0)
  59469. {
  59470. g.setColour (findColour (labelTextColourId));
  59471. g.setFont (11.0f);
  59472. for (int i = 4; --i >= 0;)
  59473. {
  59474. if (sliders[i]->isVisible())
  59475. g.drawText (sliders[i]->getName() + ":",
  59476. 0, sliders[i]->getY(),
  59477. sliders[i]->getX() - 8, sliders[i]->getHeight(),
  59478. Justification::centredRight, false);
  59479. }
  59480. }
  59481. }
  59482. void ColourSelector::resized()
  59483. {
  59484. const int swatchesPerRow = 8;
  59485. const int swatchHeight = 22;
  59486. const int numSliders = ((flags & showAlphaChannel) != 0) ? 4 : 3;
  59487. const int numSwatches = getNumSwatches();
  59488. const int swatchSpace = numSwatches > 0 ? edgeGap + swatchHeight * ((numSwatches + 7) / swatchesPerRow) : 0;
  59489. const int sliderSpace = ((flags & showSliders) != 0) ? jmin (22 * numSliders + edgeGap, proportionOfHeight (0.3f)) : 0;
  59490. topSpace = ((flags & showColourAtTop) != 0) ? jmin (30 + edgeGap * 2, proportionOfHeight (0.2f)) : edgeGap;
  59491. int y = topSpace;
  59492. if ((flags & showColourspace) != 0)
  59493. {
  59494. const int hueWidth = jmin (50, proportionOfWidth (0.15f));
  59495. colourSpace->setBounds (edgeGap, y,
  59496. getWidth() - hueWidth - edgeGap - 4,
  59497. getHeight() - topSpace - sliderSpace - swatchSpace - edgeGap);
  59498. hueSelector->setBounds (colourSpace->getRight() + 4, y,
  59499. getWidth() - edgeGap - (colourSpace->getRight() + 4),
  59500. colourSpace->getHeight());
  59501. y = getHeight() - sliderSpace - swatchSpace - edgeGap;
  59502. }
  59503. if ((flags & showSliders) != 0)
  59504. {
  59505. const int sliderHeight = jmax (4, sliderSpace / numSliders);
  59506. for (int i = 0; i < numSliders; ++i)
  59507. {
  59508. sliders[i]->setBounds (proportionOfWidth (0.2f), y,
  59509. proportionOfWidth (0.72f), sliderHeight - 2);
  59510. y += sliderHeight;
  59511. }
  59512. }
  59513. if (numSwatches > 0)
  59514. {
  59515. const int startX = 8;
  59516. const int xGap = 4;
  59517. const int yGap = 4;
  59518. const int swatchWidth = (getWidth() - startX * 2) / swatchesPerRow;
  59519. y += edgeGap;
  59520. if (swatchComponents.size() != numSwatches)
  59521. {
  59522. swatchComponents.clear();
  59523. for (int i = 0; i < numSwatches; ++i)
  59524. {
  59525. SwatchComponent* const sc = new SwatchComponent (this, i);
  59526. swatchComponents.add (sc);
  59527. addAndMakeVisible (sc);
  59528. }
  59529. }
  59530. int x = startX;
  59531. for (int i = 0; i < swatchComponents.size(); ++i)
  59532. {
  59533. SwatchComponent* const sc = swatchComponents.getUnchecked(i);
  59534. sc->setBounds (x + xGap / 2,
  59535. y + yGap / 2,
  59536. swatchWidth - xGap,
  59537. swatchHeight - yGap);
  59538. if (((i + 1) % swatchesPerRow) == 0)
  59539. {
  59540. x = startX;
  59541. y += swatchHeight;
  59542. }
  59543. else
  59544. {
  59545. x += swatchWidth;
  59546. }
  59547. }
  59548. }
  59549. }
  59550. void ColourSelector::sliderValueChanged (Slider*)
  59551. {
  59552. if (sliders[0] != 0)
  59553. setCurrentColour (Colour ((uint8) sliders[0]->getValue(),
  59554. (uint8) sliders[1]->getValue(),
  59555. (uint8) sliders[2]->getValue(),
  59556. (uint8) sliders[3]->getValue()));
  59557. }
  59558. int ColourSelector::getNumSwatches() const
  59559. {
  59560. return 0;
  59561. }
  59562. const Colour ColourSelector::getSwatchColour (const int) const
  59563. {
  59564. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  59565. return Colours::black;
  59566. }
  59567. void ColourSelector::setSwatchColour (const int, const Colour&) const
  59568. {
  59569. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  59570. }
  59571. END_JUCE_NAMESPACE
  59572. /*** End of inlined file: juce_ColourSelector.cpp ***/
  59573. /*** Start of inlined file: juce_DropShadower.cpp ***/
  59574. BEGIN_JUCE_NAMESPACE
  59575. class ShadowWindow : public Component
  59576. {
  59577. Component* owner;
  59578. Image shadowImageSections [12];
  59579. const int type; // 0 = left, 1 = right, 2 = top, 3 = bottom. left + right are full-height
  59580. public:
  59581. ShadowWindow (Component* const owner_,
  59582. const int type_,
  59583. const Image shadowImageSections_ [12])
  59584. : owner (owner_),
  59585. type (type_)
  59586. {
  59587. for (int i = 0; i < numElementsInArray (shadowImageSections); ++i)
  59588. shadowImageSections [i] = shadowImageSections_ [i];
  59589. setInterceptsMouseClicks (false, false);
  59590. if (owner_->isOnDesktop())
  59591. {
  59592. setSize (1, 1); // to keep the OS happy by not having zero-size windows
  59593. addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  59594. | ComponentPeer::windowIsTemporary
  59595. | ComponentPeer::windowIgnoresKeyPresses);
  59596. }
  59597. else if (owner_->getParentComponent() != 0)
  59598. {
  59599. owner_->getParentComponent()->addChildComponent (this);
  59600. }
  59601. }
  59602. ~ShadowWindow()
  59603. {
  59604. }
  59605. void paint (Graphics& g)
  59606. {
  59607. const Image& topLeft = shadowImageSections [type * 3];
  59608. const Image& bottomRight = shadowImageSections [type * 3 + 1];
  59609. const Image& filler = shadowImageSections [type * 3 + 2];
  59610. g.setOpacity (1.0f);
  59611. if (type < 2)
  59612. {
  59613. int imH = jmin (topLeft.getHeight(), getHeight() / 2);
  59614. g.drawImage (topLeft,
  59615. 0, 0, topLeft.getWidth(), imH,
  59616. 0, 0, topLeft.getWidth(), imH);
  59617. imH = jmin (bottomRight.getHeight(), getHeight() - getHeight() / 2);
  59618. g.drawImage (bottomRight,
  59619. 0, getHeight() - imH, bottomRight.getWidth(), imH,
  59620. 0, bottomRight.getHeight() - imH, bottomRight.getWidth(), imH);
  59621. g.setTiledImageFill (filler, 0, 0, 1.0f);
  59622. g.fillRect (0, topLeft.getHeight(), getWidth(), getHeight() - (topLeft.getHeight() + bottomRight.getHeight()));
  59623. }
  59624. else
  59625. {
  59626. int imW = jmin (topLeft.getWidth(), getWidth() / 2);
  59627. g.drawImage (topLeft,
  59628. 0, 0, imW, topLeft.getHeight(),
  59629. 0, 0, imW, topLeft.getHeight());
  59630. imW = jmin (bottomRight.getWidth(), getWidth() - getWidth() / 2);
  59631. g.drawImage (bottomRight,
  59632. getWidth() - imW, 0, imW, bottomRight.getHeight(),
  59633. bottomRight.getWidth() - imW, 0, imW, bottomRight.getHeight());
  59634. g.setTiledImageFill (filler, 0, 0, 1.0f);
  59635. g.fillRect (topLeft.getWidth(), 0, getWidth() - (topLeft.getWidth() + bottomRight.getWidth()), getHeight());
  59636. }
  59637. }
  59638. void resized()
  59639. {
  59640. repaint(); // (needed for correct repainting)
  59641. }
  59642. private:
  59643. ShadowWindow (const ShadowWindow&);
  59644. ShadowWindow& operator= (const ShadowWindow&);
  59645. };
  59646. DropShadower::DropShadower (const float alpha_,
  59647. const int xOffset_,
  59648. const int yOffset_,
  59649. const float blurRadius_)
  59650. : owner (0),
  59651. numShadows (0),
  59652. shadowEdge (jmax (xOffset_, yOffset_) + (int) blurRadius_),
  59653. xOffset (xOffset_),
  59654. yOffset (yOffset_),
  59655. alpha (alpha_),
  59656. blurRadius (blurRadius_),
  59657. inDestructor (false),
  59658. reentrant (false)
  59659. {
  59660. }
  59661. DropShadower::~DropShadower()
  59662. {
  59663. if (owner != 0)
  59664. owner->removeComponentListener (this);
  59665. inDestructor = true;
  59666. deleteShadowWindows();
  59667. }
  59668. void DropShadower::deleteShadowWindows()
  59669. {
  59670. if (numShadows > 0)
  59671. {
  59672. int i;
  59673. for (i = numShadows; --i >= 0;)
  59674. delete shadowWindows[i];
  59675. numShadows = 0;
  59676. }
  59677. }
  59678. void DropShadower::setOwner (Component* componentToFollow)
  59679. {
  59680. if (componentToFollow != owner)
  59681. {
  59682. if (owner != 0)
  59683. owner->removeComponentListener (this);
  59684. // (the component can't be null)
  59685. jassert (componentToFollow != 0);
  59686. owner = componentToFollow;
  59687. jassert (owner != 0);
  59688. jassert (owner->isOpaque()); // doesn't work properly for semi-transparent comps!
  59689. owner->addComponentListener (this);
  59690. updateShadows();
  59691. }
  59692. }
  59693. void DropShadower::componentMovedOrResized (Component&, bool /*wasMoved*/, bool /*wasResized*/)
  59694. {
  59695. updateShadows();
  59696. }
  59697. void DropShadower::componentBroughtToFront (Component&)
  59698. {
  59699. bringShadowWindowsToFront();
  59700. }
  59701. void DropShadower::componentChildrenChanged (Component&)
  59702. {
  59703. }
  59704. void DropShadower::componentParentHierarchyChanged (Component&)
  59705. {
  59706. deleteShadowWindows();
  59707. updateShadows();
  59708. }
  59709. void DropShadower::componentVisibilityChanged (Component&)
  59710. {
  59711. updateShadows();
  59712. }
  59713. void DropShadower::updateShadows()
  59714. {
  59715. if (reentrant || inDestructor || (owner == 0))
  59716. return;
  59717. reentrant = true;
  59718. ComponentPeer* const nw = owner->getPeer();
  59719. const bool isOwnerVisible = owner->isVisible()
  59720. && (nw == 0 || ! nw->isMinimised());
  59721. const bool createShadowWindows = numShadows == 0
  59722. && owner->getWidth() > 0
  59723. && owner->getHeight() > 0
  59724. && isOwnerVisible
  59725. && (Desktop::canUseSemiTransparentWindows()
  59726. || owner->getParentComponent() != 0);
  59727. if (createShadowWindows)
  59728. {
  59729. // keep a cached version of the image to save doing the gaussian too often
  59730. String imageId;
  59731. imageId << shadowEdge << ',' << xOffset << ',' << yOffset << ',' << alpha;
  59732. const int hash = imageId.hashCode();
  59733. Image bigIm (ImageCache::getFromHashCode (hash));
  59734. if (bigIm.isNull())
  59735. {
  59736. bigIm = Image (Image::ARGB, shadowEdge * 5, shadowEdge * 5, true, Image::NativeImage);
  59737. Graphics bigG (bigIm);
  59738. bigG.setColour (Colours::black.withAlpha (alpha));
  59739. bigG.fillRect (shadowEdge + xOffset,
  59740. shadowEdge + yOffset,
  59741. bigIm.getWidth() - (shadowEdge * 2),
  59742. bigIm.getHeight() - (shadowEdge * 2));
  59743. ImageConvolutionKernel blurKernel (roundToInt (blurRadius * 2.0f));
  59744. blurKernel.createGaussianBlur (blurRadius);
  59745. blurKernel.applyToImage (bigIm, bigIm,
  59746. Rectangle<int> (xOffset, yOffset,
  59747. bigIm.getWidth(), bigIm.getHeight()));
  59748. ImageCache::addImageToCache (bigIm, hash);
  59749. }
  59750. const int iw = bigIm.getWidth();
  59751. const int ih = bigIm.getHeight();
  59752. const int shadowEdge2 = shadowEdge * 2;
  59753. setShadowImage (bigIm, 0, shadowEdge, shadowEdge2, 0, 0);
  59754. setShadowImage (bigIm, 1, shadowEdge, shadowEdge2, 0, ih - shadowEdge2);
  59755. setShadowImage (bigIm, 2, shadowEdge, shadowEdge, 0, shadowEdge2);
  59756. setShadowImage (bigIm, 3, shadowEdge, shadowEdge2, iw - shadowEdge, 0);
  59757. setShadowImage (bigIm, 4, shadowEdge, shadowEdge2, iw - shadowEdge, ih - shadowEdge2);
  59758. setShadowImage (bigIm, 5, shadowEdge, shadowEdge, iw - shadowEdge, shadowEdge2);
  59759. setShadowImage (bigIm, 6, shadowEdge, shadowEdge, shadowEdge, 0);
  59760. setShadowImage (bigIm, 7, shadowEdge, shadowEdge, iw - shadowEdge2, 0);
  59761. setShadowImage (bigIm, 8, shadowEdge, shadowEdge, shadowEdge2, 0);
  59762. setShadowImage (bigIm, 9, shadowEdge, shadowEdge, shadowEdge, ih - shadowEdge);
  59763. setShadowImage (bigIm, 10, shadowEdge, shadowEdge, iw - shadowEdge2, ih - shadowEdge);
  59764. setShadowImage (bigIm, 11, shadowEdge, shadowEdge, shadowEdge2, ih - shadowEdge);
  59765. for (int i = 0; i < 4; ++i)
  59766. {
  59767. shadowWindows[numShadows] = new ShadowWindow (owner, i, shadowImageSections);
  59768. ++numShadows;
  59769. }
  59770. }
  59771. if (numShadows > 0)
  59772. {
  59773. for (int i = numShadows; --i >= 0;)
  59774. {
  59775. shadowWindows[i]->setAlwaysOnTop (owner->isAlwaysOnTop());
  59776. shadowWindows[i]->setVisible (isOwnerVisible);
  59777. }
  59778. const int x = owner->getX();
  59779. const int y = owner->getY() - shadowEdge;
  59780. const int w = owner->getWidth();
  59781. const int h = owner->getHeight() + shadowEdge + shadowEdge;
  59782. shadowWindows[0]->setBounds (x - shadowEdge,
  59783. y,
  59784. shadowEdge,
  59785. h);
  59786. shadowWindows[1]->setBounds (x + w,
  59787. y,
  59788. shadowEdge,
  59789. h);
  59790. shadowWindows[2]->setBounds (x,
  59791. y,
  59792. w,
  59793. shadowEdge);
  59794. shadowWindows[3]->setBounds (x,
  59795. owner->getBottom(),
  59796. w,
  59797. shadowEdge);
  59798. }
  59799. reentrant = false;
  59800. if (createShadowWindows)
  59801. bringShadowWindowsToFront();
  59802. }
  59803. void DropShadower::setShadowImage (const Image& src, const int num, const int w, const int h,
  59804. const int sx, const int sy)
  59805. {
  59806. shadowImageSections[num] = Image (Image::ARGB, w, h, true, Image::NativeImage);
  59807. Graphics g (shadowImageSections[num]);
  59808. g.drawImage (src, 0, 0, w, h, sx, sy, w, h);
  59809. }
  59810. void DropShadower::bringShadowWindowsToFront()
  59811. {
  59812. if (! (inDestructor || reentrant))
  59813. {
  59814. updateShadows();
  59815. reentrant = true;
  59816. for (int i = numShadows; --i >= 0;)
  59817. shadowWindows[i]->toBehind (owner);
  59818. reentrant = false;
  59819. }
  59820. }
  59821. END_JUCE_NAMESPACE
  59822. /*** End of inlined file: juce_DropShadower.cpp ***/
  59823. /*** Start of inlined file: juce_MagnifierComponent.cpp ***/
  59824. BEGIN_JUCE_NAMESPACE
  59825. class MagnifyingPeer : public ComponentPeer
  59826. {
  59827. public:
  59828. MagnifyingPeer (Component* const component_,
  59829. MagnifierComponent* const magnifierComp_)
  59830. : ComponentPeer (component_, 0),
  59831. magnifierComp (magnifierComp_)
  59832. {
  59833. }
  59834. ~MagnifyingPeer()
  59835. {
  59836. }
  59837. void* getNativeHandle() const { return 0; }
  59838. void setVisible (bool) {}
  59839. void setTitle (const String&) {}
  59840. void setPosition (int, int) {}
  59841. void setSize (int, int) {}
  59842. void setBounds (int, int, int, int, bool) {}
  59843. void setMinimised (bool) {}
  59844. bool isMinimised() const { return false; }
  59845. void setFullScreen (bool) {}
  59846. bool isFullScreen() const { return false; }
  59847. const BorderSize getFrameSize() const { return BorderSize (0); }
  59848. bool setAlwaysOnTop (bool) { return true; }
  59849. void toFront (bool) {}
  59850. void toBehind (ComponentPeer*) {}
  59851. void setIcon (const Image&) {}
  59852. bool isFocused() const
  59853. {
  59854. return magnifierComp->hasKeyboardFocus (true);
  59855. }
  59856. void grabFocus()
  59857. {
  59858. ComponentPeer* peer = magnifierComp->getPeer();
  59859. if (peer != 0)
  59860. peer->grabFocus();
  59861. }
  59862. void textInputRequired (const Point<int>& position)
  59863. {
  59864. ComponentPeer* peer = magnifierComp->getPeer();
  59865. if (peer != 0)
  59866. peer->textInputRequired (position);
  59867. }
  59868. const Rectangle<int> getBounds() const
  59869. {
  59870. return Rectangle<int> (magnifierComp->getScreenX(), magnifierComp->getScreenY(),
  59871. component->getWidth(), component->getHeight());
  59872. }
  59873. const Point<int> getScreenPosition() const
  59874. {
  59875. return magnifierComp->getScreenPosition();
  59876. }
  59877. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  59878. {
  59879. const double zoom = magnifierComp->getScaleFactor();
  59880. return magnifierComp->relativePositionToGlobal (Point<int> (roundToInt (relativePosition.getX() * zoom),
  59881. roundToInt (relativePosition.getY() * zoom)));
  59882. }
  59883. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  59884. {
  59885. const Point<int> p (magnifierComp->globalPositionToRelative (screenPosition));
  59886. const double zoom = magnifierComp->getScaleFactor();
  59887. return Point<int> (roundToInt (p.getX() / zoom),
  59888. roundToInt (p.getY() / zoom));
  59889. }
  59890. bool contains (const Point<int>& position, bool) const
  59891. {
  59892. return ((unsigned int) position.getX()) < (unsigned int) magnifierComp->getWidth()
  59893. && ((unsigned int) position.getY()) < (unsigned int) magnifierComp->getHeight();
  59894. }
  59895. void repaint (const Rectangle<int>& area)
  59896. {
  59897. const double zoom = magnifierComp->getScaleFactor();
  59898. magnifierComp->repaint ((int) (area.getX() * zoom),
  59899. (int) (area.getY() * zoom),
  59900. roundToInt (area.getWidth() * zoom) + 1,
  59901. roundToInt (area.getHeight() * zoom) + 1);
  59902. }
  59903. void performAnyPendingRepaintsNow()
  59904. {
  59905. }
  59906. juce_UseDebuggingNewOperator
  59907. private:
  59908. MagnifierComponent* const magnifierComp;
  59909. MagnifyingPeer (const MagnifyingPeer&);
  59910. MagnifyingPeer& operator= (const MagnifyingPeer&);
  59911. };
  59912. class PeerHolderComp : public Component
  59913. {
  59914. public:
  59915. PeerHolderComp (MagnifierComponent* const magnifierComp_)
  59916. : magnifierComp (magnifierComp_)
  59917. {
  59918. setVisible (true);
  59919. }
  59920. ~PeerHolderComp()
  59921. {
  59922. }
  59923. ComponentPeer* createNewPeer (int, void*)
  59924. {
  59925. return new MagnifyingPeer (this, magnifierComp);
  59926. }
  59927. void childBoundsChanged (Component* c)
  59928. {
  59929. if (c != 0)
  59930. {
  59931. setSize (c->getWidth(), c->getHeight());
  59932. magnifierComp->childBoundsChanged (this);
  59933. }
  59934. }
  59935. void mouseWheelMove (const MouseEvent& e, float ix, float iy)
  59936. {
  59937. // unhandled mouse wheel moves can be referred upwards to the parent comp..
  59938. Component* const p = magnifierComp->getParentComponent();
  59939. if (p != 0)
  59940. p->mouseWheelMove (e.getEventRelativeTo (p), ix, iy);
  59941. }
  59942. private:
  59943. MagnifierComponent* const magnifierComp;
  59944. PeerHolderComp (const PeerHolderComp&);
  59945. PeerHolderComp& operator= (const PeerHolderComp&);
  59946. };
  59947. MagnifierComponent::MagnifierComponent (Component* const content_,
  59948. const bool deleteContentCompWhenNoLongerNeeded)
  59949. : content (content_),
  59950. scaleFactor (0.0),
  59951. peer (0),
  59952. deleteContent (deleteContentCompWhenNoLongerNeeded),
  59953. quality (Graphics::lowResamplingQuality),
  59954. mouseSource (0, true)
  59955. {
  59956. holderComp = new PeerHolderComp (this);
  59957. setScaleFactor (1.0);
  59958. }
  59959. MagnifierComponent::~MagnifierComponent()
  59960. {
  59961. delete holderComp;
  59962. if (deleteContent)
  59963. delete content;
  59964. }
  59965. void MagnifierComponent::setScaleFactor (double newScaleFactor)
  59966. {
  59967. jassert (newScaleFactor > 0.0); // hmm - unlikely to work well with a negative scale factor
  59968. newScaleFactor = jlimit (1.0 / 8.0, 1000.0, newScaleFactor);
  59969. if (scaleFactor != newScaleFactor)
  59970. {
  59971. scaleFactor = newScaleFactor;
  59972. if (scaleFactor == 1.0)
  59973. {
  59974. holderComp->removeFromDesktop();
  59975. peer = 0;
  59976. addChildComponent (content);
  59977. childBoundsChanged (content);
  59978. }
  59979. else
  59980. {
  59981. holderComp->addAndMakeVisible (content);
  59982. holderComp->childBoundsChanged (content);
  59983. childBoundsChanged (holderComp);
  59984. holderComp->addToDesktop (0);
  59985. peer = holderComp->getPeer();
  59986. }
  59987. repaint();
  59988. }
  59989. }
  59990. void MagnifierComponent::setResamplingQuality (Graphics::ResamplingQuality newQuality)
  59991. {
  59992. quality = newQuality;
  59993. }
  59994. void MagnifierComponent::paint (Graphics& g)
  59995. {
  59996. const int w = holderComp->getWidth();
  59997. const int h = holderComp->getHeight();
  59998. if (w == 0 || h == 0)
  59999. return;
  60000. const Rectangle<int> r (g.getClipBounds());
  60001. const int srcX = (int) (r.getX() / scaleFactor);
  60002. const int srcY = (int) (r.getY() / scaleFactor);
  60003. int srcW = roundToInt (r.getRight() / scaleFactor) - srcX;
  60004. int srcH = roundToInt (r.getBottom() / scaleFactor) - srcY;
  60005. if (scaleFactor >= 1.0)
  60006. {
  60007. ++srcW;
  60008. ++srcH;
  60009. }
  60010. Image temp (Image::ARGB, jmax (w, srcX + srcW), jmax (h, srcY + srcH), false);
  60011. temp.clear (Rectangle<int> (srcX, srcY, srcW, srcH));
  60012. {
  60013. Graphics g2 (temp);
  60014. g2.reduceClipRegion (srcX, srcY, srcW, srcH);
  60015. holderComp->paintEntireComponent (g2);
  60016. }
  60017. g.setImageResamplingQuality (quality);
  60018. g.drawImageTransformed (temp, temp.getBounds(),
  60019. AffineTransform::scale ((float) scaleFactor, (float) scaleFactor),
  60020. false);
  60021. }
  60022. void MagnifierComponent::childBoundsChanged (Component* c)
  60023. {
  60024. if (c != 0)
  60025. setSize (roundToInt (c->getWidth() * scaleFactor),
  60026. roundToInt (c->getHeight() * scaleFactor));
  60027. }
  60028. void MagnifierComponent::passOnMouseEventToPeer (const MouseEvent& e)
  60029. {
  60030. if (peer != 0)
  60031. mouseSource.handleEvent (peer, Point<int> (scaleInt (e.x), scaleInt (e.y)),
  60032. e.eventTime.toMilliseconds(), ModifierKeys::getCurrentModifiers());
  60033. }
  60034. void MagnifierComponent::mouseDown (const MouseEvent& e)
  60035. {
  60036. passOnMouseEventToPeer (e);
  60037. }
  60038. void MagnifierComponent::mouseUp (const MouseEvent& e)
  60039. {
  60040. passOnMouseEventToPeer (e);
  60041. }
  60042. void MagnifierComponent::mouseDrag (const MouseEvent& e)
  60043. {
  60044. passOnMouseEventToPeer (e);
  60045. }
  60046. void MagnifierComponent::mouseMove (const MouseEvent& e)
  60047. {
  60048. passOnMouseEventToPeer (e);
  60049. }
  60050. void MagnifierComponent::mouseEnter (const MouseEvent& e)
  60051. {
  60052. passOnMouseEventToPeer (e);
  60053. }
  60054. void MagnifierComponent::mouseExit (const MouseEvent& e)
  60055. {
  60056. passOnMouseEventToPeer (e);
  60057. }
  60058. void MagnifierComponent::mouseWheelMove (const MouseEvent& e, float ix, float iy)
  60059. {
  60060. if (peer != 0)
  60061. peer->handleMouseWheel (e.source.getIndex(),
  60062. Point<int> (scaleInt (e.x), scaleInt (e.y)), e.eventTime.toMilliseconds(),
  60063. ix * 256.0f, iy * 256.0f);
  60064. else
  60065. Component::mouseWheelMove (e, ix, iy);
  60066. }
  60067. int MagnifierComponent::scaleInt (const int n) const
  60068. {
  60069. return roundToInt (n / scaleFactor);
  60070. }
  60071. END_JUCE_NAMESPACE
  60072. /*** End of inlined file: juce_MagnifierComponent.cpp ***/
  60073. /*** Start of inlined file: juce_MidiKeyboardComponent.cpp ***/
  60074. BEGIN_JUCE_NAMESPACE
  60075. class MidiKeyboardUpDownButton : public Button
  60076. {
  60077. public:
  60078. MidiKeyboardUpDownButton (MidiKeyboardComponent* const owner_,
  60079. const int delta_)
  60080. : Button (String::empty),
  60081. owner (owner_),
  60082. delta (delta_)
  60083. {
  60084. setOpaque (true);
  60085. }
  60086. ~MidiKeyboardUpDownButton()
  60087. {
  60088. }
  60089. void clicked()
  60090. {
  60091. int note = owner->getLowestVisibleKey();
  60092. if (delta < 0)
  60093. note = (note - 1) / 12;
  60094. else
  60095. note = note / 12 + 1;
  60096. owner->setLowestVisibleKey (note * 12);
  60097. }
  60098. void paintButton (Graphics& g,
  60099. bool isMouseOverButton,
  60100. bool isButtonDown)
  60101. {
  60102. owner->drawUpDownButton (g, getWidth(), getHeight(),
  60103. isMouseOverButton, isButtonDown,
  60104. delta > 0);
  60105. }
  60106. private:
  60107. MidiKeyboardComponent* const owner;
  60108. const int delta;
  60109. MidiKeyboardUpDownButton (const MidiKeyboardUpDownButton&);
  60110. MidiKeyboardUpDownButton& operator= (const MidiKeyboardUpDownButton&);
  60111. };
  60112. MidiKeyboardComponent::MidiKeyboardComponent (MidiKeyboardState& state_,
  60113. const Orientation orientation_)
  60114. : state (state_),
  60115. xOffset (0),
  60116. blackNoteLength (1),
  60117. keyWidth (16.0f),
  60118. orientation (orientation_),
  60119. midiChannel (1),
  60120. midiInChannelMask (0xffff),
  60121. velocity (1.0f),
  60122. noteUnderMouse (-1),
  60123. mouseDownNote (-1),
  60124. rangeStart (0),
  60125. rangeEnd (127),
  60126. firstKey (12 * 4),
  60127. canScroll (true),
  60128. mouseDragging (false),
  60129. useMousePositionForVelocity (true),
  60130. keyMappingOctave (6),
  60131. octaveNumForMiddleC (3)
  60132. {
  60133. addChildComponent (scrollDown = new MidiKeyboardUpDownButton (this, -1));
  60134. addChildComponent (scrollUp = new MidiKeyboardUpDownButton (this, 1));
  60135. // initialise with a default set of querty key-mappings..
  60136. const char* const keymap = "awsedftgyhujkolp;";
  60137. for (int i = String (keymap).length(); --i >= 0;)
  60138. setKeyPressForNote (KeyPress (keymap[i], 0, 0), i);
  60139. setOpaque (true);
  60140. setWantsKeyboardFocus (true);
  60141. state.addListener (this);
  60142. }
  60143. MidiKeyboardComponent::~MidiKeyboardComponent()
  60144. {
  60145. state.removeListener (this);
  60146. jassert (mouseDownNote < 0 && keysPressed.countNumberOfSetBits() == 0); // leaving stuck notes!
  60147. deleteAllChildren();
  60148. }
  60149. void MidiKeyboardComponent::setKeyWidth (const float widthInPixels)
  60150. {
  60151. keyWidth = widthInPixels;
  60152. resized();
  60153. }
  60154. void MidiKeyboardComponent::setOrientation (const Orientation newOrientation)
  60155. {
  60156. if (orientation != newOrientation)
  60157. {
  60158. orientation = newOrientation;
  60159. resized();
  60160. }
  60161. }
  60162. void MidiKeyboardComponent::setAvailableRange (const int lowestNote,
  60163. const int highestNote)
  60164. {
  60165. jassert (lowestNote >= 0 && lowestNote <= 127);
  60166. jassert (highestNote >= 0 && highestNote <= 127);
  60167. jassert (lowestNote <= highestNote);
  60168. if (rangeStart != lowestNote || rangeEnd != highestNote)
  60169. {
  60170. rangeStart = jlimit (0, 127, lowestNote);
  60171. rangeEnd = jlimit (0, 127, highestNote);
  60172. firstKey = jlimit (rangeStart, rangeEnd, firstKey);
  60173. resized();
  60174. }
  60175. }
  60176. void MidiKeyboardComponent::setLowestVisibleKey (int noteNumber)
  60177. {
  60178. noteNumber = jlimit (rangeStart, rangeEnd, noteNumber);
  60179. if (noteNumber != firstKey)
  60180. {
  60181. firstKey = noteNumber;
  60182. sendChangeMessage (this);
  60183. resized();
  60184. }
  60185. }
  60186. void MidiKeyboardComponent::setScrollButtonsVisible (const bool canScroll_)
  60187. {
  60188. if (canScroll != canScroll_)
  60189. {
  60190. canScroll = canScroll_;
  60191. resized();
  60192. }
  60193. }
  60194. void MidiKeyboardComponent::colourChanged()
  60195. {
  60196. repaint();
  60197. }
  60198. void MidiKeyboardComponent::setMidiChannel (const int midiChannelNumber)
  60199. {
  60200. jassert (midiChannelNumber > 0 && midiChannelNumber <= 16);
  60201. if (midiChannel != midiChannelNumber)
  60202. {
  60203. resetAnyKeysInUse();
  60204. midiChannel = jlimit (1, 16, midiChannelNumber);
  60205. }
  60206. }
  60207. void MidiKeyboardComponent::setMidiChannelsToDisplay (const int midiChannelMask)
  60208. {
  60209. midiInChannelMask = midiChannelMask;
  60210. triggerAsyncUpdate();
  60211. }
  60212. void MidiKeyboardComponent::setVelocity (const float velocity_, const bool useMousePositionForVelocity_)
  60213. {
  60214. velocity = jlimit (0.0f, 1.0f, velocity_);
  60215. useMousePositionForVelocity = useMousePositionForVelocity_;
  60216. }
  60217. void MidiKeyboardComponent::getKeyPosition (int midiNoteNumber, const float keyWidth_, int& x, int& w) const
  60218. {
  60219. jassert (midiNoteNumber >= 0 && midiNoteNumber < 128);
  60220. static const float blackNoteWidth = 0.7f;
  60221. static const float notePos[] = { 0.0f, 1 - blackNoteWidth * 0.6f,
  60222. 1.0f, 2 - blackNoteWidth * 0.4f,
  60223. 2.0f, 3.0f, 4 - blackNoteWidth * 0.7f,
  60224. 4.0f, 5 - blackNoteWidth * 0.5f,
  60225. 5.0f, 6 - blackNoteWidth * 0.3f,
  60226. 6.0f };
  60227. static const float widths[] = { 1.0f, blackNoteWidth,
  60228. 1.0f, blackNoteWidth,
  60229. 1.0f, 1.0f, blackNoteWidth,
  60230. 1.0f, blackNoteWidth,
  60231. 1.0f, blackNoteWidth,
  60232. 1.0f };
  60233. const int octave = midiNoteNumber / 12;
  60234. const int note = midiNoteNumber % 12;
  60235. x = roundToInt (octave * 7.0f * keyWidth_ + notePos [note] * keyWidth_);
  60236. w = roundToInt (widths [note] * keyWidth_);
  60237. }
  60238. void MidiKeyboardComponent::getKeyPos (int midiNoteNumber, int& x, int& w) const
  60239. {
  60240. getKeyPosition (midiNoteNumber, keyWidth, x, w);
  60241. int rx, rw;
  60242. getKeyPosition (rangeStart, keyWidth, rx, rw);
  60243. x -= xOffset + rx;
  60244. }
  60245. int MidiKeyboardComponent::getKeyStartPosition (const int midiNoteNumber) const
  60246. {
  60247. int x, y;
  60248. getKeyPos (midiNoteNumber, x, y);
  60249. return x;
  60250. }
  60251. const uint8 MidiKeyboardComponent::whiteNotes[] = { 0, 2, 4, 5, 7, 9, 11 };
  60252. const uint8 MidiKeyboardComponent::blackNotes[] = { 1, 3, 6, 8, 10 };
  60253. int MidiKeyboardComponent::xyToNote (const Point<int>& pos, float& mousePositionVelocity)
  60254. {
  60255. if (! reallyContains (pos.getX(), pos.getY(), false))
  60256. return -1;
  60257. Point<int> p (pos);
  60258. if (orientation != horizontalKeyboard)
  60259. {
  60260. p = Point<int> (p.getY(), p.getX());
  60261. if (orientation == verticalKeyboardFacingLeft)
  60262. p = Point<int> (p.getX(), getWidth() - p.getY());
  60263. else
  60264. p = Point<int> (getHeight() - p.getX(), p.getY());
  60265. }
  60266. return remappedXYToNote (p + Point<int> (xOffset, 0), mousePositionVelocity);
  60267. }
  60268. int MidiKeyboardComponent::remappedXYToNote (const Point<int>& pos, float& mousePositionVelocity) const
  60269. {
  60270. if (pos.getY() < blackNoteLength)
  60271. {
  60272. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  60273. {
  60274. for (int i = 0; i < 5; ++i)
  60275. {
  60276. const int note = octaveStart + blackNotes [i];
  60277. if (note >= rangeStart && note <= rangeEnd)
  60278. {
  60279. int kx, kw;
  60280. getKeyPos (note, kx, kw);
  60281. kx += xOffset;
  60282. if (pos.getX() >= kx && pos.getX() < kx + kw)
  60283. {
  60284. mousePositionVelocity = pos.getY() / (float) blackNoteLength;
  60285. return note;
  60286. }
  60287. }
  60288. }
  60289. }
  60290. }
  60291. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  60292. {
  60293. for (int i = 0; i < 7; ++i)
  60294. {
  60295. const int note = octaveStart + whiteNotes [i];
  60296. if (note >= rangeStart && note <= rangeEnd)
  60297. {
  60298. int kx, kw;
  60299. getKeyPos (note, kx, kw);
  60300. kx += xOffset;
  60301. if (pos.getX() >= kx && pos.getX() < kx + kw)
  60302. {
  60303. const int whiteNoteLength = (orientation == horizontalKeyboard) ? getHeight() : getWidth();
  60304. mousePositionVelocity = pos.getY() / (float) whiteNoteLength;
  60305. return note;
  60306. }
  60307. }
  60308. }
  60309. }
  60310. mousePositionVelocity = 0;
  60311. return -1;
  60312. }
  60313. void MidiKeyboardComponent::repaintNote (const int noteNum)
  60314. {
  60315. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60316. {
  60317. int x, w;
  60318. getKeyPos (noteNum, x, w);
  60319. if (orientation == horizontalKeyboard)
  60320. repaint (x, 0, w, getHeight());
  60321. else if (orientation == verticalKeyboardFacingLeft)
  60322. repaint (0, x, getWidth(), w);
  60323. else if (orientation == verticalKeyboardFacingRight)
  60324. repaint (0, getHeight() - x - w, getWidth(), w);
  60325. }
  60326. }
  60327. void MidiKeyboardComponent::paint (Graphics& g)
  60328. {
  60329. g.fillAll (Colours::white.overlaidWith (findColour (whiteNoteColourId)));
  60330. const Colour lineColour (findColour (keySeparatorLineColourId));
  60331. const Colour textColour (findColour (textLabelColourId));
  60332. int x, w, octave;
  60333. for (octave = 0; octave < 128; octave += 12)
  60334. {
  60335. for (int white = 0; white < 7; ++white)
  60336. {
  60337. const int noteNum = octave + whiteNotes [white];
  60338. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60339. {
  60340. getKeyPos (noteNum, x, w);
  60341. if (orientation == horizontalKeyboard)
  60342. drawWhiteNote (noteNum, g, x, 0, w, getHeight(),
  60343. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60344. noteUnderMouse == noteNum,
  60345. lineColour, textColour);
  60346. else if (orientation == verticalKeyboardFacingLeft)
  60347. drawWhiteNote (noteNum, g, 0, x, getWidth(), w,
  60348. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60349. noteUnderMouse == noteNum,
  60350. lineColour, textColour);
  60351. else if (orientation == verticalKeyboardFacingRight)
  60352. drawWhiteNote (noteNum, g, 0, getHeight() - x - w, getWidth(), w,
  60353. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60354. noteUnderMouse == noteNum,
  60355. lineColour, textColour);
  60356. }
  60357. }
  60358. }
  60359. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  60360. if (orientation == verticalKeyboardFacingLeft)
  60361. {
  60362. x1 = getWidth() - 1.0f;
  60363. x2 = getWidth() - 5.0f;
  60364. }
  60365. else if (orientation == verticalKeyboardFacingRight)
  60366. x2 = 5.0f;
  60367. else
  60368. y2 = 5.0f;
  60369. g.setGradientFill (ColourGradient (Colours::black.withAlpha (0.3f), x1, y1,
  60370. Colours::transparentBlack, x2, y2, false));
  60371. getKeyPos (rangeEnd, x, w);
  60372. x += w;
  60373. if (orientation == verticalKeyboardFacingLeft)
  60374. g.fillRect (getWidth() - 5, 0, 5, x);
  60375. else if (orientation == verticalKeyboardFacingRight)
  60376. g.fillRect (0, 0, 5, x);
  60377. else
  60378. g.fillRect (0, 0, x, 5);
  60379. g.setColour (lineColour);
  60380. if (orientation == verticalKeyboardFacingLeft)
  60381. g.fillRect (0, 0, 1, x);
  60382. else if (orientation == verticalKeyboardFacingRight)
  60383. g.fillRect (getWidth() - 1, 0, 1, x);
  60384. else
  60385. g.fillRect (0, getHeight() - 1, x, 1);
  60386. const Colour blackNoteColour (findColour (blackNoteColourId));
  60387. for (octave = 0; octave < 128; octave += 12)
  60388. {
  60389. for (int black = 0; black < 5; ++black)
  60390. {
  60391. const int noteNum = octave + blackNotes [black];
  60392. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60393. {
  60394. getKeyPos (noteNum, x, w);
  60395. if (orientation == horizontalKeyboard)
  60396. drawBlackNote (noteNum, g, x, 0, w, blackNoteLength,
  60397. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60398. noteUnderMouse == noteNum,
  60399. blackNoteColour);
  60400. else if (orientation == verticalKeyboardFacingLeft)
  60401. drawBlackNote (noteNum, g, getWidth() - blackNoteLength, x, blackNoteLength, w,
  60402. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60403. noteUnderMouse == noteNum,
  60404. blackNoteColour);
  60405. else if (orientation == verticalKeyboardFacingRight)
  60406. drawBlackNote (noteNum, g, 0, getHeight() - x - w, blackNoteLength, w,
  60407. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60408. noteUnderMouse == noteNum,
  60409. blackNoteColour);
  60410. }
  60411. }
  60412. }
  60413. }
  60414. void MidiKeyboardComponent::drawWhiteNote (int midiNoteNumber,
  60415. Graphics& g, int x, int y, int w, int h,
  60416. bool isDown, bool isOver,
  60417. const Colour& lineColour,
  60418. const Colour& textColour)
  60419. {
  60420. Colour c (Colours::transparentWhite);
  60421. if (isDown)
  60422. c = findColour (keyDownOverlayColourId);
  60423. if (isOver)
  60424. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  60425. g.setColour (c);
  60426. g.fillRect (x, y, w, h);
  60427. const String text (getWhiteNoteText (midiNoteNumber));
  60428. if (! text.isEmpty())
  60429. {
  60430. g.setColour (textColour);
  60431. Font f (jmin (12.0f, keyWidth * 0.9f));
  60432. f.setHorizontalScale (0.8f);
  60433. g.setFont (f);
  60434. Justification justification (Justification::centredBottom);
  60435. if (orientation == verticalKeyboardFacingLeft)
  60436. justification = Justification::centredLeft;
  60437. else if (orientation == verticalKeyboardFacingRight)
  60438. justification = Justification::centredRight;
  60439. g.drawFittedText (text, x + 2, y + 2, w - 4, h - 4, justification, 1);
  60440. }
  60441. g.setColour (lineColour);
  60442. if (orientation == horizontalKeyboard)
  60443. g.fillRect (x, y, 1, h);
  60444. else if (orientation == verticalKeyboardFacingLeft)
  60445. g.fillRect (x, y, w, 1);
  60446. else if (orientation == verticalKeyboardFacingRight)
  60447. g.fillRect (x, y + h - 1, w, 1);
  60448. if (midiNoteNumber == rangeEnd)
  60449. {
  60450. if (orientation == horizontalKeyboard)
  60451. g.fillRect (x + w, y, 1, h);
  60452. else if (orientation == verticalKeyboardFacingLeft)
  60453. g.fillRect (x, y + h, w, 1);
  60454. else if (orientation == verticalKeyboardFacingRight)
  60455. g.fillRect (x, y - 1, w, 1);
  60456. }
  60457. }
  60458. void MidiKeyboardComponent::drawBlackNote (int /*midiNoteNumber*/,
  60459. Graphics& g, int x, int y, int w, int h,
  60460. bool isDown, bool isOver,
  60461. const Colour& noteFillColour)
  60462. {
  60463. Colour c (noteFillColour);
  60464. if (isDown)
  60465. c = c.overlaidWith (findColour (keyDownOverlayColourId));
  60466. if (isOver)
  60467. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  60468. g.setColour (c);
  60469. g.fillRect (x, y, w, h);
  60470. if (isDown)
  60471. {
  60472. g.setColour (noteFillColour);
  60473. g.drawRect (x, y, w, h);
  60474. }
  60475. else
  60476. {
  60477. const int xIndent = jmax (1, jmin (w, h) / 8);
  60478. g.setColour (c.brighter());
  60479. if (orientation == horizontalKeyboard)
  60480. g.fillRect (x + xIndent, y, w - xIndent * 2, 7 * h / 8);
  60481. else if (orientation == verticalKeyboardFacingLeft)
  60482. g.fillRect (x + w / 8, y + xIndent, w - w / 8, h - xIndent * 2);
  60483. else if (orientation == verticalKeyboardFacingRight)
  60484. g.fillRect (x, y + xIndent, 7 * w / 8, h - xIndent * 2);
  60485. }
  60486. }
  60487. void MidiKeyboardComponent::setOctaveForMiddleC (const int octaveNumForMiddleC_)
  60488. {
  60489. octaveNumForMiddleC = octaveNumForMiddleC_;
  60490. repaint();
  60491. }
  60492. const String MidiKeyboardComponent::getWhiteNoteText (const int midiNoteNumber)
  60493. {
  60494. if (keyWidth > 14.0f && midiNoteNumber % 12 == 0)
  60495. return MidiMessage::getMidiNoteName (midiNoteNumber, true, true, octaveNumForMiddleC);
  60496. return String::empty;
  60497. }
  60498. void MidiKeyboardComponent::drawUpDownButton (Graphics& g, int w, int h,
  60499. const bool isMouseOver_,
  60500. const bool isButtonDown,
  60501. const bool movesOctavesUp)
  60502. {
  60503. g.fillAll (findColour (upDownButtonBackgroundColourId));
  60504. float angle;
  60505. if (orientation == MidiKeyboardComponent::horizontalKeyboard)
  60506. angle = movesOctavesUp ? 0.0f : 0.5f;
  60507. else if (orientation == MidiKeyboardComponent::verticalKeyboardFacingLeft)
  60508. angle = movesOctavesUp ? 0.25f : 0.75f;
  60509. else
  60510. angle = movesOctavesUp ? 0.75f : 0.25f;
  60511. Path path;
  60512. path.lineTo (0.0f, 1.0f);
  60513. path.lineTo (1.0f, 0.5f);
  60514. path.closeSubPath();
  60515. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * angle, 0.5f, 0.5f));
  60516. g.setColour (findColour (upDownButtonArrowColourId)
  60517. .withAlpha (isButtonDown ? 1.0f : (isMouseOver_ ? 0.6f : 0.4f)));
  60518. g.fillPath (path, path.getTransformToScaleToFit (1.0f, 1.0f,
  60519. w - 2.0f,
  60520. h - 2.0f,
  60521. true));
  60522. }
  60523. void MidiKeyboardComponent::resized()
  60524. {
  60525. int w = getWidth();
  60526. int h = getHeight();
  60527. if (w > 0 && h > 0)
  60528. {
  60529. if (orientation != horizontalKeyboard)
  60530. swapVariables (w, h);
  60531. blackNoteLength = roundToInt (h * 0.7f);
  60532. int kx2, kw2;
  60533. getKeyPos (rangeEnd, kx2, kw2);
  60534. kx2 += kw2;
  60535. if (firstKey != rangeStart)
  60536. {
  60537. int kx1, kw1;
  60538. getKeyPos (rangeStart, kx1, kw1);
  60539. if (kx2 - kx1 <= w)
  60540. {
  60541. firstKey = rangeStart;
  60542. sendChangeMessage (this);
  60543. repaint();
  60544. }
  60545. }
  60546. const bool showScrollButtons = canScroll && (firstKey > rangeStart || kx2 > w + xOffset * 2);
  60547. scrollDown->setVisible (showScrollButtons);
  60548. scrollUp->setVisible (showScrollButtons);
  60549. xOffset = 0;
  60550. if (showScrollButtons)
  60551. {
  60552. const int scrollButtonW = jmin (12, w / 2);
  60553. if (orientation == horizontalKeyboard)
  60554. {
  60555. scrollDown->setBounds (0, 0, scrollButtonW, getHeight());
  60556. scrollUp->setBounds (getWidth() - scrollButtonW, 0, scrollButtonW, getHeight());
  60557. }
  60558. else if (orientation == verticalKeyboardFacingLeft)
  60559. {
  60560. scrollDown->setBounds (0, 0, getWidth(), scrollButtonW);
  60561. scrollUp->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  60562. }
  60563. else if (orientation == verticalKeyboardFacingRight)
  60564. {
  60565. scrollDown->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  60566. scrollUp->setBounds (0, 0, getWidth(), scrollButtonW);
  60567. }
  60568. int endOfLastKey, kw;
  60569. getKeyPos (rangeEnd, endOfLastKey, kw);
  60570. endOfLastKey += kw;
  60571. float mousePositionVelocity;
  60572. const int spaceAvailable = w - scrollButtonW * 2;
  60573. const int lastStartKey = remappedXYToNote (Point<int> (endOfLastKey - spaceAvailable, 0), mousePositionVelocity) + 1;
  60574. if (lastStartKey >= 0 && firstKey > lastStartKey)
  60575. {
  60576. firstKey = jlimit (rangeStart, rangeEnd, lastStartKey);
  60577. sendChangeMessage (this);
  60578. }
  60579. int newOffset = 0;
  60580. getKeyPos (firstKey, newOffset, kw);
  60581. xOffset = newOffset - scrollButtonW;
  60582. }
  60583. else
  60584. {
  60585. firstKey = rangeStart;
  60586. }
  60587. timerCallback();
  60588. repaint();
  60589. }
  60590. }
  60591. void MidiKeyboardComponent::handleNoteOn (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/, float /*velocity*/)
  60592. {
  60593. triggerAsyncUpdate();
  60594. }
  60595. void MidiKeyboardComponent::handleNoteOff (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/)
  60596. {
  60597. triggerAsyncUpdate();
  60598. }
  60599. void MidiKeyboardComponent::handleAsyncUpdate()
  60600. {
  60601. for (int i = rangeStart; i <= rangeEnd; ++i)
  60602. {
  60603. if (keysCurrentlyDrawnDown[i] != state.isNoteOnForChannels (midiInChannelMask, i))
  60604. {
  60605. keysCurrentlyDrawnDown.setBit (i, state.isNoteOnForChannels (midiInChannelMask, i));
  60606. repaintNote (i);
  60607. }
  60608. }
  60609. }
  60610. void MidiKeyboardComponent::resetAnyKeysInUse()
  60611. {
  60612. if (keysPressed.countNumberOfSetBits() > 0 || mouseDownNote > 0)
  60613. {
  60614. state.allNotesOff (midiChannel);
  60615. keysPressed.clear();
  60616. mouseDownNote = -1;
  60617. }
  60618. }
  60619. void MidiKeyboardComponent::updateNoteUnderMouse (const Point<int>& pos)
  60620. {
  60621. float mousePositionVelocity = 0.0f;
  60622. const int newNote = (mouseDragging || isMouseOver())
  60623. ? xyToNote (pos, mousePositionVelocity) : -1;
  60624. if (noteUnderMouse != newNote)
  60625. {
  60626. if (mouseDownNote >= 0)
  60627. {
  60628. state.noteOff (midiChannel, mouseDownNote);
  60629. mouseDownNote = -1;
  60630. }
  60631. if (mouseDragging && newNote >= 0)
  60632. {
  60633. if (! useMousePositionForVelocity)
  60634. mousePositionVelocity = 1.0f;
  60635. state.noteOn (midiChannel, newNote, mousePositionVelocity * velocity);
  60636. mouseDownNote = newNote;
  60637. }
  60638. repaintNote (noteUnderMouse);
  60639. noteUnderMouse = newNote;
  60640. repaintNote (noteUnderMouse);
  60641. }
  60642. else if (mouseDownNote >= 0 && ! mouseDragging)
  60643. {
  60644. state.noteOff (midiChannel, mouseDownNote);
  60645. mouseDownNote = -1;
  60646. }
  60647. }
  60648. void MidiKeyboardComponent::mouseMove (const MouseEvent& e)
  60649. {
  60650. updateNoteUnderMouse (e.getPosition());
  60651. stopTimer();
  60652. }
  60653. void MidiKeyboardComponent::mouseDrag (const MouseEvent& e)
  60654. {
  60655. float mousePositionVelocity;
  60656. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  60657. if (newNote >= 0)
  60658. mouseDraggedToKey (newNote, e);
  60659. updateNoteUnderMouse (e.getPosition());
  60660. }
  60661. bool MidiKeyboardComponent::mouseDownOnKey (int /*midiNoteNumber*/, const MouseEvent&)
  60662. {
  60663. return true;
  60664. }
  60665. void MidiKeyboardComponent::mouseDraggedToKey (int /*midiNoteNumber*/, const MouseEvent&)
  60666. {
  60667. }
  60668. void MidiKeyboardComponent::mouseDown (const MouseEvent& e)
  60669. {
  60670. float mousePositionVelocity;
  60671. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  60672. mouseDragging = false;
  60673. if (newNote >= 0 && mouseDownOnKey (newNote, e))
  60674. {
  60675. repaintNote (noteUnderMouse);
  60676. noteUnderMouse = -1;
  60677. mouseDragging = true;
  60678. updateNoteUnderMouse (e.getPosition());
  60679. startTimer (500);
  60680. }
  60681. }
  60682. void MidiKeyboardComponent::mouseUp (const MouseEvent& e)
  60683. {
  60684. mouseDragging = false;
  60685. updateNoteUnderMouse (e.getPosition());
  60686. stopTimer();
  60687. }
  60688. void MidiKeyboardComponent::mouseEnter (const MouseEvent& e)
  60689. {
  60690. updateNoteUnderMouse (e.getPosition());
  60691. }
  60692. void MidiKeyboardComponent::mouseExit (const MouseEvent& e)
  60693. {
  60694. updateNoteUnderMouse (e.getPosition());
  60695. }
  60696. void MidiKeyboardComponent::mouseWheelMove (const MouseEvent&, float ix, float iy)
  60697. {
  60698. setLowestVisibleKey (getLowestVisibleKey() + roundToInt ((ix != 0 ? ix : iy) * 5.0f));
  60699. }
  60700. void MidiKeyboardComponent::timerCallback()
  60701. {
  60702. updateNoteUnderMouse (getMouseXYRelative());
  60703. }
  60704. void MidiKeyboardComponent::clearKeyMappings()
  60705. {
  60706. resetAnyKeysInUse();
  60707. keyPressNotes.clear();
  60708. keyPresses.clear();
  60709. }
  60710. void MidiKeyboardComponent::setKeyPressForNote (const KeyPress& key,
  60711. const int midiNoteOffsetFromC)
  60712. {
  60713. removeKeyPressForNote (midiNoteOffsetFromC);
  60714. keyPressNotes.add (midiNoteOffsetFromC);
  60715. keyPresses.add (key);
  60716. }
  60717. void MidiKeyboardComponent::removeKeyPressForNote (const int midiNoteOffsetFromC)
  60718. {
  60719. for (int i = keyPressNotes.size(); --i >= 0;)
  60720. {
  60721. if (keyPressNotes.getUnchecked (i) == midiNoteOffsetFromC)
  60722. {
  60723. keyPressNotes.remove (i);
  60724. keyPresses.remove (i);
  60725. }
  60726. }
  60727. }
  60728. void MidiKeyboardComponent::setKeyPressBaseOctave (const int newOctaveNumber)
  60729. {
  60730. jassert (newOctaveNumber >= 0 && newOctaveNumber <= 10);
  60731. keyMappingOctave = newOctaveNumber;
  60732. }
  60733. bool MidiKeyboardComponent::keyStateChanged (const bool /*isKeyDown*/)
  60734. {
  60735. bool keyPressUsed = false;
  60736. for (int i = keyPresses.size(); --i >= 0;)
  60737. {
  60738. const int note = 12 * keyMappingOctave + keyPressNotes.getUnchecked (i);
  60739. if (keyPresses.getReference(i).isCurrentlyDown())
  60740. {
  60741. if (! keysPressed [note])
  60742. {
  60743. keysPressed.setBit (note);
  60744. state.noteOn (midiChannel, note, velocity);
  60745. keyPressUsed = true;
  60746. }
  60747. }
  60748. else
  60749. {
  60750. if (keysPressed [note])
  60751. {
  60752. keysPressed.clearBit (note);
  60753. state.noteOff (midiChannel, note);
  60754. keyPressUsed = true;
  60755. }
  60756. }
  60757. }
  60758. return keyPressUsed;
  60759. }
  60760. void MidiKeyboardComponent::focusLost (FocusChangeType)
  60761. {
  60762. resetAnyKeysInUse();
  60763. }
  60764. END_JUCE_NAMESPACE
  60765. /*** End of inlined file: juce_MidiKeyboardComponent.cpp ***/
  60766. /*** Start of inlined file: juce_OpenGLComponent.cpp ***/
  60767. #if JUCE_OPENGL
  60768. BEGIN_JUCE_NAMESPACE
  60769. extern void juce_glViewport (const int w, const int h);
  60770. OpenGLPixelFormat::OpenGLPixelFormat (const int bitsPerRGBComponent,
  60771. const int alphaBits_,
  60772. const int depthBufferBits_,
  60773. const int stencilBufferBits_)
  60774. : redBits (bitsPerRGBComponent),
  60775. greenBits (bitsPerRGBComponent),
  60776. blueBits (bitsPerRGBComponent),
  60777. alphaBits (alphaBits_),
  60778. depthBufferBits (depthBufferBits_),
  60779. stencilBufferBits (stencilBufferBits_),
  60780. accumulationBufferRedBits (0),
  60781. accumulationBufferGreenBits (0),
  60782. accumulationBufferBlueBits (0),
  60783. accumulationBufferAlphaBits (0),
  60784. fullSceneAntiAliasingNumSamples (0)
  60785. {
  60786. }
  60787. OpenGLPixelFormat::OpenGLPixelFormat (const OpenGLPixelFormat& other)
  60788. : redBits (other.redBits),
  60789. greenBits (other.greenBits),
  60790. blueBits (other.blueBits),
  60791. alphaBits (other.alphaBits),
  60792. depthBufferBits (other.depthBufferBits),
  60793. stencilBufferBits (other.stencilBufferBits),
  60794. accumulationBufferRedBits (other.accumulationBufferRedBits),
  60795. accumulationBufferGreenBits (other.accumulationBufferGreenBits),
  60796. accumulationBufferBlueBits (other.accumulationBufferBlueBits),
  60797. accumulationBufferAlphaBits (other.accumulationBufferAlphaBits),
  60798. fullSceneAntiAliasingNumSamples (other.fullSceneAntiAliasingNumSamples)
  60799. {
  60800. }
  60801. OpenGLPixelFormat& OpenGLPixelFormat::operator= (const OpenGLPixelFormat& other)
  60802. {
  60803. redBits = other.redBits;
  60804. greenBits = other.greenBits;
  60805. blueBits = other.blueBits;
  60806. alphaBits = other.alphaBits;
  60807. depthBufferBits = other.depthBufferBits;
  60808. stencilBufferBits = other.stencilBufferBits;
  60809. accumulationBufferRedBits = other.accumulationBufferRedBits;
  60810. accumulationBufferGreenBits = other.accumulationBufferGreenBits;
  60811. accumulationBufferBlueBits = other.accumulationBufferBlueBits;
  60812. accumulationBufferAlphaBits = other.accumulationBufferAlphaBits;
  60813. fullSceneAntiAliasingNumSamples = other.fullSceneAntiAliasingNumSamples;
  60814. return *this;
  60815. }
  60816. bool OpenGLPixelFormat::operator== (const OpenGLPixelFormat& other) const
  60817. {
  60818. return redBits == other.redBits
  60819. && greenBits == other.greenBits
  60820. && blueBits == other.blueBits
  60821. && alphaBits == other.alphaBits
  60822. && depthBufferBits == other.depthBufferBits
  60823. && stencilBufferBits == other.stencilBufferBits
  60824. && accumulationBufferRedBits == other.accumulationBufferRedBits
  60825. && accumulationBufferGreenBits == other.accumulationBufferGreenBits
  60826. && accumulationBufferBlueBits == other.accumulationBufferBlueBits
  60827. && accumulationBufferAlphaBits == other.accumulationBufferAlphaBits
  60828. && fullSceneAntiAliasingNumSamples == other.fullSceneAntiAliasingNumSamples;
  60829. }
  60830. static Array<OpenGLContext*> knownContexts;
  60831. OpenGLContext::OpenGLContext() throw()
  60832. {
  60833. knownContexts.add (this);
  60834. }
  60835. OpenGLContext::~OpenGLContext()
  60836. {
  60837. knownContexts.removeValue (this);
  60838. }
  60839. OpenGLContext* OpenGLContext::getCurrentContext()
  60840. {
  60841. for (int i = knownContexts.size(); --i >= 0;)
  60842. {
  60843. OpenGLContext* const oglc = knownContexts.getUnchecked(i);
  60844. if (oglc->isActive())
  60845. return oglc;
  60846. }
  60847. return 0;
  60848. }
  60849. class OpenGLComponent::OpenGLComponentWatcher : public ComponentMovementWatcher
  60850. {
  60851. public:
  60852. OpenGLComponentWatcher (OpenGLComponent* const owner_)
  60853. : ComponentMovementWatcher (owner_),
  60854. owner (owner_),
  60855. wasShowing (false)
  60856. {
  60857. }
  60858. ~OpenGLComponentWatcher() {}
  60859. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  60860. {
  60861. owner->updateContextPosition();
  60862. }
  60863. void componentPeerChanged()
  60864. {
  60865. const ScopedLock sl (owner->getContextLock());
  60866. owner->deleteContext();
  60867. }
  60868. void componentVisibilityChanged (Component&)
  60869. {
  60870. const bool isShowingNow = owner->isShowing();
  60871. if (wasShowing != isShowingNow)
  60872. {
  60873. wasShowing = isShowingNow;
  60874. if (! isShowingNow)
  60875. {
  60876. const ScopedLock sl (owner->getContextLock());
  60877. owner->deleteContext();
  60878. }
  60879. }
  60880. }
  60881. juce_UseDebuggingNewOperator
  60882. private:
  60883. OpenGLComponent* const owner;
  60884. bool wasShowing;
  60885. };
  60886. OpenGLComponent::OpenGLComponent (const OpenGLType type_)
  60887. : type (type_),
  60888. contextToShareListsWith (0),
  60889. needToUpdateViewport (true)
  60890. {
  60891. setOpaque (true);
  60892. componentWatcher = new OpenGLComponentWatcher (this);
  60893. }
  60894. OpenGLComponent::~OpenGLComponent()
  60895. {
  60896. deleteContext();
  60897. componentWatcher = 0;
  60898. }
  60899. void OpenGLComponent::deleteContext()
  60900. {
  60901. const ScopedLock sl (contextLock);
  60902. context = 0;
  60903. }
  60904. void OpenGLComponent::updateContextPosition()
  60905. {
  60906. needToUpdateViewport = true;
  60907. if (getWidth() > 0 && getHeight() > 0)
  60908. {
  60909. Component* const topComp = getTopLevelComponent();
  60910. if (topComp->getPeer() != 0)
  60911. {
  60912. const ScopedLock sl (contextLock);
  60913. if (context != 0)
  60914. context->updateWindowPosition (getScreenX() - topComp->getScreenX(),
  60915. getScreenY() - topComp->getScreenY(),
  60916. getWidth(),
  60917. getHeight(),
  60918. topComp->getHeight());
  60919. }
  60920. }
  60921. }
  60922. const OpenGLPixelFormat OpenGLComponent::getPixelFormat() const
  60923. {
  60924. OpenGLPixelFormat pf;
  60925. const ScopedLock sl (contextLock);
  60926. if (context != 0)
  60927. pf = context->getPixelFormat();
  60928. return pf;
  60929. }
  60930. void OpenGLComponent::setPixelFormat (const OpenGLPixelFormat& formatToUse)
  60931. {
  60932. if (! (preferredPixelFormat == formatToUse))
  60933. {
  60934. const ScopedLock sl (contextLock);
  60935. deleteContext();
  60936. preferredPixelFormat = formatToUse;
  60937. }
  60938. }
  60939. void OpenGLComponent::shareWith (OpenGLContext* c)
  60940. {
  60941. if (contextToShareListsWith != c)
  60942. {
  60943. const ScopedLock sl (contextLock);
  60944. deleteContext();
  60945. contextToShareListsWith = c;
  60946. }
  60947. }
  60948. bool OpenGLComponent::makeCurrentContextActive()
  60949. {
  60950. if (context == 0)
  60951. {
  60952. const ScopedLock sl (contextLock);
  60953. if (isShowing() && getTopLevelComponent()->getPeer() != 0)
  60954. {
  60955. context = createContext();
  60956. if (context != 0)
  60957. {
  60958. updateContextPosition();
  60959. if (context->makeActive())
  60960. newOpenGLContextCreated();
  60961. }
  60962. }
  60963. }
  60964. return context != 0 && context->makeActive();
  60965. }
  60966. void OpenGLComponent::makeCurrentContextInactive()
  60967. {
  60968. if (context != 0)
  60969. context->makeInactive();
  60970. }
  60971. bool OpenGLComponent::isActiveContext() const throw()
  60972. {
  60973. return context != 0 && context->isActive();
  60974. }
  60975. void OpenGLComponent::swapBuffers()
  60976. {
  60977. if (context != 0)
  60978. context->swapBuffers();
  60979. }
  60980. void OpenGLComponent::paint (Graphics&)
  60981. {
  60982. if (renderAndSwapBuffers())
  60983. {
  60984. ComponentPeer* const peer = getPeer();
  60985. if (peer != 0)
  60986. {
  60987. const Point<int> topLeft (getScreenPosition() - peer->getScreenPosition());
  60988. peer->addMaskedRegion (topLeft.getX(), topLeft.getY(), getWidth(), getHeight());
  60989. }
  60990. }
  60991. }
  60992. bool OpenGLComponent::renderAndSwapBuffers()
  60993. {
  60994. const ScopedLock sl (contextLock);
  60995. if (! makeCurrentContextActive())
  60996. return false;
  60997. if (needToUpdateViewport)
  60998. {
  60999. needToUpdateViewport = false;
  61000. juce_glViewport (getWidth(), getHeight());
  61001. }
  61002. renderOpenGL();
  61003. swapBuffers();
  61004. return true;
  61005. }
  61006. void OpenGLComponent::internalRepaint (int x, int y, int w, int h)
  61007. {
  61008. Component::internalRepaint (x, y, w, h);
  61009. if (context != 0)
  61010. context->repaint();
  61011. }
  61012. END_JUCE_NAMESPACE
  61013. #endif
  61014. /*** End of inlined file: juce_OpenGLComponent.cpp ***/
  61015. /*** Start of inlined file: juce_PreferencesPanel.cpp ***/
  61016. BEGIN_JUCE_NAMESPACE
  61017. PreferencesPanel::PreferencesPanel()
  61018. : buttonSize (70)
  61019. {
  61020. }
  61021. PreferencesPanel::~PreferencesPanel()
  61022. {
  61023. currentPage = 0;
  61024. deleteAllChildren();
  61025. }
  61026. void PreferencesPanel::addSettingsPage (const String& title,
  61027. const Drawable* icon,
  61028. const Drawable* overIcon,
  61029. const Drawable* downIcon)
  61030. {
  61031. DrawableButton* button = new DrawableButton (title, DrawableButton::ImageAboveTextLabel);
  61032. button->setImages (icon, overIcon, downIcon);
  61033. button->setRadioGroupId (1);
  61034. button->addButtonListener (this);
  61035. button->setClickingTogglesState (true);
  61036. button->setWantsKeyboardFocus (false);
  61037. addAndMakeVisible (button);
  61038. resized();
  61039. if (currentPage == 0)
  61040. setCurrentPage (title);
  61041. }
  61042. void PreferencesPanel::addSettingsPage (const String& title,
  61043. const void* imageData,
  61044. const int imageDataSize)
  61045. {
  61046. DrawableImage icon, iconOver, iconDown;
  61047. icon.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61048. iconOver.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61049. iconOver.setOverlayColour (Colours::black.withAlpha (0.12f));
  61050. iconDown.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61051. iconDown.setOverlayColour (Colours::black.withAlpha (0.25f));
  61052. addSettingsPage (title, &icon, &iconOver, &iconDown);
  61053. }
  61054. class PrefsDialogWindow : public DialogWindow
  61055. {
  61056. public:
  61057. PrefsDialogWindow (const String& dialogtitle,
  61058. const Colour& backgroundColour)
  61059. : DialogWindow (dialogtitle, backgroundColour, true)
  61060. {
  61061. }
  61062. ~PrefsDialogWindow()
  61063. {
  61064. }
  61065. void closeButtonPressed()
  61066. {
  61067. exitModalState (0);
  61068. }
  61069. private:
  61070. PrefsDialogWindow (const PrefsDialogWindow&);
  61071. PrefsDialogWindow& operator= (const PrefsDialogWindow&);
  61072. };
  61073. void PreferencesPanel::showInDialogBox (const String& dialogtitle,
  61074. int dialogWidth,
  61075. int dialogHeight,
  61076. const Colour& backgroundColour)
  61077. {
  61078. setSize (dialogWidth, dialogHeight);
  61079. PrefsDialogWindow dw (dialogtitle, backgroundColour);
  61080. dw.setContentComponent (this, true, true);
  61081. dw.centreAroundComponent (0, dw.getWidth(), dw.getHeight());
  61082. dw.runModalLoop();
  61083. dw.setContentComponent (0, false, false);
  61084. }
  61085. void PreferencesPanel::resized()
  61086. {
  61087. int x = 0;
  61088. for (int i = 0; i < getNumChildComponents(); ++i)
  61089. {
  61090. Component* c = getChildComponent (i);
  61091. if (dynamic_cast <DrawableButton*> (c) == 0)
  61092. {
  61093. c->setBounds (0, buttonSize + 5, getWidth(), getHeight() - buttonSize - 5);
  61094. }
  61095. else
  61096. {
  61097. c->setBounds (x, 0, buttonSize, buttonSize);
  61098. x += buttonSize;
  61099. }
  61100. }
  61101. }
  61102. void PreferencesPanel::paint (Graphics& g)
  61103. {
  61104. g.setColour (Colours::grey);
  61105. g.fillRect (0, buttonSize + 2, getWidth(), 1);
  61106. }
  61107. void PreferencesPanel::setCurrentPage (const String& pageName)
  61108. {
  61109. if (currentPageName != pageName)
  61110. {
  61111. currentPageName = pageName;
  61112. currentPage = 0;
  61113. currentPage = createComponentForPage (pageName);
  61114. if (currentPage != 0)
  61115. {
  61116. addAndMakeVisible (currentPage);
  61117. currentPage->toBack();
  61118. resized();
  61119. }
  61120. for (int i = 0; i < getNumChildComponents(); ++i)
  61121. {
  61122. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  61123. if (db != 0 && db->getName() == pageName)
  61124. {
  61125. db->setToggleState (true, false);
  61126. break;
  61127. }
  61128. }
  61129. }
  61130. }
  61131. void PreferencesPanel::buttonClicked (Button*)
  61132. {
  61133. for (int i = 0; i < getNumChildComponents(); ++i)
  61134. {
  61135. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  61136. if (db != 0 && db->getToggleState())
  61137. {
  61138. setCurrentPage (db->getName());
  61139. break;
  61140. }
  61141. }
  61142. }
  61143. END_JUCE_NAMESPACE
  61144. /*** End of inlined file: juce_PreferencesPanel.cpp ***/
  61145. /*** Start of inlined file: juce_SystemTrayIconComponent.cpp ***/
  61146. #if JUCE_WINDOWS || JUCE_LINUX
  61147. BEGIN_JUCE_NAMESPACE
  61148. SystemTrayIconComponent::SystemTrayIconComponent()
  61149. {
  61150. addToDesktop (0);
  61151. }
  61152. SystemTrayIconComponent::~SystemTrayIconComponent()
  61153. {
  61154. }
  61155. END_JUCE_NAMESPACE
  61156. #endif
  61157. /*** End of inlined file: juce_SystemTrayIconComponent.cpp ***/
  61158. /*** Start of inlined file: juce_AlertWindow.cpp ***/
  61159. BEGIN_JUCE_NAMESPACE
  61160. class AlertWindowTextEditor : public TextEditor
  61161. {
  61162. public:
  61163. AlertWindowTextEditor (const String& name, const bool isPasswordBox)
  61164. : TextEditor (name, isPasswordBox ? getDefaultPasswordChar() : 0)
  61165. {
  61166. setSelectAllWhenFocused (true);
  61167. }
  61168. ~AlertWindowTextEditor()
  61169. {
  61170. }
  61171. void returnPressed()
  61172. {
  61173. // pass these up the component hierarchy to be trigger the buttons
  61174. getParentComponent()->keyPressed (KeyPress (KeyPress::returnKey, 0, '\n'));
  61175. }
  61176. void escapePressed()
  61177. {
  61178. // pass these up the component hierarchy to be trigger the buttons
  61179. getParentComponent()->keyPressed (KeyPress (KeyPress::escapeKey, 0, 0));
  61180. }
  61181. private:
  61182. AlertWindowTextEditor (const AlertWindowTextEditor&);
  61183. AlertWindowTextEditor& operator= (const AlertWindowTextEditor&);
  61184. static juce_wchar getDefaultPasswordChar() throw()
  61185. {
  61186. #if JUCE_LINUX
  61187. return 0x2022;
  61188. #else
  61189. return 0x25cf;
  61190. #endif
  61191. }
  61192. };
  61193. AlertWindow::AlertWindow (const String& title,
  61194. const String& message,
  61195. AlertIconType iconType,
  61196. Component* associatedComponent_)
  61197. : TopLevelWindow (title, true),
  61198. alertIconType (iconType),
  61199. associatedComponent (associatedComponent_)
  61200. {
  61201. if (message.isEmpty())
  61202. text = " "; // to force an update if the message is empty
  61203. setMessage (message);
  61204. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  61205. {
  61206. Component* const c = Desktop::getInstance().getComponent (i);
  61207. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  61208. {
  61209. setAlwaysOnTop (true);
  61210. break;
  61211. }
  61212. }
  61213. if (JUCEApplication::getInstance() == 0)
  61214. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  61215. lookAndFeelChanged();
  61216. constrainer.setMinimumOnscreenAmounts (0x10000, 0x10000, 0x10000, 0x10000);
  61217. }
  61218. AlertWindow::~AlertWindow()
  61219. {
  61220. for (int i = customComps.size(); --i >= 0;)
  61221. removeChildComponent ((Component*) customComps[i]);
  61222. deleteAllChildren();
  61223. }
  61224. void AlertWindow::userTriedToCloseWindow()
  61225. {
  61226. exitModalState (0);
  61227. }
  61228. void AlertWindow::setMessage (const String& message)
  61229. {
  61230. const String newMessage (message.substring (0, 2048));
  61231. if (text != newMessage)
  61232. {
  61233. text = newMessage;
  61234. font.setHeight (15.0f);
  61235. Font titleFont (font.getHeight() * 1.1f, Font::bold);
  61236. textLayout.setText (getName() + "\n\n", titleFont);
  61237. textLayout.appendText (text, font);
  61238. updateLayout (true);
  61239. repaint();
  61240. }
  61241. }
  61242. void AlertWindow::buttonClicked (Button* button)
  61243. {
  61244. for (int i = 0; i < buttons.size(); i++)
  61245. {
  61246. TextButton* const c = (TextButton*) buttons[i];
  61247. if (button->getName() == c->getName())
  61248. {
  61249. if (c->getParentComponent() != 0)
  61250. c->getParentComponent()->exitModalState (c->getCommandID());
  61251. break;
  61252. }
  61253. }
  61254. }
  61255. void AlertWindow::addButton (const String& name,
  61256. const int returnValue,
  61257. const KeyPress& shortcutKey1,
  61258. const KeyPress& shortcutKey2)
  61259. {
  61260. TextButton* const b = new TextButton (name, String::empty);
  61261. b->setWantsKeyboardFocus (true);
  61262. b->setMouseClickGrabsKeyboardFocus (false);
  61263. b->setCommandToTrigger (0, returnValue, false);
  61264. b->addShortcut (shortcutKey1);
  61265. b->addShortcut (shortcutKey2);
  61266. b->addButtonListener (this);
  61267. b->changeWidthToFitText (getLookAndFeel().getAlertWindowButtonHeight());
  61268. addAndMakeVisible (b, 0);
  61269. buttons.add (b);
  61270. updateLayout (false);
  61271. }
  61272. int AlertWindow::getNumButtons() const
  61273. {
  61274. return buttons.size();
  61275. }
  61276. void AlertWindow::triggerButtonClick (const String& buttonName)
  61277. {
  61278. for (int i = buttons.size(); --i >= 0;)
  61279. {
  61280. TextButton* const b = (TextButton*) buttons[i];
  61281. if (buttonName == b->getName())
  61282. {
  61283. b->triggerClick();
  61284. break;
  61285. }
  61286. }
  61287. }
  61288. void AlertWindow::addTextEditor (const String& name,
  61289. const String& initialContents,
  61290. const String& onScreenLabel,
  61291. const bool isPasswordBox)
  61292. {
  61293. AlertWindowTextEditor* const tc = new AlertWindowTextEditor (name, isPasswordBox);
  61294. tc->setColour (TextEditor::outlineColourId, findColour (ComboBox::outlineColourId));
  61295. tc->setFont (font);
  61296. tc->setText (initialContents);
  61297. tc->setCaretPosition (initialContents.length());
  61298. addAndMakeVisible (tc);
  61299. textBoxes.add (tc);
  61300. allComps.add (tc);
  61301. textboxNames.add (onScreenLabel);
  61302. updateLayout (false);
  61303. }
  61304. const String AlertWindow::getTextEditorContents (const String& nameOfTextEditor) const
  61305. {
  61306. for (int i = textBoxes.size(); --i >= 0;)
  61307. if (((TextEditor*)textBoxes[i])->getName() == nameOfTextEditor)
  61308. return ((TextEditor*)textBoxes[i])->getText();
  61309. return String::empty;
  61310. }
  61311. void AlertWindow::addComboBox (const String& name,
  61312. const StringArray& items,
  61313. const String& onScreenLabel)
  61314. {
  61315. ComboBox* const cb = new ComboBox (name);
  61316. for (int i = 0; i < items.size(); ++i)
  61317. cb->addItem (items[i], i + 1);
  61318. addAndMakeVisible (cb);
  61319. cb->setSelectedItemIndex (0);
  61320. comboBoxes.add (cb);
  61321. allComps.add (cb);
  61322. comboBoxNames.add (onScreenLabel);
  61323. updateLayout (false);
  61324. }
  61325. ComboBox* AlertWindow::getComboBoxComponent (const String& nameOfList) const
  61326. {
  61327. for (int i = comboBoxes.size(); --i >= 0;)
  61328. if (((ComboBox*) comboBoxes[i])->getName() == nameOfList)
  61329. return (ComboBox*) comboBoxes[i];
  61330. return 0;
  61331. }
  61332. class AlertTextComp : public TextEditor
  61333. {
  61334. public:
  61335. AlertTextComp (const String& message,
  61336. const Font& font)
  61337. {
  61338. setReadOnly (true);
  61339. setMultiLine (true, true);
  61340. setCaretVisible (false);
  61341. setScrollbarsShown (true);
  61342. lookAndFeelChanged();
  61343. setWantsKeyboardFocus (false);
  61344. setFont (font);
  61345. setText (message, false);
  61346. bestWidth = 2 * (int) std::sqrt (font.getHeight() * font.getStringWidth (message));
  61347. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  61348. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  61349. setColour (TextEditor::shadowColourId, Colours::transparentBlack);
  61350. }
  61351. ~AlertTextComp()
  61352. {
  61353. }
  61354. int getPreferredWidth() const throw() { return bestWidth; }
  61355. void updateLayout (const int width)
  61356. {
  61357. TextLayout text;
  61358. text.appendText (getText(), getFont());
  61359. text.layout (width - 8, Justification::topLeft, true);
  61360. setSize (width, jmin (width, text.getHeight() + (int) getFont().getHeight()));
  61361. }
  61362. private:
  61363. int bestWidth;
  61364. AlertTextComp (const AlertTextComp&);
  61365. AlertTextComp& operator= (const AlertTextComp&);
  61366. };
  61367. void AlertWindow::addTextBlock (const String& textBlock)
  61368. {
  61369. AlertTextComp* const c = new AlertTextComp (textBlock, font);
  61370. textBlocks.add (c);
  61371. allComps.add (c);
  61372. addAndMakeVisible (c);
  61373. updateLayout (false);
  61374. }
  61375. void AlertWindow::addProgressBarComponent (double& progressValue)
  61376. {
  61377. ProgressBar* const pb = new ProgressBar (progressValue);
  61378. progressBars.add (pb);
  61379. allComps.add (pb);
  61380. addAndMakeVisible (pb);
  61381. updateLayout (false);
  61382. }
  61383. void AlertWindow::addCustomComponent (Component* const component)
  61384. {
  61385. customComps.add (component);
  61386. allComps.add (component);
  61387. addAndMakeVisible (component);
  61388. updateLayout (false);
  61389. }
  61390. int AlertWindow::getNumCustomComponents() const
  61391. {
  61392. return customComps.size();
  61393. }
  61394. Component* AlertWindow::getCustomComponent (const int index) const
  61395. {
  61396. return (Component*) customComps [index];
  61397. }
  61398. Component* AlertWindow::removeCustomComponent (const int index)
  61399. {
  61400. Component* const c = getCustomComponent (index);
  61401. if (c != 0)
  61402. {
  61403. customComps.removeValue (c);
  61404. allComps.removeValue (c);
  61405. removeChildComponent (c);
  61406. updateLayout (false);
  61407. }
  61408. return c;
  61409. }
  61410. void AlertWindow::paint (Graphics& g)
  61411. {
  61412. getLookAndFeel().drawAlertBox (g, *this, textArea, textLayout);
  61413. g.setColour (findColour (textColourId));
  61414. g.setFont (getLookAndFeel().getAlertWindowFont());
  61415. int i;
  61416. for (i = textBoxes.size(); --i >= 0;)
  61417. {
  61418. const TextEditor* const te = (TextEditor*) textBoxes[i];
  61419. g.drawFittedText (textboxNames[i],
  61420. te->getX(), te->getY() - 14,
  61421. te->getWidth(), 14,
  61422. Justification::centredLeft, 1);
  61423. }
  61424. for (i = comboBoxNames.size(); --i >= 0;)
  61425. {
  61426. const ComboBox* const cb = (ComboBox*) comboBoxes[i];
  61427. g.drawFittedText (comboBoxNames[i],
  61428. cb->getX(), cb->getY() - 14,
  61429. cb->getWidth(), 14,
  61430. Justification::centredLeft, 1);
  61431. }
  61432. for (i = customComps.size(); --i >= 0;)
  61433. {
  61434. const Component* const c = (Component*) customComps[i];
  61435. g.drawFittedText (c->getName(),
  61436. c->getX(), c->getY() - 14,
  61437. c->getWidth(), 14,
  61438. Justification::centredLeft, 1);
  61439. }
  61440. }
  61441. void AlertWindow::updateLayout (const bool onlyIncreaseSize)
  61442. {
  61443. const int titleH = 24;
  61444. const int iconWidth = 80;
  61445. const int wid = jmax (font.getStringWidth (text),
  61446. font.getStringWidth (getName()));
  61447. const int sw = (int) std::sqrt (font.getHeight() * wid);
  61448. int w = jmin (300 + sw * 2, (int) (getParentWidth() * 0.7f));
  61449. const int edgeGap = 10;
  61450. const int labelHeight = 18;
  61451. int iconSpace;
  61452. if (alertIconType == NoIcon)
  61453. {
  61454. textLayout.layout (w, Justification::horizontallyCentred, true);
  61455. iconSpace = 0;
  61456. }
  61457. else
  61458. {
  61459. textLayout.layout (w, Justification::left, true);
  61460. iconSpace = iconWidth;
  61461. }
  61462. w = jmax (350, textLayout.getWidth() + iconSpace + edgeGap * 4);
  61463. w = jmin (w, (int) (getParentWidth() * 0.7f));
  61464. const int textLayoutH = textLayout.getHeight();
  61465. const int textBottom = 16 + titleH + textLayoutH;
  61466. int h = textBottom;
  61467. int buttonW = 40;
  61468. int i;
  61469. for (i = 0; i < buttons.size(); ++i)
  61470. buttonW += 16 + ((const TextButton*) buttons[i])->getWidth();
  61471. w = jmax (buttonW, w);
  61472. h += (textBoxes.size() + comboBoxes.size() + progressBars.size()) * 50;
  61473. if (buttons.size() > 0)
  61474. h += 20 + ((TextButton*) buttons[0])->getHeight();
  61475. for (i = customComps.size(); --i >= 0;)
  61476. {
  61477. Component* c = (Component*) customComps[i];
  61478. w = jmax (w, (c->getWidth() * 100) / 80);
  61479. h += 10 + c->getHeight();
  61480. if (c->getName().isNotEmpty())
  61481. h += labelHeight;
  61482. }
  61483. for (i = textBlocks.size(); --i >= 0;)
  61484. {
  61485. const AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  61486. w = jmax (w, ac->getPreferredWidth());
  61487. }
  61488. w = jmin (w, (int) (getParentWidth() * 0.7f));
  61489. for (i = textBlocks.size(); --i >= 0;)
  61490. {
  61491. AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  61492. ac->updateLayout ((int) (w * 0.8f));
  61493. h += ac->getHeight() + 10;
  61494. }
  61495. h = jmin (getParentHeight() - 50, h);
  61496. if (onlyIncreaseSize)
  61497. {
  61498. w = jmax (w, getWidth());
  61499. h = jmax (h, getHeight());
  61500. }
  61501. if (! isVisible())
  61502. {
  61503. centreAroundComponent (associatedComponent, w, h);
  61504. }
  61505. else
  61506. {
  61507. const int cx = getX() + getWidth() / 2;
  61508. const int cy = getY() + getHeight() / 2;
  61509. setBounds (cx - w / 2,
  61510. cy - h / 2,
  61511. w, h);
  61512. }
  61513. textArea.setBounds (edgeGap, edgeGap, w - (edgeGap * 2), h - edgeGap);
  61514. const int spacer = 16;
  61515. int totalWidth = -spacer;
  61516. for (i = buttons.size(); --i >= 0;)
  61517. totalWidth += ((TextButton*) buttons[i])->getWidth() + spacer;
  61518. int x = (w - totalWidth) / 2;
  61519. int y = (int) (getHeight() * 0.95f);
  61520. for (i = 0; i < buttons.size(); ++i)
  61521. {
  61522. TextButton* const c = (TextButton*) buttons[i];
  61523. int ny = proportionOfHeight (0.95f) - c->getHeight();
  61524. c->setTopLeftPosition (x, ny);
  61525. if (ny < y)
  61526. y = ny;
  61527. x += c->getWidth() + spacer;
  61528. c->toFront (false);
  61529. }
  61530. y = textBottom;
  61531. for (i = 0; i < allComps.size(); ++i)
  61532. {
  61533. Component* const c = (Component*) allComps[i];
  61534. h = 22;
  61535. const int comboIndex = comboBoxes.indexOf (c);
  61536. if (comboIndex >= 0 && comboBoxNames [comboIndex].isNotEmpty())
  61537. y += labelHeight;
  61538. const int tbIndex = textBoxes.indexOf (c);
  61539. if (tbIndex >= 0 && textboxNames[tbIndex].isNotEmpty())
  61540. y += labelHeight;
  61541. if (customComps.contains (c))
  61542. {
  61543. if (c->getName().isNotEmpty())
  61544. y += labelHeight;
  61545. c->setTopLeftPosition (proportionOfWidth (0.1f), y);
  61546. h = c->getHeight();
  61547. }
  61548. else if (textBlocks.contains (c))
  61549. {
  61550. c->setTopLeftPosition ((getWidth() - c->getWidth()) / 2, y);
  61551. h = c->getHeight();
  61552. }
  61553. else
  61554. {
  61555. c->setBounds (proportionOfWidth (0.1f), y, proportionOfWidth (0.8f), h);
  61556. }
  61557. y += h + 10;
  61558. }
  61559. setWantsKeyboardFocus (getNumChildComponents() == 0);
  61560. }
  61561. bool AlertWindow::containsAnyExtraComponents() const
  61562. {
  61563. return textBoxes.size()
  61564. + comboBoxes.size()
  61565. + progressBars.size()
  61566. + customComps.size() > 0;
  61567. }
  61568. void AlertWindow::mouseDown (const MouseEvent&)
  61569. {
  61570. dragger.startDraggingComponent (this, &constrainer);
  61571. }
  61572. void AlertWindow::mouseDrag (const MouseEvent& e)
  61573. {
  61574. dragger.dragComponent (this, e);
  61575. }
  61576. bool AlertWindow::keyPressed (const KeyPress& key)
  61577. {
  61578. for (int i = buttons.size(); --i >= 0;)
  61579. {
  61580. TextButton* const b = (TextButton*) buttons[i];
  61581. if (b->isRegisteredForShortcut (key))
  61582. {
  61583. b->triggerClick();
  61584. return true;
  61585. }
  61586. }
  61587. if (key.isKeyCode (KeyPress::escapeKey) && buttons.size() == 0)
  61588. {
  61589. exitModalState (0);
  61590. return true;
  61591. }
  61592. else if (key.isKeyCode (KeyPress::returnKey) && buttons.size() == 1)
  61593. {
  61594. ((TextButton*) buttons.getFirst())->triggerClick();
  61595. return true;
  61596. }
  61597. return false;
  61598. }
  61599. void AlertWindow::lookAndFeelChanged()
  61600. {
  61601. const int newFlags = getLookAndFeel().getAlertBoxWindowFlags();
  61602. setUsingNativeTitleBar ((newFlags & ComponentPeer::windowHasTitleBar) != 0);
  61603. setDropShadowEnabled (isOpaque() && (newFlags & ComponentPeer::windowHasDropShadow) != 0);
  61604. }
  61605. int AlertWindow::getDesktopWindowStyleFlags() const
  61606. {
  61607. return getLookAndFeel().getAlertBoxWindowFlags();
  61608. }
  61609. struct AlertWindowInfo
  61610. {
  61611. String title, message, button1, button2, button3;
  61612. AlertWindow::AlertIconType iconType;
  61613. int numButtons;
  61614. Component::SafePointer<Component> associatedComponent;
  61615. int run() const
  61616. {
  61617. return (int) (pointer_sized_int)
  61618. MessageManager::getInstance()->callFunctionOnMessageThread (showCallback, (void*) this);
  61619. }
  61620. private:
  61621. int show() const
  61622. {
  61623. LookAndFeel& lf = associatedComponent != 0 ? associatedComponent->getLookAndFeel()
  61624. : LookAndFeel::getDefaultLookAndFeel();
  61625. ScopedPointer <Component> alertBox (lf.createAlertWindow (title, message, button1, button2, button3,
  61626. iconType, numButtons, associatedComponent));
  61627. jassert (alertBox != 0); // you have to return one of these!
  61628. return alertBox->runModalLoop();
  61629. }
  61630. static void* showCallback (void* userData)
  61631. {
  61632. return (void*) (pointer_sized_int) ((const AlertWindowInfo*) userData)->show();
  61633. }
  61634. };
  61635. void AlertWindow::showMessageBox (AlertIconType iconType,
  61636. const String& title,
  61637. const String& message,
  61638. const String& buttonText,
  61639. Component* associatedComponent)
  61640. {
  61641. AlertWindowInfo info;
  61642. info.title = title;
  61643. info.message = message;
  61644. info.button1 = buttonText.isEmpty() ? TRANS("ok") : buttonText;
  61645. info.iconType = iconType;
  61646. info.numButtons = 1;
  61647. info.associatedComponent = associatedComponent;
  61648. info.run();
  61649. }
  61650. bool AlertWindow::showOkCancelBox (AlertIconType iconType,
  61651. const String& title,
  61652. const String& message,
  61653. const String& button1Text,
  61654. const String& button2Text,
  61655. Component* associatedComponent)
  61656. {
  61657. AlertWindowInfo info;
  61658. info.title = title;
  61659. info.message = message;
  61660. info.button1 = button1Text.isEmpty() ? TRANS("ok") : button1Text;
  61661. info.button2 = button2Text.isEmpty() ? TRANS("cancel") : button2Text;
  61662. info.iconType = iconType;
  61663. info.numButtons = 2;
  61664. info.associatedComponent = associatedComponent;
  61665. return info.run() != 0;
  61666. }
  61667. int AlertWindow::showYesNoCancelBox (AlertIconType iconType,
  61668. const String& title,
  61669. const String& message,
  61670. const String& button1Text,
  61671. const String& button2Text,
  61672. const String& button3Text,
  61673. Component* associatedComponent)
  61674. {
  61675. AlertWindowInfo info;
  61676. info.title = title;
  61677. info.message = message;
  61678. info.button1 = button1Text.isEmpty() ? TRANS("yes") : button1Text;
  61679. info.button2 = button2Text.isEmpty() ? TRANS("no") : button2Text;
  61680. info.button3 = button3Text.isEmpty() ? TRANS("cancel") : button3Text;
  61681. info.iconType = iconType;
  61682. info.numButtons = 3;
  61683. info.associatedComponent = associatedComponent;
  61684. return info.run();
  61685. }
  61686. END_JUCE_NAMESPACE
  61687. /*** End of inlined file: juce_AlertWindow.cpp ***/
  61688. /*** Start of inlined file: juce_CallOutBox.cpp ***/
  61689. BEGIN_JUCE_NAMESPACE
  61690. CallOutBox::CallOutBox (Component& contentComponent,
  61691. Component& componentToPointTo,
  61692. Component* const parentComponent)
  61693. : borderSpace (20), arrowSize (16.0f), content (contentComponent)
  61694. {
  61695. addAndMakeVisible (&content);
  61696. if (parentComponent != 0)
  61697. {
  61698. updatePosition (parentComponent->getLocalBounds(),
  61699. componentToPointTo.getLocalBounds()
  61700. + componentToPointTo.relativePositionToOtherComponent (parentComponent, Point<int>()));
  61701. parentComponent->addAndMakeVisible (this);
  61702. }
  61703. else
  61704. {
  61705. updatePosition (componentToPointTo.getScreenBounds(),
  61706. componentToPointTo.getParentMonitorArea());
  61707. addToDesktop (ComponentPeer::windowIsTemporary);
  61708. }
  61709. }
  61710. CallOutBox::~CallOutBox()
  61711. {
  61712. }
  61713. void CallOutBox::setArrowSize (const float newSize)
  61714. {
  61715. arrowSize = newSize;
  61716. borderSpace = jmax (20, (int) arrowSize);
  61717. refreshPath();
  61718. }
  61719. void CallOutBox::paint (Graphics& g)
  61720. {
  61721. if (background.isNull())
  61722. {
  61723. background = Image (Image::ARGB, getWidth(), getHeight(), true);
  61724. Graphics g (background);
  61725. getLookAndFeel().drawCallOutBoxBackground (*this, g, outline);
  61726. }
  61727. g.setColour (Colours::black);
  61728. g.drawImageAt (background, 0, 0);
  61729. }
  61730. void CallOutBox::resized()
  61731. {
  61732. content.setTopLeftPosition (borderSpace, borderSpace);
  61733. refreshPath();
  61734. }
  61735. void CallOutBox::moved()
  61736. {
  61737. refreshPath();
  61738. }
  61739. void CallOutBox::childBoundsChanged (Component*)
  61740. {
  61741. updatePosition (targetArea, availableArea);
  61742. }
  61743. bool CallOutBox::hitTest (int x, int y)
  61744. {
  61745. return outline.contains ((float) x, (float) y);
  61746. }
  61747. enum { callOutBoxDismissCommandId = 0x4f83a04b };
  61748. void CallOutBox::inputAttemptWhenModal()
  61749. {
  61750. const Point<int> mousePos (getMouseXYRelative() + getBounds().getPosition());
  61751. if (targetArea.contains (mousePos))
  61752. {
  61753. // if you click on the area that originally popped-up the callout, you expect it
  61754. // to get rid of the box, but deleting the box here allows the click to pass through and
  61755. // probably re-trigger it, so we need to dismiss the box asynchronously to consume the click..
  61756. postCommandMessage (callOutBoxDismissCommandId);
  61757. }
  61758. else
  61759. {
  61760. exitModalState (0);
  61761. setVisible (false);
  61762. }
  61763. }
  61764. void CallOutBox::handleCommandMessage (int commandId)
  61765. {
  61766. Component::handleCommandMessage (commandId);
  61767. if (commandId == callOutBoxDismissCommandId)
  61768. {
  61769. exitModalState (0);
  61770. setVisible (false);
  61771. }
  61772. }
  61773. bool CallOutBox::keyPressed (const KeyPress& key)
  61774. {
  61775. if (key.isKeyCode (KeyPress::escapeKey))
  61776. {
  61777. inputAttemptWhenModal();
  61778. return true;
  61779. }
  61780. return false;
  61781. }
  61782. void CallOutBox::updatePosition (const Rectangle<int>& newAreaToPointTo, const Rectangle<int>& newAreaToFitIn)
  61783. {
  61784. targetArea = newAreaToPointTo;
  61785. availableArea = newAreaToFitIn;
  61786. Rectangle<int> bounds (0, 0,
  61787. content.getWidth() + borderSpace * 2,
  61788. content.getHeight() + borderSpace * 2);
  61789. const int hw = bounds.getWidth() / 2;
  61790. const int hh = bounds.getHeight() / 2;
  61791. const float hwReduced = (float) (hw - borderSpace * 3);
  61792. const float hhReduced = (float) (hh - borderSpace * 3);
  61793. const float arrowIndent = borderSpace - arrowSize;
  61794. Point<float> targets[4] = { Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getBottom()),
  61795. Point<float> ((float) targetArea.getRight(), (float) targetArea.getCentreY()),
  61796. Point<float> ((float) targetArea.getX(), (float) targetArea.getCentreY()),
  61797. Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getY()) };
  61798. Line<float> lines[4] = { Line<float> (targets[0].translated (-hwReduced, hh - arrowIndent), targets[0].translated (hwReduced, hh - arrowIndent)),
  61799. Line<float> (targets[1].translated (hw - arrowIndent, -hhReduced), targets[1].translated (hw - arrowIndent, hhReduced)),
  61800. Line<float> (targets[2].translated (-(hw - arrowIndent), -hhReduced), targets[2].translated (-(hw - arrowIndent), hhReduced)),
  61801. Line<float> (targets[3].translated (-hwReduced, -(hh - arrowIndent)), targets[3].translated (hwReduced, -(hh - arrowIndent))) };
  61802. const Rectangle<float> centrePointArea (newAreaToFitIn.reduced (hw, hh).toFloat());
  61803. float nearest = 1.0e9f;
  61804. for (int i = 0; i < 4; ++i)
  61805. {
  61806. Line<float> constrainedLine (centrePointArea.getConstrainedPoint (lines[i].getStart()),
  61807. centrePointArea.getConstrainedPoint (lines[i].getEnd()));
  61808. const Point<float> centre (constrainedLine.findNearestPointTo (centrePointArea.getCentre()));
  61809. float distanceFromCentre = centre.getDistanceFrom (centrePointArea.getCentre());
  61810. if (! (centrePointArea.contains (lines[i].getStart()) || centrePointArea.contains (lines[i].getEnd())))
  61811. distanceFromCentre *= 2.0f;
  61812. if (distanceFromCentre < nearest)
  61813. {
  61814. nearest = distanceFromCentre;
  61815. targetPoint = targets[i];
  61816. bounds.setPosition ((int) (centre.getX() - hw),
  61817. (int) (centre.getY() - hh));
  61818. }
  61819. }
  61820. setBounds (bounds);
  61821. }
  61822. void CallOutBox::refreshPath()
  61823. {
  61824. repaint();
  61825. background = Image();
  61826. outline.clear();
  61827. const float gap = 4.5f;
  61828. const float cornerSize = 9.0f;
  61829. const float cornerSize2 = 2.0f * cornerSize;
  61830. const float arrowBaseWidth = arrowSize * 0.7f;
  61831. const float left = content.getX() - gap, top = content.getY() - gap, right = content.getRight() + gap, bottom = content.getBottom() + gap;
  61832. const float targetX = targetPoint.getX() - getX(), targetY = targetPoint.getY() - getY();
  61833. outline.startNewSubPath (left + cornerSize, top);
  61834. if (targetY <= top)
  61835. {
  61836. outline.lineTo (targetX - arrowBaseWidth, top);
  61837. outline.lineTo (targetX, targetY);
  61838. outline.lineTo (targetX + arrowBaseWidth, top);
  61839. }
  61840. outline.lineTo (right - cornerSize, top);
  61841. outline.addArc (right - cornerSize2, top, cornerSize2, cornerSize2, 0, float_Pi * 0.5f);
  61842. if (targetX >= right)
  61843. {
  61844. outline.lineTo (right, targetY - arrowBaseWidth);
  61845. outline.lineTo (targetX, targetY);
  61846. outline.lineTo (right, targetY + arrowBaseWidth);
  61847. }
  61848. outline.lineTo (right, bottom - cornerSize);
  61849. outline.addArc (right - cornerSize2, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi * 0.5f, float_Pi);
  61850. if (targetY >= bottom)
  61851. {
  61852. outline.lineTo (targetX + arrowBaseWidth, bottom);
  61853. outline.lineTo (targetX, targetY);
  61854. outline.lineTo (targetX - arrowBaseWidth, bottom);
  61855. }
  61856. outline.lineTo (left + cornerSize, bottom);
  61857. outline.addArc (left, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi, float_Pi * 1.5f);
  61858. if (targetX <= left)
  61859. {
  61860. outline.lineTo (left, targetY + arrowBaseWidth);
  61861. outline.lineTo (targetX, targetY);
  61862. outline.lineTo (left, targetY - arrowBaseWidth);
  61863. }
  61864. outline.lineTo (left, top + cornerSize);
  61865. outline.addArc (left, top, cornerSize2, cornerSize2, float_Pi * 1.5f, float_Pi * 2.0f - 0.05f);
  61866. outline.closeSubPath();
  61867. }
  61868. END_JUCE_NAMESPACE
  61869. /*** End of inlined file: juce_CallOutBox.cpp ***/
  61870. /*** Start of inlined file: juce_ComponentPeer.cpp ***/
  61871. BEGIN_JUCE_NAMESPACE
  61872. //#define JUCE_ENABLE_REPAINT_DEBUGGING 1
  61873. static Array <ComponentPeer*> heavyweightPeers;
  61874. ComponentPeer::ComponentPeer (Component* const component_, const int styleFlags_)
  61875. : component (component_),
  61876. styleFlags (styleFlags_),
  61877. lastPaintTime (0),
  61878. constrainer (0),
  61879. lastDragAndDropCompUnderMouse (0),
  61880. fakeMouseMessageSent (false),
  61881. isWindowMinimised (false)
  61882. {
  61883. heavyweightPeers.add (this);
  61884. }
  61885. ComponentPeer::~ComponentPeer()
  61886. {
  61887. heavyweightPeers.removeValue (this);
  61888. Desktop::getInstance().triggerFocusCallback();
  61889. }
  61890. int ComponentPeer::getNumPeers() throw()
  61891. {
  61892. return heavyweightPeers.size();
  61893. }
  61894. ComponentPeer* ComponentPeer::getPeer (const int index) throw()
  61895. {
  61896. return heavyweightPeers [index];
  61897. }
  61898. ComponentPeer* ComponentPeer::getPeerFor (const Component* const component) throw()
  61899. {
  61900. for (int i = heavyweightPeers.size(); --i >= 0;)
  61901. {
  61902. ComponentPeer* const peer = heavyweightPeers.getUnchecked(i);
  61903. if (peer->getComponent() == component)
  61904. return peer;
  61905. }
  61906. return 0;
  61907. }
  61908. bool ComponentPeer::isValidPeer (const ComponentPeer* const peer) throw()
  61909. {
  61910. return heavyweightPeers.contains (const_cast <ComponentPeer*> (peer));
  61911. }
  61912. void ComponentPeer::updateCurrentModifiers() throw()
  61913. {
  61914. ModifierKeys::updateCurrentModifiers();
  61915. }
  61916. void ComponentPeer::handleMouseEvent (const int touchIndex, const Point<int>& positionWithinPeer, const ModifierKeys& newMods, const int64 time)
  61917. {
  61918. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  61919. jassert (mouse != 0); // not enough sources!
  61920. mouse->handleEvent (this, positionWithinPeer, time, newMods);
  61921. }
  61922. void ComponentPeer::handleMouseWheel (const int touchIndex, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  61923. {
  61924. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  61925. jassert (mouse != 0); // not enough sources!
  61926. mouse->handleWheel (this, positionWithinPeer, time, x, y);
  61927. }
  61928. void ComponentPeer::handlePaint (LowLevelGraphicsContext& contextToPaintTo)
  61929. {
  61930. Graphics g (&contextToPaintTo);
  61931. #if JUCE_ENABLE_REPAINT_DEBUGGING
  61932. g.saveState();
  61933. #endif
  61934. JUCE_TRY
  61935. {
  61936. component->paintEntireComponent (g);
  61937. }
  61938. JUCE_CATCH_EXCEPTION
  61939. #if JUCE_ENABLE_REPAINT_DEBUGGING
  61940. // enabling this code will fill all areas that get repainted with a colour overlay, to show
  61941. // clearly when things are being repainted.
  61942. {
  61943. g.restoreState();
  61944. g.fillAll (Colour ((uint8) Random::getSystemRandom().nextInt (255),
  61945. (uint8) Random::getSystemRandom().nextInt (255),
  61946. (uint8) Random::getSystemRandom().nextInt (255),
  61947. (uint8) 0x50));
  61948. }
  61949. #endif
  61950. }
  61951. bool ComponentPeer::handleKeyPress (const int keyCode,
  61952. const juce_wchar textCharacter)
  61953. {
  61954. updateCurrentModifiers();
  61955. Component* target = Component::getCurrentlyFocusedComponent() != 0
  61956. ? Component::getCurrentlyFocusedComponent()
  61957. : component;
  61958. if (target->isCurrentlyBlockedByAnotherModalComponent())
  61959. {
  61960. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  61961. if (currentModalComp != 0)
  61962. target = currentModalComp;
  61963. }
  61964. const KeyPress keyInfo (keyCode,
  61965. ModifierKeys::getCurrentModifiers().getRawFlags()
  61966. & ModifierKeys::allKeyboardModifiers,
  61967. textCharacter);
  61968. bool keyWasUsed = false;
  61969. while (target != 0)
  61970. {
  61971. const Component::SafePointer<Component> deletionChecker (target);
  61972. if (target->keyListeners_ != 0)
  61973. {
  61974. for (int i = target->keyListeners_->size(); --i >= 0;)
  61975. {
  61976. keyWasUsed = target->keyListeners_->getUnchecked(i)->keyPressed (keyInfo, target);
  61977. if (keyWasUsed || deletionChecker == 0)
  61978. return keyWasUsed;
  61979. i = jmin (i, target->keyListeners_->size());
  61980. }
  61981. }
  61982. keyWasUsed = target->keyPressed (keyInfo);
  61983. if (keyWasUsed || deletionChecker == 0)
  61984. break;
  61985. if (keyInfo.isKeyCode (KeyPress::tabKey) && Component::getCurrentlyFocusedComponent() != 0)
  61986. {
  61987. Component* const currentlyFocused = Component::getCurrentlyFocusedComponent();
  61988. currentlyFocused->moveKeyboardFocusToSibling (! keyInfo.getModifiers().isShiftDown());
  61989. keyWasUsed = (currentlyFocused != Component::getCurrentlyFocusedComponent());
  61990. break;
  61991. }
  61992. target = target->parentComponent_;
  61993. }
  61994. return keyWasUsed;
  61995. }
  61996. bool ComponentPeer::handleKeyUpOrDown (const bool isKeyDown)
  61997. {
  61998. updateCurrentModifiers();
  61999. Component* target = Component::getCurrentlyFocusedComponent() != 0
  62000. ? Component::getCurrentlyFocusedComponent()
  62001. : component;
  62002. if (target->isCurrentlyBlockedByAnotherModalComponent())
  62003. {
  62004. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  62005. if (currentModalComp != 0)
  62006. target = currentModalComp;
  62007. }
  62008. bool keyWasUsed = false;
  62009. while (target != 0)
  62010. {
  62011. const Component::SafePointer<Component> deletionChecker (target);
  62012. keyWasUsed = target->keyStateChanged (isKeyDown);
  62013. if (keyWasUsed || deletionChecker == 0)
  62014. break;
  62015. if (target->keyListeners_ != 0)
  62016. {
  62017. for (int i = target->keyListeners_->size(); --i >= 0;)
  62018. {
  62019. keyWasUsed = target->keyListeners_->getUnchecked(i)->keyStateChanged (isKeyDown, target);
  62020. if (keyWasUsed || deletionChecker == 0)
  62021. return keyWasUsed;
  62022. i = jmin (i, target->keyListeners_->size());
  62023. }
  62024. }
  62025. target = target->parentComponent_;
  62026. }
  62027. return keyWasUsed;
  62028. }
  62029. void ComponentPeer::handleModifierKeysChange()
  62030. {
  62031. updateCurrentModifiers();
  62032. Component* target = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  62033. if (target == 0)
  62034. target = Component::getCurrentlyFocusedComponent();
  62035. if (target == 0)
  62036. target = component;
  62037. if (target != 0)
  62038. target->internalModifierKeysChanged();
  62039. }
  62040. TextInputTarget* ComponentPeer::findCurrentTextInputTarget()
  62041. {
  62042. Component* const c = Component::getCurrentlyFocusedComponent();
  62043. if (component->isParentOf (c))
  62044. {
  62045. TextInputTarget* const ti = dynamic_cast <TextInputTarget*> (c);
  62046. if (ti != 0 && ti->isTextInputActive())
  62047. return ti;
  62048. }
  62049. return 0;
  62050. }
  62051. void ComponentPeer::handleBroughtToFront()
  62052. {
  62053. updateCurrentModifiers();
  62054. if (component != 0)
  62055. component->internalBroughtToFront();
  62056. }
  62057. void ComponentPeer::setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw()
  62058. {
  62059. constrainer = newConstrainer;
  62060. }
  62061. void ComponentPeer::handleMovedOrResized()
  62062. {
  62063. jassert (component->isValidComponent());
  62064. updateCurrentModifiers();
  62065. const bool nowMinimised = isMinimised();
  62066. if (component->flags.hasHeavyweightPeerFlag && ! nowMinimised)
  62067. {
  62068. const Component::SafePointer<Component> deletionChecker (component);
  62069. const Rectangle<int> newBounds (getBounds());
  62070. const bool wasMoved = (component->getPosition() != newBounds.getPosition());
  62071. const bool wasResized = (component->getWidth() != newBounds.getWidth() || component->getHeight() != newBounds.getHeight());
  62072. if (wasMoved || wasResized)
  62073. {
  62074. component->bounds_ = newBounds;
  62075. if (wasResized)
  62076. component->repaint();
  62077. component->sendMovedResizedMessages (wasMoved, wasResized);
  62078. if (deletionChecker == 0)
  62079. return;
  62080. }
  62081. }
  62082. if (isWindowMinimised != nowMinimised)
  62083. {
  62084. isWindowMinimised = nowMinimised;
  62085. component->minimisationStateChanged (nowMinimised);
  62086. component->sendVisibilityChangeMessage();
  62087. }
  62088. if (! isFullScreen())
  62089. lastNonFullscreenBounds = component->getBounds();
  62090. }
  62091. void ComponentPeer::handleFocusGain()
  62092. {
  62093. updateCurrentModifiers();
  62094. if (component->isParentOf (lastFocusedComponent))
  62095. {
  62096. Component::currentlyFocusedComponent = lastFocusedComponent;
  62097. Desktop::getInstance().triggerFocusCallback();
  62098. lastFocusedComponent->internalFocusGain (Component::focusChangedDirectly);
  62099. }
  62100. else
  62101. {
  62102. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  62103. component->grabKeyboardFocus();
  62104. else
  62105. Component::bringModalComponentToFront();
  62106. }
  62107. }
  62108. void ComponentPeer::handleFocusLoss()
  62109. {
  62110. updateCurrentModifiers();
  62111. if (component->hasKeyboardFocus (true))
  62112. {
  62113. lastFocusedComponent = Component::currentlyFocusedComponent;
  62114. if (lastFocusedComponent != 0)
  62115. {
  62116. Component::currentlyFocusedComponent = 0;
  62117. Desktop::getInstance().triggerFocusCallback();
  62118. lastFocusedComponent->internalFocusLoss (Component::focusChangedByMouseClick);
  62119. }
  62120. }
  62121. }
  62122. Component* ComponentPeer::getLastFocusedSubcomponent() const throw()
  62123. {
  62124. return (component->isParentOf (lastFocusedComponent) && lastFocusedComponent->isShowing())
  62125. ? static_cast <Component*> (lastFocusedComponent)
  62126. : component;
  62127. }
  62128. void ComponentPeer::handleScreenSizeChange()
  62129. {
  62130. updateCurrentModifiers();
  62131. component->parentSizeChanged();
  62132. handleMovedOrResized();
  62133. }
  62134. void ComponentPeer::setNonFullScreenBounds (const Rectangle<int>& newBounds) throw()
  62135. {
  62136. lastNonFullscreenBounds = newBounds;
  62137. }
  62138. const Rectangle<int>& ComponentPeer::getNonFullScreenBounds() const throw()
  62139. {
  62140. return lastNonFullscreenBounds;
  62141. }
  62142. static FileDragAndDropTarget* findDragAndDropTarget (Component* c,
  62143. const StringArray& files,
  62144. FileDragAndDropTarget* const lastOne)
  62145. {
  62146. while (c != 0)
  62147. {
  62148. FileDragAndDropTarget* const t = dynamic_cast <FileDragAndDropTarget*> (c);
  62149. if (t != 0 && (t == lastOne || t->isInterestedInFileDrag (files)))
  62150. return t;
  62151. c = c->getParentComponent();
  62152. }
  62153. return 0;
  62154. }
  62155. void ComponentPeer::handleFileDragMove (const StringArray& files, const Point<int>& position)
  62156. {
  62157. updateCurrentModifiers();
  62158. FileDragAndDropTarget* lastTarget
  62159. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  62160. FileDragAndDropTarget* newTarget = 0;
  62161. Component* const compUnderMouse = component->getComponentAt (position);
  62162. if (compUnderMouse != lastDragAndDropCompUnderMouse)
  62163. {
  62164. lastDragAndDropCompUnderMouse = compUnderMouse;
  62165. newTarget = findDragAndDropTarget (compUnderMouse, files, lastTarget);
  62166. if (newTarget != lastTarget)
  62167. {
  62168. if (lastTarget != 0)
  62169. lastTarget->fileDragExit (files);
  62170. dragAndDropTargetComponent = 0;
  62171. if (newTarget != 0)
  62172. {
  62173. dragAndDropTargetComponent = dynamic_cast <Component*> (newTarget);
  62174. const Point<int> pos (component->relativePositionToOtherComponent (dragAndDropTargetComponent, position));
  62175. newTarget->fileDragEnter (files, pos.getX(), pos.getY());
  62176. }
  62177. }
  62178. }
  62179. else
  62180. {
  62181. newTarget = lastTarget;
  62182. }
  62183. if (newTarget != 0)
  62184. {
  62185. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  62186. const Point<int> pos (component->relativePositionToOtherComponent (targetComp, position));
  62187. newTarget->fileDragMove (files, pos.getX(), pos.getY());
  62188. }
  62189. }
  62190. void ComponentPeer::handleFileDragExit (const StringArray& files)
  62191. {
  62192. handleFileDragMove (files, Point<int> (-1, -1));
  62193. jassert (dragAndDropTargetComponent == 0);
  62194. lastDragAndDropCompUnderMouse = 0;
  62195. }
  62196. void ComponentPeer::handleFileDragDrop (const StringArray& files, const Point<int>& position)
  62197. {
  62198. handleFileDragMove (files, position);
  62199. if (dragAndDropTargetComponent != 0)
  62200. {
  62201. FileDragAndDropTarget* const target
  62202. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  62203. dragAndDropTargetComponent = 0;
  62204. lastDragAndDropCompUnderMouse = 0;
  62205. if (target != 0)
  62206. {
  62207. Component* const targetComp = dynamic_cast <Component*> (target);
  62208. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  62209. {
  62210. targetComp->internalModalInputAttempt();
  62211. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  62212. return;
  62213. }
  62214. const Point<int> pos (component->relativePositionToOtherComponent (targetComp, position));
  62215. target->filesDropped (files, pos.getX(), pos.getY());
  62216. }
  62217. }
  62218. }
  62219. void ComponentPeer::handleUserClosingWindow()
  62220. {
  62221. updateCurrentModifiers();
  62222. component->userTriedToCloseWindow();
  62223. }
  62224. void ComponentPeer::bringModalComponentToFront()
  62225. {
  62226. Component::bringModalComponentToFront();
  62227. }
  62228. void ComponentPeer::clearMaskedRegion()
  62229. {
  62230. maskedRegion.clear();
  62231. }
  62232. void ComponentPeer::addMaskedRegion (int x, int y, int w, int h)
  62233. {
  62234. maskedRegion.add (x, y, w, h);
  62235. }
  62236. const StringArray ComponentPeer::getAvailableRenderingEngines() throw()
  62237. {
  62238. StringArray s;
  62239. s.add ("Software Renderer");
  62240. return s;
  62241. }
  62242. int ComponentPeer::getCurrentRenderingEngine() throw()
  62243. {
  62244. return 0;
  62245. }
  62246. void ComponentPeer::setCurrentRenderingEngine (int /*index*/) throw()
  62247. {
  62248. }
  62249. END_JUCE_NAMESPACE
  62250. /*** End of inlined file: juce_ComponentPeer.cpp ***/
  62251. /*** Start of inlined file: juce_DialogWindow.cpp ***/
  62252. BEGIN_JUCE_NAMESPACE
  62253. DialogWindow::DialogWindow (const String& name,
  62254. const Colour& backgroundColour_,
  62255. const bool escapeKeyTriggersCloseButton_,
  62256. const bool addToDesktop_)
  62257. : DocumentWindow (name, backgroundColour_, DocumentWindow::closeButton, addToDesktop_),
  62258. escapeKeyTriggersCloseButton (escapeKeyTriggersCloseButton_)
  62259. {
  62260. }
  62261. DialogWindow::~DialogWindow()
  62262. {
  62263. }
  62264. void DialogWindow::resized()
  62265. {
  62266. DocumentWindow::resized();
  62267. const KeyPress esc (KeyPress::escapeKey, 0, 0);
  62268. if (escapeKeyTriggersCloseButton
  62269. && getCloseButton() != 0
  62270. && ! getCloseButton()->isRegisteredForShortcut (esc))
  62271. {
  62272. getCloseButton()->addShortcut (esc);
  62273. }
  62274. }
  62275. class TempDialogWindow : public DialogWindow
  62276. {
  62277. public:
  62278. TempDialogWindow (const String& title, const Colour& colour, const bool escapeCloses)
  62279. : DialogWindow (title, colour, escapeCloses, true)
  62280. {
  62281. if (JUCEApplication::getInstance() == 0)
  62282. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  62283. }
  62284. ~TempDialogWindow()
  62285. {
  62286. }
  62287. void closeButtonPressed()
  62288. {
  62289. setVisible (false);
  62290. }
  62291. private:
  62292. TempDialogWindow (const TempDialogWindow&);
  62293. TempDialogWindow& operator= (const TempDialogWindow&);
  62294. };
  62295. int DialogWindow::showModalDialog (const String& dialogTitle,
  62296. Component* contentComponent,
  62297. Component* componentToCentreAround,
  62298. const Colour& colour,
  62299. const bool escapeKeyTriggersCloseButton,
  62300. const bool shouldBeResizable,
  62301. const bool useBottomRightCornerResizer)
  62302. {
  62303. TempDialogWindow dw (dialogTitle, colour, escapeKeyTriggersCloseButton);
  62304. dw.setContentComponent (contentComponent, true, true);
  62305. dw.centreAroundComponent (componentToCentreAround, dw.getWidth(), dw.getHeight());
  62306. dw.setResizable (shouldBeResizable, useBottomRightCornerResizer);
  62307. const int result = dw.runModalLoop();
  62308. dw.setContentComponent (0, false);
  62309. return result;
  62310. }
  62311. END_JUCE_NAMESPACE
  62312. /*** End of inlined file: juce_DialogWindow.cpp ***/
  62313. /*** Start of inlined file: juce_DocumentWindow.cpp ***/
  62314. BEGIN_JUCE_NAMESPACE
  62315. class DocumentWindow::ButtonListenerProxy : public ButtonListener
  62316. {
  62317. public:
  62318. ButtonListenerProxy (DocumentWindow& owner_)
  62319. : owner (owner_)
  62320. {
  62321. }
  62322. void buttonClicked (Button* button)
  62323. {
  62324. if (button == owner.getMinimiseButton())
  62325. owner.minimiseButtonPressed();
  62326. else if (button == owner.getMaximiseButton())
  62327. owner.maximiseButtonPressed();
  62328. else if (button == owner.getCloseButton())
  62329. owner.closeButtonPressed();
  62330. }
  62331. juce_UseDebuggingNewOperator
  62332. private:
  62333. DocumentWindow& owner;
  62334. ButtonListenerProxy (const ButtonListenerProxy&);
  62335. ButtonListenerProxy& operator= (const ButtonListenerProxy&);
  62336. };
  62337. DocumentWindow::DocumentWindow (const String& title,
  62338. const Colour& backgroundColour,
  62339. const int requiredButtons_,
  62340. const bool addToDesktop_)
  62341. : ResizableWindow (title, backgroundColour, addToDesktop_),
  62342. titleBarHeight (26),
  62343. menuBarHeight (24),
  62344. requiredButtons (requiredButtons_),
  62345. #if JUCE_MAC
  62346. positionTitleBarButtonsOnLeft (true),
  62347. #else
  62348. positionTitleBarButtonsOnLeft (false),
  62349. #endif
  62350. drawTitleTextCentred (true),
  62351. menuBarModel (0)
  62352. {
  62353. setResizeLimits (128, 128, 32768, 32768);
  62354. lookAndFeelChanged();
  62355. }
  62356. DocumentWindow::~DocumentWindow()
  62357. {
  62358. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  62359. titleBarButtons[i] = 0;
  62360. menuBar = 0;
  62361. }
  62362. void DocumentWindow::repaintTitleBar()
  62363. {
  62364. repaint (getTitleBarArea());
  62365. }
  62366. void DocumentWindow::setName (const String& newName)
  62367. {
  62368. if (newName != getName())
  62369. {
  62370. Component::setName (newName);
  62371. repaintTitleBar();
  62372. }
  62373. }
  62374. void DocumentWindow::setIcon (const Image& imageToUse)
  62375. {
  62376. titleBarIcon = imageToUse;
  62377. repaintTitleBar();
  62378. }
  62379. void DocumentWindow::setTitleBarHeight (const int newHeight)
  62380. {
  62381. titleBarHeight = newHeight;
  62382. resized();
  62383. repaintTitleBar();
  62384. }
  62385. void DocumentWindow::setTitleBarButtonsRequired (const int requiredButtons_,
  62386. const bool positionTitleBarButtonsOnLeft_)
  62387. {
  62388. requiredButtons = requiredButtons_;
  62389. positionTitleBarButtonsOnLeft = positionTitleBarButtonsOnLeft_;
  62390. lookAndFeelChanged();
  62391. }
  62392. void DocumentWindow::setTitleBarTextCentred (const bool textShouldBeCentred)
  62393. {
  62394. drawTitleTextCentred = textShouldBeCentred;
  62395. repaintTitleBar();
  62396. }
  62397. void DocumentWindow::setMenuBar (MenuBarModel* menuBarModel_,
  62398. const int menuBarHeight_)
  62399. {
  62400. if (menuBarModel != menuBarModel_)
  62401. {
  62402. menuBar = 0;
  62403. menuBarModel = menuBarModel_;
  62404. menuBarHeight = (menuBarHeight_ > 0) ? menuBarHeight_
  62405. : getLookAndFeel().getDefaultMenuBarHeight();
  62406. if (menuBarModel != 0)
  62407. {
  62408. // (call the Component method directly to avoid the assertion in ResizableWindow)
  62409. Component::addAndMakeVisible (menuBar = new MenuBarComponent (menuBarModel));
  62410. menuBar->setEnabled (isActiveWindow());
  62411. }
  62412. resized();
  62413. }
  62414. }
  62415. void DocumentWindow::closeButtonPressed()
  62416. {
  62417. /* If you've got a close button, you have to override this method to get
  62418. rid of your window!
  62419. If the window is just a pop-up, you should override this method and make
  62420. it delete the window in whatever way is appropriate for your app. E.g. you
  62421. might just want to call "delete this".
  62422. If your app is centred around this window such that the whole app should quit when
  62423. the window is closed, then you will probably want to use this method as an opportunity
  62424. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  62425. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  62426. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  62427. or closing it via the taskbar icon on Windows).
  62428. */
  62429. jassertfalse;
  62430. }
  62431. void DocumentWindow::minimiseButtonPressed()
  62432. {
  62433. setMinimised (true);
  62434. }
  62435. void DocumentWindow::maximiseButtonPressed()
  62436. {
  62437. setFullScreen (! isFullScreen());
  62438. }
  62439. void DocumentWindow::paint (Graphics& g)
  62440. {
  62441. ResizableWindow::paint (g);
  62442. if (resizableBorder == 0)
  62443. {
  62444. g.setColour (getBackgroundColour().overlaidWith (Colour (0x80000000)));
  62445. const BorderSize border (getBorderThickness());
  62446. g.fillRect (0, 0, getWidth(), border.getTop());
  62447. g.fillRect (0, border.getTop(), border.getLeft(), getHeight() - border.getTopAndBottom());
  62448. g.fillRect (getWidth() - border.getRight(), border.getTop(), border.getRight(), getHeight() - border.getTopAndBottom());
  62449. g.fillRect (0, getHeight() - border.getBottom(), getWidth(), border.getBottom());
  62450. }
  62451. const Rectangle<int> titleBarArea (getTitleBarArea());
  62452. g.setOrigin (titleBarArea.getX(), titleBarArea.getY());
  62453. g.reduceClipRegion (0, 0, titleBarArea.getWidth(), titleBarArea.getHeight());
  62454. int titleSpaceX1 = 6;
  62455. int titleSpaceX2 = titleBarArea.getWidth() - 6;
  62456. for (int i = 0; i < 3; ++i)
  62457. {
  62458. if (titleBarButtons[i] != 0)
  62459. {
  62460. if (positionTitleBarButtonsOnLeft)
  62461. titleSpaceX1 = jmax (titleSpaceX1, titleBarButtons[i]->getRight() + (getWidth() - titleBarButtons[i]->getRight()) / 8);
  62462. else
  62463. titleSpaceX2 = jmin (titleSpaceX2, titleBarButtons[i]->getX() - (titleBarButtons[i]->getX() / 8));
  62464. }
  62465. }
  62466. getLookAndFeel().drawDocumentWindowTitleBar (*this, g,
  62467. titleBarArea.getWidth(),
  62468. titleBarArea.getHeight(),
  62469. titleSpaceX1,
  62470. jmax (1, titleSpaceX2 - titleSpaceX1),
  62471. titleBarIcon.isValid() ? &titleBarIcon : 0,
  62472. ! drawTitleTextCentred);
  62473. }
  62474. void DocumentWindow::resized()
  62475. {
  62476. ResizableWindow::resized();
  62477. if (titleBarButtons[1] != 0)
  62478. titleBarButtons[1]->setToggleState (isFullScreen(), false);
  62479. const Rectangle<int> titleBarArea (getTitleBarArea());
  62480. getLookAndFeel()
  62481. .positionDocumentWindowButtons (*this,
  62482. titleBarArea.getX(), titleBarArea.getY(),
  62483. titleBarArea.getWidth(), titleBarArea.getHeight(),
  62484. titleBarButtons[0],
  62485. titleBarButtons[1],
  62486. titleBarButtons[2],
  62487. positionTitleBarButtonsOnLeft);
  62488. if (menuBar != 0)
  62489. menuBar->setBounds (titleBarArea.getX(), titleBarArea.getBottom(),
  62490. titleBarArea.getWidth(), menuBarHeight);
  62491. }
  62492. const BorderSize DocumentWindow::getBorderThickness()
  62493. {
  62494. return BorderSize ((isFullScreen() || isUsingNativeTitleBar())
  62495. ? 0 : (resizableBorder != 0 ? 4 : 1));
  62496. }
  62497. const BorderSize DocumentWindow::getContentComponentBorder()
  62498. {
  62499. BorderSize border (getBorderThickness());
  62500. border.setTop (border.getTop()
  62501. + (isUsingNativeTitleBar() ? 0 : titleBarHeight)
  62502. + (menuBar != 0 ? menuBarHeight : 0));
  62503. return border;
  62504. }
  62505. int DocumentWindow::getTitleBarHeight() const
  62506. {
  62507. return isUsingNativeTitleBar() ? 0 : jmin (titleBarHeight, getHeight() - 4);
  62508. }
  62509. const Rectangle<int> DocumentWindow::getTitleBarArea()
  62510. {
  62511. const BorderSize border (getBorderThickness());
  62512. return Rectangle<int> (border.getLeft(), border.getTop(),
  62513. getWidth() - border.getLeftAndRight(),
  62514. getTitleBarHeight());
  62515. }
  62516. Button* DocumentWindow::getCloseButton() const throw()
  62517. {
  62518. return titleBarButtons[2];
  62519. }
  62520. Button* DocumentWindow::getMinimiseButton() const throw()
  62521. {
  62522. return titleBarButtons[0];
  62523. }
  62524. Button* DocumentWindow::getMaximiseButton() const throw()
  62525. {
  62526. return titleBarButtons[1];
  62527. }
  62528. int DocumentWindow::getDesktopWindowStyleFlags() const
  62529. {
  62530. int styleFlags = ResizableWindow::getDesktopWindowStyleFlags();
  62531. if ((requiredButtons & minimiseButton) != 0)
  62532. styleFlags |= ComponentPeer::windowHasMinimiseButton;
  62533. if ((requiredButtons & maximiseButton) != 0)
  62534. styleFlags |= ComponentPeer::windowHasMaximiseButton;
  62535. if ((requiredButtons & closeButton) != 0)
  62536. styleFlags |= ComponentPeer::windowHasCloseButton;
  62537. return styleFlags;
  62538. }
  62539. void DocumentWindow::lookAndFeelChanged()
  62540. {
  62541. int i;
  62542. for (i = numElementsInArray (titleBarButtons); --i >= 0;)
  62543. titleBarButtons[i] = 0;
  62544. if (! isUsingNativeTitleBar())
  62545. {
  62546. titleBarButtons[0] = ((requiredButtons & minimiseButton) != 0)
  62547. ? getLookAndFeel().createDocumentWindowButton (minimiseButton) : 0;
  62548. titleBarButtons[1] = ((requiredButtons & maximiseButton) != 0)
  62549. ? getLookAndFeel().createDocumentWindowButton (maximiseButton) : 0;
  62550. titleBarButtons[2] = ((requiredButtons & closeButton) != 0)
  62551. ? getLookAndFeel().createDocumentWindowButton (closeButton) : 0;
  62552. for (i = 0; i < 3; ++i)
  62553. {
  62554. if (titleBarButtons[i] != 0)
  62555. {
  62556. if (buttonListener == 0)
  62557. buttonListener = new ButtonListenerProxy (*this);
  62558. titleBarButtons[i]->addButtonListener (buttonListener);
  62559. titleBarButtons[i]->setWantsKeyboardFocus (false);
  62560. // (call the Component method directly to avoid the assertion in ResizableWindow)
  62561. Component::addAndMakeVisible (titleBarButtons[i]);
  62562. }
  62563. }
  62564. if (getCloseButton() != 0)
  62565. {
  62566. #if JUCE_MAC
  62567. getCloseButton()->addShortcut (KeyPress ('w', ModifierKeys::commandModifier, 0));
  62568. #else
  62569. getCloseButton()->addShortcut (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0));
  62570. #endif
  62571. }
  62572. }
  62573. activeWindowStatusChanged();
  62574. ResizableWindow::lookAndFeelChanged();
  62575. }
  62576. void DocumentWindow::parentHierarchyChanged()
  62577. {
  62578. lookAndFeelChanged();
  62579. }
  62580. void DocumentWindow::activeWindowStatusChanged()
  62581. {
  62582. ResizableWindow::activeWindowStatusChanged();
  62583. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  62584. if (titleBarButtons[i] != 0)
  62585. titleBarButtons[i]->setEnabled (isActiveWindow());
  62586. if (menuBar != 0)
  62587. menuBar->setEnabled (isActiveWindow());
  62588. }
  62589. void DocumentWindow::mouseDoubleClick (const MouseEvent& e)
  62590. {
  62591. if (getTitleBarArea().contains (e.x, e.y)
  62592. && getMaximiseButton() != 0)
  62593. {
  62594. getMaximiseButton()->triggerClick();
  62595. }
  62596. }
  62597. void DocumentWindow::userTriedToCloseWindow()
  62598. {
  62599. closeButtonPressed();
  62600. }
  62601. END_JUCE_NAMESPACE
  62602. /*** End of inlined file: juce_DocumentWindow.cpp ***/
  62603. /*** Start of inlined file: juce_ResizableWindow.cpp ***/
  62604. BEGIN_JUCE_NAMESPACE
  62605. ResizableWindow::ResizableWindow (const String& name,
  62606. const bool addToDesktop_)
  62607. : TopLevelWindow (name, addToDesktop_),
  62608. resizeToFitContent (false),
  62609. fullscreen (false),
  62610. lastNonFullScreenPos (50, 50, 256, 256),
  62611. constrainer (0)
  62612. #if JUCE_DEBUG
  62613. , hasBeenResized (false)
  62614. #endif
  62615. {
  62616. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  62617. lastNonFullScreenPos.setBounds (50, 50, 256, 256);
  62618. if (addToDesktop_)
  62619. Component::addToDesktop (getDesktopWindowStyleFlags());
  62620. }
  62621. ResizableWindow::ResizableWindow (const String& name,
  62622. const Colour& backgroundColour_,
  62623. const bool addToDesktop_)
  62624. : TopLevelWindow (name, addToDesktop_),
  62625. resizeToFitContent (false),
  62626. fullscreen (false),
  62627. lastNonFullScreenPos (50, 50, 256, 256),
  62628. constrainer (0)
  62629. #if JUCE_DEBUG
  62630. , hasBeenResized (false)
  62631. #endif
  62632. {
  62633. setBackgroundColour (backgroundColour_);
  62634. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  62635. if (addToDesktop_)
  62636. Component::addToDesktop (getDesktopWindowStyleFlags());
  62637. }
  62638. ResizableWindow::~ResizableWindow()
  62639. {
  62640. resizableCorner = 0;
  62641. resizableBorder = 0;
  62642. deleteAndZero (contentComponent); // (avoid using a scoped pointer for this, so that it survives
  62643. // external deletion of the content comp)
  62644. // have you been adding your own components directly to this window..? tut tut tut.
  62645. // Read the instructions for using a ResizableWindow!
  62646. jassert (getNumChildComponents() == 0);
  62647. }
  62648. int ResizableWindow::getDesktopWindowStyleFlags() const
  62649. {
  62650. int styleFlags = TopLevelWindow::getDesktopWindowStyleFlags();
  62651. if (isResizable() && (styleFlags & ComponentPeer::windowHasTitleBar) != 0)
  62652. styleFlags |= ComponentPeer::windowIsResizable;
  62653. return styleFlags;
  62654. }
  62655. void ResizableWindow::setContentComponent (Component* const newContentComponent,
  62656. const bool deleteOldOne,
  62657. const bool resizeToFit)
  62658. {
  62659. resizeToFitContent = resizeToFit;
  62660. if (newContentComponent != static_cast <Component*> (contentComponent))
  62661. {
  62662. if (deleteOldOne)
  62663. delete static_cast <Component*> (contentComponent); // (avoid using a scoped pointer for this, so that it survives
  62664. // external deletion of the content comp)
  62665. contentComponent = newContentComponent;
  62666. Component::addAndMakeVisible (contentComponent);
  62667. }
  62668. if (resizeToFit)
  62669. childBoundsChanged (contentComponent);
  62670. resized(); // must always be called to position the new content comp
  62671. }
  62672. void ResizableWindow::setContentComponentSize (int width, int height)
  62673. {
  62674. jassert (width > 0 && height > 0); // not a great idea to give it a zero size..
  62675. const BorderSize border (getContentComponentBorder());
  62676. setSize (width + border.getLeftAndRight(),
  62677. height + border.getTopAndBottom());
  62678. }
  62679. const BorderSize ResizableWindow::getBorderThickness()
  62680. {
  62681. return BorderSize (isUsingNativeTitleBar() ? 0 : ((resizableBorder != 0 && ! isFullScreen()) ? 5 : 3));
  62682. }
  62683. const BorderSize ResizableWindow::getContentComponentBorder()
  62684. {
  62685. return getBorderThickness();
  62686. }
  62687. void ResizableWindow::moved()
  62688. {
  62689. updateLastPos();
  62690. }
  62691. void ResizableWindow::visibilityChanged()
  62692. {
  62693. TopLevelWindow::visibilityChanged();
  62694. updateLastPos();
  62695. }
  62696. void ResizableWindow::resized()
  62697. {
  62698. if (resizableBorder != 0)
  62699. {
  62700. resizableBorder->setVisible (! isFullScreen());
  62701. resizableBorder->setBorderThickness (getBorderThickness());
  62702. resizableBorder->setSize (getWidth(), getHeight());
  62703. resizableBorder->toBack();
  62704. }
  62705. if (resizableCorner != 0)
  62706. {
  62707. resizableCorner->setVisible (! isFullScreen());
  62708. const int resizerSize = 18;
  62709. resizableCorner->setBounds (getWidth() - resizerSize,
  62710. getHeight() - resizerSize,
  62711. resizerSize, resizerSize);
  62712. }
  62713. if (contentComponent != 0)
  62714. contentComponent->setBoundsInset (getContentComponentBorder());
  62715. updateLastPos();
  62716. #if JUCE_DEBUG
  62717. hasBeenResized = true;
  62718. #endif
  62719. }
  62720. void ResizableWindow::childBoundsChanged (Component* child)
  62721. {
  62722. if ((child == contentComponent) && (child != 0) && resizeToFitContent)
  62723. {
  62724. // not going to look very good if this component has a zero size..
  62725. jassert (child->getWidth() > 0);
  62726. jassert (child->getHeight() > 0);
  62727. const BorderSize borders (getContentComponentBorder());
  62728. setSize (child->getWidth() + borders.getLeftAndRight(),
  62729. child->getHeight() + borders.getTopAndBottom());
  62730. }
  62731. }
  62732. void ResizableWindow::activeWindowStatusChanged()
  62733. {
  62734. const BorderSize borders (getContentComponentBorder());
  62735. repaint (0, 0, getWidth(), borders.getTop());
  62736. repaint (0, borders.getTop(), borders.getLeft(), getHeight() - borders.getBottom() - borders.getTop());
  62737. repaint (0, getHeight() - borders.getBottom(), getWidth(), borders.getBottom());
  62738. repaint (getWidth() - borders.getRight(), borders.getTop(), borders.getRight(), getHeight() - borders.getBottom() - borders.getTop());
  62739. }
  62740. void ResizableWindow::setResizable (const bool shouldBeResizable,
  62741. const bool useBottomRightCornerResizer)
  62742. {
  62743. if (shouldBeResizable)
  62744. {
  62745. if (useBottomRightCornerResizer)
  62746. {
  62747. resizableBorder = 0;
  62748. if (resizableCorner == 0)
  62749. {
  62750. Component::addChildComponent (resizableCorner = new ResizableCornerComponent (this, constrainer));
  62751. resizableCorner->setAlwaysOnTop (true);
  62752. }
  62753. }
  62754. else
  62755. {
  62756. resizableCorner = 0;
  62757. if (resizableBorder == 0)
  62758. Component::addChildComponent (resizableBorder = new ResizableBorderComponent (this, constrainer));
  62759. }
  62760. }
  62761. else
  62762. {
  62763. resizableCorner = 0;
  62764. resizableBorder = 0;
  62765. }
  62766. if (isUsingNativeTitleBar())
  62767. recreateDesktopWindow();
  62768. childBoundsChanged (contentComponent);
  62769. resized();
  62770. }
  62771. bool ResizableWindow::isResizable() const throw()
  62772. {
  62773. return resizableCorner != 0
  62774. || resizableBorder != 0;
  62775. }
  62776. void ResizableWindow::setResizeLimits (const int newMinimumWidth,
  62777. const int newMinimumHeight,
  62778. const int newMaximumWidth,
  62779. const int newMaximumHeight) throw()
  62780. {
  62781. // if you've set up a custom constrainer then these settings won't have any effect..
  62782. jassert (constrainer == &defaultConstrainer || constrainer == 0);
  62783. if (constrainer == 0)
  62784. setConstrainer (&defaultConstrainer);
  62785. defaultConstrainer.setSizeLimits (newMinimumWidth, newMinimumHeight,
  62786. newMaximumWidth, newMaximumHeight);
  62787. setBoundsConstrained (getBounds());
  62788. }
  62789. void ResizableWindow::setConstrainer (ComponentBoundsConstrainer* newConstrainer)
  62790. {
  62791. if (constrainer != newConstrainer)
  62792. {
  62793. constrainer = newConstrainer;
  62794. const bool useBottomRightCornerResizer = resizableCorner != 0;
  62795. const bool shouldBeResizable = useBottomRightCornerResizer || resizableBorder != 0;
  62796. resizableCorner = 0;
  62797. resizableBorder = 0;
  62798. setResizable (shouldBeResizable, useBottomRightCornerResizer);
  62799. ComponentPeer* const peer = getPeer();
  62800. if (peer != 0)
  62801. peer->setConstrainer (newConstrainer);
  62802. }
  62803. }
  62804. void ResizableWindow::setBoundsConstrained (const Rectangle<int>& bounds)
  62805. {
  62806. if (constrainer != 0)
  62807. constrainer->setBoundsForComponent (this, bounds, false, false, false, false);
  62808. else
  62809. setBounds (bounds);
  62810. }
  62811. void ResizableWindow::paint (Graphics& g)
  62812. {
  62813. getLookAndFeel().fillResizableWindowBackground (g, getWidth(), getHeight(),
  62814. getBorderThickness(), *this);
  62815. if (! isFullScreen())
  62816. {
  62817. getLookAndFeel().drawResizableWindowBorder (g, getWidth(), getHeight(),
  62818. getBorderThickness(), *this);
  62819. }
  62820. #if JUCE_DEBUG
  62821. /* If this fails, then you've probably written a subclass with a resized()
  62822. callback but forgotten to make it call its parent class's resized() method.
  62823. It's important when you override methods like resized(), moved(),
  62824. etc., that you make sure the base class methods also get called.
  62825. Of course you shouldn't really be overriding ResizableWindow::resized() anyway,
  62826. because your content should all be inside the content component - and it's the
  62827. content component's resized() method that you should be using to do your
  62828. layout.
  62829. */
  62830. jassert (hasBeenResized || (getWidth() == 0 && getHeight() == 0));
  62831. #endif
  62832. }
  62833. void ResizableWindow::lookAndFeelChanged()
  62834. {
  62835. resized();
  62836. if (isOnDesktop())
  62837. {
  62838. Component::addToDesktop (getDesktopWindowStyleFlags());
  62839. ComponentPeer* const peer = getPeer();
  62840. if (peer != 0)
  62841. peer->setConstrainer (constrainer);
  62842. }
  62843. }
  62844. const Colour ResizableWindow::getBackgroundColour() const throw()
  62845. {
  62846. return findColour (backgroundColourId, false);
  62847. }
  62848. void ResizableWindow::setBackgroundColour (const Colour& newColour)
  62849. {
  62850. Colour backgroundColour (newColour);
  62851. if (! Desktop::canUseSemiTransparentWindows())
  62852. backgroundColour = newColour.withAlpha (1.0f);
  62853. setColour (backgroundColourId, backgroundColour);
  62854. setOpaque (backgroundColour.isOpaque());
  62855. repaint();
  62856. }
  62857. bool ResizableWindow::isFullScreen() const
  62858. {
  62859. if (isOnDesktop())
  62860. {
  62861. ComponentPeer* const peer = getPeer();
  62862. return peer != 0 && peer->isFullScreen();
  62863. }
  62864. return fullscreen;
  62865. }
  62866. void ResizableWindow::setFullScreen (const bool shouldBeFullScreen)
  62867. {
  62868. if (shouldBeFullScreen != isFullScreen())
  62869. {
  62870. updateLastPos();
  62871. fullscreen = shouldBeFullScreen;
  62872. if (isOnDesktop())
  62873. {
  62874. ComponentPeer* const peer = getPeer();
  62875. if (peer != 0)
  62876. {
  62877. // keep a copy of this intact in case the real one gets messed-up while we're un-maximising
  62878. const Rectangle<int> lastPos (lastNonFullScreenPos);
  62879. peer->setFullScreen (shouldBeFullScreen);
  62880. if (! shouldBeFullScreen)
  62881. setBounds (lastPos);
  62882. }
  62883. else
  62884. {
  62885. jassertfalse;
  62886. }
  62887. }
  62888. else
  62889. {
  62890. if (shouldBeFullScreen)
  62891. setBounds (0, 0, getParentWidth(), getParentHeight());
  62892. else
  62893. setBounds (lastNonFullScreenPos);
  62894. }
  62895. resized();
  62896. }
  62897. }
  62898. bool ResizableWindow::isMinimised() const
  62899. {
  62900. ComponentPeer* const peer = getPeer();
  62901. return (peer != 0) && peer->isMinimised();
  62902. }
  62903. void ResizableWindow::setMinimised (const bool shouldMinimise)
  62904. {
  62905. if (shouldMinimise != isMinimised())
  62906. {
  62907. ComponentPeer* const peer = getPeer();
  62908. if (peer != 0)
  62909. {
  62910. updateLastPos();
  62911. peer->setMinimised (shouldMinimise);
  62912. }
  62913. else
  62914. {
  62915. jassertfalse;
  62916. }
  62917. }
  62918. }
  62919. void ResizableWindow::updateLastPos()
  62920. {
  62921. if (isShowing() && ! (isFullScreen() || isMinimised()))
  62922. {
  62923. lastNonFullScreenPos = getBounds();
  62924. }
  62925. }
  62926. void ResizableWindow::parentSizeChanged()
  62927. {
  62928. if (isFullScreen() && getParentComponent() != 0)
  62929. {
  62930. setBounds (0, 0, getParentWidth(), getParentHeight());
  62931. }
  62932. }
  62933. const String ResizableWindow::getWindowStateAsString()
  62934. {
  62935. updateLastPos();
  62936. return (isFullScreen() ? "fs " : "") + lastNonFullScreenPos.toString();
  62937. }
  62938. bool ResizableWindow::restoreWindowStateFromString (const String& s)
  62939. {
  62940. StringArray tokens;
  62941. tokens.addTokens (s, false);
  62942. tokens.removeEmptyStrings();
  62943. tokens.trim();
  62944. const bool fs = tokens[0].startsWithIgnoreCase ("fs");
  62945. const int firstCoord = fs ? 1 : 0;
  62946. if (tokens.size() != firstCoord + 4)
  62947. return false;
  62948. Rectangle<int> newPos (tokens[firstCoord].getIntValue(),
  62949. tokens[firstCoord + 1].getIntValue(),
  62950. tokens[firstCoord + 2].getIntValue(),
  62951. tokens[firstCoord + 3].getIntValue());
  62952. if (newPos.isEmpty())
  62953. return false;
  62954. const Rectangle<int> screen (Desktop::getInstance().getMonitorAreaContaining (newPos.getCentre()));
  62955. ComponentPeer* const peer = isOnDesktop() ? getPeer() : 0;
  62956. if (peer != 0)
  62957. peer->getFrameSize().addTo (newPos);
  62958. if (! screen.contains (newPos))
  62959. {
  62960. newPos.setSize (jmin (newPos.getWidth(), screen.getWidth()),
  62961. jmin (newPos.getHeight(), screen.getHeight()));
  62962. newPos.setPosition (jlimit (screen.getX(), screen.getRight() - newPos.getWidth(), newPos.getX()),
  62963. jlimit (screen.getY(), screen.getBottom() - newPos.getHeight(), newPos.getY()));
  62964. }
  62965. if (peer != 0)
  62966. {
  62967. peer->getFrameSize().subtractFrom (newPos);
  62968. peer->setNonFullScreenBounds (newPos);
  62969. }
  62970. lastNonFullScreenPos = newPos;
  62971. setFullScreen (fs);
  62972. if (! fs)
  62973. setBoundsConstrained (newPos);
  62974. return true;
  62975. }
  62976. void ResizableWindow::mouseDown (const MouseEvent&)
  62977. {
  62978. if (! isFullScreen())
  62979. dragger.startDraggingComponent (this, constrainer);
  62980. }
  62981. void ResizableWindow::mouseDrag (const MouseEvent& e)
  62982. {
  62983. if (! isFullScreen())
  62984. dragger.dragComponent (this, e);
  62985. }
  62986. #if JUCE_DEBUG
  62987. void ResizableWindow::addChildComponent (Component* const child, int zOrder)
  62988. {
  62989. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  62990. manages its child components automatically, and if you add your own it'll cause
  62991. trouble. Instead, use setContentComponent() to give it a component which
  62992. will be automatically resized and kept in the right place - then you can add
  62993. subcomponents to the content comp. See the notes for the ResizableWindow class
  62994. for more info.
  62995. If you really know what you're doing and want to avoid this assertion, just call
  62996. Component::addChildComponent directly.
  62997. */
  62998. jassertfalse;
  62999. Component::addChildComponent (child, zOrder);
  63000. }
  63001. void ResizableWindow::addAndMakeVisible (Component* const child, int zOrder)
  63002. {
  63003. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  63004. manages its child components automatically, and if you add your own it'll cause
  63005. trouble. Instead, use setContentComponent() to give it a component which
  63006. will be automatically resized and kept in the right place - then you can add
  63007. subcomponents to the content comp. See the notes for the ResizableWindow class
  63008. for more info.
  63009. If you really know what you're doing and want to avoid this assertion, just call
  63010. Component::addAndMakeVisible directly.
  63011. */
  63012. jassertfalse;
  63013. Component::addAndMakeVisible (child, zOrder);
  63014. }
  63015. #endif
  63016. END_JUCE_NAMESPACE
  63017. /*** End of inlined file: juce_ResizableWindow.cpp ***/
  63018. /*** Start of inlined file: juce_SplashScreen.cpp ***/
  63019. BEGIN_JUCE_NAMESPACE
  63020. SplashScreen::SplashScreen()
  63021. {
  63022. setOpaque (true);
  63023. }
  63024. SplashScreen::~SplashScreen()
  63025. {
  63026. }
  63027. void SplashScreen::show (const String& title,
  63028. const Image& backgroundImage_,
  63029. const int minimumTimeToDisplayFor,
  63030. const bool useDropShadow,
  63031. const bool removeOnMouseClick)
  63032. {
  63033. backgroundImage = backgroundImage_;
  63034. jassert (backgroundImage_.isValid());
  63035. if (backgroundImage_.isValid())
  63036. {
  63037. setOpaque (! backgroundImage_.hasAlphaChannel());
  63038. show (title,
  63039. backgroundImage_.getWidth(),
  63040. backgroundImage_.getHeight(),
  63041. minimumTimeToDisplayFor,
  63042. useDropShadow,
  63043. removeOnMouseClick);
  63044. }
  63045. }
  63046. void SplashScreen::show (const String& title,
  63047. const int width,
  63048. const int height,
  63049. const int minimumTimeToDisplayFor,
  63050. const bool useDropShadow,
  63051. const bool removeOnMouseClick)
  63052. {
  63053. setName (title);
  63054. setAlwaysOnTop (true);
  63055. setVisible (true);
  63056. centreWithSize (width, height);
  63057. addToDesktop (useDropShadow ? ComponentPeer::windowHasDropShadow : 0);
  63058. toFront (false);
  63059. MessageManager::getInstance()->runDispatchLoopUntil (300);
  63060. repaint();
  63061. originalClickCounter = removeOnMouseClick
  63062. ? Desktop::getMouseButtonClickCounter()
  63063. : std::numeric_limits<int>::max();
  63064. earliestTimeToDelete = Time::getCurrentTime() + RelativeTime::milliseconds (minimumTimeToDisplayFor);
  63065. startTimer (50);
  63066. }
  63067. void SplashScreen::paint (Graphics& g)
  63068. {
  63069. g.setOpacity (1.0f);
  63070. g.drawImage (backgroundImage,
  63071. 0, 0, getWidth(), getHeight(),
  63072. 0, 0, backgroundImage.getWidth(), backgroundImage.getHeight());
  63073. }
  63074. void SplashScreen::timerCallback()
  63075. {
  63076. if (Time::getCurrentTime() > earliestTimeToDelete
  63077. || Desktop::getMouseButtonClickCounter() > originalClickCounter)
  63078. {
  63079. delete this;
  63080. }
  63081. }
  63082. END_JUCE_NAMESPACE
  63083. /*** End of inlined file: juce_SplashScreen.cpp ***/
  63084. /*** Start of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  63085. BEGIN_JUCE_NAMESPACE
  63086. ThreadWithProgressWindow::ThreadWithProgressWindow (const String& title,
  63087. const bool hasProgressBar,
  63088. const bool hasCancelButton,
  63089. const int timeOutMsWhenCancelling_,
  63090. const String& cancelButtonText)
  63091. : Thread ("Juce Progress Window"),
  63092. progress (0.0),
  63093. timeOutMsWhenCancelling (timeOutMsWhenCancelling_)
  63094. {
  63095. alertWindow = LookAndFeel::getDefaultLookAndFeel()
  63096. .createAlertWindow (title, String::empty, cancelButtonText,
  63097. String::empty, String::empty,
  63098. AlertWindow::NoIcon, hasCancelButton ? 1 : 0, 0);
  63099. if (hasProgressBar)
  63100. alertWindow->addProgressBarComponent (progress);
  63101. }
  63102. ThreadWithProgressWindow::~ThreadWithProgressWindow()
  63103. {
  63104. stopThread (timeOutMsWhenCancelling);
  63105. }
  63106. bool ThreadWithProgressWindow::runThread (const int priority)
  63107. {
  63108. startThread (priority);
  63109. startTimer (100);
  63110. {
  63111. const ScopedLock sl (messageLock);
  63112. alertWindow->setMessage (message);
  63113. }
  63114. const bool finishedNaturally = alertWindow->runModalLoop() != 0;
  63115. stopThread (timeOutMsWhenCancelling);
  63116. alertWindow->setVisible (false);
  63117. return finishedNaturally;
  63118. }
  63119. void ThreadWithProgressWindow::setProgress (const double newProgress)
  63120. {
  63121. progress = newProgress;
  63122. }
  63123. void ThreadWithProgressWindow::setStatusMessage (const String& newStatusMessage)
  63124. {
  63125. const ScopedLock sl (messageLock);
  63126. message = newStatusMessage;
  63127. }
  63128. void ThreadWithProgressWindow::timerCallback()
  63129. {
  63130. if (! isThreadRunning())
  63131. {
  63132. // thread has finished normally..
  63133. alertWindow->exitModalState (1);
  63134. alertWindow->setVisible (false);
  63135. }
  63136. else
  63137. {
  63138. const ScopedLock sl (messageLock);
  63139. alertWindow->setMessage (message);
  63140. }
  63141. }
  63142. END_JUCE_NAMESPACE
  63143. /*** End of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  63144. /*** Start of inlined file: juce_TooltipWindow.cpp ***/
  63145. BEGIN_JUCE_NAMESPACE
  63146. TooltipWindow::TooltipWindow (Component* const parentComponent,
  63147. const int millisecondsBeforeTipAppears_)
  63148. : Component ("tooltip"),
  63149. millisecondsBeforeTipAppears (millisecondsBeforeTipAppears_),
  63150. mouseClicks (0),
  63151. lastHideTime (0),
  63152. lastComponentUnderMouse (0),
  63153. changedCompsSinceShown (true)
  63154. {
  63155. if (Desktop::getInstance().getMainMouseSource().canHover())
  63156. startTimer (123);
  63157. setAlwaysOnTop (true);
  63158. setOpaque (true);
  63159. if (parentComponent != 0)
  63160. parentComponent->addChildComponent (this);
  63161. }
  63162. TooltipWindow::~TooltipWindow()
  63163. {
  63164. hide();
  63165. }
  63166. void TooltipWindow::setMillisecondsBeforeTipAppears (const int newTimeMs) throw()
  63167. {
  63168. millisecondsBeforeTipAppears = newTimeMs;
  63169. }
  63170. void TooltipWindow::paint (Graphics& g)
  63171. {
  63172. getLookAndFeel().drawTooltip (g, tipShowing, getWidth(), getHeight());
  63173. }
  63174. void TooltipWindow::mouseEnter (const MouseEvent&)
  63175. {
  63176. hide();
  63177. }
  63178. void TooltipWindow::showFor (const String& tip)
  63179. {
  63180. jassert (tip.isNotEmpty());
  63181. tipShowing = tip;
  63182. Point<int> mousePos (Desktop::getMousePosition());
  63183. if (getParentComponent() != 0)
  63184. mousePos = getParentComponent()->globalPositionToRelative (mousePos);
  63185. int x, y, w, h;
  63186. getLookAndFeel().getTooltipSize (tip, w, h);
  63187. if (mousePos.getX() > getParentWidth() / 2)
  63188. x = mousePos.getX() - (w + 12);
  63189. else
  63190. x = mousePos.getX() + 24;
  63191. if (mousePos.getY() > getParentHeight() / 2)
  63192. y = mousePos.getY() - (h + 6);
  63193. else
  63194. y = mousePos.getY() + 6;
  63195. setBounds (x, y, w, h);
  63196. setVisible (true);
  63197. if (getParentComponent() == 0)
  63198. {
  63199. addToDesktop (ComponentPeer::windowHasDropShadow
  63200. | ComponentPeer::windowIsTemporary
  63201. | ComponentPeer::windowIgnoresKeyPresses);
  63202. }
  63203. toFront (false);
  63204. }
  63205. const String TooltipWindow::getTipFor (Component* const c)
  63206. {
  63207. if (c != 0
  63208. && Process::isForegroundProcess()
  63209. && ! Component::isMouseButtonDownAnywhere())
  63210. {
  63211. TooltipClient* const ttc = dynamic_cast <TooltipClient*> (c);
  63212. if (ttc != 0 && ! c->isCurrentlyBlockedByAnotherModalComponent())
  63213. return ttc->getTooltip();
  63214. }
  63215. return String::empty;
  63216. }
  63217. void TooltipWindow::hide()
  63218. {
  63219. tipShowing = String::empty;
  63220. removeFromDesktop();
  63221. setVisible (false);
  63222. }
  63223. void TooltipWindow::timerCallback()
  63224. {
  63225. const unsigned int now = Time::getApproximateMillisecondCounter();
  63226. Component* const newComp = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  63227. const String newTip (getTipFor (newComp));
  63228. const bool tipChanged = (newTip != lastTipUnderMouse || newComp != lastComponentUnderMouse);
  63229. lastComponentUnderMouse = newComp;
  63230. lastTipUnderMouse = newTip;
  63231. const int clickCount = Desktop::getInstance().getMouseButtonClickCounter();
  63232. const bool mouseWasClicked = clickCount > mouseClicks;
  63233. mouseClicks = clickCount;
  63234. const Point<int> mousePos (Desktop::getMousePosition());
  63235. const bool mouseMovedQuickly = mousePos.getDistanceFrom (lastMousePos) > 12;
  63236. lastMousePos = mousePos;
  63237. if (tipChanged || mouseWasClicked || mouseMovedQuickly)
  63238. lastCompChangeTime = now;
  63239. if (isVisible() || now < lastHideTime + 500)
  63240. {
  63241. // if a tip is currently visible (or has just disappeared), update to a new one
  63242. // immediately if needed..
  63243. if (newComp == 0 || mouseWasClicked || newTip.isEmpty())
  63244. {
  63245. if (isVisible())
  63246. {
  63247. lastHideTime = now;
  63248. hide();
  63249. }
  63250. }
  63251. else if (tipChanged)
  63252. {
  63253. showFor (newTip);
  63254. }
  63255. }
  63256. else
  63257. {
  63258. // if there isn't currently a tip, but one is needed, only let it
  63259. // appear after a timeout..
  63260. if (newTip.isNotEmpty()
  63261. && newTip != tipShowing
  63262. && now > lastCompChangeTime + millisecondsBeforeTipAppears)
  63263. {
  63264. showFor (newTip);
  63265. }
  63266. }
  63267. }
  63268. END_JUCE_NAMESPACE
  63269. /*** End of inlined file: juce_TooltipWindow.cpp ***/
  63270. /*** Start of inlined file: juce_TopLevelWindow.cpp ***/
  63271. BEGIN_JUCE_NAMESPACE
  63272. /** Keeps track of the active top level window.
  63273. */
  63274. class TopLevelWindowManager : public Timer,
  63275. public DeletedAtShutdown
  63276. {
  63277. public:
  63278. TopLevelWindowManager()
  63279. : currentActive (0)
  63280. {
  63281. }
  63282. ~TopLevelWindowManager()
  63283. {
  63284. clearSingletonInstance();
  63285. }
  63286. juce_DeclareSingleton_SingleThreaded_Minimal (TopLevelWindowManager)
  63287. void timerCallback()
  63288. {
  63289. startTimer (jmin (1731, getTimerInterval() * 2));
  63290. TopLevelWindow* active = 0;
  63291. if (Process::isForegroundProcess())
  63292. {
  63293. active = currentActive;
  63294. Component* const c = Component::getCurrentlyFocusedComponent();
  63295. TopLevelWindow* tlw = dynamic_cast <TopLevelWindow*> (c);
  63296. if (tlw == 0 && c != 0)
  63297. // (unable to use the syntax findParentComponentOfClass <TopLevelWindow> () because of a VC6 compiler bug)
  63298. tlw = c->findParentComponentOfClass ((TopLevelWindow*) 0);
  63299. if (tlw != 0)
  63300. active = tlw;
  63301. }
  63302. if (active != currentActive)
  63303. {
  63304. currentActive = active;
  63305. for (int i = windows.size(); --i >= 0;)
  63306. {
  63307. TopLevelWindow* const tlw = windows.getUnchecked (i);
  63308. tlw->setWindowActive (isWindowActive (tlw));
  63309. i = jmin (i, windows.size() - 1);
  63310. }
  63311. Desktop::getInstance().triggerFocusCallback();
  63312. }
  63313. }
  63314. bool addWindow (TopLevelWindow* const w)
  63315. {
  63316. windows.add (w);
  63317. startTimer (10);
  63318. return isWindowActive (w);
  63319. }
  63320. void removeWindow (TopLevelWindow* const w)
  63321. {
  63322. startTimer (10);
  63323. if (currentActive == w)
  63324. currentActive = 0;
  63325. windows.removeValue (w);
  63326. if (windows.size() == 0)
  63327. deleteInstance();
  63328. }
  63329. Array <TopLevelWindow*> windows;
  63330. private:
  63331. TopLevelWindow* currentActive;
  63332. bool isWindowActive (TopLevelWindow* const tlw) const
  63333. {
  63334. return (tlw == currentActive
  63335. || tlw->isParentOf (currentActive)
  63336. || tlw->hasKeyboardFocus (true))
  63337. && tlw->isShowing();
  63338. }
  63339. TopLevelWindowManager (const TopLevelWindowManager&);
  63340. TopLevelWindowManager& operator= (const TopLevelWindowManager&);
  63341. };
  63342. juce_ImplementSingleton_SingleThreaded (TopLevelWindowManager)
  63343. void juce_CheckCurrentlyFocusedTopLevelWindow()
  63344. {
  63345. if (TopLevelWindowManager::getInstanceWithoutCreating() != 0)
  63346. TopLevelWindowManager::getInstanceWithoutCreating()->startTimer (20);
  63347. }
  63348. TopLevelWindow::TopLevelWindow (const String& name,
  63349. const bool addToDesktop_)
  63350. : Component (name),
  63351. useDropShadow (true),
  63352. useNativeTitleBar (false),
  63353. windowIsActive_ (false)
  63354. {
  63355. setOpaque (true);
  63356. if (addToDesktop_)
  63357. Component::addToDesktop (getDesktopWindowStyleFlags());
  63358. else
  63359. setDropShadowEnabled (true);
  63360. setWantsKeyboardFocus (true);
  63361. setBroughtToFrontOnMouseClick (true);
  63362. windowIsActive_ = TopLevelWindowManager::getInstance()->addWindow (this);
  63363. }
  63364. TopLevelWindow::~TopLevelWindow()
  63365. {
  63366. shadower = 0;
  63367. TopLevelWindowManager::getInstance()->removeWindow (this);
  63368. }
  63369. void TopLevelWindow::focusOfChildComponentChanged (FocusChangeType)
  63370. {
  63371. if (hasKeyboardFocus (true))
  63372. TopLevelWindowManager::getInstance()->timerCallback();
  63373. else
  63374. TopLevelWindowManager::getInstance()->startTimer (10);
  63375. }
  63376. void TopLevelWindow::setWindowActive (const bool isNowActive)
  63377. {
  63378. if (windowIsActive_ != isNowActive)
  63379. {
  63380. windowIsActive_ = isNowActive;
  63381. activeWindowStatusChanged();
  63382. }
  63383. }
  63384. void TopLevelWindow::activeWindowStatusChanged()
  63385. {
  63386. }
  63387. void TopLevelWindow::parentHierarchyChanged()
  63388. {
  63389. setDropShadowEnabled (useDropShadow);
  63390. }
  63391. void TopLevelWindow::visibilityChanged()
  63392. {
  63393. if (isShowing())
  63394. toFront (true);
  63395. }
  63396. int TopLevelWindow::getDesktopWindowStyleFlags() const
  63397. {
  63398. int styleFlags = ComponentPeer::windowAppearsOnTaskbar;
  63399. if (useDropShadow)
  63400. styleFlags |= ComponentPeer::windowHasDropShadow;
  63401. if (useNativeTitleBar)
  63402. styleFlags |= ComponentPeer::windowHasTitleBar;
  63403. return styleFlags;
  63404. }
  63405. void TopLevelWindow::setDropShadowEnabled (const bool useShadow)
  63406. {
  63407. useDropShadow = useShadow;
  63408. if (isOnDesktop())
  63409. {
  63410. shadower = 0;
  63411. Component::addToDesktop (getDesktopWindowStyleFlags());
  63412. }
  63413. else
  63414. {
  63415. if (useShadow && isOpaque())
  63416. {
  63417. if (shadower == 0)
  63418. {
  63419. shadower = getLookAndFeel().createDropShadowerForComponent (this);
  63420. if (shadower != 0)
  63421. shadower->setOwner (this);
  63422. }
  63423. }
  63424. else
  63425. {
  63426. shadower = 0;
  63427. }
  63428. }
  63429. }
  63430. void TopLevelWindow::setUsingNativeTitleBar (const bool useNativeTitleBar_)
  63431. {
  63432. if (useNativeTitleBar != useNativeTitleBar_)
  63433. {
  63434. useNativeTitleBar = useNativeTitleBar_;
  63435. recreateDesktopWindow();
  63436. sendLookAndFeelChange();
  63437. }
  63438. }
  63439. void TopLevelWindow::recreateDesktopWindow()
  63440. {
  63441. if (isOnDesktop())
  63442. {
  63443. Component::addToDesktop (getDesktopWindowStyleFlags());
  63444. toFront (true);
  63445. }
  63446. }
  63447. void TopLevelWindow::addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo)
  63448. {
  63449. /* It's not recommended to change the desktop window flags directly for a TopLevelWindow,
  63450. because this class needs to make sure its layout corresponds with settings like whether
  63451. it's got a native title bar or not.
  63452. If you need custom flags for your window, you can override the getDesktopWindowStyleFlags()
  63453. method. If you do this, it's best to call the base class's getDesktopWindowStyleFlags()
  63454. method, then add or remove whatever flags are necessary from this value before returning it.
  63455. */
  63456. jassert ((windowStyleFlags & ~ComponentPeer::windowIsSemiTransparent)
  63457. == (getDesktopWindowStyleFlags() & ~ComponentPeer::windowIsSemiTransparent));
  63458. Component::addToDesktop (windowStyleFlags, nativeWindowToAttachTo);
  63459. if (windowStyleFlags != getDesktopWindowStyleFlags())
  63460. sendLookAndFeelChange();
  63461. }
  63462. void TopLevelWindow::centreAroundComponent (Component* c, const int width, const int height)
  63463. {
  63464. if (c == 0)
  63465. c = TopLevelWindow::getActiveTopLevelWindow();
  63466. if (c == 0)
  63467. {
  63468. centreWithSize (width, height);
  63469. }
  63470. else
  63471. {
  63472. Point<int> p (c->relativePositionToGlobal (Point<int> ((c->getWidth() - width) / 2,
  63473. (c->getHeight() - height) / 2)));
  63474. Rectangle<int> parentArea (c->getParentMonitorArea());
  63475. if (getParentComponent() != 0)
  63476. {
  63477. p = getParentComponent()->globalPositionToRelative (p);
  63478. parentArea.setBounds (0, 0, getParentWidth(), getParentHeight());
  63479. }
  63480. parentArea.reduce (12, 12);
  63481. setBounds (jlimit (parentArea.getX(), jmax (parentArea.getX(), parentArea.getRight() - width), p.getX()),
  63482. jlimit (parentArea.getY(), jmax (parentArea.getY(), parentArea.getBottom() - height), p.getY()),
  63483. width, height);
  63484. }
  63485. }
  63486. int TopLevelWindow::getNumTopLevelWindows() throw()
  63487. {
  63488. return TopLevelWindowManager::getInstance()->windows.size();
  63489. }
  63490. TopLevelWindow* TopLevelWindow::getTopLevelWindow (const int index) throw()
  63491. {
  63492. return static_cast <TopLevelWindow*> (TopLevelWindowManager::getInstance()->windows [index]);
  63493. }
  63494. TopLevelWindow* TopLevelWindow::getActiveTopLevelWindow() throw()
  63495. {
  63496. TopLevelWindow* best = 0;
  63497. int bestNumTWLParents = -1;
  63498. for (int i = TopLevelWindow::getNumTopLevelWindows(); --i >= 0;)
  63499. {
  63500. TopLevelWindow* const tlw = TopLevelWindow::getTopLevelWindow (i);
  63501. if (tlw->isActiveWindow())
  63502. {
  63503. int numTWLParents = 0;
  63504. const Component* c = tlw->getParentComponent();
  63505. while (c != 0)
  63506. {
  63507. if (dynamic_cast <const TopLevelWindow*> (c) != 0)
  63508. ++numTWLParents;
  63509. c = c->getParentComponent();
  63510. }
  63511. if (bestNumTWLParents < numTWLParents)
  63512. {
  63513. best = tlw;
  63514. bestNumTWLParents = numTWLParents;
  63515. }
  63516. }
  63517. }
  63518. return best;
  63519. }
  63520. END_JUCE_NAMESPACE
  63521. /*** End of inlined file: juce_TopLevelWindow.cpp ***/
  63522. #endif
  63523. #if JUCE_BUILD_MISC // (put these in misc to balance the file sizes and avoid problems in iphone build)
  63524. /*** Start of inlined file: juce_Colour.cpp ***/
  63525. BEGIN_JUCE_NAMESPACE
  63526. namespace ColourHelpers
  63527. {
  63528. static uint8 floatAlphaToInt (const float alpha) throw()
  63529. {
  63530. return (uint8) jlimit (0, 0xff, roundToInt (alpha * 255.0f));
  63531. }
  63532. static void convertHSBtoRGB (float h, float s, float v,
  63533. uint8& r, uint8& g, uint8& b) throw()
  63534. {
  63535. v = jlimit (0.0f, 1.0f, v);
  63536. v *= 255.0f;
  63537. const uint8 intV = (uint8) roundToInt (v);
  63538. if (s <= 0)
  63539. {
  63540. r = intV;
  63541. g = intV;
  63542. b = intV;
  63543. }
  63544. else
  63545. {
  63546. s = jmin (1.0f, s);
  63547. h = jlimit (0.0f, 1.0f, h);
  63548. h = (h - std::floor (h)) * 6.0f + 0.00001f; // need a small adjustment to compensate for rounding errors
  63549. const float f = h - std::floor (h);
  63550. const uint8 x = (uint8) roundToInt (v * (1.0f - s));
  63551. const float y = v * (1.0f - s * f);
  63552. const float z = v * (1.0f - (s * (1.0f - f)));
  63553. if (h < 1.0f)
  63554. {
  63555. r = intV;
  63556. g = (uint8) roundToInt (z);
  63557. b = x;
  63558. }
  63559. else if (h < 2.0f)
  63560. {
  63561. r = (uint8) roundToInt (y);
  63562. g = intV;
  63563. b = x;
  63564. }
  63565. else if (h < 3.0f)
  63566. {
  63567. r = x;
  63568. g = intV;
  63569. b = (uint8) roundToInt (z);
  63570. }
  63571. else if (h < 4.0f)
  63572. {
  63573. r = x;
  63574. g = (uint8) roundToInt (y);
  63575. b = intV;
  63576. }
  63577. else if (h < 5.0f)
  63578. {
  63579. r = (uint8) roundToInt (z);
  63580. g = x;
  63581. b = intV;
  63582. }
  63583. else if (h < 6.0f)
  63584. {
  63585. r = intV;
  63586. g = x;
  63587. b = (uint8) roundToInt (y);
  63588. }
  63589. else
  63590. {
  63591. r = 0;
  63592. g = 0;
  63593. b = 0;
  63594. }
  63595. }
  63596. }
  63597. }
  63598. Colour::Colour() throw()
  63599. : argb (0)
  63600. {
  63601. }
  63602. Colour::Colour (const Colour& other) throw()
  63603. : argb (other.argb)
  63604. {
  63605. }
  63606. Colour& Colour::operator= (const Colour& other) throw()
  63607. {
  63608. argb = other.argb;
  63609. return *this;
  63610. }
  63611. bool Colour::operator== (const Colour& other) const throw()
  63612. {
  63613. return argb.getARGB() == other.argb.getARGB();
  63614. }
  63615. bool Colour::operator!= (const Colour& other) const throw()
  63616. {
  63617. return argb.getARGB() != other.argb.getARGB();
  63618. }
  63619. Colour::Colour (const uint32 argb_) throw()
  63620. : argb (argb_)
  63621. {
  63622. }
  63623. Colour::Colour (const uint8 red,
  63624. const uint8 green,
  63625. const uint8 blue) throw()
  63626. {
  63627. argb.setARGB (0xff, red, green, blue);
  63628. }
  63629. const Colour Colour::fromRGB (const uint8 red,
  63630. const uint8 green,
  63631. const uint8 blue) throw()
  63632. {
  63633. return Colour (red, green, blue);
  63634. }
  63635. Colour::Colour (const uint8 red,
  63636. const uint8 green,
  63637. const uint8 blue,
  63638. const uint8 alpha) throw()
  63639. {
  63640. argb.setARGB (alpha, red, green, blue);
  63641. }
  63642. const Colour Colour::fromRGBA (const uint8 red,
  63643. const uint8 green,
  63644. const uint8 blue,
  63645. const uint8 alpha) throw()
  63646. {
  63647. return Colour (red, green, blue, alpha);
  63648. }
  63649. Colour::Colour (const uint8 red,
  63650. const uint8 green,
  63651. const uint8 blue,
  63652. const float alpha) throw()
  63653. {
  63654. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), red, green, blue);
  63655. }
  63656. const Colour Colour::fromRGBAFloat (const uint8 red,
  63657. const uint8 green,
  63658. const uint8 blue,
  63659. const float alpha) throw()
  63660. {
  63661. return Colour (red, green, blue, alpha);
  63662. }
  63663. Colour::Colour (const float hue,
  63664. const float saturation,
  63665. const float brightness,
  63666. const float alpha) throw()
  63667. {
  63668. uint8 r = getRed(), g = getGreen(), b = getBlue();
  63669. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  63670. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), r, g, b);
  63671. }
  63672. const Colour Colour::fromHSV (const float hue,
  63673. const float saturation,
  63674. const float brightness,
  63675. const float alpha) throw()
  63676. {
  63677. return Colour (hue, saturation, brightness, alpha);
  63678. }
  63679. Colour::Colour (const float hue,
  63680. const float saturation,
  63681. const float brightness,
  63682. const uint8 alpha) throw()
  63683. {
  63684. uint8 r = getRed(), g = getGreen(), b = getBlue();
  63685. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  63686. argb.setARGB (alpha, r, g, b);
  63687. }
  63688. Colour::~Colour() throw()
  63689. {
  63690. }
  63691. const PixelARGB Colour::getPixelARGB() const throw()
  63692. {
  63693. PixelARGB p (argb);
  63694. p.premultiply();
  63695. return p;
  63696. }
  63697. uint32 Colour::getARGB() const throw()
  63698. {
  63699. return argb.getARGB();
  63700. }
  63701. bool Colour::isTransparent() const throw()
  63702. {
  63703. return getAlpha() == 0;
  63704. }
  63705. bool Colour::isOpaque() const throw()
  63706. {
  63707. return getAlpha() == 0xff;
  63708. }
  63709. const Colour Colour::withAlpha (const uint8 newAlpha) const throw()
  63710. {
  63711. PixelARGB newCol (argb);
  63712. newCol.setAlpha (newAlpha);
  63713. return Colour (newCol.getARGB());
  63714. }
  63715. const Colour Colour::withAlpha (const float newAlpha) const throw()
  63716. {
  63717. jassert (newAlpha >= 0 && newAlpha <= 1.0f);
  63718. PixelARGB newCol (argb);
  63719. newCol.setAlpha (ColourHelpers::floatAlphaToInt (newAlpha));
  63720. return Colour (newCol.getARGB());
  63721. }
  63722. const Colour Colour::withMultipliedAlpha (const float alphaMultiplier) const throw()
  63723. {
  63724. jassert (alphaMultiplier >= 0);
  63725. PixelARGB newCol (argb);
  63726. newCol.setAlpha ((uint8) jmin (0xff, roundToInt (alphaMultiplier * newCol.getAlpha())));
  63727. return Colour (newCol.getARGB());
  63728. }
  63729. const Colour Colour::overlaidWith (const Colour& src) const throw()
  63730. {
  63731. const int destAlpha = getAlpha();
  63732. if (destAlpha > 0)
  63733. {
  63734. const int invA = 0xff - (int) src.getAlpha();
  63735. const int resA = 0xff - (((0xff - destAlpha) * invA) >> 8);
  63736. if (resA > 0)
  63737. {
  63738. const int da = (invA * destAlpha) / resA;
  63739. return Colour ((uint8) (src.getRed() + ((((int) getRed() - src.getRed()) * da) >> 8)),
  63740. (uint8) (src.getGreen() + ((((int) getGreen() - src.getGreen()) * da) >> 8)),
  63741. (uint8) (src.getBlue() + ((((int) getBlue() - src.getBlue()) * da) >> 8)),
  63742. (uint8) resA);
  63743. }
  63744. return *this;
  63745. }
  63746. else
  63747. {
  63748. return src;
  63749. }
  63750. }
  63751. const Colour Colour::interpolatedWith (const Colour& other, float proportionOfOther) const throw()
  63752. {
  63753. if (proportionOfOther <= 0)
  63754. return *this;
  63755. if (proportionOfOther >= 1.0f)
  63756. return other;
  63757. PixelARGB c1 (getPixelARGB());
  63758. const PixelARGB c2 (other.getPixelARGB());
  63759. c1.tween (c2, roundToInt (proportionOfOther * 255.0f));
  63760. c1.unpremultiply();
  63761. return Colour (c1.getARGB());
  63762. }
  63763. float Colour::getFloatRed() const throw()
  63764. {
  63765. return getRed() / 255.0f;
  63766. }
  63767. float Colour::getFloatGreen() const throw()
  63768. {
  63769. return getGreen() / 255.0f;
  63770. }
  63771. float Colour::getFloatBlue() const throw()
  63772. {
  63773. return getBlue() / 255.0f;
  63774. }
  63775. float Colour::getFloatAlpha() const throw()
  63776. {
  63777. return getAlpha() / 255.0f;
  63778. }
  63779. void Colour::getHSB (float& h, float& s, float& v) const throw()
  63780. {
  63781. const int r = getRed();
  63782. const int g = getGreen();
  63783. const int b = getBlue();
  63784. const int hi = jmax (r, g, b);
  63785. const int lo = jmin (r, g, b);
  63786. if (hi != 0)
  63787. {
  63788. s = (hi - lo) / (float) hi;
  63789. if (s != 0)
  63790. {
  63791. const float invDiff = 1.0f / (hi - lo);
  63792. const float red = (hi - r) * invDiff;
  63793. const float green = (hi - g) * invDiff;
  63794. const float blue = (hi - b) * invDiff;
  63795. if (r == hi)
  63796. h = blue - green;
  63797. else if (g == hi)
  63798. h = 2.0f + red - blue;
  63799. else
  63800. h = 4.0f + green - red;
  63801. h *= 1.0f / 6.0f;
  63802. if (h < 0)
  63803. ++h;
  63804. }
  63805. else
  63806. {
  63807. h = 0;
  63808. }
  63809. }
  63810. else
  63811. {
  63812. s = 0;
  63813. h = 0;
  63814. }
  63815. v = hi / 255.0f;
  63816. }
  63817. float Colour::getHue() const throw()
  63818. {
  63819. float h, s, b;
  63820. getHSB (h, s, b);
  63821. return h;
  63822. }
  63823. const Colour Colour::withHue (const float hue) const throw()
  63824. {
  63825. float h, s, b;
  63826. getHSB (h, s, b);
  63827. return Colour (hue, s, b, getAlpha());
  63828. }
  63829. const Colour Colour::withRotatedHue (const float amountToRotate) const throw()
  63830. {
  63831. float h, s, b;
  63832. getHSB (h, s, b);
  63833. h += amountToRotate;
  63834. h -= std::floor (h);
  63835. return Colour (h, s, b, getAlpha());
  63836. }
  63837. float Colour::getSaturation() const throw()
  63838. {
  63839. float h, s, b;
  63840. getHSB (h, s, b);
  63841. return s;
  63842. }
  63843. const Colour Colour::withSaturation (const float saturation) const throw()
  63844. {
  63845. float h, s, b;
  63846. getHSB (h, s, b);
  63847. return Colour (h, saturation, b, getAlpha());
  63848. }
  63849. const Colour Colour::withMultipliedSaturation (const float amount) const throw()
  63850. {
  63851. float h, s, b;
  63852. getHSB (h, s, b);
  63853. return Colour (h, jmin (1.0f, s * amount), b, getAlpha());
  63854. }
  63855. float Colour::getBrightness() const throw()
  63856. {
  63857. float h, s, b;
  63858. getHSB (h, s, b);
  63859. return b;
  63860. }
  63861. const Colour Colour::withBrightness (const float brightness) const throw()
  63862. {
  63863. float h, s, b;
  63864. getHSB (h, s, b);
  63865. return Colour (h, s, brightness, getAlpha());
  63866. }
  63867. const Colour Colour::withMultipliedBrightness (const float amount) const throw()
  63868. {
  63869. float h, s, b;
  63870. getHSB (h, s, b);
  63871. b *= amount;
  63872. if (b > 1.0f)
  63873. b = 1.0f;
  63874. return Colour (h, s, b, getAlpha());
  63875. }
  63876. const Colour Colour::brighter (float amount) const throw()
  63877. {
  63878. amount = 1.0f / (1.0f + amount);
  63879. return Colour ((uint8) (255 - (amount * (255 - getRed()))),
  63880. (uint8) (255 - (amount * (255 - getGreen()))),
  63881. (uint8) (255 - (amount * (255 - getBlue()))),
  63882. getAlpha());
  63883. }
  63884. const Colour Colour::darker (float amount) const throw()
  63885. {
  63886. amount = 1.0f / (1.0f + amount);
  63887. return Colour ((uint8) (amount * getRed()),
  63888. (uint8) (amount * getGreen()),
  63889. (uint8) (amount * getBlue()),
  63890. getAlpha());
  63891. }
  63892. const Colour Colour::greyLevel (const float brightness) throw()
  63893. {
  63894. const uint8 level
  63895. = (uint8) jlimit (0x00, 0xff, roundToInt (brightness * 255.0f));
  63896. return Colour (level, level, level);
  63897. }
  63898. const Colour Colour::contrasting (const float amount) const throw()
  63899. {
  63900. return overlaidWith ((((int) getRed() + (int) getGreen() + (int) getBlue() >= 3 * 128)
  63901. ? Colours::black
  63902. : Colours::white).withAlpha (amount));
  63903. }
  63904. const Colour Colour::contrasting (const Colour& colour1,
  63905. const Colour& colour2) throw()
  63906. {
  63907. const float b1 = colour1.getBrightness();
  63908. const float b2 = colour2.getBrightness();
  63909. float best = 0.0f;
  63910. float bestDist = 0.0f;
  63911. for (float i = 0.0f; i < 1.0f; i += 0.02f)
  63912. {
  63913. const float d1 = std::abs (i - b1);
  63914. const float d2 = std::abs (i - b2);
  63915. const float dist = jmin (d1, d2, 1.0f - d1, 1.0f - d2);
  63916. if (dist > bestDist)
  63917. {
  63918. best = i;
  63919. bestDist = dist;
  63920. }
  63921. }
  63922. return colour1.overlaidWith (colour2.withMultipliedAlpha (0.5f))
  63923. .withBrightness (best);
  63924. }
  63925. const String Colour::toString() const
  63926. {
  63927. return String::toHexString ((int) argb.getARGB());
  63928. }
  63929. const Colour Colour::fromString (const String& encodedColourString)
  63930. {
  63931. return Colour ((uint32) encodedColourString.getHexValue32());
  63932. }
  63933. const String Colour::toDisplayString (const bool includeAlphaValue) const
  63934. {
  63935. return String::toHexString ((int) (argb.getARGB() & (includeAlphaValue ? 0xffffffff : 0xffffff)))
  63936. .paddedLeft ('0', includeAlphaValue ? 8 : 6)
  63937. .toUpperCase();
  63938. }
  63939. END_JUCE_NAMESPACE
  63940. /*** End of inlined file: juce_Colour.cpp ***/
  63941. /*** Start of inlined file: juce_ColourGradient.cpp ***/
  63942. BEGIN_JUCE_NAMESPACE
  63943. ColourGradient::ColourGradient() throw()
  63944. {
  63945. #if JUCE_DEBUG
  63946. point1.setX (987654.0f);
  63947. #endif
  63948. }
  63949. ColourGradient::ColourGradient (const Colour& colour1, const float x1_, const float y1_,
  63950. const Colour& colour2, const float x2_, const float y2_,
  63951. const bool isRadial_)
  63952. : point1 (x1_, y1_),
  63953. point2 (x2_, y2_),
  63954. isRadial (isRadial_)
  63955. {
  63956. colours.add (ColourPoint (0.0, colour1));
  63957. colours.add (ColourPoint (1.0, colour2));
  63958. }
  63959. ColourGradient::~ColourGradient()
  63960. {
  63961. }
  63962. bool ColourGradient::operator== (const ColourGradient& other) const throw()
  63963. {
  63964. return point1 == other.point1 && point2 == other.point2
  63965. && isRadial == other.isRadial
  63966. && colours == other.colours;
  63967. }
  63968. bool ColourGradient::operator!= (const ColourGradient& other) const throw()
  63969. {
  63970. return ! operator== (other);
  63971. }
  63972. void ColourGradient::clearColours()
  63973. {
  63974. colours.clear();
  63975. }
  63976. int ColourGradient::addColour (const double proportionAlongGradient, const Colour& colour)
  63977. {
  63978. // must be within the two end-points
  63979. jassert (proportionAlongGradient >= 0 && proportionAlongGradient <= 1.0);
  63980. const double pos = jlimit (0.0, 1.0, proportionAlongGradient);
  63981. int i;
  63982. for (i = 0; i < colours.size(); ++i)
  63983. if (colours.getReference(i).position > pos)
  63984. break;
  63985. colours.insert (i, ColourPoint (pos, colour));
  63986. return i;
  63987. }
  63988. void ColourGradient::removeColour (int index)
  63989. {
  63990. jassert (index > 0 && index < colours.size() - 1);
  63991. colours.remove (index);
  63992. }
  63993. void ColourGradient::multiplyOpacity (const float multiplier) throw()
  63994. {
  63995. for (int i = 0; i < colours.size(); ++i)
  63996. {
  63997. Colour& c = colours.getReference(i).colour;
  63998. c = c.withMultipliedAlpha (multiplier);
  63999. }
  64000. }
  64001. int ColourGradient::getNumColours() const throw()
  64002. {
  64003. return colours.size();
  64004. }
  64005. double ColourGradient::getColourPosition (const int index) const throw()
  64006. {
  64007. if (((unsigned int) index) < (unsigned int) colours.size())
  64008. return colours.getReference (index).position;
  64009. return 0;
  64010. }
  64011. const Colour ColourGradient::getColour (const int index) const throw()
  64012. {
  64013. if (((unsigned int) index) < (unsigned int) colours.size())
  64014. return colours.getReference (index).colour;
  64015. return Colour();
  64016. }
  64017. void ColourGradient::setColour (int index, const Colour& newColour) throw()
  64018. {
  64019. if (((unsigned int) index) < (unsigned int) colours.size())
  64020. colours.getReference (index).colour = newColour;
  64021. }
  64022. const Colour ColourGradient::getColourAtPosition (const double position) const throw()
  64023. {
  64024. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  64025. if (position <= 0 || colours.size() <= 1)
  64026. return colours.getReference(0).colour;
  64027. int i = colours.size() - 1;
  64028. while (position < colours.getReference(i).position)
  64029. --i;
  64030. const ColourPoint& p1 = colours.getReference (i);
  64031. if (i >= colours.size() - 1)
  64032. return p1.colour;
  64033. const ColourPoint& p2 = colours.getReference (i + 1);
  64034. return p1.colour.interpolatedWith (p2.colour, (float) ((position - p1.position) / (p2.position - p1.position)));
  64035. }
  64036. int ColourGradient::createLookupTable (const AffineTransform& transform, HeapBlock <PixelARGB>& lookupTable) const
  64037. {
  64038. #if JUCE_DEBUG
  64039. // trying to use the object without setting its co-ordinates? Have a careful read of
  64040. // the comments for the constructors.
  64041. jassert (point1.getX() != 987654.0f);
  64042. #endif
  64043. const int numEntries = jlimit (1, jmax (1, (colours.size() - 1) << 8),
  64044. 3 * (int) point1.transformedBy (transform)
  64045. .getDistanceFrom (point2.transformedBy (transform)));
  64046. lookupTable.malloc (numEntries);
  64047. if (colours.size() >= 2)
  64048. {
  64049. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  64050. PixelARGB pix1 (colours.getReference (0).colour.getPixelARGB());
  64051. int index = 0;
  64052. for (int j = 1; j < colours.size(); ++j)
  64053. {
  64054. const ColourPoint& p = colours.getReference (j);
  64055. const int numToDo = roundToInt (p.position * (numEntries - 1)) - index;
  64056. const PixelARGB pix2 (p.colour.getPixelARGB());
  64057. for (int i = 0; i < numToDo; ++i)
  64058. {
  64059. jassert (index >= 0 && index < numEntries);
  64060. lookupTable[index] = pix1;
  64061. lookupTable[index].tween (pix2, (i << 8) / numToDo);
  64062. ++index;
  64063. }
  64064. pix1 = pix2;
  64065. }
  64066. while (index < numEntries)
  64067. lookupTable [index++] = pix1;
  64068. }
  64069. else
  64070. {
  64071. jassertfalse; // no colours specified!
  64072. }
  64073. return numEntries;
  64074. }
  64075. bool ColourGradient::isOpaque() const throw()
  64076. {
  64077. for (int i = 0; i < colours.size(); ++i)
  64078. if (! colours.getReference(i).colour.isOpaque())
  64079. return false;
  64080. return true;
  64081. }
  64082. bool ColourGradient::isInvisible() const throw()
  64083. {
  64084. for (int i = 0; i < colours.size(); ++i)
  64085. if (! colours.getReference(i).colour.isTransparent())
  64086. return false;
  64087. return true;
  64088. }
  64089. END_JUCE_NAMESPACE
  64090. /*** End of inlined file: juce_ColourGradient.cpp ***/
  64091. /*** Start of inlined file: juce_Colours.cpp ***/
  64092. BEGIN_JUCE_NAMESPACE
  64093. const Colour Colours::transparentBlack (0);
  64094. const Colour Colours::transparentWhite (0x00ffffff);
  64095. const Colour Colours::aliceblue (0xfff0f8ff);
  64096. const Colour Colours::antiquewhite (0xfffaebd7);
  64097. const Colour Colours::aqua (0xff00ffff);
  64098. const Colour Colours::aquamarine (0xff7fffd4);
  64099. const Colour Colours::azure (0xfff0ffff);
  64100. const Colour Colours::beige (0xfff5f5dc);
  64101. const Colour Colours::bisque (0xffffe4c4);
  64102. const Colour Colours::black (0xff000000);
  64103. const Colour Colours::blanchedalmond (0xffffebcd);
  64104. const Colour Colours::blue (0xff0000ff);
  64105. const Colour Colours::blueviolet (0xff8a2be2);
  64106. const Colour Colours::brown (0xffa52a2a);
  64107. const Colour Colours::burlywood (0xffdeb887);
  64108. const Colour Colours::cadetblue (0xff5f9ea0);
  64109. const Colour Colours::chartreuse (0xff7fff00);
  64110. const Colour Colours::chocolate (0xffd2691e);
  64111. const Colour Colours::coral (0xffff7f50);
  64112. const Colour Colours::cornflowerblue (0xff6495ed);
  64113. const Colour Colours::cornsilk (0xfffff8dc);
  64114. const Colour Colours::crimson (0xffdc143c);
  64115. const Colour Colours::cyan (0xff00ffff);
  64116. const Colour Colours::darkblue (0xff00008b);
  64117. const Colour Colours::darkcyan (0xff008b8b);
  64118. const Colour Colours::darkgoldenrod (0xffb8860b);
  64119. const Colour Colours::darkgrey (0xff555555);
  64120. const Colour Colours::darkgreen (0xff006400);
  64121. const Colour Colours::darkkhaki (0xffbdb76b);
  64122. const Colour Colours::darkmagenta (0xff8b008b);
  64123. const Colour Colours::darkolivegreen (0xff556b2f);
  64124. const Colour Colours::darkorange (0xffff8c00);
  64125. const Colour Colours::darkorchid (0xff9932cc);
  64126. const Colour Colours::darkred (0xff8b0000);
  64127. const Colour Colours::darksalmon (0xffe9967a);
  64128. const Colour Colours::darkseagreen (0xff8fbc8f);
  64129. const Colour Colours::darkslateblue (0xff483d8b);
  64130. const Colour Colours::darkslategrey (0xff2f4f4f);
  64131. const Colour Colours::darkturquoise (0xff00ced1);
  64132. const Colour Colours::darkviolet (0xff9400d3);
  64133. const Colour Colours::deeppink (0xffff1493);
  64134. const Colour Colours::deepskyblue (0xff00bfff);
  64135. const Colour Colours::dimgrey (0xff696969);
  64136. const Colour Colours::dodgerblue (0xff1e90ff);
  64137. const Colour Colours::firebrick (0xffb22222);
  64138. const Colour Colours::floralwhite (0xfffffaf0);
  64139. const Colour Colours::forestgreen (0xff228b22);
  64140. const Colour Colours::fuchsia (0xffff00ff);
  64141. const Colour Colours::gainsboro (0xffdcdcdc);
  64142. const Colour Colours::gold (0xffffd700);
  64143. const Colour Colours::goldenrod (0xffdaa520);
  64144. const Colour Colours::grey (0xff808080);
  64145. const Colour Colours::green (0xff008000);
  64146. const Colour Colours::greenyellow (0xffadff2f);
  64147. const Colour Colours::honeydew (0xfff0fff0);
  64148. const Colour Colours::hotpink (0xffff69b4);
  64149. const Colour Colours::indianred (0xffcd5c5c);
  64150. const Colour Colours::indigo (0xff4b0082);
  64151. const Colour Colours::ivory (0xfffffff0);
  64152. const Colour Colours::khaki (0xfff0e68c);
  64153. const Colour Colours::lavender (0xffe6e6fa);
  64154. const Colour Colours::lavenderblush (0xfffff0f5);
  64155. const Colour Colours::lemonchiffon (0xfffffacd);
  64156. const Colour Colours::lightblue (0xffadd8e6);
  64157. const Colour Colours::lightcoral (0xfff08080);
  64158. const Colour Colours::lightcyan (0xffe0ffff);
  64159. const Colour Colours::lightgoldenrodyellow (0xfffafad2);
  64160. const Colour Colours::lightgreen (0xff90ee90);
  64161. const Colour Colours::lightgrey (0xffd3d3d3);
  64162. const Colour Colours::lightpink (0xffffb6c1);
  64163. const Colour Colours::lightsalmon (0xffffa07a);
  64164. const Colour Colours::lightseagreen (0xff20b2aa);
  64165. const Colour Colours::lightskyblue (0xff87cefa);
  64166. const Colour Colours::lightslategrey (0xff778899);
  64167. const Colour Colours::lightsteelblue (0xffb0c4de);
  64168. const Colour Colours::lightyellow (0xffffffe0);
  64169. const Colour Colours::lime (0xff00ff00);
  64170. const Colour Colours::limegreen (0xff32cd32);
  64171. const Colour Colours::linen (0xfffaf0e6);
  64172. const Colour Colours::magenta (0xffff00ff);
  64173. const Colour Colours::maroon (0xff800000);
  64174. const Colour Colours::mediumaquamarine (0xff66cdaa);
  64175. const Colour Colours::mediumblue (0xff0000cd);
  64176. const Colour Colours::mediumorchid (0xffba55d3);
  64177. const Colour Colours::mediumpurple (0xff9370db);
  64178. const Colour Colours::mediumseagreen (0xff3cb371);
  64179. const Colour Colours::mediumslateblue (0xff7b68ee);
  64180. const Colour Colours::mediumspringgreen (0xff00fa9a);
  64181. const Colour Colours::mediumturquoise (0xff48d1cc);
  64182. const Colour Colours::mediumvioletred (0xffc71585);
  64183. const Colour Colours::midnightblue (0xff191970);
  64184. const Colour Colours::mintcream (0xfff5fffa);
  64185. const Colour Colours::mistyrose (0xffffe4e1);
  64186. const Colour Colours::navajowhite (0xffffdead);
  64187. const Colour Colours::navy (0xff000080);
  64188. const Colour Colours::oldlace (0xfffdf5e6);
  64189. const Colour Colours::olive (0xff808000);
  64190. const Colour Colours::olivedrab (0xff6b8e23);
  64191. const Colour Colours::orange (0xffffa500);
  64192. const Colour Colours::orangered (0xffff4500);
  64193. const Colour Colours::orchid (0xffda70d6);
  64194. const Colour Colours::palegoldenrod (0xffeee8aa);
  64195. const Colour Colours::palegreen (0xff98fb98);
  64196. const Colour Colours::paleturquoise (0xffafeeee);
  64197. const Colour Colours::palevioletred (0xffdb7093);
  64198. const Colour Colours::papayawhip (0xffffefd5);
  64199. const Colour Colours::peachpuff (0xffffdab9);
  64200. const Colour Colours::peru (0xffcd853f);
  64201. const Colour Colours::pink (0xffffc0cb);
  64202. const Colour Colours::plum (0xffdda0dd);
  64203. const Colour Colours::powderblue (0xffb0e0e6);
  64204. const Colour Colours::purple (0xff800080);
  64205. const Colour Colours::red (0xffff0000);
  64206. const Colour Colours::rosybrown (0xffbc8f8f);
  64207. const Colour Colours::royalblue (0xff4169e1);
  64208. const Colour Colours::saddlebrown (0xff8b4513);
  64209. const Colour Colours::salmon (0xfffa8072);
  64210. const Colour Colours::sandybrown (0xfff4a460);
  64211. const Colour Colours::seagreen (0xff2e8b57);
  64212. const Colour Colours::seashell (0xfffff5ee);
  64213. const Colour Colours::sienna (0xffa0522d);
  64214. const Colour Colours::silver (0xffc0c0c0);
  64215. const Colour Colours::skyblue (0xff87ceeb);
  64216. const Colour Colours::slateblue (0xff6a5acd);
  64217. const Colour Colours::slategrey (0xff708090);
  64218. const Colour Colours::snow (0xfffffafa);
  64219. const Colour Colours::springgreen (0xff00ff7f);
  64220. const Colour Colours::steelblue (0xff4682b4);
  64221. const Colour Colours::tan (0xffd2b48c);
  64222. const Colour Colours::teal (0xff008080);
  64223. const Colour Colours::thistle (0xffd8bfd8);
  64224. const Colour Colours::tomato (0xffff6347);
  64225. const Colour Colours::turquoise (0xff40e0d0);
  64226. const Colour Colours::violet (0xffee82ee);
  64227. const Colour Colours::wheat (0xfff5deb3);
  64228. const Colour Colours::white (0xffffffff);
  64229. const Colour Colours::whitesmoke (0xfff5f5f5);
  64230. const Colour Colours::yellow (0xffffff00);
  64231. const Colour Colours::yellowgreen (0xff9acd32);
  64232. const Colour Colours::findColourForName (const String& colourName,
  64233. const Colour& defaultColour)
  64234. {
  64235. static const int presets[] =
  64236. {
  64237. // (first value is the string's hashcode, second is ARGB)
  64238. 0x05978fff, 0xff000000, /* black */
  64239. 0x06bdcc29, 0xffffffff, /* white */
  64240. 0x002e305a, 0xff0000ff, /* blue */
  64241. 0x00308adf, 0xff808080, /* grey */
  64242. 0x05e0cf03, 0xff008000, /* green */
  64243. 0x0001b891, 0xffff0000, /* red */
  64244. 0xd43c6474, 0xffffff00, /* yellow */
  64245. 0x620886da, 0xfff0f8ff, /* aliceblue */
  64246. 0x20a2676a, 0xfffaebd7, /* antiquewhite */
  64247. 0x002dcebc, 0xff00ffff, /* aqua */
  64248. 0x46bb5f7e, 0xff7fffd4, /* aquamarine */
  64249. 0x0590228f, 0xfff0ffff, /* azure */
  64250. 0x05947fe4, 0xfff5f5dc, /* beige */
  64251. 0xad388e35, 0xffffe4c4, /* bisque */
  64252. 0x00674f7e, 0xffffebcd, /* blanchedalmond */
  64253. 0x39129959, 0xff8a2be2, /* blueviolet */
  64254. 0x059a8136, 0xffa52a2a, /* brown */
  64255. 0x89cea8f9, 0xffdeb887, /* burlywood */
  64256. 0x0fa260cf, 0xff5f9ea0, /* cadetblue */
  64257. 0x6b748956, 0xff7fff00, /* chartreuse */
  64258. 0x2903623c, 0xffd2691e, /* chocolate */
  64259. 0x05a74431, 0xffff7f50, /* coral */
  64260. 0x618d42dd, 0xff6495ed, /* cornflowerblue */
  64261. 0xe4b479fd, 0xfffff8dc, /* cornsilk */
  64262. 0x3d8c4edf, 0xffdc143c, /* crimson */
  64263. 0x002ed323, 0xff00ffff, /* cyan */
  64264. 0x67cc74d0, 0xff00008b, /* darkblue */
  64265. 0x67cd1799, 0xff008b8b, /* darkcyan */
  64266. 0x31bbd168, 0xffb8860b, /* darkgoldenrod */
  64267. 0x67cecf55, 0xff555555, /* darkgrey */
  64268. 0x920b194d, 0xff006400, /* darkgreen */
  64269. 0x923edd4c, 0xffbdb76b, /* darkkhaki */
  64270. 0x5c293873, 0xff8b008b, /* darkmagenta */
  64271. 0x6b6671fe, 0xff556b2f, /* darkolivegreen */
  64272. 0xbcfd2524, 0xffff8c00, /* darkorange */
  64273. 0xbcfdf799, 0xff9932cc, /* darkorchid */
  64274. 0x55ee0d5b, 0xff8b0000, /* darkred */
  64275. 0xc2e5f564, 0xffe9967a, /* darksalmon */
  64276. 0x61be858a, 0xff8fbc8f, /* darkseagreen */
  64277. 0xc2b0f2bd, 0xff483d8b, /* darkslateblue */
  64278. 0xc2b34d42, 0xff2f4f4f, /* darkslategrey */
  64279. 0x7cf2b06b, 0xff00ced1, /* darkturquoise */
  64280. 0xc8769375, 0xff9400d3, /* darkviolet */
  64281. 0x25832862, 0xffff1493, /* deeppink */
  64282. 0xfcad568f, 0xff00bfff, /* deepskyblue */
  64283. 0x634c8b67, 0xff696969, /* dimgrey */
  64284. 0x45c1ce55, 0xff1e90ff, /* dodgerblue */
  64285. 0xef19e3cb, 0xffb22222, /* firebrick */
  64286. 0xb852b195, 0xfffffaf0, /* floralwhite */
  64287. 0xd086fd06, 0xff228b22, /* forestgreen */
  64288. 0xe106b6d7, 0xffff00ff, /* fuchsia */
  64289. 0x7880d61e, 0xffdcdcdc, /* gainsboro */
  64290. 0x00308060, 0xffffd700, /* gold */
  64291. 0xb3b3bc1e, 0xffdaa520, /* goldenrod */
  64292. 0xbab8a537, 0xffadff2f, /* greenyellow */
  64293. 0xe4cacafb, 0xfff0fff0, /* honeydew */
  64294. 0x41892743, 0xffff69b4, /* hotpink */
  64295. 0xd5796f1a, 0xffcd5c5c, /* indianred */
  64296. 0xb969fed2, 0xff4b0082, /* indigo */
  64297. 0x05fef6a9, 0xfffffff0, /* ivory */
  64298. 0x06149302, 0xfff0e68c, /* khaki */
  64299. 0xad5a05c7, 0xffe6e6fa, /* lavender */
  64300. 0x7c4d5b99, 0xfffff0f5, /* lavenderblush */
  64301. 0x195756f0, 0xfffffacd, /* lemonchiffon */
  64302. 0x28e4ea70, 0xffadd8e6, /* lightblue */
  64303. 0xf3c7ccdb, 0xfff08080, /* lightcoral */
  64304. 0x28e58d39, 0xffe0ffff, /* lightcyan */
  64305. 0x21234e3c, 0xfffafad2, /* lightgoldenrodyellow */
  64306. 0xf40157ad, 0xff90ee90, /* lightgreen */
  64307. 0x28e744f5, 0xffd3d3d3, /* lightgrey */
  64308. 0x28eb3b8c, 0xffffb6c1, /* lightpink */
  64309. 0x9fb78304, 0xffffa07a, /* lightsalmon */
  64310. 0x50632b2a, 0xff20b2aa, /* lightseagreen */
  64311. 0x68fb7b25, 0xff87cefa, /* lightskyblue */
  64312. 0xa8a35ba2, 0xff778899, /* lightslategrey */
  64313. 0xa20d484f, 0xffb0c4de, /* lightsteelblue */
  64314. 0xaa2cf10a, 0xffffffe0, /* lightyellow */
  64315. 0x0032afd5, 0xff00ff00, /* lime */
  64316. 0x607bbc4e, 0xff32cd32, /* limegreen */
  64317. 0x06234efa, 0xfffaf0e6, /* linen */
  64318. 0x316858a9, 0xffff00ff, /* magenta */
  64319. 0xbf8ca470, 0xff800000, /* maroon */
  64320. 0xbd58e0b3, 0xff66cdaa, /* mediumaquamarine */
  64321. 0x967dfd4f, 0xff0000cd, /* mediumblue */
  64322. 0x056f5c58, 0xffba55d3, /* mediumorchid */
  64323. 0x07556b71, 0xff9370db, /* mediumpurple */
  64324. 0x5369b689, 0xff3cb371, /* mediumseagreen */
  64325. 0x066be19e, 0xff7b68ee, /* mediumslateblue */
  64326. 0x3256b281, 0xff00fa9a, /* mediumspringgreen */
  64327. 0xc0ad9f4c, 0xff48d1cc, /* mediumturquoise */
  64328. 0x628e63dd, 0xffc71585, /* mediumvioletred */
  64329. 0x168eb32a, 0xff191970, /* midnightblue */
  64330. 0x4306b960, 0xfff5fffa, /* mintcream */
  64331. 0x4cbc0e6b, 0xffffe4e1, /* mistyrose */
  64332. 0xe97218a6, 0xffffdead, /* navajowhite */
  64333. 0x00337bb6, 0xff000080, /* navy */
  64334. 0xadd2d33e, 0xfffdf5e6, /* oldlace */
  64335. 0x064ee1db, 0xff808000, /* olive */
  64336. 0x9e33a98a, 0xff6b8e23, /* olivedrab */
  64337. 0xc3de262e, 0xffffa500, /* orange */
  64338. 0x58bebba3, 0xffff4500, /* orangered */
  64339. 0xc3def8a3, 0xffda70d6, /* orchid */
  64340. 0x28cb4834, 0xffeee8aa, /* palegoldenrod */
  64341. 0x3d9dd619, 0xff98fb98, /* palegreen */
  64342. 0x74022737, 0xffafeeee, /* paleturquoise */
  64343. 0x15e2ebc8, 0xffdb7093, /* palevioletred */
  64344. 0x5fd898e2, 0xffffefd5, /* papayawhip */
  64345. 0x93e1b776, 0xffffdab9, /* peachpuff */
  64346. 0x003472f8, 0xffcd853f, /* peru */
  64347. 0x00348176, 0xffffc0cb, /* pink */
  64348. 0x00348d94, 0xffdda0dd, /* plum */
  64349. 0xd036be93, 0xffb0e0e6, /* powderblue */
  64350. 0xc5c507bc, 0xff800080, /* purple */
  64351. 0xa89d65b3, 0xffbc8f8f, /* rosybrown */
  64352. 0xbd9413e1, 0xff4169e1, /* royalblue */
  64353. 0xf456044f, 0xff8b4513, /* saddlebrown */
  64354. 0xc9c6f66e, 0xfffa8072, /* salmon */
  64355. 0x0bb131e1, 0xfff4a460, /* sandybrown */
  64356. 0x34636c14, 0xff2e8b57, /* seagreen */
  64357. 0x3507fb41, 0xfffff5ee, /* seashell */
  64358. 0xca348772, 0xffa0522d, /* sienna */
  64359. 0xca37d30d, 0xffc0c0c0, /* silver */
  64360. 0x80da74fb, 0xff87ceeb, /* skyblue */
  64361. 0x44a8dd73, 0xff6a5acd, /* slateblue */
  64362. 0x44ab37f8, 0xff708090, /* slategrey */
  64363. 0x0035f183, 0xfffffafa, /* snow */
  64364. 0xd5440d16, 0xff00ff7f, /* springgreen */
  64365. 0x3e1524a5, 0xff4682b4, /* steelblue */
  64366. 0x0001bfa1, 0xffd2b48c, /* tan */
  64367. 0x0036425c, 0xff008080, /* teal */
  64368. 0xafc8858f, 0xffd8bfd8, /* thistle */
  64369. 0xcc41600a, 0xffff6347, /* tomato */
  64370. 0xfeea9b21, 0xff40e0d0, /* turquoise */
  64371. 0xcf57947f, 0xffee82ee, /* violet */
  64372. 0x06bdbae7, 0xfff5deb3, /* wheat */
  64373. 0x10802ee6, 0xfff5f5f5, /* whitesmoke */
  64374. 0xe1b5130f, 0xff9acd32 /* yellowgreen */
  64375. };
  64376. const int hash = colourName.trim().toLowerCase().hashCode();
  64377. for (int i = 0; i < numElementsInArray (presets); i += 2)
  64378. if (presets [i] == hash)
  64379. return Colour (presets [i + 1]);
  64380. return defaultColour;
  64381. }
  64382. END_JUCE_NAMESPACE
  64383. /*** End of inlined file: juce_Colours.cpp ***/
  64384. /*** Start of inlined file: juce_EdgeTable.cpp ***/
  64385. BEGIN_JUCE_NAMESPACE
  64386. const int juce_edgeTableDefaultEdgesPerLine = 32;
  64387. EdgeTable::EdgeTable (const Rectangle<int>& bounds_,
  64388. const Path& path, const AffineTransform& transform)
  64389. : bounds (bounds_),
  64390. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  64391. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  64392. needToCheckEmptinesss (true)
  64393. {
  64394. table.malloc ((bounds.getHeight() + 1) * lineStrideElements);
  64395. int* t = table;
  64396. for (int i = bounds.getHeight(); --i >= 0;)
  64397. {
  64398. *t = 0;
  64399. t += lineStrideElements;
  64400. }
  64401. const int topLimit = bounds.getY() << 8;
  64402. const int heightLimit = bounds.getHeight() << 8;
  64403. const int leftLimit = bounds.getX() << 8;
  64404. const int rightLimit = bounds.getRight() << 8;
  64405. PathFlatteningIterator iter (path, transform);
  64406. while (iter.next())
  64407. {
  64408. int y1 = roundToInt (iter.y1 * 256.0f);
  64409. int y2 = roundToInt (iter.y2 * 256.0f);
  64410. if (y1 != y2)
  64411. {
  64412. y1 -= topLimit;
  64413. y2 -= topLimit;
  64414. const int startY = y1;
  64415. int direction = -1;
  64416. if (y1 > y2)
  64417. {
  64418. swapVariables (y1, y2);
  64419. direction = 1;
  64420. }
  64421. if (y1 < 0)
  64422. y1 = 0;
  64423. if (y2 > heightLimit)
  64424. y2 = heightLimit;
  64425. if (y1 < y2)
  64426. {
  64427. const double startX = 256.0f * iter.x1;
  64428. const double multiplier = (iter.x2 - iter.x1) / (iter.y2 - iter.y1);
  64429. const int stepSize = jlimit (1, 256, 256 / (1 + (int) std::abs (multiplier)));
  64430. do
  64431. {
  64432. const int step = jmin (stepSize, y2 - y1, 256 - (y1 & 255));
  64433. int x = roundToInt (startX + multiplier * ((y1 + (step >> 1)) - startY));
  64434. if (x < leftLimit)
  64435. x = leftLimit;
  64436. else if (x >= rightLimit)
  64437. x = rightLimit - 1;
  64438. addEdgePoint (x, y1 >> 8, direction * step);
  64439. y1 += step;
  64440. }
  64441. while (y1 < y2);
  64442. }
  64443. }
  64444. }
  64445. sanitiseLevels (path.isUsingNonZeroWinding());
  64446. }
  64447. EdgeTable::EdgeTable (const Rectangle<int>& rectangleToAdd)
  64448. : bounds (rectangleToAdd),
  64449. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  64450. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  64451. needToCheckEmptinesss (true)
  64452. {
  64453. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  64454. table[0] = 0;
  64455. const int x1 = rectangleToAdd.getX() << 8;
  64456. const int x2 = rectangleToAdd.getRight() << 8;
  64457. int* t = table;
  64458. for (int i = rectangleToAdd.getHeight(); --i >= 0;)
  64459. {
  64460. t[0] = 2;
  64461. t[1] = x1;
  64462. t[2] = 255;
  64463. t[3] = x2;
  64464. t[4] = 0;
  64465. t += lineStrideElements;
  64466. }
  64467. }
  64468. EdgeTable::EdgeTable (const RectangleList& rectanglesToAdd)
  64469. : bounds (rectanglesToAdd.getBounds()),
  64470. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  64471. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  64472. needToCheckEmptinesss (true)
  64473. {
  64474. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  64475. int* t = table;
  64476. for (int i = bounds.getHeight(); --i >= 0;)
  64477. {
  64478. *t = 0;
  64479. t += lineStrideElements;
  64480. }
  64481. for (RectangleList::Iterator iter (rectanglesToAdd); iter.next();)
  64482. {
  64483. const Rectangle<int>* const r = iter.getRectangle();
  64484. const int x1 = r->getX() << 8;
  64485. const int x2 = r->getRight() << 8;
  64486. int y = r->getY() - bounds.getY();
  64487. for (int j = r->getHeight(); --j >= 0;)
  64488. {
  64489. addEdgePoint (x1, y, 255);
  64490. addEdgePoint (x2, y, -255);
  64491. ++y;
  64492. }
  64493. }
  64494. sanitiseLevels (true);
  64495. }
  64496. EdgeTable::EdgeTable (const Rectangle<float>& rectangleToAdd)
  64497. : bounds (Rectangle<int> ((int) std::floor (rectangleToAdd.getX()),
  64498. roundToInt (rectangleToAdd.getY() * 256.0f) >> 8,
  64499. 2 + (int) rectangleToAdd.getWidth(),
  64500. 2 + (int) rectangleToAdd.getHeight())),
  64501. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  64502. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  64503. needToCheckEmptinesss (true)
  64504. {
  64505. jassert (! rectangleToAdd.isEmpty());
  64506. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  64507. table[0] = 0;
  64508. const int x1 = roundToInt (rectangleToAdd.getX() * 256.0f);
  64509. const int x2 = roundToInt (rectangleToAdd.getRight() * 256.0f);
  64510. int y1 = roundToInt (rectangleToAdd.getY() * 256.0f) - (bounds.getY() << 8);
  64511. jassert (y1 < 256);
  64512. int y2 = roundToInt (rectangleToAdd.getBottom() * 256.0f) - (bounds.getY() << 8);
  64513. if (x2 <= x1 || y2 <= y1)
  64514. {
  64515. bounds.setHeight (0);
  64516. return;
  64517. }
  64518. int lineY = 0;
  64519. int* t = table;
  64520. if ((y1 >> 8) == (y2 >> 8))
  64521. {
  64522. t[0] = 2;
  64523. t[1] = x1;
  64524. t[2] = y2 - y1;
  64525. t[3] = x2;
  64526. t[4] = 0;
  64527. ++lineY;
  64528. t += lineStrideElements;
  64529. }
  64530. else
  64531. {
  64532. t[0] = 2;
  64533. t[1] = x1;
  64534. t[2] = 255 - (y1 & 255);
  64535. t[3] = x2;
  64536. t[4] = 0;
  64537. ++lineY;
  64538. t += lineStrideElements;
  64539. while (lineY < (y2 >> 8))
  64540. {
  64541. t[0] = 2;
  64542. t[1] = x1;
  64543. t[2] = 255;
  64544. t[3] = x2;
  64545. t[4] = 0;
  64546. ++lineY;
  64547. t += lineStrideElements;
  64548. }
  64549. jassert (lineY < bounds.getHeight());
  64550. t[0] = 2;
  64551. t[1] = x1;
  64552. t[2] = y2 & 255;
  64553. t[3] = x2;
  64554. t[4] = 0;
  64555. ++lineY;
  64556. t += lineStrideElements;
  64557. }
  64558. while (lineY < bounds.getHeight())
  64559. {
  64560. t[0] = 0;
  64561. t += lineStrideElements;
  64562. ++lineY;
  64563. }
  64564. }
  64565. EdgeTable::EdgeTable (const EdgeTable& other)
  64566. {
  64567. operator= (other);
  64568. }
  64569. EdgeTable& EdgeTable::operator= (const EdgeTable& other)
  64570. {
  64571. bounds = other.bounds;
  64572. maxEdgesPerLine = other.maxEdgesPerLine;
  64573. lineStrideElements = other.lineStrideElements;
  64574. needToCheckEmptinesss = other.needToCheckEmptinesss;
  64575. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  64576. copyEdgeTableData (table, lineStrideElements, other.table, lineStrideElements, bounds.getHeight());
  64577. return *this;
  64578. }
  64579. EdgeTable::~EdgeTable()
  64580. {
  64581. }
  64582. void EdgeTable::copyEdgeTableData (int* dest, const int destLineStride, const int* src, const int srcLineStride, int numLines) throw()
  64583. {
  64584. while (--numLines >= 0)
  64585. {
  64586. memcpy (dest, src, (src[0] * 2 + 1) * sizeof (int));
  64587. src += srcLineStride;
  64588. dest += destLineStride;
  64589. }
  64590. }
  64591. void EdgeTable::sanitiseLevels (const bool useNonZeroWinding) throw()
  64592. {
  64593. // Convert the table from relative windings to absolute levels..
  64594. int* lineStart = table;
  64595. for (int i = bounds.getHeight(); --i >= 0;)
  64596. {
  64597. int* line = lineStart;
  64598. lineStart += lineStrideElements;
  64599. int num = *line;
  64600. if (num == 0)
  64601. continue;
  64602. int level = 0;
  64603. if (useNonZeroWinding)
  64604. {
  64605. while (--num > 0)
  64606. {
  64607. line += 2;
  64608. level += *line;
  64609. int corrected = abs (level);
  64610. if (corrected >> 8)
  64611. corrected = 255;
  64612. *line = corrected;
  64613. }
  64614. }
  64615. else
  64616. {
  64617. while (--num > 0)
  64618. {
  64619. line += 2;
  64620. level += *line;
  64621. int corrected = abs (level);
  64622. if (corrected >> 8)
  64623. {
  64624. corrected &= 511;
  64625. if (corrected >> 8)
  64626. corrected = 511 - corrected;
  64627. }
  64628. *line = corrected;
  64629. }
  64630. }
  64631. line[2] = 0; // force the last level to 0, just in case something went wrong in creating the table
  64632. }
  64633. }
  64634. void EdgeTable::remapTableForNumEdges (const int newNumEdgesPerLine) throw()
  64635. {
  64636. if (newNumEdgesPerLine != maxEdgesPerLine)
  64637. {
  64638. maxEdgesPerLine = newNumEdgesPerLine;
  64639. jassert (bounds.getHeight() > 0);
  64640. const int newLineStrideElements = maxEdgesPerLine * 2 + 1;
  64641. HeapBlock <int> newTable (bounds.getHeight() * newLineStrideElements);
  64642. copyEdgeTableData (newTable, newLineStrideElements, table, lineStrideElements, bounds.getHeight());
  64643. table.swapWith (newTable);
  64644. lineStrideElements = newLineStrideElements;
  64645. }
  64646. }
  64647. void EdgeTable::optimiseTable() throw()
  64648. {
  64649. int maxLineElements = 0;
  64650. for (int i = bounds.getHeight(); --i >= 0;)
  64651. maxLineElements = jmax (maxLineElements, table [i * lineStrideElements]);
  64652. remapTableForNumEdges (maxLineElements);
  64653. }
  64654. void EdgeTable::addEdgePoint (const int x, const int y, const int winding) throw()
  64655. {
  64656. jassert (y >= 0 && y < bounds.getHeight());
  64657. int* line = table + lineStrideElements * y;
  64658. const int numPoints = line[0];
  64659. int n = numPoints << 1;
  64660. if (n > 0)
  64661. {
  64662. while (n > 0)
  64663. {
  64664. const int cx = line [n - 1];
  64665. if (cx <= x)
  64666. {
  64667. if (cx == x)
  64668. {
  64669. line [n] += winding;
  64670. return;
  64671. }
  64672. break;
  64673. }
  64674. n -= 2;
  64675. }
  64676. if (numPoints >= maxEdgesPerLine)
  64677. {
  64678. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  64679. jassert (numPoints < maxEdgesPerLine);
  64680. line = table + lineStrideElements * y;
  64681. }
  64682. memmove (line + (n + 3), line + (n + 1), sizeof (int) * ((numPoints << 1) - n));
  64683. }
  64684. line [n + 1] = x;
  64685. line [n + 2] = winding;
  64686. line[0]++;
  64687. }
  64688. void EdgeTable::translate (float dx, const int dy) throw()
  64689. {
  64690. bounds.translate ((int) std::floor (dx), dy);
  64691. int* lineStart = table;
  64692. const int intDx = (int) (dx * 256.0f);
  64693. for (int i = bounds.getHeight(); --i >= 0;)
  64694. {
  64695. int* line = lineStart;
  64696. lineStart += lineStrideElements;
  64697. int num = *line++;
  64698. while (--num >= 0)
  64699. {
  64700. *line += intDx;
  64701. line += 2;
  64702. }
  64703. }
  64704. }
  64705. void EdgeTable::intersectWithEdgeTableLine (const int y, const int* otherLine) throw()
  64706. {
  64707. jassert (y >= 0 && y < bounds.getHeight());
  64708. int* dest = table + lineStrideElements * y;
  64709. if (dest[0] == 0)
  64710. return;
  64711. int otherNumPoints = *otherLine;
  64712. if (otherNumPoints == 0)
  64713. {
  64714. *dest = 0;
  64715. return;
  64716. }
  64717. const int right = bounds.getRight() << 8;
  64718. // optimise for the common case where our line lies entirely within a
  64719. // single pair of points, as happens when clipping to a simple rect.
  64720. if (otherNumPoints == 2 && otherLine[2] >= 255)
  64721. {
  64722. clipEdgeTableLineToRange (dest, otherLine[1], jmin (right, otherLine[3]));
  64723. return;
  64724. }
  64725. ++otherLine;
  64726. const size_t lineSizeBytes = (dest[0] * 2 + 1) * sizeof (int);
  64727. int* temp = (int*) alloca (lineSizeBytes);
  64728. memcpy (temp, dest, lineSizeBytes);
  64729. const int* src1 = temp;
  64730. int srcNum1 = *src1++;
  64731. int x1 = *src1++;
  64732. const int* src2 = otherLine;
  64733. int srcNum2 = otherNumPoints;
  64734. int x2 = *src2++;
  64735. int destIndex = 0, destTotal = 0;
  64736. int level1 = 0, level2 = 0;
  64737. int lastX = std::numeric_limits<int>::min(), lastLevel = 0;
  64738. while (srcNum1 > 0 && srcNum2 > 0)
  64739. {
  64740. int nextX;
  64741. if (x1 < x2)
  64742. {
  64743. nextX = x1;
  64744. level1 = *src1++;
  64745. x1 = *src1++;
  64746. --srcNum1;
  64747. }
  64748. else if (x1 == x2)
  64749. {
  64750. nextX = x1;
  64751. level1 = *src1++;
  64752. level2 = *src2++;
  64753. x1 = *src1++;
  64754. x2 = *src2++;
  64755. --srcNum1;
  64756. --srcNum2;
  64757. }
  64758. else
  64759. {
  64760. nextX = x2;
  64761. level2 = *src2++;
  64762. x2 = *src2++;
  64763. --srcNum2;
  64764. }
  64765. if (nextX > lastX)
  64766. {
  64767. if (nextX >= right)
  64768. break;
  64769. lastX = nextX;
  64770. const int nextLevel = (level1 * (level2 + 1)) >> 8;
  64771. jassert (((unsigned int) nextLevel) < (unsigned int) 256);
  64772. if (nextLevel != lastLevel)
  64773. {
  64774. if (destTotal >= maxEdgesPerLine)
  64775. {
  64776. dest[0] = destTotal;
  64777. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  64778. dest = table + lineStrideElements * y;
  64779. }
  64780. ++destTotal;
  64781. lastLevel = nextLevel;
  64782. dest[++destIndex] = nextX;
  64783. dest[++destIndex] = nextLevel;
  64784. }
  64785. }
  64786. }
  64787. if (lastLevel > 0)
  64788. {
  64789. if (destTotal >= maxEdgesPerLine)
  64790. {
  64791. dest[0] = destTotal;
  64792. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  64793. dest = table + lineStrideElements * y;
  64794. }
  64795. ++destTotal;
  64796. dest[++destIndex] = right;
  64797. dest[++destIndex] = 0;
  64798. }
  64799. dest[0] = destTotal;
  64800. #if JUCE_DEBUG
  64801. int last = std::numeric_limits<int>::min();
  64802. for (int i = 0; i < dest[0]; ++i)
  64803. {
  64804. jassert (dest[i * 2 + 1] > last);
  64805. last = dest[i * 2 + 1];
  64806. }
  64807. jassert (dest [dest[0] * 2] == 0);
  64808. #endif
  64809. }
  64810. void EdgeTable::clipEdgeTableLineToRange (int* dest, const int x1, const int x2) throw()
  64811. {
  64812. int* lastItem = dest + (dest[0] * 2 - 1);
  64813. if (x2 < lastItem[0])
  64814. {
  64815. if (x2 <= dest[1])
  64816. {
  64817. dest[0] = 0;
  64818. return;
  64819. }
  64820. while (x2 < lastItem[-2])
  64821. {
  64822. --(dest[0]);
  64823. lastItem -= 2;
  64824. }
  64825. lastItem[0] = x2;
  64826. lastItem[1] = 0;
  64827. }
  64828. if (x1 > dest[1])
  64829. {
  64830. while (lastItem[0] > x1)
  64831. lastItem -= 2;
  64832. const int itemsRemoved = (int) (lastItem - (dest + 1)) / 2;
  64833. if (itemsRemoved > 0)
  64834. {
  64835. dest[0] -= itemsRemoved;
  64836. memmove (dest + 1, lastItem, dest[0] * (sizeof (int) * 2));
  64837. }
  64838. dest[1] = x1;
  64839. }
  64840. }
  64841. void EdgeTable::clipToRectangle (const Rectangle<int>& r) throw()
  64842. {
  64843. const Rectangle<int> clipped (r.getIntersection (bounds));
  64844. if (clipped.isEmpty())
  64845. {
  64846. needToCheckEmptinesss = false;
  64847. bounds.setHeight (0);
  64848. }
  64849. else
  64850. {
  64851. const int top = clipped.getY() - bounds.getY();
  64852. const int bottom = clipped.getBottom() - bounds.getY();
  64853. if (bottom < bounds.getHeight())
  64854. bounds.setHeight (bottom);
  64855. if (clipped.getRight() < bounds.getRight())
  64856. bounds.setRight (clipped.getRight());
  64857. for (int i = top; --i >= 0;)
  64858. table [lineStrideElements * i] = 0;
  64859. if (clipped.getX() > bounds.getX())
  64860. {
  64861. const int x1 = clipped.getX() << 8;
  64862. const int x2 = jmin (bounds.getRight(), clipped.getRight()) << 8;
  64863. int* line = table + lineStrideElements * top;
  64864. for (int i = bottom - top; --i >= 0;)
  64865. {
  64866. if (line[0] != 0)
  64867. clipEdgeTableLineToRange (line, x1, x2);
  64868. line += lineStrideElements;
  64869. }
  64870. }
  64871. needToCheckEmptinesss = true;
  64872. }
  64873. }
  64874. void EdgeTable::excludeRectangle (const Rectangle<int>& r) throw()
  64875. {
  64876. const Rectangle<int> clipped (r.getIntersection (bounds));
  64877. if (! clipped.isEmpty())
  64878. {
  64879. const int top = clipped.getY() - bounds.getY();
  64880. const int bottom = clipped.getBottom() - bounds.getY();
  64881. //XXX optimise here by shortening the table if it fills top or bottom
  64882. const int rectLine[] = { 4, std::numeric_limits<int>::min(), 255,
  64883. clipped.getX() << 8, 0,
  64884. clipped.getRight() << 8, 255,
  64885. std::numeric_limits<int>::max(), 0 };
  64886. for (int i = top; i < bottom; ++i)
  64887. intersectWithEdgeTableLine (i, rectLine);
  64888. needToCheckEmptinesss = true;
  64889. }
  64890. }
  64891. void EdgeTable::clipToEdgeTable (const EdgeTable& other)
  64892. {
  64893. const Rectangle<int> clipped (other.bounds.getIntersection (bounds));
  64894. if (clipped.isEmpty())
  64895. {
  64896. needToCheckEmptinesss = false;
  64897. bounds.setHeight (0);
  64898. }
  64899. else
  64900. {
  64901. const int top = clipped.getY() - bounds.getY();
  64902. const int bottom = clipped.getBottom() - bounds.getY();
  64903. if (bottom < bounds.getHeight())
  64904. bounds.setHeight (bottom);
  64905. if (clipped.getRight() < bounds.getRight())
  64906. bounds.setRight (clipped.getRight());
  64907. int i = 0;
  64908. for (i = top; --i >= 0;)
  64909. table [lineStrideElements * i] = 0;
  64910. const int* otherLine = other.table + other.lineStrideElements * (clipped.getY() - other.bounds.getY());
  64911. for (i = top; i < bottom; ++i)
  64912. {
  64913. intersectWithEdgeTableLine (i, otherLine);
  64914. otherLine += other.lineStrideElements;
  64915. }
  64916. needToCheckEmptinesss = true;
  64917. }
  64918. }
  64919. void EdgeTable::clipLineToMask (int x, int y, const uint8* mask, int maskStride, int numPixels) throw()
  64920. {
  64921. y -= bounds.getY();
  64922. if (y < 0 || y >= bounds.getHeight())
  64923. return;
  64924. needToCheckEmptinesss = true;
  64925. if (numPixels <= 0)
  64926. {
  64927. table [lineStrideElements * y] = 0;
  64928. return;
  64929. }
  64930. int* tempLine = (int*) alloca ((numPixels * 2 + 4) * sizeof (int));
  64931. int destIndex = 0, lastLevel = 0;
  64932. while (--numPixels >= 0)
  64933. {
  64934. const int alpha = *mask;
  64935. mask += maskStride;
  64936. if (alpha != lastLevel)
  64937. {
  64938. tempLine[++destIndex] = (x << 8);
  64939. tempLine[++destIndex] = alpha;
  64940. lastLevel = alpha;
  64941. }
  64942. ++x;
  64943. }
  64944. if (lastLevel > 0)
  64945. {
  64946. tempLine[++destIndex] = (x << 8);
  64947. tempLine[++destIndex] = 0;
  64948. }
  64949. tempLine[0] = destIndex >> 1;
  64950. intersectWithEdgeTableLine (y, tempLine);
  64951. }
  64952. bool EdgeTable::isEmpty() throw()
  64953. {
  64954. if (needToCheckEmptinesss)
  64955. {
  64956. needToCheckEmptinesss = false;
  64957. int* t = table;
  64958. for (int i = bounds.getHeight(); --i >= 0;)
  64959. {
  64960. if (t[0] > 1)
  64961. return false;
  64962. t += lineStrideElements;
  64963. }
  64964. bounds.setHeight (0);
  64965. }
  64966. return bounds.getHeight() == 0;
  64967. }
  64968. END_JUCE_NAMESPACE
  64969. /*** End of inlined file: juce_EdgeTable.cpp ***/
  64970. /*** Start of inlined file: juce_FillType.cpp ***/
  64971. BEGIN_JUCE_NAMESPACE
  64972. FillType::FillType() throw()
  64973. : colour (0xff000000), image (0)
  64974. {
  64975. }
  64976. FillType::FillType (const Colour& colour_) throw()
  64977. : colour (colour_), image (0)
  64978. {
  64979. }
  64980. FillType::FillType (const ColourGradient& gradient_)
  64981. : colour (0xff000000), gradient (new ColourGradient (gradient_)), image (0)
  64982. {
  64983. }
  64984. FillType::FillType (const Image& image_, const AffineTransform& transform_) throw()
  64985. : colour (0xff000000), image (image_), transform (transform_)
  64986. {
  64987. }
  64988. FillType::FillType (const FillType& other)
  64989. : colour (other.colour),
  64990. gradient (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0),
  64991. image (other.image), transform (other.transform)
  64992. {
  64993. }
  64994. FillType& FillType::operator= (const FillType& other)
  64995. {
  64996. if (this != &other)
  64997. {
  64998. colour = other.colour;
  64999. gradient = (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0);
  65000. image = other.image;
  65001. transform = other.transform;
  65002. }
  65003. return *this;
  65004. }
  65005. FillType::~FillType() throw()
  65006. {
  65007. }
  65008. bool FillType::operator== (const FillType& other) const
  65009. {
  65010. return colour == other.colour && image == other.image
  65011. && (gradient == other.gradient
  65012. || (gradient != 0 && other.gradient != 0 && *gradient == *other.gradient));
  65013. }
  65014. bool FillType::operator!= (const FillType& other) const
  65015. {
  65016. return ! operator== (other);
  65017. }
  65018. void FillType::setColour (const Colour& newColour) throw()
  65019. {
  65020. gradient = 0;
  65021. image = Image();
  65022. colour = newColour;
  65023. }
  65024. void FillType::setGradient (const ColourGradient& newGradient)
  65025. {
  65026. if (gradient != 0)
  65027. {
  65028. *gradient = newGradient;
  65029. }
  65030. else
  65031. {
  65032. image = Image();
  65033. gradient = new ColourGradient (newGradient);
  65034. colour = Colours::black;
  65035. }
  65036. }
  65037. void FillType::setTiledImage (const Image& image_, const AffineTransform& transform_) throw()
  65038. {
  65039. gradient = 0;
  65040. image = image_;
  65041. transform = transform_;
  65042. colour = Colours::black;
  65043. }
  65044. void FillType::setOpacity (const float newOpacity) throw()
  65045. {
  65046. colour = colour.withAlpha (newOpacity);
  65047. }
  65048. bool FillType::isInvisible() const throw()
  65049. {
  65050. return colour.isTransparent() || (gradient != 0 && gradient->isInvisible());
  65051. }
  65052. END_JUCE_NAMESPACE
  65053. /*** End of inlined file: juce_FillType.cpp ***/
  65054. /*** Start of inlined file: juce_Graphics.cpp ***/
  65055. BEGIN_JUCE_NAMESPACE
  65056. template <typename Type>
  65057. static bool areCoordsSensibleNumbers (Type x, Type y, Type w, Type h)
  65058. {
  65059. const int maxVal = 0x3fffffff;
  65060. return (int) x >= -maxVal && (int) x <= maxVal
  65061. && (int) y >= -maxVal && (int) y <= maxVal
  65062. && (int) w >= -maxVal && (int) w <= maxVal
  65063. && (int) h >= -maxVal && (int) h <= maxVal;
  65064. }
  65065. LowLevelGraphicsContext::LowLevelGraphicsContext()
  65066. {
  65067. }
  65068. LowLevelGraphicsContext::~LowLevelGraphicsContext()
  65069. {
  65070. }
  65071. Graphics::Graphics (const Image& imageToDrawOnto)
  65072. : context (imageToDrawOnto.createLowLevelContext()),
  65073. contextToDelete (context),
  65074. saveStatePending (false)
  65075. {
  65076. }
  65077. Graphics::Graphics (LowLevelGraphicsContext* const internalContext) throw()
  65078. : context (internalContext),
  65079. saveStatePending (false)
  65080. {
  65081. }
  65082. Graphics::~Graphics()
  65083. {
  65084. }
  65085. void Graphics::resetToDefaultState()
  65086. {
  65087. saveStateIfPending();
  65088. context->setFill (FillType());
  65089. context->setFont (Font());
  65090. context->setInterpolationQuality (Graphics::mediumResamplingQuality);
  65091. }
  65092. bool Graphics::isVectorDevice() const
  65093. {
  65094. return context->isVectorDevice();
  65095. }
  65096. bool Graphics::reduceClipRegion (const int x, const int y, const int w, const int h)
  65097. {
  65098. saveStateIfPending();
  65099. return context->clipToRectangle (Rectangle<int> (x, y, w, h));
  65100. }
  65101. bool Graphics::reduceClipRegion (const RectangleList& clipRegion)
  65102. {
  65103. saveStateIfPending();
  65104. return context->clipToRectangleList (clipRegion);
  65105. }
  65106. bool Graphics::reduceClipRegion (const Path& path, const AffineTransform& transform)
  65107. {
  65108. saveStateIfPending();
  65109. context->clipToPath (path, transform);
  65110. return ! context->isClipEmpty();
  65111. }
  65112. bool Graphics::reduceClipRegion (const Image& image, const Rectangle<int>& sourceClipRegion, const AffineTransform& transform)
  65113. {
  65114. saveStateIfPending();
  65115. context->clipToImageAlpha (image, sourceClipRegion, transform);
  65116. return ! context->isClipEmpty();
  65117. }
  65118. void Graphics::excludeClipRegion (const Rectangle<int>& rectangleToExclude)
  65119. {
  65120. saveStateIfPending();
  65121. context->excludeClipRectangle (rectangleToExclude);
  65122. }
  65123. bool Graphics::isClipEmpty() const
  65124. {
  65125. return context->isClipEmpty();
  65126. }
  65127. const Rectangle<int> Graphics::getClipBounds() const
  65128. {
  65129. return context->getClipBounds();
  65130. }
  65131. void Graphics::saveState()
  65132. {
  65133. saveStateIfPending();
  65134. saveStatePending = true;
  65135. }
  65136. void Graphics::restoreState()
  65137. {
  65138. if (saveStatePending)
  65139. saveStatePending = false;
  65140. else
  65141. context->restoreState();
  65142. }
  65143. void Graphics::saveStateIfPending()
  65144. {
  65145. if (saveStatePending)
  65146. {
  65147. saveStatePending = false;
  65148. context->saveState();
  65149. }
  65150. }
  65151. void Graphics::setOrigin (const int newOriginX, const int newOriginY)
  65152. {
  65153. saveStateIfPending();
  65154. context->setOrigin (newOriginX, newOriginY);
  65155. }
  65156. bool Graphics::clipRegionIntersects (const Rectangle<int>& area) const
  65157. {
  65158. return context->clipRegionIntersects (area);
  65159. }
  65160. void Graphics::setColour (const Colour& newColour)
  65161. {
  65162. saveStateIfPending();
  65163. context->setFill (newColour);
  65164. }
  65165. void Graphics::setOpacity (const float newOpacity)
  65166. {
  65167. saveStateIfPending();
  65168. context->setOpacity (newOpacity);
  65169. }
  65170. void Graphics::setGradientFill (const ColourGradient& gradient)
  65171. {
  65172. setFillType (gradient);
  65173. }
  65174. void Graphics::setTiledImageFill (const Image& imageToUse, const int anchorX, const int anchorY, const float opacity)
  65175. {
  65176. saveStateIfPending();
  65177. context->setFill (FillType (imageToUse, AffineTransform::translation ((float) anchorX, (float) anchorY)));
  65178. context->setOpacity (opacity);
  65179. }
  65180. void Graphics::setFillType (const FillType& newFill)
  65181. {
  65182. saveStateIfPending();
  65183. context->setFill (newFill);
  65184. }
  65185. void Graphics::setFont (const Font& newFont)
  65186. {
  65187. saveStateIfPending();
  65188. context->setFont (newFont);
  65189. }
  65190. void Graphics::setFont (const float newFontHeight, const int newFontStyleFlags)
  65191. {
  65192. saveStateIfPending();
  65193. Font f (context->getFont());
  65194. f.setSizeAndStyle (newFontHeight, newFontStyleFlags, 1.0f, 0);
  65195. context->setFont (f);
  65196. }
  65197. const Font Graphics::getCurrentFont() const
  65198. {
  65199. return context->getFont();
  65200. }
  65201. void Graphics::drawSingleLineText (const String& text, const int startX, const int baselineY) const
  65202. {
  65203. if (text.isNotEmpty()
  65204. && startX < context->getClipBounds().getRight())
  65205. {
  65206. GlyphArrangement arr;
  65207. arr.addLineOfText (context->getFont(), text, (float) startX, (float) baselineY);
  65208. arr.draw (*this);
  65209. }
  65210. }
  65211. void Graphics::drawTextAsPath (const String& text, const AffineTransform& transform) const
  65212. {
  65213. if (text.isNotEmpty())
  65214. {
  65215. GlyphArrangement arr;
  65216. arr.addLineOfText (context->getFont(), text, 0.0f, 0.0f);
  65217. arr.draw (*this, transform);
  65218. }
  65219. }
  65220. void Graphics::drawMultiLineText (const String& text, const int startX, const int baselineY, const int maximumLineWidth) const
  65221. {
  65222. if (text.isNotEmpty()
  65223. && startX < context->getClipBounds().getRight())
  65224. {
  65225. GlyphArrangement arr;
  65226. arr.addJustifiedText (context->getFont(), text,
  65227. (float) startX, (float) baselineY, (float) maximumLineWidth,
  65228. Justification::left);
  65229. arr.draw (*this);
  65230. }
  65231. }
  65232. void Graphics::drawText (const String& text,
  65233. const int x, const int y, const int width, const int height,
  65234. const Justification& justificationType,
  65235. const bool useEllipsesIfTooBig) const
  65236. {
  65237. if (text.isNotEmpty() && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  65238. {
  65239. GlyphArrangement arr;
  65240. arr.addCurtailedLineOfText (context->getFont(), text,
  65241. 0.0f, 0.0f, (float) width,
  65242. useEllipsesIfTooBig);
  65243. arr.justifyGlyphs (0, arr.getNumGlyphs(),
  65244. (float) x, (float) y, (float) width, (float) height,
  65245. justificationType);
  65246. arr.draw (*this);
  65247. }
  65248. }
  65249. void Graphics::drawFittedText (const String& text,
  65250. const int x, const int y, const int width, const int height,
  65251. const Justification& justification,
  65252. const int maximumNumberOfLines,
  65253. const float minimumHorizontalScale) const
  65254. {
  65255. if (text.isNotEmpty()
  65256. && width > 0 && height > 0
  65257. && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  65258. {
  65259. GlyphArrangement arr;
  65260. arr.addFittedText (context->getFont(), text,
  65261. (float) x, (float) y, (float) width, (float) height,
  65262. justification,
  65263. maximumNumberOfLines,
  65264. minimumHorizontalScale);
  65265. arr.draw (*this);
  65266. }
  65267. }
  65268. void Graphics::fillRect (int x, int y, int width, int height) const
  65269. {
  65270. // passing in a silly number can cause maths problems in rendering!
  65271. jassert (areCoordsSensibleNumbers (x, y, width, height));
  65272. context->fillRect (Rectangle<int> (x, y, width, height), false);
  65273. }
  65274. void Graphics::fillRect (const Rectangle<int>& r) const
  65275. {
  65276. context->fillRect (r, false);
  65277. }
  65278. void Graphics::fillRect (const float x, const float y, const float width, const float height) const
  65279. {
  65280. // passing in a silly number can cause maths problems in rendering!
  65281. jassert (areCoordsSensibleNumbers (x, y, width, height));
  65282. Path p;
  65283. p.addRectangle (x, y, width, height);
  65284. fillPath (p);
  65285. }
  65286. void Graphics::setPixel (int x, int y) const
  65287. {
  65288. context->fillRect (Rectangle<int> (x, y, 1, 1), false);
  65289. }
  65290. void Graphics::fillAll() const
  65291. {
  65292. fillRect (context->getClipBounds());
  65293. }
  65294. void Graphics::fillAll (const Colour& colourToUse) const
  65295. {
  65296. if (! colourToUse.isTransparent())
  65297. {
  65298. const Rectangle<int> clip (context->getClipBounds());
  65299. context->saveState();
  65300. context->setFill (colourToUse);
  65301. context->fillRect (clip, false);
  65302. context->restoreState();
  65303. }
  65304. }
  65305. void Graphics::fillPath (const Path& path, const AffineTransform& transform) const
  65306. {
  65307. if ((! context->isClipEmpty()) && ! path.isEmpty())
  65308. context->fillPath (path, transform);
  65309. }
  65310. void Graphics::strokePath (const Path& path,
  65311. const PathStrokeType& strokeType,
  65312. const AffineTransform& transform) const
  65313. {
  65314. Path stroke;
  65315. strokeType.createStrokedPath (stroke, path, transform);
  65316. fillPath (stroke);
  65317. }
  65318. void Graphics::drawRect (const int x, const int y, const int width, const int height,
  65319. const int lineThickness) const
  65320. {
  65321. // passing in a silly number can cause maths problems in rendering!
  65322. jassert (areCoordsSensibleNumbers (x, y, width, height));
  65323. context->fillRect (Rectangle<int> (x, y, width, lineThickness), false);
  65324. context->fillRect (Rectangle<int> (x, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  65325. context->fillRect (Rectangle<int> (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  65326. context->fillRect (Rectangle<int> (x, y + height - lineThickness, width, lineThickness), false);
  65327. }
  65328. void Graphics::drawRect (const float x, const float y, const float width, const float height, const float lineThickness) const
  65329. {
  65330. // passing in a silly number can cause maths problems in rendering!
  65331. jassert (areCoordsSensibleNumbers (x, y, width, height));
  65332. Path p;
  65333. p.addRectangle (x, y, width, lineThickness);
  65334. p.addRectangle (x, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  65335. p.addRectangle (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  65336. p.addRectangle (x, y + height - lineThickness, width, lineThickness);
  65337. fillPath (p);
  65338. }
  65339. void Graphics::drawRect (const Rectangle<int>& r, const int lineThickness) const
  65340. {
  65341. drawRect (r.getX(), r.getY(), r.getWidth(), r.getHeight(), lineThickness);
  65342. }
  65343. void Graphics::drawBevel (const int x, const int y, const int width, const int height,
  65344. const int bevelThickness, const Colour& topLeftColour, const Colour& bottomRightColour,
  65345. const bool useGradient, const bool sharpEdgeOnOutside) const
  65346. {
  65347. // passing in a silly number can cause maths problems in rendering!
  65348. jassert (areCoordsSensibleNumbers (x, y, width, height));
  65349. if (clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  65350. {
  65351. context->saveState();
  65352. const float oldOpacity = 1.0f;//xxx state->colour.getFloatAlpha();
  65353. const float ramp = oldOpacity / bevelThickness;
  65354. for (int i = bevelThickness; --i >= 0;)
  65355. {
  65356. const float op = useGradient ? ramp * (sharpEdgeOnOutside ? bevelThickness - i : i)
  65357. : oldOpacity;
  65358. context->setFill (topLeftColour.withMultipliedAlpha (op));
  65359. context->fillRect (Rectangle<int> (x + i, y + i, width - i * 2, 1), false);
  65360. context->setFill (topLeftColour.withMultipliedAlpha (op * 0.75f));
  65361. context->fillRect (Rectangle<int> (x + i, y + i + 1, 1, height - i * 2 - 2), false);
  65362. context->setFill (bottomRightColour.withMultipliedAlpha (op));
  65363. context->fillRect (Rectangle<int> (x + i, y + height - i - 1, width - i * 2, 1), false);
  65364. context->setFill (bottomRightColour.withMultipliedAlpha (op * 0.75f));
  65365. context->fillRect (Rectangle<int> (x + width - i - 1, y + i + 1, 1, height - i * 2 - 2), false);
  65366. }
  65367. context->restoreState();
  65368. }
  65369. }
  65370. void Graphics::fillEllipse (const float x, const float y, const float width, const float height) const
  65371. {
  65372. // passing in a silly number can cause maths problems in rendering!
  65373. jassert (areCoordsSensibleNumbers (x, y, width, height));
  65374. Path p;
  65375. p.addEllipse (x, y, width, height);
  65376. fillPath (p);
  65377. }
  65378. void Graphics::drawEllipse (const float x, const float y, const float width, const float height,
  65379. const float lineThickness) const
  65380. {
  65381. // passing in a silly number can cause maths problems in rendering!
  65382. jassert (areCoordsSensibleNumbers (x, y, width, height));
  65383. Path p;
  65384. p.addEllipse (x, y, width, height);
  65385. strokePath (p, PathStrokeType (lineThickness));
  65386. }
  65387. void Graphics::fillRoundedRectangle (const float x, const float y, const float width, const float height, const float cornerSize) const
  65388. {
  65389. // passing in a silly number can cause maths problems in rendering!
  65390. jassert (areCoordsSensibleNumbers (x, y, width, height));
  65391. Path p;
  65392. p.addRoundedRectangle (x, y, width, height, cornerSize);
  65393. fillPath (p);
  65394. }
  65395. void Graphics::fillRoundedRectangle (const Rectangle<float>& r, const float cornerSize) const
  65396. {
  65397. fillRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize);
  65398. }
  65399. void Graphics::drawRoundedRectangle (const float x, const float y, const float width, const float height,
  65400. const float cornerSize, const float lineThickness) const
  65401. {
  65402. // passing in a silly number can cause maths problems in rendering!
  65403. jassert (areCoordsSensibleNumbers (x, y, width, height));
  65404. Path p;
  65405. p.addRoundedRectangle (x, y, width, height, cornerSize);
  65406. strokePath (p, PathStrokeType (lineThickness));
  65407. }
  65408. void Graphics::drawRoundedRectangle (const Rectangle<float>& r, const float cornerSize, const float lineThickness) const
  65409. {
  65410. drawRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize, lineThickness);
  65411. }
  65412. void Graphics::drawArrow (const Line<float>& line, const float lineThickness, const float arrowheadWidth, const float arrowheadLength) const
  65413. {
  65414. Path p;
  65415. p.addArrow (line, lineThickness, arrowheadWidth, arrowheadLength);
  65416. fillPath (p);
  65417. }
  65418. void Graphics::fillCheckerBoard (int x, int y, int width, int height,
  65419. const int checkWidth, const int checkHeight,
  65420. const Colour& colour1, const Colour& colour2) const
  65421. {
  65422. jassert (checkWidth > 0 && checkHeight > 0); // can't be zero or less!
  65423. if (checkWidth > 0 && checkHeight > 0)
  65424. {
  65425. context->saveState();
  65426. if (colour1 == colour2)
  65427. {
  65428. context->setFill (colour1);
  65429. context->fillRect (Rectangle<int> (x, y, width, height), false);
  65430. }
  65431. else
  65432. {
  65433. const Rectangle<int> clip (context->getClipBounds());
  65434. const int right = jmin (x + width, clip.getRight());
  65435. const int bottom = jmin (y + height, clip.getBottom());
  65436. int cy = 0;
  65437. while (y < bottom)
  65438. {
  65439. int cx = cy;
  65440. for (int xx = x; xx < right; xx += checkWidth)
  65441. {
  65442. context->setFill (((cx++ & 1) == 0) ? colour1 : colour2);
  65443. context->fillRect (Rectangle<int> (xx, y, jmin (checkWidth, right - xx), jmin (checkHeight, bottom - y)),
  65444. false);
  65445. }
  65446. ++cy;
  65447. y += checkHeight;
  65448. }
  65449. }
  65450. context->restoreState();
  65451. }
  65452. }
  65453. void Graphics::drawVerticalLine (const int x, float top, float bottom) const
  65454. {
  65455. context->drawVerticalLine (x, top, bottom);
  65456. }
  65457. void Graphics::drawHorizontalLine (const int y, float left, float right) const
  65458. {
  65459. context->drawHorizontalLine (y, left, right);
  65460. }
  65461. void Graphics::drawLine (float x1, float y1, float x2, float y2) const
  65462. {
  65463. context->drawLine (Line<float> (x1, y1, x2, y2));
  65464. }
  65465. void Graphics::drawLine (const float startX, const float startY,
  65466. const float endX, const float endY,
  65467. const float lineThickness) const
  65468. {
  65469. drawLine (Line<float> (startX, startY, endX, endY),lineThickness);
  65470. }
  65471. void Graphics::drawLine (const Line<float>& line) const
  65472. {
  65473. drawLine (line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY());
  65474. }
  65475. void Graphics::drawLine (const Line<float>& line, const float lineThickness) const
  65476. {
  65477. Path p;
  65478. p.addLineSegment (line, lineThickness);
  65479. fillPath (p);
  65480. }
  65481. void Graphics::drawDashedLine (const float startX, const float startY,
  65482. const float endX, const float endY,
  65483. const float* const dashLengths,
  65484. const int numDashLengths,
  65485. const float lineThickness) const
  65486. {
  65487. const double dx = endX - startX;
  65488. const double dy = endY - startY;
  65489. const double totalLen = juce_hypot (dx, dy);
  65490. if (totalLen >= 0.5)
  65491. {
  65492. const double onePixAlpha = 1.0 / totalLen;
  65493. double alpha = 0.0;
  65494. float x = startX;
  65495. float y = startY;
  65496. int n = 0;
  65497. while (alpha < 1.0f)
  65498. {
  65499. alpha = jmin (1.0, alpha + dashLengths[n++] * onePixAlpha);
  65500. n = n % numDashLengths;
  65501. const float oldX = x;
  65502. const float oldY = y;
  65503. x = (float) (startX + dx * alpha);
  65504. y = (float) (startY + dy * alpha);
  65505. if ((n & 1) != 0)
  65506. {
  65507. if (lineThickness != 1.0f)
  65508. drawLine (oldX, oldY, x, y, lineThickness);
  65509. else
  65510. drawLine (oldX, oldY, x, y);
  65511. }
  65512. }
  65513. }
  65514. }
  65515. void Graphics::setImageResamplingQuality (const Graphics::ResamplingQuality newQuality)
  65516. {
  65517. saveStateIfPending();
  65518. context->setInterpolationQuality (newQuality);
  65519. }
  65520. void Graphics::drawImageAt (const Image& imageToDraw,
  65521. const int topLeftX, const int topLeftY,
  65522. const bool fillAlphaChannelWithCurrentBrush) const
  65523. {
  65524. const int imageW = imageToDraw.getWidth();
  65525. const int imageH = imageToDraw.getHeight();
  65526. drawImage (imageToDraw,
  65527. topLeftX, topLeftY, imageW, imageH,
  65528. 0, 0, imageW, imageH,
  65529. fillAlphaChannelWithCurrentBrush);
  65530. }
  65531. void Graphics::drawImageWithin (const Image& imageToDraw,
  65532. const int destX, const int destY,
  65533. const int destW, const int destH,
  65534. const RectanglePlacement& placementWithinTarget,
  65535. const bool fillAlphaChannelWithCurrentBrush) const
  65536. {
  65537. // passing in a silly number can cause maths problems in rendering!
  65538. jassert (areCoordsSensibleNumbers (destX, destY, destW, destH));
  65539. if (imageToDraw.isValid())
  65540. {
  65541. const int imageW = imageToDraw.getWidth();
  65542. const int imageH = imageToDraw.getHeight();
  65543. if (imageW > 0 && imageH > 0)
  65544. {
  65545. double newX = 0.0, newY = 0.0;
  65546. double newW = imageW;
  65547. double newH = imageH;
  65548. placementWithinTarget.applyTo (newX, newY, newW, newH,
  65549. destX, destY, destW, destH);
  65550. if (newW > 0 && newH > 0)
  65551. {
  65552. drawImage (imageToDraw,
  65553. roundToInt (newX), roundToInt (newY),
  65554. roundToInt (newW), roundToInt (newH),
  65555. 0, 0, imageW, imageH,
  65556. fillAlphaChannelWithCurrentBrush);
  65557. }
  65558. }
  65559. }
  65560. }
  65561. void Graphics::drawImage (const Image& imageToDraw,
  65562. int dx, int dy, int dw, int dh,
  65563. int sx, int sy, int sw, int sh,
  65564. const bool fillAlphaChannelWithCurrentBrush) const
  65565. {
  65566. // passing in a silly number can cause maths problems in rendering!
  65567. jassert (areCoordsSensibleNumbers (dx, dy, dw, dh));
  65568. jassert (areCoordsSensibleNumbers (sx, sy, sw, sh));
  65569. if (imageToDraw.isValid() && context->clipRegionIntersects (Rectangle<int> (dx, dy, dw, dh)))
  65570. {
  65571. drawImageTransformed (imageToDraw, Rectangle<int> (sx, sy, sw, sh),
  65572. AffineTransform::scale (dw / (float) sw, dh / (float) sh)
  65573. .translated ((float) dx, (float) dy),
  65574. fillAlphaChannelWithCurrentBrush);
  65575. }
  65576. }
  65577. void Graphics::drawImageTransformed (const Image& imageToDraw,
  65578. const Rectangle<int>& imageSubRegion,
  65579. const AffineTransform& transform,
  65580. const bool fillAlphaChannelWithCurrentBrush) const
  65581. {
  65582. if (imageToDraw.isValid() && ! context->isClipEmpty())
  65583. {
  65584. const Rectangle<int> srcClip (imageSubRegion.getIntersection (imageToDraw.getBounds()));
  65585. if (fillAlphaChannelWithCurrentBrush)
  65586. {
  65587. context->saveState();
  65588. context->clipToImageAlpha (imageToDraw, srcClip, transform);
  65589. fillAll();
  65590. context->restoreState();
  65591. }
  65592. else
  65593. {
  65594. context->drawImage (imageToDraw, srcClip, transform, false);
  65595. }
  65596. }
  65597. }
  65598. END_JUCE_NAMESPACE
  65599. /*** End of inlined file: juce_Graphics.cpp ***/
  65600. /*** Start of inlined file: juce_Justification.cpp ***/
  65601. BEGIN_JUCE_NAMESPACE
  65602. Justification::Justification (const Justification& other) throw()
  65603. : flags (other.flags)
  65604. {
  65605. }
  65606. Justification& Justification::operator= (const Justification& other) throw()
  65607. {
  65608. flags = other.flags;
  65609. return *this;
  65610. }
  65611. int Justification::getOnlyVerticalFlags() const throw()
  65612. {
  65613. return flags & (top | bottom | verticallyCentred);
  65614. }
  65615. int Justification::getOnlyHorizontalFlags() const throw()
  65616. {
  65617. return flags & (left | right | horizontallyCentred | horizontallyJustified);
  65618. }
  65619. void Justification::applyToRectangle (int& x, int& y,
  65620. const int w, const int h,
  65621. const int spaceX, const int spaceY,
  65622. const int spaceW, const int spaceH) const throw()
  65623. {
  65624. if ((flags & horizontallyCentred) != 0)
  65625. x = spaceX + ((spaceW - w) >> 1);
  65626. else if ((flags & right) != 0)
  65627. x = spaceX + spaceW - w;
  65628. else
  65629. x = spaceX;
  65630. if ((flags & verticallyCentred) != 0)
  65631. y = spaceY + ((spaceH - h) >> 1);
  65632. else if ((flags & bottom) != 0)
  65633. y = spaceY + spaceH - h;
  65634. else
  65635. y = spaceY;
  65636. }
  65637. END_JUCE_NAMESPACE
  65638. /*** End of inlined file: juce_Justification.cpp ***/
  65639. /*** Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  65640. BEGIN_JUCE_NAMESPACE
  65641. // this will throw an assertion if you try to draw something that's not
  65642. // possible in postscript
  65643. #define WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS 0
  65644. #if JUCE_DEBUG && WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS
  65645. #define notPossibleInPostscriptAssert jassertfalse
  65646. #else
  65647. #define notPossibleInPostscriptAssert
  65648. #endif
  65649. LowLevelGraphicsPostScriptRenderer::LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  65650. const String& documentTitle,
  65651. const int totalWidth_,
  65652. const int totalHeight_)
  65653. : out (resultingPostScript),
  65654. totalWidth (totalWidth_),
  65655. totalHeight (totalHeight_),
  65656. needToClip (true)
  65657. {
  65658. stateStack.add (new SavedState());
  65659. stateStack.getLast()->clip = Rectangle<int> (0, 0, totalWidth_, totalHeight_);
  65660. const float scale = jmin ((520.0f / totalWidth_), (750.0f / totalHeight));
  65661. out << "%!PS-Adobe-3.0 EPSF-3.0"
  65662. "\n%%BoundingBox: 0 0 600 824"
  65663. "\n%%Pages: 0"
  65664. "\n%%Creator: Raw Material Software JUCE"
  65665. "\n%%Title: " << documentTitle <<
  65666. "\n%%CreationDate: none"
  65667. "\n%%LanguageLevel: 2"
  65668. "\n%%EndComments"
  65669. "\n%%BeginProlog"
  65670. "\n%%BeginResource: JRes"
  65671. "\n/bd {bind def} bind def"
  65672. "\n/c {setrgbcolor} bd"
  65673. "\n/m {moveto} bd"
  65674. "\n/l {lineto} bd"
  65675. "\n/rl {rlineto} bd"
  65676. "\n/ct {curveto} bd"
  65677. "\n/cp {closepath} bd"
  65678. "\n/pr {3 index 3 index moveto 1 index 0 rlineto 0 1 index rlineto pop neg 0 rlineto pop pop closepath} bd"
  65679. "\n/doclip {initclip newpath} bd"
  65680. "\n/endclip {clip newpath} bd"
  65681. "\n%%EndResource"
  65682. "\n%%EndProlog"
  65683. "\n%%BeginSetup"
  65684. "\n%%EndSetup"
  65685. "\n%%Page: 1 1"
  65686. "\n%%BeginPageSetup"
  65687. "\n%%EndPageSetup\n\n"
  65688. << "40 800 translate\n"
  65689. << scale << ' ' << scale << " scale\n\n";
  65690. }
  65691. LowLevelGraphicsPostScriptRenderer::~LowLevelGraphicsPostScriptRenderer()
  65692. {
  65693. }
  65694. bool LowLevelGraphicsPostScriptRenderer::isVectorDevice() const
  65695. {
  65696. return true;
  65697. }
  65698. void LowLevelGraphicsPostScriptRenderer::setOrigin (int x, int y)
  65699. {
  65700. if (x != 0 || y != 0)
  65701. {
  65702. stateStack.getLast()->xOffset += x;
  65703. stateStack.getLast()->yOffset += y;
  65704. needToClip = true;
  65705. }
  65706. }
  65707. bool LowLevelGraphicsPostScriptRenderer::clipToRectangle (const Rectangle<int>& r)
  65708. {
  65709. needToClip = true;
  65710. return stateStack.getLast()->clip.clipTo (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  65711. }
  65712. bool LowLevelGraphicsPostScriptRenderer::clipToRectangleList (const RectangleList& clipRegion)
  65713. {
  65714. needToClip = true;
  65715. return stateStack.getLast()->clip.clipTo (clipRegion);
  65716. }
  65717. void LowLevelGraphicsPostScriptRenderer::excludeClipRectangle (const Rectangle<int>& r)
  65718. {
  65719. needToClip = true;
  65720. stateStack.getLast()->clip.subtract (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  65721. }
  65722. void LowLevelGraphicsPostScriptRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  65723. {
  65724. writeClip();
  65725. Path p (path);
  65726. p.applyTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  65727. writePath (p);
  65728. out << "clip\n";
  65729. }
  65730. void LowLevelGraphicsPostScriptRenderer::clipToImageAlpha (const Image& /*sourceImage*/, const Rectangle<int>& /*srcClip*/, const AffineTransform& /*transform*/)
  65731. {
  65732. needToClip = true;
  65733. jassertfalse; // xxx
  65734. }
  65735. bool LowLevelGraphicsPostScriptRenderer::clipRegionIntersects (const Rectangle<int>& r)
  65736. {
  65737. return stateStack.getLast()->clip.intersectsRectangle (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  65738. }
  65739. const Rectangle<int> LowLevelGraphicsPostScriptRenderer::getClipBounds() const
  65740. {
  65741. return stateStack.getLast()->clip.getBounds().translated (-stateStack.getLast()->xOffset,
  65742. -stateStack.getLast()->yOffset);
  65743. }
  65744. bool LowLevelGraphicsPostScriptRenderer::isClipEmpty() const
  65745. {
  65746. return stateStack.getLast()->clip.isEmpty();
  65747. }
  65748. LowLevelGraphicsPostScriptRenderer::SavedState::SavedState()
  65749. : xOffset (0),
  65750. yOffset (0)
  65751. {
  65752. }
  65753. LowLevelGraphicsPostScriptRenderer::SavedState::~SavedState()
  65754. {
  65755. }
  65756. void LowLevelGraphicsPostScriptRenderer::saveState()
  65757. {
  65758. stateStack.add (new SavedState (*stateStack.getLast()));
  65759. }
  65760. void LowLevelGraphicsPostScriptRenderer::restoreState()
  65761. {
  65762. jassert (stateStack.size() > 0);
  65763. if (stateStack.size() > 0)
  65764. stateStack.removeLast();
  65765. }
  65766. void LowLevelGraphicsPostScriptRenderer::writeClip()
  65767. {
  65768. if (needToClip)
  65769. {
  65770. needToClip = false;
  65771. out << "doclip ";
  65772. int itemsOnLine = 0;
  65773. for (RectangleList::Iterator i (stateStack.getLast()->clip); i.next();)
  65774. {
  65775. if (++itemsOnLine == 6)
  65776. {
  65777. itemsOnLine = 0;
  65778. out << '\n';
  65779. }
  65780. const Rectangle<int>& r = *i.getRectangle();
  65781. out << r.getX() << ' ' << -r.getY() << ' '
  65782. << r.getWidth() << ' ' << -r.getHeight() << " pr ";
  65783. }
  65784. out << "endclip\n";
  65785. }
  65786. }
  65787. void LowLevelGraphicsPostScriptRenderer::writeColour (const Colour& colour)
  65788. {
  65789. Colour c (Colours::white.overlaidWith (colour));
  65790. if (lastColour != c)
  65791. {
  65792. lastColour = c;
  65793. out << String (c.getFloatRed(), 3) << ' '
  65794. << String (c.getFloatGreen(), 3) << ' '
  65795. << String (c.getFloatBlue(), 3) << " c\n";
  65796. }
  65797. }
  65798. void LowLevelGraphicsPostScriptRenderer::writeXY (const float x, const float y) const
  65799. {
  65800. out << String (x, 2) << ' '
  65801. << String (-y, 2) << ' ';
  65802. }
  65803. void LowLevelGraphicsPostScriptRenderer::writePath (const Path& path) const
  65804. {
  65805. out << "newpath ";
  65806. float lastX = 0.0f;
  65807. float lastY = 0.0f;
  65808. int itemsOnLine = 0;
  65809. Path::Iterator i (path);
  65810. while (i.next())
  65811. {
  65812. if (++itemsOnLine == 4)
  65813. {
  65814. itemsOnLine = 0;
  65815. out << '\n';
  65816. }
  65817. switch (i.elementType)
  65818. {
  65819. case Path::Iterator::startNewSubPath:
  65820. writeXY (i.x1, i.y1);
  65821. lastX = i.x1;
  65822. lastY = i.y1;
  65823. out << "m ";
  65824. break;
  65825. case Path::Iterator::lineTo:
  65826. writeXY (i.x1, i.y1);
  65827. lastX = i.x1;
  65828. lastY = i.y1;
  65829. out << "l ";
  65830. break;
  65831. case Path::Iterator::quadraticTo:
  65832. {
  65833. const float cp1x = lastX + (i.x1 - lastX) * 2.0f / 3.0f;
  65834. const float cp1y = lastY + (i.y1 - lastY) * 2.0f / 3.0f;
  65835. const float cp2x = cp1x + (i.x2 - lastX) / 3.0f;
  65836. const float cp2y = cp1y + (i.y2 - lastY) / 3.0f;
  65837. writeXY (cp1x, cp1y);
  65838. writeXY (cp2x, cp2y);
  65839. writeXY (i.x2, i.y2);
  65840. out << "ct ";
  65841. lastX = i.x2;
  65842. lastY = i.y2;
  65843. }
  65844. break;
  65845. case Path::Iterator::cubicTo:
  65846. writeXY (i.x1, i.y1);
  65847. writeXY (i.x2, i.y2);
  65848. writeXY (i.x3, i.y3);
  65849. out << "ct ";
  65850. lastX = i.x3;
  65851. lastY = i.y3;
  65852. break;
  65853. case Path::Iterator::closePath:
  65854. out << "cp ";
  65855. break;
  65856. default:
  65857. jassertfalse;
  65858. break;
  65859. }
  65860. }
  65861. out << '\n';
  65862. }
  65863. void LowLevelGraphicsPostScriptRenderer::writeTransform (const AffineTransform& trans) const
  65864. {
  65865. out << "[ "
  65866. << trans.mat00 << ' '
  65867. << trans.mat10 << ' '
  65868. << trans.mat01 << ' '
  65869. << trans.mat11 << ' '
  65870. << trans.mat02 << ' '
  65871. << trans.mat12 << " ] concat ";
  65872. }
  65873. void LowLevelGraphicsPostScriptRenderer::setFill (const FillType& fillType)
  65874. {
  65875. stateStack.getLast()->fillType = fillType;
  65876. }
  65877. void LowLevelGraphicsPostScriptRenderer::setOpacity (float /*opacity*/)
  65878. {
  65879. }
  65880. void LowLevelGraphicsPostScriptRenderer::setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  65881. {
  65882. }
  65883. void LowLevelGraphicsPostScriptRenderer::fillRect (const Rectangle<int>& r, const bool /*replaceExistingContents*/)
  65884. {
  65885. if (stateStack.getLast()->fillType.isColour())
  65886. {
  65887. writeClip();
  65888. writeColour (stateStack.getLast()->fillType.colour);
  65889. Rectangle<int> r2 (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  65890. out << r2.getX() << ' ' << -r2.getBottom() << ' ' << r2.getWidth() << ' ' << r2.getHeight() << " rectfill\n";
  65891. }
  65892. else
  65893. {
  65894. Path p;
  65895. p.addRectangle (r);
  65896. fillPath (p, AffineTransform::identity);
  65897. }
  65898. }
  65899. void LowLevelGraphicsPostScriptRenderer::fillPath (const Path& path, const AffineTransform& t)
  65900. {
  65901. if (stateStack.getLast()->fillType.isColour())
  65902. {
  65903. writeClip();
  65904. Path p (path);
  65905. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset,
  65906. (float) stateStack.getLast()->yOffset));
  65907. writePath (p);
  65908. writeColour (stateStack.getLast()->fillType.colour);
  65909. out << "fill\n";
  65910. }
  65911. else if (stateStack.getLast()->fillType.isGradient())
  65912. {
  65913. // this doesn't work correctly yet - it could be improved to handle solid gradients, but
  65914. // postscript can't do semi-transparent ones.
  65915. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  65916. writeClip();
  65917. out << "gsave ";
  65918. {
  65919. Path p (path);
  65920. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  65921. writePath (p);
  65922. out << "clip\n";
  65923. }
  65924. const Rectangle<int> bounds (stateStack.getLast()->clip.getBounds());
  65925. // ideally this would draw lots of lines or ellipses to approximate the gradient, but for the
  65926. // time-being, this just fills it with the average colour..
  65927. writeColour (stateStack.getLast()->fillType.gradient->getColourAtPosition (0.5f));
  65928. out << bounds.getX() << ' ' << -bounds.getBottom() << ' ' << bounds.getWidth() << ' ' << bounds.getHeight() << " rectfill\n";
  65929. out << "grestore\n";
  65930. }
  65931. }
  65932. void LowLevelGraphicsPostScriptRenderer::writeImage (const Image& im,
  65933. const int sx, const int sy,
  65934. const int maxW, const int maxH) const
  65935. {
  65936. out << "{<\n";
  65937. const int w = jmin (maxW, im.getWidth());
  65938. const int h = jmin (maxH, im.getHeight());
  65939. int charsOnLine = 0;
  65940. const Image::BitmapData srcData (im, 0, 0, w, h);
  65941. Colour pixel;
  65942. for (int y = h; --y >= 0;)
  65943. {
  65944. for (int x = 0; x < w; ++x)
  65945. {
  65946. const uint8* pixelData = srcData.getPixelPointer (x, y);
  65947. if (x >= sx && y >= sy)
  65948. {
  65949. if (im.isARGB())
  65950. {
  65951. PixelARGB p (*(const PixelARGB*) pixelData);
  65952. p.unpremultiply();
  65953. pixel = Colours::white.overlaidWith (Colour (p.getARGB()));
  65954. }
  65955. else if (im.isRGB())
  65956. {
  65957. pixel = Colour (((const PixelRGB*) pixelData)->getARGB());
  65958. }
  65959. else
  65960. {
  65961. pixel = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixelData);
  65962. }
  65963. }
  65964. else
  65965. {
  65966. pixel = Colours::transparentWhite;
  65967. }
  65968. const uint8 pixelValues[3] = { pixel.getRed(), pixel.getGreen(), pixel.getBlue() };
  65969. out << String::toHexString (pixelValues, 3, 0);
  65970. charsOnLine += 3;
  65971. if (charsOnLine > 100)
  65972. {
  65973. out << '\n';
  65974. charsOnLine = 0;
  65975. }
  65976. }
  65977. }
  65978. out << "\n>}\n";
  65979. }
  65980. void LowLevelGraphicsPostScriptRenderer::drawImage (const Image& sourceImage, const Rectangle<int>& srcClip,
  65981. const AffineTransform& transform, const bool /*fillEntireClipAsTiles*/)
  65982. {
  65983. const int w = jmin (sourceImage.getWidth(), srcClip.getRight());
  65984. const int h = jmin (sourceImage.getHeight(), srcClip.getBottom());
  65985. writeClip();
  65986. out << "gsave ";
  65987. writeTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset)
  65988. .scaled (1.0f, -1.0f));
  65989. RectangleList imageClip;
  65990. sourceImage.createSolidAreaMask (imageClip, 0.5f);
  65991. imageClip.clipTo (srcClip);
  65992. out << "newpath ";
  65993. int itemsOnLine = 0;
  65994. for (RectangleList::Iterator i (imageClip); i.next();)
  65995. {
  65996. if (++itemsOnLine == 6)
  65997. {
  65998. out << '\n';
  65999. itemsOnLine = 0;
  66000. }
  66001. const Rectangle<int>& r = *i.getRectangle();
  66002. out << r.getX() << ' ' << r.getY() << ' ' << r.getWidth() << ' ' << r.getHeight() << " pr ";
  66003. }
  66004. out << " clip newpath\n";
  66005. out << w << ' ' << h << " scale\n";
  66006. out << w << ' ' << h << " 8 [" << w << " 0 0 -" << h << ' ' << (int) 0 << ' ' << h << " ]\n";
  66007. writeImage (sourceImage, srcClip.getX(), srcClip.getY(), srcClip.getWidth(), srcClip.getHeight());
  66008. out << "false 3 colorimage grestore\n";
  66009. needToClip = true;
  66010. }
  66011. void LowLevelGraphicsPostScriptRenderer::drawLine (const Line <float>& line)
  66012. {
  66013. Path p;
  66014. p.addLineSegment (line, 1.0f);
  66015. fillPath (p, AffineTransform::identity);
  66016. }
  66017. void LowLevelGraphicsPostScriptRenderer::drawVerticalLine (const int x, float top, float bottom)
  66018. {
  66019. drawLine (Line<float> ((float) x, top, (float) x, bottom));
  66020. }
  66021. void LowLevelGraphicsPostScriptRenderer::drawHorizontalLine (const int y, float left, float right)
  66022. {
  66023. drawLine (Line<float> (left, (float) y, right, (float) y));
  66024. }
  66025. void LowLevelGraphicsPostScriptRenderer::setFont (const Font& newFont)
  66026. {
  66027. stateStack.getLast()->font = newFont;
  66028. }
  66029. const Font LowLevelGraphicsPostScriptRenderer::getFont()
  66030. {
  66031. return stateStack.getLast()->font;
  66032. }
  66033. void LowLevelGraphicsPostScriptRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  66034. {
  66035. Path p;
  66036. Font& font = stateStack.getLast()->font;
  66037. font.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  66038. fillPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight()).followedBy (transform));
  66039. }
  66040. END_JUCE_NAMESPACE
  66041. /*** End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  66042. /*** Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  66043. BEGIN_JUCE_NAMESPACE
  66044. #if (JUCE_WINDOWS || JUCE_LINUX) && ! JUCE_64BIT
  66045. #define JUCE_USE_SSE_INSTRUCTIONS 1
  66046. #endif
  66047. #if JUCE_MSVC
  66048. #pragma warning (push)
  66049. #pragma warning (disable: 4127) // "expression is constant" warning
  66050. #if JUCE_DEBUG
  66051. #pragma optimize ("t", on) // optimise just this file, to avoid sluggish graphics when debugging
  66052. #pragma warning (disable: 4714) // warning about forcedinline methods not being inlined
  66053. #endif
  66054. #endif
  66055. namespace SoftwareRendererClasses
  66056. {
  66057. template <class PixelType, bool replaceExisting = false>
  66058. class SolidColourEdgeTableRenderer
  66059. {
  66060. public:
  66061. SolidColourEdgeTableRenderer (const Image::BitmapData& data_, const PixelARGB& colour)
  66062. : data (data_),
  66063. sourceColour (colour)
  66064. {
  66065. if (sizeof (PixelType) == 3)
  66066. {
  66067. areRGBComponentsEqual = sourceColour.getRed() == sourceColour.getGreen()
  66068. && sourceColour.getGreen() == sourceColour.getBlue();
  66069. filler[0].set (sourceColour);
  66070. filler[1].set (sourceColour);
  66071. filler[2].set (sourceColour);
  66072. filler[3].set (sourceColour);
  66073. }
  66074. }
  66075. forcedinline void setEdgeTableYPos (const int y) throw()
  66076. {
  66077. linePixels = (PixelType*) data.getLinePointer (y);
  66078. }
  66079. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  66080. {
  66081. if (replaceExisting)
  66082. linePixels[x].set (sourceColour);
  66083. else
  66084. linePixels[x].blend (sourceColour, alphaLevel);
  66085. }
  66086. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  66087. {
  66088. if (replaceExisting)
  66089. linePixels[x].set (sourceColour);
  66090. else
  66091. linePixels[x].blend (sourceColour);
  66092. }
  66093. forcedinline void handleEdgeTableLine (const int x, const int width, const int alphaLevel) const throw()
  66094. {
  66095. PixelARGB p (sourceColour);
  66096. p.multiplyAlpha (alphaLevel);
  66097. PixelType* dest = linePixels + x;
  66098. if (replaceExisting || p.getAlpha() >= 0xff)
  66099. replaceLine (dest, p, width);
  66100. else
  66101. blendLine (dest, p, width);
  66102. }
  66103. forcedinline void handleEdgeTableLineFull (const int x, const int width) const throw()
  66104. {
  66105. PixelType* dest = linePixels + x;
  66106. if (replaceExisting || sourceColour.getAlpha() >= 0xff)
  66107. replaceLine (dest, sourceColour, width);
  66108. else
  66109. blendLine (dest, sourceColour, width);
  66110. }
  66111. private:
  66112. const Image::BitmapData& data;
  66113. PixelType* linePixels;
  66114. PixelARGB sourceColour;
  66115. PixelRGB filler [4];
  66116. bool areRGBComponentsEqual;
  66117. inline void blendLine (PixelType* dest, const PixelARGB& colour, int width) const throw()
  66118. {
  66119. do
  66120. {
  66121. dest->blend (colour);
  66122. ++dest;
  66123. } while (--width > 0);
  66124. }
  66125. forcedinline void replaceLine (PixelRGB* dest, const PixelARGB& colour, int width) const throw()
  66126. {
  66127. if (areRGBComponentsEqual) // if all the component values are the same, we can cheat..
  66128. {
  66129. memset (dest, colour.getRed(), width * 3);
  66130. }
  66131. else
  66132. {
  66133. if (width >> 5)
  66134. {
  66135. const int* const intFiller = (const int*) filler;
  66136. while (width > 8 && (((pointer_sized_int) dest) & 7) != 0)
  66137. {
  66138. dest->set (colour);
  66139. ++dest;
  66140. --width;
  66141. }
  66142. while (width > 4)
  66143. {
  66144. ((int*) dest) [0] = intFiller[0];
  66145. ((int*) dest) [1] = intFiller[1];
  66146. ((int*) dest) [2] = intFiller[2];
  66147. dest = (PixelRGB*) (((uint8*) dest) + 12);
  66148. width -= 4;
  66149. }
  66150. }
  66151. while (--width >= 0)
  66152. {
  66153. dest->set (colour);
  66154. ++dest;
  66155. }
  66156. }
  66157. }
  66158. forcedinline void replaceLine (PixelAlpha* const dest, const PixelARGB& colour, int const width) const throw()
  66159. {
  66160. memset (dest, colour.getAlpha(), width);
  66161. }
  66162. forcedinline void replaceLine (PixelARGB* dest, const PixelARGB& colour, int width) const throw()
  66163. {
  66164. do
  66165. {
  66166. dest->set (colour);
  66167. ++dest;
  66168. } while (--width > 0);
  66169. }
  66170. SolidColourEdgeTableRenderer (const SolidColourEdgeTableRenderer&);
  66171. SolidColourEdgeTableRenderer& operator= (const SolidColourEdgeTableRenderer&);
  66172. };
  66173. class LinearGradientPixelGenerator
  66174. {
  66175. public:
  66176. LinearGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform, const PixelARGB* const lookupTable_, const int numEntries_)
  66177. : lookupTable (lookupTable_), numEntries (numEntries_)
  66178. {
  66179. jassert (numEntries_ >= 0);
  66180. Point<float> p1 (gradient.point1);
  66181. Point<float> p2 (gradient.point2);
  66182. if (! transform.isIdentity())
  66183. {
  66184. const Line<float> l (p2, p1);
  66185. Point<float> p3 = l.getPointAlongLine (0.0f, 100.0f);
  66186. p1.applyTransform (transform);
  66187. p2.applyTransform (transform);
  66188. p3.applyTransform (transform);
  66189. p2 = Line<float> (p2, p3).findNearestPointTo (p1);
  66190. }
  66191. vertical = std::abs (p1.getX() - p2.getX()) < 0.001f;
  66192. horizontal = std::abs (p1.getY() - p2.getY()) < 0.001f;
  66193. if (vertical)
  66194. {
  66195. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getY() - p1.getY()));
  66196. start = roundToInt (p1.getY() * scale);
  66197. }
  66198. else if (horizontal)
  66199. {
  66200. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getX() - p1.getX()));
  66201. start = roundToInt (p1.getX() * scale);
  66202. }
  66203. else
  66204. {
  66205. grad = (p2.getY() - p1.getY()) / (double) (p1.getX() - p2.getX());
  66206. yTerm = p1.getY() - p1.getX() / grad;
  66207. scale = roundToInt ((numEntries << (int) numScaleBits) / (yTerm * grad - (p2.getY() * grad - p2.getX())));
  66208. grad *= scale;
  66209. }
  66210. }
  66211. forcedinline void setY (const int y) throw()
  66212. {
  66213. if (vertical)
  66214. linePix = lookupTable [jlimit (0, numEntries, (y * scale - start) >> (int) numScaleBits)];
  66215. else if (! horizontal)
  66216. start = roundToInt ((y - yTerm) * grad);
  66217. }
  66218. inline const PixelARGB getPixel (const int x) const throw()
  66219. {
  66220. return vertical ? linePix
  66221. : lookupTable [jlimit (0, numEntries, (x * scale - start) >> (int) numScaleBits)];
  66222. }
  66223. private:
  66224. const PixelARGB* const lookupTable;
  66225. const int numEntries;
  66226. PixelARGB linePix;
  66227. int start, scale;
  66228. double grad, yTerm;
  66229. bool vertical, horizontal;
  66230. enum { numScaleBits = 12 };
  66231. LinearGradientPixelGenerator (const LinearGradientPixelGenerator&);
  66232. LinearGradientPixelGenerator& operator= (const LinearGradientPixelGenerator&);
  66233. };
  66234. class RadialGradientPixelGenerator
  66235. {
  66236. public:
  66237. RadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform&,
  66238. const PixelARGB* const lookupTable_, const int numEntries_)
  66239. : lookupTable (lookupTable_),
  66240. numEntries (numEntries_),
  66241. gx1 (gradient.point1.getX()),
  66242. gy1 (gradient.point1.getY())
  66243. {
  66244. jassert (numEntries_ >= 0);
  66245. const Point<float> diff (gradient.point1 - gradient.point2);
  66246. maxDist = diff.getX() * diff.getX() + diff.getY() * diff.getY();
  66247. invScale = numEntries / std::sqrt (maxDist);
  66248. jassert (roundToInt (std::sqrt (maxDist) * invScale) <= numEntries);
  66249. }
  66250. forcedinline void setY (const int y) throw()
  66251. {
  66252. dy = y - gy1;
  66253. dy *= dy;
  66254. }
  66255. inline const PixelARGB getPixel (const int px) const throw()
  66256. {
  66257. double x = px - gx1;
  66258. x *= x;
  66259. x += dy;
  66260. return lookupTable [x >= maxDist ? numEntries : roundToInt (std::sqrt (x) * invScale)];
  66261. }
  66262. protected:
  66263. const PixelARGB* const lookupTable;
  66264. const int numEntries;
  66265. const double gx1, gy1;
  66266. double maxDist, invScale, dy;
  66267. RadialGradientPixelGenerator (const RadialGradientPixelGenerator&);
  66268. RadialGradientPixelGenerator& operator= (const RadialGradientPixelGenerator&);
  66269. };
  66270. class TransformedRadialGradientPixelGenerator : public RadialGradientPixelGenerator
  66271. {
  66272. public:
  66273. TransformedRadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform,
  66274. const PixelARGB* const lookupTable_, const int numEntries_)
  66275. : RadialGradientPixelGenerator (gradient, transform, lookupTable_, numEntries_),
  66276. inverseTransform (transform.inverted())
  66277. {
  66278. tM10 = inverseTransform.mat10;
  66279. tM00 = inverseTransform.mat00;
  66280. }
  66281. forcedinline void setY (const int y) throw()
  66282. {
  66283. lineYM01 = inverseTransform.mat01 * y + inverseTransform.mat02 - gx1;
  66284. lineYM11 = inverseTransform.mat11 * y + inverseTransform.mat12 - gy1;
  66285. }
  66286. inline const PixelARGB getPixel (const int px) const throw()
  66287. {
  66288. double x = px;
  66289. const double y = tM10 * x + lineYM11;
  66290. x = tM00 * x + lineYM01;
  66291. x *= x;
  66292. x += y * y;
  66293. if (x >= maxDist)
  66294. return lookupTable [numEntries];
  66295. else
  66296. return lookupTable [jmin (numEntries, roundToInt (std::sqrt (x) * invScale))];
  66297. }
  66298. private:
  66299. double tM10, tM00, lineYM01, lineYM11;
  66300. const AffineTransform inverseTransform;
  66301. TransformedRadialGradientPixelGenerator (const TransformedRadialGradientPixelGenerator&);
  66302. TransformedRadialGradientPixelGenerator& operator= (const TransformedRadialGradientPixelGenerator&);
  66303. };
  66304. template <class PixelType, class GradientType>
  66305. class GradientEdgeTableRenderer : public GradientType
  66306. {
  66307. public:
  66308. GradientEdgeTableRenderer (const Image::BitmapData& destData_, const ColourGradient& gradient, const AffineTransform& transform,
  66309. const PixelARGB* const lookupTable_, const int numEntries_)
  66310. : GradientType (gradient, transform, lookupTable_, numEntries_ - 1),
  66311. destData (destData_)
  66312. {
  66313. }
  66314. forcedinline void setEdgeTableYPos (const int y) throw()
  66315. {
  66316. linePixels = (PixelType*) destData.getLinePointer (y);
  66317. GradientType::setY (y);
  66318. }
  66319. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  66320. {
  66321. linePixels[x].blend (GradientType::getPixel (x), alphaLevel);
  66322. }
  66323. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  66324. {
  66325. linePixels[x].blend (GradientType::getPixel (x));
  66326. }
  66327. void handleEdgeTableLine (int x, int width, const int alphaLevel) const throw()
  66328. {
  66329. PixelType* dest = linePixels + x;
  66330. if (alphaLevel < 0xff)
  66331. {
  66332. do
  66333. {
  66334. (dest++)->blend (GradientType::getPixel (x++), alphaLevel);
  66335. } while (--width > 0);
  66336. }
  66337. else
  66338. {
  66339. do
  66340. {
  66341. (dest++)->blend (GradientType::getPixel (x++));
  66342. } while (--width > 0);
  66343. }
  66344. }
  66345. void handleEdgeTableLineFull (int x, int width) const throw()
  66346. {
  66347. PixelType* dest = linePixels + x;
  66348. do
  66349. {
  66350. (dest++)->blend (GradientType::getPixel (x++));
  66351. } while (--width > 0);
  66352. }
  66353. private:
  66354. const Image::BitmapData& destData;
  66355. PixelType* linePixels;
  66356. GradientEdgeTableRenderer (const GradientEdgeTableRenderer&);
  66357. GradientEdgeTableRenderer& operator= (const GradientEdgeTableRenderer&);
  66358. };
  66359. static forcedinline int safeModulo (int n, const int divisor) throw()
  66360. {
  66361. jassert (divisor > 0);
  66362. n %= divisor;
  66363. return (n < 0) ? (n + divisor) : n;
  66364. }
  66365. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  66366. class ImageFillEdgeTableRenderer
  66367. {
  66368. public:
  66369. ImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  66370. const Image::BitmapData& srcData_,
  66371. const int extraAlpha_,
  66372. const int x, const int y)
  66373. : destData (destData_),
  66374. srcData (srcData_),
  66375. extraAlpha (extraAlpha_ + 1),
  66376. xOffset (repeatPattern ? safeModulo (x, srcData_.width) - srcData_.width : x),
  66377. yOffset (repeatPattern ? safeModulo (y, srcData_.height) - srcData_.height : y)
  66378. {
  66379. }
  66380. forcedinline void setEdgeTableYPos (int y) throw()
  66381. {
  66382. linePixels = (DestPixelType*) destData.getLinePointer (y);
  66383. y -= yOffset;
  66384. if (repeatPattern)
  66385. {
  66386. jassert (y >= 0);
  66387. y %= srcData.height;
  66388. }
  66389. sourceLineStart = (SrcPixelType*) srcData.getLinePointer (y);
  66390. }
  66391. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) const throw()
  66392. {
  66393. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  66394. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], alphaLevel);
  66395. }
  66396. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  66397. {
  66398. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], extraAlpha);
  66399. }
  66400. void handleEdgeTableLine (int x, int width, int alphaLevel) const throw()
  66401. {
  66402. DestPixelType* dest = linePixels + x;
  66403. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  66404. x -= xOffset;
  66405. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  66406. if (alphaLevel < 0xfe)
  66407. {
  66408. do
  66409. {
  66410. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], alphaLevel);
  66411. } while (--width > 0);
  66412. }
  66413. else
  66414. {
  66415. if (repeatPattern)
  66416. {
  66417. do
  66418. {
  66419. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  66420. } while (--width > 0);
  66421. }
  66422. else
  66423. {
  66424. copyRow (dest, sourceLineStart + x, width);
  66425. }
  66426. }
  66427. }
  66428. void handleEdgeTableLineFull (int x, int width) const throw()
  66429. {
  66430. DestPixelType* dest = linePixels + x;
  66431. x -= xOffset;
  66432. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  66433. if (extraAlpha < 0xfe)
  66434. {
  66435. do
  66436. {
  66437. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], extraAlpha);
  66438. } while (--width > 0);
  66439. }
  66440. else
  66441. {
  66442. if (repeatPattern)
  66443. {
  66444. do
  66445. {
  66446. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  66447. } while (--width > 0);
  66448. }
  66449. else
  66450. {
  66451. copyRow (dest, sourceLineStart + x, width);
  66452. }
  66453. }
  66454. }
  66455. void clipEdgeTableLine (EdgeTable& et, int x, int y, int width)
  66456. {
  66457. jassert (x - xOffset >= 0 && x + width - xOffset <= srcData.width);
  66458. SrcPixelType* s = (SrcPixelType*) srcData.getLinePointer (y - yOffset);
  66459. uint8* mask = (uint8*) (s + x - xOffset);
  66460. if (sizeof (SrcPixelType) == sizeof (PixelARGB))
  66461. mask += PixelARGB::indexA;
  66462. et.clipLineToMask (x, y, mask, sizeof (SrcPixelType), width);
  66463. }
  66464. private:
  66465. const Image::BitmapData& destData;
  66466. const Image::BitmapData& srcData;
  66467. const int extraAlpha, xOffset, yOffset;
  66468. DestPixelType* linePixels;
  66469. SrcPixelType* sourceLineStart;
  66470. template <class PixelType1, class PixelType2>
  66471. forcedinline static void copyRow (PixelType1* dest, PixelType2* src, int width) throw()
  66472. {
  66473. do
  66474. {
  66475. dest++ ->blend (*src++);
  66476. } while (--width > 0);
  66477. }
  66478. forcedinline static void copyRow (PixelRGB* dest, PixelRGB* src, int width) throw()
  66479. {
  66480. memcpy (dest, src, width * sizeof (PixelRGB));
  66481. }
  66482. ImageFillEdgeTableRenderer (const ImageFillEdgeTableRenderer&);
  66483. ImageFillEdgeTableRenderer& operator= (const ImageFillEdgeTableRenderer&);
  66484. };
  66485. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  66486. class TransformedImageFillEdgeTableRenderer
  66487. {
  66488. public:
  66489. TransformedImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  66490. const Image::BitmapData& srcData_,
  66491. const AffineTransform& transform,
  66492. const int extraAlpha_,
  66493. const bool betterQuality_)
  66494. : interpolator (transform),
  66495. destData (destData_),
  66496. srcData (srcData_),
  66497. extraAlpha (extraAlpha_ + 1),
  66498. betterQuality (betterQuality_),
  66499. pixelOffset (betterQuality_ ? 0.5f : 0.0f),
  66500. pixelOffsetInt (betterQuality_ ? -128 : 0),
  66501. maxX (srcData_.width - 1),
  66502. maxY (srcData_.height - 1),
  66503. scratchSize (2048)
  66504. {
  66505. scratchBuffer.malloc (scratchSize);
  66506. }
  66507. ~TransformedImageFillEdgeTableRenderer()
  66508. {
  66509. }
  66510. forcedinline void setEdgeTableYPos (const int newY) throw()
  66511. {
  66512. y = newY;
  66513. linePixels = (DestPixelType*) destData.getLinePointer (newY);
  66514. }
  66515. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) throw()
  66516. {
  66517. alphaLevel *= extraAlpha;
  66518. alphaLevel >>= 8;
  66519. SrcPixelType p;
  66520. generate (&p, x, 1);
  66521. linePixels[x].blend (p, alphaLevel);
  66522. }
  66523. forcedinline void handleEdgeTablePixelFull (const int x) throw()
  66524. {
  66525. SrcPixelType p;
  66526. generate (&p, x, 1);
  66527. linePixels[x].blend (p, extraAlpha);
  66528. }
  66529. void handleEdgeTableLine (const int x, int width, int alphaLevel) throw()
  66530. {
  66531. if (width > scratchSize)
  66532. {
  66533. scratchSize = width;
  66534. scratchBuffer.malloc (scratchSize);
  66535. }
  66536. SrcPixelType* span = scratchBuffer;
  66537. generate (span, x, width);
  66538. DestPixelType* dest = linePixels + x;
  66539. alphaLevel *= extraAlpha;
  66540. alphaLevel >>= 8;
  66541. if (alphaLevel < 0xfe)
  66542. {
  66543. do
  66544. {
  66545. dest++ ->blend (*span++, alphaLevel);
  66546. } while (--width > 0);
  66547. }
  66548. else
  66549. {
  66550. do
  66551. {
  66552. dest++ ->blend (*span++);
  66553. } while (--width > 0);
  66554. }
  66555. }
  66556. forcedinline void handleEdgeTableLineFull (const int x, int width) throw()
  66557. {
  66558. handleEdgeTableLine (x, width, 255);
  66559. }
  66560. void clipEdgeTableLine (EdgeTable& et, int x, int y_, int width)
  66561. {
  66562. if (width > scratchSize)
  66563. {
  66564. scratchSize = width;
  66565. scratchBuffer.malloc (scratchSize);
  66566. }
  66567. y = y_;
  66568. generate (scratchBuffer, x, width);
  66569. et.clipLineToMask (x, y_,
  66570. reinterpret_cast<uint8*> (scratchBuffer.getData()) + SrcPixelType::indexA,
  66571. sizeof (SrcPixelType), width);
  66572. }
  66573. private:
  66574. void generate (PixelARGB* dest, const int x, int numPixels) throw()
  66575. {
  66576. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  66577. do
  66578. {
  66579. int hiResX, hiResY;
  66580. this->interpolator.next (hiResX, hiResY);
  66581. hiResX += pixelOffsetInt;
  66582. hiResY += pixelOffsetInt;
  66583. int loResX = hiResX >> 8;
  66584. int loResY = hiResY >> 8;
  66585. if (repeatPattern)
  66586. {
  66587. loResX = safeModulo (loResX, srcData.width);
  66588. loResY = safeModulo (loResY, srcData.height);
  66589. }
  66590. if (betterQuality
  66591. && ((unsigned int) loResX) < (unsigned int) maxX
  66592. && ((unsigned int) loResY) < (unsigned int) maxY)
  66593. {
  66594. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  66595. hiResX &= 255;
  66596. hiResY &= 255;
  66597. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  66598. uint32 weight = (256 - hiResX) * (256 - hiResY);
  66599. c[0] += weight * src[0];
  66600. c[1] += weight * src[1];
  66601. c[2] += weight * src[2];
  66602. c[3] += weight * src[3];
  66603. weight = hiResX * (256 - hiResY);
  66604. c[0] += weight * src[4];
  66605. c[1] += weight * src[5];
  66606. c[2] += weight * src[6];
  66607. c[3] += weight * src[7];
  66608. src += this->srcData.lineStride;
  66609. weight = (256 - hiResX) * hiResY;
  66610. c[0] += weight * src[0];
  66611. c[1] += weight * src[1];
  66612. c[2] += weight * src[2];
  66613. c[3] += weight * src[3];
  66614. weight = hiResX * hiResY;
  66615. c[0] += weight * src[4];
  66616. c[1] += weight * src[5];
  66617. c[2] += weight * src[6];
  66618. c[3] += weight * src[7];
  66619. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  66620. (uint8) (c[PixelARGB::indexR] >> 16),
  66621. (uint8) (c[PixelARGB::indexG] >> 16),
  66622. (uint8) (c[PixelARGB::indexB] >> 16));
  66623. }
  66624. else
  66625. {
  66626. if (! repeatPattern)
  66627. {
  66628. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  66629. if (loResX < 0) loResX = 0;
  66630. if (loResY < 0) loResY = 0;
  66631. if (loResX > maxX) loResX = maxX;
  66632. if (loResY > maxY) loResY = maxY;
  66633. }
  66634. dest->set (*(const PixelARGB*) this->srcData.getPixelPointer (loResX, loResY));
  66635. }
  66636. ++dest;
  66637. } while (--numPixels > 0);
  66638. }
  66639. void generate (PixelRGB* dest, const int x, int numPixels) throw()
  66640. {
  66641. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  66642. do
  66643. {
  66644. int hiResX, hiResY;
  66645. this->interpolator.next (hiResX, hiResY);
  66646. hiResX += pixelOffsetInt;
  66647. hiResY += pixelOffsetInt;
  66648. int loResX = hiResX >> 8;
  66649. int loResY = hiResY >> 8;
  66650. if (repeatPattern)
  66651. {
  66652. loResX = safeModulo (loResX, srcData.width);
  66653. loResY = safeModulo (loResY, srcData.height);
  66654. }
  66655. if (betterQuality
  66656. && ((unsigned int) loResX) < (unsigned int) maxX
  66657. && ((unsigned int) loResY) < (unsigned int) maxY)
  66658. {
  66659. uint32 c[3] = { 256 * 128, 256 * 128, 256 * 128 };
  66660. hiResX &= 255;
  66661. hiResY &= 255;
  66662. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  66663. unsigned int weight = (256 - hiResX) * (256 - hiResY);
  66664. c[0] += weight * src[0];
  66665. c[1] += weight * src[1];
  66666. c[2] += weight * src[2];
  66667. weight = hiResX * (256 - hiResY);
  66668. c[0] += weight * src[3];
  66669. c[1] += weight * src[4];
  66670. c[2] += weight * src[5];
  66671. src += this->srcData.lineStride;
  66672. weight = (256 - hiResX) * hiResY;
  66673. c[0] += weight * src[0];
  66674. c[1] += weight * src[1];
  66675. c[2] += weight * src[2];
  66676. weight = hiResX * hiResY;
  66677. c[0] += weight * src[3];
  66678. c[1] += weight * src[4];
  66679. c[2] += weight * src[5];
  66680. dest->setARGB ((uint8) 255,
  66681. (uint8) (c[PixelRGB::indexR] >> 16),
  66682. (uint8) (c[PixelRGB::indexG] >> 16),
  66683. (uint8) (c[PixelRGB::indexB] >> 16));
  66684. }
  66685. else
  66686. {
  66687. if (! repeatPattern)
  66688. {
  66689. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  66690. if (loResX < 0) loResX = 0;
  66691. if (loResY < 0) loResY = 0;
  66692. if (loResX > maxX) loResX = maxX;
  66693. if (loResY > maxY) loResY = maxY;
  66694. }
  66695. dest->set (*(const PixelRGB*) this->srcData.getPixelPointer (loResX, loResY));
  66696. }
  66697. ++dest;
  66698. } while (--numPixels > 0);
  66699. }
  66700. void generate (PixelAlpha* dest, const int x, int numPixels) throw()
  66701. {
  66702. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  66703. do
  66704. {
  66705. int hiResX, hiResY;
  66706. this->interpolator.next (hiResX, hiResY);
  66707. hiResX += pixelOffsetInt;
  66708. hiResY += pixelOffsetInt;
  66709. int loResX = hiResX >> 8;
  66710. int loResY = hiResY >> 8;
  66711. if (repeatPattern)
  66712. {
  66713. loResX = safeModulo (loResX, srcData.width);
  66714. loResY = safeModulo (loResY, srcData.height);
  66715. }
  66716. if (betterQuality
  66717. && ((unsigned int) loResX) < (unsigned int) maxX
  66718. && ((unsigned int) loResY) < (unsigned int) maxY)
  66719. {
  66720. hiResX &= 255;
  66721. hiResY &= 255;
  66722. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  66723. uint32 c = 256 * 128;
  66724. c += src[0] * ((256 - hiResX) * (256 - hiResY));
  66725. c += src[1] * (hiResX * (256 - hiResY));
  66726. src += this->srcData.lineStride;
  66727. c += src[0] * ((256 - hiResX) * hiResY);
  66728. c += src[1] * (hiResX * hiResY);
  66729. *((uint8*) dest) = (uint8) c;
  66730. }
  66731. else
  66732. {
  66733. if (! repeatPattern)
  66734. {
  66735. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  66736. if (loResX < 0) loResX = 0;
  66737. if (loResY < 0) loResY = 0;
  66738. if (loResX > maxX) loResX = maxX;
  66739. if (loResY > maxY) loResY = maxY;
  66740. }
  66741. *((uint8*) dest) = *(this->srcData.getPixelPointer (loResX, loResY));
  66742. }
  66743. ++dest;
  66744. } while (--numPixels > 0);
  66745. }
  66746. class TransformedImageSpanInterpolator
  66747. {
  66748. public:
  66749. TransformedImageSpanInterpolator (const AffineTransform& transform) throw()
  66750. : inverseTransform (transform.inverted())
  66751. {}
  66752. void setStartOfLine (float x, float y, const int numPixels) throw()
  66753. {
  66754. float x1 = x, y1 = y;
  66755. x += numPixels;
  66756. inverseTransform.transformPoints (x1, y1, x, y);
  66757. xBresenham.set ((int) (x1 * 256.0f), (int) (x * 256.0f), numPixels);
  66758. yBresenham.set ((int) (y1 * 256.0f), (int) (y * 256.0f), numPixels);
  66759. }
  66760. void next (int& x, int& y) throw()
  66761. {
  66762. x = xBresenham.n;
  66763. xBresenham.stepToNext();
  66764. y = yBresenham.n;
  66765. yBresenham.stepToNext();
  66766. }
  66767. private:
  66768. class BresenhamInterpolator
  66769. {
  66770. public:
  66771. BresenhamInterpolator() throw() {}
  66772. void set (const int n1, const int n2, const int numSteps_) throw()
  66773. {
  66774. numSteps = jmax (1, numSteps_);
  66775. step = (n2 - n1) / numSteps;
  66776. remainder = modulo = (n2 - n1) % numSteps;
  66777. n = n1;
  66778. if (modulo <= 0)
  66779. {
  66780. modulo += numSteps;
  66781. remainder += numSteps;
  66782. --step;
  66783. }
  66784. modulo -= numSteps;
  66785. }
  66786. forcedinline void stepToNext() throw()
  66787. {
  66788. modulo += remainder;
  66789. n += step;
  66790. if (modulo > 0)
  66791. {
  66792. modulo -= numSteps;
  66793. ++n;
  66794. }
  66795. }
  66796. int n;
  66797. private:
  66798. int numSteps, step, modulo, remainder;
  66799. };
  66800. const AffineTransform inverseTransform;
  66801. BresenhamInterpolator xBresenham, yBresenham;
  66802. TransformedImageSpanInterpolator (const TransformedImageSpanInterpolator&);
  66803. TransformedImageSpanInterpolator& operator= (const TransformedImageSpanInterpolator&);
  66804. };
  66805. TransformedImageSpanInterpolator interpolator;
  66806. const Image::BitmapData& destData;
  66807. const Image::BitmapData& srcData;
  66808. const int extraAlpha;
  66809. const bool betterQuality;
  66810. const float pixelOffset;
  66811. const int pixelOffsetInt, maxX, maxY;
  66812. int y;
  66813. DestPixelType* linePixels;
  66814. HeapBlock <SrcPixelType> scratchBuffer;
  66815. int scratchSize;
  66816. TransformedImageFillEdgeTableRenderer (const TransformedImageFillEdgeTableRenderer&);
  66817. TransformedImageFillEdgeTableRenderer& operator= (const TransformedImageFillEdgeTableRenderer&);
  66818. };
  66819. class ClipRegionBase : public ReferenceCountedObject
  66820. {
  66821. public:
  66822. ClipRegionBase() {}
  66823. virtual ~ClipRegionBase() {}
  66824. typedef ReferenceCountedObjectPtr<ClipRegionBase> Ptr;
  66825. virtual const Ptr clone() const = 0;
  66826. virtual const Ptr applyClipTo (const Ptr& target) const = 0;
  66827. virtual const Ptr clipToRectangle (const Rectangle<int>& r) = 0;
  66828. virtual const Ptr clipToRectangleList (const RectangleList& r) = 0;
  66829. virtual const Ptr excludeClipRectangle (const Rectangle<int>& r) = 0;
  66830. virtual const Ptr clipToPath (const Path& p, const AffineTransform& transform) = 0;
  66831. virtual const Ptr clipToEdgeTable (const EdgeTable& et) = 0;
  66832. virtual const Ptr clipToImageAlpha (const Image& image, const Rectangle<int>& srcClip, const AffineTransform& t, const bool betterQuality) = 0;
  66833. virtual bool clipRegionIntersects (const Rectangle<int>& r) const = 0;
  66834. virtual const Rectangle<int> getClipBounds() const = 0;
  66835. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const = 0;
  66836. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const = 0;
  66837. virtual void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const = 0;
  66838. virtual void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const = 0;
  66839. virtual void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& t, bool betterQuality, bool tiledFill) const = 0;
  66840. virtual void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const = 0;
  66841. protected:
  66842. template <class Iterator>
  66843. static void renderImageTransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData,
  66844. const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill)
  66845. {
  66846. switch (destData.pixelFormat)
  66847. {
  66848. case Image::ARGB:
  66849. switch (srcData.pixelFormat)
  66850. {
  66851. case Image::ARGB:
  66852. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66853. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66854. break;
  66855. case Image::RGB:
  66856. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66857. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66858. break;
  66859. default:
  66860. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66861. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66862. break;
  66863. }
  66864. break;
  66865. case Image::RGB:
  66866. switch (srcData.pixelFormat)
  66867. {
  66868. case Image::ARGB:
  66869. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66870. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66871. break;
  66872. case Image::RGB:
  66873. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66874. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66875. break;
  66876. default:
  66877. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66878. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66879. break;
  66880. }
  66881. break;
  66882. default:
  66883. switch (srcData.pixelFormat)
  66884. {
  66885. case Image::ARGB:
  66886. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66887. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66888. break;
  66889. case Image::RGB:
  66890. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66891. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66892. break;
  66893. default:
  66894. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66895. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66896. break;
  66897. }
  66898. break;
  66899. }
  66900. }
  66901. template <class Iterator>
  66902. static void renderImageUntransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill)
  66903. {
  66904. switch (destData.pixelFormat)
  66905. {
  66906. case Image::ARGB:
  66907. switch (srcData.pixelFormat)
  66908. {
  66909. case Image::ARGB:
  66910. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66911. else { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66912. break;
  66913. case Image::RGB:
  66914. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66915. else { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66916. break;
  66917. default:
  66918. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66919. else { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66920. break;
  66921. }
  66922. break;
  66923. case Image::RGB:
  66924. switch (srcData.pixelFormat)
  66925. {
  66926. case Image::ARGB:
  66927. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66928. else { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66929. break;
  66930. case Image::RGB:
  66931. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66932. else { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66933. break;
  66934. default:
  66935. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66936. else { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66937. break;
  66938. }
  66939. break;
  66940. default:
  66941. switch (srcData.pixelFormat)
  66942. {
  66943. case Image::ARGB:
  66944. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66945. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66946. break;
  66947. case Image::RGB:
  66948. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66949. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66950. break;
  66951. default:
  66952. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66953. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66954. break;
  66955. }
  66956. break;
  66957. }
  66958. }
  66959. template <class Iterator, class DestPixelType>
  66960. static void renderSolidFill (Iterator& iter, const Image::BitmapData& destData, const PixelARGB& fillColour, const bool replaceContents, DestPixelType*)
  66961. {
  66962. jassert (destData.pixelStride == sizeof (DestPixelType));
  66963. if (replaceContents)
  66964. {
  66965. SolidColourEdgeTableRenderer <DestPixelType, true> r (destData, fillColour);
  66966. iter.iterate (r);
  66967. }
  66968. else
  66969. {
  66970. SolidColourEdgeTableRenderer <DestPixelType, false> r (destData, fillColour);
  66971. iter.iterate (r);
  66972. }
  66973. }
  66974. template <class Iterator, class DestPixelType>
  66975. static void renderGradient (Iterator& iter, const Image::BitmapData& destData, const ColourGradient& g, const AffineTransform& transform,
  66976. const PixelARGB* const lookupTable, const int numLookupEntries, const bool isIdentity, DestPixelType*)
  66977. {
  66978. jassert (destData.pixelStride == sizeof (DestPixelType));
  66979. if (g.isRadial)
  66980. {
  66981. if (isIdentity)
  66982. {
  66983. GradientEdgeTableRenderer <DestPixelType, RadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  66984. iter.iterate (renderer);
  66985. }
  66986. else
  66987. {
  66988. GradientEdgeTableRenderer <DestPixelType, TransformedRadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  66989. iter.iterate (renderer);
  66990. }
  66991. }
  66992. else
  66993. {
  66994. GradientEdgeTableRenderer <DestPixelType, LinearGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  66995. iter.iterate (renderer);
  66996. }
  66997. }
  66998. };
  66999. class ClipRegion_EdgeTable : public ClipRegionBase
  67000. {
  67001. public:
  67002. ClipRegion_EdgeTable (const EdgeTable& e) : edgeTable (e) {}
  67003. ClipRegion_EdgeTable (const Rectangle<int>& r) : edgeTable (r) {}
  67004. ClipRegion_EdgeTable (const Rectangle<float>& r) : edgeTable (r) {}
  67005. ClipRegion_EdgeTable (const RectangleList& r) : edgeTable (r) {}
  67006. ClipRegion_EdgeTable (const Rectangle<int>& bounds, const Path& p, const AffineTransform& t) : edgeTable (bounds, p, t) {}
  67007. ClipRegion_EdgeTable (const ClipRegion_EdgeTable& other) : edgeTable (other.edgeTable) {}
  67008. ~ClipRegion_EdgeTable() {}
  67009. const Ptr clone() const
  67010. {
  67011. return new ClipRegion_EdgeTable (*this);
  67012. }
  67013. const Ptr applyClipTo (const Ptr& target) const
  67014. {
  67015. return target->clipToEdgeTable (edgeTable);
  67016. }
  67017. const Ptr clipToRectangle (const Rectangle<int>& r)
  67018. {
  67019. edgeTable.clipToRectangle (r);
  67020. return edgeTable.isEmpty() ? 0 : this;
  67021. }
  67022. const Ptr clipToRectangleList (const RectangleList& r)
  67023. {
  67024. RectangleList inverse (edgeTable.getMaximumBounds());
  67025. if (inverse.subtract (r))
  67026. for (RectangleList::Iterator iter (inverse); iter.next();)
  67027. edgeTable.excludeRectangle (*iter.getRectangle());
  67028. return edgeTable.isEmpty() ? 0 : this;
  67029. }
  67030. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  67031. {
  67032. edgeTable.excludeRectangle (r);
  67033. return edgeTable.isEmpty() ? 0 : this;
  67034. }
  67035. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  67036. {
  67037. EdgeTable et (edgeTable.getMaximumBounds(), p, transform);
  67038. edgeTable.clipToEdgeTable (et);
  67039. return edgeTable.isEmpty() ? 0 : this;
  67040. }
  67041. const Ptr clipToEdgeTable (const EdgeTable& et)
  67042. {
  67043. edgeTable.clipToEdgeTable (et);
  67044. return edgeTable.isEmpty() ? 0 : this;
  67045. }
  67046. const Ptr clipToImageAlpha (const Image& image, const Rectangle<int>& srcClip, const AffineTransform& transform, const bool betterQuality)
  67047. {
  67048. const Image::BitmapData srcData (image, srcClip.getX(), srcClip.getY(), srcClip.getWidth(), srcClip.getHeight());
  67049. if (transform.isOnlyTranslation())
  67050. {
  67051. // If our translation doesn't involve any distortion, just use a simple blit..
  67052. const int tx = (int) (transform.getTranslationX() * 256.0f);
  67053. const int ty = (int) (transform.getTranslationY() * 256.0f);
  67054. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  67055. {
  67056. const int imageX = ((tx + 128) >> 8);
  67057. const int imageY = ((ty + 128) >> 8);
  67058. if (image.getFormat() == Image::ARGB)
  67059. straightClipImage (srcData, imageX, imageY, (PixelARGB*) 0);
  67060. else
  67061. straightClipImage (srcData, imageX, imageY, (PixelAlpha*) 0);
  67062. return edgeTable.isEmpty() ? 0 : this;
  67063. }
  67064. }
  67065. if (transform.isSingularity())
  67066. return 0;
  67067. {
  67068. Path p;
  67069. p.addRectangle (0, 0, (float) srcData.width, (float) srcData.height);
  67070. EdgeTable et2 (edgeTable.getMaximumBounds(), p, transform);
  67071. edgeTable.clipToEdgeTable (et2);
  67072. }
  67073. if (! edgeTable.isEmpty())
  67074. {
  67075. if (image.getFormat() == Image::ARGB)
  67076. transformedClipImage (srcData, transform, betterQuality, (PixelARGB*) 0);
  67077. else
  67078. transformedClipImage (srcData, transform, betterQuality, (PixelAlpha*) 0);
  67079. }
  67080. return edgeTable.isEmpty() ? 0 : this;
  67081. }
  67082. bool clipRegionIntersects (const Rectangle<int>& r) const
  67083. {
  67084. return edgeTable.getMaximumBounds().intersects (r);
  67085. }
  67086. const Rectangle<int> getClipBounds() const
  67087. {
  67088. return edgeTable.getMaximumBounds();
  67089. }
  67090. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  67091. {
  67092. const Rectangle<int> totalClip (edgeTable.getMaximumBounds());
  67093. const Rectangle<int> clipped (totalClip.getIntersection (area));
  67094. if (! clipped.isEmpty())
  67095. {
  67096. ClipRegion_EdgeTable et (clipped);
  67097. et.edgeTable.clipToEdgeTable (edgeTable);
  67098. et.fillAllWithColour (destData, colour, replaceContents);
  67099. }
  67100. }
  67101. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  67102. {
  67103. const Rectangle<float> totalClip (edgeTable.getMaximumBounds().toFloat());
  67104. const Rectangle<float> clipped (totalClip.getIntersection (area));
  67105. if (! clipped.isEmpty())
  67106. {
  67107. ClipRegion_EdgeTable et (clipped);
  67108. et.edgeTable.clipToEdgeTable (edgeTable);
  67109. et.fillAllWithColour (destData, colour, false);
  67110. }
  67111. }
  67112. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  67113. {
  67114. switch (destData.pixelFormat)
  67115. {
  67116. case Image::ARGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelARGB*) 0); break;
  67117. case Image::RGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelRGB*) 0); break;
  67118. default: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  67119. }
  67120. }
  67121. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  67122. {
  67123. HeapBlock <PixelARGB> lookupTable;
  67124. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  67125. jassert (numLookupEntries > 0);
  67126. switch (destData.pixelFormat)
  67127. {
  67128. case Image::ARGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  67129. case Image::RGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  67130. default: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  67131. }
  67132. }
  67133. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  67134. {
  67135. renderImageTransformedInternal (edgeTable, destData, srcData, alpha, transform, betterQuality, tiledFill);
  67136. }
  67137. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  67138. {
  67139. renderImageUntransformedInternal (edgeTable, destData, srcData, alpha, x, y, tiledFill);
  67140. }
  67141. EdgeTable edgeTable;
  67142. private:
  67143. template <class SrcPixelType>
  67144. void transformedClipImage (const Image::BitmapData& srcData, const AffineTransform& transform, const bool betterQuality, const SrcPixelType*)
  67145. {
  67146. TransformedImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, transform, 255, betterQuality);
  67147. for (int y = 0; y < edgeTable.getMaximumBounds().getHeight(); ++y)
  67148. renderer.clipEdgeTableLine (edgeTable, edgeTable.getMaximumBounds().getX(), y + edgeTable.getMaximumBounds().getY(),
  67149. edgeTable.getMaximumBounds().getWidth());
  67150. }
  67151. template <class SrcPixelType>
  67152. void straightClipImage (const Image::BitmapData& srcData, int imageX, int imageY, const SrcPixelType*)
  67153. {
  67154. Rectangle<int> r (imageX, imageY, srcData.width, srcData.height);
  67155. edgeTable.clipToRectangle (r);
  67156. ImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, 255, imageX, imageY);
  67157. for (int y = 0; y < r.getHeight(); ++y)
  67158. renderer.clipEdgeTableLine (edgeTable, r.getX(), y + r.getY(), r.getWidth());
  67159. }
  67160. ClipRegion_EdgeTable& operator= (const ClipRegion_EdgeTable&);
  67161. };
  67162. class ClipRegion_RectangleList : public ClipRegionBase
  67163. {
  67164. public:
  67165. ClipRegion_RectangleList (const Rectangle<int>& r) : clip (r) {}
  67166. ClipRegion_RectangleList (const RectangleList& r) : clip (r) {}
  67167. ClipRegion_RectangleList (const ClipRegion_RectangleList& other) : clip (other.clip) {}
  67168. ~ClipRegion_RectangleList() {}
  67169. const Ptr clone() const
  67170. {
  67171. return new ClipRegion_RectangleList (*this);
  67172. }
  67173. const Ptr applyClipTo (const Ptr& target) const
  67174. {
  67175. return target->clipToRectangleList (clip);
  67176. }
  67177. const Ptr clipToRectangle (const Rectangle<int>& r)
  67178. {
  67179. clip.clipTo (r);
  67180. return clip.isEmpty() ? 0 : this;
  67181. }
  67182. const Ptr clipToRectangleList (const RectangleList& r)
  67183. {
  67184. clip.clipTo (r);
  67185. return clip.isEmpty() ? 0 : this;
  67186. }
  67187. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  67188. {
  67189. clip.subtract (r);
  67190. return clip.isEmpty() ? 0 : this;
  67191. }
  67192. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  67193. {
  67194. return Ptr (new ClipRegion_EdgeTable (clip))->clipToPath (p, transform);
  67195. }
  67196. const Ptr clipToEdgeTable (const EdgeTable& et)
  67197. {
  67198. return Ptr (new ClipRegion_EdgeTable (clip))->clipToEdgeTable (et);
  67199. }
  67200. const Ptr clipToImageAlpha (const Image& image, const Rectangle<int>& srcClip, const AffineTransform& transform, const bool betterQuality)
  67201. {
  67202. return Ptr (new ClipRegion_EdgeTable (clip))->clipToImageAlpha (image, srcClip, transform, betterQuality);
  67203. }
  67204. bool clipRegionIntersects (const Rectangle<int>& r) const
  67205. {
  67206. return clip.intersects (r);
  67207. }
  67208. const Rectangle<int> getClipBounds() const
  67209. {
  67210. return clip.getBounds();
  67211. }
  67212. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  67213. {
  67214. SubRectangleIterator iter (clip, area);
  67215. switch (destData.pixelFormat)
  67216. {
  67217. case Image::ARGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelARGB*) 0); break;
  67218. case Image::RGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelRGB*) 0); break;
  67219. default: renderSolidFill (iter, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  67220. }
  67221. }
  67222. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  67223. {
  67224. SubRectangleIteratorFloat iter (clip, area);
  67225. switch (destData.pixelFormat)
  67226. {
  67227. case Image::ARGB: renderSolidFill (iter, destData, colour, false, (PixelARGB*) 0); break;
  67228. case Image::RGB: renderSolidFill (iter, destData, colour, false, (PixelRGB*) 0); break;
  67229. default: renderSolidFill (iter, destData, colour, false, (PixelAlpha*) 0); break;
  67230. }
  67231. }
  67232. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  67233. {
  67234. switch (destData.pixelFormat)
  67235. {
  67236. case Image::ARGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelARGB*) 0); break;
  67237. case Image::RGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelRGB*) 0); break;
  67238. default: renderSolidFill (*this, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  67239. }
  67240. }
  67241. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  67242. {
  67243. HeapBlock <PixelARGB> lookupTable;
  67244. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  67245. jassert (numLookupEntries > 0);
  67246. switch (destData.pixelFormat)
  67247. {
  67248. case Image::ARGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  67249. case Image::RGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  67250. default: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  67251. }
  67252. }
  67253. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  67254. {
  67255. renderImageTransformedInternal (*this, destData, srcData, alpha, transform, betterQuality, tiledFill);
  67256. }
  67257. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  67258. {
  67259. renderImageUntransformedInternal (*this, destData, srcData, alpha, x, y, tiledFill);
  67260. }
  67261. RectangleList clip;
  67262. template <class Renderer>
  67263. void iterate (Renderer& r) const throw()
  67264. {
  67265. RectangleList::Iterator iter (clip);
  67266. while (iter.next())
  67267. {
  67268. const Rectangle<int> rect (*iter.getRectangle());
  67269. const int x = rect.getX();
  67270. const int w = rect.getWidth();
  67271. jassert (w > 0);
  67272. const int bottom = rect.getBottom();
  67273. for (int y = rect.getY(); y < bottom; ++y)
  67274. {
  67275. r.setEdgeTableYPos (y);
  67276. r.handleEdgeTableLineFull (x, w);
  67277. }
  67278. }
  67279. }
  67280. private:
  67281. class SubRectangleIterator
  67282. {
  67283. public:
  67284. SubRectangleIterator (const RectangleList& clip_, const Rectangle<int>& area_)
  67285. : clip (clip_), area (area_)
  67286. {
  67287. }
  67288. template <class Renderer>
  67289. void iterate (Renderer& r) const throw()
  67290. {
  67291. RectangleList::Iterator iter (clip);
  67292. while (iter.next())
  67293. {
  67294. const Rectangle<int> rect (iter.getRectangle()->getIntersection (area));
  67295. if (! rect.isEmpty())
  67296. {
  67297. const int x = rect.getX();
  67298. const int w = rect.getWidth();
  67299. const int bottom = rect.getBottom();
  67300. for (int y = rect.getY(); y < bottom; ++y)
  67301. {
  67302. r.setEdgeTableYPos (y);
  67303. r.handleEdgeTableLineFull (x, w);
  67304. }
  67305. }
  67306. }
  67307. }
  67308. private:
  67309. const RectangleList& clip;
  67310. const Rectangle<int> area;
  67311. SubRectangleIterator (const SubRectangleIterator&);
  67312. SubRectangleIterator& operator= (const SubRectangleIterator&);
  67313. };
  67314. class SubRectangleIteratorFloat
  67315. {
  67316. public:
  67317. SubRectangleIteratorFloat (const RectangleList& clip_, const Rectangle<float>& area_)
  67318. : clip (clip_), area (area_)
  67319. {
  67320. }
  67321. template <class Renderer>
  67322. void iterate (Renderer& r) const throw()
  67323. {
  67324. int left = roundToInt (area.getX() * 256.0f);
  67325. int top = roundToInt (area.getY() * 256.0f);
  67326. int right = roundToInt (area.getRight() * 256.0f);
  67327. int bottom = roundToInt (area.getBottom() * 256.0f);
  67328. int totalTop, totalLeft, totalBottom, totalRight;
  67329. int topAlpha, leftAlpha, bottomAlpha, rightAlpha;
  67330. if ((top >> 8) == (bottom >> 8))
  67331. {
  67332. topAlpha = bottom - top;
  67333. bottomAlpha = 0;
  67334. totalTop = top >> 8;
  67335. totalBottom = bottom = top = totalTop + 1;
  67336. }
  67337. else
  67338. {
  67339. if ((top & 255) == 0)
  67340. {
  67341. topAlpha = 0;
  67342. top = totalTop = (top >> 8);
  67343. }
  67344. else
  67345. {
  67346. topAlpha = 255 - (top & 255);
  67347. totalTop = (top >> 8);
  67348. top = totalTop + 1;
  67349. }
  67350. bottomAlpha = bottom & 255;
  67351. bottom >>= 8;
  67352. totalBottom = bottom + (bottomAlpha != 0 ? 1 : 0);
  67353. }
  67354. if ((left >> 8) == (right >> 8))
  67355. {
  67356. leftAlpha = right - left;
  67357. rightAlpha = 0;
  67358. totalLeft = (left >> 8);
  67359. totalRight = right = left = totalLeft + 1;
  67360. }
  67361. else
  67362. {
  67363. if ((left & 255) == 0)
  67364. {
  67365. leftAlpha = 0;
  67366. left = totalLeft = (left >> 8);
  67367. }
  67368. else
  67369. {
  67370. leftAlpha = 255 - (left & 255);
  67371. totalLeft = (left >> 8);
  67372. left = totalLeft + 1;
  67373. }
  67374. rightAlpha = right & 255;
  67375. right >>= 8;
  67376. totalRight = right + (rightAlpha != 0 ? 1 : 0);
  67377. }
  67378. RectangleList::Iterator iter (clip);
  67379. while (iter.next())
  67380. {
  67381. const int clipLeft = iter.getRectangle()->getX();
  67382. const int clipRight = iter.getRectangle()->getRight();
  67383. const int clipTop = iter.getRectangle()->getY();
  67384. const int clipBottom = iter.getRectangle()->getBottom();
  67385. if (totalBottom > clipTop && totalTop < clipBottom && totalRight > clipLeft && totalLeft < clipRight)
  67386. {
  67387. if (right - left == 1 && leftAlpha + rightAlpha == 0) // special case for 1-pix vertical lines
  67388. {
  67389. if (topAlpha != 0 && totalTop >= clipTop)
  67390. {
  67391. r.setEdgeTableYPos (totalTop);
  67392. r.handleEdgeTablePixel (left, topAlpha);
  67393. }
  67394. const int endY = jmin (bottom, clipBottom);
  67395. for (int y = jmax (clipTop, top); y < endY; ++y)
  67396. {
  67397. r.setEdgeTableYPos (y);
  67398. r.handleEdgeTablePixelFull (left);
  67399. }
  67400. if (bottomAlpha != 0 && bottom < clipBottom)
  67401. {
  67402. r.setEdgeTableYPos (bottom);
  67403. r.handleEdgeTablePixel (left, bottomAlpha);
  67404. }
  67405. }
  67406. else
  67407. {
  67408. const int clippedLeft = jmax (left, clipLeft);
  67409. const int clippedWidth = jmin (right, clipRight) - clippedLeft;
  67410. const bool doLeftAlpha = leftAlpha != 0 && totalLeft >= clipLeft;
  67411. const bool doRightAlpha = rightAlpha != 0 && right < clipRight;
  67412. if (topAlpha != 0 && totalTop >= clipTop)
  67413. {
  67414. r.setEdgeTableYPos (totalTop);
  67415. if (doLeftAlpha)
  67416. r.handleEdgeTablePixel (totalLeft, (leftAlpha * topAlpha) >> 8);
  67417. if (clippedWidth > 0)
  67418. r.handleEdgeTableLine (clippedLeft, clippedWidth, topAlpha);
  67419. if (doRightAlpha)
  67420. r.handleEdgeTablePixel (right, (rightAlpha * topAlpha) >> 8);
  67421. }
  67422. const int endY = jmin (bottom, clipBottom);
  67423. for (int y = jmax (clipTop, top); y < endY; ++y)
  67424. {
  67425. r.setEdgeTableYPos (y);
  67426. if (doLeftAlpha)
  67427. r.handleEdgeTablePixel (totalLeft, leftAlpha);
  67428. if (clippedWidth > 0)
  67429. r.handleEdgeTableLineFull (clippedLeft, clippedWidth);
  67430. if (doRightAlpha)
  67431. r.handleEdgeTablePixel (right, rightAlpha);
  67432. }
  67433. if (bottomAlpha != 0 && bottom < clipBottom)
  67434. {
  67435. r.setEdgeTableYPos (bottom);
  67436. if (doLeftAlpha)
  67437. r.handleEdgeTablePixel (totalLeft, (leftAlpha * bottomAlpha) >> 8);
  67438. if (clippedWidth > 0)
  67439. r.handleEdgeTableLine (clippedLeft, clippedWidth, bottomAlpha);
  67440. if (doRightAlpha)
  67441. r.handleEdgeTablePixel (right, (rightAlpha * bottomAlpha) >> 8);
  67442. }
  67443. }
  67444. }
  67445. }
  67446. }
  67447. private:
  67448. const RectangleList& clip;
  67449. const Rectangle<float>& area;
  67450. SubRectangleIteratorFloat (const SubRectangleIteratorFloat&);
  67451. SubRectangleIteratorFloat& operator= (const SubRectangleIteratorFloat&);
  67452. };
  67453. ClipRegion_RectangleList& operator= (const ClipRegion_RectangleList&);
  67454. };
  67455. }
  67456. class LowLevelGraphicsSoftwareRenderer::SavedState
  67457. {
  67458. public:
  67459. SavedState (const Rectangle<int>& clip_, const int xOffset_, const int yOffset_)
  67460. : clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  67461. xOffset (xOffset_), yOffset (yOffset_), interpolationQuality (Graphics::mediumResamplingQuality)
  67462. {
  67463. }
  67464. SavedState (const RectangleList& clip_, const int xOffset_, const int yOffset_)
  67465. : clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  67466. xOffset (xOffset_), yOffset (yOffset_), interpolationQuality (Graphics::mediumResamplingQuality)
  67467. {
  67468. }
  67469. SavedState (const SavedState& other)
  67470. : clip (other.clip), xOffset (other.xOffset), yOffset (other.yOffset), font (other.font),
  67471. fillType (other.fillType), interpolationQuality (other.interpolationQuality)
  67472. {
  67473. }
  67474. ~SavedState()
  67475. {
  67476. }
  67477. void setOrigin (const int x, const int y) throw()
  67478. {
  67479. xOffset += x;
  67480. yOffset += y;
  67481. }
  67482. bool clipToRectangle (const Rectangle<int>& r)
  67483. {
  67484. if (clip != 0)
  67485. {
  67486. cloneClipIfMultiplyReferenced();
  67487. clip = clip->clipToRectangle (r.translated (xOffset, yOffset));
  67488. }
  67489. return clip != 0;
  67490. }
  67491. bool clipToRectangleList (const RectangleList& r)
  67492. {
  67493. if (clip != 0)
  67494. {
  67495. cloneClipIfMultiplyReferenced();
  67496. RectangleList offsetList (r);
  67497. offsetList.offsetAll (xOffset, yOffset);
  67498. clip = clip->clipToRectangleList (offsetList);
  67499. }
  67500. return clip != 0;
  67501. }
  67502. bool excludeClipRectangle (const Rectangle<int>& r)
  67503. {
  67504. if (clip != 0)
  67505. {
  67506. cloneClipIfMultiplyReferenced();
  67507. clip = clip->excludeClipRectangle (r.translated (xOffset, yOffset));
  67508. }
  67509. return clip != 0;
  67510. }
  67511. void clipToPath (const Path& p, const AffineTransform& transform)
  67512. {
  67513. if (clip != 0)
  67514. {
  67515. cloneClipIfMultiplyReferenced();
  67516. clip = clip->clipToPath (p, transform.translated ((float) xOffset, (float) yOffset));
  67517. }
  67518. }
  67519. void clipToImageAlpha (const Image& image, const Rectangle<int>& srcClip, const AffineTransform& t)
  67520. {
  67521. if (clip != 0)
  67522. {
  67523. if (image.hasAlphaChannel())
  67524. {
  67525. cloneClipIfMultiplyReferenced();
  67526. clip = clip->clipToImageAlpha (image, srcClip, t.translated ((float) xOffset, (float) yOffset),
  67527. interpolationQuality != Graphics::lowResamplingQuality);
  67528. }
  67529. else
  67530. {
  67531. Path p;
  67532. p.addRectangle (srcClip);
  67533. clipToPath (p, t);
  67534. }
  67535. }
  67536. }
  67537. bool clipRegionIntersects (const Rectangle<int>& r) const
  67538. {
  67539. return clip != 0 && clip->clipRegionIntersects (r.translated (xOffset, yOffset));
  67540. }
  67541. const Rectangle<int> getClipBounds() const
  67542. {
  67543. return clip == 0 ? Rectangle<int>() : clip->getClipBounds().translated (-xOffset, -yOffset);
  67544. }
  67545. void fillRect (Image& image, const Rectangle<int>& r, const bool replaceContents)
  67546. {
  67547. if (clip != 0)
  67548. {
  67549. if (fillType.isColour())
  67550. {
  67551. Image::BitmapData destData (image, 0, 0, image.getWidth(), image.getHeight(), true);
  67552. clip->fillRectWithColour (destData, r.translated (xOffset, yOffset), fillType.colour.getPixelARGB(), replaceContents);
  67553. }
  67554. else
  67555. {
  67556. const Rectangle<int> totalClip (clip->getClipBounds());
  67557. const Rectangle<int> clipped (totalClip.getIntersection (r.translated (xOffset, yOffset)));
  67558. if (! clipped.isEmpty())
  67559. fillShape (image, new SoftwareRendererClasses::ClipRegion_RectangleList (clipped), false);
  67560. }
  67561. }
  67562. }
  67563. void fillRect (Image& image, const Rectangle<float>& r)
  67564. {
  67565. if (clip != 0)
  67566. {
  67567. if (fillType.isColour())
  67568. {
  67569. Image::BitmapData destData (image, 0, 0, image.getWidth(), image.getHeight(), true);
  67570. clip->fillRectWithColour (destData, r.translated ((float) xOffset, (float) yOffset), fillType.colour.getPixelARGB());
  67571. }
  67572. else
  67573. {
  67574. const Rectangle<float> totalClip (clip->getClipBounds().toFloat());
  67575. const Rectangle<float> clipped (totalClip.getIntersection (r.translated ((float) xOffset, (float) yOffset)));
  67576. if (! clipped.isEmpty())
  67577. fillShape (image, new SoftwareRendererClasses::ClipRegion_EdgeTable (clipped), false);
  67578. }
  67579. }
  67580. }
  67581. void fillPath (Image& image, const Path& path, const AffineTransform& transform)
  67582. {
  67583. if (clip != 0)
  67584. fillShape (image, new SoftwareRendererClasses::ClipRegion_EdgeTable (clip->getClipBounds(), path, transform.translated ((float) xOffset, (float) yOffset)), false);
  67585. }
  67586. void fillEdgeTable (Image& image, const EdgeTable& edgeTable, const float x, const int y)
  67587. {
  67588. if (clip != 0)
  67589. {
  67590. SoftwareRendererClasses::ClipRegion_EdgeTable* edgeTableClip = new SoftwareRendererClasses::ClipRegion_EdgeTable (edgeTable);
  67591. SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill (edgeTableClip);
  67592. edgeTableClip->edgeTable.translate (x + xOffset, y + yOffset);
  67593. fillShape (image, shapeToFill, false);
  67594. }
  67595. }
  67596. void fillShape (Image& image, SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill, const bool replaceContents)
  67597. {
  67598. jassert (clip != 0);
  67599. shapeToFill = clip->applyClipTo (shapeToFill);
  67600. if (shapeToFill != 0)
  67601. {
  67602. Image::BitmapData destData (image, 0, 0, image.getWidth(), image.getHeight(), true);
  67603. if (fillType.isGradient())
  67604. {
  67605. jassert (! replaceContents); // that option is just for solid colours
  67606. ColourGradient g2 (*(fillType.gradient));
  67607. g2.multiplyOpacity (fillType.getOpacity());
  67608. g2.point1.addXY (-0.5f, -0.5f);
  67609. g2.point2.addXY (-0.5f, -0.5f);
  67610. AffineTransform transform (fillType.transform.translated ((float) xOffset, (float) yOffset));
  67611. const bool isIdentity = transform.isOnlyTranslation();
  67612. if (isIdentity)
  67613. {
  67614. // If our translation doesn't involve any distortion, we can speed it up..
  67615. g2.point1.applyTransform (transform);
  67616. g2.point2.applyTransform (transform);
  67617. transform = AffineTransform::identity;
  67618. }
  67619. shapeToFill->fillAllWithGradient (destData, g2, transform, isIdentity);
  67620. }
  67621. else if (fillType.isTiledImage())
  67622. {
  67623. renderImage (image, fillType.image, fillType.image.getBounds(), fillType.transform, shapeToFill);
  67624. }
  67625. else
  67626. {
  67627. shapeToFill->fillAllWithColour (destData, fillType.colour.getPixelARGB(), replaceContents);
  67628. }
  67629. }
  67630. }
  67631. void renderImage (Image& destImage, const Image& sourceImage, const Rectangle<int>& srcClip,
  67632. const AffineTransform& t, const SoftwareRendererClasses::ClipRegionBase* const tiledFillClipRegion)
  67633. {
  67634. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  67635. const Image::BitmapData destData (destImage, 0, 0, destImage.getWidth(), destImage.getHeight(), true);
  67636. const Image::BitmapData srcData (sourceImage, srcClip.getX(), srcClip.getY(), srcClip.getWidth(), srcClip.getHeight());
  67637. const int alpha = fillType.colour.getAlpha();
  67638. const bool betterQuality = (interpolationQuality != Graphics::lowResamplingQuality);
  67639. if (transform.isOnlyTranslation())
  67640. {
  67641. // If our translation doesn't involve any distortion, just use a simple blit..
  67642. int tx = (int) (transform.getTranslationX() * 256.0f);
  67643. int ty = (int) (transform.getTranslationY() * 256.0f);
  67644. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  67645. {
  67646. tx = ((tx + 128) >> 8);
  67647. ty = ((ty + 128) >> 8);
  67648. if (tiledFillClipRegion != 0)
  67649. {
  67650. tiledFillClipRegion->renderImageUntransformed (destData, srcData, alpha, tx, ty, true);
  67651. }
  67652. else
  67653. {
  67654. SoftwareRendererClasses::ClipRegionBase::Ptr c (new SoftwareRendererClasses::ClipRegion_EdgeTable (Rectangle<int> (tx, ty, srcClip.getWidth(), srcClip.getHeight()).getIntersection (destImage.getBounds())));
  67655. c = clip->applyClipTo (c);
  67656. if (c != 0)
  67657. c->renderImageUntransformed (destData, srcData, alpha, tx, ty, false);
  67658. }
  67659. return;
  67660. }
  67661. }
  67662. if (transform.isSingularity())
  67663. return;
  67664. if (tiledFillClipRegion != 0)
  67665. {
  67666. tiledFillClipRegion->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, true);
  67667. }
  67668. else
  67669. {
  67670. Path p;
  67671. p.addRectangle (srcClip);
  67672. SoftwareRendererClasses::ClipRegionBase::Ptr c (clip->clone());
  67673. c = c->clipToPath (p, transform);
  67674. if (c != 0)
  67675. c->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, false);
  67676. }
  67677. }
  67678. SoftwareRendererClasses::ClipRegionBase::Ptr clip;
  67679. int xOffset, yOffset;
  67680. Font font;
  67681. FillType fillType;
  67682. Graphics::ResamplingQuality interpolationQuality;
  67683. private:
  67684. void cloneClipIfMultiplyReferenced()
  67685. {
  67686. if (clip->getReferenceCount() > 1)
  67687. clip = clip->clone();
  67688. }
  67689. SavedState& operator= (const SavedState&);
  67690. };
  67691. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_)
  67692. : image (image_)
  67693. {
  67694. currentState = new SavedState (image_.getBounds(), 0, 0);
  67695. }
  67696. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_, const int xOffset, const int yOffset,
  67697. const RectangleList& initialClip)
  67698. : image (image_)
  67699. {
  67700. currentState = new SavedState (initialClip, xOffset, yOffset);
  67701. }
  67702. LowLevelGraphicsSoftwareRenderer::~LowLevelGraphicsSoftwareRenderer()
  67703. {
  67704. }
  67705. bool LowLevelGraphicsSoftwareRenderer::isVectorDevice() const
  67706. {
  67707. return false;
  67708. }
  67709. void LowLevelGraphicsSoftwareRenderer::setOrigin (int x, int y)
  67710. {
  67711. currentState->setOrigin (x, y);
  67712. }
  67713. bool LowLevelGraphicsSoftwareRenderer::clipToRectangle (const Rectangle<int>& r)
  67714. {
  67715. return currentState->clipToRectangle (r);
  67716. }
  67717. bool LowLevelGraphicsSoftwareRenderer::clipToRectangleList (const RectangleList& clipRegion)
  67718. {
  67719. return currentState->clipToRectangleList (clipRegion);
  67720. }
  67721. void LowLevelGraphicsSoftwareRenderer::excludeClipRectangle (const Rectangle<int>& r)
  67722. {
  67723. currentState->excludeClipRectangle (r);
  67724. }
  67725. void LowLevelGraphicsSoftwareRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  67726. {
  67727. currentState->clipToPath (path, transform);
  67728. }
  67729. void LowLevelGraphicsSoftwareRenderer::clipToImageAlpha (const Image& sourceImage, const Rectangle<int>& srcClip, const AffineTransform& transform)
  67730. {
  67731. currentState->clipToImageAlpha (sourceImage, srcClip, transform);
  67732. }
  67733. bool LowLevelGraphicsSoftwareRenderer::clipRegionIntersects (const Rectangle<int>& r)
  67734. {
  67735. return currentState->clipRegionIntersects (r);
  67736. }
  67737. const Rectangle<int> LowLevelGraphicsSoftwareRenderer::getClipBounds() const
  67738. {
  67739. return currentState->getClipBounds();
  67740. }
  67741. bool LowLevelGraphicsSoftwareRenderer::isClipEmpty() const
  67742. {
  67743. return currentState->clip == 0;
  67744. }
  67745. void LowLevelGraphicsSoftwareRenderer::saveState()
  67746. {
  67747. stateStack.add (new SavedState (*currentState));
  67748. }
  67749. void LowLevelGraphicsSoftwareRenderer::restoreState()
  67750. {
  67751. SavedState* const top = stateStack.getLast();
  67752. if (top != 0)
  67753. {
  67754. currentState = top;
  67755. stateStack.removeLast (1, false);
  67756. }
  67757. else
  67758. {
  67759. jassertfalse; // trying to pop with an empty stack!
  67760. }
  67761. }
  67762. void LowLevelGraphicsSoftwareRenderer::setFill (const FillType& fillType)
  67763. {
  67764. currentState->fillType = fillType;
  67765. }
  67766. void LowLevelGraphicsSoftwareRenderer::setOpacity (float newOpacity)
  67767. {
  67768. currentState->fillType.setOpacity (newOpacity);
  67769. }
  67770. void LowLevelGraphicsSoftwareRenderer::setInterpolationQuality (Graphics::ResamplingQuality quality)
  67771. {
  67772. currentState->interpolationQuality = quality;
  67773. }
  67774. void LowLevelGraphicsSoftwareRenderer::fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  67775. {
  67776. currentState->fillRect (image, r, replaceExistingContents);
  67777. }
  67778. void LowLevelGraphicsSoftwareRenderer::fillPath (const Path& path, const AffineTransform& transform)
  67779. {
  67780. currentState->fillPath (image, path, transform);
  67781. }
  67782. void LowLevelGraphicsSoftwareRenderer::drawImage (const Image& sourceImage, const Rectangle<int>& srcClip,
  67783. const AffineTransform& transform, const bool fillEntireClipAsTiles)
  67784. {
  67785. jassert (sourceImage.getBounds().contains (srcClip));
  67786. currentState->renderImage (image, sourceImage, srcClip, transform,
  67787. fillEntireClipAsTiles ? currentState->clip : 0);
  67788. }
  67789. void LowLevelGraphicsSoftwareRenderer::drawLine (const Line <float>& line)
  67790. {
  67791. Path p;
  67792. p.addLineSegment (line, 1.0f);
  67793. fillPath (p, AffineTransform::identity);
  67794. }
  67795. void LowLevelGraphicsSoftwareRenderer::drawVerticalLine (const int x, float top, float bottom)
  67796. {
  67797. if (bottom > top)
  67798. currentState->fillRect (image, Rectangle<float> ((float) x, top, 1.0f, bottom - top));
  67799. }
  67800. void LowLevelGraphicsSoftwareRenderer::drawHorizontalLine (const int y, float left, float right)
  67801. {
  67802. if (right > left)
  67803. currentState->fillRect (image, Rectangle<float> (left, (float) y, right - left, 1.0f));
  67804. }
  67805. class LowLevelGraphicsSoftwareRenderer::CachedGlyph
  67806. {
  67807. public:
  67808. CachedGlyph() : glyph (0), lastAccessCount (0) {}
  67809. ~CachedGlyph() {}
  67810. void draw (SavedState& state, Image& image, const float x, const float y) const
  67811. {
  67812. if (edgeTable != 0)
  67813. state.fillEdgeTable (image, *edgeTable, x, roundToInt (y));
  67814. }
  67815. void generate (const Font& newFont, const int glyphNumber)
  67816. {
  67817. font = newFont;
  67818. glyph = glyphNumber;
  67819. edgeTable = 0;
  67820. Path glyphPath;
  67821. font.getTypeface()->getOutlineForGlyph (glyphNumber, glyphPath);
  67822. if (! glyphPath.isEmpty())
  67823. {
  67824. const float fontHeight = font.getHeight();
  67825. const AffineTransform transform (AffineTransform::scale (fontHeight * font.getHorizontalScale(), fontHeight)
  67826. .translated (0.0f, -0.5f));
  67827. edgeTable = new EdgeTable (glyphPath.getBoundsTransformed (transform).getSmallestIntegerContainer().expanded (1, 0),
  67828. glyphPath, transform);
  67829. }
  67830. }
  67831. int glyph, lastAccessCount;
  67832. Font font;
  67833. juce_UseDebuggingNewOperator
  67834. private:
  67835. ScopedPointer <EdgeTable> edgeTable;
  67836. CachedGlyph (const CachedGlyph&);
  67837. CachedGlyph& operator= (const CachedGlyph&);
  67838. };
  67839. class LowLevelGraphicsSoftwareRenderer::GlyphCache : private DeletedAtShutdown
  67840. {
  67841. public:
  67842. GlyphCache()
  67843. : accessCounter (0), hits (0), misses (0)
  67844. {
  67845. for (int i = 120; --i >= 0;)
  67846. glyphs.add (new CachedGlyph());
  67847. }
  67848. ~GlyphCache()
  67849. {
  67850. clearSingletonInstance();
  67851. }
  67852. juce_DeclareSingleton_SingleThreaded_Minimal (GlyphCache);
  67853. void drawGlyph (SavedState& state, Image& image, const Font& font, const int glyphNumber, float x, float y)
  67854. {
  67855. ++accessCounter;
  67856. int oldestCounter = std::numeric_limits<int>::max();
  67857. CachedGlyph* oldest = 0;
  67858. for (int i = glyphs.size(); --i >= 0;)
  67859. {
  67860. CachedGlyph* const glyph = glyphs.getUnchecked (i);
  67861. if (glyph->glyph == glyphNumber && glyph->font == font)
  67862. {
  67863. ++hits;
  67864. glyph->lastAccessCount = accessCounter;
  67865. glyph->draw (state, image, x, y);
  67866. return;
  67867. }
  67868. if (glyph->lastAccessCount <= oldestCounter)
  67869. {
  67870. oldestCounter = glyph->lastAccessCount;
  67871. oldest = glyph;
  67872. }
  67873. }
  67874. if (hits + ++misses > (glyphs.size() << 4))
  67875. {
  67876. if (misses * 2 > hits)
  67877. {
  67878. for (int i = 32; --i >= 0;)
  67879. glyphs.add (new CachedGlyph());
  67880. }
  67881. hits = misses = 0;
  67882. oldest = glyphs.getLast();
  67883. }
  67884. jassert (oldest != 0);
  67885. oldest->lastAccessCount = accessCounter;
  67886. oldest->generate (font, glyphNumber);
  67887. oldest->draw (state, image, x, y);
  67888. }
  67889. juce_UseDebuggingNewOperator
  67890. private:
  67891. friend class OwnedArray <CachedGlyph>;
  67892. OwnedArray <CachedGlyph> glyphs;
  67893. int accessCounter, hits, misses;
  67894. GlyphCache (const GlyphCache&);
  67895. GlyphCache& operator= (const GlyphCache&);
  67896. };
  67897. juce_ImplementSingleton_SingleThreaded (LowLevelGraphicsSoftwareRenderer::GlyphCache);
  67898. void LowLevelGraphicsSoftwareRenderer::setFont (const Font& newFont)
  67899. {
  67900. currentState->font = newFont;
  67901. }
  67902. const Font LowLevelGraphicsSoftwareRenderer::getFont()
  67903. {
  67904. return currentState->font;
  67905. }
  67906. void LowLevelGraphicsSoftwareRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  67907. {
  67908. Font& f = currentState->font;
  67909. if (transform.isOnlyTranslation())
  67910. {
  67911. GlyphCache::getInstance()->drawGlyph (*currentState, image, f, glyphNumber,
  67912. transform.getTranslationX(),
  67913. transform.getTranslationY());
  67914. }
  67915. else
  67916. {
  67917. Path p;
  67918. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  67919. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight()).followedBy (transform));
  67920. }
  67921. }
  67922. #if JUCE_MSVC
  67923. #pragma warning (pop)
  67924. #if JUCE_DEBUG
  67925. #pragma optimize ("", on) // resets optimisations to the project defaults
  67926. #endif
  67927. #endif
  67928. END_JUCE_NAMESPACE
  67929. /*** End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  67930. /*** Start of inlined file: juce_RectanglePlacement.cpp ***/
  67931. BEGIN_JUCE_NAMESPACE
  67932. RectanglePlacement::RectanglePlacement (const RectanglePlacement& other) throw()
  67933. : flags (other.flags)
  67934. {
  67935. }
  67936. RectanglePlacement& RectanglePlacement::operator= (const RectanglePlacement& other) throw()
  67937. {
  67938. flags = other.flags;
  67939. return *this;
  67940. }
  67941. void RectanglePlacement::applyTo (double& x, double& y,
  67942. double& w, double& h,
  67943. const double dx, const double dy,
  67944. const double dw, const double dh) const throw()
  67945. {
  67946. if (w == 0 || h == 0)
  67947. return;
  67948. if ((flags & stretchToFit) != 0)
  67949. {
  67950. x = dx;
  67951. y = dy;
  67952. w = dw;
  67953. h = dh;
  67954. }
  67955. else
  67956. {
  67957. double scale = (flags & fillDestination) != 0 ? jmax (dw / w, dh / h)
  67958. : jmin (dw / w, dh / h);
  67959. if ((flags & onlyReduceInSize) != 0)
  67960. scale = jmin (scale, 1.0);
  67961. if ((flags & onlyIncreaseInSize) != 0)
  67962. scale = jmax (scale, 1.0);
  67963. w *= scale;
  67964. h *= scale;
  67965. if ((flags & xLeft) != 0)
  67966. x = dx;
  67967. else if ((flags & xRight) != 0)
  67968. x = dx + dw - w;
  67969. else
  67970. x = dx + (dw - w) * 0.5;
  67971. if ((flags & yTop) != 0)
  67972. y = dy;
  67973. else if ((flags & yBottom) != 0)
  67974. y = dy + dh - h;
  67975. else
  67976. y = dy + (dh - h) * 0.5;
  67977. }
  67978. }
  67979. const AffineTransform RectanglePlacement::getTransformToFit (float x, float y,
  67980. float w, float h,
  67981. const float dx, const float dy,
  67982. const float dw, const float dh) const throw()
  67983. {
  67984. if (w == 0 || h == 0)
  67985. return AffineTransform::identity;
  67986. const float scaleX = dw / w;
  67987. const float scaleY = dh / h;
  67988. if ((flags & stretchToFit) != 0)
  67989. return AffineTransform::translation (-x, -y)
  67990. .scaled (scaleX, scaleY)
  67991. .translated (dx, dy);
  67992. float scale = (flags & fillDestination) != 0 ? jmax (scaleX, scaleY)
  67993. : jmin (scaleX, scaleY);
  67994. if ((flags & onlyReduceInSize) != 0)
  67995. scale = jmin (scale, 1.0f);
  67996. if ((flags & onlyIncreaseInSize) != 0)
  67997. scale = jmax (scale, 1.0f);
  67998. w *= scale;
  67999. h *= scale;
  68000. float newX = dx;
  68001. if ((flags & xRight) != 0)
  68002. newX += dw - w; // right
  68003. else if ((flags & xLeft) == 0)
  68004. newX += (dw - w) / 2.0f; // centre
  68005. float newY = dy;
  68006. if ((flags & yBottom) != 0)
  68007. newY += dh - h; // bottom
  68008. else if ((flags & yTop) == 0)
  68009. newY += (dh - h) / 2.0f; // centre
  68010. return AffineTransform::translation (-x, -y)
  68011. .scaled (scale, scale)
  68012. .translated (newX, newY);
  68013. }
  68014. END_JUCE_NAMESPACE
  68015. /*** End of inlined file: juce_RectanglePlacement.cpp ***/
  68016. /*** Start of inlined file: juce_Drawable.cpp ***/
  68017. BEGIN_JUCE_NAMESPACE
  68018. Drawable::RenderingContext::RenderingContext (Graphics& g_,
  68019. const AffineTransform& transform_,
  68020. const float opacity_) throw()
  68021. : g (g_),
  68022. transform (transform_),
  68023. opacity (opacity_)
  68024. {
  68025. }
  68026. Drawable::Drawable()
  68027. : parent (0)
  68028. {
  68029. }
  68030. Drawable::~Drawable()
  68031. {
  68032. }
  68033. void Drawable::draw (Graphics& g, const float opacity, const AffineTransform& transform) const
  68034. {
  68035. render (RenderingContext (g, transform, opacity));
  68036. }
  68037. void Drawable::drawAt (Graphics& g, const float x, const float y, const float opacity) const
  68038. {
  68039. draw (g, opacity, AffineTransform::translation (x, y));
  68040. }
  68041. void Drawable::drawWithin (Graphics& g,
  68042. const int destX,
  68043. const int destY,
  68044. const int destW,
  68045. const int destH,
  68046. const RectanglePlacement& placement,
  68047. const float opacity) const
  68048. {
  68049. if (destW > 0 && destH > 0)
  68050. {
  68051. Rectangle<float> bounds (getBounds());
  68052. draw (g, opacity,
  68053. placement.getTransformToFit (bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight(),
  68054. (float) destX, (float) destY,
  68055. (float) destW, (float) destH));
  68056. }
  68057. }
  68058. Drawable* Drawable::createFromImageData (const void* data, const size_t numBytes)
  68059. {
  68060. Drawable* result = 0;
  68061. Image image (ImageFileFormat::loadFrom (data, (int) numBytes));
  68062. if (image.isValid())
  68063. {
  68064. DrawableImage* const di = new DrawableImage();
  68065. di->setImage (image);
  68066. result = di;
  68067. }
  68068. else
  68069. {
  68070. const String asString (String::createStringFromData (data, (int) numBytes));
  68071. XmlDocument doc (asString);
  68072. ScopedPointer <XmlElement> outer (doc.getDocumentElement (true));
  68073. if (outer != 0 && outer->hasTagName ("svg"))
  68074. {
  68075. ScopedPointer <XmlElement> svg (doc.getDocumentElement());
  68076. if (svg != 0)
  68077. result = Drawable::createFromSVG (*svg);
  68078. }
  68079. }
  68080. return result;
  68081. }
  68082. Drawable* Drawable::createFromImageDataStream (InputStream& dataSource)
  68083. {
  68084. MemoryBlock mb;
  68085. dataSource.readIntoMemoryBlock (mb);
  68086. return createFromImageData (mb.getData(), mb.getSize());
  68087. }
  68088. Drawable* Drawable::createFromImageFile (const File& file)
  68089. {
  68090. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  68091. return fin != 0 ? createFromImageDataStream (*fin) : 0;
  68092. }
  68093. Drawable* Drawable::createFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  68094. {
  68095. return createChildFromValueTree (0, tree, imageProvider);
  68096. }
  68097. Drawable* Drawable::createChildFromValueTree (DrawableComposite* parent, const ValueTree& tree, ImageProvider* imageProvider)
  68098. {
  68099. const Identifier type (tree.getType());
  68100. Drawable* d = 0;
  68101. if (type == DrawablePath::valueTreeType)
  68102. d = new DrawablePath();
  68103. else if (type == DrawableComposite::valueTreeType)
  68104. d = new DrawableComposite();
  68105. else if (type == DrawableImage::valueTreeType)
  68106. d = new DrawableImage();
  68107. else if (type == DrawableText::valueTreeType)
  68108. d = new DrawableText();
  68109. if (d != 0)
  68110. {
  68111. d->parent = parent;
  68112. d->refreshFromValueTree (tree, imageProvider);
  68113. }
  68114. return d;
  68115. }
  68116. const Identifier Drawable::ValueTreeWrapperBase::idProperty ("id");
  68117. const Identifier Drawable::ValueTreeWrapperBase::type ("type");
  68118. const Identifier Drawable::ValueTreeWrapperBase::gradientPoint1 ("point1");
  68119. const Identifier Drawable::ValueTreeWrapperBase::gradientPoint2 ("point2");
  68120. const Identifier Drawable::ValueTreeWrapperBase::colour ("colour");
  68121. const Identifier Drawable::ValueTreeWrapperBase::radial ("radial");
  68122. const Identifier Drawable::ValueTreeWrapperBase::colours ("colours");
  68123. const Identifier Drawable::ValueTreeWrapperBase::imageId ("imageId");
  68124. const Identifier Drawable::ValueTreeWrapperBase::imageOpacity ("imageOpacity");
  68125. Drawable::ValueTreeWrapperBase::ValueTreeWrapperBase (const ValueTree& state_)
  68126. : state (state_)
  68127. {
  68128. }
  68129. Drawable::ValueTreeWrapperBase::~ValueTreeWrapperBase()
  68130. {
  68131. }
  68132. const String Drawable::ValueTreeWrapperBase::getID() const
  68133. {
  68134. return state [idProperty];
  68135. }
  68136. void Drawable::ValueTreeWrapperBase::setID (const String& newID, UndoManager* const undoManager)
  68137. {
  68138. if (newID.isEmpty())
  68139. state.removeProperty (idProperty, undoManager);
  68140. else
  68141. state.setProperty (idProperty, newID, undoManager);
  68142. }
  68143. const FillType Drawable::ValueTreeWrapperBase::readFillType (const ValueTree& v, RelativePoint* const gp1, RelativePoint* const gp2,
  68144. RelativeCoordinate::NamedCoordinateFinder* const nameFinder, ImageProvider* imageProvider)
  68145. {
  68146. const String newType (v[type].toString());
  68147. if (newType == "solid")
  68148. {
  68149. const String colourString (v [colour].toString());
  68150. return FillType (Colour (colourString.isEmpty() ? (uint32) 0xff000000
  68151. : (uint32) colourString.getHexValue32()));
  68152. }
  68153. else if (newType == "gradient")
  68154. {
  68155. RelativePoint p1 (v [gradientPoint1]), p2 (v [gradientPoint2]);
  68156. ColourGradient g;
  68157. if (gp1 != 0)
  68158. *gp1 = p1;
  68159. if (gp2 != 0)
  68160. *gp2 = p2;
  68161. g.point1 = p1.resolve (nameFinder);
  68162. g.point2 = p2.resolve (nameFinder);
  68163. g.isRadial = v[radial];
  68164. StringArray colourSteps;
  68165. colourSteps.addTokens (v[colours].toString(), false);
  68166. for (int i = 0; i < colourSteps.size() / 2; ++i)
  68167. g.addColour (colourSteps[i * 2].getDoubleValue(),
  68168. Colour ((uint32) colourSteps[i * 2 + 1].getHexValue32()));
  68169. return FillType (g);
  68170. }
  68171. else if (newType == "image")
  68172. {
  68173. Image im;
  68174. if (imageProvider != 0)
  68175. im = imageProvider->getImageForIdentifier (v[imageId]);
  68176. FillType f (im, AffineTransform::identity);
  68177. f.setOpacity ((float) v.getProperty (imageOpacity, 1.0f));
  68178. return f;
  68179. }
  68180. jassertfalse;
  68181. return FillType();
  68182. }
  68183. void Drawable::ValueTreeWrapperBase::writeFillType (ValueTree& v, const FillType& fillType,
  68184. const RelativePoint* const gp1, const RelativePoint* const gp2,
  68185. ImageProvider* imageProvider, UndoManager* const undoManager)
  68186. {
  68187. if (fillType.isColour())
  68188. {
  68189. v.setProperty (type, "solid", undoManager);
  68190. v.setProperty (colour, String::toHexString ((int) fillType.colour.getARGB()), undoManager);
  68191. }
  68192. else if (fillType.isGradient())
  68193. {
  68194. v.setProperty (type, "gradient", undoManager);
  68195. v.setProperty (gradientPoint1, gp1 != 0 ? gp1->toString() : fillType.gradient->point1.toString(), undoManager);
  68196. v.setProperty (gradientPoint2, gp2 != 0 ? gp2->toString() : fillType.gradient->point2.toString(), undoManager);
  68197. v.setProperty (radial, fillType.gradient->isRadial, undoManager);
  68198. String s;
  68199. for (int i = 0; i < fillType.gradient->getNumColours(); ++i)
  68200. s << ' ' << fillType.gradient->getColourPosition (i)
  68201. << ' ' << String::toHexString ((int) fillType.gradient->getColour(i).getARGB());
  68202. v.setProperty (colours, s.trimStart(), undoManager);
  68203. }
  68204. else if (fillType.isTiledImage())
  68205. {
  68206. v.setProperty (type, "image", undoManager);
  68207. if (imageProvider != 0)
  68208. v.setProperty (imageId, imageProvider->getIdentifierForImage (fillType.image), undoManager);
  68209. if (fillType.getOpacity() < 1.0f)
  68210. v.setProperty (imageOpacity, fillType.getOpacity(), undoManager);
  68211. else
  68212. v.removeProperty (imageOpacity, undoManager);
  68213. }
  68214. else
  68215. {
  68216. jassertfalse;
  68217. }
  68218. }
  68219. END_JUCE_NAMESPACE
  68220. /*** End of inlined file: juce_Drawable.cpp ***/
  68221. /*** Start of inlined file: juce_DrawableComposite.cpp ***/
  68222. BEGIN_JUCE_NAMESPACE
  68223. DrawableComposite::DrawableComposite()
  68224. : bounds (Point<float>(), Point<float> (100.0f, 0.0f), Point<float> (0.0f, 100.0f))
  68225. {
  68226. setContentArea (RelativeRectangle (RelativeCoordinate (0.0, true),
  68227. RelativeCoordinate (100.0, true),
  68228. RelativeCoordinate (0.0, false),
  68229. RelativeCoordinate (100.0, false)));
  68230. }
  68231. DrawableComposite::DrawableComposite (const DrawableComposite& other)
  68232. {
  68233. bounds = other.bounds;
  68234. for (int i = 0; i < other.drawables.size(); ++i)
  68235. drawables.add (other.drawables.getUnchecked(i)->createCopy());
  68236. markersX.addCopiesOf (other.markersX);
  68237. markersY.addCopiesOf (other.markersY);
  68238. }
  68239. DrawableComposite::~DrawableComposite()
  68240. {
  68241. }
  68242. void DrawableComposite::insertDrawable (Drawable* drawable, const int index)
  68243. {
  68244. if (drawable != 0)
  68245. {
  68246. jassert (! drawables.contains (drawable)); // trying to add a drawable that's already in here!
  68247. jassert (drawable->parent == 0); // A drawable can only live inside one parent at a time!
  68248. drawables.insert (index, drawable);
  68249. drawable->parent = this;
  68250. }
  68251. }
  68252. void DrawableComposite::insertDrawable (const Drawable& drawable, const int index)
  68253. {
  68254. insertDrawable (drawable.createCopy(), index);
  68255. }
  68256. void DrawableComposite::removeDrawable (const int index, const bool deleteDrawable)
  68257. {
  68258. drawables.remove (index, deleteDrawable);
  68259. }
  68260. Drawable* DrawableComposite::getDrawableWithName (const String& name) const throw()
  68261. {
  68262. for (int i = drawables.size(); --i >= 0;)
  68263. if (drawables.getUnchecked(i)->getName() == name)
  68264. return drawables.getUnchecked(i);
  68265. return 0;
  68266. }
  68267. void DrawableComposite::bringToFront (const int index)
  68268. {
  68269. if (index >= 0 && index < drawables.size() - 1)
  68270. drawables.move (index, -1);
  68271. }
  68272. void DrawableComposite::setBoundingBox (const RelativeParallelogram& newBoundingBox)
  68273. {
  68274. bounds = newBoundingBox;
  68275. }
  68276. DrawableComposite::Marker::Marker (const DrawableComposite::Marker& other)
  68277. : name (other.name), position (other.position)
  68278. {
  68279. }
  68280. DrawableComposite::Marker::Marker (const String& name_, const RelativeCoordinate& position_)
  68281. : name (name_), position (position_)
  68282. {
  68283. }
  68284. bool DrawableComposite::Marker::operator!= (const DrawableComposite::Marker& other) const throw()
  68285. {
  68286. return name != other.name || position != other.position;
  68287. }
  68288. const char* const DrawableComposite::contentLeftMarkerName ("left");
  68289. const char* const DrawableComposite::contentRightMarkerName ("right");
  68290. const char* const DrawableComposite::contentTopMarkerName ("top");
  68291. const char* const DrawableComposite::contentBottomMarkerName ("bottom");
  68292. const RelativeRectangle DrawableComposite::getContentArea() const
  68293. {
  68294. jassert (markersX.size() >= 2 && getMarker (true, 0)->name == contentLeftMarkerName && getMarker (true, 1)->name == contentRightMarkerName);
  68295. jassert (markersY.size() >= 2 && getMarker (false, 0)->name == contentTopMarkerName && getMarker (false, 1)->name == contentBottomMarkerName);
  68296. return RelativeRectangle (markersX.getUnchecked(0)->position, markersX.getUnchecked(1)->position,
  68297. markersY.getUnchecked(0)->position, markersY.getUnchecked(1)->position);
  68298. }
  68299. void DrawableComposite::setContentArea (const RelativeRectangle& newArea)
  68300. {
  68301. setMarker (contentLeftMarkerName, true, newArea.left);
  68302. setMarker (contentRightMarkerName, true, newArea.right);
  68303. setMarker (contentTopMarkerName, false, newArea.top);
  68304. setMarker (contentBottomMarkerName, false, newArea.bottom);
  68305. }
  68306. void DrawableComposite::resetBoundingBoxToContentArea()
  68307. {
  68308. const RelativeRectangle content (getContentArea());
  68309. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  68310. RelativePoint (content.right, content.top),
  68311. RelativePoint (content.left, content.bottom)));
  68312. }
  68313. void DrawableComposite::resetContentAreaAndBoundingBoxToFitChildren()
  68314. {
  68315. const Rectangle<float> bounds (getUntransformedBounds (false));
  68316. setContentArea (RelativeRectangle (RelativeCoordinate (bounds.getX(), true),
  68317. RelativeCoordinate (bounds.getRight(), true),
  68318. RelativeCoordinate (bounds.getY(), false),
  68319. RelativeCoordinate (bounds.getBottom(), false)));
  68320. resetBoundingBoxToContentArea();
  68321. }
  68322. int DrawableComposite::getNumMarkers (const bool xAxis) const throw()
  68323. {
  68324. return (xAxis ? markersX : markersY).size();
  68325. }
  68326. const DrawableComposite::Marker* DrawableComposite::getMarker (const bool xAxis, const int index) const throw()
  68327. {
  68328. return (xAxis ? markersX : markersY) [index];
  68329. }
  68330. void DrawableComposite::setMarker (const String& name, const bool xAxis, const RelativeCoordinate& position)
  68331. {
  68332. OwnedArray <Marker>& markers = (xAxis ? markersX : markersY);
  68333. for (int i = 0; i < markers.size(); ++i)
  68334. {
  68335. Marker* const m = markers.getUnchecked(i);
  68336. if (m->name == name)
  68337. {
  68338. if (m->position != position)
  68339. {
  68340. m->position = position;
  68341. invalidatePoints();
  68342. }
  68343. return;
  68344. }
  68345. }
  68346. (xAxis ? markersX : markersY).add (new Marker (name, position));
  68347. invalidatePoints();
  68348. }
  68349. void DrawableComposite::removeMarker (const bool xAxis, const int index)
  68350. {
  68351. jassert (index >= 2);
  68352. if (index >= 2)
  68353. (xAxis ? markersX : markersY).remove (index);
  68354. }
  68355. const AffineTransform DrawableComposite::calculateTransform() const
  68356. {
  68357. Point<float> resolved[3];
  68358. bounds.resolveThreePoints (resolved, parent);
  68359. const Rectangle<float> content (getContentArea().resolve (parent));
  68360. return AffineTransform::fromTargetPoints (content.getX(), content.getY(), resolved[0].getX(), resolved[0].getY(),
  68361. content.getRight(), content.getY(), resolved[1].getX(), resolved[1].getY(),
  68362. content.getX(), content.getBottom(), resolved[2].getX(), resolved[2].getY());
  68363. }
  68364. void DrawableComposite::render (const Drawable::RenderingContext& context) const
  68365. {
  68366. if (drawables.size() > 0 && context.opacity > 0)
  68367. {
  68368. if (context.opacity >= 1.0f || drawables.size() == 1)
  68369. {
  68370. Drawable::RenderingContext contextCopy (context);
  68371. contextCopy.transform = calculateTransform().followedBy (context.transform);
  68372. for (int i = 0; i < drawables.size(); ++i)
  68373. drawables.getUnchecked(i)->render (contextCopy);
  68374. }
  68375. else
  68376. {
  68377. // To correctly render a whole composite layer with an overall transparency,
  68378. // we need to render everything opaquely into a temp buffer, then blend that
  68379. // with the target opacity...
  68380. const Rectangle<int> clipBounds (context.g.getClipBounds());
  68381. Image tempImage (Image::ARGB, clipBounds.getWidth(), clipBounds.getHeight(), true);
  68382. {
  68383. Graphics tempG (tempImage);
  68384. tempG.setOrigin (-clipBounds.getX(), -clipBounds.getY());
  68385. Drawable::RenderingContext tempContext (tempG, context.transform, 1.0f);
  68386. render (tempContext);
  68387. }
  68388. context.g.setOpacity (context.opacity);
  68389. context.g.drawImageAt (tempImage, clipBounds.getX(), clipBounds.getY());
  68390. }
  68391. }
  68392. }
  68393. const RelativeCoordinate DrawableComposite::findNamedCoordinate (const String& objectName, const String& edge) const
  68394. {
  68395. if (objectName == RelativeCoordinate::Strings::parent)
  68396. {
  68397. if (edge == RelativeCoordinate::Strings::right)
  68398. {
  68399. jassertfalse; // a Drawable doesn't have a fixed right-hand edge - use a marker instead if you need a point of reference.
  68400. return RelativeCoordinate (100.0, true);
  68401. }
  68402. if (edge == RelativeCoordinate::Strings::bottom)
  68403. {
  68404. jassertfalse; // a Drawable doesn't have a fixed bottom edge - use a marker instead if you need a point of reference.
  68405. return RelativeCoordinate (100.0, false);
  68406. }
  68407. }
  68408. int i;
  68409. for (i = 0; i < markersX.size(); ++i)
  68410. {
  68411. Marker* const m = markersX.getUnchecked(i);
  68412. if (m->name == objectName)
  68413. return m->position;
  68414. }
  68415. for (i = 0; i < markersY.size(); ++i)
  68416. {
  68417. Marker* const m = markersY.getUnchecked(i);
  68418. if (m->name == objectName)
  68419. return m->position;
  68420. }
  68421. return RelativeCoordinate();
  68422. }
  68423. const Rectangle<float> DrawableComposite::getUntransformedBounds (const bool includeMarkers) const
  68424. {
  68425. Rectangle<float> bounds;
  68426. int i;
  68427. for (i = 0; i < drawables.size(); ++i)
  68428. bounds = bounds.getUnion (drawables.getUnchecked(i)->getBounds());
  68429. if (includeMarkers)
  68430. {
  68431. if (markersX.size() > 0)
  68432. {
  68433. float minX = std::numeric_limits<float>::max();
  68434. float maxX = std::numeric_limits<float>::min();
  68435. for (i = markersX.size(); --i >= 0;)
  68436. {
  68437. const Marker* m = markersX.getUnchecked(i);
  68438. const float pos = (float) m->position.resolve (parent);
  68439. minX = jmin (minX, pos);
  68440. maxX = jmax (maxX, pos);
  68441. }
  68442. if (minX <= maxX)
  68443. {
  68444. if (bounds.getHeight() > 0)
  68445. {
  68446. minX = jmin (minX, bounds.getX());
  68447. maxX = jmax (maxX, bounds.getRight());
  68448. }
  68449. bounds.setLeft (minX);
  68450. bounds.setWidth (maxX - minX);
  68451. }
  68452. }
  68453. if (markersY.size() > 0)
  68454. {
  68455. float minY = std::numeric_limits<float>::max();
  68456. float maxY = std::numeric_limits<float>::min();
  68457. for (i = markersY.size(); --i >= 0;)
  68458. {
  68459. const Marker* m = markersY.getUnchecked(i);
  68460. const float pos = (float) m->position.resolve (parent);
  68461. minY = jmin (minY, pos);
  68462. maxY = jmax (maxY, pos);
  68463. }
  68464. if (minY <= maxY)
  68465. {
  68466. if (bounds.getHeight() > 0)
  68467. {
  68468. minY = jmin (minY, bounds.getY());
  68469. maxY = jmax (maxY, bounds.getBottom());
  68470. }
  68471. bounds.setTop (minY);
  68472. bounds.setHeight (maxY - minY);
  68473. }
  68474. }
  68475. }
  68476. return bounds;
  68477. }
  68478. const Rectangle<float> DrawableComposite::getBounds() const
  68479. {
  68480. return getUntransformedBounds (true).transformed (calculateTransform());
  68481. }
  68482. bool DrawableComposite::hitTest (float x, float y) const
  68483. {
  68484. calculateTransform().inverted().transformPoint (x, y);
  68485. for (int i = 0; i < drawables.size(); ++i)
  68486. if (drawables.getUnchecked(i)->hitTest (x, y))
  68487. return true;
  68488. return false;
  68489. }
  68490. Drawable* DrawableComposite::createCopy() const
  68491. {
  68492. return new DrawableComposite (*this);
  68493. }
  68494. void DrawableComposite::invalidatePoints()
  68495. {
  68496. for (int i = 0; i < drawables.size(); ++i)
  68497. drawables.getUnchecked(i)->invalidatePoints();
  68498. }
  68499. const Identifier DrawableComposite::valueTreeType ("Group");
  68500. const Identifier DrawableComposite::ValueTreeWrapper::topLeft ("topLeft");
  68501. const Identifier DrawableComposite::ValueTreeWrapper::topRight ("topRight");
  68502. const Identifier DrawableComposite::ValueTreeWrapper::bottomLeft ("bottomLeft");
  68503. const Identifier DrawableComposite::ValueTreeWrapper::childGroupTag ("Drawables");
  68504. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagX ("MarkersX");
  68505. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagY ("MarkersY");
  68506. const Identifier DrawableComposite::ValueTreeWrapper::markerTag ("Marker");
  68507. const Identifier DrawableComposite::ValueTreeWrapper::nameProperty ("name");
  68508. const Identifier DrawableComposite::ValueTreeWrapper::posProperty ("position");
  68509. DrawableComposite::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  68510. : ValueTreeWrapperBase (state_)
  68511. {
  68512. jassert (state.hasType (valueTreeType));
  68513. }
  68514. ValueTree DrawableComposite::ValueTreeWrapper::getChildList() const
  68515. {
  68516. return state.getChildWithName (childGroupTag);
  68517. }
  68518. ValueTree DrawableComposite::ValueTreeWrapper::getChildListCreating (UndoManager* undoManager)
  68519. {
  68520. return state.getOrCreateChildWithName (childGroupTag, undoManager);
  68521. }
  68522. int DrawableComposite::ValueTreeWrapper::getNumDrawables() const
  68523. {
  68524. return getChildList().getNumChildren();
  68525. }
  68526. ValueTree DrawableComposite::ValueTreeWrapper::getDrawableState (int index) const
  68527. {
  68528. return getChildList().getChild (index);
  68529. }
  68530. ValueTree DrawableComposite::ValueTreeWrapper::getDrawableWithId (const String& objectId, bool recursive) const
  68531. {
  68532. if (getID() == objectId)
  68533. return state;
  68534. if (! recursive)
  68535. {
  68536. return getChildList().getChildWithProperty (idProperty, objectId);
  68537. }
  68538. else
  68539. {
  68540. const ValueTree childList (getChildList());
  68541. for (int i = getNumDrawables(); --i >= 0;)
  68542. {
  68543. const ValueTree& child = childList.getChild (i);
  68544. if (child [Drawable::ValueTreeWrapperBase::idProperty] == objectId)
  68545. return child;
  68546. if (child.hasType (DrawableComposite::valueTreeType))
  68547. {
  68548. ValueTree v (DrawableComposite::ValueTreeWrapper (child).getDrawableWithId (objectId, true));
  68549. if (v.isValid())
  68550. return v;
  68551. }
  68552. }
  68553. return ValueTree::invalid;
  68554. }
  68555. }
  68556. int DrawableComposite::ValueTreeWrapper::indexOfDrawable (const ValueTree& item) const
  68557. {
  68558. return getChildList().indexOf (item);
  68559. }
  68560. void DrawableComposite::ValueTreeWrapper::addDrawable (const ValueTree& newDrawableState, int index, UndoManager* undoManager)
  68561. {
  68562. getChildListCreating (undoManager).addChild (newDrawableState, index, undoManager);
  68563. }
  68564. void DrawableComposite::ValueTreeWrapper::moveDrawableOrder (int currentIndex, int newIndex, UndoManager* undoManager)
  68565. {
  68566. getChildListCreating (undoManager).moveChild (currentIndex, newIndex, undoManager);
  68567. }
  68568. void DrawableComposite::ValueTreeWrapper::removeDrawable (const ValueTree& child, UndoManager* undoManager)
  68569. {
  68570. getChildList().removeChild (child, undoManager);
  68571. }
  68572. const RelativeParallelogram DrawableComposite::ValueTreeWrapper::getBoundingBox() const
  68573. {
  68574. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  68575. state.getProperty (topRight, "100, 0"),
  68576. state.getProperty (bottomLeft, "0, 100"));
  68577. }
  68578. void DrawableComposite::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  68579. {
  68580. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  68581. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  68582. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  68583. }
  68584. void DrawableComposite::ValueTreeWrapper::resetBoundingBoxToContentArea (UndoManager* undoManager)
  68585. {
  68586. const RelativeRectangle content (getContentArea());
  68587. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  68588. RelativePoint (content.right, content.top),
  68589. RelativePoint (content.left, content.bottom)), undoManager);
  68590. }
  68591. const RelativeRectangle DrawableComposite::ValueTreeWrapper::getContentArea() const
  68592. {
  68593. return RelativeRectangle (getMarker (true, getMarkerState (true, 0)).position,
  68594. getMarker (true, getMarkerState (true, 1)).position,
  68595. getMarker (false, getMarkerState (false, 0)).position,
  68596. getMarker (false, getMarkerState (false, 1)).position);
  68597. }
  68598. void DrawableComposite::ValueTreeWrapper::setContentArea (const RelativeRectangle& newArea, UndoManager* undoManager)
  68599. {
  68600. setMarker (true, Marker (contentLeftMarkerName, newArea.left), undoManager);
  68601. setMarker (true, Marker (contentRightMarkerName, newArea.right), undoManager);
  68602. setMarker (false, Marker (contentTopMarkerName, newArea.top), undoManager);
  68603. setMarker (false, Marker (contentBottomMarkerName, newArea.bottom), undoManager);
  68604. }
  68605. ValueTree DrawableComposite::ValueTreeWrapper::getMarkerList (bool xAxis) const
  68606. {
  68607. return state.getChildWithName (xAxis ? markerGroupTagX : markerGroupTagY);
  68608. }
  68609. ValueTree DrawableComposite::ValueTreeWrapper::getMarkerListCreating (bool xAxis, UndoManager* undoManager)
  68610. {
  68611. return state.getOrCreateChildWithName (xAxis ? markerGroupTagX : markerGroupTagY, undoManager);
  68612. }
  68613. int DrawableComposite::ValueTreeWrapper::getNumMarkers (bool xAxis) const
  68614. {
  68615. return getMarkerList (xAxis).getNumChildren();
  68616. }
  68617. const ValueTree DrawableComposite::ValueTreeWrapper::getMarkerState (bool xAxis, int index) const
  68618. {
  68619. return getMarkerList (xAxis).getChild (index);
  68620. }
  68621. const ValueTree DrawableComposite::ValueTreeWrapper::getMarkerState (bool xAxis, const String& name) const
  68622. {
  68623. return getMarkerList (xAxis).getChildWithProperty (nameProperty, name);
  68624. }
  68625. bool DrawableComposite::ValueTreeWrapper::containsMarker (bool xAxis, const ValueTree& state) const
  68626. {
  68627. return state.isAChildOf (getMarkerList (xAxis));
  68628. }
  68629. const DrawableComposite::Marker DrawableComposite::ValueTreeWrapper::getMarker (bool xAxis, const ValueTree& state) const
  68630. {
  68631. jassert (containsMarker (xAxis, state));
  68632. return Marker (state [nameProperty], RelativeCoordinate (state [posProperty].toString(), xAxis));
  68633. }
  68634. void DrawableComposite::ValueTreeWrapper::setMarker (bool xAxis, const Marker& m, UndoManager* undoManager)
  68635. {
  68636. ValueTree markerList (getMarkerListCreating (xAxis, undoManager));
  68637. ValueTree marker (markerList.getChildWithProperty (nameProperty, m.name));
  68638. if (marker.isValid())
  68639. {
  68640. marker.setProperty (posProperty, m.position.toString(), undoManager);
  68641. }
  68642. else
  68643. {
  68644. marker = ValueTree (markerTag);
  68645. marker.setProperty (nameProperty, m.name, 0);
  68646. marker.setProperty (posProperty, m.position.toString(), 0);
  68647. markerList.addChild (marker, -1, undoManager);
  68648. }
  68649. }
  68650. void DrawableComposite::ValueTreeWrapper::removeMarker (bool xAxis, const ValueTree& state, UndoManager* undoManager)
  68651. {
  68652. if (state [nameProperty].toString() != contentLeftMarkerName
  68653. && state [nameProperty].toString() != contentRightMarkerName
  68654. && state [nameProperty].toString() != contentTopMarkerName
  68655. && state [nameProperty].toString() != contentBottomMarkerName)
  68656. return getMarkerList (xAxis).removeChild (state, undoManager);
  68657. }
  68658. const Rectangle<float> DrawableComposite::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  68659. {
  68660. const ValueTreeWrapper wrapper (tree);
  68661. setName (wrapper.getID());
  68662. Rectangle<float> damage;
  68663. bool redrawAll = false;
  68664. const RelativeParallelogram newBounds (wrapper.getBoundingBox());
  68665. if (bounds != newBounds)
  68666. {
  68667. redrawAll = true;
  68668. damage = getBounds();
  68669. bounds = newBounds;
  68670. }
  68671. const int numMarkersX = wrapper.getNumMarkers (true);
  68672. const int numMarkersY = wrapper.getNumMarkers (false);
  68673. // Remove deleted markers...
  68674. if (markersX.size() > numMarkersX || markersY.size() > numMarkersY)
  68675. {
  68676. if (! redrawAll)
  68677. {
  68678. redrawAll = true;
  68679. damage = getBounds();
  68680. }
  68681. markersX.removeRange (jmax (2, numMarkersX), markersX.size());
  68682. markersY.removeRange (jmax (2, numMarkersY), markersY.size());
  68683. }
  68684. // Update markers and add new ones..
  68685. int i;
  68686. for (i = 0; i < numMarkersX; ++i)
  68687. {
  68688. const Marker newMarker (wrapper.getMarker (true, wrapper.getMarkerState (true, i)));
  68689. Marker* m = markersX[i];
  68690. if (m == 0 || newMarker != *m)
  68691. {
  68692. if (! redrawAll)
  68693. {
  68694. redrawAll = true;
  68695. damage = getBounds();
  68696. }
  68697. if (m == 0)
  68698. markersX.add (new Marker (newMarker));
  68699. else
  68700. *m = newMarker;
  68701. }
  68702. }
  68703. for (i = 0; i < numMarkersY; ++i)
  68704. {
  68705. const Marker newMarker (wrapper.getMarker (false, wrapper.getMarkerState (false, i)));
  68706. Marker* m = markersY[i];
  68707. if (m == 0 || newMarker != *m)
  68708. {
  68709. if (! redrawAll)
  68710. {
  68711. redrawAll = true;
  68712. damage = getBounds();
  68713. }
  68714. if (m == 0)
  68715. markersY.add (new Marker (newMarker));
  68716. else
  68717. *m = newMarker;
  68718. }
  68719. }
  68720. // Remove deleted drawables..
  68721. for (i = drawables.size(); --i >= wrapper.getNumDrawables();)
  68722. {
  68723. Drawable* const d = drawables.getUnchecked(i);
  68724. if (! redrawAll)
  68725. damage = damage.getUnion (d->getBounds());
  68726. d->parent = 0;
  68727. drawables.remove (i);
  68728. }
  68729. // Update drawables and add new ones..
  68730. for (i = 0; i < wrapper.getNumDrawables(); ++i)
  68731. {
  68732. const ValueTree newDrawable (wrapper.getDrawableState (i));
  68733. Drawable* d = drawables[i];
  68734. if (d != 0)
  68735. {
  68736. if (newDrawable.hasType (d->getValueTreeType()))
  68737. {
  68738. const Rectangle<float> area (d->refreshFromValueTree (newDrawable, imageProvider));
  68739. if (! redrawAll)
  68740. damage = damage.getUnion (area);
  68741. }
  68742. else
  68743. {
  68744. if (! redrawAll)
  68745. damage = damage.getUnion (d->getBounds());
  68746. d = createChildFromValueTree (this, newDrawable, imageProvider);
  68747. drawables.set (i, d);
  68748. if (! redrawAll)
  68749. damage = damage.getUnion (d->getBounds());
  68750. }
  68751. }
  68752. else
  68753. {
  68754. d = createChildFromValueTree (this, newDrawable, imageProvider);
  68755. drawables.set (i, d);
  68756. if (! redrawAll)
  68757. damage = damage.getUnion (d->getBounds());
  68758. }
  68759. }
  68760. if (redrawAll)
  68761. damage = damage.getUnion (getBounds());
  68762. else if (! damage.isEmpty())
  68763. damage = damage.transformed (calculateTransform());
  68764. return damage;
  68765. }
  68766. const ValueTree DrawableComposite::createValueTree (ImageProvider* imageProvider) const
  68767. {
  68768. ValueTree tree (valueTreeType);
  68769. ValueTreeWrapper v (tree);
  68770. v.setID (getName(), 0);
  68771. v.setBoundingBox (bounds, 0);
  68772. int i;
  68773. for (i = 0; i < drawables.size(); ++i)
  68774. v.addDrawable (drawables.getUnchecked(i)->createValueTree (imageProvider), -1, 0);
  68775. for (i = 0; i < markersX.size(); ++i)
  68776. v.setMarker (true, *markersX.getUnchecked(i), 0);
  68777. for (i = 0; i < markersY.size(); ++i)
  68778. v.setMarker (false, *markersY.getUnchecked(i), 0);
  68779. return tree;
  68780. }
  68781. END_JUCE_NAMESPACE
  68782. /*** End of inlined file: juce_DrawableComposite.cpp ***/
  68783. /*** Start of inlined file: juce_DrawableImage.cpp ***/
  68784. BEGIN_JUCE_NAMESPACE
  68785. DrawableImage::DrawableImage()
  68786. : image (0),
  68787. opacity (1.0f),
  68788. overlayColour (0x00000000)
  68789. {
  68790. bounds.topRight = RelativePoint (Point<float> (1.0f, 0.0f));
  68791. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, 1.0f));
  68792. }
  68793. DrawableImage::DrawableImage (const DrawableImage& other)
  68794. : image (other.image),
  68795. opacity (other.opacity),
  68796. overlayColour (other.overlayColour),
  68797. bounds (other.bounds)
  68798. {
  68799. }
  68800. DrawableImage::~DrawableImage()
  68801. {
  68802. }
  68803. void DrawableImage::setImage (const Image& imageToUse)
  68804. {
  68805. image = imageToUse;
  68806. if (image.isValid())
  68807. {
  68808. bounds.topLeft = RelativePoint (Point<float> (0.0f, 0.0f));
  68809. bounds.topRight = RelativePoint (Point<float> ((float) image.getWidth(), 0.0f));
  68810. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, (float) image.getHeight()));
  68811. }
  68812. }
  68813. void DrawableImage::setOpacity (const float newOpacity)
  68814. {
  68815. opacity = newOpacity;
  68816. }
  68817. void DrawableImage::setOverlayColour (const Colour& newOverlayColour)
  68818. {
  68819. overlayColour = newOverlayColour;
  68820. }
  68821. void DrawableImage::setBoundingBox (const RelativeParallelogram& newBounds)
  68822. {
  68823. bounds = newBounds;
  68824. }
  68825. const AffineTransform DrawableImage::calculateTransform() const
  68826. {
  68827. if (image.isNull())
  68828. return AffineTransform::identity;
  68829. Point<float> resolved[3];
  68830. bounds.resolveThreePoints (resolved, parent);
  68831. const Point<float> tr (resolved[0] + (resolved[1] - resolved[0]) / (float) image.getWidth());
  68832. const Point<float> bl (resolved[0] + (resolved[2] - resolved[0]) / (float) image.getHeight());
  68833. return AffineTransform::fromTargetPoints (resolved[0].getX(), resolved[0].getY(),
  68834. tr.getX(), tr.getY(),
  68835. bl.getX(), bl.getY());
  68836. }
  68837. void DrawableImage::render (const Drawable::RenderingContext& context) const
  68838. {
  68839. if (image.isValid())
  68840. {
  68841. const AffineTransform t (calculateTransform().followedBy (context.transform));
  68842. if (opacity > 0.0f && ! overlayColour.isOpaque())
  68843. {
  68844. context.g.setOpacity (context.opacity * opacity);
  68845. context.g.drawImageTransformed (image, image.getBounds(), t, false);
  68846. }
  68847. if (! overlayColour.isTransparent())
  68848. {
  68849. context.g.setColour (overlayColour.withMultipliedAlpha (context.opacity));
  68850. context.g.drawImageTransformed (image, image.getBounds(), t, true);
  68851. }
  68852. }
  68853. }
  68854. const Rectangle<float> DrawableImage::getBounds() const
  68855. {
  68856. if (image.isNull())
  68857. return Rectangle<float>();
  68858. return bounds.getBounds (parent);
  68859. }
  68860. bool DrawableImage::hitTest (float x, float y) const
  68861. {
  68862. if (image.isNull())
  68863. return false;
  68864. calculateTransform().inverted().transformPoint (x, y);
  68865. const int ix = roundToInt (x);
  68866. const int iy = roundToInt (y);
  68867. return ix >= 0
  68868. && iy >= 0
  68869. && ix < image.getWidth()
  68870. && iy < image.getHeight()
  68871. && image.getPixelAt (ix, iy).getAlpha() >= 127;
  68872. }
  68873. Drawable* DrawableImage::createCopy() const
  68874. {
  68875. return new DrawableImage (*this);
  68876. }
  68877. void DrawableImage::invalidatePoints()
  68878. {
  68879. }
  68880. const Identifier DrawableImage::valueTreeType ("Image");
  68881. const Identifier DrawableImage::ValueTreeWrapper::opacity ("opacity");
  68882. const Identifier DrawableImage::ValueTreeWrapper::overlay ("overlay");
  68883. const Identifier DrawableImage::ValueTreeWrapper::image ("image");
  68884. const Identifier DrawableImage::ValueTreeWrapper::topLeft ("topLeft");
  68885. const Identifier DrawableImage::ValueTreeWrapper::topRight ("topRight");
  68886. const Identifier DrawableImage::ValueTreeWrapper::bottomLeft ("bottomLeft");
  68887. DrawableImage::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  68888. : ValueTreeWrapperBase (state_)
  68889. {
  68890. jassert (state.hasType (valueTreeType));
  68891. }
  68892. const var DrawableImage::ValueTreeWrapper::getImageIdentifier() const
  68893. {
  68894. return state [image];
  68895. }
  68896. Value DrawableImage::ValueTreeWrapper::getImageIdentifierValue (UndoManager* undoManager)
  68897. {
  68898. return state.getPropertyAsValue (image, undoManager);
  68899. }
  68900. void DrawableImage::ValueTreeWrapper::setImageIdentifier (const var& newIdentifier, UndoManager* undoManager)
  68901. {
  68902. state.setProperty (image, newIdentifier, undoManager);
  68903. }
  68904. float DrawableImage::ValueTreeWrapper::getOpacity() const
  68905. {
  68906. return (float) state.getProperty (opacity, 1.0);
  68907. }
  68908. Value DrawableImage::ValueTreeWrapper::getOpacityValue (UndoManager* undoManager)
  68909. {
  68910. if (! state.hasProperty (opacity))
  68911. state.setProperty (opacity, 1.0, undoManager);
  68912. return state.getPropertyAsValue (opacity, undoManager);
  68913. }
  68914. void DrawableImage::ValueTreeWrapper::setOpacity (float newOpacity, UndoManager* undoManager)
  68915. {
  68916. state.setProperty (opacity, newOpacity, undoManager);
  68917. }
  68918. const Colour DrawableImage::ValueTreeWrapper::getOverlayColour() const
  68919. {
  68920. return Colour (state [overlay].toString().getHexValue32());
  68921. }
  68922. void DrawableImage::ValueTreeWrapper::setOverlayColour (const Colour& newColour, UndoManager* undoManager)
  68923. {
  68924. if (newColour.isTransparent())
  68925. state.removeProperty (overlay, undoManager);
  68926. else
  68927. state.setProperty (overlay, String::toHexString ((int) newColour.getARGB()), undoManager);
  68928. }
  68929. Value DrawableImage::ValueTreeWrapper::getOverlayColourValue (UndoManager* undoManager)
  68930. {
  68931. return state.getPropertyAsValue (overlay, undoManager);
  68932. }
  68933. const RelativeParallelogram DrawableImage::ValueTreeWrapper::getBoundingBox() const
  68934. {
  68935. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  68936. state.getProperty (topRight, "100, 0"),
  68937. state.getProperty (bottomLeft, "0, 100"));
  68938. }
  68939. void DrawableImage::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  68940. {
  68941. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  68942. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  68943. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  68944. }
  68945. const Rectangle<float> DrawableImage::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  68946. {
  68947. const ValueTreeWrapper controller (tree);
  68948. setName (controller.getID());
  68949. const float newOpacity = controller.getOpacity();
  68950. const Colour newOverlayColour (controller.getOverlayColour());
  68951. Image newImage;
  68952. const var imageIdentifier (controller.getImageIdentifier());
  68953. jassert (imageProvider != 0 || imageIdentifier.isVoid()); // if you're using images, you need to provide something that can load and save them!
  68954. if (imageProvider != 0)
  68955. newImage = imageProvider->getImageForIdentifier (imageIdentifier);
  68956. const RelativeParallelogram newBounds (controller.getBoundingBox());
  68957. if (newOpacity != opacity || overlayColour != newOverlayColour || image != newImage || bounds != newBounds)
  68958. {
  68959. const Rectangle<float> damage (getBounds());
  68960. opacity = newOpacity;
  68961. overlayColour = newOverlayColour;
  68962. bounds = newBounds;
  68963. image = newImage;
  68964. return damage.getUnion (getBounds());
  68965. }
  68966. return Rectangle<float>();
  68967. }
  68968. const ValueTree DrawableImage::createValueTree (ImageProvider* imageProvider) const
  68969. {
  68970. ValueTree tree (valueTreeType);
  68971. ValueTreeWrapper v (tree);
  68972. v.setID (getName(), 0);
  68973. v.setOpacity (opacity, 0);
  68974. v.setOverlayColour (overlayColour, 0);
  68975. v.setBoundingBox (bounds, 0);
  68976. if (image.isValid())
  68977. {
  68978. jassert (imageProvider != 0); // if you're using images, you need to provide something that can load and save them!
  68979. if (imageProvider != 0)
  68980. v.setImageIdentifier (imageProvider->getIdentifierForImage (image), 0);
  68981. }
  68982. return tree;
  68983. }
  68984. END_JUCE_NAMESPACE
  68985. /*** End of inlined file: juce_DrawableImage.cpp ***/
  68986. /*** Start of inlined file: juce_DrawablePath.cpp ***/
  68987. BEGIN_JUCE_NAMESPACE
  68988. DrawablePath::DrawablePath()
  68989. : mainFill (Colours::black),
  68990. strokeFill (Colours::black),
  68991. strokeType (0.0f),
  68992. pathNeedsUpdating (true),
  68993. strokeNeedsUpdating (true)
  68994. {
  68995. }
  68996. DrawablePath::DrawablePath (const DrawablePath& other)
  68997. : mainFill (other.mainFill),
  68998. strokeFill (other.strokeFill),
  68999. strokeType (other.strokeType),
  69000. pathNeedsUpdating (true),
  69001. strokeNeedsUpdating (true)
  69002. {
  69003. if (other.relativePath != 0)
  69004. relativePath = new RelativePointPath (*other.relativePath);
  69005. else
  69006. path = other.path;
  69007. }
  69008. DrawablePath::~DrawablePath()
  69009. {
  69010. }
  69011. void DrawablePath::setPath (const Path& newPath)
  69012. {
  69013. path = newPath;
  69014. strokeNeedsUpdating = true;
  69015. }
  69016. void DrawablePath::setFill (const FillType& newFill)
  69017. {
  69018. mainFill = newFill;
  69019. }
  69020. void DrawablePath::setStrokeFill (const FillType& newFill)
  69021. {
  69022. strokeFill = newFill;
  69023. }
  69024. void DrawablePath::setStrokeType (const PathStrokeType& newStrokeType)
  69025. {
  69026. strokeType = newStrokeType;
  69027. strokeNeedsUpdating = true;
  69028. }
  69029. void DrawablePath::setStrokeThickness (const float newThickness)
  69030. {
  69031. setStrokeType (PathStrokeType (newThickness, strokeType.getJointStyle(), strokeType.getEndStyle()));
  69032. }
  69033. void DrawablePath::updatePath() const
  69034. {
  69035. if (pathNeedsUpdating)
  69036. {
  69037. pathNeedsUpdating = false;
  69038. if (relativePath != 0)
  69039. {
  69040. path.clear();
  69041. relativePath->createPath (path, parent);
  69042. strokeNeedsUpdating = true;
  69043. }
  69044. }
  69045. }
  69046. void DrawablePath::updateStroke() const
  69047. {
  69048. if (strokeNeedsUpdating)
  69049. {
  69050. strokeNeedsUpdating = false;
  69051. updatePath();
  69052. stroke.clear();
  69053. strokeType.createStrokedPath (stroke, path, AffineTransform::identity, 4.0f);
  69054. }
  69055. }
  69056. const Path& DrawablePath::getPath() const
  69057. {
  69058. updatePath();
  69059. return path;
  69060. }
  69061. const Path& DrawablePath::getStrokePath() const
  69062. {
  69063. updateStroke();
  69064. return stroke;
  69065. }
  69066. bool DrawablePath::isStrokeVisible() const throw()
  69067. {
  69068. return strokeType.getStrokeThickness() > 0.0f && ! strokeFill.isInvisible();
  69069. }
  69070. void DrawablePath::invalidatePoints()
  69071. {
  69072. pathNeedsUpdating = true;
  69073. strokeNeedsUpdating = true;
  69074. }
  69075. void DrawablePath::render (const Drawable::RenderingContext& context) const
  69076. {
  69077. {
  69078. FillType f (mainFill);
  69079. if (f.isGradient())
  69080. f.gradient->multiplyOpacity (context.opacity);
  69081. f.transform = f.transform.followedBy (context.transform);
  69082. context.g.setFillType (f);
  69083. context.g.fillPath (getPath(), context.transform);
  69084. }
  69085. if (isStrokeVisible())
  69086. {
  69087. FillType f (strokeFill);
  69088. if (f.isGradient())
  69089. f.gradient->multiplyOpacity (context.opacity);
  69090. f.transform = f.transform.followedBy (context.transform);
  69091. context.g.setFillType (f);
  69092. context.g.fillPath (getStrokePath(), context.transform);
  69093. }
  69094. }
  69095. const Rectangle<float> DrawablePath::getBounds() const
  69096. {
  69097. if (isStrokeVisible())
  69098. return getStrokePath().getBounds();
  69099. else
  69100. return getPath().getBounds();
  69101. }
  69102. bool DrawablePath::hitTest (float x, float y) const
  69103. {
  69104. return getPath().contains (x, y)
  69105. || (isStrokeVisible() && getStrokePath().contains (x, y));
  69106. }
  69107. Drawable* DrawablePath::createCopy() const
  69108. {
  69109. return new DrawablePath (*this);
  69110. }
  69111. const Identifier DrawablePath::valueTreeType ("Path");
  69112. const Identifier DrawablePath::ValueTreeWrapper::fill ("Fill");
  69113. const Identifier DrawablePath::ValueTreeWrapper::stroke ("Stroke");
  69114. const Identifier DrawablePath::ValueTreeWrapper::path ("Path");
  69115. const Identifier DrawablePath::ValueTreeWrapper::jointStyle ("jointStyle");
  69116. const Identifier DrawablePath::ValueTreeWrapper::capStyle ("capStyle");
  69117. const Identifier DrawablePath::ValueTreeWrapper::strokeWidth ("strokeWidth");
  69118. const Identifier DrawablePath::ValueTreeWrapper::nonZeroWinding ("nonZeroWinding");
  69119. const Identifier DrawablePath::ValueTreeWrapper::point1 ("p1");
  69120. const Identifier DrawablePath::ValueTreeWrapper::point2 ("p2");
  69121. const Identifier DrawablePath::ValueTreeWrapper::point3 ("p3");
  69122. DrawablePath::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  69123. : ValueTreeWrapperBase (state_)
  69124. {
  69125. jassert (state.hasType (valueTreeType));
  69126. }
  69127. ValueTree DrawablePath::ValueTreeWrapper::getPathState()
  69128. {
  69129. return state.getOrCreateChildWithName (path, 0);
  69130. }
  69131. ValueTree DrawablePath::ValueTreeWrapper::getMainFillState()
  69132. {
  69133. ValueTree v (state.getChildWithName (fill));
  69134. if (v.isValid())
  69135. return v;
  69136. setMainFill (Colours::black, 0, 0, 0, 0);
  69137. return getMainFillState();
  69138. }
  69139. ValueTree DrawablePath::ValueTreeWrapper::getStrokeFillState()
  69140. {
  69141. ValueTree v (state.getChildWithName (stroke));
  69142. if (v.isValid())
  69143. return v;
  69144. setStrokeFill (Colours::black, 0, 0, 0, 0);
  69145. return getStrokeFillState();
  69146. }
  69147. const FillType DrawablePath::ValueTreeWrapper::getMainFill (RelativeCoordinate::NamedCoordinateFinder* nameFinder,
  69148. ImageProvider* imageProvider) const
  69149. {
  69150. return readFillType (state.getChildWithName (fill), 0, 0, nameFinder, imageProvider);
  69151. }
  69152. void DrawablePath::ValueTreeWrapper::setMainFill (const FillType& newFill, const RelativePoint* gp1,
  69153. const RelativePoint* gp2, ImageProvider* imageProvider, UndoManager* undoManager)
  69154. {
  69155. ValueTree v (state.getOrCreateChildWithName (fill, undoManager));
  69156. writeFillType (v, newFill, gp1, gp2, imageProvider, undoManager);
  69157. }
  69158. const FillType DrawablePath::ValueTreeWrapper::getStrokeFill (RelativeCoordinate::NamedCoordinateFinder* nameFinder,
  69159. ImageProvider* imageProvider) const
  69160. {
  69161. return readFillType (state.getChildWithName (stroke), 0, 0, nameFinder, imageProvider);
  69162. }
  69163. void DrawablePath::ValueTreeWrapper::setStrokeFill (const FillType& newFill, const RelativePoint* gp1,
  69164. const RelativePoint* gp2, ImageProvider* imageProvider, UndoManager* undoManager)
  69165. {
  69166. ValueTree v (state.getOrCreateChildWithName (stroke, undoManager));
  69167. writeFillType (v, newFill, gp1, gp2, imageProvider, undoManager);
  69168. }
  69169. const PathStrokeType DrawablePath::ValueTreeWrapper::getStrokeType() const
  69170. {
  69171. const String jointStyleString (state [jointStyle].toString());
  69172. const String capStyleString (state [capStyle].toString());
  69173. return PathStrokeType (state [strokeWidth],
  69174. jointStyleString == "curved" ? PathStrokeType::curved
  69175. : (jointStyleString == "bevel" ? PathStrokeType::beveled
  69176. : PathStrokeType::mitered),
  69177. capStyleString == "square" ? PathStrokeType::square
  69178. : (capStyleString == "round" ? PathStrokeType::rounded
  69179. : PathStrokeType::butt));
  69180. }
  69181. void DrawablePath::ValueTreeWrapper::setStrokeType (const PathStrokeType& newStrokeType, UndoManager* undoManager)
  69182. {
  69183. state.setProperty (strokeWidth, (double) newStrokeType.getStrokeThickness(), undoManager);
  69184. state.setProperty (jointStyle, newStrokeType.getJointStyle() == PathStrokeType::mitered
  69185. ? "miter" : (newStrokeType.getJointStyle() == PathStrokeType::curved ? "curved" : "bevel"), undoManager);
  69186. state.setProperty (capStyle, newStrokeType.getEndStyle() == PathStrokeType::butt
  69187. ? "butt" : (newStrokeType.getEndStyle() == PathStrokeType::square ? "square" : "round"), undoManager);
  69188. }
  69189. bool DrawablePath::ValueTreeWrapper::usesNonZeroWinding() const
  69190. {
  69191. return state [nonZeroWinding];
  69192. }
  69193. void DrawablePath::ValueTreeWrapper::setUsesNonZeroWinding (bool b, UndoManager* undoManager)
  69194. {
  69195. state.setProperty (nonZeroWinding, b, undoManager);
  69196. }
  69197. const Identifier DrawablePath::ValueTreeWrapper::Element::startSubPathElement ("Move");
  69198. const Identifier DrawablePath::ValueTreeWrapper::Element::closeSubPathElement ("Close");
  69199. const Identifier DrawablePath::ValueTreeWrapper::Element::lineToElement ("Line");
  69200. const Identifier DrawablePath::ValueTreeWrapper::Element::quadraticToElement ("Quad");
  69201. const Identifier DrawablePath::ValueTreeWrapper::Element::cubicToElement ("Cubic");
  69202. DrawablePath::ValueTreeWrapper::Element::Element (const ValueTree& state_)
  69203. : state (state_)
  69204. {
  69205. }
  69206. DrawablePath::ValueTreeWrapper::Element::~Element()
  69207. {
  69208. }
  69209. DrawablePath::ValueTreeWrapper DrawablePath::ValueTreeWrapper::Element::getParent() const
  69210. {
  69211. return ValueTreeWrapper (state.getParent().getParent());
  69212. }
  69213. int DrawablePath::ValueTreeWrapper::Element::getNumControlPoints() const throw()
  69214. {
  69215. const Identifier i (state.getType());
  69216. if (i == startSubPathElement || i == lineToElement) return 1;
  69217. if (i == quadraticToElement) return 2;
  69218. if (i == cubicToElement) return 3;
  69219. return 0;
  69220. }
  69221. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getControlPoint (const int index) const
  69222. {
  69223. jassert (index >= 0 && index < getNumControlPoints());
  69224. return RelativePoint (state [index == 0 ? point1 : (index == 1 ? point2 : point3)].toString());
  69225. }
  69226. Value DrawablePath::ValueTreeWrapper::Element::getControlPointValue (int index, UndoManager* undoManager) const
  69227. {
  69228. jassert (index >= 0 && index < getNumControlPoints());
  69229. return state.getPropertyAsValue (index == 0 ? point1 : (index == 1 ? point2 : point3), undoManager);
  69230. }
  69231. void DrawablePath::ValueTreeWrapper::Element::setControlPoint (const int index, const RelativePoint& point, UndoManager* undoManager)
  69232. {
  69233. jassert (index >= 0 && index < getNumControlPoints());
  69234. return state.setProperty (index == 0 ? point1 : (index == 1 ? point2 : point3), point.toString(), undoManager);
  69235. }
  69236. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getEndPoint() const
  69237. {
  69238. const Identifier i (state.getType());
  69239. if (i == startSubPathElement || i == lineToElement) return getControlPoint (0);
  69240. if (i == quadraticToElement) return getControlPoint (1);
  69241. if (i == cubicToElement) return getControlPoint (2);
  69242. return RelativePoint();
  69243. }
  69244. const Rectangle<float> DrawablePath::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  69245. {
  69246. Rectangle<float> damageRect;
  69247. ValueTreeWrapper v (tree);
  69248. setName (v.getID());
  69249. bool needsRedraw = false;
  69250. const FillType newFill (v.getMainFill (parent, imageProvider));
  69251. if (mainFill != newFill)
  69252. {
  69253. needsRedraw = true;
  69254. mainFill = newFill;
  69255. }
  69256. const FillType newStrokeFill (v.getStrokeFill (parent, imageProvider));
  69257. if (strokeFill != newStrokeFill)
  69258. {
  69259. needsRedraw = true;
  69260. strokeFill = newStrokeFill;
  69261. }
  69262. const PathStrokeType newStroke (v.getStrokeType());
  69263. ScopedPointer<RelativePointPath> newRelativePath (new RelativePointPath (tree));
  69264. Path newPath;
  69265. newRelativePath->createPath (newPath, parent);
  69266. if (! newRelativePath->containsAnyDynamicPoints())
  69267. newRelativePath = 0;
  69268. if (strokeType != newStroke || path != newPath)
  69269. {
  69270. damageRect = getBounds();
  69271. path.swapWithPath (newPath);
  69272. strokeNeedsUpdating = true;
  69273. strokeType = newStroke;
  69274. needsRedraw = true;
  69275. }
  69276. relativePath = newRelativePath.release();
  69277. if (needsRedraw)
  69278. damageRect = damageRect.getUnion (getBounds());
  69279. return damageRect;
  69280. }
  69281. const ValueTree DrawablePath::createValueTree (ImageProvider* imageProvider) const
  69282. {
  69283. ValueTree tree (valueTreeType);
  69284. ValueTreeWrapper v (tree);
  69285. v.setID (getName(), 0);
  69286. v.setMainFill (mainFill, 0, 0, imageProvider, 0);
  69287. v.setStrokeFill (strokeFill, 0, 0, imageProvider, 0);
  69288. v.setStrokeType (strokeType, 0);
  69289. if (relativePath != 0)
  69290. {
  69291. relativePath->writeTo (tree, 0);
  69292. }
  69293. else
  69294. {
  69295. RelativePointPath rp (path);
  69296. rp.writeTo (tree, 0);
  69297. }
  69298. return tree;
  69299. }
  69300. END_JUCE_NAMESPACE
  69301. /*** End of inlined file: juce_DrawablePath.cpp ***/
  69302. /*** Start of inlined file: juce_DrawableText.cpp ***/
  69303. BEGIN_JUCE_NAMESPACE
  69304. DrawableText::DrawableText()
  69305. : colour (Colours::black),
  69306. justification (Justification::centredLeft)
  69307. {
  69308. setFont (Font (15.0f), true);
  69309. }
  69310. DrawableText::DrawableText (const DrawableText& other)
  69311. : text (other.text),
  69312. font (other.font),
  69313. colour (other.colour),
  69314. justification (other.justification),
  69315. bounds (other.bounds),
  69316. fontSizeControlPoint (other.fontSizeControlPoint)
  69317. {
  69318. }
  69319. DrawableText::~DrawableText()
  69320. {
  69321. }
  69322. void DrawableText::setText (const String& newText)
  69323. {
  69324. text = newText;
  69325. }
  69326. void DrawableText::setColour (const Colour& newColour)
  69327. {
  69328. colour = newColour;
  69329. }
  69330. void DrawableText::setFont (const Font& newFont, bool applySizeAndScale)
  69331. {
  69332. font = newFont;
  69333. if (applySizeAndScale)
  69334. {
  69335. Point<float> corners[3];
  69336. bounds.resolveThreePoints (corners, parent);
  69337. setFontSizeControlPoint (RelativePoint (RelativeParallelogram::getPointForInternalCoord (corners,
  69338. Point<float> (font.getHorizontalScale() * font.getHeight(), font.getHeight()))));
  69339. }
  69340. }
  69341. void DrawableText::setJustification (const Justification& newJustification)
  69342. {
  69343. justification = newJustification;
  69344. }
  69345. void DrawableText::setBoundingBox (const RelativeParallelogram& newBounds)
  69346. {
  69347. bounds = newBounds;
  69348. }
  69349. void DrawableText::setFontSizeControlPoint (const RelativePoint& newPoint)
  69350. {
  69351. fontSizeControlPoint = newPoint;
  69352. }
  69353. void DrawableText::render (const Drawable::RenderingContext& context) const
  69354. {
  69355. Point<float> points[3];
  69356. bounds.resolveThreePoints (points, parent);
  69357. const float w = Line<float> (points[0], points[1]).getLength();
  69358. const float h = Line<float> (points[0], points[2]).getLength();
  69359. const Point<float> fontCoords (bounds.getInternalCoordForPoint (points, fontSizeControlPoint.resolve (parent)));
  69360. const float fontHeight = jlimit (1.0f, h, fontCoords.getY());
  69361. const float fontWidth = jlimit (0.01f, w, fontCoords.getX());
  69362. Font f (font);
  69363. f.setHeight (fontHeight);
  69364. f.setHorizontalScale (fontWidth / fontHeight);
  69365. context.g.setColour (colour.withMultipliedAlpha (context.opacity));
  69366. GlyphArrangement ga;
  69367. ga.addFittedText (f, text, 0, 0, w, h, justification, 0x100000);
  69368. ga.draw (context.g,
  69369. AffineTransform::fromTargetPoints (0, 0, points[0].getX(), points[0].getY(),
  69370. w, 0, points[1].getX(), points[1].getY(),
  69371. 0, h, points[2].getX(), points[2].getY())
  69372. .followedBy (context.transform));
  69373. }
  69374. const Rectangle<float> DrawableText::getBounds() const
  69375. {
  69376. return bounds.getBounds (parent);
  69377. }
  69378. bool DrawableText::hitTest (float x, float y) const
  69379. {
  69380. Path p;
  69381. bounds.getPath (p, parent);
  69382. return p.contains (x, y);
  69383. }
  69384. Drawable* DrawableText::createCopy() const
  69385. {
  69386. return new DrawableText (*this);
  69387. }
  69388. void DrawableText::invalidatePoints()
  69389. {
  69390. }
  69391. const Identifier DrawableText::valueTreeType ("Text");
  69392. const Identifier DrawableText::ValueTreeWrapper::text ("text");
  69393. const Identifier DrawableText::ValueTreeWrapper::colour ("colour");
  69394. const Identifier DrawableText::ValueTreeWrapper::font ("font");
  69395. const Identifier DrawableText::ValueTreeWrapper::justification ("justification");
  69396. const Identifier DrawableText::ValueTreeWrapper::topLeft ("topLeft");
  69397. const Identifier DrawableText::ValueTreeWrapper::topRight ("topRight");
  69398. const Identifier DrawableText::ValueTreeWrapper::bottomLeft ("bottomLeft");
  69399. const Identifier DrawableText::ValueTreeWrapper::fontSizeAnchor ("fontSizeAnchor");
  69400. DrawableText::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  69401. : ValueTreeWrapperBase (state_)
  69402. {
  69403. jassert (state.hasType (valueTreeType));
  69404. }
  69405. const String DrawableText::ValueTreeWrapper::getText() const
  69406. {
  69407. return state [text].toString();
  69408. }
  69409. void DrawableText::ValueTreeWrapper::setText (const String& newText, UndoManager* undoManager)
  69410. {
  69411. state.setProperty (text, newText, undoManager);
  69412. }
  69413. Value DrawableText::ValueTreeWrapper::getTextValue (UndoManager* undoManager)
  69414. {
  69415. return state.getPropertyAsValue (text, undoManager);
  69416. }
  69417. const Colour DrawableText::ValueTreeWrapper::getColour() const
  69418. {
  69419. return Colour::fromString (state [colour].toString());
  69420. }
  69421. void DrawableText::ValueTreeWrapper::setColour (const Colour& newColour, UndoManager* undoManager)
  69422. {
  69423. state.setProperty (colour, newColour.toString(), undoManager);
  69424. }
  69425. const Justification DrawableText::ValueTreeWrapper::getJustification() const
  69426. {
  69427. return Justification ((int) state [justification]);
  69428. }
  69429. void DrawableText::ValueTreeWrapper::setJustification (const Justification& newJustification, UndoManager* undoManager)
  69430. {
  69431. state.setProperty (justification, newJustification.getFlags(), undoManager);
  69432. }
  69433. const Font DrawableText::ValueTreeWrapper::getFont() const
  69434. {
  69435. return Font::fromString (state [font]);
  69436. }
  69437. void DrawableText::ValueTreeWrapper::setFont (const Font& newFont, UndoManager* undoManager)
  69438. {
  69439. state.setProperty (font, newFont.toString(), undoManager);
  69440. }
  69441. Value DrawableText::ValueTreeWrapper::getFontValue (UndoManager* undoManager)
  69442. {
  69443. return state.getPropertyAsValue (font, undoManager);
  69444. }
  69445. const RelativeParallelogram DrawableText::ValueTreeWrapper::getBoundingBox() const
  69446. {
  69447. return RelativeParallelogram (state [topLeft].toString(), state [topRight].toString(), state [bottomLeft].toString());
  69448. }
  69449. void DrawableText::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  69450. {
  69451. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  69452. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  69453. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  69454. }
  69455. const RelativePoint DrawableText::ValueTreeWrapper::getFontSizeControlPoint() const
  69456. {
  69457. return state [fontSizeAnchor].toString();
  69458. }
  69459. void DrawableText::ValueTreeWrapper::setFontSizeControlPoint (const RelativePoint& p, UndoManager* undoManager)
  69460. {
  69461. state.setProperty (fontSizeAnchor, p.toString(), undoManager);
  69462. }
  69463. const Rectangle<float> DrawableText::refreshFromValueTree (const ValueTree& tree, ImageProvider*)
  69464. {
  69465. ValueTreeWrapper v (tree);
  69466. setName (v.getID());
  69467. const RelativeParallelogram newBounds (v.getBoundingBox());
  69468. const RelativePoint newFontPoint (v.getFontSizeControlPoint());
  69469. const Colour newColour (v.getColour());
  69470. const Justification newJustification (v.getJustification());
  69471. const String newText (v.getText());
  69472. const Font newFont (v.getFont());
  69473. if (text != newText || font != newFont || justification != newJustification
  69474. || colour != newColour || bounds != newBounds || newFontPoint != fontSizeControlPoint)
  69475. {
  69476. const Rectangle<float> damage (getBounds());
  69477. setBoundingBox (newBounds);
  69478. setFontSizeControlPoint (newFontPoint);
  69479. setColour (newColour);
  69480. setFont (newFont, false);
  69481. setJustification (newJustification);
  69482. setText (newText);
  69483. return damage.getUnion (getBounds());
  69484. }
  69485. return Rectangle<float>();
  69486. }
  69487. const ValueTree DrawableText::createValueTree (ImageProvider*) const
  69488. {
  69489. ValueTree tree (valueTreeType);
  69490. ValueTreeWrapper v (tree);
  69491. v.setID (getName(), 0);
  69492. v.setText (text, 0);
  69493. v.setFont (font, 0);
  69494. v.setJustification (justification, 0);
  69495. v.setColour (colour, 0);
  69496. v.setBoundingBox (bounds, 0);
  69497. v.setFontSizeControlPoint (fontSizeControlPoint, 0);
  69498. return tree;
  69499. }
  69500. END_JUCE_NAMESPACE
  69501. /*** End of inlined file: juce_DrawableText.cpp ***/
  69502. /*** Start of inlined file: juce_SVGParser.cpp ***/
  69503. BEGIN_JUCE_NAMESPACE
  69504. class SVGState
  69505. {
  69506. public:
  69507. SVGState (const XmlElement* const topLevel)
  69508. : topLevelXml (topLevel),
  69509. elementX (0), elementY (0),
  69510. width (512), height (512),
  69511. viewBoxW (0), viewBoxH (0)
  69512. {
  69513. }
  69514. ~SVGState()
  69515. {
  69516. }
  69517. Drawable* parseSVGElement (const XmlElement& xml)
  69518. {
  69519. if (! xml.hasTagName ("svg"))
  69520. return 0;
  69521. DrawableComposite* const drawable = new DrawableComposite();
  69522. drawable->setName (xml.getStringAttribute ("id"));
  69523. SVGState newState (*this);
  69524. if (xml.hasAttribute ("transform"))
  69525. newState.addTransform (xml);
  69526. newState.elementX = getCoordLength (xml.getStringAttribute ("x", String (newState.elementX)), viewBoxW);
  69527. newState.elementY = getCoordLength (xml.getStringAttribute ("y", String (newState.elementY)), viewBoxH);
  69528. newState.width = getCoordLength (xml.getStringAttribute ("width", String (newState.width)), viewBoxW);
  69529. newState.height = getCoordLength (xml.getStringAttribute ("height", String (newState.height)), viewBoxH);
  69530. if (xml.hasAttribute ("viewBox"))
  69531. {
  69532. const String viewParams (xml.getStringAttribute ("viewBox"));
  69533. int i = 0;
  69534. float vx, vy, vw, vh;
  69535. if (parseCoords (viewParams, vx, vy, i, true)
  69536. && parseCoords (viewParams, vw, vh, i, true)
  69537. && vw > 0
  69538. && vh > 0)
  69539. {
  69540. newState.viewBoxW = vw;
  69541. newState.viewBoxH = vh;
  69542. int placementFlags = 0;
  69543. const String aspect (xml.getStringAttribute ("preserveAspectRatio"));
  69544. if (aspect.containsIgnoreCase ("none"))
  69545. {
  69546. placementFlags = RectanglePlacement::stretchToFit;
  69547. }
  69548. else
  69549. {
  69550. if (aspect.containsIgnoreCase ("slice"))
  69551. placementFlags |= RectanglePlacement::fillDestination;
  69552. if (aspect.containsIgnoreCase ("xMin"))
  69553. placementFlags |= RectanglePlacement::xLeft;
  69554. else if (aspect.containsIgnoreCase ("xMax"))
  69555. placementFlags |= RectanglePlacement::xRight;
  69556. else
  69557. placementFlags |= RectanglePlacement::xMid;
  69558. if (aspect.containsIgnoreCase ("yMin"))
  69559. placementFlags |= RectanglePlacement::yTop;
  69560. else if (aspect.containsIgnoreCase ("yMax"))
  69561. placementFlags |= RectanglePlacement::yBottom;
  69562. else
  69563. placementFlags |= RectanglePlacement::yMid;
  69564. }
  69565. const RectanglePlacement placement (placementFlags);
  69566. newState.transform
  69567. = placement.getTransformToFit (vx, vy, vw, vh,
  69568. 0.0f, 0.0f, newState.width, newState.height)
  69569. .followedBy (newState.transform);
  69570. }
  69571. }
  69572. else
  69573. {
  69574. if (viewBoxW == 0)
  69575. newState.viewBoxW = newState.width;
  69576. if (viewBoxH == 0)
  69577. newState.viewBoxH = newState.height;
  69578. }
  69579. newState.parseSubElements (xml, drawable);
  69580. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  69581. return drawable;
  69582. }
  69583. private:
  69584. const XmlElement* const topLevelXml;
  69585. float elementX, elementY, width, height, viewBoxW, viewBoxH;
  69586. AffineTransform transform;
  69587. String cssStyleText;
  69588. void parseSubElements (const XmlElement& xml, DrawableComposite* const parentDrawable)
  69589. {
  69590. forEachXmlChildElement (xml, e)
  69591. {
  69592. Drawable* d = 0;
  69593. if (e->hasTagName ("g")) d = parseGroupElement (*e);
  69594. else if (e->hasTagName ("svg")) d = parseSVGElement (*e);
  69595. else if (e->hasTagName ("path")) d = parsePath (*e);
  69596. else if (e->hasTagName ("rect")) d = parseRect (*e);
  69597. else if (e->hasTagName ("circle")) d = parseCircle (*e);
  69598. else if (e->hasTagName ("ellipse")) d = parseEllipse (*e);
  69599. else if (e->hasTagName ("line")) d = parseLine (*e);
  69600. else if (e->hasTagName ("polyline")) d = parsePolygon (*e, true);
  69601. else if (e->hasTagName ("polygon")) d = parsePolygon (*e, false);
  69602. else if (e->hasTagName ("text")) d = parseText (*e);
  69603. else if (e->hasTagName ("switch")) d = parseSwitch (*e);
  69604. else if (e->hasTagName ("style")) parseCSSStyle (*e);
  69605. parentDrawable->insertDrawable (d);
  69606. }
  69607. }
  69608. DrawableComposite* parseSwitch (const XmlElement& xml)
  69609. {
  69610. const XmlElement* const group = xml.getChildByName ("g");
  69611. if (group != 0)
  69612. return parseGroupElement (*group);
  69613. return 0;
  69614. }
  69615. DrawableComposite* parseGroupElement (const XmlElement& xml)
  69616. {
  69617. DrawableComposite* const drawable = new DrawableComposite();
  69618. drawable->setName (xml.getStringAttribute ("id"));
  69619. if (xml.hasAttribute ("transform"))
  69620. {
  69621. SVGState newState (*this);
  69622. newState.addTransform (xml);
  69623. newState.parseSubElements (xml, drawable);
  69624. }
  69625. else
  69626. {
  69627. parseSubElements (xml, drawable);
  69628. }
  69629. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  69630. return drawable;
  69631. }
  69632. Drawable* parsePath (const XmlElement& xml) const
  69633. {
  69634. const String d (xml.getStringAttribute ("d").trimStart());
  69635. Path path;
  69636. if (getStyleAttribute (&xml, "fill-rule").trim().equalsIgnoreCase ("evenodd"))
  69637. path.setUsingNonZeroWinding (false);
  69638. int index = 0;
  69639. float lastX = 0, lastY = 0;
  69640. float lastX2 = 0, lastY2 = 0;
  69641. juce_wchar lastCommandChar = 0;
  69642. bool isRelative = true;
  69643. bool carryOn = true;
  69644. const String validCommandChars ("MmLlHhVvCcSsQqTtAaZz");
  69645. while (d[index] != 0)
  69646. {
  69647. float x, y, x2, y2, x3, y3;
  69648. if (validCommandChars.containsChar (d[index]))
  69649. {
  69650. lastCommandChar = d [index++];
  69651. isRelative = (lastCommandChar >= 'a' && lastCommandChar <= 'z');
  69652. }
  69653. switch (lastCommandChar)
  69654. {
  69655. case 'M':
  69656. case 'm':
  69657. case 'L':
  69658. case 'l':
  69659. if (parseCoords (d, x, y, index, false))
  69660. {
  69661. if (isRelative)
  69662. {
  69663. x += lastX;
  69664. y += lastY;
  69665. }
  69666. if (lastCommandChar == 'M' || lastCommandChar == 'm')
  69667. {
  69668. path.startNewSubPath (x, y);
  69669. lastCommandChar = 'l';
  69670. }
  69671. else
  69672. path.lineTo (x, y);
  69673. lastX2 = lastX;
  69674. lastY2 = lastY;
  69675. lastX = x;
  69676. lastY = y;
  69677. }
  69678. else
  69679. {
  69680. ++index;
  69681. }
  69682. break;
  69683. case 'H':
  69684. case 'h':
  69685. if (parseCoord (d, x, index, false, true))
  69686. {
  69687. if (isRelative)
  69688. x += lastX;
  69689. path.lineTo (x, lastY);
  69690. lastX2 = lastX;
  69691. lastX = x;
  69692. }
  69693. else
  69694. {
  69695. ++index;
  69696. }
  69697. break;
  69698. case 'V':
  69699. case 'v':
  69700. if (parseCoord (d, y, index, false, false))
  69701. {
  69702. if (isRelative)
  69703. y += lastY;
  69704. path.lineTo (lastX, y);
  69705. lastY2 = lastY;
  69706. lastY = y;
  69707. }
  69708. else
  69709. {
  69710. ++index;
  69711. }
  69712. break;
  69713. case 'C':
  69714. case 'c':
  69715. if (parseCoords (d, x, y, index, false)
  69716. && parseCoords (d, x2, y2, index, false)
  69717. && parseCoords (d, x3, y3, index, false))
  69718. {
  69719. if (isRelative)
  69720. {
  69721. x += lastX;
  69722. y += lastY;
  69723. x2 += lastX;
  69724. y2 += lastY;
  69725. x3 += lastX;
  69726. y3 += lastY;
  69727. }
  69728. path.cubicTo (x, y, x2, y2, x3, y3);
  69729. lastX2 = x2;
  69730. lastY2 = y2;
  69731. lastX = x3;
  69732. lastY = y3;
  69733. }
  69734. else
  69735. {
  69736. ++index;
  69737. }
  69738. break;
  69739. case 'S':
  69740. case 's':
  69741. if (parseCoords (d, x, y, index, false)
  69742. && parseCoords (d, x3, y3, index, false))
  69743. {
  69744. if (isRelative)
  69745. {
  69746. x += lastX;
  69747. y += lastY;
  69748. x3 += lastX;
  69749. y3 += lastY;
  69750. }
  69751. x2 = lastX + (lastX - lastX2);
  69752. y2 = lastY + (lastY - lastY2);
  69753. path.cubicTo (x2, y2, x, y, x3, y3);
  69754. lastX2 = x;
  69755. lastY2 = y;
  69756. lastX = x3;
  69757. lastY = y3;
  69758. }
  69759. else
  69760. {
  69761. ++index;
  69762. }
  69763. break;
  69764. case 'Q':
  69765. case 'q':
  69766. if (parseCoords (d, x, y, index, false)
  69767. && parseCoords (d, x2, y2, index, false))
  69768. {
  69769. if (isRelative)
  69770. {
  69771. x += lastX;
  69772. y += lastY;
  69773. x2 += lastX;
  69774. y2 += lastY;
  69775. }
  69776. path.quadraticTo (x, y, x2, y2);
  69777. lastX2 = x;
  69778. lastY2 = y;
  69779. lastX = x2;
  69780. lastY = y2;
  69781. }
  69782. else
  69783. {
  69784. ++index;
  69785. }
  69786. break;
  69787. case 'T':
  69788. case 't':
  69789. if (parseCoords (d, x, y, index, false))
  69790. {
  69791. if (isRelative)
  69792. {
  69793. x += lastX;
  69794. y += lastY;
  69795. }
  69796. x2 = lastX + (lastX - lastX2);
  69797. y2 = lastY + (lastY - lastY2);
  69798. path.quadraticTo (x2, y2, x, y);
  69799. lastX2 = x2;
  69800. lastY2 = y2;
  69801. lastX = x;
  69802. lastY = y;
  69803. }
  69804. else
  69805. {
  69806. ++index;
  69807. }
  69808. break;
  69809. case 'A':
  69810. case 'a':
  69811. if (parseCoords (d, x, y, index, false))
  69812. {
  69813. String num;
  69814. if (parseNextNumber (d, num, index, false))
  69815. {
  69816. const float angle = num.getFloatValue() * (180.0f / float_Pi);
  69817. if (parseNextNumber (d, num, index, false))
  69818. {
  69819. const bool largeArc = num.getIntValue() != 0;
  69820. if (parseNextNumber (d, num, index, false))
  69821. {
  69822. const bool sweep = num.getIntValue() != 0;
  69823. if (parseCoords (d, x2, y2, index, false))
  69824. {
  69825. if (isRelative)
  69826. {
  69827. x2 += lastX;
  69828. y2 += lastY;
  69829. }
  69830. if (lastX != x2 || lastY != y2)
  69831. {
  69832. double centreX, centreY, startAngle, deltaAngle;
  69833. double rx = x, ry = y;
  69834. endpointToCentreParameters (lastX, lastY, x2, y2,
  69835. angle, largeArc, sweep,
  69836. rx, ry, centreX, centreY,
  69837. startAngle, deltaAngle);
  69838. path.addCentredArc ((float) centreX, (float) centreY,
  69839. (float) rx, (float) ry,
  69840. angle, (float) startAngle, (float) (startAngle + deltaAngle),
  69841. false);
  69842. path.lineTo (x2, y2);
  69843. }
  69844. lastX2 = lastX;
  69845. lastY2 = lastY;
  69846. lastX = x2;
  69847. lastY = y2;
  69848. }
  69849. }
  69850. }
  69851. }
  69852. }
  69853. else
  69854. {
  69855. ++index;
  69856. }
  69857. break;
  69858. case 'Z':
  69859. case 'z':
  69860. path.closeSubPath();
  69861. while (CharacterFunctions::isWhitespace (d [index]))
  69862. ++index;
  69863. break;
  69864. default:
  69865. carryOn = false;
  69866. break;
  69867. }
  69868. if (! carryOn)
  69869. break;
  69870. }
  69871. return parseShape (xml, path);
  69872. }
  69873. Drawable* parseRect (const XmlElement& xml) const
  69874. {
  69875. Path rect;
  69876. const bool hasRX = xml.hasAttribute ("rx");
  69877. const bool hasRY = xml.hasAttribute ("ry");
  69878. if (hasRX || hasRY)
  69879. {
  69880. float rx = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  69881. float ry = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  69882. if (! hasRX)
  69883. rx = ry;
  69884. else if (! hasRY)
  69885. ry = rx;
  69886. rect.addRoundedRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  69887. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  69888. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  69889. getCoordLength (xml.getStringAttribute ("height"), viewBoxH),
  69890. rx, ry);
  69891. }
  69892. else
  69893. {
  69894. rect.addRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  69895. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  69896. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  69897. getCoordLength (xml.getStringAttribute ("height"), viewBoxH));
  69898. }
  69899. return parseShape (xml, rect);
  69900. }
  69901. Drawable* parseCircle (const XmlElement& xml) const
  69902. {
  69903. Path circle;
  69904. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  69905. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  69906. const float radius = getCoordLength (xml.getStringAttribute ("r"), viewBoxW);
  69907. circle.addEllipse (cx - radius, cy - radius, radius * 2.0f, radius * 2.0f);
  69908. return parseShape (xml, circle);
  69909. }
  69910. Drawable* parseEllipse (const XmlElement& xml) const
  69911. {
  69912. Path ellipse;
  69913. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  69914. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  69915. const float radiusX = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  69916. const float radiusY = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  69917. ellipse.addEllipse (cx - radiusX, cy - radiusY, radiusX * 2.0f, radiusY * 2.0f);
  69918. return parseShape (xml, ellipse);
  69919. }
  69920. Drawable* parseLine (const XmlElement& xml) const
  69921. {
  69922. Path line;
  69923. const float x1 = getCoordLength (xml.getStringAttribute ("x1"), viewBoxW);
  69924. const float y1 = getCoordLength (xml.getStringAttribute ("y1"), viewBoxH);
  69925. const float x2 = getCoordLength (xml.getStringAttribute ("x2"), viewBoxW);
  69926. const float y2 = getCoordLength (xml.getStringAttribute ("y2"), viewBoxH);
  69927. line.startNewSubPath (x1, y1);
  69928. line.lineTo (x2, y2);
  69929. return parseShape (xml, line);
  69930. }
  69931. Drawable* parsePolygon (const XmlElement& xml, const bool isPolyline) const
  69932. {
  69933. const String points (xml.getStringAttribute ("points"));
  69934. Path path;
  69935. int index = 0;
  69936. float x, y;
  69937. if (parseCoords (points, x, y, index, true))
  69938. {
  69939. float firstX = x;
  69940. float firstY = y;
  69941. float lastX = 0, lastY = 0;
  69942. path.startNewSubPath (x, y);
  69943. while (parseCoords (points, x, y, index, true))
  69944. {
  69945. lastX = x;
  69946. lastY = y;
  69947. path.lineTo (x, y);
  69948. }
  69949. if ((! isPolyline) || (firstX == lastX && firstY == lastY))
  69950. path.closeSubPath();
  69951. }
  69952. return parseShape (xml, path);
  69953. }
  69954. Drawable* parseShape (const XmlElement& xml, Path& path,
  69955. const bool shouldParseTransform = true) const
  69956. {
  69957. if (shouldParseTransform && xml.hasAttribute ("transform"))
  69958. {
  69959. SVGState newState (*this);
  69960. newState.addTransform (xml);
  69961. return newState.parseShape (xml, path, false);
  69962. }
  69963. DrawablePath* dp = new DrawablePath();
  69964. dp->setName (xml.getStringAttribute ("id"));
  69965. dp->setFill (Colours::transparentBlack);
  69966. path.applyTransform (transform);
  69967. dp->setPath (path);
  69968. Path::Iterator iter (path);
  69969. bool containsClosedSubPath = false;
  69970. while (iter.next())
  69971. {
  69972. if (iter.elementType == Path::Iterator::closePath)
  69973. {
  69974. containsClosedSubPath = true;
  69975. break;
  69976. }
  69977. }
  69978. dp->setFill (getPathFillType (path,
  69979. getStyleAttribute (&xml, "fill"),
  69980. getStyleAttribute (&xml, "fill-opacity"),
  69981. getStyleAttribute (&xml, "opacity"),
  69982. containsClosedSubPath ? Colours::black
  69983. : Colours::transparentBlack));
  69984. const String strokeType (getStyleAttribute (&xml, "stroke"));
  69985. if (strokeType.isNotEmpty() && ! strokeType.equalsIgnoreCase ("none"))
  69986. {
  69987. dp->setStrokeFill (getPathFillType (path, strokeType,
  69988. getStyleAttribute (&xml, "stroke-opacity"),
  69989. getStyleAttribute (&xml, "opacity"),
  69990. Colours::transparentBlack));
  69991. dp->setStrokeType (getStrokeFor (&xml));
  69992. }
  69993. return dp;
  69994. }
  69995. const XmlElement* findLinkedElement (const XmlElement* e) const
  69996. {
  69997. const String id (e->getStringAttribute ("xlink:href"));
  69998. if (! id.startsWithChar ('#'))
  69999. return 0;
  70000. return findElementForId (topLevelXml, id.substring (1));
  70001. }
  70002. void addGradientStopsIn (ColourGradient& cg, const XmlElement* const fillXml) const
  70003. {
  70004. if (fillXml == 0)
  70005. return;
  70006. forEachXmlChildElementWithTagName (*fillXml, e, "stop")
  70007. {
  70008. int index = 0;
  70009. Colour col (parseColour (getStyleAttribute (e, "stop-color"), index, Colours::black));
  70010. const String opacity (getStyleAttribute (e, "stop-opacity", "1"));
  70011. col = col.withMultipliedAlpha (jlimit (0.0f, 1.0f, opacity.getFloatValue()));
  70012. double offset = e->getDoubleAttribute ("offset");
  70013. if (e->getStringAttribute ("offset").containsChar ('%'))
  70014. offset *= 0.01;
  70015. cg.addColour (jlimit (0.0, 1.0, offset), col);
  70016. }
  70017. }
  70018. const FillType getPathFillType (const Path& path,
  70019. const String& fill,
  70020. const String& fillOpacity,
  70021. const String& overallOpacity,
  70022. const Colour& defaultColour) const
  70023. {
  70024. float opacity = 1.0f;
  70025. if (overallOpacity.isNotEmpty())
  70026. opacity = jlimit (0.0f, 1.0f, overallOpacity.getFloatValue());
  70027. if (fillOpacity.isNotEmpty())
  70028. opacity *= (jlimit (0.0f, 1.0f, fillOpacity.getFloatValue()));
  70029. if (fill.startsWithIgnoreCase ("url"))
  70030. {
  70031. const String id (fill.fromFirstOccurrenceOf ("#", false, false)
  70032. .upToLastOccurrenceOf (")", false, false).trim());
  70033. const XmlElement* const fillXml = findElementForId (topLevelXml, id);
  70034. if (fillXml != 0
  70035. && (fillXml->hasTagName ("linearGradient")
  70036. || fillXml->hasTagName ("radialGradient")))
  70037. {
  70038. const XmlElement* inheritedFrom = findLinkedElement (fillXml);
  70039. ColourGradient gradient;
  70040. addGradientStopsIn (gradient, inheritedFrom);
  70041. addGradientStopsIn (gradient, fillXml);
  70042. if (gradient.getNumColours() > 0)
  70043. {
  70044. gradient.addColour (0.0, gradient.getColour (0));
  70045. gradient.addColour (1.0, gradient.getColour (gradient.getNumColours() - 1));
  70046. }
  70047. else
  70048. {
  70049. gradient.addColour (0.0, Colours::black);
  70050. gradient.addColour (1.0, Colours::black);
  70051. }
  70052. if (overallOpacity.isNotEmpty())
  70053. gradient.multiplyOpacity (overallOpacity.getFloatValue());
  70054. jassert (gradient.getNumColours() > 0);
  70055. gradient.isRadial = fillXml->hasTagName ("radialGradient");
  70056. float gradientWidth = viewBoxW;
  70057. float gradientHeight = viewBoxH;
  70058. float dx = 0.0f;
  70059. float dy = 0.0f;
  70060. const bool userSpace = fillXml->getStringAttribute ("gradientUnits").equalsIgnoreCase ("userSpaceOnUse");
  70061. if (! userSpace)
  70062. {
  70063. const Rectangle<float> bounds (path.getBounds());
  70064. dx = bounds.getX();
  70065. dy = bounds.getY();
  70066. gradientWidth = bounds.getWidth();
  70067. gradientHeight = bounds.getHeight();
  70068. }
  70069. if (gradient.isRadial)
  70070. {
  70071. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("cx", "50%"), gradientWidth),
  70072. dy + getCoordLength (fillXml->getStringAttribute ("cy", "50%"), gradientHeight));
  70073. const float radius = getCoordLength (fillXml->getStringAttribute ("r", "50%"), gradientWidth);
  70074. gradient.point2 = gradient.point1 + Point<float> (radius, 0.0f);
  70075. //xxx (the fx, fy focal point isn't handled properly here..)
  70076. }
  70077. else
  70078. {
  70079. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x1", "0%"), gradientWidth),
  70080. dy + getCoordLength (fillXml->getStringAttribute ("y1", "0%"), gradientHeight));
  70081. gradient.point2.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x2", "100%"), gradientWidth),
  70082. dy + getCoordLength (fillXml->getStringAttribute ("y2", "0%"), gradientHeight));
  70083. if (gradient.point1 == gradient.point2)
  70084. return Colour (gradient.getColour (gradient.getNumColours() - 1));
  70085. }
  70086. FillType type (gradient);
  70087. type.transform = parseTransform (fillXml->getStringAttribute ("gradientTransform"))
  70088. .followedBy (transform);
  70089. return type;
  70090. }
  70091. }
  70092. if (fill.equalsIgnoreCase ("none"))
  70093. return Colours::transparentBlack;
  70094. int i = 0;
  70095. const Colour colour (parseColour (fill, i, defaultColour));
  70096. return colour.withMultipliedAlpha (opacity);
  70097. }
  70098. const PathStrokeType getStrokeFor (const XmlElement* const xml) const
  70099. {
  70100. const String strokeWidth (getStyleAttribute (xml, "stroke-width"));
  70101. const String cap (getStyleAttribute (xml, "stroke-linecap"));
  70102. const String join (getStyleAttribute (xml, "stroke-linejoin"));
  70103. //const String mitreLimit (getStyleAttribute (xml, "stroke-miterlimit"));
  70104. //const String dashArray (getStyleAttribute (xml, "stroke-dasharray"));
  70105. //const String dashOffset (getStyleAttribute (xml, "stroke-dashoffset"));
  70106. PathStrokeType::JointStyle joinStyle = PathStrokeType::mitered;
  70107. PathStrokeType::EndCapStyle capStyle = PathStrokeType::butt;
  70108. if (join.equalsIgnoreCase ("round"))
  70109. joinStyle = PathStrokeType::curved;
  70110. else if (join.equalsIgnoreCase ("bevel"))
  70111. joinStyle = PathStrokeType::beveled;
  70112. if (cap.equalsIgnoreCase ("round"))
  70113. capStyle = PathStrokeType::rounded;
  70114. else if (cap.equalsIgnoreCase ("square"))
  70115. capStyle = PathStrokeType::square;
  70116. float ox = 0.0f, oy = 0.0f;
  70117. float x = getCoordLength (strokeWidth, viewBoxW), y = 0.0f;
  70118. transform.transformPoints (ox, oy, x, y);
  70119. return PathStrokeType (strokeWidth.isNotEmpty() ? juce_hypotf (x - ox, y - oy) : 1.0f,
  70120. joinStyle, capStyle);
  70121. }
  70122. Drawable* parseText (const XmlElement& xml)
  70123. {
  70124. Array <float> xCoords, yCoords, dxCoords, dyCoords;
  70125. getCoordList (xCoords, getInheritedAttribute (&xml, "x"), true, true);
  70126. getCoordList (yCoords, getInheritedAttribute (&xml, "y"), true, false);
  70127. getCoordList (dxCoords, getInheritedAttribute (&xml, "dx"), true, true);
  70128. getCoordList (dyCoords, getInheritedAttribute (&xml, "dy"), true, false);
  70129. //xxx not done text yet!
  70130. forEachXmlChildElement (xml, e)
  70131. {
  70132. if (e->isTextElement())
  70133. {
  70134. const String text (e->getText());
  70135. Path path;
  70136. Drawable* s = parseShape (*e, path);
  70137. delete s;
  70138. }
  70139. else if (e->hasTagName ("tspan"))
  70140. {
  70141. Drawable* s = parseText (*e);
  70142. delete s;
  70143. }
  70144. }
  70145. return 0;
  70146. }
  70147. void addTransform (const XmlElement& xml)
  70148. {
  70149. transform = parseTransform (xml.getStringAttribute ("transform"))
  70150. .followedBy (transform);
  70151. }
  70152. bool parseCoord (const String& s, float& value, int& index,
  70153. const bool allowUnits, const bool isX) const
  70154. {
  70155. String number;
  70156. if (! parseNextNumber (s, number, index, allowUnits))
  70157. {
  70158. value = 0;
  70159. return false;
  70160. }
  70161. value = getCoordLength (number, isX ? viewBoxW : viewBoxH);
  70162. return true;
  70163. }
  70164. bool parseCoords (const String& s, float& x, float& y,
  70165. int& index, const bool allowUnits) const
  70166. {
  70167. return parseCoord (s, x, index, allowUnits, true)
  70168. && parseCoord (s, y, index, allowUnits, false);
  70169. }
  70170. float getCoordLength (const String& s, const float sizeForProportions) const
  70171. {
  70172. float n = s.getFloatValue();
  70173. const int len = s.length();
  70174. if (len > 2)
  70175. {
  70176. const float dpi = 96.0f;
  70177. const juce_wchar n1 = s [len - 2];
  70178. const juce_wchar n2 = s [len - 1];
  70179. if (n1 == 'i' && n2 == 'n')
  70180. n *= dpi;
  70181. else if (n1 == 'm' && n2 == 'm')
  70182. n *= dpi / 25.4f;
  70183. else if (n1 == 'c' && n2 == 'm')
  70184. n *= dpi / 2.54f;
  70185. else if (n1 == 'p' && n2 == 'c')
  70186. n *= 15.0f;
  70187. else if (n2 == '%')
  70188. n *= 0.01f * sizeForProportions;
  70189. }
  70190. return n;
  70191. }
  70192. void getCoordList (Array <float>& coords, const String& list,
  70193. const bool allowUnits, const bool isX) const
  70194. {
  70195. int index = 0;
  70196. float value;
  70197. while (parseCoord (list, value, index, allowUnits, isX))
  70198. coords.add (value);
  70199. }
  70200. void parseCSSStyle (const XmlElement& xml)
  70201. {
  70202. cssStyleText = xml.getAllSubText() + "\n" + cssStyleText;
  70203. }
  70204. const String getStyleAttribute (const XmlElement* xml, const String& attributeName,
  70205. const String& defaultValue = String::empty) const
  70206. {
  70207. if (xml->hasAttribute (attributeName))
  70208. return xml->getStringAttribute (attributeName, defaultValue);
  70209. const String styleAtt (xml->getStringAttribute ("style"));
  70210. if (styleAtt.isNotEmpty())
  70211. {
  70212. const String value (getAttributeFromStyleList (styleAtt, attributeName, String::empty));
  70213. if (value.isNotEmpty())
  70214. return value;
  70215. }
  70216. else if (xml->hasAttribute ("class"))
  70217. {
  70218. const String className ("." + xml->getStringAttribute ("class"));
  70219. int index = cssStyleText.indexOfIgnoreCase (className + " ");
  70220. if (index < 0)
  70221. index = cssStyleText.indexOfIgnoreCase (className + "{");
  70222. if (index >= 0)
  70223. {
  70224. const int openBracket = cssStyleText.indexOfChar (index, '{');
  70225. if (openBracket > index)
  70226. {
  70227. const int closeBracket = cssStyleText.indexOfChar (openBracket, '}');
  70228. if (closeBracket > openBracket)
  70229. {
  70230. const String value (getAttributeFromStyleList (cssStyleText.substring (openBracket + 1, closeBracket), attributeName, defaultValue));
  70231. if (value.isNotEmpty())
  70232. return value;
  70233. }
  70234. }
  70235. }
  70236. }
  70237. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  70238. if (xml != 0)
  70239. return getStyleAttribute (xml, attributeName, defaultValue);
  70240. return defaultValue;
  70241. }
  70242. const String getInheritedAttribute (const XmlElement* xml, const String& attributeName) const
  70243. {
  70244. if (xml->hasAttribute (attributeName))
  70245. return xml->getStringAttribute (attributeName);
  70246. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  70247. if (xml != 0)
  70248. return getInheritedAttribute (xml, attributeName);
  70249. return String::empty;
  70250. }
  70251. static bool isIdentifierChar (const juce_wchar c)
  70252. {
  70253. return CharacterFunctions::isLetter (c) || c == '-';
  70254. }
  70255. static const String getAttributeFromStyleList (const String& list, const String& attributeName, const String& defaultValue)
  70256. {
  70257. int i = 0;
  70258. for (;;)
  70259. {
  70260. i = list.indexOf (i, attributeName);
  70261. if (i < 0)
  70262. break;
  70263. if ((i == 0 || (i > 0 && ! isIdentifierChar (list [i - 1])))
  70264. && ! isIdentifierChar (list [i + attributeName.length()]))
  70265. {
  70266. i = list.indexOfChar (i, ':');
  70267. if (i < 0)
  70268. break;
  70269. int end = list.indexOfChar (i, ';');
  70270. if (end < 0)
  70271. end = 0x7ffff;
  70272. return list.substring (i + 1, end).trim();
  70273. }
  70274. ++i;
  70275. }
  70276. return defaultValue;
  70277. }
  70278. static bool parseNextNumber (const String& source, String& value, int& index, const bool allowUnits)
  70279. {
  70280. const juce_wchar* const s = source;
  70281. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  70282. ++index;
  70283. int start = index;
  70284. if (CharacterFunctions::isDigit (s[index]) || s[index] == '.' || s[index] == '-')
  70285. ++index;
  70286. while (CharacterFunctions::isDigit (s[index]) || s[index] == '.')
  70287. ++index;
  70288. if ((s[index] == 'e' || s[index] == 'E')
  70289. && (CharacterFunctions::isDigit (s[index + 1])
  70290. || s[index + 1] == '-'
  70291. || s[index + 1] == '+'))
  70292. {
  70293. index += 2;
  70294. while (CharacterFunctions::isDigit (s[index]))
  70295. ++index;
  70296. }
  70297. if (allowUnits)
  70298. {
  70299. while (CharacterFunctions::isLetter (s[index]))
  70300. ++index;
  70301. }
  70302. if (index == start)
  70303. return false;
  70304. value = String (s + start, index - start);
  70305. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  70306. ++index;
  70307. return true;
  70308. }
  70309. static const Colour parseColour (const String& s, int& index, const Colour& defaultColour)
  70310. {
  70311. if (s [index] == '#')
  70312. {
  70313. uint32 hex [6];
  70314. zeromem (hex, sizeof (hex));
  70315. int numChars = 0;
  70316. for (int i = 6; --i >= 0;)
  70317. {
  70318. const int hexValue = CharacterFunctions::getHexDigitValue (s [++index]);
  70319. if (hexValue >= 0)
  70320. hex [numChars++] = hexValue;
  70321. else
  70322. break;
  70323. }
  70324. if (numChars <= 3)
  70325. return Colour ((uint8) (hex [0] * 0x11),
  70326. (uint8) (hex [1] * 0x11),
  70327. (uint8) (hex [2] * 0x11));
  70328. else
  70329. return Colour ((uint8) ((hex [0] << 4) + hex [1]),
  70330. (uint8) ((hex [2] << 4) + hex [3]),
  70331. (uint8) ((hex [4] << 4) + hex [5]));
  70332. }
  70333. else if (s [index] == 'r'
  70334. && s [index + 1] == 'g'
  70335. && s [index + 2] == 'b')
  70336. {
  70337. const int openBracket = s.indexOfChar (index, '(');
  70338. const int closeBracket = s.indexOfChar (openBracket, ')');
  70339. if (openBracket >= 3 && closeBracket > openBracket)
  70340. {
  70341. index = closeBracket;
  70342. StringArray tokens;
  70343. tokens.addTokens (s.substring (openBracket + 1, closeBracket), ",", "");
  70344. tokens.trim();
  70345. tokens.removeEmptyStrings();
  70346. if (tokens[0].containsChar ('%'))
  70347. return Colour ((uint8) roundToInt (2.55 * tokens[0].getDoubleValue()),
  70348. (uint8) roundToInt (2.55 * tokens[1].getDoubleValue()),
  70349. (uint8) roundToInt (2.55 * tokens[2].getDoubleValue()));
  70350. else
  70351. return Colour ((uint8) tokens[0].getIntValue(),
  70352. (uint8) tokens[1].getIntValue(),
  70353. (uint8) tokens[2].getIntValue());
  70354. }
  70355. }
  70356. return Colours::findColourForName (s, defaultColour);
  70357. }
  70358. static const AffineTransform parseTransform (String t)
  70359. {
  70360. AffineTransform result;
  70361. while (t.isNotEmpty())
  70362. {
  70363. StringArray tokens;
  70364. tokens.addTokens (t.fromFirstOccurrenceOf ("(", false, false)
  70365. .upToFirstOccurrenceOf (")", false, false),
  70366. ", ", String::empty);
  70367. tokens.removeEmptyStrings (true);
  70368. float numbers [6];
  70369. for (int i = 0; i < 6; ++i)
  70370. numbers[i] = tokens[i].getFloatValue();
  70371. AffineTransform trans;
  70372. if (t.startsWithIgnoreCase ("matrix"))
  70373. {
  70374. trans = AffineTransform (numbers[0], numbers[2], numbers[4],
  70375. numbers[1], numbers[3], numbers[5]);
  70376. }
  70377. else if (t.startsWithIgnoreCase ("translate"))
  70378. {
  70379. jassert (tokens.size() == 2);
  70380. trans = AffineTransform::translation (numbers[0], numbers[1]);
  70381. }
  70382. else if (t.startsWithIgnoreCase ("scale"))
  70383. {
  70384. if (tokens.size() == 1)
  70385. trans = AffineTransform::scale (numbers[0], numbers[0]);
  70386. else
  70387. trans = AffineTransform::scale (numbers[0], numbers[1]);
  70388. }
  70389. else if (t.startsWithIgnoreCase ("rotate"))
  70390. {
  70391. if (tokens.size() != 3)
  70392. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi));
  70393. else
  70394. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi),
  70395. numbers[1], numbers[2]);
  70396. }
  70397. else if (t.startsWithIgnoreCase ("skewX"))
  70398. {
  70399. trans = AffineTransform (1.0f, std::tan (numbers[0] * (float_Pi / 180.0f)), 0.0f,
  70400. 0.0f, 1.0f, 0.0f);
  70401. }
  70402. else if (t.startsWithIgnoreCase ("skewY"))
  70403. {
  70404. trans = AffineTransform (1.0f, 0.0f, 0.0f,
  70405. std::tan (numbers[0] * (float_Pi / 180.0f)), 1.0f, 0.0f);
  70406. }
  70407. result = trans.followedBy (result);
  70408. t = t.fromFirstOccurrenceOf (")", false, false).trimStart();
  70409. }
  70410. return result;
  70411. }
  70412. static void endpointToCentreParameters (const double x1, const double y1,
  70413. const double x2, const double y2,
  70414. const double angle,
  70415. const bool largeArc, const bool sweep,
  70416. double& rx, double& ry,
  70417. double& centreX, double& centreY,
  70418. double& startAngle, double& deltaAngle)
  70419. {
  70420. const double midX = (x1 - x2) * 0.5;
  70421. const double midY = (y1 - y2) * 0.5;
  70422. const double cosAngle = cos (angle);
  70423. const double sinAngle = sin (angle);
  70424. const double xp = cosAngle * midX + sinAngle * midY;
  70425. const double yp = cosAngle * midY - sinAngle * midX;
  70426. const double xp2 = xp * xp;
  70427. const double yp2 = yp * yp;
  70428. double rx2 = rx * rx;
  70429. double ry2 = ry * ry;
  70430. const double s = (xp2 / rx2) + (yp2 / ry2);
  70431. double c;
  70432. if (s <= 1.0)
  70433. {
  70434. c = std::sqrt (jmax (0.0, ((rx2 * ry2) - (rx2 * yp2) - (ry2 * xp2))
  70435. / (( rx2 * yp2) + (ry2 * xp2))));
  70436. if (largeArc == sweep)
  70437. c = -c;
  70438. }
  70439. else
  70440. {
  70441. const double s2 = std::sqrt (s);
  70442. rx *= s2;
  70443. ry *= s2;
  70444. rx2 = rx * rx;
  70445. ry2 = ry * ry;
  70446. c = 0;
  70447. }
  70448. const double cpx = ((rx * yp) / ry) * c;
  70449. const double cpy = ((-ry * xp) / rx) * c;
  70450. centreX = ((x1 + x2) * 0.5) + (cosAngle * cpx) - (sinAngle * cpy);
  70451. centreY = ((y1 + y2) * 0.5) + (sinAngle * cpx) + (cosAngle * cpy);
  70452. const double ux = (xp - cpx) / rx;
  70453. const double uy = (yp - cpy) / ry;
  70454. const double vx = (-xp - cpx) / rx;
  70455. const double vy = (-yp - cpy) / ry;
  70456. const double length = juce_hypot (ux, uy);
  70457. startAngle = acos (jlimit (-1.0, 1.0, ux / length));
  70458. if (uy < 0)
  70459. startAngle = -startAngle;
  70460. startAngle += double_Pi * 0.5;
  70461. deltaAngle = acos (jlimit (-1.0, 1.0, ((ux * vx) + (uy * vy))
  70462. / (length * juce_hypot (vx, vy))));
  70463. if ((ux * vy) - (uy * vx) < 0)
  70464. deltaAngle = -deltaAngle;
  70465. if (sweep)
  70466. {
  70467. if (deltaAngle < 0)
  70468. deltaAngle += double_Pi * 2.0;
  70469. }
  70470. else
  70471. {
  70472. if (deltaAngle > 0)
  70473. deltaAngle -= double_Pi * 2.0;
  70474. }
  70475. deltaAngle = fmod (deltaAngle, double_Pi * 2.0);
  70476. }
  70477. static const XmlElement* findElementForId (const XmlElement* const parent, const String& id)
  70478. {
  70479. forEachXmlChildElement (*parent, e)
  70480. {
  70481. if (e->compareAttribute ("id", id))
  70482. return e;
  70483. const XmlElement* const found = findElementForId (e, id);
  70484. if (found != 0)
  70485. return found;
  70486. }
  70487. return 0;
  70488. }
  70489. SVGState& operator= (const SVGState&);
  70490. };
  70491. Drawable* Drawable::createFromSVG (const XmlElement& svgDocument)
  70492. {
  70493. SVGState state (&svgDocument);
  70494. return state.parseSVGElement (svgDocument);
  70495. }
  70496. END_JUCE_NAMESPACE
  70497. /*** End of inlined file: juce_SVGParser.cpp ***/
  70498. /*** Start of inlined file: juce_DropShadowEffect.cpp ***/
  70499. BEGIN_JUCE_NAMESPACE
  70500. #if JUCE_MSVC && JUCE_DEBUG
  70501. #pragma optimize ("t", on)
  70502. #endif
  70503. DropShadowEffect::DropShadowEffect()
  70504. : offsetX (0),
  70505. offsetY (0),
  70506. radius (4),
  70507. opacity (0.6f)
  70508. {
  70509. }
  70510. DropShadowEffect::~DropShadowEffect()
  70511. {
  70512. }
  70513. void DropShadowEffect::setShadowProperties (const float newRadius,
  70514. const float newOpacity,
  70515. const int newShadowOffsetX,
  70516. const int newShadowOffsetY)
  70517. {
  70518. radius = jmax (1.1f, newRadius);
  70519. offsetX = newShadowOffsetX;
  70520. offsetY = newShadowOffsetY;
  70521. opacity = newOpacity;
  70522. }
  70523. void DropShadowEffect::applyEffect (Image& image, Graphics& g)
  70524. {
  70525. const int w = image.getWidth();
  70526. const int h = image.getHeight();
  70527. Image shadowImage (Image::SingleChannel, w, h, false);
  70528. const Image::BitmapData srcData (image, 0, 0, w, h);
  70529. const Image::BitmapData destData (shadowImage, 0, 0, w, h, true);
  70530. const int filter = roundToInt (63.0f / radius);
  70531. const int radiusMinus1 = roundToInt ((radius - 1.0f) * 63.0f);
  70532. for (int x = w; --x >= 0;)
  70533. {
  70534. int shadowAlpha = 0;
  70535. const PixelARGB* src = ((const PixelARGB*) srcData.data) + x;
  70536. uint8* shadowPix = destData.data + x;
  70537. for (int y = h; --y >= 0;)
  70538. {
  70539. shadowAlpha = ((shadowAlpha * radiusMinus1 + (src->getAlpha() << 6)) * filter) >> 12;
  70540. *shadowPix = (uint8) shadowAlpha;
  70541. src = (const PixelARGB*) (((const uint8*) src) + srcData.lineStride);
  70542. shadowPix += destData.lineStride;
  70543. }
  70544. }
  70545. for (int y = h; --y >= 0;)
  70546. {
  70547. int shadowAlpha = 0;
  70548. uint8* shadowPix = destData.getLinePointer (y);
  70549. for (int x = w; --x >= 0;)
  70550. {
  70551. shadowAlpha = ((shadowAlpha * radiusMinus1 + (*shadowPix << 6)) * filter) >> 12;
  70552. *shadowPix++ = (uint8) shadowAlpha;
  70553. }
  70554. }
  70555. g.setColour (Colours::black.withAlpha (opacity));
  70556. g.drawImageAt (shadowImage, offsetX, offsetY, true);
  70557. g.setOpacity (1.0f);
  70558. g.drawImageAt (image, 0, 0);
  70559. }
  70560. #if JUCE_MSVC && JUCE_DEBUG
  70561. #pragma optimize ("", on) // resets optimisations to the project defaults
  70562. #endif
  70563. END_JUCE_NAMESPACE
  70564. /*** End of inlined file: juce_DropShadowEffect.cpp ***/
  70565. /*** Start of inlined file: juce_GlowEffect.cpp ***/
  70566. BEGIN_JUCE_NAMESPACE
  70567. GlowEffect::GlowEffect()
  70568. : radius (2.0f),
  70569. colour (Colours::white)
  70570. {
  70571. }
  70572. GlowEffect::~GlowEffect()
  70573. {
  70574. }
  70575. void GlowEffect::setGlowProperties (const float newRadius,
  70576. const Colour& newColour)
  70577. {
  70578. radius = newRadius;
  70579. colour = newColour;
  70580. }
  70581. void GlowEffect::applyEffect (Image& image, Graphics& g)
  70582. {
  70583. Image temp (image.getFormat(), image.getWidth(), image.getHeight(), true);
  70584. ImageConvolutionKernel blurKernel (roundToInt (radius * 2.0f));
  70585. blurKernel.createGaussianBlur (radius);
  70586. blurKernel.rescaleAllValues (radius);
  70587. blurKernel.applyToImage (temp, image, image.getBounds());
  70588. g.setColour (colour);
  70589. g.drawImageAt (temp, 0, 0, true);
  70590. g.setOpacity (1.0f);
  70591. g.drawImageAt (image, 0, 0, false);
  70592. }
  70593. END_JUCE_NAMESPACE
  70594. /*** End of inlined file: juce_GlowEffect.cpp ***/
  70595. /*** Start of inlined file: juce_ReduceOpacityEffect.cpp ***/
  70596. BEGIN_JUCE_NAMESPACE
  70597. ReduceOpacityEffect::ReduceOpacityEffect (const float opacity_)
  70598. : opacity (opacity_)
  70599. {
  70600. }
  70601. ReduceOpacityEffect::~ReduceOpacityEffect()
  70602. {
  70603. }
  70604. void ReduceOpacityEffect::setOpacity (const float newOpacity)
  70605. {
  70606. opacity = jlimit (0.0f, 1.0f, newOpacity);
  70607. }
  70608. void ReduceOpacityEffect::applyEffect (Image& image, Graphics& g)
  70609. {
  70610. g.setOpacity (opacity);
  70611. g.drawImageAt (image, 0, 0);
  70612. }
  70613. END_JUCE_NAMESPACE
  70614. /*** End of inlined file: juce_ReduceOpacityEffect.cpp ***/
  70615. /*** Start of inlined file: juce_Font.cpp ***/
  70616. BEGIN_JUCE_NAMESPACE
  70617. namespace FontValues
  70618. {
  70619. static float limitFontHeight (const float height) throw()
  70620. {
  70621. return jlimit (0.1f, 10000.0f, height);
  70622. }
  70623. static const float defaultFontHeight = 14.0f;
  70624. static String fallbackFont;
  70625. }
  70626. Font::SharedFontInternal::SharedFontInternal (const String& typefaceName_, const float height_, const float horizontalScale_,
  70627. const float kerning_, const float ascent_, const int styleFlags_,
  70628. Typeface* const typeface_) throw()
  70629. : typefaceName (typefaceName_),
  70630. height (height_),
  70631. horizontalScale (horizontalScale_),
  70632. kerning (kerning_),
  70633. ascent (ascent_),
  70634. styleFlags (styleFlags_),
  70635. typeface (typeface_)
  70636. {
  70637. }
  70638. Font::SharedFontInternal::SharedFontInternal (const SharedFontInternal& other) throw()
  70639. : typefaceName (other.typefaceName),
  70640. height (other.height),
  70641. horizontalScale (other.horizontalScale),
  70642. kerning (other.kerning),
  70643. ascent (other.ascent),
  70644. styleFlags (other.styleFlags),
  70645. typeface (other.typeface)
  70646. {
  70647. }
  70648. Font::Font() throw()
  70649. : font (new SharedFontInternal (getDefaultSansSerifFontName(), FontValues::defaultFontHeight,
  70650. 1.0f, 0, 0, Font::plain, 0))
  70651. {
  70652. }
  70653. Font::Font (const float fontHeight, const int styleFlags_) throw()
  70654. : font (new SharedFontInternal (getDefaultSansSerifFontName(), FontValues::limitFontHeight (fontHeight),
  70655. 1.0f, 0, 0, styleFlags_, 0))
  70656. {
  70657. }
  70658. Font::Font (const String& typefaceName_,
  70659. const float fontHeight,
  70660. const int styleFlags_) throw()
  70661. : font (new SharedFontInternal (typefaceName_, FontValues::limitFontHeight (fontHeight),
  70662. 1.0f, 0, 0, styleFlags_, 0))
  70663. {
  70664. }
  70665. Font::Font (const Font& other) throw()
  70666. : font (other.font)
  70667. {
  70668. }
  70669. Font& Font::operator= (const Font& other) throw()
  70670. {
  70671. font = other.font;
  70672. return *this;
  70673. }
  70674. Font::~Font() throw()
  70675. {
  70676. }
  70677. Font::Font (const Typeface::Ptr& typeface) throw()
  70678. : font (new SharedFontInternal (typeface->getName(), FontValues::defaultFontHeight,
  70679. 1.0f, 0, 0, Font::plain, typeface))
  70680. {
  70681. }
  70682. bool Font::operator== (const Font& other) const throw()
  70683. {
  70684. return font == other.font
  70685. || (font->height == other.font->height
  70686. && font->styleFlags == other.font->styleFlags
  70687. && font->horizontalScale == other.font->horizontalScale
  70688. && font->kerning == other.font->kerning
  70689. && font->typefaceName == other.font->typefaceName);
  70690. }
  70691. bool Font::operator!= (const Font& other) const throw()
  70692. {
  70693. return ! operator== (other);
  70694. }
  70695. void Font::dupeInternalIfShared() throw()
  70696. {
  70697. if (font->getReferenceCount() > 1)
  70698. font = new SharedFontInternal (*font);
  70699. }
  70700. const String Font::getDefaultSansSerifFontName() throw()
  70701. {
  70702. static const String name ("<Sans-Serif>");
  70703. return name;
  70704. }
  70705. const String Font::getDefaultSerifFontName() throw()
  70706. {
  70707. static const String name ("<Serif>");
  70708. return name;
  70709. }
  70710. const String Font::getDefaultMonospacedFontName() throw()
  70711. {
  70712. static const String name ("<Monospaced>");
  70713. return name;
  70714. }
  70715. void Font::setTypefaceName (const String& faceName) throw()
  70716. {
  70717. if (faceName != font->typefaceName)
  70718. {
  70719. dupeInternalIfShared();
  70720. font->typefaceName = faceName;
  70721. font->typeface = 0;
  70722. font->ascent = 0;
  70723. }
  70724. }
  70725. const String Font::getFallbackFontName() throw()
  70726. {
  70727. return FontValues::fallbackFont;
  70728. }
  70729. void Font::setFallbackFontName (const String& name) throw()
  70730. {
  70731. FontValues::fallbackFont = name;
  70732. }
  70733. void Font::setHeight (float newHeight) throw()
  70734. {
  70735. newHeight = FontValues::limitFontHeight (newHeight);
  70736. if (font->height != newHeight)
  70737. {
  70738. dupeInternalIfShared();
  70739. font->height = newHeight;
  70740. }
  70741. }
  70742. void Font::setHeightWithoutChangingWidth (float newHeight) throw()
  70743. {
  70744. newHeight = FontValues::limitFontHeight (newHeight);
  70745. if (font->height != newHeight)
  70746. {
  70747. dupeInternalIfShared();
  70748. font->horizontalScale *= (font->height / newHeight);
  70749. font->height = newHeight;
  70750. }
  70751. }
  70752. void Font::setStyleFlags (const int newFlags) throw()
  70753. {
  70754. if (font->styleFlags != newFlags)
  70755. {
  70756. dupeInternalIfShared();
  70757. font->styleFlags = newFlags;
  70758. font->typeface = 0;
  70759. font->ascent = 0;
  70760. }
  70761. }
  70762. void Font::setSizeAndStyle (float newHeight,
  70763. const int newStyleFlags,
  70764. const float newHorizontalScale,
  70765. const float newKerningAmount) throw()
  70766. {
  70767. newHeight = FontValues::limitFontHeight (newHeight);
  70768. if (font->height != newHeight
  70769. || font->horizontalScale != newHorizontalScale
  70770. || font->kerning != newKerningAmount)
  70771. {
  70772. dupeInternalIfShared();
  70773. font->height = newHeight;
  70774. font->horizontalScale = newHorizontalScale;
  70775. font->kerning = newKerningAmount;
  70776. }
  70777. setStyleFlags (newStyleFlags);
  70778. }
  70779. void Font::setHorizontalScale (const float scaleFactor) throw()
  70780. {
  70781. dupeInternalIfShared();
  70782. font->horizontalScale = scaleFactor;
  70783. }
  70784. void Font::setExtraKerningFactor (const float extraKerning) throw()
  70785. {
  70786. dupeInternalIfShared();
  70787. font->kerning = extraKerning;
  70788. }
  70789. void Font::setBold (const bool shouldBeBold) throw()
  70790. {
  70791. setStyleFlags (shouldBeBold ? (font->styleFlags | bold)
  70792. : (font->styleFlags & ~bold));
  70793. }
  70794. bool Font::isBold() const throw()
  70795. {
  70796. return (font->styleFlags & bold) != 0;
  70797. }
  70798. void Font::setItalic (const bool shouldBeItalic) throw()
  70799. {
  70800. setStyleFlags (shouldBeItalic ? (font->styleFlags | italic)
  70801. : (font->styleFlags & ~italic));
  70802. }
  70803. bool Font::isItalic() const throw()
  70804. {
  70805. return (font->styleFlags & italic) != 0;
  70806. }
  70807. void Font::setUnderline (const bool shouldBeUnderlined) throw()
  70808. {
  70809. setStyleFlags (shouldBeUnderlined ? (font->styleFlags | underlined)
  70810. : (font->styleFlags & ~underlined));
  70811. }
  70812. bool Font::isUnderlined() const throw()
  70813. {
  70814. return (font->styleFlags & underlined) != 0;
  70815. }
  70816. float Font::getAscent() const throw()
  70817. {
  70818. if (font->ascent == 0)
  70819. font->ascent = getTypeface()->getAscent();
  70820. return font->height * font->ascent;
  70821. }
  70822. float Font::getDescent() const throw()
  70823. {
  70824. return font->height - getAscent();
  70825. }
  70826. int Font::getStringWidth (const String& text) const throw()
  70827. {
  70828. return roundToInt (getStringWidthFloat (text));
  70829. }
  70830. float Font::getStringWidthFloat (const String& text) const throw()
  70831. {
  70832. float w = getTypeface()->getStringWidth (text);
  70833. if (font->kerning != 0)
  70834. w += font->kerning * text.length();
  70835. return w * font->height * font->horizontalScale;
  70836. }
  70837. void Font::getGlyphPositions (const String& text, Array <int>& glyphs, Array <float>& xOffsets) const throw()
  70838. {
  70839. getTypeface()->getGlyphPositions (text, glyphs, xOffsets);
  70840. const float scale = font->height * font->horizontalScale;
  70841. const int num = xOffsets.size();
  70842. if (num > 0)
  70843. {
  70844. float* const x = &(xOffsets.getReference(0));
  70845. if (font->kerning != 0)
  70846. {
  70847. for (int i = 0; i < num; ++i)
  70848. x[i] = (x[i] + i * font->kerning) * scale;
  70849. }
  70850. else
  70851. {
  70852. for (int i = 0; i < num; ++i)
  70853. x[i] *= scale;
  70854. }
  70855. }
  70856. }
  70857. void Font::findFonts (Array<Font>& destArray) throw()
  70858. {
  70859. const StringArray names (findAllTypefaceNames());
  70860. for (int i = 0; i < names.size(); ++i)
  70861. destArray.add (Font (names[i], FontValues::defaultFontHeight, Font::plain));
  70862. }
  70863. const String Font::toString() const
  70864. {
  70865. String s (getTypefaceName());
  70866. if (s == getDefaultSansSerifFontName())
  70867. s = String::empty;
  70868. else
  70869. s += "; ";
  70870. s += String (getHeight(), 1);
  70871. if (isBold())
  70872. s += " bold";
  70873. if (isItalic())
  70874. s += " italic";
  70875. return s;
  70876. }
  70877. const Font Font::fromString (const String& fontDescription)
  70878. {
  70879. String name;
  70880. const int separator = fontDescription.indexOfChar (';');
  70881. if (separator > 0)
  70882. name = fontDescription.substring (0, separator).trim();
  70883. if (name.isEmpty())
  70884. name = getDefaultSansSerifFontName();
  70885. String sizeAndStyle (fontDescription.substring (separator + 1));
  70886. float height = sizeAndStyle.getFloatValue();
  70887. if (height <= 0)
  70888. height = 10.0f;
  70889. int flags = Font::plain;
  70890. if (sizeAndStyle.containsIgnoreCase ("bold"))
  70891. flags |= Font::bold;
  70892. if (sizeAndStyle.containsIgnoreCase ("italic"))
  70893. flags |= Font::italic;
  70894. return Font (name, height, flags);
  70895. }
  70896. class TypefaceCache : public DeletedAtShutdown
  70897. {
  70898. public:
  70899. TypefaceCache (int numToCache = 10) throw()
  70900. : counter (1)
  70901. {
  70902. while (--numToCache >= 0)
  70903. faces.add (new CachedFace());
  70904. }
  70905. ~TypefaceCache()
  70906. {
  70907. clearSingletonInstance();
  70908. }
  70909. juce_DeclareSingleton_SingleThreaded_Minimal (TypefaceCache)
  70910. const Typeface::Ptr findTypefaceFor (const Font& font) throw()
  70911. {
  70912. const int flags = font.getStyleFlags() & (Font::bold | Font::italic);
  70913. const String faceName (font.getTypefaceName());
  70914. int i;
  70915. for (i = faces.size(); --i >= 0;)
  70916. {
  70917. CachedFace* const face = faces.getUnchecked(i);
  70918. if (face->flags == flags
  70919. && face->typefaceName == faceName)
  70920. {
  70921. face->lastUsageCount = ++counter;
  70922. return face->typeFace;
  70923. }
  70924. }
  70925. int replaceIndex = 0;
  70926. int bestLastUsageCount = std::numeric_limits<int>::max();
  70927. for (i = faces.size(); --i >= 0;)
  70928. {
  70929. const int lu = faces.getUnchecked(i)->lastUsageCount;
  70930. if (bestLastUsageCount > lu)
  70931. {
  70932. bestLastUsageCount = lu;
  70933. replaceIndex = i;
  70934. }
  70935. }
  70936. CachedFace* const face = faces.getUnchecked (replaceIndex);
  70937. face->typefaceName = faceName;
  70938. face->flags = flags;
  70939. face->lastUsageCount = ++counter;
  70940. face->typeFace = LookAndFeel::getDefaultLookAndFeel().getTypefaceForFont (font);
  70941. jassert (face->typeFace != 0); // the look and feel must return a typeface!
  70942. return face->typeFace;
  70943. }
  70944. juce_UseDebuggingNewOperator
  70945. private:
  70946. struct CachedFace
  70947. {
  70948. CachedFace() throw()
  70949. : lastUsageCount (0), flags (-1)
  70950. {
  70951. }
  70952. String typefaceName;
  70953. int lastUsageCount;
  70954. int flags;
  70955. Typeface::Ptr typeFace;
  70956. };
  70957. int counter;
  70958. OwnedArray <CachedFace> faces;
  70959. TypefaceCache (const TypefaceCache&);
  70960. TypefaceCache& operator= (const TypefaceCache&);
  70961. };
  70962. juce_ImplementSingleton_SingleThreaded (TypefaceCache)
  70963. Typeface* Font::getTypeface() const throw()
  70964. {
  70965. if (font->typeface == 0)
  70966. font->typeface = TypefaceCache::getInstance()->findTypefaceFor (*this);
  70967. return font->typeface;
  70968. }
  70969. END_JUCE_NAMESPACE
  70970. /*** End of inlined file: juce_Font.cpp ***/
  70971. /*** Start of inlined file: juce_GlyphArrangement.cpp ***/
  70972. BEGIN_JUCE_NAMESPACE
  70973. PositionedGlyph::PositionedGlyph (const float x_, const float y_, const float w_, const Font& font_,
  70974. const juce_wchar character_, const int glyph_)
  70975. : x (x_),
  70976. y (y_),
  70977. w (w_),
  70978. font (font_),
  70979. character (character_),
  70980. glyph (glyph_)
  70981. {
  70982. }
  70983. PositionedGlyph::PositionedGlyph (const PositionedGlyph& other)
  70984. : x (other.x),
  70985. y (other.y),
  70986. w (other.w),
  70987. font (other.font),
  70988. character (other.character),
  70989. glyph (other.glyph)
  70990. {
  70991. }
  70992. void PositionedGlyph::draw (const Graphics& g) const
  70993. {
  70994. if (! isWhitespace())
  70995. {
  70996. g.getInternalContext()->setFont (font);
  70997. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y));
  70998. }
  70999. }
  71000. void PositionedGlyph::draw (const Graphics& g,
  71001. const AffineTransform& transform) const
  71002. {
  71003. if (! isWhitespace())
  71004. {
  71005. g.getInternalContext()->setFont (font);
  71006. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y)
  71007. .followedBy (transform));
  71008. }
  71009. }
  71010. void PositionedGlyph::createPath (Path& path) const
  71011. {
  71012. if (! isWhitespace())
  71013. {
  71014. Typeface* const t = font.getTypeface();
  71015. if (t != 0)
  71016. {
  71017. Path p;
  71018. t->getOutlineForGlyph (glyph, p);
  71019. path.addPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight())
  71020. .translated (x, y));
  71021. }
  71022. }
  71023. }
  71024. bool PositionedGlyph::hitTest (float px, float py) const
  71025. {
  71026. if (getBounds().contains (px, py) && ! isWhitespace())
  71027. {
  71028. Typeface* const t = font.getTypeface();
  71029. if (t != 0)
  71030. {
  71031. Path p;
  71032. t->getOutlineForGlyph (glyph, p);
  71033. AffineTransform::translation (-x, -y)
  71034. .scaled (1.0f / (font.getHeight() * font.getHorizontalScale()), 1.0f / font.getHeight())
  71035. .transformPoint (px, py);
  71036. return p.contains (px, py);
  71037. }
  71038. }
  71039. return false;
  71040. }
  71041. void PositionedGlyph::moveBy (const float deltaX,
  71042. const float deltaY)
  71043. {
  71044. x += deltaX;
  71045. y += deltaY;
  71046. }
  71047. GlyphArrangement::GlyphArrangement()
  71048. {
  71049. glyphs.ensureStorageAllocated (128);
  71050. }
  71051. GlyphArrangement::GlyphArrangement (const GlyphArrangement& other)
  71052. {
  71053. addGlyphArrangement (other);
  71054. }
  71055. GlyphArrangement& GlyphArrangement::operator= (const GlyphArrangement& other)
  71056. {
  71057. if (this != &other)
  71058. {
  71059. clear();
  71060. addGlyphArrangement (other);
  71061. }
  71062. return *this;
  71063. }
  71064. GlyphArrangement::~GlyphArrangement()
  71065. {
  71066. }
  71067. void GlyphArrangement::clear()
  71068. {
  71069. glyphs.clear();
  71070. }
  71071. PositionedGlyph& GlyphArrangement::getGlyph (const int index) const
  71072. {
  71073. jassert (((unsigned int) index) < (unsigned int) glyphs.size());
  71074. return *glyphs [index];
  71075. }
  71076. void GlyphArrangement::addGlyphArrangement (const GlyphArrangement& other)
  71077. {
  71078. glyphs.ensureStorageAllocated (glyphs.size() + other.glyphs.size());
  71079. glyphs.addCopiesOf (other.glyphs);
  71080. }
  71081. void GlyphArrangement::removeRangeOfGlyphs (int startIndex, const int num)
  71082. {
  71083. glyphs.removeRange (startIndex, num < 0 ? glyphs.size() : num);
  71084. }
  71085. void GlyphArrangement::addLineOfText (const Font& font,
  71086. const String& text,
  71087. const float xOffset,
  71088. const float yOffset)
  71089. {
  71090. addCurtailedLineOfText (font, text,
  71091. xOffset, yOffset,
  71092. 1.0e10f, false);
  71093. }
  71094. void GlyphArrangement::addCurtailedLineOfText (const Font& font,
  71095. const String& text,
  71096. float xOffset,
  71097. const float yOffset,
  71098. const float maxWidthPixels,
  71099. const bool useEllipsis)
  71100. {
  71101. if (text.isNotEmpty())
  71102. {
  71103. Array <int> newGlyphs;
  71104. Array <float> xOffsets;
  71105. font.getGlyphPositions (text, newGlyphs, xOffsets);
  71106. const int textLen = newGlyphs.size();
  71107. const juce_wchar* const unicodeText = text;
  71108. for (int i = 0; i < textLen; ++i)
  71109. {
  71110. const float thisX = xOffsets.getUnchecked (i);
  71111. const float nextX = xOffsets.getUnchecked (i + 1);
  71112. if (nextX > maxWidthPixels + 1.0f)
  71113. {
  71114. // curtail the string if it's too wide..
  71115. if (useEllipsis && textLen > 3 && glyphs.size() >= 3)
  71116. insertEllipsis (font, xOffset + maxWidthPixels, 0, glyphs.size());
  71117. break;
  71118. }
  71119. else
  71120. {
  71121. glyphs.add (new PositionedGlyph (xOffset + thisX, yOffset, nextX - thisX,
  71122. font, unicodeText[i], newGlyphs.getUnchecked(i)));
  71123. }
  71124. }
  71125. }
  71126. }
  71127. int GlyphArrangement::insertEllipsis (const Font& font, const float maxXPos,
  71128. const int startIndex, int endIndex)
  71129. {
  71130. int numDeleted = 0;
  71131. if (glyphs.size() > 0)
  71132. {
  71133. Array<int> dotGlyphs;
  71134. Array<float> dotXs;
  71135. font.getGlyphPositions ("..", dotGlyphs, dotXs);
  71136. const float dx = dotXs[1];
  71137. float xOffset = 0.0f, yOffset = 0.0f;
  71138. while (endIndex > startIndex)
  71139. {
  71140. const PositionedGlyph* pg = glyphs.getUnchecked (--endIndex);
  71141. xOffset = pg->x;
  71142. yOffset = pg->y;
  71143. glyphs.remove (endIndex);
  71144. ++numDeleted;
  71145. if (xOffset + dx * 3 <= maxXPos)
  71146. break;
  71147. }
  71148. for (int i = 3; --i >= 0;)
  71149. {
  71150. glyphs.insert (endIndex++, new PositionedGlyph (xOffset, yOffset, dx,
  71151. font, '.', dotGlyphs.getFirst()));
  71152. --numDeleted;
  71153. xOffset += dx;
  71154. if (xOffset > maxXPos)
  71155. break;
  71156. }
  71157. }
  71158. return numDeleted;
  71159. }
  71160. void GlyphArrangement::addJustifiedText (const Font& font,
  71161. const String& text,
  71162. float x, float y,
  71163. const float maxLineWidth,
  71164. const Justification& horizontalLayout)
  71165. {
  71166. int lineStartIndex = glyphs.size();
  71167. addLineOfText (font, text, x, y);
  71168. const float originalY = y;
  71169. while (lineStartIndex < glyphs.size())
  71170. {
  71171. int i = lineStartIndex;
  71172. if (glyphs.getUnchecked(i)->getCharacter() != '\n'
  71173. && glyphs.getUnchecked(i)->getCharacter() != '\r')
  71174. ++i;
  71175. const float lineMaxX = glyphs.getUnchecked (lineStartIndex)->getLeft() + maxLineWidth;
  71176. int lastWordBreakIndex = -1;
  71177. while (i < glyphs.size())
  71178. {
  71179. const PositionedGlyph* pg = glyphs.getUnchecked (i);
  71180. const juce_wchar c = pg->getCharacter();
  71181. if (c == '\r' || c == '\n')
  71182. {
  71183. ++i;
  71184. if (c == '\r' && i < glyphs.size()
  71185. && glyphs.getUnchecked(i)->getCharacter() == '\n')
  71186. ++i;
  71187. break;
  71188. }
  71189. else if (pg->isWhitespace())
  71190. {
  71191. lastWordBreakIndex = i + 1;
  71192. }
  71193. else if (pg->getRight() - 0.0001f >= lineMaxX)
  71194. {
  71195. if (lastWordBreakIndex >= 0)
  71196. i = lastWordBreakIndex;
  71197. break;
  71198. }
  71199. ++i;
  71200. }
  71201. const float currentLineStartX = glyphs.getUnchecked (lineStartIndex)->getLeft();
  71202. float currentLineEndX = currentLineStartX;
  71203. for (int j = i; --j >= lineStartIndex;)
  71204. {
  71205. if (! glyphs.getUnchecked (j)->isWhitespace())
  71206. {
  71207. currentLineEndX = glyphs.getUnchecked (j)->getRight();
  71208. break;
  71209. }
  71210. }
  71211. float deltaX = 0.0f;
  71212. if (horizontalLayout.testFlags (Justification::horizontallyJustified))
  71213. spreadOutLine (lineStartIndex, i - lineStartIndex, maxLineWidth);
  71214. else if (horizontalLayout.testFlags (Justification::horizontallyCentred))
  71215. deltaX = (maxLineWidth - (currentLineEndX - currentLineStartX)) * 0.5f;
  71216. else if (horizontalLayout.testFlags (Justification::right))
  71217. deltaX = maxLineWidth - (currentLineEndX - currentLineStartX);
  71218. moveRangeOfGlyphs (lineStartIndex, i - lineStartIndex,
  71219. x + deltaX - currentLineStartX, y - originalY);
  71220. lineStartIndex = i;
  71221. y += font.getHeight();
  71222. }
  71223. }
  71224. void GlyphArrangement::addFittedText (const Font& f,
  71225. const String& text,
  71226. const float x, const float y,
  71227. const float width, const float height,
  71228. const Justification& layout,
  71229. int maximumLines,
  71230. const float minimumHorizontalScale)
  71231. {
  71232. // doesn't make much sense if this is outside a sensible range of 0.5 to 1.0
  71233. jassert (minimumHorizontalScale > 0 && minimumHorizontalScale <= 1.0f);
  71234. if (text.containsAnyOf ("\r\n"))
  71235. {
  71236. GlyphArrangement ga;
  71237. ga.addJustifiedText (f, text, x, y, width, layout);
  71238. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  71239. float dy = y - bb.getY();
  71240. if (layout.testFlags (Justification::verticallyCentred))
  71241. dy += (height - bb.getHeight()) * 0.5f;
  71242. else if (layout.testFlags (Justification::bottom))
  71243. dy += height - bb.getHeight();
  71244. ga.moveRangeOfGlyphs (0, -1, 0.0f, dy);
  71245. glyphs.ensureStorageAllocated (glyphs.size() + ga.glyphs.size());
  71246. for (int i = 0; i < ga.glyphs.size(); ++i)
  71247. glyphs.add (ga.glyphs.getUnchecked (i));
  71248. ga.glyphs.clear (false);
  71249. return;
  71250. }
  71251. int startIndex = glyphs.size();
  71252. addLineOfText (f, text.trim(), x, y);
  71253. if (glyphs.size() > startIndex)
  71254. {
  71255. float lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  71256. - glyphs.getUnchecked (startIndex)->getLeft();
  71257. if (lineWidth <= 0)
  71258. return;
  71259. if (lineWidth * minimumHorizontalScale < width)
  71260. {
  71261. if (lineWidth > width)
  71262. stretchRangeOfGlyphs (startIndex, glyphs.size() - startIndex,
  71263. width / lineWidth);
  71264. justifyGlyphs (startIndex, glyphs.size() - startIndex,
  71265. x, y, width, height, layout);
  71266. }
  71267. else if (maximumLines <= 1)
  71268. {
  71269. fitLineIntoSpace (startIndex, glyphs.size() - startIndex,
  71270. x, y, width, height, f, layout, minimumHorizontalScale);
  71271. }
  71272. else
  71273. {
  71274. Font font (f);
  71275. String txt (text.trim());
  71276. const int length = txt.length();
  71277. const int originalStartIndex = startIndex;
  71278. int numLines = 1;
  71279. if (length <= 12 && ! txt.containsAnyOf (" -\t\r\n"))
  71280. maximumLines = 1;
  71281. maximumLines = jmin (maximumLines, length);
  71282. while (numLines < maximumLines)
  71283. {
  71284. ++numLines;
  71285. const float newFontHeight = height / (float) numLines;
  71286. if (newFontHeight < font.getHeight())
  71287. {
  71288. font.setHeight (jmax (8.0f, newFontHeight));
  71289. removeRangeOfGlyphs (startIndex, -1);
  71290. addLineOfText (font, txt, x, y);
  71291. lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  71292. - glyphs.getUnchecked (startIndex)->getLeft();
  71293. }
  71294. if (numLines > lineWidth / width || newFontHeight < 8.0f)
  71295. break;
  71296. }
  71297. if (numLines < 1)
  71298. numLines = 1;
  71299. float lineY = y;
  71300. float widthPerLine = lineWidth / numLines;
  71301. int lastLineStartIndex = 0;
  71302. for (int line = 0; line < numLines; ++line)
  71303. {
  71304. int i = startIndex;
  71305. lastLineStartIndex = i;
  71306. float lineStartX = glyphs.getUnchecked (startIndex)->getLeft();
  71307. if (line == numLines - 1)
  71308. {
  71309. widthPerLine = width;
  71310. i = glyphs.size();
  71311. }
  71312. else
  71313. {
  71314. while (i < glyphs.size())
  71315. {
  71316. lineWidth = (glyphs.getUnchecked (i)->getRight() - lineStartX);
  71317. if (lineWidth > widthPerLine)
  71318. {
  71319. // got to a point where the line's too long, so skip forward to find a
  71320. // good place to break it..
  71321. const int searchStartIndex = i;
  71322. while (i < glyphs.size())
  71323. {
  71324. if ((glyphs.getUnchecked (i)->getRight() - lineStartX) * minimumHorizontalScale < width)
  71325. {
  71326. if (glyphs.getUnchecked (i)->isWhitespace()
  71327. || glyphs.getUnchecked (i)->getCharacter() == '-')
  71328. {
  71329. ++i;
  71330. break;
  71331. }
  71332. }
  71333. else
  71334. {
  71335. // can't find a suitable break, so try looking backwards..
  71336. i = searchStartIndex;
  71337. for (int back = 1; back < jmin (5, i - startIndex - 1); ++back)
  71338. {
  71339. if (glyphs.getUnchecked (i - back)->isWhitespace()
  71340. || glyphs.getUnchecked (i - back)->getCharacter() == '-')
  71341. {
  71342. i -= back - 1;
  71343. break;
  71344. }
  71345. }
  71346. break;
  71347. }
  71348. ++i;
  71349. }
  71350. break;
  71351. }
  71352. ++i;
  71353. }
  71354. int wsStart = i;
  71355. while (wsStart > 0 && glyphs.getUnchecked (wsStart - 1)->isWhitespace())
  71356. --wsStart;
  71357. int wsEnd = i;
  71358. while (wsEnd < glyphs.size() && glyphs.getUnchecked (wsEnd)->isWhitespace())
  71359. ++wsEnd;
  71360. removeRangeOfGlyphs (wsStart, wsEnd - wsStart);
  71361. i = jmax (wsStart, startIndex + 1);
  71362. }
  71363. i -= fitLineIntoSpace (startIndex, i - startIndex,
  71364. x, lineY, width, font.getHeight(), font,
  71365. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  71366. minimumHorizontalScale);
  71367. startIndex = i;
  71368. lineY += font.getHeight();
  71369. if (startIndex >= glyphs.size())
  71370. break;
  71371. }
  71372. justifyGlyphs (originalStartIndex, glyphs.size() - originalStartIndex,
  71373. x, y, width, height, layout.getFlags() & ~Justification::horizontallyJustified);
  71374. }
  71375. }
  71376. }
  71377. void GlyphArrangement::moveRangeOfGlyphs (int startIndex, int num,
  71378. const float dx, const float dy)
  71379. {
  71380. jassert (startIndex >= 0);
  71381. if (dx != 0.0f || dy != 0.0f)
  71382. {
  71383. if (num < 0 || startIndex + num > glyphs.size())
  71384. num = glyphs.size() - startIndex;
  71385. while (--num >= 0)
  71386. glyphs.getUnchecked (startIndex++)->moveBy (dx, dy);
  71387. }
  71388. }
  71389. int GlyphArrangement::fitLineIntoSpace (int start, int numGlyphs, float x, float y, float w, float h, const Font& font,
  71390. const Justification& justification, float minimumHorizontalScale)
  71391. {
  71392. int numDeleted = 0;
  71393. const float lineStartX = glyphs.getUnchecked (start)->getLeft();
  71394. float lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX;
  71395. if (lineWidth > w)
  71396. {
  71397. if (minimumHorizontalScale < 1.0f)
  71398. {
  71399. stretchRangeOfGlyphs (start, numGlyphs, jmax (minimumHorizontalScale, w / lineWidth));
  71400. lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX - 0.5f;
  71401. }
  71402. if (lineWidth > w)
  71403. {
  71404. numDeleted = insertEllipsis (font, lineStartX + w, start, start + numGlyphs);
  71405. numGlyphs -= numDeleted;
  71406. }
  71407. }
  71408. justifyGlyphs (start, numGlyphs, x, y, w, h, justification);
  71409. return numDeleted;
  71410. }
  71411. void GlyphArrangement::stretchRangeOfGlyphs (int startIndex, int num,
  71412. const float horizontalScaleFactor)
  71413. {
  71414. jassert (startIndex >= 0);
  71415. if (num < 0 || startIndex + num > glyphs.size())
  71416. num = glyphs.size() - startIndex;
  71417. if (num > 0)
  71418. {
  71419. const float xAnchor = glyphs.getUnchecked (startIndex)->getLeft();
  71420. while (--num >= 0)
  71421. {
  71422. PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  71423. pg->x = xAnchor + (pg->x - xAnchor) * horizontalScaleFactor;
  71424. pg->font.setHorizontalScale (pg->font.getHorizontalScale() * horizontalScaleFactor);
  71425. pg->w *= horizontalScaleFactor;
  71426. }
  71427. }
  71428. }
  71429. const Rectangle<float> GlyphArrangement::getBoundingBox (int startIndex, int num, const bool includeWhitespace) const
  71430. {
  71431. jassert (startIndex >= 0);
  71432. if (num < 0 || startIndex + num > glyphs.size())
  71433. num = glyphs.size() - startIndex;
  71434. Rectangle<float> result;
  71435. while (--num >= 0)
  71436. {
  71437. const PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  71438. if (includeWhitespace || ! pg->isWhitespace())
  71439. result = result.getUnion (pg->getBounds());
  71440. }
  71441. return result;
  71442. }
  71443. void GlyphArrangement::justifyGlyphs (const int startIndex, const int num,
  71444. const float x, const float y, const float width, const float height,
  71445. const Justification& justification)
  71446. {
  71447. jassert (num >= 0 && startIndex >= 0);
  71448. if (glyphs.size() > 0 && num > 0)
  71449. {
  71450. const Rectangle<float> bb (getBoundingBox (startIndex, num, ! justification.testFlags (Justification::horizontallyJustified
  71451. | Justification::horizontallyCentred)));
  71452. float deltaX = 0.0f;
  71453. if (justification.testFlags (Justification::horizontallyJustified))
  71454. deltaX = x - bb.getX();
  71455. else if (justification.testFlags (Justification::horizontallyCentred))
  71456. deltaX = x + (width - bb.getWidth()) * 0.5f - bb.getX();
  71457. else if (justification.testFlags (Justification::right))
  71458. deltaX = (x + width) - bb.getRight();
  71459. else
  71460. deltaX = x - bb.getX();
  71461. float deltaY = 0.0f;
  71462. if (justification.testFlags (Justification::top))
  71463. deltaY = y - bb.getY();
  71464. else if (justification.testFlags (Justification::bottom))
  71465. deltaY = (y + height) - bb.getBottom();
  71466. else
  71467. deltaY = y + (height - bb.getHeight()) * 0.5f - bb.getY();
  71468. moveRangeOfGlyphs (startIndex, num, deltaX, deltaY);
  71469. if (justification.testFlags (Justification::horizontallyJustified))
  71470. {
  71471. int lineStart = 0;
  71472. float baseY = glyphs.getUnchecked (startIndex)->getBaselineY();
  71473. int i;
  71474. for (i = 0; i < num; ++i)
  71475. {
  71476. const float glyphY = glyphs.getUnchecked (startIndex + i)->getBaselineY();
  71477. if (glyphY != baseY)
  71478. {
  71479. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  71480. lineStart = i;
  71481. baseY = glyphY;
  71482. }
  71483. }
  71484. if (i > lineStart)
  71485. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  71486. }
  71487. }
  71488. }
  71489. void GlyphArrangement::spreadOutLine (const int start, const int num, const float targetWidth)
  71490. {
  71491. if (start + num < glyphs.size()
  71492. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\r'
  71493. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\n')
  71494. {
  71495. int numSpaces = 0;
  71496. int spacesAtEnd = 0;
  71497. for (int i = 0; i < num; ++i)
  71498. {
  71499. if (glyphs.getUnchecked (start + i)->isWhitespace())
  71500. {
  71501. ++spacesAtEnd;
  71502. ++numSpaces;
  71503. }
  71504. else
  71505. {
  71506. spacesAtEnd = 0;
  71507. }
  71508. }
  71509. numSpaces -= spacesAtEnd;
  71510. if (numSpaces > 0)
  71511. {
  71512. const float startX = glyphs.getUnchecked (start)->getLeft();
  71513. const float endX = glyphs.getUnchecked (start + num - 1 - spacesAtEnd)->getRight();
  71514. const float extraPaddingBetweenWords
  71515. = (targetWidth - (endX - startX)) / (float) numSpaces;
  71516. float deltaX = 0.0f;
  71517. for (int i = 0; i < num; ++i)
  71518. {
  71519. glyphs.getUnchecked (start + i)->moveBy (deltaX, 0.0f);
  71520. if (glyphs.getUnchecked (start + i)->isWhitespace())
  71521. deltaX += extraPaddingBetweenWords;
  71522. }
  71523. }
  71524. }
  71525. }
  71526. void GlyphArrangement::draw (const Graphics& g) const
  71527. {
  71528. for (int i = 0; i < glyphs.size(); ++i)
  71529. {
  71530. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  71531. if (pg->font.isUnderlined())
  71532. {
  71533. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  71534. float nextX = pg->x + pg->w;
  71535. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  71536. nextX = glyphs.getUnchecked (i + 1)->x;
  71537. g.fillRect (pg->x, pg->y + lineThickness * 2.0f,
  71538. nextX - pg->x, lineThickness);
  71539. }
  71540. pg->draw (g);
  71541. }
  71542. }
  71543. void GlyphArrangement::draw (const Graphics& g, const AffineTransform& transform) const
  71544. {
  71545. for (int i = 0; i < glyphs.size(); ++i)
  71546. {
  71547. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  71548. if (pg->font.isUnderlined())
  71549. {
  71550. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  71551. float nextX = pg->x + pg->w;
  71552. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  71553. nextX = glyphs.getUnchecked (i + 1)->x;
  71554. Path p;
  71555. p.addLineSegment (Line<float> (pg->x, pg->y + lineThickness * 2.0f,
  71556. nextX, pg->y + lineThickness * 2.0f),
  71557. lineThickness);
  71558. g.fillPath (p, transform);
  71559. }
  71560. pg->draw (g, transform);
  71561. }
  71562. }
  71563. void GlyphArrangement::createPath (Path& path) const
  71564. {
  71565. for (int i = 0; i < glyphs.size(); ++i)
  71566. glyphs.getUnchecked (i)->createPath (path);
  71567. }
  71568. int GlyphArrangement::findGlyphIndexAt (float x, float y) const
  71569. {
  71570. for (int i = 0; i < glyphs.size(); ++i)
  71571. if (glyphs.getUnchecked (i)->hitTest (x, y))
  71572. return i;
  71573. return -1;
  71574. }
  71575. END_JUCE_NAMESPACE
  71576. /*** End of inlined file: juce_GlyphArrangement.cpp ***/
  71577. /*** Start of inlined file: juce_TextLayout.cpp ***/
  71578. BEGIN_JUCE_NAMESPACE
  71579. class TextLayout::Token
  71580. {
  71581. public:
  71582. String text;
  71583. Font font;
  71584. int x, y, w, h;
  71585. int line, lineHeight;
  71586. bool isWhitespace, isNewLine;
  71587. Token (const String& t,
  71588. const Font& f,
  71589. const bool isWhitespace_)
  71590. : text (t),
  71591. font (f),
  71592. x(0),
  71593. y(0),
  71594. isWhitespace (isWhitespace_)
  71595. {
  71596. w = font.getStringWidth (t);
  71597. h = roundToInt (f.getHeight());
  71598. isNewLine = t.containsChar ('\n') || t.containsChar ('\r');
  71599. }
  71600. Token (const Token& other)
  71601. : text (other.text),
  71602. font (other.font),
  71603. x (other.x),
  71604. y (other.y),
  71605. w (other.w),
  71606. h (other.h),
  71607. line (other.line),
  71608. lineHeight (other.lineHeight),
  71609. isWhitespace (other.isWhitespace),
  71610. isNewLine (other.isNewLine)
  71611. {
  71612. }
  71613. ~Token()
  71614. {
  71615. }
  71616. void draw (Graphics& g,
  71617. const int xOffset,
  71618. const int yOffset)
  71619. {
  71620. if (! isWhitespace)
  71621. {
  71622. g.setFont (font);
  71623. g.drawSingleLineText (text.trimEnd(),
  71624. xOffset + x,
  71625. yOffset + y + (lineHeight - h)
  71626. + roundToInt (font.getAscent()));
  71627. }
  71628. }
  71629. juce_UseDebuggingNewOperator
  71630. };
  71631. TextLayout::TextLayout()
  71632. : totalLines (0)
  71633. {
  71634. tokens.ensureStorageAllocated (64);
  71635. }
  71636. TextLayout::TextLayout (const String& text, const Font& font)
  71637. : totalLines (0)
  71638. {
  71639. tokens.ensureStorageAllocated (64);
  71640. appendText (text, font);
  71641. }
  71642. TextLayout::TextLayout (const TextLayout& other)
  71643. : totalLines (0)
  71644. {
  71645. *this = other;
  71646. }
  71647. TextLayout& TextLayout::operator= (const TextLayout& other)
  71648. {
  71649. if (this != &other)
  71650. {
  71651. clear();
  71652. totalLines = other.totalLines;
  71653. tokens.addCopiesOf (other.tokens);
  71654. }
  71655. return *this;
  71656. }
  71657. TextLayout::~TextLayout()
  71658. {
  71659. clear();
  71660. }
  71661. void TextLayout::clear()
  71662. {
  71663. tokens.clear();
  71664. totalLines = 0;
  71665. }
  71666. void TextLayout::appendText (const String& text, const Font& font)
  71667. {
  71668. const juce_wchar* t = text;
  71669. String currentString;
  71670. int lastCharType = 0;
  71671. for (;;)
  71672. {
  71673. const juce_wchar c = *t++;
  71674. if (c == 0)
  71675. break;
  71676. int charType;
  71677. if (c == '\r' || c == '\n')
  71678. {
  71679. charType = 0;
  71680. }
  71681. else if (CharacterFunctions::isWhitespace (c))
  71682. {
  71683. charType = 2;
  71684. }
  71685. else
  71686. {
  71687. charType = 1;
  71688. }
  71689. if (charType == 0 || charType != lastCharType)
  71690. {
  71691. if (currentString.isNotEmpty())
  71692. {
  71693. tokens.add (new Token (currentString, font,
  71694. lastCharType == 2 || lastCharType == 0));
  71695. }
  71696. currentString = String::charToString (c);
  71697. if (c == '\r' && *t == '\n')
  71698. currentString += *t++;
  71699. }
  71700. else
  71701. {
  71702. currentString += c;
  71703. }
  71704. lastCharType = charType;
  71705. }
  71706. if (currentString.isNotEmpty())
  71707. tokens.add (new Token (currentString, font, lastCharType == 2));
  71708. }
  71709. void TextLayout::setText (const String& text, const Font& font)
  71710. {
  71711. clear();
  71712. appendText (text, font);
  71713. }
  71714. void TextLayout::layout (int maxWidth,
  71715. const Justification& justification,
  71716. const bool attemptToBalanceLineLengths)
  71717. {
  71718. if (attemptToBalanceLineLengths)
  71719. {
  71720. const int originalW = maxWidth;
  71721. int bestWidth = maxWidth;
  71722. float bestLineProportion = 0.0f;
  71723. while (maxWidth > originalW / 2)
  71724. {
  71725. layout (maxWidth, justification, false);
  71726. if (getNumLines() <= 1)
  71727. return;
  71728. const int lastLineW = getLineWidth (getNumLines() - 1);
  71729. const int lastButOneLineW = getLineWidth (getNumLines() - 2);
  71730. const float prop = lastLineW / (float) lastButOneLineW;
  71731. if (prop > 0.9f)
  71732. return;
  71733. if (prop > bestLineProportion)
  71734. {
  71735. bestLineProportion = prop;
  71736. bestWidth = maxWidth;
  71737. }
  71738. maxWidth -= 10;
  71739. }
  71740. layout (bestWidth, justification, false);
  71741. }
  71742. else
  71743. {
  71744. int x = 0;
  71745. int y = 0;
  71746. int h = 0;
  71747. totalLines = 0;
  71748. int i;
  71749. for (i = 0; i < tokens.size(); ++i)
  71750. {
  71751. Token* const t = tokens.getUnchecked(i);
  71752. t->x = x;
  71753. t->y = y;
  71754. t->line = totalLines;
  71755. x += t->w;
  71756. h = jmax (h, t->h);
  71757. const Token* nextTok = tokens [i + 1];
  71758. if (nextTok == 0)
  71759. break;
  71760. if (t->isNewLine || ((! nextTok->isWhitespace) && x + nextTok->w > maxWidth))
  71761. {
  71762. // finished a line, so go back and update the heights of the things on it
  71763. for (int j = i; j >= 0; --j)
  71764. {
  71765. Token* const tok = tokens.getUnchecked(j);
  71766. if (tok->line == totalLines)
  71767. tok->lineHeight = h;
  71768. else
  71769. break;
  71770. }
  71771. x = 0;
  71772. y += h;
  71773. h = 0;
  71774. ++totalLines;
  71775. }
  71776. }
  71777. // finished a line, so go back and update the heights of the things on it
  71778. for (int j = jmin (i, tokens.size() - 1); j >= 0; --j)
  71779. {
  71780. Token* const t = tokens.getUnchecked(j);
  71781. if (t->line == totalLines)
  71782. t->lineHeight = h;
  71783. else
  71784. break;
  71785. }
  71786. ++totalLines;
  71787. if (! justification.testFlags (Justification::left))
  71788. {
  71789. int totalW = getWidth();
  71790. for (i = totalLines; --i >= 0;)
  71791. {
  71792. const int lineW = getLineWidth (i);
  71793. int dx = 0;
  71794. if (justification.testFlags (Justification::horizontallyCentred))
  71795. dx = (totalW - lineW) / 2;
  71796. else if (justification.testFlags (Justification::right))
  71797. dx = totalW - lineW;
  71798. for (int j = tokens.size(); --j >= 0;)
  71799. {
  71800. Token* const t = tokens.getUnchecked(j);
  71801. if (t->line == i)
  71802. t->x += dx;
  71803. }
  71804. }
  71805. }
  71806. }
  71807. }
  71808. int TextLayout::getLineWidth (const int lineNumber) const
  71809. {
  71810. int maxW = 0;
  71811. for (int i = tokens.size(); --i >= 0;)
  71812. {
  71813. const Token* const t = tokens.getUnchecked(i);
  71814. if (t->line == lineNumber && ! t->isWhitespace)
  71815. maxW = jmax (maxW, t->x + t->w);
  71816. }
  71817. return maxW;
  71818. }
  71819. int TextLayout::getWidth() const
  71820. {
  71821. int maxW = 0;
  71822. for (int i = tokens.size(); --i >= 0;)
  71823. {
  71824. const Token* const t = tokens.getUnchecked(i);
  71825. if (! t->isWhitespace)
  71826. maxW = jmax (maxW, t->x + t->w);
  71827. }
  71828. return maxW;
  71829. }
  71830. int TextLayout::getHeight() const
  71831. {
  71832. int maxH = 0;
  71833. for (int i = tokens.size(); --i >= 0;)
  71834. {
  71835. const Token* const t = tokens.getUnchecked(i);
  71836. if (! t->isWhitespace)
  71837. maxH = jmax (maxH, t->y + t->h);
  71838. }
  71839. return maxH;
  71840. }
  71841. void TextLayout::draw (Graphics& g,
  71842. const int xOffset,
  71843. const int yOffset) const
  71844. {
  71845. for (int i = tokens.size(); --i >= 0;)
  71846. tokens.getUnchecked(i)->draw (g, xOffset, yOffset);
  71847. }
  71848. void TextLayout::drawWithin (Graphics& g,
  71849. int x, int y, int w, int h,
  71850. const Justification& justification) const
  71851. {
  71852. justification.applyToRectangle (x, y, getWidth(), getHeight(),
  71853. x, y, w, h);
  71854. draw (g, x, y);
  71855. }
  71856. END_JUCE_NAMESPACE
  71857. /*** End of inlined file: juce_TextLayout.cpp ***/
  71858. /*** Start of inlined file: juce_Typeface.cpp ***/
  71859. BEGIN_JUCE_NAMESPACE
  71860. Typeface::Typeface (const String& name_) throw()
  71861. : name (name_)
  71862. {
  71863. }
  71864. Typeface::~Typeface()
  71865. {
  71866. }
  71867. class CustomTypeface::GlyphInfo
  71868. {
  71869. public:
  71870. GlyphInfo (const juce_wchar character_, const Path& path_, const float width_) throw()
  71871. : character (character_), path (path_), width (width_)
  71872. {
  71873. }
  71874. ~GlyphInfo() throw()
  71875. {
  71876. }
  71877. struct KerningPair
  71878. {
  71879. juce_wchar character2;
  71880. float kerningAmount;
  71881. };
  71882. void addKerningPair (const juce_wchar subsequentCharacter,
  71883. const float extraKerningAmount) throw()
  71884. {
  71885. KerningPair kp;
  71886. kp.character2 = subsequentCharacter;
  71887. kp.kerningAmount = extraKerningAmount;
  71888. kerningPairs.add (kp);
  71889. }
  71890. float getHorizontalSpacing (const juce_wchar subsequentCharacter) const throw()
  71891. {
  71892. if (subsequentCharacter != 0)
  71893. {
  71894. for (int i = kerningPairs.size(); --i >= 0;)
  71895. if (kerningPairs.getReference(i).character2 == subsequentCharacter)
  71896. return width + kerningPairs.getReference(i).kerningAmount;
  71897. }
  71898. return width;
  71899. }
  71900. const juce_wchar character;
  71901. const Path path;
  71902. float width;
  71903. Array <KerningPair> kerningPairs;
  71904. juce_UseDebuggingNewOperator
  71905. private:
  71906. GlyphInfo (const GlyphInfo&);
  71907. GlyphInfo& operator= (const GlyphInfo&);
  71908. };
  71909. CustomTypeface::CustomTypeface()
  71910. : Typeface (String::empty)
  71911. {
  71912. clear();
  71913. }
  71914. CustomTypeface::CustomTypeface (InputStream& serialisedTypefaceStream)
  71915. : Typeface (String::empty)
  71916. {
  71917. clear();
  71918. GZIPDecompressorInputStream gzin (&serialisedTypefaceStream, false);
  71919. BufferedInputStream in (&gzin, 32768, false);
  71920. name = in.readString();
  71921. isBold = in.readBool();
  71922. isItalic = in.readBool();
  71923. ascent = in.readFloat();
  71924. defaultCharacter = (juce_wchar) in.readShort();
  71925. int i, numChars = in.readInt();
  71926. for (i = 0; i < numChars; ++i)
  71927. {
  71928. const juce_wchar c = (juce_wchar) in.readShort();
  71929. const float width = in.readFloat();
  71930. Path p;
  71931. p.loadPathFromStream (in);
  71932. addGlyph (c, p, width);
  71933. }
  71934. const int numKerningPairs = in.readInt();
  71935. for (i = 0; i < numKerningPairs; ++i)
  71936. {
  71937. const juce_wchar char1 = (juce_wchar) in.readShort();
  71938. const juce_wchar char2 = (juce_wchar) in.readShort();
  71939. addKerningPair (char1, char2, in.readFloat());
  71940. }
  71941. }
  71942. CustomTypeface::~CustomTypeface()
  71943. {
  71944. }
  71945. void CustomTypeface::clear()
  71946. {
  71947. defaultCharacter = 0;
  71948. ascent = 1.0f;
  71949. isBold = isItalic = false;
  71950. zeromem (lookupTable, sizeof (lookupTable));
  71951. glyphs.clear();
  71952. }
  71953. void CustomTypeface::setCharacteristics (const String& name_, const float ascent_, const bool isBold_,
  71954. const bool isItalic_, const juce_wchar defaultCharacter_) throw()
  71955. {
  71956. name = name_;
  71957. defaultCharacter = defaultCharacter_;
  71958. ascent = ascent_;
  71959. isBold = isBold_;
  71960. isItalic = isItalic_;
  71961. }
  71962. void CustomTypeface::addGlyph (const juce_wchar character, const Path& path, const float width) throw()
  71963. {
  71964. // Check that you're not trying to add the same character twice..
  71965. jassert (findGlyph (character, false) == 0);
  71966. if (((unsigned int) character) < (unsigned int) numElementsInArray (lookupTable))
  71967. lookupTable [character] = (short) glyphs.size();
  71968. glyphs.add (new GlyphInfo (character, path, width));
  71969. }
  71970. void CustomTypeface::addKerningPair (const juce_wchar char1, const juce_wchar char2, const float extraAmount) throw()
  71971. {
  71972. if (extraAmount != 0)
  71973. {
  71974. GlyphInfo* const g = findGlyph (char1, true);
  71975. jassert (g != 0); // can only add kerning pairs for characters that exist!
  71976. if (g != 0)
  71977. g->addKerningPair (char2, extraAmount);
  71978. }
  71979. }
  71980. CustomTypeface::GlyphInfo* CustomTypeface::findGlyph (const juce_wchar character, const bool loadIfNeeded) throw()
  71981. {
  71982. if (((unsigned int) character) < (unsigned int) numElementsInArray (lookupTable) && lookupTable [character] > 0)
  71983. return glyphs [(int) lookupTable [(int) character]];
  71984. for (int i = 0; i < glyphs.size(); ++i)
  71985. {
  71986. GlyphInfo* const g = glyphs.getUnchecked(i);
  71987. if (g->character == character)
  71988. return g;
  71989. }
  71990. if (loadIfNeeded && loadGlyphIfPossible (character))
  71991. return findGlyph (character, false);
  71992. return 0;
  71993. }
  71994. CustomTypeface::GlyphInfo* CustomTypeface::findGlyphSubstituting (const juce_wchar character) throw()
  71995. {
  71996. GlyphInfo* glyph = findGlyph (character, true);
  71997. if (glyph == 0)
  71998. {
  71999. if (CharacterFunctions::isWhitespace (character) && character != L' ')
  72000. glyph = findGlyph (L' ', true);
  72001. if (glyph == 0)
  72002. {
  72003. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  72004. Typeface* const fallbackTypeface = fallbackFont.getTypeface();
  72005. if (fallbackTypeface != 0 && fallbackTypeface != this)
  72006. {
  72007. //xxx
  72008. }
  72009. if (glyph == 0)
  72010. glyph = findGlyph (defaultCharacter, true);
  72011. }
  72012. }
  72013. return glyph;
  72014. }
  72015. bool CustomTypeface::loadGlyphIfPossible (const juce_wchar /*characterNeeded*/)
  72016. {
  72017. return false;
  72018. }
  72019. void CustomTypeface::addGlyphsFromOtherTypeface (Typeface& typefaceToCopy, juce_wchar characterStartIndex, int numCharacters) throw()
  72020. {
  72021. setCharacteristics (name, typefaceToCopy.getAscent(), isBold, isItalic, defaultCharacter);
  72022. for (int i = 0; i < numCharacters; ++i)
  72023. {
  72024. const juce_wchar c = (juce_wchar) (characterStartIndex + i);
  72025. Array <int> glyphIndexes;
  72026. Array <float> offsets;
  72027. typefaceToCopy.getGlyphPositions (String::charToString (c), glyphIndexes, offsets);
  72028. const int glyphIndex = glyphIndexes.getFirst();
  72029. if (glyphIndex >= 0 && glyphIndexes.size() > 0)
  72030. {
  72031. const float glyphWidth = offsets[1];
  72032. Path p;
  72033. typefaceToCopy.getOutlineForGlyph (glyphIndex, p);
  72034. addGlyph (c, p, glyphWidth);
  72035. for (int j = glyphs.size() - 1; --j >= 0;)
  72036. {
  72037. const juce_wchar char2 = glyphs.getUnchecked (j)->character;
  72038. glyphIndexes.clearQuick();
  72039. offsets.clearQuick();
  72040. typefaceToCopy.getGlyphPositions (String::charToString (c) + String::charToString (char2), glyphIndexes, offsets);
  72041. if (offsets.size() > 1)
  72042. addKerningPair (c, char2, offsets[1] - glyphWidth);
  72043. }
  72044. }
  72045. }
  72046. }
  72047. bool CustomTypeface::writeToStream (OutputStream& outputStream)
  72048. {
  72049. GZIPCompressorOutputStream out (&outputStream);
  72050. out.writeString (name);
  72051. out.writeBool (isBold);
  72052. out.writeBool (isItalic);
  72053. out.writeFloat (ascent);
  72054. out.writeShort ((short) (unsigned short) defaultCharacter);
  72055. out.writeInt (glyphs.size());
  72056. int i, numKerningPairs = 0;
  72057. for (i = 0; i < glyphs.size(); ++i)
  72058. {
  72059. const GlyphInfo* const g = glyphs.getUnchecked (i);
  72060. out.writeShort ((short) (unsigned short) g->character);
  72061. out.writeFloat (g->width);
  72062. g->path.writePathToStream (out);
  72063. numKerningPairs += g->kerningPairs.size();
  72064. }
  72065. out.writeInt (numKerningPairs);
  72066. for (i = 0; i < glyphs.size(); ++i)
  72067. {
  72068. const GlyphInfo* const g = glyphs.getUnchecked (i);
  72069. for (int j = 0; j < g->kerningPairs.size(); ++j)
  72070. {
  72071. const GlyphInfo::KerningPair& p = g->kerningPairs.getReference (j);
  72072. out.writeShort ((short) (unsigned short) g->character);
  72073. out.writeShort ((short) (unsigned short) p.character2);
  72074. out.writeFloat (p.kerningAmount);
  72075. }
  72076. }
  72077. return true;
  72078. }
  72079. float CustomTypeface::getAscent() const
  72080. {
  72081. return ascent;
  72082. }
  72083. float CustomTypeface::getDescent() const
  72084. {
  72085. return 1.0f - ascent;
  72086. }
  72087. float CustomTypeface::getStringWidth (const String& text)
  72088. {
  72089. float x = 0;
  72090. const juce_wchar* t = text;
  72091. while (*t != 0)
  72092. {
  72093. const GlyphInfo* const glyph = findGlyphSubstituting (*t++);
  72094. if (glyph != 0)
  72095. x += glyph->getHorizontalSpacing (*t);
  72096. }
  72097. return x;
  72098. }
  72099. void CustomTypeface::getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array<float>& xOffsets)
  72100. {
  72101. xOffsets.add (0);
  72102. float x = 0;
  72103. const juce_wchar* t = text;
  72104. while (*t != 0)
  72105. {
  72106. const juce_wchar c = *t++;
  72107. const GlyphInfo* const glyph = findGlyphSubstituting (c);
  72108. if (glyph != 0)
  72109. {
  72110. x += glyph->getHorizontalSpacing (*t);
  72111. resultGlyphs.add ((int) glyph->character);
  72112. xOffsets.add (x);
  72113. }
  72114. }
  72115. }
  72116. bool CustomTypeface::getOutlineForGlyph (int glyphNumber, Path& path)
  72117. {
  72118. const GlyphInfo* const glyph = findGlyphSubstituting ((juce_wchar) glyphNumber);
  72119. if (glyph != 0)
  72120. {
  72121. path = glyph->path;
  72122. return true;
  72123. }
  72124. return false;
  72125. }
  72126. END_JUCE_NAMESPACE
  72127. /*** End of inlined file: juce_Typeface.cpp ***/
  72128. /*** Start of inlined file: juce_AffineTransform.cpp ***/
  72129. BEGIN_JUCE_NAMESPACE
  72130. AffineTransform::AffineTransform() throw()
  72131. : mat00 (1.0f),
  72132. mat01 (0),
  72133. mat02 (0),
  72134. mat10 (0),
  72135. mat11 (1.0f),
  72136. mat12 (0)
  72137. {
  72138. }
  72139. AffineTransform::AffineTransform (const AffineTransform& other) throw()
  72140. : mat00 (other.mat00),
  72141. mat01 (other.mat01),
  72142. mat02 (other.mat02),
  72143. mat10 (other.mat10),
  72144. mat11 (other.mat11),
  72145. mat12 (other.mat12)
  72146. {
  72147. }
  72148. AffineTransform::AffineTransform (const float mat00_,
  72149. const float mat01_,
  72150. const float mat02_,
  72151. const float mat10_,
  72152. const float mat11_,
  72153. const float mat12_) throw()
  72154. : mat00 (mat00_),
  72155. mat01 (mat01_),
  72156. mat02 (mat02_),
  72157. mat10 (mat10_),
  72158. mat11 (mat11_),
  72159. mat12 (mat12_)
  72160. {
  72161. }
  72162. AffineTransform& AffineTransform::operator= (const AffineTransform& other) throw()
  72163. {
  72164. mat00 = other.mat00;
  72165. mat01 = other.mat01;
  72166. mat02 = other.mat02;
  72167. mat10 = other.mat10;
  72168. mat11 = other.mat11;
  72169. mat12 = other.mat12;
  72170. return *this;
  72171. }
  72172. bool AffineTransform::operator== (const AffineTransform& other) const throw()
  72173. {
  72174. return mat00 == other.mat00
  72175. && mat01 == other.mat01
  72176. && mat02 == other.mat02
  72177. && mat10 == other.mat10
  72178. && mat11 == other.mat11
  72179. && mat12 == other.mat12;
  72180. }
  72181. bool AffineTransform::operator!= (const AffineTransform& other) const throw()
  72182. {
  72183. return ! operator== (other);
  72184. }
  72185. bool AffineTransform::isIdentity() const throw()
  72186. {
  72187. return (mat01 == 0)
  72188. && (mat02 == 0)
  72189. && (mat10 == 0)
  72190. && (mat12 == 0)
  72191. && (mat00 == 1.0f)
  72192. && (mat11 == 1.0f);
  72193. }
  72194. const AffineTransform AffineTransform::identity;
  72195. const AffineTransform AffineTransform::followedBy (const AffineTransform& other) const throw()
  72196. {
  72197. return AffineTransform (other.mat00 * mat00 + other.mat01 * mat10,
  72198. other.mat00 * mat01 + other.mat01 * mat11,
  72199. other.mat00 * mat02 + other.mat01 * mat12 + other.mat02,
  72200. other.mat10 * mat00 + other.mat11 * mat10,
  72201. other.mat10 * mat01 + other.mat11 * mat11,
  72202. other.mat10 * mat02 + other.mat11 * mat12 + other.mat12);
  72203. }
  72204. const AffineTransform AffineTransform::followedBy (const float omat00,
  72205. const float omat01,
  72206. const float omat02,
  72207. const float omat10,
  72208. const float omat11,
  72209. const float omat12) const throw()
  72210. {
  72211. return AffineTransform (omat00 * mat00 + omat01 * mat10,
  72212. omat00 * mat01 + omat01 * mat11,
  72213. omat00 * mat02 + omat01 * mat12 + omat02,
  72214. omat10 * mat00 + omat11 * mat10,
  72215. omat10 * mat01 + omat11 * mat11,
  72216. omat10 * mat02 + omat11 * mat12 + omat12);
  72217. }
  72218. const AffineTransform AffineTransform::translated (const float dx,
  72219. const float dy) const throw()
  72220. {
  72221. return AffineTransform (mat00, mat01, mat02 + dx,
  72222. mat10, mat11, mat12 + dy);
  72223. }
  72224. const AffineTransform AffineTransform::translation (const float dx,
  72225. const float dy) throw()
  72226. {
  72227. return AffineTransform (1.0f, 0, dx,
  72228. 0, 1.0f, dy);
  72229. }
  72230. const AffineTransform AffineTransform::rotated (const float rad) const throw()
  72231. {
  72232. const float cosRad = std::cos (rad);
  72233. const float sinRad = std::sin (rad);
  72234. return followedBy (cosRad, -sinRad, 0,
  72235. sinRad, cosRad, 0);
  72236. }
  72237. const AffineTransform AffineTransform::rotation (const float rad) throw()
  72238. {
  72239. const float cosRad = std::cos (rad);
  72240. const float sinRad = std::sin (rad);
  72241. return AffineTransform (cosRad, -sinRad, 0,
  72242. sinRad, cosRad, 0);
  72243. }
  72244. const AffineTransform AffineTransform::rotated (const float angle,
  72245. const float pivotX,
  72246. const float pivotY) const throw()
  72247. {
  72248. return translated (-pivotX, -pivotY)
  72249. .rotated (angle)
  72250. .translated (pivotX, pivotY);
  72251. }
  72252. const AffineTransform AffineTransform::rotation (const float angle,
  72253. const float pivotX,
  72254. const float pivotY) throw()
  72255. {
  72256. return translation (-pivotX, -pivotY)
  72257. .rotated (angle)
  72258. .translated (pivotX, pivotY);
  72259. }
  72260. const AffineTransform AffineTransform::scaled (const float factorX,
  72261. const float factorY) const throw()
  72262. {
  72263. return AffineTransform (factorX * mat00, factorX * mat01, factorX * mat02,
  72264. factorY * mat10, factorY * mat11, factorY * mat12);
  72265. }
  72266. const AffineTransform AffineTransform::scale (const float factorX,
  72267. const float factorY) throw()
  72268. {
  72269. return AffineTransform (factorX, 0, 0,
  72270. 0, factorY, 0);
  72271. }
  72272. const AffineTransform AffineTransform::sheared (const float shearX,
  72273. const float shearY) const throw()
  72274. {
  72275. return followedBy (1.0f, shearX, 0,
  72276. shearY, 1.0f, 0);
  72277. }
  72278. const AffineTransform AffineTransform::inverted() const throw()
  72279. {
  72280. double determinant = (mat00 * mat11 - mat10 * mat01);
  72281. if (determinant != 0.0)
  72282. {
  72283. determinant = 1.0 / determinant;
  72284. const float dst00 = (float) (mat11 * determinant);
  72285. const float dst10 = (float) (-mat10 * determinant);
  72286. const float dst01 = (float) (-mat01 * determinant);
  72287. const float dst11 = (float) (mat00 * determinant);
  72288. return AffineTransform (dst00, dst01, -mat02 * dst00 - mat12 * dst01,
  72289. dst10, dst11, -mat02 * dst10 - mat12 * dst11);
  72290. }
  72291. else
  72292. {
  72293. // singularity..
  72294. return *this;
  72295. }
  72296. }
  72297. bool AffineTransform::isSingularity() const throw()
  72298. {
  72299. return (mat00 * mat11 - mat10 * mat01) == 0.0;
  72300. }
  72301. const AffineTransform AffineTransform::fromTargetPoints (const float x00, const float y00,
  72302. const float x10, const float y10,
  72303. const float x01, const float y01) throw()
  72304. {
  72305. return AffineTransform (x10 - x00, x01 - x00, x00,
  72306. y10 - y00, y01 - y00, y00);
  72307. }
  72308. const AffineTransform AffineTransform::fromTargetPoints (const float sx1, const float sy1, const float tx1, const float ty1,
  72309. const float sx2, const float sy2, const float tx2, const float ty2,
  72310. const float sx3, const float sy3, const float tx3, const float ty3) throw()
  72311. {
  72312. return fromTargetPoints (sx1, sy1, sx2, sy2, sx3, sy3)
  72313. .inverted()
  72314. .followedBy (fromTargetPoints (tx1, ty1, tx2, ty2, tx3, ty3));
  72315. }
  72316. bool AffineTransform::isOnlyTranslation() const throw()
  72317. {
  72318. return (mat01 == 0)
  72319. && (mat10 == 0)
  72320. && (mat00 == 1.0f)
  72321. && (mat11 == 1.0f);
  72322. }
  72323. END_JUCE_NAMESPACE
  72324. /*** End of inlined file: juce_AffineTransform.cpp ***/
  72325. /*** Start of inlined file: juce_BorderSize.cpp ***/
  72326. BEGIN_JUCE_NAMESPACE
  72327. BorderSize::BorderSize() throw()
  72328. : top (0),
  72329. left (0),
  72330. bottom (0),
  72331. right (0)
  72332. {
  72333. }
  72334. BorderSize::BorderSize (const BorderSize& other) throw()
  72335. : top (other.top),
  72336. left (other.left),
  72337. bottom (other.bottom),
  72338. right (other.right)
  72339. {
  72340. }
  72341. BorderSize::BorderSize (const int topGap,
  72342. const int leftGap,
  72343. const int bottomGap,
  72344. const int rightGap) throw()
  72345. : top (topGap),
  72346. left (leftGap),
  72347. bottom (bottomGap),
  72348. right (rightGap)
  72349. {
  72350. }
  72351. BorderSize::BorderSize (const int allGaps) throw()
  72352. : top (allGaps),
  72353. left (allGaps),
  72354. bottom (allGaps),
  72355. right (allGaps)
  72356. {
  72357. }
  72358. BorderSize::~BorderSize() throw()
  72359. {
  72360. }
  72361. void BorderSize::setTop (const int newTopGap) throw()
  72362. {
  72363. top = newTopGap;
  72364. }
  72365. void BorderSize::setLeft (const int newLeftGap) throw()
  72366. {
  72367. left = newLeftGap;
  72368. }
  72369. void BorderSize::setBottom (const int newBottomGap) throw()
  72370. {
  72371. bottom = newBottomGap;
  72372. }
  72373. void BorderSize::setRight (const int newRightGap) throw()
  72374. {
  72375. right = newRightGap;
  72376. }
  72377. const Rectangle<int> BorderSize::subtractedFrom (const Rectangle<int>& r) const throw()
  72378. {
  72379. return Rectangle<int> (r.getX() + left,
  72380. r.getY() + top,
  72381. r.getWidth() - (left + right),
  72382. r.getHeight() - (top + bottom));
  72383. }
  72384. void BorderSize::subtractFrom (Rectangle<int>& r) const throw()
  72385. {
  72386. r.setBounds (r.getX() + left,
  72387. r.getY() + top,
  72388. r.getWidth() - (left + right),
  72389. r.getHeight() - (top + bottom));
  72390. }
  72391. const Rectangle<int> BorderSize::addedTo (const Rectangle<int>& r) const throw()
  72392. {
  72393. return Rectangle<int> (r.getX() - left,
  72394. r.getY() - top,
  72395. r.getWidth() + (left + right),
  72396. r.getHeight() + (top + bottom));
  72397. }
  72398. void BorderSize::addTo (Rectangle<int>& r) const throw()
  72399. {
  72400. r.setBounds (r.getX() - left,
  72401. r.getY() - top,
  72402. r.getWidth() + (left + right),
  72403. r.getHeight() + (top + bottom));
  72404. }
  72405. bool BorderSize::operator== (const BorderSize& other) const throw()
  72406. {
  72407. return top == other.top
  72408. && left == other.left
  72409. && bottom == other.bottom
  72410. && right == other.right;
  72411. }
  72412. bool BorderSize::operator!= (const BorderSize& other) const throw()
  72413. {
  72414. return ! operator== (other);
  72415. }
  72416. END_JUCE_NAMESPACE
  72417. /*** End of inlined file: juce_BorderSize.cpp ***/
  72418. /*** Start of inlined file: juce_Path.cpp ***/
  72419. BEGIN_JUCE_NAMESPACE
  72420. // tests that some co-ords aren't NaNs
  72421. #define CHECK_COORDS_ARE_VALID(x, y) \
  72422. jassert (x == x && y == y);
  72423. namespace PathHelpers
  72424. {
  72425. static const float ellipseAngularIncrement = 0.05f;
  72426. static const String nextToken (const juce_wchar*& t)
  72427. {
  72428. while (CharacterFunctions::isWhitespace (*t))
  72429. ++t;
  72430. const juce_wchar* const start = t;
  72431. while (*t != 0 && ! CharacterFunctions::isWhitespace (*t))
  72432. ++t;
  72433. return String (start, (int) (t - start));
  72434. }
  72435. }
  72436. const float Path::lineMarker = 100001.0f;
  72437. const float Path::moveMarker = 100002.0f;
  72438. const float Path::quadMarker = 100003.0f;
  72439. const float Path::cubicMarker = 100004.0f;
  72440. const float Path::closeSubPathMarker = 100005.0f;
  72441. Path::Path()
  72442. : numElements (0),
  72443. pathXMin (0),
  72444. pathXMax (0),
  72445. pathYMin (0),
  72446. pathYMax (0),
  72447. useNonZeroWinding (true)
  72448. {
  72449. }
  72450. Path::~Path()
  72451. {
  72452. }
  72453. Path::Path (const Path& other)
  72454. : numElements (other.numElements),
  72455. pathXMin (other.pathXMin),
  72456. pathXMax (other.pathXMax),
  72457. pathYMin (other.pathYMin),
  72458. pathYMax (other.pathYMax),
  72459. useNonZeroWinding (other.useNonZeroWinding)
  72460. {
  72461. if (numElements > 0)
  72462. {
  72463. data.setAllocatedSize ((int) numElements);
  72464. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  72465. }
  72466. }
  72467. Path& Path::operator= (const Path& other)
  72468. {
  72469. if (this != &other)
  72470. {
  72471. data.ensureAllocatedSize ((int) other.numElements);
  72472. numElements = other.numElements;
  72473. pathXMin = other.pathXMin;
  72474. pathXMax = other.pathXMax;
  72475. pathYMin = other.pathYMin;
  72476. pathYMax = other.pathYMax;
  72477. useNonZeroWinding = other.useNonZeroWinding;
  72478. if (numElements > 0)
  72479. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  72480. }
  72481. return *this;
  72482. }
  72483. bool Path::operator== (const Path& other) const throw()
  72484. {
  72485. return ! operator!= (other);
  72486. }
  72487. bool Path::operator!= (const Path& other) const throw()
  72488. {
  72489. if (numElements != other.numElements || useNonZeroWinding != other.useNonZeroWinding)
  72490. return true;
  72491. for (size_t i = 0; i < numElements; ++i)
  72492. if (data.elements[i] != other.data.elements[i])
  72493. return true;
  72494. return false;
  72495. }
  72496. void Path::clear() throw()
  72497. {
  72498. numElements = 0;
  72499. pathXMin = 0;
  72500. pathYMin = 0;
  72501. pathYMax = 0;
  72502. pathXMax = 0;
  72503. }
  72504. void Path::swapWithPath (Path& other) throw()
  72505. {
  72506. data.swapWith (other.data);
  72507. swapVariables <size_t> (numElements, other.numElements);
  72508. swapVariables <float> (pathXMin, other.pathXMin);
  72509. swapVariables <float> (pathXMax, other.pathXMax);
  72510. swapVariables <float> (pathYMin, other.pathYMin);
  72511. swapVariables <float> (pathYMax, other.pathYMax);
  72512. swapVariables <bool> (useNonZeroWinding, other.useNonZeroWinding);
  72513. }
  72514. void Path::setUsingNonZeroWinding (const bool isNonZero) throw()
  72515. {
  72516. useNonZeroWinding = isNonZero;
  72517. }
  72518. void Path::scaleToFit (const float x, const float y, const float w, const float h,
  72519. const bool preserveProportions) throw()
  72520. {
  72521. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions));
  72522. }
  72523. bool Path::isEmpty() const throw()
  72524. {
  72525. size_t i = 0;
  72526. while (i < numElements)
  72527. {
  72528. const float type = data.elements [i++];
  72529. if (type == moveMarker)
  72530. {
  72531. i += 2;
  72532. }
  72533. else if (type == lineMarker
  72534. || type == quadMarker
  72535. || type == cubicMarker)
  72536. {
  72537. return false;
  72538. }
  72539. }
  72540. return true;
  72541. }
  72542. const Rectangle<float> Path::getBounds() const throw()
  72543. {
  72544. return Rectangle<float> (pathXMin, pathYMin,
  72545. pathXMax - pathXMin,
  72546. pathYMax - pathYMin);
  72547. }
  72548. const Rectangle<float> Path::getBoundsTransformed (const AffineTransform& transform) const throw()
  72549. {
  72550. return getBounds().transformed (transform);
  72551. }
  72552. void Path::startNewSubPath (const float x, const float y)
  72553. {
  72554. CHECK_COORDS_ARE_VALID (x, y);
  72555. if (numElements == 0)
  72556. {
  72557. pathXMin = pathXMax = x;
  72558. pathYMin = pathYMax = y;
  72559. }
  72560. else
  72561. {
  72562. pathXMin = jmin (pathXMin, x);
  72563. pathXMax = jmax (pathXMax, x);
  72564. pathYMin = jmin (pathYMin, y);
  72565. pathYMax = jmax (pathYMax, y);
  72566. }
  72567. data.ensureAllocatedSize ((int) numElements + 3);
  72568. data.elements [numElements++] = moveMarker;
  72569. data.elements [numElements++] = x;
  72570. data.elements [numElements++] = y;
  72571. }
  72572. void Path::startNewSubPath (const Point<float>& start)
  72573. {
  72574. startNewSubPath (start.getX(), start.getY());
  72575. }
  72576. void Path::lineTo (const float x, const float y)
  72577. {
  72578. CHECK_COORDS_ARE_VALID (x, y);
  72579. if (numElements == 0)
  72580. startNewSubPath (0, 0);
  72581. data.ensureAllocatedSize ((int) numElements + 3);
  72582. data.elements [numElements++] = lineMarker;
  72583. data.elements [numElements++] = x;
  72584. data.elements [numElements++] = y;
  72585. pathXMin = jmin (pathXMin, x);
  72586. pathXMax = jmax (pathXMax, x);
  72587. pathYMin = jmin (pathYMin, y);
  72588. pathYMax = jmax (pathYMax, y);
  72589. }
  72590. void Path::lineTo (const Point<float>& end)
  72591. {
  72592. lineTo (end.getX(), end.getY());
  72593. }
  72594. void Path::quadraticTo (const float x1, const float y1,
  72595. const float x2, const float y2)
  72596. {
  72597. CHECK_COORDS_ARE_VALID (x1, y1);
  72598. CHECK_COORDS_ARE_VALID (x2, y2);
  72599. if (numElements == 0)
  72600. startNewSubPath (0, 0);
  72601. data.ensureAllocatedSize ((int) numElements + 5);
  72602. data.elements [numElements++] = quadMarker;
  72603. data.elements [numElements++] = x1;
  72604. data.elements [numElements++] = y1;
  72605. data.elements [numElements++] = x2;
  72606. data.elements [numElements++] = y2;
  72607. pathXMin = jmin (pathXMin, x1, x2);
  72608. pathXMax = jmax (pathXMax, x1, x2);
  72609. pathYMin = jmin (pathYMin, y1, y2);
  72610. pathYMax = jmax (pathYMax, y1, y2);
  72611. }
  72612. void Path::quadraticTo (const Point<float>& controlPoint,
  72613. const Point<float>& endPoint)
  72614. {
  72615. quadraticTo (controlPoint.getX(), controlPoint.getY(),
  72616. endPoint.getX(), endPoint.getY());
  72617. }
  72618. void Path::cubicTo (const float x1, const float y1,
  72619. const float x2, const float y2,
  72620. const float x3, const float y3)
  72621. {
  72622. CHECK_COORDS_ARE_VALID (x1, y1);
  72623. CHECK_COORDS_ARE_VALID (x2, y2);
  72624. CHECK_COORDS_ARE_VALID (x3, y3);
  72625. if (numElements == 0)
  72626. startNewSubPath (0, 0);
  72627. data.ensureAllocatedSize ((int) numElements + 7);
  72628. data.elements [numElements++] = cubicMarker;
  72629. data.elements [numElements++] = x1;
  72630. data.elements [numElements++] = y1;
  72631. data.elements [numElements++] = x2;
  72632. data.elements [numElements++] = y2;
  72633. data.elements [numElements++] = x3;
  72634. data.elements [numElements++] = y3;
  72635. pathXMin = jmin (pathXMin, x1, x2, x3);
  72636. pathXMax = jmax (pathXMax, x1, x2, x3);
  72637. pathYMin = jmin (pathYMin, y1, y2, y3);
  72638. pathYMax = jmax (pathYMax, y1, y2, y3);
  72639. }
  72640. void Path::cubicTo (const Point<float>& controlPoint1,
  72641. const Point<float>& controlPoint2,
  72642. const Point<float>& endPoint)
  72643. {
  72644. cubicTo (controlPoint1.getX(), controlPoint1.getY(),
  72645. controlPoint2.getX(), controlPoint2.getY(),
  72646. endPoint.getX(), endPoint.getY());
  72647. }
  72648. void Path::closeSubPath()
  72649. {
  72650. if (numElements > 0
  72651. && data.elements [numElements - 1] != closeSubPathMarker)
  72652. {
  72653. data.ensureAllocatedSize ((int) numElements + 1);
  72654. data.elements [numElements++] = closeSubPathMarker;
  72655. }
  72656. }
  72657. const Point<float> Path::getCurrentPosition() const
  72658. {
  72659. size_t i = numElements - 1;
  72660. if (i > 0 && data.elements[i] == closeSubPathMarker)
  72661. {
  72662. while (i >= 0)
  72663. {
  72664. if (data.elements[i] == moveMarker)
  72665. {
  72666. i += 2;
  72667. break;
  72668. }
  72669. --i;
  72670. }
  72671. }
  72672. if (i > 0)
  72673. return Point<float> (data.elements [i - 1], data.elements [i]);
  72674. return Point<float>();
  72675. }
  72676. void Path::addRectangle (const float x, const float y,
  72677. const float w, const float h)
  72678. {
  72679. float x1 = x, y1 = y, x2 = x + w, y2 = y + h;
  72680. if (w < 0)
  72681. swapVariables (x1, x2);
  72682. if (h < 0)
  72683. swapVariables (y1, y2);
  72684. data.ensureAllocatedSize ((int) numElements + 13);
  72685. if (numElements == 0)
  72686. {
  72687. pathXMin = x1;
  72688. pathXMax = x2;
  72689. pathYMin = y1;
  72690. pathYMax = y2;
  72691. }
  72692. else
  72693. {
  72694. pathXMin = jmin (pathXMin, x1);
  72695. pathXMax = jmax (pathXMax, x2);
  72696. pathYMin = jmin (pathYMin, y1);
  72697. pathYMax = jmax (pathYMax, y2);
  72698. }
  72699. data.elements [numElements++] = moveMarker;
  72700. data.elements [numElements++] = x1;
  72701. data.elements [numElements++] = y2;
  72702. data.elements [numElements++] = lineMarker;
  72703. data.elements [numElements++] = x1;
  72704. data.elements [numElements++] = y1;
  72705. data.elements [numElements++] = lineMarker;
  72706. data.elements [numElements++] = x2;
  72707. data.elements [numElements++] = y1;
  72708. data.elements [numElements++] = lineMarker;
  72709. data.elements [numElements++] = x2;
  72710. data.elements [numElements++] = y2;
  72711. data.elements [numElements++] = closeSubPathMarker;
  72712. }
  72713. void Path::addRectangle (const Rectangle<int>& rectangle)
  72714. {
  72715. addRectangle ((float) rectangle.getX(), (float) rectangle.getY(),
  72716. (float) rectangle.getWidth(), (float) rectangle.getHeight());
  72717. }
  72718. void Path::addRoundedRectangle (const float x, const float y,
  72719. const float w, const float h,
  72720. float csx,
  72721. float csy)
  72722. {
  72723. csx = jmin (csx, w * 0.5f);
  72724. csy = jmin (csy, h * 0.5f);
  72725. const float cs45x = csx * 0.45f;
  72726. const float cs45y = csy * 0.45f;
  72727. const float x2 = x + w;
  72728. const float y2 = y + h;
  72729. startNewSubPath (x + csx, y);
  72730. lineTo (x2 - csx, y);
  72731. cubicTo (x2 - cs45x, y, x2, y + cs45y, x2, y + csy);
  72732. lineTo (x2, y2 - csy);
  72733. cubicTo (x2, y2 - cs45y, x2 - cs45x, y2, x2 - csx, y2);
  72734. lineTo (x + csx, y2);
  72735. cubicTo (x + cs45x, y2, x, y2 - cs45y, x, y2 - csy);
  72736. lineTo (x, y + csy);
  72737. cubicTo (x, y + cs45y, x + cs45x, y, x + csx, y);
  72738. closeSubPath();
  72739. }
  72740. void Path::addRoundedRectangle (const float x, const float y,
  72741. const float w, const float h,
  72742. float cs)
  72743. {
  72744. addRoundedRectangle (x, y, w, h, cs, cs);
  72745. }
  72746. void Path::addTriangle (const float x1, const float y1,
  72747. const float x2, const float y2,
  72748. const float x3, const float y3)
  72749. {
  72750. startNewSubPath (x1, y1);
  72751. lineTo (x2, y2);
  72752. lineTo (x3, y3);
  72753. closeSubPath();
  72754. }
  72755. void Path::addQuadrilateral (const float x1, const float y1,
  72756. const float x2, const float y2,
  72757. const float x3, const float y3,
  72758. const float x4, const float y4)
  72759. {
  72760. startNewSubPath (x1, y1);
  72761. lineTo (x2, y2);
  72762. lineTo (x3, y3);
  72763. lineTo (x4, y4);
  72764. closeSubPath();
  72765. }
  72766. void Path::addEllipse (const float x, const float y,
  72767. const float w, const float h)
  72768. {
  72769. const float hw = w * 0.5f;
  72770. const float hw55 = hw * 0.55f;
  72771. const float hh = h * 0.5f;
  72772. const float hh45 = hh * 0.55f;
  72773. const float cx = x + hw;
  72774. const float cy = y + hh;
  72775. startNewSubPath (cx, cy - hh);
  72776. cubicTo (cx + hw55, cy - hh, cx + hw, cy - hh45, cx + hw, cy);
  72777. cubicTo (cx + hw, cy + hh45, cx + hw55, cy + hh, cx, cy + hh);
  72778. cubicTo (cx - hw55, cy + hh, cx - hw, cy + hh45, cx - hw, cy);
  72779. cubicTo (cx - hw, cy - hh45, cx - hw55, cy - hh, cx, cy - hh);
  72780. closeSubPath();
  72781. }
  72782. void Path::addArc (const float x, const float y,
  72783. const float w, const float h,
  72784. const float fromRadians,
  72785. const float toRadians,
  72786. const bool startAsNewSubPath)
  72787. {
  72788. const float radiusX = w / 2.0f;
  72789. const float radiusY = h / 2.0f;
  72790. addCentredArc (x + radiusX,
  72791. y + radiusY,
  72792. radiusX, radiusY,
  72793. 0.0f,
  72794. fromRadians, toRadians,
  72795. startAsNewSubPath);
  72796. }
  72797. void Path::addCentredArc (const float centreX, const float centreY,
  72798. const float radiusX, const float radiusY,
  72799. const float rotationOfEllipse,
  72800. const float fromRadians,
  72801. const float toRadians,
  72802. const bool startAsNewSubPath)
  72803. {
  72804. if (radiusX > 0.0f && radiusY > 0.0f)
  72805. {
  72806. const Point<float> centre (centreX, centreY);
  72807. const AffineTransform rotation (AffineTransform::rotation (rotationOfEllipse, centreX, centreY));
  72808. float angle = fromRadians;
  72809. if (startAsNewSubPath)
  72810. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  72811. if (fromRadians < toRadians)
  72812. {
  72813. if (startAsNewSubPath)
  72814. angle += PathHelpers::ellipseAngularIncrement;
  72815. while (angle < toRadians)
  72816. {
  72817. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  72818. angle += PathHelpers::ellipseAngularIncrement;
  72819. }
  72820. }
  72821. else
  72822. {
  72823. if (startAsNewSubPath)
  72824. angle -= PathHelpers::ellipseAngularIncrement;
  72825. while (angle > toRadians)
  72826. {
  72827. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  72828. angle -= PathHelpers::ellipseAngularIncrement;
  72829. }
  72830. }
  72831. lineTo (centre.getPointOnCircumference (radiusX, radiusY, toRadians).transformedBy (rotation));
  72832. }
  72833. }
  72834. void Path::addPieSegment (const float x, const float y,
  72835. const float width, const float height,
  72836. const float fromRadians,
  72837. const float toRadians,
  72838. const float innerCircleProportionalSize)
  72839. {
  72840. float radiusX = width * 0.5f;
  72841. float radiusY = height * 0.5f;
  72842. const Point<float> centre (x + radiusX, y + radiusY);
  72843. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, fromRadians));
  72844. addArc (x, y, width, height, fromRadians, toRadians);
  72845. if (std::abs (fromRadians - toRadians) > float_Pi * 1.999f)
  72846. {
  72847. closeSubPath();
  72848. if (innerCircleProportionalSize > 0)
  72849. {
  72850. radiusX *= innerCircleProportionalSize;
  72851. radiusY *= innerCircleProportionalSize;
  72852. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, toRadians));
  72853. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  72854. }
  72855. }
  72856. else
  72857. {
  72858. if (innerCircleProportionalSize > 0)
  72859. {
  72860. radiusX *= innerCircleProportionalSize;
  72861. radiusY *= innerCircleProportionalSize;
  72862. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  72863. }
  72864. else
  72865. {
  72866. lineTo (centre);
  72867. }
  72868. }
  72869. closeSubPath();
  72870. }
  72871. void Path::addLineSegment (const Line<float>& line, float lineThickness)
  72872. {
  72873. const Line<float> reversed (line.reversed());
  72874. lineThickness *= 0.5f;
  72875. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  72876. lineTo (line.getPointAlongLine (0, -lineThickness));
  72877. lineTo (reversed.getPointAlongLine (0, lineThickness));
  72878. lineTo (reversed.getPointAlongLine (0, -lineThickness));
  72879. closeSubPath();
  72880. }
  72881. void Path::addArrow (const Line<float>& line, float lineThickness,
  72882. float arrowheadWidth, float arrowheadLength)
  72883. {
  72884. const Line<float> reversed (line.reversed());
  72885. lineThickness *= 0.5f;
  72886. arrowheadWidth *= 0.5f;
  72887. arrowheadLength = jmin (arrowheadLength, 0.8f * line.getLength());
  72888. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  72889. lineTo (line.getPointAlongLine (0, -lineThickness));
  72890. lineTo (reversed.getPointAlongLine (arrowheadLength, lineThickness));
  72891. lineTo (reversed.getPointAlongLine (arrowheadLength, arrowheadWidth));
  72892. lineTo (line.getEnd());
  72893. lineTo (reversed.getPointAlongLine (arrowheadLength, -arrowheadWidth));
  72894. lineTo (reversed.getPointAlongLine (arrowheadLength, -lineThickness));
  72895. closeSubPath();
  72896. }
  72897. void Path::addPolygon (const Point<float>& centre, const int numberOfSides,
  72898. const float radius, const float startAngle)
  72899. {
  72900. jassert (numberOfSides > 1); // this would be silly.
  72901. if (numberOfSides > 1)
  72902. {
  72903. const float angleBetweenPoints = float_Pi * 2.0f / numberOfSides;
  72904. for (int i = 0; i < numberOfSides; ++i)
  72905. {
  72906. const float angle = startAngle + i * angleBetweenPoints;
  72907. const Point<float> p (centre.getPointOnCircumference (radius, angle));
  72908. if (i == 0)
  72909. startNewSubPath (p);
  72910. else
  72911. lineTo (p);
  72912. }
  72913. closeSubPath();
  72914. }
  72915. }
  72916. void Path::addStar (const Point<float>& centre, const int numberOfPoints,
  72917. const float innerRadius, const float outerRadius, const float startAngle)
  72918. {
  72919. jassert (numberOfPoints > 1); // this would be silly.
  72920. if (numberOfPoints > 1)
  72921. {
  72922. const float angleBetweenPoints = float_Pi * 2.0f / numberOfPoints;
  72923. for (int i = 0; i < numberOfPoints; ++i)
  72924. {
  72925. const float angle = startAngle + i * angleBetweenPoints;
  72926. const Point<float> p (centre.getPointOnCircumference (outerRadius, angle));
  72927. if (i == 0)
  72928. startNewSubPath (p);
  72929. else
  72930. lineTo (p);
  72931. lineTo (centre.getPointOnCircumference (innerRadius, angle + angleBetweenPoints * 0.5f));
  72932. }
  72933. closeSubPath();
  72934. }
  72935. }
  72936. void Path::addBubble (float x, float y,
  72937. float w, float h,
  72938. float cs,
  72939. float tipX,
  72940. float tipY,
  72941. int whichSide,
  72942. float arrowPos,
  72943. float arrowWidth)
  72944. {
  72945. if (w > 1.0f && h > 1.0f)
  72946. {
  72947. cs = jmin (cs, w * 0.5f, h * 0.5f);
  72948. const float cs2 = 2.0f * cs;
  72949. startNewSubPath (x + cs, y);
  72950. if (whichSide == 0)
  72951. {
  72952. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  72953. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  72954. lineTo (arrowX1, y);
  72955. lineTo (tipX, tipY);
  72956. lineTo (arrowX1 + halfArrowW * 2.0f, y);
  72957. }
  72958. lineTo (x + w - cs, y);
  72959. if (cs > 0.0f)
  72960. addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  72961. if (whichSide == 3)
  72962. {
  72963. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  72964. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  72965. lineTo (x + w, arrowY1);
  72966. lineTo (tipX, tipY);
  72967. lineTo (x + w, arrowY1 + halfArrowH * 2.0f);
  72968. }
  72969. lineTo (x + w, y + h - cs);
  72970. if (cs > 0.0f)
  72971. addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  72972. if (whichSide == 2)
  72973. {
  72974. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  72975. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  72976. lineTo (arrowX1 + halfArrowW * 2.0f, y + h);
  72977. lineTo (tipX, tipY);
  72978. lineTo (arrowX1, y + h);
  72979. }
  72980. lineTo (x + cs, y + h);
  72981. if (cs > 0.0f)
  72982. addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  72983. if (whichSide == 1)
  72984. {
  72985. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  72986. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  72987. lineTo (x, arrowY1 + halfArrowH * 2.0f);
  72988. lineTo (tipX, tipY);
  72989. lineTo (x, arrowY1);
  72990. }
  72991. lineTo (x, y + cs);
  72992. if (cs > 0.0f)
  72993. addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f - PathHelpers::ellipseAngularIncrement);
  72994. closeSubPath();
  72995. }
  72996. }
  72997. void Path::addPath (const Path& other)
  72998. {
  72999. size_t i = 0;
  73000. while (i < other.numElements)
  73001. {
  73002. const float type = other.data.elements [i++];
  73003. if (type == moveMarker)
  73004. {
  73005. startNewSubPath (other.data.elements [i],
  73006. other.data.elements [i + 1]);
  73007. i += 2;
  73008. }
  73009. else if (type == lineMarker)
  73010. {
  73011. lineTo (other.data.elements [i],
  73012. other.data.elements [i + 1]);
  73013. i += 2;
  73014. }
  73015. else if (type == quadMarker)
  73016. {
  73017. quadraticTo (other.data.elements [i],
  73018. other.data.elements [i + 1],
  73019. other.data.elements [i + 2],
  73020. other.data.elements [i + 3]);
  73021. i += 4;
  73022. }
  73023. else if (type == cubicMarker)
  73024. {
  73025. cubicTo (other.data.elements [i],
  73026. other.data.elements [i + 1],
  73027. other.data.elements [i + 2],
  73028. other.data.elements [i + 3],
  73029. other.data.elements [i + 4],
  73030. other.data.elements [i + 5]);
  73031. i += 6;
  73032. }
  73033. else if (type == closeSubPathMarker)
  73034. {
  73035. closeSubPath();
  73036. }
  73037. else
  73038. {
  73039. // something's gone wrong with the element list!
  73040. jassertfalse;
  73041. }
  73042. }
  73043. }
  73044. void Path::addPath (const Path& other,
  73045. const AffineTransform& transformToApply)
  73046. {
  73047. size_t i = 0;
  73048. while (i < other.numElements)
  73049. {
  73050. const float type = other.data.elements [i++];
  73051. if (type == closeSubPathMarker)
  73052. {
  73053. closeSubPath();
  73054. }
  73055. else
  73056. {
  73057. float x = other.data.elements [i++];
  73058. float y = other.data.elements [i++];
  73059. transformToApply.transformPoint (x, y);
  73060. if (type == moveMarker)
  73061. {
  73062. startNewSubPath (x, y);
  73063. }
  73064. else if (type == lineMarker)
  73065. {
  73066. lineTo (x, y);
  73067. }
  73068. else if (type == quadMarker)
  73069. {
  73070. float x2 = other.data.elements [i++];
  73071. float y2 = other.data.elements [i++];
  73072. transformToApply.transformPoint (x2, y2);
  73073. quadraticTo (x, y, x2, y2);
  73074. }
  73075. else if (type == cubicMarker)
  73076. {
  73077. float x2 = other.data.elements [i++];
  73078. float y2 = other.data.elements [i++];
  73079. float x3 = other.data.elements [i++];
  73080. float y3 = other.data.elements [i++];
  73081. transformToApply.transformPoints (x2, y2, x3, y3);
  73082. cubicTo (x, y, x2, y2, x3, y3);
  73083. }
  73084. else
  73085. {
  73086. // something's gone wrong with the element list!
  73087. jassertfalse;
  73088. }
  73089. }
  73090. }
  73091. }
  73092. void Path::applyTransform (const AffineTransform& transform) throw()
  73093. {
  73094. size_t i = 0;
  73095. pathYMin = pathXMin = 0;
  73096. pathYMax = pathXMax = 0;
  73097. bool setMaxMin = false;
  73098. while (i < numElements)
  73099. {
  73100. const float type = data.elements [i++];
  73101. if (type == moveMarker)
  73102. {
  73103. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  73104. if (setMaxMin)
  73105. {
  73106. pathXMin = jmin (pathXMin, data.elements [i]);
  73107. pathXMax = jmax (pathXMax, data.elements [i]);
  73108. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  73109. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  73110. }
  73111. else
  73112. {
  73113. pathXMin = pathXMax = data.elements [i];
  73114. pathYMin = pathYMax = data.elements [i + 1];
  73115. setMaxMin = true;
  73116. }
  73117. i += 2;
  73118. }
  73119. else if (type == lineMarker)
  73120. {
  73121. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  73122. pathXMin = jmin (pathXMin, data.elements [i]);
  73123. pathXMax = jmax (pathXMax, data.elements [i]);
  73124. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  73125. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  73126. i += 2;
  73127. }
  73128. else if (type == quadMarker)
  73129. {
  73130. transform.transformPoints (data.elements [i], data.elements [i + 1],
  73131. data.elements [i + 2], data.elements [i + 3]);
  73132. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2]);
  73133. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2]);
  73134. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3]);
  73135. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3]);
  73136. i += 4;
  73137. }
  73138. else if (type == cubicMarker)
  73139. {
  73140. transform.transformPoints (data.elements [i], data.elements [i + 1],
  73141. data.elements [i + 2], data.elements [i + 3],
  73142. data.elements [i + 4], data.elements [i + 5]);
  73143. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  73144. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  73145. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  73146. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  73147. i += 6;
  73148. }
  73149. }
  73150. }
  73151. const AffineTransform Path::getTransformToScaleToFit (const float x, const float y,
  73152. const float w, const float h,
  73153. const bool preserveProportions,
  73154. const Justification& justification) const
  73155. {
  73156. Rectangle<float> bounds (getBounds());
  73157. if (preserveProportions)
  73158. {
  73159. if (w <= 0 || h <= 0 || bounds.isEmpty())
  73160. return AffineTransform::identity;
  73161. float newW, newH;
  73162. const float srcRatio = bounds.getHeight() / bounds.getWidth();
  73163. if (srcRatio > h / w)
  73164. {
  73165. newW = h / srcRatio;
  73166. newH = h;
  73167. }
  73168. else
  73169. {
  73170. newW = w;
  73171. newH = w * srcRatio;
  73172. }
  73173. float newXCentre = x;
  73174. float newYCentre = y;
  73175. if (justification.testFlags (Justification::left))
  73176. newXCentre += newW * 0.5f;
  73177. else if (justification.testFlags (Justification::right))
  73178. newXCentre += w - newW * 0.5f;
  73179. else
  73180. newXCentre += w * 0.5f;
  73181. if (justification.testFlags (Justification::top))
  73182. newYCentre += newH * 0.5f;
  73183. else if (justification.testFlags (Justification::bottom))
  73184. newYCentre += h - newH * 0.5f;
  73185. else
  73186. newYCentre += h * 0.5f;
  73187. return AffineTransform::translation (bounds.getWidth() * -0.5f - bounds.getX(),
  73188. bounds.getHeight() * -0.5f - bounds.getY())
  73189. .scaled (newW / bounds.getWidth(), newH / bounds.getHeight())
  73190. .translated (newXCentre, newYCentre);
  73191. }
  73192. else
  73193. {
  73194. return AffineTransform::translation (-bounds.getX(), -bounds.getY())
  73195. .scaled (w / bounds.getWidth(), h / bounds.getHeight())
  73196. .translated (x, y);
  73197. }
  73198. }
  73199. bool Path::contains (const float x, const float y, const float tolerence) const
  73200. {
  73201. if (x <= pathXMin || x >= pathXMax
  73202. || y <= pathYMin || y >= pathYMax)
  73203. return false;
  73204. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  73205. int positiveCrossings = 0;
  73206. int negativeCrossings = 0;
  73207. while (i.next())
  73208. {
  73209. if ((i.y1 <= y && i.y2 > y) || (i.y2 <= y && i.y1 > y))
  73210. {
  73211. const float intersectX = i.x1 + (i.x2 - i.x1) * (y - i.y1) / (i.y2 - i.y1);
  73212. if (intersectX <= x)
  73213. {
  73214. if (i.y1 < i.y2)
  73215. ++positiveCrossings;
  73216. else
  73217. ++negativeCrossings;
  73218. }
  73219. }
  73220. }
  73221. return useNonZeroWinding ? (negativeCrossings != positiveCrossings)
  73222. : ((negativeCrossings + positiveCrossings) & 1) != 0;
  73223. }
  73224. bool Path::contains (const Point<float>& point, const float tolerence) const
  73225. {
  73226. return contains (point.getX(), point.getY(), tolerence);
  73227. }
  73228. bool Path::intersectsLine (const Line<float>& line, const float tolerence)
  73229. {
  73230. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  73231. Point<float> intersection;
  73232. while (i.next())
  73233. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  73234. return true;
  73235. return false;
  73236. }
  73237. const Line<float> Path::getClippedLine (const Line<float>& line, const bool keepSectionOutsidePath) const
  73238. {
  73239. Line<float> result (line);
  73240. const bool startInside = contains (line.getStart());
  73241. const bool endInside = contains (line.getEnd());
  73242. if (startInside == endInside)
  73243. {
  73244. if (keepSectionOutsidePath == startInside)
  73245. result = Line<float>();
  73246. }
  73247. else
  73248. {
  73249. PathFlatteningIterator i (*this, AffineTransform::identity);
  73250. Point<float> intersection;
  73251. while (i.next())
  73252. {
  73253. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  73254. {
  73255. if ((startInside && keepSectionOutsidePath) || (endInside && ! keepSectionOutsidePath))
  73256. result.setStart (intersection);
  73257. else
  73258. result.setEnd (intersection);
  73259. }
  73260. }
  73261. }
  73262. return result;
  73263. }
  73264. const Path Path::createPathWithRoundedCorners (const float cornerRadius) const
  73265. {
  73266. if (cornerRadius <= 0.01f)
  73267. return *this;
  73268. size_t indexOfPathStart = 0, indexOfPathStartThis = 0;
  73269. size_t n = 0;
  73270. bool lastWasLine = false, firstWasLine = false;
  73271. Path p;
  73272. while (n < numElements)
  73273. {
  73274. const float type = data.elements [n++];
  73275. if (type == moveMarker)
  73276. {
  73277. indexOfPathStart = p.numElements;
  73278. indexOfPathStartThis = n - 1;
  73279. const float x = data.elements [n++];
  73280. const float y = data.elements [n++];
  73281. p.startNewSubPath (x, y);
  73282. lastWasLine = false;
  73283. firstWasLine = (data.elements [n] == lineMarker);
  73284. }
  73285. else if (type == lineMarker || type == closeSubPathMarker)
  73286. {
  73287. float startX = 0, startY = 0, joinX = 0, joinY = 0, endX, endY;
  73288. if (type == lineMarker)
  73289. {
  73290. endX = data.elements [n++];
  73291. endY = data.elements [n++];
  73292. if (n > 8)
  73293. {
  73294. startX = data.elements [n - 8];
  73295. startY = data.elements [n - 7];
  73296. joinX = data.elements [n - 5];
  73297. joinY = data.elements [n - 4];
  73298. }
  73299. }
  73300. else
  73301. {
  73302. endX = data.elements [indexOfPathStartThis + 1];
  73303. endY = data.elements [indexOfPathStartThis + 2];
  73304. if (n > 6)
  73305. {
  73306. startX = data.elements [n - 6];
  73307. startY = data.elements [n - 5];
  73308. joinX = data.elements [n - 3];
  73309. joinY = data.elements [n - 2];
  73310. }
  73311. }
  73312. if (lastWasLine)
  73313. {
  73314. const double len1 = juce_hypot (startX - joinX,
  73315. startY - joinY);
  73316. if (len1 > 0)
  73317. {
  73318. const double propNeeded = jmin (0.5, cornerRadius / len1);
  73319. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  73320. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  73321. }
  73322. const double len2 = juce_hypot (endX - joinX,
  73323. endY - joinY);
  73324. if (len2 > 0)
  73325. {
  73326. const double propNeeded = jmin (0.5, cornerRadius / len2);
  73327. p.quadraticTo (joinX, joinY,
  73328. (float) (joinX + (endX - joinX) * propNeeded),
  73329. (float) (joinY + (endY - joinY) * propNeeded));
  73330. }
  73331. p.lineTo (endX, endY);
  73332. }
  73333. else if (type == lineMarker)
  73334. {
  73335. p.lineTo (endX, endY);
  73336. lastWasLine = true;
  73337. }
  73338. if (type == closeSubPathMarker)
  73339. {
  73340. if (firstWasLine)
  73341. {
  73342. startX = data.elements [n - 3];
  73343. startY = data.elements [n - 2];
  73344. joinX = endX;
  73345. joinY = endY;
  73346. endX = data.elements [indexOfPathStartThis + 4];
  73347. endY = data.elements [indexOfPathStartThis + 5];
  73348. const double len1 = juce_hypot (startX - joinX,
  73349. startY - joinY);
  73350. if (len1 > 0)
  73351. {
  73352. const double propNeeded = jmin (0.5, cornerRadius / len1);
  73353. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  73354. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  73355. }
  73356. const double len2 = juce_hypot (endX - joinX,
  73357. endY - joinY);
  73358. if (len2 > 0)
  73359. {
  73360. const double propNeeded = jmin (0.5, cornerRadius / len2);
  73361. endX = (float) (joinX + (endX - joinX) * propNeeded);
  73362. endY = (float) (joinY + (endY - joinY) * propNeeded);
  73363. p.quadraticTo (joinX, joinY, endX, endY);
  73364. p.data.elements [indexOfPathStart + 1] = endX;
  73365. p.data.elements [indexOfPathStart + 2] = endY;
  73366. }
  73367. }
  73368. p.closeSubPath();
  73369. }
  73370. }
  73371. else if (type == quadMarker)
  73372. {
  73373. lastWasLine = false;
  73374. const float x1 = data.elements [n++];
  73375. const float y1 = data.elements [n++];
  73376. const float x2 = data.elements [n++];
  73377. const float y2 = data.elements [n++];
  73378. p.quadraticTo (x1, y1, x2, y2);
  73379. }
  73380. else if (type == cubicMarker)
  73381. {
  73382. lastWasLine = false;
  73383. const float x1 = data.elements [n++];
  73384. const float y1 = data.elements [n++];
  73385. const float x2 = data.elements [n++];
  73386. const float y2 = data.elements [n++];
  73387. const float x3 = data.elements [n++];
  73388. const float y3 = data.elements [n++];
  73389. p.cubicTo (x1, y1, x2, y2, x3, y3);
  73390. }
  73391. }
  73392. return p;
  73393. }
  73394. void Path::loadPathFromStream (InputStream& source)
  73395. {
  73396. while (! source.isExhausted())
  73397. {
  73398. switch (source.readByte())
  73399. {
  73400. case 'm':
  73401. {
  73402. const float x = source.readFloat();
  73403. const float y = source.readFloat();
  73404. startNewSubPath (x, y);
  73405. break;
  73406. }
  73407. case 'l':
  73408. {
  73409. const float x = source.readFloat();
  73410. const float y = source.readFloat();
  73411. lineTo (x, y);
  73412. break;
  73413. }
  73414. case 'q':
  73415. {
  73416. const float x1 = source.readFloat();
  73417. const float y1 = source.readFloat();
  73418. const float x2 = source.readFloat();
  73419. const float y2 = source.readFloat();
  73420. quadraticTo (x1, y1, x2, y2);
  73421. break;
  73422. }
  73423. case 'b':
  73424. {
  73425. const float x1 = source.readFloat();
  73426. const float y1 = source.readFloat();
  73427. const float x2 = source.readFloat();
  73428. const float y2 = source.readFloat();
  73429. const float x3 = source.readFloat();
  73430. const float y3 = source.readFloat();
  73431. cubicTo (x1, y1, x2, y2, x3, y3);
  73432. break;
  73433. }
  73434. case 'c':
  73435. closeSubPath();
  73436. break;
  73437. case 'n':
  73438. useNonZeroWinding = true;
  73439. break;
  73440. case 'z':
  73441. useNonZeroWinding = false;
  73442. break;
  73443. case 'e':
  73444. return; // end of path marker
  73445. default:
  73446. jassertfalse; // illegal char in the stream
  73447. break;
  73448. }
  73449. }
  73450. }
  73451. void Path::loadPathFromData (const void* const pathData, const int numberOfBytes)
  73452. {
  73453. MemoryInputStream in (pathData, numberOfBytes, false);
  73454. loadPathFromStream (in);
  73455. }
  73456. void Path::writePathToStream (OutputStream& dest) const
  73457. {
  73458. dest.writeByte (useNonZeroWinding ? 'n' : 'z');
  73459. size_t i = 0;
  73460. while (i < numElements)
  73461. {
  73462. const float type = data.elements [i++];
  73463. if (type == moveMarker)
  73464. {
  73465. dest.writeByte ('m');
  73466. dest.writeFloat (data.elements [i++]);
  73467. dest.writeFloat (data.elements [i++]);
  73468. }
  73469. else if (type == lineMarker)
  73470. {
  73471. dest.writeByte ('l');
  73472. dest.writeFloat (data.elements [i++]);
  73473. dest.writeFloat (data.elements [i++]);
  73474. }
  73475. else if (type == quadMarker)
  73476. {
  73477. dest.writeByte ('q');
  73478. dest.writeFloat (data.elements [i++]);
  73479. dest.writeFloat (data.elements [i++]);
  73480. dest.writeFloat (data.elements [i++]);
  73481. dest.writeFloat (data.elements [i++]);
  73482. }
  73483. else if (type == cubicMarker)
  73484. {
  73485. dest.writeByte ('b');
  73486. dest.writeFloat (data.elements [i++]);
  73487. dest.writeFloat (data.elements [i++]);
  73488. dest.writeFloat (data.elements [i++]);
  73489. dest.writeFloat (data.elements [i++]);
  73490. dest.writeFloat (data.elements [i++]);
  73491. dest.writeFloat (data.elements [i++]);
  73492. }
  73493. else if (type == closeSubPathMarker)
  73494. {
  73495. dest.writeByte ('c');
  73496. }
  73497. }
  73498. dest.writeByte ('e'); // marks the end-of-path
  73499. }
  73500. const String Path::toString() const
  73501. {
  73502. MemoryOutputStream s (2048, 2048);
  73503. if (! useNonZeroWinding)
  73504. s << 'a';
  73505. size_t i = 0;
  73506. float lastMarker = 0.0f;
  73507. while (i < numElements)
  73508. {
  73509. const float marker = data.elements [i++];
  73510. char markerChar = 0;
  73511. int numCoords = 0;
  73512. if (marker == moveMarker)
  73513. {
  73514. markerChar = 'm';
  73515. numCoords = 2;
  73516. }
  73517. else if (marker == lineMarker)
  73518. {
  73519. markerChar = 'l';
  73520. numCoords = 2;
  73521. }
  73522. else if (marker == quadMarker)
  73523. {
  73524. markerChar = 'q';
  73525. numCoords = 4;
  73526. }
  73527. else if (marker == cubicMarker)
  73528. {
  73529. markerChar = 'c';
  73530. numCoords = 6;
  73531. }
  73532. else
  73533. {
  73534. jassert (marker == closeSubPathMarker);
  73535. markerChar = 'z';
  73536. }
  73537. if (marker != lastMarker)
  73538. {
  73539. if (s.getDataSize() != 0)
  73540. s << ' ';
  73541. s << markerChar;
  73542. lastMarker = marker;
  73543. }
  73544. while (--numCoords >= 0 && i < numElements)
  73545. {
  73546. String coord (data.elements [i++], 3);
  73547. while (coord.endsWithChar ('0') && coord != "0")
  73548. coord = coord.dropLastCharacters (1);
  73549. if (coord.endsWithChar ('.'))
  73550. coord = coord.dropLastCharacters (1);
  73551. if (s.getDataSize() != 0)
  73552. s << ' ';
  73553. s << coord;
  73554. }
  73555. }
  73556. return s.toUTF8();
  73557. }
  73558. void Path::restoreFromString (const String& stringVersion)
  73559. {
  73560. clear();
  73561. setUsingNonZeroWinding (true);
  73562. const juce_wchar* t = stringVersion;
  73563. juce_wchar marker = 'm';
  73564. int numValues = 2;
  73565. float values [6];
  73566. for (;;)
  73567. {
  73568. const String token (PathHelpers::nextToken (t));
  73569. const juce_wchar firstChar = token[0];
  73570. int startNum = 0;
  73571. if (firstChar == 0)
  73572. break;
  73573. if (firstChar == 'm' || firstChar == 'l')
  73574. {
  73575. marker = firstChar;
  73576. numValues = 2;
  73577. }
  73578. else if (firstChar == 'q')
  73579. {
  73580. marker = firstChar;
  73581. numValues = 4;
  73582. }
  73583. else if (firstChar == 'c')
  73584. {
  73585. marker = firstChar;
  73586. numValues = 6;
  73587. }
  73588. else if (firstChar == 'z')
  73589. {
  73590. marker = firstChar;
  73591. numValues = 0;
  73592. }
  73593. else if (firstChar == 'a')
  73594. {
  73595. setUsingNonZeroWinding (false);
  73596. continue;
  73597. }
  73598. else
  73599. {
  73600. ++startNum;
  73601. values [0] = token.getFloatValue();
  73602. }
  73603. for (int i = startNum; i < numValues; ++i)
  73604. values [i] = PathHelpers::nextToken (t).getFloatValue();
  73605. switch (marker)
  73606. {
  73607. case 'm':
  73608. startNewSubPath (values[0], values[1]);
  73609. break;
  73610. case 'l':
  73611. lineTo (values[0], values[1]);
  73612. break;
  73613. case 'q':
  73614. quadraticTo (values[0], values[1],
  73615. values[2], values[3]);
  73616. break;
  73617. case 'c':
  73618. cubicTo (values[0], values[1],
  73619. values[2], values[3],
  73620. values[4], values[5]);
  73621. break;
  73622. case 'z':
  73623. closeSubPath();
  73624. break;
  73625. default:
  73626. jassertfalse; // illegal string format?
  73627. break;
  73628. }
  73629. }
  73630. }
  73631. Path::Iterator::Iterator (const Path& path_)
  73632. : path (path_),
  73633. index (0)
  73634. {
  73635. }
  73636. Path::Iterator::~Iterator()
  73637. {
  73638. }
  73639. bool Path::Iterator::next()
  73640. {
  73641. const float* const elements = path.data.elements;
  73642. if (index < path.numElements)
  73643. {
  73644. const float type = elements [index++];
  73645. if (type == moveMarker)
  73646. {
  73647. elementType = startNewSubPath;
  73648. x1 = elements [index++];
  73649. y1 = elements [index++];
  73650. }
  73651. else if (type == lineMarker)
  73652. {
  73653. elementType = lineTo;
  73654. x1 = elements [index++];
  73655. y1 = elements [index++];
  73656. }
  73657. else if (type == quadMarker)
  73658. {
  73659. elementType = quadraticTo;
  73660. x1 = elements [index++];
  73661. y1 = elements [index++];
  73662. x2 = elements [index++];
  73663. y2 = elements [index++];
  73664. }
  73665. else if (type == cubicMarker)
  73666. {
  73667. elementType = cubicTo;
  73668. x1 = elements [index++];
  73669. y1 = elements [index++];
  73670. x2 = elements [index++];
  73671. y2 = elements [index++];
  73672. x3 = elements [index++];
  73673. y3 = elements [index++];
  73674. }
  73675. else if (type == closeSubPathMarker)
  73676. {
  73677. elementType = closePath;
  73678. }
  73679. return true;
  73680. }
  73681. return false;
  73682. }
  73683. END_JUCE_NAMESPACE
  73684. /*** End of inlined file: juce_Path.cpp ***/
  73685. /*** Start of inlined file: juce_PathIterator.cpp ***/
  73686. BEGIN_JUCE_NAMESPACE
  73687. #if JUCE_MSVC && JUCE_DEBUG
  73688. #pragma optimize ("t", on)
  73689. #endif
  73690. PathFlatteningIterator::PathFlatteningIterator (const Path& path_,
  73691. const AffineTransform& transform_,
  73692. float tolerence_)
  73693. : x2 (0),
  73694. y2 (0),
  73695. closesSubPath (false),
  73696. subPathIndex (-1),
  73697. path (path_),
  73698. transform (transform_),
  73699. points (path_.data.elements),
  73700. tolerence (tolerence_ * tolerence_),
  73701. subPathCloseX (0),
  73702. subPathCloseY (0),
  73703. isIdentityTransform (transform_.isIdentity()),
  73704. stackBase (32),
  73705. index (0),
  73706. stackSize (32)
  73707. {
  73708. stackPos = stackBase;
  73709. }
  73710. PathFlatteningIterator::~PathFlatteningIterator()
  73711. {
  73712. }
  73713. bool PathFlatteningIterator::next()
  73714. {
  73715. x1 = x2;
  73716. y1 = y2;
  73717. float x3 = 0;
  73718. float y3 = 0;
  73719. float x4 = 0;
  73720. float y4 = 0;
  73721. float type;
  73722. for (;;)
  73723. {
  73724. if (stackPos == stackBase)
  73725. {
  73726. if (index >= path.numElements)
  73727. {
  73728. return false;
  73729. }
  73730. else
  73731. {
  73732. type = points [index++];
  73733. if (type != Path::closeSubPathMarker)
  73734. {
  73735. x2 = points [index++];
  73736. y2 = points [index++];
  73737. if (type == Path::quadMarker)
  73738. {
  73739. x3 = points [index++];
  73740. y3 = points [index++];
  73741. if (! isIdentityTransform)
  73742. transform.transformPoints (x2, y2, x3, y3);
  73743. }
  73744. else if (type == Path::cubicMarker)
  73745. {
  73746. x3 = points [index++];
  73747. y3 = points [index++];
  73748. x4 = points [index++];
  73749. y4 = points [index++];
  73750. if (! isIdentityTransform)
  73751. transform.transformPoints (x2, y2, x3, y3, x4, y4);
  73752. }
  73753. else
  73754. {
  73755. if (! isIdentityTransform)
  73756. transform.transformPoint (x2, y2);
  73757. }
  73758. }
  73759. }
  73760. }
  73761. else
  73762. {
  73763. type = *--stackPos;
  73764. if (type != Path::closeSubPathMarker)
  73765. {
  73766. x2 = *--stackPos;
  73767. y2 = *--stackPos;
  73768. if (type == Path::quadMarker)
  73769. {
  73770. x3 = *--stackPos;
  73771. y3 = *--stackPos;
  73772. }
  73773. else if (type == Path::cubicMarker)
  73774. {
  73775. x3 = *--stackPos;
  73776. y3 = *--stackPos;
  73777. x4 = *--stackPos;
  73778. y4 = *--stackPos;
  73779. }
  73780. }
  73781. }
  73782. if (type == Path::lineMarker)
  73783. {
  73784. ++subPathIndex;
  73785. closesSubPath = (stackPos == stackBase)
  73786. && (index < path.numElements)
  73787. && (points [index] == Path::closeSubPathMarker)
  73788. && x2 == subPathCloseX
  73789. && y2 == subPathCloseY;
  73790. return true;
  73791. }
  73792. else if (type == Path::quadMarker)
  73793. {
  73794. const size_t offset = (size_t) (stackPos - stackBase);
  73795. if (offset >= stackSize - 10)
  73796. {
  73797. stackSize <<= 1;
  73798. stackBase.realloc (stackSize);
  73799. stackPos = stackBase + offset;
  73800. }
  73801. const float dx1 = x1 - x2;
  73802. const float dy1 = y1 - y2;
  73803. const float dx2 = x2 - x3;
  73804. const float dy2 = y2 - y3;
  73805. const float m1x = (x1 + x2) * 0.5f;
  73806. const float m1y = (y1 + y2) * 0.5f;
  73807. const float m2x = (x2 + x3) * 0.5f;
  73808. const float m2y = (y2 + y3) * 0.5f;
  73809. const float m3x = (m1x + m2x) * 0.5f;
  73810. const float m3y = (m1y + m2y) * 0.5f;
  73811. if (dx1*dx1 + dy1*dy1 + dx2*dx2 + dy2*dy2 > tolerence)
  73812. {
  73813. *stackPos++ = y3;
  73814. *stackPos++ = x3;
  73815. *stackPos++ = m2y;
  73816. *stackPos++ = m2x;
  73817. *stackPos++ = Path::quadMarker;
  73818. *stackPos++ = m3y;
  73819. *stackPos++ = m3x;
  73820. *stackPos++ = m1y;
  73821. *stackPos++ = m1x;
  73822. *stackPos++ = Path::quadMarker;
  73823. }
  73824. else
  73825. {
  73826. *stackPos++ = y3;
  73827. *stackPos++ = x3;
  73828. *stackPos++ = Path::lineMarker;
  73829. *stackPos++ = m3y;
  73830. *stackPos++ = m3x;
  73831. *stackPos++ = Path::lineMarker;
  73832. }
  73833. jassert (stackPos < stackBase + stackSize);
  73834. }
  73835. else if (type == Path::cubicMarker)
  73836. {
  73837. const size_t offset = (size_t) (stackPos - stackBase);
  73838. if (offset >= stackSize - 16)
  73839. {
  73840. stackSize <<= 1;
  73841. stackBase.realloc (stackSize);
  73842. stackPos = stackBase + offset;
  73843. }
  73844. const float dx1 = x1 - x2;
  73845. const float dy1 = y1 - y2;
  73846. const float dx2 = x2 - x3;
  73847. const float dy2 = y2 - y3;
  73848. const float dx3 = x3 - x4;
  73849. const float dy3 = y3 - y4;
  73850. const float m1x = (x1 + x2) * 0.5f;
  73851. const float m1y = (y1 + y2) * 0.5f;
  73852. const float m2x = (x3 + x2) * 0.5f;
  73853. const float m2y = (y3 + y2) * 0.5f;
  73854. const float m3x = (x3 + x4) * 0.5f;
  73855. const float m3y = (y3 + y4) * 0.5f;
  73856. const float m4x = (m1x + m2x) * 0.5f;
  73857. const float m4y = (m1y + m2y) * 0.5f;
  73858. const float m5x = (m3x + m2x) * 0.5f;
  73859. const float m5y = (m3y + m2y) * 0.5f;
  73860. if (dx1*dx1 + dy1*dy1 + dx2*dx2
  73861. + dy2*dy2 + dx3*dx3 + dy3*dy3 > tolerence)
  73862. {
  73863. *stackPos++ = y4;
  73864. *stackPos++ = x4;
  73865. *stackPos++ = m3y;
  73866. *stackPos++ = m3x;
  73867. *stackPos++ = m5y;
  73868. *stackPos++ = m5x;
  73869. *stackPos++ = Path::cubicMarker;
  73870. *stackPos++ = (m4y + m5y) * 0.5f;
  73871. *stackPos++ = (m4x + m5x) * 0.5f;
  73872. *stackPos++ = m4y;
  73873. *stackPos++ = m4x;
  73874. *stackPos++ = m1y;
  73875. *stackPos++ = m1x;
  73876. *stackPos++ = Path::cubicMarker;
  73877. }
  73878. else
  73879. {
  73880. *stackPos++ = y4;
  73881. *stackPos++ = x4;
  73882. *stackPos++ = Path::lineMarker;
  73883. *stackPos++ = m5y;
  73884. *stackPos++ = m5x;
  73885. *stackPos++ = Path::lineMarker;
  73886. *stackPos++ = m4y;
  73887. *stackPos++ = m4x;
  73888. *stackPos++ = Path::lineMarker;
  73889. }
  73890. }
  73891. else if (type == Path::closeSubPathMarker)
  73892. {
  73893. if (x2 != subPathCloseX || y2 != subPathCloseY)
  73894. {
  73895. x1 = x2;
  73896. y1 = y2;
  73897. x2 = subPathCloseX;
  73898. y2 = subPathCloseY;
  73899. closesSubPath = true;
  73900. return true;
  73901. }
  73902. }
  73903. else
  73904. {
  73905. jassert (type == Path::moveMarker);
  73906. subPathIndex = -1;
  73907. subPathCloseX = x1 = x2;
  73908. subPathCloseY = y1 = y2;
  73909. }
  73910. }
  73911. }
  73912. #if JUCE_MSVC && JUCE_DEBUG
  73913. #pragma optimize ("", on) // resets optimisations to the project defaults
  73914. #endif
  73915. END_JUCE_NAMESPACE
  73916. /*** End of inlined file: juce_PathIterator.cpp ***/
  73917. /*** Start of inlined file: juce_PathStrokeType.cpp ***/
  73918. BEGIN_JUCE_NAMESPACE
  73919. PathStrokeType::PathStrokeType (const float strokeThickness,
  73920. const JointStyle jointStyle_,
  73921. const EndCapStyle endStyle_) throw()
  73922. : thickness (strokeThickness),
  73923. jointStyle (jointStyle_),
  73924. endStyle (endStyle_)
  73925. {
  73926. }
  73927. PathStrokeType::PathStrokeType (const PathStrokeType& other) throw()
  73928. : thickness (other.thickness),
  73929. jointStyle (other.jointStyle),
  73930. endStyle (other.endStyle)
  73931. {
  73932. }
  73933. PathStrokeType& PathStrokeType::operator= (const PathStrokeType& other) throw()
  73934. {
  73935. thickness = other.thickness;
  73936. jointStyle = other.jointStyle;
  73937. endStyle = other.endStyle;
  73938. return *this;
  73939. }
  73940. PathStrokeType::~PathStrokeType() throw()
  73941. {
  73942. }
  73943. bool PathStrokeType::operator== (const PathStrokeType& other) const throw()
  73944. {
  73945. return thickness == other.thickness
  73946. && jointStyle == other.jointStyle
  73947. && endStyle == other.endStyle;
  73948. }
  73949. bool PathStrokeType::operator!= (const PathStrokeType& other) const throw()
  73950. {
  73951. return ! operator== (other);
  73952. }
  73953. namespace PathStrokeHelpers
  73954. {
  73955. static bool lineIntersection (const float x1, const float y1,
  73956. const float x2, const float y2,
  73957. const float x3, const float y3,
  73958. const float x4, const float y4,
  73959. float& intersectionX,
  73960. float& intersectionY,
  73961. float& distanceBeyondLine1EndSquared) throw()
  73962. {
  73963. if (x2 != x3 || y2 != y3)
  73964. {
  73965. const float dx1 = x2 - x1;
  73966. const float dy1 = y2 - y1;
  73967. const float dx2 = x4 - x3;
  73968. const float dy2 = y4 - y3;
  73969. const float divisor = dx1 * dy2 - dx2 * dy1;
  73970. if (divisor == 0)
  73971. {
  73972. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  73973. {
  73974. if (dy1 == 0 && dy2 != 0)
  73975. {
  73976. const float along = (y1 - y3) / dy2;
  73977. intersectionX = x3 + along * dx2;
  73978. intersectionY = y1;
  73979. distanceBeyondLine1EndSquared = intersectionX - x2;
  73980. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  73981. if ((x2 > x1) == (intersectionX < x2))
  73982. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  73983. return along >= 0 && along <= 1.0f;
  73984. }
  73985. else if (dy2 == 0 && dy1 != 0)
  73986. {
  73987. const float along = (y3 - y1) / dy1;
  73988. intersectionX = x1 + along * dx1;
  73989. intersectionY = y3;
  73990. distanceBeyondLine1EndSquared = (along - 1.0f) * dx1;
  73991. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  73992. if (along < 1.0f)
  73993. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  73994. return along >= 0 && along <= 1.0f;
  73995. }
  73996. else if (dx1 == 0 && dx2 != 0)
  73997. {
  73998. const float along = (x1 - x3) / dx2;
  73999. intersectionX = x1;
  74000. intersectionY = y3 + along * dy2;
  74001. distanceBeyondLine1EndSquared = intersectionY - y2;
  74002. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  74003. if ((y2 > y1) == (intersectionY < y2))
  74004. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  74005. return along >= 0 && along <= 1.0f;
  74006. }
  74007. else if (dx2 == 0 && dx1 != 0)
  74008. {
  74009. const float along = (x3 - x1) / dx1;
  74010. intersectionX = x3;
  74011. intersectionY = y1 + along * dy1;
  74012. distanceBeyondLine1EndSquared = (along - 1.0f) * dy1;
  74013. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  74014. if (along < 1.0f)
  74015. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  74016. return along >= 0 && along <= 1.0f;
  74017. }
  74018. }
  74019. intersectionX = 0.5f * (x2 + x3);
  74020. intersectionY = 0.5f * (y2 + y3);
  74021. distanceBeyondLine1EndSquared = 0.0f;
  74022. return false;
  74023. }
  74024. else
  74025. {
  74026. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  74027. intersectionX = x1 + along1 * dx1;
  74028. intersectionY = y1 + along1 * dy1;
  74029. if (along1 >= 0 && along1 <= 1.0f)
  74030. {
  74031. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1);
  74032. if (along2 >= 0 && along2 <= divisor)
  74033. {
  74034. distanceBeyondLine1EndSquared = 0.0f;
  74035. return true;
  74036. }
  74037. }
  74038. distanceBeyondLine1EndSquared = along1 - 1.0f;
  74039. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  74040. distanceBeyondLine1EndSquared *= (dx1 * dx1 + dy1 * dy1);
  74041. if (along1 < 1.0f)
  74042. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  74043. return false;
  74044. }
  74045. }
  74046. intersectionX = x2;
  74047. intersectionY = y2;
  74048. distanceBeyondLine1EndSquared = 0.0f;
  74049. return true;
  74050. }
  74051. static void addEdgeAndJoint (Path& destPath,
  74052. const PathStrokeType::JointStyle style,
  74053. const float maxMiterExtensionSquared, const float width,
  74054. const float x1, const float y1,
  74055. const float x2, const float y2,
  74056. const float x3, const float y3,
  74057. const float x4, const float y4,
  74058. const float midX, const float midY)
  74059. {
  74060. if (style == PathStrokeType::beveled
  74061. || (x3 == x4 && y3 == y4)
  74062. || (x1 == x2 && y1 == y2))
  74063. {
  74064. destPath.lineTo (x2, y2);
  74065. destPath.lineTo (x3, y3);
  74066. }
  74067. else
  74068. {
  74069. float jx, jy, distanceBeyondLine1EndSquared;
  74070. // if they intersect, use this point..
  74071. if (lineIntersection (x1, y1, x2, y2,
  74072. x3, y3, x4, y4,
  74073. jx, jy, distanceBeyondLine1EndSquared))
  74074. {
  74075. destPath.lineTo (jx, jy);
  74076. }
  74077. else
  74078. {
  74079. if (style == PathStrokeType::mitered)
  74080. {
  74081. if (distanceBeyondLine1EndSquared < maxMiterExtensionSquared
  74082. && distanceBeyondLine1EndSquared > 0.0f)
  74083. {
  74084. destPath.lineTo (jx, jy);
  74085. }
  74086. else
  74087. {
  74088. // the end sticks out too far, so just use a blunt joint
  74089. destPath.lineTo (x2, y2);
  74090. destPath.lineTo (x3, y3);
  74091. }
  74092. }
  74093. else
  74094. {
  74095. // curved joints
  74096. float angle1 = std::atan2 (x2 - midX, y2 - midY);
  74097. float angle2 = std::atan2 (x3 - midX, y3 - midY);
  74098. const float angleIncrement = 0.1f;
  74099. destPath.lineTo (x2, y2);
  74100. if (std::abs (angle1 - angle2) > angleIncrement)
  74101. {
  74102. if (angle2 > angle1 + float_Pi
  74103. || (angle2 < angle1 && angle2 >= angle1 - float_Pi))
  74104. {
  74105. if (angle2 > angle1)
  74106. angle2 -= float_Pi * 2.0f;
  74107. jassert (angle1 <= angle2 + float_Pi);
  74108. angle1 -= angleIncrement;
  74109. while (angle1 > angle2)
  74110. {
  74111. destPath.lineTo (midX + width * std::sin (angle1),
  74112. midY + width * std::cos (angle1));
  74113. angle1 -= angleIncrement;
  74114. }
  74115. }
  74116. else
  74117. {
  74118. if (angle1 > angle2)
  74119. angle1 -= float_Pi * 2.0f;
  74120. jassert (angle1 >= angle2 - float_Pi);
  74121. angle1 += angleIncrement;
  74122. while (angle1 < angle2)
  74123. {
  74124. destPath.lineTo (midX + width * std::sin (angle1),
  74125. midY + width * std::cos (angle1));
  74126. angle1 += angleIncrement;
  74127. }
  74128. }
  74129. }
  74130. destPath.lineTo (x3, y3);
  74131. }
  74132. }
  74133. }
  74134. }
  74135. static void addLineEnd (Path& destPath,
  74136. const PathStrokeType::EndCapStyle style,
  74137. const float x1, const float y1,
  74138. const float x2, const float y2,
  74139. const float width)
  74140. {
  74141. if (style == PathStrokeType::butt)
  74142. {
  74143. destPath.lineTo (x2, y2);
  74144. }
  74145. else
  74146. {
  74147. float offx1, offy1, offx2, offy2;
  74148. float dx = x2 - x1;
  74149. float dy = y2 - y1;
  74150. const float len = juce_hypotf (dx, dy);
  74151. if (len == 0)
  74152. {
  74153. offx1 = offx2 = x1;
  74154. offy1 = offy2 = y1;
  74155. }
  74156. else
  74157. {
  74158. const float offset = width / len;
  74159. dx *= offset;
  74160. dy *= offset;
  74161. offx1 = x1 + dy;
  74162. offy1 = y1 - dx;
  74163. offx2 = x2 + dy;
  74164. offy2 = y2 - dx;
  74165. }
  74166. if (style == PathStrokeType::square)
  74167. {
  74168. // sqaure ends
  74169. destPath.lineTo (offx1, offy1);
  74170. destPath.lineTo (offx2, offy2);
  74171. destPath.lineTo (x2, y2);
  74172. }
  74173. else
  74174. {
  74175. // rounded ends
  74176. const float midx = (offx1 + offx2) * 0.5f;
  74177. const float midy = (offy1 + offy2) * 0.5f;
  74178. destPath.cubicTo (x1 + (offx1 - x1) * 0.55f, y1 + (offy1 - y1) * 0.55f,
  74179. offx1 + (midx - offx1) * 0.45f, offy1 + (midy - offy1) * 0.45f,
  74180. midx, midy);
  74181. destPath.cubicTo (midx + (offx2 - midx) * 0.55f, midy + (offy2 - midy) * 0.55f,
  74182. offx2 + (x2 - offx2) * 0.45f, offy2 + (y2 - offy2) * 0.45f,
  74183. x2, y2);
  74184. }
  74185. }
  74186. }
  74187. struct Arrowhead
  74188. {
  74189. float startWidth, startLength;
  74190. float endWidth, endLength;
  74191. };
  74192. static void addArrowhead (Path& destPath,
  74193. const float x1, const float y1,
  74194. const float x2, const float y2,
  74195. const float tipX, const float tipY,
  74196. const float width,
  74197. const float arrowheadWidth)
  74198. {
  74199. Line<float> line (x1, y1, x2, y2);
  74200. destPath.lineTo (line.getPointAlongLine (-(arrowheadWidth / 2.0f - width), 0));
  74201. destPath.lineTo (tipX, tipY);
  74202. destPath.lineTo (line.getPointAlongLine (arrowheadWidth - (arrowheadWidth / 2.0f - width), 0));
  74203. destPath.lineTo (x2, y2);
  74204. }
  74205. struct LineSection
  74206. {
  74207. float x1, y1, x2, y2; // original line
  74208. float lx1, ly1, lx2, ly2; // the left-hand stroke
  74209. float rx1, ry1, rx2, ry2; // the right-hand stroke
  74210. };
  74211. static void shortenSubPath (Array<LineSection>& subPath, float amountAtStart, float amountAtEnd)
  74212. {
  74213. while (amountAtEnd > 0 && subPath.size() > 0)
  74214. {
  74215. LineSection& l = subPath.getReference (subPath.size() - 1);
  74216. float dx = l.rx2 - l.rx1;
  74217. float dy = l.ry2 - l.ry1;
  74218. const float len = juce_hypotf (dx, dy);
  74219. if (len <= amountAtEnd && subPath.size() > 1)
  74220. {
  74221. LineSection& prev = subPath.getReference (subPath.size() - 2);
  74222. prev.x2 = l.x2;
  74223. prev.y2 = l.y2;
  74224. subPath.removeLast();
  74225. amountAtEnd -= len;
  74226. }
  74227. else
  74228. {
  74229. const float prop = jmin (0.9999f, amountAtEnd / len);
  74230. dx *= prop;
  74231. dy *= prop;
  74232. l.rx1 += dx;
  74233. l.ry1 += dy;
  74234. l.lx2 += dx;
  74235. l.ly2 += dy;
  74236. break;
  74237. }
  74238. }
  74239. while (amountAtStart > 0 && subPath.size() > 0)
  74240. {
  74241. LineSection& l = subPath.getReference (0);
  74242. float dx = l.rx2 - l.rx1;
  74243. float dy = l.ry2 - l.ry1;
  74244. const float len = juce_hypotf (dx, dy);
  74245. if (len <= amountAtStart && subPath.size() > 1)
  74246. {
  74247. LineSection& next = subPath.getReference (1);
  74248. next.x1 = l.x1;
  74249. next.y1 = l.y1;
  74250. subPath.remove (0);
  74251. amountAtStart -= len;
  74252. }
  74253. else
  74254. {
  74255. const float prop = jmin (0.9999f, amountAtStart / len);
  74256. dx *= prop;
  74257. dy *= prop;
  74258. l.rx2 -= dx;
  74259. l.ry2 -= dy;
  74260. l.lx1 -= dx;
  74261. l.ly1 -= dy;
  74262. break;
  74263. }
  74264. }
  74265. }
  74266. static void addSubPath (Path& destPath, Array<LineSection>& subPath,
  74267. const bool isClosed, const float width, const float maxMiterExtensionSquared,
  74268. const PathStrokeType::JointStyle jointStyle, const PathStrokeType::EndCapStyle endStyle,
  74269. const Arrowhead* const arrowhead)
  74270. {
  74271. jassert (subPath.size() > 0);
  74272. if (arrowhead != 0)
  74273. shortenSubPath (subPath, arrowhead->startLength, arrowhead->endLength);
  74274. const LineSection& firstLine = subPath.getReference (0);
  74275. float lastX1 = firstLine.lx1;
  74276. float lastY1 = firstLine.ly1;
  74277. float lastX2 = firstLine.lx2;
  74278. float lastY2 = firstLine.ly2;
  74279. if (isClosed)
  74280. {
  74281. destPath.startNewSubPath (lastX1, lastY1);
  74282. }
  74283. else
  74284. {
  74285. destPath.startNewSubPath (firstLine.rx2, firstLine.ry2);
  74286. if (arrowhead != 0)
  74287. addArrowhead (destPath, firstLine.rx2, firstLine.ry2, lastX1, lastY1, firstLine.x1, firstLine.y1,
  74288. width, arrowhead->startWidth);
  74289. else
  74290. addLineEnd (destPath, endStyle, firstLine.rx2, firstLine.ry2, lastX1, lastY1, width);
  74291. }
  74292. int i;
  74293. for (i = 1; i < subPath.size(); ++i)
  74294. {
  74295. const LineSection& l = subPath.getReference (i);
  74296. addEdgeAndJoint (destPath, jointStyle,
  74297. maxMiterExtensionSquared, width,
  74298. lastX1, lastY1, lastX2, lastY2,
  74299. l.lx1, l.ly1, l.lx2, l.ly2,
  74300. l.x1, l.y1);
  74301. lastX1 = l.lx1;
  74302. lastY1 = l.ly1;
  74303. lastX2 = l.lx2;
  74304. lastY2 = l.ly2;
  74305. }
  74306. const LineSection& lastLine = subPath.getReference (subPath.size() - 1);
  74307. if (isClosed)
  74308. {
  74309. const LineSection& l = subPath.getReference (0);
  74310. addEdgeAndJoint (destPath, jointStyle,
  74311. maxMiterExtensionSquared, width,
  74312. lastX1, lastY1, lastX2, lastY2,
  74313. l.lx1, l.ly1, l.lx2, l.ly2,
  74314. l.x1, l.y1);
  74315. destPath.closeSubPath();
  74316. destPath.startNewSubPath (lastLine.rx1, lastLine.ry1);
  74317. }
  74318. else
  74319. {
  74320. destPath.lineTo (lastX2, lastY2);
  74321. if (arrowhead != 0)
  74322. addArrowhead (destPath, lastX2, lastY2, lastLine.rx1, lastLine.ry1, lastLine.x2, lastLine.y2,
  74323. width, arrowhead->endWidth);
  74324. else
  74325. addLineEnd (destPath, endStyle, lastX2, lastY2, lastLine.rx1, lastLine.ry1, width);
  74326. }
  74327. lastX1 = lastLine.rx1;
  74328. lastY1 = lastLine.ry1;
  74329. lastX2 = lastLine.rx2;
  74330. lastY2 = lastLine.ry2;
  74331. for (i = subPath.size() - 1; --i >= 0;)
  74332. {
  74333. const LineSection& l = subPath.getReference (i);
  74334. addEdgeAndJoint (destPath, jointStyle,
  74335. maxMiterExtensionSquared, width,
  74336. lastX1, lastY1, lastX2, lastY2,
  74337. l.rx1, l.ry1, l.rx2, l.ry2,
  74338. l.x2, l.y2);
  74339. lastX1 = l.rx1;
  74340. lastY1 = l.ry1;
  74341. lastX2 = l.rx2;
  74342. lastY2 = l.ry2;
  74343. }
  74344. if (isClosed)
  74345. {
  74346. addEdgeAndJoint (destPath, jointStyle,
  74347. maxMiterExtensionSquared, width,
  74348. lastX1, lastY1, lastX2, lastY2,
  74349. lastLine.rx1, lastLine.ry1, lastLine.rx2, lastLine.ry2,
  74350. lastLine.x2, lastLine.y2);
  74351. }
  74352. else
  74353. {
  74354. // do the last line
  74355. destPath.lineTo (lastX2, lastY2);
  74356. }
  74357. destPath.closeSubPath();
  74358. }
  74359. static void createStroke (const float thickness, const PathStrokeType::JointStyle jointStyle,
  74360. const PathStrokeType::EndCapStyle endStyle,
  74361. Path& destPath, const Path& source,
  74362. const AffineTransform& transform,
  74363. const float extraAccuracy, const Arrowhead* const arrowhead)
  74364. {
  74365. if (thickness <= 0)
  74366. {
  74367. destPath.clear();
  74368. return;
  74369. }
  74370. const Path* sourcePath = &source;
  74371. Path temp;
  74372. if (sourcePath == &destPath)
  74373. {
  74374. destPath.swapWithPath (temp);
  74375. sourcePath = &temp;
  74376. }
  74377. else
  74378. {
  74379. destPath.clear();
  74380. }
  74381. destPath.setUsingNonZeroWinding (true);
  74382. const float maxMiterExtensionSquared = 9.0f * thickness * thickness;
  74383. const float width = 0.5f * thickness;
  74384. // Iterate the path, creating a list of the
  74385. // left/right-hand lines along either side of it...
  74386. PathFlatteningIterator it (*sourcePath, transform, 9.0f / extraAccuracy);
  74387. Array <LineSection> subPath;
  74388. subPath.ensureStorageAllocated (512);
  74389. LineSection l;
  74390. l.x1 = 0;
  74391. l.y1 = 0;
  74392. const float minSegmentLength = 2.0f / (extraAccuracy * extraAccuracy);
  74393. while (it.next())
  74394. {
  74395. if (it.subPathIndex == 0)
  74396. {
  74397. if (subPath.size() > 0)
  74398. {
  74399. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  74400. subPath.clearQuick();
  74401. }
  74402. l.x1 = it.x1;
  74403. l.y1 = it.y1;
  74404. }
  74405. l.x2 = it.x2;
  74406. l.y2 = it.y2;
  74407. float dx = l.x2 - l.x1;
  74408. float dy = l.y2 - l.y1;
  74409. const float hypotSquared = dx*dx + dy*dy;
  74410. if (it.closesSubPath || hypotSquared > minSegmentLength || it.isLastInSubpath())
  74411. {
  74412. const float len = std::sqrt (hypotSquared);
  74413. if (len == 0)
  74414. {
  74415. l.rx1 = l.rx2 = l.lx1 = l.lx2 = l.x1;
  74416. l.ry1 = l.ry2 = l.ly1 = l.ly2 = l.y1;
  74417. }
  74418. else
  74419. {
  74420. const float offset = width / len;
  74421. dx *= offset;
  74422. dy *= offset;
  74423. l.rx2 = l.x1 - dy;
  74424. l.ry2 = l.y1 + dx;
  74425. l.lx1 = l.x1 + dy;
  74426. l.ly1 = l.y1 - dx;
  74427. l.lx2 = l.x2 + dy;
  74428. l.ly2 = l.y2 - dx;
  74429. l.rx1 = l.x2 - dy;
  74430. l.ry1 = l.y2 + dx;
  74431. }
  74432. subPath.add (l);
  74433. if (it.closesSubPath)
  74434. {
  74435. addSubPath (destPath, subPath, true, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  74436. subPath.clearQuick();
  74437. }
  74438. else
  74439. {
  74440. l.x1 = it.x2;
  74441. l.y1 = it.y2;
  74442. }
  74443. }
  74444. }
  74445. if (subPath.size() > 0)
  74446. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  74447. }
  74448. }
  74449. void PathStrokeType::createStrokedPath (Path& destPath, const Path& sourcePath,
  74450. const AffineTransform& transform, const float extraAccuracy) const
  74451. {
  74452. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle, destPath, sourcePath,
  74453. transform, extraAccuracy, 0);
  74454. }
  74455. void PathStrokeType::createDashedStroke (Path& destPath,
  74456. const Path& sourcePath,
  74457. const float* dashLengths,
  74458. int numDashLengths,
  74459. const AffineTransform& transform,
  74460. const float extraAccuracy) const
  74461. {
  74462. if (thickness <= 0)
  74463. return;
  74464. // this should really be an even number..
  74465. jassert ((numDashLengths & 1) == 0);
  74466. Path newDestPath;
  74467. PathFlatteningIterator it (sourcePath, transform, 9.0f / extraAccuracy);
  74468. bool first = true;
  74469. int dashNum = 0;
  74470. float pos = 0.0f, lineLen = 0.0f, lineEndPos = 0.0f;
  74471. float dx = 0.0f, dy = 0.0f;
  74472. for (;;)
  74473. {
  74474. const bool isSolid = ((dashNum & 1) == 0);
  74475. const float dashLen = dashLengths [dashNum++ % numDashLengths];
  74476. jassert (dashLen > 0); // must be a positive increment!
  74477. if (dashLen <= 0)
  74478. break;
  74479. pos += dashLen;
  74480. while (pos > lineEndPos)
  74481. {
  74482. if (! it.next())
  74483. {
  74484. if (isSolid && ! first)
  74485. newDestPath.lineTo (it.x2, it.y2);
  74486. createStrokedPath (destPath, newDestPath, AffineTransform::identity, extraAccuracy);
  74487. return;
  74488. }
  74489. if (isSolid && ! first)
  74490. newDestPath.lineTo (it.x1, it.y1);
  74491. else
  74492. newDestPath.startNewSubPath (it.x1, it.y1);
  74493. dx = it.x2 - it.x1;
  74494. dy = it.y2 - it.y1;
  74495. lineLen = juce_hypotf (dx, dy);
  74496. lineEndPos += lineLen;
  74497. first = it.closesSubPath;
  74498. }
  74499. const float alpha = (pos - (lineEndPos - lineLen)) / lineLen;
  74500. if (isSolid)
  74501. newDestPath.lineTo (it.x1 + dx * alpha,
  74502. it.y1 + dy * alpha);
  74503. else
  74504. newDestPath.startNewSubPath (it.x1 + dx * alpha,
  74505. it.y1 + dy * alpha);
  74506. }
  74507. }
  74508. void PathStrokeType::createStrokeWithArrowheads (Path& destPath,
  74509. const Path& sourcePath,
  74510. const float arrowheadStartWidth, const float arrowheadStartLength,
  74511. const float arrowheadEndWidth, const float arrowheadEndLength,
  74512. const AffineTransform& transform,
  74513. const float extraAccuracy) const
  74514. {
  74515. PathStrokeHelpers::Arrowhead head;
  74516. head.startWidth = arrowheadStartWidth;
  74517. head.startLength = arrowheadStartLength;
  74518. head.endWidth = arrowheadEndWidth;
  74519. head.endLength = arrowheadEndLength;
  74520. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle,
  74521. destPath, sourcePath, transform, extraAccuracy, &head);
  74522. }
  74523. END_JUCE_NAMESPACE
  74524. /*** End of inlined file: juce_PathStrokeType.cpp ***/
  74525. /*** Start of inlined file: juce_PositionedRectangle.cpp ***/
  74526. BEGIN_JUCE_NAMESPACE
  74527. PositionedRectangle::PositionedRectangle() throw()
  74528. : x (0.0),
  74529. y (0.0),
  74530. w (0.0),
  74531. h (0.0),
  74532. xMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  74533. yMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  74534. wMode (absoluteSize),
  74535. hMode (absoluteSize)
  74536. {
  74537. }
  74538. PositionedRectangle::PositionedRectangle (const PositionedRectangle& other) throw()
  74539. : x (other.x),
  74540. y (other.y),
  74541. w (other.w),
  74542. h (other.h),
  74543. xMode (other.xMode),
  74544. yMode (other.yMode),
  74545. wMode (other.wMode),
  74546. hMode (other.hMode)
  74547. {
  74548. }
  74549. PositionedRectangle& PositionedRectangle::operator= (const PositionedRectangle& other) throw()
  74550. {
  74551. x = other.x;
  74552. y = other.y;
  74553. w = other.w;
  74554. h = other.h;
  74555. xMode = other.xMode;
  74556. yMode = other.yMode;
  74557. wMode = other.wMode;
  74558. hMode = other.hMode;
  74559. return *this;
  74560. }
  74561. PositionedRectangle::~PositionedRectangle() throw()
  74562. {
  74563. }
  74564. bool PositionedRectangle::operator== (const PositionedRectangle& other) const throw()
  74565. {
  74566. return x == other.x
  74567. && y == other.y
  74568. && w == other.w
  74569. && h == other.h
  74570. && xMode == other.xMode
  74571. && yMode == other.yMode
  74572. && wMode == other.wMode
  74573. && hMode == other.hMode;
  74574. }
  74575. bool PositionedRectangle::operator!= (const PositionedRectangle& other) const throw()
  74576. {
  74577. return ! operator== (other);
  74578. }
  74579. PositionedRectangle::PositionedRectangle (const String& stringVersion) throw()
  74580. {
  74581. StringArray tokens;
  74582. tokens.addTokens (stringVersion, false);
  74583. decodePosString (tokens [0], xMode, x);
  74584. decodePosString (tokens [1], yMode, y);
  74585. decodeSizeString (tokens [2], wMode, w);
  74586. decodeSizeString (tokens [3], hMode, h);
  74587. }
  74588. const String PositionedRectangle::toString() const throw()
  74589. {
  74590. String s;
  74591. s.preallocateStorage (12);
  74592. addPosDescription (s, xMode, x);
  74593. s << ' ';
  74594. addPosDescription (s, yMode, y);
  74595. s << ' ';
  74596. addSizeDescription (s, wMode, w);
  74597. s << ' ';
  74598. addSizeDescription (s, hMode, h);
  74599. return s;
  74600. }
  74601. const Rectangle<int> PositionedRectangle::getRectangle (const Rectangle<int>& target) const throw()
  74602. {
  74603. jassert (! target.isEmpty());
  74604. double x_, y_, w_, h_;
  74605. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  74606. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  74607. return Rectangle<int> (roundToInt (x_), roundToInt (y_),
  74608. roundToInt (w_), roundToInt (h_));
  74609. }
  74610. void PositionedRectangle::getRectangleDouble (const Rectangle<int>& target,
  74611. double& x_, double& y_,
  74612. double& w_, double& h_) const throw()
  74613. {
  74614. jassert (! target.isEmpty());
  74615. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  74616. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  74617. }
  74618. void PositionedRectangle::applyToComponent (Component& comp) const throw()
  74619. {
  74620. comp.setBounds (getRectangle (Rectangle<int> (0, 0, comp.getParentWidth(), comp.getParentHeight())));
  74621. }
  74622. void PositionedRectangle::updateFrom (const Rectangle<int>& rectangle,
  74623. const Rectangle<int>& target) throw()
  74624. {
  74625. updatePosAndSize (x, w, rectangle.getX(), rectangle.getWidth(), xMode, wMode, target.getX(), target.getWidth());
  74626. updatePosAndSize (y, h, rectangle.getY(), rectangle.getHeight(), yMode, hMode, target.getY(), target.getHeight());
  74627. }
  74628. void PositionedRectangle::updateFromDouble (const double newX, const double newY,
  74629. const double newW, const double newH,
  74630. const Rectangle<int>& target) throw()
  74631. {
  74632. updatePosAndSize (x, w, newX, newW, xMode, wMode, target.getX(), target.getWidth());
  74633. updatePosAndSize (y, h, newY, newH, yMode, hMode, target.getY(), target.getHeight());
  74634. }
  74635. void PositionedRectangle::updateFromComponent (const Component& comp) throw()
  74636. {
  74637. if (comp.getParentComponent() == 0 && ! comp.isOnDesktop())
  74638. updateFrom (comp.getBounds(), Rectangle<int>());
  74639. else
  74640. updateFrom (comp.getBounds(), Rectangle<int> (0, 0, comp.getParentWidth(), comp.getParentHeight()));
  74641. }
  74642. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointX() const throw()
  74643. {
  74644. return (AnchorPoint) (xMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  74645. }
  74646. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeX() const throw()
  74647. {
  74648. return (PositionMode) (xMode & (absoluteFromParentTopLeft
  74649. | absoluteFromParentBottomRight
  74650. | absoluteFromParentCentre
  74651. | proportionOfParentSize));
  74652. }
  74653. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointY() const throw()
  74654. {
  74655. return (AnchorPoint) (yMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  74656. }
  74657. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeY() const throw()
  74658. {
  74659. return (PositionMode) (yMode & (absoluteFromParentTopLeft
  74660. | absoluteFromParentBottomRight
  74661. | absoluteFromParentCentre
  74662. | proportionOfParentSize));
  74663. }
  74664. PositionedRectangle::SizeMode PositionedRectangle::getWidthMode() const throw()
  74665. {
  74666. return (SizeMode) wMode;
  74667. }
  74668. PositionedRectangle::SizeMode PositionedRectangle::getHeightMode() const throw()
  74669. {
  74670. return (SizeMode) hMode;
  74671. }
  74672. void PositionedRectangle::setModes (const AnchorPoint xAnchor,
  74673. const PositionMode xMode_,
  74674. const AnchorPoint yAnchor,
  74675. const PositionMode yMode_,
  74676. const SizeMode widthMode,
  74677. const SizeMode heightMode,
  74678. const Rectangle<int>& target) throw()
  74679. {
  74680. if (xMode != (xAnchor | xMode_) || wMode != widthMode)
  74681. {
  74682. double tx, tw;
  74683. applyPosAndSize (tx, tw, x, w, xMode, wMode, target.getX(), target.getWidth());
  74684. xMode = (uint8) (xAnchor | xMode_);
  74685. wMode = (uint8) widthMode;
  74686. updatePosAndSize (x, w, tx, tw, xMode, wMode, target.getX(), target.getWidth());
  74687. }
  74688. if (yMode != (yAnchor | yMode_) || hMode != heightMode)
  74689. {
  74690. double ty, th;
  74691. applyPosAndSize (ty, th, y, h, yMode, hMode, target.getY(), target.getHeight());
  74692. yMode = (uint8) (yAnchor | yMode_);
  74693. hMode = (uint8) heightMode;
  74694. updatePosAndSize (y, h, ty, th, yMode, hMode, target.getY(), target.getHeight());
  74695. }
  74696. }
  74697. bool PositionedRectangle::isPositionAbsolute() const throw()
  74698. {
  74699. return xMode == absoluteFromParentTopLeft
  74700. && yMode == absoluteFromParentTopLeft
  74701. && wMode == absoluteSize
  74702. && hMode == absoluteSize;
  74703. }
  74704. void PositionedRectangle::addPosDescription (String& s, const uint8 mode, const double value) const throw()
  74705. {
  74706. if ((mode & proportionOfParentSize) != 0)
  74707. {
  74708. s << (roundToInt (value * 100000.0) / 1000.0) << '%';
  74709. }
  74710. else
  74711. {
  74712. s << (roundToInt (value * 100.0) / 100.0);
  74713. if ((mode & absoluteFromParentBottomRight) != 0)
  74714. s << 'R';
  74715. else if ((mode & absoluteFromParentCentre) != 0)
  74716. s << 'C';
  74717. }
  74718. if ((mode & anchorAtRightOrBottom) != 0)
  74719. s << 'r';
  74720. else if ((mode & anchorAtCentre) != 0)
  74721. s << 'c';
  74722. }
  74723. void PositionedRectangle::addSizeDescription (String& s, const uint8 mode, const double value) const throw()
  74724. {
  74725. if (mode == proportionalSize)
  74726. s << (roundToInt (value * 100000.0) / 1000.0) << '%';
  74727. else if (mode == parentSizeMinusAbsolute)
  74728. s << (roundToInt (value * 100.0) / 100.0) << 'M';
  74729. else
  74730. s << (roundToInt (value * 100.0) / 100.0);
  74731. }
  74732. void PositionedRectangle::decodePosString (const String& s, uint8& mode, double& value) throw()
  74733. {
  74734. if (s.containsChar ('r'))
  74735. mode = anchorAtRightOrBottom;
  74736. else if (s.containsChar ('c'))
  74737. mode = anchorAtCentre;
  74738. else
  74739. mode = anchorAtLeftOrTop;
  74740. if (s.containsChar ('%'))
  74741. {
  74742. mode |= proportionOfParentSize;
  74743. value = s.removeCharacters ("%rcRC").getDoubleValue() / 100.0;
  74744. }
  74745. else
  74746. {
  74747. if (s.containsChar ('R'))
  74748. mode |= absoluteFromParentBottomRight;
  74749. else if (s.containsChar ('C'))
  74750. mode |= absoluteFromParentCentre;
  74751. else
  74752. mode |= absoluteFromParentTopLeft;
  74753. value = s.removeCharacters ("rcRC").getDoubleValue();
  74754. }
  74755. }
  74756. void PositionedRectangle::decodeSizeString (const String& s, uint8& mode, double& value) throw()
  74757. {
  74758. if (s.containsChar ('%'))
  74759. {
  74760. mode = proportionalSize;
  74761. value = s.upToFirstOccurrenceOf ("%", false, false).getDoubleValue() / 100.0;
  74762. }
  74763. else if (s.containsChar ('M'))
  74764. {
  74765. mode = parentSizeMinusAbsolute;
  74766. value = s.getDoubleValue();
  74767. }
  74768. else
  74769. {
  74770. mode = absoluteSize;
  74771. value = s.getDoubleValue();
  74772. }
  74773. }
  74774. void PositionedRectangle::applyPosAndSize (double& xOut, double& wOut,
  74775. const double x_, const double w_,
  74776. const uint8 xMode_, const uint8 wMode_,
  74777. const int parentPos,
  74778. const int parentSize) const throw()
  74779. {
  74780. if (wMode_ == proportionalSize)
  74781. wOut = roundToInt (w_ * parentSize);
  74782. else if (wMode_ == parentSizeMinusAbsolute)
  74783. wOut = jmax (0, parentSize - roundToInt (w_));
  74784. else
  74785. wOut = roundToInt (w_);
  74786. if ((xMode_ & proportionOfParentSize) != 0)
  74787. xOut = parentPos + x_ * parentSize;
  74788. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  74789. xOut = (parentPos + parentSize) - x_;
  74790. else if ((xMode_ & absoluteFromParentCentre) != 0)
  74791. xOut = x_ + (parentPos + parentSize / 2);
  74792. else
  74793. xOut = x_ + parentPos;
  74794. if ((xMode_ & anchorAtRightOrBottom) != 0)
  74795. xOut -= wOut;
  74796. else if ((xMode_ & anchorAtCentre) != 0)
  74797. xOut -= wOut / 2;
  74798. }
  74799. void PositionedRectangle::updatePosAndSize (double& xOut, double& wOut,
  74800. double x_, const double w_,
  74801. const uint8 xMode_, const uint8 wMode_,
  74802. const int parentPos,
  74803. const int parentSize) const throw()
  74804. {
  74805. if (wMode_ == proportionalSize)
  74806. {
  74807. if (parentSize > 0)
  74808. wOut = w_ / parentSize;
  74809. }
  74810. else if (wMode_ == parentSizeMinusAbsolute)
  74811. wOut = parentSize - w_;
  74812. else
  74813. wOut = w_;
  74814. if ((xMode_ & anchorAtRightOrBottom) != 0)
  74815. x_ += w_;
  74816. else if ((xMode_ & anchorAtCentre) != 0)
  74817. x_ += w_ / 2;
  74818. if ((xMode_ & proportionOfParentSize) != 0)
  74819. {
  74820. if (parentSize > 0)
  74821. xOut = (x_ - parentPos) / parentSize;
  74822. }
  74823. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  74824. xOut = (parentPos + parentSize) - x_;
  74825. else if ((xMode_ & absoluteFromParentCentre) != 0)
  74826. xOut = x_ - (parentPos + parentSize / 2);
  74827. else
  74828. xOut = x_ - parentPos;
  74829. }
  74830. END_JUCE_NAMESPACE
  74831. /*** End of inlined file: juce_PositionedRectangle.cpp ***/
  74832. /*** Start of inlined file: juce_RectangleList.cpp ***/
  74833. BEGIN_JUCE_NAMESPACE
  74834. RectangleList::RectangleList() throw()
  74835. {
  74836. }
  74837. RectangleList::RectangleList (const Rectangle<int>& rect)
  74838. {
  74839. if (! rect.isEmpty())
  74840. rects.add (rect);
  74841. }
  74842. RectangleList::RectangleList (const RectangleList& other)
  74843. : rects (other.rects)
  74844. {
  74845. }
  74846. RectangleList& RectangleList::operator= (const RectangleList& other)
  74847. {
  74848. rects = other.rects;
  74849. return *this;
  74850. }
  74851. RectangleList::~RectangleList()
  74852. {
  74853. }
  74854. void RectangleList::clear()
  74855. {
  74856. rects.clearQuick();
  74857. }
  74858. const Rectangle<int> RectangleList::getRectangle (const int index) const throw()
  74859. {
  74860. if (((unsigned int) index) < (unsigned int) rects.size())
  74861. return rects.getReference (index);
  74862. return Rectangle<int>();
  74863. }
  74864. bool RectangleList::isEmpty() const throw()
  74865. {
  74866. return rects.size() == 0;
  74867. }
  74868. RectangleList::Iterator::Iterator (const RectangleList& list) throw()
  74869. : current (0),
  74870. owner (list),
  74871. index (list.rects.size())
  74872. {
  74873. }
  74874. RectangleList::Iterator::~Iterator()
  74875. {
  74876. }
  74877. bool RectangleList::Iterator::next() throw()
  74878. {
  74879. if (--index >= 0)
  74880. {
  74881. current = & (owner.rects.getReference (index));
  74882. return true;
  74883. }
  74884. return false;
  74885. }
  74886. void RectangleList::add (const Rectangle<int>& rect)
  74887. {
  74888. if (! rect.isEmpty())
  74889. {
  74890. if (rects.size() == 0)
  74891. {
  74892. rects.add (rect);
  74893. }
  74894. else
  74895. {
  74896. bool anyOverlaps = false;
  74897. int i;
  74898. for (i = rects.size(); --i >= 0;)
  74899. {
  74900. Rectangle<int>& ourRect = rects.getReference (i);
  74901. if (rect.intersects (ourRect))
  74902. {
  74903. if (rect.contains (ourRect))
  74904. rects.remove (i);
  74905. else if (! ourRect.reduceIfPartlyContainedIn (rect))
  74906. anyOverlaps = true;
  74907. }
  74908. }
  74909. if (anyOverlaps && rects.size() > 0)
  74910. {
  74911. RectangleList r (rect);
  74912. for (i = rects.size(); --i >= 0;)
  74913. {
  74914. const Rectangle<int>& ourRect = rects.getReference (i);
  74915. if (rect.intersects (ourRect))
  74916. {
  74917. r.subtract (ourRect);
  74918. if (r.rects.size() == 0)
  74919. return;
  74920. }
  74921. }
  74922. for (i = r.getNumRectangles(); --i >= 0;)
  74923. rects.add (r.rects.getReference (i));
  74924. }
  74925. else
  74926. {
  74927. rects.add (rect);
  74928. }
  74929. }
  74930. }
  74931. }
  74932. void RectangleList::addWithoutMerging (const Rectangle<int>& rect)
  74933. {
  74934. if (! rect.isEmpty())
  74935. rects.add (rect);
  74936. }
  74937. void RectangleList::add (const int x, const int y, const int w, const int h)
  74938. {
  74939. if (rects.size() == 0)
  74940. {
  74941. if (w > 0 && h > 0)
  74942. rects.add (Rectangle<int> (x, y, w, h));
  74943. }
  74944. else
  74945. {
  74946. add (Rectangle<int> (x, y, w, h));
  74947. }
  74948. }
  74949. void RectangleList::add (const RectangleList& other)
  74950. {
  74951. for (int i = 0; i < other.rects.size(); ++i)
  74952. add (other.rects.getReference (i));
  74953. }
  74954. void RectangleList::subtract (const Rectangle<int>& rect)
  74955. {
  74956. const int originalNumRects = rects.size();
  74957. if (originalNumRects > 0)
  74958. {
  74959. const int x1 = rect.x;
  74960. const int y1 = rect.y;
  74961. const int x2 = x1 + rect.w;
  74962. const int y2 = y1 + rect.h;
  74963. for (int i = getNumRectangles(); --i >= 0;)
  74964. {
  74965. Rectangle<int>& r = rects.getReference (i);
  74966. const int rx1 = r.x;
  74967. const int ry1 = r.y;
  74968. const int rx2 = rx1 + r.w;
  74969. const int ry2 = ry1 + r.h;
  74970. if (! (x2 <= rx1 || x1 >= rx2 || y2 <= ry1 || y1 >= ry2))
  74971. {
  74972. if (x1 > rx1 && x1 < rx2)
  74973. {
  74974. if (y1 <= ry1 && y2 >= ry2 && x2 >= rx2)
  74975. {
  74976. r.w = x1 - rx1;
  74977. }
  74978. else
  74979. {
  74980. r.x = x1;
  74981. r.w = rx2 - x1;
  74982. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x1 - rx1, ry2 - ry1));
  74983. i += 2;
  74984. }
  74985. }
  74986. else if (x2 > rx1 && x2 < rx2)
  74987. {
  74988. r.x = x2;
  74989. r.w = rx2 - x2;
  74990. if (y1 > ry1 || y2 < ry2 || x1 > rx1)
  74991. {
  74992. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x2 - rx1, ry2 - ry1));
  74993. i += 2;
  74994. }
  74995. }
  74996. else if (y1 > ry1 && y1 < ry2)
  74997. {
  74998. if (x1 <= rx1 && x2 >= rx2 && y2 >= ry2)
  74999. {
  75000. r.h = y1 - ry1;
  75001. }
  75002. else
  75003. {
  75004. r.y = y1;
  75005. r.h = ry2 - y1;
  75006. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y1 - ry1));
  75007. i += 2;
  75008. }
  75009. }
  75010. else if (y2 > ry1 && y2 < ry2)
  75011. {
  75012. r.y = y2;
  75013. r.h = ry2 - y2;
  75014. if (x1 > rx1 || x2 < rx2 || y1 > ry1)
  75015. {
  75016. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y2 - ry1));
  75017. i += 2;
  75018. }
  75019. }
  75020. else
  75021. {
  75022. rects.remove (i);
  75023. }
  75024. }
  75025. }
  75026. }
  75027. }
  75028. bool RectangleList::subtract (const RectangleList& otherList)
  75029. {
  75030. for (int i = otherList.rects.size(); --i >= 0 && rects.size() > 0;)
  75031. subtract (otherList.rects.getReference (i));
  75032. return rects.size() > 0;
  75033. }
  75034. bool RectangleList::clipTo (const Rectangle<int>& rect)
  75035. {
  75036. bool notEmpty = false;
  75037. if (rect.isEmpty())
  75038. {
  75039. clear();
  75040. }
  75041. else
  75042. {
  75043. for (int i = rects.size(); --i >= 0;)
  75044. {
  75045. Rectangle<int>& r = rects.getReference (i);
  75046. if (! rect.intersectRectangle (r.x, r.y, r.w, r.h))
  75047. rects.remove (i);
  75048. else
  75049. notEmpty = true;
  75050. }
  75051. }
  75052. return notEmpty;
  75053. }
  75054. bool RectangleList::clipTo (const RectangleList& other)
  75055. {
  75056. if (rects.size() == 0)
  75057. return false;
  75058. RectangleList result;
  75059. for (int j = 0; j < rects.size(); ++j)
  75060. {
  75061. const Rectangle<int>& rect = rects.getReference (j);
  75062. for (int i = other.rects.size(); --i >= 0;)
  75063. {
  75064. Rectangle<int> r (other.rects.getReference (i));
  75065. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  75066. result.rects.add (r);
  75067. }
  75068. }
  75069. swapWith (result);
  75070. return ! isEmpty();
  75071. }
  75072. bool RectangleList::getIntersectionWith (const Rectangle<int>& rect, RectangleList& destRegion) const
  75073. {
  75074. destRegion.clear();
  75075. if (! rect.isEmpty())
  75076. {
  75077. for (int i = rects.size(); --i >= 0;)
  75078. {
  75079. Rectangle<int> r (rects.getReference (i));
  75080. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  75081. destRegion.rects.add (r);
  75082. }
  75083. }
  75084. return destRegion.rects.size() > 0;
  75085. }
  75086. void RectangleList::swapWith (RectangleList& otherList) throw()
  75087. {
  75088. rects.swapWithArray (otherList.rects);
  75089. }
  75090. void RectangleList::consolidate()
  75091. {
  75092. int i;
  75093. for (i = 0; i < getNumRectangles() - 1; ++i)
  75094. {
  75095. Rectangle<int>& r = rects.getReference (i);
  75096. const int rx1 = r.x;
  75097. const int ry1 = r.y;
  75098. const int rx2 = rx1 + r.w;
  75099. const int ry2 = ry1 + r.h;
  75100. for (int j = rects.size(); --j > i;)
  75101. {
  75102. Rectangle<int>& r2 = rects.getReference (j);
  75103. const int jrx1 = r2.x;
  75104. const int jry1 = r2.y;
  75105. const int jrx2 = jrx1 + r2.w;
  75106. const int jry2 = jry1 + r2.h;
  75107. // if the vertical edges of any blocks are touching and their horizontals don't
  75108. // line up, split them horizontally..
  75109. if (jrx1 == rx2 || jrx2 == rx1)
  75110. {
  75111. if (jry1 > ry1 && jry1 < ry2)
  75112. {
  75113. r.h = jry1 - ry1;
  75114. rects.add (Rectangle<int> (rx1, jry1, rx2 - rx1, ry2 - jry1));
  75115. i = -1;
  75116. break;
  75117. }
  75118. if (jry2 > ry1 && jry2 < ry2)
  75119. {
  75120. r.h = jry2 - ry1;
  75121. rects.add (Rectangle<int> (rx1, jry2, rx2 - rx1, ry2 - jry2));
  75122. i = -1;
  75123. break;
  75124. }
  75125. else if (ry1 > jry1 && ry1 < jry2)
  75126. {
  75127. r2.h = ry1 - jry1;
  75128. rects.add (Rectangle<int> (jrx1, ry1, jrx2 - jrx1, jry2 - ry1));
  75129. i = -1;
  75130. break;
  75131. }
  75132. else if (ry2 > jry1 && ry2 < jry2)
  75133. {
  75134. r2.h = ry2 - jry1;
  75135. rects.add (Rectangle<int> (jrx1, ry2, jrx2 - jrx1, jry2 - ry2));
  75136. i = -1;
  75137. break;
  75138. }
  75139. }
  75140. }
  75141. }
  75142. for (i = 0; i < rects.size() - 1; ++i)
  75143. {
  75144. Rectangle<int>& r = rects.getReference (i);
  75145. for (int j = rects.size(); --j > i;)
  75146. {
  75147. if (r.enlargeIfAdjacent (rects.getReference (j)))
  75148. {
  75149. rects.remove (j);
  75150. i = -1;
  75151. break;
  75152. }
  75153. }
  75154. }
  75155. }
  75156. bool RectangleList::containsPoint (const int x, const int y) const throw()
  75157. {
  75158. for (int i = getNumRectangles(); --i >= 0;)
  75159. if (rects.getReference (i).contains (x, y))
  75160. return true;
  75161. return false;
  75162. }
  75163. bool RectangleList::containsRectangle (const Rectangle<int>& rectangleToCheck) const
  75164. {
  75165. if (rects.size() > 1)
  75166. {
  75167. RectangleList r (rectangleToCheck);
  75168. for (int i = rects.size(); --i >= 0;)
  75169. {
  75170. r.subtract (rects.getReference (i));
  75171. if (r.rects.size() == 0)
  75172. return true;
  75173. }
  75174. }
  75175. else if (rects.size() > 0)
  75176. {
  75177. return rects.getReference (0).contains (rectangleToCheck);
  75178. }
  75179. return false;
  75180. }
  75181. bool RectangleList::intersectsRectangle (const Rectangle<int>& rectangleToCheck) const throw()
  75182. {
  75183. for (int i = rects.size(); --i >= 0;)
  75184. if (rects.getReference (i).intersects (rectangleToCheck))
  75185. return true;
  75186. return false;
  75187. }
  75188. bool RectangleList::intersects (const RectangleList& other) const throw()
  75189. {
  75190. for (int i = rects.size(); --i >= 0;)
  75191. if (other.intersectsRectangle (rects.getReference (i)))
  75192. return true;
  75193. return false;
  75194. }
  75195. const Rectangle<int> RectangleList::getBounds() const throw()
  75196. {
  75197. if (rects.size() <= 1)
  75198. {
  75199. if (rects.size() == 0)
  75200. return Rectangle<int>();
  75201. else
  75202. return rects.getReference (0);
  75203. }
  75204. else
  75205. {
  75206. const Rectangle<int>& r = rects.getReference (0);
  75207. int minX = r.x;
  75208. int minY = r.y;
  75209. int maxX = minX + r.w;
  75210. int maxY = minY + r.h;
  75211. for (int i = rects.size(); --i > 0;)
  75212. {
  75213. const Rectangle<int>& r2 = rects.getReference (i);
  75214. minX = jmin (minX, r2.x);
  75215. minY = jmin (minY, r2.y);
  75216. maxX = jmax (maxX, r2.getRight());
  75217. maxY = jmax (maxY, r2.getBottom());
  75218. }
  75219. return Rectangle<int> (minX, minY, maxX - minX, maxY - minY);
  75220. }
  75221. }
  75222. void RectangleList::offsetAll (const int dx, const int dy) throw()
  75223. {
  75224. for (int i = rects.size(); --i >= 0;)
  75225. {
  75226. Rectangle<int>& r = rects.getReference (i);
  75227. r.x += dx;
  75228. r.y += dy;
  75229. }
  75230. }
  75231. const Path RectangleList::toPath() const
  75232. {
  75233. Path p;
  75234. for (int i = rects.size(); --i >= 0;)
  75235. {
  75236. const Rectangle<int>& r = rects.getReference (i);
  75237. p.addRectangle ((float) r.x,
  75238. (float) r.y,
  75239. (float) r.w,
  75240. (float) r.h);
  75241. }
  75242. return p;
  75243. }
  75244. END_JUCE_NAMESPACE
  75245. /*** End of inlined file: juce_RectangleList.cpp ***/
  75246. /*** Start of inlined file: juce_RelativeCoordinate.cpp ***/
  75247. BEGIN_JUCE_NAMESPACE
  75248. namespace RelativeCoordinateHelpers
  75249. {
  75250. static bool isOrigin (const String& name)
  75251. {
  75252. return name.isEmpty()
  75253. || name == RelativeCoordinate::Strings::parentLeft
  75254. || name == RelativeCoordinate::Strings::parentTop;
  75255. }
  75256. static const String getOriginAnchorName (const bool isHorizontal) throw()
  75257. {
  75258. return isHorizontal ? RelativeCoordinate::Strings::parentLeft
  75259. : RelativeCoordinate::Strings::parentTop;
  75260. }
  75261. static const String getExtentAnchorName (const bool isHorizontal) throw()
  75262. {
  75263. return isHorizontal ? RelativeCoordinate::Strings::parentRight
  75264. : RelativeCoordinate::Strings::parentBottom;
  75265. }
  75266. static const String getObjectName (const String& fullName)
  75267. {
  75268. return fullName.upToFirstOccurrenceOf (".", false, false);
  75269. }
  75270. static const String getEdgeName (const String& fullName)
  75271. {
  75272. return fullName.fromFirstOccurrenceOf (".", false, false);
  75273. }
  75274. static const RelativeCoordinate findCoordinate (const String& name, const RelativeCoordinate::NamedCoordinateFinder* nameFinder)
  75275. {
  75276. return nameFinder != 0 ? nameFinder->findNamedCoordinate (getObjectName (name), getEdgeName (name))
  75277. : RelativeCoordinate();
  75278. }
  75279. struct RecursionException : public std::runtime_error
  75280. {
  75281. RecursionException() : std::runtime_error ("Recursive RelativeCoordinate expression")
  75282. {
  75283. }
  75284. };
  75285. static void skipWhitespace (const juce_wchar* const s, int& i)
  75286. {
  75287. while (CharacterFunctions::isWhitespace (s[i]))
  75288. ++i;
  75289. }
  75290. static void skipComma (const juce_wchar* const s, int& i)
  75291. {
  75292. skipWhitespace (s, i);
  75293. if (s[i] == ',')
  75294. ++i;
  75295. }
  75296. static const String readAnchorName (const juce_wchar* const s, int& i)
  75297. {
  75298. skipWhitespace (s, i);
  75299. if (CharacterFunctions::isLetter (s[i]) || s[i] == '_')
  75300. {
  75301. int start = i;
  75302. while (CharacterFunctions::isLetterOrDigit (s[i]) || s[i] == '_' || s[i] == '.')
  75303. ++i;
  75304. return String (s + start, i - start);
  75305. }
  75306. return String::empty;
  75307. }
  75308. static double readNumber (const juce_wchar* const s, int& i)
  75309. {
  75310. skipWhitespace (s, i);
  75311. int start = i;
  75312. if (CharacterFunctions::isDigit (s[i]) || s[i] == '.' || s[i] == '-')
  75313. ++i;
  75314. while (CharacterFunctions::isDigit (s[i]) || s[i] == '.')
  75315. ++i;
  75316. if ((s[i] == 'e' || s[i] == 'E')
  75317. && (CharacterFunctions::isDigit (s[i + 1])
  75318. || s[i + 1] == '-'
  75319. || s[i + 1] == '+'))
  75320. {
  75321. i += 2;
  75322. while (CharacterFunctions::isDigit (s[i]))
  75323. ++i;
  75324. }
  75325. const double value = String (s + start, i - start).getDoubleValue();
  75326. while (CharacterFunctions::isWhitespace (s[i]) || s[i] == ',')
  75327. ++i;
  75328. return value;
  75329. }
  75330. static const RelativeCoordinate readNextCoordinate (const juce_wchar* const s, int& i, const bool isHorizontal)
  75331. {
  75332. String anchor1 (readAnchorName (s, i));
  75333. double value = 0;
  75334. if (anchor1.isNotEmpty())
  75335. {
  75336. skipWhitespace (s, i);
  75337. if (s[i] == '+')
  75338. value = readNumber (s, ++i);
  75339. else if (s[i] == '-')
  75340. value = -readNumber (s, ++i);
  75341. return RelativeCoordinate (value, anchor1);
  75342. }
  75343. else
  75344. {
  75345. value = readNumber (s, i);
  75346. skipWhitespace (s, i);
  75347. if (s[i] == '%')
  75348. {
  75349. value /= 100.0;
  75350. skipWhitespace (s, ++i);
  75351. String anchor2;
  75352. if (s[i] == '*')
  75353. {
  75354. anchor1 = readAnchorName (s, ++i);
  75355. if (anchor1.isEmpty())
  75356. anchor1 = getOriginAnchorName (isHorizontal);
  75357. skipWhitespace (s, i);
  75358. if (s[i] == '-' && s[i + 1] == '>')
  75359. {
  75360. i += 2;
  75361. anchor2 = readAnchorName (s, i);
  75362. }
  75363. else
  75364. {
  75365. anchor2 = anchor1;
  75366. anchor1 = getOriginAnchorName (isHorizontal);
  75367. }
  75368. }
  75369. else
  75370. {
  75371. anchor1 = getOriginAnchorName (isHorizontal);
  75372. anchor2 = getExtentAnchorName (isHorizontal);
  75373. }
  75374. return RelativeCoordinate (value, anchor1, anchor2);
  75375. }
  75376. return RelativeCoordinate (value, isHorizontal);
  75377. }
  75378. }
  75379. static const String limitedAccuracyString (const double n)
  75380. {
  75381. if (! (n < -0.001 || n > 0.001)) // to detect NaN and inf as well as for rounding
  75382. return "0";
  75383. return String (n, 3).trimCharactersAtEnd ("0").trimCharactersAtEnd (".");
  75384. }
  75385. }
  75386. const String RelativeCoordinate::Strings::parent ("parent");
  75387. const String RelativeCoordinate::Strings::left ("left");
  75388. const String RelativeCoordinate::Strings::right ("right");
  75389. const String RelativeCoordinate::Strings::top ("top");
  75390. const String RelativeCoordinate::Strings::bottom ("bottom");
  75391. const String RelativeCoordinate::Strings::parentLeft ("parent.left");
  75392. const String RelativeCoordinate::Strings::parentTop ("parent.top");
  75393. const String RelativeCoordinate::Strings::parentRight ("parent.right");
  75394. const String RelativeCoordinate::Strings::parentBottom ("parent.bottom");
  75395. RelativeCoordinate::RelativeCoordinate()
  75396. : value (0)
  75397. {
  75398. }
  75399. RelativeCoordinate::RelativeCoordinate (const double absoluteDistanceFromOrigin, const bool horizontal_)
  75400. : anchor1 (RelativeCoordinateHelpers::getOriginAnchorName (horizontal_)),
  75401. value (absoluteDistanceFromOrigin)
  75402. {
  75403. }
  75404. RelativeCoordinate::RelativeCoordinate (const double absoluteDistance, const String& source)
  75405. : anchor1 (source.trim()),
  75406. value (absoluteDistance)
  75407. {
  75408. jassert (anchor1.isNotEmpty());
  75409. }
  75410. RelativeCoordinate::RelativeCoordinate (const double relativeProportion, const String& pos1, const String& pos2)
  75411. : anchor1 (pos1.trim()),
  75412. anchor2 (pos2.trim()),
  75413. value (relativeProportion)
  75414. {
  75415. jassert (anchor1.isNotEmpty());
  75416. jassert (anchor2.isNotEmpty());
  75417. }
  75418. RelativeCoordinate::RelativeCoordinate (const String& s, const bool isHorizontal)
  75419. : value (0)
  75420. {
  75421. int i = 0;
  75422. *this = RelativeCoordinateHelpers::readNextCoordinate (s, i, isHorizontal);
  75423. }
  75424. RelativeCoordinate::~RelativeCoordinate()
  75425. {
  75426. }
  75427. bool RelativeCoordinate::operator== (const RelativeCoordinate& other) const throw()
  75428. {
  75429. return value == other.value && anchor1 == other.anchor1 && anchor2 == other.anchor2;
  75430. }
  75431. bool RelativeCoordinate::operator!= (const RelativeCoordinate& other) const throw()
  75432. {
  75433. return ! operator== (other);
  75434. }
  75435. const RelativeCoordinate RelativeCoordinate::getAnchorCoordinate1() const
  75436. {
  75437. return RelativeCoordinate (0.0, anchor1);
  75438. }
  75439. const RelativeCoordinate RelativeCoordinate::getAnchorCoordinate2() const
  75440. {
  75441. return RelativeCoordinate (0.0, anchor2);
  75442. }
  75443. double RelativeCoordinate::resolveAnchor (const String& anchorName, const NamedCoordinateFinder* nameFinder, int recursionCounter)
  75444. {
  75445. if (RelativeCoordinateHelpers::isOrigin (anchorName))
  75446. return 0.0;
  75447. return RelativeCoordinateHelpers::findCoordinate (anchorName, nameFinder).resolve (nameFinder, recursionCounter + 1);
  75448. }
  75449. double RelativeCoordinate::resolve (const NamedCoordinateFinder* nameFinder, int recursionCounter) const
  75450. {
  75451. if (recursionCounter > 150)
  75452. {
  75453. jassertfalse
  75454. throw RelativeCoordinateHelpers::RecursionException();
  75455. }
  75456. const double pos1 = resolveAnchor (anchor1, nameFinder, recursionCounter);
  75457. return isProportional() ? pos1 + (resolveAnchor (anchor2, nameFinder, recursionCounter) - pos1) * value
  75458. : pos1 + value;
  75459. }
  75460. double RelativeCoordinate::resolve (const NamedCoordinateFinder* nameFinder) const
  75461. {
  75462. try
  75463. {
  75464. return resolve (nameFinder, 0);
  75465. }
  75466. catch (RelativeCoordinateHelpers::RecursionException&)
  75467. {}
  75468. return 0.0;
  75469. }
  75470. bool RelativeCoordinate::isRecursive (const NamedCoordinateFinder* nameFinder) const
  75471. {
  75472. try
  75473. {
  75474. (void) resolve (nameFinder, 0);
  75475. }
  75476. catch (RelativeCoordinateHelpers::RecursionException&)
  75477. {
  75478. return true;
  75479. }
  75480. return false;
  75481. }
  75482. void RelativeCoordinate::moveToAbsolute (double newPos, const NamedCoordinateFinder* nameFinder)
  75483. {
  75484. try
  75485. {
  75486. const double pos1 = resolveAnchor (anchor1, nameFinder, 0);
  75487. if (isProportional())
  75488. {
  75489. const double size = resolveAnchor (anchor2, nameFinder, 0) - pos1;
  75490. if (size != 0)
  75491. value = (newPos - pos1) / size;
  75492. }
  75493. else
  75494. {
  75495. value = newPos - pos1;
  75496. }
  75497. }
  75498. catch (RelativeCoordinateHelpers::RecursionException&)
  75499. {}
  75500. }
  75501. void RelativeCoordinate::toggleProportionality (const NamedCoordinateFinder* nameFinder, bool isHorizontal)
  75502. {
  75503. const double oldValue = resolve (nameFinder);
  75504. anchor1 = RelativeCoordinateHelpers::getOriginAnchorName (isHorizontal);
  75505. anchor2 = isProportional() ? String::empty
  75506. : RelativeCoordinateHelpers::getExtentAnchorName (isHorizontal);
  75507. moveToAbsolute (oldValue, nameFinder);
  75508. }
  75509. bool RelativeCoordinate::references (const String& coordName, const NamedCoordinateFinder* nameFinder) const
  75510. {
  75511. using namespace RelativeCoordinateHelpers;
  75512. if (isOrigin (anchor1) && ! isProportional())
  75513. return isOrigin (coordName);
  75514. return anchor1 == coordName
  75515. || anchor2 == coordName
  75516. || findCoordinate (anchor1, nameFinder).references (coordName, nameFinder)
  75517. || (isProportional() && findCoordinate (anchor2, nameFinder).references (coordName, nameFinder));
  75518. }
  75519. bool RelativeCoordinate::isDynamic() const
  75520. {
  75521. return anchor2.isNotEmpty() || ! RelativeCoordinateHelpers::isOrigin (anchor1);
  75522. }
  75523. const String RelativeCoordinate::toString() const
  75524. {
  75525. using namespace RelativeCoordinateHelpers;
  75526. if (isProportional())
  75527. {
  75528. const String percent (limitedAccuracyString (value * 100.0));
  75529. if (isOrigin (anchor1))
  75530. {
  75531. if (anchor2 == "parent.right" || anchor2 == "parent.bottom")
  75532. return percent + "%";
  75533. else
  75534. return percent + "% * " + anchor2;
  75535. }
  75536. else
  75537. return percent + "% * " + anchor1 + " -> " + anchor2;
  75538. }
  75539. else
  75540. {
  75541. if (isOrigin (anchor1))
  75542. return limitedAccuracyString (value);
  75543. else if (value > 0)
  75544. return anchor1 + " + " + limitedAccuracyString (value);
  75545. else if (value < 0)
  75546. return anchor1 + " - " + limitedAccuracyString (-value);
  75547. else
  75548. return anchor1;
  75549. }
  75550. }
  75551. const double RelativeCoordinate::getEditableNumber() const
  75552. {
  75553. return isProportional() ? value * 100.0 : value;
  75554. }
  75555. void RelativeCoordinate::setEditableNumber (const double newValue)
  75556. {
  75557. value = isProportional() ? newValue / 100.0 : newValue;
  75558. }
  75559. void RelativeCoordinate::changeAnchor1 (const String& newAnchorName, const NamedCoordinateFinder* nameFinder)
  75560. {
  75561. jassert (newAnchorName.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_."));
  75562. const double oldValue = resolve (nameFinder);
  75563. anchor1 = newAnchorName;
  75564. moveToAbsolute (oldValue, nameFinder);
  75565. }
  75566. void RelativeCoordinate::changeAnchor2 (const String& newAnchorName, const NamedCoordinateFinder* nameFinder)
  75567. {
  75568. jassert (isProportional());
  75569. jassert (newAnchorName.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_."));
  75570. const double oldValue = resolve (nameFinder);
  75571. anchor2 = newAnchorName;
  75572. moveToAbsolute (oldValue, nameFinder);
  75573. }
  75574. void RelativeCoordinate::renameAnchorIfUsed (const String& oldName, const String& newName, const NamedCoordinateFinder* nameFinder)
  75575. {
  75576. using namespace RelativeCoordinateHelpers;
  75577. jassert (oldName.isNotEmpty());
  75578. jassert (newName.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_"));
  75579. if (newName.isEmpty())
  75580. {
  75581. if (getObjectName (anchor1) == oldName
  75582. || getObjectName (anchor2) == oldName)
  75583. {
  75584. value = resolve (nameFinder);
  75585. anchor1 = String::empty;
  75586. anchor2 = String::empty;
  75587. }
  75588. }
  75589. else
  75590. {
  75591. if (getObjectName (anchor1) == oldName)
  75592. anchor1 = newName + "." + getEdgeName (anchor1);
  75593. if (getObjectName (anchor2) == oldName)
  75594. anchor2 = newName + "." + getEdgeName (anchor2);
  75595. }
  75596. }
  75597. RelativePoint::RelativePoint()
  75598. : x (0, true), y (0, false)
  75599. {
  75600. }
  75601. RelativePoint::RelativePoint (const Point<float>& absolutePoint)
  75602. : x (absolutePoint.getX(), true), y (absolutePoint.getY(), false)
  75603. {
  75604. }
  75605. RelativePoint::RelativePoint (const float x_, const float y_)
  75606. : x (x_, true), y (y_, false)
  75607. {
  75608. }
  75609. RelativePoint::RelativePoint (const RelativeCoordinate& x_, const RelativeCoordinate& y_)
  75610. : x (x_), y (y_)
  75611. {
  75612. }
  75613. RelativePoint::RelativePoint (const String& s)
  75614. {
  75615. int i = 0;
  75616. x = RelativeCoordinateHelpers::readNextCoordinate (s, i, true);
  75617. RelativeCoordinateHelpers::skipComma (s, i);
  75618. y = RelativeCoordinateHelpers::readNextCoordinate (s, i, false);
  75619. }
  75620. bool RelativePoint::operator== (const RelativePoint& other) const throw()
  75621. {
  75622. return x == other.x && y == other.y;
  75623. }
  75624. bool RelativePoint::operator!= (const RelativePoint& other) const throw()
  75625. {
  75626. return ! operator== (other);
  75627. }
  75628. const Point<float> RelativePoint::resolve (const RelativeCoordinate::NamedCoordinateFinder* nameFinder) const
  75629. {
  75630. return Point<float> ((float) x.resolve (nameFinder),
  75631. (float) y.resolve (nameFinder));
  75632. }
  75633. void RelativePoint::moveToAbsolute (const Point<float>& newPos, const RelativeCoordinate::NamedCoordinateFinder* nameFinder)
  75634. {
  75635. x.moveToAbsolute (newPos.getX(), nameFinder);
  75636. y.moveToAbsolute (newPos.getY(), nameFinder);
  75637. }
  75638. const String RelativePoint::toString() const
  75639. {
  75640. return x.toString() + ", " + y.toString();
  75641. }
  75642. void RelativePoint::renameAnchorIfUsed (const String& oldName, const String& newName, const RelativeCoordinate::NamedCoordinateFinder* nameFinder)
  75643. {
  75644. x.renameAnchorIfUsed (oldName, newName, nameFinder);
  75645. y.renameAnchorIfUsed (oldName, newName, nameFinder);
  75646. }
  75647. bool RelativePoint::isDynamic() const
  75648. {
  75649. return x.isDynamic() || y.isDynamic();
  75650. }
  75651. RelativeRectangle::RelativeRectangle()
  75652. {
  75653. }
  75654. RelativeRectangle::RelativeRectangle (const RelativeCoordinate& left_, const RelativeCoordinate& right_,
  75655. const RelativeCoordinate& top_, const RelativeCoordinate& bottom_)
  75656. : left (left_), right (right_), top (top_), bottom (bottom_)
  75657. {
  75658. }
  75659. RelativeRectangle::RelativeRectangle (const Rectangle<float>& rect, const String& componentName)
  75660. : left (rect.getX(), true),
  75661. right (rect.getWidth(), componentName + "." + RelativeCoordinate::Strings::left),
  75662. top (rect.getY(), false),
  75663. bottom (rect.getHeight(), componentName + "." + RelativeCoordinate::Strings::top)
  75664. {
  75665. }
  75666. RelativeRectangle::RelativeRectangle (const String& s)
  75667. {
  75668. int i = 0;
  75669. left = RelativeCoordinateHelpers::readNextCoordinate (s, i, true);
  75670. RelativeCoordinateHelpers::skipComma (s, i);
  75671. top = RelativeCoordinateHelpers::readNextCoordinate (s, i, false);
  75672. RelativeCoordinateHelpers::skipComma (s, i);
  75673. right = RelativeCoordinateHelpers::readNextCoordinate (s, i, true);
  75674. RelativeCoordinateHelpers::skipComma (s, i);
  75675. bottom = RelativeCoordinateHelpers::readNextCoordinate (s, i, false);
  75676. }
  75677. bool RelativeRectangle::operator== (const RelativeRectangle& other) const throw()
  75678. {
  75679. return left == other.left && top == other.top && right == other.right && bottom == other.bottom;
  75680. }
  75681. bool RelativeRectangle::operator!= (const RelativeRectangle& other) const throw()
  75682. {
  75683. return ! operator== (other);
  75684. }
  75685. const Rectangle<float> RelativeRectangle::resolve (const RelativeCoordinate::NamedCoordinateFinder* nameFinder) const
  75686. {
  75687. const double l = left.resolve (nameFinder);
  75688. const double r = right.resolve (nameFinder);
  75689. const double t = top.resolve (nameFinder);
  75690. const double b = bottom.resolve (nameFinder);
  75691. return Rectangle<float> ((float) l, (float) t, (float) (r - l), (float) (b - t));
  75692. }
  75693. void RelativeRectangle::moveToAbsolute (const Rectangle<float>& newPos, const RelativeCoordinate::NamedCoordinateFinder* nameFinder)
  75694. {
  75695. left.moveToAbsolute (newPos.getX(), nameFinder);
  75696. right.moveToAbsolute (newPos.getRight(), nameFinder);
  75697. top.moveToAbsolute (newPos.getY(), nameFinder);
  75698. bottom.moveToAbsolute (newPos.getBottom(), nameFinder);
  75699. }
  75700. const String RelativeRectangle::toString() const
  75701. {
  75702. return left.toString() + ", " + top.toString() + ", " + right.toString() + ", " + bottom.toString();
  75703. }
  75704. void RelativeRectangle::renameAnchorIfUsed (const String& oldName, const String& newName,
  75705. const RelativeCoordinate::NamedCoordinateFinder* nameFinder)
  75706. {
  75707. left.renameAnchorIfUsed (oldName, newName, nameFinder);
  75708. right.renameAnchorIfUsed (oldName, newName, nameFinder);
  75709. top.renameAnchorIfUsed (oldName, newName, nameFinder);
  75710. bottom.renameAnchorIfUsed (oldName, newName, nameFinder);
  75711. }
  75712. RelativePointPath::RelativePointPath()
  75713. : usesNonZeroWinding (true),
  75714. containsDynamicPoints (false)
  75715. {
  75716. }
  75717. RelativePointPath::RelativePointPath (const RelativePointPath& other)
  75718. : usesNonZeroWinding (true),
  75719. containsDynamicPoints (false)
  75720. {
  75721. ValueTree state (DrawablePath::valueTreeType);
  75722. other.writeTo (state, 0);
  75723. parse (state);
  75724. }
  75725. RelativePointPath::RelativePointPath (const ValueTree& drawable)
  75726. : usesNonZeroWinding (true),
  75727. containsDynamicPoints (false)
  75728. {
  75729. parse (drawable);
  75730. }
  75731. RelativePointPath::RelativePointPath (const Path& path)
  75732. {
  75733. usesNonZeroWinding = path.isUsingNonZeroWinding();
  75734. Path::Iterator i (path);
  75735. while (i.next())
  75736. {
  75737. switch (i.elementType)
  75738. {
  75739. case Path::Iterator::startNewSubPath: elements.add (new StartSubPath (RelativePoint (i.x1, i.y1))); break;
  75740. case Path::Iterator::lineTo: elements.add (new LineTo (RelativePoint (i.x1, i.y1))); break;
  75741. case Path::Iterator::quadraticTo: elements.add (new QuadraticTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2))); break;
  75742. case Path::Iterator::cubicTo: elements.add (new CubicTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2), RelativePoint (i.x3, i.y3))); break;
  75743. case Path::Iterator::closePath: elements.add (new CloseSubPath()); break;
  75744. default: jassertfalse; break;
  75745. }
  75746. }
  75747. }
  75748. void RelativePointPath::writeTo (ValueTree state, UndoManager* undoManager) const
  75749. {
  75750. DrawablePath::ValueTreeWrapper wrapper (state);
  75751. wrapper.setUsesNonZeroWinding (usesNonZeroWinding, undoManager);
  75752. ValueTree pathTree (wrapper.getPathState());
  75753. pathTree.removeAllChildren (undoManager);
  75754. for (int i = 0; i < elements.size(); ++i)
  75755. pathTree.addChild (elements.getUnchecked(i)->createTree(), -1, undoManager);
  75756. }
  75757. void RelativePointPath::parse (const ValueTree& state)
  75758. {
  75759. DrawablePath::ValueTreeWrapper wrapper (state);
  75760. usesNonZeroWinding = wrapper.usesNonZeroWinding();
  75761. RelativePoint points[3];
  75762. const ValueTree pathTree (wrapper.getPathState());
  75763. const int num = pathTree.getNumChildren();
  75764. for (int i = 0; i < num; ++i)
  75765. {
  75766. const DrawablePath::ValueTreeWrapper::Element e (pathTree.getChild(i));
  75767. const int numCps = e.getNumControlPoints();
  75768. for (int j = 0; j < numCps; ++j)
  75769. {
  75770. points[j] = e.getControlPoint (j);
  75771. containsDynamicPoints = containsDynamicPoints || points[j].isDynamic();
  75772. }
  75773. const Identifier type (e.getType());
  75774. if (type == DrawablePath::ValueTreeWrapper::Element::startSubPathElement)
  75775. elements.add (new StartSubPath (points[0]));
  75776. else if (type == DrawablePath::ValueTreeWrapper::Element::closeSubPathElement)
  75777. elements.add (new CloseSubPath());
  75778. else if (type == DrawablePath::ValueTreeWrapper::Element::lineToElement)
  75779. elements.add (new LineTo (points[0]));
  75780. else if (type == DrawablePath::ValueTreeWrapper::Element::quadraticToElement)
  75781. elements.add (new QuadraticTo (points[0], points[1]));
  75782. else if (type == DrawablePath::ValueTreeWrapper::Element::cubicToElement)
  75783. elements.add (new CubicTo (points[0], points[1], points[2]));
  75784. else
  75785. jassertfalse;
  75786. }
  75787. }
  75788. RelativePointPath::~RelativePointPath()
  75789. {
  75790. }
  75791. void RelativePointPath::swapWith (RelativePointPath& other) throw()
  75792. {
  75793. elements.swapWithArray (other.elements);
  75794. swapVariables (usesNonZeroWinding, other.usesNonZeroWinding);
  75795. }
  75796. void RelativePointPath::createPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder)
  75797. {
  75798. for (int i = 0; i < elements.size(); ++i)
  75799. elements.getUnchecked(i)->addToPath (path, coordFinder);
  75800. }
  75801. bool RelativePointPath::containsAnyDynamicPoints() const
  75802. {
  75803. return containsDynamicPoints;
  75804. }
  75805. RelativePointPath::ElementBase::ElementBase (const ElementType type_) : type (type_)
  75806. {
  75807. }
  75808. RelativePointPath::StartSubPath::StartSubPath (const RelativePoint& pos)
  75809. : ElementBase (startSubPathElement), startPos (pos)
  75810. {
  75811. }
  75812. const ValueTree RelativePointPath::StartSubPath::createTree() const
  75813. {
  75814. ValueTree v (DrawablePath::ValueTreeWrapper::Element::startSubPathElement);
  75815. v.setProperty (DrawablePath::ValueTreeWrapper::point1, startPos.toString(), 0);
  75816. return v;
  75817. }
  75818. void RelativePointPath::StartSubPath::addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const
  75819. {
  75820. path.startNewSubPath (startPos.resolve (coordFinder));
  75821. }
  75822. RelativePoint* RelativePointPath::StartSubPath::getControlPoints (int& numPoints)
  75823. {
  75824. numPoints = 1;
  75825. return &startPos;
  75826. }
  75827. RelativePointPath::CloseSubPath::CloseSubPath()
  75828. : ElementBase (closeSubPathElement)
  75829. {
  75830. }
  75831. const ValueTree RelativePointPath::CloseSubPath::createTree() const
  75832. {
  75833. return ValueTree (DrawablePath::ValueTreeWrapper::Element::closeSubPathElement);
  75834. }
  75835. void RelativePointPath::CloseSubPath::addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder*) const
  75836. {
  75837. path.closeSubPath();
  75838. }
  75839. RelativePoint* RelativePointPath::CloseSubPath::getControlPoints (int& numPoints)
  75840. {
  75841. numPoints = 0;
  75842. return 0;
  75843. }
  75844. RelativePointPath::LineTo::LineTo (const RelativePoint& endPoint_)
  75845. : ElementBase (lineToElement), endPoint (endPoint_)
  75846. {
  75847. }
  75848. const ValueTree RelativePointPath::LineTo::createTree() const
  75849. {
  75850. ValueTree v (DrawablePath::ValueTreeWrapper::Element::lineToElement);
  75851. v.setProperty (DrawablePath::ValueTreeWrapper::point1, endPoint.toString(), 0);
  75852. return v;
  75853. }
  75854. void RelativePointPath::LineTo::addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const
  75855. {
  75856. path.lineTo (endPoint.resolve (coordFinder));
  75857. }
  75858. RelativePoint* RelativePointPath::LineTo::getControlPoints (int& numPoints)
  75859. {
  75860. numPoints = 1;
  75861. return &endPoint;
  75862. }
  75863. RelativePointPath::QuadraticTo::QuadraticTo (const RelativePoint& controlPoint, const RelativePoint& endPoint)
  75864. : ElementBase (quadraticToElement)
  75865. {
  75866. controlPoints[0] = controlPoint;
  75867. controlPoints[1] = endPoint;
  75868. }
  75869. const ValueTree RelativePointPath::QuadraticTo::createTree() const
  75870. {
  75871. ValueTree v (DrawablePath::ValueTreeWrapper::Element::quadraticToElement);
  75872. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  75873. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  75874. return v;
  75875. }
  75876. void RelativePointPath::QuadraticTo::addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const
  75877. {
  75878. path.quadraticTo (controlPoints[0].resolve (coordFinder),
  75879. controlPoints[1].resolve (coordFinder));
  75880. }
  75881. RelativePoint* RelativePointPath::QuadraticTo::getControlPoints (int& numPoints)
  75882. {
  75883. numPoints = 2;
  75884. return controlPoints;
  75885. }
  75886. RelativePointPath::CubicTo::CubicTo (const RelativePoint& controlPoint1, const RelativePoint& controlPoint2, const RelativePoint& endPoint)
  75887. : ElementBase (cubicToElement)
  75888. {
  75889. controlPoints[0] = controlPoint1;
  75890. controlPoints[1] = controlPoint2;
  75891. controlPoints[2] = endPoint;
  75892. }
  75893. const ValueTree RelativePointPath::CubicTo::createTree() const
  75894. {
  75895. ValueTree v (DrawablePath::ValueTreeWrapper::Element::cubicToElement);
  75896. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  75897. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  75898. v.setProperty (DrawablePath::ValueTreeWrapper::point3, controlPoints[2].toString(), 0);
  75899. return v;
  75900. }
  75901. void RelativePointPath::CubicTo::addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const
  75902. {
  75903. path.cubicTo (controlPoints[0].resolve (coordFinder),
  75904. controlPoints[1].resolve (coordFinder),
  75905. controlPoints[2].resolve (coordFinder));
  75906. }
  75907. RelativePoint* RelativePointPath::CubicTo::getControlPoints (int& numPoints)
  75908. {
  75909. numPoints = 3;
  75910. return controlPoints;
  75911. }
  75912. RelativeParallelogram::RelativeParallelogram()
  75913. {
  75914. }
  75915. RelativeParallelogram::RelativeParallelogram (const RelativePoint& topLeft_, const RelativePoint& topRight_, const RelativePoint& bottomLeft_)
  75916. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  75917. {
  75918. }
  75919. RelativeParallelogram::RelativeParallelogram (const String& topLeft_, const String& topRight_, const String& bottomLeft_)
  75920. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  75921. {
  75922. }
  75923. RelativeParallelogram::~RelativeParallelogram()
  75924. {
  75925. }
  75926. void RelativeParallelogram::resolveThreePoints (Point<float>* points, RelativeCoordinate::NamedCoordinateFinder* const coordFinder) const
  75927. {
  75928. points[0] = topLeft.resolve (coordFinder);
  75929. points[1] = topRight.resolve (coordFinder);
  75930. points[2] = bottomLeft.resolve (coordFinder);
  75931. }
  75932. void RelativeParallelogram::resolveFourCorners (Point<float>* points, RelativeCoordinate::NamedCoordinateFinder* const coordFinder) const
  75933. {
  75934. resolveThreePoints (points, coordFinder);
  75935. points[3] = points[1] + (points[2] - points[0]);
  75936. }
  75937. const Rectangle<float> RelativeParallelogram::getBounds (RelativeCoordinate::NamedCoordinateFinder* const coordFinder) const
  75938. {
  75939. Point<float> points[4];
  75940. resolveFourCorners (points, coordFinder);
  75941. return Rectangle<float>::findAreaContainingPoints (points, 4);
  75942. }
  75943. void RelativeParallelogram::getPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* const coordFinder) const
  75944. {
  75945. Point<float> points[4];
  75946. resolveFourCorners (points, coordFinder);
  75947. path.startNewSubPath (points[0]);
  75948. path.lineTo (points[1]);
  75949. path.lineTo (points[3]);
  75950. path.lineTo (points[2]);
  75951. path.closeSubPath();
  75952. }
  75953. const AffineTransform RelativeParallelogram::resetToPerpendicular (RelativeCoordinate::NamedCoordinateFinder* const coordFinder)
  75954. {
  75955. Point<float> corners[3];
  75956. resolveThreePoints (corners, coordFinder);
  75957. const Line<float> top (corners[0], corners[1]);
  75958. const Line<float> left (corners[0], corners[2]);
  75959. const Point<float> newTopRight (corners[0] + Point<float> (top.getLength(), 0.0f));
  75960. const Point<float> newBottomLeft (corners[0] + Point<float> (0.0f, left.getLength()));
  75961. topRight.moveToAbsolute (newTopRight, coordFinder);
  75962. bottomLeft.moveToAbsolute (newBottomLeft, coordFinder);
  75963. return AffineTransform::fromTargetPoints (corners[0].getX(), corners[0].getY(), corners[0].getX(), corners[0].getY(),
  75964. corners[1].getX(), corners[1].getY(), newTopRight.getX(), newTopRight.getY(),
  75965. corners[2].getX(), corners[2].getY(), newBottomLeft.getX(), newBottomLeft.getY());
  75966. }
  75967. bool RelativeParallelogram::operator== (const RelativeParallelogram& other) const throw()
  75968. {
  75969. return topLeft == other.topLeft && topRight == other.topRight && bottomLeft == other.bottomLeft;
  75970. }
  75971. bool RelativeParallelogram::operator!= (const RelativeParallelogram& other) const throw()
  75972. {
  75973. return ! operator== (other);
  75974. }
  75975. const Point<float> RelativeParallelogram::getInternalCoordForPoint (const Point<float>* const corners, Point<float> target) throw()
  75976. {
  75977. const Point<float> tr (corners[1] - corners[0]);
  75978. const Point<float> bl (corners[2] - corners[0]);
  75979. target -= corners[0];
  75980. return Point<float> (Line<float> (Point<float>(), tr).getIntersection (Line<float> (target, target - bl)).getDistanceFromOrigin(),
  75981. Line<float> (Point<float>(), bl).getIntersection (Line<float> (target, target - tr)).getDistanceFromOrigin());
  75982. }
  75983. const Point<float> RelativeParallelogram::getPointForInternalCoord (const Point<float>* const corners, const Point<float>& point) throw()
  75984. {
  75985. return corners[0]
  75986. + Line<float> (Point<float>(), corners[1] - corners[0]).getPointAlongLine (point.getX())
  75987. + Line<float> (Point<float>(), corners[2] - corners[0]).getPointAlongLine (point.getY());
  75988. }
  75989. END_JUCE_NAMESPACE
  75990. /*** End of inlined file: juce_RelativeCoordinate.cpp ***/
  75991. /*** Start of inlined file: juce_Image.cpp ***/
  75992. BEGIN_JUCE_NAMESPACE
  75993. Image::SharedImage::SharedImage (const PixelFormat format_, const int width_, const int height_)
  75994. : format (format_), width (width_), height (height_)
  75995. {
  75996. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  75997. jassert (width > 0 && height > 0); // It's illegal to create a zero-sized image!
  75998. }
  75999. Image::SharedImage::~SharedImage()
  76000. {
  76001. }
  76002. inline uint8* Image::SharedImage::getPixelData (const int x, const int y) const throw()
  76003. {
  76004. return imageData + lineStride * y + pixelStride * x;
  76005. }
  76006. class SoftwareSharedImage : public Image::SharedImage
  76007. {
  76008. public:
  76009. SoftwareSharedImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  76010. : Image::SharedImage (format_, width_, height_)
  76011. {
  76012. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  76013. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  76014. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  76015. imageData = imageDataAllocated;
  76016. }
  76017. ~SoftwareSharedImage()
  76018. {
  76019. }
  76020. Image::ImageType getType() const
  76021. {
  76022. return Image::SoftwareImage;
  76023. }
  76024. LowLevelGraphicsContext* createLowLevelContext()
  76025. {
  76026. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  76027. }
  76028. SharedImage* clone()
  76029. {
  76030. SoftwareSharedImage* s = new SoftwareSharedImage (format, width, height, false);
  76031. memcpy (s->imageData, imageData, lineStride * height);
  76032. return s;
  76033. }
  76034. private:
  76035. HeapBlock<uint8> imageDataAllocated;
  76036. };
  76037. Image::SharedImage* Image::SharedImage::createSoftwareImage (Image::PixelFormat format, int width, int height, bool clearImage)
  76038. {
  76039. return new SoftwareSharedImage (format, width, height, clearImage);
  76040. }
  76041. Image::Image()
  76042. {
  76043. }
  76044. Image::Image (SharedImage* const instance)
  76045. : image (instance)
  76046. {
  76047. }
  76048. Image::Image (const PixelFormat format,
  76049. const int width, const int height,
  76050. const bool clearImage, const ImageType type)
  76051. : image (type == Image::NativeImage ? SharedImage::createNativeImage (format, width, height, clearImage)
  76052. : new SoftwareSharedImage (format, width, height, clearImage))
  76053. {
  76054. }
  76055. Image::Image (const Image& other)
  76056. : image (other.image)
  76057. {
  76058. }
  76059. Image& Image::operator= (const Image& other)
  76060. {
  76061. image = other.image;
  76062. return *this;
  76063. }
  76064. Image::~Image()
  76065. {
  76066. }
  76067. LowLevelGraphicsContext* Image::createLowLevelContext() const
  76068. {
  76069. return image == 0 ? 0 : image->createLowLevelContext();
  76070. }
  76071. void Image::duplicateIfShared()
  76072. {
  76073. if (image != 0 && image->getReferenceCount() > 1)
  76074. image = image->clone();
  76075. }
  76076. const Image Image::rescaled (const int newWidth, const int newHeight, const Graphics::ResamplingQuality quality) const
  76077. {
  76078. if (image == 0 || (image->width == newWidth && image->height == newHeight))
  76079. return *this;
  76080. Image newImage (image->format, newWidth, newHeight, hasAlphaChannel(), image->getType());
  76081. Graphics g (newImage);
  76082. g.setImageResamplingQuality (quality);
  76083. g.drawImage (*this, 0, 0, newWidth, newHeight, 0, 0, image->width, image->height, false);
  76084. return newImage;
  76085. }
  76086. const Image Image::convertedToFormat (PixelFormat newFormat) const
  76087. {
  76088. if (image == 0 || newFormat == image->format)
  76089. return *this;
  76090. Image newImage (newFormat, image->width, image->height, false, image->getType());
  76091. if (newFormat == SingleChannel)
  76092. {
  76093. if (! hasAlphaChannel())
  76094. {
  76095. newImage.clear (getBounds(), Colours::black);
  76096. }
  76097. else
  76098. {
  76099. const BitmapData destData (newImage, 0, 0, image->width, image->height, true);
  76100. const BitmapData srcData (*this, 0, 0, image->width, image->height);
  76101. for (int y = 0; y < image->height; ++y)
  76102. {
  76103. const PixelARGB* src = (const PixelARGB*) srcData.getLinePointer(y);
  76104. uint8* dst = destData.getLinePointer (y);
  76105. for (int x = image->width; --x >= 0;)
  76106. {
  76107. *dst++ = src->getAlpha();
  76108. ++src;
  76109. }
  76110. }
  76111. }
  76112. }
  76113. else
  76114. {
  76115. if (hasAlphaChannel())
  76116. newImage.clear (getBounds());
  76117. Graphics g (newImage);
  76118. g.drawImageAt (*this, 0, 0);
  76119. }
  76120. return newImage;
  76121. }
  76122. const var Image::getTag() const
  76123. {
  76124. return image == 0 ? var::null : image->userTag;
  76125. }
  76126. void Image::setTag (const var& newTag)
  76127. {
  76128. if (image != 0)
  76129. image->userTag = newTag;
  76130. }
  76131. Image::BitmapData::BitmapData (Image& image, const int x, const int y, const int w, const int h, const bool /*makeWritable*/)
  76132. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  76133. pixelFormat (image.getFormat()),
  76134. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  76135. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  76136. width (w),
  76137. height (h)
  76138. {
  76139. jassert (data != 0);
  76140. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  76141. }
  76142. Image::BitmapData::BitmapData (const Image& image, const int x, const int y, const int w, const int h)
  76143. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  76144. pixelFormat (image.getFormat()),
  76145. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  76146. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  76147. width (w),
  76148. height (h)
  76149. {
  76150. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  76151. }
  76152. Image::BitmapData::~BitmapData()
  76153. {
  76154. }
  76155. const Colour Image::BitmapData::getPixelColour (const int x, const int y) const throw()
  76156. {
  76157. jassert (((unsigned int) x) < (unsigned int) width && ((unsigned int) y) < (unsigned int) height);
  76158. const uint8* const pixel = getPixelPointer (x, y);
  76159. switch (pixelFormat)
  76160. {
  76161. case Image::ARGB:
  76162. {
  76163. PixelARGB p (*(const PixelARGB*) pixel);
  76164. p.unpremultiply();
  76165. return Colour (p.getARGB());
  76166. }
  76167. case Image::RGB:
  76168. return Colour (((const PixelRGB*) pixel)->getARGB());
  76169. case Image::SingleChannel:
  76170. return Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixel);
  76171. default:
  76172. jassertfalse;
  76173. break;
  76174. }
  76175. return Colour();
  76176. }
  76177. void Image::BitmapData::setPixelColour (const int x, const int y, const Colour& colour) const throw()
  76178. {
  76179. jassert (((unsigned int) x) < (unsigned int) width && ((unsigned int) y) < (unsigned int) height);
  76180. uint8* const pixel = getPixelPointer (x, y);
  76181. const PixelARGB col (colour.getPixelARGB());
  76182. switch (pixelFormat)
  76183. {
  76184. case Image::ARGB: ((PixelARGB*) pixel)->set (col); break;
  76185. case Image::RGB: ((PixelRGB*) pixel)->set (col); break;
  76186. case Image::SingleChannel: *pixel = col.getAlpha(); break;
  76187. default: jassertfalse; break;
  76188. }
  76189. }
  76190. void Image::setPixelData (int x, int y, int w, int h,
  76191. const uint8* const sourcePixelData, const int sourceLineStride)
  76192. {
  76193. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= getWidth() && y + h <= getHeight());
  76194. if (Rectangle<int>::intersectRectangles (x, y, w, h, 0, 0, getWidth(), getHeight()))
  76195. {
  76196. const BitmapData dest (*this, x, y, w, h, true);
  76197. for (int i = 0; i < h; ++i)
  76198. {
  76199. memcpy (dest.getLinePointer(i),
  76200. sourcePixelData + sourceLineStride * i,
  76201. w * dest.pixelStride);
  76202. }
  76203. }
  76204. }
  76205. void Image::clear (const Rectangle<int>& area, const Colour& colourToClearTo)
  76206. {
  76207. const Rectangle<int> clipped (area.getIntersection (getBounds()));
  76208. if (! clipped.isEmpty())
  76209. {
  76210. const PixelARGB col (colourToClearTo.getPixelARGB());
  76211. const BitmapData destData (*this, clipped.getX(), clipped.getY(), clipped.getWidth(), clipped.getHeight(), true);
  76212. uint8* dest = destData.data;
  76213. int dh = clipped.getHeight();
  76214. while (--dh >= 0)
  76215. {
  76216. uint8* line = dest;
  76217. dest += destData.lineStride;
  76218. if (isARGB())
  76219. {
  76220. for (int x = clipped.getWidth(); --x >= 0;)
  76221. {
  76222. ((PixelARGB*) line)->set (col);
  76223. line += destData.pixelStride;
  76224. }
  76225. }
  76226. else if (isRGB())
  76227. {
  76228. for (int x = clipped.getWidth(); --x >= 0;)
  76229. {
  76230. ((PixelRGB*) line)->set (col);
  76231. line += destData.pixelStride;
  76232. }
  76233. }
  76234. else
  76235. {
  76236. for (int x = clipped.getWidth(); --x >= 0;)
  76237. {
  76238. *line = col.getAlpha();
  76239. line += destData.pixelStride;
  76240. }
  76241. }
  76242. }
  76243. }
  76244. }
  76245. const Colour Image::getPixelAt (const int x, const int y) const
  76246. {
  76247. if (((unsigned int) x) < (unsigned int) getWidth()
  76248. && ((unsigned int) y) < (unsigned int) getHeight())
  76249. {
  76250. const BitmapData srcData (*this, x, y, 1, 1);
  76251. return srcData.getPixelColour (0, 0);
  76252. }
  76253. return Colour();
  76254. }
  76255. void Image::setPixelAt (const int x, const int y, const Colour& colour)
  76256. {
  76257. if (((unsigned int) x) < (unsigned int) getWidth()
  76258. && ((unsigned int) y) < (unsigned int) getHeight())
  76259. {
  76260. const BitmapData destData (*this, x, y, 1, 1, true);
  76261. destData.setPixelColour (0, 0, colour);
  76262. }
  76263. }
  76264. void Image::multiplyAlphaAt (const int x, const int y, const float multiplier)
  76265. {
  76266. if (((unsigned int) x) < (unsigned int) getWidth()
  76267. && ((unsigned int) y) < (unsigned int) getHeight()
  76268. && hasAlphaChannel())
  76269. {
  76270. const BitmapData destData (*this, x, y, 1, 1, true);
  76271. if (isARGB())
  76272. ((PixelARGB*) destData.data)->multiplyAlpha (multiplier);
  76273. else
  76274. *(destData.data) = (uint8) (*(destData.data) * multiplier);
  76275. }
  76276. }
  76277. void Image::multiplyAllAlphas (const float amountToMultiplyBy)
  76278. {
  76279. if (hasAlphaChannel())
  76280. {
  76281. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  76282. if (isARGB())
  76283. {
  76284. for (int y = 0; y < destData.height; ++y)
  76285. {
  76286. uint8* p = destData.getLinePointer (y);
  76287. for (int x = 0; x < destData.width; ++x)
  76288. {
  76289. ((PixelARGB*) p)->multiplyAlpha (amountToMultiplyBy);
  76290. p += destData.pixelStride;
  76291. }
  76292. }
  76293. }
  76294. else
  76295. {
  76296. for (int y = 0; y < destData.height; ++y)
  76297. {
  76298. uint8* p = destData.getLinePointer (y);
  76299. for (int x = 0; x < destData.width; ++x)
  76300. {
  76301. *p = (uint8) (*p * amountToMultiplyBy);
  76302. p += destData.pixelStride;
  76303. }
  76304. }
  76305. }
  76306. }
  76307. else
  76308. {
  76309. jassertfalse; // can't do this without an alpha-channel!
  76310. }
  76311. }
  76312. void Image::desaturate()
  76313. {
  76314. if (isARGB() || isRGB())
  76315. {
  76316. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  76317. if (isARGB())
  76318. {
  76319. for (int y = 0; y < destData.height; ++y)
  76320. {
  76321. uint8* p = destData.getLinePointer (y);
  76322. for (int x = 0; x < destData.width; ++x)
  76323. {
  76324. ((PixelARGB*) p)->desaturate();
  76325. p += destData.pixelStride;
  76326. }
  76327. }
  76328. }
  76329. else
  76330. {
  76331. for (int y = 0; y < destData.height; ++y)
  76332. {
  76333. uint8* p = destData.getLinePointer (y);
  76334. for (int x = 0; x < destData.width; ++x)
  76335. {
  76336. ((PixelRGB*) p)->desaturate();
  76337. p += destData.pixelStride;
  76338. }
  76339. }
  76340. }
  76341. }
  76342. }
  76343. void Image::createSolidAreaMask (RectangleList& result, const float alphaThreshold) const
  76344. {
  76345. if (hasAlphaChannel())
  76346. {
  76347. const uint8 threshold = (uint8) jlimit (0, 255, roundToInt (alphaThreshold * 255.0f));
  76348. SparseSet<int> pixelsOnRow;
  76349. const BitmapData srcData (*this, 0, 0, getWidth(), getHeight());
  76350. for (int y = 0; y < srcData.height; ++y)
  76351. {
  76352. pixelsOnRow.clear();
  76353. const uint8* lineData = srcData.getLinePointer (y);
  76354. if (isARGB())
  76355. {
  76356. for (int x = 0; x < srcData.width; ++x)
  76357. {
  76358. if (((const PixelARGB*) lineData)->getAlpha() >= threshold)
  76359. pixelsOnRow.addRange (Range<int> (x, x + 1));
  76360. lineData += srcData.pixelStride;
  76361. }
  76362. }
  76363. else
  76364. {
  76365. for (int x = 0; x < srcData.width; ++x)
  76366. {
  76367. if (*lineData >= threshold)
  76368. pixelsOnRow.addRange (Range<int> (x, x + 1));
  76369. lineData += srcData.pixelStride;
  76370. }
  76371. }
  76372. for (int i = 0; i < pixelsOnRow.getNumRanges(); ++i)
  76373. {
  76374. const Range<int> range (pixelsOnRow.getRange (i));
  76375. result.add (Rectangle<int> (range.getStart(), y, range.getLength(), 1));
  76376. }
  76377. result.consolidate();
  76378. }
  76379. }
  76380. else
  76381. {
  76382. result.add (0, 0, getWidth(), getHeight());
  76383. }
  76384. }
  76385. void Image::moveImageSection (int dx, int dy,
  76386. int sx, int sy,
  76387. int w, int h)
  76388. {
  76389. if (dx < 0)
  76390. {
  76391. w += dx;
  76392. sx -= dx;
  76393. dx = 0;
  76394. }
  76395. if (dy < 0)
  76396. {
  76397. h += dy;
  76398. sy -= dy;
  76399. dy = 0;
  76400. }
  76401. if (sx < 0)
  76402. {
  76403. w += sx;
  76404. dx -= sx;
  76405. sx = 0;
  76406. }
  76407. if (sy < 0)
  76408. {
  76409. h += sy;
  76410. dy -= sy;
  76411. sy = 0;
  76412. }
  76413. const int minX = jmin (dx, sx);
  76414. const int minY = jmin (dy, sy);
  76415. w = jmin (w, getWidth() - jmax (sx, dx));
  76416. h = jmin (h, getHeight() - jmax (sy, dy));
  76417. if (w > 0 && h > 0)
  76418. {
  76419. const int maxX = jmax (dx, sx) + w;
  76420. const int maxY = jmax (dy, sy) + h;
  76421. const BitmapData destData (*this, minX, minY, maxX - minX, maxY - minY, true);
  76422. uint8* dst = destData.getPixelPointer (dx - minX, dy - minY);
  76423. const uint8* src = destData.getPixelPointer (sx - minX, sy - minY);
  76424. const int lineSize = destData.pixelStride * w;
  76425. if (dy > sy)
  76426. {
  76427. while (--h >= 0)
  76428. {
  76429. const int offset = h * destData.lineStride;
  76430. memmove (dst + offset, src + offset, lineSize);
  76431. }
  76432. }
  76433. else if (dst != src)
  76434. {
  76435. while (--h >= 0)
  76436. {
  76437. memmove (dst, src, lineSize);
  76438. dst += destData.lineStride;
  76439. src += destData.lineStride;
  76440. }
  76441. }
  76442. }
  76443. }
  76444. END_JUCE_NAMESPACE
  76445. /*** End of inlined file: juce_Image.cpp ***/
  76446. /*** Start of inlined file: juce_ImageCache.cpp ***/
  76447. BEGIN_JUCE_NAMESPACE
  76448. class ImageCache::Pimpl : public Timer,
  76449. public DeletedAtShutdown
  76450. {
  76451. public:
  76452. Pimpl()
  76453. : cacheTimeout (5000)
  76454. {
  76455. }
  76456. ~Pimpl()
  76457. {
  76458. clearSingletonInstance();
  76459. }
  76460. const Image getFromHashCode (const int64 hashCode)
  76461. {
  76462. const ScopedLock sl (lock);
  76463. for (int i = images.size(); --i >= 0;)
  76464. {
  76465. Item* const item = images.getUnchecked(i);
  76466. if (item->hashCode == hashCode)
  76467. return item->image;
  76468. }
  76469. return Image();
  76470. }
  76471. void addImageToCache (const Image& image, const int64 hashCode)
  76472. {
  76473. if (image.isValid())
  76474. {
  76475. if (! isTimerRunning())
  76476. startTimer (2000);
  76477. Item* const item = new Item();
  76478. item->hashCode = hashCode;
  76479. item->image = image;
  76480. item->lastUseTime = Time::getApproximateMillisecondCounter();
  76481. const ScopedLock sl (lock);
  76482. images.add (item);
  76483. }
  76484. }
  76485. void timerCallback()
  76486. {
  76487. const uint32 now = Time::getApproximateMillisecondCounter();
  76488. const ScopedLock sl (lock);
  76489. for (int i = images.size(); --i >= 0;)
  76490. {
  76491. Item* const item = images.getUnchecked(i);
  76492. if (item->image.getReferenceCount() <= 1)
  76493. {
  76494. if (now > item->lastUseTime + cacheTimeout || now < item->lastUseTime - 1000)
  76495. images.remove (i);
  76496. }
  76497. else
  76498. {
  76499. item->lastUseTime = now; // multiply-referenced, so this image is still in use.
  76500. }
  76501. }
  76502. if (images.size() == 0)
  76503. stopTimer();
  76504. }
  76505. struct Item
  76506. {
  76507. Image image;
  76508. int64 hashCode;
  76509. uint32 lastUseTime;
  76510. };
  76511. int cacheTimeout;
  76512. juce_DeclareSingleton_SingleThreaded_Minimal (ImageCache::Pimpl);
  76513. private:
  76514. OwnedArray<Item> images;
  76515. CriticalSection lock;
  76516. Pimpl (const Pimpl&);
  76517. Pimpl& operator= (const Pimpl&);
  76518. };
  76519. juce_ImplementSingleton_SingleThreaded (ImageCache::Pimpl);
  76520. const Image ImageCache::getFromHashCode (const int64 hashCode)
  76521. {
  76522. if (Pimpl::getInstanceWithoutCreating() != 0)
  76523. return Pimpl::getInstanceWithoutCreating()->getFromHashCode (hashCode);
  76524. return Image();
  76525. }
  76526. void ImageCache::addImageToCache (const Image& image, const int64 hashCode)
  76527. {
  76528. Pimpl::getInstance()->addImageToCache (image, hashCode);
  76529. }
  76530. const Image ImageCache::getFromFile (const File& file)
  76531. {
  76532. const int64 hashCode = file.hashCode64();
  76533. Image image (getFromHashCode (hashCode));
  76534. if (image.isNull())
  76535. {
  76536. image = ImageFileFormat::loadFrom (file);
  76537. addImageToCache (image, hashCode);
  76538. }
  76539. return image;
  76540. }
  76541. const Image ImageCache::getFromMemory (const void* imageData, const int dataSize)
  76542. {
  76543. const int64 hashCode = (int64) (pointer_sized_int) imageData;
  76544. Image image (getFromHashCode (hashCode));
  76545. if (image.isNull())
  76546. {
  76547. image = ImageFileFormat::loadFrom (imageData, dataSize);
  76548. addImageToCache (image, hashCode);
  76549. }
  76550. return image;
  76551. }
  76552. void ImageCache::setCacheTimeout (const int millisecs)
  76553. {
  76554. Pimpl::getInstance()->cacheTimeout = millisecs;
  76555. }
  76556. END_JUCE_NAMESPACE
  76557. /*** End of inlined file: juce_ImageCache.cpp ***/
  76558. /*** Start of inlined file: juce_ImageConvolutionKernel.cpp ***/
  76559. BEGIN_JUCE_NAMESPACE
  76560. ImageConvolutionKernel::ImageConvolutionKernel (const int size_)
  76561. : values (size_ * size_),
  76562. size (size_)
  76563. {
  76564. clear();
  76565. }
  76566. ImageConvolutionKernel::~ImageConvolutionKernel()
  76567. {
  76568. }
  76569. float ImageConvolutionKernel::getKernelValue (const int x, const int y) const throw()
  76570. {
  76571. if (((unsigned int) x) < (unsigned int) size
  76572. && ((unsigned int) y) < (unsigned int) size)
  76573. {
  76574. return values [x + y * size];
  76575. }
  76576. else
  76577. {
  76578. jassertfalse;
  76579. return 0;
  76580. }
  76581. }
  76582. void ImageConvolutionKernel::setKernelValue (const int x, const int y, const float value) throw()
  76583. {
  76584. if (((unsigned int) x) < (unsigned int) size
  76585. && ((unsigned int) y) < (unsigned int) size)
  76586. {
  76587. values [x + y * size] = value;
  76588. }
  76589. else
  76590. {
  76591. jassertfalse;
  76592. }
  76593. }
  76594. void ImageConvolutionKernel::clear()
  76595. {
  76596. for (int i = size * size; --i >= 0;)
  76597. values[i] = 0;
  76598. }
  76599. void ImageConvolutionKernel::setOverallSum (const float desiredTotalSum)
  76600. {
  76601. double currentTotal = 0.0;
  76602. for (int i = size * size; --i >= 0;)
  76603. currentTotal += values[i];
  76604. rescaleAllValues ((float) (desiredTotalSum / currentTotal));
  76605. }
  76606. void ImageConvolutionKernel::rescaleAllValues (const float multiplier)
  76607. {
  76608. for (int i = size * size; --i >= 0;)
  76609. values[i] *= multiplier;
  76610. }
  76611. void ImageConvolutionKernel::createGaussianBlur (const float radius)
  76612. {
  76613. const double radiusFactor = -1.0 / (radius * radius * 2);
  76614. const int centre = size >> 1;
  76615. for (int y = size; --y >= 0;)
  76616. {
  76617. for (int x = size; --x >= 0;)
  76618. {
  76619. const int cx = x - centre;
  76620. const int cy = y - centre;
  76621. values [x + y * size] = (float) exp (radiusFactor * (cx * cx + cy * cy));
  76622. }
  76623. }
  76624. setOverallSum (1.0f);
  76625. }
  76626. void ImageConvolutionKernel::applyToImage (Image& destImage,
  76627. const Image& sourceImage,
  76628. const Rectangle<int>& destinationArea) const
  76629. {
  76630. if (sourceImage == destImage)
  76631. {
  76632. destImage.duplicateIfShared();
  76633. }
  76634. else
  76635. {
  76636. if (sourceImage.getWidth() != destImage.getWidth()
  76637. || sourceImage.getHeight() != destImage.getHeight()
  76638. || sourceImage.getFormat() != destImage.getFormat())
  76639. {
  76640. jassertfalse;
  76641. return;
  76642. }
  76643. }
  76644. const Rectangle<int> area (destinationArea.getIntersection (destImage.getBounds()));
  76645. if (area.isEmpty())
  76646. return;
  76647. const int right = area.getRight();
  76648. const int bottom = area.getBottom();
  76649. const Image::BitmapData destData (destImage, area.getX(), area.getY(), area.getWidth(), area.getHeight(), true);
  76650. uint8* line = destData.data;
  76651. const Image::BitmapData srcData (sourceImage, 0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  76652. if (destData.pixelStride == 4)
  76653. {
  76654. for (int y = area.getY(); y < bottom; ++y)
  76655. {
  76656. uint8* dest = line;
  76657. line += destData.lineStride;
  76658. for (int x = area.getX(); x < right; ++x)
  76659. {
  76660. float c1 = 0;
  76661. float c2 = 0;
  76662. float c3 = 0;
  76663. float c4 = 0;
  76664. for (int yy = 0; yy < size; ++yy)
  76665. {
  76666. const int sy = y + yy - (size >> 1);
  76667. if (sy >= srcData.height)
  76668. break;
  76669. if (sy >= 0)
  76670. {
  76671. int sx = x - (size >> 1);
  76672. const uint8* src = srcData.getPixelPointer (sx, sy);
  76673. for (int xx = 0; xx < size; ++xx)
  76674. {
  76675. if (sx >= srcData.width)
  76676. break;
  76677. if (sx >= 0)
  76678. {
  76679. const float kernelMult = values [xx + yy * size];
  76680. c1 += kernelMult * *src++;
  76681. c2 += kernelMult * *src++;
  76682. c3 += kernelMult * *src++;
  76683. c4 += kernelMult * *src++;
  76684. }
  76685. else
  76686. {
  76687. src += 4;
  76688. }
  76689. ++sx;
  76690. }
  76691. }
  76692. }
  76693. *dest++ = (uint8) jmin (0xff, roundToInt (c1));
  76694. *dest++ = (uint8) jmin (0xff, roundToInt (c2));
  76695. *dest++ = (uint8) jmin (0xff, roundToInt (c3));
  76696. *dest++ = (uint8) jmin (0xff, roundToInt (c4));
  76697. }
  76698. }
  76699. }
  76700. else if (destData.pixelStride == 3)
  76701. {
  76702. for (int y = area.getY(); y < bottom; ++y)
  76703. {
  76704. uint8* dest = line;
  76705. line += destData.lineStride;
  76706. for (int x = area.getX(); x < right; ++x)
  76707. {
  76708. float c1 = 0;
  76709. float c2 = 0;
  76710. float c3 = 0;
  76711. for (int yy = 0; yy < size; ++yy)
  76712. {
  76713. const int sy = y + yy - (size >> 1);
  76714. if (sy >= srcData.height)
  76715. break;
  76716. if (sy >= 0)
  76717. {
  76718. int sx = x - (size >> 1);
  76719. const uint8* src = srcData.getPixelPointer (sx, sy);
  76720. for (int xx = 0; xx < size; ++xx)
  76721. {
  76722. if (sx >= srcData.width)
  76723. break;
  76724. if (sx >= 0)
  76725. {
  76726. const float kernelMult = values [xx + yy * size];
  76727. c1 += kernelMult * *src++;
  76728. c2 += kernelMult * *src++;
  76729. c3 += kernelMult * *src++;
  76730. }
  76731. else
  76732. {
  76733. src += 3;
  76734. }
  76735. ++sx;
  76736. }
  76737. }
  76738. }
  76739. *dest++ = (uint8) roundToInt (c1);
  76740. *dest++ = (uint8) roundToInt (c2);
  76741. *dest++ = (uint8) roundToInt (c3);
  76742. }
  76743. }
  76744. }
  76745. }
  76746. END_JUCE_NAMESPACE
  76747. /*** End of inlined file: juce_ImageConvolutionKernel.cpp ***/
  76748. /*** Start of inlined file: juce_ImageFileFormat.cpp ***/
  76749. BEGIN_JUCE_NAMESPACE
  76750. /*** Start of inlined file: juce_GIFLoader.h ***/
  76751. #ifndef __JUCE_GIFLOADER_JUCEHEADER__
  76752. #define __JUCE_GIFLOADER_JUCEHEADER__
  76753. #ifndef DOXYGEN
  76754. /**
  76755. Used internally by ImageFileFormat - don't use this class directly in your
  76756. application.
  76757. @see ImageFileFormat
  76758. */
  76759. class GIFLoader
  76760. {
  76761. public:
  76762. GIFLoader (InputStream& in);
  76763. ~GIFLoader();
  76764. const Image& getImage() const { return image; }
  76765. private:
  76766. Image image;
  76767. InputStream& input;
  76768. uint8 buffer [300];
  76769. uint8 palette [256][4];
  76770. bool dataBlockIsZero, fresh, finished;
  76771. int currentBit, lastBit, lastByteIndex;
  76772. int codeSize, setCodeSize;
  76773. int maxCode, maxCodeSize;
  76774. int firstcode, oldcode;
  76775. int clearCode, end_code;
  76776. enum { maxGifCode = 1 << 12 };
  76777. int table [2] [maxGifCode];
  76778. int stack [2 * maxGifCode];
  76779. int *sp;
  76780. bool getSizeFromHeader (int& width, int& height);
  76781. bool readPalette (const int numCols);
  76782. int readDataBlock (unsigned char* dest);
  76783. int processExtension (int type, int& transparent);
  76784. int readLZWByte (bool initialise, int input_code_size);
  76785. int getCode (int code_size, bool initialise);
  76786. bool readImage (int width, int height, int interlace, int transparent);
  76787. static inline int makeWord (const uint8 a, const uint8 b) { return (b << 8) | a; }
  76788. GIFLoader (const GIFLoader&);
  76789. GIFLoader& operator= (const GIFLoader&);
  76790. };
  76791. #endif // DOXYGEN
  76792. #endif // __JUCE_GIFLOADER_JUCEHEADER__
  76793. /*** End of inlined file: juce_GIFLoader.h ***/
  76794. class GIFImageFormat : public ImageFileFormat
  76795. {
  76796. public:
  76797. GIFImageFormat() {}
  76798. ~GIFImageFormat() {}
  76799. const String getFormatName()
  76800. {
  76801. return "GIF";
  76802. }
  76803. bool canUnderstand (InputStream& in)
  76804. {
  76805. const int bytesNeeded = 4;
  76806. char header [bytesNeeded];
  76807. return (in.read (header, bytesNeeded) == bytesNeeded)
  76808. && header[0] == 'G'
  76809. && header[1] == 'I'
  76810. && header[2] == 'F';
  76811. }
  76812. const Image decodeImage (InputStream& in)
  76813. {
  76814. const ScopedPointer <GIFLoader> loader (new GIFLoader (in));
  76815. return loader->getImage();
  76816. }
  76817. bool writeImageToStream (const Image& /*sourceImage*/, OutputStream& /*destStream*/)
  76818. {
  76819. return false;
  76820. }
  76821. };
  76822. ImageFileFormat* ImageFileFormat::findImageFormatForStream (InputStream& input)
  76823. {
  76824. static PNGImageFormat png;
  76825. static JPEGImageFormat jpg;
  76826. static GIFImageFormat gif;
  76827. ImageFileFormat* formats[4];
  76828. int numFormats = 0;
  76829. formats [numFormats++] = &png;
  76830. formats [numFormats++] = &jpg;
  76831. formats [numFormats++] = &gif;
  76832. const int64 streamPos = input.getPosition();
  76833. for (int i = 0; i < numFormats; ++i)
  76834. {
  76835. const bool found = formats[i]->canUnderstand (input);
  76836. input.setPosition (streamPos);
  76837. if (found)
  76838. return formats[i];
  76839. }
  76840. return 0;
  76841. }
  76842. const Image ImageFileFormat::loadFrom (InputStream& input)
  76843. {
  76844. ImageFileFormat* const format = findImageFormatForStream (input);
  76845. if (format != 0)
  76846. return format->decodeImage (input);
  76847. return Image();
  76848. }
  76849. const Image ImageFileFormat::loadFrom (const File& file)
  76850. {
  76851. InputStream* const in = file.createInputStream();
  76852. if (in != 0)
  76853. {
  76854. BufferedInputStream b (in, 8192, true);
  76855. return loadFrom (b);
  76856. }
  76857. return Image();
  76858. }
  76859. const Image ImageFileFormat::loadFrom (const void* rawData, const int numBytes)
  76860. {
  76861. if (rawData != 0 && numBytes > 4)
  76862. {
  76863. MemoryInputStream stream (rawData, numBytes, false);
  76864. return loadFrom (stream);
  76865. }
  76866. return Image();
  76867. }
  76868. END_JUCE_NAMESPACE
  76869. /*** End of inlined file: juce_ImageFileFormat.cpp ***/
  76870. /*** Start of inlined file: juce_GIFLoader.cpp ***/
  76871. BEGIN_JUCE_NAMESPACE
  76872. GIFLoader::GIFLoader (InputStream& in)
  76873. : image (0),
  76874. input (in),
  76875. dataBlockIsZero (false),
  76876. fresh (false),
  76877. finished (false)
  76878. {
  76879. currentBit = lastBit = lastByteIndex = 0;
  76880. maxCode = maxCodeSize = codeSize = setCodeSize = 0;
  76881. firstcode = oldcode = 0;
  76882. clearCode = end_code = 0;
  76883. int imageWidth, imageHeight;
  76884. int transparent = -1;
  76885. if (! getSizeFromHeader (imageWidth, imageHeight))
  76886. return;
  76887. if ((imageWidth <= 0) || (imageHeight <= 0))
  76888. return;
  76889. unsigned char buf [16];
  76890. if (in.read (buf, 3) != 3)
  76891. return;
  76892. int numColours = 2 << (buf[0] & 7);
  76893. if ((buf[0] & 0x80) != 0)
  76894. readPalette (numColours);
  76895. for (;;)
  76896. {
  76897. if (input.read (buf, 1) != 1)
  76898. break;
  76899. if (buf[0] == ';')
  76900. break;
  76901. if (buf[0] == '!')
  76902. {
  76903. if (input.read (buf, 1) != 1)
  76904. break;
  76905. if (processExtension (buf[0], transparent) < 0)
  76906. break;
  76907. continue;
  76908. }
  76909. if (buf[0] != ',')
  76910. continue;
  76911. if (input.read (buf, 9) != 9)
  76912. break;
  76913. imageWidth = makeWord (buf[4], buf[5]);
  76914. imageHeight = makeWord (buf[6], buf[7]);
  76915. numColours = 2 << (buf[8] & 7);
  76916. if ((buf[8] & 0x80) != 0)
  76917. if (! readPalette (numColours))
  76918. break;
  76919. image = Image ((transparent >= 0) ? Image::ARGB : Image::RGB,
  76920. imageWidth, imageHeight, (transparent >= 0));
  76921. readImage (imageWidth, imageHeight,
  76922. (buf[8] & 0x40) != 0,
  76923. transparent);
  76924. break;
  76925. }
  76926. }
  76927. GIFLoader::~GIFLoader()
  76928. {
  76929. }
  76930. bool GIFLoader::getSizeFromHeader (int& w, int& h)
  76931. {
  76932. char b[8];
  76933. if (input.read (b, 6) == 6)
  76934. {
  76935. if ((strncmp ("GIF87a", b, 6) == 0)
  76936. || (strncmp ("GIF89a", b, 6) == 0))
  76937. {
  76938. if (input.read (b, 4) == 4)
  76939. {
  76940. w = makeWord (b[0], b[1]);
  76941. h = makeWord (b[2], b[3]);
  76942. return true;
  76943. }
  76944. }
  76945. }
  76946. return false;
  76947. }
  76948. bool GIFLoader::readPalette (const int numCols)
  76949. {
  76950. unsigned char rgb[4];
  76951. for (int i = 0; i < numCols; ++i)
  76952. {
  76953. input.read (rgb, 3);
  76954. palette [i][0] = rgb[0];
  76955. palette [i][1] = rgb[1];
  76956. palette [i][2] = rgb[2];
  76957. palette [i][3] = 0xff;
  76958. }
  76959. return true;
  76960. }
  76961. int GIFLoader::readDataBlock (unsigned char* const dest)
  76962. {
  76963. unsigned char n;
  76964. if (input.read (&n, 1) == 1)
  76965. {
  76966. dataBlockIsZero = (n == 0);
  76967. if (dataBlockIsZero || (input.read (dest, n) == n))
  76968. return n;
  76969. }
  76970. return -1;
  76971. }
  76972. int GIFLoader::processExtension (const int type, int& transparent)
  76973. {
  76974. unsigned char b [300];
  76975. int n = 0;
  76976. if (type == 0xf9)
  76977. {
  76978. n = readDataBlock (b);
  76979. if (n < 0)
  76980. return 1;
  76981. if ((b[0] & 0x1) != 0)
  76982. transparent = b[3];
  76983. }
  76984. do
  76985. {
  76986. n = readDataBlock (b);
  76987. }
  76988. while (n > 0);
  76989. return n;
  76990. }
  76991. int GIFLoader::getCode (const int codeSize_, const bool initialise)
  76992. {
  76993. if (initialise)
  76994. {
  76995. currentBit = 0;
  76996. lastBit = 0;
  76997. finished = false;
  76998. return 0;
  76999. }
  77000. if ((currentBit + codeSize_) >= lastBit)
  77001. {
  77002. if (finished)
  77003. return -1;
  77004. buffer[0] = buffer [lastByteIndex - 2];
  77005. buffer[1] = buffer [lastByteIndex - 1];
  77006. const int n = readDataBlock (&buffer[2]);
  77007. if (n == 0)
  77008. finished = true;
  77009. lastByteIndex = 2 + n;
  77010. currentBit = (currentBit - lastBit) + 16;
  77011. lastBit = (2 + n) * 8 ;
  77012. }
  77013. int result = 0;
  77014. int i = currentBit;
  77015. for (int j = 0; j < codeSize_; ++j)
  77016. {
  77017. result |= ((buffer[i >> 3] & (1 << (i & 7))) != 0) << j;
  77018. ++i;
  77019. }
  77020. currentBit += codeSize_;
  77021. return result;
  77022. }
  77023. int GIFLoader::readLZWByte (const bool initialise, const int inputCodeSize)
  77024. {
  77025. int code, incode, i;
  77026. if (initialise)
  77027. {
  77028. setCodeSize = inputCodeSize;
  77029. codeSize = setCodeSize + 1;
  77030. clearCode = 1 << setCodeSize;
  77031. end_code = clearCode + 1;
  77032. maxCodeSize = 2 * clearCode;
  77033. maxCode = clearCode + 2;
  77034. getCode (0, true);
  77035. fresh = true;
  77036. for (i = 0; i < clearCode; ++i)
  77037. {
  77038. table[0][i] = 0;
  77039. table[1][i] = i;
  77040. }
  77041. for (; i < maxGifCode; ++i)
  77042. {
  77043. table[0][i] = 0;
  77044. table[1][i] = 0;
  77045. }
  77046. sp = stack;
  77047. return 0;
  77048. }
  77049. else if (fresh)
  77050. {
  77051. fresh = false;
  77052. do
  77053. {
  77054. firstcode = oldcode
  77055. = getCode (codeSize, false);
  77056. }
  77057. while (firstcode == clearCode);
  77058. return firstcode;
  77059. }
  77060. if (sp > stack)
  77061. return *--sp;
  77062. while ((code = getCode (codeSize, false)) >= 0)
  77063. {
  77064. if (code == clearCode)
  77065. {
  77066. for (i = 0; i < clearCode; ++i)
  77067. {
  77068. table[0][i] = 0;
  77069. table[1][i] = i;
  77070. }
  77071. for (; i < maxGifCode; ++i)
  77072. {
  77073. table[0][i] = 0;
  77074. table[1][i] = 0;
  77075. }
  77076. codeSize = setCodeSize + 1;
  77077. maxCodeSize = 2 * clearCode;
  77078. maxCode = clearCode + 2;
  77079. sp = stack;
  77080. firstcode = oldcode = getCode (codeSize, false);
  77081. return firstcode;
  77082. }
  77083. else if (code == end_code)
  77084. {
  77085. if (dataBlockIsZero)
  77086. return -2;
  77087. unsigned char buf [260];
  77088. int n;
  77089. while ((n = readDataBlock (buf)) > 0)
  77090. {}
  77091. if (n != 0)
  77092. return -2;
  77093. }
  77094. incode = code;
  77095. if (code >= maxCode)
  77096. {
  77097. *sp++ = firstcode;
  77098. code = oldcode;
  77099. }
  77100. while (code >= clearCode)
  77101. {
  77102. *sp++ = table[1][code];
  77103. if (code == table[0][code])
  77104. return -2;
  77105. code = table[0][code];
  77106. }
  77107. *sp++ = firstcode = table[1][code];
  77108. if ((code = maxCode) < maxGifCode)
  77109. {
  77110. table[0][code] = oldcode;
  77111. table[1][code] = firstcode;
  77112. ++maxCode;
  77113. if ((maxCode >= maxCodeSize)
  77114. && (maxCodeSize < maxGifCode))
  77115. {
  77116. maxCodeSize <<= 1;
  77117. ++codeSize;
  77118. }
  77119. }
  77120. oldcode = incode;
  77121. if (sp > stack)
  77122. return *--sp;
  77123. }
  77124. return code;
  77125. }
  77126. bool GIFLoader::readImage (const int width, const int height,
  77127. const int interlace, const int transparent)
  77128. {
  77129. unsigned char c;
  77130. if (input.read (&c, 1) != 1
  77131. || readLZWByte (true, c) < 0)
  77132. return false;
  77133. if (transparent >= 0)
  77134. {
  77135. palette [transparent][0] = 0;
  77136. palette [transparent][1] = 0;
  77137. palette [transparent][2] = 0;
  77138. palette [transparent][3] = 0;
  77139. }
  77140. int index;
  77141. int xpos = 0, ypos = 0, pass = 0;
  77142. const Image::BitmapData destData (image, 0, 0, width, height, true);
  77143. uint8* p = destData.data;
  77144. const bool hasAlpha = image.hasAlphaChannel();
  77145. while ((index = readLZWByte (false, c)) >= 0)
  77146. {
  77147. const uint8* const paletteEntry = palette [index];
  77148. if (hasAlpha)
  77149. {
  77150. ((PixelARGB*) p)->setARGB (paletteEntry[3],
  77151. paletteEntry[0],
  77152. paletteEntry[1],
  77153. paletteEntry[2]);
  77154. ((PixelARGB*) p)->premultiply();
  77155. }
  77156. else
  77157. {
  77158. ((PixelRGB*) p)->setARGB (0,
  77159. paletteEntry[0],
  77160. paletteEntry[1],
  77161. paletteEntry[2]);
  77162. }
  77163. p += destData.pixelStride;
  77164. ++xpos;
  77165. if (xpos == width)
  77166. {
  77167. xpos = 0;
  77168. if (interlace)
  77169. {
  77170. switch (pass)
  77171. {
  77172. case 0:
  77173. case 1: ypos += 8; break;
  77174. case 2: ypos += 4; break;
  77175. case 3: ypos += 2; break;
  77176. }
  77177. while (ypos >= height)
  77178. {
  77179. ++pass;
  77180. switch (pass)
  77181. {
  77182. case 1: ypos = 4; break;
  77183. case 2: ypos = 2; break;
  77184. case 3: ypos = 1; break;
  77185. default: return true;
  77186. }
  77187. }
  77188. }
  77189. else
  77190. {
  77191. ++ypos;
  77192. }
  77193. p = destData.getPixelPointer (xpos, ypos);
  77194. }
  77195. if (ypos >= height)
  77196. break;
  77197. }
  77198. return true;
  77199. }
  77200. END_JUCE_NAMESPACE
  77201. /*** End of inlined file: juce_GIFLoader.cpp ***/
  77202. #endif
  77203. //==============================================================================
  77204. // some files include lots of library code, so leave them to the end to avoid cluttering
  77205. // up the build for the clean files.
  77206. #if JUCE_BUILD_CORE
  77207. /*** Start of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  77208. namespace zlibNamespace
  77209. {
  77210. #if JUCE_INCLUDE_ZLIB_CODE
  77211. #undef OS_CODE
  77212. #undef fdopen
  77213. /*** Start of inlined file: zlib.h ***/
  77214. #ifndef ZLIB_H
  77215. #define ZLIB_H
  77216. /*** Start of inlined file: zconf.h ***/
  77217. /* @(#) $Id: zconf.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  77218. #ifndef ZCONF_H
  77219. #define ZCONF_H
  77220. // *** Just a few hacks here to make it compile nicely with Juce..
  77221. #define Z_PREFIX 1
  77222. #undef __MACTYPES__
  77223. #ifdef _MSC_VER
  77224. #pragma warning (disable : 4131 4127 4244 4267)
  77225. #endif
  77226. /*
  77227. * If you *really* need a unique prefix for all types and library functions,
  77228. * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
  77229. */
  77230. #ifdef Z_PREFIX
  77231. # define deflateInit_ z_deflateInit_
  77232. # define deflate z_deflate
  77233. # define deflateEnd z_deflateEnd
  77234. # define inflateInit_ z_inflateInit_
  77235. # define inflate z_inflate
  77236. # define inflateEnd z_inflateEnd
  77237. # define inflatePrime z_inflatePrime
  77238. # define inflateGetHeader z_inflateGetHeader
  77239. # define adler32_combine z_adler32_combine
  77240. # define crc32_combine z_crc32_combine
  77241. # define deflateInit2_ z_deflateInit2_
  77242. # define deflateSetDictionary z_deflateSetDictionary
  77243. # define deflateCopy z_deflateCopy
  77244. # define deflateReset z_deflateReset
  77245. # define deflateParams z_deflateParams
  77246. # define deflateBound z_deflateBound
  77247. # define deflatePrime z_deflatePrime
  77248. # define inflateInit2_ z_inflateInit2_
  77249. # define inflateSetDictionary z_inflateSetDictionary
  77250. # define inflateSync z_inflateSync
  77251. # define inflateSyncPoint z_inflateSyncPoint
  77252. # define inflateCopy z_inflateCopy
  77253. # define inflateReset z_inflateReset
  77254. # define inflateBack z_inflateBack
  77255. # define inflateBackEnd z_inflateBackEnd
  77256. # define compress z_compress
  77257. # define compress2 z_compress2
  77258. # define compressBound z_compressBound
  77259. # define uncompress z_uncompress
  77260. # define adler32 z_adler32
  77261. # define crc32 z_crc32
  77262. # define get_crc_table z_get_crc_table
  77263. # define zError z_zError
  77264. # define alloc_func z_alloc_func
  77265. # define free_func z_free_func
  77266. # define in_func z_in_func
  77267. # define out_func z_out_func
  77268. # define Byte z_Byte
  77269. # define uInt z_uInt
  77270. # define uLong z_uLong
  77271. # define Bytef z_Bytef
  77272. # define charf z_charf
  77273. # define intf z_intf
  77274. # define uIntf z_uIntf
  77275. # define uLongf z_uLongf
  77276. # define voidpf z_voidpf
  77277. # define voidp z_voidp
  77278. #endif
  77279. #if defined(__MSDOS__) && !defined(MSDOS)
  77280. # define MSDOS
  77281. #endif
  77282. #if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
  77283. # define OS2
  77284. #endif
  77285. #if defined(_WINDOWS) && !defined(WINDOWS)
  77286. # define WINDOWS
  77287. #endif
  77288. #if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
  77289. # ifndef WIN32
  77290. # define WIN32
  77291. # endif
  77292. #endif
  77293. #if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
  77294. # if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
  77295. # ifndef SYS16BIT
  77296. # define SYS16BIT
  77297. # endif
  77298. # endif
  77299. #endif
  77300. /*
  77301. * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
  77302. * than 64k bytes at a time (needed on systems with 16-bit int).
  77303. */
  77304. #ifdef SYS16BIT
  77305. # define MAXSEG_64K
  77306. #endif
  77307. #ifdef MSDOS
  77308. # define UNALIGNED_OK
  77309. #endif
  77310. #ifdef __STDC_VERSION__
  77311. # ifndef STDC
  77312. # define STDC
  77313. # endif
  77314. # if __STDC_VERSION__ >= 199901L
  77315. # ifndef STDC99
  77316. # define STDC99
  77317. # endif
  77318. # endif
  77319. #endif
  77320. #if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
  77321. # define STDC
  77322. #endif
  77323. #if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
  77324. # define STDC
  77325. #endif
  77326. #if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
  77327. # define STDC
  77328. #endif
  77329. #if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
  77330. # define STDC
  77331. #endif
  77332. #if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */
  77333. # define STDC
  77334. #endif
  77335. #ifndef STDC
  77336. # ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
  77337. # define const /* note: need a more gentle solution here */
  77338. # endif
  77339. #endif
  77340. /* Some Mac compilers merge all .h files incorrectly: */
  77341. #if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
  77342. # define NO_DUMMY_DECL
  77343. #endif
  77344. /* Maximum value for memLevel in deflateInit2 */
  77345. #ifndef MAX_MEM_LEVEL
  77346. # ifdef MAXSEG_64K
  77347. # define MAX_MEM_LEVEL 8
  77348. # else
  77349. # define MAX_MEM_LEVEL 9
  77350. # endif
  77351. #endif
  77352. /* Maximum value for windowBits in deflateInit2 and inflateInit2.
  77353. * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
  77354. * created by gzip. (Files created by minigzip can still be extracted by
  77355. * gzip.)
  77356. */
  77357. #ifndef MAX_WBITS
  77358. # define MAX_WBITS 15 /* 32K LZ77 window */
  77359. #endif
  77360. /* The memory requirements for deflate are (in bytes):
  77361. (1 << (windowBits+2)) + (1 << (memLevel+9))
  77362. that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
  77363. plus a few kilobytes for small objects. For example, if you want to reduce
  77364. the default memory requirements from 256K to 128K, compile with
  77365. make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
  77366. Of course this will generally degrade compression (there's no free lunch).
  77367. The memory requirements for inflate are (in bytes) 1 << windowBits
  77368. that is, 32K for windowBits=15 (default value) plus a few kilobytes
  77369. for small objects.
  77370. */
  77371. /* Type declarations */
  77372. #ifndef OF /* function prototypes */
  77373. # ifdef STDC
  77374. # define OF(args) args
  77375. # else
  77376. # define OF(args) ()
  77377. # endif
  77378. #endif
  77379. /* The following definitions for FAR are needed only for MSDOS mixed
  77380. * model programming (small or medium model with some far allocations).
  77381. * This was tested only with MSC; for other MSDOS compilers you may have
  77382. * to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
  77383. * just define FAR to be empty.
  77384. */
  77385. #ifdef SYS16BIT
  77386. # if defined(M_I86SM) || defined(M_I86MM)
  77387. /* MSC small or medium model */
  77388. # define SMALL_MEDIUM
  77389. # ifdef _MSC_VER
  77390. # define FAR _far
  77391. # else
  77392. # define FAR far
  77393. # endif
  77394. # endif
  77395. # if (defined(__SMALL__) || defined(__MEDIUM__))
  77396. /* Turbo C small or medium model */
  77397. # define SMALL_MEDIUM
  77398. # ifdef __BORLANDC__
  77399. # define FAR _far
  77400. # else
  77401. # define FAR far
  77402. # endif
  77403. # endif
  77404. #endif
  77405. #if defined(WINDOWS) || defined(WIN32)
  77406. /* If building or using zlib as a DLL, define ZLIB_DLL.
  77407. * This is not mandatory, but it offers a little performance increase.
  77408. */
  77409. # ifdef ZLIB_DLL
  77410. # if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
  77411. # ifdef ZLIB_INTERNAL
  77412. # define ZEXTERN extern __declspec(dllexport)
  77413. # else
  77414. # define ZEXTERN extern __declspec(dllimport)
  77415. # endif
  77416. # endif
  77417. # endif /* ZLIB_DLL */
  77418. /* If building or using zlib with the WINAPI/WINAPIV calling convention,
  77419. * define ZLIB_WINAPI.
  77420. * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
  77421. */
  77422. # ifdef ZLIB_WINAPI
  77423. # ifdef FAR
  77424. # undef FAR
  77425. # endif
  77426. # include <windows.h>
  77427. /* No need for _export, use ZLIB.DEF instead. */
  77428. /* For complete Windows compatibility, use WINAPI, not __stdcall. */
  77429. # define ZEXPORT WINAPI
  77430. # ifdef WIN32
  77431. # define ZEXPORTVA WINAPIV
  77432. # else
  77433. # define ZEXPORTVA FAR CDECL
  77434. # endif
  77435. # endif
  77436. #endif
  77437. #if defined (__BEOS__)
  77438. # ifdef ZLIB_DLL
  77439. # ifdef ZLIB_INTERNAL
  77440. # define ZEXPORT __declspec(dllexport)
  77441. # define ZEXPORTVA __declspec(dllexport)
  77442. # else
  77443. # define ZEXPORT __declspec(dllimport)
  77444. # define ZEXPORTVA __declspec(dllimport)
  77445. # endif
  77446. # endif
  77447. #endif
  77448. #ifndef ZEXTERN
  77449. # define ZEXTERN extern
  77450. #endif
  77451. #ifndef ZEXPORT
  77452. # define ZEXPORT
  77453. #endif
  77454. #ifndef ZEXPORTVA
  77455. # define ZEXPORTVA
  77456. #endif
  77457. #ifndef FAR
  77458. # define FAR
  77459. #endif
  77460. #if !defined(__MACTYPES__)
  77461. typedef unsigned char Byte; /* 8 bits */
  77462. #endif
  77463. typedef unsigned int uInt; /* 16 bits or more */
  77464. typedef unsigned long uLong; /* 32 bits or more */
  77465. #ifdef SMALL_MEDIUM
  77466. /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
  77467. # define Bytef Byte FAR
  77468. #else
  77469. typedef Byte FAR Bytef;
  77470. #endif
  77471. typedef char FAR charf;
  77472. typedef int FAR intf;
  77473. typedef uInt FAR uIntf;
  77474. typedef uLong FAR uLongf;
  77475. #ifdef STDC
  77476. typedef void const *voidpc;
  77477. typedef void FAR *voidpf;
  77478. typedef void *voidp;
  77479. #else
  77480. typedef Byte const *voidpc;
  77481. typedef Byte FAR *voidpf;
  77482. typedef Byte *voidp;
  77483. #endif
  77484. #if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */
  77485. # include <sys/types.h> /* for off_t */
  77486. # include <unistd.h> /* for SEEK_* and off_t */
  77487. # ifdef VMS
  77488. # include <unixio.h> /* for off_t */
  77489. # endif
  77490. # define z_off_t off_t
  77491. #endif
  77492. #ifndef SEEK_SET
  77493. # define SEEK_SET 0 /* Seek from beginning of file. */
  77494. # define SEEK_CUR 1 /* Seek from current position. */
  77495. # define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
  77496. #endif
  77497. #ifndef z_off_t
  77498. # define z_off_t long
  77499. #endif
  77500. #if defined(__OS400__)
  77501. # define NO_vsnprintf
  77502. #endif
  77503. #if defined(__MVS__)
  77504. # define NO_vsnprintf
  77505. # ifdef FAR
  77506. # undef FAR
  77507. # endif
  77508. #endif
  77509. /* MVS linker does not support external names larger than 8 bytes */
  77510. #if defined(__MVS__)
  77511. # pragma map(deflateInit_,"DEIN")
  77512. # pragma map(deflateInit2_,"DEIN2")
  77513. # pragma map(deflateEnd,"DEEND")
  77514. # pragma map(deflateBound,"DEBND")
  77515. # pragma map(inflateInit_,"ININ")
  77516. # pragma map(inflateInit2_,"ININ2")
  77517. # pragma map(inflateEnd,"INEND")
  77518. # pragma map(inflateSync,"INSY")
  77519. # pragma map(inflateSetDictionary,"INSEDI")
  77520. # pragma map(compressBound,"CMBND")
  77521. # pragma map(inflate_table,"INTABL")
  77522. # pragma map(inflate_fast,"INFA")
  77523. # pragma map(inflate_copyright,"INCOPY")
  77524. #endif
  77525. #endif /* ZCONF_H */
  77526. /*** End of inlined file: zconf.h ***/
  77527. #ifdef __cplusplus
  77528. extern "C" {
  77529. #endif
  77530. #define ZLIB_VERSION "1.2.3"
  77531. #define ZLIB_VERNUM 0x1230
  77532. /*
  77533. The 'zlib' compression library provides in-memory compression and
  77534. decompression functions, including integrity checks of the uncompressed
  77535. data. This version of the library supports only one compression method
  77536. (deflation) but other algorithms will be added later and will have the same
  77537. stream interface.
  77538. Compression can be done in a single step if the buffers are large
  77539. enough (for example if an input file is mmap'ed), or can be done by
  77540. repeated calls of the compression function. In the latter case, the
  77541. application must provide more input and/or consume the output
  77542. (providing more output space) before each call.
  77543. The compressed data format used by default by the in-memory functions is
  77544. the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
  77545. around a deflate stream, which is itself documented in RFC 1951.
  77546. The library also supports reading and writing files in gzip (.gz) format
  77547. with an interface similar to that of stdio using the functions that start
  77548. with "gz". The gzip format is different from the zlib format. gzip is a
  77549. gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
  77550. This library can optionally read and write gzip streams in memory as well.
  77551. The zlib format was designed to be compact and fast for use in memory
  77552. and on communications channels. The gzip format was designed for single-
  77553. file compression on file systems, has a larger header than zlib to maintain
  77554. directory information, and uses a different, slower check method than zlib.
  77555. The library does not install any signal handler. The decoder checks
  77556. the consistency of the compressed data, so the library should never
  77557. crash even in case of corrupted input.
  77558. */
  77559. typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
  77560. typedef void (*free_func) OF((voidpf opaque, voidpf address));
  77561. struct internal_state;
  77562. typedef struct z_stream_s {
  77563. Bytef *next_in; /* next input byte */
  77564. uInt avail_in; /* number of bytes available at next_in */
  77565. uLong total_in; /* total nb of input bytes read so far */
  77566. Bytef *next_out; /* next output byte should be put there */
  77567. uInt avail_out; /* remaining free space at next_out */
  77568. uLong total_out; /* total nb of bytes output so far */
  77569. char *msg; /* last error message, NULL if no error */
  77570. struct internal_state FAR *state; /* not visible by applications */
  77571. alloc_func zalloc; /* used to allocate the internal state */
  77572. free_func zfree; /* used to free the internal state */
  77573. voidpf opaque; /* private data object passed to zalloc and zfree */
  77574. int data_type; /* best guess about the data type: binary or text */
  77575. uLong adler; /* adler32 value of the uncompressed data */
  77576. uLong reserved; /* reserved for future use */
  77577. } z_stream;
  77578. typedef z_stream FAR *z_streamp;
  77579. /*
  77580. gzip header information passed to and from zlib routines. See RFC 1952
  77581. for more details on the meanings of these fields.
  77582. */
  77583. typedef struct gz_header_s {
  77584. int text; /* true if compressed data believed to be text */
  77585. uLong time; /* modification time */
  77586. int xflags; /* extra flags (not used when writing a gzip file) */
  77587. int os; /* operating system */
  77588. Bytef *extra; /* pointer to extra field or Z_NULL if none */
  77589. uInt extra_len; /* extra field length (valid if extra != Z_NULL) */
  77590. uInt extra_max; /* space at extra (only when reading header) */
  77591. Bytef *name; /* pointer to zero-terminated file name or Z_NULL */
  77592. uInt name_max; /* space at name (only when reading header) */
  77593. Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */
  77594. uInt comm_max; /* space at comment (only when reading header) */
  77595. int hcrc; /* true if there was or will be a header crc */
  77596. int done; /* true when done reading gzip header (not used
  77597. when writing a gzip file) */
  77598. } gz_header;
  77599. typedef gz_header FAR *gz_headerp;
  77600. /*
  77601. The application must update next_in and avail_in when avail_in has
  77602. dropped to zero. It must update next_out and avail_out when avail_out
  77603. has dropped to zero. The application must initialize zalloc, zfree and
  77604. opaque before calling the init function. All other fields are set by the
  77605. compression library and must not be updated by the application.
  77606. The opaque value provided by the application will be passed as the first
  77607. parameter for calls of zalloc and zfree. This can be useful for custom
  77608. memory management. The compression library attaches no meaning to the
  77609. opaque value.
  77610. zalloc must return Z_NULL if there is not enough memory for the object.
  77611. If zlib is used in a multi-threaded application, zalloc and zfree must be
  77612. thread safe.
  77613. On 16-bit systems, the functions zalloc and zfree must be able to allocate
  77614. exactly 65536 bytes, but will not be required to allocate more than this
  77615. if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
  77616. pointers returned by zalloc for objects of exactly 65536 bytes *must*
  77617. have their offset normalized to zero. The default allocation function
  77618. provided by this library ensures this (see zutil.c). To reduce memory
  77619. requirements and avoid any allocation of 64K objects, at the expense of
  77620. compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
  77621. The fields total_in and total_out can be used for statistics or
  77622. progress reports. After compression, total_in holds the total size of
  77623. the uncompressed data and may be saved for use in the decompressor
  77624. (particularly if the decompressor wants to decompress everything in
  77625. a single step).
  77626. */
  77627. /* constants */
  77628. #define Z_NO_FLUSH 0
  77629. #define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
  77630. #define Z_SYNC_FLUSH 2
  77631. #define Z_FULL_FLUSH 3
  77632. #define Z_FINISH 4
  77633. #define Z_BLOCK 5
  77634. /* Allowed flush values; see deflate() and inflate() below for details */
  77635. #define Z_OK 0
  77636. #define Z_STREAM_END 1
  77637. #define Z_NEED_DICT 2
  77638. #define Z_ERRNO (-1)
  77639. #define Z_STREAM_ERROR (-2)
  77640. #define Z_DATA_ERROR (-3)
  77641. #define Z_MEM_ERROR (-4)
  77642. #define Z_BUF_ERROR (-5)
  77643. #define Z_VERSION_ERROR (-6)
  77644. /* Return codes for the compression/decompression functions. Negative
  77645. * values are errors, positive values are used for special but normal events.
  77646. */
  77647. #define Z_NO_COMPRESSION 0
  77648. #define Z_BEST_SPEED 1
  77649. #define Z_BEST_COMPRESSION 9
  77650. #define Z_DEFAULT_COMPRESSION (-1)
  77651. /* compression levels */
  77652. #define Z_FILTERED 1
  77653. #define Z_HUFFMAN_ONLY 2
  77654. #define Z_RLE 3
  77655. #define Z_FIXED 4
  77656. #define Z_DEFAULT_STRATEGY 0
  77657. /* compression strategy; see deflateInit2() below for details */
  77658. #define Z_BINARY 0
  77659. #define Z_TEXT 1
  77660. #define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */
  77661. #define Z_UNKNOWN 2
  77662. /* Possible values of the data_type field (though see inflate()) */
  77663. #define Z_DEFLATED 8
  77664. /* The deflate compression method (the only one supported in this version) */
  77665. #define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
  77666. #define zlib_version zlibVersion()
  77667. /* for compatibility with versions < 1.0.2 */
  77668. /* basic functions */
  77669. //ZEXTERN const char * ZEXPORT zlibVersion OF((void));
  77670. /* The application can compare zlibVersion and ZLIB_VERSION for consistency.
  77671. If the first character differs, the library code actually used is
  77672. not compatible with the zlib.h header file used by the application.
  77673. This check is automatically made by deflateInit and inflateInit.
  77674. */
  77675. /*
  77676. ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
  77677. Initializes the internal stream state for compression. The fields
  77678. zalloc, zfree and opaque must be initialized before by the caller.
  77679. If zalloc and zfree are set to Z_NULL, deflateInit updates them to
  77680. use default allocation functions.
  77681. The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
  77682. 1 gives best speed, 9 gives best compression, 0 gives no compression at
  77683. all (the input data is simply copied a block at a time).
  77684. Z_DEFAULT_COMPRESSION requests a default compromise between speed and
  77685. compression (currently equivalent to level 6).
  77686. deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
  77687. enough memory, Z_STREAM_ERROR if level is not a valid compression level,
  77688. Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
  77689. with the version assumed by the caller (ZLIB_VERSION).
  77690. msg is set to null if there is no error message. deflateInit does not
  77691. perform any compression: this will be done by deflate().
  77692. */
  77693. ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
  77694. /*
  77695. deflate compresses as much data as possible, and stops when the input
  77696. buffer becomes empty or the output buffer becomes full. It may introduce some
  77697. output latency (reading input without producing any output) except when
  77698. forced to flush.
  77699. The detailed semantics are as follows. deflate performs one or both of the
  77700. following actions:
  77701. - Compress more input starting at next_in and update next_in and avail_in
  77702. accordingly. If not all input can be processed (because there is not
  77703. enough room in the output buffer), next_in and avail_in are updated and
  77704. processing will resume at this point for the next call of deflate().
  77705. - Provide more output starting at next_out and update next_out and avail_out
  77706. accordingly. This action is forced if the parameter flush is non zero.
  77707. Forcing flush frequently degrades the compression ratio, so this parameter
  77708. should be set only when necessary (in interactive applications).
  77709. Some output may be provided even if flush is not set.
  77710. Before the call of deflate(), the application should ensure that at least
  77711. one of the actions is possible, by providing more input and/or consuming
  77712. more output, and updating avail_in or avail_out accordingly; avail_out
  77713. should never be zero before the call. The application can consume the
  77714. compressed output when it wants, for example when the output buffer is full
  77715. (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
  77716. and with zero avail_out, it must be called again after making room in the
  77717. output buffer because there might be more output pending.
  77718. Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
  77719. decide how much data to accumualte before producing output, in order to
  77720. maximize compression.
  77721. If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
  77722. flushed to the output buffer and the output is aligned on a byte boundary, so
  77723. that the decompressor can get all input data available so far. (In particular
  77724. avail_in is zero after the call if enough output space has been provided
  77725. before the call.) Flushing may degrade compression for some compression
  77726. algorithms and so it should be used only when necessary.
  77727. If flush is set to Z_FULL_FLUSH, all output is flushed as with
  77728. Z_SYNC_FLUSH, and the compression state is reset so that decompression can
  77729. restart from this point if previous compressed data has been damaged or if
  77730. random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
  77731. compression.
  77732. If deflate returns with avail_out == 0, this function must be called again
  77733. with the same value of the flush parameter and more output space (updated
  77734. avail_out), until the flush is complete (deflate returns with non-zero
  77735. avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
  77736. avail_out is greater than six to avoid repeated flush markers due to
  77737. avail_out == 0 on return.
  77738. If the parameter flush is set to Z_FINISH, pending input is processed,
  77739. pending output is flushed and deflate returns with Z_STREAM_END if there
  77740. was enough output space; if deflate returns with Z_OK, this function must be
  77741. called again with Z_FINISH and more output space (updated avail_out) but no
  77742. more input data, until it returns with Z_STREAM_END or an error. After
  77743. deflate has returned Z_STREAM_END, the only possible operations on the
  77744. stream are deflateReset or deflateEnd.
  77745. Z_FINISH can be used immediately after deflateInit if all the compression
  77746. is to be done in a single step. In this case, avail_out must be at least
  77747. the value returned by deflateBound (see below). If deflate does not return
  77748. Z_STREAM_END, then it must be called again as described above.
  77749. deflate() sets strm->adler to the adler32 checksum of all input read
  77750. so far (that is, total_in bytes).
  77751. deflate() may update strm->data_type if it can make a good guess about
  77752. the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered
  77753. binary. This field is only for information purposes and does not affect
  77754. the compression algorithm in any manner.
  77755. deflate() returns Z_OK if some progress has been made (more input
  77756. processed or more output produced), Z_STREAM_END if all input has been
  77757. consumed and all output has been produced (only when flush is set to
  77758. Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
  77759. if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
  77760. (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not
  77761. fatal, and deflate() can be called again with more input and more output
  77762. space to continue compressing.
  77763. */
  77764. ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
  77765. /*
  77766. All dynamically allocated data structures for this stream are freed.
  77767. This function discards any unprocessed input and does not flush any
  77768. pending output.
  77769. deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
  77770. stream state was inconsistent, Z_DATA_ERROR if the stream was freed
  77771. prematurely (some input or output was discarded). In the error case,
  77772. msg may be set but then points to a static string (which must not be
  77773. deallocated).
  77774. */
  77775. /*
  77776. ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
  77777. Initializes the internal stream state for decompression. The fields
  77778. next_in, avail_in, zalloc, zfree and opaque must be initialized before by
  77779. the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
  77780. value depends on the compression method), inflateInit determines the
  77781. compression method from the zlib header and allocates all data structures
  77782. accordingly; otherwise the allocation will be deferred to the first call of
  77783. inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to
  77784. use default allocation functions.
  77785. inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
  77786. memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
  77787. version assumed by the caller. msg is set to null if there is no error
  77788. message. inflateInit does not perform any decompression apart from reading
  77789. the zlib header if present: this will be done by inflate(). (So next_in and
  77790. avail_in may be modified, but next_out and avail_out are unchanged.)
  77791. */
  77792. ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
  77793. /*
  77794. inflate decompresses as much data as possible, and stops when the input
  77795. buffer becomes empty or the output buffer becomes full. It may introduce
  77796. some output latency (reading input without producing any output) except when
  77797. forced to flush.
  77798. The detailed semantics are as follows. inflate performs one or both of the
  77799. following actions:
  77800. - Decompress more input starting at next_in and update next_in and avail_in
  77801. accordingly. If not all input can be processed (because there is not
  77802. enough room in the output buffer), next_in is updated and processing
  77803. will resume at this point for the next call of inflate().
  77804. - Provide more output starting at next_out and update next_out and avail_out
  77805. accordingly. inflate() provides as much output as possible, until there
  77806. is no more input data or no more space in the output buffer (see below
  77807. about the flush parameter).
  77808. Before the call of inflate(), the application should ensure that at least
  77809. one of the actions is possible, by providing more input and/or consuming
  77810. more output, and updating the next_* and avail_* values accordingly.
  77811. The application can consume the uncompressed output when it wants, for
  77812. example when the output buffer is full (avail_out == 0), or after each
  77813. call of inflate(). If inflate returns Z_OK and with zero avail_out, it
  77814. must be called again after making room in the output buffer because there
  77815. might be more output pending.
  77816. The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH,
  77817. Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much
  77818. output as possible to the output buffer. Z_BLOCK requests that inflate() stop
  77819. if and when it gets to the next deflate block boundary. When decoding the
  77820. zlib or gzip format, this will cause inflate() to return immediately after
  77821. the header and before the first block. When doing a raw inflate, inflate()
  77822. will go ahead and process the first block, and will return when it gets to
  77823. the end of that block, or when it runs out of data.
  77824. The Z_BLOCK option assists in appending to or combining deflate streams.
  77825. Also to assist in this, on return inflate() will set strm->data_type to the
  77826. number of unused bits in the last byte taken from strm->next_in, plus 64
  77827. if inflate() is currently decoding the last block in the deflate stream,
  77828. plus 128 if inflate() returned immediately after decoding an end-of-block
  77829. code or decoding the complete header up to just before the first byte of the
  77830. deflate stream. The end-of-block will not be indicated until all of the
  77831. uncompressed data from that block has been written to strm->next_out. The
  77832. number of unused bits may in general be greater than seven, except when
  77833. bit 7 of data_type is set, in which case the number of unused bits will be
  77834. less than eight.
  77835. inflate() should normally be called until it returns Z_STREAM_END or an
  77836. error. However if all decompression is to be performed in a single step
  77837. (a single call of inflate), the parameter flush should be set to
  77838. Z_FINISH. In this case all pending input is processed and all pending
  77839. output is flushed; avail_out must be large enough to hold all the
  77840. uncompressed data. (The size of the uncompressed data may have been saved
  77841. by the compressor for this purpose.) The next operation on this stream must
  77842. be inflateEnd to deallocate the decompression state. The use of Z_FINISH
  77843. is never required, but can be used to inform inflate that a faster approach
  77844. may be used for the single inflate() call.
  77845. In this implementation, inflate() always flushes as much output as
  77846. possible to the output buffer, and always uses the faster approach on the
  77847. first call. So the only effect of the flush parameter in this implementation
  77848. is on the return value of inflate(), as noted below, or when it returns early
  77849. because Z_BLOCK is used.
  77850. If a preset dictionary is needed after this call (see inflateSetDictionary
  77851. below), inflate sets strm->adler to the adler32 checksum of the dictionary
  77852. chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
  77853. strm->adler to the adler32 checksum of all output produced so far (that is,
  77854. total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
  77855. below. At the end of the stream, inflate() checks that its computed adler32
  77856. checksum is equal to that saved by the compressor and returns Z_STREAM_END
  77857. only if the checksum is correct.
  77858. inflate() will decompress and check either zlib-wrapped or gzip-wrapped
  77859. deflate data. The header type is detected automatically. Any information
  77860. contained in the gzip header is not retained, so applications that need that
  77861. information should instead use raw inflate, see inflateInit2() below, or
  77862. inflateBack() and perform their own processing of the gzip header and
  77863. trailer.
  77864. inflate() returns Z_OK if some progress has been made (more input processed
  77865. or more output produced), Z_STREAM_END if the end of the compressed data has
  77866. been reached and all uncompressed output has been produced, Z_NEED_DICT if a
  77867. preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
  77868. corrupted (input stream not conforming to the zlib format or incorrect check
  77869. value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
  77870. if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory,
  77871. Z_BUF_ERROR if no progress is possible or if there was not enough room in the
  77872. output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
  77873. inflate() can be called again with more input and more output space to
  77874. continue decompressing. If Z_DATA_ERROR is returned, the application may then
  77875. call inflateSync() to look for a good compression block if a partial recovery
  77876. of the data is desired.
  77877. */
  77878. ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
  77879. /*
  77880. All dynamically allocated data structures for this stream are freed.
  77881. This function discards any unprocessed input and does not flush any
  77882. pending output.
  77883. inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
  77884. was inconsistent. In the error case, msg may be set but then points to a
  77885. static string (which must not be deallocated).
  77886. */
  77887. /* Advanced functions */
  77888. /*
  77889. The following functions are needed only in some special applications.
  77890. */
  77891. /*
  77892. ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
  77893. int level,
  77894. int method,
  77895. int windowBits,
  77896. int memLevel,
  77897. int strategy));
  77898. This is another version of deflateInit with more compression options. The
  77899. fields next_in, zalloc, zfree and opaque must be initialized before by
  77900. the caller.
  77901. The method parameter is the compression method. It must be Z_DEFLATED in
  77902. this version of the library.
  77903. The windowBits parameter is the base two logarithm of the window size
  77904. (the size of the history buffer). It should be in the range 8..15 for this
  77905. version of the library. Larger values of this parameter result in better
  77906. compression at the expense of memory usage. The default value is 15 if
  77907. deflateInit is used instead.
  77908. windowBits can also be -8..-15 for raw deflate. In this case, -windowBits
  77909. determines the window size. deflate() will then generate raw deflate data
  77910. with no zlib header or trailer, and will not compute an adler32 check value.
  77911. windowBits can also be greater than 15 for optional gzip encoding. Add
  77912. 16 to windowBits to write a simple gzip header and trailer around the
  77913. compressed data instead of a zlib wrapper. The gzip header will have no
  77914. file name, no extra data, no comment, no modification time (set to zero),
  77915. no header crc, and the operating system will be set to 255 (unknown). If a
  77916. gzip stream is being written, strm->adler is a crc32 instead of an adler32.
  77917. The memLevel parameter specifies how much memory should be allocated
  77918. for the internal compression state. memLevel=1 uses minimum memory but
  77919. is slow and reduces compression ratio; memLevel=9 uses maximum memory
  77920. for optimal speed. The default value is 8. See zconf.h for total memory
  77921. usage as a function of windowBits and memLevel.
  77922. The strategy parameter is used to tune the compression algorithm. Use the
  77923. value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
  77924. filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
  77925. string match), or Z_RLE to limit match distances to one (run-length
  77926. encoding). Filtered data consists mostly of small values with a somewhat
  77927. random distribution. In this case, the compression algorithm is tuned to
  77928. compress them better. The effect of Z_FILTERED is to force more Huffman
  77929. coding and less string matching; it is somewhat intermediate between
  77930. Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as
  77931. Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy
  77932. parameter only affects the compression ratio but not the correctness of the
  77933. compressed output even if it is not set appropriately. Z_FIXED prevents the
  77934. use of dynamic Huffman codes, allowing for a simpler decoder for special
  77935. applications.
  77936. deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  77937. memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
  77938. method). msg is set to null if there is no error message. deflateInit2 does
  77939. not perform any compression: this will be done by deflate().
  77940. */
  77941. ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
  77942. const Bytef *dictionary,
  77943. uInt dictLength));
  77944. /*
  77945. Initializes the compression dictionary from the given byte sequence
  77946. without producing any compressed output. This function must be called
  77947. immediately after deflateInit, deflateInit2 or deflateReset, before any
  77948. call of deflate. The compressor and decompressor must use exactly the same
  77949. dictionary (see inflateSetDictionary).
  77950. The dictionary should consist of strings (byte sequences) that are likely
  77951. to be encountered later in the data to be compressed, with the most commonly
  77952. used strings preferably put towards the end of the dictionary. Using a
  77953. dictionary is most useful when the data to be compressed is short and can be
  77954. predicted with good accuracy; the data can then be compressed better than
  77955. with the default empty dictionary.
  77956. Depending on the size of the compression data structures selected by
  77957. deflateInit or deflateInit2, a part of the dictionary may in effect be
  77958. discarded, for example if the dictionary is larger than the window size in
  77959. deflate or deflate2. Thus the strings most likely to be useful should be
  77960. put at the end of the dictionary, not at the front. In addition, the
  77961. current implementation of deflate will use at most the window size minus
  77962. 262 bytes of the provided dictionary.
  77963. Upon return of this function, strm->adler is set to the adler32 value
  77964. of the dictionary; the decompressor may later use this value to determine
  77965. which dictionary has been used by the compressor. (The adler32 value
  77966. applies to the whole dictionary even if only a subset of the dictionary is
  77967. actually used by the compressor.) If a raw deflate was requested, then the
  77968. adler32 value is not computed and strm->adler is not set.
  77969. deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
  77970. parameter is invalid (such as NULL dictionary) or the stream state is
  77971. inconsistent (for example if deflate has already been called for this stream
  77972. or if the compression method is bsort). deflateSetDictionary does not
  77973. perform any compression: this will be done by deflate().
  77974. */
  77975. ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
  77976. z_streamp source));
  77977. /*
  77978. Sets the destination stream as a complete copy of the source stream.
  77979. This function can be useful when several compression strategies will be
  77980. tried, for example when there are several ways of pre-processing the input
  77981. data with a filter. The streams that will be discarded should then be freed
  77982. by calling deflateEnd. Note that deflateCopy duplicates the internal
  77983. compression state which can be quite large, so this strategy is slow and
  77984. can consume lots of memory.
  77985. deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  77986. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  77987. (such as zalloc being NULL). msg is left unchanged in both source and
  77988. destination.
  77989. */
  77990. ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
  77991. /*
  77992. This function is equivalent to deflateEnd followed by deflateInit,
  77993. but does not free and reallocate all the internal compression state.
  77994. The stream will keep the same compression level and any other attributes
  77995. that may have been set by deflateInit2.
  77996. deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  77997. stream state was inconsistent (such as zalloc or state being NULL).
  77998. */
  77999. ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
  78000. int level,
  78001. int strategy));
  78002. /*
  78003. Dynamically update the compression level and compression strategy. The
  78004. interpretation of level and strategy is as in deflateInit2. This can be
  78005. used to switch between compression and straight copy of the input data, or
  78006. to switch to a different kind of input data requiring a different
  78007. strategy. If the compression level is changed, the input available so far
  78008. is compressed with the old level (and may be flushed); the new level will
  78009. take effect only at the next call of deflate().
  78010. Before the call of deflateParams, the stream state must be set as for
  78011. a call of deflate(), since the currently available input may have to
  78012. be compressed and flushed. In particular, strm->avail_out must be non-zero.
  78013. deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
  78014. stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
  78015. if strm->avail_out was zero.
  78016. */
  78017. ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
  78018. int good_length,
  78019. int max_lazy,
  78020. int nice_length,
  78021. int max_chain));
  78022. /*
  78023. Fine tune deflate's internal compression parameters. This should only be
  78024. used by someone who understands the algorithm used by zlib's deflate for
  78025. searching for the best matching string, and even then only by the most
  78026. fanatic optimizer trying to squeeze out the last compressed bit for their
  78027. specific input data. Read the deflate.c source code for the meaning of the
  78028. max_lazy, good_length, nice_length, and max_chain parameters.
  78029. deflateTune() can be called after deflateInit() or deflateInit2(), and
  78030. returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
  78031. */
  78032. ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
  78033. uLong sourceLen));
  78034. /*
  78035. deflateBound() returns an upper bound on the compressed size after
  78036. deflation of sourceLen bytes. It must be called after deflateInit()
  78037. or deflateInit2(). This would be used to allocate an output buffer
  78038. for deflation in a single pass, and so would be called before deflate().
  78039. */
  78040. ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
  78041. int bits,
  78042. int value));
  78043. /*
  78044. deflatePrime() inserts bits in the deflate output stream. The intent
  78045. is that this function is used to start off the deflate output with the
  78046. bits leftover from a previous deflate stream when appending to it. As such,
  78047. this function can only be used for raw deflate, and must be used before the
  78048. first deflate() call after a deflateInit2() or deflateReset(). bits must be
  78049. less than or equal to 16, and that many of the least significant bits of
  78050. value will be inserted in the output.
  78051. deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  78052. stream state was inconsistent.
  78053. */
  78054. ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
  78055. gz_headerp head));
  78056. /*
  78057. deflateSetHeader() provides gzip header information for when a gzip
  78058. stream is requested by deflateInit2(). deflateSetHeader() may be called
  78059. after deflateInit2() or deflateReset() and before the first call of
  78060. deflate(). The text, time, os, extra field, name, and comment information
  78061. in the provided gz_header structure are written to the gzip header (xflag is
  78062. ignored -- the extra flags are set according to the compression level). The
  78063. caller must assure that, if not Z_NULL, name and comment are terminated with
  78064. a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
  78065. available there. If hcrc is true, a gzip header crc is included. Note that
  78066. the current versions of the command-line version of gzip (up through version
  78067. 1.3.x) do not support header crc's, and will report that it is a "multi-part
  78068. gzip file" and give up.
  78069. If deflateSetHeader is not used, the default gzip header has text false,
  78070. the time set to zero, and os set to 255, with no extra, name, or comment
  78071. fields. The gzip header is returned to the default state by deflateReset().
  78072. deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  78073. stream state was inconsistent.
  78074. */
  78075. /*
  78076. ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
  78077. int windowBits));
  78078. This is another version of inflateInit with an extra parameter. The
  78079. fields next_in, avail_in, zalloc, zfree and opaque must be initialized
  78080. before by the caller.
  78081. The windowBits parameter is the base two logarithm of the maximum window
  78082. size (the size of the history buffer). It should be in the range 8..15 for
  78083. this version of the library. The default value is 15 if inflateInit is used
  78084. instead. windowBits must be greater than or equal to the windowBits value
  78085. provided to deflateInit2() while compressing, or it must be equal to 15 if
  78086. deflateInit2() was not used. If a compressed stream with a larger window
  78087. size is given as input, inflate() will return with the error code
  78088. Z_DATA_ERROR instead of trying to allocate a larger window.
  78089. windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
  78090. determines the window size. inflate() will then process raw deflate data,
  78091. not looking for a zlib or gzip header, not generating a check value, and not
  78092. looking for any check values for comparison at the end of the stream. This
  78093. is for use with other formats that use the deflate compressed data format
  78094. such as zip. Those formats provide their own check values. If a custom
  78095. format is developed using the raw deflate format for compressed data, it is
  78096. recommended that a check value such as an adler32 or a crc32 be applied to
  78097. the uncompressed data as is done in the zlib, gzip, and zip formats. For
  78098. most applications, the zlib format should be used as is. Note that comments
  78099. above on the use in deflateInit2() applies to the magnitude of windowBits.
  78100. windowBits can also be greater than 15 for optional gzip decoding. Add
  78101. 32 to windowBits to enable zlib and gzip decoding with automatic header
  78102. detection, or add 16 to decode only the gzip format (the zlib format will
  78103. return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is
  78104. a crc32 instead of an adler32.
  78105. inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78106. memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg
  78107. is set to null if there is no error message. inflateInit2 does not perform
  78108. any decompression apart from reading the zlib header if present: this will
  78109. be done by inflate(). (So next_in and avail_in may be modified, but next_out
  78110. and avail_out are unchanged.)
  78111. */
  78112. ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
  78113. const Bytef *dictionary,
  78114. uInt dictLength));
  78115. /*
  78116. Initializes the decompression dictionary from the given uncompressed byte
  78117. sequence. This function must be called immediately after a call of inflate,
  78118. if that call returned Z_NEED_DICT. The dictionary chosen by the compressor
  78119. can be determined from the adler32 value returned by that call of inflate.
  78120. The compressor and decompressor must use exactly the same dictionary (see
  78121. deflateSetDictionary). For raw inflate, this function can be called
  78122. immediately after inflateInit2() or inflateReset() and before any call of
  78123. inflate() to set the dictionary. The application must insure that the
  78124. dictionary that was used for compression is provided.
  78125. inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
  78126. parameter is invalid (such as NULL dictionary) or the stream state is
  78127. inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
  78128. expected one (incorrect adler32 value). inflateSetDictionary does not
  78129. perform any decompression: this will be done by subsequent calls of
  78130. inflate().
  78131. */
  78132. ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
  78133. /*
  78134. Skips invalid compressed data until a full flush point (see above the
  78135. description of deflate with Z_FULL_FLUSH) can be found, or until all
  78136. available input is skipped. No output is provided.
  78137. inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
  78138. if no more input was provided, Z_DATA_ERROR if no flush point has been found,
  78139. or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
  78140. case, the application may save the current current value of total_in which
  78141. indicates where valid compressed data was found. In the error case, the
  78142. application may repeatedly call inflateSync, providing more input each time,
  78143. until success or end of the input data.
  78144. */
  78145. ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
  78146. z_streamp source));
  78147. /*
  78148. Sets the destination stream as a complete copy of the source stream.
  78149. This function can be useful when randomly accessing a large stream. The
  78150. first pass through the stream can periodically record the inflate state,
  78151. allowing restarting inflate at those points when randomly accessing the
  78152. stream.
  78153. inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  78154. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  78155. (such as zalloc being NULL). msg is left unchanged in both source and
  78156. destination.
  78157. */
  78158. ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
  78159. /*
  78160. This function is equivalent to inflateEnd followed by inflateInit,
  78161. but does not free and reallocate all the internal decompression state.
  78162. The stream will keep attributes that may have been set by inflateInit2.
  78163. inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  78164. stream state was inconsistent (such as zalloc or state being NULL).
  78165. */
  78166. ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
  78167. int bits,
  78168. int value));
  78169. /*
  78170. This function inserts bits in the inflate input stream. The intent is
  78171. that this function is used to start inflating at a bit position in the
  78172. middle of a byte. The provided bits will be used before any bytes are used
  78173. from next_in. This function should only be used with raw inflate, and
  78174. should be used before the first inflate() call after inflateInit2() or
  78175. inflateReset(). bits must be less than or equal to 16, and that many of the
  78176. least significant bits of value will be inserted in the input.
  78177. inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  78178. stream state was inconsistent.
  78179. */
  78180. ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
  78181. gz_headerp head));
  78182. /*
  78183. inflateGetHeader() requests that gzip header information be stored in the
  78184. provided gz_header structure. inflateGetHeader() may be called after
  78185. inflateInit2() or inflateReset(), and before the first call of inflate().
  78186. As inflate() processes the gzip stream, head->done is zero until the header
  78187. is completed, at which time head->done is set to one. If a zlib stream is
  78188. being decoded, then head->done is set to -1 to indicate that there will be
  78189. no gzip header information forthcoming. Note that Z_BLOCK can be used to
  78190. force inflate() to return immediately after header processing is complete
  78191. and before any actual data is decompressed.
  78192. The text, time, xflags, and os fields are filled in with the gzip header
  78193. contents. hcrc is set to true if there is a header CRC. (The header CRC
  78194. was valid if done is set to one.) If extra is not Z_NULL, then extra_max
  78195. contains the maximum number of bytes to write to extra. Once done is true,
  78196. extra_len contains the actual extra field length, and extra contains the
  78197. extra field, or that field truncated if extra_max is less than extra_len.
  78198. If name is not Z_NULL, then up to name_max characters are written there,
  78199. terminated with a zero unless the length is greater than name_max. If
  78200. comment is not Z_NULL, then up to comm_max characters are written there,
  78201. terminated with a zero unless the length is greater than comm_max. When
  78202. any of extra, name, or comment are not Z_NULL and the respective field is
  78203. not present in the header, then that field is set to Z_NULL to signal its
  78204. absence. This allows the use of deflateSetHeader() with the returned
  78205. structure to duplicate the header. However if those fields are set to
  78206. allocated memory, then the application will need to save those pointers
  78207. elsewhere so that they can be eventually freed.
  78208. If inflateGetHeader is not used, then the header information is simply
  78209. discarded. The header is always checked for validity, including the header
  78210. CRC if present. inflateReset() will reset the process to discard the header
  78211. information. The application would need to call inflateGetHeader() again to
  78212. retrieve the header from the next gzip stream.
  78213. inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  78214. stream state was inconsistent.
  78215. */
  78216. /*
  78217. ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,
  78218. unsigned char FAR *window));
  78219. Initialize the internal stream state for decompression using inflateBack()
  78220. calls. The fields zalloc, zfree and opaque in strm must be initialized
  78221. before the call. If zalloc and zfree are Z_NULL, then the default library-
  78222. derived memory allocation routines are used. windowBits is the base two
  78223. logarithm of the window size, in the range 8..15. window is a caller
  78224. supplied buffer of that size. Except for special applications where it is
  78225. assured that deflate was used with small window sizes, windowBits must be 15
  78226. and a 32K byte window must be supplied to be able to decompress general
  78227. deflate streams.
  78228. See inflateBack() for the usage of these routines.
  78229. inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
  78230. the paramaters are invalid, Z_MEM_ERROR if the internal state could not
  78231. be allocated, or Z_VERSION_ERROR if the version of the library does not
  78232. match the version of the header file.
  78233. */
  78234. typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *));
  78235. typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
  78236. ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,
  78237. in_func in, void FAR *in_desc,
  78238. out_func out, void FAR *out_desc));
  78239. /*
  78240. inflateBack() does a raw inflate with a single call using a call-back
  78241. interface for input and output. This is more efficient than inflate() for
  78242. file i/o applications in that it avoids copying between the output and the
  78243. sliding window by simply making the window itself the output buffer. This
  78244. function trusts the application to not change the output buffer passed by
  78245. the output function, at least until inflateBack() returns.
  78246. inflateBackInit() must be called first to allocate the internal state
  78247. and to initialize the state with the user-provided window buffer.
  78248. inflateBack() may then be used multiple times to inflate a complete, raw
  78249. deflate stream with each call. inflateBackEnd() is then called to free
  78250. the allocated state.
  78251. A raw deflate stream is one with no zlib or gzip header or trailer.
  78252. This routine would normally be used in a utility that reads zip or gzip
  78253. files and writes out uncompressed files. The utility would decode the
  78254. header and process the trailer on its own, hence this routine expects
  78255. only the raw deflate stream to decompress. This is different from the
  78256. normal behavior of inflate(), which expects either a zlib or gzip header and
  78257. trailer around the deflate stream.
  78258. inflateBack() uses two subroutines supplied by the caller that are then
  78259. called by inflateBack() for input and output. inflateBack() calls those
  78260. routines until it reads a complete deflate stream and writes out all of the
  78261. uncompressed data, or until it encounters an error. The function's
  78262. parameters and return types are defined above in the in_func and out_func
  78263. typedefs. inflateBack() will call in(in_desc, &buf) which should return the
  78264. number of bytes of provided input, and a pointer to that input in buf. If
  78265. there is no input available, in() must return zero--buf is ignored in that
  78266. case--and inflateBack() will return a buffer error. inflateBack() will call
  78267. out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out()
  78268. should return zero on success, or non-zero on failure. If out() returns
  78269. non-zero, inflateBack() will return with an error. Neither in() nor out()
  78270. are permitted to change the contents of the window provided to
  78271. inflateBackInit(), which is also the buffer that out() uses to write from.
  78272. The length written by out() will be at most the window size. Any non-zero
  78273. amount of input may be provided by in().
  78274. For convenience, inflateBack() can be provided input on the first call by
  78275. setting strm->next_in and strm->avail_in. If that input is exhausted, then
  78276. in() will be called. Therefore strm->next_in must be initialized before
  78277. calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called
  78278. immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in
  78279. must also be initialized, and then if strm->avail_in is not zero, input will
  78280. initially be taken from strm->next_in[0 .. strm->avail_in - 1].
  78281. The in_desc and out_desc parameters of inflateBack() is passed as the
  78282. first parameter of in() and out() respectively when they are called. These
  78283. descriptors can be optionally used to pass any information that the caller-
  78284. supplied in() and out() functions need to do their job.
  78285. On return, inflateBack() will set strm->next_in and strm->avail_in to
  78286. pass back any unused input that was provided by the last in() call. The
  78287. return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
  78288. if in() or out() returned an error, Z_DATA_ERROR if there was a format
  78289. error in the deflate stream (in which case strm->msg is set to indicate the
  78290. nature of the error), or Z_STREAM_ERROR if the stream was not properly
  78291. initialized. In the case of Z_BUF_ERROR, an input or output error can be
  78292. distinguished using strm->next_in which will be Z_NULL only if in() returned
  78293. an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to
  78294. out() returning non-zero. (in() will always be called before out(), so
  78295. strm->next_in is assured to be defined if out() returns non-zero.) Note
  78296. that inflateBack() cannot return Z_OK.
  78297. */
  78298. ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
  78299. /*
  78300. All memory allocated by inflateBackInit() is freed.
  78301. inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
  78302. state was inconsistent.
  78303. */
  78304. //ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));
  78305. /* Return flags indicating compile-time options.
  78306. Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
  78307. 1.0: size of uInt
  78308. 3.2: size of uLong
  78309. 5.4: size of voidpf (pointer)
  78310. 7.6: size of z_off_t
  78311. Compiler, assembler, and debug options:
  78312. 8: DEBUG
  78313. 9: ASMV or ASMINF -- use ASM code
  78314. 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
  78315. 11: 0 (reserved)
  78316. One-time table building (smaller code, but not thread-safe if true):
  78317. 12: BUILDFIXED -- build static block decoding tables when needed
  78318. 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
  78319. 14,15: 0 (reserved)
  78320. Library content (indicates missing functionality):
  78321. 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
  78322. deflate code when not needed)
  78323. 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
  78324. and decode gzip streams (to avoid linking crc code)
  78325. 18-19: 0 (reserved)
  78326. Operation variations (changes in library functionality):
  78327. 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
  78328. 21: FASTEST -- deflate algorithm with only one, lowest compression level
  78329. 22,23: 0 (reserved)
  78330. The sprintf variant used by gzprintf (zero is best):
  78331. 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
  78332. 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
  78333. 26: 0 = returns value, 1 = void -- 1 means inferred string length returned
  78334. Remainder:
  78335. 27-31: 0 (reserved)
  78336. */
  78337. /* utility functions */
  78338. /*
  78339. The following utility functions are implemented on top of the
  78340. basic stream-oriented functions. To simplify the interface, some
  78341. default options are assumed (compression level and memory usage,
  78342. standard memory allocation functions). The source code of these
  78343. utility functions can easily be modified if you need special options.
  78344. */
  78345. ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen,
  78346. const Bytef *source, uLong sourceLen));
  78347. /*
  78348. Compresses the source buffer into the destination buffer. sourceLen is
  78349. the byte length of the source buffer. Upon entry, destLen is the total
  78350. size of the destination buffer, which must be at least the value returned
  78351. by compressBound(sourceLen). Upon exit, destLen is the actual size of the
  78352. compressed buffer.
  78353. This function can be used to compress a whole file at once if the
  78354. input file is mmap'ed.
  78355. compress returns Z_OK if success, Z_MEM_ERROR if there was not
  78356. enough memory, Z_BUF_ERROR if there was not enough room in the output
  78357. buffer.
  78358. */
  78359. ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen,
  78360. const Bytef *source, uLong sourceLen,
  78361. int level));
  78362. /*
  78363. Compresses the source buffer into the destination buffer. The level
  78364. parameter has the same meaning as in deflateInit. sourceLen is the byte
  78365. length of the source buffer. Upon entry, destLen is the total size of the
  78366. destination buffer, which must be at least the value returned by
  78367. compressBound(sourceLen). Upon exit, destLen is the actual size of the
  78368. compressed buffer.
  78369. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78370. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  78371. Z_STREAM_ERROR if the level parameter is invalid.
  78372. */
  78373. ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
  78374. /*
  78375. compressBound() returns an upper bound on the compressed size after
  78376. compress() or compress2() on sourceLen bytes. It would be used before
  78377. a compress() or compress2() call to allocate the destination buffer.
  78378. */
  78379. ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen,
  78380. const Bytef *source, uLong sourceLen));
  78381. /*
  78382. Decompresses the source buffer into the destination buffer. sourceLen is
  78383. the byte length of the source buffer. Upon entry, destLen is the total
  78384. size of the destination buffer, which must be large enough to hold the
  78385. entire uncompressed data. (The size of the uncompressed data must have
  78386. been saved previously by the compressor and transmitted to the decompressor
  78387. by some mechanism outside the scope of this compression library.)
  78388. Upon exit, destLen is the actual size of the compressed buffer.
  78389. This function can be used to decompress a whole file at once if the
  78390. input file is mmap'ed.
  78391. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
  78392. enough memory, Z_BUF_ERROR if there was not enough room in the output
  78393. buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.
  78394. */
  78395. typedef voidp gzFile;
  78396. ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
  78397. /*
  78398. Opens a gzip (.gz) file for reading or writing. The mode parameter
  78399. is as in fopen ("rb" or "wb") but can also include a compression level
  78400. ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
  78401. Huffman only compression as in "wb1h", or 'R' for run-length encoding
  78402. as in "wb1R". (See the description of deflateInit2 for more information
  78403. about the strategy parameter.)
  78404. gzopen can be used to read a file which is not in gzip format; in this
  78405. case gzread will directly read from the file without decompression.
  78406. gzopen returns NULL if the file could not be opened or if there was
  78407. insufficient memory to allocate the (de)compression state; errno
  78408. can be checked to distinguish the two cases (if errno is zero, the
  78409. zlib error is Z_MEM_ERROR). */
  78410. ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
  78411. /*
  78412. gzdopen() associates a gzFile with the file descriptor fd. File
  78413. descriptors are obtained from calls like open, dup, creat, pipe or
  78414. fileno (in the file has been previously opened with fopen).
  78415. The mode parameter is as in gzopen.
  78416. The next call of gzclose on the returned gzFile will also close the
  78417. file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
  78418. descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
  78419. gzdopen returns NULL if there was insufficient memory to allocate
  78420. the (de)compression state.
  78421. */
  78422. ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
  78423. /*
  78424. Dynamically update the compression level or strategy. See the description
  78425. of deflateInit2 for the meaning of these parameters.
  78426. gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
  78427. opened for writing.
  78428. */
  78429. ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
  78430. /*
  78431. Reads the given number of uncompressed bytes from the compressed file.
  78432. If the input file was not in gzip format, gzread copies the given number
  78433. of bytes into the buffer.
  78434. gzread returns the number of uncompressed bytes actually read (0 for
  78435. end of file, -1 for error). */
  78436. ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
  78437. voidpc buf, unsigned len));
  78438. /*
  78439. Writes the given number of uncompressed bytes into the compressed file.
  78440. gzwrite returns the number of uncompressed bytes actually written
  78441. (0 in case of error).
  78442. */
  78443. ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...));
  78444. /*
  78445. Converts, formats, and writes the args to the compressed file under
  78446. control of the format string, as in fprintf. gzprintf returns the number of
  78447. uncompressed bytes actually written (0 in case of error). The number of
  78448. uncompressed bytes written is limited to 4095. The caller should assure that
  78449. this limit is not exceeded. If it is exceeded, then gzprintf() will return
  78450. return an error (0) with nothing written. In this case, there may also be a
  78451. buffer overflow with unpredictable consequences, which is possible only if
  78452. zlib was compiled with the insecure functions sprintf() or vsprintf()
  78453. because the secure snprintf() or vsnprintf() functions were not available.
  78454. */
  78455. ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
  78456. /*
  78457. Writes the given null-terminated string to the compressed file, excluding
  78458. the terminating null character.
  78459. gzputs returns the number of characters written, or -1 in case of error.
  78460. */
  78461. ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
  78462. /*
  78463. Reads bytes from the compressed file until len-1 characters are read, or
  78464. a newline character is read and transferred to buf, or an end-of-file
  78465. condition is encountered. The string is then terminated with a null
  78466. character.
  78467. gzgets returns buf, or Z_NULL in case of error.
  78468. */
  78469. ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
  78470. /*
  78471. Writes c, converted to an unsigned char, into the compressed file.
  78472. gzputc returns the value that was written, or -1 in case of error.
  78473. */
  78474. ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
  78475. /*
  78476. Reads one byte from the compressed file. gzgetc returns this byte
  78477. or -1 in case of end of file or error.
  78478. */
  78479. ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));
  78480. /*
  78481. Push one character back onto the stream to be read again later.
  78482. Only one character of push-back is allowed. gzungetc() returns the
  78483. character pushed, or -1 on failure. gzungetc() will fail if a
  78484. character has been pushed but not read yet, or if c is -1. The pushed
  78485. character will be discarded if the stream is repositioned with gzseek()
  78486. or gzrewind().
  78487. */
  78488. ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
  78489. /*
  78490. Flushes all pending output into the compressed file. The parameter
  78491. flush is as in the deflate() function. The return value is the zlib
  78492. error number (see function gzerror below). gzflush returns Z_OK if
  78493. the flush parameter is Z_FINISH and all output could be flushed.
  78494. gzflush should be called only when strictly necessary because it can
  78495. degrade compression.
  78496. */
  78497. ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
  78498. z_off_t offset, int whence));
  78499. /*
  78500. Sets the starting position for the next gzread or gzwrite on the
  78501. given compressed file. The offset represents a number of bytes in the
  78502. uncompressed data stream. The whence parameter is defined as in lseek(2);
  78503. the value SEEK_END is not supported.
  78504. If the file is opened for reading, this function is emulated but can be
  78505. extremely slow. If the file is opened for writing, only forward seeks are
  78506. supported; gzseek then compresses a sequence of zeroes up to the new
  78507. starting position.
  78508. gzseek returns the resulting offset location as measured in bytes from
  78509. the beginning of the uncompressed stream, or -1 in case of error, in
  78510. particular if the file is opened for writing and the new starting position
  78511. would be before the current position.
  78512. */
  78513. ZEXTERN int ZEXPORT gzrewind OF((gzFile file));
  78514. /*
  78515. Rewinds the given file. This function is supported only for reading.
  78516. gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
  78517. */
  78518. ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file));
  78519. /*
  78520. Returns the starting position for the next gzread or gzwrite on the
  78521. given compressed file. This position represents a number of bytes in the
  78522. uncompressed data stream.
  78523. gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
  78524. */
  78525. ZEXTERN int ZEXPORT gzeof OF((gzFile file));
  78526. /*
  78527. Returns 1 when EOF has previously been detected reading the given
  78528. input stream, otherwise zero.
  78529. */
  78530. ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
  78531. /*
  78532. Returns 1 if file is being read directly without decompression, otherwise
  78533. zero.
  78534. */
  78535. ZEXTERN int ZEXPORT gzclose OF((gzFile file));
  78536. /*
  78537. Flushes all pending output if necessary, closes the compressed file
  78538. and deallocates all the (de)compression state. The return value is the zlib
  78539. error number (see function gzerror below).
  78540. */
  78541. ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
  78542. /*
  78543. Returns the error message for the last error which occurred on the
  78544. given compressed file. errnum is set to zlib error number. If an
  78545. error occurred in the file system and not in the compression library,
  78546. errnum is set to Z_ERRNO and the application may consult errno
  78547. to get the exact error code.
  78548. */
  78549. ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
  78550. /*
  78551. Clears the error and end-of-file flags for file. This is analogous to the
  78552. clearerr() function in stdio. This is useful for continuing to read a gzip
  78553. file that is being written concurrently.
  78554. */
  78555. /* checksum functions */
  78556. /*
  78557. These functions are not related to compression but are exported
  78558. anyway because they might be useful in applications using the
  78559. compression library.
  78560. */
  78561. ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
  78562. /*
  78563. Update a running Adler-32 checksum with the bytes buf[0..len-1] and
  78564. return the updated checksum. If buf is NULL, this function returns
  78565. the required initial value for the checksum.
  78566. An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
  78567. much faster. Usage example:
  78568. uLong adler = adler32(0L, Z_NULL, 0);
  78569. while (read_buffer(buffer, length) != EOF) {
  78570. adler = adler32(adler, buffer, length);
  78571. }
  78572. if (adler != original_adler) error();
  78573. */
  78574. ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
  78575. z_off_t len2));
  78576. /*
  78577. Combine two Adler-32 checksums into one. For two sequences of bytes, seq1
  78578. and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
  78579. each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of
  78580. seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.
  78581. */
  78582. ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len));
  78583. /*
  78584. Update a running CRC-32 with the bytes buf[0..len-1] and return the
  78585. updated CRC-32. If buf is NULL, this function returns the required initial
  78586. value for the for the crc. Pre- and post-conditioning (one's complement) is
  78587. performed within this function so it shouldn't be done by the application.
  78588. Usage example:
  78589. uLong crc = crc32(0L, Z_NULL, 0);
  78590. while (read_buffer(buffer, length) != EOF) {
  78591. crc = crc32(crc, buffer, length);
  78592. }
  78593. if (crc != original_crc) error();
  78594. */
  78595. ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
  78596. /*
  78597. Combine two CRC-32 check values into one. For two sequences of bytes,
  78598. seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
  78599. calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32
  78600. check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
  78601. len2.
  78602. */
  78603. /* various hacks, don't look :) */
  78604. /* deflateInit and inflateInit are macros to allow checking the zlib version
  78605. * and the compiler's view of z_stream:
  78606. */
  78607. ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
  78608. const char *version, int stream_size));
  78609. ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
  78610. const char *version, int stream_size));
  78611. ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method,
  78612. int windowBits, int memLevel,
  78613. int strategy, const char *version,
  78614. int stream_size));
  78615. ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits,
  78616. const char *version, int stream_size));
  78617. ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,
  78618. unsigned char FAR *window,
  78619. const char *version,
  78620. int stream_size));
  78621. #define deflateInit(strm, level) \
  78622. deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream))
  78623. #define inflateInit(strm) \
  78624. inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream))
  78625. #define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
  78626. deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
  78627. (strategy), ZLIB_VERSION, sizeof(z_stream))
  78628. #define inflateInit2(strm, windowBits) \
  78629. inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
  78630. #define inflateBackInit(strm, windowBits, window) \
  78631. inflateBackInit_((strm), (windowBits), (window), \
  78632. ZLIB_VERSION, sizeof(z_stream))
  78633. #if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
  78634. struct internal_state {int dummy;}; /* hack for buggy compilers */
  78635. #endif
  78636. ZEXTERN const char * ZEXPORT zError OF((int));
  78637. ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z));
  78638. ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void));
  78639. #ifdef __cplusplus
  78640. }
  78641. #endif
  78642. #endif /* ZLIB_H */
  78643. /*** End of inlined file: zlib.h ***/
  78644. #undef OS_CODE
  78645. #else
  78646. #include <zlib.h>
  78647. #endif
  78648. }
  78649. BEGIN_JUCE_NAMESPACE
  78650. // internal helper object that holds the zlib structures so they don't have to be
  78651. // included publicly.
  78652. class GZIPCompressorHelper
  78653. {
  78654. public:
  78655. GZIPCompressorHelper (const int compressionLevel, const bool nowrap)
  78656. : data (0),
  78657. dataSize (0),
  78658. compLevel (compressionLevel),
  78659. strategy (0),
  78660. setParams (true),
  78661. streamIsValid (false),
  78662. finished (false),
  78663. shouldFinish (false)
  78664. {
  78665. using namespace zlibNamespace;
  78666. zerostruct (stream);
  78667. streamIsValid = (deflateInit2 (&stream, compLevel, Z_DEFLATED,
  78668. nowrap ? -MAX_WBITS : MAX_WBITS,
  78669. 8, strategy) == Z_OK);
  78670. }
  78671. ~GZIPCompressorHelper()
  78672. {
  78673. using namespace zlibNamespace;
  78674. if (streamIsValid)
  78675. deflateEnd (&stream);
  78676. }
  78677. bool needsInput() const throw()
  78678. {
  78679. return dataSize <= 0;
  78680. }
  78681. void setInput (const uint8* const newData, const int size) throw()
  78682. {
  78683. data = newData;
  78684. dataSize = size;
  78685. }
  78686. int doNextBlock (uint8* const dest, const int destSize) throw()
  78687. {
  78688. using namespace zlibNamespace;
  78689. if (streamIsValid)
  78690. {
  78691. stream.next_in = const_cast <uint8*> (data);
  78692. stream.next_out = dest;
  78693. stream.avail_in = dataSize;
  78694. stream.avail_out = destSize;
  78695. const int result = setParams ? deflateParams (&stream, compLevel, strategy)
  78696. : deflate (&stream, shouldFinish ? Z_FINISH : Z_NO_FLUSH);
  78697. setParams = false;
  78698. switch (result)
  78699. {
  78700. case Z_STREAM_END:
  78701. finished = true;
  78702. // Deliberate fall-through..
  78703. case Z_OK:
  78704. data += dataSize - stream.avail_in;
  78705. dataSize = stream.avail_in;
  78706. return destSize - stream.avail_out;
  78707. default:
  78708. break;
  78709. }
  78710. }
  78711. return 0;
  78712. }
  78713. private:
  78714. zlibNamespace::z_stream stream;
  78715. const uint8* data;
  78716. int dataSize, compLevel, strategy;
  78717. bool setParams, streamIsValid;
  78718. public:
  78719. bool finished, shouldFinish;
  78720. };
  78721. const int gzipCompBufferSize = 32768;
  78722. GZIPCompressorOutputStream::GZIPCompressorOutputStream (OutputStream* const destStream_,
  78723. int compressionLevel,
  78724. const bool deleteDestStream,
  78725. const bool noWrap)
  78726. : destStream (destStream_),
  78727. streamToDelete (deleteDestStream ? destStream_ : 0),
  78728. buffer (gzipCompBufferSize)
  78729. {
  78730. if (compressionLevel < 1 || compressionLevel > 9)
  78731. compressionLevel = -1;
  78732. helper = new GZIPCompressorHelper (compressionLevel, noWrap);
  78733. }
  78734. GZIPCompressorOutputStream::~GZIPCompressorOutputStream()
  78735. {
  78736. flush();
  78737. }
  78738. void GZIPCompressorOutputStream::flush()
  78739. {
  78740. if (! helper->finished)
  78741. {
  78742. helper->shouldFinish = true;
  78743. while (! helper->finished)
  78744. doNextBlock();
  78745. }
  78746. destStream->flush();
  78747. }
  78748. bool GZIPCompressorOutputStream::write (const void* destBuffer, int howMany)
  78749. {
  78750. if (! helper->finished)
  78751. {
  78752. helper->setInput (static_cast <const uint8*> (destBuffer), howMany);
  78753. while (! helper->needsInput())
  78754. {
  78755. if (! doNextBlock())
  78756. return false;
  78757. }
  78758. }
  78759. return true;
  78760. }
  78761. bool GZIPCompressorOutputStream::doNextBlock()
  78762. {
  78763. const int len = helper->doNextBlock (buffer, gzipCompBufferSize);
  78764. if (len > 0)
  78765. return destStream->write (buffer, len);
  78766. else
  78767. return true;
  78768. }
  78769. int64 GZIPCompressorOutputStream::getPosition()
  78770. {
  78771. return destStream->getPosition();
  78772. }
  78773. bool GZIPCompressorOutputStream::setPosition (int64 /*newPosition*/)
  78774. {
  78775. jassertfalse; // can't do it!
  78776. return false;
  78777. }
  78778. END_JUCE_NAMESPACE
  78779. /*** End of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  78780. /*** Start of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  78781. #if JUCE_MSVC
  78782. #pragma warning (push)
  78783. #pragma warning (disable: 4309 4305)
  78784. #endif
  78785. namespace zlibNamespace
  78786. {
  78787. #if JUCE_INCLUDE_ZLIB_CODE
  78788. extern "C"
  78789. {
  78790. #undef OS_CODE
  78791. #undef fdopen
  78792. #define ZLIB_INTERNAL
  78793. #define NO_DUMMY_DECL
  78794. /*** Start of inlined file: adler32.c ***/
  78795. /* @(#) $Id: adler32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  78796. #define ZLIB_INTERNAL
  78797. #define BASE 65521UL /* largest prime smaller than 65536 */
  78798. #define NMAX 5552
  78799. /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
  78800. #define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;}
  78801. #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
  78802. #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
  78803. #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
  78804. #define DO16(buf) DO8(buf,0); DO8(buf,8);
  78805. /* use NO_DIVIDE if your processor does not do division in hardware */
  78806. #ifdef NO_DIVIDE
  78807. # define MOD(a) \
  78808. do { \
  78809. if (a >= (BASE << 16)) a -= (BASE << 16); \
  78810. if (a >= (BASE << 15)) a -= (BASE << 15); \
  78811. if (a >= (BASE << 14)) a -= (BASE << 14); \
  78812. if (a >= (BASE << 13)) a -= (BASE << 13); \
  78813. if (a >= (BASE << 12)) a -= (BASE << 12); \
  78814. if (a >= (BASE << 11)) a -= (BASE << 11); \
  78815. if (a >= (BASE << 10)) a -= (BASE << 10); \
  78816. if (a >= (BASE << 9)) a -= (BASE << 9); \
  78817. if (a >= (BASE << 8)) a -= (BASE << 8); \
  78818. if (a >= (BASE << 7)) a -= (BASE << 7); \
  78819. if (a >= (BASE << 6)) a -= (BASE << 6); \
  78820. if (a >= (BASE << 5)) a -= (BASE << 5); \
  78821. if (a >= (BASE << 4)) a -= (BASE << 4); \
  78822. if (a >= (BASE << 3)) a -= (BASE << 3); \
  78823. if (a >= (BASE << 2)) a -= (BASE << 2); \
  78824. if (a >= (BASE << 1)) a -= (BASE << 1); \
  78825. if (a >= BASE) a -= BASE; \
  78826. } while (0)
  78827. # define MOD4(a) \
  78828. do { \
  78829. if (a >= (BASE << 4)) a -= (BASE << 4); \
  78830. if (a >= (BASE << 3)) a -= (BASE << 3); \
  78831. if (a >= (BASE << 2)) a -= (BASE << 2); \
  78832. if (a >= (BASE << 1)) a -= (BASE << 1); \
  78833. if (a >= BASE) a -= BASE; \
  78834. } while (0)
  78835. #else
  78836. # define MOD(a) a %= BASE
  78837. # define MOD4(a) a %= BASE
  78838. #endif
  78839. /* ========================================================================= */
  78840. uLong ZEXPORT adler32(uLong adler, const Bytef *buf, uInt len)
  78841. {
  78842. unsigned long sum2;
  78843. unsigned n;
  78844. /* split Adler-32 into component sums */
  78845. sum2 = (adler >> 16) & 0xffff;
  78846. adler &= 0xffff;
  78847. /* in case user likes doing a byte at a time, keep it fast */
  78848. if (len == 1) {
  78849. adler += buf[0];
  78850. if (adler >= BASE)
  78851. adler -= BASE;
  78852. sum2 += adler;
  78853. if (sum2 >= BASE)
  78854. sum2 -= BASE;
  78855. return adler | (sum2 << 16);
  78856. }
  78857. /* initial Adler-32 value (deferred check for len == 1 speed) */
  78858. if (buf == Z_NULL)
  78859. return 1L;
  78860. /* in case short lengths are provided, keep it somewhat fast */
  78861. if (len < 16) {
  78862. while (len--) {
  78863. adler += *buf++;
  78864. sum2 += adler;
  78865. }
  78866. if (adler >= BASE)
  78867. adler -= BASE;
  78868. MOD4(sum2); /* only added so many BASE's */
  78869. return adler | (sum2 << 16);
  78870. }
  78871. /* do length NMAX blocks -- requires just one modulo operation */
  78872. while (len >= NMAX) {
  78873. len -= NMAX;
  78874. n = NMAX / 16; /* NMAX is divisible by 16 */
  78875. do {
  78876. DO16(buf); /* 16 sums unrolled */
  78877. buf += 16;
  78878. } while (--n);
  78879. MOD(adler);
  78880. MOD(sum2);
  78881. }
  78882. /* do remaining bytes (less than NMAX, still just one modulo) */
  78883. if (len) { /* avoid modulos if none remaining */
  78884. while (len >= 16) {
  78885. len -= 16;
  78886. DO16(buf);
  78887. buf += 16;
  78888. }
  78889. while (len--) {
  78890. adler += *buf++;
  78891. sum2 += adler;
  78892. }
  78893. MOD(adler);
  78894. MOD(sum2);
  78895. }
  78896. /* return recombined sums */
  78897. return adler | (sum2 << 16);
  78898. }
  78899. /* ========================================================================= */
  78900. uLong ZEXPORT adler32_combine(uLong adler1, uLong adler2, z_off_t len2)
  78901. {
  78902. unsigned long sum1;
  78903. unsigned long sum2;
  78904. unsigned rem;
  78905. /* the derivation of this formula is left as an exercise for the reader */
  78906. rem = (unsigned)(len2 % BASE);
  78907. sum1 = adler1 & 0xffff;
  78908. sum2 = rem * sum1;
  78909. MOD(sum2);
  78910. sum1 += (adler2 & 0xffff) + BASE - 1;
  78911. sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
  78912. if (sum1 > BASE) sum1 -= BASE;
  78913. if (sum1 > BASE) sum1 -= BASE;
  78914. if (sum2 > (BASE << 1)) sum2 -= (BASE << 1);
  78915. if (sum2 > BASE) sum2 -= BASE;
  78916. return sum1 | (sum2 << 16);
  78917. }
  78918. /*** End of inlined file: adler32.c ***/
  78919. /*** Start of inlined file: compress.c ***/
  78920. /* @(#) $Id: compress.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  78921. #define ZLIB_INTERNAL
  78922. /* ===========================================================================
  78923. Compresses the source buffer into the destination buffer. The level
  78924. parameter has the same meaning as in deflateInit. sourceLen is the byte
  78925. length of the source buffer. Upon entry, destLen is the total size of the
  78926. destination buffer, which must be at least 0.1% larger than sourceLen plus
  78927. 12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
  78928. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78929. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  78930. Z_STREAM_ERROR if the level parameter is invalid.
  78931. */
  78932. int ZEXPORT compress2 (Bytef *dest, uLongf *destLen, const Bytef *source,
  78933. uLong sourceLen, int level)
  78934. {
  78935. z_stream stream;
  78936. int err;
  78937. stream.next_in = (Bytef*)source;
  78938. stream.avail_in = (uInt)sourceLen;
  78939. #ifdef MAXSEG_64K
  78940. /* Check for source > 64K on 16-bit machine: */
  78941. if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
  78942. #endif
  78943. stream.next_out = dest;
  78944. stream.avail_out = (uInt)*destLen;
  78945. if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
  78946. stream.zalloc = (alloc_func)0;
  78947. stream.zfree = (free_func)0;
  78948. stream.opaque = (voidpf)0;
  78949. err = deflateInit(&stream, level);
  78950. if (err != Z_OK) return err;
  78951. err = deflate(&stream, Z_FINISH);
  78952. if (err != Z_STREAM_END) {
  78953. deflateEnd(&stream);
  78954. return err == Z_OK ? Z_BUF_ERROR : err;
  78955. }
  78956. *destLen = stream.total_out;
  78957. err = deflateEnd(&stream);
  78958. return err;
  78959. }
  78960. /* ===========================================================================
  78961. */
  78962. int ZEXPORT compress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)
  78963. {
  78964. return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
  78965. }
  78966. /* ===========================================================================
  78967. If the default memLevel or windowBits for deflateInit() is changed, then
  78968. this function needs to be updated.
  78969. */
  78970. uLong ZEXPORT compressBound (uLong sourceLen)
  78971. {
  78972. return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11;
  78973. }
  78974. /*** End of inlined file: compress.c ***/
  78975. #undef DO1
  78976. #undef DO8
  78977. /*** Start of inlined file: crc32.c ***/
  78978. /* @(#) $Id: crc32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  78979. /*
  78980. Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
  78981. protection on the static variables used to control the first-use generation
  78982. of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should
  78983. first call get_crc_table() to initialize the tables before allowing more than
  78984. one thread to use crc32().
  78985. */
  78986. #ifdef MAKECRCH
  78987. # include <stdio.h>
  78988. # ifndef DYNAMIC_CRC_TABLE
  78989. # define DYNAMIC_CRC_TABLE
  78990. # endif /* !DYNAMIC_CRC_TABLE */
  78991. #endif /* MAKECRCH */
  78992. /*** Start of inlined file: zutil.h ***/
  78993. /* WARNING: this file should *not* be used by applications. It is
  78994. part of the implementation of the compression library and is
  78995. subject to change. Applications should only use zlib.h.
  78996. */
  78997. /* @(#) $Id: zutil.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  78998. #ifndef ZUTIL_H
  78999. #define ZUTIL_H
  79000. #define ZLIB_INTERNAL
  79001. #ifdef STDC
  79002. # ifndef _WIN32_WCE
  79003. # include <stddef.h>
  79004. # endif
  79005. # include <string.h>
  79006. # include <stdlib.h>
  79007. #endif
  79008. #ifdef NO_ERRNO_H
  79009. # ifdef _WIN32_WCE
  79010. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  79011. * errno. We define it as a global variable to simplify porting.
  79012. * Its value is always 0 and should not be used. We rename it to
  79013. * avoid conflict with other libraries that use the same workaround.
  79014. */
  79015. # define errno z_errno
  79016. # endif
  79017. extern int errno;
  79018. #else
  79019. # ifndef _WIN32_WCE
  79020. # include <errno.h>
  79021. # endif
  79022. #endif
  79023. #ifndef local
  79024. # define local static
  79025. #endif
  79026. /* compile with -Dlocal if your debugger can't find static symbols */
  79027. typedef unsigned char uch;
  79028. typedef uch FAR uchf;
  79029. typedef unsigned short ush;
  79030. typedef ush FAR ushf;
  79031. typedef unsigned long ulg;
  79032. extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
  79033. /* (size given to avoid silly warnings with Visual C++) */
  79034. #define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
  79035. #define ERR_RETURN(strm,err) \
  79036. return (strm->msg = (char*)ERR_MSG(err), (err))
  79037. /* To be used only when the state is known to be valid */
  79038. /* common constants */
  79039. #ifndef DEF_WBITS
  79040. # define DEF_WBITS MAX_WBITS
  79041. #endif
  79042. /* default windowBits for decompression. MAX_WBITS is for compression only */
  79043. #if MAX_MEM_LEVEL >= 8
  79044. # define DEF_MEM_LEVEL 8
  79045. #else
  79046. # define DEF_MEM_LEVEL MAX_MEM_LEVEL
  79047. #endif
  79048. /* default memLevel */
  79049. #define STORED_BLOCK 0
  79050. #define STATIC_TREES 1
  79051. #define DYN_TREES 2
  79052. /* The three kinds of block type */
  79053. #define MIN_MATCH 3
  79054. #define MAX_MATCH 258
  79055. /* The minimum and maximum match lengths */
  79056. #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
  79057. /* target dependencies */
  79058. #if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
  79059. # define OS_CODE 0x00
  79060. # if defined(__TURBOC__) || defined(__BORLANDC__)
  79061. # if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
  79062. /* Allow compilation with ANSI keywords only enabled */
  79063. void _Cdecl farfree( void *block );
  79064. void *_Cdecl farmalloc( unsigned long nbytes );
  79065. # else
  79066. # include <alloc.h>
  79067. # endif
  79068. # else /* MSC or DJGPP */
  79069. # include <malloc.h>
  79070. # endif
  79071. #endif
  79072. #ifdef AMIGA
  79073. # define OS_CODE 0x01
  79074. #endif
  79075. #if defined(VAXC) || defined(VMS)
  79076. # define OS_CODE 0x02
  79077. # define F_OPEN(name, mode) \
  79078. fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
  79079. #endif
  79080. #if defined(ATARI) || defined(atarist)
  79081. # define OS_CODE 0x05
  79082. #endif
  79083. #ifdef OS2
  79084. # define OS_CODE 0x06
  79085. # ifdef M_I86
  79086. #include <malloc.h>
  79087. # endif
  79088. #endif
  79089. #if defined(MACOS) || TARGET_OS_MAC
  79090. # define OS_CODE 0x07
  79091. # if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
  79092. # include <unix.h> /* for fdopen */
  79093. # else
  79094. # ifndef fdopen
  79095. # define fdopen(fd,mode) NULL /* No fdopen() */
  79096. # endif
  79097. # endif
  79098. #endif
  79099. #ifdef TOPS20
  79100. # define OS_CODE 0x0a
  79101. #endif
  79102. #ifdef WIN32
  79103. # ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */
  79104. # define OS_CODE 0x0b
  79105. # endif
  79106. #endif
  79107. #ifdef __50SERIES /* Prime/PRIMOS */
  79108. # define OS_CODE 0x0f
  79109. #endif
  79110. #if defined(_BEOS_) || defined(RISCOS)
  79111. # define fdopen(fd,mode) NULL /* No fdopen() */
  79112. #endif
  79113. #if (defined(_MSC_VER) && (_MSC_VER > 600))
  79114. # if defined(_WIN32_WCE)
  79115. # define fdopen(fd,mode) NULL /* No fdopen() */
  79116. # ifndef _PTRDIFF_T_DEFINED
  79117. typedef int ptrdiff_t;
  79118. # define _PTRDIFF_T_DEFINED
  79119. # endif
  79120. # else
  79121. # define fdopen(fd,type) _fdopen(fd,type)
  79122. # endif
  79123. #endif
  79124. /* common defaults */
  79125. #ifndef OS_CODE
  79126. # define OS_CODE 0x03 /* assume Unix */
  79127. #endif
  79128. #ifndef F_OPEN
  79129. # define F_OPEN(name, mode) fopen((name), (mode))
  79130. #endif
  79131. /* functions */
  79132. #if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
  79133. # ifndef HAVE_VSNPRINTF
  79134. # define HAVE_VSNPRINTF
  79135. # endif
  79136. #endif
  79137. #if defined(__CYGWIN__)
  79138. # ifndef HAVE_VSNPRINTF
  79139. # define HAVE_VSNPRINTF
  79140. # endif
  79141. #endif
  79142. #ifndef HAVE_VSNPRINTF
  79143. # ifdef MSDOS
  79144. /* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
  79145. but for now we just assume it doesn't. */
  79146. # define NO_vsnprintf
  79147. # endif
  79148. # ifdef __TURBOC__
  79149. # define NO_vsnprintf
  79150. # endif
  79151. # ifdef WIN32
  79152. /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
  79153. # if !defined(vsnprintf) && !defined(NO_vsnprintf)
  79154. # define vsnprintf _vsnprintf
  79155. # endif
  79156. # endif
  79157. # ifdef __SASC
  79158. # define NO_vsnprintf
  79159. # endif
  79160. #endif
  79161. #ifdef VMS
  79162. # define NO_vsnprintf
  79163. #endif
  79164. #if defined(pyr)
  79165. # define NO_MEMCPY
  79166. #endif
  79167. #if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
  79168. /* Use our own functions for small and medium model with MSC <= 5.0.
  79169. * You may have to use the same strategy for Borland C (untested).
  79170. * The __SC__ check is for Symantec.
  79171. */
  79172. # define NO_MEMCPY
  79173. #endif
  79174. #if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
  79175. # define HAVE_MEMCPY
  79176. #endif
  79177. #ifdef HAVE_MEMCPY
  79178. # ifdef SMALL_MEDIUM /* MSDOS small or medium model */
  79179. # define zmemcpy _fmemcpy
  79180. # define zmemcmp _fmemcmp
  79181. # define zmemzero(dest, len) _fmemset(dest, 0, len)
  79182. # else
  79183. # define zmemcpy memcpy
  79184. # define zmemcmp memcmp
  79185. # define zmemzero(dest, len) memset(dest, 0, len)
  79186. # endif
  79187. #else
  79188. extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
  79189. extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
  79190. extern void zmemzero OF((Bytef* dest, uInt len));
  79191. #endif
  79192. /* Diagnostic functions */
  79193. #ifdef DEBUG
  79194. # include <stdio.h>
  79195. extern int z_verbose;
  79196. extern void z_error OF((const char *m));
  79197. # define Assert(cond,msg) {if(!(cond)) z_error(msg);}
  79198. # define Trace(x) {if (z_verbose>=0) fprintf x ;}
  79199. # define Tracev(x) {if (z_verbose>0) fprintf x ;}
  79200. # define Tracevv(x) {if (z_verbose>1) fprintf x ;}
  79201. # define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
  79202. # define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
  79203. #else
  79204. # define Assert(cond,msg)
  79205. # define Trace(x)
  79206. # define Tracev(x)
  79207. # define Tracevv(x)
  79208. # define Tracec(c,x)
  79209. # define Tracecv(c,x)
  79210. #endif
  79211. voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));
  79212. void zcfree OF((voidpf opaque, voidpf ptr));
  79213. #define ZALLOC(strm, items, size) \
  79214. (*((strm)->zalloc))((strm)->opaque, (items), (size))
  79215. #define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
  79216. #define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
  79217. #endif /* ZUTIL_H */
  79218. /*** End of inlined file: zutil.h ***/
  79219. /* for STDC and FAR definitions */
  79220. #define local static
  79221. /* Find a four-byte integer type for crc32_little() and crc32_big(). */
  79222. #ifndef NOBYFOUR
  79223. # ifdef STDC /* need ANSI C limits.h to determine sizes */
  79224. # include <limits.h>
  79225. # define BYFOUR
  79226. # if (UINT_MAX == 0xffffffffUL)
  79227. typedef unsigned int u4;
  79228. # else
  79229. # if (ULONG_MAX == 0xffffffffUL)
  79230. typedef unsigned long u4;
  79231. # else
  79232. # if (USHRT_MAX == 0xffffffffUL)
  79233. typedef unsigned short u4;
  79234. # else
  79235. # undef BYFOUR /* can't find a four-byte integer type! */
  79236. # endif
  79237. # endif
  79238. # endif
  79239. # endif /* STDC */
  79240. #endif /* !NOBYFOUR */
  79241. /* Definitions for doing the crc four data bytes at a time. */
  79242. #ifdef BYFOUR
  79243. # define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \
  79244. (((w)&0xff00)<<8)+(((w)&0xff)<<24))
  79245. local unsigned long crc32_little OF((unsigned long,
  79246. const unsigned char FAR *, unsigned));
  79247. local unsigned long crc32_big OF((unsigned long,
  79248. const unsigned char FAR *, unsigned));
  79249. # define TBLS 8
  79250. #else
  79251. # define TBLS 1
  79252. #endif /* BYFOUR */
  79253. /* Local functions for crc concatenation */
  79254. local unsigned long gf2_matrix_times OF((unsigned long *mat,
  79255. unsigned long vec));
  79256. local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
  79257. #ifdef DYNAMIC_CRC_TABLE
  79258. local volatile int crc_table_empty = 1;
  79259. local unsigned long FAR crc_table[TBLS][256];
  79260. local void make_crc_table OF((void));
  79261. #ifdef MAKECRCH
  79262. local void write_table OF((FILE *, const unsigned long FAR *));
  79263. #endif /* MAKECRCH */
  79264. /*
  79265. Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
  79266. 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.
  79267. Polynomials over GF(2) are represented in binary, one bit per coefficient,
  79268. with the lowest powers in the most significant bit. Then adding polynomials
  79269. is just exclusive-or, and multiplying a polynomial by x is a right shift by
  79270. one. If we call the above polynomial p, and represent a byte as the
  79271. polynomial q, also with the lowest power in the most significant bit (so the
  79272. byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
  79273. where a mod b means the remainder after dividing a by b.
  79274. This calculation is done using the shift-register method of multiplying and
  79275. taking the remainder. The register is initialized to zero, and for each
  79276. incoming bit, x^32 is added mod p to the register if the bit is a one (where
  79277. x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
  79278. x (which is shifting right by one and adding x^32 mod p if the bit shifted
  79279. out is a one). We start with the highest power (least significant bit) of
  79280. q and repeat for all eight bits of q.
  79281. The first table is simply the CRC of all possible eight bit values. This is
  79282. all the information needed to generate CRCs on data a byte at a time for all
  79283. combinations of CRC register values and incoming bytes. The remaining tables
  79284. allow for word-at-a-time CRC calculation for both big-endian and little-
  79285. endian machines, where a word is four bytes.
  79286. */
  79287. local void make_crc_table()
  79288. {
  79289. unsigned long c;
  79290. int n, k;
  79291. unsigned long poly; /* polynomial exclusive-or pattern */
  79292. /* terms of polynomial defining this crc (except x^32): */
  79293. static volatile int first = 1; /* flag to limit concurrent making */
  79294. static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
  79295. /* See if another task is already doing this (not thread-safe, but better
  79296. than nothing -- significantly reduces duration of vulnerability in
  79297. case the advice about DYNAMIC_CRC_TABLE is ignored) */
  79298. if (first) {
  79299. first = 0;
  79300. /* make exclusive-or pattern from polynomial (0xedb88320UL) */
  79301. poly = 0UL;
  79302. for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++)
  79303. poly |= 1UL << (31 - p[n]);
  79304. /* generate a crc for every 8-bit value */
  79305. for (n = 0; n < 256; n++) {
  79306. c = (unsigned long)n;
  79307. for (k = 0; k < 8; k++)
  79308. c = c & 1 ? poly ^ (c >> 1) : c >> 1;
  79309. crc_table[0][n] = c;
  79310. }
  79311. #ifdef BYFOUR
  79312. /* generate crc for each value followed by one, two, and three zeros,
  79313. and then the byte reversal of those as well as the first table */
  79314. for (n = 0; n < 256; n++) {
  79315. c = crc_table[0][n];
  79316. crc_table[4][n] = REV(c);
  79317. for (k = 1; k < 4; k++) {
  79318. c = crc_table[0][c & 0xff] ^ (c >> 8);
  79319. crc_table[k][n] = c;
  79320. crc_table[k + 4][n] = REV(c);
  79321. }
  79322. }
  79323. #endif /* BYFOUR */
  79324. crc_table_empty = 0;
  79325. }
  79326. else { /* not first */
  79327. /* wait for the other guy to finish (not efficient, but rare) */
  79328. while (crc_table_empty)
  79329. ;
  79330. }
  79331. #ifdef MAKECRCH
  79332. /* write out CRC tables to crc32.h */
  79333. {
  79334. FILE *out;
  79335. out = fopen("crc32.h", "w");
  79336. if (out == NULL) return;
  79337. fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
  79338. fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
  79339. fprintf(out, "local const unsigned long FAR ");
  79340. fprintf(out, "crc_table[TBLS][256] =\n{\n {\n");
  79341. write_table(out, crc_table[0]);
  79342. # ifdef BYFOUR
  79343. fprintf(out, "#ifdef BYFOUR\n");
  79344. for (k = 1; k < 8; k++) {
  79345. fprintf(out, " },\n {\n");
  79346. write_table(out, crc_table[k]);
  79347. }
  79348. fprintf(out, "#endif\n");
  79349. # endif /* BYFOUR */
  79350. fprintf(out, " }\n};\n");
  79351. fclose(out);
  79352. }
  79353. #endif /* MAKECRCH */
  79354. }
  79355. #ifdef MAKECRCH
  79356. local void write_table(out, table)
  79357. FILE *out;
  79358. const unsigned long FAR *table;
  79359. {
  79360. int n;
  79361. for (n = 0; n < 256; n++)
  79362. fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n],
  79363. n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
  79364. }
  79365. #endif /* MAKECRCH */
  79366. #else /* !DYNAMIC_CRC_TABLE */
  79367. /* ========================================================================
  79368. * Tables of CRC-32s of all single-byte values, made by make_crc_table().
  79369. */
  79370. /*** Start of inlined file: crc32.h ***/
  79371. local const unsigned long FAR crc_table[TBLS][256] =
  79372. {
  79373. {
  79374. 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
  79375. 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
  79376. 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
  79377. 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
  79378. 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
  79379. 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
  79380. 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
  79381. 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
  79382. 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
  79383. 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
  79384. 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
  79385. 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
  79386. 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
  79387. 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
  79388. 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
  79389. 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
  79390. 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
  79391. 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
  79392. 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
  79393. 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
  79394. 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
  79395. 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
  79396. 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
  79397. 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
  79398. 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
  79399. 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
  79400. 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
  79401. 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
  79402. 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
  79403. 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
  79404. 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
  79405. 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
  79406. 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
  79407. 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
  79408. 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
  79409. 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
  79410. 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
  79411. 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
  79412. 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
  79413. 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
  79414. 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
  79415. 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
  79416. 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
  79417. 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
  79418. 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
  79419. 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
  79420. 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
  79421. 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
  79422. 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
  79423. 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
  79424. 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
  79425. 0x2d02ef8dUL
  79426. #ifdef BYFOUR
  79427. },
  79428. {
  79429. 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,
  79430. 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,
  79431. 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,
  79432. 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,
  79433. 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,
  79434. 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,
  79435. 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,
  79436. 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,
  79437. 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,
  79438. 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,
  79439. 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,
  79440. 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,
  79441. 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,
  79442. 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,
  79443. 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,
  79444. 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,
  79445. 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,
  79446. 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,
  79447. 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,
  79448. 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,
  79449. 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,
  79450. 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,
  79451. 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,
  79452. 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,
  79453. 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,
  79454. 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,
  79455. 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,
  79456. 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,
  79457. 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,
  79458. 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,
  79459. 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,
  79460. 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,
  79461. 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,
  79462. 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,
  79463. 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,
  79464. 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,
  79465. 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,
  79466. 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,
  79467. 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,
  79468. 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,
  79469. 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,
  79470. 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,
  79471. 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,
  79472. 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,
  79473. 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,
  79474. 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,
  79475. 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,
  79476. 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,
  79477. 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,
  79478. 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,
  79479. 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,
  79480. 0x9324fd72UL
  79481. },
  79482. {
  79483. 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,
  79484. 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,
  79485. 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,
  79486. 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,
  79487. 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,
  79488. 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,
  79489. 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,
  79490. 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,
  79491. 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,
  79492. 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,
  79493. 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,
  79494. 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,
  79495. 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,
  79496. 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,
  79497. 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,
  79498. 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,
  79499. 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,
  79500. 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,
  79501. 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,
  79502. 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,
  79503. 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,
  79504. 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,
  79505. 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,
  79506. 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,
  79507. 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,
  79508. 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,
  79509. 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,
  79510. 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,
  79511. 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,
  79512. 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,
  79513. 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,
  79514. 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,
  79515. 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,
  79516. 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,
  79517. 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,
  79518. 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,
  79519. 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,
  79520. 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,
  79521. 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,
  79522. 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,
  79523. 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,
  79524. 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,
  79525. 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,
  79526. 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,
  79527. 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,
  79528. 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,
  79529. 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,
  79530. 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,
  79531. 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,
  79532. 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,
  79533. 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,
  79534. 0xbe9834edUL
  79535. },
  79536. {
  79537. 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,
  79538. 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,
  79539. 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,
  79540. 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,
  79541. 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,
  79542. 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,
  79543. 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,
  79544. 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,
  79545. 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,
  79546. 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,
  79547. 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,
  79548. 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,
  79549. 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,
  79550. 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,
  79551. 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,
  79552. 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,
  79553. 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,
  79554. 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,
  79555. 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,
  79556. 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,
  79557. 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,
  79558. 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,
  79559. 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,
  79560. 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,
  79561. 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,
  79562. 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,
  79563. 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,
  79564. 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,
  79565. 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,
  79566. 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,
  79567. 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,
  79568. 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,
  79569. 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,
  79570. 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,
  79571. 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,
  79572. 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,
  79573. 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,
  79574. 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,
  79575. 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,
  79576. 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,
  79577. 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,
  79578. 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,
  79579. 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,
  79580. 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,
  79581. 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,
  79582. 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,
  79583. 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,
  79584. 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,
  79585. 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,
  79586. 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,
  79587. 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,
  79588. 0xde0506f1UL
  79589. },
  79590. {
  79591. 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,
  79592. 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,
  79593. 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,
  79594. 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,
  79595. 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,
  79596. 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,
  79597. 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,
  79598. 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,
  79599. 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,
  79600. 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,
  79601. 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,
  79602. 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,
  79603. 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,
  79604. 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,
  79605. 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,
  79606. 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,
  79607. 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,
  79608. 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,
  79609. 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,
  79610. 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,
  79611. 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,
  79612. 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,
  79613. 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,
  79614. 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,
  79615. 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,
  79616. 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,
  79617. 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,
  79618. 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,
  79619. 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,
  79620. 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,
  79621. 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,
  79622. 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,
  79623. 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,
  79624. 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,
  79625. 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,
  79626. 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,
  79627. 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,
  79628. 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,
  79629. 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,
  79630. 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,
  79631. 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,
  79632. 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,
  79633. 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,
  79634. 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,
  79635. 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,
  79636. 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,
  79637. 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,
  79638. 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,
  79639. 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,
  79640. 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,
  79641. 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,
  79642. 0x8def022dUL
  79643. },
  79644. {
  79645. 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,
  79646. 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,
  79647. 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,
  79648. 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,
  79649. 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,
  79650. 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,
  79651. 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,
  79652. 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,
  79653. 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,
  79654. 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,
  79655. 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,
  79656. 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,
  79657. 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,
  79658. 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,
  79659. 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,
  79660. 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,
  79661. 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,
  79662. 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,
  79663. 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,
  79664. 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,
  79665. 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,
  79666. 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,
  79667. 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,
  79668. 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,
  79669. 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,
  79670. 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,
  79671. 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,
  79672. 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,
  79673. 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,
  79674. 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,
  79675. 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,
  79676. 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,
  79677. 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,
  79678. 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,
  79679. 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,
  79680. 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,
  79681. 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,
  79682. 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,
  79683. 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,
  79684. 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,
  79685. 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,
  79686. 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,
  79687. 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,
  79688. 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,
  79689. 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,
  79690. 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,
  79691. 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,
  79692. 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,
  79693. 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,
  79694. 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,
  79695. 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,
  79696. 0x72fd2493UL
  79697. },
  79698. {
  79699. 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,
  79700. 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,
  79701. 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,
  79702. 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,
  79703. 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,
  79704. 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,
  79705. 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,
  79706. 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,
  79707. 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,
  79708. 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,
  79709. 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,
  79710. 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,
  79711. 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,
  79712. 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,
  79713. 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,
  79714. 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,
  79715. 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,
  79716. 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,
  79717. 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,
  79718. 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,
  79719. 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,
  79720. 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,
  79721. 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,
  79722. 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,
  79723. 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,
  79724. 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,
  79725. 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,
  79726. 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,
  79727. 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,
  79728. 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,
  79729. 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,
  79730. 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,
  79731. 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,
  79732. 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,
  79733. 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,
  79734. 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,
  79735. 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,
  79736. 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,
  79737. 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,
  79738. 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,
  79739. 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,
  79740. 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,
  79741. 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,
  79742. 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,
  79743. 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,
  79744. 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,
  79745. 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,
  79746. 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,
  79747. 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,
  79748. 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,
  79749. 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,
  79750. 0xed3498beUL
  79751. },
  79752. {
  79753. 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,
  79754. 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,
  79755. 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,
  79756. 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,
  79757. 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,
  79758. 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,
  79759. 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,
  79760. 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,
  79761. 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,
  79762. 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,
  79763. 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,
  79764. 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,
  79765. 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,
  79766. 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,
  79767. 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,
  79768. 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,
  79769. 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,
  79770. 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,
  79771. 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,
  79772. 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,
  79773. 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,
  79774. 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,
  79775. 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,
  79776. 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,
  79777. 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,
  79778. 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,
  79779. 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,
  79780. 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,
  79781. 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,
  79782. 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,
  79783. 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,
  79784. 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,
  79785. 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,
  79786. 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,
  79787. 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,
  79788. 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,
  79789. 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,
  79790. 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,
  79791. 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,
  79792. 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,
  79793. 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,
  79794. 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,
  79795. 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,
  79796. 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,
  79797. 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,
  79798. 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,
  79799. 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,
  79800. 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,
  79801. 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,
  79802. 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,
  79803. 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,
  79804. 0xf10605deUL
  79805. #endif
  79806. }
  79807. };
  79808. /*** End of inlined file: crc32.h ***/
  79809. #endif /* DYNAMIC_CRC_TABLE */
  79810. /* =========================================================================
  79811. * This function can be used by asm versions of crc32()
  79812. */
  79813. const unsigned long FAR * ZEXPORT get_crc_table()
  79814. {
  79815. #ifdef DYNAMIC_CRC_TABLE
  79816. if (crc_table_empty)
  79817. make_crc_table();
  79818. #endif /* DYNAMIC_CRC_TABLE */
  79819. return (const unsigned long FAR *)crc_table;
  79820. }
  79821. /* ========================================================================= */
  79822. #define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
  79823. #define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
  79824. /* ========================================================================= */
  79825. unsigned long ZEXPORT crc32 (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  79826. {
  79827. if (buf == Z_NULL) return 0UL;
  79828. #ifdef DYNAMIC_CRC_TABLE
  79829. if (crc_table_empty)
  79830. make_crc_table();
  79831. #endif /* DYNAMIC_CRC_TABLE */
  79832. #ifdef BYFOUR
  79833. if (sizeof(void *) == sizeof(ptrdiff_t)) {
  79834. u4 endian;
  79835. endian = 1;
  79836. if (*((unsigned char *)(&endian)))
  79837. return crc32_little(crc, buf, len);
  79838. else
  79839. return crc32_big(crc, buf, len);
  79840. }
  79841. #endif /* BYFOUR */
  79842. crc = crc ^ 0xffffffffUL;
  79843. while (len >= 8) {
  79844. DO8;
  79845. len -= 8;
  79846. }
  79847. if (len) do {
  79848. DO1;
  79849. } while (--len);
  79850. return crc ^ 0xffffffffUL;
  79851. }
  79852. #ifdef BYFOUR
  79853. /* ========================================================================= */
  79854. #define DOLIT4 c ^= *buf4++; \
  79855. c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
  79856. crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
  79857. #define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
  79858. /* ========================================================================= */
  79859. local unsigned long crc32_little(unsigned long crc, const unsigned char FAR *buf, unsigned len)
  79860. {
  79861. register u4 c;
  79862. register const u4 FAR *buf4;
  79863. c = (u4)crc;
  79864. c = ~c;
  79865. while (len && ((ptrdiff_t)buf & 3)) {
  79866. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  79867. len--;
  79868. }
  79869. buf4 = (const u4 FAR *)(const void FAR *)buf;
  79870. while (len >= 32) {
  79871. DOLIT32;
  79872. len -= 32;
  79873. }
  79874. while (len >= 4) {
  79875. DOLIT4;
  79876. len -= 4;
  79877. }
  79878. buf = (const unsigned char FAR *)buf4;
  79879. if (len) do {
  79880. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  79881. } while (--len);
  79882. c = ~c;
  79883. return (unsigned long)c;
  79884. }
  79885. /* ========================================================================= */
  79886. #define DOBIG4 c ^= *++buf4; \
  79887. c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
  79888. crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
  79889. #define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
  79890. /* ========================================================================= */
  79891. local unsigned long crc32_big (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  79892. {
  79893. register u4 c;
  79894. register const u4 FAR *buf4;
  79895. c = REV((u4)crc);
  79896. c = ~c;
  79897. while (len && ((ptrdiff_t)buf & 3)) {
  79898. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  79899. len--;
  79900. }
  79901. buf4 = (const u4 FAR *)(const void FAR *)buf;
  79902. buf4--;
  79903. while (len >= 32) {
  79904. DOBIG32;
  79905. len -= 32;
  79906. }
  79907. while (len >= 4) {
  79908. DOBIG4;
  79909. len -= 4;
  79910. }
  79911. buf4++;
  79912. buf = (const unsigned char FAR *)buf4;
  79913. if (len) do {
  79914. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  79915. } while (--len);
  79916. c = ~c;
  79917. return (unsigned long)(REV(c));
  79918. }
  79919. #endif /* BYFOUR */
  79920. #define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */
  79921. /* ========================================================================= */
  79922. local unsigned long gf2_matrix_times (unsigned long *mat, unsigned long vec)
  79923. {
  79924. unsigned long sum;
  79925. sum = 0;
  79926. while (vec) {
  79927. if (vec & 1)
  79928. sum ^= *mat;
  79929. vec >>= 1;
  79930. mat++;
  79931. }
  79932. return sum;
  79933. }
  79934. /* ========================================================================= */
  79935. local void gf2_matrix_square (unsigned long *square, unsigned long *mat)
  79936. {
  79937. int n;
  79938. for (n = 0; n < GF2_DIM; n++)
  79939. square[n] = gf2_matrix_times(mat, mat[n]);
  79940. }
  79941. /* ========================================================================= */
  79942. uLong ZEXPORT crc32_combine (uLong crc1, uLong crc2, z_off_t len2)
  79943. {
  79944. int n;
  79945. unsigned long row;
  79946. unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */
  79947. unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */
  79948. /* degenerate case */
  79949. if (len2 == 0)
  79950. return crc1;
  79951. /* put operator for one zero bit in odd */
  79952. odd[0] = 0xedb88320L; /* CRC-32 polynomial */
  79953. row = 1;
  79954. for (n = 1; n < GF2_DIM; n++) {
  79955. odd[n] = row;
  79956. row <<= 1;
  79957. }
  79958. /* put operator for two zero bits in even */
  79959. gf2_matrix_square(even, odd);
  79960. /* put operator for four zero bits in odd */
  79961. gf2_matrix_square(odd, even);
  79962. /* apply len2 zeros to crc1 (first square will put the operator for one
  79963. zero byte, eight zero bits, in even) */
  79964. do {
  79965. /* apply zeros operator for this bit of len2 */
  79966. gf2_matrix_square(even, odd);
  79967. if (len2 & 1)
  79968. crc1 = gf2_matrix_times(even, crc1);
  79969. len2 >>= 1;
  79970. /* if no more bits set, then done */
  79971. if (len2 == 0)
  79972. break;
  79973. /* another iteration of the loop with odd and even swapped */
  79974. gf2_matrix_square(odd, even);
  79975. if (len2 & 1)
  79976. crc1 = gf2_matrix_times(odd, crc1);
  79977. len2 >>= 1;
  79978. /* if no more bits set, then done */
  79979. } while (len2 != 0);
  79980. /* return combined crc */
  79981. crc1 ^= crc2;
  79982. return crc1;
  79983. }
  79984. /*** End of inlined file: crc32.c ***/
  79985. /*** Start of inlined file: deflate.c ***/
  79986. /*
  79987. * ALGORITHM
  79988. *
  79989. * The "deflation" process depends on being able to identify portions
  79990. * of the input text which are identical to earlier input (within a
  79991. * sliding window trailing behind the input currently being processed).
  79992. *
  79993. * The most straightforward technique turns out to be the fastest for
  79994. * most input files: try all possible matches and select the longest.
  79995. * The key feature of this algorithm is that insertions into the string
  79996. * dictionary are very simple and thus fast, and deletions are avoided
  79997. * completely. Insertions are performed at each input character, whereas
  79998. * string matches are performed only when the previous match ends. So it
  79999. * is preferable to spend more time in matches to allow very fast string
  80000. * insertions and avoid deletions. The matching algorithm for small
  80001. * strings is inspired from that of Rabin & Karp. A brute force approach
  80002. * is used to find longer strings when a small match has been found.
  80003. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  80004. * (by Leonid Broukhis).
  80005. * A previous version of this file used a more sophisticated algorithm
  80006. * (by Fiala and Greene) which is guaranteed to run in linear amortized
  80007. * time, but has a larger average cost, uses more memory and is patented.
  80008. * However the F&G algorithm may be faster for some highly redundant
  80009. * files if the parameter max_chain_length (described below) is too large.
  80010. *
  80011. * ACKNOWLEDGEMENTS
  80012. *
  80013. * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  80014. * I found it in 'freeze' written by Leonid Broukhis.
  80015. * Thanks to many people for bug reports and testing.
  80016. *
  80017. * REFERENCES
  80018. *
  80019. * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
  80020. * Available in http://www.ietf.org/rfc/rfc1951.txt
  80021. *
  80022. * A description of the Rabin and Karp algorithm is given in the book
  80023. * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  80024. *
  80025. * Fiala,E.R., and Greene,D.H.
  80026. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  80027. *
  80028. */
  80029. /* @(#) $Id: deflate.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80030. /*** Start of inlined file: deflate.h ***/
  80031. /* WARNING: this file should *not* be used by applications. It is
  80032. part of the implementation of the compression library and is
  80033. subject to change. Applications should only use zlib.h.
  80034. */
  80035. /* @(#) $Id: deflate.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80036. #ifndef DEFLATE_H
  80037. #define DEFLATE_H
  80038. /* define NO_GZIP when compiling if you want to disable gzip header and
  80039. trailer creation by deflate(). NO_GZIP would be used to avoid linking in
  80040. the crc code when it is not needed. For shared libraries, gzip encoding
  80041. should be left enabled. */
  80042. #ifndef NO_GZIP
  80043. # define GZIP
  80044. #endif
  80045. #define NO_DUMMY_DECL
  80046. /* ===========================================================================
  80047. * Internal compression state.
  80048. */
  80049. #define LENGTH_CODES 29
  80050. /* number of length codes, not counting the special END_BLOCK code */
  80051. #define LITERALS 256
  80052. /* number of literal bytes 0..255 */
  80053. #define L_CODES (LITERALS+1+LENGTH_CODES)
  80054. /* number of Literal or Length codes, including the END_BLOCK code */
  80055. #define D_CODES 30
  80056. /* number of distance codes */
  80057. #define BL_CODES 19
  80058. /* number of codes used to transfer the bit lengths */
  80059. #define HEAP_SIZE (2*L_CODES+1)
  80060. /* maximum heap size */
  80061. #define MAX_BITS 15
  80062. /* All codes must not exceed MAX_BITS bits */
  80063. #define INIT_STATE 42
  80064. #define EXTRA_STATE 69
  80065. #define NAME_STATE 73
  80066. #define COMMENT_STATE 91
  80067. #define HCRC_STATE 103
  80068. #define BUSY_STATE 113
  80069. #define FINISH_STATE 666
  80070. /* Stream status */
  80071. /* Data structure describing a single value and its code string. */
  80072. typedef struct ct_data_s {
  80073. union {
  80074. ush freq; /* frequency count */
  80075. ush code; /* bit string */
  80076. } fc;
  80077. union {
  80078. ush dad; /* father node in Huffman tree */
  80079. ush len; /* length of bit string */
  80080. } dl;
  80081. } FAR ct_data;
  80082. #define Freq fc.freq
  80083. #define Code fc.code
  80084. #define Dad dl.dad
  80085. #define Len dl.len
  80086. typedef struct static_tree_desc_s static_tree_desc;
  80087. typedef struct tree_desc_s {
  80088. ct_data *dyn_tree; /* the dynamic tree */
  80089. int max_code; /* largest code with non zero frequency */
  80090. static_tree_desc *stat_desc; /* the corresponding static tree */
  80091. } FAR tree_desc;
  80092. typedef ush Pos;
  80093. typedef Pos FAR Posf;
  80094. typedef unsigned IPos;
  80095. /* A Pos is an index in the character window. We use short instead of int to
  80096. * save space in the various tables. IPos is used only for parameter passing.
  80097. */
  80098. typedef struct internal_state {
  80099. z_streamp strm; /* pointer back to this zlib stream */
  80100. int status; /* as the name implies */
  80101. Bytef *pending_buf; /* output still pending */
  80102. ulg pending_buf_size; /* size of pending_buf */
  80103. Bytef *pending_out; /* next pending byte to output to the stream */
  80104. uInt pending; /* nb of bytes in the pending buffer */
  80105. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  80106. gz_headerp gzhead; /* gzip header information to write */
  80107. uInt gzindex; /* where in extra, name, or comment */
  80108. Byte method; /* STORED (for zip only) or DEFLATED */
  80109. int last_flush; /* value of flush param for previous deflate call */
  80110. /* used by deflate.c: */
  80111. uInt w_size; /* LZ77 window size (32K by default) */
  80112. uInt w_bits; /* log2(w_size) (8..16) */
  80113. uInt w_mask; /* w_size - 1 */
  80114. Bytef *window;
  80115. /* Sliding window. Input bytes are read into the second half of the window,
  80116. * and move to the first half later to keep a dictionary of at least wSize
  80117. * bytes. With this organization, matches are limited to a distance of
  80118. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  80119. * performed with a length multiple of the block size. Also, it limits
  80120. * the window size to 64K, which is quite useful on MSDOS.
  80121. * To do: use the user input buffer as sliding window.
  80122. */
  80123. ulg window_size;
  80124. /* Actual size of window: 2*wSize, except when the user input buffer
  80125. * is directly used as sliding window.
  80126. */
  80127. Posf *prev;
  80128. /* Link to older string with same hash index. To limit the size of this
  80129. * array to 64K, this link is maintained only for the last 32K strings.
  80130. * An index in this array is thus a window index modulo 32K.
  80131. */
  80132. Posf *head; /* Heads of the hash chains or NIL. */
  80133. uInt ins_h; /* hash index of string to be inserted */
  80134. uInt hash_size; /* number of elements in hash table */
  80135. uInt hash_bits; /* log2(hash_size) */
  80136. uInt hash_mask; /* hash_size-1 */
  80137. uInt hash_shift;
  80138. /* Number of bits by which ins_h must be shifted at each input
  80139. * step. It must be such that after MIN_MATCH steps, the oldest
  80140. * byte no longer takes part in the hash key, that is:
  80141. * hash_shift * MIN_MATCH >= hash_bits
  80142. */
  80143. long block_start;
  80144. /* Window position at the beginning of the current output block. Gets
  80145. * negative when the window is moved backwards.
  80146. */
  80147. uInt match_length; /* length of best match */
  80148. IPos prev_match; /* previous match */
  80149. int match_available; /* set if previous match exists */
  80150. uInt strstart; /* start of string to insert */
  80151. uInt match_start; /* start of matching string */
  80152. uInt lookahead; /* number of valid bytes ahead in window */
  80153. uInt prev_length;
  80154. /* Length of the best match at previous step. Matches not greater than this
  80155. * are discarded. This is used in the lazy match evaluation.
  80156. */
  80157. uInt max_chain_length;
  80158. /* To speed up deflation, hash chains are never searched beyond this
  80159. * length. A higher limit improves compression ratio but degrades the
  80160. * speed.
  80161. */
  80162. uInt max_lazy_match;
  80163. /* Attempt to find a better match only when the current match is strictly
  80164. * smaller than this value. This mechanism is used only for compression
  80165. * levels >= 4.
  80166. */
  80167. # define max_insert_length max_lazy_match
  80168. /* Insert new strings in the hash table only if the match length is not
  80169. * greater than this length. This saves time but degrades compression.
  80170. * max_insert_length is used only for compression levels <= 3.
  80171. */
  80172. int level; /* compression level (1..9) */
  80173. int strategy; /* favor or force Huffman coding*/
  80174. uInt good_match;
  80175. /* Use a faster search when the previous match is longer than this */
  80176. int nice_match; /* Stop searching when current match exceeds this */
  80177. /* used by trees.c: */
  80178. /* Didn't use ct_data typedef below to supress compiler warning */
  80179. struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  80180. struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  80181. struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  80182. struct tree_desc_s l_desc; /* desc. for literal tree */
  80183. struct tree_desc_s d_desc; /* desc. for distance tree */
  80184. struct tree_desc_s bl_desc; /* desc. for bit length tree */
  80185. ush bl_count[MAX_BITS+1];
  80186. /* number of codes at each bit length for an optimal tree */
  80187. int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  80188. int heap_len; /* number of elements in the heap */
  80189. int heap_max; /* element of largest frequency */
  80190. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  80191. * The same heap array is used to build all trees.
  80192. */
  80193. uch depth[2*L_CODES+1];
  80194. /* Depth of each subtree used as tie breaker for trees of equal frequency
  80195. */
  80196. uchf *l_buf; /* buffer for literals or lengths */
  80197. uInt lit_bufsize;
  80198. /* Size of match buffer for literals/lengths. There are 4 reasons for
  80199. * limiting lit_bufsize to 64K:
  80200. * - frequencies can be kept in 16 bit counters
  80201. * - if compression is not successful for the first block, all input
  80202. * data is still in the window so we can still emit a stored block even
  80203. * when input comes from standard input. (This can also be done for
  80204. * all blocks if lit_bufsize is not greater than 32K.)
  80205. * - if compression is not successful for a file smaller than 64K, we can
  80206. * even emit a stored file instead of a stored block (saving 5 bytes).
  80207. * This is applicable only for zip (not gzip or zlib).
  80208. * - creating new Huffman trees less frequently may not provide fast
  80209. * adaptation to changes in the input data statistics. (Take for
  80210. * example a binary file with poorly compressible code followed by
  80211. * a highly compressible string table.) Smaller buffer sizes give
  80212. * fast adaptation but have of course the overhead of transmitting
  80213. * trees more frequently.
  80214. * - I can't count above 4
  80215. */
  80216. uInt last_lit; /* running index in l_buf */
  80217. ushf *d_buf;
  80218. /* Buffer for distances. To simplify the code, d_buf and l_buf have
  80219. * the same number of elements. To use different lengths, an extra flag
  80220. * array would be necessary.
  80221. */
  80222. ulg opt_len; /* bit length of current block with optimal trees */
  80223. ulg static_len; /* bit length of current block with static trees */
  80224. uInt matches; /* number of string matches in current block */
  80225. int last_eob_len; /* bit length of EOB code for last block */
  80226. #ifdef DEBUG
  80227. ulg compressed_len; /* total bit length of compressed file mod 2^32 */
  80228. ulg bits_sent; /* bit length of compressed data sent mod 2^32 */
  80229. #endif
  80230. ush bi_buf;
  80231. /* Output buffer. bits are inserted starting at the bottom (least
  80232. * significant bits).
  80233. */
  80234. int bi_valid;
  80235. /* Number of valid bits in bi_buf. All bits above the last valid bit
  80236. * are always zero.
  80237. */
  80238. } FAR deflate_state;
  80239. /* Output a byte on the stream.
  80240. * IN assertion: there is enough room in pending_buf.
  80241. */
  80242. #define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
  80243. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  80244. /* Minimum amount of lookahead, except at the end of the input file.
  80245. * See deflate.c for comments about the MIN_MATCH+1.
  80246. */
  80247. #define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD)
  80248. /* In order to simplify the code, particularly on 16 bit machines, match
  80249. * distances are limited to MAX_DIST instead of WSIZE.
  80250. */
  80251. /* in trees.c */
  80252. void _tr_init OF((deflate_state *s));
  80253. int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
  80254. void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len,
  80255. int eof));
  80256. void _tr_align OF((deflate_state *s));
  80257. void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
  80258. int eof));
  80259. #define d_code(dist) \
  80260. ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
  80261. /* Mapping from a distance to a distance code. dist is the distance - 1 and
  80262. * must not have side effects. _dist_code[256] and _dist_code[257] are never
  80263. * used.
  80264. */
  80265. #ifndef DEBUG
  80266. /* Inline versions of _tr_tally for speed: */
  80267. #if defined(GEN_TREES_H) || !defined(STDC)
  80268. extern uch _length_code[];
  80269. extern uch _dist_code[];
  80270. #else
  80271. extern const uch _length_code[];
  80272. extern const uch _dist_code[];
  80273. #endif
  80274. # define _tr_tally_lit(s, c, flush) \
  80275. { uch cc = (c); \
  80276. s->d_buf[s->last_lit] = 0; \
  80277. s->l_buf[s->last_lit++] = cc; \
  80278. s->dyn_ltree[cc].Freq++; \
  80279. flush = (s->last_lit == s->lit_bufsize-1); \
  80280. }
  80281. # define _tr_tally_dist(s, distance, length, flush) \
  80282. { uch len = (length); \
  80283. ush dist = (distance); \
  80284. s->d_buf[s->last_lit] = dist; \
  80285. s->l_buf[s->last_lit++] = len; \
  80286. dist--; \
  80287. s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
  80288. s->dyn_dtree[d_code(dist)].Freq++; \
  80289. flush = (s->last_lit == s->lit_bufsize-1); \
  80290. }
  80291. #else
  80292. # define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
  80293. # define _tr_tally_dist(s, distance, length, flush) \
  80294. flush = _tr_tally(s, distance, length)
  80295. #endif
  80296. #endif /* DEFLATE_H */
  80297. /*** End of inlined file: deflate.h ***/
  80298. const char deflate_copyright[] =
  80299. " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly ";
  80300. /*
  80301. If you use the zlib library in a product, an acknowledgment is welcome
  80302. in the documentation of your product. If for some reason you cannot
  80303. include such an acknowledgment, I would appreciate that you keep this
  80304. copyright string in the executable of your product.
  80305. */
  80306. /* ===========================================================================
  80307. * Function prototypes.
  80308. */
  80309. typedef enum {
  80310. need_more, /* block not completed, need more input or more output */
  80311. block_done, /* block flush performed */
  80312. finish_started, /* finish started, need only more output at next deflate */
  80313. finish_done /* finish done, accept no more input or output */
  80314. } block_state;
  80315. typedef block_state (*compress_func) OF((deflate_state *s, int flush));
  80316. /* Compression function. Returns the block state after the call. */
  80317. local void fill_window OF((deflate_state *s));
  80318. local block_state deflate_stored OF((deflate_state *s, int flush));
  80319. local block_state deflate_fast OF((deflate_state *s, int flush));
  80320. #ifndef FASTEST
  80321. local block_state deflate_slow OF((deflate_state *s, int flush));
  80322. #endif
  80323. local void lm_init OF((deflate_state *s));
  80324. local void putShortMSB OF((deflate_state *s, uInt b));
  80325. local void flush_pending OF((z_streamp strm));
  80326. local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
  80327. #ifndef FASTEST
  80328. #ifdef ASMV
  80329. void match_init OF((void)); /* asm code initialization */
  80330. uInt longest_match OF((deflate_state *s, IPos cur_match));
  80331. #else
  80332. local uInt longest_match OF((deflate_state *s, IPos cur_match));
  80333. #endif
  80334. #endif
  80335. local uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
  80336. #ifdef DEBUG
  80337. local void check_match OF((deflate_state *s, IPos start, IPos match,
  80338. int length));
  80339. #endif
  80340. /* ===========================================================================
  80341. * Local data
  80342. */
  80343. #define NIL 0
  80344. /* Tail of hash chains */
  80345. #ifndef TOO_FAR
  80346. # define TOO_FAR 4096
  80347. #endif
  80348. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  80349. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  80350. /* Minimum amount of lookahead, except at the end of the input file.
  80351. * See deflate.c for comments about the MIN_MATCH+1.
  80352. */
  80353. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  80354. * the desired pack level (0..9). The values given below have been tuned to
  80355. * exclude worst case performance for pathological files. Better values may be
  80356. * found for specific files.
  80357. */
  80358. typedef struct config_s {
  80359. ush good_length; /* reduce lazy search above this match length */
  80360. ush max_lazy; /* do not perform lazy search above this match length */
  80361. ush nice_length; /* quit search above this match length */
  80362. ush max_chain;
  80363. compress_func func;
  80364. } config;
  80365. #ifdef FASTEST
  80366. local const config configuration_table[2] = {
  80367. /* good lazy nice chain */
  80368. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  80369. /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
  80370. #else
  80371. local const config configuration_table[10] = {
  80372. /* good lazy nice chain */
  80373. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  80374. /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
  80375. /* 2 */ {4, 5, 16, 8, deflate_fast},
  80376. /* 3 */ {4, 6, 32, 32, deflate_fast},
  80377. /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
  80378. /* 5 */ {8, 16, 32, 32, deflate_slow},
  80379. /* 6 */ {8, 16, 128, 128, deflate_slow},
  80380. /* 7 */ {8, 32, 128, 256, deflate_slow},
  80381. /* 8 */ {32, 128, 258, 1024, deflate_slow},
  80382. /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
  80383. #endif
  80384. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  80385. * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  80386. * meaning.
  80387. */
  80388. #define EQUAL 0
  80389. /* result of memcmp for equal strings */
  80390. #ifndef NO_DUMMY_DECL
  80391. struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
  80392. #endif
  80393. /* ===========================================================================
  80394. * Update a hash value with the given input byte
  80395. * IN assertion: all calls to to UPDATE_HASH are made with consecutive
  80396. * input characters, so that a running hash key can be computed from the
  80397. * previous key instead of complete recalculation each time.
  80398. */
  80399. #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
  80400. /* ===========================================================================
  80401. * Insert string str in the dictionary and set match_head to the previous head
  80402. * of the hash chain (the most recent string with same hash key). Return
  80403. * the previous length of the hash chain.
  80404. * If this file is compiled with -DFASTEST, the compression level is forced
  80405. * to 1, and no hash chains are maintained.
  80406. * IN assertion: all calls to to INSERT_STRING are made with consecutive
  80407. * input characters and the first MIN_MATCH bytes of str are valid
  80408. * (except for the last MIN_MATCH-1 bytes of the input file).
  80409. */
  80410. #ifdef FASTEST
  80411. #define INSERT_STRING(s, str, match_head) \
  80412. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  80413. match_head = s->head[s->ins_h], \
  80414. s->head[s->ins_h] = (Pos)(str))
  80415. #else
  80416. #define INSERT_STRING(s, str, match_head) \
  80417. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  80418. match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
  80419. s->head[s->ins_h] = (Pos)(str))
  80420. #endif
  80421. /* ===========================================================================
  80422. * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
  80423. * prev[] will be initialized on the fly.
  80424. */
  80425. #define CLEAR_HASH(s) \
  80426. s->head[s->hash_size-1] = NIL; \
  80427. zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
  80428. /* ========================================================================= */
  80429. int ZEXPORT deflateInit_(z_streamp strm, int level, const char *version, int stream_size)
  80430. {
  80431. return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
  80432. Z_DEFAULT_STRATEGY, version, stream_size);
  80433. /* To do: ignore strm->next_in if we use it as window */
  80434. }
  80435. /* ========================================================================= */
  80436. int ZEXPORT deflateInit2_ (z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size)
  80437. {
  80438. deflate_state *s;
  80439. int wrap = 1;
  80440. static const char my_version[] = ZLIB_VERSION;
  80441. ushf *overlay;
  80442. /* We overlay pending_buf and d_buf+l_buf. This works since the average
  80443. * output size for (length,distance) codes is <= 24 bits.
  80444. */
  80445. if (version == Z_NULL || version[0] != my_version[0] ||
  80446. stream_size != sizeof(z_stream)) {
  80447. return Z_VERSION_ERROR;
  80448. }
  80449. if (strm == Z_NULL) return Z_STREAM_ERROR;
  80450. strm->msg = Z_NULL;
  80451. if (strm->zalloc == (alloc_func)0) {
  80452. strm->zalloc = zcalloc;
  80453. strm->opaque = (voidpf)0;
  80454. }
  80455. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  80456. #ifdef FASTEST
  80457. if (level != 0) level = 1;
  80458. #else
  80459. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  80460. #endif
  80461. if (windowBits < 0) { /* suppress zlib wrapper */
  80462. wrap = 0;
  80463. windowBits = -windowBits;
  80464. }
  80465. #ifdef GZIP
  80466. else if (windowBits > 15) {
  80467. wrap = 2; /* write gzip wrapper instead */
  80468. windowBits -= 16;
  80469. }
  80470. #endif
  80471. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
  80472. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  80473. strategy < 0 || strategy > Z_FIXED) {
  80474. return Z_STREAM_ERROR;
  80475. }
  80476. if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
  80477. s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
  80478. if (s == Z_NULL) return Z_MEM_ERROR;
  80479. strm->state = (struct internal_state FAR *)s;
  80480. s->strm = strm;
  80481. s->wrap = wrap;
  80482. s->gzhead = Z_NULL;
  80483. s->w_bits = windowBits;
  80484. s->w_size = 1 << s->w_bits;
  80485. s->w_mask = s->w_size - 1;
  80486. s->hash_bits = memLevel + 7;
  80487. s->hash_size = 1 << s->hash_bits;
  80488. s->hash_mask = s->hash_size - 1;
  80489. s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
  80490. s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
  80491. s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
  80492. s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
  80493. s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  80494. overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  80495. s->pending_buf = (uchf *) overlay;
  80496. s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
  80497. if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
  80498. s->pending_buf == Z_NULL) {
  80499. s->status = FINISH_STATE;
  80500. strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
  80501. deflateEnd (strm);
  80502. return Z_MEM_ERROR;
  80503. }
  80504. s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  80505. s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  80506. s->level = level;
  80507. s->strategy = strategy;
  80508. s->method = (Byte)method;
  80509. return deflateReset(strm);
  80510. }
  80511. /* ========================================================================= */
  80512. int ZEXPORT deflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  80513. {
  80514. deflate_state *s;
  80515. uInt length = dictLength;
  80516. uInt n;
  80517. IPos hash_head = 0;
  80518. if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
  80519. strm->state->wrap == 2 ||
  80520. (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
  80521. return Z_STREAM_ERROR;
  80522. s = strm->state;
  80523. if (s->wrap)
  80524. strm->adler = adler32(strm->adler, dictionary, dictLength);
  80525. if (length < MIN_MATCH) return Z_OK;
  80526. if (length > MAX_DIST(s)) {
  80527. length = MAX_DIST(s);
  80528. dictionary += dictLength - length; /* use the tail of the dictionary */
  80529. }
  80530. zmemcpy(s->window, dictionary, length);
  80531. s->strstart = length;
  80532. s->block_start = (long)length;
  80533. /* Insert all strings in the hash table (except for the last two bytes).
  80534. * s->lookahead stays null, so s->ins_h will be recomputed at the next
  80535. * call of fill_window.
  80536. */
  80537. s->ins_h = s->window[0];
  80538. UPDATE_HASH(s, s->ins_h, s->window[1]);
  80539. for (n = 0; n <= length - MIN_MATCH; n++) {
  80540. INSERT_STRING(s, n, hash_head);
  80541. }
  80542. if (hash_head) hash_head = 0; /* to make compiler happy */
  80543. return Z_OK;
  80544. }
  80545. /* ========================================================================= */
  80546. int ZEXPORT deflateReset (z_streamp strm)
  80547. {
  80548. deflate_state *s;
  80549. if (strm == Z_NULL || strm->state == Z_NULL ||
  80550. strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
  80551. return Z_STREAM_ERROR;
  80552. }
  80553. strm->total_in = strm->total_out = 0;
  80554. strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
  80555. strm->data_type = Z_UNKNOWN;
  80556. s = (deflate_state *)strm->state;
  80557. s->pending = 0;
  80558. s->pending_out = s->pending_buf;
  80559. if (s->wrap < 0) {
  80560. s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
  80561. }
  80562. s->status = s->wrap ? INIT_STATE : BUSY_STATE;
  80563. strm->adler =
  80564. #ifdef GZIP
  80565. s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
  80566. #endif
  80567. adler32(0L, Z_NULL, 0);
  80568. s->last_flush = Z_NO_FLUSH;
  80569. _tr_init(s);
  80570. lm_init(s);
  80571. return Z_OK;
  80572. }
  80573. /* ========================================================================= */
  80574. int ZEXPORT deflateSetHeader (z_streamp strm, gz_headerp head)
  80575. {
  80576. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  80577. if (strm->state->wrap != 2) return Z_STREAM_ERROR;
  80578. strm->state->gzhead = head;
  80579. return Z_OK;
  80580. }
  80581. /* ========================================================================= */
  80582. int ZEXPORT deflatePrime (z_streamp strm, int bits, int value)
  80583. {
  80584. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  80585. strm->state->bi_valid = bits;
  80586. strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
  80587. return Z_OK;
  80588. }
  80589. /* ========================================================================= */
  80590. int ZEXPORT deflateParams (z_streamp strm, int level, int strategy)
  80591. {
  80592. deflate_state *s;
  80593. compress_func func;
  80594. int err = Z_OK;
  80595. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  80596. s = strm->state;
  80597. #ifdef FASTEST
  80598. if (level != 0) level = 1;
  80599. #else
  80600. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  80601. #endif
  80602. if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
  80603. return Z_STREAM_ERROR;
  80604. }
  80605. func = configuration_table[s->level].func;
  80606. if (func != configuration_table[level].func && strm->total_in != 0) {
  80607. /* Flush the last buffer: */
  80608. err = deflate(strm, Z_PARTIAL_FLUSH);
  80609. }
  80610. if (s->level != level) {
  80611. s->level = level;
  80612. s->max_lazy_match = configuration_table[level].max_lazy;
  80613. s->good_match = configuration_table[level].good_length;
  80614. s->nice_match = configuration_table[level].nice_length;
  80615. s->max_chain_length = configuration_table[level].max_chain;
  80616. }
  80617. s->strategy = strategy;
  80618. return err;
  80619. }
  80620. /* ========================================================================= */
  80621. int ZEXPORT deflateTune (z_streamp strm, int good_length, int max_lazy, int nice_length, int max_chain)
  80622. {
  80623. deflate_state *s;
  80624. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  80625. s = strm->state;
  80626. s->good_match = good_length;
  80627. s->max_lazy_match = max_lazy;
  80628. s->nice_match = nice_length;
  80629. s->max_chain_length = max_chain;
  80630. return Z_OK;
  80631. }
  80632. /* =========================================================================
  80633. * For the default windowBits of 15 and memLevel of 8, this function returns
  80634. * a close to exact, as well as small, upper bound on the compressed size.
  80635. * They are coded as constants here for a reason--if the #define's are
  80636. * changed, then this function needs to be changed as well. The return
  80637. * value for 15 and 8 only works for those exact settings.
  80638. *
  80639. * For any setting other than those defaults for windowBits and memLevel,
  80640. * the value returned is a conservative worst case for the maximum expansion
  80641. * resulting from using fixed blocks instead of stored blocks, which deflate
  80642. * can emit on compressed data for some combinations of the parameters.
  80643. *
  80644. * This function could be more sophisticated to provide closer upper bounds
  80645. * for every combination of windowBits and memLevel, as well as wrap.
  80646. * But even the conservative upper bound of about 14% expansion does not
  80647. * seem onerous for output buffer allocation.
  80648. */
  80649. uLong ZEXPORT deflateBound (z_streamp strm, uLong sourceLen)
  80650. {
  80651. deflate_state *s;
  80652. uLong destLen;
  80653. /* conservative upper bound */
  80654. destLen = sourceLen +
  80655. ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
  80656. /* if can't get parameters, return conservative bound */
  80657. if (strm == Z_NULL || strm->state == Z_NULL)
  80658. return destLen;
  80659. /* if not default parameters, return conservative bound */
  80660. s = strm->state;
  80661. if (s->w_bits != 15 || s->hash_bits != 8 + 7)
  80662. return destLen;
  80663. /* default settings: return tight bound for that case */
  80664. return compressBound(sourceLen);
  80665. }
  80666. /* =========================================================================
  80667. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  80668. * IN assertion: the stream state is correct and there is enough room in
  80669. * pending_buf.
  80670. */
  80671. local void putShortMSB (deflate_state *s, uInt b)
  80672. {
  80673. put_byte(s, (Byte)(b >> 8));
  80674. put_byte(s, (Byte)(b & 0xff));
  80675. }
  80676. /* =========================================================================
  80677. * Flush as much pending output as possible. All deflate() output goes
  80678. * through this function so some applications may wish to modify it
  80679. * to avoid allocating a large strm->next_out buffer and copying into it.
  80680. * (See also read_buf()).
  80681. */
  80682. local void flush_pending (z_streamp strm)
  80683. {
  80684. unsigned len = strm->state->pending;
  80685. if (len > strm->avail_out) len = strm->avail_out;
  80686. if (len == 0) return;
  80687. zmemcpy(strm->next_out, strm->state->pending_out, len);
  80688. strm->next_out += len;
  80689. strm->state->pending_out += len;
  80690. strm->total_out += len;
  80691. strm->avail_out -= len;
  80692. strm->state->pending -= len;
  80693. if (strm->state->pending == 0) {
  80694. strm->state->pending_out = strm->state->pending_buf;
  80695. }
  80696. }
  80697. /* ========================================================================= */
  80698. int ZEXPORT deflate (z_streamp strm, int flush)
  80699. {
  80700. int old_flush; /* value of flush param for previous deflate call */
  80701. deflate_state *s;
  80702. if (strm == Z_NULL || strm->state == Z_NULL ||
  80703. flush > Z_FINISH || flush < 0) {
  80704. return Z_STREAM_ERROR;
  80705. }
  80706. s = strm->state;
  80707. if (strm->next_out == Z_NULL ||
  80708. (strm->next_in == Z_NULL && strm->avail_in != 0) ||
  80709. (s->status == FINISH_STATE && flush != Z_FINISH)) {
  80710. ERR_RETURN(strm, Z_STREAM_ERROR);
  80711. }
  80712. if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
  80713. s->strm = strm; /* just in case */
  80714. old_flush = s->last_flush;
  80715. s->last_flush = flush;
  80716. /* Write the header */
  80717. if (s->status == INIT_STATE) {
  80718. #ifdef GZIP
  80719. if (s->wrap == 2) {
  80720. strm->adler = crc32(0L, Z_NULL, 0);
  80721. put_byte(s, 31);
  80722. put_byte(s, 139);
  80723. put_byte(s, 8);
  80724. if (s->gzhead == NULL) {
  80725. put_byte(s, 0);
  80726. put_byte(s, 0);
  80727. put_byte(s, 0);
  80728. put_byte(s, 0);
  80729. put_byte(s, 0);
  80730. put_byte(s, s->level == 9 ? 2 :
  80731. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  80732. 4 : 0));
  80733. put_byte(s, OS_CODE);
  80734. s->status = BUSY_STATE;
  80735. }
  80736. else {
  80737. put_byte(s, (s->gzhead->text ? 1 : 0) +
  80738. (s->gzhead->hcrc ? 2 : 0) +
  80739. (s->gzhead->extra == Z_NULL ? 0 : 4) +
  80740. (s->gzhead->name == Z_NULL ? 0 : 8) +
  80741. (s->gzhead->comment == Z_NULL ? 0 : 16)
  80742. );
  80743. put_byte(s, (Byte)(s->gzhead->time & 0xff));
  80744. put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
  80745. put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
  80746. put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
  80747. put_byte(s, s->level == 9 ? 2 :
  80748. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  80749. 4 : 0));
  80750. put_byte(s, s->gzhead->os & 0xff);
  80751. if (s->gzhead->extra != NULL) {
  80752. put_byte(s, s->gzhead->extra_len & 0xff);
  80753. put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
  80754. }
  80755. if (s->gzhead->hcrc)
  80756. strm->adler = crc32(strm->adler, s->pending_buf,
  80757. s->pending);
  80758. s->gzindex = 0;
  80759. s->status = EXTRA_STATE;
  80760. }
  80761. }
  80762. else
  80763. #endif
  80764. {
  80765. uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
  80766. uInt level_flags;
  80767. if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
  80768. level_flags = 0;
  80769. else if (s->level < 6)
  80770. level_flags = 1;
  80771. else if (s->level == 6)
  80772. level_flags = 2;
  80773. else
  80774. level_flags = 3;
  80775. header |= (level_flags << 6);
  80776. if (s->strstart != 0) header |= PRESET_DICT;
  80777. header += 31 - (header % 31);
  80778. s->status = BUSY_STATE;
  80779. putShortMSB(s, header);
  80780. /* Save the adler32 of the preset dictionary: */
  80781. if (s->strstart != 0) {
  80782. putShortMSB(s, (uInt)(strm->adler >> 16));
  80783. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  80784. }
  80785. strm->adler = adler32(0L, Z_NULL, 0);
  80786. }
  80787. }
  80788. #ifdef GZIP
  80789. if (s->status == EXTRA_STATE) {
  80790. if (s->gzhead->extra != NULL) {
  80791. uInt beg = s->pending; /* start of bytes to update crc */
  80792. while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
  80793. if (s->pending == s->pending_buf_size) {
  80794. if (s->gzhead->hcrc && s->pending > beg)
  80795. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  80796. s->pending - beg);
  80797. flush_pending(strm);
  80798. beg = s->pending;
  80799. if (s->pending == s->pending_buf_size)
  80800. break;
  80801. }
  80802. put_byte(s, s->gzhead->extra[s->gzindex]);
  80803. s->gzindex++;
  80804. }
  80805. if (s->gzhead->hcrc && s->pending > beg)
  80806. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  80807. s->pending - beg);
  80808. if (s->gzindex == s->gzhead->extra_len) {
  80809. s->gzindex = 0;
  80810. s->status = NAME_STATE;
  80811. }
  80812. }
  80813. else
  80814. s->status = NAME_STATE;
  80815. }
  80816. if (s->status == NAME_STATE) {
  80817. if (s->gzhead->name != NULL) {
  80818. uInt beg = s->pending; /* start of bytes to update crc */
  80819. int val;
  80820. do {
  80821. if (s->pending == s->pending_buf_size) {
  80822. if (s->gzhead->hcrc && s->pending > beg)
  80823. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  80824. s->pending - beg);
  80825. flush_pending(strm);
  80826. beg = s->pending;
  80827. if (s->pending == s->pending_buf_size) {
  80828. val = 1;
  80829. break;
  80830. }
  80831. }
  80832. val = s->gzhead->name[s->gzindex++];
  80833. put_byte(s, val);
  80834. } while (val != 0);
  80835. if (s->gzhead->hcrc && s->pending > beg)
  80836. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  80837. s->pending - beg);
  80838. if (val == 0) {
  80839. s->gzindex = 0;
  80840. s->status = COMMENT_STATE;
  80841. }
  80842. }
  80843. else
  80844. s->status = COMMENT_STATE;
  80845. }
  80846. if (s->status == COMMENT_STATE) {
  80847. if (s->gzhead->comment != NULL) {
  80848. uInt beg = s->pending; /* start of bytes to update crc */
  80849. int val;
  80850. do {
  80851. if (s->pending == s->pending_buf_size) {
  80852. if (s->gzhead->hcrc && s->pending > beg)
  80853. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  80854. s->pending - beg);
  80855. flush_pending(strm);
  80856. beg = s->pending;
  80857. if (s->pending == s->pending_buf_size) {
  80858. val = 1;
  80859. break;
  80860. }
  80861. }
  80862. val = s->gzhead->comment[s->gzindex++];
  80863. put_byte(s, val);
  80864. } while (val != 0);
  80865. if (s->gzhead->hcrc && s->pending > beg)
  80866. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  80867. s->pending - beg);
  80868. if (val == 0)
  80869. s->status = HCRC_STATE;
  80870. }
  80871. else
  80872. s->status = HCRC_STATE;
  80873. }
  80874. if (s->status == HCRC_STATE) {
  80875. if (s->gzhead->hcrc) {
  80876. if (s->pending + 2 > s->pending_buf_size)
  80877. flush_pending(strm);
  80878. if (s->pending + 2 <= s->pending_buf_size) {
  80879. put_byte(s, (Byte)(strm->adler & 0xff));
  80880. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  80881. strm->adler = crc32(0L, Z_NULL, 0);
  80882. s->status = BUSY_STATE;
  80883. }
  80884. }
  80885. else
  80886. s->status = BUSY_STATE;
  80887. }
  80888. #endif
  80889. /* Flush as much pending output as possible */
  80890. if (s->pending != 0) {
  80891. flush_pending(strm);
  80892. if (strm->avail_out == 0) {
  80893. /* Since avail_out is 0, deflate will be called again with
  80894. * more output space, but possibly with both pending and
  80895. * avail_in equal to zero. There won't be anything to do,
  80896. * but this is not an error situation so make sure we
  80897. * return OK instead of BUF_ERROR at next call of deflate:
  80898. */
  80899. s->last_flush = -1;
  80900. return Z_OK;
  80901. }
  80902. /* Make sure there is something to do and avoid duplicate consecutive
  80903. * flushes. For repeated and useless calls with Z_FINISH, we keep
  80904. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  80905. */
  80906. } else if (strm->avail_in == 0 && flush <= old_flush &&
  80907. flush != Z_FINISH) {
  80908. ERR_RETURN(strm, Z_BUF_ERROR);
  80909. }
  80910. /* User must not provide more input after the first FINISH: */
  80911. if (s->status == FINISH_STATE && strm->avail_in != 0) {
  80912. ERR_RETURN(strm, Z_BUF_ERROR);
  80913. }
  80914. /* Start a new block or continue the current one.
  80915. */
  80916. if (strm->avail_in != 0 || s->lookahead != 0 ||
  80917. (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
  80918. block_state bstate;
  80919. bstate = (*(configuration_table[s->level].func))(s, flush);
  80920. if (bstate == finish_started || bstate == finish_done) {
  80921. s->status = FINISH_STATE;
  80922. }
  80923. if (bstate == need_more || bstate == finish_started) {
  80924. if (strm->avail_out == 0) {
  80925. s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
  80926. }
  80927. return Z_OK;
  80928. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  80929. * of deflate should use the same flush parameter to make sure
  80930. * that the flush is complete. So we don't have to output an
  80931. * empty block here, this will be done at next call. This also
  80932. * ensures that for a very small output buffer, we emit at most
  80933. * one empty block.
  80934. */
  80935. }
  80936. if (bstate == block_done) {
  80937. if (flush == Z_PARTIAL_FLUSH) {
  80938. _tr_align(s);
  80939. } else { /* FULL_FLUSH or SYNC_FLUSH */
  80940. _tr_stored_block(s, (char*)0, 0L, 0);
  80941. /* For a full flush, this empty block will be recognized
  80942. * as a special marker by inflate_sync().
  80943. */
  80944. if (flush == Z_FULL_FLUSH) {
  80945. CLEAR_HASH(s); /* forget history */
  80946. }
  80947. }
  80948. flush_pending(strm);
  80949. if (strm->avail_out == 0) {
  80950. s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  80951. return Z_OK;
  80952. }
  80953. }
  80954. }
  80955. Assert(strm->avail_out > 0, "bug2");
  80956. if (flush != Z_FINISH) return Z_OK;
  80957. if (s->wrap <= 0) return Z_STREAM_END;
  80958. /* Write the trailer */
  80959. #ifdef GZIP
  80960. if (s->wrap == 2) {
  80961. put_byte(s, (Byte)(strm->adler & 0xff));
  80962. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  80963. put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
  80964. put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
  80965. put_byte(s, (Byte)(strm->total_in & 0xff));
  80966. put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
  80967. put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
  80968. put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
  80969. }
  80970. else
  80971. #endif
  80972. {
  80973. putShortMSB(s, (uInt)(strm->adler >> 16));
  80974. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  80975. }
  80976. flush_pending(strm);
  80977. /* If avail_out is zero, the application will call deflate again
  80978. * to flush the rest.
  80979. */
  80980. if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
  80981. return s->pending != 0 ? Z_OK : Z_STREAM_END;
  80982. }
  80983. /* ========================================================================= */
  80984. int ZEXPORT deflateEnd (z_streamp strm)
  80985. {
  80986. int status;
  80987. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  80988. status = strm->state->status;
  80989. if (status != INIT_STATE &&
  80990. status != EXTRA_STATE &&
  80991. status != NAME_STATE &&
  80992. status != COMMENT_STATE &&
  80993. status != HCRC_STATE &&
  80994. status != BUSY_STATE &&
  80995. status != FINISH_STATE) {
  80996. return Z_STREAM_ERROR;
  80997. }
  80998. /* Deallocate in reverse order of allocations: */
  80999. TRY_FREE(strm, strm->state->pending_buf);
  81000. TRY_FREE(strm, strm->state->head);
  81001. TRY_FREE(strm, strm->state->prev);
  81002. TRY_FREE(strm, strm->state->window);
  81003. ZFREE(strm, strm->state);
  81004. strm->state = Z_NULL;
  81005. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  81006. }
  81007. /* =========================================================================
  81008. * Copy the source state to the destination state.
  81009. * To simplify the source, this is not supported for 16-bit MSDOS (which
  81010. * doesn't have enough memory anyway to duplicate compression states).
  81011. */
  81012. int ZEXPORT deflateCopy (z_streamp dest, z_streamp source)
  81013. {
  81014. #ifdef MAXSEG_64K
  81015. return Z_STREAM_ERROR;
  81016. #else
  81017. deflate_state *ds;
  81018. deflate_state *ss;
  81019. ushf *overlay;
  81020. if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
  81021. return Z_STREAM_ERROR;
  81022. }
  81023. ss = source->state;
  81024. zmemcpy(dest, source, sizeof(z_stream));
  81025. ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
  81026. if (ds == Z_NULL) return Z_MEM_ERROR;
  81027. dest->state = (struct internal_state FAR *) ds;
  81028. zmemcpy(ds, ss, sizeof(deflate_state));
  81029. ds->strm = dest;
  81030. ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
  81031. ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
  81032. ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
  81033. overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
  81034. ds->pending_buf = (uchf *) overlay;
  81035. if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
  81036. ds->pending_buf == Z_NULL) {
  81037. deflateEnd (dest);
  81038. return Z_MEM_ERROR;
  81039. }
  81040. /* following zmemcpy do not work for 16-bit MSDOS */
  81041. zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
  81042. zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
  81043. zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
  81044. zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
  81045. ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
  81046. ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
  81047. ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
  81048. ds->l_desc.dyn_tree = ds->dyn_ltree;
  81049. ds->d_desc.dyn_tree = ds->dyn_dtree;
  81050. ds->bl_desc.dyn_tree = ds->bl_tree;
  81051. return Z_OK;
  81052. #endif /* MAXSEG_64K */
  81053. }
  81054. /* ===========================================================================
  81055. * Read a new buffer from the current input stream, update the adler32
  81056. * and total number of bytes read. All deflate() input goes through
  81057. * this function so some applications may wish to modify it to avoid
  81058. * allocating a large strm->next_in buffer and copying from it.
  81059. * (See also flush_pending()).
  81060. */
  81061. local int read_buf (z_streamp strm, Bytef *buf, unsigned size)
  81062. {
  81063. unsigned len = strm->avail_in;
  81064. if (len > size) len = size;
  81065. if (len == 0) return 0;
  81066. strm->avail_in -= len;
  81067. if (strm->state->wrap == 1) {
  81068. strm->adler = adler32(strm->adler, strm->next_in, len);
  81069. }
  81070. #ifdef GZIP
  81071. else if (strm->state->wrap == 2) {
  81072. strm->adler = crc32(strm->adler, strm->next_in, len);
  81073. }
  81074. #endif
  81075. zmemcpy(buf, strm->next_in, len);
  81076. strm->next_in += len;
  81077. strm->total_in += len;
  81078. return (int)len;
  81079. }
  81080. /* ===========================================================================
  81081. * Initialize the "longest match" routines for a new zlib stream
  81082. */
  81083. local void lm_init (deflate_state *s)
  81084. {
  81085. s->window_size = (ulg)2L*s->w_size;
  81086. CLEAR_HASH(s);
  81087. /* Set the default configuration parameters:
  81088. */
  81089. s->max_lazy_match = configuration_table[s->level].max_lazy;
  81090. s->good_match = configuration_table[s->level].good_length;
  81091. s->nice_match = configuration_table[s->level].nice_length;
  81092. s->max_chain_length = configuration_table[s->level].max_chain;
  81093. s->strstart = 0;
  81094. s->block_start = 0L;
  81095. s->lookahead = 0;
  81096. s->match_length = s->prev_length = MIN_MATCH-1;
  81097. s->match_available = 0;
  81098. s->ins_h = 0;
  81099. #ifndef FASTEST
  81100. #ifdef ASMV
  81101. match_init(); /* initialize the asm code */
  81102. #endif
  81103. #endif
  81104. }
  81105. #ifndef FASTEST
  81106. /* ===========================================================================
  81107. * Set match_start to the longest match starting at the given string and
  81108. * return its length. Matches shorter or equal to prev_length are discarded,
  81109. * in which case the result is equal to prev_length and match_start is
  81110. * garbage.
  81111. * IN assertions: cur_match is the head of the hash chain for the current
  81112. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  81113. * OUT assertion: the match length is not greater than s->lookahead.
  81114. */
  81115. #ifndef ASMV
  81116. /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
  81117. * match.S. The code will be functionally equivalent.
  81118. */
  81119. local uInt longest_match(deflate_state *s, IPos cur_match)
  81120. {
  81121. unsigned chain_length = s->max_chain_length;/* max hash chain length */
  81122. register Bytef *scan = s->window + s->strstart; /* current string */
  81123. register Bytef *match; /* matched string */
  81124. register int len; /* length of current match */
  81125. int best_len = s->prev_length; /* best match length so far */
  81126. int nice_match = s->nice_match; /* stop if match long enough */
  81127. IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
  81128. s->strstart - (IPos)MAX_DIST(s) : NIL;
  81129. /* Stop when cur_match becomes <= limit. To simplify the code,
  81130. * we prevent matches with the string of window index 0.
  81131. */
  81132. Posf *prev = s->prev;
  81133. uInt wmask = s->w_mask;
  81134. #ifdef UNALIGNED_OK
  81135. /* Compare two bytes at a time. Note: this is not always beneficial.
  81136. * Try with and without -DUNALIGNED_OK to check.
  81137. */
  81138. register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
  81139. register ush scan_start = *(ushf*)scan;
  81140. register ush scan_end = *(ushf*)(scan+best_len-1);
  81141. #else
  81142. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  81143. register Byte scan_end1 = scan[best_len-1];
  81144. register Byte scan_end = scan[best_len];
  81145. #endif
  81146. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  81147. * It is easy to get rid of this optimization if necessary.
  81148. */
  81149. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  81150. /* Do not waste too much time if we already have a good match: */
  81151. if (s->prev_length >= s->good_match) {
  81152. chain_length >>= 2;
  81153. }
  81154. /* Do not look for matches beyond the end of the input. This is necessary
  81155. * to make deflate deterministic.
  81156. */
  81157. if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
  81158. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  81159. do {
  81160. Assert(cur_match < s->strstart, "no future");
  81161. match = s->window + cur_match;
  81162. /* Skip to next match if the match length cannot increase
  81163. * or if the match length is less than 2. Note that the checks below
  81164. * for insufficient lookahead only occur occasionally for performance
  81165. * reasons. Therefore uninitialized memory will be accessed, and
  81166. * conditional jumps will be made that depend on those values.
  81167. * However the length of the match is limited to the lookahead, so
  81168. * the output of deflate is not affected by the uninitialized values.
  81169. */
  81170. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  81171. /* This code assumes sizeof(unsigned short) == 2. Do not use
  81172. * UNALIGNED_OK if your compiler uses a different size.
  81173. */
  81174. if (*(ushf*)(match+best_len-1) != scan_end ||
  81175. *(ushf*)match != scan_start) continue;
  81176. /* It is not necessary to compare scan[2] and match[2] since they are
  81177. * always equal when the other bytes match, given that the hash keys
  81178. * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  81179. * strstart+3, +5, ... up to strstart+257. We check for insufficient
  81180. * lookahead only every 4th comparison; the 128th check will be made
  81181. * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  81182. * necessary to put more guard bytes at the end of the window, or
  81183. * to check more often for insufficient lookahead.
  81184. */
  81185. Assert(scan[2] == match[2], "scan[2]?");
  81186. scan++, match++;
  81187. do {
  81188. } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81189. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81190. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81191. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81192. scan < strend);
  81193. /* The funny "do {}" generates better code on most compilers */
  81194. /* Here, scan <= window+strstart+257 */
  81195. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  81196. if (*scan == *match) scan++;
  81197. len = (MAX_MATCH - 1) - (int)(strend-scan);
  81198. scan = strend - (MAX_MATCH-1);
  81199. #else /* UNALIGNED_OK */
  81200. if (match[best_len] != scan_end ||
  81201. match[best_len-1] != scan_end1 ||
  81202. *match != *scan ||
  81203. *++match != scan[1]) continue;
  81204. /* The check at best_len-1 can be removed because it will be made
  81205. * again later. (This heuristic is not always a win.)
  81206. * It is not necessary to compare scan[2] and match[2] since they
  81207. * are always equal when the other bytes match, given that
  81208. * the hash keys are equal and that HASH_BITS >= 8.
  81209. */
  81210. scan += 2, match++;
  81211. Assert(*scan == *match, "match[2]?");
  81212. /* We check for insufficient lookahead only every 8th comparison;
  81213. * the 256th check will be made at strstart+258.
  81214. */
  81215. do {
  81216. } while (*++scan == *++match && *++scan == *++match &&
  81217. *++scan == *++match && *++scan == *++match &&
  81218. *++scan == *++match && *++scan == *++match &&
  81219. *++scan == *++match && *++scan == *++match &&
  81220. scan < strend);
  81221. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  81222. len = MAX_MATCH - (int)(strend - scan);
  81223. scan = strend - MAX_MATCH;
  81224. #endif /* UNALIGNED_OK */
  81225. if (len > best_len) {
  81226. s->match_start = cur_match;
  81227. best_len = len;
  81228. if (len >= nice_match) break;
  81229. #ifdef UNALIGNED_OK
  81230. scan_end = *(ushf*)(scan+best_len-1);
  81231. #else
  81232. scan_end1 = scan[best_len-1];
  81233. scan_end = scan[best_len];
  81234. #endif
  81235. }
  81236. } while ((cur_match = prev[cur_match & wmask]) > limit
  81237. && --chain_length != 0);
  81238. if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
  81239. return s->lookahead;
  81240. }
  81241. #endif /* ASMV */
  81242. #endif /* FASTEST */
  81243. /* ---------------------------------------------------------------------------
  81244. * Optimized version for level == 1 or strategy == Z_RLE only
  81245. */
  81246. local uInt longest_match_fast (deflate_state *s, IPos cur_match)
  81247. {
  81248. register Bytef *scan = s->window + s->strstart; /* current string */
  81249. register Bytef *match; /* matched string */
  81250. register int len; /* length of current match */
  81251. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  81252. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  81253. * It is easy to get rid of this optimization if necessary.
  81254. */
  81255. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  81256. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  81257. Assert(cur_match < s->strstart, "no future");
  81258. match = s->window + cur_match;
  81259. /* Return failure if the match length is less than 2:
  81260. */
  81261. if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
  81262. /* The check at best_len-1 can be removed because it will be made
  81263. * again later. (This heuristic is not always a win.)
  81264. * It is not necessary to compare scan[2] and match[2] since they
  81265. * are always equal when the other bytes match, given that
  81266. * the hash keys are equal and that HASH_BITS >= 8.
  81267. */
  81268. scan += 2, match += 2;
  81269. Assert(*scan == *match, "match[2]?");
  81270. /* We check for insufficient lookahead only every 8th comparison;
  81271. * the 256th check will be made at strstart+258.
  81272. */
  81273. do {
  81274. } while (*++scan == *++match && *++scan == *++match &&
  81275. *++scan == *++match && *++scan == *++match &&
  81276. *++scan == *++match && *++scan == *++match &&
  81277. *++scan == *++match && *++scan == *++match &&
  81278. scan < strend);
  81279. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  81280. len = MAX_MATCH - (int)(strend - scan);
  81281. if (len < MIN_MATCH) return MIN_MATCH - 1;
  81282. s->match_start = cur_match;
  81283. return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
  81284. }
  81285. #ifdef DEBUG
  81286. /* ===========================================================================
  81287. * Check that the match at match_start is indeed a match.
  81288. */
  81289. local void check_match(deflate_state *s, IPos start, IPos match, int length)
  81290. {
  81291. /* check that the match is indeed a match */
  81292. if (zmemcmp(s->window + match,
  81293. s->window + start, length) != EQUAL) {
  81294. fprintf(stderr, " start %u, match %u, length %d\n",
  81295. start, match, length);
  81296. do {
  81297. fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
  81298. } while (--length != 0);
  81299. z_error("invalid match");
  81300. }
  81301. if (z_verbose > 1) {
  81302. fprintf(stderr,"\\[%d,%d]", start-match, length);
  81303. do { putc(s->window[start++], stderr); } while (--length != 0);
  81304. }
  81305. }
  81306. #else
  81307. # define check_match(s, start, match, length)
  81308. #endif /* DEBUG */
  81309. /* ===========================================================================
  81310. * Fill the window when the lookahead becomes insufficient.
  81311. * Updates strstart and lookahead.
  81312. *
  81313. * IN assertion: lookahead < MIN_LOOKAHEAD
  81314. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  81315. * At least one byte has been read, or avail_in == 0; reads are
  81316. * performed for at least two bytes (required for the zip translate_eol
  81317. * option -- not supported here).
  81318. */
  81319. local void fill_window (deflate_state *s)
  81320. {
  81321. register unsigned n, m;
  81322. register Posf *p;
  81323. unsigned more; /* Amount of free space at the end of the window. */
  81324. uInt wsize = s->w_size;
  81325. do {
  81326. more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
  81327. /* Deal with !@#$% 64K limit: */
  81328. if (sizeof(int) <= 2) {
  81329. if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  81330. more = wsize;
  81331. } else if (more == (unsigned)(-1)) {
  81332. /* Very unlikely, but possible on 16 bit machine if
  81333. * strstart == 0 && lookahead == 1 (input done a byte at time)
  81334. */
  81335. more--;
  81336. }
  81337. }
  81338. /* If the window is almost full and there is insufficient lookahead,
  81339. * move the upper half to the lower one to make room in the upper half.
  81340. */
  81341. if (s->strstart >= wsize+MAX_DIST(s)) {
  81342. zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
  81343. s->match_start -= wsize;
  81344. s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
  81345. s->block_start -= (long) wsize;
  81346. /* Slide the hash table (could be avoided with 32 bit values
  81347. at the expense of memory usage). We slide even when level == 0
  81348. to keep the hash table consistent if we switch back to level > 0
  81349. later. (Using level 0 permanently is not an optimal usage of
  81350. zlib, so we don't care about this pathological case.)
  81351. */
  81352. /* %%% avoid this when Z_RLE */
  81353. n = s->hash_size;
  81354. p = &s->head[n];
  81355. do {
  81356. m = *--p;
  81357. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  81358. } while (--n);
  81359. n = wsize;
  81360. #ifndef FASTEST
  81361. p = &s->prev[n];
  81362. do {
  81363. m = *--p;
  81364. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  81365. /* If n is not on any hash chain, prev[n] is garbage but
  81366. * its value will never be used.
  81367. */
  81368. } while (--n);
  81369. #endif
  81370. more += wsize;
  81371. }
  81372. if (s->strm->avail_in == 0) return;
  81373. /* If there was no sliding:
  81374. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  81375. * more == window_size - lookahead - strstart
  81376. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  81377. * => more >= window_size - 2*WSIZE + 2
  81378. * In the BIG_MEM or MMAP case (not yet supported),
  81379. * window_size == input_size + MIN_LOOKAHEAD &&
  81380. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  81381. * Otherwise, window_size == 2*WSIZE so more >= 2.
  81382. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  81383. */
  81384. Assert(more >= 2, "more < 2");
  81385. n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
  81386. s->lookahead += n;
  81387. /* Initialize the hash value now that we have some input: */
  81388. if (s->lookahead >= MIN_MATCH) {
  81389. s->ins_h = s->window[s->strstart];
  81390. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  81391. #if MIN_MATCH != 3
  81392. Call UPDATE_HASH() MIN_MATCH-3 more times
  81393. #endif
  81394. }
  81395. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  81396. * but this is not important since only literal bytes will be emitted.
  81397. */
  81398. } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
  81399. }
  81400. /* ===========================================================================
  81401. * Flush the current block, with given end-of-file flag.
  81402. * IN assertion: strstart is set to the end of the current match.
  81403. */
  81404. #define FLUSH_BLOCK_ONLY(s, eof) { \
  81405. _tr_flush_block(s, (s->block_start >= 0L ? \
  81406. (charf *)&s->window[(unsigned)s->block_start] : \
  81407. (charf *)Z_NULL), \
  81408. (ulg)((long)s->strstart - s->block_start), \
  81409. (eof)); \
  81410. s->block_start = s->strstart; \
  81411. flush_pending(s->strm); \
  81412. Tracev((stderr,"[FLUSH]")); \
  81413. }
  81414. /* Same but force premature exit if necessary. */
  81415. #define FLUSH_BLOCK(s, eof) { \
  81416. FLUSH_BLOCK_ONLY(s, eof); \
  81417. if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
  81418. }
  81419. /* ===========================================================================
  81420. * Copy without compression as much as possible from the input stream, return
  81421. * the current block state.
  81422. * This function does not insert new strings in the dictionary since
  81423. * uncompressible data is probably not useful. This function is used
  81424. * only for the level=0 compression option.
  81425. * NOTE: this function should be optimized to avoid extra copying from
  81426. * window to pending_buf.
  81427. */
  81428. local block_state deflate_stored(deflate_state *s, int flush)
  81429. {
  81430. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  81431. * to pending_buf_size, and each stored block has a 5 byte header:
  81432. */
  81433. ulg max_block_size = 0xffff;
  81434. ulg max_start;
  81435. if (max_block_size > s->pending_buf_size - 5) {
  81436. max_block_size = s->pending_buf_size - 5;
  81437. }
  81438. /* Copy as much as possible from input to output: */
  81439. for (;;) {
  81440. /* Fill the window as much as possible: */
  81441. if (s->lookahead <= 1) {
  81442. Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  81443. s->block_start >= (long)s->w_size, "slide too late");
  81444. fill_window(s);
  81445. if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
  81446. if (s->lookahead == 0) break; /* flush the current block */
  81447. }
  81448. Assert(s->block_start >= 0L, "block gone");
  81449. s->strstart += s->lookahead;
  81450. s->lookahead = 0;
  81451. /* Emit a stored block if pending_buf will be full: */
  81452. max_start = s->block_start + max_block_size;
  81453. if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
  81454. /* strstart == 0 is possible when wraparound on 16-bit machine */
  81455. s->lookahead = (uInt)(s->strstart - max_start);
  81456. s->strstart = (uInt)max_start;
  81457. FLUSH_BLOCK(s, 0);
  81458. }
  81459. /* Flush if we may have to slide, otherwise block_start may become
  81460. * negative and the data will be gone:
  81461. */
  81462. if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
  81463. FLUSH_BLOCK(s, 0);
  81464. }
  81465. }
  81466. FLUSH_BLOCK(s, flush == Z_FINISH);
  81467. return flush == Z_FINISH ? finish_done : block_done;
  81468. }
  81469. /* ===========================================================================
  81470. * Compress as much as possible from the input stream, return the current
  81471. * block state.
  81472. * This function does not perform lazy evaluation of matches and inserts
  81473. * new strings in the dictionary only for unmatched strings or for short
  81474. * matches. It is used only for the fast compression options.
  81475. */
  81476. local block_state deflate_fast(deflate_state *s, int flush)
  81477. {
  81478. IPos hash_head = NIL; /* head of the hash chain */
  81479. int bflush; /* set if current block must be flushed */
  81480. for (;;) {
  81481. /* Make sure that we always have enough lookahead, except
  81482. * at the end of the input file. We need MAX_MATCH bytes
  81483. * for the next match, plus MIN_MATCH bytes to insert the
  81484. * string following the next match.
  81485. */
  81486. if (s->lookahead < MIN_LOOKAHEAD) {
  81487. fill_window(s);
  81488. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  81489. return need_more;
  81490. }
  81491. if (s->lookahead == 0) break; /* flush the current block */
  81492. }
  81493. /* Insert the string window[strstart .. strstart+2] in the
  81494. * dictionary, and set hash_head to the head of the hash chain:
  81495. */
  81496. if (s->lookahead >= MIN_MATCH) {
  81497. INSERT_STRING(s, s->strstart, hash_head);
  81498. }
  81499. /* Find the longest match, discarding those <= prev_length.
  81500. * At this point we have always match_length < MIN_MATCH
  81501. */
  81502. if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
  81503. /* To simplify the code, we prevent matches with the string
  81504. * of window index 0 (in particular we have to avoid a match
  81505. * of the string with itself at the start of the input file).
  81506. */
  81507. #ifdef FASTEST
  81508. if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) ||
  81509. (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
  81510. s->match_length = longest_match_fast (s, hash_head);
  81511. }
  81512. #else
  81513. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  81514. s->match_length = longest_match (s, hash_head);
  81515. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  81516. s->match_length = longest_match_fast (s, hash_head);
  81517. }
  81518. #endif
  81519. /* longest_match() or longest_match_fast() sets match_start */
  81520. }
  81521. if (s->match_length >= MIN_MATCH) {
  81522. check_match(s, s->strstart, s->match_start, s->match_length);
  81523. _tr_tally_dist(s, s->strstart - s->match_start,
  81524. s->match_length - MIN_MATCH, bflush);
  81525. s->lookahead -= s->match_length;
  81526. /* Insert new strings in the hash table only if the match length
  81527. * is not too large. This saves time but degrades compression.
  81528. */
  81529. #ifndef FASTEST
  81530. if (s->match_length <= s->max_insert_length &&
  81531. s->lookahead >= MIN_MATCH) {
  81532. s->match_length--; /* string at strstart already in table */
  81533. do {
  81534. s->strstart++;
  81535. INSERT_STRING(s, s->strstart, hash_head);
  81536. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  81537. * always MIN_MATCH bytes ahead.
  81538. */
  81539. } while (--s->match_length != 0);
  81540. s->strstart++;
  81541. } else
  81542. #endif
  81543. {
  81544. s->strstart += s->match_length;
  81545. s->match_length = 0;
  81546. s->ins_h = s->window[s->strstart];
  81547. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  81548. #if MIN_MATCH != 3
  81549. Call UPDATE_HASH() MIN_MATCH-3 more times
  81550. #endif
  81551. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  81552. * matter since it will be recomputed at next deflate call.
  81553. */
  81554. }
  81555. } else {
  81556. /* No match, output a literal byte */
  81557. Tracevv((stderr,"%c", s->window[s->strstart]));
  81558. _tr_tally_lit (s, s->window[s->strstart], bflush);
  81559. s->lookahead--;
  81560. s->strstart++;
  81561. }
  81562. if (bflush) FLUSH_BLOCK(s, 0);
  81563. }
  81564. FLUSH_BLOCK(s, flush == Z_FINISH);
  81565. return flush == Z_FINISH ? finish_done : block_done;
  81566. }
  81567. #ifndef FASTEST
  81568. /* ===========================================================================
  81569. * Same as above, but achieves better compression. We use a lazy
  81570. * evaluation for matches: a match is finally adopted only if there is
  81571. * no better match at the next window position.
  81572. */
  81573. local block_state deflate_slow(deflate_state *s, int flush)
  81574. {
  81575. IPos hash_head = NIL; /* head of hash chain */
  81576. int bflush; /* set if current block must be flushed */
  81577. /* Process the input block. */
  81578. for (;;) {
  81579. /* Make sure that we always have enough lookahead, except
  81580. * at the end of the input file. We need MAX_MATCH bytes
  81581. * for the next match, plus MIN_MATCH bytes to insert the
  81582. * string following the next match.
  81583. */
  81584. if (s->lookahead < MIN_LOOKAHEAD) {
  81585. fill_window(s);
  81586. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  81587. return need_more;
  81588. }
  81589. if (s->lookahead == 0) break; /* flush the current block */
  81590. }
  81591. /* Insert the string window[strstart .. strstart+2] in the
  81592. * dictionary, and set hash_head to the head of the hash chain:
  81593. */
  81594. if (s->lookahead >= MIN_MATCH) {
  81595. INSERT_STRING(s, s->strstart, hash_head);
  81596. }
  81597. /* Find the longest match, discarding those <= prev_length.
  81598. */
  81599. s->prev_length = s->match_length, s->prev_match = s->match_start;
  81600. s->match_length = MIN_MATCH-1;
  81601. if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
  81602. s->strstart - hash_head <= MAX_DIST(s)) {
  81603. /* To simplify the code, we prevent matches with the string
  81604. * of window index 0 (in particular we have to avoid a match
  81605. * of the string with itself at the start of the input file).
  81606. */
  81607. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  81608. s->match_length = longest_match (s, hash_head);
  81609. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  81610. s->match_length = longest_match_fast (s, hash_head);
  81611. }
  81612. /* longest_match() or longest_match_fast() sets match_start */
  81613. if (s->match_length <= 5 && (s->strategy == Z_FILTERED
  81614. #if TOO_FAR <= 32767
  81615. || (s->match_length == MIN_MATCH &&
  81616. s->strstart - s->match_start > TOO_FAR)
  81617. #endif
  81618. )) {
  81619. /* If prev_match is also MIN_MATCH, match_start is garbage
  81620. * but we will ignore the current match anyway.
  81621. */
  81622. s->match_length = MIN_MATCH-1;
  81623. }
  81624. }
  81625. /* If there was a match at the previous step and the current
  81626. * match is not better, output the previous match:
  81627. */
  81628. if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
  81629. uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
  81630. /* Do not insert strings in hash table beyond this. */
  81631. check_match(s, s->strstart-1, s->prev_match, s->prev_length);
  81632. _tr_tally_dist(s, s->strstart -1 - s->prev_match,
  81633. s->prev_length - MIN_MATCH, bflush);
  81634. /* Insert in hash table all strings up to the end of the match.
  81635. * strstart-1 and strstart are already inserted. If there is not
  81636. * enough lookahead, the last two strings are not inserted in
  81637. * the hash table.
  81638. */
  81639. s->lookahead -= s->prev_length-1;
  81640. s->prev_length -= 2;
  81641. do {
  81642. if (++s->strstart <= max_insert) {
  81643. INSERT_STRING(s, s->strstart, hash_head);
  81644. }
  81645. } while (--s->prev_length != 0);
  81646. s->match_available = 0;
  81647. s->match_length = MIN_MATCH-1;
  81648. s->strstart++;
  81649. if (bflush) FLUSH_BLOCK(s, 0);
  81650. } else if (s->match_available) {
  81651. /* If there was no match at the previous position, output a
  81652. * single literal. If there was a match but the current match
  81653. * is longer, truncate the previous match to a single literal.
  81654. */
  81655. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  81656. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  81657. if (bflush) {
  81658. FLUSH_BLOCK_ONLY(s, 0);
  81659. }
  81660. s->strstart++;
  81661. s->lookahead--;
  81662. if (s->strm->avail_out == 0) return need_more;
  81663. } else {
  81664. /* There is no previous match to compare with, wait for
  81665. * the next step to decide.
  81666. */
  81667. s->match_available = 1;
  81668. s->strstart++;
  81669. s->lookahead--;
  81670. }
  81671. }
  81672. Assert (flush != Z_NO_FLUSH, "no flush?");
  81673. if (s->match_available) {
  81674. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  81675. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  81676. s->match_available = 0;
  81677. }
  81678. FLUSH_BLOCK(s, flush == Z_FINISH);
  81679. return flush == Z_FINISH ? finish_done : block_done;
  81680. }
  81681. #endif /* FASTEST */
  81682. #if 0
  81683. /* ===========================================================================
  81684. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  81685. * one. Do not maintain a hash table. (It will be regenerated if this run of
  81686. * deflate switches away from Z_RLE.)
  81687. */
  81688. local block_state deflate_rle(s, flush)
  81689. deflate_state *s;
  81690. int flush;
  81691. {
  81692. int bflush; /* set if current block must be flushed */
  81693. uInt run; /* length of run */
  81694. uInt max; /* maximum length of run */
  81695. uInt prev; /* byte at distance one to match */
  81696. Bytef *scan; /* scan for end of run */
  81697. for (;;) {
  81698. /* Make sure that we always have enough lookahead, except
  81699. * at the end of the input file. We need MAX_MATCH bytes
  81700. * for the longest encodable run.
  81701. */
  81702. if (s->lookahead < MAX_MATCH) {
  81703. fill_window(s);
  81704. if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
  81705. return need_more;
  81706. }
  81707. if (s->lookahead == 0) break; /* flush the current block */
  81708. }
  81709. /* See how many times the previous byte repeats */
  81710. run = 0;
  81711. if (s->strstart > 0) { /* if there is a previous byte, that is */
  81712. max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH;
  81713. scan = s->window + s->strstart - 1;
  81714. prev = *scan++;
  81715. do {
  81716. if (*scan++ != prev)
  81717. break;
  81718. } while (++run < max);
  81719. }
  81720. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  81721. if (run >= MIN_MATCH) {
  81722. check_match(s, s->strstart, s->strstart - 1, run);
  81723. _tr_tally_dist(s, 1, run - MIN_MATCH, bflush);
  81724. s->lookahead -= run;
  81725. s->strstart += run;
  81726. } else {
  81727. /* No match, output a literal byte */
  81728. Tracevv((stderr,"%c", s->window[s->strstart]));
  81729. _tr_tally_lit (s, s->window[s->strstart], bflush);
  81730. s->lookahead--;
  81731. s->strstart++;
  81732. }
  81733. if (bflush) FLUSH_BLOCK(s, 0);
  81734. }
  81735. FLUSH_BLOCK(s, flush == Z_FINISH);
  81736. return flush == Z_FINISH ? finish_done : block_done;
  81737. }
  81738. #endif
  81739. /*** End of inlined file: deflate.c ***/
  81740. /*** Start of inlined file: inffast.c ***/
  81741. /*** Start of inlined file: inftrees.h ***/
  81742. /* WARNING: this file should *not* be used by applications. It is
  81743. part of the implementation of the compression library and is
  81744. subject to change. Applications should only use zlib.h.
  81745. */
  81746. #ifndef _INFTREES_H_
  81747. #define _INFTREES_H_
  81748. /* Structure for decoding tables. Each entry provides either the
  81749. information needed to do the operation requested by the code that
  81750. indexed that table entry, or it provides a pointer to another
  81751. table that indexes more bits of the code. op indicates whether
  81752. the entry is a pointer to another table, a literal, a length or
  81753. distance, an end-of-block, or an invalid code. For a table
  81754. pointer, the low four bits of op is the number of index bits of
  81755. that table. For a length or distance, the low four bits of op
  81756. is the number of extra bits to get after the code. bits is
  81757. the number of bits in this code or part of the code to drop off
  81758. of the bit buffer. val is the actual byte to output in the case
  81759. of a literal, the base length or distance, or the offset from
  81760. the current table to the next table. Each entry is four bytes. */
  81761. typedef struct {
  81762. unsigned char op; /* operation, extra bits, table bits */
  81763. unsigned char bits; /* bits in this part of the code */
  81764. unsigned short val; /* offset in table or code value */
  81765. } code;
  81766. /* op values as set by inflate_table():
  81767. 00000000 - literal
  81768. 0000tttt - table link, tttt != 0 is the number of table index bits
  81769. 0001eeee - length or distance, eeee is the number of extra bits
  81770. 01100000 - end of block
  81771. 01000000 - invalid code
  81772. */
  81773. /* Maximum size of dynamic tree. The maximum found in a long but non-
  81774. exhaustive search was 1444 code structures (852 for length/literals
  81775. and 592 for distances, the latter actually the result of an
  81776. exhaustive search). The true maximum is not known, but the value
  81777. below is more than safe. */
  81778. #define ENOUGH 2048
  81779. #define MAXD 592
  81780. /* Type of code to build for inftable() */
  81781. typedef enum {
  81782. CODES,
  81783. LENS,
  81784. DISTS
  81785. } codetype;
  81786. extern int inflate_table OF((codetype type, unsigned short FAR *lens,
  81787. unsigned codes, code FAR * FAR *table,
  81788. unsigned FAR *bits, unsigned short FAR *work));
  81789. #endif
  81790. /*** End of inlined file: inftrees.h ***/
  81791. /*** Start of inlined file: inflate.h ***/
  81792. /* WARNING: this file should *not* be used by applications. It is
  81793. part of the implementation of the compression library and is
  81794. subject to change. Applications should only use zlib.h.
  81795. */
  81796. #ifndef _INFLATE_H_
  81797. #define _INFLATE_H_
  81798. /* define NO_GZIP when compiling if you want to disable gzip header and
  81799. trailer decoding by inflate(). NO_GZIP would be used to avoid linking in
  81800. the crc code when it is not needed. For shared libraries, gzip decoding
  81801. should be left enabled. */
  81802. #ifndef NO_GZIP
  81803. # define GUNZIP
  81804. #endif
  81805. /* Possible inflate modes between inflate() calls */
  81806. typedef enum {
  81807. HEAD, /* i: waiting for magic header */
  81808. FLAGS, /* i: waiting for method and flags (gzip) */
  81809. TIME, /* i: waiting for modification time (gzip) */
  81810. OS, /* i: waiting for extra flags and operating system (gzip) */
  81811. EXLEN, /* i: waiting for extra length (gzip) */
  81812. EXTRA, /* i: waiting for extra bytes (gzip) */
  81813. NAME, /* i: waiting for end of file name (gzip) */
  81814. COMMENT, /* i: waiting for end of comment (gzip) */
  81815. HCRC, /* i: waiting for header crc (gzip) */
  81816. DICTID, /* i: waiting for dictionary check value */
  81817. DICT, /* waiting for inflateSetDictionary() call */
  81818. TYPE, /* i: waiting for type bits, including last-flag bit */
  81819. TYPEDO, /* i: same, but skip check to exit inflate on new block */
  81820. STORED, /* i: waiting for stored size (length and complement) */
  81821. COPY, /* i/o: waiting for input or output to copy stored block */
  81822. TABLE, /* i: waiting for dynamic block table lengths */
  81823. LENLENS, /* i: waiting for code length code lengths */
  81824. CODELENS, /* i: waiting for length/lit and distance code lengths */
  81825. LEN, /* i: waiting for length/lit code */
  81826. LENEXT, /* i: waiting for length extra bits */
  81827. DIST, /* i: waiting for distance code */
  81828. DISTEXT, /* i: waiting for distance extra bits */
  81829. MATCH, /* o: waiting for output space to copy string */
  81830. LIT, /* o: waiting for output space to write literal */
  81831. CHECK, /* i: waiting for 32-bit check value */
  81832. LENGTH, /* i: waiting for 32-bit length (gzip) */
  81833. DONE, /* finished check, done -- remain here until reset */
  81834. BAD, /* got a data error -- remain here until reset */
  81835. MEM, /* got an inflate() memory error -- remain here until reset */
  81836. SYNC /* looking for synchronization bytes to restart inflate() */
  81837. } inflate_mode;
  81838. /*
  81839. State transitions between above modes -
  81840. (most modes can go to the BAD or MEM mode -- not shown for clarity)
  81841. Process header:
  81842. HEAD -> (gzip) or (zlib)
  81843. (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME
  81844. NAME -> COMMENT -> HCRC -> TYPE
  81845. (zlib) -> DICTID or TYPE
  81846. DICTID -> DICT -> TYPE
  81847. Read deflate blocks:
  81848. TYPE -> STORED or TABLE or LEN or CHECK
  81849. STORED -> COPY -> TYPE
  81850. TABLE -> LENLENS -> CODELENS -> LEN
  81851. Read deflate codes:
  81852. LEN -> LENEXT or LIT or TYPE
  81853. LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
  81854. LIT -> LEN
  81855. Process trailer:
  81856. CHECK -> LENGTH -> DONE
  81857. */
  81858. /* state maintained between inflate() calls. Approximately 7K bytes. */
  81859. struct inflate_state {
  81860. inflate_mode mode; /* current inflate mode */
  81861. int last; /* true if processing last block */
  81862. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  81863. int havedict; /* true if dictionary provided */
  81864. int flags; /* gzip header method and flags (0 if zlib) */
  81865. unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */
  81866. unsigned long check; /* protected copy of check value */
  81867. unsigned long total; /* protected copy of output count */
  81868. gz_headerp head; /* where to save gzip header information */
  81869. /* sliding window */
  81870. unsigned wbits; /* log base 2 of requested window size */
  81871. unsigned wsize; /* window size or zero if not using window */
  81872. unsigned whave; /* valid bytes in the window */
  81873. unsigned write; /* window write index */
  81874. unsigned char FAR *window; /* allocated sliding window, if needed */
  81875. /* bit accumulator */
  81876. unsigned long hold; /* input bit accumulator */
  81877. unsigned bits; /* number of bits in "in" */
  81878. /* for string and stored block copying */
  81879. unsigned length; /* literal or length of data to copy */
  81880. unsigned offset; /* distance back to copy string from */
  81881. /* for table and code decoding */
  81882. unsigned extra; /* extra bits needed */
  81883. /* fixed and dynamic code tables */
  81884. code const FAR *lencode; /* starting table for length/literal codes */
  81885. code const FAR *distcode; /* starting table for distance codes */
  81886. unsigned lenbits; /* index bits for lencode */
  81887. unsigned distbits; /* index bits for distcode */
  81888. /* dynamic table building */
  81889. unsigned ncode; /* number of code length code lengths */
  81890. unsigned nlen; /* number of length code lengths */
  81891. unsigned ndist; /* number of distance code lengths */
  81892. unsigned have; /* number of code lengths in lens[] */
  81893. code FAR *next; /* next available space in codes[] */
  81894. unsigned short lens[320]; /* temporary storage for code lengths */
  81895. unsigned short work[288]; /* work area for code table building */
  81896. code codes[ENOUGH]; /* space for code tables */
  81897. };
  81898. #endif
  81899. /*** End of inlined file: inflate.h ***/
  81900. /*** Start of inlined file: inffast.h ***/
  81901. /* WARNING: this file should *not* be used by applications. It is
  81902. part of the implementation of the compression library and is
  81903. subject to change. Applications should only use zlib.h.
  81904. */
  81905. void inflate_fast OF((z_streamp strm, unsigned start));
  81906. /*** End of inlined file: inffast.h ***/
  81907. #ifndef ASMINF
  81908. /* Allow machine dependent optimization for post-increment or pre-increment.
  81909. Based on testing to date,
  81910. Pre-increment preferred for:
  81911. - PowerPC G3 (Adler)
  81912. - MIPS R5000 (Randers-Pehrson)
  81913. Post-increment preferred for:
  81914. - none
  81915. No measurable difference:
  81916. - Pentium III (Anderson)
  81917. - M68060 (Nikl)
  81918. */
  81919. #ifdef POSTINC
  81920. # define OFF 0
  81921. # define PUP(a) *(a)++
  81922. #else
  81923. # define OFF 1
  81924. # define PUP(a) *++(a)
  81925. #endif
  81926. /*
  81927. Decode literal, length, and distance codes and write out the resulting
  81928. literal and match bytes until either not enough input or output is
  81929. available, an end-of-block is encountered, or a data error is encountered.
  81930. When large enough input and output buffers are supplied to inflate(), for
  81931. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  81932. inflate execution time is spent in this routine.
  81933. Entry assumptions:
  81934. state->mode == LEN
  81935. strm->avail_in >= 6
  81936. strm->avail_out >= 258
  81937. start >= strm->avail_out
  81938. state->bits < 8
  81939. On return, state->mode is one of:
  81940. LEN -- ran out of enough output space or enough available input
  81941. TYPE -- reached end of block code, inflate() to interpret next block
  81942. BAD -- error in block data
  81943. Notes:
  81944. - The maximum input bits used by a length/distance pair is 15 bits for the
  81945. length code, 5 bits for the length extra, 15 bits for the distance code,
  81946. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  81947. Therefore if strm->avail_in >= 6, then there is enough input to avoid
  81948. checking for available input while decoding.
  81949. - The maximum bytes that a single length/distance pair can output is 258
  81950. bytes, which is the maximum length that can be coded. inflate_fast()
  81951. requires strm->avail_out >= 258 for each loop to avoid checking for
  81952. output space.
  81953. */
  81954. void inflate_fast (z_streamp strm, unsigned start)
  81955. {
  81956. struct inflate_state FAR *state;
  81957. unsigned char FAR *in; /* local strm->next_in */
  81958. unsigned char FAR *last; /* while in < last, enough input available */
  81959. unsigned char FAR *out; /* local strm->next_out */
  81960. unsigned char FAR *beg; /* inflate()'s initial strm->next_out */
  81961. unsigned char FAR *end; /* while out < end, enough space available */
  81962. #ifdef INFLATE_STRICT
  81963. unsigned dmax; /* maximum distance from zlib header */
  81964. #endif
  81965. unsigned wsize; /* window size or zero if not using window */
  81966. unsigned whave; /* valid bytes in the window */
  81967. unsigned write; /* window write index */
  81968. unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */
  81969. unsigned long hold; /* local strm->hold */
  81970. unsigned bits; /* local strm->bits */
  81971. code const FAR *lcode; /* local strm->lencode */
  81972. code const FAR *dcode; /* local strm->distcode */
  81973. unsigned lmask; /* mask for first level of length codes */
  81974. unsigned dmask; /* mask for first level of distance codes */
  81975. code thisx; /* retrieved table entry */
  81976. unsigned op; /* code bits, operation, extra bits, or */
  81977. /* window position, window bytes to copy */
  81978. unsigned len; /* match length, unused bytes */
  81979. unsigned dist; /* match distance */
  81980. unsigned char FAR *from; /* where to copy match from */
  81981. /* copy state to local variables */
  81982. state = (struct inflate_state FAR *)strm->state;
  81983. in = strm->next_in - OFF;
  81984. last = in + (strm->avail_in - 5);
  81985. out = strm->next_out - OFF;
  81986. beg = out - (start - strm->avail_out);
  81987. end = out + (strm->avail_out - 257);
  81988. #ifdef INFLATE_STRICT
  81989. dmax = state->dmax;
  81990. #endif
  81991. wsize = state->wsize;
  81992. whave = state->whave;
  81993. write = state->write;
  81994. window = state->window;
  81995. hold = state->hold;
  81996. bits = state->bits;
  81997. lcode = state->lencode;
  81998. dcode = state->distcode;
  81999. lmask = (1U << state->lenbits) - 1;
  82000. dmask = (1U << state->distbits) - 1;
  82001. /* decode literals and length/distances until end-of-block or not enough
  82002. input data or output space */
  82003. do {
  82004. if (bits < 15) {
  82005. hold += (unsigned long)(PUP(in)) << bits;
  82006. bits += 8;
  82007. hold += (unsigned long)(PUP(in)) << bits;
  82008. bits += 8;
  82009. }
  82010. thisx = lcode[hold & lmask];
  82011. dolen:
  82012. op = (unsigned)(thisx.bits);
  82013. hold >>= op;
  82014. bits -= op;
  82015. op = (unsigned)(thisx.op);
  82016. if (op == 0) { /* literal */
  82017. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  82018. "inflate: literal '%c'\n" :
  82019. "inflate: literal 0x%02x\n", thisx.val));
  82020. PUP(out) = (unsigned char)(thisx.val);
  82021. }
  82022. else if (op & 16) { /* length base */
  82023. len = (unsigned)(thisx.val);
  82024. op &= 15; /* number of extra bits */
  82025. if (op) {
  82026. if (bits < op) {
  82027. hold += (unsigned long)(PUP(in)) << bits;
  82028. bits += 8;
  82029. }
  82030. len += (unsigned)hold & ((1U << op) - 1);
  82031. hold >>= op;
  82032. bits -= op;
  82033. }
  82034. Tracevv((stderr, "inflate: length %u\n", len));
  82035. if (bits < 15) {
  82036. hold += (unsigned long)(PUP(in)) << bits;
  82037. bits += 8;
  82038. hold += (unsigned long)(PUP(in)) << bits;
  82039. bits += 8;
  82040. }
  82041. thisx = dcode[hold & dmask];
  82042. dodist:
  82043. op = (unsigned)(thisx.bits);
  82044. hold >>= op;
  82045. bits -= op;
  82046. op = (unsigned)(thisx.op);
  82047. if (op & 16) { /* distance base */
  82048. dist = (unsigned)(thisx.val);
  82049. op &= 15; /* number of extra bits */
  82050. if (bits < op) {
  82051. hold += (unsigned long)(PUP(in)) << bits;
  82052. bits += 8;
  82053. if (bits < op) {
  82054. hold += (unsigned long)(PUP(in)) << bits;
  82055. bits += 8;
  82056. }
  82057. }
  82058. dist += (unsigned)hold & ((1U << op) - 1);
  82059. #ifdef INFLATE_STRICT
  82060. if (dist > dmax) {
  82061. strm->msg = (char *)"invalid distance too far back";
  82062. state->mode = BAD;
  82063. break;
  82064. }
  82065. #endif
  82066. hold >>= op;
  82067. bits -= op;
  82068. Tracevv((stderr, "inflate: distance %u\n", dist));
  82069. op = (unsigned)(out - beg); /* max distance in output */
  82070. if (dist > op) { /* see if copy from window */
  82071. op = dist - op; /* distance back in window */
  82072. if (op > whave) {
  82073. strm->msg = (char *)"invalid distance too far back";
  82074. state->mode = BAD;
  82075. break;
  82076. }
  82077. from = window - OFF;
  82078. if (write == 0) { /* very common case */
  82079. from += wsize - op;
  82080. if (op < len) { /* some from window */
  82081. len -= op;
  82082. do {
  82083. PUP(out) = PUP(from);
  82084. } while (--op);
  82085. from = out - dist; /* rest from output */
  82086. }
  82087. }
  82088. else if (write < op) { /* wrap around window */
  82089. from += wsize + write - op;
  82090. op -= write;
  82091. if (op < len) { /* some from end of window */
  82092. len -= op;
  82093. do {
  82094. PUP(out) = PUP(from);
  82095. } while (--op);
  82096. from = window - OFF;
  82097. if (write < len) { /* some from start of window */
  82098. op = write;
  82099. len -= op;
  82100. do {
  82101. PUP(out) = PUP(from);
  82102. } while (--op);
  82103. from = out - dist; /* rest from output */
  82104. }
  82105. }
  82106. }
  82107. else { /* contiguous in window */
  82108. from += write - op;
  82109. if (op < len) { /* some from window */
  82110. len -= op;
  82111. do {
  82112. PUP(out) = PUP(from);
  82113. } while (--op);
  82114. from = out - dist; /* rest from output */
  82115. }
  82116. }
  82117. while (len > 2) {
  82118. PUP(out) = PUP(from);
  82119. PUP(out) = PUP(from);
  82120. PUP(out) = PUP(from);
  82121. len -= 3;
  82122. }
  82123. if (len) {
  82124. PUP(out) = PUP(from);
  82125. if (len > 1)
  82126. PUP(out) = PUP(from);
  82127. }
  82128. }
  82129. else {
  82130. from = out - dist; /* copy direct from output */
  82131. do { /* minimum length is three */
  82132. PUP(out) = PUP(from);
  82133. PUP(out) = PUP(from);
  82134. PUP(out) = PUP(from);
  82135. len -= 3;
  82136. } while (len > 2);
  82137. if (len) {
  82138. PUP(out) = PUP(from);
  82139. if (len > 1)
  82140. PUP(out) = PUP(from);
  82141. }
  82142. }
  82143. }
  82144. else if ((op & 64) == 0) { /* 2nd level distance code */
  82145. thisx = dcode[thisx.val + (hold & ((1U << op) - 1))];
  82146. goto dodist;
  82147. }
  82148. else {
  82149. strm->msg = (char *)"invalid distance code";
  82150. state->mode = BAD;
  82151. break;
  82152. }
  82153. }
  82154. else if ((op & 64) == 0) { /* 2nd level length code */
  82155. thisx = lcode[thisx.val + (hold & ((1U << op) - 1))];
  82156. goto dolen;
  82157. }
  82158. else if (op & 32) { /* end-of-block */
  82159. Tracevv((stderr, "inflate: end of block\n"));
  82160. state->mode = TYPE;
  82161. break;
  82162. }
  82163. else {
  82164. strm->msg = (char *)"invalid literal/length code";
  82165. state->mode = BAD;
  82166. break;
  82167. }
  82168. } while (in < last && out < end);
  82169. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  82170. len = bits >> 3;
  82171. in -= len;
  82172. bits -= len << 3;
  82173. hold &= (1U << bits) - 1;
  82174. /* update state and return */
  82175. strm->next_in = in + OFF;
  82176. strm->next_out = out + OFF;
  82177. strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
  82178. strm->avail_out = (unsigned)(out < end ?
  82179. 257 + (end - out) : 257 - (out - end));
  82180. state->hold = hold;
  82181. state->bits = bits;
  82182. return;
  82183. }
  82184. /*
  82185. inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
  82186. - Using bit fields for code structure
  82187. - Different op definition to avoid & for extra bits (do & for table bits)
  82188. - Three separate decoding do-loops for direct, window, and write == 0
  82189. - Special case for distance > 1 copies to do overlapped load and store copy
  82190. - Explicit branch predictions (based on measured branch probabilities)
  82191. - Deferring match copy and interspersed it with decoding subsequent codes
  82192. - Swapping literal/length else
  82193. - Swapping window/direct else
  82194. - Larger unrolled copy loops (three is about right)
  82195. - Moving len -= 3 statement into middle of loop
  82196. */
  82197. #endif /* !ASMINF */
  82198. /*** End of inlined file: inffast.c ***/
  82199. #undef PULLBYTE
  82200. #undef LOAD
  82201. #undef RESTORE
  82202. #undef INITBITS
  82203. #undef NEEDBITS
  82204. #undef DROPBITS
  82205. #undef BYTEBITS
  82206. /*** Start of inlined file: inflate.c ***/
  82207. /*
  82208. * Change history:
  82209. *
  82210. * 1.2.beta0 24 Nov 2002
  82211. * - First version -- complete rewrite of inflate to simplify code, avoid
  82212. * creation of window when not needed, minimize use of window when it is
  82213. * needed, make inffast.c even faster, implement gzip decoding, and to
  82214. * improve code readability and style over the previous zlib inflate code
  82215. *
  82216. * 1.2.beta1 25 Nov 2002
  82217. * - Use pointers for available input and output checking in inffast.c
  82218. * - Remove input and output counters in inffast.c
  82219. * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
  82220. * - Remove unnecessary second byte pull from length extra in inffast.c
  82221. * - Unroll direct copy to three copies per loop in inffast.c
  82222. *
  82223. * 1.2.beta2 4 Dec 2002
  82224. * - Change external routine names to reduce potential conflicts
  82225. * - Correct filename to inffixed.h for fixed tables in inflate.c
  82226. * - Make hbuf[] unsigned char to match parameter type in inflate.c
  82227. * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
  82228. * to avoid negation problem on Alphas (64 bit) in inflate.c
  82229. *
  82230. * 1.2.beta3 22 Dec 2002
  82231. * - Add comments on state->bits assertion in inffast.c
  82232. * - Add comments on op field in inftrees.h
  82233. * - Fix bug in reuse of allocated window after inflateReset()
  82234. * - Remove bit fields--back to byte structure for speed
  82235. * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
  82236. * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
  82237. * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
  82238. * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
  82239. * - Use local copies of stream next and avail values, as well as local bit
  82240. * buffer and bit count in inflate()--for speed when inflate_fast() not used
  82241. *
  82242. * 1.2.beta4 1 Jan 2003
  82243. * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
  82244. * - Move a comment on output buffer sizes from inffast.c to inflate.c
  82245. * - Add comments in inffast.c to introduce the inflate_fast() routine
  82246. * - Rearrange window copies in inflate_fast() for speed and simplification
  82247. * - Unroll last copy for window match in inflate_fast()
  82248. * - Use local copies of window variables in inflate_fast() for speed
  82249. * - Pull out common write == 0 case for speed in inflate_fast()
  82250. * - Make op and len in inflate_fast() unsigned for consistency
  82251. * - Add FAR to lcode and dcode declarations in inflate_fast()
  82252. * - Simplified bad distance check in inflate_fast()
  82253. * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
  82254. * source file infback.c to provide a call-back interface to inflate for
  82255. * programs like gzip and unzip -- uses window as output buffer to avoid
  82256. * window copying
  82257. *
  82258. * 1.2.beta5 1 Jan 2003
  82259. * - Improved inflateBack() interface to allow the caller to provide initial
  82260. * input in strm.
  82261. * - Fixed stored blocks bug in inflateBack()
  82262. *
  82263. * 1.2.beta6 4 Jan 2003
  82264. * - Added comments in inffast.c on effectiveness of POSTINC
  82265. * - Typecasting all around to reduce compiler warnings
  82266. * - Changed loops from while (1) or do {} while (1) to for (;;), again to
  82267. * make compilers happy
  82268. * - Changed type of window in inflateBackInit() to unsigned char *
  82269. *
  82270. * 1.2.beta7 27 Jan 2003
  82271. * - Changed many types to unsigned or unsigned short to avoid warnings
  82272. * - Added inflateCopy() function
  82273. *
  82274. * 1.2.0 9 Mar 2003
  82275. * - Changed inflateBack() interface to provide separate opaque descriptors
  82276. * for the in() and out() functions
  82277. * - Changed inflateBack() argument and in_func typedef to swap the length
  82278. * and buffer address return values for the input function
  82279. * - Check next_in and next_out for Z_NULL on entry to inflate()
  82280. *
  82281. * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
  82282. */
  82283. /*** Start of inlined file: inffast.h ***/
  82284. /* WARNING: this file should *not* be used by applications. It is
  82285. part of the implementation of the compression library and is
  82286. subject to change. Applications should only use zlib.h.
  82287. */
  82288. void inflate_fast OF((z_streamp strm, unsigned start));
  82289. /*** End of inlined file: inffast.h ***/
  82290. #ifdef MAKEFIXED
  82291. # ifndef BUILDFIXED
  82292. # define BUILDFIXED
  82293. # endif
  82294. #endif
  82295. /* function prototypes */
  82296. local void fixedtables OF((struct inflate_state FAR *state));
  82297. local int updatewindow OF((z_streamp strm, unsigned out));
  82298. #ifdef BUILDFIXED
  82299. void makefixed OF((void));
  82300. #endif
  82301. local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf,
  82302. unsigned len));
  82303. int ZEXPORT inflateReset (z_streamp strm)
  82304. {
  82305. struct inflate_state FAR *state;
  82306. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  82307. state = (struct inflate_state FAR *)strm->state;
  82308. strm->total_in = strm->total_out = state->total = 0;
  82309. strm->msg = Z_NULL;
  82310. strm->adler = 1; /* to support ill-conceived Java test suite */
  82311. state->mode = HEAD;
  82312. state->last = 0;
  82313. state->havedict = 0;
  82314. state->dmax = 32768U;
  82315. state->head = Z_NULL;
  82316. state->wsize = 0;
  82317. state->whave = 0;
  82318. state->write = 0;
  82319. state->hold = 0;
  82320. state->bits = 0;
  82321. state->lencode = state->distcode = state->next = state->codes;
  82322. Tracev((stderr, "inflate: reset\n"));
  82323. return Z_OK;
  82324. }
  82325. int ZEXPORT inflatePrime (z_streamp strm, int bits, int value)
  82326. {
  82327. struct inflate_state FAR *state;
  82328. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  82329. state = (struct inflate_state FAR *)strm->state;
  82330. if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
  82331. value &= (1L << bits) - 1;
  82332. state->hold += value << state->bits;
  82333. state->bits += bits;
  82334. return Z_OK;
  82335. }
  82336. int ZEXPORT inflateInit2_(z_streamp strm, int windowBits, const char *version, int stream_size)
  82337. {
  82338. struct inflate_state FAR *state;
  82339. if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
  82340. stream_size != (int)(sizeof(z_stream)))
  82341. return Z_VERSION_ERROR;
  82342. if (strm == Z_NULL) return Z_STREAM_ERROR;
  82343. strm->msg = Z_NULL; /* in case we return an error */
  82344. if (strm->zalloc == (alloc_func)0) {
  82345. strm->zalloc = zcalloc;
  82346. strm->opaque = (voidpf)0;
  82347. }
  82348. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  82349. state = (struct inflate_state FAR *)
  82350. ZALLOC(strm, 1, sizeof(struct inflate_state));
  82351. if (state == Z_NULL) return Z_MEM_ERROR;
  82352. Tracev((stderr, "inflate: allocated\n"));
  82353. strm->state = (struct internal_state FAR *)state;
  82354. if (windowBits < 0) {
  82355. state->wrap = 0;
  82356. windowBits = -windowBits;
  82357. }
  82358. else {
  82359. state->wrap = (windowBits >> 4) + 1;
  82360. #ifdef GUNZIP
  82361. if (windowBits < 48) windowBits &= 15;
  82362. #endif
  82363. }
  82364. if (windowBits < 8 || windowBits > 15) {
  82365. ZFREE(strm, state);
  82366. strm->state = Z_NULL;
  82367. return Z_STREAM_ERROR;
  82368. }
  82369. state->wbits = (unsigned)windowBits;
  82370. state->window = Z_NULL;
  82371. return inflateReset(strm);
  82372. }
  82373. int ZEXPORT inflateInit_ (z_streamp strm, const char *version, int stream_size)
  82374. {
  82375. return inflateInit2_(strm, DEF_WBITS, version, stream_size);
  82376. }
  82377. /*
  82378. Return state with length and distance decoding tables and index sizes set to
  82379. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  82380. If BUILDFIXED is defined, then instead this routine builds the tables the
  82381. first time it's called, and returns those tables the first time and
  82382. thereafter. This reduces the size of the code by about 2K bytes, in
  82383. exchange for a little execution time. However, BUILDFIXED should not be
  82384. used for threaded applications, since the rewriting of the tables and virgin
  82385. may not be thread-safe.
  82386. */
  82387. local void fixedtables (struct inflate_state FAR *state)
  82388. {
  82389. #ifdef BUILDFIXED
  82390. static int virgin = 1;
  82391. static code *lenfix, *distfix;
  82392. static code fixed[544];
  82393. /* build fixed huffman tables if first call (may not be thread safe) */
  82394. if (virgin) {
  82395. unsigned sym, bits;
  82396. static code *next;
  82397. /* literal/length table */
  82398. sym = 0;
  82399. while (sym < 144) state->lens[sym++] = 8;
  82400. while (sym < 256) state->lens[sym++] = 9;
  82401. while (sym < 280) state->lens[sym++] = 7;
  82402. while (sym < 288) state->lens[sym++] = 8;
  82403. next = fixed;
  82404. lenfix = next;
  82405. bits = 9;
  82406. inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
  82407. /* distance table */
  82408. sym = 0;
  82409. while (sym < 32) state->lens[sym++] = 5;
  82410. distfix = next;
  82411. bits = 5;
  82412. inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
  82413. /* do this just once */
  82414. virgin = 0;
  82415. }
  82416. #else /* !BUILDFIXED */
  82417. /*** Start of inlined file: inffixed.h ***/
  82418. /* WARNING: this file should *not* be used by applications. It
  82419. is part of the implementation of the compression library and
  82420. is subject to change. Applications should only use zlib.h.
  82421. */
  82422. static const code lenfix[512] = {
  82423. {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
  82424. {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
  82425. {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
  82426. {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
  82427. {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
  82428. {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
  82429. {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
  82430. {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
  82431. {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
  82432. {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
  82433. {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
  82434. {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
  82435. {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
  82436. {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
  82437. {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
  82438. {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
  82439. {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
  82440. {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
  82441. {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
  82442. {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
  82443. {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
  82444. {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
  82445. {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
  82446. {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
  82447. {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
  82448. {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
  82449. {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
  82450. {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
  82451. {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
  82452. {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
  82453. {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
  82454. {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
  82455. {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
  82456. {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
  82457. {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
  82458. {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
  82459. {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
  82460. {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
  82461. {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
  82462. {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
  82463. {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
  82464. {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
  82465. {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
  82466. {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
  82467. {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
  82468. {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
  82469. {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
  82470. {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
  82471. {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
  82472. {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
  82473. {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
  82474. {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
  82475. {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
  82476. {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
  82477. {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
  82478. {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
  82479. {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
  82480. {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
  82481. {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
  82482. {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
  82483. {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
  82484. {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
  82485. {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
  82486. {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
  82487. {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
  82488. {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
  82489. {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
  82490. {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
  82491. {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
  82492. {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
  82493. {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
  82494. {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
  82495. {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
  82496. {0,9,255}
  82497. };
  82498. static const code distfix[32] = {
  82499. {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
  82500. {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
  82501. {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
  82502. {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
  82503. {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
  82504. {22,5,193},{64,5,0}
  82505. };
  82506. /*** End of inlined file: inffixed.h ***/
  82507. #endif /* BUILDFIXED */
  82508. state->lencode = lenfix;
  82509. state->lenbits = 9;
  82510. state->distcode = distfix;
  82511. state->distbits = 5;
  82512. }
  82513. #ifdef MAKEFIXED
  82514. #include <stdio.h>
  82515. /*
  82516. Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also
  82517. defines BUILDFIXED, so the tables are built on the fly. makefixed() writes
  82518. those tables to stdout, which would be piped to inffixed.h. A small program
  82519. can simply call makefixed to do this:
  82520. void makefixed(void);
  82521. int main(void)
  82522. {
  82523. makefixed();
  82524. return 0;
  82525. }
  82526. Then that can be linked with zlib built with MAKEFIXED defined and run:
  82527. a.out > inffixed.h
  82528. */
  82529. void makefixed()
  82530. {
  82531. unsigned low, size;
  82532. struct inflate_state state;
  82533. fixedtables(&state);
  82534. puts(" /* inffixed.h -- table for decoding fixed codes");
  82535. puts(" * Generated automatically by makefixed().");
  82536. puts(" */");
  82537. puts("");
  82538. puts(" /* WARNING: this file should *not* be used by applications.");
  82539. puts(" It is part of the implementation of this library and is");
  82540. puts(" subject to change. Applications should only use zlib.h.");
  82541. puts(" */");
  82542. puts("");
  82543. size = 1U << 9;
  82544. printf(" static const code lenfix[%u] = {", size);
  82545. low = 0;
  82546. for (;;) {
  82547. if ((low % 7) == 0) printf("\n ");
  82548. printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits,
  82549. state.lencode[low].val);
  82550. if (++low == size) break;
  82551. putchar(',');
  82552. }
  82553. puts("\n };");
  82554. size = 1U << 5;
  82555. printf("\n static const code distfix[%u] = {", size);
  82556. low = 0;
  82557. for (;;) {
  82558. if ((low % 6) == 0) printf("\n ");
  82559. printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
  82560. state.distcode[low].val);
  82561. if (++low == size) break;
  82562. putchar(',');
  82563. }
  82564. puts("\n };");
  82565. }
  82566. #endif /* MAKEFIXED */
  82567. /*
  82568. Update the window with the last wsize (normally 32K) bytes written before
  82569. returning. If window does not exist yet, create it. This is only called
  82570. when a window is already in use, or when output has been written during this
  82571. inflate call, but the end of the deflate stream has not been reached yet.
  82572. It is also called to create a window for dictionary data when a dictionary
  82573. is loaded.
  82574. Providing output buffers larger than 32K to inflate() should provide a speed
  82575. advantage, since only the last 32K of output is copied to the sliding window
  82576. upon return from inflate(), and since all distances after the first 32K of
  82577. output will fall in the output data, making match copies simpler and faster.
  82578. The advantage may be dependent on the size of the processor's data caches.
  82579. */
  82580. local int updatewindow (z_streamp strm, unsigned out)
  82581. {
  82582. struct inflate_state FAR *state;
  82583. unsigned copy, dist;
  82584. state = (struct inflate_state FAR *)strm->state;
  82585. /* if it hasn't been done already, allocate space for the window */
  82586. if (state->window == Z_NULL) {
  82587. state->window = (unsigned char FAR *)
  82588. ZALLOC(strm, 1U << state->wbits,
  82589. sizeof(unsigned char));
  82590. if (state->window == Z_NULL) return 1;
  82591. }
  82592. /* if window not in use yet, initialize */
  82593. if (state->wsize == 0) {
  82594. state->wsize = 1U << state->wbits;
  82595. state->write = 0;
  82596. state->whave = 0;
  82597. }
  82598. /* copy state->wsize or less output bytes into the circular window */
  82599. copy = out - strm->avail_out;
  82600. if (copy >= state->wsize) {
  82601. zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
  82602. state->write = 0;
  82603. state->whave = state->wsize;
  82604. }
  82605. else {
  82606. dist = state->wsize - state->write;
  82607. if (dist > copy) dist = copy;
  82608. zmemcpy(state->window + state->write, strm->next_out - copy, dist);
  82609. copy -= dist;
  82610. if (copy) {
  82611. zmemcpy(state->window, strm->next_out - copy, copy);
  82612. state->write = copy;
  82613. state->whave = state->wsize;
  82614. }
  82615. else {
  82616. state->write += dist;
  82617. if (state->write == state->wsize) state->write = 0;
  82618. if (state->whave < state->wsize) state->whave += dist;
  82619. }
  82620. }
  82621. return 0;
  82622. }
  82623. /* Macros for inflate(): */
  82624. /* check function to use adler32() for zlib or crc32() for gzip */
  82625. #ifdef GUNZIP
  82626. # define UPDATE(check, buf, len) \
  82627. (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
  82628. #else
  82629. # define UPDATE(check, buf, len) adler32(check, buf, len)
  82630. #endif
  82631. /* check macros for header crc */
  82632. #ifdef GUNZIP
  82633. # define CRC2(check, word) \
  82634. do { \
  82635. hbuf[0] = (unsigned char)(word); \
  82636. hbuf[1] = (unsigned char)((word) >> 8); \
  82637. check = crc32(check, hbuf, 2); \
  82638. } while (0)
  82639. # define CRC4(check, word) \
  82640. do { \
  82641. hbuf[0] = (unsigned char)(word); \
  82642. hbuf[1] = (unsigned char)((word) >> 8); \
  82643. hbuf[2] = (unsigned char)((word) >> 16); \
  82644. hbuf[3] = (unsigned char)((word) >> 24); \
  82645. check = crc32(check, hbuf, 4); \
  82646. } while (0)
  82647. #endif
  82648. /* Load registers with state in inflate() for speed */
  82649. #define LOAD() \
  82650. do { \
  82651. put = strm->next_out; \
  82652. left = strm->avail_out; \
  82653. next = strm->next_in; \
  82654. have = strm->avail_in; \
  82655. hold = state->hold; \
  82656. bits = state->bits; \
  82657. } while (0)
  82658. /* Restore state from registers in inflate() */
  82659. #define RESTORE() \
  82660. do { \
  82661. strm->next_out = put; \
  82662. strm->avail_out = left; \
  82663. strm->next_in = next; \
  82664. strm->avail_in = have; \
  82665. state->hold = hold; \
  82666. state->bits = bits; \
  82667. } while (0)
  82668. /* Clear the input bit accumulator */
  82669. #define INITBITS() \
  82670. do { \
  82671. hold = 0; \
  82672. bits = 0; \
  82673. } while (0)
  82674. /* Get a byte of input into the bit accumulator, or return from inflate()
  82675. if there is no input available. */
  82676. #define PULLBYTE() \
  82677. do { \
  82678. if (have == 0) goto inf_leave; \
  82679. have--; \
  82680. hold += (unsigned long)(*next++) << bits; \
  82681. bits += 8; \
  82682. } while (0)
  82683. /* Assure that there are at least n bits in the bit accumulator. If there is
  82684. not enough available input to do that, then return from inflate(). */
  82685. #define NEEDBITS(n) \
  82686. do { \
  82687. while (bits < (unsigned)(n)) \
  82688. PULLBYTE(); \
  82689. } while (0)
  82690. /* Return the low n bits of the bit accumulator (n < 16) */
  82691. #define BITS(n) \
  82692. ((unsigned)hold & ((1U << (n)) - 1))
  82693. /* Remove n bits from the bit accumulator */
  82694. #define DROPBITS(n) \
  82695. do { \
  82696. hold >>= (n); \
  82697. bits -= (unsigned)(n); \
  82698. } while (0)
  82699. /* Remove zero to seven bits as needed to go to a byte boundary */
  82700. #define BYTEBITS() \
  82701. do { \
  82702. hold >>= bits & 7; \
  82703. bits -= bits & 7; \
  82704. } while (0)
  82705. /* Reverse the bytes in a 32-bit value */
  82706. #define REVERSE(q) \
  82707. ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
  82708. (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
  82709. /*
  82710. inflate() uses a state machine to process as much input data and generate as
  82711. much output data as possible before returning. The state machine is
  82712. structured roughly as follows:
  82713. for (;;) switch (state) {
  82714. ...
  82715. case STATEn:
  82716. if (not enough input data or output space to make progress)
  82717. return;
  82718. ... make progress ...
  82719. state = STATEm;
  82720. break;
  82721. ...
  82722. }
  82723. so when inflate() is called again, the same case is attempted again, and
  82724. if the appropriate resources are provided, the machine proceeds to the
  82725. next state. The NEEDBITS() macro is usually the way the state evaluates
  82726. whether it can proceed or should return. NEEDBITS() does the return if
  82727. the requested bits are not available. The typical use of the BITS macros
  82728. is:
  82729. NEEDBITS(n);
  82730. ... do something with BITS(n) ...
  82731. DROPBITS(n);
  82732. where NEEDBITS(n) either returns from inflate() if there isn't enough
  82733. input left to load n bits into the accumulator, or it continues. BITS(n)
  82734. gives the low n bits in the accumulator. When done, DROPBITS(n) drops
  82735. the low n bits off the accumulator. INITBITS() clears the accumulator
  82736. and sets the number of available bits to zero. BYTEBITS() discards just
  82737. enough bits to put the accumulator on a byte boundary. After BYTEBITS()
  82738. and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
  82739. NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
  82740. if there is no input available. The decoding of variable length codes uses
  82741. PULLBYTE() directly in order to pull just enough bytes to decode the next
  82742. code, and no more.
  82743. Some states loop until they get enough input, making sure that enough
  82744. state information is maintained to continue the loop where it left off
  82745. if NEEDBITS() returns in the loop. For example, want, need, and keep
  82746. would all have to actually be part of the saved state in case NEEDBITS()
  82747. returns:
  82748. case STATEw:
  82749. while (want < need) {
  82750. NEEDBITS(n);
  82751. keep[want++] = BITS(n);
  82752. DROPBITS(n);
  82753. }
  82754. state = STATEx;
  82755. case STATEx:
  82756. As shown above, if the next state is also the next case, then the break
  82757. is omitted.
  82758. A state may also return if there is not enough output space available to
  82759. complete that state. Those states are copying stored data, writing a
  82760. literal byte, and copying a matching string.
  82761. When returning, a "goto inf_leave" is used to update the total counters,
  82762. update the check value, and determine whether any progress has been made
  82763. during that inflate() call in order to return the proper return code.
  82764. Progress is defined as a change in either strm->avail_in or strm->avail_out.
  82765. When there is a window, goto inf_leave will update the window with the last
  82766. output written. If a goto inf_leave occurs in the middle of decompression
  82767. and there is no window currently, goto inf_leave will create one and copy
  82768. output to the window for the next call of inflate().
  82769. In this implementation, the flush parameter of inflate() only affects the
  82770. return code (per zlib.h). inflate() always writes as much as possible to
  82771. strm->next_out, given the space available and the provided input--the effect
  82772. documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers
  82773. the allocation of and copying into a sliding window until necessary, which
  82774. provides the effect documented in zlib.h for Z_FINISH when the entire input
  82775. stream available. So the only thing the flush parameter actually does is:
  82776. when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it
  82777. will return Z_BUF_ERROR if it has not reached the end of the stream.
  82778. */
  82779. int ZEXPORT inflate (z_streamp strm, int flush)
  82780. {
  82781. struct inflate_state FAR *state;
  82782. unsigned char FAR *next; /* next input */
  82783. unsigned char FAR *put; /* next output */
  82784. unsigned have, left; /* available input and output */
  82785. unsigned long hold; /* bit buffer */
  82786. unsigned bits; /* bits in bit buffer */
  82787. unsigned in, out; /* save starting available input and output */
  82788. unsigned copy; /* number of stored or match bytes to copy */
  82789. unsigned char FAR *from; /* where to copy match bytes from */
  82790. code thisx; /* current decoding table entry */
  82791. code last; /* parent table entry */
  82792. unsigned len; /* length to copy for repeats, bits to drop */
  82793. int ret; /* return code */
  82794. #ifdef GUNZIP
  82795. unsigned char hbuf[4]; /* buffer for gzip header crc calculation */
  82796. #endif
  82797. static const unsigned short order[19] = /* permutation of code lengths */
  82798. {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  82799. if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL ||
  82800. (strm->next_in == Z_NULL && strm->avail_in != 0))
  82801. return Z_STREAM_ERROR;
  82802. state = (struct inflate_state FAR *)strm->state;
  82803. if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */
  82804. LOAD();
  82805. in = have;
  82806. out = left;
  82807. ret = Z_OK;
  82808. for (;;)
  82809. switch (state->mode) {
  82810. case HEAD:
  82811. if (state->wrap == 0) {
  82812. state->mode = TYPEDO;
  82813. break;
  82814. }
  82815. NEEDBITS(16);
  82816. #ifdef GUNZIP
  82817. if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */
  82818. state->check = crc32(0L, Z_NULL, 0);
  82819. CRC2(state->check, hold);
  82820. INITBITS();
  82821. state->mode = FLAGS;
  82822. break;
  82823. }
  82824. state->flags = 0; /* expect zlib header */
  82825. if (state->head != Z_NULL)
  82826. state->head->done = -1;
  82827. if (!(state->wrap & 1) || /* check if zlib header allowed */
  82828. #else
  82829. if (
  82830. #endif
  82831. ((BITS(8) << 8) + (hold >> 8)) % 31) {
  82832. strm->msg = (char *)"incorrect header check";
  82833. state->mode = BAD;
  82834. break;
  82835. }
  82836. if (BITS(4) != Z_DEFLATED) {
  82837. strm->msg = (char *)"unknown compression method";
  82838. state->mode = BAD;
  82839. break;
  82840. }
  82841. DROPBITS(4);
  82842. len = BITS(4) + 8;
  82843. if (len > state->wbits) {
  82844. strm->msg = (char *)"invalid window size";
  82845. state->mode = BAD;
  82846. break;
  82847. }
  82848. state->dmax = 1U << len;
  82849. Tracev((stderr, "inflate: zlib header ok\n"));
  82850. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  82851. state->mode = hold & 0x200 ? DICTID : TYPE;
  82852. INITBITS();
  82853. break;
  82854. #ifdef GUNZIP
  82855. case FLAGS:
  82856. NEEDBITS(16);
  82857. state->flags = (int)(hold);
  82858. if ((state->flags & 0xff) != Z_DEFLATED) {
  82859. strm->msg = (char *)"unknown compression method";
  82860. state->mode = BAD;
  82861. break;
  82862. }
  82863. if (state->flags & 0xe000) {
  82864. strm->msg = (char *)"unknown header flags set";
  82865. state->mode = BAD;
  82866. break;
  82867. }
  82868. if (state->head != Z_NULL)
  82869. state->head->text = (int)((hold >> 8) & 1);
  82870. if (state->flags & 0x0200) CRC2(state->check, hold);
  82871. INITBITS();
  82872. state->mode = TIME;
  82873. case TIME:
  82874. NEEDBITS(32);
  82875. if (state->head != Z_NULL)
  82876. state->head->time = hold;
  82877. if (state->flags & 0x0200) CRC4(state->check, hold);
  82878. INITBITS();
  82879. state->mode = OS;
  82880. case OS:
  82881. NEEDBITS(16);
  82882. if (state->head != Z_NULL) {
  82883. state->head->xflags = (int)(hold & 0xff);
  82884. state->head->os = (int)(hold >> 8);
  82885. }
  82886. if (state->flags & 0x0200) CRC2(state->check, hold);
  82887. INITBITS();
  82888. state->mode = EXLEN;
  82889. case EXLEN:
  82890. if (state->flags & 0x0400) {
  82891. NEEDBITS(16);
  82892. state->length = (unsigned)(hold);
  82893. if (state->head != Z_NULL)
  82894. state->head->extra_len = (unsigned)hold;
  82895. if (state->flags & 0x0200) CRC2(state->check, hold);
  82896. INITBITS();
  82897. }
  82898. else if (state->head != Z_NULL)
  82899. state->head->extra = Z_NULL;
  82900. state->mode = EXTRA;
  82901. case EXTRA:
  82902. if (state->flags & 0x0400) {
  82903. copy = state->length;
  82904. if (copy > have) copy = have;
  82905. if (copy) {
  82906. if (state->head != Z_NULL &&
  82907. state->head->extra != Z_NULL) {
  82908. len = state->head->extra_len - state->length;
  82909. zmemcpy(state->head->extra + len, next,
  82910. len + copy > state->head->extra_max ?
  82911. state->head->extra_max - len : copy);
  82912. }
  82913. if (state->flags & 0x0200)
  82914. state->check = crc32(state->check, next, copy);
  82915. have -= copy;
  82916. next += copy;
  82917. state->length -= copy;
  82918. }
  82919. if (state->length) goto inf_leave;
  82920. }
  82921. state->length = 0;
  82922. state->mode = NAME;
  82923. case NAME:
  82924. if (state->flags & 0x0800) {
  82925. if (have == 0) goto inf_leave;
  82926. copy = 0;
  82927. do {
  82928. len = (unsigned)(next[copy++]);
  82929. if (state->head != Z_NULL &&
  82930. state->head->name != Z_NULL &&
  82931. state->length < state->head->name_max)
  82932. state->head->name[state->length++] = len;
  82933. } while (len && copy < have);
  82934. if (state->flags & 0x0200)
  82935. state->check = crc32(state->check, next, copy);
  82936. have -= copy;
  82937. next += copy;
  82938. if (len) goto inf_leave;
  82939. }
  82940. else if (state->head != Z_NULL)
  82941. state->head->name = Z_NULL;
  82942. state->length = 0;
  82943. state->mode = COMMENT;
  82944. case COMMENT:
  82945. if (state->flags & 0x1000) {
  82946. if (have == 0) goto inf_leave;
  82947. copy = 0;
  82948. do {
  82949. len = (unsigned)(next[copy++]);
  82950. if (state->head != Z_NULL &&
  82951. state->head->comment != Z_NULL &&
  82952. state->length < state->head->comm_max)
  82953. state->head->comment[state->length++] = len;
  82954. } while (len && copy < have);
  82955. if (state->flags & 0x0200)
  82956. state->check = crc32(state->check, next, copy);
  82957. have -= copy;
  82958. next += copy;
  82959. if (len) goto inf_leave;
  82960. }
  82961. else if (state->head != Z_NULL)
  82962. state->head->comment = Z_NULL;
  82963. state->mode = HCRC;
  82964. case HCRC:
  82965. if (state->flags & 0x0200) {
  82966. NEEDBITS(16);
  82967. if (hold != (state->check & 0xffff)) {
  82968. strm->msg = (char *)"header crc mismatch";
  82969. state->mode = BAD;
  82970. break;
  82971. }
  82972. INITBITS();
  82973. }
  82974. if (state->head != Z_NULL) {
  82975. state->head->hcrc = (int)((state->flags >> 9) & 1);
  82976. state->head->done = 1;
  82977. }
  82978. strm->adler = state->check = crc32(0L, Z_NULL, 0);
  82979. state->mode = TYPE;
  82980. break;
  82981. #endif
  82982. case DICTID:
  82983. NEEDBITS(32);
  82984. strm->adler = state->check = REVERSE(hold);
  82985. INITBITS();
  82986. state->mode = DICT;
  82987. case DICT:
  82988. if (state->havedict == 0) {
  82989. RESTORE();
  82990. return Z_NEED_DICT;
  82991. }
  82992. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  82993. state->mode = TYPE;
  82994. case TYPE:
  82995. if (flush == Z_BLOCK) goto inf_leave;
  82996. case TYPEDO:
  82997. if (state->last) {
  82998. BYTEBITS();
  82999. state->mode = CHECK;
  83000. break;
  83001. }
  83002. NEEDBITS(3);
  83003. state->last = BITS(1);
  83004. DROPBITS(1);
  83005. switch (BITS(2)) {
  83006. case 0: /* stored block */
  83007. Tracev((stderr, "inflate: stored block%s\n",
  83008. state->last ? " (last)" : ""));
  83009. state->mode = STORED;
  83010. break;
  83011. case 1: /* fixed block */
  83012. fixedtables(state);
  83013. Tracev((stderr, "inflate: fixed codes block%s\n",
  83014. state->last ? " (last)" : ""));
  83015. state->mode = LEN; /* decode codes */
  83016. break;
  83017. case 2: /* dynamic block */
  83018. Tracev((stderr, "inflate: dynamic codes block%s\n",
  83019. state->last ? " (last)" : ""));
  83020. state->mode = TABLE;
  83021. break;
  83022. case 3:
  83023. strm->msg = (char *)"invalid block type";
  83024. state->mode = BAD;
  83025. }
  83026. DROPBITS(2);
  83027. break;
  83028. case STORED:
  83029. BYTEBITS(); /* go to byte boundary */
  83030. NEEDBITS(32);
  83031. if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
  83032. strm->msg = (char *)"invalid stored block lengths";
  83033. state->mode = BAD;
  83034. break;
  83035. }
  83036. state->length = (unsigned)hold & 0xffff;
  83037. Tracev((stderr, "inflate: stored length %u\n",
  83038. state->length));
  83039. INITBITS();
  83040. state->mode = COPY;
  83041. case COPY:
  83042. copy = state->length;
  83043. if (copy) {
  83044. if (copy > have) copy = have;
  83045. if (copy > left) copy = left;
  83046. if (copy == 0) goto inf_leave;
  83047. zmemcpy(put, next, copy);
  83048. have -= copy;
  83049. next += copy;
  83050. left -= copy;
  83051. put += copy;
  83052. state->length -= copy;
  83053. break;
  83054. }
  83055. Tracev((stderr, "inflate: stored end\n"));
  83056. state->mode = TYPE;
  83057. break;
  83058. case TABLE:
  83059. NEEDBITS(14);
  83060. state->nlen = BITS(5) + 257;
  83061. DROPBITS(5);
  83062. state->ndist = BITS(5) + 1;
  83063. DROPBITS(5);
  83064. state->ncode = BITS(4) + 4;
  83065. DROPBITS(4);
  83066. #ifndef PKZIP_BUG_WORKAROUND
  83067. if (state->nlen > 286 || state->ndist > 30) {
  83068. strm->msg = (char *)"too many length or distance symbols";
  83069. state->mode = BAD;
  83070. break;
  83071. }
  83072. #endif
  83073. Tracev((stderr, "inflate: table sizes ok\n"));
  83074. state->have = 0;
  83075. state->mode = LENLENS;
  83076. case LENLENS:
  83077. while (state->have < state->ncode) {
  83078. NEEDBITS(3);
  83079. state->lens[order[state->have++]] = (unsigned short)BITS(3);
  83080. DROPBITS(3);
  83081. }
  83082. while (state->have < 19)
  83083. state->lens[order[state->have++]] = 0;
  83084. state->next = state->codes;
  83085. state->lencode = (code const FAR *)(state->next);
  83086. state->lenbits = 7;
  83087. ret = inflate_table(CODES, state->lens, 19, &(state->next),
  83088. &(state->lenbits), state->work);
  83089. if (ret) {
  83090. strm->msg = (char *)"invalid code lengths set";
  83091. state->mode = BAD;
  83092. break;
  83093. }
  83094. Tracev((stderr, "inflate: code lengths ok\n"));
  83095. state->have = 0;
  83096. state->mode = CODELENS;
  83097. case CODELENS:
  83098. while (state->have < state->nlen + state->ndist) {
  83099. for (;;) {
  83100. thisx = state->lencode[BITS(state->lenbits)];
  83101. if ((unsigned)(thisx.bits) <= bits) break;
  83102. PULLBYTE();
  83103. }
  83104. if (thisx.val < 16) {
  83105. NEEDBITS(thisx.bits);
  83106. DROPBITS(thisx.bits);
  83107. state->lens[state->have++] = thisx.val;
  83108. }
  83109. else {
  83110. if (thisx.val == 16) {
  83111. NEEDBITS(thisx.bits + 2);
  83112. DROPBITS(thisx.bits);
  83113. if (state->have == 0) {
  83114. strm->msg = (char *)"invalid bit length repeat";
  83115. state->mode = BAD;
  83116. break;
  83117. }
  83118. len = state->lens[state->have - 1];
  83119. copy = 3 + BITS(2);
  83120. DROPBITS(2);
  83121. }
  83122. else if (thisx.val == 17) {
  83123. NEEDBITS(thisx.bits + 3);
  83124. DROPBITS(thisx.bits);
  83125. len = 0;
  83126. copy = 3 + BITS(3);
  83127. DROPBITS(3);
  83128. }
  83129. else {
  83130. NEEDBITS(thisx.bits + 7);
  83131. DROPBITS(thisx.bits);
  83132. len = 0;
  83133. copy = 11 + BITS(7);
  83134. DROPBITS(7);
  83135. }
  83136. if (state->have + copy > state->nlen + state->ndist) {
  83137. strm->msg = (char *)"invalid bit length repeat";
  83138. state->mode = BAD;
  83139. break;
  83140. }
  83141. while (copy--)
  83142. state->lens[state->have++] = (unsigned short)len;
  83143. }
  83144. }
  83145. /* handle error breaks in while */
  83146. if (state->mode == BAD) break;
  83147. /* build code tables */
  83148. state->next = state->codes;
  83149. state->lencode = (code const FAR *)(state->next);
  83150. state->lenbits = 9;
  83151. ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
  83152. &(state->lenbits), state->work);
  83153. if (ret) {
  83154. strm->msg = (char *)"invalid literal/lengths set";
  83155. state->mode = BAD;
  83156. break;
  83157. }
  83158. state->distcode = (code const FAR *)(state->next);
  83159. state->distbits = 6;
  83160. ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
  83161. &(state->next), &(state->distbits), state->work);
  83162. if (ret) {
  83163. strm->msg = (char *)"invalid distances set";
  83164. state->mode = BAD;
  83165. break;
  83166. }
  83167. Tracev((stderr, "inflate: codes ok\n"));
  83168. state->mode = LEN;
  83169. case LEN:
  83170. if (have >= 6 && left >= 258) {
  83171. RESTORE();
  83172. inflate_fast(strm, out);
  83173. LOAD();
  83174. break;
  83175. }
  83176. for (;;) {
  83177. thisx = state->lencode[BITS(state->lenbits)];
  83178. if ((unsigned)(thisx.bits) <= bits) break;
  83179. PULLBYTE();
  83180. }
  83181. if (thisx.op && (thisx.op & 0xf0) == 0) {
  83182. last = thisx;
  83183. for (;;) {
  83184. thisx = state->lencode[last.val +
  83185. (BITS(last.bits + last.op) >> last.bits)];
  83186. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  83187. PULLBYTE();
  83188. }
  83189. DROPBITS(last.bits);
  83190. }
  83191. DROPBITS(thisx.bits);
  83192. state->length = (unsigned)thisx.val;
  83193. if ((int)(thisx.op) == 0) {
  83194. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  83195. "inflate: literal '%c'\n" :
  83196. "inflate: literal 0x%02x\n", thisx.val));
  83197. state->mode = LIT;
  83198. break;
  83199. }
  83200. if (thisx.op & 32) {
  83201. Tracevv((stderr, "inflate: end of block\n"));
  83202. state->mode = TYPE;
  83203. break;
  83204. }
  83205. if (thisx.op & 64) {
  83206. strm->msg = (char *)"invalid literal/length code";
  83207. state->mode = BAD;
  83208. break;
  83209. }
  83210. state->extra = (unsigned)(thisx.op) & 15;
  83211. state->mode = LENEXT;
  83212. case LENEXT:
  83213. if (state->extra) {
  83214. NEEDBITS(state->extra);
  83215. state->length += BITS(state->extra);
  83216. DROPBITS(state->extra);
  83217. }
  83218. Tracevv((stderr, "inflate: length %u\n", state->length));
  83219. state->mode = DIST;
  83220. case DIST:
  83221. for (;;) {
  83222. thisx = state->distcode[BITS(state->distbits)];
  83223. if ((unsigned)(thisx.bits) <= bits) break;
  83224. PULLBYTE();
  83225. }
  83226. if ((thisx.op & 0xf0) == 0) {
  83227. last = thisx;
  83228. for (;;) {
  83229. thisx = state->distcode[last.val +
  83230. (BITS(last.bits + last.op) >> last.bits)];
  83231. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  83232. PULLBYTE();
  83233. }
  83234. DROPBITS(last.bits);
  83235. }
  83236. DROPBITS(thisx.bits);
  83237. if (thisx.op & 64) {
  83238. strm->msg = (char *)"invalid distance code";
  83239. state->mode = BAD;
  83240. break;
  83241. }
  83242. state->offset = (unsigned)thisx.val;
  83243. state->extra = (unsigned)(thisx.op) & 15;
  83244. state->mode = DISTEXT;
  83245. case DISTEXT:
  83246. if (state->extra) {
  83247. NEEDBITS(state->extra);
  83248. state->offset += BITS(state->extra);
  83249. DROPBITS(state->extra);
  83250. }
  83251. #ifdef INFLATE_STRICT
  83252. if (state->offset > state->dmax) {
  83253. strm->msg = (char *)"invalid distance too far back";
  83254. state->mode = BAD;
  83255. break;
  83256. }
  83257. #endif
  83258. if (state->offset > state->whave + out - left) {
  83259. strm->msg = (char *)"invalid distance too far back";
  83260. state->mode = BAD;
  83261. break;
  83262. }
  83263. Tracevv((stderr, "inflate: distance %u\n", state->offset));
  83264. state->mode = MATCH;
  83265. case MATCH:
  83266. if (left == 0) goto inf_leave;
  83267. copy = out - left;
  83268. if (state->offset > copy) { /* copy from window */
  83269. copy = state->offset - copy;
  83270. if (copy > state->write) {
  83271. copy -= state->write;
  83272. from = state->window + (state->wsize - copy);
  83273. }
  83274. else
  83275. from = state->window + (state->write - copy);
  83276. if (copy > state->length) copy = state->length;
  83277. }
  83278. else { /* copy from output */
  83279. from = put - state->offset;
  83280. copy = state->length;
  83281. }
  83282. if (copy > left) copy = left;
  83283. left -= copy;
  83284. state->length -= copy;
  83285. do {
  83286. *put++ = *from++;
  83287. } while (--copy);
  83288. if (state->length == 0) state->mode = LEN;
  83289. break;
  83290. case LIT:
  83291. if (left == 0) goto inf_leave;
  83292. *put++ = (unsigned char)(state->length);
  83293. left--;
  83294. state->mode = LEN;
  83295. break;
  83296. case CHECK:
  83297. if (state->wrap) {
  83298. NEEDBITS(32);
  83299. out -= left;
  83300. strm->total_out += out;
  83301. state->total += out;
  83302. if (out)
  83303. strm->adler = state->check =
  83304. UPDATE(state->check, put - out, out);
  83305. out = left;
  83306. if ((
  83307. #ifdef GUNZIP
  83308. state->flags ? hold :
  83309. #endif
  83310. REVERSE(hold)) != state->check) {
  83311. strm->msg = (char *)"incorrect data check";
  83312. state->mode = BAD;
  83313. break;
  83314. }
  83315. INITBITS();
  83316. Tracev((stderr, "inflate: check matches trailer\n"));
  83317. }
  83318. #ifdef GUNZIP
  83319. state->mode = LENGTH;
  83320. case LENGTH:
  83321. if (state->wrap && state->flags) {
  83322. NEEDBITS(32);
  83323. if (hold != (state->total & 0xffffffffUL)) {
  83324. strm->msg = (char *)"incorrect length check";
  83325. state->mode = BAD;
  83326. break;
  83327. }
  83328. INITBITS();
  83329. Tracev((stderr, "inflate: length matches trailer\n"));
  83330. }
  83331. #endif
  83332. state->mode = DONE;
  83333. case DONE:
  83334. ret = Z_STREAM_END;
  83335. goto inf_leave;
  83336. case BAD:
  83337. ret = Z_DATA_ERROR;
  83338. goto inf_leave;
  83339. case MEM:
  83340. return Z_MEM_ERROR;
  83341. case SYNC:
  83342. default:
  83343. return Z_STREAM_ERROR;
  83344. }
  83345. /*
  83346. Return from inflate(), updating the total counts and the check value.
  83347. If there was no progress during the inflate() call, return a buffer
  83348. error. Call updatewindow() to create and/or update the window state.
  83349. Note: a memory error from inflate() is non-recoverable.
  83350. */
  83351. inf_leave:
  83352. RESTORE();
  83353. if (state->wsize || (state->mode < CHECK && out != strm->avail_out))
  83354. if (updatewindow(strm, out)) {
  83355. state->mode = MEM;
  83356. return Z_MEM_ERROR;
  83357. }
  83358. in -= strm->avail_in;
  83359. out -= strm->avail_out;
  83360. strm->total_in += in;
  83361. strm->total_out += out;
  83362. state->total += out;
  83363. if (state->wrap && out)
  83364. strm->adler = state->check =
  83365. UPDATE(state->check, strm->next_out - out, out);
  83366. strm->data_type = state->bits + (state->last ? 64 : 0) +
  83367. (state->mode == TYPE ? 128 : 0);
  83368. if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
  83369. ret = Z_BUF_ERROR;
  83370. return ret;
  83371. }
  83372. int ZEXPORT inflateEnd (z_streamp strm)
  83373. {
  83374. struct inflate_state FAR *state;
  83375. if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
  83376. return Z_STREAM_ERROR;
  83377. state = (struct inflate_state FAR *)strm->state;
  83378. if (state->window != Z_NULL) ZFREE(strm, state->window);
  83379. ZFREE(strm, strm->state);
  83380. strm->state = Z_NULL;
  83381. Tracev((stderr, "inflate: end\n"));
  83382. return Z_OK;
  83383. }
  83384. int ZEXPORT inflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  83385. {
  83386. struct inflate_state FAR *state;
  83387. unsigned long id_;
  83388. /* check state */
  83389. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83390. state = (struct inflate_state FAR *)strm->state;
  83391. if (state->wrap != 0 && state->mode != DICT)
  83392. return Z_STREAM_ERROR;
  83393. /* check for correct dictionary id */
  83394. if (state->mode == DICT) {
  83395. id_ = adler32(0L, Z_NULL, 0);
  83396. id_ = adler32(id_, dictionary, dictLength);
  83397. if (id_ != state->check)
  83398. return Z_DATA_ERROR;
  83399. }
  83400. /* copy dictionary to window */
  83401. if (updatewindow(strm, strm->avail_out)) {
  83402. state->mode = MEM;
  83403. return Z_MEM_ERROR;
  83404. }
  83405. if (dictLength > state->wsize) {
  83406. zmemcpy(state->window, dictionary + dictLength - state->wsize,
  83407. state->wsize);
  83408. state->whave = state->wsize;
  83409. }
  83410. else {
  83411. zmemcpy(state->window + state->wsize - dictLength, dictionary,
  83412. dictLength);
  83413. state->whave = dictLength;
  83414. }
  83415. state->havedict = 1;
  83416. Tracev((stderr, "inflate: dictionary set\n"));
  83417. return Z_OK;
  83418. }
  83419. int ZEXPORT inflateGetHeader (z_streamp strm, gz_headerp head)
  83420. {
  83421. struct inflate_state FAR *state;
  83422. /* check state */
  83423. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83424. state = (struct inflate_state FAR *)strm->state;
  83425. if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
  83426. /* save header structure */
  83427. state->head = head;
  83428. head->done = 0;
  83429. return Z_OK;
  83430. }
  83431. /*
  83432. Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found
  83433. or when out of input. When called, *have is the number of pattern bytes
  83434. found in order so far, in 0..3. On return *have is updated to the new
  83435. state. If on return *have equals four, then the pattern was found and the
  83436. return value is how many bytes were read including the last byte of the
  83437. pattern. If *have is less than four, then the pattern has not been found
  83438. yet and the return value is len. In the latter case, syncsearch() can be
  83439. called again with more data and the *have state. *have is initialized to
  83440. zero for the first call.
  83441. */
  83442. local unsigned syncsearch (unsigned FAR *have, unsigned char FAR *buf, unsigned len)
  83443. {
  83444. unsigned got;
  83445. unsigned next;
  83446. got = *have;
  83447. next = 0;
  83448. while (next < len && got < 4) {
  83449. if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
  83450. got++;
  83451. else if (buf[next])
  83452. got = 0;
  83453. else
  83454. got = 4 - got;
  83455. next++;
  83456. }
  83457. *have = got;
  83458. return next;
  83459. }
  83460. int ZEXPORT inflateSync (z_streamp strm)
  83461. {
  83462. unsigned len; /* number of bytes to look at or looked at */
  83463. unsigned long in, out; /* temporary to save total_in and total_out */
  83464. unsigned char buf[4]; /* to restore bit buffer to byte string */
  83465. struct inflate_state FAR *state;
  83466. /* check parameters */
  83467. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83468. state = (struct inflate_state FAR *)strm->state;
  83469. if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
  83470. /* if first time, start search in bit buffer */
  83471. if (state->mode != SYNC) {
  83472. state->mode = SYNC;
  83473. state->hold <<= state->bits & 7;
  83474. state->bits -= state->bits & 7;
  83475. len = 0;
  83476. while (state->bits >= 8) {
  83477. buf[len++] = (unsigned char)(state->hold);
  83478. state->hold >>= 8;
  83479. state->bits -= 8;
  83480. }
  83481. state->have = 0;
  83482. syncsearch(&(state->have), buf, len);
  83483. }
  83484. /* search available input */
  83485. len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
  83486. strm->avail_in -= len;
  83487. strm->next_in += len;
  83488. strm->total_in += len;
  83489. /* return no joy or set up to restart inflate() on a new block */
  83490. if (state->have != 4) return Z_DATA_ERROR;
  83491. in = strm->total_in; out = strm->total_out;
  83492. inflateReset(strm);
  83493. strm->total_in = in; strm->total_out = out;
  83494. state->mode = TYPE;
  83495. return Z_OK;
  83496. }
  83497. /*
  83498. Returns true if inflate is currently at the end of a block generated by
  83499. Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
  83500. implementation to provide an additional safety check. PPP uses
  83501. Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
  83502. block. When decompressing, PPP checks that at the end of input packet,
  83503. inflate is waiting for these length bytes.
  83504. */
  83505. int ZEXPORT inflateSyncPoint (z_streamp strm)
  83506. {
  83507. struct inflate_state FAR *state;
  83508. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83509. state = (struct inflate_state FAR *)strm->state;
  83510. return state->mode == STORED && state->bits == 0;
  83511. }
  83512. int ZEXPORT inflateCopy(z_streamp dest, z_streamp source)
  83513. {
  83514. struct inflate_state FAR *state;
  83515. struct inflate_state FAR *copy;
  83516. unsigned char FAR *window;
  83517. unsigned wsize;
  83518. /* check input */
  83519. if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||
  83520. source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)
  83521. return Z_STREAM_ERROR;
  83522. state = (struct inflate_state FAR *)source->state;
  83523. /* allocate space */
  83524. copy = (struct inflate_state FAR *)
  83525. ZALLOC(source, 1, sizeof(struct inflate_state));
  83526. if (copy == Z_NULL) return Z_MEM_ERROR;
  83527. window = Z_NULL;
  83528. if (state->window != Z_NULL) {
  83529. window = (unsigned char FAR *)
  83530. ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
  83531. if (window == Z_NULL) {
  83532. ZFREE(source, copy);
  83533. return Z_MEM_ERROR;
  83534. }
  83535. }
  83536. /* copy state */
  83537. zmemcpy(dest, source, sizeof(z_stream));
  83538. zmemcpy(copy, state, sizeof(struct inflate_state));
  83539. if (state->lencode >= state->codes &&
  83540. state->lencode <= state->codes + ENOUGH - 1) {
  83541. copy->lencode = copy->codes + (state->lencode - state->codes);
  83542. copy->distcode = copy->codes + (state->distcode - state->codes);
  83543. }
  83544. copy->next = copy->codes + (state->next - state->codes);
  83545. if (window != Z_NULL) {
  83546. wsize = 1U << state->wbits;
  83547. zmemcpy(window, state->window, wsize);
  83548. }
  83549. copy->window = window;
  83550. dest->state = (struct internal_state FAR *)copy;
  83551. return Z_OK;
  83552. }
  83553. /*** End of inlined file: inflate.c ***/
  83554. /*** Start of inlined file: inftrees.c ***/
  83555. #define MAXBITS 15
  83556. const char inflate_copyright[] =
  83557. " inflate 1.2.3 Copyright 1995-2005 Mark Adler ";
  83558. /*
  83559. If you use the zlib library in a product, an acknowledgment is welcome
  83560. in the documentation of your product. If for some reason you cannot
  83561. include such an acknowledgment, I would appreciate that you keep this
  83562. copyright string in the executable of your product.
  83563. */
  83564. /*
  83565. Build a set of tables to decode the provided canonical Huffman code.
  83566. The code lengths are lens[0..codes-1]. The result starts at *table,
  83567. whose indices are 0..2^bits-1. work is a writable array of at least
  83568. lens shorts, which is used as a work area. type is the type of code
  83569. to be generated, CODES, LENS, or DISTS. On return, zero is success,
  83570. -1 is an invalid code, and +1 means that ENOUGH isn't enough. table
  83571. on return points to the next available entry's address. bits is the
  83572. requested root table index bits, and on return it is the actual root
  83573. table index bits. It will differ if the request is greater than the
  83574. longest code or if it is less than the shortest code.
  83575. */
  83576. int inflate_table (codetype type,
  83577. unsigned short FAR *lens,
  83578. unsigned codes,
  83579. code FAR * FAR *table,
  83580. unsigned FAR *bits,
  83581. unsigned short FAR *work)
  83582. {
  83583. unsigned len; /* a code's length in bits */
  83584. unsigned sym; /* index of code symbols */
  83585. unsigned min, max; /* minimum and maximum code lengths */
  83586. unsigned root; /* number of index bits for root table */
  83587. unsigned curr; /* number of index bits for current table */
  83588. unsigned drop; /* code bits to drop for sub-table */
  83589. int left; /* number of prefix codes available */
  83590. unsigned used; /* code entries in table used */
  83591. unsigned huff; /* Huffman code */
  83592. unsigned incr; /* for incrementing code, index */
  83593. unsigned fill; /* index for replicating entries */
  83594. unsigned low; /* low bits for current root entry */
  83595. unsigned mask; /* mask for low root bits */
  83596. code thisx; /* table entry for duplication */
  83597. code FAR *next; /* next available space in table */
  83598. const unsigned short FAR *base; /* base value table to use */
  83599. const unsigned short FAR *extra; /* extra bits table to use */
  83600. int end; /* use base and extra for symbol > end */
  83601. unsigned short count[MAXBITS+1]; /* number of codes of each length */
  83602. unsigned short offs[MAXBITS+1]; /* offsets in table for each length */
  83603. static const unsigned short lbase[31] = { /* Length codes 257..285 base */
  83604. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  83605. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  83606. static const unsigned short lext[31] = { /* Length codes 257..285 extra */
  83607. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  83608. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196};
  83609. static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
  83610. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  83611. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  83612. 8193, 12289, 16385, 24577, 0, 0};
  83613. static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
  83614. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  83615. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  83616. 28, 28, 29, 29, 64, 64};
  83617. /*
  83618. Process a set of code lengths to create a canonical Huffman code. The
  83619. code lengths are lens[0..codes-1]. Each length corresponds to the
  83620. symbols 0..codes-1. The Huffman code is generated by first sorting the
  83621. symbols by length from short to long, and retaining the symbol order
  83622. for codes with equal lengths. Then the code starts with all zero bits
  83623. for the first code of the shortest length, and the codes are integer
  83624. increments for the same length, and zeros are appended as the length
  83625. increases. For the deflate format, these bits are stored backwards
  83626. from their more natural integer increment ordering, and so when the
  83627. decoding tables are built in the large loop below, the integer codes
  83628. are incremented backwards.
  83629. This routine assumes, but does not check, that all of the entries in
  83630. lens[] are in the range 0..MAXBITS. The caller must assure this.
  83631. 1..MAXBITS is interpreted as that code length. zero means that that
  83632. symbol does not occur in this code.
  83633. The codes are sorted by computing a count of codes for each length,
  83634. creating from that a table of starting indices for each length in the
  83635. sorted table, and then entering the symbols in order in the sorted
  83636. table. The sorted table is work[], with that space being provided by
  83637. the caller.
  83638. The length counts are used for other purposes as well, i.e. finding
  83639. the minimum and maximum length codes, determining if there are any
  83640. codes at all, checking for a valid set of lengths, and looking ahead
  83641. at length counts to determine sub-table sizes when building the
  83642. decoding tables.
  83643. */
  83644. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  83645. for (len = 0; len <= MAXBITS; len++)
  83646. count[len] = 0;
  83647. for (sym = 0; sym < codes; sym++)
  83648. count[lens[sym]]++;
  83649. /* bound code lengths, force root to be within code lengths */
  83650. root = *bits;
  83651. for (max = MAXBITS; max >= 1; max--)
  83652. if (count[max] != 0) break;
  83653. if (root > max) root = max;
  83654. if (max == 0) { /* no symbols to code at all */
  83655. thisx.op = (unsigned char)64; /* invalid code marker */
  83656. thisx.bits = (unsigned char)1;
  83657. thisx.val = (unsigned short)0;
  83658. *(*table)++ = thisx; /* make a table to force an error */
  83659. *(*table)++ = thisx;
  83660. *bits = 1;
  83661. return 0; /* no symbols, but wait for decoding to report error */
  83662. }
  83663. for (min = 1; min <= MAXBITS; min++)
  83664. if (count[min] != 0) break;
  83665. if (root < min) root = min;
  83666. /* check for an over-subscribed or incomplete set of lengths */
  83667. left = 1;
  83668. for (len = 1; len <= MAXBITS; len++) {
  83669. left <<= 1;
  83670. left -= count[len];
  83671. if (left < 0) return -1; /* over-subscribed */
  83672. }
  83673. if (left > 0 && (type == CODES || max != 1))
  83674. return -1; /* incomplete set */
  83675. /* generate offsets into symbol table for each length for sorting */
  83676. offs[1] = 0;
  83677. for (len = 1; len < MAXBITS; len++)
  83678. offs[len + 1] = offs[len] + count[len];
  83679. /* sort symbols by length, by symbol order within each length */
  83680. for (sym = 0; sym < codes; sym++)
  83681. if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
  83682. /*
  83683. Create and fill in decoding tables. In this loop, the table being
  83684. filled is at next and has curr index bits. The code being used is huff
  83685. with length len. That code is converted to an index by dropping drop
  83686. bits off of the bottom. For codes where len is less than drop + curr,
  83687. those top drop + curr - len bits are incremented through all values to
  83688. fill the table with replicated entries.
  83689. root is the number of index bits for the root table. When len exceeds
  83690. root, sub-tables are created pointed to by the root entry with an index
  83691. of the low root bits of huff. This is saved in low to check for when a
  83692. new sub-table should be started. drop is zero when the root table is
  83693. being filled, and drop is root when sub-tables are being filled.
  83694. When a new sub-table is needed, it is necessary to look ahead in the
  83695. code lengths to determine what size sub-table is needed. The length
  83696. counts are used for this, and so count[] is decremented as codes are
  83697. entered in the tables.
  83698. used keeps track of how many table entries have been allocated from the
  83699. provided *table space. It is checked when a LENS table is being made
  83700. against the space in *table, ENOUGH, minus the maximum space needed by
  83701. the worst case distance code, MAXD. This should never happen, but the
  83702. sufficiency of ENOUGH has not been proven exhaustively, hence the check.
  83703. This assumes that when type == LENS, bits == 9.
  83704. sym increments through all symbols, and the loop terminates when
  83705. all codes of length max, i.e. all codes, have been processed. This
  83706. routine permits incomplete codes, so another loop after this one fills
  83707. in the rest of the decoding tables with invalid code markers.
  83708. */
  83709. /* set up for code type */
  83710. switch (type) {
  83711. case CODES:
  83712. base = extra = work; /* dummy value--not used */
  83713. end = 19;
  83714. break;
  83715. case LENS:
  83716. base = lbase;
  83717. base -= 257;
  83718. extra = lext;
  83719. extra -= 257;
  83720. end = 256;
  83721. break;
  83722. default: /* DISTS */
  83723. base = dbase;
  83724. extra = dext;
  83725. end = -1;
  83726. }
  83727. /* initialize state for loop */
  83728. huff = 0; /* starting code */
  83729. sym = 0; /* starting code symbol */
  83730. len = min; /* starting code length */
  83731. next = *table; /* current table to fill in */
  83732. curr = root; /* current table index bits */
  83733. drop = 0; /* current bits to drop from code for index */
  83734. low = (unsigned)(-1); /* trigger new sub-table when len > root */
  83735. used = 1U << root; /* use root table entries */
  83736. mask = used - 1; /* mask for comparing low */
  83737. /* check available table space */
  83738. if (type == LENS && used >= ENOUGH - MAXD)
  83739. return 1;
  83740. /* process all codes and make table entries */
  83741. for (;;) {
  83742. /* create table entry */
  83743. thisx.bits = (unsigned char)(len - drop);
  83744. if ((int)(work[sym]) < end) {
  83745. thisx.op = (unsigned char)0;
  83746. thisx.val = work[sym];
  83747. }
  83748. else if ((int)(work[sym]) > end) {
  83749. thisx.op = (unsigned char)(extra[work[sym]]);
  83750. thisx.val = base[work[sym]];
  83751. }
  83752. else {
  83753. thisx.op = (unsigned char)(32 + 64); /* end of block */
  83754. thisx.val = 0;
  83755. }
  83756. /* replicate for those indices with low len bits equal to huff */
  83757. incr = 1U << (len - drop);
  83758. fill = 1U << curr;
  83759. min = fill; /* save offset to next table */
  83760. do {
  83761. fill -= incr;
  83762. next[(huff >> drop) + fill] = thisx;
  83763. } while (fill != 0);
  83764. /* backwards increment the len-bit code huff */
  83765. incr = 1U << (len - 1);
  83766. while (huff & incr)
  83767. incr >>= 1;
  83768. if (incr != 0) {
  83769. huff &= incr - 1;
  83770. huff += incr;
  83771. }
  83772. else
  83773. huff = 0;
  83774. /* go to next symbol, update count, len */
  83775. sym++;
  83776. if (--(count[len]) == 0) {
  83777. if (len == max) break;
  83778. len = lens[work[sym]];
  83779. }
  83780. /* create new sub-table if needed */
  83781. if (len > root && (huff & mask) != low) {
  83782. /* if first time, transition to sub-tables */
  83783. if (drop == 0)
  83784. drop = root;
  83785. /* increment past last table */
  83786. next += min; /* here min is 1 << curr */
  83787. /* determine length of next table */
  83788. curr = len - drop;
  83789. left = (int)(1 << curr);
  83790. while (curr + drop < max) {
  83791. left -= count[curr + drop];
  83792. if (left <= 0) break;
  83793. curr++;
  83794. left <<= 1;
  83795. }
  83796. /* check for enough space */
  83797. used += 1U << curr;
  83798. if (type == LENS && used >= ENOUGH - MAXD)
  83799. return 1;
  83800. /* point entry in root table to sub-table */
  83801. low = huff & mask;
  83802. (*table)[low].op = (unsigned char)curr;
  83803. (*table)[low].bits = (unsigned char)root;
  83804. (*table)[low].val = (unsigned short)(next - *table);
  83805. }
  83806. }
  83807. /*
  83808. Fill in rest of table for incomplete codes. This loop is similar to the
  83809. loop above in incrementing huff for table indices. It is assumed that
  83810. len is equal to curr + drop, so there is no loop needed to increment
  83811. through high index bits. When the current sub-table is filled, the loop
  83812. drops back to the root table to fill in any remaining entries there.
  83813. */
  83814. thisx.op = (unsigned char)64; /* invalid code marker */
  83815. thisx.bits = (unsigned char)(len - drop);
  83816. thisx.val = (unsigned short)0;
  83817. while (huff != 0) {
  83818. /* when done with sub-table, drop back to root table */
  83819. if (drop != 0 && (huff & mask) != low) {
  83820. drop = 0;
  83821. len = root;
  83822. next = *table;
  83823. thisx.bits = (unsigned char)len;
  83824. }
  83825. /* put invalid code marker in table */
  83826. next[huff >> drop] = thisx;
  83827. /* backwards increment the len-bit code huff */
  83828. incr = 1U << (len - 1);
  83829. while (huff & incr)
  83830. incr >>= 1;
  83831. if (incr != 0) {
  83832. huff &= incr - 1;
  83833. huff += incr;
  83834. }
  83835. else
  83836. huff = 0;
  83837. }
  83838. /* set return parameters */
  83839. *table += used;
  83840. *bits = root;
  83841. return 0;
  83842. }
  83843. /*** End of inlined file: inftrees.c ***/
  83844. /*** Start of inlined file: trees.c ***/
  83845. /*
  83846. * ALGORITHM
  83847. *
  83848. * The "deflation" process uses several Huffman trees. The more
  83849. * common source values are represented by shorter bit sequences.
  83850. *
  83851. * Each code tree is stored in a compressed form which is itself
  83852. * a Huffman encoding of the lengths of all the code strings (in
  83853. * ascending order by source values). The actual code strings are
  83854. * reconstructed from the lengths in the inflate process, as described
  83855. * in the deflate specification.
  83856. *
  83857. * REFERENCES
  83858. *
  83859. * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  83860. * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  83861. *
  83862. * Storer, James A.
  83863. * Data Compression: Methods and Theory, pp. 49-50.
  83864. * Computer Science Press, 1988. ISBN 0-7167-8156-5.
  83865. *
  83866. * Sedgewick, R.
  83867. * Algorithms, p290.
  83868. * Addison-Wesley, 1983. ISBN 0-201-06672-6.
  83869. */
  83870. /* @(#) $Id: trees.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  83871. /* #define GEN_TREES_H */
  83872. #ifdef DEBUG
  83873. # include <ctype.h>
  83874. #endif
  83875. /* ===========================================================================
  83876. * Constants
  83877. */
  83878. #define MAX_BL_BITS 7
  83879. /* Bit length codes must not exceed MAX_BL_BITS bits */
  83880. #define END_BLOCK 256
  83881. /* end of block literal code */
  83882. #define REP_3_6 16
  83883. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  83884. #define REPZ_3_10 17
  83885. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  83886. #define REPZ_11_138 18
  83887. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  83888. local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
  83889. = {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};
  83890. local const int extra_dbits[D_CODES] /* extra bits for each distance code */
  83891. = {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};
  83892. local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
  83893. = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  83894. local const uch bl_order[BL_CODES]
  83895. = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  83896. /* The lengths of the bit length codes are sent in order of decreasing
  83897. * probability, to avoid transmitting the lengths for unused bit length codes.
  83898. */
  83899. #define Buf_size (8 * 2*sizeof(char))
  83900. /* Number of bits used within bi_buf. (bi_buf might be implemented on
  83901. * more than 16 bits on some systems.)
  83902. */
  83903. /* ===========================================================================
  83904. * Local data. These are initialized only once.
  83905. */
  83906. #define DIST_CODE_LEN 512 /* see definition of array dist_code below */
  83907. #if defined(GEN_TREES_H) || !defined(STDC)
  83908. /* non ANSI compilers may not accept trees.h */
  83909. local ct_data static_ltree[L_CODES+2];
  83910. /* The static literal tree. Since the bit lengths are imposed, there is no
  83911. * need for the L_CODES extra codes used during heap construction. However
  83912. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  83913. * below).
  83914. */
  83915. local ct_data static_dtree[D_CODES];
  83916. /* The static distance tree. (Actually a trivial tree since all codes use
  83917. * 5 bits.)
  83918. */
  83919. uch _dist_code[DIST_CODE_LEN];
  83920. /* Distance codes. The first 256 values correspond to the distances
  83921. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  83922. * the 15 bit distances.
  83923. */
  83924. uch _length_code[MAX_MATCH-MIN_MATCH+1];
  83925. /* length code for each normalized match length (0 == MIN_MATCH) */
  83926. local int base_length[LENGTH_CODES];
  83927. /* First normalized length for each code (0 = MIN_MATCH) */
  83928. local int base_dist[D_CODES];
  83929. /* First normalized distance for each code (0 = distance of 1) */
  83930. #else
  83931. /*** Start of inlined file: trees.h ***/
  83932. local const ct_data static_ltree[L_CODES+2] = {
  83933. {{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}},
  83934. {{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}},
  83935. {{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}},
  83936. {{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}},
  83937. {{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}},
  83938. {{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}},
  83939. {{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}},
  83940. {{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}},
  83941. {{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}},
  83942. {{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}},
  83943. {{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}},
  83944. {{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}},
  83945. {{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}},
  83946. {{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}},
  83947. {{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}},
  83948. {{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}},
  83949. {{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}},
  83950. {{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}},
  83951. {{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}},
  83952. {{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}},
  83953. {{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}},
  83954. {{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}},
  83955. {{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}},
  83956. {{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}},
  83957. {{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}},
  83958. {{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}},
  83959. {{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}},
  83960. {{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}},
  83961. {{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}},
  83962. {{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}},
  83963. {{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}},
  83964. {{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}},
  83965. {{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}},
  83966. {{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}},
  83967. {{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}},
  83968. {{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}},
  83969. {{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}},
  83970. {{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}},
  83971. {{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}},
  83972. {{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}},
  83973. {{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}},
  83974. {{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}},
  83975. {{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}},
  83976. {{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}},
  83977. {{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}},
  83978. {{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}},
  83979. {{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}},
  83980. {{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}},
  83981. {{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}},
  83982. {{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}},
  83983. {{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}},
  83984. {{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}},
  83985. {{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}},
  83986. {{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}},
  83987. {{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}},
  83988. {{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}},
  83989. {{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}},
  83990. {{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}}
  83991. };
  83992. local const ct_data static_dtree[D_CODES] = {
  83993. {{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
  83994. {{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
  83995. {{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
  83996. {{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
  83997. {{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
  83998. {{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
  83999. };
  84000. const uch _dist_code[DIST_CODE_LEN] = {
  84001. 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
  84002. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
  84003. 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
  84004. 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  84005. 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
  84006. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  84007. 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84008. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84009. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84010. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
  84011. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  84012. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  84013. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
  84014. 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
  84015. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84016. 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  84017. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  84018. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
  84019. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  84020. 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84021. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84022. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84023. 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84024. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84025. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84026. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
  84027. };
  84028. const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {
  84029. 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
  84030. 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
  84031. 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
  84032. 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  84033. 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
  84034. 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
  84035. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84036. 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84037. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  84038. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
  84039. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  84040. 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  84041. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
  84042. };
  84043. local const int base_length[LENGTH_CODES] = {
  84044. 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
  84045. 64, 80, 96, 112, 128, 160, 192, 224, 0
  84046. };
  84047. local const int base_dist[D_CODES] = {
  84048. 0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
  84049. 32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
  84050. 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
  84051. };
  84052. /*** End of inlined file: trees.h ***/
  84053. #endif /* GEN_TREES_H */
  84054. struct static_tree_desc_s {
  84055. const ct_data *static_tree; /* static tree or NULL */
  84056. const intf *extra_bits; /* extra bits for each code or NULL */
  84057. int extra_base; /* base index for extra_bits */
  84058. int elems; /* max number of elements in the tree */
  84059. int max_length; /* max bit length for the codes */
  84060. };
  84061. local static_tree_desc static_l_desc =
  84062. {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
  84063. local static_tree_desc static_d_desc =
  84064. {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
  84065. local static_tree_desc static_bl_desc =
  84066. {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
  84067. /* ===========================================================================
  84068. * Local (static) routines in this file.
  84069. */
  84070. local void tr_static_init OF((void));
  84071. local void init_block OF((deflate_state *s));
  84072. local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));
  84073. local void gen_bitlen OF((deflate_state *s, tree_desc *desc));
  84074. local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));
  84075. local void build_tree OF((deflate_state *s, tree_desc *desc));
  84076. local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));
  84077. local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));
  84078. local int build_bl_tree OF((deflate_state *s));
  84079. local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
  84080. int blcodes));
  84081. local void compress_block OF((deflate_state *s, ct_data *ltree,
  84082. ct_data *dtree));
  84083. local void set_data_type OF((deflate_state *s));
  84084. local unsigned bi_reverse OF((unsigned value, int length));
  84085. local void bi_windup OF((deflate_state *s));
  84086. local void bi_flush OF((deflate_state *s));
  84087. local void copy_block OF((deflate_state *s, charf *buf, unsigned len,
  84088. int header));
  84089. #ifdef GEN_TREES_H
  84090. local void gen_trees_header OF((void));
  84091. #endif
  84092. #ifndef DEBUG
  84093. # define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
  84094. /* Send a code of the given tree. c and tree must not have side effects */
  84095. #else /* DEBUG */
  84096. # define send_code(s, c, tree) \
  84097. { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
  84098. send_bits(s, tree[c].Code, tree[c].Len); }
  84099. #endif
  84100. /* ===========================================================================
  84101. * Output a short LSB first on the stream.
  84102. * IN assertion: there is enough room in pendingBuf.
  84103. */
  84104. #define put_short(s, w) { \
  84105. put_byte(s, (uch)((w) & 0xff)); \
  84106. put_byte(s, (uch)((ush)(w) >> 8)); \
  84107. }
  84108. /* ===========================================================================
  84109. * Send a value on a given number of bits.
  84110. * IN assertion: length <= 16 and value fits in length bits.
  84111. */
  84112. #ifdef DEBUG
  84113. local void send_bits OF((deflate_state *s, int value, int length));
  84114. local void send_bits (deflate_state *s, int value, int length)
  84115. {
  84116. Tracevv((stderr," l %2d v %4x ", length, value));
  84117. Assert(length > 0 && length <= 15, "invalid length");
  84118. s->bits_sent += (ulg)length;
  84119. /* If not enough room in bi_buf, use (valid) bits from bi_buf and
  84120. * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
  84121. * unused bits in value.
  84122. */
  84123. if (s->bi_valid > (int)Buf_size - length) {
  84124. s->bi_buf |= (value << s->bi_valid);
  84125. put_short(s, s->bi_buf);
  84126. s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
  84127. s->bi_valid += length - Buf_size;
  84128. } else {
  84129. s->bi_buf |= value << s->bi_valid;
  84130. s->bi_valid += length;
  84131. }
  84132. }
  84133. #else /* !DEBUG */
  84134. #define send_bits(s, value, length) \
  84135. { int len = length;\
  84136. if (s->bi_valid > (int)Buf_size - len) {\
  84137. int val = value;\
  84138. s->bi_buf |= (val << s->bi_valid);\
  84139. put_short(s, s->bi_buf);\
  84140. s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
  84141. s->bi_valid += len - Buf_size;\
  84142. } else {\
  84143. s->bi_buf |= (value) << s->bi_valid;\
  84144. s->bi_valid += len;\
  84145. }\
  84146. }
  84147. #endif /* DEBUG */
  84148. /* the arguments must not have side effects */
  84149. /* ===========================================================================
  84150. * Initialize the various 'constant' tables.
  84151. */
  84152. local void tr_static_init()
  84153. {
  84154. #if defined(GEN_TREES_H) || !defined(STDC)
  84155. static int static_init_done = 0;
  84156. int n; /* iterates over tree elements */
  84157. int bits; /* bit counter */
  84158. int length; /* length value */
  84159. int code; /* code value */
  84160. int dist; /* distance index */
  84161. ush bl_count[MAX_BITS+1];
  84162. /* number of codes at each bit length for an optimal tree */
  84163. if (static_init_done) return;
  84164. /* For some embedded targets, global variables are not initialized: */
  84165. static_l_desc.static_tree = static_ltree;
  84166. static_l_desc.extra_bits = extra_lbits;
  84167. static_d_desc.static_tree = static_dtree;
  84168. static_d_desc.extra_bits = extra_dbits;
  84169. static_bl_desc.extra_bits = extra_blbits;
  84170. /* Initialize the mapping length (0..255) -> length code (0..28) */
  84171. length = 0;
  84172. for (code = 0; code < LENGTH_CODES-1; code++) {
  84173. base_length[code] = length;
  84174. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  84175. _length_code[length++] = (uch)code;
  84176. }
  84177. }
  84178. Assert (length == 256, "tr_static_init: length != 256");
  84179. /* Note that the length 255 (match length 258) can be represented
  84180. * in two different ways: code 284 + 5 bits or code 285, so we
  84181. * overwrite length_code[255] to use the best encoding:
  84182. */
  84183. _length_code[length-1] = (uch)code;
  84184. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  84185. dist = 0;
  84186. for (code = 0 ; code < 16; code++) {
  84187. base_dist[code] = dist;
  84188. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  84189. _dist_code[dist++] = (uch)code;
  84190. }
  84191. }
  84192. Assert (dist == 256, "tr_static_init: dist != 256");
  84193. dist >>= 7; /* from now on, all distances are divided by 128 */
  84194. for ( ; code < D_CODES; code++) {
  84195. base_dist[code] = dist << 7;
  84196. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  84197. _dist_code[256 + dist++] = (uch)code;
  84198. }
  84199. }
  84200. Assert (dist == 256, "tr_static_init: 256+dist != 512");
  84201. /* Construct the codes of the static literal tree */
  84202. for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
  84203. n = 0;
  84204. while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
  84205. while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
  84206. while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
  84207. while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
  84208. /* Codes 286 and 287 do not exist, but we must include them in the
  84209. * tree construction to get a canonical Huffman tree (longest code
  84210. * all ones)
  84211. */
  84212. gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
  84213. /* The static distance tree is trivial: */
  84214. for (n = 0; n < D_CODES; n++) {
  84215. static_dtree[n].Len = 5;
  84216. static_dtree[n].Code = bi_reverse((unsigned)n, 5);
  84217. }
  84218. static_init_done = 1;
  84219. # ifdef GEN_TREES_H
  84220. gen_trees_header();
  84221. # endif
  84222. #endif /* defined(GEN_TREES_H) || !defined(STDC) */
  84223. }
  84224. /* ===========================================================================
  84225. * Genererate the file trees.h describing the static trees.
  84226. */
  84227. #ifdef GEN_TREES_H
  84228. # ifndef DEBUG
  84229. # include <stdio.h>
  84230. # endif
  84231. # define SEPARATOR(i, last, width) \
  84232. ((i) == (last)? "\n};\n\n" : \
  84233. ((i) % (width) == (width)-1 ? ",\n" : ", "))
  84234. void gen_trees_header()
  84235. {
  84236. FILE *header = fopen("trees.h", "w");
  84237. int i;
  84238. Assert (header != NULL, "Can't open trees.h");
  84239. fprintf(header,
  84240. "/* header created automatically with -DGEN_TREES_H */\n\n");
  84241. fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
  84242. for (i = 0; i < L_CODES+2; i++) {
  84243. fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
  84244. static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
  84245. }
  84246. fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
  84247. for (i = 0; i < D_CODES; i++) {
  84248. fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
  84249. static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
  84250. }
  84251. fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
  84252. for (i = 0; i < DIST_CODE_LEN; i++) {
  84253. fprintf(header, "%2u%s", _dist_code[i],
  84254. SEPARATOR(i, DIST_CODE_LEN-1, 20));
  84255. }
  84256. fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
  84257. for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
  84258. fprintf(header, "%2u%s", _length_code[i],
  84259. SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
  84260. }
  84261. fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
  84262. for (i = 0; i < LENGTH_CODES; i++) {
  84263. fprintf(header, "%1u%s", base_length[i],
  84264. SEPARATOR(i, LENGTH_CODES-1, 20));
  84265. }
  84266. fprintf(header, "local const int base_dist[D_CODES] = {\n");
  84267. for (i = 0; i < D_CODES; i++) {
  84268. fprintf(header, "%5u%s", base_dist[i],
  84269. SEPARATOR(i, D_CODES-1, 10));
  84270. }
  84271. fclose(header);
  84272. }
  84273. #endif /* GEN_TREES_H */
  84274. /* ===========================================================================
  84275. * Initialize the tree data structures for a new zlib stream.
  84276. */
  84277. void _tr_init(deflate_state *s)
  84278. {
  84279. tr_static_init();
  84280. s->l_desc.dyn_tree = s->dyn_ltree;
  84281. s->l_desc.stat_desc = &static_l_desc;
  84282. s->d_desc.dyn_tree = s->dyn_dtree;
  84283. s->d_desc.stat_desc = &static_d_desc;
  84284. s->bl_desc.dyn_tree = s->bl_tree;
  84285. s->bl_desc.stat_desc = &static_bl_desc;
  84286. s->bi_buf = 0;
  84287. s->bi_valid = 0;
  84288. s->last_eob_len = 8; /* enough lookahead for inflate */
  84289. #ifdef DEBUG
  84290. s->compressed_len = 0L;
  84291. s->bits_sent = 0L;
  84292. #endif
  84293. /* Initialize the first block of the first file: */
  84294. init_block(s);
  84295. }
  84296. /* ===========================================================================
  84297. * Initialize a new block.
  84298. */
  84299. local void init_block (deflate_state *s)
  84300. {
  84301. int n; /* iterates over tree elements */
  84302. /* Initialize the trees. */
  84303. for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
  84304. for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
  84305. for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
  84306. s->dyn_ltree[END_BLOCK].Freq = 1;
  84307. s->opt_len = s->static_len = 0L;
  84308. s->last_lit = s->matches = 0;
  84309. }
  84310. #define SMALLEST 1
  84311. /* Index within the heap array of least frequent node in the Huffman tree */
  84312. /* ===========================================================================
  84313. * Remove the smallest element from the heap and recreate the heap with
  84314. * one less element. Updates heap and heap_len.
  84315. */
  84316. #define pqremove(s, tree, top) \
  84317. {\
  84318. top = s->heap[SMALLEST]; \
  84319. s->heap[SMALLEST] = s->heap[s->heap_len--]; \
  84320. pqdownheap(s, tree, SMALLEST); \
  84321. }
  84322. /* ===========================================================================
  84323. * Compares to subtrees, using the tree depth as tie breaker when
  84324. * the subtrees have equal frequency. This minimizes the worst case length.
  84325. */
  84326. #define smaller(tree, n, m, depth) \
  84327. (tree[n].Freq < tree[m].Freq || \
  84328. (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
  84329. /* ===========================================================================
  84330. * Restore the heap property by moving down the tree starting at node k,
  84331. * exchanging a node with the smallest of its two sons if necessary, stopping
  84332. * when the heap property is re-established (each father smaller than its
  84333. * two sons).
  84334. */
  84335. local void pqdownheap (deflate_state *s,
  84336. ct_data *tree, /* the tree to restore */
  84337. int k) /* node to move down */
  84338. {
  84339. int v = s->heap[k];
  84340. int j = k << 1; /* left son of k */
  84341. while (j <= s->heap_len) {
  84342. /* Set j to the smallest of the two sons: */
  84343. if (j < s->heap_len &&
  84344. smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
  84345. j++;
  84346. }
  84347. /* Exit if v is smaller than both sons */
  84348. if (smaller(tree, v, s->heap[j], s->depth)) break;
  84349. /* Exchange v with the smallest son */
  84350. s->heap[k] = s->heap[j]; k = j;
  84351. /* And continue down the tree, setting j to the left son of k */
  84352. j <<= 1;
  84353. }
  84354. s->heap[k] = v;
  84355. }
  84356. /* ===========================================================================
  84357. * Compute the optimal bit lengths for a tree and update the total bit length
  84358. * for the current block.
  84359. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  84360. * above are the tree nodes sorted by increasing frequency.
  84361. * OUT assertions: the field len is set to the optimal bit length, the
  84362. * array bl_count contains the frequencies for each bit length.
  84363. * The length opt_len is updated; static_len is also updated if stree is
  84364. * not null.
  84365. */
  84366. local void gen_bitlen (deflate_state *s, tree_desc *desc)
  84367. {
  84368. ct_data *tree = desc->dyn_tree;
  84369. int max_code = desc->max_code;
  84370. const ct_data *stree = desc->stat_desc->static_tree;
  84371. const intf *extra = desc->stat_desc->extra_bits;
  84372. int base = desc->stat_desc->extra_base;
  84373. int max_length = desc->stat_desc->max_length;
  84374. int h; /* heap index */
  84375. int n, m; /* iterate over the tree elements */
  84376. int bits; /* bit length */
  84377. int xbits; /* extra bits */
  84378. ush f; /* frequency */
  84379. int overflow = 0; /* number of elements with bit length too large */
  84380. for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
  84381. /* In a first pass, compute the optimal bit lengths (which may
  84382. * overflow in the case of the bit length tree).
  84383. */
  84384. tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
  84385. for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
  84386. n = s->heap[h];
  84387. bits = tree[tree[n].Dad].Len + 1;
  84388. if (bits > max_length) bits = max_length, overflow++;
  84389. tree[n].Len = (ush)bits;
  84390. /* We overwrite tree[n].Dad which is no longer needed */
  84391. if (n > max_code) continue; /* not a leaf node */
  84392. s->bl_count[bits]++;
  84393. xbits = 0;
  84394. if (n >= base) xbits = extra[n-base];
  84395. f = tree[n].Freq;
  84396. s->opt_len += (ulg)f * (bits + xbits);
  84397. if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
  84398. }
  84399. if (overflow == 0) return;
  84400. Trace((stderr,"\nbit length overflow\n"));
  84401. /* This happens for example on obj2 and pic of the Calgary corpus */
  84402. /* Find the first bit length which could increase: */
  84403. do {
  84404. bits = max_length-1;
  84405. while (s->bl_count[bits] == 0) bits--;
  84406. s->bl_count[bits]--; /* move one leaf down the tree */
  84407. s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
  84408. s->bl_count[max_length]--;
  84409. /* The brother of the overflow item also moves one step up,
  84410. * but this does not affect bl_count[max_length]
  84411. */
  84412. overflow -= 2;
  84413. } while (overflow > 0);
  84414. /* Now recompute all bit lengths, scanning in increasing frequency.
  84415. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  84416. * lengths instead of fixing only the wrong ones. This idea is taken
  84417. * from 'ar' written by Haruhiko Okumura.)
  84418. */
  84419. for (bits = max_length; bits != 0; bits--) {
  84420. n = s->bl_count[bits];
  84421. while (n != 0) {
  84422. m = s->heap[--h];
  84423. if (m > max_code) continue;
  84424. if ((unsigned) tree[m].Len != (unsigned) bits) {
  84425. Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  84426. s->opt_len += ((long)bits - (long)tree[m].Len)
  84427. *(long)tree[m].Freq;
  84428. tree[m].Len = (ush)bits;
  84429. }
  84430. n--;
  84431. }
  84432. }
  84433. }
  84434. /* ===========================================================================
  84435. * Generate the codes for a given tree and bit counts (which need not be
  84436. * optimal).
  84437. * IN assertion: the array bl_count contains the bit length statistics for
  84438. * the given tree and the field len is set for all tree elements.
  84439. * OUT assertion: the field code is set for all tree elements of non
  84440. * zero code length.
  84441. */
  84442. local void gen_codes (ct_data *tree, /* the tree to decorate */
  84443. int max_code, /* largest code with non zero frequency */
  84444. ushf *bl_count) /* number of codes at each bit length */
  84445. {
  84446. ush next_code[MAX_BITS+1]; /* next code value for each bit length */
  84447. ush code = 0; /* running code value */
  84448. int bits; /* bit index */
  84449. int n; /* code index */
  84450. /* The distribution counts are first used to generate the code values
  84451. * without bit reversal.
  84452. */
  84453. for (bits = 1; bits <= MAX_BITS; bits++) {
  84454. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  84455. }
  84456. /* Check that the bit counts in bl_count are consistent. The last code
  84457. * must be all ones.
  84458. */
  84459. Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  84460. "inconsistent bit counts");
  84461. Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  84462. for (n = 0; n <= max_code; n++) {
  84463. int len = tree[n].Len;
  84464. if (len == 0) continue;
  84465. /* Now reverse the bits */
  84466. tree[n].Code = bi_reverse(next_code[len]++, len);
  84467. Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  84468. n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  84469. }
  84470. }
  84471. /* ===========================================================================
  84472. * Construct one Huffman tree and assigns the code bit strings and lengths.
  84473. * Update the total bit length for the current block.
  84474. * IN assertion: the field freq is set for all tree elements.
  84475. * OUT assertions: the fields len and code are set to the optimal bit length
  84476. * and corresponding code. The length opt_len is updated; static_len is
  84477. * also updated if stree is not null. The field max_code is set.
  84478. */
  84479. local void build_tree (deflate_state *s,
  84480. tree_desc *desc) /* the tree descriptor */
  84481. {
  84482. ct_data *tree = desc->dyn_tree;
  84483. const ct_data *stree = desc->stat_desc->static_tree;
  84484. int elems = desc->stat_desc->elems;
  84485. int n, m; /* iterate over heap elements */
  84486. int max_code = -1; /* largest code with non zero frequency */
  84487. int node; /* new node being created */
  84488. /* Construct the initial heap, with least frequent element in
  84489. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  84490. * heap[0] is not used.
  84491. */
  84492. s->heap_len = 0, s->heap_max = HEAP_SIZE;
  84493. for (n = 0; n < elems; n++) {
  84494. if (tree[n].Freq != 0) {
  84495. s->heap[++(s->heap_len)] = max_code = n;
  84496. s->depth[n] = 0;
  84497. } else {
  84498. tree[n].Len = 0;
  84499. }
  84500. }
  84501. /* The pkzip format requires that at least one distance code exists,
  84502. * and that at least one bit should be sent even if there is only one
  84503. * possible code. So to avoid special checks later on we force at least
  84504. * two codes of non zero frequency.
  84505. */
  84506. while (s->heap_len < 2) {
  84507. node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
  84508. tree[node].Freq = 1;
  84509. s->depth[node] = 0;
  84510. s->opt_len--; if (stree) s->static_len -= stree[node].Len;
  84511. /* node is 0 or 1 so it does not have extra bits */
  84512. }
  84513. desc->max_code = max_code;
  84514. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  84515. * establish sub-heaps of increasing lengths:
  84516. */
  84517. for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
  84518. /* Construct the Huffman tree by repeatedly combining the least two
  84519. * frequent nodes.
  84520. */
  84521. node = elems; /* next internal node of the tree */
  84522. do {
  84523. pqremove(s, tree, n); /* n = node of least frequency */
  84524. m = s->heap[SMALLEST]; /* m = node of next least frequency */
  84525. s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
  84526. s->heap[--(s->heap_max)] = m;
  84527. /* Create a new node father of n and m */
  84528. tree[node].Freq = tree[n].Freq + tree[m].Freq;
  84529. s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
  84530. s->depth[n] : s->depth[m]) + 1);
  84531. tree[n].Dad = tree[m].Dad = (ush)node;
  84532. #ifdef DUMP_BL_TREE
  84533. if (tree == s->bl_tree) {
  84534. fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
  84535. node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  84536. }
  84537. #endif
  84538. /* and insert the new node in the heap */
  84539. s->heap[SMALLEST] = node++;
  84540. pqdownheap(s, tree, SMALLEST);
  84541. } while (s->heap_len >= 2);
  84542. s->heap[--(s->heap_max)] = s->heap[SMALLEST];
  84543. /* At this point, the fields freq and dad are set. We can now
  84544. * generate the bit lengths.
  84545. */
  84546. gen_bitlen(s, (tree_desc *)desc);
  84547. /* The field len is now set, we can generate the bit codes */
  84548. gen_codes ((ct_data *)tree, max_code, s->bl_count);
  84549. }
  84550. /* ===========================================================================
  84551. * Scan a literal or distance tree to determine the frequencies of the codes
  84552. * in the bit length tree.
  84553. */
  84554. local void scan_tree (deflate_state *s,
  84555. ct_data *tree, /* the tree to be scanned */
  84556. int max_code) /* and its largest code of non zero frequency */
  84557. {
  84558. int n; /* iterates over all tree elements */
  84559. int prevlen = -1; /* last emitted length */
  84560. int curlen; /* length of current code */
  84561. int nextlen = tree[0].Len; /* length of next code */
  84562. int count = 0; /* repeat count of the current code */
  84563. int max_count = 7; /* max repeat count */
  84564. int min_count = 4; /* min repeat count */
  84565. if (nextlen == 0) max_count = 138, min_count = 3;
  84566. tree[max_code+1].Len = (ush)0xffff; /* guard */
  84567. for (n = 0; n <= max_code; n++) {
  84568. curlen = nextlen; nextlen = tree[n+1].Len;
  84569. if (++count < max_count && curlen == nextlen) {
  84570. continue;
  84571. } else if (count < min_count) {
  84572. s->bl_tree[curlen].Freq += count;
  84573. } else if (curlen != 0) {
  84574. if (curlen != prevlen) s->bl_tree[curlen].Freq++;
  84575. s->bl_tree[REP_3_6].Freq++;
  84576. } else if (count <= 10) {
  84577. s->bl_tree[REPZ_3_10].Freq++;
  84578. } else {
  84579. s->bl_tree[REPZ_11_138].Freq++;
  84580. }
  84581. count = 0; prevlen = curlen;
  84582. if (nextlen == 0) {
  84583. max_count = 138, min_count = 3;
  84584. } else if (curlen == nextlen) {
  84585. max_count = 6, min_count = 3;
  84586. } else {
  84587. max_count = 7, min_count = 4;
  84588. }
  84589. }
  84590. }
  84591. /* ===========================================================================
  84592. * Send a literal or distance tree in compressed form, using the codes in
  84593. * bl_tree.
  84594. */
  84595. local void send_tree (deflate_state *s,
  84596. ct_data *tree, /* the tree to be scanned */
  84597. int max_code) /* and its largest code of non zero frequency */
  84598. {
  84599. int n; /* iterates over all tree elements */
  84600. int prevlen = -1; /* last emitted length */
  84601. int curlen; /* length of current code */
  84602. int nextlen = tree[0].Len; /* length of next code */
  84603. int count = 0; /* repeat count of the current code */
  84604. int max_count = 7; /* max repeat count */
  84605. int min_count = 4; /* min repeat count */
  84606. /* tree[max_code+1].Len = -1; */ /* guard already set */
  84607. if (nextlen == 0) max_count = 138, min_count = 3;
  84608. for (n = 0; n <= max_code; n++) {
  84609. curlen = nextlen; nextlen = tree[n+1].Len;
  84610. if (++count < max_count && curlen == nextlen) {
  84611. continue;
  84612. } else if (count < min_count) {
  84613. do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
  84614. } else if (curlen != 0) {
  84615. if (curlen != prevlen) {
  84616. send_code(s, curlen, s->bl_tree); count--;
  84617. }
  84618. Assert(count >= 3 && count <= 6, " 3_6?");
  84619. send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
  84620. } else if (count <= 10) {
  84621. send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
  84622. } else {
  84623. send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
  84624. }
  84625. count = 0; prevlen = curlen;
  84626. if (nextlen == 0) {
  84627. max_count = 138, min_count = 3;
  84628. } else if (curlen == nextlen) {
  84629. max_count = 6, min_count = 3;
  84630. } else {
  84631. max_count = 7, min_count = 4;
  84632. }
  84633. }
  84634. }
  84635. /* ===========================================================================
  84636. * Construct the Huffman tree for the bit lengths and return the index in
  84637. * bl_order of the last bit length code to send.
  84638. */
  84639. local int build_bl_tree (deflate_state *s)
  84640. {
  84641. int max_blindex; /* index of last bit length code of non zero freq */
  84642. /* Determine the bit length frequencies for literal and distance trees */
  84643. scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
  84644. scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
  84645. /* Build the bit length tree: */
  84646. build_tree(s, (tree_desc *)(&(s->bl_desc)));
  84647. /* opt_len now includes the length of the tree representations, except
  84648. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  84649. */
  84650. /* Determine the number of bit length codes to send. The pkzip format
  84651. * requires that at least 4 bit length codes be sent. (appnote.txt says
  84652. * 3 but the actual value used is 4.)
  84653. */
  84654. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  84655. if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
  84656. }
  84657. /* Update opt_len to include the bit length tree and counts */
  84658. s->opt_len += 3*(max_blindex+1) + 5+5+4;
  84659. Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  84660. s->opt_len, s->static_len));
  84661. return max_blindex;
  84662. }
  84663. /* ===========================================================================
  84664. * Send the header for a block using dynamic Huffman trees: the counts, the
  84665. * lengths of the bit length codes, the literal tree and the distance tree.
  84666. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  84667. */
  84668. local void send_all_trees (deflate_state *s,
  84669. int lcodes, int dcodes, int blcodes) /* number of codes for each tree */
  84670. {
  84671. int rank; /* index in bl_order */
  84672. Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  84673. Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  84674. "too many codes");
  84675. Tracev((stderr, "\nbl counts: "));
  84676. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  84677. send_bits(s, dcodes-1, 5);
  84678. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  84679. for (rank = 0; rank < blcodes; rank++) {
  84680. Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  84681. send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
  84682. }
  84683. Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  84684. send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
  84685. Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  84686. send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
  84687. Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  84688. }
  84689. /* ===========================================================================
  84690. * Send a stored block
  84691. */
  84692. void _tr_stored_block (deflate_state *s, charf *buf, ulg stored_len, int eof)
  84693. {
  84694. send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */
  84695. #ifdef DEBUG
  84696. s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
  84697. s->compressed_len += (stored_len + 4) << 3;
  84698. #endif
  84699. copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
  84700. }
  84701. /* ===========================================================================
  84702. * Send one empty static block to give enough lookahead for inflate.
  84703. * This takes 10 bits, of which 7 may remain in the bit buffer.
  84704. * The current inflate code requires 9 bits of lookahead. If the
  84705. * last two codes for the previous block (real code plus EOB) were coded
  84706. * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  84707. * the last real code. In this case we send two empty static blocks instead
  84708. * of one. (There are no problems if the previous block is stored or fixed.)
  84709. * To simplify the code, we assume the worst case of last real code encoded
  84710. * on one bit only.
  84711. */
  84712. void _tr_align (deflate_state *s)
  84713. {
  84714. send_bits(s, STATIC_TREES<<1, 3);
  84715. send_code(s, END_BLOCK, static_ltree);
  84716. #ifdef DEBUG
  84717. s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
  84718. #endif
  84719. bi_flush(s);
  84720. /* Of the 10 bits for the empty block, we have already sent
  84721. * (10 - bi_valid) bits. The lookahead for the last real code (before
  84722. * the EOB of the previous block) was thus at least one plus the length
  84723. * of the EOB plus what we have just sent of the empty static block.
  84724. */
  84725. if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
  84726. send_bits(s, STATIC_TREES<<1, 3);
  84727. send_code(s, END_BLOCK, static_ltree);
  84728. #ifdef DEBUG
  84729. s->compressed_len += 10L;
  84730. #endif
  84731. bi_flush(s);
  84732. }
  84733. s->last_eob_len = 7;
  84734. }
  84735. /* ===========================================================================
  84736. * Determine the best encoding for the current block: dynamic trees, static
  84737. * trees or store, and output the encoded block to the zip file.
  84738. */
  84739. void _tr_flush_block (deflate_state *s,
  84740. charf *buf, /* input block, or NULL if too old */
  84741. ulg stored_len, /* length of input block */
  84742. int eof) /* true if this is the last block for a file */
  84743. {
  84744. ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  84745. int max_blindex = 0; /* index of last bit length code of non zero freq */
  84746. /* Build the Huffman trees unless a stored block is forced */
  84747. if (s->level > 0) {
  84748. /* Check if the file is binary or text */
  84749. if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN)
  84750. set_data_type(s);
  84751. /* Construct the literal and distance trees */
  84752. build_tree(s, (tree_desc *)(&(s->l_desc)));
  84753. Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  84754. s->static_len));
  84755. build_tree(s, (tree_desc *)(&(s->d_desc)));
  84756. Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  84757. s->static_len));
  84758. /* At this point, opt_len and static_len are the total bit lengths of
  84759. * the compressed block data, excluding the tree representations.
  84760. */
  84761. /* Build the bit length tree for the above two trees, and get the index
  84762. * in bl_order of the last bit length code to send.
  84763. */
  84764. max_blindex = build_bl_tree(s);
  84765. /* Determine the best encoding. Compute the block lengths in bytes. */
  84766. opt_lenb = (s->opt_len+3+7)>>3;
  84767. static_lenb = (s->static_len+3+7)>>3;
  84768. Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  84769. opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  84770. s->last_lit));
  84771. if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
  84772. } else {
  84773. Assert(buf != (char*)0, "lost buf");
  84774. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  84775. }
  84776. #ifdef FORCE_STORED
  84777. if (buf != (char*)0) { /* force stored block */
  84778. #else
  84779. if (stored_len+4 <= opt_lenb && buf != (char*)0) {
  84780. /* 4: two words for the lengths */
  84781. #endif
  84782. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  84783. * Otherwise we can't have processed more than WSIZE input bytes since
  84784. * the last block flush, because compression would have been
  84785. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  84786. * transform a block into a stored block.
  84787. */
  84788. _tr_stored_block(s, buf, stored_len, eof);
  84789. #ifdef FORCE_STATIC
  84790. } else if (static_lenb >= 0) { /* force static trees */
  84791. #else
  84792. } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
  84793. #endif
  84794. send_bits(s, (STATIC_TREES<<1)+eof, 3);
  84795. compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
  84796. #ifdef DEBUG
  84797. s->compressed_len += 3 + s->static_len;
  84798. #endif
  84799. } else {
  84800. send_bits(s, (DYN_TREES<<1)+eof, 3);
  84801. send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
  84802. max_blindex+1);
  84803. compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
  84804. #ifdef DEBUG
  84805. s->compressed_len += 3 + s->opt_len;
  84806. #endif
  84807. }
  84808. Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  84809. /* The above check is made mod 2^32, for files larger than 512 MB
  84810. * and uLong implemented on 32 bits.
  84811. */
  84812. init_block(s);
  84813. if (eof) {
  84814. bi_windup(s);
  84815. #ifdef DEBUG
  84816. s->compressed_len += 7; /* align on byte boundary */
  84817. #endif
  84818. }
  84819. Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  84820. s->compressed_len-7*eof));
  84821. }
  84822. /* ===========================================================================
  84823. * Save the match info and tally the frequency counts. Return true if
  84824. * the current block must be flushed.
  84825. */
  84826. int _tr_tally (deflate_state *s,
  84827. unsigned dist, /* distance of matched string */
  84828. unsigned lc) /* match length-MIN_MATCH or unmatched char (if dist==0) */
  84829. {
  84830. s->d_buf[s->last_lit] = (ush)dist;
  84831. s->l_buf[s->last_lit++] = (uch)lc;
  84832. if (dist == 0) {
  84833. /* lc is the unmatched char */
  84834. s->dyn_ltree[lc].Freq++;
  84835. } else {
  84836. s->matches++;
  84837. /* Here, lc is the match length - MIN_MATCH */
  84838. dist--; /* dist = match distance - 1 */
  84839. Assert((ush)dist < (ush)MAX_DIST(s) &&
  84840. (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  84841. (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  84842. s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
  84843. s->dyn_dtree[d_code(dist)].Freq++;
  84844. }
  84845. #ifdef TRUNCATE_BLOCK
  84846. /* Try to guess if it is profitable to stop the current block here */
  84847. if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
  84848. /* Compute an upper bound for the compressed length */
  84849. ulg out_length = (ulg)s->last_lit*8L;
  84850. ulg in_length = (ulg)((long)s->strstart - s->block_start);
  84851. int dcode;
  84852. for (dcode = 0; dcode < D_CODES; dcode++) {
  84853. out_length += (ulg)s->dyn_dtree[dcode].Freq *
  84854. (5L+extra_dbits[dcode]);
  84855. }
  84856. out_length >>= 3;
  84857. Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  84858. s->last_lit, in_length, out_length,
  84859. 100L - out_length*100L/in_length));
  84860. if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
  84861. }
  84862. #endif
  84863. return (s->last_lit == s->lit_bufsize-1);
  84864. /* We avoid equality with lit_bufsize because of wraparound at 64K
  84865. * on 16 bit machines and because stored blocks are restricted to
  84866. * 64K-1 bytes.
  84867. */
  84868. }
  84869. /* ===========================================================================
  84870. * Send the block data compressed using the given Huffman trees
  84871. */
  84872. local void compress_block (deflate_state *s,
  84873. ct_data *ltree, /* literal tree */
  84874. ct_data *dtree) /* distance tree */
  84875. {
  84876. unsigned dist; /* distance of matched string */
  84877. int lc; /* match length or unmatched char (if dist == 0) */
  84878. unsigned lx = 0; /* running index in l_buf */
  84879. unsigned code; /* the code to send */
  84880. int extra; /* number of extra bits to send */
  84881. if (s->last_lit != 0) do {
  84882. dist = s->d_buf[lx];
  84883. lc = s->l_buf[lx++];
  84884. if (dist == 0) {
  84885. send_code(s, lc, ltree); /* send a literal byte */
  84886. Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  84887. } else {
  84888. /* Here, lc is the match length - MIN_MATCH */
  84889. code = _length_code[lc];
  84890. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  84891. extra = extra_lbits[code];
  84892. if (extra != 0) {
  84893. lc -= base_length[code];
  84894. send_bits(s, lc, extra); /* send the extra length bits */
  84895. }
  84896. dist--; /* dist is now the match distance - 1 */
  84897. code = d_code(dist);
  84898. Assert (code < D_CODES, "bad d_code");
  84899. send_code(s, code, dtree); /* send the distance code */
  84900. extra = extra_dbits[code];
  84901. if (extra != 0) {
  84902. dist -= base_dist[code];
  84903. send_bits(s, dist, extra); /* send the extra distance bits */
  84904. }
  84905. } /* literal or match pair ? */
  84906. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  84907. Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  84908. "pendingBuf overflow");
  84909. } while (lx < s->last_lit);
  84910. send_code(s, END_BLOCK, ltree);
  84911. s->last_eob_len = ltree[END_BLOCK].Len;
  84912. }
  84913. /* ===========================================================================
  84914. * Set the data type to BINARY or TEXT, using a crude approximation:
  84915. * set it to Z_TEXT if all symbols are either printable characters (33 to 255)
  84916. * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise.
  84917. * IN assertion: the fields Freq of dyn_ltree are set.
  84918. */
  84919. local void set_data_type (deflate_state *s)
  84920. {
  84921. int n;
  84922. for (n = 0; n < 9; n++)
  84923. if (s->dyn_ltree[n].Freq != 0)
  84924. break;
  84925. if (n == 9)
  84926. for (n = 14; n < 32; n++)
  84927. if (s->dyn_ltree[n].Freq != 0)
  84928. break;
  84929. s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY;
  84930. }
  84931. /* ===========================================================================
  84932. * Reverse the first len bits of a code, using straightforward code (a faster
  84933. * method would use a table)
  84934. * IN assertion: 1 <= len <= 15
  84935. */
  84936. local unsigned bi_reverse (unsigned code, int len)
  84937. {
  84938. register unsigned res = 0;
  84939. do {
  84940. res |= code & 1;
  84941. code >>= 1, res <<= 1;
  84942. } while (--len > 0);
  84943. return res >> 1;
  84944. }
  84945. /* ===========================================================================
  84946. * Flush the bit buffer, keeping at most 7 bits in it.
  84947. */
  84948. local void bi_flush (deflate_state *s)
  84949. {
  84950. if (s->bi_valid == 16) {
  84951. put_short(s, s->bi_buf);
  84952. s->bi_buf = 0;
  84953. s->bi_valid = 0;
  84954. } else if (s->bi_valid >= 8) {
  84955. put_byte(s, (Byte)s->bi_buf);
  84956. s->bi_buf >>= 8;
  84957. s->bi_valid -= 8;
  84958. }
  84959. }
  84960. /* ===========================================================================
  84961. * Flush the bit buffer and align the output on a byte boundary
  84962. */
  84963. local void bi_windup (deflate_state *s)
  84964. {
  84965. if (s->bi_valid > 8) {
  84966. put_short(s, s->bi_buf);
  84967. } else if (s->bi_valid > 0) {
  84968. put_byte(s, (Byte)s->bi_buf);
  84969. }
  84970. s->bi_buf = 0;
  84971. s->bi_valid = 0;
  84972. #ifdef DEBUG
  84973. s->bits_sent = (s->bits_sent+7) & ~7;
  84974. #endif
  84975. }
  84976. /* ===========================================================================
  84977. * Copy a stored block, storing first the length and its
  84978. * one's complement if requested.
  84979. */
  84980. local void copy_block(deflate_state *s,
  84981. charf *buf, /* the input data */
  84982. unsigned len, /* its length */
  84983. int header) /* true if block header must be written */
  84984. {
  84985. bi_windup(s); /* align on byte boundary */
  84986. s->last_eob_len = 8; /* enough lookahead for inflate */
  84987. if (header) {
  84988. put_short(s, (ush)len);
  84989. put_short(s, (ush)~len);
  84990. #ifdef DEBUG
  84991. s->bits_sent += 2*16;
  84992. #endif
  84993. }
  84994. #ifdef DEBUG
  84995. s->bits_sent += (ulg)len<<3;
  84996. #endif
  84997. while (len--) {
  84998. put_byte(s, *buf++);
  84999. }
  85000. }
  85001. /*** End of inlined file: trees.c ***/
  85002. /*** Start of inlined file: zutil.c ***/
  85003. /* @(#) $Id: zutil.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  85004. #ifndef NO_DUMMY_DECL
  85005. struct internal_state {int dummy;}; /* for buggy compilers */
  85006. #endif
  85007. const char * const z_errmsg[10] = {
  85008. "need dictionary", /* Z_NEED_DICT 2 */
  85009. "stream end", /* Z_STREAM_END 1 */
  85010. "", /* Z_OK 0 */
  85011. "file error", /* Z_ERRNO (-1) */
  85012. "stream error", /* Z_STREAM_ERROR (-2) */
  85013. "data error", /* Z_DATA_ERROR (-3) */
  85014. "insufficient memory", /* Z_MEM_ERROR (-4) */
  85015. "buffer error", /* Z_BUF_ERROR (-5) */
  85016. "incompatible version",/* Z_VERSION_ERROR (-6) */
  85017. ""};
  85018. /*const char * ZEXPORT zlibVersion()
  85019. {
  85020. return ZLIB_VERSION;
  85021. }
  85022. uLong ZEXPORT zlibCompileFlags()
  85023. {
  85024. uLong flags;
  85025. flags = 0;
  85026. switch (sizeof(uInt)) {
  85027. case 2: break;
  85028. case 4: flags += 1; break;
  85029. case 8: flags += 2; break;
  85030. default: flags += 3;
  85031. }
  85032. switch (sizeof(uLong)) {
  85033. case 2: break;
  85034. case 4: flags += 1 << 2; break;
  85035. case 8: flags += 2 << 2; break;
  85036. default: flags += 3 << 2;
  85037. }
  85038. switch (sizeof(voidpf)) {
  85039. case 2: break;
  85040. case 4: flags += 1 << 4; break;
  85041. case 8: flags += 2 << 4; break;
  85042. default: flags += 3 << 4;
  85043. }
  85044. switch (sizeof(z_off_t)) {
  85045. case 2: break;
  85046. case 4: flags += 1 << 6; break;
  85047. case 8: flags += 2 << 6; break;
  85048. default: flags += 3 << 6;
  85049. }
  85050. #ifdef DEBUG
  85051. flags += 1 << 8;
  85052. #endif
  85053. #if defined(ASMV) || defined(ASMINF)
  85054. flags += 1 << 9;
  85055. #endif
  85056. #ifdef ZLIB_WINAPI
  85057. flags += 1 << 10;
  85058. #endif
  85059. #ifdef BUILDFIXED
  85060. flags += 1 << 12;
  85061. #endif
  85062. #ifdef DYNAMIC_CRC_TABLE
  85063. flags += 1 << 13;
  85064. #endif
  85065. #ifdef NO_GZCOMPRESS
  85066. flags += 1L << 16;
  85067. #endif
  85068. #ifdef NO_GZIP
  85069. flags += 1L << 17;
  85070. #endif
  85071. #ifdef PKZIP_BUG_WORKAROUND
  85072. flags += 1L << 20;
  85073. #endif
  85074. #ifdef FASTEST
  85075. flags += 1L << 21;
  85076. #endif
  85077. #ifdef STDC
  85078. # ifdef NO_vsnprintf
  85079. flags += 1L << 25;
  85080. # ifdef HAS_vsprintf_void
  85081. flags += 1L << 26;
  85082. # endif
  85083. # else
  85084. # ifdef HAS_vsnprintf_void
  85085. flags += 1L << 26;
  85086. # endif
  85087. # endif
  85088. #else
  85089. flags += 1L << 24;
  85090. # ifdef NO_snprintf
  85091. flags += 1L << 25;
  85092. # ifdef HAS_sprintf_void
  85093. flags += 1L << 26;
  85094. # endif
  85095. # else
  85096. # ifdef HAS_snprintf_void
  85097. flags += 1L << 26;
  85098. # endif
  85099. # endif
  85100. #endif
  85101. return flags;
  85102. }*/
  85103. #ifdef DEBUG
  85104. # ifndef verbose
  85105. # define verbose 0
  85106. # endif
  85107. int z_verbose = verbose;
  85108. void z_error (const char *m)
  85109. {
  85110. fprintf(stderr, "%s\n", m);
  85111. exit(1);
  85112. }
  85113. #endif
  85114. /* exported to allow conversion of error code to string for compress() and
  85115. * uncompress()
  85116. */
  85117. const char * ZEXPORT zError(int err)
  85118. {
  85119. return ERR_MSG(err);
  85120. }
  85121. #if defined(_WIN32_WCE)
  85122. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  85123. * errno. We define it as a global variable to simplify porting.
  85124. * Its value is always 0 and should not be used.
  85125. */
  85126. int errno = 0;
  85127. #endif
  85128. #ifndef HAVE_MEMCPY
  85129. void zmemcpy(dest, source, len)
  85130. Bytef* dest;
  85131. const Bytef* source;
  85132. uInt len;
  85133. {
  85134. if (len == 0) return;
  85135. do {
  85136. *dest++ = *source++; /* ??? to be unrolled */
  85137. } while (--len != 0);
  85138. }
  85139. int zmemcmp(s1, s2, len)
  85140. const Bytef* s1;
  85141. const Bytef* s2;
  85142. uInt len;
  85143. {
  85144. uInt j;
  85145. for (j = 0; j < len; j++) {
  85146. if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
  85147. }
  85148. return 0;
  85149. }
  85150. void zmemzero(dest, len)
  85151. Bytef* dest;
  85152. uInt len;
  85153. {
  85154. if (len == 0) return;
  85155. do {
  85156. *dest++ = 0; /* ??? to be unrolled */
  85157. } while (--len != 0);
  85158. }
  85159. #endif
  85160. #ifdef SYS16BIT
  85161. #ifdef __TURBOC__
  85162. /* Turbo C in 16-bit mode */
  85163. # define MY_ZCALLOC
  85164. /* Turbo C malloc() does not allow dynamic allocation of 64K bytes
  85165. * and farmalloc(64K) returns a pointer with an offset of 8, so we
  85166. * must fix the pointer. Warning: the pointer must be put back to its
  85167. * original form in order to free it, use zcfree().
  85168. */
  85169. #define MAX_PTR 10
  85170. /* 10*64K = 640K */
  85171. local int next_ptr = 0;
  85172. typedef struct ptr_table_s {
  85173. voidpf org_ptr;
  85174. voidpf new_ptr;
  85175. } ptr_table;
  85176. local ptr_table table[MAX_PTR];
  85177. /* This table is used to remember the original form of pointers
  85178. * to large buffers (64K). Such pointers are normalized with a zero offset.
  85179. * Since MSDOS is not a preemptive multitasking OS, this table is not
  85180. * protected from concurrent access. This hack doesn't work anyway on
  85181. * a protected system like OS/2. Use Microsoft C instead.
  85182. */
  85183. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  85184. {
  85185. voidpf buf = opaque; /* just to make some compilers happy */
  85186. ulg bsize = (ulg)items*size;
  85187. /* If we allocate less than 65520 bytes, we assume that farmalloc
  85188. * will return a usable pointer which doesn't have to be normalized.
  85189. */
  85190. if (bsize < 65520L) {
  85191. buf = farmalloc(bsize);
  85192. if (*(ush*)&buf != 0) return buf;
  85193. } else {
  85194. buf = farmalloc(bsize + 16L);
  85195. }
  85196. if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
  85197. table[next_ptr].org_ptr = buf;
  85198. /* Normalize the pointer to seg:0 */
  85199. *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
  85200. *(ush*)&buf = 0;
  85201. table[next_ptr++].new_ptr = buf;
  85202. return buf;
  85203. }
  85204. void zcfree (voidpf opaque, voidpf ptr)
  85205. {
  85206. int n;
  85207. if (*(ush*)&ptr != 0) { /* object < 64K */
  85208. farfree(ptr);
  85209. return;
  85210. }
  85211. /* Find the original pointer */
  85212. for (n = 0; n < next_ptr; n++) {
  85213. if (ptr != table[n].new_ptr) continue;
  85214. farfree(table[n].org_ptr);
  85215. while (++n < next_ptr) {
  85216. table[n-1] = table[n];
  85217. }
  85218. next_ptr--;
  85219. return;
  85220. }
  85221. ptr = opaque; /* just to make some compilers happy */
  85222. Assert(0, "zcfree: ptr not found");
  85223. }
  85224. #endif /* __TURBOC__ */
  85225. #ifdef M_I86
  85226. /* Microsoft C in 16-bit mode */
  85227. # define MY_ZCALLOC
  85228. #if (!defined(_MSC_VER) || (_MSC_VER <= 600))
  85229. # define _halloc halloc
  85230. # define _hfree hfree
  85231. #endif
  85232. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  85233. {
  85234. if (opaque) opaque = 0; /* to make compiler happy */
  85235. return _halloc((long)items, size);
  85236. }
  85237. void zcfree (voidpf opaque, voidpf ptr)
  85238. {
  85239. if (opaque) opaque = 0; /* to make compiler happy */
  85240. _hfree(ptr);
  85241. }
  85242. #endif /* M_I86 */
  85243. #endif /* SYS16BIT */
  85244. #ifndef MY_ZCALLOC /* Any system without a special alloc function */
  85245. #ifndef STDC
  85246. extern voidp malloc OF((uInt size));
  85247. extern voidp calloc OF((uInt items, uInt size));
  85248. extern void free OF((voidpf ptr));
  85249. #endif
  85250. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  85251. {
  85252. if (opaque) items += size - size; /* make compiler happy */
  85253. return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
  85254. (voidpf)calloc(items, size);
  85255. }
  85256. void zcfree (voidpf opaque, voidpf ptr)
  85257. {
  85258. free(ptr);
  85259. if (opaque) return; /* make compiler happy */
  85260. }
  85261. #endif /* MY_ZCALLOC */
  85262. /*** End of inlined file: zutil.c ***/
  85263. #undef Byte
  85264. }
  85265. #else
  85266. #include <zlib.h>
  85267. #endif
  85268. }
  85269. #if JUCE_MSVC
  85270. #pragma warning (pop)
  85271. #endif
  85272. BEGIN_JUCE_NAMESPACE
  85273. // internal helper object that holds the zlib structures so they don't have to be
  85274. // included publicly.
  85275. class GZIPDecompressHelper
  85276. {
  85277. public:
  85278. GZIPDecompressHelper (const bool noWrap)
  85279. : finished (true),
  85280. needsDictionary (false),
  85281. error (true),
  85282. streamIsValid (false),
  85283. data (0),
  85284. dataSize (0)
  85285. {
  85286. using namespace zlibNamespace;
  85287. zerostruct (stream);
  85288. streamIsValid = (inflateInit2 (&stream, noWrap ? -MAX_WBITS : MAX_WBITS) == Z_OK);
  85289. finished = error = ! streamIsValid;
  85290. }
  85291. ~GZIPDecompressHelper()
  85292. {
  85293. using namespace zlibNamespace;
  85294. if (streamIsValid)
  85295. inflateEnd (&stream);
  85296. }
  85297. bool needsInput() const throw() { return dataSize <= 0; }
  85298. void setInput (uint8* const data_, const int size) throw()
  85299. {
  85300. data = data_;
  85301. dataSize = size;
  85302. }
  85303. int doNextBlock (uint8* const dest, const int destSize)
  85304. {
  85305. using namespace zlibNamespace;
  85306. if (streamIsValid && data != 0 && ! finished)
  85307. {
  85308. stream.next_in = data;
  85309. stream.next_out = dest;
  85310. stream.avail_in = dataSize;
  85311. stream.avail_out = destSize;
  85312. switch (inflate (&stream, Z_PARTIAL_FLUSH))
  85313. {
  85314. case Z_STREAM_END:
  85315. finished = true;
  85316. // deliberate fall-through
  85317. case Z_OK:
  85318. data += dataSize - stream.avail_in;
  85319. dataSize = stream.avail_in;
  85320. return destSize - stream.avail_out;
  85321. case Z_NEED_DICT:
  85322. needsDictionary = true;
  85323. data += dataSize - stream.avail_in;
  85324. dataSize = stream.avail_in;
  85325. break;
  85326. case Z_DATA_ERROR:
  85327. case Z_MEM_ERROR:
  85328. error = true;
  85329. default:
  85330. break;
  85331. }
  85332. }
  85333. return 0;
  85334. }
  85335. bool finished, needsDictionary, error, streamIsValid;
  85336. private:
  85337. zlibNamespace::z_stream stream;
  85338. uint8* data;
  85339. int dataSize;
  85340. GZIPDecompressHelper (const GZIPDecompressHelper&);
  85341. GZIPDecompressHelper& operator= (const GZIPDecompressHelper&);
  85342. };
  85343. const int gzipDecompBufferSize = 32768;
  85344. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream* const sourceStream_,
  85345. const bool deleteSourceWhenDestroyed,
  85346. const bool noWrap_,
  85347. const int64 uncompressedStreamLength_)
  85348. : sourceStream (sourceStream_),
  85349. streamToDelete (deleteSourceWhenDestroyed ? sourceStream_ : 0),
  85350. uncompressedStreamLength (uncompressedStreamLength_),
  85351. noWrap (noWrap_),
  85352. isEof (false),
  85353. activeBufferSize (0),
  85354. originalSourcePos (sourceStream_->getPosition()),
  85355. currentPos (0),
  85356. buffer (gzipDecompBufferSize),
  85357. helper (new GZIPDecompressHelper (noWrap_))
  85358. {
  85359. }
  85360. GZIPDecompressorInputStream::~GZIPDecompressorInputStream()
  85361. {
  85362. }
  85363. int64 GZIPDecompressorInputStream::getTotalLength()
  85364. {
  85365. return uncompressedStreamLength;
  85366. }
  85367. int GZIPDecompressorInputStream::read (void* destBuffer, int howMany)
  85368. {
  85369. if ((howMany > 0) && ! isEof)
  85370. {
  85371. jassert (destBuffer != 0);
  85372. if (destBuffer != 0)
  85373. {
  85374. int numRead = 0;
  85375. uint8* d = static_cast <uint8*> (destBuffer);
  85376. while (! helper->error)
  85377. {
  85378. const int n = helper->doNextBlock (d, howMany);
  85379. currentPos += n;
  85380. if (n == 0)
  85381. {
  85382. if (helper->finished || helper->needsDictionary)
  85383. {
  85384. isEof = true;
  85385. return numRead;
  85386. }
  85387. if (helper->needsInput())
  85388. {
  85389. activeBufferSize = sourceStream->read (buffer, gzipDecompBufferSize);
  85390. if (activeBufferSize > 0)
  85391. {
  85392. helper->setInput (buffer, activeBufferSize);
  85393. }
  85394. else
  85395. {
  85396. isEof = true;
  85397. return numRead;
  85398. }
  85399. }
  85400. }
  85401. else
  85402. {
  85403. numRead += n;
  85404. howMany -= n;
  85405. d += n;
  85406. if (howMany <= 0)
  85407. return numRead;
  85408. }
  85409. }
  85410. }
  85411. }
  85412. return 0;
  85413. }
  85414. bool GZIPDecompressorInputStream::isExhausted()
  85415. {
  85416. return helper->error || isEof;
  85417. }
  85418. int64 GZIPDecompressorInputStream::getPosition()
  85419. {
  85420. return currentPos;
  85421. }
  85422. bool GZIPDecompressorInputStream::setPosition (int64 newPos)
  85423. {
  85424. if (newPos < currentPos)
  85425. {
  85426. // to go backwards, reset the stream and start again..
  85427. isEof = false;
  85428. activeBufferSize = 0;
  85429. currentPos = 0;
  85430. helper = new GZIPDecompressHelper (noWrap);
  85431. sourceStream->setPosition (originalSourcePos);
  85432. }
  85433. skipNextBytes (newPos - currentPos);
  85434. return true;
  85435. }
  85436. END_JUCE_NAMESPACE
  85437. /*** End of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  85438. #endif
  85439. #if JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  85440. /*** Start of inlined file: juce_FlacAudioFormat.cpp ***/
  85441. #if JUCE_USE_FLAC
  85442. #if JUCE_WINDOWS
  85443. #include <windows.h>
  85444. #endif
  85445. namespace FlacNamespace
  85446. {
  85447. #if JUCE_INCLUDE_FLAC_CODE
  85448. #if JUCE_MSVC
  85449. #pragma warning (disable : 4505) // (unreferenced static function removal warning)
  85450. #endif
  85451. #define FLAC__NO_DLL 1
  85452. #if ! defined (SIZE_MAX)
  85453. #define SIZE_MAX 0xffffffff
  85454. #endif
  85455. #define __STDC_LIMIT_MACROS 1
  85456. /*** Start of inlined file: all.h ***/
  85457. #ifndef FLAC__ALL_H
  85458. #define FLAC__ALL_H
  85459. /*** Start of inlined file: export.h ***/
  85460. #ifndef FLAC__EXPORT_H
  85461. #define FLAC__EXPORT_H
  85462. /** \file include/FLAC/export.h
  85463. *
  85464. * \brief
  85465. * This module contains #defines and symbols for exporting function
  85466. * calls, and providing version information and compiled-in features.
  85467. *
  85468. * See the \link flac_export export \endlink module.
  85469. */
  85470. /** \defgroup flac_export FLAC/export.h: export symbols
  85471. * \ingroup flac
  85472. *
  85473. * \brief
  85474. * This module contains #defines and symbols for exporting function
  85475. * calls, and providing version information and compiled-in features.
  85476. *
  85477. * If you are compiling with MSVC and will link to the static library
  85478. * (libFLAC.lib) you should define FLAC__NO_DLL in your project to
  85479. * make sure the symbols are exported properly.
  85480. *
  85481. * \{
  85482. */
  85483. #if defined(FLAC__NO_DLL) || !defined(_MSC_VER)
  85484. #define FLAC_API
  85485. #else
  85486. #ifdef FLAC_API_EXPORTS
  85487. #define FLAC_API _declspec(dllexport)
  85488. #else
  85489. #define FLAC_API _declspec(dllimport)
  85490. #endif
  85491. #endif
  85492. /** These #defines will mirror the libtool-based library version number, see
  85493. * http://www.gnu.org/software/libtool/manual.html#Libtool-versioning
  85494. */
  85495. #define FLAC_API_VERSION_CURRENT 10
  85496. #define FLAC_API_VERSION_REVISION 0 /**< see above */
  85497. #define FLAC_API_VERSION_AGE 2 /**< see above */
  85498. #ifdef __cplusplus
  85499. extern "C" {
  85500. #endif
  85501. /** \c 1 if the library has been compiled with support for Ogg FLAC, else \c 0. */
  85502. extern FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC;
  85503. #ifdef __cplusplus
  85504. }
  85505. #endif
  85506. /* \} */
  85507. #endif
  85508. /*** End of inlined file: export.h ***/
  85509. /*** Start of inlined file: assert.h ***/
  85510. #ifndef FLAC__ASSERT_H
  85511. #define FLAC__ASSERT_H
  85512. /* we need this since some compilers (like MSVC) leave assert()s on release code (and we don't want to use their ASSERT) */
  85513. #ifdef DEBUG
  85514. #include <assert.h>
  85515. #define FLAC__ASSERT(x) assert(x)
  85516. #define FLAC__ASSERT_DECLARATION(x) x
  85517. #else
  85518. #define FLAC__ASSERT(x)
  85519. #define FLAC__ASSERT_DECLARATION(x)
  85520. #endif
  85521. #endif
  85522. /*** End of inlined file: assert.h ***/
  85523. /*** Start of inlined file: callback.h ***/
  85524. #ifndef FLAC__CALLBACK_H
  85525. #define FLAC__CALLBACK_H
  85526. /*** Start of inlined file: ordinals.h ***/
  85527. #ifndef FLAC__ORDINALS_H
  85528. #define FLAC__ORDINALS_H
  85529. #if !(defined(_MSC_VER) || defined(__BORLANDC__) || defined(__EMX__))
  85530. #include <inttypes.h>
  85531. #endif
  85532. typedef signed char FLAC__int8;
  85533. typedef unsigned char FLAC__uint8;
  85534. #if defined(_MSC_VER) || defined(__BORLANDC__)
  85535. typedef __int16 FLAC__int16;
  85536. typedef __int32 FLAC__int32;
  85537. typedef __int64 FLAC__int64;
  85538. typedef unsigned __int16 FLAC__uint16;
  85539. typedef unsigned __int32 FLAC__uint32;
  85540. typedef unsigned __int64 FLAC__uint64;
  85541. #elif defined(__EMX__)
  85542. typedef short FLAC__int16;
  85543. typedef long FLAC__int32;
  85544. typedef long long FLAC__int64;
  85545. typedef unsigned short FLAC__uint16;
  85546. typedef unsigned long FLAC__uint32;
  85547. typedef unsigned long long FLAC__uint64;
  85548. #else
  85549. typedef int16_t FLAC__int16;
  85550. typedef int32_t FLAC__int32;
  85551. typedef int64_t FLAC__int64;
  85552. typedef uint16_t FLAC__uint16;
  85553. typedef uint32_t FLAC__uint32;
  85554. typedef uint64_t FLAC__uint64;
  85555. #endif
  85556. typedef int FLAC__bool;
  85557. typedef FLAC__uint8 FLAC__byte;
  85558. #ifdef true
  85559. #undef true
  85560. #endif
  85561. #ifdef false
  85562. #undef false
  85563. #endif
  85564. #ifndef __cplusplus
  85565. #define true 1
  85566. #define false 0
  85567. #endif
  85568. #endif
  85569. /*** End of inlined file: ordinals.h ***/
  85570. #include <stdlib.h> /* for size_t */
  85571. /** \file include/FLAC/callback.h
  85572. *
  85573. * \brief
  85574. * This module defines the structures for describing I/O callbacks
  85575. * to the other FLAC interfaces.
  85576. *
  85577. * See the detailed documentation for callbacks in the
  85578. * \link flac_callbacks callbacks \endlink module.
  85579. */
  85580. /** \defgroup flac_callbacks FLAC/callback.h: I/O callback structures
  85581. * \ingroup flac
  85582. *
  85583. * \brief
  85584. * This module defines the structures for describing I/O callbacks
  85585. * to the other FLAC interfaces.
  85586. *
  85587. * The purpose of the I/O callback functions is to create a common way
  85588. * for the metadata interfaces to handle I/O.
  85589. *
  85590. * Originally the metadata interfaces required filenames as the way of
  85591. * specifying FLAC files to operate on. This is problematic in some
  85592. * environments so there is an additional option to specify a set of
  85593. * callbacks for doing I/O on the FLAC file, instead of the filename.
  85594. *
  85595. * In addition to the callbacks, a FLAC__IOHandle type is defined as an
  85596. * opaque structure for a data source.
  85597. *
  85598. * The callback function prototypes are similar (but not identical) to the
  85599. * stdio functions fread, fwrite, fseek, ftell, feof, and fclose. If you use
  85600. * stdio streams to implement the callbacks, you can pass fread, fwrite, and
  85601. * fclose anywhere a FLAC__IOCallback_Read, FLAC__IOCallback_Write, or
  85602. * FLAC__IOCallback_Close is required, and a FILE* anywhere a FLAC__IOHandle
  85603. * is required. \warning You generally CANNOT directly use fseek or ftell
  85604. * for FLAC__IOCallback_Seek or FLAC__IOCallback_Tell since on most systems
  85605. * these use 32-bit offsets and FLAC requires 64-bit offsets to deal with
  85606. * large files. You will have to find an equivalent function (e.g. ftello),
  85607. * or write a wrapper. The same is true for feof() since this is usually
  85608. * implemented as a macro, not as a function whose address can be taken.
  85609. *
  85610. * \{
  85611. */
  85612. #ifdef __cplusplus
  85613. extern "C" {
  85614. #endif
  85615. /** This is the opaque handle type used by the callbacks. Typically
  85616. * this is a \c FILE* or address of a file descriptor.
  85617. */
  85618. typedef void* FLAC__IOHandle;
  85619. /** Signature for the read callback.
  85620. * The signature and semantics match POSIX fread() implementations
  85621. * and can generally be used interchangeably.
  85622. *
  85623. * \param ptr The address of the read buffer.
  85624. * \param size The size of the records to be read.
  85625. * \param nmemb The number of records to be read.
  85626. * \param handle The handle to the data source.
  85627. * \retval size_t
  85628. * The number of records read.
  85629. */
  85630. typedef size_t (*FLAC__IOCallback_Read) (void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  85631. /** Signature for the write callback.
  85632. * The signature and semantics match POSIX fwrite() implementations
  85633. * and can generally be used interchangeably.
  85634. *
  85635. * \param ptr The address of the write buffer.
  85636. * \param size The size of the records to be written.
  85637. * \param nmemb The number of records to be written.
  85638. * \param handle The handle to the data source.
  85639. * \retval size_t
  85640. * The number of records written.
  85641. */
  85642. typedef size_t (*FLAC__IOCallback_Write) (const void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  85643. /** Signature for the seek callback.
  85644. * The signature and semantics mostly match POSIX fseek() WITH ONE IMPORTANT
  85645. * EXCEPTION: the offset is a 64-bit type whereas fseek() is generally 'long'
  85646. * and 32-bits wide.
  85647. *
  85648. * \param handle The handle to the data source.
  85649. * \param offset The new position, relative to \a whence
  85650. * \param whence \c SEEK_SET, \c SEEK_CUR, or \c SEEK_END
  85651. * \retval int
  85652. * \c 0 on success, \c -1 on error.
  85653. */
  85654. typedef int (*FLAC__IOCallback_Seek) (FLAC__IOHandle handle, FLAC__int64 offset, int whence);
  85655. /** Signature for the tell callback.
  85656. * The signature and semantics mostly match POSIX ftell() WITH ONE IMPORTANT
  85657. * EXCEPTION: the offset is a 64-bit type whereas ftell() is generally 'long'
  85658. * and 32-bits wide.
  85659. *
  85660. * \param handle The handle to the data source.
  85661. * \retval FLAC__int64
  85662. * The current position on success, \c -1 on error.
  85663. */
  85664. typedef FLAC__int64 (*FLAC__IOCallback_Tell) (FLAC__IOHandle handle);
  85665. /** Signature for the EOF callback.
  85666. * The signature and semantics mostly match POSIX feof() but WATCHOUT:
  85667. * on many systems, feof() is a macro, so in this case a wrapper function
  85668. * must be provided instead.
  85669. *
  85670. * \param handle The handle to the data source.
  85671. * \retval int
  85672. * \c 0 if not at end of file, nonzero if at end of file.
  85673. */
  85674. typedef int (*FLAC__IOCallback_Eof) (FLAC__IOHandle handle);
  85675. /** Signature for the close callback.
  85676. * The signature and semantics match POSIX fclose() implementations
  85677. * and can generally be used interchangeably.
  85678. *
  85679. * \param handle The handle to the data source.
  85680. * \retval int
  85681. * \c 0 on success, \c EOF on error.
  85682. */
  85683. typedef int (*FLAC__IOCallback_Close) (FLAC__IOHandle handle);
  85684. /** A structure for holding a set of callbacks.
  85685. * Each FLAC interface that requires a FLAC__IOCallbacks structure will
  85686. * describe which of the callbacks are required. The ones that are not
  85687. * required may be set to NULL.
  85688. *
  85689. * If the seek requirement for an interface is optional, you can signify that
  85690. * a data sorce is not seekable by setting the \a seek field to \c NULL.
  85691. */
  85692. typedef struct {
  85693. FLAC__IOCallback_Read read;
  85694. FLAC__IOCallback_Write write;
  85695. FLAC__IOCallback_Seek seek;
  85696. FLAC__IOCallback_Tell tell;
  85697. FLAC__IOCallback_Eof eof;
  85698. FLAC__IOCallback_Close close;
  85699. } FLAC__IOCallbacks;
  85700. /* \} */
  85701. #ifdef __cplusplus
  85702. }
  85703. #endif
  85704. #endif
  85705. /*** End of inlined file: callback.h ***/
  85706. /*** Start of inlined file: format.h ***/
  85707. #ifndef FLAC__FORMAT_H
  85708. #define FLAC__FORMAT_H
  85709. #ifdef __cplusplus
  85710. extern "C" {
  85711. #endif
  85712. /** \file include/FLAC/format.h
  85713. *
  85714. * \brief
  85715. * This module contains structure definitions for the representation
  85716. * of FLAC format components in memory. These are the basic
  85717. * structures used by the rest of the interfaces.
  85718. *
  85719. * See the detailed documentation in the
  85720. * \link flac_format format \endlink module.
  85721. */
  85722. /** \defgroup flac_format FLAC/format.h: format components
  85723. * \ingroup flac
  85724. *
  85725. * \brief
  85726. * This module contains structure definitions for the representation
  85727. * of FLAC format components in memory. These are the basic
  85728. * structures used by the rest of the interfaces.
  85729. *
  85730. * First, you should be familiar with the
  85731. * <A HREF="../format.html">FLAC format</A>. Many of the values here
  85732. * follow directly from the specification. As a user of libFLAC, the
  85733. * interesting parts really are the structures that describe the frame
  85734. * header and metadata blocks.
  85735. *
  85736. * The format structures here are very primitive, designed to store
  85737. * information in an efficient way. Reading information from the
  85738. * structures is easy but creating or modifying them directly is
  85739. * more complex. For the most part, as a user of a library, editing
  85740. * is not necessary; however, for metadata blocks it is, so there are
  85741. * convenience functions provided in the \link flac_metadata metadata
  85742. * module \endlink to simplify the manipulation of metadata blocks.
  85743. *
  85744. * \note
  85745. * It's not the best convention, but symbols ending in _LEN are in bits
  85746. * and _LENGTH are in bytes. _LENGTH symbols are \#defines instead of
  85747. * global variables because they are usually used when declaring byte
  85748. * arrays and some compilers require compile-time knowledge of array
  85749. * sizes when declared on the stack.
  85750. *
  85751. * \{
  85752. */
  85753. /*
  85754. Most of the values described in this file are defined by the FLAC
  85755. format specification. There is nothing to tune here.
  85756. */
  85757. /** The largest legal metadata type code. */
  85758. #define FLAC__MAX_METADATA_TYPE_CODE (126u)
  85759. /** The minimum block size, in samples, permitted by the format. */
  85760. #define FLAC__MIN_BLOCK_SIZE (16u)
  85761. /** The maximum block size, in samples, permitted by the format. */
  85762. #define FLAC__MAX_BLOCK_SIZE (65535u)
  85763. /** The maximum block size, in samples, permitted by the FLAC subset for
  85764. * sample rates up to 48kHz. */
  85765. #define FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ (4608u)
  85766. /** The maximum number of channels permitted by the format. */
  85767. #define FLAC__MAX_CHANNELS (8u)
  85768. /** The minimum sample resolution permitted by the format. */
  85769. #define FLAC__MIN_BITS_PER_SAMPLE (4u)
  85770. /** The maximum sample resolution permitted by the format. */
  85771. #define FLAC__MAX_BITS_PER_SAMPLE (32u)
  85772. /** The maximum sample resolution permitted by libFLAC.
  85773. *
  85774. * \warning
  85775. * FLAC__MAX_BITS_PER_SAMPLE is the limit of the FLAC format. However,
  85776. * the reference encoder/decoder is currently limited to 24 bits because
  85777. * of prevalent 32-bit math, so make sure and use this value when
  85778. * appropriate.
  85779. */
  85780. #define FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE (24u)
  85781. /** The maximum sample rate permitted by the format. The value is
  85782. * ((2 ^ 16) - 1) * 10; see <A HREF="../format.html">FLAC format</A>
  85783. * as to why.
  85784. */
  85785. #define FLAC__MAX_SAMPLE_RATE (655350u)
  85786. /** The maximum LPC order permitted by the format. */
  85787. #define FLAC__MAX_LPC_ORDER (32u)
  85788. /** The maximum LPC order permitted by the FLAC subset for sample rates
  85789. * up to 48kHz. */
  85790. #define FLAC__SUBSET_MAX_LPC_ORDER_48000HZ (12u)
  85791. /** The minimum quantized linear predictor coefficient precision
  85792. * permitted by the format.
  85793. */
  85794. #define FLAC__MIN_QLP_COEFF_PRECISION (5u)
  85795. /** The maximum quantized linear predictor coefficient precision
  85796. * permitted by the format.
  85797. */
  85798. #define FLAC__MAX_QLP_COEFF_PRECISION (15u)
  85799. /** The maximum order of the fixed predictors permitted by the format. */
  85800. #define FLAC__MAX_FIXED_ORDER (4u)
  85801. /** The maximum Rice partition order permitted by the format. */
  85802. #define FLAC__MAX_RICE_PARTITION_ORDER (15u)
  85803. /** The maximum Rice partition order permitted by the FLAC Subset. */
  85804. #define FLAC__SUBSET_MAX_RICE_PARTITION_ORDER (8u)
  85805. /** The version string of the release, stamped onto the libraries and binaries.
  85806. *
  85807. * \note
  85808. * This does not correspond to the shared library version number, which
  85809. * is used to determine binary compatibility.
  85810. */
  85811. extern FLAC_API const char *FLAC__VERSION_STRING;
  85812. /** The vendor string inserted by the encoder into the VORBIS_COMMENT block.
  85813. * This is a NUL-terminated ASCII string; when inserted into the
  85814. * VORBIS_COMMENT the trailing null is stripped.
  85815. */
  85816. extern FLAC_API const char *FLAC__VENDOR_STRING;
  85817. /** The byte string representation of the beginning of a FLAC stream. */
  85818. extern FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4]; /* = "fLaC" */
  85819. /** The 32-bit integer big-endian representation of the beginning of
  85820. * a FLAC stream.
  85821. */
  85822. extern FLAC_API const unsigned FLAC__STREAM_SYNC; /* = 0x664C6143 */
  85823. /** The length of the FLAC signature in bits. */
  85824. extern FLAC_API const unsigned FLAC__STREAM_SYNC_LEN; /* = 32 bits */
  85825. /** The length of the FLAC signature in bytes. */
  85826. #define FLAC__STREAM_SYNC_LENGTH (4u)
  85827. /*****************************************************************************
  85828. *
  85829. * Subframe structures
  85830. *
  85831. *****************************************************************************/
  85832. /*****************************************************************************/
  85833. /** An enumeration of the available entropy coding methods. */
  85834. typedef enum {
  85835. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE = 0,
  85836. /**< Residual is coded by partitioning into contexts, each with it's own
  85837. * 4-bit Rice parameter. */
  85838. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 = 1
  85839. /**< Residual is coded by partitioning into contexts, each with it's own
  85840. * 5-bit Rice parameter. */
  85841. } FLAC__EntropyCodingMethodType;
  85842. /** Maps a FLAC__EntropyCodingMethodType to a C string.
  85843. *
  85844. * Using a FLAC__EntropyCodingMethodType as the index to this array will
  85845. * give the string equivalent. The contents should not be modified.
  85846. */
  85847. extern FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[];
  85848. /** Contents of a Rice partitioned residual
  85849. */
  85850. typedef struct {
  85851. unsigned *parameters;
  85852. /**< The Rice parameters for each context. */
  85853. unsigned *raw_bits;
  85854. /**< Widths for escape-coded partitions. Will be non-zero for escaped
  85855. * partitions and zero for unescaped partitions.
  85856. */
  85857. unsigned capacity_by_order;
  85858. /**< The capacity of the \a parameters and \a raw_bits arrays
  85859. * specified as an order, i.e. the number of array elements
  85860. * allocated is 2 ^ \a capacity_by_order.
  85861. */
  85862. } FLAC__EntropyCodingMethod_PartitionedRiceContents;
  85863. /** Header for a Rice partitioned residual. (c.f. <A HREF="../format.html#partitioned_rice">format specification</A>)
  85864. */
  85865. typedef struct {
  85866. unsigned order;
  85867. /**< The partition order, i.e. # of contexts = 2 ^ \a order. */
  85868. const FLAC__EntropyCodingMethod_PartitionedRiceContents *contents;
  85869. /**< The context's Rice parameters and/or raw bits. */
  85870. } FLAC__EntropyCodingMethod_PartitionedRice;
  85871. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN; /**< == 4 (bits) */
  85872. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN; /**< == 4 (bits) */
  85873. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN; /**< == 5 (bits) */
  85874. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN; /**< == 5 (bits) */
  85875. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  85876. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  85877. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER;
  85878. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  85879. /** Header for the entropy coding method. (c.f. <A HREF="../format.html#residual">format specification</A>)
  85880. */
  85881. typedef struct {
  85882. FLAC__EntropyCodingMethodType type;
  85883. union {
  85884. FLAC__EntropyCodingMethod_PartitionedRice partitioned_rice;
  85885. } data;
  85886. } FLAC__EntropyCodingMethod;
  85887. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN; /**< == 2 (bits) */
  85888. /*****************************************************************************/
  85889. /** An enumeration of the available subframe types. */
  85890. typedef enum {
  85891. FLAC__SUBFRAME_TYPE_CONSTANT = 0, /**< constant signal */
  85892. FLAC__SUBFRAME_TYPE_VERBATIM = 1, /**< uncompressed signal */
  85893. FLAC__SUBFRAME_TYPE_FIXED = 2, /**< fixed polynomial prediction */
  85894. FLAC__SUBFRAME_TYPE_LPC = 3 /**< linear prediction */
  85895. } FLAC__SubframeType;
  85896. /** Maps a FLAC__SubframeType to a C string.
  85897. *
  85898. * Using a FLAC__SubframeType as the index to this array will
  85899. * give the string equivalent. The contents should not be modified.
  85900. */
  85901. extern FLAC_API const char * const FLAC__SubframeTypeString[];
  85902. /** CONSTANT subframe. (c.f. <A HREF="../format.html#subframe_constant">format specification</A>)
  85903. */
  85904. typedef struct {
  85905. FLAC__int32 value; /**< The constant signal value. */
  85906. } FLAC__Subframe_Constant;
  85907. /** VERBATIM subframe. (c.f. <A HREF="../format.html#subframe_verbatim">format specification</A>)
  85908. */
  85909. typedef struct {
  85910. const FLAC__int32 *data; /**< A pointer to verbatim signal. */
  85911. } FLAC__Subframe_Verbatim;
  85912. /** FIXED subframe. (c.f. <A HREF="../format.html#subframe_fixed">format specification</A>)
  85913. */
  85914. typedef struct {
  85915. FLAC__EntropyCodingMethod entropy_coding_method;
  85916. /**< The residual coding method. */
  85917. unsigned order;
  85918. /**< The polynomial order. */
  85919. FLAC__int32 warmup[FLAC__MAX_FIXED_ORDER];
  85920. /**< Warmup samples to prime the predictor, length == order. */
  85921. const FLAC__int32 *residual;
  85922. /**< The residual signal, length == (blocksize minus order) samples. */
  85923. } FLAC__Subframe_Fixed;
  85924. /** LPC subframe. (c.f. <A HREF="../format.html#subframe_lpc">format specification</A>)
  85925. */
  85926. typedef struct {
  85927. FLAC__EntropyCodingMethod entropy_coding_method;
  85928. /**< The residual coding method. */
  85929. unsigned order;
  85930. /**< The FIR order. */
  85931. unsigned qlp_coeff_precision;
  85932. /**< Quantized FIR filter coefficient precision in bits. */
  85933. int quantization_level;
  85934. /**< The qlp coeff shift needed. */
  85935. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  85936. /**< FIR filter coefficients. */
  85937. FLAC__int32 warmup[FLAC__MAX_LPC_ORDER];
  85938. /**< Warmup samples to prime the predictor, length == order. */
  85939. const FLAC__int32 *residual;
  85940. /**< The residual signal, length == (blocksize minus order) samples. */
  85941. } FLAC__Subframe_LPC;
  85942. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN; /**< == 4 (bits) */
  85943. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN; /**< == 5 (bits) */
  85944. /** FLAC subframe structure. (c.f. <A HREF="../format.html#subframe">format specification</A>)
  85945. */
  85946. typedef struct {
  85947. FLAC__SubframeType type;
  85948. union {
  85949. FLAC__Subframe_Constant constant;
  85950. FLAC__Subframe_Fixed fixed;
  85951. FLAC__Subframe_LPC lpc;
  85952. FLAC__Subframe_Verbatim verbatim;
  85953. } data;
  85954. unsigned wasted_bits;
  85955. } FLAC__Subframe;
  85956. /** == 1 (bit)
  85957. *
  85958. * This used to be a zero-padding bit (hence the name
  85959. * FLAC__SUBFRAME_ZERO_PAD_LEN) but is now a reserved bit. It still has a
  85960. * mandatory value of \c 0 but in the future may take on the value \c 0 or \c 1
  85961. * to mean something else.
  85962. */
  85963. extern FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN;
  85964. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN; /**< == 6 (bits) */
  85965. extern FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN; /**< == 1 (bit) */
  85966. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK; /**< = 0x00 */
  85967. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK; /**< = 0x02 */
  85968. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK; /**< = 0x10 */
  85969. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK; /**< = 0x40 */
  85970. /*****************************************************************************/
  85971. /*****************************************************************************
  85972. *
  85973. * Frame structures
  85974. *
  85975. *****************************************************************************/
  85976. /** An enumeration of the available channel assignments. */
  85977. typedef enum {
  85978. FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT = 0, /**< independent channels */
  85979. FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE = 1, /**< left+side stereo */
  85980. FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE = 2, /**< right+side stereo */
  85981. FLAC__CHANNEL_ASSIGNMENT_MID_SIDE = 3 /**< mid+side stereo */
  85982. } FLAC__ChannelAssignment;
  85983. /** Maps a FLAC__ChannelAssignment to a C string.
  85984. *
  85985. * Using a FLAC__ChannelAssignment as the index to this array will
  85986. * give the string equivalent. The contents should not be modified.
  85987. */
  85988. extern FLAC_API const char * const FLAC__ChannelAssignmentString[];
  85989. /** An enumeration of the possible frame numbering methods. */
  85990. typedef enum {
  85991. FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER, /**< number contains the frame number */
  85992. FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER /**< number contains the sample number of first sample in frame */
  85993. } FLAC__FrameNumberType;
  85994. /** Maps a FLAC__FrameNumberType to a C string.
  85995. *
  85996. * Using a FLAC__FrameNumberType as the index to this array will
  85997. * give the string equivalent. The contents should not be modified.
  85998. */
  85999. extern FLAC_API const char * const FLAC__FrameNumberTypeString[];
  86000. /** FLAC frame header structure. (c.f. <A HREF="../format.html#frame_header">format specification</A>)
  86001. */
  86002. typedef struct {
  86003. unsigned blocksize;
  86004. /**< The number of samples per subframe. */
  86005. unsigned sample_rate;
  86006. /**< The sample rate in Hz. */
  86007. unsigned channels;
  86008. /**< The number of channels (== number of subframes). */
  86009. FLAC__ChannelAssignment channel_assignment;
  86010. /**< The channel assignment for the frame. */
  86011. unsigned bits_per_sample;
  86012. /**< The sample resolution. */
  86013. FLAC__FrameNumberType number_type;
  86014. /**< The numbering scheme used for the frame. As a convenience, the
  86015. * decoder will always convert a frame number to a sample number because
  86016. * the rules are complex. */
  86017. union {
  86018. FLAC__uint32 frame_number;
  86019. FLAC__uint64 sample_number;
  86020. } number;
  86021. /**< The frame number or sample number of first sample in frame;
  86022. * use the \a number_type value to determine which to use. */
  86023. FLAC__uint8 crc;
  86024. /**< CRC-8 (polynomial = x^8 + x^2 + x^1 + x^0, initialized with 0)
  86025. * of the raw frame header bytes, meaning everything before the CRC byte
  86026. * including the sync code.
  86027. */
  86028. } FLAC__FrameHeader;
  86029. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC; /**< == 0x3ffe; the frame header sync code */
  86030. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN; /**< == 14 (bits) */
  86031. extern FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN; /**< == 1 (bits) */
  86032. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN; /**< == 1 (bits) */
  86033. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN; /**< == 4 (bits) */
  86034. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN; /**< == 4 (bits) */
  86035. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN; /**< == 4 (bits) */
  86036. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN; /**< == 3 (bits) */
  86037. extern FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN; /**< == 1 (bit) */
  86038. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN; /**< == 8 (bits) */
  86039. /** FLAC frame footer structure. (c.f. <A HREF="../format.html#frame_footer">format specification</A>)
  86040. */
  86041. typedef struct {
  86042. FLAC__uint16 crc;
  86043. /**< CRC-16 (polynomial = x^16 + x^15 + x^2 + x^0, initialized with
  86044. * 0) of the bytes before the crc, back to and including the frame header
  86045. * sync code.
  86046. */
  86047. } FLAC__FrameFooter;
  86048. extern FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN; /**< == 16 (bits) */
  86049. /** FLAC frame structure. (c.f. <A HREF="../format.html#frame">format specification</A>)
  86050. */
  86051. typedef struct {
  86052. FLAC__FrameHeader header;
  86053. FLAC__Subframe subframes[FLAC__MAX_CHANNELS];
  86054. FLAC__FrameFooter footer;
  86055. } FLAC__Frame;
  86056. /*****************************************************************************/
  86057. /*****************************************************************************
  86058. *
  86059. * Meta-data structures
  86060. *
  86061. *****************************************************************************/
  86062. /** An enumeration of the available metadata block types. */
  86063. typedef enum {
  86064. FLAC__METADATA_TYPE_STREAMINFO = 0,
  86065. /**< <A HREF="../format.html#metadata_block_streaminfo">STREAMINFO</A> block */
  86066. FLAC__METADATA_TYPE_PADDING = 1,
  86067. /**< <A HREF="../format.html#metadata_block_padding">PADDING</A> block */
  86068. FLAC__METADATA_TYPE_APPLICATION = 2,
  86069. /**< <A HREF="../format.html#metadata_block_application">APPLICATION</A> block */
  86070. FLAC__METADATA_TYPE_SEEKTABLE = 3,
  86071. /**< <A HREF="../format.html#metadata_block_seektable">SEEKTABLE</A> block */
  86072. FLAC__METADATA_TYPE_VORBIS_COMMENT = 4,
  86073. /**< <A HREF="../format.html#metadata_block_vorbis_comment">VORBISCOMMENT</A> block (a.k.a. FLAC tags) */
  86074. FLAC__METADATA_TYPE_CUESHEET = 5,
  86075. /**< <A HREF="../format.html#metadata_block_cuesheet">CUESHEET</A> block */
  86076. FLAC__METADATA_TYPE_PICTURE = 6,
  86077. /**< <A HREF="../format.html#metadata_block_picture">PICTURE</A> block */
  86078. FLAC__METADATA_TYPE_UNDEFINED = 7
  86079. /**< marker to denote beginning of undefined type range; this number will increase as new metadata types are added */
  86080. } FLAC__MetadataType;
  86081. /** Maps a FLAC__MetadataType to a C string.
  86082. *
  86083. * Using a FLAC__MetadataType as the index to this array will
  86084. * give the string equivalent. The contents should not be modified.
  86085. */
  86086. extern FLAC_API const char * const FLAC__MetadataTypeString[];
  86087. /** FLAC STREAMINFO structure. (c.f. <A HREF="../format.html#metadata_block_streaminfo">format specification</A>)
  86088. */
  86089. typedef struct {
  86090. unsigned min_blocksize, max_blocksize;
  86091. unsigned min_framesize, max_framesize;
  86092. unsigned sample_rate;
  86093. unsigned channels;
  86094. unsigned bits_per_sample;
  86095. FLAC__uint64 total_samples;
  86096. FLAC__byte md5sum[16];
  86097. } FLAC__StreamMetadata_StreamInfo;
  86098. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  86099. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  86100. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN; /**< == 24 (bits) */
  86101. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN; /**< == 24 (bits) */
  86102. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN; /**< == 20 (bits) */
  86103. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN; /**< == 3 (bits) */
  86104. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN; /**< == 5 (bits) */
  86105. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN; /**< == 36 (bits) */
  86106. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN; /**< == 128 (bits) */
  86107. /** The total stream length of the STREAMINFO block in bytes. */
  86108. #define FLAC__STREAM_METADATA_STREAMINFO_LENGTH (34u)
  86109. /** FLAC PADDING structure. (c.f. <A HREF="../format.html#metadata_block_padding">format specification</A>)
  86110. */
  86111. typedef struct {
  86112. int dummy;
  86113. /**< Conceptually this is an empty struct since we don't store the
  86114. * padding bytes. Empty structs are not allowed by some C compilers,
  86115. * hence the dummy.
  86116. */
  86117. } FLAC__StreamMetadata_Padding;
  86118. /** FLAC APPLICATION structure. (c.f. <A HREF="../format.html#metadata_block_application">format specification</A>)
  86119. */
  86120. typedef struct {
  86121. FLAC__byte id[4];
  86122. FLAC__byte *data;
  86123. } FLAC__StreamMetadata_Application;
  86124. extern FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN; /**< == 32 (bits) */
  86125. /** SeekPoint structure used in SEEKTABLE blocks. (c.f. <A HREF="../format.html#seekpoint">format specification</A>)
  86126. */
  86127. typedef struct {
  86128. FLAC__uint64 sample_number;
  86129. /**< The sample number of the target frame. */
  86130. FLAC__uint64 stream_offset;
  86131. /**< The offset, in bytes, of the target frame with respect to
  86132. * beginning of the first frame. */
  86133. unsigned frame_samples;
  86134. /**< The number of samples in the target frame. */
  86135. } FLAC__StreamMetadata_SeekPoint;
  86136. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN; /**< == 64 (bits) */
  86137. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN; /**< == 64 (bits) */
  86138. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN; /**< == 16 (bits) */
  86139. /** The total stream length of a seek point in bytes. */
  86140. #define FLAC__STREAM_METADATA_SEEKPOINT_LENGTH (18u)
  86141. /** The value used in the \a sample_number field of
  86142. * FLAC__StreamMetadataSeekPoint used to indicate a placeholder
  86143. * point (== 0xffffffffffffffff).
  86144. */
  86145. extern FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  86146. /** FLAC SEEKTABLE structure. (c.f. <A HREF="../format.html#metadata_block_seektable">format specification</A>)
  86147. *
  86148. * \note From the format specification:
  86149. * - The seek points must be sorted by ascending sample number.
  86150. * - Each seek point's sample number must be the first sample of the
  86151. * target frame.
  86152. * - Each seek point's sample number must be unique within the table.
  86153. * - Existence of a SEEKTABLE block implies a correct setting of
  86154. * total_samples in the stream_info block.
  86155. * - Behavior is undefined when more than one SEEKTABLE block is
  86156. * present in a stream.
  86157. */
  86158. typedef struct {
  86159. unsigned num_points;
  86160. FLAC__StreamMetadata_SeekPoint *points;
  86161. } FLAC__StreamMetadata_SeekTable;
  86162. /** Vorbis comment entry structure used in VORBIS_COMMENT blocks. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  86163. *
  86164. * For convenience, the APIs maintain a trailing NUL character at the end of
  86165. * \a entry which is not counted toward \a length, i.e.
  86166. * \code strlen(entry) == length \endcode
  86167. */
  86168. typedef struct {
  86169. FLAC__uint32 length;
  86170. FLAC__byte *entry;
  86171. } FLAC__StreamMetadata_VorbisComment_Entry;
  86172. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN; /**< == 32 (bits) */
  86173. /** FLAC VORBIS_COMMENT structure. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  86174. */
  86175. typedef struct {
  86176. FLAC__StreamMetadata_VorbisComment_Entry vendor_string;
  86177. FLAC__uint32 num_comments;
  86178. FLAC__StreamMetadata_VorbisComment_Entry *comments;
  86179. } FLAC__StreamMetadata_VorbisComment;
  86180. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN; /**< == 32 (bits) */
  86181. /** FLAC CUESHEET track index structure. (See the
  86182. * <A HREF="../format.html#cuesheet_track_index">format specification</A> for
  86183. * the full description of each field.)
  86184. */
  86185. typedef struct {
  86186. FLAC__uint64 offset;
  86187. /**< Offset in samples, relative to the track offset, of the index
  86188. * point.
  86189. */
  86190. FLAC__byte number;
  86191. /**< The index point number. */
  86192. } FLAC__StreamMetadata_CueSheet_Index;
  86193. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN; /**< == 64 (bits) */
  86194. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN; /**< == 8 (bits) */
  86195. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN; /**< == 3*8 (bits) */
  86196. /** FLAC CUESHEET track structure. (See the
  86197. * <A HREF="../format.html#cuesheet_track">format specification</A> for
  86198. * the full description of each field.)
  86199. */
  86200. typedef struct {
  86201. FLAC__uint64 offset;
  86202. /**< Track offset in samples, relative to the beginning of the FLAC audio stream. */
  86203. FLAC__byte number;
  86204. /**< The track number. */
  86205. char isrc[13];
  86206. /**< Track ISRC. This is a 12-digit alphanumeric code plus a trailing \c NUL byte */
  86207. unsigned type:1;
  86208. /**< The track type: 0 for audio, 1 for non-audio. */
  86209. unsigned pre_emphasis:1;
  86210. /**< The pre-emphasis flag: 0 for no pre-emphasis, 1 for pre-emphasis. */
  86211. FLAC__byte num_indices;
  86212. /**< The number of track index points. */
  86213. FLAC__StreamMetadata_CueSheet_Index *indices;
  86214. /**< NULL if num_indices == 0, else pointer to array of index points. */
  86215. } FLAC__StreamMetadata_CueSheet_Track;
  86216. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN; /**< == 64 (bits) */
  86217. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN; /**< == 8 (bits) */
  86218. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN; /**< == 12*8 (bits) */
  86219. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN; /**< == 1 (bit) */
  86220. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN; /**< == 1 (bit) */
  86221. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN; /**< == 6+13*8 (bits) */
  86222. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN; /**< == 8 (bits) */
  86223. /** FLAC CUESHEET structure. (See the
  86224. * <A HREF="../format.html#metadata_block_cuesheet">format specification</A>
  86225. * for the full description of each field.)
  86226. */
  86227. typedef struct {
  86228. char media_catalog_number[129];
  86229. /**< Media catalog number, in ASCII printable characters 0x20-0x7e. In
  86230. * general, the media catalog number may be 0 to 128 bytes long; any
  86231. * unused characters should be right-padded with NUL characters.
  86232. */
  86233. FLAC__uint64 lead_in;
  86234. /**< The number of lead-in samples. */
  86235. FLAC__bool is_cd;
  86236. /**< \c true if CUESHEET corresponds to a Compact Disc, else \c false. */
  86237. unsigned num_tracks;
  86238. /**< The number of tracks. */
  86239. FLAC__StreamMetadata_CueSheet_Track *tracks;
  86240. /**< NULL if num_tracks == 0, else pointer to array of tracks. */
  86241. } FLAC__StreamMetadata_CueSheet;
  86242. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN; /**< == 128*8 (bits) */
  86243. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN; /**< == 64 (bits) */
  86244. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN; /**< == 1 (bit) */
  86245. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN; /**< == 7+258*8 (bits) */
  86246. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN; /**< == 8 (bits) */
  86247. /** An enumeration of the PICTURE types (see FLAC__StreamMetadataPicture and id3 v2.4 APIC tag). */
  86248. typedef enum {
  86249. FLAC__STREAM_METADATA_PICTURE_TYPE_OTHER = 0, /**< Other */
  86250. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD = 1, /**< 32x32 pixels 'file icon' (PNG only) */
  86251. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON = 2, /**< Other file icon */
  86252. FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER = 3, /**< Cover (front) */
  86253. FLAC__STREAM_METADATA_PICTURE_TYPE_BACK_COVER = 4, /**< Cover (back) */
  86254. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAFLET_PAGE = 5, /**< Leaflet page */
  86255. FLAC__STREAM_METADATA_PICTURE_TYPE_MEDIA = 6, /**< Media (e.g. label side of CD) */
  86256. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAD_ARTIST = 7, /**< Lead artist/lead performer/soloist */
  86257. FLAC__STREAM_METADATA_PICTURE_TYPE_ARTIST = 8, /**< Artist/performer */
  86258. FLAC__STREAM_METADATA_PICTURE_TYPE_CONDUCTOR = 9, /**< Conductor */
  86259. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND = 10, /**< Band/Orchestra */
  86260. FLAC__STREAM_METADATA_PICTURE_TYPE_COMPOSER = 11, /**< Composer */
  86261. FLAC__STREAM_METADATA_PICTURE_TYPE_LYRICIST = 12, /**< Lyricist/text writer */
  86262. FLAC__STREAM_METADATA_PICTURE_TYPE_RECORDING_LOCATION = 13, /**< Recording Location */
  86263. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_RECORDING = 14, /**< During recording */
  86264. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_PERFORMANCE = 15, /**< During performance */
  86265. FLAC__STREAM_METADATA_PICTURE_TYPE_VIDEO_SCREEN_CAPTURE = 16, /**< Movie/video screen capture */
  86266. FLAC__STREAM_METADATA_PICTURE_TYPE_FISH = 17, /**< A bright coloured fish */
  86267. FLAC__STREAM_METADATA_PICTURE_TYPE_ILLUSTRATION = 18, /**< Illustration */
  86268. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND_LOGOTYPE = 19, /**< Band/artist logotype */
  86269. FLAC__STREAM_METADATA_PICTURE_TYPE_PUBLISHER_LOGOTYPE = 20, /**< Publisher/Studio logotype */
  86270. FLAC__STREAM_METADATA_PICTURE_TYPE_UNDEFINED
  86271. } FLAC__StreamMetadata_Picture_Type;
  86272. /** Maps a FLAC__StreamMetadata_Picture_Type to a C string.
  86273. *
  86274. * Using a FLAC__StreamMetadata_Picture_Type as the index to this array
  86275. * will give the string equivalent. The contents should not be
  86276. * modified.
  86277. */
  86278. extern FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[];
  86279. /** FLAC PICTURE structure. (See the
  86280. * <A HREF="../format.html#metadata_block_picture">format specification</A>
  86281. * for the full description of each field.)
  86282. */
  86283. typedef struct {
  86284. FLAC__StreamMetadata_Picture_Type type;
  86285. /**< The kind of picture stored. */
  86286. char *mime_type;
  86287. /**< Picture data's MIME type, in ASCII printable characters
  86288. * 0x20-0x7e, NUL terminated. For best compatibility with players,
  86289. * use picture data of MIME type \c image/jpeg or \c image/png. A
  86290. * MIME type of '-->' is also allowed, in which case the picture
  86291. * data should be a complete URL. In file storage, the MIME type is
  86292. * stored as a 32-bit length followed by the ASCII string with no NUL
  86293. * terminator, but is converted to a plain C string in this structure
  86294. * for convenience.
  86295. */
  86296. FLAC__byte *description;
  86297. /**< Picture's description in UTF-8, NUL terminated. In file storage,
  86298. * the description is stored as a 32-bit length followed by the UTF-8
  86299. * string with no NUL terminator, but is converted to a plain C string
  86300. * in this structure for convenience.
  86301. */
  86302. FLAC__uint32 width;
  86303. /**< Picture's width in pixels. */
  86304. FLAC__uint32 height;
  86305. /**< Picture's height in pixels. */
  86306. FLAC__uint32 depth;
  86307. /**< Picture's color depth in bits-per-pixel. */
  86308. FLAC__uint32 colors;
  86309. /**< For indexed palettes (like GIF), picture's number of colors (the
  86310. * number of palette entries), or \c 0 for non-indexed (i.e. 2^depth).
  86311. */
  86312. FLAC__uint32 data_length;
  86313. /**< Length of binary picture data in bytes. */
  86314. FLAC__byte *data;
  86315. /**< Binary picture data. */
  86316. } FLAC__StreamMetadata_Picture;
  86317. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN; /**< == 32 (bits) */
  86318. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN; /**< == 32 (bits) */
  86319. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN; /**< == 32 (bits) */
  86320. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN; /**< == 32 (bits) */
  86321. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN; /**< == 32 (bits) */
  86322. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN; /**< == 32 (bits) */
  86323. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN; /**< == 32 (bits) */
  86324. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN; /**< == 32 (bits) */
  86325. /** Structure that is used when a metadata block of unknown type is loaded.
  86326. * The contents are opaque. The structure is used only internally to
  86327. * correctly handle unknown metadata.
  86328. */
  86329. typedef struct {
  86330. FLAC__byte *data;
  86331. } FLAC__StreamMetadata_Unknown;
  86332. /** FLAC metadata block structure. (c.f. <A HREF="../format.html#metadata_block">format specification</A>)
  86333. */
  86334. typedef struct {
  86335. FLAC__MetadataType type;
  86336. /**< The type of the metadata block; used determine which member of the
  86337. * \a data union to dereference. If type >= FLAC__METADATA_TYPE_UNDEFINED
  86338. * then \a data.unknown must be used. */
  86339. FLAC__bool is_last;
  86340. /**< \c true if this metadata block is the last, else \a false */
  86341. unsigned length;
  86342. /**< Length, in bytes, of the block data as it appears in the stream. */
  86343. union {
  86344. FLAC__StreamMetadata_StreamInfo stream_info;
  86345. FLAC__StreamMetadata_Padding padding;
  86346. FLAC__StreamMetadata_Application application;
  86347. FLAC__StreamMetadata_SeekTable seek_table;
  86348. FLAC__StreamMetadata_VorbisComment vorbis_comment;
  86349. FLAC__StreamMetadata_CueSheet cue_sheet;
  86350. FLAC__StreamMetadata_Picture picture;
  86351. FLAC__StreamMetadata_Unknown unknown;
  86352. } data;
  86353. /**< Polymorphic block data; use the \a type value to determine which
  86354. * to use. */
  86355. } FLAC__StreamMetadata;
  86356. extern FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN; /**< == 1 (bit) */
  86357. extern FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN; /**< == 7 (bits) */
  86358. extern FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN; /**< == 24 (bits) */
  86359. /** The total stream length of a metadata block header in bytes. */
  86360. #define FLAC__STREAM_METADATA_HEADER_LENGTH (4u)
  86361. /*****************************************************************************/
  86362. /*****************************************************************************
  86363. *
  86364. * Utility functions
  86365. *
  86366. *****************************************************************************/
  86367. /** Tests that a sample rate is valid for FLAC.
  86368. *
  86369. * \param sample_rate The sample rate to test for compliance.
  86370. * \retval FLAC__bool
  86371. * \c true if the given sample rate conforms to the specification, else
  86372. * \c false.
  86373. */
  86374. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate);
  86375. /** Tests that a sample rate is valid for the FLAC subset. The subset rules
  86376. * for valid sample rates are slightly more complex since the rate has to
  86377. * be expressible completely in the frame header.
  86378. *
  86379. * \param sample_rate The sample rate to test for compliance.
  86380. * \retval FLAC__bool
  86381. * \c true if the given sample rate conforms to the specification for the
  86382. * subset, else \c false.
  86383. */
  86384. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate);
  86385. /** Check a Vorbis comment entry name to see if it conforms to the Vorbis
  86386. * comment specification.
  86387. *
  86388. * Vorbis comment names must be composed only of characters from
  86389. * [0x20-0x3C,0x3E-0x7D].
  86390. *
  86391. * \param name A NUL-terminated string to be checked.
  86392. * \assert
  86393. * \code name != NULL \endcode
  86394. * \retval FLAC__bool
  86395. * \c false if entry name is illegal, else \c true.
  86396. */
  86397. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name);
  86398. /** Check a Vorbis comment entry value to see if it conforms to the Vorbis
  86399. * comment specification.
  86400. *
  86401. * Vorbis comment values must be valid UTF-8 sequences.
  86402. *
  86403. * \param value A string to be checked.
  86404. * \param length A the length of \a value in bytes. May be
  86405. * \c (unsigned)(-1) to indicate that \a value is a plain
  86406. * UTF-8 NUL-terminated string.
  86407. * \assert
  86408. * \code value != NULL \endcode
  86409. * \retval FLAC__bool
  86410. * \c false if entry name is illegal, else \c true.
  86411. */
  86412. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length);
  86413. /** Check a Vorbis comment entry to see if it conforms to the Vorbis
  86414. * comment specification.
  86415. *
  86416. * Vorbis comment entries must be of the form 'name=value', and 'name' and
  86417. * 'value' must be legal according to
  86418. * FLAC__format_vorbiscomment_entry_name_is_legal() and
  86419. * FLAC__format_vorbiscomment_entry_value_is_legal() respectively.
  86420. *
  86421. * \param entry An entry to be checked.
  86422. * \param length The length of \a entry in bytes.
  86423. * \assert
  86424. * \code value != NULL \endcode
  86425. * \retval FLAC__bool
  86426. * \c false if entry name is illegal, else \c true.
  86427. */
  86428. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length);
  86429. /** Check a seek table to see if it conforms to the FLAC specification.
  86430. * See the format specification for limits on the contents of the
  86431. * seek table.
  86432. *
  86433. * \param seek_table A pointer to a seek table to be checked.
  86434. * \assert
  86435. * \code seek_table != NULL \endcode
  86436. * \retval FLAC__bool
  86437. * \c false if seek table is illegal, else \c true.
  86438. */
  86439. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table);
  86440. /** Sort a seek table's seek points according to the format specification.
  86441. * This includes a "unique-ification" step to remove duplicates, i.e.
  86442. * seek points with identical \a sample_number values. Duplicate seek
  86443. * points are converted into placeholder points and sorted to the end of
  86444. * the table.
  86445. *
  86446. * \param seek_table A pointer to a seek table to be sorted.
  86447. * \assert
  86448. * \code seek_table != NULL \endcode
  86449. * \retval unsigned
  86450. * The number of duplicate seek points converted into placeholders.
  86451. */
  86452. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table);
  86453. /** Check a cue sheet to see if it conforms to the FLAC specification.
  86454. * See the format specification for limits on the contents of the
  86455. * cue sheet.
  86456. *
  86457. * \param cue_sheet A pointer to an existing cue sheet to be checked.
  86458. * \param check_cd_da_subset If \c true, check CUESHEET against more
  86459. * stringent requirements for a CD-DA (audio) disc.
  86460. * \param violation Address of a pointer to a string. If there is a
  86461. * violation, a pointer to a string explanation of the
  86462. * violation will be returned here. \a violation may be
  86463. * \c NULL if you don't need the returned string. Do not
  86464. * free the returned string; it will always point to static
  86465. * data.
  86466. * \assert
  86467. * \code cue_sheet != NULL \endcode
  86468. * \retval FLAC__bool
  86469. * \c false if cue sheet is illegal, else \c true.
  86470. */
  86471. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation);
  86472. /** Check picture data to see if it conforms to the FLAC specification.
  86473. * See the format specification for limits on the contents of the
  86474. * PICTURE block.
  86475. *
  86476. * \param picture A pointer to existing picture data to be checked.
  86477. * \param violation Address of a pointer to a string. If there is a
  86478. * violation, a pointer to a string explanation of the
  86479. * violation will be returned here. \a violation may be
  86480. * \c NULL if you don't need the returned string. Do not
  86481. * free the returned string; it will always point to static
  86482. * data.
  86483. * \assert
  86484. * \code picture != NULL \endcode
  86485. * \retval FLAC__bool
  86486. * \c false if picture data is illegal, else \c true.
  86487. */
  86488. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation);
  86489. /* \} */
  86490. #ifdef __cplusplus
  86491. }
  86492. #endif
  86493. #endif
  86494. /*** End of inlined file: format.h ***/
  86495. /*** Start of inlined file: metadata.h ***/
  86496. #ifndef FLAC__METADATA_H
  86497. #define FLAC__METADATA_H
  86498. #include <sys/types.h> /* for off_t */
  86499. /* --------------------------------------------------------------------
  86500. (For an example of how all these routines are used, see the source
  86501. code for the unit tests in src/test_libFLAC/metadata_*.c, or
  86502. metaflac in src/metaflac/)
  86503. ------------------------------------------------------------------*/
  86504. /** \file include/FLAC/metadata.h
  86505. *
  86506. * \brief
  86507. * This module provides functions for creating and manipulating FLAC
  86508. * metadata blocks in memory, and three progressively more powerful
  86509. * interfaces for traversing and editing metadata in FLAC files.
  86510. *
  86511. * See the detailed documentation for each interface in the
  86512. * \link flac_metadata metadata \endlink module.
  86513. */
  86514. /** \defgroup flac_metadata FLAC/metadata.h: metadata interfaces
  86515. * \ingroup flac
  86516. *
  86517. * \brief
  86518. * This module provides functions for creating and manipulating FLAC
  86519. * metadata blocks in memory, and three progressively more powerful
  86520. * interfaces for traversing and editing metadata in native FLAC files.
  86521. * Note that currently only the Chain interface (level 2) supports Ogg
  86522. * FLAC files, and it is read-only i.e. no writing back changed
  86523. * metadata to file.
  86524. *
  86525. * There are three metadata interfaces of increasing complexity:
  86526. *
  86527. * Level 0:
  86528. * Read-only access to the STREAMINFO, VORBIS_COMMENT, CUESHEET, and
  86529. * PICTURE blocks.
  86530. *
  86531. * Level 1:
  86532. * Read-write access to all metadata blocks. This level is write-
  86533. * efficient in most cases (more on this below), and uses less memory
  86534. * than level 2.
  86535. *
  86536. * Level 2:
  86537. * Read-write access to all metadata blocks. This level is write-
  86538. * efficient in all cases, but uses more memory since all metadata for
  86539. * the whole file is read into memory and manipulated before writing
  86540. * out again.
  86541. *
  86542. * What do we mean by efficient? Since FLAC metadata appears at the
  86543. * beginning of the file, when writing metadata back to a FLAC file
  86544. * it is possible to grow or shrink the metadata such that the entire
  86545. * file must be rewritten. However, if the size remains the same during
  86546. * changes or PADDING blocks are utilized, only the metadata needs to be
  86547. * overwritten, which is much faster.
  86548. *
  86549. * Efficient means the whole file is rewritten at most one time, and only
  86550. * when necessary. Level 1 is not efficient only in the case that you
  86551. * cause more than one metadata block to grow or shrink beyond what can
  86552. * be accomodated by padding. In this case you should probably use level
  86553. * 2, which allows you to edit all the metadata for a file in memory and
  86554. * write it out all at once.
  86555. *
  86556. * All levels know how to skip over and not disturb an ID3v2 tag at the
  86557. * front of the file.
  86558. *
  86559. * All levels access files via their filenames. In addition, level 2
  86560. * has additional alternative read and write functions that take an I/O
  86561. * handle and callbacks, for situations where access by filename is not
  86562. * possible.
  86563. *
  86564. * In addition to the three interfaces, this module defines functions for
  86565. * creating and manipulating various metadata objects in memory. As we see
  86566. * from the Format module, FLAC metadata blocks in memory are very primitive
  86567. * structures for storing information in an efficient way. Reading
  86568. * information from the structures is easy but creating or modifying them
  86569. * directly is more complex. The metadata object routines here facilitate
  86570. * this by taking care of the consistency and memory management drudgery.
  86571. *
  86572. * Unless you will be using the level 1 or 2 interfaces to modify existing
  86573. * metadata however, you will not probably not need these.
  86574. *
  86575. * From a dependency standpoint, none of the encoders or decoders require
  86576. * the metadata module. This is so that embedded users can strip out the
  86577. * metadata module from libFLAC to reduce the size and complexity.
  86578. */
  86579. #ifdef __cplusplus
  86580. extern "C" {
  86581. #endif
  86582. /** \defgroup flac_metadata_level0 FLAC/metadata.h: metadata level 0 interface
  86583. * \ingroup flac_metadata
  86584. *
  86585. * \brief
  86586. * The level 0 interface consists of individual routines to read the
  86587. * STREAMINFO, VORBIS_COMMENT, CUESHEET, and PICTURE blocks, requiring
  86588. * only a filename.
  86589. *
  86590. * They try to skip any ID3v2 tag at the head of the file.
  86591. *
  86592. * \{
  86593. */
  86594. /** Read the STREAMINFO metadata block of the given FLAC file. This function
  86595. * will try to skip any ID3v2 tag at the head of the file.
  86596. *
  86597. * \param filename The path to the FLAC file to read.
  86598. * \param streaminfo A pointer to space for the STREAMINFO block. Since
  86599. * FLAC__StreamMetadata is a simple structure with no
  86600. * memory allocation involved, you pass the address of
  86601. * an existing structure. It need not be initialized.
  86602. * \assert
  86603. * \code filename != NULL \endcode
  86604. * \code streaminfo != NULL \endcode
  86605. * \retval FLAC__bool
  86606. * \c true if a valid STREAMINFO block was read from \a filename. Returns
  86607. * \c false if there was a memory allocation error, a file decoder error,
  86608. * or the file contained no STREAMINFO block. (A memory allocation error
  86609. * is possible because this function must set up a file decoder.)
  86610. */
  86611. FLAC_API FLAC__bool FLAC__metadata_get_streaminfo(const char *filename, FLAC__StreamMetadata *streaminfo);
  86612. /** Read the VORBIS_COMMENT metadata block of the given FLAC file. This
  86613. * function will try to skip any ID3v2 tag at the head of the file.
  86614. *
  86615. * \param filename The path to the FLAC file to read.
  86616. * \param tags The address where the returned pointer will be
  86617. * stored. The \a tags object must be deleted by
  86618. * the caller using FLAC__metadata_object_delete().
  86619. * \assert
  86620. * \code filename != NULL \endcode
  86621. * \code tags != NULL \endcode
  86622. * \retval FLAC__bool
  86623. * \c true if a valid VORBIS_COMMENT block was read from \a filename,
  86624. * and \a *tags will be set to the address of the metadata structure.
  86625. * Returns \c false if there was a memory allocation error, a file
  86626. * decoder error, or the file contained no VORBIS_COMMENT block, and
  86627. * \a *tags will be set to \c NULL.
  86628. */
  86629. FLAC_API FLAC__bool FLAC__metadata_get_tags(const char *filename, FLAC__StreamMetadata **tags);
  86630. /** Read the CUESHEET metadata block of the given FLAC file. This
  86631. * function will try to skip any ID3v2 tag at the head of the file.
  86632. *
  86633. * \param filename The path to the FLAC file to read.
  86634. * \param cuesheet The address where the returned pointer will be
  86635. * stored. The \a cuesheet object must be deleted by
  86636. * the caller using FLAC__metadata_object_delete().
  86637. * \assert
  86638. * \code filename != NULL \endcode
  86639. * \code cuesheet != NULL \endcode
  86640. * \retval FLAC__bool
  86641. * \c true if a valid CUESHEET block was read from \a filename,
  86642. * and \a *cuesheet will be set to the address of the metadata
  86643. * structure. Returns \c false if there was a memory allocation
  86644. * error, a file decoder error, or the file contained no CUESHEET
  86645. * block, and \a *cuesheet will be set to \c NULL.
  86646. */
  86647. FLAC_API FLAC__bool FLAC__metadata_get_cuesheet(const char *filename, FLAC__StreamMetadata **cuesheet);
  86648. /** Read a PICTURE metadata block of the given FLAC file. This
  86649. * function will try to skip any ID3v2 tag at the head of the file.
  86650. * Since there can be more than one PICTURE block in a file, this
  86651. * function takes a number of parameters that act as constraints to
  86652. * the search. The PICTURE block with the largest area matching all
  86653. * the constraints will be returned, or \a *picture will be set to
  86654. * \c NULL if there was no such block.
  86655. *
  86656. * \param filename The path to the FLAC file to read.
  86657. * \param picture The address where the returned pointer will be
  86658. * stored. The \a picture object must be deleted by
  86659. * the caller using FLAC__metadata_object_delete().
  86660. * \param type The desired picture type. Use \c -1 to mean
  86661. * "any type".
  86662. * \param mime_type The desired MIME type, e.g. "image/jpeg". The
  86663. * string will be matched exactly. Use \c NULL to
  86664. * mean "any MIME type".
  86665. * \param description The desired description. The string will be
  86666. * matched exactly. Use \c NULL to mean "any
  86667. * description".
  86668. * \param max_width The maximum width in pixels desired. Use
  86669. * \c (unsigned)(-1) to mean "any width".
  86670. * \param max_height The maximum height in pixels desired. Use
  86671. * \c (unsigned)(-1) to mean "any height".
  86672. * \param max_depth The maximum color depth in bits-per-pixel desired.
  86673. * Use \c (unsigned)(-1) to mean "any depth".
  86674. * \param max_colors The maximum number of colors desired. Use
  86675. * \c (unsigned)(-1) to mean "any number of colors".
  86676. * \assert
  86677. * \code filename != NULL \endcode
  86678. * \code picture != NULL \endcode
  86679. * \retval FLAC__bool
  86680. * \c true if a valid PICTURE block was read from \a filename,
  86681. * and \a *picture will be set to the address of the metadata
  86682. * structure. Returns \c false if there was a memory allocation
  86683. * error, a file decoder error, or the file contained no PICTURE
  86684. * block, and \a *picture will be set to \c NULL.
  86685. */
  86686. 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);
  86687. /* \} */
  86688. /** \defgroup flac_metadata_level1 FLAC/metadata.h: metadata level 1 interface
  86689. * \ingroup flac_metadata
  86690. *
  86691. * \brief
  86692. * The level 1 interface provides read-write access to FLAC file metadata and
  86693. * operates directly on the FLAC file.
  86694. *
  86695. * The general usage of this interface is:
  86696. *
  86697. * - Create an iterator using FLAC__metadata_simple_iterator_new()
  86698. * - Attach it to a file using FLAC__metadata_simple_iterator_init() and check
  86699. * the exit code. Call FLAC__metadata_simple_iterator_is_writable() to
  86700. * see if the file is writable, or only read access is allowed.
  86701. * - Use FLAC__metadata_simple_iterator_next() and
  86702. * FLAC__metadata_simple_iterator_prev() to traverse the blocks.
  86703. * This is does not read the actual blocks themselves.
  86704. * FLAC__metadata_simple_iterator_next() is relatively fast.
  86705. * FLAC__metadata_simple_iterator_prev() is slower since it needs to search
  86706. * forward from the front of the file.
  86707. * - Use FLAC__metadata_simple_iterator_get_block_type() or
  86708. * FLAC__metadata_simple_iterator_get_block() to access the actual data at
  86709. * the current iterator position. The returned object is yours to modify
  86710. * and free.
  86711. * - Use FLAC__metadata_simple_iterator_set_block() to write a modified block
  86712. * back. You must have write permission to the original file. Make sure to
  86713. * read the whole comment to FLAC__metadata_simple_iterator_set_block()
  86714. * below.
  86715. * - Use FLAC__metadata_simple_iterator_insert_block_after() to add new blocks.
  86716. * Use the object creation functions from
  86717. * \link flac_metadata_object here \endlink to generate new objects.
  86718. * - Use FLAC__metadata_simple_iterator_delete_block() to remove the block
  86719. * currently referred to by the iterator, or replace it with padding.
  86720. * - Destroy the iterator with FLAC__metadata_simple_iterator_delete() when
  86721. * finished.
  86722. *
  86723. * \note
  86724. * The FLAC file remains open the whole time between
  86725. * FLAC__metadata_simple_iterator_init() and
  86726. * FLAC__metadata_simple_iterator_delete(), so make sure you are not altering
  86727. * the file during this time.
  86728. *
  86729. * \note
  86730. * Do not modify the \a is_last, \a length, or \a type fields of returned
  86731. * FLAC__StreamMetadata objects. These are managed automatically.
  86732. *
  86733. * \note
  86734. * If any of the modification functions
  86735. * (FLAC__metadata_simple_iterator_set_block(),
  86736. * FLAC__metadata_simple_iterator_delete_block(),
  86737. * FLAC__metadata_simple_iterator_insert_block_after(), etc.) return \c false,
  86738. * you should delete the iterator as it may no longer be valid.
  86739. *
  86740. * \{
  86741. */
  86742. struct FLAC__Metadata_SimpleIterator;
  86743. /** The opaque structure definition for the level 1 iterator type.
  86744. * See the
  86745. * \link flac_metadata_level1 metadata level 1 module \endlink
  86746. * for a detailed description.
  86747. */
  86748. typedef struct FLAC__Metadata_SimpleIterator FLAC__Metadata_SimpleIterator;
  86749. /** Status type for FLAC__Metadata_SimpleIterator.
  86750. *
  86751. * The iterator's current status can be obtained by calling FLAC__metadata_simple_iterator_status().
  86752. */
  86753. typedef enum {
  86754. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK = 0,
  86755. /**< The iterator is in the normal OK state */
  86756. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT,
  86757. /**< The data passed into a function violated the function's usage criteria */
  86758. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE,
  86759. /**< The iterator could not open the target file */
  86760. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE,
  86761. /**< The iterator could not find the FLAC signature at the start of the file */
  86762. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE,
  86763. /**< The iterator tried to write to a file that was not writable */
  86764. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA,
  86765. /**< The iterator encountered input that does not conform to the FLAC metadata specification */
  86766. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR,
  86767. /**< The iterator encountered an error while reading the FLAC file */
  86768. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR,
  86769. /**< The iterator encountered an error while seeking in the FLAC file */
  86770. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR,
  86771. /**< The iterator encountered an error while writing the FLAC file */
  86772. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR,
  86773. /**< The iterator encountered an error renaming the FLAC file */
  86774. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR,
  86775. /**< The iterator encountered an error removing the temporary file */
  86776. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR,
  86777. /**< Memory allocation failed */
  86778. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR
  86779. /**< The caller violated an assertion or an unexpected error occurred */
  86780. } FLAC__Metadata_SimpleIteratorStatus;
  86781. /** Maps a FLAC__Metadata_SimpleIteratorStatus to a C string.
  86782. *
  86783. * Using a FLAC__Metadata_SimpleIteratorStatus as the index to this array
  86784. * will give the string equivalent. The contents should not be modified.
  86785. */
  86786. extern FLAC_API const char * const FLAC__Metadata_SimpleIteratorStatusString[];
  86787. /** Create a new iterator instance.
  86788. *
  86789. * \retval FLAC__Metadata_SimpleIterator*
  86790. * \c NULL if there was an error allocating memory, else the new instance.
  86791. */
  86792. FLAC_API FLAC__Metadata_SimpleIterator *FLAC__metadata_simple_iterator_new(void);
  86793. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  86794. *
  86795. * \param iterator A pointer to an existing iterator.
  86796. * \assert
  86797. * \code iterator != NULL \endcode
  86798. */
  86799. FLAC_API void FLAC__metadata_simple_iterator_delete(FLAC__Metadata_SimpleIterator *iterator);
  86800. /** Get the current status of the iterator. Call this after a function
  86801. * returns \c false to get the reason for the error. Also resets the status
  86802. * to FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK.
  86803. *
  86804. * \param iterator A pointer to an existing iterator.
  86805. * \assert
  86806. * \code iterator != NULL \endcode
  86807. * \retval FLAC__Metadata_SimpleIteratorStatus
  86808. * The current status of the iterator.
  86809. */
  86810. FLAC_API FLAC__Metadata_SimpleIteratorStatus FLAC__metadata_simple_iterator_status(FLAC__Metadata_SimpleIterator *iterator);
  86811. /** Initialize the iterator to point to the first metadata block in the
  86812. * given FLAC file.
  86813. *
  86814. * \param iterator A pointer to an existing iterator.
  86815. * \param filename The path to the FLAC file.
  86816. * \param read_only If \c true, the FLAC file will be opened
  86817. * in read-only mode; if \c false, the FLAC
  86818. * file will be opened for edit even if no
  86819. * edits are performed.
  86820. * \param preserve_file_stats If \c true, the owner and modification
  86821. * time will be preserved even if the FLAC
  86822. * file is written to.
  86823. * \assert
  86824. * \code iterator != NULL \endcode
  86825. * \code filename != NULL \endcode
  86826. * \retval FLAC__bool
  86827. * \c false if a memory allocation error occurs, the file can't be
  86828. * opened, or another error occurs, else \c true.
  86829. */
  86830. 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);
  86831. /** Returns \c true if the FLAC file is writable. If \c false, calls to
  86832. * FLAC__metadata_simple_iterator_set_block() and
  86833. * FLAC__metadata_simple_iterator_insert_block_after() will fail.
  86834. *
  86835. * \param iterator A pointer to an existing iterator.
  86836. * \assert
  86837. * \code iterator != NULL \endcode
  86838. * \retval FLAC__bool
  86839. * See above.
  86840. */
  86841. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_writable(const FLAC__Metadata_SimpleIterator *iterator);
  86842. /** Moves the iterator forward one metadata block, returning \c false if
  86843. * already at the end.
  86844. *
  86845. * \param iterator A pointer to an existing initialized iterator.
  86846. * \assert
  86847. * \code iterator != NULL \endcode
  86848. * \a iterator has been successfully initialized with
  86849. * FLAC__metadata_simple_iterator_init()
  86850. * \retval FLAC__bool
  86851. * \c false if already at the last metadata block of the chain, else
  86852. * \c true.
  86853. */
  86854. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_next(FLAC__Metadata_SimpleIterator *iterator);
  86855. /** Moves the iterator backward one metadata block, returning \c false if
  86856. * already at the beginning.
  86857. *
  86858. * \param iterator A pointer to an existing initialized iterator.
  86859. * \assert
  86860. * \code iterator != NULL \endcode
  86861. * \a iterator has been successfully initialized with
  86862. * FLAC__metadata_simple_iterator_init()
  86863. * \retval FLAC__bool
  86864. * \c false if already at the first metadata block of the chain, else
  86865. * \c true.
  86866. */
  86867. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_prev(FLAC__Metadata_SimpleIterator *iterator);
  86868. /** Returns a flag telling if the current metadata block is the last.
  86869. *
  86870. * \param iterator A pointer to an existing initialized iterator.
  86871. * \assert
  86872. * \code iterator != NULL \endcode
  86873. * \a iterator has been successfully initialized with
  86874. * FLAC__metadata_simple_iterator_init()
  86875. * \retval FLAC__bool
  86876. * \c true if the current metadata block is the last in the file,
  86877. * else \c false.
  86878. */
  86879. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_last(const FLAC__Metadata_SimpleIterator *iterator);
  86880. /** Get the offset of the metadata block at the current position. This
  86881. * avoids reading the actual block data which can save time for large
  86882. * blocks.
  86883. *
  86884. * \param iterator A pointer to an existing initialized iterator.
  86885. * \assert
  86886. * \code iterator != NULL \endcode
  86887. * \a iterator has been successfully initialized with
  86888. * FLAC__metadata_simple_iterator_init()
  86889. * \retval off_t
  86890. * The offset of the metadata block at the current iterator position.
  86891. * This is the byte offset relative to the beginning of the file of
  86892. * the current metadata block's header.
  86893. */
  86894. FLAC_API off_t FLAC__metadata_simple_iterator_get_block_offset(const FLAC__Metadata_SimpleIterator *iterator);
  86895. /** Get the type of the metadata block at the current position. This
  86896. * avoids reading the actual block data which can save time for large
  86897. * blocks.
  86898. *
  86899. * \param iterator A pointer to an existing initialized iterator.
  86900. * \assert
  86901. * \code iterator != NULL \endcode
  86902. * \a iterator has been successfully initialized with
  86903. * FLAC__metadata_simple_iterator_init()
  86904. * \retval FLAC__MetadataType
  86905. * The type of the metadata block at the current iterator position.
  86906. */
  86907. FLAC_API FLAC__MetadataType FLAC__metadata_simple_iterator_get_block_type(const FLAC__Metadata_SimpleIterator *iterator);
  86908. /** Get the length of the metadata block at the current position. This
  86909. * avoids reading the actual block data which can save time for large
  86910. * blocks.
  86911. *
  86912. * \param iterator A pointer to an existing initialized iterator.
  86913. * \assert
  86914. * \code iterator != NULL \endcode
  86915. * \a iterator has been successfully initialized with
  86916. * FLAC__metadata_simple_iterator_init()
  86917. * \retval unsigned
  86918. * The length of the metadata block at the current iterator position.
  86919. * The is same length as that in the
  86920. * <a href="http://flac.sourceforge.net/format.html#metadata_block_header">metadata block header</a>,
  86921. * i.e. the length of the metadata body that follows the header.
  86922. */
  86923. FLAC_API unsigned FLAC__metadata_simple_iterator_get_block_length(const FLAC__Metadata_SimpleIterator *iterator);
  86924. /** Get the application ID of the \c APPLICATION block at the current
  86925. * position. This avoids reading the actual block data which can save
  86926. * time for large blocks.
  86927. *
  86928. * \param iterator A pointer to an existing initialized iterator.
  86929. * \param id A pointer to a buffer of at least \c 4 bytes where
  86930. * the ID will be stored.
  86931. * \assert
  86932. * \code iterator != NULL \endcode
  86933. * \code id != NULL \endcode
  86934. * \a iterator has been successfully initialized with
  86935. * FLAC__metadata_simple_iterator_init()
  86936. * \retval FLAC__bool
  86937. * \c true if the ID was successfully read, else \c false, in which
  86938. * case you should check FLAC__metadata_simple_iterator_status() to
  86939. * find out why. If the status is
  86940. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT, then the
  86941. * current metadata block is not an \c APPLICATION block. Otherwise
  86942. * if the status is
  86943. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR or
  86944. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR, an I/O error
  86945. * occurred and the iterator can no longer be used.
  86946. */
  86947. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_get_application_id(FLAC__Metadata_SimpleIterator *iterator, FLAC__byte *id);
  86948. /** Get the metadata block at the current position. You can modify the
  86949. * block but must use FLAC__metadata_simple_iterator_set_block() to
  86950. * write it back to the FLAC file.
  86951. *
  86952. * You must call FLAC__metadata_object_delete() on the returned object
  86953. * when you are finished with it.
  86954. *
  86955. * \param iterator A pointer to an existing initialized iterator.
  86956. * \assert
  86957. * \code iterator != NULL \endcode
  86958. * \a iterator has been successfully initialized with
  86959. * FLAC__metadata_simple_iterator_init()
  86960. * \retval FLAC__StreamMetadata*
  86961. * The current metadata block, or \c NULL if there was a memory
  86962. * allocation error.
  86963. */
  86964. FLAC_API FLAC__StreamMetadata *FLAC__metadata_simple_iterator_get_block(FLAC__Metadata_SimpleIterator *iterator);
  86965. /** Write a block back to the FLAC file. This function tries to be
  86966. * as efficient as possible; how the block is actually written is
  86967. * shown by the following:
  86968. *
  86969. * Existing block is a STREAMINFO block and the new block is a
  86970. * STREAMINFO block: the new block is written in place. Make sure
  86971. * you know what you're doing when changing the values of a
  86972. * STREAMINFO block.
  86973. *
  86974. * Existing block is a STREAMINFO block and the new block is a
  86975. * not a STREAMINFO block: this is an error since the first block
  86976. * must be a STREAMINFO block. Returns \c false without altering the
  86977. * file.
  86978. *
  86979. * Existing block is not a STREAMINFO block and the new block is a
  86980. * STREAMINFO block: this is an error since there may be only one
  86981. * STREAMINFO block. Returns \c false without altering the file.
  86982. *
  86983. * Existing block and new block are the same length: the existing
  86984. * block will be replaced by the new block, written in place.
  86985. *
  86986. * Existing block is longer than new block: if use_padding is \c true,
  86987. * the existing block will be overwritten in place with the new
  86988. * block followed by a PADDING block, if possible, to make the total
  86989. * size the same as the existing block. Remember that a padding
  86990. * block requires at least four bytes so if the difference in size
  86991. * between the new block and existing block is less than that, the
  86992. * entire file will have to be rewritten, using the new block's
  86993. * exact size. If use_padding is \c false, the entire file will be
  86994. * rewritten, replacing the existing block by the new block.
  86995. *
  86996. * Existing block is shorter than new block: if use_padding is \c true,
  86997. * the function will try and expand the new block into the following
  86998. * PADDING block, if it exists and doing so won't shrink the PADDING
  86999. * block to less than 4 bytes. If there is no following PADDING
  87000. * block, or it will shrink to less than 4 bytes, or use_padding is
  87001. * \c false, the entire file is rewritten, replacing the existing block
  87002. * with the new block. Note that in this case any following PADDING
  87003. * block is preserved as is.
  87004. *
  87005. * After writing the block, the iterator will remain in the same
  87006. * place, i.e. pointing to the new block.
  87007. *
  87008. * \param iterator A pointer to an existing initialized iterator.
  87009. * \param block The block to set.
  87010. * \param use_padding See above.
  87011. * \assert
  87012. * \code iterator != NULL \endcode
  87013. * \a iterator has been successfully initialized with
  87014. * FLAC__metadata_simple_iterator_init()
  87015. * \code block != NULL \endcode
  87016. * \retval FLAC__bool
  87017. * \c true if successful, else \c false.
  87018. */
  87019. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_set_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  87020. /** This is similar to FLAC__metadata_simple_iterator_set_block()
  87021. * except that instead of writing over an existing block, it appends
  87022. * a block after the existing block. \a use_padding is again used to
  87023. * tell the function to try an expand into following padding in an
  87024. * attempt to avoid rewriting the entire file.
  87025. *
  87026. * This function will fail and return \c false if given a STREAMINFO
  87027. * block.
  87028. *
  87029. * After writing the block, the iterator will be pointing to the
  87030. * new block.
  87031. *
  87032. * \param iterator A pointer to an existing initialized iterator.
  87033. * \param block The block to set.
  87034. * \param use_padding See above.
  87035. * \assert
  87036. * \code iterator != NULL \endcode
  87037. * \a iterator has been successfully initialized with
  87038. * FLAC__metadata_simple_iterator_init()
  87039. * \code block != NULL \endcode
  87040. * \retval FLAC__bool
  87041. * \c true if successful, else \c false.
  87042. */
  87043. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_insert_block_after(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  87044. /** Deletes the block at the current position. This will cause the
  87045. * entire FLAC file to be rewritten, unless \a use_padding is \c true,
  87046. * in which case the block will be replaced by an equal-sized PADDING
  87047. * block. The iterator will be left pointing to the block before the
  87048. * one just deleted.
  87049. *
  87050. * You may not delete the STREAMINFO block.
  87051. *
  87052. * \param iterator A pointer to an existing initialized iterator.
  87053. * \param use_padding See above.
  87054. * \assert
  87055. * \code iterator != NULL \endcode
  87056. * \a iterator has been successfully initialized with
  87057. * FLAC__metadata_simple_iterator_init()
  87058. * \retval FLAC__bool
  87059. * \c true if successful, else \c false.
  87060. */
  87061. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_delete_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool use_padding);
  87062. /* \} */
  87063. /** \defgroup flac_metadata_level2 FLAC/metadata.h: metadata level 2 interface
  87064. * \ingroup flac_metadata
  87065. *
  87066. * \brief
  87067. * The level 2 interface provides read-write access to FLAC file metadata;
  87068. * all metadata is read into memory, operated on in memory, and then written
  87069. * to file, which is more efficient than level 1 when editing multiple blocks.
  87070. *
  87071. * Currently Ogg FLAC is supported for read only, via
  87072. * FLAC__metadata_chain_read_ogg() but a subsequent
  87073. * FLAC__metadata_chain_write() will fail.
  87074. *
  87075. * The general usage of this interface is:
  87076. *
  87077. * - Create a new chain using FLAC__metadata_chain_new(). A chain is a
  87078. * linked list of FLAC metadata blocks.
  87079. * - Read all metadata into the the chain from a FLAC file using
  87080. * FLAC__metadata_chain_read() or FLAC__metadata_chain_read_ogg() and
  87081. * check the status.
  87082. * - Optionally, consolidate the padding using
  87083. * FLAC__metadata_chain_merge_padding() or
  87084. * FLAC__metadata_chain_sort_padding().
  87085. * - Create a new iterator using FLAC__metadata_iterator_new()
  87086. * - Initialize the iterator to point to the first element in the chain
  87087. * using FLAC__metadata_iterator_init()
  87088. * - Traverse the chain using FLAC__metadata_iterator_next and
  87089. * FLAC__metadata_iterator_prev().
  87090. * - Get a block for reading or modification using
  87091. * FLAC__metadata_iterator_get_block(). The pointer to the object
  87092. * inside the chain is returned, so the block is yours to modify.
  87093. * Changes will be reflected in the FLAC file when you write the
  87094. * chain. You can also add and delete blocks (see functions below).
  87095. * - When done, write out the chain using FLAC__metadata_chain_write().
  87096. * Make sure to read the whole comment to the function below.
  87097. * - Delete the chain using FLAC__metadata_chain_delete().
  87098. *
  87099. * \note
  87100. * Even though the FLAC file is not open while the chain is being
  87101. * manipulated, you must not alter the file externally during
  87102. * this time. The chain assumes the FLAC file will not change
  87103. * between the time of FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg()
  87104. * and FLAC__metadata_chain_write().
  87105. *
  87106. * \note
  87107. * Do not modify the is_last, length, or type fields of returned
  87108. * FLAC__StreamMetadata objects. These are managed automatically.
  87109. *
  87110. * \note
  87111. * The metadata objects returned by FLAC__metadata_iterator_get_block()
  87112. * are owned by the chain; do not FLAC__metadata_object_delete() them.
  87113. * In the same way, blocks passed to FLAC__metadata_iterator_set_block()
  87114. * become owned by the chain and they will be deleted when the chain is
  87115. * deleted.
  87116. *
  87117. * \{
  87118. */
  87119. struct FLAC__Metadata_Chain;
  87120. /** The opaque structure definition for the level 2 chain type.
  87121. */
  87122. typedef struct FLAC__Metadata_Chain FLAC__Metadata_Chain;
  87123. struct FLAC__Metadata_Iterator;
  87124. /** The opaque structure definition for the level 2 iterator type.
  87125. */
  87126. typedef struct FLAC__Metadata_Iterator FLAC__Metadata_Iterator;
  87127. typedef enum {
  87128. FLAC__METADATA_CHAIN_STATUS_OK = 0,
  87129. /**< The chain is in the normal OK state */
  87130. FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT,
  87131. /**< The data passed into a function violated the function's usage criteria */
  87132. FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE,
  87133. /**< The chain could not open the target file */
  87134. FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE,
  87135. /**< The chain could not find the FLAC signature at the start of the file */
  87136. FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE,
  87137. /**< The chain tried to write to a file that was not writable */
  87138. FLAC__METADATA_CHAIN_STATUS_BAD_METADATA,
  87139. /**< The chain encountered input that does not conform to the FLAC metadata specification */
  87140. FLAC__METADATA_CHAIN_STATUS_READ_ERROR,
  87141. /**< The chain encountered an error while reading the FLAC file */
  87142. FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR,
  87143. /**< The chain encountered an error while seeking in the FLAC file */
  87144. FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR,
  87145. /**< The chain encountered an error while writing the FLAC file */
  87146. FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR,
  87147. /**< The chain encountered an error renaming the FLAC file */
  87148. FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR,
  87149. /**< The chain encountered an error removing the temporary file */
  87150. FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR,
  87151. /**< Memory allocation failed */
  87152. FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR,
  87153. /**< The caller violated an assertion or an unexpected error occurred */
  87154. FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS,
  87155. /**< One or more of the required callbacks was NULL */
  87156. FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH,
  87157. /**< FLAC__metadata_chain_write() was called on a chain read by
  87158. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  87159. * or
  87160. * FLAC__metadata_chain_write_with_callbacks()/FLAC__metadata_chain_write_with_callbacks_and_tempfile()
  87161. * was called on a chain read by
  87162. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  87163. * Matching read/write methods must always be used. */
  87164. FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL
  87165. /**< FLAC__metadata_chain_write_with_callbacks() was called when the
  87166. * chain write requires a tempfile; use
  87167. * FLAC__metadata_chain_write_with_callbacks_and_tempfile() instead.
  87168. * Or, FLAC__metadata_chain_write_with_callbacks_and_tempfile() was
  87169. * called when the chain write does not require a tempfile; use
  87170. * FLAC__metadata_chain_write_with_callbacks() instead.
  87171. * Always check FLAC__metadata_chain_check_if_tempfile_needed()
  87172. * before writing via callbacks. */
  87173. } FLAC__Metadata_ChainStatus;
  87174. /** Maps a FLAC__Metadata_ChainStatus to a C string.
  87175. *
  87176. * Using a FLAC__Metadata_ChainStatus as the index to this array
  87177. * will give the string equivalent. The contents should not be modified.
  87178. */
  87179. extern FLAC_API const char * const FLAC__Metadata_ChainStatusString[];
  87180. /*********** FLAC__Metadata_Chain ***********/
  87181. /** Create a new chain instance.
  87182. *
  87183. * \retval FLAC__Metadata_Chain*
  87184. * \c NULL if there was an error allocating memory, else the new instance.
  87185. */
  87186. FLAC_API FLAC__Metadata_Chain *FLAC__metadata_chain_new(void);
  87187. /** Free a chain instance. Deletes the object pointed to by \a chain.
  87188. *
  87189. * \param chain A pointer to an existing chain.
  87190. * \assert
  87191. * \code chain != NULL \endcode
  87192. */
  87193. FLAC_API void FLAC__metadata_chain_delete(FLAC__Metadata_Chain *chain);
  87194. /** Get the current status of the chain. Call this after a function
  87195. * returns \c false to get the reason for the error. Also resets the
  87196. * status to FLAC__METADATA_CHAIN_STATUS_OK.
  87197. *
  87198. * \param chain A pointer to an existing chain.
  87199. * \assert
  87200. * \code chain != NULL \endcode
  87201. * \retval FLAC__Metadata_ChainStatus
  87202. * The current status of the chain.
  87203. */
  87204. FLAC_API FLAC__Metadata_ChainStatus FLAC__metadata_chain_status(FLAC__Metadata_Chain *chain);
  87205. /** Read all metadata from a FLAC file into the chain.
  87206. *
  87207. * \param chain A pointer to an existing chain.
  87208. * \param filename The path to the FLAC file to read.
  87209. * \assert
  87210. * \code chain != NULL \endcode
  87211. * \code filename != NULL \endcode
  87212. * \retval FLAC__bool
  87213. * \c true if a valid list of metadata blocks was read from
  87214. * \a filename, else \c false. On failure, check the status with
  87215. * FLAC__metadata_chain_status().
  87216. */
  87217. FLAC_API FLAC__bool FLAC__metadata_chain_read(FLAC__Metadata_Chain *chain, const char *filename);
  87218. /** Read all metadata from an Ogg FLAC file into the chain.
  87219. *
  87220. * \note Ogg FLAC metadata data writing is not supported yet and
  87221. * FLAC__metadata_chain_write() will fail.
  87222. *
  87223. * \param chain A pointer to an existing chain.
  87224. * \param filename The path to the Ogg FLAC file to read.
  87225. * \assert
  87226. * \code chain != NULL \endcode
  87227. * \code filename != NULL \endcode
  87228. * \retval FLAC__bool
  87229. * \c true if a valid list of metadata blocks was read from
  87230. * \a filename, else \c false. On failure, check the status with
  87231. * FLAC__metadata_chain_status().
  87232. */
  87233. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg(FLAC__Metadata_Chain *chain, const char *filename);
  87234. /** Read all metadata from a FLAC stream into the chain via I/O callbacks.
  87235. *
  87236. * The \a handle need only be open for reading, but must be seekable.
  87237. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  87238. * for Windows).
  87239. *
  87240. * \param chain A pointer to an existing chain.
  87241. * \param handle The I/O handle of the FLAC stream to read. The
  87242. * handle will NOT be closed after the metadata is read;
  87243. * that is the duty of the caller.
  87244. * \param callbacks
  87245. * A set of callbacks to use for I/O. The mandatory
  87246. * callbacks are \a read, \a seek, and \a tell.
  87247. * \assert
  87248. * \code chain != NULL \endcode
  87249. * \retval FLAC__bool
  87250. * \c true if a valid list of metadata blocks was read from
  87251. * \a handle, else \c false. On failure, check the status with
  87252. * FLAC__metadata_chain_status().
  87253. */
  87254. FLAC_API FLAC__bool FLAC__metadata_chain_read_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  87255. /** Read all metadata from an Ogg FLAC stream into the chain via I/O callbacks.
  87256. *
  87257. * The \a handle need only be open for reading, but must be seekable.
  87258. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  87259. * for Windows).
  87260. *
  87261. * \note Ogg FLAC metadata data writing is not supported yet and
  87262. * FLAC__metadata_chain_write() will fail.
  87263. *
  87264. * \param chain A pointer to an existing chain.
  87265. * \param handle The I/O handle of the Ogg FLAC stream to read. The
  87266. * handle will NOT be closed after the metadata is read;
  87267. * that is the duty of the caller.
  87268. * \param callbacks
  87269. * A set of callbacks to use for I/O. The mandatory
  87270. * callbacks are \a read, \a seek, and \a tell.
  87271. * \assert
  87272. * \code chain != NULL \endcode
  87273. * \retval FLAC__bool
  87274. * \c true if a valid list of metadata blocks was read from
  87275. * \a handle, else \c false. On failure, check the status with
  87276. * FLAC__metadata_chain_status().
  87277. */
  87278. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  87279. /** Checks if writing the given chain would require the use of a
  87280. * temporary file, or if it could be written in place.
  87281. *
  87282. * Under certain conditions, padding can be utilized so that writing
  87283. * edited metadata back to the FLAC file does not require rewriting the
  87284. * entire file. If rewriting is required, then a temporary workfile is
  87285. * required. When writing metadata using callbacks, you must check
  87286. * this function to know whether to call
  87287. * FLAC__metadata_chain_write_with_callbacks() or
  87288. * FLAC__metadata_chain_write_with_callbacks_and_tempfile(). When
  87289. * writing with FLAC__metadata_chain_write(), the temporary file is
  87290. * handled internally.
  87291. *
  87292. * \param chain A pointer to an existing chain.
  87293. * \param use_padding
  87294. * Whether or not padding will be allowed to be used
  87295. * during the write. The value of \a use_padding given
  87296. * here must match the value later passed to
  87297. * FLAC__metadata_chain_write_with_callbacks() or
  87298. * FLAC__metadata_chain_write_with_callbacks_with_tempfile().
  87299. * \assert
  87300. * \code chain != NULL \endcode
  87301. * \retval FLAC__bool
  87302. * \c true if writing the current chain would require a tempfile, or
  87303. * \c false if metadata can be written in place.
  87304. */
  87305. FLAC_API FLAC__bool FLAC__metadata_chain_check_if_tempfile_needed(FLAC__Metadata_Chain *chain, FLAC__bool use_padding);
  87306. /** Write all metadata out to the FLAC file. This function tries to be as
  87307. * efficient as possible; how the metadata is actually written is shown by
  87308. * the following:
  87309. *
  87310. * If the current chain is the same size as the existing metadata, the new
  87311. * data is written in place.
  87312. *
  87313. * If the current chain is longer than the existing metadata, and
  87314. * \a use_padding is \c true, and the last block is a PADDING block of
  87315. * sufficient length, the function will truncate the final padding block
  87316. * so that the overall size of the metadata is the same as the existing
  87317. * metadata, and then just rewrite the metadata. Otherwise, if not all of
  87318. * the above conditions are met, the entire FLAC file must be rewritten.
  87319. * If you want to use padding this way it is a good idea to call
  87320. * FLAC__metadata_chain_sort_padding() first so that you have the maximum
  87321. * amount of padding to work with, unless you need to preserve ordering
  87322. * of the PADDING blocks for some reason.
  87323. *
  87324. * If the current chain is shorter than the existing metadata, and
  87325. * \a use_padding is \c true, and the final block is a PADDING block, the padding
  87326. * is extended to make the overall size the same as the existing data. If
  87327. * \a use_padding is \c true and the last block is not a PADDING block, a new
  87328. * PADDING block is added to the end of the new data to make it the same
  87329. * size as the existing data (if possible, see the note to
  87330. * FLAC__metadata_simple_iterator_set_block() about the four byte limit)
  87331. * and the new data is written in place. If none of the above apply or
  87332. * \a use_padding is \c false, the entire FLAC file is rewritten.
  87333. *
  87334. * If \a preserve_file_stats is \c true, the owner and modification time will
  87335. * be preserved even if the FLAC file is written.
  87336. *
  87337. * For this write function to be used, the chain must have been read with
  87338. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg(), not
  87339. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks().
  87340. *
  87341. * \param chain A pointer to an existing chain.
  87342. * \param use_padding See above.
  87343. * \param preserve_file_stats See above.
  87344. * \assert
  87345. * \code chain != NULL \endcode
  87346. * \retval FLAC__bool
  87347. * \c true if the write succeeded, else \c false. On failure,
  87348. * check the status with FLAC__metadata_chain_status().
  87349. */
  87350. FLAC_API FLAC__bool FLAC__metadata_chain_write(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__bool preserve_file_stats);
  87351. /** Write all metadata out to a FLAC stream via callbacks.
  87352. *
  87353. * (See FLAC__metadata_chain_write() for the details on how padding is
  87354. * used to write metadata in place if possible.)
  87355. *
  87356. * The \a handle must be open for updating and be seekable. The
  87357. * equivalent minimum stdio fopen() file mode is \c "r+" (or \c "r+b"
  87358. * for Windows).
  87359. *
  87360. * For this write function to be used, the chain must have been read with
  87361. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  87362. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  87363. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  87364. * \c false.
  87365. *
  87366. * \param chain A pointer to an existing chain.
  87367. * \param use_padding See FLAC__metadata_chain_write()
  87368. * \param handle The I/O handle of the FLAC stream to write. The
  87369. * handle will NOT be closed after the metadata is
  87370. * written; that is the duty of the caller.
  87371. * \param callbacks A set of callbacks to use for I/O. The mandatory
  87372. * callbacks are \a write and \a seek.
  87373. * \assert
  87374. * \code chain != NULL \endcode
  87375. * \retval FLAC__bool
  87376. * \c true if the write succeeded, else \c false. On failure,
  87377. * check the status with FLAC__metadata_chain_status().
  87378. */
  87379. FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  87380. /** Write all metadata out to a FLAC stream via callbacks.
  87381. *
  87382. * (See FLAC__metadata_chain_write() for the details on how padding is
  87383. * used to write metadata in place if possible.)
  87384. *
  87385. * This version of the write-with-callbacks function must be used when
  87386. * FLAC__metadata_chain_check_if_tempfile_needed() returns true. In
  87387. * this function, you must supply an I/O handle corresponding to the
  87388. * FLAC file to edit, and a temporary handle to which the new FLAC
  87389. * file will be written. It is the caller's job to move this temporary
  87390. * FLAC file on top of the original FLAC file to complete the metadata
  87391. * edit.
  87392. *
  87393. * The \a handle must be open for reading and be seekable. The
  87394. * equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  87395. * for Windows).
  87396. *
  87397. * The \a temp_handle must be open for writing. The
  87398. * equivalent minimum stdio fopen() file mode is \c "w" (or \c "wb"
  87399. * for Windows). It should be an empty stream, or at least positioned
  87400. * at the start-of-file (in which case it is the caller's duty to
  87401. * truncate it on return).
  87402. *
  87403. * For this write function to be used, the chain must have been read with
  87404. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  87405. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  87406. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  87407. * \c true.
  87408. *
  87409. * \param chain A pointer to an existing chain.
  87410. * \param use_padding See FLAC__metadata_chain_write()
  87411. * \param handle The I/O handle of the original FLAC stream to read.
  87412. * The handle will NOT be closed after the metadata is
  87413. * written; that is the duty of the caller.
  87414. * \param callbacks A set of callbacks to use for I/O on \a handle.
  87415. * The mandatory callbacks are \a read, \a seek, and
  87416. * \a eof.
  87417. * \param temp_handle The I/O handle of the FLAC stream to write. The
  87418. * handle will NOT be closed after the metadata is
  87419. * written; that is the duty of the caller.
  87420. * \param temp_callbacks
  87421. * A set of callbacks to use for I/O on temp_handle.
  87422. * The only mandatory callback is \a write.
  87423. * \assert
  87424. * \code chain != NULL \endcode
  87425. * \retval FLAC__bool
  87426. * \c true if the write succeeded, else \c false. On failure,
  87427. * check the status with FLAC__metadata_chain_status().
  87428. */
  87429. 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);
  87430. /** Merge adjacent PADDING blocks into a single block.
  87431. *
  87432. * \note This function does not write to the FLAC file, it only
  87433. * modifies the chain.
  87434. *
  87435. * \warning Any iterator on the current chain will become invalid after this
  87436. * call. You should delete the iterator and get a new one.
  87437. *
  87438. * \param chain A pointer to an existing chain.
  87439. * \assert
  87440. * \code chain != NULL \endcode
  87441. */
  87442. FLAC_API void FLAC__metadata_chain_merge_padding(FLAC__Metadata_Chain *chain);
  87443. /** This function will move all PADDING blocks to the end on the metadata,
  87444. * then merge them into a single block.
  87445. *
  87446. * \note This function does not write to the FLAC file, it only
  87447. * modifies the chain.
  87448. *
  87449. * \warning Any iterator on the current chain will become invalid after this
  87450. * call. You should delete the iterator and get a new one.
  87451. *
  87452. * \param chain A pointer to an existing chain.
  87453. * \assert
  87454. * \code chain != NULL \endcode
  87455. */
  87456. FLAC_API void FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain *chain);
  87457. /*********** FLAC__Metadata_Iterator ***********/
  87458. /** Create a new iterator instance.
  87459. *
  87460. * \retval FLAC__Metadata_Iterator*
  87461. * \c NULL if there was an error allocating memory, else the new instance.
  87462. */
  87463. FLAC_API FLAC__Metadata_Iterator *FLAC__metadata_iterator_new(void);
  87464. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  87465. *
  87466. * \param iterator A pointer to an existing iterator.
  87467. * \assert
  87468. * \code iterator != NULL \endcode
  87469. */
  87470. FLAC_API void FLAC__metadata_iterator_delete(FLAC__Metadata_Iterator *iterator);
  87471. /** Initialize the iterator to point to the first metadata block in the
  87472. * given chain.
  87473. *
  87474. * \param iterator A pointer to an existing iterator.
  87475. * \param chain A pointer to an existing and initialized (read) chain.
  87476. * \assert
  87477. * \code iterator != NULL \endcode
  87478. * \code chain != NULL \endcode
  87479. */
  87480. FLAC_API void FLAC__metadata_iterator_init(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Chain *chain);
  87481. /** Moves the iterator forward one metadata block, returning \c false if
  87482. * already at the end.
  87483. *
  87484. * \param iterator A pointer to an existing initialized iterator.
  87485. * \assert
  87486. * \code iterator != NULL \endcode
  87487. * \a iterator has been successfully initialized with
  87488. * FLAC__metadata_iterator_init()
  87489. * \retval FLAC__bool
  87490. * \c false if already at the last metadata block of the chain, else
  87491. * \c true.
  87492. */
  87493. FLAC_API FLAC__bool FLAC__metadata_iterator_next(FLAC__Metadata_Iterator *iterator);
  87494. /** Moves the iterator backward one metadata block, returning \c false if
  87495. * already at the beginning.
  87496. *
  87497. * \param iterator A pointer to an existing initialized iterator.
  87498. * \assert
  87499. * \code iterator != NULL \endcode
  87500. * \a iterator has been successfully initialized with
  87501. * FLAC__metadata_iterator_init()
  87502. * \retval FLAC__bool
  87503. * \c false if already at the first metadata block of the chain, else
  87504. * \c true.
  87505. */
  87506. FLAC_API FLAC__bool FLAC__metadata_iterator_prev(FLAC__Metadata_Iterator *iterator);
  87507. /** Get the type of the metadata block at the current position.
  87508. *
  87509. * \param iterator A pointer to an existing initialized iterator.
  87510. * \assert
  87511. * \code iterator != NULL \endcode
  87512. * \a iterator has been successfully initialized with
  87513. * FLAC__metadata_iterator_init()
  87514. * \retval FLAC__MetadataType
  87515. * The type of the metadata block at the current iterator position.
  87516. */
  87517. FLAC_API FLAC__MetadataType FLAC__metadata_iterator_get_block_type(const FLAC__Metadata_Iterator *iterator);
  87518. /** Get the metadata block at the current position. You can modify
  87519. * the block in place but must write the chain before the changes
  87520. * are reflected to the FLAC file. You do not need to call
  87521. * FLAC__metadata_iterator_set_block() to reflect the changes;
  87522. * the pointer returned by FLAC__metadata_iterator_get_block()
  87523. * points directly into the chain.
  87524. *
  87525. * \warning
  87526. * Do not call FLAC__metadata_object_delete() on the returned object;
  87527. * to delete a block use FLAC__metadata_iterator_delete_block().
  87528. *
  87529. * \param iterator A pointer to an existing initialized iterator.
  87530. * \assert
  87531. * \code iterator != NULL \endcode
  87532. * \a iterator has been successfully initialized with
  87533. * FLAC__metadata_iterator_init()
  87534. * \retval FLAC__StreamMetadata*
  87535. * The current metadata block.
  87536. */
  87537. FLAC_API FLAC__StreamMetadata *FLAC__metadata_iterator_get_block(FLAC__Metadata_Iterator *iterator);
  87538. /** Set the metadata block at the current position, replacing the existing
  87539. * block. The new block passed in becomes owned by the chain and it will be
  87540. * deleted when the chain is deleted.
  87541. *
  87542. * \param iterator A pointer to an existing initialized iterator.
  87543. * \param block A pointer to a metadata block.
  87544. * \assert
  87545. * \code iterator != NULL \endcode
  87546. * \a iterator has been successfully initialized with
  87547. * FLAC__metadata_iterator_init()
  87548. * \code block != NULL \endcode
  87549. * \retval FLAC__bool
  87550. * \c false if the conditions in the above description are not met, or
  87551. * a memory allocation error occurs, otherwise \c true.
  87552. */
  87553. FLAC_API FLAC__bool FLAC__metadata_iterator_set_block(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  87554. /** Removes the current block from the chain. If \a replace_with_padding is
  87555. * \c true, the block will instead be replaced with a padding block of equal
  87556. * size. You can not delete the STREAMINFO block. The iterator will be
  87557. * left pointing to the block before the one just "deleted", even if
  87558. * \a replace_with_padding is \c true.
  87559. *
  87560. * \param iterator A pointer to an existing initialized iterator.
  87561. * \param replace_with_padding See above.
  87562. * \assert
  87563. * \code iterator != NULL \endcode
  87564. * \a iterator has been successfully initialized with
  87565. * FLAC__metadata_iterator_init()
  87566. * \retval FLAC__bool
  87567. * \c false if the conditions in the above description are not met,
  87568. * otherwise \c true.
  87569. */
  87570. FLAC_API FLAC__bool FLAC__metadata_iterator_delete_block(FLAC__Metadata_Iterator *iterator, FLAC__bool replace_with_padding);
  87571. /** Insert a new block before the current block. You cannot insert a block
  87572. * before the first STREAMINFO block. You cannot insert a STREAMINFO block
  87573. * as there can be only one, the one that already exists at the head when you
  87574. * read in a chain. The chain takes ownership of the new block and it will be
  87575. * deleted when the chain is deleted. The iterator will be left pointing to
  87576. * the new block.
  87577. *
  87578. * \param iterator A pointer to an existing initialized iterator.
  87579. * \param block A pointer to a metadata block to insert.
  87580. * \assert
  87581. * \code iterator != NULL \endcode
  87582. * \a iterator has been successfully initialized with
  87583. * FLAC__metadata_iterator_init()
  87584. * \retval FLAC__bool
  87585. * \c false if the conditions in the above description are not met, or
  87586. * a memory allocation error occurs, otherwise \c true.
  87587. */
  87588. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_before(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  87589. /** Insert a new block after the current block. You cannot insert a STREAMINFO
  87590. * block as there can be only one, the one that already exists at the head when
  87591. * you read in a chain. The chain takes ownership of the new block and it will
  87592. * be deleted when the chain is deleted. The iterator will be left pointing to
  87593. * the new block.
  87594. *
  87595. * \param iterator A pointer to an existing initialized iterator.
  87596. * \param block A pointer to a metadata block to insert.
  87597. * \assert
  87598. * \code iterator != NULL \endcode
  87599. * \a iterator has been successfully initialized with
  87600. * FLAC__metadata_iterator_init()
  87601. * \retval FLAC__bool
  87602. * \c false if the conditions in the above description are not met, or
  87603. * a memory allocation error occurs, otherwise \c true.
  87604. */
  87605. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_after(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  87606. /* \} */
  87607. /** \defgroup flac_metadata_object FLAC/metadata.h: metadata object methods
  87608. * \ingroup flac_metadata
  87609. *
  87610. * \brief
  87611. * This module contains methods for manipulating FLAC metadata objects.
  87612. *
  87613. * Since many are variable length we have to be careful about the memory
  87614. * management. We decree that all pointers to data in the object are
  87615. * owned by the object and memory-managed by the object.
  87616. *
  87617. * Use the FLAC__metadata_object_new() and FLAC__metadata_object_delete()
  87618. * functions to create all instances. When using the
  87619. * FLAC__metadata_object_set_*() functions to set pointers to data, set
  87620. * \a copy to \c true to have the function make it's own copy of the data, or
  87621. * to \c false to give the object ownership of your data. In the latter case
  87622. * your pointer must be freeable by free() and will be free()d when the object
  87623. * is FLAC__metadata_object_delete()d. It is legal to pass a null pointer as
  87624. * the data pointer to a FLAC__metadata_object_set_*() function as long as
  87625. * the length argument is 0 and the \a copy argument is \c false.
  87626. *
  87627. * The FLAC__metadata_object_new() and FLAC__metadata_object_clone() function
  87628. * will return \c NULL in the case of a memory allocation error, otherwise a new
  87629. * object. The FLAC__metadata_object_set_*() functions return \c false in the
  87630. * case of a memory allocation error.
  87631. *
  87632. * We don't have the convenience of C++ here, so note that the library relies
  87633. * on you to keep the types straight. In other words, if you pass, for
  87634. * example, a FLAC__StreamMetadata* that represents a STREAMINFO block to
  87635. * FLAC__metadata_object_application_set_data(), you will get an assertion
  87636. * failure.
  87637. *
  87638. * For convenience the FLAC__metadata_object_vorbiscomment_*() functions
  87639. * maintain a trailing NUL on each Vorbis comment entry. This is not counted
  87640. * toward the length or stored in the stream, but it can make working with plain
  87641. * comments (those that don't contain embedded-NULs in the value) easier.
  87642. * Entries passed into these functions have trailing NULs added if missing, and
  87643. * returned entries are guaranteed to have a trailing NUL.
  87644. *
  87645. * The FLAC__metadata_object_vorbiscomment_*() functions that take a Vorbis
  87646. * comment entry/name/value will first validate that it complies with the Vorbis
  87647. * comment specification and return false if it does not.
  87648. *
  87649. * There is no need to recalculate the length field on metadata blocks you
  87650. * have modified. They will be calculated automatically before they are
  87651. * written back to a file.
  87652. *
  87653. * \{
  87654. */
  87655. /** Create a new metadata object instance of the given type.
  87656. *
  87657. * The object will be "empty"; i.e. values and data pointers will be \c 0,
  87658. * with the exception of FLAC__METADATA_TYPE_VORBIS_COMMENT, which will have
  87659. * the vendor string set (but zero comments).
  87660. *
  87661. * Do not pass in a value greater than or equal to
  87662. * \a FLAC__METADATA_TYPE_UNDEFINED unless you really know what you're
  87663. * doing.
  87664. *
  87665. * \param type Type of object to create
  87666. * \retval FLAC__StreamMetadata*
  87667. * \c NULL if there was an error allocating memory or the type code is
  87668. * greater than FLAC__MAX_METADATA_TYPE_CODE, else the new instance.
  87669. */
  87670. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_new(FLAC__MetadataType type);
  87671. /** Create a copy of an existing metadata object.
  87672. *
  87673. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  87674. * object is also copied. The caller takes ownership of the new block and
  87675. * is responsible for freeing it with FLAC__metadata_object_delete().
  87676. *
  87677. * \param object Pointer to object to copy.
  87678. * \assert
  87679. * \code object != NULL \endcode
  87680. * \retval FLAC__StreamMetadata*
  87681. * \c NULL if there was an error allocating memory, else the new instance.
  87682. */
  87683. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_clone(const FLAC__StreamMetadata *object);
  87684. /** Free a metadata object. Deletes the object pointed to by \a object.
  87685. *
  87686. * The delete is a "deep" delete, i.e. dynamically allocated data within the
  87687. * object is also deleted.
  87688. *
  87689. * \param object A pointer to an existing object.
  87690. * \assert
  87691. * \code object != NULL \endcode
  87692. */
  87693. FLAC_API void FLAC__metadata_object_delete(FLAC__StreamMetadata *object);
  87694. /** Compares two metadata objects.
  87695. *
  87696. * The compare is "deep", i.e. dynamically allocated data within the
  87697. * object is also compared.
  87698. *
  87699. * \param block1 A pointer to an existing object.
  87700. * \param block2 A pointer to an existing object.
  87701. * \assert
  87702. * \code block1 != NULL \endcode
  87703. * \code block2 != NULL \endcode
  87704. * \retval FLAC__bool
  87705. * \c true if objects are identical, else \c false.
  87706. */
  87707. FLAC_API FLAC__bool FLAC__metadata_object_is_equal(const FLAC__StreamMetadata *block1, const FLAC__StreamMetadata *block2);
  87708. /** Sets the application data of an APPLICATION block.
  87709. *
  87710. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  87711. * takes ownership of the pointer. The existing data will be freed if this
  87712. * function is successful, otherwise the original data will remain if \a copy
  87713. * is \c true and malloc() fails.
  87714. *
  87715. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  87716. *
  87717. * \param object A pointer to an existing APPLICATION object.
  87718. * \param data A pointer to the data to set.
  87719. * \param length The length of \a data in bytes.
  87720. * \param copy See above.
  87721. * \assert
  87722. * \code object != NULL \endcode
  87723. * \code object->type == FLAC__METADATA_TYPE_APPLICATION \endcode
  87724. * \code (data != NULL && length > 0) ||
  87725. * (data == NULL && length == 0 && copy == false) \endcode
  87726. * \retval FLAC__bool
  87727. * \c false if \a copy is \c true and malloc() fails, else \c true.
  87728. */
  87729. FLAC_API FLAC__bool FLAC__metadata_object_application_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, unsigned length, FLAC__bool copy);
  87730. /** Resize the seekpoint array.
  87731. *
  87732. * If the size shrinks, elements will truncated; if it grows, new placeholder
  87733. * points will be added to the end.
  87734. *
  87735. * \param object A pointer to an existing SEEKTABLE object.
  87736. * \param new_num_points The desired length of the array; may be \c 0.
  87737. * \assert
  87738. * \code object != NULL \endcode
  87739. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  87740. * \code (object->data.seek_table.points == NULL && object->data.seek_table.num_points == 0) ||
  87741. * (object->data.seek_table.points != NULL && object->data.seek_table.num_points > 0) \endcode
  87742. * \retval FLAC__bool
  87743. * \c false if memory allocation error, else \c true.
  87744. */
  87745. FLAC_API FLAC__bool FLAC__metadata_object_seektable_resize_points(FLAC__StreamMetadata *object, unsigned new_num_points);
  87746. /** Set a seekpoint in a seektable.
  87747. *
  87748. * \param object A pointer to an existing SEEKTABLE object.
  87749. * \param point_num Index into seekpoint array to set.
  87750. * \param point The point to set.
  87751. * \assert
  87752. * \code object != NULL \endcode
  87753. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  87754. * \code object->data.seek_table.num_points > point_num \endcode
  87755. */
  87756. FLAC_API void FLAC__metadata_object_seektable_set_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  87757. /** Insert a seekpoint into a seektable.
  87758. *
  87759. * \param object A pointer to an existing SEEKTABLE object.
  87760. * \param point_num Index into seekpoint array to set.
  87761. * \param point The point to set.
  87762. * \assert
  87763. * \code object != NULL \endcode
  87764. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  87765. * \code object->data.seek_table.num_points >= point_num \endcode
  87766. * \retval FLAC__bool
  87767. * \c false if memory allocation error, else \c true.
  87768. */
  87769. FLAC_API FLAC__bool FLAC__metadata_object_seektable_insert_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  87770. /** Delete a seekpoint from a seektable.
  87771. *
  87772. * \param object A pointer to an existing SEEKTABLE object.
  87773. * \param point_num Index into seekpoint array to set.
  87774. * \assert
  87775. * \code object != NULL \endcode
  87776. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  87777. * \code object->data.seek_table.num_points > point_num \endcode
  87778. * \retval FLAC__bool
  87779. * \c false if memory allocation error, else \c true.
  87780. */
  87781. FLAC_API FLAC__bool FLAC__metadata_object_seektable_delete_point(FLAC__StreamMetadata *object, unsigned point_num);
  87782. /** Check a seektable to see if it conforms to the FLAC specification.
  87783. * See the format specification for limits on the contents of the
  87784. * seektable.
  87785. *
  87786. * \param object A pointer to an existing SEEKTABLE object.
  87787. * \assert
  87788. * \code object != NULL \endcode
  87789. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  87790. * \retval FLAC__bool
  87791. * \c false if seek table is illegal, else \c true.
  87792. */
  87793. FLAC_API FLAC__bool FLAC__metadata_object_seektable_is_legal(const FLAC__StreamMetadata *object);
  87794. /** Append a number of placeholder points to the end of a seek table.
  87795. *
  87796. * \note
  87797. * As with the other ..._seektable_template_... functions, you should
  87798. * call FLAC__metadata_object_seektable_template_sort() when finished
  87799. * to make the seek table legal.
  87800. *
  87801. * \param object A pointer to an existing SEEKTABLE object.
  87802. * \param num The number of placeholder points to append.
  87803. * \assert
  87804. * \code object != NULL \endcode
  87805. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  87806. * \retval FLAC__bool
  87807. * \c false if memory allocation fails, else \c true.
  87808. */
  87809. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_placeholders(FLAC__StreamMetadata *object, unsigned num);
  87810. /** Append a specific seek point template to the end of a seek table.
  87811. *
  87812. * \note
  87813. * As with the other ..._seektable_template_... functions, you should
  87814. * call FLAC__metadata_object_seektable_template_sort() when finished
  87815. * to make the seek table legal.
  87816. *
  87817. * \param object A pointer to an existing SEEKTABLE object.
  87818. * \param sample_number The sample number of the seek point template.
  87819. * \assert
  87820. * \code object != NULL \endcode
  87821. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  87822. * \retval FLAC__bool
  87823. * \c false if memory allocation fails, else \c true.
  87824. */
  87825. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_point(FLAC__StreamMetadata *object, FLAC__uint64 sample_number);
  87826. /** Append specific seek point templates to the end of a seek table.
  87827. *
  87828. * \note
  87829. * As with the other ..._seektable_template_... functions, you should
  87830. * call FLAC__metadata_object_seektable_template_sort() when finished
  87831. * to make the seek table legal.
  87832. *
  87833. * \param object A pointer to an existing SEEKTABLE object.
  87834. * \param sample_numbers An array of sample numbers for the seek points.
  87835. * \param num The number of seek point templates to append.
  87836. * \assert
  87837. * \code object != NULL \endcode
  87838. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  87839. * \retval FLAC__bool
  87840. * \c false if memory allocation fails, else \c true.
  87841. */
  87842. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_points(FLAC__StreamMetadata *object, FLAC__uint64 sample_numbers[], unsigned num);
  87843. /** Append a set of evenly-spaced seek point templates to the end of a
  87844. * seek table.
  87845. *
  87846. * \note
  87847. * As with the other ..._seektable_template_... functions, you should
  87848. * call FLAC__metadata_object_seektable_template_sort() when finished
  87849. * to make the seek table legal.
  87850. *
  87851. * \param object A pointer to an existing SEEKTABLE object.
  87852. * \param num The number of placeholder points to append.
  87853. * \param total_samples The total number of samples to be encoded;
  87854. * the seekpoints will be spaced approximately
  87855. * \a total_samples / \a num samples apart.
  87856. * \assert
  87857. * \code object != NULL \endcode
  87858. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  87859. * \code total_samples > 0 \endcode
  87860. * \retval FLAC__bool
  87861. * \c false if memory allocation fails, else \c true.
  87862. */
  87863. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points(FLAC__StreamMetadata *object, unsigned num, FLAC__uint64 total_samples);
  87864. /** Append a set of evenly-spaced seek point templates to the end of a
  87865. * seek table.
  87866. *
  87867. * \note
  87868. * As with the other ..._seektable_template_... functions, you should
  87869. * call FLAC__metadata_object_seektable_template_sort() when finished
  87870. * to make the seek table legal.
  87871. *
  87872. * \param object A pointer to an existing SEEKTABLE object.
  87873. * \param samples The number of samples apart to space the placeholder
  87874. * points. The first point will be at sample \c 0, the
  87875. * second at sample \a samples, then 2*\a samples, and
  87876. * so on. As long as \a samples and \a total_samples
  87877. * are greater than \c 0, there will always be at least
  87878. * one seekpoint at sample \c 0.
  87879. * \param total_samples The total number of samples to be encoded;
  87880. * the seekpoints will be spaced
  87881. * \a samples samples apart.
  87882. * \assert
  87883. * \code object != NULL \endcode
  87884. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  87885. * \code samples > 0 \endcode
  87886. * \code total_samples > 0 \endcode
  87887. * \retval FLAC__bool
  87888. * \c false if memory allocation fails, else \c true.
  87889. */
  87890. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points_by_samples(FLAC__StreamMetadata *object, unsigned samples, FLAC__uint64 total_samples);
  87891. /** Sort a seek table's seek points according to the format specification,
  87892. * removing duplicates.
  87893. *
  87894. * \param object A pointer to a seek table to be sorted.
  87895. * \param compact If \c false, behaves like FLAC__format_seektable_sort().
  87896. * If \c true, duplicates are deleted and the seek table is
  87897. * shrunk appropriately; the number of placeholder points
  87898. * present in the seek table will be the same after the call
  87899. * as before.
  87900. * \assert
  87901. * \code object != NULL \endcode
  87902. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  87903. * \retval FLAC__bool
  87904. * \c false if realloc() fails, else \c true.
  87905. */
  87906. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_sort(FLAC__StreamMetadata *object, FLAC__bool compact);
  87907. /** Sets the vendor string in a VORBIS_COMMENT block.
  87908. *
  87909. * For convenience, a trailing NUL is added to the entry if it doesn't have
  87910. * one already.
  87911. *
  87912. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  87913. * takes ownership of the \c entry.entry pointer.
  87914. *
  87915. * \note If this function returns \c false, the caller still owns the
  87916. * pointer.
  87917. *
  87918. * \param object A pointer to an existing VORBIS_COMMENT object.
  87919. * \param entry The entry to set the vendor string to.
  87920. * \param copy See above.
  87921. * \assert
  87922. * \code object != NULL \endcode
  87923. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  87924. * \code (entry.entry != NULL && entry.length > 0) ||
  87925. * (entry.entry == NULL && entry.length == 0) \endcode
  87926. * \retval FLAC__bool
  87927. * \c false if memory allocation fails or \a entry does not comply with the
  87928. * Vorbis comment specification, else \c true.
  87929. */
  87930. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_vendor_string(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  87931. /** Resize the comment array.
  87932. *
  87933. * If the size shrinks, elements will truncated; if it grows, new empty
  87934. * fields will be added to the end.
  87935. *
  87936. * \param object A pointer to an existing VORBIS_COMMENT object.
  87937. * \param new_num_comments The desired length of the array; may be \c 0.
  87938. * \assert
  87939. * \code object != NULL \endcode
  87940. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  87941. * \code (object->data.vorbis_comment.comments == NULL && object->data.vorbis_comment.num_comments == 0) ||
  87942. * (object->data.vorbis_comment.comments != NULL && object->data.vorbis_comment.num_comments > 0) \endcode
  87943. * \retval FLAC__bool
  87944. * \c false if memory allocation fails, else \c true.
  87945. */
  87946. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_resize_comments(FLAC__StreamMetadata *object, unsigned new_num_comments);
  87947. /** Sets a comment in a VORBIS_COMMENT block.
  87948. *
  87949. * For convenience, a trailing NUL is added to the entry if it doesn't have
  87950. * one already.
  87951. *
  87952. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  87953. * takes ownership of the \c entry.entry pointer.
  87954. *
  87955. * \note If this function returns \c false, the caller still owns the
  87956. * pointer.
  87957. *
  87958. * \param object A pointer to an existing VORBIS_COMMENT object.
  87959. * \param comment_num Index into comment array to set.
  87960. * \param entry The entry to set the comment to.
  87961. * \param copy See above.
  87962. * \assert
  87963. * \code object != NULL \endcode
  87964. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  87965. * \code comment_num < object->data.vorbis_comment.num_comments \endcode
  87966. * \code (entry.entry != NULL && entry.length > 0) ||
  87967. * (entry.entry == NULL && entry.length == 0) \endcode
  87968. * \retval FLAC__bool
  87969. * \c false if memory allocation fails or \a entry does not comply with the
  87970. * Vorbis comment specification, else \c true.
  87971. */
  87972. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  87973. /** Insert a comment in a VORBIS_COMMENT block at the given index.
  87974. *
  87975. * For convenience, a trailing NUL is added to the entry if it doesn't have
  87976. * one already.
  87977. *
  87978. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  87979. * takes ownership of the \c entry.entry pointer.
  87980. *
  87981. * \note If this function returns \c false, the caller still owns the
  87982. * pointer.
  87983. *
  87984. * \param object A pointer to an existing VORBIS_COMMENT object.
  87985. * \param comment_num The index at which to insert the comment. The comments
  87986. * at and after \a comment_num move right one position.
  87987. * To append a comment to the end, set \a comment_num to
  87988. * \c object->data.vorbis_comment.num_comments .
  87989. * \param entry The comment to insert.
  87990. * \param copy See above.
  87991. * \assert
  87992. * \code object != NULL \endcode
  87993. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  87994. * \code object->data.vorbis_comment.num_comments >= comment_num \endcode
  87995. * \code (entry.entry != NULL && entry.length > 0) ||
  87996. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  87997. * \retval FLAC__bool
  87998. * \c false if memory allocation fails or \a entry does not comply with the
  87999. * Vorbis comment specification, else \c true.
  88000. */
  88001. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_insert_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88002. /** Appends a comment to a VORBIS_COMMENT block.
  88003. *
  88004. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88005. * one already.
  88006. *
  88007. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88008. * takes ownership of the \c entry.entry pointer.
  88009. *
  88010. * \note If this function returns \c false, the caller still owns the
  88011. * pointer.
  88012. *
  88013. * \param object A pointer to an existing VORBIS_COMMENT object.
  88014. * \param entry The comment to insert.
  88015. * \param copy See above.
  88016. * \assert
  88017. * \code object != NULL \endcode
  88018. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88019. * \code (entry.entry != NULL && entry.length > 0) ||
  88020. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88021. * \retval FLAC__bool
  88022. * \c false if memory allocation fails or \a entry does not comply with the
  88023. * Vorbis comment specification, else \c true.
  88024. */
  88025. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_append_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88026. /** Replaces comments in a VORBIS_COMMENT block with a new one.
  88027. *
  88028. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88029. * one already.
  88030. *
  88031. * Depending on the the value of \a all, either all or just the first comment
  88032. * whose field name(s) match the given entry's name will be replaced by the
  88033. * given entry. If no comments match, \a entry will simply be appended.
  88034. *
  88035. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88036. * takes ownership of the \c entry.entry pointer.
  88037. *
  88038. * \note If this function returns \c false, the caller still owns the
  88039. * pointer.
  88040. *
  88041. * \param object A pointer to an existing VORBIS_COMMENT object.
  88042. * \param entry The comment to insert.
  88043. * \param all If \c true, all comments whose field name matches
  88044. * \a entry's field name will be removed, and \a entry will
  88045. * be inserted at the position of the first matching
  88046. * comment. If \c false, only the first comment whose
  88047. * field name matches \a entry's field name will be
  88048. * replaced with \a entry.
  88049. * \param copy See above.
  88050. * \assert
  88051. * \code object != NULL \endcode
  88052. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88053. * \code (entry.entry != NULL && entry.length > 0) ||
  88054. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88055. * \retval FLAC__bool
  88056. * \c false if memory allocation fails or \a entry does not comply with the
  88057. * Vorbis comment specification, else \c true.
  88058. */
  88059. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_replace_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool all, FLAC__bool copy);
  88060. /** Delete a comment in a VORBIS_COMMENT block at the given index.
  88061. *
  88062. * \param object A pointer to an existing VORBIS_COMMENT object.
  88063. * \param comment_num The index of the comment to delete.
  88064. * \assert
  88065. * \code object != NULL \endcode
  88066. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88067. * \code object->data.vorbis_comment.num_comments > comment_num \endcode
  88068. * \retval FLAC__bool
  88069. * \c false if realloc() fails, else \c true.
  88070. */
  88071. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_delete_comment(FLAC__StreamMetadata *object, unsigned comment_num);
  88072. /** Creates a Vorbis comment entry from NUL-terminated name and value strings.
  88073. *
  88074. * On return, the filled-in \a entry->entry pointer will point to malloc()ed
  88075. * memory and shall be owned by the caller. For convenience the entry will
  88076. * have a terminating NUL.
  88077. *
  88078. * \param entry A pointer to a Vorbis comment entry. The entry's
  88079. * \c entry pointer should not point to allocated
  88080. * memory as it will be overwritten.
  88081. * \param field_name The field name in ASCII, \c NUL terminated.
  88082. * \param field_value The field value in UTF-8, \c NUL terminated.
  88083. * \assert
  88084. * \code entry != NULL \endcode
  88085. * \code field_name != NULL \endcode
  88086. * \code field_value != NULL \endcode
  88087. * \retval FLAC__bool
  88088. * \c false if malloc() fails, or if \a field_name or \a field_value does
  88089. * not comply with the Vorbis comment specification, else \c true.
  88090. */
  88091. 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);
  88092. /** Splits a Vorbis comment entry into NUL-terminated name and value strings.
  88093. *
  88094. * The returned pointers to name and value will be allocated by malloc()
  88095. * and shall be owned by the caller.
  88096. *
  88097. * \param entry An existing Vorbis comment entry.
  88098. * \param field_name The address of where the returned pointer to the
  88099. * field name will be stored.
  88100. * \param field_value The address of where the returned pointer to the
  88101. * field value will be stored.
  88102. * \assert
  88103. * \code (entry.entry != NULL && entry.length > 0) \endcode
  88104. * \code memchr(entry.entry, '=', entry.length) != NULL \endcode
  88105. * \code field_name != NULL \endcode
  88106. * \code field_value != NULL \endcode
  88107. * \retval FLAC__bool
  88108. * \c false if memory allocation fails or \a entry does not comply with the
  88109. * Vorbis comment specification, else \c true.
  88110. */
  88111. 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);
  88112. /** Check if the given Vorbis comment entry's field name matches the given
  88113. * field name.
  88114. *
  88115. * \param entry An existing Vorbis comment entry.
  88116. * \param field_name The field name to check.
  88117. * \param field_name_length The length of \a field_name, not including the
  88118. * terminating \c NUL.
  88119. * \assert
  88120. * \code (entry.entry != NULL && entry.length > 0) \endcode
  88121. * \retval FLAC__bool
  88122. * \c true if the field names match, else \c false
  88123. */
  88124. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_matches(const FLAC__StreamMetadata_VorbisComment_Entry entry, const char *field_name, unsigned field_name_length);
  88125. /** Find a Vorbis comment with the given field name.
  88126. *
  88127. * The search begins at entry number \a offset; use an offset of 0 to
  88128. * search from the beginning of the comment array.
  88129. *
  88130. * \param object A pointer to an existing VORBIS_COMMENT object.
  88131. * \param offset The offset into the comment array from where to start
  88132. * the search.
  88133. * \param field_name The field name of the comment to find.
  88134. * \assert
  88135. * \code object != NULL \endcode
  88136. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88137. * \code field_name != NULL \endcode
  88138. * \retval int
  88139. * The offset in the comment array of the first comment whose field
  88140. * name matches \a field_name, or \c -1 if no match was found.
  88141. */
  88142. FLAC_API int FLAC__metadata_object_vorbiscomment_find_entry_from(const FLAC__StreamMetadata *object, unsigned offset, const char *field_name);
  88143. /** Remove first Vorbis comment matching the given field name.
  88144. *
  88145. * \param object A pointer to an existing VORBIS_COMMENT object.
  88146. * \param field_name The field name of comment to delete.
  88147. * \assert
  88148. * \code object != NULL \endcode
  88149. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88150. * \retval int
  88151. * \c -1 for memory allocation error, \c 0 for no matching entries,
  88152. * \c 1 for one matching entry deleted.
  88153. */
  88154. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entry_matching(FLAC__StreamMetadata *object, const char *field_name);
  88155. /** Remove all Vorbis comments matching the given field name.
  88156. *
  88157. * \param object A pointer to an existing VORBIS_COMMENT object.
  88158. * \param field_name The field name of comments to delete.
  88159. * \assert
  88160. * \code object != NULL \endcode
  88161. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88162. * \retval int
  88163. * \c -1 for memory allocation error, \c 0 for no matching entries,
  88164. * else the number of matching entries deleted.
  88165. */
  88166. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entries_matching(FLAC__StreamMetadata *object, const char *field_name);
  88167. /** Create a new CUESHEET track instance.
  88168. *
  88169. * The object will be "empty"; i.e. values and data pointers will be \c 0.
  88170. *
  88171. * \retval FLAC__StreamMetadata_CueSheet_Track*
  88172. * \c NULL if there was an error allocating memory, else the new instance.
  88173. */
  88174. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_new(void);
  88175. /** Create a copy of an existing CUESHEET track object.
  88176. *
  88177. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  88178. * object is also copied. The caller takes ownership of the new object and
  88179. * is responsible for freeing it with
  88180. * FLAC__metadata_object_cuesheet_track_delete().
  88181. *
  88182. * \param object Pointer to object to copy.
  88183. * \assert
  88184. * \code object != NULL \endcode
  88185. * \retval FLAC__StreamMetadata_CueSheet_Track*
  88186. * \c NULL if there was an error allocating memory, else the new instance.
  88187. */
  88188. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_clone(const FLAC__StreamMetadata_CueSheet_Track *object);
  88189. /** Delete a CUESHEET track object
  88190. *
  88191. * \param object A pointer to an existing CUESHEET track object.
  88192. * \assert
  88193. * \code object != NULL \endcode
  88194. */
  88195. FLAC_API void FLAC__metadata_object_cuesheet_track_delete(FLAC__StreamMetadata_CueSheet_Track *object);
  88196. /** Resize a track's index point array.
  88197. *
  88198. * If the size shrinks, elements will truncated; if it grows, new blank
  88199. * indices will be added to the end.
  88200. *
  88201. * \param object A pointer to an existing CUESHEET object.
  88202. * \param track_num The index of the track to modify. NOTE: this is not
  88203. * necessarily the same as the track's \a number field.
  88204. * \param new_num_indices The desired length of the array; may be \c 0.
  88205. * \assert
  88206. * \code object != NULL \endcode
  88207. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88208. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88209. * \code (object->data.cue_sheet.tracks[track_num].indices == NULL && object->data.cue_sheet.tracks[track_num].num_indices == 0) ||
  88210. * (object->data.cue_sheet.tracks[track_num].indices != NULL && object->data.cue_sheet.tracks[track_num].num_indices > 0) \endcode
  88211. * \retval FLAC__bool
  88212. * \c false if memory allocation error, else \c true.
  88213. */
  88214. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_resize_indices(FLAC__StreamMetadata *object, unsigned track_num, unsigned new_num_indices);
  88215. /** Insert an index point in a CUESHEET track at the given index.
  88216. *
  88217. * \param object A pointer to an existing CUESHEET object.
  88218. * \param track_num The index of the track to modify. NOTE: this is not
  88219. * necessarily the same as the track's \a number field.
  88220. * \param index_num The index into the track's index array at which to
  88221. * insert the index point. NOTE: this is not necessarily
  88222. * the same as the index point's \a number field. The
  88223. * indices at and after \a index_num move right one
  88224. * position. To append an index point to the end, set
  88225. * \a index_num to
  88226. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  88227. * \param index The index point to insert.
  88228. * \assert
  88229. * \code object != NULL \endcode
  88230. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88231. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88232. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  88233. * \retval FLAC__bool
  88234. * \c false if realloc() fails, else \c true.
  88235. */
  88236. 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);
  88237. /** Insert a blank index point in a CUESHEET track at the given index.
  88238. *
  88239. * A blank index point is one in which all field values are zero.
  88240. *
  88241. * \param object A pointer to an existing CUESHEET object.
  88242. * \param track_num The index of the track to modify. NOTE: this is not
  88243. * necessarily the same as the track's \a number field.
  88244. * \param index_num The index into the track's index array at which to
  88245. * insert the index point. NOTE: this is not necessarily
  88246. * the same as the index point's \a number field. The
  88247. * indices at and after \a index_num move right one
  88248. * position. To append an index point to the end, set
  88249. * \a index_num to
  88250. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  88251. * \assert
  88252. * \code object != NULL \endcode
  88253. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88254. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88255. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  88256. * \retval FLAC__bool
  88257. * \c false if realloc() fails, else \c true.
  88258. */
  88259. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_blank_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  88260. /** Delete an index point in a CUESHEET track at the given index.
  88261. *
  88262. * \param object A pointer to an existing CUESHEET object.
  88263. * \param track_num The index into the track array of the track to
  88264. * modify. NOTE: this is not necessarily the same
  88265. * as the track's \a number field.
  88266. * \param index_num The index into the track's index array of the index
  88267. * to delete. NOTE: this is not necessarily the same
  88268. * as the index's \a number field.
  88269. * \assert
  88270. * \code object != NULL \endcode
  88271. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88272. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88273. * \code object->data.cue_sheet.tracks[track_num].num_indices > index_num \endcode
  88274. * \retval FLAC__bool
  88275. * \c false if realloc() fails, else \c true.
  88276. */
  88277. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_delete_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  88278. /** Resize the track array.
  88279. *
  88280. * If the size shrinks, elements will truncated; if it grows, new blank
  88281. * tracks will be added to the end.
  88282. *
  88283. * \param object A pointer to an existing CUESHEET object.
  88284. * \param new_num_tracks The desired length of the array; may be \c 0.
  88285. * \assert
  88286. * \code object != NULL \endcode
  88287. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88288. * \code (object->data.cue_sheet.tracks == NULL && object->data.cue_sheet.num_tracks == 0) ||
  88289. * (object->data.cue_sheet.tracks != NULL && object->data.cue_sheet.num_tracks > 0) \endcode
  88290. * \retval FLAC__bool
  88291. * \c false if memory allocation error, else \c true.
  88292. */
  88293. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_resize_tracks(FLAC__StreamMetadata *object, unsigned new_num_tracks);
  88294. /** Sets a track in a CUESHEET block.
  88295. *
  88296. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  88297. * takes ownership of the \a track pointer.
  88298. *
  88299. * \param object A pointer to an existing CUESHEET object.
  88300. * \param track_num Index into track array to set. NOTE: this is not
  88301. * necessarily the same as the track's \a number field.
  88302. * \param track The track to set the track to. You may safely pass in
  88303. * a const pointer if \a copy is \c true.
  88304. * \param copy See above.
  88305. * \assert
  88306. * \code object != NULL \endcode
  88307. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88308. * \code track_num < object->data.cue_sheet.num_tracks \endcode
  88309. * \code (track->indices != NULL && track->num_indices > 0) ||
  88310. * (track->indices == NULL && track->num_indices == 0)
  88311. * \retval FLAC__bool
  88312. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88313. */
  88314. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_set_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  88315. /** Insert a track in a CUESHEET block at the given index.
  88316. *
  88317. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  88318. * takes ownership of the \a track pointer.
  88319. *
  88320. * \param object A pointer to an existing CUESHEET object.
  88321. * \param track_num The index at which to insert the track. NOTE: this
  88322. * is not necessarily the same as the track's \a number
  88323. * field. The tracks at and after \a track_num move right
  88324. * one position. To append a track to the end, set
  88325. * \a track_num to \c object->data.cue_sheet.num_tracks .
  88326. * \param track The track to insert. You may safely pass in a const
  88327. * pointer if \a copy is \c true.
  88328. * \param copy See above.
  88329. * \assert
  88330. * \code object != NULL \endcode
  88331. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88332. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  88333. * \retval FLAC__bool
  88334. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88335. */
  88336. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  88337. /** Insert a blank track in a CUESHEET block at the given index.
  88338. *
  88339. * A blank track is one in which all field values are zero.
  88340. *
  88341. * \param object A pointer to an existing CUESHEET object.
  88342. * \param track_num The index at which to insert the track. NOTE: this
  88343. * is not necessarily the same as the track's \a number
  88344. * field. The tracks at and after \a track_num move right
  88345. * one position. To append a track to the end, set
  88346. * \a track_num to \c object->data.cue_sheet.num_tracks .
  88347. * \assert
  88348. * \code object != NULL \endcode
  88349. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88350. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  88351. * \retval FLAC__bool
  88352. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88353. */
  88354. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_blank_track(FLAC__StreamMetadata *object, unsigned track_num);
  88355. /** Delete a track in a CUESHEET block at the given index.
  88356. *
  88357. * \param object A pointer to an existing CUESHEET object.
  88358. * \param track_num The index into the track array of the track to
  88359. * delete. NOTE: this is not necessarily the same
  88360. * as the track's \a number field.
  88361. * \assert
  88362. * \code object != NULL \endcode
  88363. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88364. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88365. * \retval FLAC__bool
  88366. * \c false if realloc() fails, else \c true.
  88367. */
  88368. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_delete_track(FLAC__StreamMetadata *object, unsigned track_num);
  88369. /** Check a cue sheet to see if it conforms to the FLAC specification.
  88370. * See the format specification for limits on the contents of the
  88371. * cue sheet.
  88372. *
  88373. * \param object A pointer to an existing CUESHEET object.
  88374. * \param check_cd_da_subset If \c true, check CUESHEET against more
  88375. * stringent requirements for a CD-DA (audio) disc.
  88376. * \param violation Address of a pointer to a string. If there is a
  88377. * violation, a pointer to a string explanation of the
  88378. * violation will be returned here. \a violation may be
  88379. * \c NULL if you don't need the returned string. Do not
  88380. * free the returned string; it will always point to static
  88381. * data.
  88382. * \assert
  88383. * \code object != NULL \endcode
  88384. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88385. * \retval FLAC__bool
  88386. * \c false if cue sheet is illegal, else \c true.
  88387. */
  88388. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_is_legal(const FLAC__StreamMetadata *object, FLAC__bool check_cd_da_subset, const char **violation);
  88389. /** Calculate and return the CDDB/freedb ID for a cue sheet. The function
  88390. * assumes the cue sheet corresponds to a CD; the result is undefined
  88391. * if the cuesheet's is_cd bit is not set.
  88392. *
  88393. * \param object A pointer to an existing CUESHEET object.
  88394. * \assert
  88395. * \code object != NULL \endcode
  88396. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88397. * \retval FLAC__uint32
  88398. * The unsigned integer representation of the CDDB/freedb ID
  88399. */
  88400. FLAC_API FLAC__uint32 FLAC__metadata_object_cuesheet_calculate_cddb_id(const FLAC__StreamMetadata *object);
  88401. /** Sets the MIME type of a PICTURE block.
  88402. *
  88403. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  88404. * takes ownership of the pointer. The existing string will be freed if this
  88405. * function is successful, otherwise the original string will remain if \a copy
  88406. * is \c true and malloc() fails.
  88407. *
  88408. * \note It is safe to pass a const pointer to \a mime_type if \a copy is \c true.
  88409. *
  88410. * \param object A pointer to an existing PICTURE object.
  88411. * \param mime_type A pointer to the MIME type string. The string must be
  88412. * ASCII characters 0x20-0x7e, NUL-terminated. No validation
  88413. * is done.
  88414. * \param copy See above.
  88415. * \assert
  88416. * \code object != NULL \endcode
  88417. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  88418. * \code (mime_type != NULL) \endcode
  88419. * \retval FLAC__bool
  88420. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88421. */
  88422. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_mime_type(FLAC__StreamMetadata *object, char *mime_type, FLAC__bool copy);
  88423. /** Sets the description of a PICTURE block.
  88424. *
  88425. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  88426. * takes ownership of the pointer. The existing string will be freed if this
  88427. * function is successful, otherwise the original string will remain if \a copy
  88428. * is \c true and malloc() fails.
  88429. *
  88430. * \note It is safe to pass a const pointer to \a description if \a copy is \c true.
  88431. *
  88432. * \param object A pointer to an existing PICTURE object.
  88433. * \param description A pointer to the description string. The string must be
  88434. * valid UTF-8, NUL-terminated. No validation is done.
  88435. * \param copy See above.
  88436. * \assert
  88437. * \code object != NULL \endcode
  88438. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  88439. * \code (description != NULL) \endcode
  88440. * \retval FLAC__bool
  88441. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88442. */
  88443. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_description(FLAC__StreamMetadata *object, FLAC__byte *description, FLAC__bool copy);
  88444. /** Sets the picture data of a PICTURE block.
  88445. *
  88446. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  88447. * takes ownership of the pointer. Also sets the \a data_length field of the
  88448. * metadata object to what is passed in as the \a length parameter. The
  88449. * existing data will be freed if this function is successful, otherwise the
  88450. * original data and data_length will remain if \a copy is \c true and
  88451. * malloc() fails.
  88452. *
  88453. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  88454. *
  88455. * \param object A pointer to an existing PICTURE object.
  88456. * \param data A pointer to the data to set.
  88457. * \param length The length of \a data in bytes.
  88458. * \param copy See above.
  88459. * \assert
  88460. * \code object != NULL \endcode
  88461. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  88462. * \code (data != NULL && length > 0) ||
  88463. * (data == NULL && length == 0 && copy == false) \endcode
  88464. * \retval FLAC__bool
  88465. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88466. */
  88467. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, FLAC__uint32 length, FLAC__bool copy);
  88468. /** Check a PICTURE block to see if it conforms to the FLAC specification.
  88469. * See the format specification for limits on the contents of the
  88470. * PICTURE block.
  88471. *
  88472. * \param object A pointer to existing PICTURE block to be checked.
  88473. * \param violation Address of a pointer to a string. If there is a
  88474. * violation, a pointer to a string explanation of the
  88475. * violation will be returned here. \a violation may be
  88476. * \c NULL if you don't need the returned string. Do not
  88477. * free the returned string; it will always point to static
  88478. * data.
  88479. * \assert
  88480. * \code object != NULL \endcode
  88481. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  88482. * \retval FLAC__bool
  88483. * \c false if PICTURE block is illegal, else \c true.
  88484. */
  88485. FLAC_API FLAC__bool FLAC__metadata_object_picture_is_legal(const FLAC__StreamMetadata *object, const char **violation);
  88486. /* \} */
  88487. #ifdef __cplusplus
  88488. }
  88489. #endif
  88490. #endif
  88491. /*** End of inlined file: metadata.h ***/
  88492. /*** Start of inlined file: stream_decoder.h ***/
  88493. #ifndef FLAC__STREAM_DECODER_H
  88494. #define FLAC__STREAM_DECODER_H
  88495. #include <stdio.h> /* for FILE */
  88496. #ifdef __cplusplus
  88497. extern "C" {
  88498. #endif
  88499. /** \file include/FLAC/stream_decoder.h
  88500. *
  88501. * \brief
  88502. * This module contains the functions which implement the stream
  88503. * decoder.
  88504. *
  88505. * See the detailed documentation in the
  88506. * \link flac_stream_decoder stream decoder \endlink module.
  88507. */
  88508. /** \defgroup flac_decoder FLAC/ \*_decoder.h: decoder interfaces
  88509. * \ingroup flac
  88510. *
  88511. * \brief
  88512. * This module describes the decoder layers provided by libFLAC.
  88513. *
  88514. * The stream decoder can be used to decode complete streams either from
  88515. * the client via callbacks, or directly from a file, depending on how
  88516. * it is initialized. When decoding via callbacks, the client provides
  88517. * callbacks for reading FLAC data and writing decoded samples, and
  88518. * handling metadata and errors. If the client also supplies seek-related
  88519. * callback, the decoder function for sample-accurate seeking within the
  88520. * FLAC input is also available. When decoding from a file, the client
  88521. * needs only supply a filename or open \c FILE* and write/metadata/error
  88522. * callbacks; the rest of the callbacks are supplied internally. For more
  88523. * info see the \link flac_stream_decoder stream decoder \endlink module.
  88524. */
  88525. /** \defgroup flac_stream_decoder FLAC/stream_decoder.h: stream decoder interface
  88526. * \ingroup flac_decoder
  88527. *
  88528. * \brief
  88529. * This module contains the functions which implement the stream
  88530. * decoder.
  88531. *
  88532. * The stream decoder can decode native FLAC, and optionally Ogg FLAC
  88533. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  88534. *
  88535. * The basic usage of this decoder is as follows:
  88536. * - The program creates an instance of a decoder using
  88537. * FLAC__stream_decoder_new().
  88538. * - The program overrides the default settings using
  88539. * FLAC__stream_decoder_set_*() functions.
  88540. * - The program initializes the instance to validate the settings and
  88541. * prepare for decoding using
  88542. * - FLAC__stream_decoder_init_stream() or FLAC__stream_decoder_init_FILE()
  88543. * or FLAC__stream_decoder_init_file() for native FLAC,
  88544. * - FLAC__stream_decoder_init_ogg_stream() or FLAC__stream_decoder_init_ogg_FILE()
  88545. * or FLAC__stream_decoder_init_ogg_file() for Ogg FLAC
  88546. * - The program calls the FLAC__stream_decoder_process_*() functions
  88547. * to decode data, which subsequently calls the callbacks.
  88548. * - The program finishes the decoding with FLAC__stream_decoder_finish(),
  88549. * which flushes the input and output and resets the decoder to the
  88550. * uninitialized state.
  88551. * - The instance may be used again or deleted with
  88552. * FLAC__stream_decoder_delete().
  88553. *
  88554. * In more detail, the program will create a new instance by calling
  88555. * FLAC__stream_decoder_new(), then call FLAC__stream_decoder_set_*()
  88556. * functions to override the default decoder options, and call
  88557. * one of the FLAC__stream_decoder_init_*() functions.
  88558. *
  88559. * There are three initialization functions for native FLAC, one for
  88560. * setting up the decoder to decode FLAC data from the client via
  88561. * callbacks, and two for decoding directly from a FLAC file.
  88562. *
  88563. * For decoding via callbacks, use FLAC__stream_decoder_init_stream().
  88564. * You must also supply several callbacks for handling I/O. Some (like
  88565. * seeking) are optional, depending on the capabilities of the input.
  88566. *
  88567. * For decoding directly from a file, use FLAC__stream_decoder_init_FILE()
  88568. * or FLAC__stream_decoder_init_file(). Then you must only supply an open
  88569. * \c FILE* or filename and fewer callbacks; the decoder will handle
  88570. * the other callbacks internally.
  88571. *
  88572. * There are three similarly-named init functions for decoding from Ogg
  88573. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  88574. * library has been built with Ogg support.
  88575. *
  88576. * Once the decoder is initialized, your program will call one of several
  88577. * functions to start the decoding process:
  88578. *
  88579. * - FLAC__stream_decoder_process_single() - Tells the decoder to process at
  88580. * most one metadata block or audio frame and return, calling either the
  88581. * metadata callback or write callback, respectively, once. If the decoder
  88582. * loses sync it will return with only the error callback being called.
  88583. * - FLAC__stream_decoder_process_until_end_of_metadata() - Tells the decoder
  88584. * to process the stream from the current location and stop upon reaching
  88585. * the first audio frame. The client will get one metadata, write, or error
  88586. * callback per metadata block, audio frame, or sync error, respectively.
  88587. * - FLAC__stream_decoder_process_until_end_of_stream() - Tells the decoder
  88588. * to process the stream from the current location until the read callback
  88589. * returns FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM or
  88590. * FLAC__STREAM_DECODER_READ_STATUS_ABORT. The client will get one metadata,
  88591. * write, or error callback per metadata block, audio frame, or sync error,
  88592. * respectively.
  88593. *
  88594. * When the decoder has finished decoding (normally or through an abort),
  88595. * the instance is finished by calling FLAC__stream_decoder_finish(), which
  88596. * ensures the decoder is in the correct state and frees memory. Then the
  88597. * instance may be deleted with FLAC__stream_decoder_delete() or initialized
  88598. * again to decode another stream.
  88599. *
  88600. * Seeking is exposed through the FLAC__stream_decoder_seek_absolute() method.
  88601. * At any point after the stream decoder has been initialized, the client can
  88602. * call this function to seek to an exact sample within the stream.
  88603. * Subsequently, the first time the write callback is called it will be
  88604. * passed a (possibly partial) block starting at that sample.
  88605. *
  88606. * If the client cannot seek via the callback interface provided, but still
  88607. * has another way of seeking, it can flush the decoder using
  88608. * FLAC__stream_decoder_flush() and start feeding data from the new position
  88609. * through the read callback.
  88610. *
  88611. * The stream decoder also provides MD5 signature checking. If this is
  88612. * turned on before initialization, FLAC__stream_decoder_finish() will
  88613. * report when the decoded MD5 signature does not match the one stored
  88614. * in the STREAMINFO block. MD5 checking is automatically turned off
  88615. * (until the next FLAC__stream_decoder_reset()) if there is no signature
  88616. * in the STREAMINFO block or when a seek is attempted.
  88617. *
  88618. * The FLAC__stream_decoder_set_metadata_*() functions deserve special
  88619. * attention. By default, the decoder only calls the metadata_callback for
  88620. * the STREAMINFO block. These functions allow you to tell the decoder
  88621. * explicitly which blocks to parse and return via the metadata_callback
  88622. * and/or which to skip. Use a FLAC__stream_decoder_set_metadata_respond_all(),
  88623. * FLAC__stream_decoder_set_metadata_ignore() ... or FLAC__stream_decoder_set_metadata_ignore_all(),
  88624. * FLAC__stream_decoder_set_metadata_respond() ... sequence to exactly specify
  88625. * which blocks to return. Remember that metadata blocks can potentially
  88626. * be big (for example, cover art) so filtering out the ones you don't
  88627. * use can reduce the memory requirements of the decoder. Also note the
  88628. * special forms FLAC__stream_decoder_set_metadata_respond_application(id)
  88629. * and FLAC__stream_decoder_set_metadata_ignore_application(id) for
  88630. * filtering APPLICATION blocks based on the application ID.
  88631. *
  88632. * STREAMINFO and SEEKTABLE blocks are always parsed and used internally, but
  88633. * they still can legally be filtered from the metadata_callback.
  88634. *
  88635. * \note
  88636. * The "set" functions may only be called when the decoder is in the
  88637. * state FLAC__STREAM_DECODER_UNINITIALIZED, i.e. after
  88638. * FLAC__stream_decoder_new() or FLAC__stream_decoder_finish(), but
  88639. * before FLAC__stream_decoder_init_*(). If this is the case they will
  88640. * return \c true, otherwise \c false.
  88641. *
  88642. * \note
  88643. * FLAC__stream_decoder_finish() resets all settings to the constructor
  88644. * defaults, including the callbacks.
  88645. *
  88646. * \{
  88647. */
  88648. /** State values for a FLAC__StreamDecoder
  88649. *
  88650. * The decoder's state can be obtained by calling FLAC__stream_decoder_get_state().
  88651. */
  88652. typedef enum {
  88653. FLAC__STREAM_DECODER_SEARCH_FOR_METADATA = 0,
  88654. /**< The decoder is ready to search for metadata. */
  88655. FLAC__STREAM_DECODER_READ_METADATA,
  88656. /**< The decoder is ready to or is in the process of reading metadata. */
  88657. FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC,
  88658. /**< The decoder is ready to or is in the process of searching for the
  88659. * frame sync code.
  88660. */
  88661. FLAC__STREAM_DECODER_READ_FRAME,
  88662. /**< The decoder is ready to or is in the process of reading a frame. */
  88663. FLAC__STREAM_DECODER_END_OF_STREAM,
  88664. /**< The decoder has reached the end of the stream. */
  88665. FLAC__STREAM_DECODER_OGG_ERROR,
  88666. /**< An error occurred in the underlying Ogg layer. */
  88667. FLAC__STREAM_DECODER_SEEK_ERROR,
  88668. /**< An error occurred while seeking. The decoder must be flushed
  88669. * with FLAC__stream_decoder_flush() or reset with
  88670. * FLAC__stream_decoder_reset() before decoding can continue.
  88671. */
  88672. FLAC__STREAM_DECODER_ABORTED,
  88673. /**< The decoder was aborted by the read callback. */
  88674. FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR,
  88675. /**< An error occurred allocating memory. The decoder is in an invalid
  88676. * state and can no longer be used.
  88677. */
  88678. FLAC__STREAM_DECODER_UNINITIALIZED
  88679. /**< The decoder is in the uninitialized state; one of the
  88680. * FLAC__stream_decoder_init_*() functions must be called before samples
  88681. * can be processed.
  88682. */
  88683. } FLAC__StreamDecoderState;
  88684. /** Maps a FLAC__StreamDecoderState to a C string.
  88685. *
  88686. * Using a FLAC__StreamDecoderState as the index to this array
  88687. * will give the string equivalent. The contents should not be modified.
  88688. */
  88689. extern FLAC_API const char * const FLAC__StreamDecoderStateString[];
  88690. /** Possible return values for the FLAC__stream_decoder_init_*() functions.
  88691. */
  88692. typedef enum {
  88693. FLAC__STREAM_DECODER_INIT_STATUS_OK = 0,
  88694. /**< Initialization was successful. */
  88695. FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  88696. /**< The library was not compiled with support for the given container
  88697. * format.
  88698. */
  88699. FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS,
  88700. /**< A required callback was not supplied. */
  88701. FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR,
  88702. /**< An error occurred allocating memory. */
  88703. FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE,
  88704. /**< fopen() failed in FLAC__stream_decoder_init_file() or
  88705. * FLAC__stream_decoder_init_ogg_file(). */
  88706. FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED
  88707. /**< FLAC__stream_decoder_init_*() was called when the decoder was
  88708. * already initialized, usually because
  88709. * FLAC__stream_decoder_finish() was not called.
  88710. */
  88711. } FLAC__StreamDecoderInitStatus;
  88712. /** Maps a FLAC__StreamDecoderInitStatus to a C string.
  88713. *
  88714. * Using a FLAC__StreamDecoderInitStatus as the index to this array
  88715. * will give the string equivalent. The contents should not be modified.
  88716. */
  88717. extern FLAC_API const char * const FLAC__StreamDecoderInitStatusString[];
  88718. /** Return values for the FLAC__StreamDecoder read callback.
  88719. */
  88720. typedef enum {
  88721. FLAC__STREAM_DECODER_READ_STATUS_CONTINUE,
  88722. /**< The read was OK and decoding can continue. */
  88723. FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM,
  88724. /**< The read was attempted while at the end of the stream. Note that
  88725. * the client must only return this value when the read callback was
  88726. * called when already at the end of the stream. Otherwise, if the read
  88727. * itself moves to the end of the stream, the client should still return
  88728. * the data and \c FLAC__STREAM_DECODER_READ_STATUS_CONTINUE, and then on
  88729. * the next read callback it should return
  88730. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM with a byte count
  88731. * of \c 0.
  88732. */
  88733. FLAC__STREAM_DECODER_READ_STATUS_ABORT
  88734. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  88735. } FLAC__StreamDecoderReadStatus;
  88736. /** Maps a FLAC__StreamDecoderReadStatus to a C string.
  88737. *
  88738. * Using a FLAC__StreamDecoderReadStatus as the index to this array
  88739. * will give the string equivalent. The contents should not be modified.
  88740. */
  88741. extern FLAC_API const char * const FLAC__StreamDecoderReadStatusString[];
  88742. /** Return values for the FLAC__StreamDecoder seek callback.
  88743. */
  88744. typedef enum {
  88745. FLAC__STREAM_DECODER_SEEK_STATUS_OK,
  88746. /**< The seek was OK and decoding can continue. */
  88747. FLAC__STREAM_DECODER_SEEK_STATUS_ERROR,
  88748. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  88749. FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  88750. /**< Client does not support seeking. */
  88751. } FLAC__StreamDecoderSeekStatus;
  88752. /** Maps a FLAC__StreamDecoderSeekStatus to a C string.
  88753. *
  88754. * Using a FLAC__StreamDecoderSeekStatus as the index to this array
  88755. * will give the string equivalent. The contents should not be modified.
  88756. */
  88757. extern FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[];
  88758. /** Return values for the FLAC__StreamDecoder tell callback.
  88759. */
  88760. typedef enum {
  88761. FLAC__STREAM_DECODER_TELL_STATUS_OK,
  88762. /**< The tell was OK and decoding can continue. */
  88763. FLAC__STREAM_DECODER_TELL_STATUS_ERROR,
  88764. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  88765. FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  88766. /**< Client does not support telling the position. */
  88767. } FLAC__StreamDecoderTellStatus;
  88768. /** Maps a FLAC__StreamDecoderTellStatus to a C string.
  88769. *
  88770. * Using a FLAC__StreamDecoderTellStatus as the index to this array
  88771. * will give the string equivalent. The contents should not be modified.
  88772. */
  88773. extern FLAC_API const char * const FLAC__StreamDecoderTellStatusString[];
  88774. /** Return values for the FLAC__StreamDecoder length callback.
  88775. */
  88776. typedef enum {
  88777. FLAC__STREAM_DECODER_LENGTH_STATUS_OK,
  88778. /**< The length call was OK and decoding can continue. */
  88779. FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR,
  88780. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  88781. FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  88782. /**< Client does not support reporting the length. */
  88783. } FLAC__StreamDecoderLengthStatus;
  88784. /** Maps a FLAC__StreamDecoderLengthStatus to a C string.
  88785. *
  88786. * Using a FLAC__StreamDecoderLengthStatus as the index to this array
  88787. * will give the string equivalent. The contents should not be modified.
  88788. */
  88789. extern FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[];
  88790. /** Return values for the FLAC__StreamDecoder write callback.
  88791. */
  88792. typedef enum {
  88793. FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE,
  88794. /**< The write was OK and decoding can continue. */
  88795. FLAC__STREAM_DECODER_WRITE_STATUS_ABORT
  88796. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  88797. } FLAC__StreamDecoderWriteStatus;
  88798. /** Maps a FLAC__StreamDecoderWriteStatus to a C string.
  88799. *
  88800. * Using a FLAC__StreamDecoderWriteStatus as the index to this array
  88801. * will give the string equivalent. The contents should not be modified.
  88802. */
  88803. extern FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[];
  88804. /** Possible values passed back to the FLAC__StreamDecoder error callback.
  88805. * \c FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC is the generic catch-
  88806. * all. The rest could be caused by bad sync (false synchronization on
  88807. * data that is not the start of a frame) or corrupted data. The error
  88808. * itself is the decoder's best guess at what happened assuming a correct
  88809. * sync. For example \c FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER
  88810. * could be caused by a correct sync on the start of a frame, but some
  88811. * data in the frame header was corrupted. Or it could be the result of
  88812. * syncing on a point the stream that looked like the starting of a frame
  88813. * but was not. \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  88814. * could be because the decoder encountered a valid frame made by a future
  88815. * version of the encoder which it cannot parse, or because of a false
  88816. * sync making it appear as though an encountered frame was generated by
  88817. * a future encoder.
  88818. */
  88819. typedef enum {
  88820. FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC,
  88821. /**< An error in the stream caused the decoder to lose synchronization. */
  88822. FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER,
  88823. /**< The decoder encountered a corrupted frame header. */
  88824. FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH,
  88825. /**< The frame's data did not match the CRC in the footer. */
  88826. FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  88827. /**< The decoder encountered reserved fields in use in the stream. */
  88828. } FLAC__StreamDecoderErrorStatus;
  88829. /** Maps a FLAC__StreamDecoderErrorStatus to a C string.
  88830. *
  88831. * Using a FLAC__StreamDecoderErrorStatus as the index to this array
  88832. * will give the string equivalent. The contents should not be modified.
  88833. */
  88834. extern FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[];
  88835. /***********************************************************************
  88836. *
  88837. * class FLAC__StreamDecoder
  88838. *
  88839. ***********************************************************************/
  88840. struct FLAC__StreamDecoderProtected;
  88841. struct FLAC__StreamDecoderPrivate;
  88842. /** The opaque structure definition for the stream decoder type.
  88843. * See the \link flac_stream_decoder stream decoder module \endlink
  88844. * for a detailed description.
  88845. */
  88846. typedef struct {
  88847. struct FLAC__StreamDecoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  88848. struct FLAC__StreamDecoderPrivate *private_; /* avoid the C++ keyword 'private' */
  88849. } FLAC__StreamDecoder;
  88850. /** Signature for the read callback.
  88851. *
  88852. * A function pointer matching this signature must be passed to
  88853. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  88854. * called when the decoder needs more input data. The address of the
  88855. * buffer to be filled is supplied, along with the number of bytes the
  88856. * buffer can hold. The callback may choose to supply less data and
  88857. * modify the byte count but must be careful not to overflow the buffer.
  88858. * The callback then returns a status code chosen from
  88859. * FLAC__StreamDecoderReadStatus.
  88860. *
  88861. * Here is an example of a read callback for stdio streams:
  88862. * \code
  88863. * FLAC__StreamDecoderReadStatus read_cb(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  88864. * {
  88865. * FILE *file = ((MyClientData*)client_data)->file;
  88866. * if(*bytes > 0) {
  88867. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  88868. * if(ferror(file))
  88869. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  88870. * else if(*bytes == 0)
  88871. * return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  88872. * else
  88873. * return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  88874. * }
  88875. * else
  88876. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  88877. * }
  88878. * \endcode
  88879. *
  88880. * \note In general, FLAC__StreamDecoder functions which change the
  88881. * state should not be called on the \a decoder while in the callback.
  88882. *
  88883. * \param decoder The decoder instance calling the callback.
  88884. * \param buffer A pointer to a location for the callee to store
  88885. * data to be decoded.
  88886. * \param bytes A pointer to the size of the buffer. On entry
  88887. * to the callback, it contains the maximum number
  88888. * of bytes that may be stored in \a buffer. The
  88889. * callee must set it to the actual number of bytes
  88890. * stored (0 in case of error or end-of-stream) before
  88891. * returning.
  88892. * \param client_data The callee's client data set through
  88893. * FLAC__stream_decoder_init_*().
  88894. * \retval FLAC__StreamDecoderReadStatus
  88895. * The callee's return status. Note that the callback should return
  88896. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM if and only if
  88897. * zero bytes were read and there is no more data to be read.
  88898. */
  88899. typedef FLAC__StreamDecoderReadStatus (*FLAC__StreamDecoderReadCallback)(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  88900. /** Signature for the seek callback.
  88901. *
  88902. * A function pointer matching this signature may be passed to
  88903. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  88904. * called when the decoder needs to seek the input stream. The decoder
  88905. * will pass the absolute byte offset to seek to, 0 meaning the
  88906. * beginning of the stream.
  88907. *
  88908. * Here is an example of a seek callback for stdio streams:
  88909. * \code
  88910. * FLAC__StreamDecoderSeekStatus seek_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  88911. * {
  88912. * FILE *file = ((MyClientData*)client_data)->file;
  88913. * if(file == stdin)
  88914. * return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  88915. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  88916. * return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  88917. * else
  88918. * return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  88919. * }
  88920. * \endcode
  88921. *
  88922. * \note In general, FLAC__StreamDecoder functions which change the
  88923. * state should not be called on the \a decoder while in the callback.
  88924. *
  88925. * \param decoder The decoder instance calling the callback.
  88926. * \param absolute_byte_offset The offset from the beginning of the stream
  88927. * to seek to.
  88928. * \param client_data The callee's client data set through
  88929. * FLAC__stream_decoder_init_*().
  88930. * \retval FLAC__StreamDecoderSeekStatus
  88931. * The callee's return status.
  88932. */
  88933. typedef FLAC__StreamDecoderSeekStatus (*FLAC__StreamDecoderSeekCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  88934. /** Signature for the tell callback.
  88935. *
  88936. * A function pointer matching this signature may be passed to
  88937. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  88938. * called when the decoder wants to know the current position of the
  88939. * stream. The callback should return the byte offset from the
  88940. * beginning of the stream.
  88941. *
  88942. * Here is an example of a tell callback for stdio streams:
  88943. * \code
  88944. * FLAC__StreamDecoderTellStatus tell_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  88945. * {
  88946. * FILE *file = ((MyClientData*)client_data)->file;
  88947. * off_t pos;
  88948. * if(file == stdin)
  88949. * return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  88950. * else if((pos = ftello(file)) < 0)
  88951. * return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  88952. * else {
  88953. * *absolute_byte_offset = (FLAC__uint64)pos;
  88954. * return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  88955. * }
  88956. * }
  88957. * \endcode
  88958. *
  88959. * \note In general, FLAC__StreamDecoder functions which change the
  88960. * state should not be called on the \a decoder while in the callback.
  88961. *
  88962. * \param decoder The decoder instance calling the callback.
  88963. * \param absolute_byte_offset A pointer to storage for the current offset
  88964. * from the beginning of the stream.
  88965. * \param client_data The callee's client data set through
  88966. * FLAC__stream_decoder_init_*().
  88967. * \retval FLAC__StreamDecoderTellStatus
  88968. * The callee's return status.
  88969. */
  88970. typedef FLAC__StreamDecoderTellStatus (*FLAC__StreamDecoderTellCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  88971. /** Signature for the length callback.
  88972. *
  88973. * A function pointer matching this signature may be passed to
  88974. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  88975. * called when the decoder wants to know the total length of the stream
  88976. * in bytes.
  88977. *
  88978. * Here is an example of a length callback for stdio streams:
  88979. * \code
  88980. * FLAC__StreamDecoderLengthStatus length_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  88981. * {
  88982. * FILE *file = ((MyClientData*)client_data)->file;
  88983. * struct stat filestats;
  88984. *
  88985. * if(file == stdin)
  88986. * return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  88987. * else if(fstat(fileno(file), &filestats) != 0)
  88988. * return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  88989. * else {
  88990. * *stream_length = (FLAC__uint64)filestats.st_size;
  88991. * return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  88992. * }
  88993. * }
  88994. * \endcode
  88995. *
  88996. * \note In general, FLAC__StreamDecoder functions which change the
  88997. * state should not be called on the \a decoder while in the callback.
  88998. *
  88999. * \param decoder The decoder instance calling the callback.
  89000. * \param stream_length A pointer to storage for the length of the stream
  89001. * in bytes.
  89002. * \param client_data The callee's client data set through
  89003. * FLAC__stream_decoder_init_*().
  89004. * \retval FLAC__StreamDecoderLengthStatus
  89005. * The callee's return status.
  89006. */
  89007. typedef FLAC__StreamDecoderLengthStatus (*FLAC__StreamDecoderLengthCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  89008. /** Signature for the EOF callback.
  89009. *
  89010. * A function pointer matching this signature may be passed to
  89011. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89012. * called when the decoder needs to know if the end of the stream has
  89013. * been reached.
  89014. *
  89015. * Here is an example of a EOF callback for stdio streams:
  89016. * FLAC__bool eof_cb(const FLAC__StreamDecoder *decoder, void *client_data)
  89017. * \code
  89018. * {
  89019. * FILE *file = ((MyClientData*)client_data)->file;
  89020. * return feof(file)? true : false;
  89021. * }
  89022. * \endcode
  89023. *
  89024. * \note In general, FLAC__StreamDecoder functions which change the
  89025. * state should not be called on the \a decoder while in the callback.
  89026. *
  89027. * \param decoder The decoder instance calling the callback.
  89028. * \param client_data The callee's client data set through
  89029. * FLAC__stream_decoder_init_*().
  89030. * \retval FLAC__bool
  89031. * \c true if the currently at the end of the stream, else \c false.
  89032. */
  89033. typedef FLAC__bool (*FLAC__StreamDecoderEofCallback)(const FLAC__StreamDecoder *decoder, void *client_data);
  89034. /** Signature for the write callback.
  89035. *
  89036. * A function pointer matching this signature must be passed to one of
  89037. * the FLAC__stream_decoder_init_*() functions.
  89038. * The supplied function will be called when the decoder has decoded a
  89039. * single audio frame. The decoder will pass the frame metadata as well
  89040. * as an array of pointers (one for each channel) pointing to the
  89041. * decoded audio.
  89042. *
  89043. * \note In general, FLAC__StreamDecoder functions which change the
  89044. * state should not be called on the \a decoder while in the callback.
  89045. *
  89046. * \param decoder The decoder instance calling the callback.
  89047. * \param frame The description of the decoded frame. See
  89048. * FLAC__Frame.
  89049. * \param buffer An array of pointers to decoded channels of data.
  89050. * Each pointer will point to an array of signed
  89051. * samples of length \a frame->header.blocksize.
  89052. * Channels will be ordered according to the FLAC
  89053. * specification; see the documentation for the
  89054. * <A HREF="../format.html#frame_header">frame header</A>.
  89055. * \param client_data The callee's client data set through
  89056. * FLAC__stream_decoder_init_*().
  89057. * \retval FLAC__StreamDecoderWriteStatus
  89058. * The callee's return status.
  89059. */
  89060. typedef FLAC__StreamDecoderWriteStatus (*FLAC__StreamDecoderWriteCallback)(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  89061. /** Signature for the metadata callback.
  89062. *
  89063. * A function pointer matching this signature must be passed to one of
  89064. * the FLAC__stream_decoder_init_*() functions.
  89065. * The supplied function will be called when the decoder has decoded a
  89066. * metadata block. In a valid FLAC file there will always be one
  89067. * \c STREAMINFO block, followed by zero or more other metadata blocks.
  89068. * These will be supplied by the decoder in the same order as they
  89069. * appear in the stream and always before the first audio frame (i.e.
  89070. * write callback). The metadata block that is passed in must not be
  89071. * modified, and it doesn't live beyond the callback, so you should make
  89072. * a copy of it with FLAC__metadata_object_clone() if you will need it
  89073. * elsewhere. Since metadata blocks can potentially be large, by
  89074. * default the decoder only calls the metadata callback for the
  89075. * \c STREAMINFO block; you can instruct the decoder to pass or filter
  89076. * other blocks with FLAC__stream_decoder_set_metadata_*() calls.
  89077. *
  89078. * \note In general, FLAC__StreamDecoder functions which change the
  89079. * state should not be called on the \a decoder while in the callback.
  89080. *
  89081. * \param decoder The decoder instance calling the callback.
  89082. * \param metadata The decoded metadata block.
  89083. * \param client_data The callee's client data set through
  89084. * FLAC__stream_decoder_init_*().
  89085. */
  89086. typedef void (*FLAC__StreamDecoderMetadataCallback)(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  89087. /** Signature for the error callback.
  89088. *
  89089. * A function pointer matching this signature must be passed to one of
  89090. * the FLAC__stream_decoder_init_*() functions.
  89091. * The supplied function will be called whenever an error occurs during
  89092. * decoding.
  89093. *
  89094. * \note In general, FLAC__StreamDecoder functions which change the
  89095. * state should not be called on the \a decoder while in the callback.
  89096. *
  89097. * \param decoder The decoder instance calling the callback.
  89098. * \param status The error encountered by the decoder.
  89099. * \param client_data The callee's client data set through
  89100. * FLAC__stream_decoder_init_*().
  89101. */
  89102. typedef void (*FLAC__StreamDecoderErrorCallback)(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  89103. /***********************************************************************
  89104. *
  89105. * Class constructor/destructor
  89106. *
  89107. ***********************************************************************/
  89108. /** Create a new stream decoder instance. The instance is created with
  89109. * default settings; see the individual FLAC__stream_decoder_set_*()
  89110. * functions for each setting's default.
  89111. *
  89112. * \retval FLAC__StreamDecoder*
  89113. * \c NULL if there was an error allocating memory, else the new instance.
  89114. */
  89115. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void);
  89116. /** Free a decoder instance. Deletes the object pointed to by \a decoder.
  89117. *
  89118. * \param decoder A pointer to an existing decoder.
  89119. * \assert
  89120. * \code decoder != NULL \endcode
  89121. */
  89122. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder);
  89123. /***********************************************************************
  89124. *
  89125. * Public class method prototypes
  89126. *
  89127. ***********************************************************************/
  89128. /** Set the serial number for the FLAC stream within the Ogg container.
  89129. * The default behavior is to use the serial number of the first Ogg
  89130. * page. Setting a serial number here will explicitly specify which
  89131. * stream is to be decoded.
  89132. *
  89133. * \note
  89134. * This does not need to be set for native FLAC decoding.
  89135. *
  89136. * \default \c use serial number of first page
  89137. * \param decoder A decoder instance to set.
  89138. * \param serial_number See above.
  89139. * \assert
  89140. * \code decoder != NULL \endcode
  89141. * \retval FLAC__bool
  89142. * \c false if the decoder is already initialized, else \c true.
  89143. */
  89144. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long serial_number);
  89145. /** Set the "MD5 signature checking" flag. If \c true, the decoder will
  89146. * compute the MD5 signature of the unencoded audio data while decoding
  89147. * and compare it to the signature from the STREAMINFO block, if it
  89148. * exists, during FLAC__stream_decoder_finish().
  89149. *
  89150. * MD5 signature checking will be turned off (until the next
  89151. * FLAC__stream_decoder_reset()) if there is no signature in the
  89152. * STREAMINFO block or when a seek is attempted.
  89153. *
  89154. * Clients that do not use the MD5 check should leave this off to speed
  89155. * up decoding.
  89156. *
  89157. * \default \c false
  89158. * \param decoder A decoder instance to set.
  89159. * \param value Flag value (see above).
  89160. * \assert
  89161. * \code decoder != NULL \endcode
  89162. * \retval FLAC__bool
  89163. * \c false if the decoder is already initialized, else \c true.
  89164. */
  89165. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value);
  89166. /** Direct the decoder to pass on all metadata blocks of type \a type.
  89167. *
  89168. * \default By default, only the \c STREAMINFO block is returned via the
  89169. * metadata callback.
  89170. * \param decoder A decoder instance to set.
  89171. * \param type See above.
  89172. * \assert
  89173. * \code decoder != NULL \endcode
  89174. * \a type is valid
  89175. * \retval FLAC__bool
  89176. * \c false if the decoder is already initialized, else \c true.
  89177. */
  89178. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  89179. /** Direct the decoder to pass on all APPLICATION metadata blocks of the
  89180. * given \a id.
  89181. *
  89182. * \default By default, only the \c STREAMINFO block is returned via the
  89183. * metadata callback.
  89184. * \param decoder A decoder instance to set.
  89185. * \param id See above.
  89186. * \assert
  89187. * \code decoder != NULL \endcode
  89188. * \code id != NULL \endcode
  89189. * \retval FLAC__bool
  89190. * \c false if the decoder is already initialized, else \c true.
  89191. */
  89192. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  89193. /** Direct the decoder to pass on all metadata blocks of any type.
  89194. *
  89195. * \default By default, only the \c STREAMINFO block is returned via the
  89196. * metadata callback.
  89197. * \param decoder A decoder instance to set.
  89198. * \assert
  89199. * \code decoder != NULL \endcode
  89200. * \retval FLAC__bool
  89201. * \c false if the decoder is already initialized, else \c true.
  89202. */
  89203. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder);
  89204. /** Direct the decoder to filter out all metadata blocks of type \a type.
  89205. *
  89206. * \default By default, only the \c STREAMINFO block is returned via the
  89207. * metadata callback.
  89208. * \param decoder A decoder instance to set.
  89209. * \param type See above.
  89210. * \assert
  89211. * \code decoder != NULL \endcode
  89212. * \a type is valid
  89213. * \retval FLAC__bool
  89214. * \c false if the decoder is already initialized, else \c true.
  89215. */
  89216. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  89217. /** Direct the decoder to filter out all APPLICATION metadata blocks of
  89218. * the given \a id.
  89219. *
  89220. * \default By default, only the \c STREAMINFO block is returned via the
  89221. * metadata callback.
  89222. * \param decoder A decoder instance to set.
  89223. * \param id See above.
  89224. * \assert
  89225. * \code decoder != NULL \endcode
  89226. * \code id != NULL \endcode
  89227. * \retval FLAC__bool
  89228. * \c false if the decoder is already initialized, else \c true.
  89229. */
  89230. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  89231. /** Direct the decoder to filter out all metadata blocks of any type.
  89232. *
  89233. * \default By default, only the \c STREAMINFO block is returned via the
  89234. * metadata callback.
  89235. * \param decoder A decoder instance to set.
  89236. * \assert
  89237. * \code decoder != NULL \endcode
  89238. * \retval FLAC__bool
  89239. * \c false if the decoder is already initialized, else \c true.
  89240. */
  89241. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder);
  89242. /** Get the current decoder state.
  89243. *
  89244. * \param decoder A decoder instance to query.
  89245. * \assert
  89246. * \code decoder != NULL \endcode
  89247. * \retval FLAC__StreamDecoderState
  89248. * The current decoder state.
  89249. */
  89250. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder);
  89251. /** Get the current decoder state as a C string.
  89252. *
  89253. * \param decoder A decoder instance to query.
  89254. * \assert
  89255. * \code decoder != NULL \endcode
  89256. * \retval const char *
  89257. * The decoder state as a C string. Do not modify the contents.
  89258. */
  89259. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder);
  89260. /** Get the "MD5 signature checking" flag.
  89261. * This is the value of the setting, not whether or not the decoder is
  89262. * currently checking the MD5 (remember, it can be turned off automatically
  89263. * by a seek). When the decoder is reset the flag will be restored to the
  89264. * value returned by this function.
  89265. *
  89266. * \param decoder A decoder instance to query.
  89267. * \assert
  89268. * \code decoder != NULL \endcode
  89269. * \retval FLAC__bool
  89270. * See above.
  89271. */
  89272. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder);
  89273. /** Get the total number of samples in the stream being decoded.
  89274. * Will only be valid after decoding has started and will contain the
  89275. * value from the \c STREAMINFO block. A value of \c 0 means "unknown".
  89276. *
  89277. * \param decoder A decoder instance to query.
  89278. * \assert
  89279. * \code decoder != NULL \endcode
  89280. * \retval unsigned
  89281. * See above.
  89282. */
  89283. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder);
  89284. /** Get the current number of channels in the stream being decoded.
  89285. * Will only be valid after decoding has started and will contain the
  89286. * value from the most recently decoded frame header.
  89287. *
  89288. * \param decoder A decoder instance to query.
  89289. * \assert
  89290. * \code decoder != NULL \endcode
  89291. * \retval unsigned
  89292. * See above.
  89293. */
  89294. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder);
  89295. /** Get the current channel assignment in the stream being decoded.
  89296. * Will only be valid after decoding has started and will contain the
  89297. * value from the most recently decoded frame header.
  89298. *
  89299. * \param decoder A decoder instance to query.
  89300. * \assert
  89301. * \code decoder != NULL \endcode
  89302. * \retval FLAC__ChannelAssignment
  89303. * See above.
  89304. */
  89305. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder);
  89306. /** Get the current sample resolution in the stream being decoded.
  89307. * Will only be valid after decoding has started and will contain the
  89308. * value from the most recently decoded frame header.
  89309. *
  89310. * \param decoder A decoder instance to query.
  89311. * \assert
  89312. * \code decoder != NULL \endcode
  89313. * \retval unsigned
  89314. * See above.
  89315. */
  89316. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder);
  89317. /** Get the current sample rate in Hz of the stream being decoded.
  89318. * Will only be valid after decoding has started and will contain the
  89319. * value from the most recently decoded frame header.
  89320. *
  89321. * \param decoder A decoder instance to query.
  89322. * \assert
  89323. * \code decoder != NULL \endcode
  89324. * \retval unsigned
  89325. * See above.
  89326. */
  89327. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder);
  89328. /** Get the current blocksize of the stream being decoded.
  89329. * Will only be valid after decoding has started and will contain the
  89330. * value from the most recently decoded frame header.
  89331. *
  89332. * \param decoder A decoder instance to query.
  89333. * \assert
  89334. * \code decoder != NULL \endcode
  89335. * \retval unsigned
  89336. * See above.
  89337. */
  89338. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder);
  89339. /** Returns the decoder's current read position within the stream.
  89340. * The position is the byte offset from the start of the stream.
  89341. * Bytes before this position have been fully decoded. Note that
  89342. * there may still be undecoded bytes in the decoder's read FIFO.
  89343. * The returned position is correct even after a seek.
  89344. *
  89345. * \warning This function currently only works for native FLAC,
  89346. * not Ogg FLAC streams.
  89347. *
  89348. * \param decoder A decoder instance to query.
  89349. * \param position Address at which to return the desired position.
  89350. * \assert
  89351. * \code decoder != NULL \endcode
  89352. * \code position != NULL \endcode
  89353. * \retval FLAC__bool
  89354. * \c true if successful, \c false if the stream is not native FLAC,
  89355. * or there was an error from the 'tell' callback or it returned
  89356. * \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED.
  89357. */
  89358. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position);
  89359. /** Initialize the decoder instance to decode native FLAC streams.
  89360. *
  89361. * This flavor of initialization sets up the decoder to decode from a
  89362. * native FLAC stream. I/O is performed via callbacks to the client.
  89363. * For decoding from a plain file via filename or open FILE*,
  89364. * FLAC__stream_decoder_init_file() and FLAC__stream_decoder_init_FILE()
  89365. * provide a simpler interface.
  89366. *
  89367. * This function should be called after FLAC__stream_decoder_new() and
  89368. * FLAC__stream_decoder_set_*() but before any of the
  89369. * FLAC__stream_decoder_process_*() functions. Will set and return the
  89370. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  89371. * if initialization succeeded.
  89372. *
  89373. * \param decoder An uninitialized decoder instance.
  89374. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  89375. * pointer must not be \c NULL.
  89376. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  89377. * pointer may be \c NULL if seeking is not
  89378. * supported. If \a seek_callback is not \c NULL then a
  89379. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  89380. * Alternatively, a dummy seek callback that just
  89381. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  89382. * may also be supplied, all though this is slightly
  89383. * less efficient for the decoder.
  89384. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  89385. * pointer may be \c NULL if not supported by the client. If
  89386. * \a seek_callback is not \c NULL then a
  89387. * \a tell_callback must also be supplied.
  89388. * Alternatively, a dummy tell callback that just
  89389. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  89390. * may also be supplied, all though this is slightly
  89391. * less efficient for the decoder.
  89392. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  89393. * pointer may be \c NULL if not supported by the client. If
  89394. * \a seek_callback is not \c NULL then a
  89395. * \a length_callback must also be supplied.
  89396. * Alternatively, a dummy length callback that just
  89397. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  89398. * may also be supplied, all though this is slightly
  89399. * less efficient for the decoder.
  89400. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  89401. * pointer may be \c NULL if not supported by the client. If
  89402. * \a seek_callback is not \c NULL then a
  89403. * \a eof_callback must also be supplied.
  89404. * Alternatively, a dummy length callback that just
  89405. * returns \c false
  89406. * may also be supplied, all though this is slightly
  89407. * less efficient for the decoder.
  89408. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  89409. * pointer must not be \c NULL.
  89410. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  89411. * pointer may be \c NULL if the callback is not
  89412. * desired.
  89413. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  89414. * pointer must not be \c NULL.
  89415. * \param client_data This value will be supplied to callbacks in their
  89416. * \a client_data argument.
  89417. * \assert
  89418. * \code decoder != NULL \endcode
  89419. * \retval FLAC__StreamDecoderInitStatus
  89420. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  89421. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  89422. */
  89423. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  89424. FLAC__StreamDecoder *decoder,
  89425. FLAC__StreamDecoderReadCallback read_callback,
  89426. FLAC__StreamDecoderSeekCallback seek_callback,
  89427. FLAC__StreamDecoderTellCallback tell_callback,
  89428. FLAC__StreamDecoderLengthCallback length_callback,
  89429. FLAC__StreamDecoderEofCallback eof_callback,
  89430. FLAC__StreamDecoderWriteCallback write_callback,
  89431. FLAC__StreamDecoderMetadataCallback metadata_callback,
  89432. FLAC__StreamDecoderErrorCallback error_callback,
  89433. void *client_data
  89434. );
  89435. /** Initialize the decoder instance to decode Ogg FLAC streams.
  89436. *
  89437. * This flavor of initialization sets up the decoder to decode from a
  89438. * FLAC stream in an Ogg container. I/O is performed via callbacks to the
  89439. * client. For decoding from a plain file via filename or open FILE*,
  89440. * FLAC__stream_decoder_init_ogg_file() and FLAC__stream_decoder_init_ogg_FILE()
  89441. * provide a simpler interface.
  89442. *
  89443. * This function should be called after FLAC__stream_decoder_new() and
  89444. * FLAC__stream_decoder_set_*() but before any of the
  89445. * FLAC__stream_decoder_process_*() functions. Will set and return the
  89446. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  89447. * if initialization succeeded.
  89448. *
  89449. * \note Support for Ogg FLAC in the library is optional. If this
  89450. * library has been built without support for Ogg FLAC, this function
  89451. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  89452. *
  89453. * \param decoder An uninitialized decoder instance.
  89454. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  89455. * pointer must not be \c NULL.
  89456. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  89457. * pointer may be \c NULL if seeking is not
  89458. * supported. If \a seek_callback is not \c NULL then a
  89459. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  89460. * Alternatively, a dummy seek callback that just
  89461. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  89462. * may also be supplied, all though this is slightly
  89463. * less efficient for the decoder.
  89464. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  89465. * pointer may be \c NULL if not supported by the client. If
  89466. * \a seek_callback is not \c NULL then a
  89467. * \a tell_callback must also be supplied.
  89468. * Alternatively, a dummy tell callback that just
  89469. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  89470. * may also be supplied, all though this is slightly
  89471. * less efficient for the decoder.
  89472. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  89473. * pointer may be \c NULL if not supported by the client. If
  89474. * \a seek_callback is not \c NULL then a
  89475. * \a length_callback must also be supplied.
  89476. * Alternatively, a dummy length callback that just
  89477. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  89478. * may also be supplied, all though this is slightly
  89479. * less efficient for the decoder.
  89480. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  89481. * pointer may be \c NULL if not supported by the client. If
  89482. * \a seek_callback is not \c NULL then a
  89483. * \a eof_callback must also be supplied.
  89484. * Alternatively, a dummy length callback that just
  89485. * returns \c false
  89486. * may also be supplied, all though this is slightly
  89487. * less efficient for the decoder.
  89488. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  89489. * pointer must not be \c NULL.
  89490. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  89491. * pointer may be \c NULL if the callback is not
  89492. * desired.
  89493. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  89494. * pointer must not be \c NULL.
  89495. * \param client_data This value will be supplied to callbacks in their
  89496. * \a client_data argument.
  89497. * \assert
  89498. * \code decoder != NULL \endcode
  89499. * \retval FLAC__StreamDecoderInitStatus
  89500. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  89501. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  89502. */
  89503. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  89504. FLAC__StreamDecoder *decoder,
  89505. FLAC__StreamDecoderReadCallback read_callback,
  89506. FLAC__StreamDecoderSeekCallback seek_callback,
  89507. FLAC__StreamDecoderTellCallback tell_callback,
  89508. FLAC__StreamDecoderLengthCallback length_callback,
  89509. FLAC__StreamDecoderEofCallback eof_callback,
  89510. FLAC__StreamDecoderWriteCallback write_callback,
  89511. FLAC__StreamDecoderMetadataCallback metadata_callback,
  89512. FLAC__StreamDecoderErrorCallback error_callback,
  89513. void *client_data
  89514. );
  89515. /** Initialize the decoder instance to decode native FLAC files.
  89516. *
  89517. * This flavor of initialization sets up the decoder to decode from a
  89518. * plain native FLAC file. For non-stdio streams, you must use
  89519. * FLAC__stream_decoder_init_stream() and provide callbacks for the I/O.
  89520. *
  89521. * This function should be called after FLAC__stream_decoder_new() and
  89522. * FLAC__stream_decoder_set_*() but before any of the
  89523. * FLAC__stream_decoder_process_*() functions. Will set and return the
  89524. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  89525. * if initialization succeeded.
  89526. *
  89527. * \param decoder An uninitialized decoder instance.
  89528. * \param file An open FLAC file. The file should have been
  89529. * opened with mode \c "rb" and rewound. The file
  89530. * becomes owned by the decoder and should not be
  89531. * manipulated by the client while decoding.
  89532. * Unless \a file is \c stdin, it will be closed
  89533. * when FLAC__stream_decoder_finish() is called.
  89534. * Note however that seeking will not work when
  89535. * decoding from \c stdout since it is not seekable.
  89536. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  89537. * pointer must not be \c NULL.
  89538. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  89539. * pointer may be \c NULL if the callback is not
  89540. * desired.
  89541. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  89542. * pointer must not be \c NULL.
  89543. * \param client_data This value will be supplied to callbacks in their
  89544. * \a client_data argument.
  89545. * \assert
  89546. * \code decoder != NULL \endcode
  89547. * \code file != NULL \endcode
  89548. * \retval FLAC__StreamDecoderInitStatus
  89549. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  89550. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  89551. */
  89552. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  89553. FLAC__StreamDecoder *decoder,
  89554. FILE *file,
  89555. FLAC__StreamDecoderWriteCallback write_callback,
  89556. FLAC__StreamDecoderMetadataCallback metadata_callback,
  89557. FLAC__StreamDecoderErrorCallback error_callback,
  89558. void *client_data
  89559. );
  89560. /** Initialize the decoder instance to decode Ogg FLAC files.
  89561. *
  89562. * This flavor of initialization sets up the decoder to decode from a
  89563. * plain Ogg FLAC file. For non-stdio streams, you must use
  89564. * FLAC__stream_decoder_init_ogg_stream() and provide callbacks for the I/O.
  89565. *
  89566. * This function should be called after FLAC__stream_decoder_new() and
  89567. * FLAC__stream_decoder_set_*() but before any of the
  89568. * FLAC__stream_decoder_process_*() functions. Will set and return the
  89569. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  89570. * if initialization succeeded.
  89571. *
  89572. * \note Support for Ogg FLAC in the library is optional. If this
  89573. * library has been built without support for Ogg FLAC, this function
  89574. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  89575. *
  89576. * \param decoder An uninitialized decoder instance.
  89577. * \param file An open FLAC file. The file should have been
  89578. * opened with mode \c "rb" and rewound. The file
  89579. * becomes owned by the decoder and should not be
  89580. * manipulated by the client while decoding.
  89581. * Unless \a file is \c stdin, it will be closed
  89582. * when FLAC__stream_decoder_finish() is called.
  89583. * Note however that seeking will not work when
  89584. * decoding from \c stdout since it is not seekable.
  89585. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  89586. * pointer must not be \c NULL.
  89587. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  89588. * pointer may be \c NULL if the callback is not
  89589. * desired.
  89590. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  89591. * pointer must not be \c NULL.
  89592. * \param client_data This value will be supplied to callbacks in their
  89593. * \a client_data argument.
  89594. * \assert
  89595. * \code decoder != NULL \endcode
  89596. * \code file != NULL \endcode
  89597. * \retval FLAC__StreamDecoderInitStatus
  89598. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  89599. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  89600. */
  89601. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  89602. FLAC__StreamDecoder *decoder,
  89603. FILE *file,
  89604. FLAC__StreamDecoderWriteCallback write_callback,
  89605. FLAC__StreamDecoderMetadataCallback metadata_callback,
  89606. FLAC__StreamDecoderErrorCallback error_callback,
  89607. void *client_data
  89608. );
  89609. /** Initialize the decoder instance to decode native FLAC files.
  89610. *
  89611. * This flavor of initialization sets up the decoder to decode from a plain
  89612. * native FLAC file. If POSIX fopen() semantics are not sufficient, (for
  89613. * example, with Unicode filenames on Windows), you must use
  89614. * FLAC__stream_decoder_init_FILE(), or FLAC__stream_decoder_init_stream()
  89615. * and provide callbacks for the I/O.
  89616. *
  89617. * This function should be called after FLAC__stream_decoder_new() and
  89618. * FLAC__stream_decoder_set_*() but before any of the
  89619. * FLAC__stream_decoder_process_*() functions. Will set and return the
  89620. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  89621. * if initialization succeeded.
  89622. *
  89623. * \param decoder An uninitialized decoder instance.
  89624. * \param filename The name of the file to decode from. The file will
  89625. * be opened with fopen(). Use \c NULL to decode from
  89626. * \c stdin. Note that \c stdin is not seekable.
  89627. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  89628. * pointer must not be \c NULL.
  89629. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  89630. * pointer may be \c NULL if the callback is not
  89631. * desired.
  89632. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  89633. * pointer must not be \c NULL.
  89634. * \param client_data This value will be supplied to callbacks in their
  89635. * \a client_data argument.
  89636. * \assert
  89637. * \code decoder != NULL \endcode
  89638. * \retval FLAC__StreamDecoderInitStatus
  89639. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  89640. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  89641. */
  89642. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  89643. FLAC__StreamDecoder *decoder,
  89644. const char *filename,
  89645. FLAC__StreamDecoderWriteCallback write_callback,
  89646. FLAC__StreamDecoderMetadataCallback metadata_callback,
  89647. FLAC__StreamDecoderErrorCallback error_callback,
  89648. void *client_data
  89649. );
  89650. /** Initialize the decoder instance to decode Ogg FLAC files.
  89651. *
  89652. * This flavor of initialization sets up the decoder to decode from a plain
  89653. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient, (for
  89654. * example, with Unicode filenames on Windows), you must use
  89655. * FLAC__stream_decoder_init_ogg_FILE(), or FLAC__stream_decoder_init_ogg_stream()
  89656. * and provide callbacks for the I/O.
  89657. *
  89658. * This function should be called after FLAC__stream_decoder_new() and
  89659. * FLAC__stream_decoder_set_*() but before any of the
  89660. * FLAC__stream_decoder_process_*() functions. Will set and return the
  89661. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  89662. * if initialization succeeded.
  89663. *
  89664. * \note Support for Ogg FLAC in the library is optional. If this
  89665. * library has been built without support for Ogg FLAC, this function
  89666. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  89667. *
  89668. * \param decoder An uninitialized decoder instance.
  89669. * \param filename The name of the file to decode from. The file will
  89670. * be opened with fopen(). Use \c NULL to decode from
  89671. * \c stdin. Note that \c stdin is not seekable.
  89672. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  89673. * pointer must not be \c NULL.
  89674. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  89675. * pointer may be \c NULL if the callback is not
  89676. * desired.
  89677. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  89678. * pointer must not be \c NULL.
  89679. * \param client_data This value will be supplied to callbacks in their
  89680. * \a client_data argument.
  89681. * \assert
  89682. * \code decoder != NULL \endcode
  89683. * \retval FLAC__StreamDecoderInitStatus
  89684. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  89685. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  89686. */
  89687. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  89688. FLAC__StreamDecoder *decoder,
  89689. const char *filename,
  89690. FLAC__StreamDecoderWriteCallback write_callback,
  89691. FLAC__StreamDecoderMetadataCallback metadata_callback,
  89692. FLAC__StreamDecoderErrorCallback error_callback,
  89693. void *client_data
  89694. );
  89695. /** Finish the decoding process.
  89696. * Flushes the decoding buffer, releases resources, resets the decoder
  89697. * settings to their defaults, and returns the decoder state to
  89698. * FLAC__STREAM_DECODER_UNINITIALIZED.
  89699. *
  89700. * In the event of a prematurely-terminated decode, it is not strictly
  89701. * necessary to call this immediately before FLAC__stream_decoder_delete()
  89702. * but it is good practice to match every FLAC__stream_decoder_init_*()
  89703. * with a FLAC__stream_decoder_finish().
  89704. *
  89705. * \param decoder An uninitialized decoder instance.
  89706. * \assert
  89707. * \code decoder != NULL \endcode
  89708. * \retval FLAC__bool
  89709. * \c false if MD5 checking is on AND a STREAMINFO block was available
  89710. * AND the MD5 signature in the STREAMINFO block was non-zero AND the
  89711. * signature does not match the one computed by the decoder; else
  89712. * \c true.
  89713. */
  89714. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder);
  89715. /** Flush the stream input.
  89716. * The decoder's input buffer will be cleared and the state set to
  89717. * \c FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC. This will also turn
  89718. * off MD5 checking.
  89719. *
  89720. * \param decoder A decoder instance.
  89721. * \assert
  89722. * \code decoder != NULL \endcode
  89723. * \retval FLAC__bool
  89724. * \c true if successful, else \c false if a memory allocation
  89725. * error occurs (in which case the state will be set to
  89726. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR).
  89727. */
  89728. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder);
  89729. /** Reset the decoding process.
  89730. * The decoder's input buffer will be cleared and the state set to
  89731. * \c FLAC__STREAM_DECODER_SEARCH_FOR_METADATA. This is similar to
  89732. * FLAC__stream_decoder_finish() except that the settings are
  89733. * preserved; there is no need to call FLAC__stream_decoder_init_*()
  89734. * before decoding again. MD5 checking will be restored to its original
  89735. * setting.
  89736. *
  89737. * If the decoder is seekable, or was initialized with
  89738. * FLAC__stream_decoder_init*_FILE() or FLAC__stream_decoder_init*_file(),
  89739. * the decoder will also attempt to seek to the beginning of the file.
  89740. * If this rewind fails, this function will return \c false. It follows
  89741. * that FLAC__stream_decoder_reset() cannot be used when decoding from
  89742. * \c stdin.
  89743. *
  89744. * If the decoder was initialized with FLAC__stream_encoder_init*_stream()
  89745. * and is not seekable (i.e. no seek callback was provided or the seek
  89746. * callback returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED), it
  89747. * is the duty of the client to start feeding data from the beginning of
  89748. * the stream on the next FLAC__stream_decoder_process() or
  89749. * FLAC__stream_decoder_process_interleaved() call.
  89750. *
  89751. * \param decoder A decoder instance.
  89752. * \assert
  89753. * \code decoder != NULL \endcode
  89754. * \retval FLAC__bool
  89755. * \c true if successful, else \c false if a memory allocation occurs
  89756. * (in which case the state will be set to
  89757. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR) or a seek error
  89758. * occurs (the state will be unchanged).
  89759. */
  89760. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder);
  89761. /** Decode one metadata block or audio frame.
  89762. * This version instructs the decoder to decode a either a single metadata
  89763. * block or a single frame and stop, unless the callbacks return a fatal
  89764. * error or the read callback returns
  89765. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  89766. *
  89767. * As the decoder needs more input it will call the read callback.
  89768. * Depending on what was decoded, the metadata or write callback will be
  89769. * called with the decoded metadata block or audio frame.
  89770. *
  89771. * Unless there is a fatal read error or end of stream, this function
  89772. * will return once one whole frame is decoded. In other words, if the
  89773. * stream is not synchronized or points to a corrupt frame header, the
  89774. * decoder will continue to try and resync until it gets to a valid
  89775. * frame, then decode one frame, then return. If the decoder points to
  89776. * a frame whose frame CRC in the frame footer does not match the
  89777. * computed frame CRC, this function will issue a
  89778. * FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH error to the
  89779. * error callback, and return, having decoded one complete, although
  89780. * corrupt, frame. (Such corrupted frames are sent as silence of the
  89781. * correct length to the write callback.)
  89782. *
  89783. * \param decoder An initialized decoder instance.
  89784. * \assert
  89785. * \code decoder != NULL \endcode
  89786. * \retval FLAC__bool
  89787. * \c false if any fatal read, write, or memory allocation error
  89788. * occurred (meaning decoding must stop), else \c true; for more
  89789. * information about the decoder, check the decoder state with
  89790. * FLAC__stream_decoder_get_state().
  89791. */
  89792. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder);
  89793. /** Decode until the end of the metadata.
  89794. * This version instructs the decoder to decode from the current position
  89795. * and continue until all the metadata has been read, or until the
  89796. * callbacks return a fatal error or the read callback returns
  89797. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  89798. *
  89799. * As the decoder needs more input it will call the read callback.
  89800. * As each metadata block is decoded, the metadata callback will be called
  89801. * with the decoded metadata.
  89802. *
  89803. * \param decoder An initialized decoder instance.
  89804. * \assert
  89805. * \code decoder != NULL \endcode
  89806. * \retval FLAC__bool
  89807. * \c false if any fatal read, write, or memory allocation error
  89808. * occurred (meaning decoding must stop), else \c true; for more
  89809. * information about the decoder, check the decoder state with
  89810. * FLAC__stream_decoder_get_state().
  89811. */
  89812. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder);
  89813. /** Decode until the end of the stream.
  89814. * This version instructs the decoder to decode from the current position
  89815. * and continue until the end of stream (the read callback returns
  89816. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM), or until the
  89817. * callbacks return a fatal error.
  89818. *
  89819. * As the decoder needs more input it will call the read callback.
  89820. * As each metadata block and frame is decoded, the metadata or write
  89821. * callback will be called with the decoded metadata or frame.
  89822. *
  89823. * \param decoder An initialized decoder instance.
  89824. * \assert
  89825. * \code decoder != NULL \endcode
  89826. * \retval FLAC__bool
  89827. * \c false if any fatal read, write, or memory allocation error
  89828. * occurred (meaning decoding must stop), else \c true; for more
  89829. * information about the decoder, check the decoder state with
  89830. * FLAC__stream_decoder_get_state().
  89831. */
  89832. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder);
  89833. /** Skip one audio frame.
  89834. * This version instructs the decoder to 'skip' a single frame and stop,
  89835. * unless the callbacks return a fatal error or the read callback returns
  89836. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  89837. *
  89838. * The decoding flow is the same as what occurs when
  89839. * FLAC__stream_decoder_process_single() is called to process an audio
  89840. * frame, except that this function does not decode the parsed data into
  89841. * PCM or call the write callback. The integrity of the frame is still
  89842. * checked the same way as in the other process functions.
  89843. *
  89844. * This function will return once one whole frame is skipped, in the
  89845. * same way that FLAC__stream_decoder_process_single() will return once
  89846. * one whole frame is decoded.
  89847. *
  89848. * This function can be used in more quickly determining FLAC frame
  89849. * boundaries when decoding of the actual data is not needed, for
  89850. * example when an application is separating a FLAC stream into frames
  89851. * for editing or storing in a container. To do this, the application
  89852. * can use FLAC__stream_decoder_skip_single_frame() to quickly advance
  89853. * to the next frame, then use
  89854. * FLAC__stream_decoder_get_decode_position() to find the new frame
  89855. * boundary.
  89856. *
  89857. * This function should only be called when the stream has advanced
  89858. * past all the metadata, otherwise it will return \c false.
  89859. *
  89860. * \param decoder An initialized decoder instance not in a metadata
  89861. * state.
  89862. * \assert
  89863. * \code decoder != NULL \endcode
  89864. * \retval FLAC__bool
  89865. * \c false if any fatal read, write, or memory allocation error
  89866. * occurred (meaning decoding must stop), or if the decoder
  89867. * is in the FLAC__STREAM_DECODER_SEARCH_FOR_METADATA or
  89868. * FLAC__STREAM_DECODER_READ_METADATA state, else \c true; for more
  89869. * information about the decoder, check the decoder state with
  89870. * FLAC__stream_decoder_get_state().
  89871. */
  89872. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder);
  89873. /** Flush the input and seek to an absolute sample.
  89874. * Decoding will resume at the given sample. Note that because of
  89875. * this, the next write callback may contain a partial block. The
  89876. * client must support seeking the input or this function will fail
  89877. * and return \c false. Furthermore, if the decoder state is
  89878. * \c FLAC__STREAM_DECODER_SEEK_ERROR, then the decoder must be flushed
  89879. * with FLAC__stream_decoder_flush() or reset with
  89880. * FLAC__stream_decoder_reset() before decoding can continue.
  89881. *
  89882. * \param decoder A decoder instance.
  89883. * \param sample The target sample number to seek to.
  89884. * \assert
  89885. * \code decoder != NULL \endcode
  89886. * \retval FLAC__bool
  89887. * \c true if successful, else \c false.
  89888. */
  89889. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample);
  89890. /* \} */
  89891. #ifdef __cplusplus
  89892. }
  89893. #endif
  89894. #endif
  89895. /*** End of inlined file: stream_decoder.h ***/
  89896. /*** Start of inlined file: stream_encoder.h ***/
  89897. #ifndef FLAC__STREAM_ENCODER_H
  89898. #define FLAC__STREAM_ENCODER_H
  89899. #include <stdio.h> /* for FILE */
  89900. #ifdef __cplusplus
  89901. extern "C" {
  89902. #endif
  89903. /** \file include/FLAC/stream_encoder.h
  89904. *
  89905. * \brief
  89906. * This module contains the functions which implement the stream
  89907. * encoder.
  89908. *
  89909. * See the detailed documentation in the
  89910. * \link flac_stream_encoder stream encoder \endlink module.
  89911. */
  89912. /** \defgroup flac_encoder FLAC/ \*_encoder.h: encoder interfaces
  89913. * \ingroup flac
  89914. *
  89915. * \brief
  89916. * This module describes the encoder layers provided by libFLAC.
  89917. *
  89918. * The stream encoder can be used to encode complete streams either to the
  89919. * client via callbacks, or directly to a file, depending on how it is
  89920. * initialized. When encoding via callbacks, the client provides a write
  89921. * callback which will be called whenever FLAC data is ready to be written.
  89922. * If the client also supplies a seek callback, the encoder will also
  89923. * automatically handle the writing back of metadata discovered while
  89924. * encoding, like stream info, seek points offsets, etc. When encoding to
  89925. * a file, the client needs only supply a filename or open \c FILE* and an
  89926. * optional progress callback for periodic notification of progress; the
  89927. * write and seek callbacks are supplied internally. For more info see the
  89928. * \link flac_stream_encoder stream encoder \endlink module.
  89929. */
  89930. /** \defgroup flac_stream_encoder FLAC/stream_encoder.h: stream encoder interface
  89931. * \ingroup flac_encoder
  89932. *
  89933. * \brief
  89934. * This module contains the functions which implement the stream
  89935. * encoder.
  89936. *
  89937. * The stream encoder can encode to native FLAC, and optionally Ogg FLAC
  89938. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  89939. *
  89940. * The basic usage of this encoder is as follows:
  89941. * - The program creates an instance of an encoder using
  89942. * FLAC__stream_encoder_new().
  89943. * - The program overrides the default settings using
  89944. * FLAC__stream_encoder_set_*() functions. At a minimum, the following
  89945. * functions should be called:
  89946. * - FLAC__stream_encoder_set_channels()
  89947. * - FLAC__stream_encoder_set_bits_per_sample()
  89948. * - FLAC__stream_encoder_set_sample_rate()
  89949. * - FLAC__stream_encoder_set_ogg_serial_number() (if encoding to Ogg FLAC)
  89950. * - FLAC__stream_encoder_set_total_samples_estimate() (if known)
  89951. * - If the application wants to control the compression level or set its own
  89952. * metadata, then the following should also be called:
  89953. * - FLAC__stream_encoder_set_compression_level()
  89954. * - FLAC__stream_encoder_set_verify()
  89955. * - FLAC__stream_encoder_set_metadata()
  89956. * - The rest of the set functions should only be called if the client needs
  89957. * exact control over how the audio is compressed; thorough understanding
  89958. * of the FLAC format is necessary to achieve good results.
  89959. * - The program initializes the instance to validate the settings and
  89960. * prepare for encoding using
  89961. * - FLAC__stream_encoder_init_stream() or FLAC__stream_encoder_init_FILE()
  89962. * or FLAC__stream_encoder_init_file() for native FLAC
  89963. * - FLAC__stream_encoder_init_ogg_stream() or FLAC__stream_encoder_init_ogg_FILE()
  89964. * or FLAC__stream_encoder_init_ogg_file() for Ogg FLAC
  89965. * - The program calls FLAC__stream_encoder_process() or
  89966. * FLAC__stream_encoder_process_interleaved() to encode data, which
  89967. * subsequently calls the callbacks when there is encoder data ready
  89968. * to be written.
  89969. * - The program finishes the encoding with FLAC__stream_encoder_finish(),
  89970. * which causes the encoder to encode any data still in its input pipe,
  89971. * update the metadata with the final encoding statistics if output
  89972. * seeking is possible, and finally reset the encoder to the
  89973. * uninitialized state.
  89974. * - The instance may be used again or deleted with
  89975. * FLAC__stream_encoder_delete().
  89976. *
  89977. * In more detail, the stream encoder functions similarly to the
  89978. * \link flac_stream_decoder stream decoder \endlink, but has fewer
  89979. * callbacks and more options. Typically the client will create a new
  89980. * instance by calling FLAC__stream_encoder_new(), then set the necessary
  89981. * parameters with FLAC__stream_encoder_set_*(), and initialize it by
  89982. * calling one of the FLAC__stream_encoder_init_*() functions.
  89983. *
  89984. * Unlike the decoders, the stream encoder has many options that can
  89985. * affect the speed and compression ratio. When setting these parameters
  89986. * you should have some basic knowledge of the format (see the
  89987. * <A HREF="../documentation.html#format">user-level documentation</A>
  89988. * or the <A HREF="../format.html">formal description</A>). The
  89989. * FLAC__stream_encoder_set_*() functions themselves do not validate the
  89990. * values as many are interdependent. The FLAC__stream_encoder_init_*()
  89991. * functions will do this, so make sure to pay attention to the state
  89992. * returned by FLAC__stream_encoder_init_*() to make sure that it is
  89993. * FLAC__STREAM_ENCODER_INIT_STATUS_OK. Any parameters that are not set
  89994. * before FLAC__stream_encoder_init_*() will take on the defaults from
  89995. * the constructor.
  89996. *
  89997. * There are three initialization functions for native FLAC, one for
  89998. * setting up the encoder to encode FLAC data to the client via
  89999. * callbacks, and two for encoding directly to a file.
  90000. *
  90001. * For encoding via callbacks, use FLAC__stream_encoder_init_stream().
  90002. * You must also supply a write callback which will be called anytime
  90003. * there is raw encoded data to write. If the client can seek the output
  90004. * it is best to also supply seek and tell callbacks, as this allows the
  90005. * encoder to go back after encoding is finished to write back
  90006. * information that was collected while encoding, like seek point offsets,
  90007. * frame sizes, etc.
  90008. *
  90009. * For encoding directly to a file, use FLAC__stream_encoder_init_FILE()
  90010. * or FLAC__stream_encoder_init_file(). Then you must only supply a
  90011. * filename or open \c FILE*; the encoder will handle all the callbacks
  90012. * internally. You may also supply a progress callback for periodic
  90013. * notification of the encoding progress.
  90014. *
  90015. * There are three similarly-named init functions for encoding to Ogg
  90016. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  90017. * library has been built with Ogg support.
  90018. *
  90019. * The call to FLAC__stream_encoder_init_*() currently will also immediately
  90020. * call the write callback several times, once with the \c fLaC signature,
  90021. * and once for each encoded metadata block. Note that for Ogg FLAC
  90022. * encoding you will usually get at least twice the number of callbacks than
  90023. * with native FLAC, one for the Ogg page header and one for the page body.
  90024. *
  90025. * After initializing the instance, the client may feed audio data to the
  90026. * encoder in one of two ways:
  90027. *
  90028. * - Channel separate, through FLAC__stream_encoder_process() - The client
  90029. * will pass an array of pointers to buffers, one for each channel, to
  90030. * the encoder, each of the same length. The samples need not be
  90031. * block-aligned, but each channel should have the same number of samples.
  90032. * - Channel interleaved, through
  90033. * FLAC__stream_encoder_process_interleaved() - The client will pass a single
  90034. * pointer to data that is channel-interleaved (i.e. channel0_sample0,
  90035. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  90036. * Again, the samples need not be block-aligned but they must be
  90037. * sample-aligned, i.e. the first value should be channel0_sample0 and
  90038. * the last value channelN_sampleM.
  90039. *
  90040. * Note that for either process call, each sample in the buffers should be a
  90041. * signed integer, right-justified to the resolution set by
  90042. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the resolution
  90043. * is 16 bits per sample, the samples should all be in the range [-32768,32767].
  90044. *
  90045. * When the client is finished encoding data, it calls
  90046. * FLAC__stream_encoder_finish(), which causes the encoder to encode any
  90047. * data still in its input pipe, and call the metadata callback with the
  90048. * final encoding statistics. Then the instance may be deleted with
  90049. * FLAC__stream_encoder_delete() or initialized again to encode another
  90050. * stream.
  90051. *
  90052. * For programs that write their own metadata, but that do not know the
  90053. * actual metadata until after encoding, it is advantageous to instruct
  90054. * the encoder to write a PADDING block of the correct size, so that
  90055. * instead of rewriting the whole stream after encoding, the program can
  90056. * just overwrite the PADDING block. If only the maximum size of the
  90057. * metadata is known, the program can write a slightly larger padding
  90058. * block, then split it after encoding.
  90059. *
  90060. * Make sure you understand how lengths are calculated. All FLAC metadata
  90061. * blocks have a 4 byte header which contains the type and length. This
  90062. * length does not include the 4 bytes of the header. See the format page
  90063. * for the specification of metadata blocks and their lengths.
  90064. *
  90065. * \note
  90066. * If you are writing the FLAC data to a file via callbacks, make sure it
  90067. * is open for update (e.g. mode "w+" for stdio streams). This is because
  90068. * after the first encoding pass, the encoder will try to seek back to the
  90069. * beginning of the stream, to the STREAMINFO block, to write some data
  90070. * there. (If using FLAC__stream_encoder_init*_file() or
  90071. * FLAC__stream_encoder_init*_FILE(), the file is managed internally.)
  90072. *
  90073. * \note
  90074. * The "set" functions may only be called when the encoder is in the
  90075. * state FLAC__STREAM_ENCODER_UNINITIALIZED, i.e. after
  90076. * FLAC__stream_encoder_new() or FLAC__stream_encoder_finish(), but
  90077. * before FLAC__stream_encoder_init_*(). If this is the case they will
  90078. * return \c true, otherwise \c false.
  90079. *
  90080. * \note
  90081. * FLAC__stream_encoder_finish() resets all settings to the constructor
  90082. * defaults.
  90083. *
  90084. * \{
  90085. */
  90086. /** State values for a FLAC__StreamEncoder.
  90087. *
  90088. * The encoder's state can be obtained by calling FLAC__stream_encoder_get_state().
  90089. *
  90090. * If the encoder gets into any other state besides \c FLAC__STREAM_ENCODER_OK
  90091. * or \c FLAC__STREAM_ENCODER_UNINITIALIZED, it becomes invalid for encoding and
  90092. * must be deleted with FLAC__stream_encoder_delete().
  90093. */
  90094. typedef enum {
  90095. FLAC__STREAM_ENCODER_OK = 0,
  90096. /**< The encoder is in the normal OK state and samples can be processed. */
  90097. FLAC__STREAM_ENCODER_UNINITIALIZED,
  90098. /**< The encoder is in the uninitialized state; one of the
  90099. * FLAC__stream_encoder_init_*() functions must be called before samples
  90100. * can be processed.
  90101. */
  90102. FLAC__STREAM_ENCODER_OGG_ERROR,
  90103. /**< An error occurred in the underlying Ogg layer. */
  90104. FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR,
  90105. /**< An error occurred in the underlying verify stream decoder;
  90106. * check FLAC__stream_encoder_get_verify_decoder_state().
  90107. */
  90108. FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA,
  90109. /**< The verify decoder detected a mismatch between the original
  90110. * audio signal and the decoded audio signal.
  90111. */
  90112. FLAC__STREAM_ENCODER_CLIENT_ERROR,
  90113. /**< One of the callbacks returned a fatal error. */
  90114. FLAC__STREAM_ENCODER_IO_ERROR,
  90115. /**< An I/O error occurred while opening/reading/writing a file.
  90116. * Check \c errno.
  90117. */
  90118. FLAC__STREAM_ENCODER_FRAMING_ERROR,
  90119. /**< An error occurred while writing the stream; usually, the
  90120. * write_callback returned an error.
  90121. */
  90122. FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR
  90123. /**< Memory allocation failed. */
  90124. } FLAC__StreamEncoderState;
  90125. /** Maps a FLAC__StreamEncoderState to a C string.
  90126. *
  90127. * Using a FLAC__StreamEncoderState as the index to this array
  90128. * will give the string equivalent. The contents should not be modified.
  90129. */
  90130. extern FLAC_API const char * const FLAC__StreamEncoderStateString[];
  90131. /** Possible return values for the FLAC__stream_encoder_init_*() functions.
  90132. */
  90133. typedef enum {
  90134. FLAC__STREAM_ENCODER_INIT_STATUS_OK = 0,
  90135. /**< Initialization was successful. */
  90136. FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR,
  90137. /**< General failure to set up encoder; call FLAC__stream_encoder_get_state() for cause. */
  90138. FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  90139. /**< The library was not compiled with support for the given container
  90140. * format.
  90141. */
  90142. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS,
  90143. /**< A required callback was not supplied. */
  90144. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS,
  90145. /**< The encoder has an invalid setting for number of channels. */
  90146. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE,
  90147. /**< The encoder has an invalid setting for bits-per-sample.
  90148. * FLAC supports 4-32 bps but the reference encoder currently supports
  90149. * only up to 24 bps.
  90150. */
  90151. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE,
  90152. /**< The encoder has an invalid setting for the input sample rate. */
  90153. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE,
  90154. /**< The encoder has an invalid setting for the block size. */
  90155. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER,
  90156. /**< The encoder has an invalid setting for the maximum LPC order. */
  90157. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION,
  90158. /**< The encoder has an invalid setting for the precision of the quantized linear predictor coefficients. */
  90159. FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER,
  90160. /**< The specified block size is less than the maximum LPC order. */
  90161. FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE,
  90162. /**< The encoder is bound to the <A HREF="../format.html#subset">Subset</A> but other settings violate it. */
  90163. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA,
  90164. /**< The metadata input to the encoder is invalid, in one of the following ways:
  90165. * - FLAC__stream_encoder_set_metadata() was called with a null pointer but a block count > 0
  90166. * - One of the metadata blocks contains an undefined type
  90167. * - It contains an illegal CUESHEET as checked by FLAC__format_cuesheet_is_legal()
  90168. * - It contains an illegal SEEKTABLE as checked by FLAC__format_seektable_is_legal()
  90169. * - It contains more than one SEEKTABLE block or more than one VORBIS_COMMENT block
  90170. */
  90171. FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED
  90172. /**< FLAC__stream_encoder_init_*() was called when the encoder was
  90173. * already initialized, usually because
  90174. * FLAC__stream_encoder_finish() was not called.
  90175. */
  90176. } FLAC__StreamEncoderInitStatus;
  90177. /** Maps a FLAC__StreamEncoderInitStatus to a C string.
  90178. *
  90179. * Using a FLAC__StreamEncoderInitStatus as the index to this array
  90180. * will give the string equivalent. The contents should not be modified.
  90181. */
  90182. extern FLAC_API const char * const FLAC__StreamEncoderInitStatusString[];
  90183. /** Return values for the FLAC__StreamEncoder read callback.
  90184. */
  90185. typedef enum {
  90186. FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE,
  90187. /**< The read was OK and decoding can continue. */
  90188. FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM,
  90189. /**< The read was attempted at the end of the stream. */
  90190. FLAC__STREAM_ENCODER_READ_STATUS_ABORT,
  90191. /**< An unrecoverable error occurred. */
  90192. FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED
  90193. /**< Client does not support reading back from the output. */
  90194. } FLAC__StreamEncoderReadStatus;
  90195. /** Maps a FLAC__StreamEncoderReadStatus to a C string.
  90196. *
  90197. * Using a FLAC__StreamEncoderReadStatus as the index to this array
  90198. * will give the string equivalent. The contents should not be modified.
  90199. */
  90200. extern FLAC_API const char * const FLAC__StreamEncoderReadStatusString[];
  90201. /** Return values for the FLAC__StreamEncoder write callback.
  90202. */
  90203. typedef enum {
  90204. FLAC__STREAM_ENCODER_WRITE_STATUS_OK = 0,
  90205. /**< The write was OK and encoding can continue. */
  90206. FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR
  90207. /**< An unrecoverable error occurred. The encoder will return from the process call. */
  90208. } FLAC__StreamEncoderWriteStatus;
  90209. /** Maps a FLAC__StreamEncoderWriteStatus to a C string.
  90210. *
  90211. * Using a FLAC__StreamEncoderWriteStatus as the index to this array
  90212. * will give the string equivalent. The contents should not be modified.
  90213. */
  90214. extern FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[];
  90215. /** Return values for the FLAC__StreamEncoder seek callback.
  90216. */
  90217. typedef enum {
  90218. FLAC__STREAM_ENCODER_SEEK_STATUS_OK,
  90219. /**< The seek was OK and encoding can continue. */
  90220. FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR,
  90221. /**< An unrecoverable error occurred. */
  90222. FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  90223. /**< Client does not support seeking. */
  90224. } FLAC__StreamEncoderSeekStatus;
  90225. /** Maps a FLAC__StreamEncoderSeekStatus to a C string.
  90226. *
  90227. * Using a FLAC__StreamEncoderSeekStatus as the index to this array
  90228. * will give the string equivalent. The contents should not be modified.
  90229. */
  90230. extern FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[];
  90231. /** Return values for the FLAC__StreamEncoder tell callback.
  90232. */
  90233. typedef enum {
  90234. FLAC__STREAM_ENCODER_TELL_STATUS_OK,
  90235. /**< The tell was OK and encoding can continue. */
  90236. FLAC__STREAM_ENCODER_TELL_STATUS_ERROR,
  90237. /**< An unrecoverable error occurred. */
  90238. FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  90239. /**< Client does not support seeking. */
  90240. } FLAC__StreamEncoderTellStatus;
  90241. /** Maps a FLAC__StreamEncoderTellStatus to a C string.
  90242. *
  90243. * Using a FLAC__StreamEncoderTellStatus as the index to this array
  90244. * will give the string equivalent. The contents should not be modified.
  90245. */
  90246. extern FLAC_API const char * const FLAC__StreamEncoderTellStatusString[];
  90247. /***********************************************************************
  90248. *
  90249. * class FLAC__StreamEncoder
  90250. *
  90251. ***********************************************************************/
  90252. struct FLAC__StreamEncoderProtected;
  90253. struct FLAC__StreamEncoderPrivate;
  90254. /** The opaque structure definition for the stream encoder type.
  90255. * See the \link flac_stream_encoder stream encoder module \endlink
  90256. * for a detailed description.
  90257. */
  90258. typedef struct {
  90259. struct FLAC__StreamEncoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  90260. struct FLAC__StreamEncoderPrivate *private_; /* avoid the C++ keyword 'private' */
  90261. } FLAC__StreamEncoder;
  90262. /** Signature for the read callback.
  90263. *
  90264. * A function pointer matching this signature must be passed to
  90265. * FLAC__stream_encoder_init_ogg_stream() if seeking is supported.
  90266. * The supplied function will be called when the encoder needs to read back
  90267. * encoded data. This happens during the metadata callback, when the encoder
  90268. * has to read, modify, and rewrite the metadata (e.g. seekpoints) gathered
  90269. * while encoding. The address of the buffer to be filled is supplied, along
  90270. * with the number of bytes the buffer can hold. The callback may choose to
  90271. * supply less data and modify the byte count but must be careful not to
  90272. * overflow the buffer. The callback then returns a status code chosen from
  90273. * FLAC__StreamEncoderReadStatus.
  90274. *
  90275. * Here is an example of a read callback for stdio streams:
  90276. * \code
  90277. * FLAC__StreamEncoderReadStatus read_cb(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  90278. * {
  90279. * FILE *file = ((MyClientData*)client_data)->file;
  90280. * if(*bytes > 0) {
  90281. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  90282. * if(ferror(file))
  90283. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  90284. * else if(*bytes == 0)
  90285. * return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  90286. * else
  90287. * return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  90288. * }
  90289. * else
  90290. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  90291. * }
  90292. * \endcode
  90293. *
  90294. * \note In general, FLAC__StreamEncoder functions which change the
  90295. * state should not be called on the \a encoder while in the callback.
  90296. *
  90297. * \param encoder The encoder instance calling the callback.
  90298. * \param buffer A pointer to a location for the callee to store
  90299. * data to be encoded.
  90300. * \param bytes A pointer to the size of the buffer. On entry
  90301. * to the callback, it contains the maximum number
  90302. * of bytes that may be stored in \a buffer. The
  90303. * callee must set it to the actual number of bytes
  90304. * stored (0 in case of error or end-of-stream) before
  90305. * returning.
  90306. * \param client_data The callee's client data set through
  90307. * FLAC__stream_encoder_set_client_data().
  90308. * \retval FLAC__StreamEncoderReadStatus
  90309. * The callee's return status.
  90310. */
  90311. typedef FLAC__StreamEncoderReadStatus (*FLAC__StreamEncoderReadCallback)(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  90312. /** Signature for the write callback.
  90313. *
  90314. * A function pointer matching this signature must be passed to
  90315. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  90316. * by the encoder anytime there is raw encoded data ready to write. It may
  90317. * include metadata mixed with encoded audio frames and the data is not
  90318. * guaranteed to be aligned on frame or metadata block boundaries.
  90319. *
  90320. * The only duty of the callback is to write out the \a bytes worth of data
  90321. * in \a buffer to the current position in the output stream. The arguments
  90322. * \a samples and \a current_frame are purely informational. If \a samples
  90323. * is greater than \c 0, then \a current_frame will hold the current frame
  90324. * number that is being written; otherwise it indicates that the write
  90325. * callback is being called to write metadata.
  90326. *
  90327. * \note
  90328. * Unlike when writing to native FLAC, when writing to Ogg FLAC the
  90329. * write callback will be called twice when writing each audio
  90330. * frame; once for the page header, and once for the page body.
  90331. * When writing the page header, the \a samples argument to the
  90332. * write callback will be \c 0.
  90333. *
  90334. * \note In general, FLAC__StreamEncoder functions which change the
  90335. * state should not be called on the \a encoder while in the callback.
  90336. *
  90337. * \param encoder The encoder instance calling the callback.
  90338. * \param buffer An array of encoded data of length \a bytes.
  90339. * \param bytes The byte length of \a buffer.
  90340. * \param samples The number of samples encoded by \a buffer.
  90341. * \c 0 has a special meaning; see above.
  90342. * \param current_frame The number of the current frame being encoded.
  90343. * \param client_data The callee's client data set through
  90344. * FLAC__stream_encoder_init_*().
  90345. * \retval FLAC__StreamEncoderWriteStatus
  90346. * The callee's return status.
  90347. */
  90348. typedef FLAC__StreamEncoderWriteStatus (*FLAC__StreamEncoderWriteCallback)(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
  90349. /** Signature for the seek callback.
  90350. *
  90351. * A function pointer matching this signature may be passed to
  90352. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  90353. * when the encoder needs to seek the output stream. The encoder will pass
  90354. * the absolute byte offset to seek to, 0 meaning the beginning of the stream.
  90355. *
  90356. * Here is an example of a seek callback for stdio streams:
  90357. * \code
  90358. * FLAC__StreamEncoderSeekStatus seek_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  90359. * {
  90360. * FILE *file = ((MyClientData*)client_data)->file;
  90361. * if(file == stdin)
  90362. * return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  90363. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  90364. * return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  90365. * else
  90366. * return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  90367. * }
  90368. * \endcode
  90369. *
  90370. * \note In general, FLAC__StreamEncoder functions which change the
  90371. * state should not be called on the \a encoder while in the callback.
  90372. *
  90373. * \param encoder The encoder instance calling the callback.
  90374. * \param absolute_byte_offset The offset from the beginning of the stream
  90375. * to seek to.
  90376. * \param client_data The callee's client data set through
  90377. * FLAC__stream_encoder_init_*().
  90378. * \retval FLAC__StreamEncoderSeekStatus
  90379. * The callee's return status.
  90380. */
  90381. typedef FLAC__StreamEncoderSeekStatus (*FLAC__StreamEncoderSeekCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  90382. /** Signature for the tell callback.
  90383. *
  90384. * A function pointer matching this signature may be passed to
  90385. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  90386. * when the encoder needs to know the current position of the output stream.
  90387. *
  90388. * \warning
  90389. * The callback must return the true current byte offset of the output to
  90390. * which the encoder is writing. If you are buffering the output, make
  90391. * sure and take this into account. If you are writing directly to a
  90392. * FILE* from your write callback, ftell() is sufficient. If you are
  90393. * writing directly to a file descriptor from your write callback, you
  90394. * can use lseek(fd, SEEK_CUR, 0). The encoder may later seek back to
  90395. * these points to rewrite metadata after encoding.
  90396. *
  90397. * Here is an example of a tell callback for stdio streams:
  90398. * \code
  90399. * FLAC__StreamEncoderTellStatus tell_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  90400. * {
  90401. * FILE *file = ((MyClientData*)client_data)->file;
  90402. * off_t pos;
  90403. * if(file == stdin)
  90404. * return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  90405. * else if((pos = ftello(file)) < 0)
  90406. * return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  90407. * else {
  90408. * *absolute_byte_offset = (FLAC__uint64)pos;
  90409. * return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  90410. * }
  90411. * }
  90412. * \endcode
  90413. *
  90414. * \note In general, FLAC__StreamEncoder functions which change the
  90415. * state should not be called on the \a encoder while in the callback.
  90416. *
  90417. * \param encoder The encoder instance calling the callback.
  90418. * \param absolute_byte_offset The address at which to store the current
  90419. * position of the output.
  90420. * \param client_data The callee's client data set through
  90421. * FLAC__stream_encoder_init_*().
  90422. * \retval FLAC__StreamEncoderTellStatus
  90423. * The callee's return status.
  90424. */
  90425. typedef FLAC__StreamEncoderTellStatus (*FLAC__StreamEncoderTellCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  90426. /** Signature for the metadata callback.
  90427. *
  90428. * A function pointer matching this signature may be passed to
  90429. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  90430. * once at the end of encoding with the populated STREAMINFO structure. This
  90431. * is so the client can seek back to the beginning of the file and write the
  90432. * STREAMINFO block with the correct statistics after encoding (like
  90433. * minimum/maximum frame size and total samples).
  90434. *
  90435. * \note In general, FLAC__StreamEncoder functions which change the
  90436. * state should not be called on the \a encoder while in the callback.
  90437. *
  90438. * \param encoder The encoder instance calling the callback.
  90439. * \param metadata The final populated STREAMINFO block.
  90440. * \param client_data The callee's client data set through
  90441. * FLAC__stream_encoder_init_*().
  90442. */
  90443. typedef void (*FLAC__StreamEncoderMetadataCallback)(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
  90444. /** Signature for the progress callback.
  90445. *
  90446. * A function pointer matching this signature may be passed to
  90447. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE().
  90448. * The supplied function will be called when the encoder has finished
  90449. * writing a frame. The \c total_frames_estimate argument to the
  90450. * callback will be based on the value from
  90451. * FLAC__stream_encoder_set_total_samples_estimate().
  90452. *
  90453. * \note In general, FLAC__StreamEncoder functions which change the
  90454. * state should not be called on the \a encoder while in the callback.
  90455. *
  90456. * \param encoder The encoder instance calling the callback.
  90457. * \param bytes_written Bytes written so far.
  90458. * \param samples_written Samples written so far.
  90459. * \param frames_written Frames written so far.
  90460. * \param total_frames_estimate The estimate of the total number of
  90461. * frames to be written.
  90462. * \param client_data The callee's client data set through
  90463. * FLAC__stream_encoder_init_*().
  90464. */
  90465. 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);
  90466. /***********************************************************************
  90467. *
  90468. * Class constructor/destructor
  90469. *
  90470. ***********************************************************************/
  90471. /** Create a new stream encoder instance. The instance is created with
  90472. * default settings; see the individual FLAC__stream_encoder_set_*()
  90473. * functions for each setting's default.
  90474. *
  90475. * \retval FLAC__StreamEncoder*
  90476. * \c NULL if there was an error allocating memory, else the new instance.
  90477. */
  90478. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void);
  90479. /** Free an encoder instance. Deletes the object pointed to by \a encoder.
  90480. *
  90481. * \param encoder A pointer to an existing encoder.
  90482. * \assert
  90483. * \code encoder != NULL \endcode
  90484. */
  90485. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder);
  90486. /***********************************************************************
  90487. *
  90488. * Public class method prototypes
  90489. *
  90490. ***********************************************************************/
  90491. /** Set the serial number for the FLAC stream to use in the Ogg container.
  90492. *
  90493. * \note
  90494. * This does not need to be set for native FLAC encoding.
  90495. *
  90496. * \note
  90497. * It is recommended to set a serial number explicitly as the default of '0'
  90498. * may collide with other streams.
  90499. *
  90500. * \default \c 0
  90501. * \param encoder An encoder instance to set.
  90502. * \param serial_number See above.
  90503. * \assert
  90504. * \code encoder != NULL \endcode
  90505. * \retval FLAC__bool
  90506. * \c false if the encoder is already initialized, else \c true.
  90507. */
  90508. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long serial_number);
  90509. /** Set the "verify" flag. If \c true, the encoder will verify it's own
  90510. * encoded output by feeding it through an internal decoder and comparing
  90511. * the original signal against the decoded signal. If a mismatch occurs,
  90512. * the process call will return \c false. Note that this will slow the
  90513. * encoding process by the extra time required for decoding and comparison.
  90514. *
  90515. * \default \c false
  90516. * \param encoder An encoder instance to set.
  90517. * \param value Flag value (see above).
  90518. * \assert
  90519. * \code encoder != NULL \endcode
  90520. * \retval FLAC__bool
  90521. * \c false if the encoder is already initialized, else \c true.
  90522. */
  90523. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value);
  90524. /** Set the <A HREF="../format.html#subset">Subset</A> flag. If \c true,
  90525. * the encoder will comply with the Subset and will check the
  90526. * settings during FLAC__stream_encoder_init_*() to see if all settings
  90527. * comply. If \c false, the settings may take advantage of the full
  90528. * range that the format allows.
  90529. *
  90530. * Make sure you know what it entails before setting this to \c false.
  90531. *
  90532. * \default \c true
  90533. * \param encoder An encoder instance to set.
  90534. * \param value Flag value (see above).
  90535. * \assert
  90536. * \code encoder != NULL \endcode
  90537. * \retval FLAC__bool
  90538. * \c false if the encoder is already initialized, else \c true.
  90539. */
  90540. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value);
  90541. /** Set the number of channels to be encoded.
  90542. *
  90543. * \default \c 2
  90544. * \param encoder An encoder instance to set.
  90545. * \param value See above.
  90546. * \assert
  90547. * \code encoder != NULL \endcode
  90548. * \retval FLAC__bool
  90549. * \c false if the encoder is already initialized, else \c true.
  90550. */
  90551. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value);
  90552. /** Set the sample resolution of the input to be encoded.
  90553. *
  90554. * \warning
  90555. * Do not feed the encoder data that is wider than the value you
  90556. * set here or you will generate an invalid stream.
  90557. *
  90558. * \default \c 16
  90559. * \param encoder An encoder instance to set.
  90560. * \param value See above.
  90561. * \assert
  90562. * \code encoder != NULL \endcode
  90563. * \retval FLAC__bool
  90564. * \c false if the encoder is already initialized, else \c true.
  90565. */
  90566. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value);
  90567. /** Set the sample rate (in Hz) of the input to be encoded.
  90568. *
  90569. * \default \c 44100
  90570. * \param encoder An encoder instance to set.
  90571. * \param value See above.
  90572. * \assert
  90573. * \code encoder != NULL \endcode
  90574. * \retval FLAC__bool
  90575. * \c false if the encoder is already initialized, else \c true.
  90576. */
  90577. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value);
  90578. /** Set the compression level
  90579. *
  90580. * The compression level is roughly proportional to the amount of effort
  90581. * the encoder expends to compress the file. A higher level usually
  90582. * means more computation but higher compression. The default level is
  90583. * suitable for most applications.
  90584. *
  90585. * Currently the levels range from \c 0 (fastest, least compression) to
  90586. * \c 8 (slowest, most compression). A value larger than \c 8 will be
  90587. * treated as \c 8.
  90588. *
  90589. * This function automatically calls the following other \c _set_
  90590. * functions with appropriate values, so the client does not need to
  90591. * unless it specifically wants to override them:
  90592. * - FLAC__stream_encoder_set_do_mid_side_stereo()
  90593. * - FLAC__stream_encoder_set_loose_mid_side_stereo()
  90594. * - FLAC__stream_encoder_set_apodization()
  90595. * - FLAC__stream_encoder_set_max_lpc_order()
  90596. * - FLAC__stream_encoder_set_qlp_coeff_precision()
  90597. * - FLAC__stream_encoder_set_do_qlp_coeff_prec_search()
  90598. * - FLAC__stream_encoder_set_do_escape_coding()
  90599. * - FLAC__stream_encoder_set_do_exhaustive_model_search()
  90600. * - FLAC__stream_encoder_set_min_residual_partition_order()
  90601. * - FLAC__stream_encoder_set_max_residual_partition_order()
  90602. * - FLAC__stream_encoder_set_rice_parameter_search_dist()
  90603. *
  90604. * The actual values set for each level are:
  90605. * <table>
  90606. * <tr>
  90607. * <td><b>level</b><td>
  90608. * <td>do mid-side stereo<td>
  90609. * <td>loose mid-side stereo<td>
  90610. * <td>apodization<td>
  90611. * <td>max lpc order<td>
  90612. * <td>qlp coeff precision<td>
  90613. * <td>qlp coeff prec search<td>
  90614. * <td>escape coding<td>
  90615. * <td>exhaustive model search<td>
  90616. * <td>min residual partition order<td>
  90617. * <td>max residual partition order<td>
  90618. * <td>rice parameter search dist<td>
  90619. * </tr>
  90620. * <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>
  90621. * <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>
  90622. * <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>
  90623. * <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>
  90624. * <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>
  90625. * <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>
  90626. * <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>
  90627. * <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>
  90628. * <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>
  90629. * </table>
  90630. *
  90631. * \default \c 5
  90632. * \param encoder An encoder instance to set.
  90633. * \param value See above.
  90634. * \assert
  90635. * \code encoder != NULL \endcode
  90636. * \retval FLAC__bool
  90637. * \c false if the encoder is already initialized, else \c true.
  90638. */
  90639. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value);
  90640. /** Set the blocksize to use while encoding.
  90641. *
  90642. * The number of samples to use per frame. Use \c 0 to let the encoder
  90643. * estimate a blocksize; this is usually best.
  90644. *
  90645. * \default \c 0
  90646. * \param encoder An encoder instance to set.
  90647. * \param value See above.
  90648. * \assert
  90649. * \code encoder != NULL \endcode
  90650. * \retval FLAC__bool
  90651. * \c false if the encoder is already initialized, else \c true.
  90652. */
  90653. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value);
  90654. /** Set to \c true to enable mid-side encoding on stereo input. The
  90655. * number of channels must be 2 for this to have any effect. Set to
  90656. * \c false to use only independent channel coding.
  90657. *
  90658. * \default \c false
  90659. * \param encoder An encoder instance to set.
  90660. * \param value Flag value (see above).
  90661. * \assert
  90662. * \code encoder != NULL \endcode
  90663. * \retval FLAC__bool
  90664. * \c false if the encoder is already initialized, else \c true.
  90665. */
  90666. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  90667. /** Set to \c true to enable adaptive switching between mid-side and
  90668. * left-right encoding on stereo input. Set to \c false to use
  90669. * exhaustive searching. Setting this to \c true requires
  90670. * FLAC__stream_encoder_set_do_mid_side_stereo() to also be set to
  90671. * \c true in order to have any effect.
  90672. *
  90673. * \default \c false
  90674. * \param encoder An encoder instance to set.
  90675. * \param value Flag value (see above).
  90676. * \assert
  90677. * \code encoder != NULL \endcode
  90678. * \retval FLAC__bool
  90679. * \c false if the encoder is already initialized, else \c true.
  90680. */
  90681. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  90682. /** Sets the apodization function(s) the encoder will use when windowing
  90683. * audio data for LPC analysis.
  90684. *
  90685. * The \a specification is a plain ASCII string which specifies exactly
  90686. * which functions to use. There may be more than one (up to 32),
  90687. * separated by \c ';' characters. Some functions take one or more
  90688. * comma-separated arguments in parentheses.
  90689. *
  90690. * The available functions are \c bartlett, \c bartlett_hann,
  90691. * \c blackman, \c blackman_harris_4term_92db, \c connes, \c flattop,
  90692. * \c gauss(STDDEV), \c hamming, \c hann, \c kaiser_bessel, \c nuttall,
  90693. * \c rectangle, \c triangle, \c tukey(P), \c welch.
  90694. *
  90695. * For \c gauss(STDDEV), STDDEV specifies the standard deviation
  90696. * (0<STDDEV<=0.5).
  90697. *
  90698. * For \c tukey(P), P specifies the fraction of the window that is
  90699. * tapered (0<=P<=1). P=0 corresponds to \c rectangle and P=1
  90700. * corresponds to \c hann.
  90701. *
  90702. * Example specifications are \c "blackman" or
  90703. * \c "hann;triangle;tukey(0.5);tukey(0.25);tukey(0.125)"
  90704. *
  90705. * Any function that is specified erroneously is silently dropped. Up
  90706. * to 32 functions are kept, the rest are dropped. If the specification
  90707. * is empty the encoder defaults to \c "tukey(0.5)".
  90708. *
  90709. * When more than one function is specified, then for every subframe the
  90710. * encoder will try each of them separately and choose the window that
  90711. * results in the smallest compressed subframe.
  90712. *
  90713. * Note that each function specified causes the encoder to occupy a
  90714. * floating point array in which to store the window.
  90715. *
  90716. * \default \c "tukey(0.5)"
  90717. * \param encoder An encoder instance to set.
  90718. * \param specification See above.
  90719. * \assert
  90720. * \code encoder != NULL \endcode
  90721. * \code specification != NULL \endcode
  90722. * \retval FLAC__bool
  90723. * \c false if the encoder is already initialized, else \c true.
  90724. */
  90725. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification);
  90726. /** Set the maximum LPC order, or \c 0 to use only the fixed predictors.
  90727. *
  90728. * \default \c 0
  90729. * \param encoder An encoder instance to set.
  90730. * \param value See above.
  90731. * \assert
  90732. * \code encoder != NULL \endcode
  90733. * \retval FLAC__bool
  90734. * \c false if the encoder is already initialized, else \c true.
  90735. */
  90736. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value);
  90737. /** Set the precision, in bits, of the quantized linear predictor
  90738. * coefficients, or \c 0 to let the encoder select it based on the
  90739. * blocksize.
  90740. *
  90741. * \note
  90742. * In the current implementation, qlp_coeff_precision + bits_per_sample must
  90743. * be less than 32.
  90744. *
  90745. * \default \c 0
  90746. * \param encoder An encoder instance to set.
  90747. * \param value See above.
  90748. * \assert
  90749. * \code encoder != NULL \endcode
  90750. * \retval FLAC__bool
  90751. * \c false if the encoder is already initialized, else \c true.
  90752. */
  90753. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value);
  90754. /** Set to \c false to use only the specified quantized linear predictor
  90755. * coefficient precision, or \c true to search neighboring precision
  90756. * values and use the best one.
  90757. *
  90758. * \default \c false
  90759. * \param encoder An encoder instance to set.
  90760. * \param value See above.
  90761. * \assert
  90762. * \code encoder != NULL \endcode
  90763. * \retval FLAC__bool
  90764. * \c false if the encoder is already initialized, else \c true.
  90765. */
  90766. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  90767. /** Deprecated. Setting this value has no effect.
  90768. *
  90769. * \default \c false
  90770. * \param encoder An encoder instance to set.
  90771. * \param value See above.
  90772. * \assert
  90773. * \code encoder != NULL \endcode
  90774. * \retval FLAC__bool
  90775. * \c false if the encoder is already initialized, else \c true.
  90776. */
  90777. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value);
  90778. /** Set to \c false to let the encoder estimate the best model order
  90779. * based on the residual signal energy, or \c true to force the
  90780. * encoder to evaluate all order models and select the best.
  90781. *
  90782. * \default \c false
  90783. * \param encoder An encoder instance to set.
  90784. * \param value See above.
  90785. * \assert
  90786. * \code encoder != NULL \endcode
  90787. * \retval FLAC__bool
  90788. * \c false if the encoder is already initialized, else \c true.
  90789. */
  90790. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  90791. /** Set the minimum partition order to search when coding the residual.
  90792. * This is used in tandem with
  90793. * FLAC__stream_encoder_set_max_residual_partition_order().
  90794. *
  90795. * The partition order determines the context size in the residual.
  90796. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  90797. *
  90798. * Set both min and max values to \c 0 to force a single context,
  90799. * whose Rice parameter is based on the residual signal variance.
  90800. * Otherwise, set a min and max order, and the encoder will search
  90801. * all orders, using the mean of each context for its Rice parameter,
  90802. * and use the best.
  90803. *
  90804. * \default \c 0
  90805. * \param encoder An encoder instance to set.
  90806. * \param value See above.
  90807. * \assert
  90808. * \code encoder != NULL \endcode
  90809. * \retval FLAC__bool
  90810. * \c false if the encoder is already initialized, else \c true.
  90811. */
  90812. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  90813. /** Set the maximum partition order to search when coding the residual.
  90814. * This is used in tandem with
  90815. * FLAC__stream_encoder_set_min_residual_partition_order().
  90816. *
  90817. * The partition order determines the context size in the residual.
  90818. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  90819. *
  90820. * Set both min and max values to \c 0 to force a single context,
  90821. * whose Rice parameter is based on the residual signal variance.
  90822. * Otherwise, set a min and max order, and the encoder will search
  90823. * all orders, using the mean of each context for its Rice parameter,
  90824. * and use the best.
  90825. *
  90826. * \default \c 0
  90827. * \param encoder An encoder instance to set.
  90828. * \param value See above.
  90829. * \assert
  90830. * \code encoder != NULL \endcode
  90831. * \retval FLAC__bool
  90832. * \c false if the encoder is already initialized, else \c true.
  90833. */
  90834. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  90835. /** Deprecated. Setting this value has no effect.
  90836. *
  90837. * \default \c 0
  90838. * \param encoder An encoder instance to set.
  90839. * \param value See above.
  90840. * \assert
  90841. * \code encoder != NULL \endcode
  90842. * \retval FLAC__bool
  90843. * \c false if the encoder is already initialized, else \c true.
  90844. */
  90845. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value);
  90846. /** Set an estimate of the total samples that will be encoded.
  90847. * This is merely an estimate and may be set to \c 0 if unknown.
  90848. * This value will be written to the STREAMINFO block before encoding,
  90849. * and can remove the need for the caller to rewrite the value later
  90850. * if the value is known before encoding.
  90851. *
  90852. * \default \c 0
  90853. * \param encoder An encoder instance to set.
  90854. * \param value See above.
  90855. * \assert
  90856. * \code encoder != NULL \endcode
  90857. * \retval FLAC__bool
  90858. * \c false if the encoder is already initialized, else \c true.
  90859. */
  90860. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value);
  90861. /** Set the metadata blocks to be emitted to the stream before encoding.
  90862. * A value of \c NULL, \c 0 implies no metadata; otherwise, supply an
  90863. * array of pointers to metadata blocks. The array is non-const since
  90864. * the encoder may need to change the \a is_last flag inside them, and
  90865. * in some cases update seek point offsets. Otherwise, the encoder will
  90866. * not modify or free the blocks. It is up to the caller to free the
  90867. * metadata blocks after encoding finishes.
  90868. *
  90869. * \note
  90870. * The encoder stores only copies of the pointers in the \a metadata array;
  90871. * the metadata blocks themselves must survive at least until after
  90872. * FLAC__stream_encoder_finish() returns. Do not free the blocks until then.
  90873. *
  90874. * \note
  90875. * The STREAMINFO block is always written and no STREAMINFO block may
  90876. * occur in the supplied array.
  90877. *
  90878. * \note
  90879. * By default the encoder does not create a SEEKTABLE. If one is supplied
  90880. * in the \a metadata array, but the client has specified that it does not
  90881. * support seeking, then the SEEKTABLE will be written verbatim. However
  90882. * by itself this is not very useful as the client will not know the stream
  90883. * offsets for the seekpoints ahead of time. In order to get a proper
  90884. * seektable the client must support seeking. See next note.
  90885. *
  90886. * \note
  90887. * SEEKTABLE blocks are handled specially. Since you will not know
  90888. * the values for the seek point stream offsets, you should pass in
  90889. * a SEEKTABLE 'template', that is, a SEEKTABLE object with the
  90890. * required sample numbers (or placeholder points), with \c 0 for the
  90891. * \a frame_samples and \a stream_offset fields for each point. If the
  90892. * client has specified that it supports seeking by providing a seek
  90893. * callback to FLAC__stream_encoder_init_stream() or both seek AND read
  90894. * callback to FLAC__stream_encoder_init_ogg_stream() (or by using
  90895. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE()),
  90896. * then while it is encoding the encoder will fill the stream offsets in
  90897. * for you and when encoding is finished, it will seek back and write the
  90898. * real values into the SEEKTABLE block in the stream. There are helper
  90899. * routines for manipulating seektable template blocks; see metadata.h:
  90900. * FLAC__metadata_object_seektable_template_*(). If the client does
  90901. * not support seeking, the SEEKTABLE will have inaccurate offsets which
  90902. * will slow down or remove the ability to seek in the FLAC stream.
  90903. *
  90904. * \note
  90905. * The encoder instance \b will modify the first \c SEEKTABLE block
  90906. * as it transforms the template to a valid seektable while encoding,
  90907. * but it is still up to the caller to free all metadata blocks after
  90908. * encoding.
  90909. *
  90910. * \note
  90911. * A VORBIS_COMMENT block may be supplied. The vendor string in it
  90912. * will be ignored. libFLAC will use it's own vendor string. libFLAC
  90913. * will not modify the passed-in VORBIS_COMMENT's vendor string, it
  90914. * will simply write it's own into the stream. If no VORBIS_COMMENT
  90915. * block is present in the \a metadata array, libFLAC will write an
  90916. * empty one, containing only the vendor string.
  90917. *
  90918. * \note The Ogg FLAC mapping requires that the VORBIS_COMMENT block be
  90919. * the second metadata block of the stream. The encoder already supplies
  90920. * the STREAMINFO block automatically. If \a metadata does not contain a
  90921. * VORBIS_COMMENT block, the encoder will supply that too. Otherwise, if
  90922. * \a metadata does contain a VORBIS_COMMENT block and it is not the
  90923. * first, the init function will reorder \a metadata by moving the
  90924. * VORBIS_COMMENT block to the front; the relative ordering of the other
  90925. * blocks will remain as they were.
  90926. *
  90927. * \note The Ogg FLAC mapping limits the number of metadata blocks per
  90928. * stream to \c 65535. If \a num_blocks exceeds this the function will
  90929. * return \c false.
  90930. *
  90931. * \default \c NULL, 0
  90932. * \param encoder An encoder instance to set.
  90933. * \param metadata See above.
  90934. * \param num_blocks See above.
  90935. * \assert
  90936. * \code encoder != NULL \endcode
  90937. * \retval FLAC__bool
  90938. * \c false if the encoder is already initialized, else \c true.
  90939. * \c false if the encoder is already initialized, or if
  90940. * \a num_blocks > 65535 if encoding to Ogg FLAC, else \c true.
  90941. */
  90942. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks);
  90943. /** Get the current encoder state.
  90944. *
  90945. * \param encoder An encoder instance to query.
  90946. * \assert
  90947. * \code encoder != NULL \endcode
  90948. * \retval FLAC__StreamEncoderState
  90949. * The current encoder state.
  90950. */
  90951. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder);
  90952. /** Get the state of the verify stream decoder.
  90953. * Useful when the stream encoder state is
  90954. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR.
  90955. *
  90956. * \param encoder An encoder instance to query.
  90957. * \assert
  90958. * \code encoder != NULL \endcode
  90959. * \retval FLAC__StreamDecoderState
  90960. * The verify stream decoder state.
  90961. */
  90962. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder);
  90963. /** Get the current encoder state as a C string.
  90964. * This version automatically resolves
  90965. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR by getting the
  90966. * verify decoder's state.
  90967. *
  90968. * \param encoder A encoder instance to query.
  90969. * \assert
  90970. * \code encoder != NULL \endcode
  90971. * \retval const char *
  90972. * The encoder state as a C string. Do not modify the contents.
  90973. */
  90974. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder);
  90975. /** Get relevant values about the nature of a verify decoder error.
  90976. * Useful when the stream encoder state is
  90977. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR. The arguments should
  90978. * be addresses in which the stats will be returned, or NULL if value
  90979. * is not desired.
  90980. *
  90981. * \param encoder An encoder instance to query.
  90982. * \param absolute_sample The absolute sample number of the mismatch.
  90983. * \param frame_number The number of the frame in which the mismatch occurred.
  90984. * \param channel The channel in which the mismatch occurred.
  90985. * \param sample The number of the sample (relative to the frame) in
  90986. * which the mismatch occurred.
  90987. * \param expected The expected value for the sample in question.
  90988. * \param got The actual value returned by the decoder.
  90989. * \assert
  90990. * \code encoder != NULL \endcode
  90991. */
  90992. 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);
  90993. /** Get the "verify" flag.
  90994. *
  90995. * \param encoder An encoder instance to query.
  90996. * \assert
  90997. * \code encoder != NULL \endcode
  90998. * \retval FLAC__bool
  90999. * See FLAC__stream_encoder_set_verify().
  91000. */
  91001. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder);
  91002. /** Get the <A HREF="../format.html#subset>Subset</A> flag.
  91003. *
  91004. * \param encoder An encoder instance to query.
  91005. * \assert
  91006. * \code encoder != NULL \endcode
  91007. * \retval FLAC__bool
  91008. * See FLAC__stream_encoder_set_streamable_subset().
  91009. */
  91010. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder);
  91011. /** Get the number of input channels being processed.
  91012. *
  91013. * \param encoder An encoder instance to query.
  91014. * \assert
  91015. * \code encoder != NULL \endcode
  91016. * \retval unsigned
  91017. * See FLAC__stream_encoder_set_channels().
  91018. */
  91019. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder);
  91020. /** Get the input sample resolution setting.
  91021. *
  91022. * \param encoder An encoder instance to query.
  91023. * \assert
  91024. * \code encoder != NULL \endcode
  91025. * \retval unsigned
  91026. * See FLAC__stream_encoder_set_bits_per_sample().
  91027. */
  91028. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder);
  91029. /** Get the input sample rate setting.
  91030. *
  91031. * \param encoder An encoder instance to query.
  91032. * \assert
  91033. * \code encoder != NULL \endcode
  91034. * \retval unsigned
  91035. * See FLAC__stream_encoder_set_sample_rate().
  91036. */
  91037. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder);
  91038. /** Get the blocksize setting.
  91039. *
  91040. * \param encoder An encoder instance to query.
  91041. * \assert
  91042. * \code encoder != NULL \endcode
  91043. * \retval unsigned
  91044. * See FLAC__stream_encoder_set_blocksize().
  91045. */
  91046. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder);
  91047. /** Get the "mid/side stereo coding" flag.
  91048. *
  91049. * \param encoder An encoder instance to query.
  91050. * \assert
  91051. * \code encoder != NULL \endcode
  91052. * \retval FLAC__bool
  91053. * See FLAC__stream_encoder_get_do_mid_side_stereo().
  91054. */
  91055. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  91056. /** Get the "adaptive mid/side switching" flag.
  91057. *
  91058. * \param encoder An encoder instance to query.
  91059. * \assert
  91060. * \code encoder != NULL \endcode
  91061. * \retval FLAC__bool
  91062. * See FLAC__stream_encoder_set_loose_mid_side_stereo().
  91063. */
  91064. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  91065. /** Get the maximum LPC order setting.
  91066. *
  91067. * \param encoder An encoder instance to query.
  91068. * \assert
  91069. * \code encoder != NULL \endcode
  91070. * \retval unsigned
  91071. * See FLAC__stream_encoder_set_max_lpc_order().
  91072. */
  91073. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder);
  91074. /** Get the quantized linear predictor coefficient precision setting.
  91075. *
  91076. * \param encoder An encoder instance to query.
  91077. * \assert
  91078. * \code encoder != NULL \endcode
  91079. * \retval unsigned
  91080. * See FLAC__stream_encoder_set_qlp_coeff_precision().
  91081. */
  91082. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder);
  91083. /** Get the qlp coefficient precision search flag.
  91084. *
  91085. * \param encoder An encoder instance to query.
  91086. * \assert
  91087. * \code encoder != NULL \endcode
  91088. * \retval FLAC__bool
  91089. * See FLAC__stream_encoder_set_do_qlp_coeff_prec_search().
  91090. */
  91091. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder);
  91092. /** Get the "escape coding" flag.
  91093. *
  91094. * \param encoder An encoder instance to query.
  91095. * \assert
  91096. * \code encoder != NULL \endcode
  91097. * \retval FLAC__bool
  91098. * See FLAC__stream_encoder_set_do_escape_coding().
  91099. */
  91100. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder);
  91101. /** Get the exhaustive model search flag.
  91102. *
  91103. * \param encoder An encoder instance to query.
  91104. * \assert
  91105. * \code encoder != NULL \endcode
  91106. * \retval FLAC__bool
  91107. * See FLAC__stream_encoder_set_do_exhaustive_model_search().
  91108. */
  91109. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder);
  91110. /** Get the minimum residual partition order setting.
  91111. *
  91112. * \param encoder An encoder instance to query.
  91113. * \assert
  91114. * \code encoder != NULL \endcode
  91115. * \retval unsigned
  91116. * See FLAC__stream_encoder_set_min_residual_partition_order().
  91117. */
  91118. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder);
  91119. /** Get maximum residual partition order setting.
  91120. *
  91121. * \param encoder An encoder instance to query.
  91122. * \assert
  91123. * \code encoder != NULL \endcode
  91124. * \retval unsigned
  91125. * See FLAC__stream_encoder_set_max_residual_partition_order().
  91126. */
  91127. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder);
  91128. /** Get the Rice parameter search distance setting.
  91129. *
  91130. * \param encoder An encoder instance to query.
  91131. * \assert
  91132. * \code encoder != NULL \endcode
  91133. * \retval unsigned
  91134. * See FLAC__stream_encoder_set_rice_parameter_search_dist().
  91135. */
  91136. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder);
  91137. /** Get the previously set estimate of the total samples to be encoded.
  91138. * The encoder merely mimics back the value given to
  91139. * FLAC__stream_encoder_set_total_samples_estimate() since it has no
  91140. * other way of knowing how many samples the client will encode.
  91141. *
  91142. * \param encoder An encoder instance to set.
  91143. * \assert
  91144. * \code encoder != NULL \endcode
  91145. * \retval FLAC__uint64
  91146. * See FLAC__stream_encoder_get_total_samples_estimate().
  91147. */
  91148. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder);
  91149. /** Initialize the encoder instance to encode native FLAC streams.
  91150. *
  91151. * This flavor of initialization sets up the encoder to encode to a
  91152. * native FLAC stream. I/O is performed via callbacks to the client.
  91153. * For encoding to a plain file via filename or open \c FILE*,
  91154. * FLAC__stream_encoder_init_file() and FLAC__stream_encoder_init_FILE()
  91155. * provide a simpler interface.
  91156. *
  91157. * This function should be called after FLAC__stream_encoder_new() and
  91158. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91159. * or FLAC__stream_encoder_process_interleaved().
  91160. * initialization succeeded.
  91161. *
  91162. * The call to FLAC__stream_encoder_init_stream() currently will also
  91163. * immediately call the write callback several times, once with the \c fLaC
  91164. * signature, and once for each encoded metadata block.
  91165. *
  91166. * \param encoder An uninitialized encoder instance.
  91167. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  91168. * pointer must not be \c NULL.
  91169. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  91170. * pointer may be \c NULL if seeking is not
  91171. * supported. The encoder uses seeking to go back
  91172. * and write some some stream statistics to the
  91173. * STREAMINFO block; this is recommended but not
  91174. * necessary to create a valid FLAC stream. If
  91175. * \a seek_callback is not \c NULL then a
  91176. * \a tell_callback must also be supplied.
  91177. * Alternatively, a dummy seek callback that just
  91178. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  91179. * may also be supplied, all though this is slightly
  91180. * less efficient for the encoder.
  91181. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  91182. * pointer may be \c NULL if seeking is not
  91183. * supported. If \a seek_callback is \c NULL then
  91184. * this argument will be ignored. If
  91185. * \a seek_callback is not \c NULL then a
  91186. * \a tell_callback must also be supplied.
  91187. * Alternatively, a dummy tell callback that just
  91188. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  91189. * may also be supplied, all though this is slightly
  91190. * less efficient for the encoder.
  91191. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  91192. * pointer may be \c NULL if the callback is not
  91193. * desired. If the client provides a seek callback,
  91194. * this function is not necessary as the encoder
  91195. * will automatically seek back and update the
  91196. * STREAMINFO block. It may also be \c NULL if the
  91197. * client does not support seeking, since it will
  91198. * have no way of going back to update the
  91199. * STREAMINFO. However the client can still supply
  91200. * a callback if it would like to know the details
  91201. * from the STREAMINFO.
  91202. * \param client_data This value will be supplied to callbacks in their
  91203. * \a client_data argument.
  91204. * \assert
  91205. * \code encoder != NULL \endcode
  91206. * \retval FLAC__StreamEncoderInitStatus
  91207. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91208. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91209. */
  91210. 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);
  91211. /** Initialize the encoder instance to encode Ogg FLAC streams.
  91212. *
  91213. * This flavor of initialization sets up the encoder to encode to a FLAC
  91214. * stream in an Ogg container. I/O is performed via callbacks to the
  91215. * client. For encoding to a plain file via filename or open \c FILE*,
  91216. * FLAC__stream_encoder_init_ogg_file() and FLAC__stream_encoder_init_ogg_FILE()
  91217. * provide a simpler interface.
  91218. *
  91219. * This function should be called after FLAC__stream_encoder_new() and
  91220. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91221. * or FLAC__stream_encoder_process_interleaved().
  91222. * initialization succeeded.
  91223. *
  91224. * The call to FLAC__stream_encoder_init_ogg_stream() currently will also
  91225. * immediately call the write callback several times to write the metadata
  91226. * packets.
  91227. *
  91228. * \param encoder An uninitialized encoder instance.
  91229. * \param read_callback See FLAC__StreamEncoderReadCallback. This
  91230. * pointer must not be \c NULL if \a seek_callback
  91231. * is non-NULL since they are both needed to be
  91232. * able to write data back to the Ogg FLAC stream
  91233. * in the post-encode phase.
  91234. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  91235. * pointer must not be \c NULL.
  91236. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  91237. * pointer may be \c NULL if seeking is not
  91238. * supported. The encoder uses seeking to go back
  91239. * and write some some stream statistics to the
  91240. * STREAMINFO block; this is recommended but not
  91241. * necessary to create a valid FLAC stream. If
  91242. * \a seek_callback is not \c NULL then a
  91243. * \a tell_callback must also be supplied.
  91244. * Alternatively, a dummy seek callback that just
  91245. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  91246. * may also be supplied, all though this is slightly
  91247. * less efficient for the encoder.
  91248. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  91249. * pointer may be \c NULL if seeking is not
  91250. * supported. If \a seek_callback is \c NULL then
  91251. * this argument will be ignored. If
  91252. * \a seek_callback is not \c NULL then a
  91253. * \a tell_callback must also be supplied.
  91254. * Alternatively, a dummy tell callback that just
  91255. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  91256. * may also be supplied, all though this is slightly
  91257. * less efficient for the encoder.
  91258. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  91259. * pointer may be \c NULL if the callback is not
  91260. * desired. If the client provides a seek callback,
  91261. * this function is not necessary as the encoder
  91262. * will automatically seek back and update the
  91263. * STREAMINFO block. It may also be \c NULL if the
  91264. * client does not support seeking, since it will
  91265. * have no way of going back to update the
  91266. * STREAMINFO. However the client can still supply
  91267. * a callback if it would like to know the details
  91268. * from the STREAMINFO.
  91269. * \param client_data This value will be supplied to callbacks in their
  91270. * \a client_data argument.
  91271. * \assert
  91272. * \code encoder != NULL \endcode
  91273. * \retval FLAC__StreamEncoderInitStatus
  91274. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91275. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91276. */
  91277. 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);
  91278. /** Initialize the encoder instance to encode native FLAC files.
  91279. *
  91280. * This flavor of initialization sets up the encoder to encode to a
  91281. * plain native FLAC file. For non-stdio streams, you must use
  91282. * FLAC__stream_encoder_init_stream() and provide callbacks for the I/O.
  91283. *
  91284. * This function should be called after FLAC__stream_encoder_new() and
  91285. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91286. * or FLAC__stream_encoder_process_interleaved().
  91287. * initialization succeeded.
  91288. *
  91289. * \param encoder An uninitialized encoder instance.
  91290. * \param file An open file. The file should have been opened
  91291. * with mode \c "w+b" and rewound. The file
  91292. * becomes owned by the encoder and should not be
  91293. * manipulated by the client while encoding.
  91294. * Unless \a file is \c stdout, it will be closed
  91295. * when FLAC__stream_encoder_finish() is called.
  91296. * Note however that a proper SEEKTABLE cannot be
  91297. * created when encoding to \c stdout since it is
  91298. * not seekable.
  91299. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  91300. * pointer may be \c NULL if the callback is not
  91301. * desired.
  91302. * \param client_data This value will be supplied to callbacks in their
  91303. * \a client_data argument.
  91304. * \assert
  91305. * \code encoder != NULL \endcode
  91306. * \code file != NULL \endcode
  91307. * \retval FLAC__StreamEncoderInitStatus
  91308. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91309. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91310. */
  91311. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  91312. /** Initialize the encoder instance to encode Ogg FLAC files.
  91313. *
  91314. * This flavor of initialization sets up the encoder to encode to a
  91315. * plain Ogg FLAC file. For non-stdio streams, you must use
  91316. * FLAC__stream_encoder_init_ogg_stream() and provide callbacks for the I/O.
  91317. *
  91318. * This function should be called after FLAC__stream_encoder_new() and
  91319. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91320. * or FLAC__stream_encoder_process_interleaved().
  91321. * initialization succeeded.
  91322. *
  91323. * \param encoder An uninitialized encoder instance.
  91324. * \param file An open file. The file should have been opened
  91325. * with mode \c "w+b" and rewound. The file
  91326. * becomes owned by the encoder and should not be
  91327. * manipulated by the client while encoding.
  91328. * Unless \a file is \c stdout, it will be closed
  91329. * when FLAC__stream_encoder_finish() is called.
  91330. * Note however that a proper SEEKTABLE cannot be
  91331. * created when encoding to \c stdout since it is
  91332. * not seekable.
  91333. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  91334. * pointer may be \c NULL if the callback is not
  91335. * desired.
  91336. * \param client_data This value will be supplied to callbacks in their
  91337. * \a client_data argument.
  91338. * \assert
  91339. * \code encoder != NULL \endcode
  91340. * \code file != NULL \endcode
  91341. * \retval FLAC__StreamEncoderInitStatus
  91342. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91343. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91344. */
  91345. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  91346. /** Initialize the encoder instance to encode native FLAC files.
  91347. *
  91348. * This flavor of initialization sets up the encoder to encode to a plain
  91349. * FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  91350. * with Unicode filenames on Windows), you must use
  91351. * FLAC__stream_encoder_init_FILE(), or FLAC__stream_encoder_init_stream()
  91352. * and provide callbacks for the I/O.
  91353. *
  91354. * This function should be called after FLAC__stream_encoder_new() and
  91355. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91356. * or FLAC__stream_encoder_process_interleaved().
  91357. * initialization succeeded.
  91358. *
  91359. * \param encoder An uninitialized encoder instance.
  91360. * \param filename The name of the file to encode to. The file will
  91361. * be opened with fopen(). Use \c NULL to encode to
  91362. * \c stdout. Note however that a proper SEEKTABLE
  91363. * cannot be created when encoding to \c stdout since
  91364. * it is not seekable.
  91365. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  91366. * pointer may be \c NULL if the callback is not
  91367. * desired.
  91368. * \param client_data This value will be supplied to callbacks in their
  91369. * \a client_data argument.
  91370. * \assert
  91371. * \code encoder != NULL \endcode
  91372. * \retval FLAC__StreamEncoderInitStatus
  91373. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91374. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91375. */
  91376. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  91377. /** Initialize the encoder instance to encode Ogg FLAC files.
  91378. *
  91379. * This flavor of initialization sets up the encoder to encode to a plain
  91380. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  91381. * with Unicode filenames on Windows), you must use
  91382. * FLAC__stream_encoder_init_ogg_FILE(), or FLAC__stream_encoder_init_ogg_stream()
  91383. * and provide callbacks for the I/O.
  91384. *
  91385. * This function should be called after FLAC__stream_encoder_new() and
  91386. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91387. * or FLAC__stream_encoder_process_interleaved().
  91388. * initialization succeeded.
  91389. *
  91390. * \param encoder An uninitialized encoder instance.
  91391. * \param filename The name of the file to encode to. The file will
  91392. * be opened with fopen(). Use \c NULL to encode to
  91393. * \c stdout. Note however that a proper SEEKTABLE
  91394. * cannot be created when encoding to \c stdout since
  91395. * it is not seekable.
  91396. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  91397. * pointer may be \c NULL if the callback is not
  91398. * desired.
  91399. * \param client_data This value will be supplied to callbacks in their
  91400. * \a client_data argument.
  91401. * \assert
  91402. * \code encoder != NULL \endcode
  91403. * \retval FLAC__StreamEncoderInitStatus
  91404. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91405. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91406. */
  91407. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  91408. /** Finish the encoding process.
  91409. * Flushes the encoding buffer, releases resources, resets the encoder
  91410. * settings to their defaults, and returns the encoder state to
  91411. * FLAC__STREAM_ENCODER_UNINITIALIZED. Note that this can generate
  91412. * one or more write callbacks before returning, and will generate
  91413. * a metadata callback.
  91414. *
  91415. * Note that in the course of processing the last frame, errors can
  91416. * occur, so the caller should be sure to check the return value to
  91417. * ensure the file was encoded properly.
  91418. *
  91419. * In the event of a prematurely-terminated encode, it is not strictly
  91420. * necessary to call this immediately before FLAC__stream_encoder_delete()
  91421. * but it is good practice to match every FLAC__stream_encoder_init_*()
  91422. * with a FLAC__stream_encoder_finish().
  91423. *
  91424. * \param encoder An uninitialized encoder instance.
  91425. * \assert
  91426. * \code encoder != NULL \endcode
  91427. * \retval FLAC__bool
  91428. * \c false if an error occurred processing the last frame; or if verify
  91429. * mode is set (see FLAC__stream_encoder_set_verify()), there was a
  91430. * verify mismatch; else \c true. If \c false, caller should check the
  91431. * state with FLAC__stream_encoder_get_state() for more information
  91432. * about the error.
  91433. */
  91434. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder);
  91435. /** Submit data for encoding.
  91436. * This version allows you to supply the input data via an array of
  91437. * pointers, each pointer pointing to an array of \a samples samples
  91438. * representing one channel. The samples need not be block-aligned,
  91439. * but each channel should have the same number of samples. Each sample
  91440. * should be a signed integer, right-justified to the resolution set by
  91441. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  91442. * resolution is 16 bits per sample, the samples should all be in the
  91443. * range [-32768,32767].
  91444. *
  91445. * For applications where channel order is important, channels must
  91446. * follow the order as described in the
  91447. * <A HREF="../format.html#frame_header">frame header</A>.
  91448. *
  91449. * \param encoder An initialized encoder instance in the OK state.
  91450. * \param buffer An array of pointers to each channel's signal.
  91451. * \param samples The number of samples in one channel.
  91452. * \assert
  91453. * \code encoder != NULL \endcode
  91454. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  91455. * \retval FLAC__bool
  91456. * \c true if successful, else \c false; in this case, check the
  91457. * encoder state with FLAC__stream_encoder_get_state() to see what
  91458. * went wrong.
  91459. */
  91460. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples);
  91461. /** Submit data for encoding.
  91462. * This version allows you to supply the input data where the channels
  91463. * are interleaved into a single array (i.e. channel0_sample0,
  91464. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  91465. * The samples need not be block-aligned but they must be
  91466. * sample-aligned, i.e. the first value should be channel0_sample0
  91467. * and the last value channelN_sampleM. Each sample should be a signed
  91468. * integer, right-justified to the resolution set by
  91469. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  91470. * resolution is 16 bits per sample, the samples should all be in the
  91471. * range [-32768,32767].
  91472. *
  91473. * For applications where channel order is important, channels must
  91474. * follow the order as described in the
  91475. * <A HREF="../format.html#frame_header">frame header</A>.
  91476. *
  91477. * \param encoder An initialized encoder instance in the OK state.
  91478. * \param buffer An array of channel-interleaved data (see above).
  91479. * \param samples The number of samples in one channel, the same as for
  91480. * FLAC__stream_encoder_process(). For example, if
  91481. * encoding two channels, \c 1000 \a samples corresponds
  91482. * to a \a buffer of 2000 values.
  91483. * \assert
  91484. * \code encoder != NULL \endcode
  91485. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  91486. * \retval FLAC__bool
  91487. * \c true if successful, else \c false; in this case, check the
  91488. * encoder state with FLAC__stream_encoder_get_state() to see what
  91489. * went wrong.
  91490. */
  91491. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples);
  91492. /* \} */
  91493. #ifdef __cplusplus
  91494. }
  91495. #endif
  91496. #endif
  91497. /*** End of inlined file: stream_encoder.h ***/
  91498. #ifdef _MSC_VER
  91499. /* OPT: an MSVC built-in would be better */
  91500. static _inline FLAC__uint32 local_swap32_(FLAC__uint32 x)
  91501. {
  91502. x = ((x<<8)&0xFF00FF00) | ((x>>8)&0x00FF00FF);
  91503. return (x>>16) | (x<<16);
  91504. }
  91505. #endif
  91506. #if defined(_MSC_VER) && defined(_X86_)
  91507. /* OPT: an MSVC built-in would be better */
  91508. static void local_swap32_block_(FLAC__uint32 *start, FLAC__uint32 len)
  91509. {
  91510. __asm {
  91511. mov edx, start
  91512. mov ecx, len
  91513. test ecx, ecx
  91514. loop1:
  91515. jz done1
  91516. mov eax, [edx]
  91517. bswap eax
  91518. mov [edx], eax
  91519. add edx, 4
  91520. dec ecx
  91521. jmp short loop1
  91522. done1:
  91523. }
  91524. }
  91525. #endif
  91526. /** \mainpage
  91527. *
  91528. * \section intro Introduction
  91529. *
  91530. * This is the documentation for the FLAC C and C++ APIs. It is
  91531. * highly interconnected; this introduction should give you a top
  91532. * level idea of the structure and how to find the information you
  91533. * need. As a prerequisite you should have at least a basic
  91534. * knowledge of the FLAC format, documented
  91535. * <A HREF="../format.html">here</A>.
  91536. *
  91537. * \section c_api FLAC C API
  91538. *
  91539. * The FLAC C API is the interface to libFLAC, a set of structures
  91540. * describing the components of FLAC streams, and functions for
  91541. * encoding and decoding streams, as well as manipulating FLAC
  91542. * metadata in files. The public include files will be installed
  91543. * in your include area (for example /usr/include/FLAC/...).
  91544. *
  91545. * By writing a little code and linking against libFLAC, it is
  91546. * relatively easy to add FLAC support to another program. The
  91547. * library is licensed under <A HREF="../license.html">Xiph's BSD license</A>.
  91548. * Complete source code of libFLAC as well as the command-line
  91549. * encoder and plugins is available and is a useful source of
  91550. * examples.
  91551. *
  91552. * Aside from encoders and decoders, libFLAC provides a powerful
  91553. * metadata interface for manipulating metadata in FLAC files. It
  91554. * allows the user to add, delete, and modify FLAC metadata blocks
  91555. * and it can automatically take advantage of PADDING blocks to avoid
  91556. * rewriting the entire FLAC file when changing the size of the
  91557. * metadata.
  91558. *
  91559. * libFLAC usually only requires the standard C library and C math
  91560. * library. In particular, threading is not used so there is no
  91561. * dependency on a thread library. However, libFLAC does not use
  91562. * global variables and should be thread-safe.
  91563. *
  91564. * libFLAC also supports encoding to and decoding from Ogg FLAC.
  91565. * However the metadata editing interfaces currently have limited
  91566. * read-only support for Ogg FLAC files.
  91567. *
  91568. * \section cpp_api FLAC C++ API
  91569. *
  91570. * The FLAC C++ API is a set of classes that encapsulate the
  91571. * structures and functions in libFLAC. They provide slightly more
  91572. * functionality with respect to metadata but are otherwise
  91573. * equivalent. For the most part, they share the same usage as
  91574. * their counterparts in libFLAC, and the FLAC C API documentation
  91575. * can be used as a supplement. The public include files
  91576. * for the C++ API will be installed in your include area (for
  91577. * example /usr/include/FLAC++/...).
  91578. *
  91579. * libFLAC++ is also licensed under
  91580. * <A HREF="../license.html">Xiph's BSD license</A>.
  91581. *
  91582. * \section getting_started Getting Started
  91583. *
  91584. * A good starting point for learning the API is to browse through
  91585. * the <A HREF="modules.html">modules</A>. Modules are logical
  91586. * groupings of related functions or classes, which correspond roughly
  91587. * to header files or sections of header files. Each module includes a
  91588. * detailed description of the general usage of its functions or
  91589. * classes.
  91590. *
  91591. * From there you can go on to look at the documentation of
  91592. * individual functions. You can see different views of the individual
  91593. * functions through the links in top bar across this page.
  91594. *
  91595. * If you prefer a more hands-on approach, you can jump right to some
  91596. * <A HREF="../documentation_example_code.html">example code</A>.
  91597. *
  91598. * \section porting_guide Porting Guide
  91599. *
  91600. * Starting with FLAC 1.1.3 a \link porting Porting Guide \endlink
  91601. * has been introduced which gives detailed instructions on how to
  91602. * port your code to newer versions of FLAC.
  91603. *
  91604. * \section embedded_developers Embedded Developers
  91605. *
  91606. * libFLAC has grown larger over time as more functionality has been
  91607. * included, but much of it may be unnecessary for a particular embedded
  91608. * implementation. Unused parts may be pruned by some simple editing of
  91609. * src/libFLAC/Makefile.am. In general, the decoders, encoders, and
  91610. * metadata interface are all independent from each other.
  91611. *
  91612. * It is easiest to just describe the dependencies:
  91613. *
  91614. * - All modules depend on the \link flac_format Format \endlink module.
  91615. * - The decoders and encoders depend on the bitbuffer.
  91616. * - The decoder is independent of the encoder. The encoder uses the
  91617. * decoder because of the verify feature, but this can be removed if
  91618. * not needed.
  91619. * - Parts of the metadata interface require the stream decoder (but not
  91620. * the encoder).
  91621. * - Ogg support is selectable through the compile time macro
  91622. * \c FLAC__HAS_OGG.
  91623. *
  91624. * For example, if your application only requires the stream decoder, no
  91625. * encoder, and no metadata interface, you can remove the stream encoder
  91626. * and the metadata interface, which will greatly reduce the size of the
  91627. * library.
  91628. *
  91629. * Also, there are several places in the libFLAC code with comments marked
  91630. * with "OPT:" where a #define can be changed to enable code that might be
  91631. * faster on a specific platform. Experimenting with these can yield faster
  91632. * binaries.
  91633. */
  91634. /** \defgroup porting Porting Guide for New Versions
  91635. *
  91636. * This module describes differences in the library interfaces from
  91637. * version to version. It assists in the porting of code that uses
  91638. * the libraries to newer versions of FLAC.
  91639. *
  91640. * One simple facility for making porting easier that has been added
  91641. * in FLAC 1.1.3 is a set of \c #defines in \c export.h of each
  91642. * library's includes (e.g. \c include/FLAC/export.h). The
  91643. * \c #defines mirror the libraries'
  91644. * <A HREF="http://www.gnu.org/software/libtool/manual.html#Libtool-versioning">libtool version numbers</A>,
  91645. * e.g. in libFLAC there are \c FLAC_API_VERSION_CURRENT,
  91646. * \c FLAC_API_VERSION_REVISION, and \c FLAC_API_VERSION_AGE.
  91647. * These can be used to support multiple versions of an API during the
  91648. * transition phase, e.g.
  91649. *
  91650. * \code
  91651. * #if !defined(FLAC_API_VERSION_CURRENT) || FLAC_API_VERSION_CURRENT <= 7
  91652. * legacy code
  91653. * #else
  91654. * new code
  91655. * #endif
  91656. * \endcode
  91657. *
  91658. * The the source will work for multiple versions and the legacy code can
  91659. * easily be removed when the transition is complete.
  91660. *
  91661. * Another available symbol is FLAC_API_SUPPORTS_OGG_FLAC (defined in
  91662. * include/FLAC/export.h), which can be used to determine whether or not
  91663. * the library has been compiled with support for Ogg FLAC. This is
  91664. * simpler than trying to call an Ogg init function and catching the
  91665. * error.
  91666. */
  91667. /** \defgroup porting_1_1_2_to_1_1_3 Porting from FLAC 1.1.2 to 1.1.3
  91668. * \ingroup porting
  91669. *
  91670. * \brief
  91671. * This module describes porting from FLAC 1.1.2 to FLAC 1.1.3.
  91672. *
  91673. * The main change between the APIs in 1.1.2 and 1.1.3 is that they have
  91674. * been simplified. First, libOggFLAC has been merged into libFLAC and
  91675. * libOggFLAC++ has been merged into libFLAC++. Second, both the three
  91676. * decoding layers and three encoding layers have been merged into a
  91677. * single stream decoder and stream encoder. That is, the functionality
  91678. * of FLAC__SeekableStreamDecoder and FLAC__FileDecoder has been merged
  91679. * into FLAC__StreamDecoder, and FLAC__SeekableStreamEncoder and
  91680. * FLAC__FileEncoder into FLAC__StreamEncoder. Only the
  91681. * FLAC__StreamDecoder and FLAC__StreamEncoder remain. What this means
  91682. * is there is now a single API that can be used to encode or decode
  91683. * streams to/from native FLAC or Ogg FLAC and the single API can work
  91684. * on both seekable and non-seekable streams.
  91685. *
  91686. * Instead of creating an encoder or decoder of a certain layer, now the
  91687. * client will always create a FLAC__StreamEncoder or
  91688. * FLAC__StreamDecoder. The old layers are now differentiated by the
  91689. * initialization function. For example, for the decoder,
  91690. * FLAC__stream_decoder_init() has been replaced by
  91691. * FLAC__stream_decoder_init_stream(). This init function takes
  91692. * callbacks for the I/O, and the seeking callbacks are optional. This
  91693. * allows the client to use the same object for seekable and
  91694. * non-seekable streams. For decoding a FLAC file directly, the client
  91695. * can use FLAC__stream_decoder_init_file() and pass just a filename
  91696. * and fewer callbacks; most of the other callbacks are supplied
  91697. * internally. For situations where fopen()ing by filename is not
  91698. * possible (e.g. Unicode filenames on Windows) the client can instead
  91699. * open the file itself and supply the FILE* to
  91700. * FLAC__stream_decoder_init_FILE(). The init functions now returns a
  91701. * FLAC__StreamDecoderInitStatus instead of FLAC__StreamDecoderState.
  91702. * Since the callbacks and client data are now passed to the init
  91703. * function, the FLAC__stream_decoder_set_*_callback() functions and
  91704. * FLAC__stream_decoder_set_client_data() are no longer needed. The
  91705. * rest of the calls to the decoder are the same as before.
  91706. *
  91707. * There are counterpart init functions for Ogg FLAC, e.g.
  91708. * FLAC__stream_decoder_init_ogg_stream(). All the rest of the calls
  91709. * and callbacks are the same as for native FLAC.
  91710. *
  91711. * As an example, in FLAC 1.1.2 a seekable stream decoder would have
  91712. * been set up like so:
  91713. *
  91714. * \code
  91715. * FLAC__SeekableStreamDecoder *decoder = FLAC__seekable_stream_decoder_new();
  91716. * if(decoder == NULL) do_something;
  91717. * FLAC__seekable_stream_decoder_set_md5_checking(decoder, true);
  91718. * [... other settings ...]
  91719. * FLAC__seekable_stream_decoder_set_read_callback(decoder, my_read_callback);
  91720. * FLAC__seekable_stream_decoder_set_seek_callback(decoder, my_seek_callback);
  91721. * FLAC__seekable_stream_decoder_set_tell_callback(decoder, my_tell_callback);
  91722. * FLAC__seekable_stream_decoder_set_length_callback(decoder, my_length_callback);
  91723. * FLAC__seekable_stream_decoder_set_eof_callback(decoder, my_eof_callback);
  91724. * FLAC__seekable_stream_decoder_set_write_callback(decoder, my_write_callback);
  91725. * FLAC__seekable_stream_decoder_set_metadata_callback(decoder, my_metadata_callback);
  91726. * FLAC__seekable_stream_decoder_set_error_callback(decoder, my_error_callback);
  91727. * FLAC__seekable_stream_decoder_set_client_data(decoder, my_client_data);
  91728. * if(FLAC__seekable_stream_decoder_init(decoder) != FLAC__SEEKABLE_STREAM_DECODER_OK) do_something;
  91729. * \endcode
  91730. *
  91731. * In FLAC 1.1.3 it is like this:
  91732. *
  91733. * \code
  91734. * FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new();
  91735. * if(decoder == NULL) do_something;
  91736. * FLAC__stream_decoder_set_md5_checking(decoder, true);
  91737. * [... other settings ...]
  91738. * if(FLAC__stream_decoder_init_stream(
  91739. * decoder,
  91740. * my_read_callback,
  91741. * my_seek_callback, // or NULL
  91742. * my_tell_callback, // or NULL
  91743. * my_length_callback, // or NULL
  91744. * my_eof_callback, // or NULL
  91745. * my_write_callback,
  91746. * my_metadata_callback, // or NULL
  91747. * my_error_callback,
  91748. * my_client_data
  91749. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  91750. * \endcode
  91751. *
  91752. * or you could do;
  91753. *
  91754. * \code
  91755. * [...]
  91756. * FILE *file = fopen("somefile.flac","rb");
  91757. * if(file == NULL) do_somthing;
  91758. * if(FLAC__stream_decoder_init_FILE(
  91759. * decoder,
  91760. * file,
  91761. * my_write_callback,
  91762. * my_metadata_callback, // or NULL
  91763. * my_error_callback,
  91764. * my_client_data
  91765. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  91766. * \endcode
  91767. *
  91768. * or just:
  91769. *
  91770. * \code
  91771. * [...]
  91772. * if(FLAC__stream_decoder_init_file(
  91773. * decoder,
  91774. * "somefile.flac",
  91775. * my_write_callback,
  91776. * my_metadata_callback, // or NULL
  91777. * my_error_callback,
  91778. * my_client_data
  91779. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  91780. * \endcode
  91781. *
  91782. * Another small change to the decoder is in how it handles unparseable
  91783. * streams. Before, when the decoder found an unparseable stream
  91784. * (reserved for when the decoder encounters a stream from a future
  91785. * encoder that it can't parse), it changed the state to
  91786. * \c FLAC__STREAM_DECODER_UNPARSEABLE_STREAM. Now the decoder instead
  91787. * drops sync and calls the error callback with a new error code
  91788. * \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM. This is
  91789. * more robust. If your error callback does not discriminate on the the
  91790. * error state, your code does not need to be changed.
  91791. *
  91792. * The encoder now has a new setting:
  91793. * FLAC__stream_encoder_set_apodization(). This is for setting the
  91794. * method used to window the data before LPC analysis. You only need to
  91795. * add a call to this function if the default is not suitable. There
  91796. * are also two new convenience functions that may be useful:
  91797. * FLAC__metadata_object_cuesheet_calculate_cddb_id() and
  91798. * FLAC__metadata_get_cuesheet().
  91799. *
  91800. * The \a bytes parameter to FLAC__StreamDecoderReadCallback,
  91801. * FLAC__StreamEncoderReadCallback, and FLAC__StreamEncoderWriteCallback
  91802. * is now \c size_t instead of \c unsigned.
  91803. */
  91804. /** \defgroup porting_1_1_3_to_1_1_4 Porting from FLAC 1.1.3 to 1.1.4
  91805. * \ingroup porting
  91806. *
  91807. * \brief
  91808. * This module describes porting from FLAC 1.1.3 to FLAC 1.1.4.
  91809. *
  91810. * There were no changes to any of the interfaces from 1.1.3 to 1.1.4.
  91811. * There was a slight change in the implementation of
  91812. * FLAC__stream_encoder_set_metadata(); the function now makes a copy
  91813. * of the \a metadata array of pointers so the client no longer needs
  91814. * to maintain it after the call. The objects themselves that are
  91815. * pointed to by the array are still not copied though and must be
  91816. * maintained until the call to FLAC__stream_encoder_finish().
  91817. */
  91818. /** \defgroup porting_1_1_4_to_1_2_0 Porting from FLAC 1.1.4 to 1.2.0
  91819. * \ingroup porting
  91820. *
  91821. * \brief
  91822. * This module describes porting from FLAC 1.1.4 to FLAC 1.2.0.
  91823. *
  91824. * There were only very minor changes to the interfaces from 1.1.4 to 1.2.0.
  91825. * In libFLAC, \c FLAC__format_sample_rate_is_subset() was added.
  91826. * In libFLAC++, \c FLAC::Decoder::Stream::get_decode_position() was added.
  91827. *
  91828. * Finally, value of the constant \c FLAC__FRAME_HEADER_RESERVED_LEN
  91829. * has changed to reflect the conversion of one of the reserved bits
  91830. * into active use. It used to be \c 2 and now is \c 1. However the
  91831. * FLAC frame header length has not changed, so to skip the proper
  91832. * number of bits, use \c FLAC__FRAME_HEADER_RESERVED_LEN +
  91833. * \c FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN
  91834. */
  91835. /** \defgroup flac FLAC C API
  91836. *
  91837. * The FLAC C API is the interface to libFLAC, a set of structures
  91838. * describing the components of FLAC streams, and functions for
  91839. * encoding and decoding streams, as well as manipulating FLAC
  91840. * metadata in files.
  91841. *
  91842. * You should start with the format components as all other modules
  91843. * are dependent on it.
  91844. */
  91845. #endif
  91846. /*** End of inlined file: all.h ***/
  91847. /*** Start of inlined file: bitmath.c ***/
  91848. /*** Start of inlined file: juce_FlacHeader.h ***/
  91849. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  91850. // tasks..
  91851. #define VERSION "1.2.1"
  91852. #define FLAC__NO_DLL 1
  91853. #if JUCE_MSVC
  91854. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  91855. #endif
  91856. #if JUCE_MAC
  91857. #define FLAC__SYS_DARWIN 1
  91858. #endif
  91859. /*** End of inlined file: juce_FlacHeader.h ***/
  91860. #if JUCE_USE_FLAC
  91861. #if HAVE_CONFIG_H
  91862. # include <config.h>
  91863. #endif
  91864. /*** Start of inlined file: bitmath.h ***/
  91865. #ifndef FLAC__PRIVATE__BITMATH_H
  91866. #define FLAC__PRIVATE__BITMATH_H
  91867. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v);
  91868. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v);
  91869. unsigned FLAC__bitmath_silog2(int v);
  91870. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v);
  91871. #endif
  91872. /*** End of inlined file: bitmath.h ***/
  91873. /* An example of what FLAC__bitmath_ilog2() computes:
  91874. *
  91875. * ilog2( 0) = assertion failure
  91876. * ilog2( 1) = 0
  91877. * ilog2( 2) = 1
  91878. * ilog2( 3) = 1
  91879. * ilog2( 4) = 2
  91880. * ilog2( 5) = 2
  91881. * ilog2( 6) = 2
  91882. * ilog2( 7) = 2
  91883. * ilog2( 8) = 3
  91884. * ilog2( 9) = 3
  91885. * ilog2(10) = 3
  91886. * ilog2(11) = 3
  91887. * ilog2(12) = 3
  91888. * ilog2(13) = 3
  91889. * ilog2(14) = 3
  91890. * ilog2(15) = 3
  91891. * ilog2(16) = 4
  91892. * ilog2(17) = 4
  91893. * ilog2(18) = 4
  91894. */
  91895. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v)
  91896. {
  91897. unsigned l = 0;
  91898. FLAC__ASSERT(v > 0);
  91899. while(v >>= 1)
  91900. l++;
  91901. return l;
  91902. }
  91903. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v)
  91904. {
  91905. unsigned l = 0;
  91906. FLAC__ASSERT(v > 0);
  91907. while(v >>= 1)
  91908. l++;
  91909. return l;
  91910. }
  91911. /* An example of what FLAC__bitmath_silog2() computes:
  91912. *
  91913. * silog2(-10) = 5
  91914. * silog2(- 9) = 5
  91915. * silog2(- 8) = 4
  91916. * silog2(- 7) = 4
  91917. * silog2(- 6) = 4
  91918. * silog2(- 5) = 4
  91919. * silog2(- 4) = 3
  91920. * silog2(- 3) = 3
  91921. * silog2(- 2) = 2
  91922. * silog2(- 1) = 2
  91923. * silog2( 0) = 0
  91924. * silog2( 1) = 2
  91925. * silog2( 2) = 3
  91926. * silog2( 3) = 3
  91927. * silog2( 4) = 4
  91928. * silog2( 5) = 4
  91929. * silog2( 6) = 4
  91930. * silog2( 7) = 4
  91931. * silog2( 8) = 5
  91932. * silog2( 9) = 5
  91933. * silog2( 10) = 5
  91934. */
  91935. unsigned FLAC__bitmath_silog2(int v)
  91936. {
  91937. while(1) {
  91938. if(v == 0) {
  91939. return 0;
  91940. }
  91941. else if(v > 0) {
  91942. unsigned l = 0;
  91943. while(v) {
  91944. l++;
  91945. v >>= 1;
  91946. }
  91947. return l+1;
  91948. }
  91949. else if(v == -1) {
  91950. return 2;
  91951. }
  91952. else {
  91953. v++;
  91954. v = -v;
  91955. }
  91956. }
  91957. }
  91958. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v)
  91959. {
  91960. while(1) {
  91961. if(v == 0) {
  91962. return 0;
  91963. }
  91964. else if(v > 0) {
  91965. unsigned l = 0;
  91966. while(v) {
  91967. l++;
  91968. v >>= 1;
  91969. }
  91970. return l+1;
  91971. }
  91972. else if(v == -1) {
  91973. return 2;
  91974. }
  91975. else {
  91976. v++;
  91977. v = -v;
  91978. }
  91979. }
  91980. }
  91981. #endif
  91982. /*** End of inlined file: bitmath.c ***/
  91983. /*** Start of inlined file: bitreader.c ***/
  91984. /*** Start of inlined file: juce_FlacHeader.h ***/
  91985. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  91986. // tasks..
  91987. #define VERSION "1.2.1"
  91988. #define FLAC__NO_DLL 1
  91989. #if JUCE_MSVC
  91990. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  91991. #endif
  91992. #if JUCE_MAC
  91993. #define FLAC__SYS_DARWIN 1
  91994. #endif
  91995. /*** End of inlined file: juce_FlacHeader.h ***/
  91996. #if JUCE_USE_FLAC
  91997. #if HAVE_CONFIG_H
  91998. # include <config.h>
  91999. #endif
  92000. #include <stdlib.h> /* for malloc() */
  92001. #include <string.h> /* for memcpy(), memset() */
  92002. #ifdef _MSC_VER
  92003. #include <winsock.h> /* for ntohl() */
  92004. #elif defined FLAC__SYS_DARWIN
  92005. #include <machine/endian.h> /* for ntohl() */
  92006. #elif defined __MINGW32__
  92007. #include <winsock.h> /* for ntohl() */
  92008. #else
  92009. #include <netinet/in.h> /* for ntohl() */
  92010. #endif
  92011. /*** Start of inlined file: bitreader.h ***/
  92012. #ifndef FLAC__PRIVATE__BITREADER_H
  92013. #define FLAC__PRIVATE__BITREADER_H
  92014. #include <stdio.h> /* for FILE */
  92015. /*** Start of inlined file: cpu.h ***/
  92016. #ifndef FLAC__PRIVATE__CPU_H
  92017. #define FLAC__PRIVATE__CPU_H
  92018. #ifdef HAVE_CONFIG_H
  92019. #include <config.h>
  92020. #endif
  92021. typedef enum {
  92022. FLAC__CPUINFO_TYPE_IA32,
  92023. FLAC__CPUINFO_TYPE_PPC,
  92024. FLAC__CPUINFO_TYPE_UNKNOWN
  92025. } FLAC__CPUInfo_Type;
  92026. typedef struct {
  92027. FLAC__bool cpuid;
  92028. FLAC__bool bswap;
  92029. FLAC__bool cmov;
  92030. FLAC__bool mmx;
  92031. FLAC__bool fxsr;
  92032. FLAC__bool sse;
  92033. FLAC__bool sse2;
  92034. FLAC__bool sse3;
  92035. FLAC__bool ssse3;
  92036. FLAC__bool _3dnow;
  92037. FLAC__bool ext3dnow;
  92038. FLAC__bool extmmx;
  92039. } FLAC__CPUInfo_IA32;
  92040. typedef struct {
  92041. FLAC__bool altivec;
  92042. FLAC__bool ppc64;
  92043. } FLAC__CPUInfo_PPC;
  92044. typedef struct {
  92045. FLAC__bool use_asm;
  92046. FLAC__CPUInfo_Type type;
  92047. union {
  92048. FLAC__CPUInfo_IA32 ia32;
  92049. FLAC__CPUInfo_PPC ppc;
  92050. } data;
  92051. } FLAC__CPUInfo;
  92052. void FLAC__cpu_info(FLAC__CPUInfo *info);
  92053. #ifndef FLAC__NO_ASM
  92054. #ifdef FLAC__CPU_IA32
  92055. #ifdef FLAC__HAS_NASM
  92056. FLAC__uint32 FLAC__cpu_have_cpuid_asm_ia32(void);
  92057. void FLAC__cpu_info_asm_ia32(FLAC__uint32 *flags_edx, FLAC__uint32 *flags_ecx);
  92058. FLAC__uint32 FLAC__cpu_info_extended_amd_asm_ia32(void);
  92059. #endif
  92060. #endif
  92061. #endif
  92062. #endif
  92063. /*** End of inlined file: cpu.h ***/
  92064. /*
  92065. * opaque structure definition
  92066. */
  92067. struct FLAC__BitReader;
  92068. typedef struct FLAC__BitReader FLAC__BitReader;
  92069. typedef FLAC__bool (*FLAC__BitReaderReadCallback)(FLAC__byte buffer[], size_t *bytes, void *client_data);
  92070. /*
  92071. * construction, deletion, initialization, etc functions
  92072. */
  92073. FLAC__BitReader *FLAC__bitreader_new(void);
  92074. void FLAC__bitreader_delete(FLAC__BitReader *br);
  92075. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd);
  92076. void FLAC__bitreader_free(FLAC__BitReader *br); /* does not 'free(br)' */
  92077. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br);
  92078. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out);
  92079. /*
  92080. * CRC functions
  92081. */
  92082. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed);
  92083. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br);
  92084. /*
  92085. * info functions
  92086. */
  92087. FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br);
  92088. unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br);
  92089. unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br);
  92090. /*
  92091. * read functions
  92092. */
  92093. FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits);
  92094. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits);
  92095. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits);
  92096. FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val); /*only for bits=32*/
  92097. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits); /* WATCHOUT: does not CRC the skipped data! */ /*@@@@ add to unit tests */
  92098. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals); /* WATCHOUT: does not CRC the read data! */
  92099. 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! */
  92100. FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val);
  92101. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  92102. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  92103. #ifndef FLAC__NO_ASM
  92104. # ifdef FLAC__CPU_IA32
  92105. # ifdef FLAC__HAS_NASM
  92106. FLAC__bool FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  92107. # endif
  92108. # endif
  92109. #endif
  92110. #if 0 /* UNUSED */
  92111. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  92112. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter);
  92113. #endif
  92114. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen);
  92115. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen);
  92116. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br);
  92117. #endif
  92118. /*** End of inlined file: bitreader.h ***/
  92119. /*** Start of inlined file: crc.h ***/
  92120. #ifndef FLAC__PRIVATE__CRC_H
  92121. #define FLAC__PRIVATE__CRC_H
  92122. /* 8 bit CRC generator, MSB shifted first
  92123. ** polynomial = x^8 + x^2 + x^1 + x^0
  92124. ** init = 0
  92125. */
  92126. extern FLAC__byte const FLAC__crc8_table[256];
  92127. #define FLAC__CRC8_UPDATE(data, crc) (crc) = FLAC__crc8_table[(crc) ^ (data)];
  92128. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc);
  92129. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc);
  92130. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len);
  92131. /* 16 bit CRC generator, MSB shifted first
  92132. ** polynomial = x^16 + x^15 + x^2 + x^0
  92133. ** init = 0
  92134. */
  92135. extern unsigned FLAC__crc16_table[256];
  92136. #define FLAC__CRC16_UPDATE(data, crc) (((((crc)<<8) & 0xffff) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]))
  92137. /* this alternate may be faster on some systems/compilers */
  92138. #if 0
  92139. #define FLAC__CRC16_UPDATE(data, crc) ((((crc)<<8) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]) & 0xffff)
  92140. #endif
  92141. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len);
  92142. #endif
  92143. /*** End of inlined file: crc.h ***/
  92144. /* Things should be fastest when this matches the machine word size */
  92145. /* WATCHOUT: if you change this you must also change the following #defines down to COUNT_ZERO_MSBS below to match */
  92146. /* WATCHOUT: there are a few places where the code will not work unless brword is >= 32 bits wide */
  92147. /* also, some sections currently only have fast versions for 4 or 8 bytes per word */
  92148. typedef FLAC__uint32 brword;
  92149. #define FLAC__BYTES_PER_WORD 4
  92150. #define FLAC__BITS_PER_WORD 32
  92151. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  92152. /* SWAP_BE_WORD_TO_HOST swaps bytes in a brword (which is always big-endian) if necessary to match host byte order */
  92153. #if WORDS_BIGENDIAN
  92154. #define SWAP_BE_WORD_TO_HOST(x) (x)
  92155. #else
  92156. #if defined (_MSC_VER) && defined (_X86_)
  92157. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  92158. #else
  92159. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  92160. #endif
  92161. #endif
  92162. /* counts the # of zero MSBs in a word */
  92163. #define COUNT_ZERO_MSBS(word) ( \
  92164. (word) <= 0xffff ? \
  92165. ( (word) <= 0xff? byte_to_unary_table[word] + 24 : byte_to_unary_table[(word) >> 8] + 16 ) : \
  92166. ( (word) <= 0xffffff? byte_to_unary_table[word >> 16] + 8 : byte_to_unary_table[(word) >> 24] ) \
  92167. )
  92168. /* this alternate might be slightly faster on some systems/compilers: */
  92169. #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])) )
  92170. /*
  92171. * This should be at least twice as large as the largest number of words
  92172. * required to represent any 'number' (in any encoding) you are going to
  92173. * read. With FLAC this is on the order of maybe a few hundred bits.
  92174. * If the buffer is smaller than that, the decoder won't be able to read
  92175. * in a whole number that is in a variable length encoding (e.g. Rice).
  92176. * But to be practical it should be at least 1K bytes.
  92177. *
  92178. * Increase this number to decrease the number of read callbacks, at the
  92179. * expense of using more memory. Or decrease for the reverse effect,
  92180. * keeping in mind the limit from the first paragraph. The optimal size
  92181. * also depends on the CPU cache size and other factors; some twiddling
  92182. * may be necessary to squeeze out the best performance.
  92183. */
  92184. static const unsigned FLAC__BITREADER_DEFAULT_CAPACITY = 65536u / FLAC__BITS_PER_WORD; /* in words */
  92185. static const unsigned char byte_to_unary_table[] = {
  92186. 8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
  92187. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  92188. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  92189. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  92190. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  92191. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  92192. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  92193. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  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. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  92202. };
  92203. #ifdef min
  92204. #undef min
  92205. #endif
  92206. #define min(x,y) ((x)<(y)?(x):(y))
  92207. #ifdef max
  92208. #undef max
  92209. #endif
  92210. #define max(x,y) ((x)>(y)?(x):(y))
  92211. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  92212. #ifdef _MSC_VER
  92213. #define FLAC__U64L(x) x
  92214. #else
  92215. #define FLAC__U64L(x) x##LLU
  92216. #endif
  92217. #ifndef FLaC__INLINE
  92218. #define FLaC__INLINE
  92219. #endif
  92220. /* WATCHOUT: assembly routines rely on the order in which these fields are declared */
  92221. struct FLAC__BitReader {
  92222. /* any partially-consumed word at the head will stay right-justified as bits are consumed from the left */
  92223. /* any incomplete word at the tail will be left-justified, and bytes from the read callback are added on the right */
  92224. brword *buffer;
  92225. unsigned capacity; /* in words */
  92226. unsigned words; /* # of completed words in buffer */
  92227. unsigned bytes; /* # of bytes in incomplete word at buffer[words] */
  92228. unsigned consumed_words; /* #words ... */
  92229. unsigned consumed_bits; /* ... + (#bits of head word) already consumed from the front of buffer */
  92230. unsigned read_crc16; /* the running frame CRC */
  92231. unsigned crc16_align; /* the number of bits in the current consumed word that should not be CRC'd */
  92232. FLAC__BitReaderReadCallback read_callback;
  92233. void *client_data;
  92234. FLAC__CPUInfo cpu_info;
  92235. };
  92236. static FLaC__INLINE void crc16_update_word_(FLAC__BitReader *br, brword word)
  92237. {
  92238. register unsigned crc = br->read_crc16;
  92239. #if FLAC__BYTES_PER_WORD == 4
  92240. switch(br->crc16_align) {
  92241. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 24), crc);
  92242. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  92243. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  92244. case 24: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  92245. }
  92246. #elif FLAC__BYTES_PER_WORD == 8
  92247. switch(br->crc16_align) {
  92248. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 56), crc);
  92249. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 48) & 0xff), crc);
  92250. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 40) & 0xff), crc);
  92251. case 24: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 32) & 0xff), crc);
  92252. case 32: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 24) & 0xff), crc);
  92253. case 40: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  92254. case 48: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  92255. case 56: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  92256. }
  92257. #else
  92258. for( ; br->crc16_align < FLAC__BITS_PER_WORD; br->crc16_align += 8)
  92259. crc = FLAC__CRC16_UPDATE((unsigned)((word >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), crc);
  92260. br->read_crc16 = crc;
  92261. #endif
  92262. br->crc16_align = 0;
  92263. }
  92264. /* would be static except it needs to be called by asm routines */
  92265. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br)
  92266. {
  92267. unsigned start, end;
  92268. size_t bytes;
  92269. FLAC__byte *target;
  92270. /* first shift the unconsumed buffer data toward the front as much as possible */
  92271. if(br->consumed_words > 0) {
  92272. start = br->consumed_words;
  92273. end = br->words + (br->bytes? 1:0);
  92274. memmove(br->buffer, br->buffer+start, FLAC__BYTES_PER_WORD * (end - start));
  92275. br->words -= start;
  92276. br->consumed_words = 0;
  92277. }
  92278. /*
  92279. * set the target for reading, taking into account word alignment and endianness
  92280. */
  92281. bytes = (br->capacity - br->words) * FLAC__BYTES_PER_WORD - br->bytes;
  92282. if(bytes == 0)
  92283. return false; /* no space left, buffer is too small; see note for FLAC__BITREADER_DEFAULT_CAPACITY */
  92284. target = ((FLAC__byte*)(br->buffer+br->words)) + br->bytes;
  92285. /* before reading, if the existing reader looks like this (say brword is 32 bits wide)
  92286. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1 (partial tail word is left-justified)
  92287. * buffer[BE]: 11 22 33 44 55 ?? ?? ?? (shown layed out as bytes sequentially in memory)
  92288. * buffer[LE]: 44 33 22 11 ?? ?? ?? 55 (?? being don't-care)
  92289. * ^^-------target, bytes=3
  92290. * on LE machines, have to byteswap the odd tail word so nothing is
  92291. * overwritten:
  92292. */
  92293. #if WORDS_BIGENDIAN
  92294. #else
  92295. if(br->bytes)
  92296. br->buffer[br->words] = SWAP_BE_WORD_TO_HOST(br->buffer[br->words]);
  92297. #endif
  92298. /* now it looks like:
  92299. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1
  92300. * buffer[BE]: 11 22 33 44 55 ?? ?? ??
  92301. * buffer[LE]: 44 33 22 11 55 ?? ?? ??
  92302. * ^^-------target, bytes=3
  92303. */
  92304. /* read in the data; note that the callback may return a smaller number of bytes */
  92305. if(!br->read_callback(target, &bytes, br->client_data))
  92306. return false;
  92307. /* after reading bytes 66 77 88 99 AA BB CC DD EE FF from the client:
  92308. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  92309. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  92310. * buffer[LE]: 44 33 22 11 55 66 77 88 99 AA BB CC DD EE FF ??
  92311. * now have to byteswap on LE machines:
  92312. */
  92313. #if WORDS_BIGENDIAN
  92314. #else
  92315. end = (br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes + (FLAC__BYTES_PER_WORD-1)) / FLAC__BYTES_PER_WORD;
  92316. # if defined(_MSC_VER) && defined (_X86_) && (FLAC__BYTES_PER_WORD == 4)
  92317. if(br->cpu_info.type == FLAC__CPUINFO_TYPE_IA32 && br->cpu_info.data.ia32.bswap) {
  92318. start = br->words;
  92319. local_swap32_block_(br->buffer + start, end - start);
  92320. }
  92321. else
  92322. # endif
  92323. for(start = br->words; start < end; start++)
  92324. br->buffer[start] = SWAP_BE_WORD_TO_HOST(br->buffer[start]);
  92325. #endif
  92326. /* now it looks like:
  92327. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  92328. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  92329. * buffer[LE]: 44 33 22 11 88 77 66 55 CC BB AA 99 ?? FF EE DD
  92330. * finally we'll update the reader values:
  92331. */
  92332. end = br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes;
  92333. br->words = end / FLAC__BYTES_PER_WORD;
  92334. br->bytes = end % FLAC__BYTES_PER_WORD;
  92335. return true;
  92336. }
  92337. /***********************************************************************
  92338. *
  92339. * Class constructor/destructor
  92340. *
  92341. ***********************************************************************/
  92342. FLAC__BitReader *FLAC__bitreader_new(void)
  92343. {
  92344. FLAC__BitReader *br = (FLAC__BitReader*)calloc(1, sizeof(FLAC__BitReader));
  92345. /* calloc() implies:
  92346. memset(br, 0, sizeof(FLAC__BitReader));
  92347. br->buffer = 0;
  92348. br->capacity = 0;
  92349. br->words = br->bytes = 0;
  92350. br->consumed_words = br->consumed_bits = 0;
  92351. br->read_callback = 0;
  92352. br->client_data = 0;
  92353. */
  92354. return br;
  92355. }
  92356. void FLAC__bitreader_delete(FLAC__BitReader *br)
  92357. {
  92358. FLAC__ASSERT(0 != br);
  92359. FLAC__bitreader_free(br);
  92360. free(br);
  92361. }
  92362. /***********************************************************************
  92363. *
  92364. * Public class methods
  92365. *
  92366. ***********************************************************************/
  92367. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd)
  92368. {
  92369. FLAC__ASSERT(0 != br);
  92370. br->words = br->bytes = 0;
  92371. br->consumed_words = br->consumed_bits = 0;
  92372. br->capacity = FLAC__BITREADER_DEFAULT_CAPACITY;
  92373. br->buffer = (brword*)malloc(sizeof(brword) * br->capacity);
  92374. if(br->buffer == 0)
  92375. return false;
  92376. br->read_callback = rcb;
  92377. br->client_data = cd;
  92378. br->cpu_info = cpu;
  92379. return true;
  92380. }
  92381. void FLAC__bitreader_free(FLAC__BitReader *br)
  92382. {
  92383. FLAC__ASSERT(0 != br);
  92384. if(0 != br->buffer)
  92385. free(br->buffer);
  92386. br->buffer = 0;
  92387. br->capacity = 0;
  92388. br->words = br->bytes = 0;
  92389. br->consumed_words = br->consumed_bits = 0;
  92390. br->read_callback = 0;
  92391. br->client_data = 0;
  92392. }
  92393. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br)
  92394. {
  92395. br->words = br->bytes = 0;
  92396. br->consumed_words = br->consumed_bits = 0;
  92397. return true;
  92398. }
  92399. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out)
  92400. {
  92401. unsigned i, j;
  92402. if(br == 0) {
  92403. fprintf(out, "bitreader is NULL\n");
  92404. }
  92405. else {
  92406. 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);
  92407. for(i = 0; i < br->words; i++) {
  92408. fprintf(out, "%08X: ", i);
  92409. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  92410. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  92411. fprintf(out, ".");
  92412. else
  92413. fprintf(out, "%01u", br->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  92414. fprintf(out, "\n");
  92415. }
  92416. if(br->bytes > 0) {
  92417. fprintf(out, "%08X: ", i);
  92418. for(j = 0; j < br->bytes*8; j++)
  92419. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  92420. fprintf(out, ".");
  92421. else
  92422. fprintf(out, "%01u", br->buffer[i] & (1 << (br->bytes*8-j-1)) ? 1:0);
  92423. fprintf(out, "\n");
  92424. }
  92425. }
  92426. }
  92427. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed)
  92428. {
  92429. FLAC__ASSERT(0 != br);
  92430. FLAC__ASSERT(0 != br->buffer);
  92431. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  92432. br->read_crc16 = (unsigned)seed;
  92433. br->crc16_align = br->consumed_bits;
  92434. }
  92435. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br)
  92436. {
  92437. FLAC__ASSERT(0 != br);
  92438. FLAC__ASSERT(0 != br->buffer);
  92439. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  92440. FLAC__ASSERT(br->crc16_align <= br->consumed_bits);
  92441. /* CRC any tail bytes in a partially-consumed word */
  92442. if(br->consumed_bits) {
  92443. const brword tail = br->buffer[br->consumed_words];
  92444. for( ; br->crc16_align < br->consumed_bits; br->crc16_align += 8)
  92445. br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)((tail >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), br->read_crc16);
  92446. }
  92447. return br->read_crc16;
  92448. }
  92449. FLaC__INLINE FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br)
  92450. {
  92451. return ((br->consumed_bits & 7) == 0);
  92452. }
  92453. FLaC__INLINE unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br)
  92454. {
  92455. return 8 - (br->consumed_bits & 7);
  92456. }
  92457. FLaC__INLINE unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br)
  92458. {
  92459. return (br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits;
  92460. }
  92461. FLaC__INLINE FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits)
  92462. {
  92463. FLAC__ASSERT(0 != br);
  92464. FLAC__ASSERT(0 != br->buffer);
  92465. FLAC__ASSERT(bits <= 32);
  92466. FLAC__ASSERT((br->capacity*FLAC__BITS_PER_WORD) * 2 >= bits);
  92467. FLAC__ASSERT(br->consumed_words <= br->words);
  92468. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  92469. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  92470. if(bits == 0) { /* OPT: investigate if this can ever happen, maybe change to assertion */
  92471. *val = 0;
  92472. return true;
  92473. }
  92474. while((br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits < bits) {
  92475. if(!bitreader_read_from_client_(br))
  92476. return false;
  92477. }
  92478. if(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  92479. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  92480. if(br->consumed_bits) {
  92481. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  92482. const unsigned n = FLAC__BITS_PER_WORD - br->consumed_bits;
  92483. const brword word = br->buffer[br->consumed_words];
  92484. if(bits < n) {
  92485. *val = (word & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (n-bits);
  92486. br->consumed_bits += bits;
  92487. return true;
  92488. }
  92489. *val = word & (FLAC__WORD_ALL_ONES >> br->consumed_bits);
  92490. bits -= n;
  92491. crc16_update_word_(br, word);
  92492. br->consumed_words++;
  92493. br->consumed_bits = 0;
  92494. 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 */
  92495. *val <<= bits;
  92496. *val |= (br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits));
  92497. br->consumed_bits = bits;
  92498. }
  92499. return true;
  92500. }
  92501. else {
  92502. const brword word = br->buffer[br->consumed_words];
  92503. if(bits < FLAC__BITS_PER_WORD) {
  92504. *val = word >> (FLAC__BITS_PER_WORD-bits);
  92505. br->consumed_bits = bits;
  92506. return true;
  92507. }
  92508. /* at this point 'bits' must be == FLAC__BITS_PER_WORD; because of previous assertions, it can't be larger */
  92509. *val = word;
  92510. crc16_update_word_(br, word);
  92511. br->consumed_words++;
  92512. return true;
  92513. }
  92514. }
  92515. else {
  92516. /* in this case we're starting our read at a partial tail word;
  92517. * the reader has guaranteed that we have at least 'bits' bits
  92518. * available to read, which makes this case simpler.
  92519. */
  92520. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  92521. if(br->consumed_bits) {
  92522. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  92523. FLAC__ASSERT(br->consumed_bits + bits <= br->bytes*8);
  92524. *val = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (FLAC__BITS_PER_WORD-br->consumed_bits-bits);
  92525. br->consumed_bits += bits;
  92526. return true;
  92527. }
  92528. else {
  92529. *val = br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits);
  92530. br->consumed_bits += bits;
  92531. return true;
  92532. }
  92533. }
  92534. }
  92535. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits)
  92536. {
  92537. /* OPT: inline raw uint32 code here, or make into a macro if possible in the .h file */
  92538. if(!FLAC__bitreader_read_raw_uint32(br, (FLAC__uint32*)val, bits))
  92539. return false;
  92540. /* sign-extend: */
  92541. *val <<= (32-bits);
  92542. *val >>= (32-bits);
  92543. return true;
  92544. }
  92545. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits)
  92546. {
  92547. FLAC__uint32 hi, lo;
  92548. if(bits > 32) {
  92549. if(!FLAC__bitreader_read_raw_uint32(br, &hi, bits-32))
  92550. return false;
  92551. if(!FLAC__bitreader_read_raw_uint32(br, &lo, 32))
  92552. return false;
  92553. *val = hi;
  92554. *val <<= 32;
  92555. *val |= lo;
  92556. }
  92557. else {
  92558. if(!FLAC__bitreader_read_raw_uint32(br, &lo, bits))
  92559. return false;
  92560. *val = lo;
  92561. }
  92562. return true;
  92563. }
  92564. FLaC__INLINE FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val)
  92565. {
  92566. FLAC__uint32 x8, x32 = 0;
  92567. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  92568. if(!FLAC__bitreader_read_raw_uint32(br, &x32, 8))
  92569. return false;
  92570. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  92571. return false;
  92572. x32 |= (x8 << 8);
  92573. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  92574. return false;
  92575. x32 |= (x8 << 16);
  92576. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  92577. return false;
  92578. x32 |= (x8 << 24);
  92579. *val = x32;
  92580. return true;
  92581. }
  92582. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits)
  92583. {
  92584. /*
  92585. * OPT: a faster implementation is possible but probably not that useful
  92586. * since this is only called a couple of times in the metadata readers.
  92587. */
  92588. FLAC__ASSERT(0 != br);
  92589. FLAC__ASSERT(0 != br->buffer);
  92590. if(bits > 0) {
  92591. const unsigned n = br->consumed_bits & 7;
  92592. unsigned m;
  92593. FLAC__uint32 x;
  92594. if(n != 0) {
  92595. m = min(8-n, bits);
  92596. if(!FLAC__bitreader_read_raw_uint32(br, &x, m))
  92597. return false;
  92598. bits -= m;
  92599. }
  92600. m = bits / 8;
  92601. if(m > 0) {
  92602. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(br, m))
  92603. return false;
  92604. bits %= 8;
  92605. }
  92606. if(bits > 0) {
  92607. if(!FLAC__bitreader_read_raw_uint32(br, &x, bits))
  92608. return false;
  92609. }
  92610. }
  92611. return true;
  92612. }
  92613. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals)
  92614. {
  92615. FLAC__uint32 x;
  92616. FLAC__ASSERT(0 != br);
  92617. FLAC__ASSERT(0 != br->buffer);
  92618. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  92619. /* step 1: skip over partial head word to get word aligned */
  92620. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  92621. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  92622. return false;
  92623. nvals--;
  92624. }
  92625. if(0 == nvals)
  92626. return true;
  92627. /* step 2: skip whole words in chunks */
  92628. while(nvals >= FLAC__BYTES_PER_WORD) {
  92629. if(br->consumed_words < br->words) {
  92630. br->consumed_words++;
  92631. nvals -= FLAC__BYTES_PER_WORD;
  92632. }
  92633. else if(!bitreader_read_from_client_(br))
  92634. return false;
  92635. }
  92636. /* step 3: skip any remainder from partial tail bytes */
  92637. while(nvals) {
  92638. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  92639. return false;
  92640. nvals--;
  92641. }
  92642. return true;
  92643. }
  92644. FLAC__bool FLAC__bitreader_read_byte_block_aligned_no_crc(FLAC__BitReader *br, FLAC__byte *val, unsigned nvals)
  92645. {
  92646. FLAC__uint32 x;
  92647. FLAC__ASSERT(0 != br);
  92648. FLAC__ASSERT(0 != br->buffer);
  92649. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  92650. /* step 1: read from partial head word to get word aligned */
  92651. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  92652. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  92653. return false;
  92654. *val++ = (FLAC__byte)x;
  92655. nvals--;
  92656. }
  92657. if(0 == nvals)
  92658. return true;
  92659. /* step 2: read whole words in chunks */
  92660. while(nvals >= FLAC__BYTES_PER_WORD) {
  92661. if(br->consumed_words < br->words) {
  92662. const brword word = br->buffer[br->consumed_words++];
  92663. #if FLAC__BYTES_PER_WORD == 4
  92664. val[0] = (FLAC__byte)(word >> 24);
  92665. val[1] = (FLAC__byte)(word >> 16);
  92666. val[2] = (FLAC__byte)(word >> 8);
  92667. val[3] = (FLAC__byte)word;
  92668. #elif FLAC__BYTES_PER_WORD == 8
  92669. val[0] = (FLAC__byte)(word >> 56);
  92670. val[1] = (FLAC__byte)(word >> 48);
  92671. val[2] = (FLAC__byte)(word >> 40);
  92672. val[3] = (FLAC__byte)(word >> 32);
  92673. val[4] = (FLAC__byte)(word >> 24);
  92674. val[5] = (FLAC__byte)(word >> 16);
  92675. val[6] = (FLAC__byte)(word >> 8);
  92676. val[7] = (FLAC__byte)word;
  92677. #else
  92678. for(x = 0; x < FLAC__BYTES_PER_WORD; x++)
  92679. val[x] = (FLAC__byte)(word >> (8*(FLAC__BYTES_PER_WORD-x-1)));
  92680. #endif
  92681. val += FLAC__BYTES_PER_WORD;
  92682. nvals -= FLAC__BYTES_PER_WORD;
  92683. }
  92684. else if(!bitreader_read_from_client_(br))
  92685. return false;
  92686. }
  92687. /* step 3: read any remainder from partial tail bytes */
  92688. while(nvals) {
  92689. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  92690. return false;
  92691. *val++ = (FLAC__byte)x;
  92692. nvals--;
  92693. }
  92694. return true;
  92695. }
  92696. FLaC__INLINE FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val)
  92697. #if 0 /* slow but readable version */
  92698. {
  92699. unsigned bit;
  92700. FLAC__ASSERT(0 != br);
  92701. FLAC__ASSERT(0 != br->buffer);
  92702. *val = 0;
  92703. while(1) {
  92704. if(!FLAC__bitreader_read_bit(br, &bit))
  92705. return false;
  92706. if(bit)
  92707. break;
  92708. else
  92709. *val++;
  92710. }
  92711. return true;
  92712. }
  92713. #else
  92714. {
  92715. unsigned i;
  92716. FLAC__ASSERT(0 != br);
  92717. FLAC__ASSERT(0 != br->buffer);
  92718. *val = 0;
  92719. while(1) {
  92720. while(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  92721. brword b = br->buffer[br->consumed_words] << br->consumed_bits;
  92722. if(b) {
  92723. i = COUNT_ZERO_MSBS(b);
  92724. *val += i;
  92725. i++;
  92726. br->consumed_bits += i;
  92727. if(br->consumed_bits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(br->consumed_bits == FLAC__BITS_PER_WORD) */
  92728. crc16_update_word_(br, br->buffer[br->consumed_words]);
  92729. br->consumed_words++;
  92730. br->consumed_bits = 0;
  92731. }
  92732. return true;
  92733. }
  92734. else {
  92735. *val += FLAC__BITS_PER_WORD - br->consumed_bits;
  92736. crc16_update_word_(br, br->buffer[br->consumed_words]);
  92737. br->consumed_words++;
  92738. br->consumed_bits = 0;
  92739. /* didn't find stop bit yet, have to keep going... */
  92740. }
  92741. }
  92742. /* at this point we've eaten up all the whole words; have to try
  92743. * reading through any tail bytes before calling the read callback.
  92744. * this is a repeat of the above logic adjusted for the fact we
  92745. * don't have a whole word. note though if the client is feeding
  92746. * us data a byte at a time (unlikely), br->consumed_bits may not
  92747. * be zero.
  92748. */
  92749. if(br->bytes) {
  92750. const unsigned end = br->bytes * 8;
  92751. brword b = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << br->consumed_bits;
  92752. if(b) {
  92753. i = COUNT_ZERO_MSBS(b);
  92754. *val += i;
  92755. i++;
  92756. br->consumed_bits += i;
  92757. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  92758. return true;
  92759. }
  92760. else {
  92761. *val += end - br->consumed_bits;
  92762. br->consumed_bits += end;
  92763. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  92764. /* didn't find stop bit yet, have to keep going... */
  92765. }
  92766. }
  92767. if(!bitreader_read_from_client_(br))
  92768. return false;
  92769. }
  92770. }
  92771. #endif
  92772. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  92773. {
  92774. FLAC__uint32 lsbs = 0, msbs = 0;
  92775. unsigned uval;
  92776. FLAC__ASSERT(0 != br);
  92777. FLAC__ASSERT(0 != br->buffer);
  92778. FLAC__ASSERT(parameter <= 31);
  92779. /* read the unary MSBs and end bit */
  92780. if(!FLAC__bitreader_read_unary_unsigned(br, (unsigned int*) &msbs))
  92781. return false;
  92782. /* read the binary LSBs */
  92783. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, parameter))
  92784. return false;
  92785. /* compose the value */
  92786. uval = (msbs << parameter) | lsbs;
  92787. if(uval & 1)
  92788. *val = -((int)(uval >> 1)) - 1;
  92789. else
  92790. *val = (int)(uval >> 1);
  92791. return true;
  92792. }
  92793. /* this is by far the most heavily used reader call. it ain't pretty but it's fast */
  92794. /* a lot of the logic is copied, then adapted, from FLAC__bitreader_read_unary_unsigned() and FLAC__bitreader_read_raw_uint32() */
  92795. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter)
  92796. /* OPT: possibly faster version for use with MSVC */
  92797. #ifdef _MSC_VER
  92798. {
  92799. unsigned i;
  92800. unsigned uval = 0;
  92801. unsigned bits; /* the # of binary LSBs left to read to finish a rice codeword */
  92802. /* try and get br->consumed_words and br->consumed_bits into register;
  92803. * must remember to flush them back to *br before calling other
  92804. * bitwriter functions that use them, and before returning */
  92805. register unsigned cwords;
  92806. register unsigned cbits;
  92807. FLAC__ASSERT(0 != br);
  92808. FLAC__ASSERT(0 != br->buffer);
  92809. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  92810. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  92811. FLAC__ASSERT(parameter < 32);
  92812. /* 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 */
  92813. if(nvals == 0)
  92814. return true;
  92815. cbits = br->consumed_bits;
  92816. cwords = br->consumed_words;
  92817. while(1) {
  92818. /* read unary part */
  92819. while(1) {
  92820. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  92821. brword b = br->buffer[cwords] << cbits;
  92822. if(b) {
  92823. #if 0 /* slower, probably due to bad register allocation... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32
  92824. __asm {
  92825. bsr eax, b
  92826. not eax
  92827. and eax, 31
  92828. mov i, eax
  92829. }
  92830. #else
  92831. i = COUNT_ZERO_MSBS(b);
  92832. #endif
  92833. uval += i;
  92834. bits = parameter;
  92835. i++;
  92836. cbits += i;
  92837. if(cbits == FLAC__BITS_PER_WORD) {
  92838. crc16_update_word_(br, br->buffer[cwords]);
  92839. cwords++;
  92840. cbits = 0;
  92841. }
  92842. goto break1;
  92843. }
  92844. else {
  92845. uval += FLAC__BITS_PER_WORD - cbits;
  92846. crc16_update_word_(br, br->buffer[cwords]);
  92847. cwords++;
  92848. cbits = 0;
  92849. /* didn't find stop bit yet, have to keep going... */
  92850. }
  92851. }
  92852. /* at this point we've eaten up all the whole words; have to try
  92853. * reading through any tail bytes before calling the read callback.
  92854. * this is a repeat of the above logic adjusted for the fact we
  92855. * don't have a whole word. note though if the client is feeding
  92856. * us data a byte at a time (unlikely), br->consumed_bits may not
  92857. * be zero.
  92858. */
  92859. if(br->bytes) {
  92860. const unsigned end = br->bytes * 8;
  92861. brword b = (br->buffer[cwords] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << cbits;
  92862. if(b) {
  92863. i = COUNT_ZERO_MSBS(b);
  92864. uval += i;
  92865. bits = parameter;
  92866. i++;
  92867. cbits += i;
  92868. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  92869. goto break1;
  92870. }
  92871. else {
  92872. uval += end - cbits;
  92873. cbits += end;
  92874. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  92875. /* didn't find stop bit yet, have to keep going... */
  92876. }
  92877. }
  92878. /* flush registers and read; bitreader_read_from_client_() does
  92879. * not touch br->consumed_bits at all but we still need to set
  92880. * it in case it fails and we have to return false.
  92881. */
  92882. br->consumed_bits = cbits;
  92883. br->consumed_words = cwords;
  92884. if(!bitreader_read_from_client_(br))
  92885. return false;
  92886. cwords = br->consumed_words;
  92887. }
  92888. break1:
  92889. /* read binary part */
  92890. FLAC__ASSERT(cwords <= br->words);
  92891. if(bits) {
  92892. while((br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits < bits) {
  92893. /* flush registers and read; bitreader_read_from_client_() does
  92894. * not touch br->consumed_bits at all but we still need to set
  92895. * it in case it fails and we have to return false.
  92896. */
  92897. br->consumed_bits = cbits;
  92898. br->consumed_words = cwords;
  92899. if(!bitreader_read_from_client_(br))
  92900. return false;
  92901. cwords = br->consumed_words;
  92902. }
  92903. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  92904. if(cbits) {
  92905. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  92906. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  92907. const brword word = br->buffer[cwords];
  92908. if(bits < n) {
  92909. uval <<= bits;
  92910. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-bits);
  92911. cbits += bits;
  92912. goto break2;
  92913. }
  92914. uval <<= n;
  92915. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  92916. bits -= n;
  92917. crc16_update_word_(br, word);
  92918. cwords++;
  92919. cbits = 0;
  92920. 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 */
  92921. uval <<= bits;
  92922. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits));
  92923. cbits = bits;
  92924. }
  92925. goto break2;
  92926. }
  92927. else {
  92928. FLAC__ASSERT(bits < FLAC__BITS_PER_WORD);
  92929. uval <<= bits;
  92930. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  92931. cbits = bits;
  92932. goto break2;
  92933. }
  92934. }
  92935. else {
  92936. /* in this case we're starting our read at a partial tail word;
  92937. * the reader has guaranteed that we have at least 'bits' bits
  92938. * available to read, which makes this case simpler.
  92939. */
  92940. uval <<= bits;
  92941. if(cbits) {
  92942. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  92943. FLAC__ASSERT(cbits + bits <= br->bytes*8);
  92944. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-bits);
  92945. cbits += bits;
  92946. goto break2;
  92947. }
  92948. else {
  92949. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  92950. cbits += bits;
  92951. goto break2;
  92952. }
  92953. }
  92954. }
  92955. break2:
  92956. /* compose the value */
  92957. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  92958. /* are we done? */
  92959. --nvals;
  92960. if(nvals == 0) {
  92961. br->consumed_bits = cbits;
  92962. br->consumed_words = cwords;
  92963. return true;
  92964. }
  92965. uval = 0;
  92966. ++vals;
  92967. }
  92968. }
  92969. #else
  92970. {
  92971. unsigned i;
  92972. unsigned uval = 0;
  92973. /* try and get br->consumed_words and br->consumed_bits into register;
  92974. * must remember to flush them back to *br before calling other
  92975. * bitwriter functions that use them, and before returning */
  92976. register unsigned cwords;
  92977. register unsigned cbits;
  92978. unsigned ucbits; /* keep track of the number of unconsumed bits in the buffer */
  92979. FLAC__ASSERT(0 != br);
  92980. FLAC__ASSERT(0 != br->buffer);
  92981. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  92982. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  92983. FLAC__ASSERT(parameter < 32);
  92984. /* 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 */
  92985. if(nvals == 0)
  92986. return true;
  92987. cbits = br->consumed_bits;
  92988. cwords = br->consumed_words;
  92989. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  92990. while(1) {
  92991. /* read unary part */
  92992. while(1) {
  92993. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  92994. brword b = br->buffer[cwords] << cbits;
  92995. if(b) {
  92996. #if 0 /* is not discernably faster... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32 && defined __GNUC__
  92997. asm volatile (
  92998. "bsrl %1, %0;"
  92999. "notl %0;"
  93000. "andl $31, %0;"
  93001. : "=r"(i)
  93002. : "r"(b)
  93003. );
  93004. #else
  93005. i = COUNT_ZERO_MSBS(b);
  93006. #endif
  93007. uval += i;
  93008. cbits += i;
  93009. cbits++; /* skip over stop bit */
  93010. if(cbits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(cbits == FLAC__BITS_PER_WORD) */
  93011. crc16_update_word_(br, br->buffer[cwords]);
  93012. cwords++;
  93013. cbits = 0;
  93014. }
  93015. goto break1;
  93016. }
  93017. else {
  93018. uval += FLAC__BITS_PER_WORD - cbits;
  93019. crc16_update_word_(br, br->buffer[cwords]);
  93020. cwords++;
  93021. cbits = 0;
  93022. /* didn't find stop bit yet, have to keep going... */
  93023. }
  93024. }
  93025. /* at this point we've eaten up all the whole words; have to try
  93026. * reading through any tail bytes before calling the read callback.
  93027. * this is a repeat of the above logic adjusted for the fact we
  93028. * don't have a whole word. note though if the client is feeding
  93029. * us data a byte at a time (unlikely), br->consumed_bits may not
  93030. * be zero.
  93031. */
  93032. if(br->bytes) {
  93033. const unsigned end = br->bytes * 8;
  93034. brword b = (br->buffer[cwords] & ~(FLAC__WORD_ALL_ONES >> end)) << cbits;
  93035. if(b) {
  93036. i = COUNT_ZERO_MSBS(b);
  93037. uval += i;
  93038. cbits += i;
  93039. cbits++; /* skip over stop bit */
  93040. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93041. goto break1;
  93042. }
  93043. else {
  93044. uval += end - cbits;
  93045. cbits += end;
  93046. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93047. /* didn't find stop bit yet, have to keep going... */
  93048. }
  93049. }
  93050. /* flush registers and read; bitreader_read_from_client_() does
  93051. * not touch br->consumed_bits at all but we still need to set
  93052. * it in case it fails and we have to return false.
  93053. */
  93054. br->consumed_bits = cbits;
  93055. br->consumed_words = cwords;
  93056. if(!bitreader_read_from_client_(br))
  93057. return false;
  93058. cwords = br->consumed_words;
  93059. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits + uval;
  93060. /* + uval to offset our count by the # of unary bits already
  93061. * consumed before the read, because we will add these back
  93062. * in all at once at break1
  93063. */
  93064. }
  93065. break1:
  93066. ucbits -= uval;
  93067. ucbits--; /* account for stop bit */
  93068. /* read binary part */
  93069. FLAC__ASSERT(cwords <= br->words);
  93070. if(parameter) {
  93071. while(ucbits < parameter) {
  93072. /* flush registers and read; bitreader_read_from_client_() does
  93073. * not touch br->consumed_bits at all but we still need to set
  93074. * it in case it fails and we have to return false.
  93075. */
  93076. br->consumed_bits = cbits;
  93077. br->consumed_words = cwords;
  93078. if(!bitreader_read_from_client_(br))
  93079. return false;
  93080. cwords = br->consumed_words;
  93081. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  93082. }
  93083. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93084. if(cbits) {
  93085. /* this also works when consumed_bits==0, it's just slower than necessary for that case */
  93086. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  93087. const brword word = br->buffer[cwords];
  93088. if(parameter < n) {
  93089. uval <<= parameter;
  93090. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-parameter);
  93091. cbits += parameter;
  93092. }
  93093. else {
  93094. uval <<= n;
  93095. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  93096. crc16_update_word_(br, word);
  93097. cwords++;
  93098. cbits = parameter - n;
  93099. 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 */
  93100. uval <<= cbits;
  93101. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits));
  93102. }
  93103. }
  93104. }
  93105. else {
  93106. cbits = parameter;
  93107. uval <<= parameter;
  93108. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  93109. }
  93110. }
  93111. else {
  93112. /* in this case we're starting our read at a partial tail word;
  93113. * the reader has guaranteed that we have at least 'parameter'
  93114. * bits available to read, which makes this case simpler.
  93115. */
  93116. uval <<= parameter;
  93117. if(cbits) {
  93118. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93119. FLAC__ASSERT(cbits + parameter <= br->bytes*8);
  93120. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-parameter);
  93121. cbits += parameter;
  93122. }
  93123. else {
  93124. cbits = parameter;
  93125. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  93126. }
  93127. }
  93128. }
  93129. ucbits -= parameter;
  93130. /* compose the value */
  93131. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  93132. /* are we done? */
  93133. --nvals;
  93134. if(nvals == 0) {
  93135. br->consumed_bits = cbits;
  93136. br->consumed_words = cwords;
  93137. return true;
  93138. }
  93139. uval = 0;
  93140. ++vals;
  93141. }
  93142. }
  93143. #endif
  93144. #if 0 /* UNUSED */
  93145. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  93146. {
  93147. FLAC__uint32 lsbs = 0, msbs = 0;
  93148. unsigned bit, uval, k;
  93149. FLAC__ASSERT(0 != br);
  93150. FLAC__ASSERT(0 != br->buffer);
  93151. k = FLAC__bitmath_ilog2(parameter);
  93152. /* read the unary MSBs and end bit */
  93153. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  93154. return false;
  93155. /* read the binary LSBs */
  93156. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  93157. return false;
  93158. if(parameter == 1u<<k) {
  93159. /* compose the value */
  93160. uval = (msbs << k) | lsbs;
  93161. }
  93162. else {
  93163. unsigned d = (1 << (k+1)) - parameter;
  93164. if(lsbs >= d) {
  93165. if(!FLAC__bitreader_read_bit(br, &bit))
  93166. return false;
  93167. lsbs <<= 1;
  93168. lsbs |= bit;
  93169. lsbs -= d;
  93170. }
  93171. /* compose the value */
  93172. uval = msbs * parameter + lsbs;
  93173. }
  93174. /* unfold unsigned to signed */
  93175. if(uval & 1)
  93176. *val = -((int)(uval >> 1)) - 1;
  93177. else
  93178. *val = (int)(uval >> 1);
  93179. return true;
  93180. }
  93181. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter)
  93182. {
  93183. FLAC__uint32 lsbs, msbs = 0;
  93184. unsigned bit, k;
  93185. FLAC__ASSERT(0 != br);
  93186. FLAC__ASSERT(0 != br->buffer);
  93187. k = FLAC__bitmath_ilog2(parameter);
  93188. /* read the unary MSBs and end bit */
  93189. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  93190. return false;
  93191. /* read the binary LSBs */
  93192. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  93193. return false;
  93194. if(parameter == 1u<<k) {
  93195. /* compose the value */
  93196. *val = (msbs << k) | lsbs;
  93197. }
  93198. else {
  93199. unsigned d = (1 << (k+1)) - parameter;
  93200. if(lsbs >= d) {
  93201. if(!FLAC__bitreader_read_bit(br, &bit))
  93202. return false;
  93203. lsbs <<= 1;
  93204. lsbs |= bit;
  93205. lsbs -= d;
  93206. }
  93207. /* compose the value */
  93208. *val = msbs * parameter + lsbs;
  93209. }
  93210. return true;
  93211. }
  93212. #endif /* UNUSED */
  93213. /* on return, if *val == 0xffffffff then the utf-8 sequence was invalid, but the return value will be true */
  93214. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen)
  93215. {
  93216. FLAC__uint32 v = 0;
  93217. FLAC__uint32 x;
  93218. unsigned i;
  93219. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93220. return false;
  93221. if(raw)
  93222. raw[(*rawlen)++] = (FLAC__byte)x;
  93223. if(!(x & 0x80)) { /* 0xxxxxxx */
  93224. v = x;
  93225. i = 0;
  93226. }
  93227. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  93228. v = x & 0x1F;
  93229. i = 1;
  93230. }
  93231. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  93232. v = x & 0x0F;
  93233. i = 2;
  93234. }
  93235. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  93236. v = x & 0x07;
  93237. i = 3;
  93238. }
  93239. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  93240. v = x & 0x03;
  93241. i = 4;
  93242. }
  93243. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  93244. v = x & 0x01;
  93245. i = 5;
  93246. }
  93247. else {
  93248. *val = 0xffffffff;
  93249. return true;
  93250. }
  93251. for( ; i; i--) {
  93252. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93253. return false;
  93254. if(raw)
  93255. raw[(*rawlen)++] = (FLAC__byte)x;
  93256. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  93257. *val = 0xffffffff;
  93258. return true;
  93259. }
  93260. v <<= 6;
  93261. v |= (x & 0x3F);
  93262. }
  93263. *val = v;
  93264. return true;
  93265. }
  93266. /* on return, if *val == 0xffffffffffffffff then the utf-8 sequence was invalid, but the return value will be true */
  93267. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen)
  93268. {
  93269. FLAC__uint64 v = 0;
  93270. FLAC__uint32 x;
  93271. unsigned i;
  93272. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93273. return false;
  93274. if(raw)
  93275. raw[(*rawlen)++] = (FLAC__byte)x;
  93276. if(!(x & 0x80)) { /* 0xxxxxxx */
  93277. v = x;
  93278. i = 0;
  93279. }
  93280. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  93281. v = x & 0x1F;
  93282. i = 1;
  93283. }
  93284. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  93285. v = x & 0x0F;
  93286. i = 2;
  93287. }
  93288. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  93289. v = x & 0x07;
  93290. i = 3;
  93291. }
  93292. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  93293. v = x & 0x03;
  93294. i = 4;
  93295. }
  93296. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  93297. v = x & 0x01;
  93298. i = 5;
  93299. }
  93300. else if(x & 0xFE && !(x & 0x01)) { /* 11111110 */
  93301. v = 0;
  93302. i = 6;
  93303. }
  93304. else {
  93305. *val = FLAC__U64L(0xffffffffffffffff);
  93306. return true;
  93307. }
  93308. for( ; i; i--) {
  93309. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93310. return false;
  93311. if(raw)
  93312. raw[(*rawlen)++] = (FLAC__byte)x;
  93313. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  93314. *val = FLAC__U64L(0xffffffffffffffff);
  93315. return true;
  93316. }
  93317. v <<= 6;
  93318. v |= (x & 0x3F);
  93319. }
  93320. *val = v;
  93321. return true;
  93322. }
  93323. #endif
  93324. /*** End of inlined file: bitreader.c ***/
  93325. /*** Start of inlined file: bitwriter.c ***/
  93326. /*** Start of inlined file: juce_FlacHeader.h ***/
  93327. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  93328. // tasks..
  93329. #define VERSION "1.2.1"
  93330. #define FLAC__NO_DLL 1
  93331. #if JUCE_MSVC
  93332. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  93333. #endif
  93334. #if JUCE_MAC
  93335. #define FLAC__SYS_DARWIN 1
  93336. #endif
  93337. /*** End of inlined file: juce_FlacHeader.h ***/
  93338. #if JUCE_USE_FLAC
  93339. #if HAVE_CONFIG_H
  93340. # include <config.h>
  93341. #endif
  93342. #include <stdlib.h> /* for malloc() */
  93343. #include <string.h> /* for memcpy(), memset() */
  93344. #ifdef _MSC_VER
  93345. #include <winsock.h> /* for ntohl() */
  93346. #elif defined FLAC__SYS_DARWIN
  93347. #include <machine/endian.h> /* for ntohl() */
  93348. #elif defined __MINGW32__
  93349. #include <winsock.h> /* for ntohl() */
  93350. #else
  93351. #include <netinet/in.h> /* for ntohl() */
  93352. #endif
  93353. #if 0 /* UNUSED */
  93354. #endif
  93355. /*** Start of inlined file: bitwriter.h ***/
  93356. #ifndef FLAC__PRIVATE__BITWRITER_H
  93357. #define FLAC__PRIVATE__BITWRITER_H
  93358. #include <stdio.h> /* for FILE */
  93359. /*
  93360. * opaque structure definition
  93361. */
  93362. struct FLAC__BitWriter;
  93363. typedef struct FLAC__BitWriter FLAC__BitWriter;
  93364. /*
  93365. * construction, deletion, initialization, etc functions
  93366. */
  93367. FLAC__BitWriter *FLAC__bitwriter_new(void);
  93368. void FLAC__bitwriter_delete(FLAC__BitWriter *bw);
  93369. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw);
  93370. void FLAC__bitwriter_free(FLAC__BitWriter *bw); /* does not 'free(buffer)' */
  93371. void FLAC__bitwriter_clear(FLAC__BitWriter *bw);
  93372. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out);
  93373. /*
  93374. * CRC functions
  93375. *
  93376. * non-const *bw because they have to cal FLAC__bitwriter_get_buffer()
  93377. */
  93378. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc);
  93379. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc);
  93380. /*
  93381. * info functions
  93382. */
  93383. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw);
  93384. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw); /* can be called anytime, returns total # of bits unconsumed */
  93385. /*
  93386. * direct buffer access
  93387. *
  93388. * there may be no calls on the bitwriter between get and release.
  93389. * the bitwriter continues to own the returned buffer.
  93390. * before get, bitwriter MUST be byte aligned: check with FLAC__bitwriter_is_byte_aligned()
  93391. */
  93392. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes);
  93393. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw);
  93394. /*
  93395. * write functions
  93396. */
  93397. FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits);
  93398. FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits);
  93399. FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits);
  93400. FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits);
  93401. FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val); /*only for bits=32*/
  93402. FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals);
  93403. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val);
  93404. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter);
  93405. #if 0 /* UNUSED */
  93406. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter);
  93407. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned val, unsigned parameter);
  93408. #endif
  93409. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter);
  93410. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter);
  93411. #if 0 /* UNUSED */
  93412. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter);
  93413. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned val, unsigned parameter);
  93414. #endif
  93415. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val);
  93416. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val);
  93417. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw);
  93418. #endif
  93419. /*** End of inlined file: bitwriter.h ***/
  93420. /*** Start of inlined file: alloc.h ***/
  93421. #ifndef FLAC__SHARE__ALLOC_H
  93422. #define FLAC__SHARE__ALLOC_H
  93423. #if HAVE_CONFIG_H
  93424. # include <config.h>
  93425. #endif
  93426. /* WATCHOUT: for c++ you may have to #define __STDC_LIMIT_MACROS 1 real early
  93427. * before #including this file, otherwise SIZE_MAX might not be defined
  93428. */
  93429. #include <limits.h> /* for SIZE_MAX */
  93430. #if !defined _MSC_VER && !defined __MINGW32__ && !defined __EMX__
  93431. #include <stdint.h> /* for SIZE_MAX in case limits.h didn't get it */
  93432. #endif
  93433. #include <stdlib.h> /* for size_t, malloc(), etc */
  93434. #ifndef SIZE_MAX
  93435. # ifndef SIZE_T_MAX
  93436. # ifdef _MSC_VER
  93437. # define SIZE_T_MAX UINT_MAX
  93438. # else
  93439. # error
  93440. # endif
  93441. # endif
  93442. # define SIZE_MAX SIZE_T_MAX
  93443. #endif
  93444. #ifndef FLaC__INLINE
  93445. #define FLaC__INLINE
  93446. #endif
  93447. /* avoid malloc()ing 0 bytes, see:
  93448. * https://www.securecoding.cert.org/confluence/display/seccode/MEM04-A.+Do+not+make+assumptions+about+the+result+of+allocating+0+bytes?focusedCommentId=5407003
  93449. */
  93450. static FLaC__INLINE void *safe_malloc_(size_t size)
  93451. {
  93452. /* malloc(0) is undefined; FLAC src convention is to always allocate */
  93453. if(!size)
  93454. size++;
  93455. return malloc(size);
  93456. }
  93457. static FLaC__INLINE void *safe_calloc_(size_t nmemb, size_t size)
  93458. {
  93459. if(!nmemb || !size)
  93460. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  93461. return calloc(nmemb, size);
  93462. }
  93463. /*@@@@ there's probably a better way to prevent overflows when allocating untrusted sums but this works for now */
  93464. static FLaC__INLINE void *safe_malloc_add_2op_(size_t size1, size_t size2)
  93465. {
  93466. size2 += size1;
  93467. if(size2 < size1)
  93468. return 0;
  93469. return safe_malloc_(size2);
  93470. }
  93471. static FLaC__INLINE void *safe_malloc_add_3op_(size_t size1, size_t size2, size_t size3)
  93472. {
  93473. size2 += size1;
  93474. if(size2 < size1)
  93475. return 0;
  93476. size3 += size2;
  93477. if(size3 < size2)
  93478. return 0;
  93479. return safe_malloc_(size3);
  93480. }
  93481. static FLaC__INLINE void *safe_malloc_add_4op_(size_t size1, size_t size2, size_t size3, size_t size4)
  93482. {
  93483. size2 += size1;
  93484. if(size2 < size1)
  93485. return 0;
  93486. size3 += size2;
  93487. if(size3 < size2)
  93488. return 0;
  93489. size4 += size3;
  93490. if(size4 < size3)
  93491. return 0;
  93492. return safe_malloc_(size4);
  93493. }
  93494. static FLaC__INLINE void *safe_malloc_mul_2op_(size_t size1, size_t size2)
  93495. #if 0
  93496. needs support for cases where sizeof(size_t) != 4
  93497. {
  93498. /* could be faster #ifdef'ing off SIZEOF_SIZE_T */
  93499. if(sizeof(size_t) == 4) {
  93500. if ((double)size1 * (double)size2 < 4294967296.0)
  93501. return malloc(size1*size2);
  93502. }
  93503. return 0;
  93504. }
  93505. #else
  93506. /* better? */
  93507. {
  93508. if(!size1 || !size2)
  93509. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  93510. if(size1 > SIZE_MAX / size2)
  93511. return 0;
  93512. return malloc(size1*size2);
  93513. }
  93514. #endif
  93515. static FLaC__INLINE void *safe_malloc_mul_3op_(size_t size1, size_t size2, size_t size3)
  93516. {
  93517. if(!size1 || !size2 || !size3)
  93518. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  93519. if(size1 > SIZE_MAX / size2)
  93520. return 0;
  93521. size1 *= size2;
  93522. if(size1 > SIZE_MAX / size3)
  93523. return 0;
  93524. return malloc(size1*size3);
  93525. }
  93526. /* size1*size2 + size3 */
  93527. static FLaC__INLINE void *safe_malloc_mul2add_(size_t size1, size_t size2, size_t size3)
  93528. {
  93529. if(!size1 || !size2)
  93530. return safe_malloc_(size3);
  93531. if(size1 > SIZE_MAX / size2)
  93532. return 0;
  93533. return safe_malloc_add_2op_(size1*size2, size3);
  93534. }
  93535. /* size1 * (size2 + size3) */
  93536. static FLaC__INLINE void *safe_malloc_muladd2_(size_t size1, size_t size2, size_t size3)
  93537. {
  93538. if(!size1 || (!size2 && !size3))
  93539. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  93540. size2 += size3;
  93541. if(size2 < size3)
  93542. return 0;
  93543. return safe_malloc_mul_2op_(size1, size2);
  93544. }
  93545. static FLaC__INLINE void *safe_realloc_add_2op_(void *ptr, size_t size1, size_t size2)
  93546. {
  93547. size2 += size1;
  93548. if(size2 < size1)
  93549. return 0;
  93550. return realloc(ptr, size2);
  93551. }
  93552. static FLaC__INLINE void *safe_realloc_add_3op_(void *ptr, size_t size1, size_t size2, size_t size3)
  93553. {
  93554. size2 += size1;
  93555. if(size2 < size1)
  93556. return 0;
  93557. size3 += size2;
  93558. if(size3 < size2)
  93559. return 0;
  93560. return realloc(ptr, size3);
  93561. }
  93562. static FLaC__INLINE void *safe_realloc_add_4op_(void *ptr, size_t size1, size_t size2, size_t size3, size_t size4)
  93563. {
  93564. size2 += size1;
  93565. if(size2 < size1)
  93566. return 0;
  93567. size3 += size2;
  93568. if(size3 < size2)
  93569. return 0;
  93570. size4 += size3;
  93571. if(size4 < size3)
  93572. return 0;
  93573. return realloc(ptr, size4);
  93574. }
  93575. static FLaC__INLINE void *safe_realloc_mul_2op_(void *ptr, size_t size1, size_t size2)
  93576. {
  93577. if(!size1 || !size2)
  93578. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  93579. if(size1 > SIZE_MAX / size2)
  93580. return 0;
  93581. return realloc(ptr, size1*size2);
  93582. }
  93583. /* size1 * (size2 + size3) */
  93584. static FLaC__INLINE void *safe_realloc_muladd2_(void *ptr, size_t size1, size_t size2, size_t size3)
  93585. {
  93586. if(!size1 || (!size2 && !size3))
  93587. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  93588. size2 += size3;
  93589. if(size2 < size3)
  93590. return 0;
  93591. return safe_realloc_mul_2op_(ptr, size1, size2);
  93592. }
  93593. #endif
  93594. /*** End of inlined file: alloc.h ***/
  93595. /* Things should be fastest when this matches the machine word size */
  93596. /* WATCHOUT: if you change this you must also change the following #defines down to SWAP_BE_WORD_TO_HOST below to match */
  93597. /* WATCHOUT: there are a few places where the code will not work unless bwword is >= 32 bits wide */
  93598. typedef FLAC__uint32 bwword;
  93599. #define FLAC__BYTES_PER_WORD 4
  93600. #define FLAC__BITS_PER_WORD 32
  93601. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  93602. /* SWAP_BE_WORD_TO_HOST swaps bytes in a bwword (which is always big-endian) if necessary to match host byte order */
  93603. #if WORDS_BIGENDIAN
  93604. #define SWAP_BE_WORD_TO_HOST(x) (x)
  93605. #else
  93606. #ifdef _MSC_VER
  93607. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  93608. #else
  93609. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  93610. #endif
  93611. #endif
  93612. /*
  93613. * The default capacity here doesn't matter too much. The buffer always grows
  93614. * to hold whatever is written to it. Usually the encoder will stop adding at
  93615. * a frame or metadata block, then write that out and clear the buffer for the
  93616. * next one.
  93617. */
  93618. static const unsigned FLAC__BITWRITER_DEFAULT_CAPACITY = 32768u / sizeof(bwword); /* size in words */
  93619. /* When growing, increment 4K at a time */
  93620. static const unsigned FLAC__BITWRITER_DEFAULT_INCREMENT = 4096u / sizeof(bwword); /* size in words */
  93621. #define FLAC__WORDS_TO_BITS(words) ((words) * FLAC__BITS_PER_WORD)
  93622. #define FLAC__TOTAL_BITS(bw) (FLAC__WORDS_TO_BITS((bw)->words) + (bw)->bits)
  93623. #ifdef min
  93624. #undef min
  93625. #endif
  93626. #define min(x,y) ((x)<(y)?(x):(y))
  93627. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  93628. #ifdef _MSC_VER
  93629. #define FLAC__U64L(x) x
  93630. #else
  93631. #define FLAC__U64L(x) x##LLU
  93632. #endif
  93633. #ifndef FLaC__INLINE
  93634. #define FLaC__INLINE
  93635. #endif
  93636. struct FLAC__BitWriter {
  93637. bwword *buffer;
  93638. bwword accum; /* accumulator; bits are right-justified; when full, accum is appended to buffer */
  93639. unsigned capacity; /* capacity of buffer in words */
  93640. unsigned words; /* # of complete words in buffer */
  93641. unsigned bits; /* # of used bits in accum */
  93642. };
  93643. /* * WATCHOUT: The current implementation only grows the buffer. */
  93644. static FLAC__bool bitwriter_grow_(FLAC__BitWriter *bw, unsigned bits_to_add)
  93645. {
  93646. unsigned new_capacity;
  93647. bwword *new_buffer;
  93648. FLAC__ASSERT(0 != bw);
  93649. FLAC__ASSERT(0 != bw->buffer);
  93650. /* calculate total words needed to store 'bits_to_add' additional bits */
  93651. new_capacity = bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD);
  93652. /* it's possible (due to pessimism in the growth estimation that
  93653. * leads to this call) that we don't actually need to grow
  93654. */
  93655. if(bw->capacity >= new_capacity)
  93656. return true;
  93657. /* round up capacity increase to the nearest FLAC__BITWRITER_DEFAULT_INCREMENT */
  93658. if((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT)
  93659. new_capacity += FLAC__BITWRITER_DEFAULT_INCREMENT - ((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  93660. /* make sure we got everything right */
  93661. FLAC__ASSERT(0 == (new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  93662. FLAC__ASSERT(new_capacity > bw->capacity);
  93663. FLAC__ASSERT(new_capacity >= bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD));
  93664. new_buffer = (bwword*)safe_realloc_mul_2op_(bw->buffer, sizeof(bwword), /*times*/new_capacity);
  93665. if(new_buffer == 0)
  93666. return false;
  93667. bw->buffer = new_buffer;
  93668. bw->capacity = new_capacity;
  93669. return true;
  93670. }
  93671. /***********************************************************************
  93672. *
  93673. * Class constructor/destructor
  93674. *
  93675. ***********************************************************************/
  93676. FLAC__BitWriter *FLAC__bitwriter_new(void)
  93677. {
  93678. FLAC__BitWriter *bw = (FLAC__BitWriter*)calloc(1, sizeof(FLAC__BitWriter));
  93679. /* note that calloc() sets all members to 0 for us */
  93680. return bw;
  93681. }
  93682. void FLAC__bitwriter_delete(FLAC__BitWriter *bw)
  93683. {
  93684. FLAC__ASSERT(0 != bw);
  93685. FLAC__bitwriter_free(bw);
  93686. free(bw);
  93687. }
  93688. /***********************************************************************
  93689. *
  93690. * Public class methods
  93691. *
  93692. ***********************************************************************/
  93693. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw)
  93694. {
  93695. FLAC__ASSERT(0 != bw);
  93696. bw->words = bw->bits = 0;
  93697. bw->capacity = FLAC__BITWRITER_DEFAULT_CAPACITY;
  93698. bw->buffer = (bwword*)malloc(sizeof(bwword) * bw->capacity);
  93699. if(bw->buffer == 0)
  93700. return false;
  93701. return true;
  93702. }
  93703. void FLAC__bitwriter_free(FLAC__BitWriter *bw)
  93704. {
  93705. FLAC__ASSERT(0 != bw);
  93706. if(0 != bw->buffer)
  93707. free(bw->buffer);
  93708. bw->buffer = 0;
  93709. bw->capacity = 0;
  93710. bw->words = bw->bits = 0;
  93711. }
  93712. void FLAC__bitwriter_clear(FLAC__BitWriter *bw)
  93713. {
  93714. bw->words = bw->bits = 0;
  93715. }
  93716. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out)
  93717. {
  93718. unsigned i, j;
  93719. if(bw == 0) {
  93720. fprintf(out, "bitwriter is NULL\n");
  93721. }
  93722. else {
  93723. fprintf(out, "bitwriter: capacity=%u words=%u bits=%u total_bits=%u\n", bw->capacity, bw->words, bw->bits, FLAC__TOTAL_BITS(bw));
  93724. for(i = 0; i < bw->words; i++) {
  93725. fprintf(out, "%08X: ", i);
  93726. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  93727. fprintf(out, "%01u", bw->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  93728. fprintf(out, "\n");
  93729. }
  93730. if(bw->bits > 0) {
  93731. fprintf(out, "%08X: ", i);
  93732. for(j = 0; j < bw->bits; j++)
  93733. fprintf(out, "%01u", bw->accum & (1 << (bw->bits-j-1)) ? 1:0);
  93734. fprintf(out, "\n");
  93735. }
  93736. }
  93737. }
  93738. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc)
  93739. {
  93740. const FLAC__byte *buffer;
  93741. size_t bytes;
  93742. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  93743. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  93744. return false;
  93745. *crc = (FLAC__uint16)FLAC__crc16(buffer, bytes);
  93746. FLAC__bitwriter_release_buffer(bw);
  93747. return true;
  93748. }
  93749. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc)
  93750. {
  93751. const FLAC__byte *buffer;
  93752. size_t bytes;
  93753. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  93754. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  93755. return false;
  93756. *crc = FLAC__crc8(buffer, bytes);
  93757. FLAC__bitwriter_release_buffer(bw);
  93758. return true;
  93759. }
  93760. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw)
  93761. {
  93762. return ((bw->bits & 7) == 0);
  93763. }
  93764. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw)
  93765. {
  93766. return FLAC__TOTAL_BITS(bw);
  93767. }
  93768. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes)
  93769. {
  93770. FLAC__ASSERT((bw->bits & 7) == 0);
  93771. /* double protection */
  93772. if(bw->bits & 7)
  93773. return false;
  93774. /* if we have bits in the accumulator we have to flush those to the buffer first */
  93775. if(bw->bits) {
  93776. FLAC__ASSERT(bw->words <= bw->capacity);
  93777. if(bw->words == bw->capacity && !bitwriter_grow_(bw, FLAC__BITS_PER_WORD))
  93778. return false;
  93779. /* append bits as complete word to buffer, but don't change bw->accum or bw->bits */
  93780. bw->buffer[bw->words] = SWAP_BE_WORD_TO_HOST(bw->accum << (FLAC__BITS_PER_WORD-bw->bits));
  93781. }
  93782. /* now we can just return what we have */
  93783. *buffer = (FLAC__byte*)bw->buffer;
  93784. *bytes = (FLAC__BYTES_PER_WORD * bw->words) + (bw->bits >> 3);
  93785. return true;
  93786. }
  93787. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw)
  93788. {
  93789. /* nothing to do. in the future, strict checking of a 'writer-is-in-
  93790. * get-mode' flag could be added everywhere and then cleared here
  93791. */
  93792. (void)bw;
  93793. }
  93794. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits)
  93795. {
  93796. unsigned n;
  93797. FLAC__ASSERT(0 != bw);
  93798. FLAC__ASSERT(0 != bw->buffer);
  93799. if(bits == 0)
  93800. return true;
  93801. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  93802. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  93803. return false;
  93804. /* first part gets to word alignment */
  93805. if(bw->bits) {
  93806. n = min(FLAC__BITS_PER_WORD - bw->bits, bits);
  93807. bw->accum <<= n;
  93808. bits -= n;
  93809. bw->bits += n;
  93810. if(bw->bits == FLAC__BITS_PER_WORD) {
  93811. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  93812. bw->bits = 0;
  93813. }
  93814. else
  93815. return true;
  93816. }
  93817. /* do whole words */
  93818. while(bits >= FLAC__BITS_PER_WORD) {
  93819. bw->buffer[bw->words++] = 0;
  93820. bits -= FLAC__BITS_PER_WORD;
  93821. }
  93822. /* do any leftovers */
  93823. if(bits > 0) {
  93824. bw->accum = 0;
  93825. bw->bits = bits;
  93826. }
  93827. return true;
  93828. }
  93829. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits)
  93830. {
  93831. register unsigned left;
  93832. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93833. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93834. FLAC__ASSERT(0 != bw);
  93835. FLAC__ASSERT(0 != bw->buffer);
  93836. FLAC__ASSERT(bits <= 32);
  93837. if(bits == 0)
  93838. return true;
  93839. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  93840. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  93841. return false;
  93842. left = FLAC__BITS_PER_WORD - bw->bits;
  93843. if(bits < left) {
  93844. bw->accum <<= bits;
  93845. bw->accum |= val;
  93846. bw->bits += bits;
  93847. }
  93848. 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 */
  93849. bw->accum <<= left;
  93850. bw->accum |= val >> (bw->bits = bits - left);
  93851. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  93852. bw->accum = val;
  93853. }
  93854. else {
  93855. bw->accum = val;
  93856. bw->bits = 0;
  93857. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(val);
  93858. }
  93859. return true;
  93860. }
  93861. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits)
  93862. {
  93863. /* zero-out unused bits */
  93864. if(bits < 32)
  93865. val &= (~(0xffffffff << bits));
  93866. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  93867. }
  93868. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits)
  93869. {
  93870. /* this could be a little faster but it's not used for much */
  93871. if(bits > 32) {
  93872. return
  93873. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(val>>32), bits-32) &&
  93874. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 32);
  93875. }
  93876. else
  93877. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  93878. }
  93879. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val)
  93880. {
  93881. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  93882. if(!FLAC__bitwriter_write_raw_uint32(bw, val & 0xff, 8))
  93883. return false;
  93884. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>8) & 0xff, 8))
  93885. return false;
  93886. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>16) & 0xff, 8))
  93887. return false;
  93888. if(!FLAC__bitwriter_write_raw_uint32(bw, val>>24, 8))
  93889. return false;
  93890. return true;
  93891. }
  93892. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals)
  93893. {
  93894. unsigned i;
  93895. /* this could be faster but currently we don't need it to be since it's only used for writing metadata */
  93896. for(i = 0; i < nvals; i++) {
  93897. if(!FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(vals[i]), 8))
  93898. return false;
  93899. }
  93900. return true;
  93901. }
  93902. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val)
  93903. {
  93904. if(val < 32)
  93905. return FLAC__bitwriter_write_raw_uint32(bw, 1, ++val);
  93906. else
  93907. return
  93908. FLAC__bitwriter_write_zeroes(bw, val) &&
  93909. FLAC__bitwriter_write_raw_uint32(bw, 1, 1);
  93910. }
  93911. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter)
  93912. {
  93913. FLAC__uint32 uval;
  93914. FLAC__ASSERT(parameter < sizeof(unsigned)*8);
  93915. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  93916. uval = (val<<1) ^ (val>>31);
  93917. return 1 + parameter + (uval >> parameter);
  93918. }
  93919. #if 0 /* UNUSED */
  93920. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter)
  93921. {
  93922. unsigned bits, msbs, uval;
  93923. unsigned k;
  93924. FLAC__ASSERT(parameter > 0);
  93925. /* fold signed to unsigned */
  93926. if(val < 0)
  93927. uval = (unsigned)(((-(++val)) << 1) + 1);
  93928. else
  93929. uval = (unsigned)(val << 1);
  93930. k = FLAC__bitmath_ilog2(parameter);
  93931. if(parameter == 1u<<k) {
  93932. FLAC__ASSERT(k <= 30);
  93933. msbs = uval >> k;
  93934. bits = 1 + k + msbs;
  93935. }
  93936. else {
  93937. unsigned q, r, d;
  93938. d = (1 << (k+1)) - parameter;
  93939. q = uval / parameter;
  93940. r = uval - (q * parameter);
  93941. bits = 1 + q + k;
  93942. if(r >= d)
  93943. bits++;
  93944. }
  93945. return bits;
  93946. }
  93947. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned uval, unsigned parameter)
  93948. {
  93949. unsigned bits, msbs;
  93950. unsigned k;
  93951. FLAC__ASSERT(parameter > 0);
  93952. k = FLAC__bitmath_ilog2(parameter);
  93953. if(parameter == 1u<<k) {
  93954. FLAC__ASSERT(k <= 30);
  93955. msbs = uval >> k;
  93956. bits = 1 + k + msbs;
  93957. }
  93958. else {
  93959. unsigned q, r, d;
  93960. d = (1 << (k+1)) - parameter;
  93961. q = uval / parameter;
  93962. r = uval - (q * parameter);
  93963. bits = 1 + q + k;
  93964. if(r >= d)
  93965. bits++;
  93966. }
  93967. return bits;
  93968. }
  93969. #endif /* UNUSED */
  93970. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter)
  93971. {
  93972. unsigned total_bits, interesting_bits, msbs;
  93973. FLAC__uint32 uval, pattern;
  93974. FLAC__ASSERT(0 != bw);
  93975. FLAC__ASSERT(0 != bw->buffer);
  93976. FLAC__ASSERT(parameter < 8*sizeof(uval));
  93977. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  93978. uval = (val<<1) ^ (val>>31);
  93979. msbs = uval >> parameter;
  93980. interesting_bits = 1 + parameter;
  93981. total_bits = interesting_bits + msbs;
  93982. pattern = 1 << parameter; /* the unary end bit */
  93983. pattern |= (uval & ((1<<parameter)-1)); /* the binary LSBs */
  93984. if(total_bits <= 32)
  93985. return FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits);
  93986. else
  93987. return
  93988. FLAC__bitwriter_write_zeroes(bw, msbs) && /* write the unary MSBs */
  93989. FLAC__bitwriter_write_raw_uint32(bw, pattern, interesting_bits); /* write the unary end bit and binary LSBs */
  93990. }
  93991. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter)
  93992. {
  93993. const FLAC__uint32 mask1 = FLAC__WORD_ALL_ONES << parameter; /* we val|=mask1 to set the stop bit above it... */
  93994. const FLAC__uint32 mask2 = FLAC__WORD_ALL_ONES >> (31-parameter); /* ...then mask off the bits above the stop bit with val&=mask2*/
  93995. FLAC__uint32 uval;
  93996. unsigned left;
  93997. const unsigned lsbits = 1 + parameter;
  93998. unsigned msbits;
  93999. FLAC__ASSERT(0 != bw);
  94000. FLAC__ASSERT(0 != bw->buffer);
  94001. FLAC__ASSERT(parameter < 8*sizeof(bwword)-1);
  94002. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  94003. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  94004. while(nvals) {
  94005. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94006. uval = (*vals<<1) ^ (*vals>>31);
  94007. msbits = uval >> parameter;
  94008. #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) */
  94009. if(bw->bits && bw->bits + msbits + lsbits <= FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  94010. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  94011. bw->bits = bw->bits + msbits + lsbits;
  94012. uval |= mask1; /* set stop bit */
  94013. uval &= mask2; /* mask off unused top bits */
  94014. /* NOT: bw->accum <<= msbits + lsbits because msbits+lsbits could be 32, then the shift would be a NOP */
  94015. bw->accum <<= msbits;
  94016. bw->accum <<= lsbits;
  94017. bw->accum |= uval;
  94018. if(bw->bits == FLAC__BITS_PER_WORD) {
  94019. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94020. bw->bits = 0;
  94021. /* burying the capacity check down here means we have to grow the buffer a little if there are more vals to do */
  94022. if(bw->capacity <= bw->words && nvals > 1 && !bitwriter_grow_(bw, 1)) {
  94023. FLAC__ASSERT(bw->capacity == bw->words);
  94024. return false;
  94025. }
  94026. }
  94027. }
  94028. else {
  94029. #elif 1 /*@@@@@@ OPT: try this version with MSVC6 to see if better, not much difference for gcc-4 */
  94030. if(bw->bits && bw->bits + msbits + lsbits < FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  94031. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  94032. bw->bits = bw->bits + msbits + lsbits;
  94033. uval |= mask1; /* set stop bit */
  94034. uval &= mask2; /* mask off unused top bits */
  94035. bw->accum <<= msbits + lsbits;
  94036. bw->accum |= uval;
  94037. }
  94038. else {
  94039. #endif
  94040. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+msbits+lsbits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94041. /* OPT: pessimism may cause flurry of false calls to grow_ which eat up all savings before it */
  94042. if(bw->capacity <= bw->words + bw->bits + msbits + 1/*lsbits always fit in 1 bwword*/ && !bitwriter_grow_(bw, msbits+lsbits))
  94043. return false;
  94044. if(msbits) {
  94045. /* first part gets to word alignment */
  94046. if(bw->bits) {
  94047. left = FLAC__BITS_PER_WORD - bw->bits;
  94048. if(msbits < left) {
  94049. bw->accum <<= msbits;
  94050. bw->bits += msbits;
  94051. goto break1;
  94052. }
  94053. else {
  94054. bw->accum <<= left;
  94055. msbits -= left;
  94056. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94057. bw->bits = 0;
  94058. }
  94059. }
  94060. /* do whole words */
  94061. while(msbits >= FLAC__BITS_PER_WORD) {
  94062. bw->buffer[bw->words++] = 0;
  94063. msbits -= FLAC__BITS_PER_WORD;
  94064. }
  94065. /* do any leftovers */
  94066. if(msbits > 0) {
  94067. bw->accum = 0;
  94068. bw->bits = msbits;
  94069. }
  94070. }
  94071. break1:
  94072. uval |= mask1; /* set stop bit */
  94073. uval &= mask2; /* mask off unused top bits */
  94074. left = FLAC__BITS_PER_WORD - bw->bits;
  94075. if(lsbits < left) {
  94076. bw->accum <<= lsbits;
  94077. bw->accum |= uval;
  94078. bw->bits += lsbits;
  94079. }
  94080. else {
  94081. /* if bw->bits == 0, left==FLAC__BITS_PER_WORD which will always
  94082. * be > lsbits (because of previous assertions) so it would have
  94083. * triggered the (lsbits<left) case above.
  94084. */
  94085. FLAC__ASSERT(bw->bits);
  94086. FLAC__ASSERT(left < FLAC__BITS_PER_WORD);
  94087. bw->accum <<= left;
  94088. bw->accum |= uval >> (bw->bits = lsbits - left);
  94089. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94090. bw->accum = uval;
  94091. }
  94092. #if 1
  94093. }
  94094. #endif
  94095. vals++;
  94096. nvals--;
  94097. }
  94098. return true;
  94099. }
  94100. #if 0 /* UNUSED */
  94101. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter)
  94102. {
  94103. unsigned total_bits, msbs, uval;
  94104. unsigned k;
  94105. FLAC__ASSERT(0 != bw);
  94106. FLAC__ASSERT(0 != bw->buffer);
  94107. FLAC__ASSERT(parameter > 0);
  94108. /* fold signed to unsigned */
  94109. if(val < 0)
  94110. uval = (unsigned)(((-(++val)) << 1) + 1);
  94111. else
  94112. uval = (unsigned)(val << 1);
  94113. k = FLAC__bitmath_ilog2(parameter);
  94114. if(parameter == 1u<<k) {
  94115. unsigned pattern;
  94116. FLAC__ASSERT(k <= 30);
  94117. msbs = uval >> k;
  94118. total_bits = 1 + k + msbs;
  94119. pattern = 1 << k; /* the unary end bit */
  94120. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  94121. if(total_bits <= 32) {
  94122. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  94123. return false;
  94124. }
  94125. else {
  94126. /* write the unary MSBs */
  94127. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  94128. return false;
  94129. /* write the unary end bit and binary LSBs */
  94130. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  94131. return false;
  94132. }
  94133. }
  94134. else {
  94135. unsigned q, r, d;
  94136. d = (1 << (k+1)) - parameter;
  94137. q = uval / parameter;
  94138. r = uval - (q * parameter);
  94139. /* write the unary MSBs */
  94140. if(!FLAC__bitwriter_write_zeroes(bw, q))
  94141. return false;
  94142. /* write the unary end bit */
  94143. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  94144. return false;
  94145. /* write the binary LSBs */
  94146. if(r >= d) {
  94147. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  94148. return false;
  94149. }
  94150. else {
  94151. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  94152. return false;
  94153. }
  94154. }
  94155. return true;
  94156. }
  94157. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned uval, unsigned parameter)
  94158. {
  94159. unsigned total_bits, msbs;
  94160. unsigned k;
  94161. FLAC__ASSERT(0 != bw);
  94162. FLAC__ASSERT(0 != bw->buffer);
  94163. FLAC__ASSERT(parameter > 0);
  94164. k = FLAC__bitmath_ilog2(parameter);
  94165. if(parameter == 1u<<k) {
  94166. unsigned pattern;
  94167. FLAC__ASSERT(k <= 30);
  94168. msbs = uval >> k;
  94169. total_bits = 1 + k + msbs;
  94170. pattern = 1 << k; /* the unary end bit */
  94171. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  94172. if(total_bits <= 32) {
  94173. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  94174. return false;
  94175. }
  94176. else {
  94177. /* write the unary MSBs */
  94178. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  94179. return false;
  94180. /* write the unary end bit and binary LSBs */
  94181. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  94182. return false;
  94183. }
  94184. }
  94185. else {
  94186. unsigned q, r, d;
  94187. d = (1 << (k+1)) - parameter;
  94188. q = uval / parameter;
  94189. r = uval - (q * parameter);
  94190. /* write the unary MSBs */
  94191. if(!FLAC__bitwriter_write_zeroes(bw, q))
  94192. return false;
  94193. /* write the unary end bit */
  94194. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  94195. return false;
  94196. /* write the binary LSBs */
  94197. if(r >= d) {
  94198. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  94199. return false;
  94200. }
  94201. else {
  94202. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  94203. return false;
  94204. }
  94205. }
  94206. return true;
  94207. }
  94208. #endif /* UNUSED */
  94209. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val)
  94210. {
  94211. FLAC__bool ok = 1;
  94212. FLAC__ASSERT(0 != bw);
  94213. FLAC__ASSERT(0 != bw->buffer);
  94214. FLAC__ASSERT(!(val & 0x80000000)); /* this version only handles 31 bits */
  94215. if(val < 0x80) {
  94216. return FLAC__bitwriter_write_raw_uint32(bw, val, 8);
  94217. }
  94218. else if(val < 0x800) {
  94219. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (val>>6), 8);
  94220. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94221. }
  94222. else if(val < 0x10000) {
  94223. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (val>>12), 8);
  94224. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  94225. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94226. }
  94227. else if(val < 0x200000) {
  94228. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (val>>18), 8);
  94229. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  94230. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  94231. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94232. }
  94233. else if(val < 0x4000000) {
  94234. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (val>>24), 8);
  94235. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  94236. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  94237. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  94238. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94239. }
  94240. else {
  94241. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (val>>30), 8);
  94242. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>24)&0x3F), 8);
  94243. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  94244. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  94245. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  94246. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94247. }
  94248. return ok;
  94249. }
  94250. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val)
  94251. {
  94252. FLAC__bool ok = 1;
  94253. FLAC__ASSERT(0 != bw);
  94254. FLAC__ASSERT(0 != bw->buffer);
  94255. FLAC__ASSERT(!(val & FLAC__U64L(0xFFFFFFF000000000))); /* this version only handles 36 bits */
  94256. if(val < 0x80) {
  94257. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 8);
  94258. }
  94259. else if(val < 0x800) {
  94260. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (FLAC__uint32)(val>>6), 8);
  94261. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94262. }
  94263. else if(val < 0x10000) {
  94264. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (FLAC__uint32)(val>>12), 8);
  94265. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94266. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94267. }
  94268. else if(val < 0x200000) {
  94269. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (FLAC__uint32)(val>>18), 8);
  94270. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  94271. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94272. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94273. }
  94274. else if(val < 0x4000000) {
  94275. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (FLAC__uint32)(val>>24), 8);
  94276. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  94277. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  94278. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94279. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94280. }
  94281. else if(val < 0x80000000) {
  94282. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (FLAC__uint32)(val>>30), 8);
  94283. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  94284. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  94285. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  94286. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94287. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94288. }
  94289. else {
  94290. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFE, 8);
  94291. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>30)&0x3F), 8);
  94292. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  94293. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  94294. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  94295. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94296. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94297. }
  94298. return ok;
  94299. }
  94300. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw)
  94301. {
  94302. /* 0-pad to byte boundary */
  94303. if(bw->bits & 7u)
  94304. return FLAC__bitwriter_write_zeroes(bw, 8 - (bw->bits & 7u));
  94305. else
  94306. return true;
  94307. }
  94308. #endif
  94309. /*** End of inlined file: bitwriter.c ***/
  94310. /*** Start of inlined file: cpu.c ***/
  94311. /*** Start of inlined file: juce_FlacHeader.h ***/
  94312. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94313. // tasks..
  94314. #define VERSION "1.2.1"
  94315. #define FLAC__NO_DLL 1
  94316. #if JUCE_MSVC
  94317. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94318. #endif
  94319. #if JUCE_MAC
  94320. #define FLAC__SYS_DARWIN 1
  94321. #endif
  94322. /*** End of inlined file: juce_FlacHeader.h ***/
  94323. #if JUCE_USE_FLAC
  94324. #if HAVE_CONFIG_H
  94325. # include <config.h>
  94326. #endif
  94327. #include <stdlib.h>
  94328. #include <stdio.h>
  94329. #if defined FLAC__CPU_IA32
  94330. # include <signal.h>
  94331. #elif defined FLAC__CPU_PPC
  94332. # if !defined FLAC__NO_ASM
  94333. # if defined FLAC__SYS_DARWIN
  94334. # include <sys/sysctl.h>
  94335. # include <mach/mach.h>
  94336. # include <mach/mach_host.h>
  94337. # include <mach/host_info.h>
  94338. # include <mach/machine.h>
  94339. # ifndef CPU_SUBTYPE_POWERPC_970
  94340. # define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100)
  94341. # endif
  94342. # else /* FLAC__SYS_DARWIN */
  94343. # include <signal.h>
  94344. # include <setjmp.h>
  94345. static sigjmp_buf jmpbuf;
  94346. static volatile sig_atomic_t canjump = 0;
  94347. static void sigill_handler (int sig)
  94348. {
  94349. if (!canjump) {
  94350. signal (sig, SIG_DFL);
  94351. raise (sig);
  94352. }
  94353. canjump = 0;
  94354. siglongjmp (jmpbuf, 1);
  94355. }
  94356. # endif /* FLAC__SYS_DARWIN */
  94357. # endif /* FLAC__NO_ASM */
  94358. #endif /* FLAC__CPU_PPC */
  94359. #if defined (__NetBSD__) || defined(__OpenBSD__)
  94360. #include <sys/param.h>
  94361. #include <sys/sysctl.h>
  94362. #include <machine/cpu.h>
  94363. #endif
  94364. #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
  94365. #include <sys/types.h>
  94366. #include <sys/sysctl.h>
  94367. #endif
  94368. #if defined(__APPLE__)
  94369. /* how to get sysctlbyname()? */
  94370. #endif
  94371. /* these are flags in EDX of CPUID AX=00000001 */
  94372. static const unsigned FLAC__CPUINFO_IA32_CPUID_CMOV = 0x00008000;
  94373. static const unsigned FLAC__CPUINFO_IA32_CPUID_MMX = 0x00800000;
  94374. static const unsigned FLAC__CPUINFO_IA32_CPUID_FXSR = 0x01000000;
  94375. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE = 0x02000000;
  94376. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE2 = 0x04000000;
  94377. /* these are flags in ECX of CPUID AX=00000001 */
  94378. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE3 = 0x00000001;
  94379. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSSE3 = 0x00000200;
  94380. /* these are flags in EDX of CPUID AX=80000001 */
  94381. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW = 0x80000000;
  94382. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW = 0x40000000;
  94383. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX = 0x00400000;
  94384. /*
  94385. * Extra stuff needed for detection of OS support for SSE on IA-32
  94386. */
  94387. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM && !defined FLAC__NO_SSE_OS && !defined FLAC__SSE_OS
  94388. # if defined(__linux__)
  94389. /*
  94390. * If the OS doesn't support SSE, we will get here with a SIGILL. We
  94391. * modify the return address to jump over the offending SSE instruction
  94392. * and also the operation following it that indicates the instruction
  94393. * executed successfully. In this way we use no global variables and
  94394. * stay thread-safe.
  94395. *
  94396. * 3 + 3 + 6:
  94397. * 3 bytes for "xorps xmm0,xmm0"
  94398. * 3 bytes for estimate of how long the follwing "inc var" instruction is
  94399. * 6 bytes extra in case our estimate is wrong
  94400. * 12 bytes puts us in the NOP "landing zone"
  94401. */
  94402. # undef USE_OBSOLETE_SIGCONTEXT_FLAVOR /* #define this to use the older signal handler method */
  94403. # ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  94404. static void sigill_handler_sse_os(int signal, struct sigcontext sc)
  94405. {
  94406. (void)signal;
  94407. sc.eip += 3 + 3 + 6;
  94408. }
  94409. # else
  94410. # include <sys/ucontext.h>
  94411. static void sigill_handler_sse_os(int signal, siginfo_t *si, void *uc)
  94412. {
  94413. (void)signal, (void)si;
  94414. ((ucontext_t*)uc)->uc_mcontext.gregs[14/*REG_EIP*/] += 3 + 3 + 6;
  94415. }
  94416. # endif
  94417. # elif defined(_MSC_VER)
  94418. # include <windows.h>
  94419. # undef USE_TRY_CATCH_FLAVOR /* #define this to use the try/catch method for catching illegal opcode exception */
  94420. # ifdef USE_TRY_CATCH_FLAVOR
  94421. # else
  94422. LONG CALLBACK sigill_handler_sse_os(EXCEPTION_POINTERS *ep)
  94423. {
  94424. if(ep->ExceptionRecord->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION) {
  94425. ep->ContextRecord->Eip += 3 + 3 + 6;
  94426. return EXCEPTION_CONTINUE_EXECUTION;
  94427. }
  94428. return EXCEPTION_CONTINUE_SEARCH;
  94429. }
  94430. # endif
  94431. # endif
  94432. #endif
  94433. void FLAC__cpu_info(FLAC__CPUInfo *info)
  94434. {
  94435. /*
  94436. * IA32-specific
  94437. */
  94438. #ifdef FLAC__CPU_IA32
  94439. info->type = FLAC__CPUINFO_TYPE_IA32;
  94440. #if !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  94441. info->use_asm = true; /* we assume a minimum of 80386 with FLAC__CPU_IA32 */
  94442. info->data.ia32.cpuid = FLAC__cpu_have_cpuid_asm_ia32()? true : false;
  94443. info->data.ia32.bswap = info->data.ia32.cpuid; /* CPUID => BSWAP since it came after */
  94444. info->data.ia32.cmov = false;
  94445. info->data.ia32.mmx = false;
  94446. info->data.ia32.fxsr = false;
  94447. info->data.ia32.sse = false;
  94448. info->data.ia32.sse2 = false;
  94449. info->data.ia32.sse3 = false;
  94450. info->data.ia32.ssse3 = false;
  94451. info->data.ia32._3dnow = false;
  94452. info->data.ia32.ext3dnow = false;
  94453. info->data.ia32.extmmx = false;
  94454. if(info->data.ia32.cpuid) {
  94455. /* http://www.sandpile.org/ia32/cpuid.htm */
  94456. FLAC__uint32 flags_edx, flags_ecx;
  94457. FLAC__cpu_info_asm_ia32(&flags_edx, &flags_ecx);
  94458. info->data.ia32.cmov = (flags_edx & FLAC__CPUINFO_IA32_CPUID_CMOV )? true : false;
  94459. info->data.ia32.mmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_MMX )? true : false;
  94460. info->data.ia32.fxsr = (flags_edx & FLAC__CPUINFO_IA32_CPUID_FXSR )? true : false;
  94461. info->data.ia32.sse = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE )? true : false;
  94462. info->data.ia32.sse2 = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE2 )? true : false;
  94463. info->data.ia32.sse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSE3 )? true : false;
  94464. info->data.ia32.ssse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSSE3)? true : false;
  94465. #ifdef FLAC__USE_3DNOW
  94466. flags_edx = FLAC__cpu_info_extended_amd_asm_ia32();
  94467. info->data.ia32._3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW )? true : false;
  94468. info->data.ia32.ext3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW)? true : false;
  94469. info->data.ia32.extmmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX )? true : false;
  94470. #else
  94471. info->data.ia32._3dnow = info->data.ia32.ext3dnow = info->data.ia32.extmmx = false;
  94472. #endif
  94473. #ifdef DEBUG
  94474. fprintf(stderr, "CPU info (IA-32):\n");
  94475. fprintf(stderr, " CPUID ...... %c\n", info->data.ia32.cpuid ? 'Y' : 'n');
  94476. fprintf(stderr, " BSWAP ...... %c\n", info->data.ia32.bswap ? 'Y' : 'n');
  94477. fprintf(stderr, " CMOV ....... %c\n", info->data.ia32.cmov ? 'Y' : 'n');
  94478. fprintf(stderr, " MMX ........ %c\n", info->data.ia32.mmx ? 'Y' : 'n');
  94479. fprintf(stderr, " FXSR ....... %c\n", info->data.ia32.fxsr ? 'Y' : 'n');
  94480. fprintf(stderr, " SSE ........ %c\n", info->data.ia32.sse ? 'Y' : 'n');
  94481. fprintf(stderr, " SSE2 ....... %c\n", info->data.ia32.sse2 ? 'Y' : 'n');
  94482. fprintf(stderr, " SSE3 ....... %c\n", info->data.ia32.sse3 ? 'Y' : 'n');
  94483. fprintf(stderr, " SSSE3 ...... %c\n", info->data.ia32.ssse3 ? 'Y' : 'n');
  94484. fprintf(stderr, " 3DNow! ..... %c\n", info->data.ia32._3dnow ? 'Y' : 'n');
  94485. fprintf(stderr, " 3DNow!-ext . %c\n", info->data.ia32.ext3dnow? 'Y' : 'n');
  94486. fprintf(stderr, " 3DNow!-MMX . %c\n", info->data.ia32.extmmx ? 'Y' : 'n');
  94487. #endif
  94488. /*
  94489. * now have to check for OS support of SSE/SSE2
  94490. */
  94491. if(info->data.ia32.fxsr || info->data.ia32.sse || info->data.ia32.sse2) {
  94492. #if defined FLAC__NO_SSE_OS
  94493. /* assume user knows better than us; turn it off */
  94494. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94495. #elif defined FLAC__SSE_OS
  94496. /* assume user knows better than us; leave as detected above */
  94497. #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
  94498. int sse = 0;
  94499. size_t len;
  94500. /* at least one of these must work: */
  94501. len = sizeof(sse); sse = sse || (sysctlbyname("hw.instruction_sse", &sse, &len, NULL, 0) == 0 && sse);
  94502. len = sizeof(sse); sse = sse || (sysctlbyname("hw.optional.sse" , &sse, &len, NULL, 0) == 0 && sse); /* __APPLE__ ? */
  94503. if(!sse)
  94504. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94505. #elif defined(__NetBSD__) || defined (__OpenBSD__)
  94506. # if __NetBSD_Version__ >= 105250000 || (defined __OpenBSD__)
  94507. int val = 0, mib[2] = { CTL_MACHDEP, CPU_SSE };
  94508. size_t len = sizeof(val);
  94509. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  94510. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94511. else { /* double-check SSE2 */
  94512. mib[1] = CPU_SSE2;
  94513. len = sizeof(val);
  94514. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  94515. info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94516. }
  94517. # else
  94518. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94519. # endif
  94520. #elif defined(__linux__)
  94521. int sse = 0;
  94522. struct sigaction sigill_save;
  94523. #ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  94524. if(0 == sigaction(SIGILL, NULL, &sigill_save) && signal(SIGILL, (void (*)(int))sigill_handler_sse_os) != SIG_ERR)
  94525. #else
  94526. struct sigaction sigill_sse;
  94527. sigill_sse.sa_sigaction = sigill_handler_sse_os;
  94528. __sigemptyset(&sigill_sse.sa_mask);
  94529. 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 */
  94530. if(0 == sigaction(SIGILL, &sigill_sse, &sigill_save))
  94531. #endif
  94532. {
  94533. /* http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html */
  94534. /* see sigill_handler_sse_os() for an explanation of the following: */
  94535. asm volatile (
  94536. "xorl %0,%0\n\t" /* for some reason, still need to do this to clear 'sse' var */
  94537. "xorps %%xmm0,%%xmm0\n\t" /* will cause SIGILL if unsupported by OS */
  94538. "incl %0\n\t" /* SIGILL handler will jump over this */
  94539. /* landing zone */
  94540. "nop\n\t" /* SIGILL jump lands here if "inc" is 9 bytes */
  94541. "nop\n\t"
  94542. "nop\n\t"
  94543. "nop\n\t"
  94544. "nop\n\t"
  94545. "nop\n\t"
  94546. "nop\n\t" /* SIGILL jump lands here if "inc" is 3 bytes (expected) */
  94547. "nop\n\t"
  94548. "nop" /* SIGILL jump lands here if "inc" is 1 byte */
  94549. : "=r"(sse)
  94550. : "r"(sse)
  94551. );
  94552. sigaction(SIGILL, &sigill_save, NULL);
  94553. }
  94554. if(!sse)
  94555. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94556. #elif defined(_MSC_VER)
  94557. # ifdef USE_TRY_CATCH_FLAVOR
  94558. _try {
  94559. __asm {
  94560. # if _MSC_VER <= 1200
  94561. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  94562. _emit 0x0F
  94563. _emit 0x57
  94564. _emit 0xC0
  94565. # else
  94566. xorps xmm0,xmm0
  94567. # endif
  94568. }
  94569. }
  94570. _except(EXCEPTION_EXECUTE_HANDLER) {
  94571. if (_exception_code() == STATUS_ILLEGAL_INSTRUCTION)
  94572. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94573. }
  94574. # else
  94575. int sse = 0;
  94576. LPTOP_LEVEL_EXCEPTION_FILTER save = SetUnhandledExceptionFilter(sigill_handler_sse_os);
  94577. /* see GCC version above for explanation */
  94578. /* http://msdn2.microsoft.com/en-us/library/4ks26t93.aspx */
  94579. /* http://www.codeproject.com/cpp/gccasm.asp */
  94580. /* http://www.hick.org/~mmiller/msvc_inline_asm.html */
  94581. __asm {
  94582. # if _MSC_VER <= 1200
  94583. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  94584. _emit 0x0F
  94585. _emit 0x57
  94586. _emit 0xC0
  94587. # else
  94588. xorps xmm0,xmm0
  94589. # endif
  94590. inc sse
  94591. nop
  94592. nop
  94593. nop
  94594. nop
  94595. nop
  94596. nop
  94597. nop
  94598. nop
  94599. nop
  94600. }
  94601. SetUnhandledExceptionFilter(save);
  94602. if(!sse)
  94603. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94604. # endif
  94605. #else
  94606. /* no way to test, disable to be safe */
  94607. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94608. #endif
  94609. #ifdef DEBUG
  94610. fprintf(stderr, " SSE OS sup . %c\n", info->data.ia32.sse ? 'Y' : 'n');
  94611. #endif
  94612. }
  94613. }
  94614. #else
  94615. info->use_asm = false;
  94616. #endif
  94617. /*
  94618. * PPC-specific
  94619. */
  94620. #elif defined FLAC__CPU_PPC
  94621. info->type = FLAC__CPUINFO_TYPE_PPC;
  94622. # if !defined FLAC__NO_ASM
  94623. info->use_asm = true;
  94624. # ifdef FLAC__USE_ALTIVEC
  94625. # if defined FLAC__SYS_DARWIN
  94626. {
  94627. int val = 0, mib[2] = { CTL_HW, HW_VECTORUNIT };
  94628. size_t len = sizeof(val);
  94629. info->data.ppc.altivec = !(sysctl(mib, 2, &val, &len, NULL, 0) || !val);
  94630. }
  94631. {
  94632. host_basic_info_data_t hostInfo;
  94633. mach_msg_type_number_t infoCount;
  94634. infoCount = HOST_BASIC_INFO_COUNT;
  94635. host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo, &infoCount);
  94636. info->data.ppc.ppc64 = (hostInfo.cpu_type == CPU_TYPE_POWERPC) && (hostInfo.cpu_subtype == CPU_SUBTYPE_POWERPC_970);
  94637. }
  94638. # else /* FLAC__USE_ALTIVEC && !FLAC__SYS_DARWIN */
  94639. {
  94640. /* no Darwin, do it the brute-force way */
  94641. /* @@@@@@ this is not thread-safe; replace with SSE OS method above or remove */
  94642. info->data.ppc.altivec = 0;
  94643. info->data.ppc.ppc64 = 0;
  94644. signal (SIGILL, sigill_handler);
  94645. canjump = 0;
  94646. if (!sigsetjmp (jmpbuf, 1)) {
  94647. canjump = 1;
  94648. asm volatile (
  94649. "mtspr 256, %0\n\t"
  94650. "vand %%v0, %%v0, %%v0"
  94651. :
  94652. : "r" (-1)
  94653. );
  94654. info->data.ppc.altivec = 1;
  94655. }
  94656. canjump = 0;
  94657. if (!sigsetjmp (jmpbuf, 1)) {
  94658. int x = 0;
  94659. canjump = 1;
  94660. /* PPC64 hardware implements the cntlzd instruction */
  94661. asm volatile ("cntlzd %0, %1" : "=r" (x) : "r" (x) );
  94662. info->data.ppc.ppc64 = 1;
  94663. }
  94664. signal (SIGILL, SIG_DFL); /*@@@@@@ should save and restore old signal */
  94665. }
  94666. # endif
  94667. # else /* !FLAC__USE_ALTIVEC */
  94668. info->data.ppc.altivec = 0;
  94669. info->data.ppc.ppc64 = 0;
  94670. # endif
  94671. # else
  94672. info->use_asm = false;
  94673. # endif
  94674. /*
  94675. * unknown CPI
  94676. */
  94677. #else
  94678. info->type = FLAC__CPUINFO_TYPE_UNKNOWN;
  94679. info->use_asm = false;
  94680. #endif
  94681. }
  94682. #endif
  94683. /*** End of inlined file: cpu.c ***/
  94684. /*** Start of inlined file: crc.c ***/
  94685. /*** Start of inlined file: juce_FlacHeader.h ***/
  94686. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94687. // tasks..
  94688. #define VERSION "1.2.1"
  94689. #define FLAC__NO_DLL 1
  94690. #if JUCE_MSVC
  94691. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94692. #endif
  94693. #if JUCE_MAC
  94694. #define FLAC__SYS_DARWIN 1
  94695. #endif
  94696. /*** End of inlined file: juce_FlacHeader.h ***/
  94697. #if JUCE_USE_FLAC
  94698. #if HAVE_CONFIG_H
  94699. # include <config.h>
  94700. #endif
  94701. /* CRC-8, poly = x^8 + x^2 + x^1 + x^0, init = 0 */
  94702. FLAC__byte const FLAC__crc8_table[256] = {
  94703. 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15,
  94704. 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
  94705. 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65,
  94706. 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
  94707. 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5,
  94708. 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
  94709. 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85,
  94710. 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
  94711. 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2,
  94712. 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
  94713. 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2,
  94714. 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
  94715. 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32,
  94716. 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
  94717. 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42,
  94718. 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
  94719. 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C,
  94720. 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
  94721. 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC,
  94722. 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
  94723. 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C,
  94724. 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
  94725. 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C,
  94726. 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
  94727. 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B,
  94728. 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
  94729. 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B,
  94730. 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
  94731. 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB,
  94732. 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
  94733. 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB,
  94734. 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
  94735. };
  94736. /* CRC-16, poly = x^16 + x^15 + x^2 + x^0, init = 0 */
  94737. unsigned FLAC__crc16_table[256] = {
  94738. 0x0000, 0x8005, 0x800f, 0x000a, 0x801b, 0x001e, 0x0014, 0x8011,
  94739. 0x8033, 0x0036, 0x003c, 0x8039, 0x0028, 0x802d, 0x8027, 0x0022,
  94740. 0x8063, 0x0066, 0x006c, 0x8069, 0x0078, 0x807d, 0x8077, 0x0072,
  94741. 0x0050, 0x8055, 0x805f, 0x005a, 0x804b, 0x004e, 0x0044, 0x8041,
  94742. 0x80c3, 0x00c6, 0x00cc, 0x80c9, 0x00d8, 0x80dd, 0x80d7, 0x00d2,
  94743. 0x00f0, 0x80f5, 0x80ff, 0x00fa, 0x80eb, 0x00ee, 0x00e4, 0x80e1,
  94744. 0x00a0, 0x80a5, 0x80af, 0x00aa, 0x80bb, 0x00be, 0x00b4, 0x80b1,
  94745. 0x8093, 0x0096, 0x009c, 0x8099, 0x0088, 0x808d, 0x8087, 0x0082,
  94746. 0x8183, 0x0186, 0x018c, 0x8189, 0x0198, 0x819d, 0x8197, 0x0192,
  94747. 0x01b0, 0x81b5, 0x81bf, 0x01ba, 0x81ab, 0x01ae, 0x01a4, 0x81a1,
  94748. 0x01e0, 0x81e5, 0x81ef, 0x01ea, 0x81fb, 0x01fe, 0x01f4, 0x81f1,
  94749. 0x81d3, 0x01d6, 0x01dc, 0x81d9, 0x01c8, 0x81cd, 0x81c7, 0x01c2,
  94750. 0x0140, 0x8145, 0x814f, 0x014a, 0x815b, 0x015e, 0x0154, 0x8151,
  94751. 0x8173, 0x0176, 0x017c, 0x8179, 0x0168, 0x816d, 0x8167, 0x0162,
  94752. 0x8123, 0x0126, 0x012c, 0x8129, 0x0138, 0x813d, 0x8137, 0x0132,
  94753. 0x0110, 0x8115, 0x811f, 0x011a, 0x810b, 0x010e, 0x0104, 0x8101,
  94754. 0x8303, 0x0306, 0x030c, 0x8309, 0x0318, 0x831d, 0x8317, 0x0312,
  94755. 0x0330, 0x8335, 0x833f, 0x033a, 0x832b, 0x032e, 0x0324, 0x8321,
  94756. 0x0360, 0x8365, 0x836f, 0x036a, 0x837b, 0x037e, 0x0374, 0x8371,
  94757. 0x8353, 0x0356, 0x035c, 0x8359, 0x0348, 0x834d, 0x8347, 0x0342,
  94758. 0x03c0, 0x83c5, 0x83cf, 0x03ca, 0x83db, 0x03de, 0x03d4, 0x83d1,
  94759. 0x83f3, 0x03f6, 0x03fc, 0x83f9, 0x03e8, 0x83ed, 0x83e7, 0x03e2,
  94760. 0x83a3, 0x03a6, 0x03ac, 0x83a9, 0x03b8, 0x83bd, 0x83b7, 0x03b2,
  94761. 0x0390, 0x8395, 0x839f, 0x039a, 0x838b, 0x038e, 0x0384, 0x8381,
  94762. 0x0280, 0x8285, 0x828f, 0x028a, 0x829b, 0x029e, 0x0294, 0x8291,
  94763. 0x82b3, 0x02b6, 0x02bc, 0x82b9, 0x02a8, 0x82ad, 0x82a7, 0x02a2,
  94764. 0x82e3, 0x02e6, 0x02ec, 0x82e9, 0x02f8, 0x82fd, 0x82f7, 0x02f2,
  94765. 0x02d0, 0x82d5, 0x82df, 0x02da, 0x82cb, 0x02ce, 0x02c4, 0x82c1,
  94766. 0x8243, 0x0246, 0x024c, 0x8249, 0x0258, 0x825d, 0x8257, 0x0252,
  94767. 0x0270, 0x8275, 0x827f, 0x027a, 0x826b, 0x026e, 0x0264, 0x8261,
  94768. 0x0220, 0x8225, 0x822f, 0x022a, 0x823b, 0x023e, 0x0234, 0x8231,
  94769. 0x8213, 0x0216, 0x021c, 0x8219, 0x0208, 0x820d, 0x8207, 0x0202
  94770. };
  94771. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc)
  94772. {
  94773. *crc = FLAC__crc8_table[*crc ^ data];
  94774. }
  94775. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc)
  94776. {
  94777. while(len--)
  94778. *crc = FLAC__crc8_table[*crc ^ *data++];
  94779. }
  94780. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len)
  94781. {
  94782. FLAC__uint8 crc = 0;
  94783. while(len--)
  94784. crc = FLAC__crc8_table[crc ^ *data++];
  94785. return crc;
  94786. }
  94787. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len)
  94788. {
  94789. unsigned crc = 0;
  94790. while(len--)
  94791. crc = ((crc<<8) ^ FLAC__crc16_table[(crc>>8) ^ *data++]) & 0xffff;
  94792. return crc;
  94793. }
  94794. #endif
  94795. /*** End of inlined file: crc.c ***/
  94796. /*** Start of inlined file: fixed.c ***/
  94797. /*** Start of inlined file: juce_FlacHeader.h ***/
  94798. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94799. // tasks..
  94800. #define VERSION "1.2.1"
  94801. #define FLAC__NO_DLL 1
  94802. #if JUCE_MSVC
  94803. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94804. #endif
  94805. #if JUCE_MAC
  94806. #define FLAC__SYS_DARWIN 1
  94807. #endif
  94808. /*** End of inlined file: juce_FlacHeader.h ***/
  94809. #if JUCE_USE_FLAC
  94810. #if HAVE_CONFIG_H
  94811. # include <config.h>
  94812. #endif
  94813. #include <math.h>
  94814. #include <string.h>
  94815. /*** Start of inlined file: fixed.h ***/
  94816. #ifndef FLAC__PRIVATE__FIXED_H
  94817. #define FLAC__PRIVATE__FIXED_H
  94818. #ifdef HAVE_CONFIG_H
  94819. #include <config.h>
  94820. #endif
  94821. /*** Start of inlined file: float.h ***/
  94822. #ifndef FLAC__PRIVATE__FLOAT_H
  94823. #define FLAC__PRIVATE__FLOAT_H
  94824. #ifdef HAVE_CONFIG_H
  94825. #include <config.h>
  94826. #endif
  94827. /*
  94828. * These typedefs make it easier to ensure that integer versions of
  94829. * the library really only contain integer operations. All the code
  94830. * in libFLAC should use FLAC__float and FLAC__double in place of
  94831. * float and double, and be protected by checks of the macro
  94832. * FLAC__INTEGER_ONLY_LIBRARY.
  94833. *
  94834. * FLAC__real is the basic floating point type used in LPC analysis.
  94835. */
  94836. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  94837. typedef double FLAC__double;
  94838. typedef float FLAC__float;
  94839. /*
  94840. * WATCHOUT: changing FLAC__real will change the signatures of many
  94841. * functions that have assembly language equivalents and break them.
  94842. */
  94843. typedef float FLAC__real;
  94844. #else
  94845. /*
  94846. * The convention for FLAC__fixedpoint is to use the upper 16 bits
  94847. * for the integer part and lower 16 bits for the fractional part.
  94848. */
  94849. typedef FLAC__int32 FLAC__fixedpoint;
  94850. extern const FLAC__fixedpoint FLAC__FP_ZERO;
  94851. extern const FLAC__fixedpoint FLAC__FP_ONE_HALF;
  94852. extern const FLAC__fixedpoint FLAC__FP_ONE;
  94853. extern const FLAC__fixedpoint FLAC__FP_LN2;
  94854. extern const FLAC__fixedpoint FLAC__FP_E;
  94855. #define FLAC__fixedpoint_trunc(x) ((x)>>16)
  94856. #define FLAC__fixedpoint_mul(x, y) ( (FLAC__fixedpoint) ( ((FLAC__int64)(x)*(FLAC__int64)(y)) >> 16 ) )
  94857. #define FLAC__fixedpoint_div(x, y) ( (FLAC__fixedpoint) ( ( ((FLAC__int64)(x)<<32) / (FLAC__int64)(y) ) >> 16 ) )
  94858. /*
  94859. * FLAC__fixedpoint_log2()
  94860. * --------------------------------------------------------------------
  94861. * Returns the base-2 logarithm of the fixed-point number 'x' using an
  94862. * algorithm by Knuth for x >= 1.0
  94863. *
  94864. * 'fracbits' is the number of fractional bits of 'x'. 'fracbits' must
  94865. * be < 32 and evenly divisible by 4 (0 is OK but not very precise).
  94866. *
  94867. * 'precision' roughly limits the number of iterations that are done;
  94868. * use (unsigned)(-1) for maximum precision.
  94869. *
  94870. * If 'x' is less than one -- that is, x < (1<<fracbits) -- then this
  94871. * function will punt and return 0.
  94872. *
  94873. * The return value will also have 'fracbits' fractional bits.
  94874. */
  94875. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision);
  94876. #endif
  94877. #endif
  94878. /*** End of inlined file: float.h ***/
  94879. /*** Start of inlined file: format.h ***/
  94880. #ifndef FLAC__PRIVATE__FORMAT_H
  94881. #define FLAC__PRIVATE__FORMAT_H
  94882. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order);
  94883. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize);
  94884. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order);
  94885. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  94886. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  94887. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order);
  94888. #endif
  94889. /*** End of inlined file: format.h ***/
  94890. /*
  94891. * FLAC__fixed_compute_best_predictor()
  94892. * --------------------------------------------------------------------
  94893. * Compute the best fixed predictor and the expected bits-per-sample
  94894. * of the residual signal for each order. The _wide() version uses
  94895. * 64-bit integers which is statistically necessary when bits-per-
  94896. * sample + log2(blocksize) > 30
  94897. *
  94898. * IN data[0,data_len-1]
  94899. * IN data_len
  94900. * OUT residual_bits_per_sample[0,FLAC__MAX_FIXED_ORDER]
  94901. */
  94902. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  94903. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  94904. # ifndef FLAC__NO_ASM
  94905. # ifdef FLAC__CPU_IA32
  94906. # ifdef FLAC__HAS_NASM
  94907. 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]);
  94908. # endif
  94909. # endif
  94910. # endif
  94911. 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]);
  94912. #else
  94913. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  94914. 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]);
  94915. #endif
  94916. /*
  94917. * FLAC__fixed_compute_residual()
  94918. * --------------------------------------------------------------------
  94919. * Compute the residual signal obtained from sutracting the predicted
  94920. * signal from the original.
  94921. *
  94922. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  94923. * IN data_len length of original signal
  94924. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  94925. * OUT residual[0,data_len-1] residual signal
  94926. */
  94927. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[]);
  94928. /*
  94929. * FLAC__fixed_restore_signal()
  94930. * --------------------------------------------------------------------
  94931. * Restore the original signal by summing the residual and the
  94932. * predictor.
  94933. *
  94934. * IN residual[0,data_len-1] residual signal
  94935. * IN data_len length of original signal
  94936. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  94937. * *** IMPORTANT: the caller must pass in the historical samples:
  94938. * IN data[-order,-1] previously-reconstructed historical samples
  94939. * OUT data[0,data_len-1] original signal
  94940. */
  94941. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[]);
  94942. #endif
  94943. /*** End of inlined file: fixed.h ***/
  94944. #ifndef M_LN2
  94945. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  94946. #define M_LN2 0.69314718055994530942
  94947. #endif
  94948. #ifdef min
  94949. #undef min
  94950. #endif
  94951. #define min(x,y) ((x) < (y)? (x) : (y))
  94952. #ifdef local_abs
  94953. #undef local_abs
  94954. #endif
  94955. #define local_abs(x) ((unsigned)((x)<0? -(x) : (x)))
  94956. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  94957. /* rbps stands for residual bits per sample
  94958. *
  94959. * (ln(2) * err)
  94960. * rbps = log (-----------)
  94961. * 2 ( n )
  94962. */
  94963. static FLAC__fixedpoint local__compute_rbps_integerized(FLAC__uint32 err, FLAC__uint32 n)
  94964. {
  94965. FLAC__uint32 rbps;
  94966. unsigned bits; /* the number of bits required to represent a number */
  94967. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  94968. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  94969. FLAC__ASSERT(err > 0);
  94970. FLAC__ASSERT(n > 0);
  94971. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  94972. if(err <= n)
  94973. return 0;
  94974. /*
  94975. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  94976. * These allow us later to know we won't lose too much precision in the
  94977. * fixed-point division (err<<fracbits)/n.
  94978. */
  94979. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2(err)+1);
  94980. err <<= fracbits;
  94981. err /= n;
  94982. /* err now holds err/n with fracbits fractional bits */
  94983. /*
  94984. * Whittle err down to 16 bits max. 16 significant bits is enough for
  94985. * our purposes.
  94986. */
  94987. FLAC__ASSERT(err > 0);
  94988. bits = FLAC__bitmath_ilog2(err)+1;
  94989. if(bits > 16) {
  94990. err >>= (bits-16);
  94991. fracbits -= (bits-16);
  94992. }
  94993. rbps = (FLAC__uint32)err;
  94994. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  94995. rbps *= FLAC__FP_LN2;
  94996. fracbits += 16;
  94997. FLAC__ASSERT(fracbits >= 0);
  94998. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  94999. {
  95000. const int f = fracbits & 3;
  95001. if(f) {
  95002. rbps >>= f;
  95003. fracbits -= f;
  95004. }
  95005. }
  95006. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  95007. if(rbps == 0)
  95008. return 0;
  95009. /*
  95010. * The return value must have 16 fractional bits. Since the whole part
  95011. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  95012. * must be >= -3, these assertion allows us to be able to shift rbps
  95013. * left if necessary to get 16 fracbits without losing any bits of the
  95014. * whole part of rbps.
  95015. *
  95016. * There is a slight chance due to accumulated error that the whole part
  95017. * will require 6 bits, so we use 6 in the assertion. Really though as
  95018. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  95019. */
  95020. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  95021. FLAC__ASSERT(fracbits >= -3);
  95022. /* now shift the decimal point into place */
  95023. if(fracbits < 16)
  95024. return rbps << (16-fracbits);
  95025. else if(fracbits > 16)
  95026. return rbps >> (fracbits-16);
  95027. else
  95028. return rbps;
  95029. }
  95030. static FLAC__fixedpoint local__compute_rbps_wide_integerized(FLAC__uint64 err, FLAC__uint32 n)
  95031. {
  95032. FLAC__uint32 rbps;
  95033. unsigned bits; /* the number of bits required to represent a number */
  95034. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  95035. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  95036. FLAC__ASSERT(err > 0);
  95037. FLAC__ASSERT(n > 0);
  95038. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  95039. if(err <= n)
  95040. return 0;
  95041. /*
  95042. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  95043. * These allow us later to know we won't lose too much precision in the
  95044. * fixed-point division (err<<fracbits)/n.
  95045. */
  95046. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2_wide(err)+1);
  95047. err <<= fracbits;
  95048. err /= n;
  95049. /* err now holds err/n with fracbits fractional bits */
  95050. /*
  95051. * Whittle err down to 16 bits max. 16 significant bits is enough for
  95052. * our purposes.
  95053. */
  95054. FLAC__ASSERT(err > 0);
  95055. bits = FLAC__bitmath_ilog2_wide(err)+1;
  95056. if(bits > 16) {
  95057. err >>= (bits-16);
  95058. fracbits -= (bits-16);
  95059. }
  95060. rbps = (FLAC__uint32)err;
  95061. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  95062. rbps *= FLAC__FP_LN2;
  95063. fracbits += 16;
  95064. FLAC__ASSERT(fracbits >= 0);
  95065. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  95066. {
  95067. const int f = fracbits & 3;
  95068. if(f) {
  95069. rbps >>= f;
  95070. fracbits -= f;
  95071. }
  95072. }
  95073. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  95074. if(rbps == 0)
  95075. return 0;
  95076. /*
  95077. * The return value must have 16 fractional bits. Since the whole part
  95078. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  95079. * must be >= -3, these assertion allows us to be able to shift rbps
  95080. * left if necessary to get 16 fracbits without losing any bits of the
  95081. * whole part of rbps.
  95082. *
  95083. * There is a slight chance due to accumulated error that the whole part
  95084. * will require 6 bits, so we use 6 in the assertion. Really though as
  95085. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  95086. */
  95087. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  95088. FLAC__ASSERT(fracbits >= -3);
  95089. /* now shift the decimal point into place */
  95090. if(fracbits < 16)
  95091. return rbps << (16-fracbits);
  95092. else if(fracbits > 16)
  95093. return rbps >> (fracbits-16);
  95094. else
  95095. return rbps;
  95096. }
  95097. #endif
  95098. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95099. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  95100. #else
  95101. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  95102. #endif
  95103. {
  95104. FLAC__int32 last_error_0 = data[-1];
  95105. FLAC__int32 last_error_1 = data[-1] - data[-2];
  95106. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  95107. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  95108. FLAC__int32 error, save;
  95109. FLAC__uint32 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  95110. unsigned i, order;
  95111. for(i = 0; i < data_len; i++) {
  95112. error = data[i] ; total_error_0 += local_abs(error); save = error;
  95113. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  95114. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  95115. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  95116. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  95117. }
  95118. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  95119. order = 0;
  95120. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  95121. order = 1;
  95122. else if(total_error_2 < min(total_error_3, total_error_4))
  95123. order = 2;
  95124. else if(total_error_3 < total_error_4)
  95125. order = 3;
  95126. else
  95127. order = 4;
  95128. /* Estimate the expected number of bits per residual signal sample. */
  95129. /* 'total_error*' is linearly related to the variance of the residual */
  95130. /* signal, so we use it directly to compute E(|x|) */
  95131. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  95132. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  95133. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  95134. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  95135. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  95136. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95137. 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);
  95138. 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);
  95139. 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);
  95140. 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);
  95141. 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);
  95142. #else
  95143. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_integerized(total_error_0, data_len) : 0;
  95144. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_integerized(total_error_1, data_len) : 0;
  95145. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_integerized(total_error_2, data_len) : 0;
  95146. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_integerized(total_error_3, data_len) : 0;
  95147. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_integerized(total_error_4, data_len) : 0;
  95148. #endif
  95149. return order;
  95150. }
  95151. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95152. 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])
  95153. #else
  95154. 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])
  95155. #endif
  95156. {
  95157. FLAC__int32 last_error_0 = data[-1];
  95158. FLAC__int32 last_error_1 = data[-1] - data[-2];
  95159. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  95160. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  95161. FLAC__int32 error, save;
  95162. /* total_error_* are 64-bits to avoid overflow when encoding
  95163. * erratic signals when the bits-per-sample and blocksize are
  95164. * large.
  95165. */
  95166. FLAC__uint64 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  95167. unsigned i, order;
  95168. for(i = 0; i < data_len; i++) {
  95169. error = data[i] ; total_error_0 += local_abs(error); save = error;
  95170. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  95171. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  95172. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  95173. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  95174. }
  95175. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  95176. order = 0;
  95177. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  95178. order = 1;
  95179. else if(total_error_2 < min(total_error_3, total_error_4))
  95180. order = 2;
  95181. else if(total_error_3 < total_error_4)
  95182. order = 3;
  95183. else
  95184. order = 4;
  95185. /* Estimate the expected number of bits per residual signal sample. */
  95186. /* 'total_error*' is linearly related to the variance of the residual */
  95187. /* signal, so we use it directly to compute E(|x|) */
  95188. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  95189. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  95190. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  95191. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  95192. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  95193. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95194. #if defined _MSC_VER || defined __MINGW32__
  95195. /* with MSVC you have to spoon feed it the casting */
  95196. 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);
  95197. 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);
  95198. 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);
  95199. 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);
  95200. 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);
  95201. #else
  95202. 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);
  95203. 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);
  95204. 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);
  95205. 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);
  95206. 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);
  95207. #endif
  95208. #else
  95209. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_wide_integerized(total_error_0, data_len) : 0;
  95210. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_wide_integerized(total_error_1, data_len) : 0;
  95211. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_wide_integerized(total_error_2, data_len) : 0;
  95212. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_wide_integerized(total_error_3, data_len) : 0;
  95213. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_wide_integerized(total_error_4, data_len) : 0;
  95214. #endif
  95215. return order;
  95216. }
  95217. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[])
  95218. {
  95219. const int idata_len = (int)data_len;
  95220. int i;
  95221. switch(order) {
  95222. case 0:
  95223. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  95224. memcpy(residual, data, sizeof(residual[0])*data_len);
  95225. break;
  95226. case 1:
  95227. for(i = 0; i < idata_len; i++)
  95228. residual[i] = data[i] - data[i-1];
  95229. break;
  95230. case 2:
  95231. for(i = 0; i < idata_len; i++)
  95232. #if 1 /* OPT: may be faster with some compilers on some systems */
  95233. residual[i] = data[i] - (data[i-1] << 1) + data[i-2];
  95234. #else
  95235. residual[i] = data[i] - 2*data[i-1] + data[i-2];
  95236. #endif
  95237. break;
  95238. case 3:
  95239. for(i = 0; i < idata_len; i++)
  95240. #if 1 /* OPT: may be faster with some compilers on some systems */
  95241. residual[i] = data[i] - (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) - data[i-3];
  95242. #else
  95243. residual[i] = data[i] - 3*data[i-1] + 3*data[i-2] - data[i-3];
  95244. #endif
  95245. break;
  95246. case 4:
  95247. for(i = 0; i < idata_len; i++)
  95248. #if 1 /* OPT: may be faster with some compilers on some systems */
  95249. residual[i] = data[i] - ((data[i-1]+data[i-3])<<2) + ((data[i-2]<<2) + (data[i-2]<<1)) + data[i-4];
  95250. #else
  95251. residual[i] = data[i] - 4*data[i-1] + 6*data[i-2] - 4*data[i-3] + data[i-4];
  95252. #endif
  95253. break;
  95254. default:
  95255. FLAC__ASSERT(0);
  95256. }
  95257. }
  95258. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[])
  95259. {
  95260. int i, idata_len = (int)data_len;
  95261. switch(order) {
  95262. case 0:
  95263. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  95264. memcpy(data, residual, sizeof(residual[0])*data_len);
  95265. break;
  95266. case 1:
  95267. for(i = 0; i < idata_len; i++)
  95268. data[i] = residual[i] + data[i-1];
  95269. break;
  95270. case 2:
  95271. for(i = 0; i < idata_len; i++)
  95272. #if 1 /* OPT: may be faster with some compilers on some systems */
  95273. data[i] = residual[i] + (data[i-1]<<1) - data[i-2];
  95274. #else
  95275. data[i] = residual[i] + 2*data[i-1] - data[i-2];
  95276. #endif
  95277. break;
  95278. case 3:
  95279. for(i = 0; i < idata_len; i++)
  95280. #if 1 /* OPT: may be faster with some compilers on some systems */
  95281. data[i] = residual[i] + (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) + data[i-3];
  95282. #else
  95283. data[i] = residual[i] + 3*data[i-1] - 3*data[i-2] + data[i-3];
  95284. #endif
  95285. break;
  95286. case 4:
  95287. for(i = 0; i < idata_len; i++)
  95288. #if 1 /* OPT: may be faster with some compilers on some systems */
  95289. data[i] = residual[i] + ((data[i-1]+data[i-3])<<2) - ((data[i-2]<<2) + (data[i-2]<<1)) - data[i-4];
  95290. #else
  95291. data[i] = residual[i] + 4*data[i-1] - 6*data[i-2] + 4*data[i-3] - data[i-4];
  95292. #endif
  95293. break;
  95294. default:
  95295. FLAC__ASSERT(0);
  95296. }
  95297. }
  95298. #endif
  95299. /*** End of inlined file: fixed.c ***/
  95300. /*** Start of inlined file: float.c ***/
  95301. /*** Start of inlined file: juce_FlacHeader.h ***/
  95302. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95303. // tasks..
  95304. #define VERSION "1.2.1"
  95305. #define FLAC__NO_DLL 1
  95306. #if JUCE_MSVC
  95307. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95308. #endif
  95309. #if JUCE_MAC
  95310. #define FLAC__SYS_DARWIN 1
  95311. #endif
  95312. /*** End of inlined file: juce_FlacHeader.h ***/
  95313. #if JUCE_USE_FLAC
  95314. #if HAVE_CONFIG_H
  95315. # include <config.h>
  95316. #endif
  95317. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  95318. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  95319. #ifdef _MSC_VER
  95320. #define FLAC__U64L(x) x
  95321. #else
  95322. #define FLAC__U64L(x) x##LLU
  95323. #endif
  95324. const FLAC__fixedpoint FLAC__FP_ZERO = 0;
  95325. const FLAC__fixedpoint FLAC__FP_ONE_HALF = 0x00008000;
  95326. const FLAC__fixedpoint FLAC__FP_ONE = 0x00010000;
  95327. const FLAC__fixedpoint FLAC__FP_LN2 = 45426;
  95328. const FLAC__fixedpoint FLAC__FP_E = 178145;
  95329. /* Lookup tables for Knuth's logarithm algorithm */
  95330. #define LOG2_LOOKUP_PRECISION 16
  95331. static const FLAC__uint32 log2_lookup[][LOG2_LOOKUP_PRECISION] = {
  95332. {
  95333. /*
  95334. * 0 fraction bits
  95335. */
  95336. /* undefined */ 0x00000000,
  95337. /* lg(2/1) = */ 0x00000001,
  95338. /* lg(4/3) = */ 0x00000000,
  95339. /* lg(8/7) = */ 0x00000000,
  95340. /* lg(16/15) = */ 0x00000000,
  95341. /* lg(32/31) = */ 0x00000000,
  95342. /* lg(64/63) = */ 0x00000000,
  95343. /* lg(128/127) = */ 0x00000000,
  95344. /* lg(256/255) = */ 0x00000000,
  95345. /* lg(512/511) = */ 0x00000000,
  95346. /* lg(1024/1023) = */ 0x00000000,
  95347. /* lg(2048/2047) = */ 0x00000000,
  95348. /* lg(4096/4095) = */ 0x00000000,
  95349. /* lg(8192/8191) = */ 0x00000000,
  95350. /* lg(16384/16383) = */ 0x00000000,
  95351. /* lg(32768/32767) = */ 0x00000000
  95352. },
  95353. {
  95354. /*
  95355. * 4 fraction bits
  95356. */
  95357. /* undefined */ 0x00000000,
  95358. /* lg(2/1) = */ 0x00000010,
  95359. /* lg(4/3) = */ 0x00000007,
  95360. /* lg(8/7) = */ 0x00000003,
  95361. /* lg(16/15) = */ 0x00000001,
  95362. /* lg(32/31) = */ 0x00000001,
  95363. /* lg(64/63) = */ 0x00000000,
  95364. /* lg(128/127) = */ 0x00000000,
  95365. /* lg(256/255) = */ 0x00000000,
  95366. /* lg(512/511) = */ 0x00000000,
  95367. /* lg(1024/1023) = */ 0x00000000,
  95368. /* lg(2048/2047) = */ 0x00000000,
  95369. /* lg(4096/4095) = */ 0x00000000,
  95370. /* lg(8192/8191) = */ 0x00000000,
  95371. /* lg(16384/16383) = */ 0x00000000,
  95372. /* lg(32768/32767) = */ 0x00000000
  95373. },
  95374. {
  95375. /*
  95376. * 8 fraction bits
  95377. */
  95378. /* undefined */ 0x00000000,
  95379. /* lg(2/1) = */ 0x00000100,
  95380. /* lg(4/3) = */ 0x0000006a,
  95381. /* lg(8/7) = */ 0x00000031,
  95382. /* lg(16/15) = */ 0x00000018,
  95383. /* lg(32/31) = */ 0x0000000c,
  95384. /* lg(64/63) = */ 0x00000006,
  95385. /* lg(128/127) = */ 0x00000003,
  95386. /* lg(256/255) = */ 0x00000001,
  95387. /* lg(512/511) = */ 0x00000001,
  95388. /* lg(1024/1023) = */ 0x00000000,
  95389. /* lg(2048/2047) = */ 0x00000000,
  95390. /* lg(4096/4095) = */ 0x00000000,
  95391. /* lg(8192/8191) = */ 0x00000000,
  95392. /* lg(16384/16383) = */ 0x00000000,
  95393. /* lg(32768/32767) = */ 0x00000000
  95394. },
  95395. {
  95396. /*
  95397. * 12 fraction bits
  95398. */
  95399. /* undefined */ 0x00000000,
  95400. /* lg(2/1) = */ 0x00001000,
  95401. /* lg(4/3) = */ 0x000006a4,
  95402. /* lg(8/7) = */ 0x00000315,
  95403. /* lg(16/15) = */ 0x0000017d,
  95404. /* lg(32/31) = */ 0x000000bc,
  95405. /* lg(64/63) = */ 0x0000005d,
  95406. /* lg(128/127) = */ 0x0000002e,
  95407. /* lg(256/255) = */ 0x00000017,
  95408. /* lg(512/511) = */ 0x0000000c,
  95409. /* lg(1024/1023) = */ 0x00000006,
  95410. /* lg(2048/2047) = */ 0x00000003,
  95411. /* lg(4096/4095) = */ 0x00000001,
  95412. /* lg(8192/8191) = */ 0x00000001,
  95413. /* lg(16384/16383) = */ 0x00000000,
  95414. /* lg(32768/32767) = */ 0x00000000
  95415. },
  95416. {
  95417. /*
  95418. * 16 fraction bits
  95419. */
  95420. /* undefined */ 0x00000000,
  95421. /* lg(2/1) = */ 0x00010000,
  95422. /* lg(4/3) = */ 0x00006a40,
  95423. /* lg(8/7) = */ 0x00003151,
  95424. /* lg(16/15) = */ 0x000017d6,
  95425. /* lg(32/31) = */ 0x00000bba,
  95426. /* lg(64/63) = */ 0x000005d1,
  95427. /* lg(128/127) = */ 0x000002e6,
  95428. /* lg(256/255) = */ 0x00000172,
  95429. /* lg(512/511) = */ 0x000000b9,
  95430. /* lg(1024/1023) = */ 0x0000005c,
  95431. /* lg(2048/2047) = */ 0x0000002e,
  95432. /* lg(4096/4095) = */ 0x00000017,
  95433. /* lg(8192/8191) = */ 0x0000000c,
  95434. /* lg(16384/16383) = */ 0x00000006,
  95435. /* lg(32768/32767) = */ 0x00000003
  95436. },
  95437. {
  95438. /*
  95439. * 20 fraction bits
  95440. */
  95441. /* undefined */ 0x00000000,
  95442. /* lg(2/1) = */ 0x00100000,
  95443. /* lg(4/3) = */ 0x0006a3fe,
  95444. /* lg(8/7) = */ 0x00031513,
  95445. /* lg(16/15) = */ 0x00017d60,
  95446. /* lg(32/31) = */ 0x0000bb9d,
  95447. /* lg(64/63) = */ 0x00005d10,
  95448. /* lg(128/127) = */ 0x00002e59,
  95449. /* lg(256/255) = */ 0x00001721,
  95450. /* lg(512/511) = */ 0x00000b8e,
  95451. /* lg(1024/1023) = */ 0x000005c6,
  95452. /* lg(2048/2047) = */ 0x000002e3,
  95453. /* lg(4096/4095) = */ 0x00000171,
  95454. /* lg(8192/8191) = */ 0x000000b9,
  95455. /* lg(16384/16383) = */ 0x0000005c,
  95456. /* lg(32768/32767) = */ 0x0000002e
  95457. },
  95458. {
  95459. /*
  95460. * 24 fraction bits
  95461. */
  95462. /* undefined */ 0x00000000,
  95463. /* lg(2/1) = */ 0x01000000,
  95464. /* lg(4/3) = */ 0x006a3fe6,
  95465. /* lg(8/7) = */ 0x00315130,
  95466. /* lg(16/15) = */ 0x0017d605,
  95467. /* lg(32/31) = */ 0x000bb9ca,
  95468. /* lg(64/63) = */ 0x0005d0fc,
  95469. /* lg(128/127) = */ 0x0002e58f,
  95470. /* lg(256/255) = */ 0x0001720e,
  95471. /* lg(512/511) = */ 0x0000b8d8,
  95472. /* lg(1024/1023) = */ 0x00005c61,
  95473. /* lg(2048/2047) = */ 0x00002e2d,
  95474. /* lg(4096/4095) = */ 0x00001716,
  95475. /* lg(8192/8191) = */ 0x00000b8b,
  95476. /* lg(16384/16383) = */ 0x000005c5,
  95477. /* lg(32768/32767) = */ 0x000002e3
  95478. },
  95479. {
  95480. /*
  95481. * 28 fraction bits
  95482. */
  95483. /* undefined */ 0x00000000,
  95484. /* lg(2/1) = */ 0x10000000,
  95485. /* lg(4/3) = */ 0x06a3fe5c,
  95486. /* lg(8/7) = */ 0x03151301,
  95487. /* lg(16/15) = */ 0x017d6049,
  95488. /* lg(32/31) = */ 0x00bb9ca6,
  95489. /* lg(64/63) = */ 0x005d0fba,
  95490. /* lg(128/127) = */ 0x002e58f7,
  95491. /* lg(256/255) = */ 0x001720da,
  95492. /* lg(512/511) = */ 0x000b8d87,
  95493. /* lg(1024/1023) = */ 0x0005c60b,
  95494. /* lg(2048/2047) = */ 0x0002e2d7,
  95495. /* lg(4096/4095) = */ 0x00017160,
  95496. /* lg(8192/8191) = */ 0x0000b8ad,
  95497. /* lg(16384/16383) = */ 0x00005c56,
  95498. /* lg(32768/32767) = */ 0x00002e2b
  95499. }
  95500. };
  95501. #if 0
  95502. static const FLAC__uint64 log2_lookup_wide[] = {
  95503. {
  95504. /*
  95505. * 32 fraction bits
  95506. */
  95507. /* undefined */ 0x00000000,
  95508. /* lg(2/1) = */ FLAC__U64L(0x100000000),
  95509. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c6),
  95510. /* lg(8/7) = */ FLAC__U64L(0x31513015),
  95511. /* lg(16/15) = */ FLAC__U64L(0x17d60497),
  95512. /* lg(32/31) = */ FLAC__U64L(0x0bb9ca65),
  95513. /* lg(64/63) = */ FLAC__U64L(0x05d0fba2),
  95514. /* lg(128/127) = */ FLAC__U64L(0x02e58f74),
  95515. /* lg(256/255) = */ FLAC__U64L(0x01720d9c),
  95516. /* lg(512/511) = */ FLAC__U64L(0x00b8d875),
  95517. /* lg(1024/1023) = */ FLAC__U64L(0x005c60aa),
  95518. /* lg(2048/2047) = */ FLAC__U64L(0x002e2d72),
  95519. /* lg(4096/4095) = */ FLAC__U64L(0x00171600),
  95520. /* lg(8192/8191) = */ FLAC__U64L(0x000b8ad2),
  95521. /* lg(16384/16383) = */ FLAC__U64L(0x0005c55d),
  95522. /* lg(32768/32767) = */ FLAC__U64L(0x0002e2ac)
  95523. },
  95524. {
  95525. /*
  95526. * 48 fraction bits
  95527. */
  95528. /* undefined */ 0x00000000,
  95529. /* lg(2/1) = */ FLAC__U64L(0x1000000000000),
  95530. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c60429),
  95531. /* lg(8/7) = */ FLAC__U64L(0x315130157f7a),
  95532. /* lg(16/15) = */ FLAC__U64L(0x17d60496cfbb),
  95533. /* lg(32/31) = */ FLAC__U64L(0xbb9ca64ecac),
  95534. /* lg(64/63) = */ FLAC__U64L(0x5d0fba187cd),
  95535. /* lg(128/127) = */ FLAC__U64L(0x2e58f7441ee),
  95536. /* lg(256/255) = */ FLAC__U64L(0x1720d9c06a8),
  95537. /* lg(512/511) = */ FLAC__U64L(0xb8d8752173),
  95538. /* lg(1024/1023) = */ FLAC__U64L(0x5c60aa252e),
  95539. /* lg(2048/2047) = */ FLAC__U64L(0x2e2d71b0d8),
  95540. /* lg(4096/4095) = */ FLAC__U64L(0x1716001719),
  95541. /* lg(8192/8191) = */ FLAC__U64L(0xb8ad1de1b),
  95542. /* lg(16384/16383) = */ FLAC__U64L(0x5c55d640d),
  95543. /* lg(32768/32767) = */ FLAC__U64L(0x2e2abcf52)
  95544. }
  95545. };
  95546. #endif
  95547. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision)
  95548. {
  95549. const FLAC__uint32 ONE = (1u << fracbits);
  95550. const FLAC__uint32 *table = log2_lookup[fracbits >> 2];
  95551. FLAC__ASSERT(fracbits < 32);
  95552. FLAC__ASSERT((fracbits & 0x3) == 0);
  95553. if(x < ONE)
  95554. return 0;
  95555. if(precision > LOG2_LOOKUP_PRECISION)
  95556. precision = LOG2_LOOKUP_PRECISION;
  95557. /* Knuth's algorithm for computing logarithms, optimized for base-2 with lookup tables */
  95558. {
  95559. FLAC__uint32 y = 0;
  95560. FLAC__uint32 z = x >> 1, k = 1;
  95561. while (x > ONE && k < precision) {
  95562. if (x - z >= ONE) {
  95563. x -= z;
  95564. z = x >> k;
  95565. y += table[k];
  95566. }
  95567. else {
  95568. z >>= 1;
  95569. k++;
  95570. }
  95571. }
  95572. return y;
  95573. }
  95574. }
  95575. #endif /* defined FLAC__INTEGER_ONLY_LIBRARY */
  95576. #endif
  95577. /*** End of inlined file: float.c ***/
  95578. /*** Start of inlined file: format.c ***/
  95579. /*** Start of inlined file: juce_FlacHeader.h ***/
  95580. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95581. // tasks..
  95582. #define VERSION "1.2.1"
  95583. #define FLAC__NO_DLL 1
  95584. #if JUCE_MSVC
  95585. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95586. #endif
  95587. #if JUCE_MAC
  95588. #define FLAC__SYS_DARWIN 1
  95589. #endif
  95590. /*** End of inlined file: juce_FlacHeader.h ***/
  95591. #if JUCE_USE_FLAC
  95592. #if HAVE_CONFIG_H
  95593. # include <config.h>
  95594. #endif
  95595. #include <stdio.h>
  95596. #include <stdlib.h> /* for qsort() */
  95597. #include <string.h> /* for memset() */
  95598. #ifndef FLaC__INLINE
  95599. #define FLaC__INLINE
  95600. #endif
  95601. #ifdef min
  95602. #undef min
  95603. #endif
  95604. #define min(a,b) ((a)<(b)?(a):(b))
  95605. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  95606. #ifdef _MSC_VER
  95607. #define FLAC__U64L(x) x
  95608. #else
  95609. #define FLAC__U64L(x) x##LLU
  95610. #endif
  95611. /* VERSION should come from configure */
  95612. FLAC_API const char *FLAC__VERSION_STRING = VERSION
  95613. ;
  95614. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINW32__
  95615. /* yet one more hack because of MSVC6: */
  95616. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC 1.2.1 20070917";
  95617. #else
  95618. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC " VERSION " 20070917";
  95619. #endif
  95620. FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4] = { 'f','L','a','C' };
  95621. FLAC_API const unsigned FLAC__STREAM_SYNC = 0x664C6143;
  95622. FLAC_API const unsigned FLAC__STREAM_SYNC_LEN = 32; /* bits */
  95623. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN = 16; /* bits */
  95624. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN = 16; /* bits */
  95625. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN = 24; /* bits */
  95626. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN = 24; /* bits */
  95627. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN = 20; /* bits */
  95628. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN = 3; /* bits */
  95629. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN = 5; /* bits */
  95630. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN = 36; /* bits */
  95631. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN = 128; /* bits */
  95632. FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN = 32; /* bits */
  95633. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN = 64; /* bits */
  95634. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN = 64; /* bits */
  95635. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN = 16; /* bits */
  95636. FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER = FLAC__U64L(0xffffffffffffffff);
  95637. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN = 32; /* bits */
  95638. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN = 32; /* bits */
  95639. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN = 64; /* bits */
  95640. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN = 8; /* bits */
  95641. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN = 3*8; /* bits */
  95642. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN = 64; /* bits */
  95643. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN = 8; /* bits */
  95644. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN = 12*8; /* bits */
  95645. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN = 1; /* bit */
  95646. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN = 1; /* bit */
  95647. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN = 6+13*8; /* bits */
  95648. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN = 8; /* bits */
  95649. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN = 128*8; /* bits */
  95650. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN = 64; /* bits */
  95651. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN = 1; /* bit */
  95652. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN = 7+258*8; /* bits */
  95653. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN = 8; /* bits */
  95654. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN = 32; /* bits */
  95655. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN = 32; /* bits */
  95656. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN = 32; /* bits */
  95657. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN = 32; /* bits */
  95658. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN = 32; /* bits */
  95659. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN = 32; /* bits */
  95660. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN = 32; /* bits */
  95661. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN = 32; /* bits */
  95662. FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN = 1; /* bits */
  95663. FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN = 7; /* bits */
  95664. FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN = 24; /* bits */
  95665. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC = 0x3ffe;
  95666. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN = 14; /* bits */
  95667. FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN = 1; /* bits */
  95668. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN = 1; /* bits */
  95669. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN = 4; /* bits */
  95670. FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN = 4; /* bits */
  95671. FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN = 4; /* bits */
  95672. FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN = 3; /* bits */
  95673. FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN = 1; /* bits */
  95674. FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN = 8; /* bits */
  95675. FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN = 16; /* bits */
  95676. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN = 2; /* bits */
  95677. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN = 4; /* bits */
  95678. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN = 4; /* bits */
  95679. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN = 5; /* bits */
  95680. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN = 5; /* bits */
  95681. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER = 15; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  95682. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER = 31; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  95683. FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[] = {
  95684. "PARTITIONED_RICE",
  95685. "PARTITIONED_RICE2"
  95686. };
  95687. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN = 4; /* bits */
  95688. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN = 5; /* bits */
  95689. FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN = 1; /* bits */
  95690. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN = 6; /* bits */
  95691. FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN = 1; /* bits */
  95692. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK = 0x00;
  95693. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK = 0x02;
  95694. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK = 0x10;
  95695. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK = 0x40;
  95696. FLAC_API const char * const FLAC__SubframeTypeString[] = {
  95697. "CONSTANT",
  95698. "VERBATIM",
  95699. "FIXED",
  95700. "LPC"
  95701. };
  95702. FLAC_API const char * const FLAC__ChannelAssignmentString[] = {
  95703. "INDEPENDENT",
  95704. "LEFT_SIDE",
  95705. "RIGHT_SIDE",
  95706. "MID_SIDE"
  95707. };
  95708. FLAC_API const char * const FLAC__FrameNumberTypeString[] = {
  95709. "FRAME_NUMBER_TYPE_FRAME_NUMBER",
  95710. "FRAME_NUMBER_TYPE_SAMPLE_NUMBER"
  95711. };
  95712. FLAC_API const char * const FLAC__MetadataTypeString[] = {
  95713. "STREAMINFO",
  95714. "PADDING",
  95715. "APPLICATION",
  95716. "SEEKTABLE",
  95717. "VORBIS_COMMENT",
  95718. "CUESHEET",
  95719. "PICTURE"
  95720. };
  95721. FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[] = {
  95722. "Other",
  95723. "32x32 pixels 'file icon' (PNG only)",
  95724. "Other file icon",
  95725. "Cover (front)",
  95726. "Cover (back)",
  95727. "Leaflet page",
  95728. "Media (e.g. label side of CD)",
  95729. "Lead artist/lead performer/soloist",
  95730. "Artist/performer",
  95731. "Conductor",
  95732. "Band/Orchestra",
  95733. "Composer",
  95734. "Lyricist/text writer",
  95735. "Recording Location",
  95736. "During recording",
  95737. "During performance",
  95738. "Movie/video screen capture",
  95739. "A bright coloured fish",
  95740. "Illustration",
  95741. "Band/artist logotype",
  95742. "Publisher/Studio logotype"
  95743. };
  95744. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate)
  95745. {
  95746. if(sample_rate == 0 || sample_rate > FLAC__MAX_SAMPLE_RATE) {
  95747. return false;
  95748. }
  95749. else
  95750. return true;
  95751. }
  95752. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate)
  95753. {
  95754. if(
  95755. !FLAC__format_sample_rate_is_valid(sample_rate) ||
  95756. (
  95757. sample_rate >= (1u << 16) &&
  95758. !(sample_rate % 1000 == 0 || sample_rate % 10 == 0)
  95759. )
  95760. ) {
  95761. return false;
  95762. }
  95763. else
  95764. return true;
  95765. }
  95766. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  95767. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table)
  95768. {
  95769. unsigned i;
  95770. FLAC__uint64 prev_sample_number = 0;
  95771. FLAC__bool got_prev = false;
  95772. FLAC__ASSERT(0 != seek_table);
  95773. for(i = 0; i < seek_table->num_points; i++) {
  95774. if(got_prev) {
  95775. if(
  95776. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  95777. seek_table->points[i].sample_number <= prev_sample_number
  95778. )
  95779. return false;
  95780. }
  95781. prev_sample_number = seek_table->points[i].sample_number;
  95782. got_prev = true;
  95783. }
  95784. return true;
  95785. }
  95786. /* used as the sort predicate for qsort() */
  95787. static int seekpoint_compare_(const FLAC__StreamMetadata_SeekPoint *l, const FLAC__StreamMetadata_SeekPoint *r)
  95788. {
  95789. /* we don't just 'return l->sample_number - r->sample_number' since the result (FLAC__int64) might overflow an 'int' */
  95790. if(l->sample_number == r->sample_number)
  95791. return 0;
  95792. else if(l->sample_number < r->sample_number)
  95793. return -1;
  95794. else
  95795. return 1;
  95796. }
  95797. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  95798. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table)
  95799. {
  95800. unsigned i, j;
  95801. FLAC__bool first;
  95802. FLAC__ASSERT(0 != seek_table);
  95803. /* sort the seekpoints */
  95804. qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetadata_SeekPoint), (int (*)(const void *, const void *))seekpoint_compare_);
  95805. /* uniquify the seekpoints */
  95806. first = true;
  95807. for(i = j = 0; i < seek_table->num_points; i++) {
  95808. if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER) {
  95809. if(!first) {
  95810. if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
  95811. continue;
  95812. }
  95813. }
  95814. first = false;
  95815. seek_table->points[j++] = seek_table->points[i];
  95816. }
  95817. for(i = j; i < seek_table->num_points; i++) {
  95818. seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  95819. seek_table->points[i].stream_offset = 0;
  95820. seek_table->points[i].frame_samples = 0;
  95821. }
  95822. return j;
  95823. }
  95824. /*
  95825. * also disallows non-shortest-form encodings, c.f.
  95826. * http://www.unicode.org/versions/corrigendum1.html
  95827. * and a more clear explanation at the end of this section:
  95828. * http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  95829. */
  95830. static FLaC__INLINE unsigned utf8len_(const FLAC__byte *utf8)
  95831. {
  95832. FLAC__ASSERT(0 != utf8);
  95833. if ((utf8[0] & 0x80) == 0) {
  95834. return 1;
  95835. }
  95836. else if ((utf8[0] & 0xE0) == 0xC0 && (utf8[1] & 0xC0) == 0x80) {
  95837. if ((utf8[0] & 0xFE) == 0xC0) /* overlong sequence check */
  95838. return 0;
  95839. return 2;
  95840. }
  95841. else if ((utf8[0] & 0xF0) == 0xE0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80) {
  95842. if (utf8[0] == 0xE0 && (utf8[1] & 0xE0) == 0x80) /* overlong sequence check */
  95843. return 0;
  95844. /* illegal surrogates check (U+D800...U+DFFF and U+FFFE...U+FFFF) */
  95845. if (utf8[0] == 0xED && (utf8[1] & 0xE0) == 0xA0) /* D800-DFFF */
  95846. return 0;
  95847. if (utf8[0] == 0xEF && utf8[1] == 0xBF && (utf8[2] & 0xFE) == 0xBE) /* FFFE-FFFF */
  95848. return 0;
  95849. return 3;
  95850. }
  95851. else if ((utf8[0] & 0xF8) == 0xF0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80) {
  95852. if (utf8[0] == 0xF0 && (utf8[1] & 0xF0) == 0x80) /* overlong sequence check */
  95853. return 0;
  95854. return 4;
  95855. }
  95856. else if ((utf8[0] & 0xFC) == 0xF8 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80) {
  95857. if (utf8[0] == 0xF8 && (utf8[1] & 0xF8) == 0x80) /* overlong sequence check */
  95858. return 0;
  95859. return 5;
  95860. }
  95861. 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) {
  95862. if (utf8[0] == 0xFC && (utf8[1] & 0xFC) == 0x80) /* overlong sequence check */
  95863. return 0;
  95864. return 6;
  95865. }
  95866. else {
  95867. return 0;
  95868. }
  95869. }
  95870. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name)
  95871. {
  95872. char c;
  95873. for(c = *name; c; c = *(++name))
  95874. if(c < 0x20 || c == 0x3d || c > 0x7d)
  95875. return false;
  95876. return true;
  95877. }
  95878. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length)
  95879. {
  95880. if(length == (unsigned)(-1)) {
  95881. while(*value) {
  95882. unsigned n = utf8len_(value);
  95883. if(n == 0)
  95884. return false;
  95885. value += n;
  95886. }
  95887. }
  95888. else {
  95889. const FLAC__byte *end = value + length;
  95890. while(value < end) {
  95891. unsigned n = utf8len_(value);
  95892. if(n == 0)
  95893. return false;
  95894. value += n;
  95895. }
  95896. if(value != end)
  95897. return false;
  95898. }
  95899. return true;
  95900. }
  95901. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length)
  95902. {
  95903. const FLAC__byte *s, *end;
  95904. for(s = entry, end = s + length; s < end && *s != '='; s++) {
  95905. if(*s < 0x20 || *s > 0x7D)
  95906. return false;
  95907. }
  95908. if(s == end)
  95909. return false;
  95910. s++; /* skip '=' */
  95911. while(s < end) {
  95912. unsigned n = utf8len_(s);
  95913. if(n == 0)
  95914. return false;
  95915. s += n;
  95916. }
  95917. if(s != end)
  95918. return false;
  95919. return true;
  95920. }
  95921. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  95922. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation)
  95923. {
  95924. unsigned i, j;
  95925. if(check_cd_da_subset) {
  95926. if(cue_sheet->lead_in < 2 * 44100) {
  95927. if(violation) *violation = "CD-DA cue sheet must have a lead-in length of at least 2 seconds";
  95928. return false;
  95929. }
  95930. if(cue_sheet->lead_in % 588 != 0) {
  95931. if(violation) *violation = "CD-DA cue sheet lead-in length must be evenly divisible by 588 samples";
  95932. return false;
  95933. }
  95934. }
  95935. if(cue_sheet->num_tracks == 0) {
  95936. if(violation) *violation = "cue sheet must have at least one track (the lead-out)";
  95937. return false;
  95938. }
  95939. if(check_cd_da_subset && cue_sheet->tracks[cue_sheet->num_tracks-1].number != 170) {
  95940. if(violation) *violation = "CD-DA cue sheet must have a lead-out track number 170 (0xAA)";
  95941. return false;
  95942. }
  95943. for(i = 0; i < cue_sheet->num_tracks; i++) {
  95944. if(cue_sheet->tracks[i].number == 0) {
  95945. if(violation) *violation = "cue sheet may not have a track number 0";
  95946. return false;
  95947. }
  95948. if(check_cd_da_subset) {
  95949. if(!((cue_sheet->tracks[i].number >= 1 && cue_sheet->tracks[i].number <= 99) || cue_sheet->tracks[i].number == 170)) {
  95950. if(violation) *violation = "CD-DA cue sheet track number must be 1-99 or 170";
  95951. return false;
  95952. }
  95953. }
  95954. if(check_cd_da_subset && cue_sheet->tracks[i].offset % 588 != 0) {
  95955. if(violation) {
  95956. if(i == cue_sheet->num_tracks-1) /* the lead-out track... */
  95957. *violation = "CD-DA cue sheet lead-out offset must be evenly divisible by 588 samples";
  95958. else
  95959. *violation = "CD-DA cue sheet track offset must be evenly divisible by 588 samples";
  95960. }
  95961. return false;
  95962. }
  95963. if(i < cue_sheet->num_tracks - 1) {
  95964. if(cue_sheet->tracks[i].num_indices == 0) {
  95965. if(violation) *violation = "cue sheet track must have at least one index point";
  95966. return false;
  95967. }
  95968. if(cue_sheet->tracks[i].indices[0].number > 1) {
  95969. if(violation) *violation = "cue sheet track's first index number must be 0 or 1";
  95970. return false;
  95971. }
  95972. }
  95973. for(j = 0; j < cue_sheet->tracks[i].num_indices; j++) {
  95974. if(check_cd_da_subset && cue_sheet->tracks[i].indices[j].offset % 588 != 0) {
  95975. if(violation) *violation = "CD-DA cue sheet track index offset must be evenly divisible by 588 samples";
  95976. return false;
  95977. }
  95978. if(j > 0) {
  95979. if(cue_sheet->tracks[i].indices[j].number != cue_sheet->tracks[i].indices[j-1].number + 1) {
  95980. if(violation) *violation = "cue sheet track index numbers must increase by 1";
  95981. return false;
  95982. }
  95983. }
  95984. }
  95985. }
  95986. return true;
  95987. }
  95988. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  95989. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation)
  95990. {
  95991. char *p;
  95992. FLAC__byte *b;
  95993. for(p = picture->mime_type; *p; p++) {
  95994. if(*p < 0x20 || *p > 0x7e) {
  95995. if(violation) *violation = "MIME type string must contain only printable ASCII characters (0x20-0x7e)";
  95996. return false;
  95997. }
  95998. }
  95999. for(b = picture->description; *b; ) {
  96000. unsigned n = utf8len_(b);
  96001. if(n == 0) {
  96002. if(violation) *violation = "description string must be valid UTF-8";
  96003. return false;
  96004. }
  96005. b += n;
  96006. }
  96007. return true;
  96008. }
  96009. /*
  96010. * These routines are private to libFLAC
  96011. */
  96012. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order)
  96013. {
  96014. return
  96015. FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(
  96016. FLAC__format_get_max_rice_partition_order_from_blocksize(blocksize),
  96017. blocksize,
  96018. predictor_order
  96019. );
  96020. }
  96021. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize)
  96022. {
  96023. unsigned max_rice_partition_order = 0;
  96024. while(!(blocksize & 1)) {
  96025. max_rice_partition_order++;
  96026. blocksize >>= 1;
  96027. }
  96028. return min(FLAC__MAX_RICE_PARTITION_ORDER, max_rice_partition_order);
  96029. }
  96030. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order)
  96031. {
  96032. unsigned max_rice_partition_order = limit;
  96033. while(max_rice_partition_order > 0 && (blocksize >> max_rice_partition_order) <= predictor_order)
  96034. max_rice_partition_order--;
  96035. FLAC__ASSERT(
  96036. (max_rice_partition_order == 0 && blocksize >= predictor_order) ||
  96037. (max_rice_partition_order > 0 && blocksize >> max_rice_partition_order > predictor_order)
  96038. );
  96039. return max_rice_partition_order;
  96040. }
  96041. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  96042. {
  96043. FLAC__ASSERT(0 != object);
  96044. object->parameters = 0;
  96045. object->raw_bits = 0;
  96046. object->capacity_by_order = 0;
  96047. }
  96048. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  96049. {
  96050. FLAC__ASSERT(0 != object);
  96051. if(0 != object->parameters)
  96052. free(object->parameters);
  96053. if(0 != object->raw_bits)
  96054. free(object->raw_bits);
  96055. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(object);
  96056. }
  96057. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order)
  96058. {
  96059. FLAC__ASSERT(0 != object);
  96060. FLAC__ASSERT(object->capacity_by_order > 0 || (0 == object->parameters && 0 == object->raw_bits));
  96061. if(object->capacity_by_order < max_partition_order) {
  96062. if(0 == (object->parameters = (unsigned*)realloc(object->parameters, sizeof(unsigned)*(1 << max_partition_order))))
  96063. return false;
  96064. if(0 == (object->raw_bits = (unsigned*)realloc(object->raw_bits, sizeof(unsigned)*(1 << max_partition_order))))
  96065. return false;
  96066. memset(object->raw_bits, 0, sizeof(unsigned)*(1 << max_partition_order));
  96067. object->capacity_by_order = max_partition_order;
  96068. }
  96069. return true;
  96070. }
  96071. #endif
  96072. /*** End of inlined file: format.c ***/
  96073. /*** Start of inlined file: lpc_flac.c ***/
  96074. /*** Start of inlined file: juce_FlacHeader.h ***/
  96075. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96076. // tasks..
  96077. #define VERSION "1.2.1"
  96078. #define FLAC__NO_DLL 1
  96079. #if JUCE_MSVC
  96080. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96081. #endif
  96082. #if JUCE_MAC
  96083. #define FLAC__SYS_DARWIN 1
  96084. #endif
  96085. /*** End of inlined file: juce_FlacHeader.h ***/
  96086. #if JUCE_USE_FLAC
  96087. #if HAVE_CONFIG_H
  96088. # include <config.h>
  96089. #endif
  96090. #include <math.h>
  96091. /*** Start of inlined file: lpc.h ***/
  96092. #ifndef FLAC__PRIVATE__LPC_H
  96093. #define FLAC__PRIVATE__LPC_H
  96094. #ifdef HAVE_CONFIG_H
  96095. #include <config.h>
  96096. #endif
  96097. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96098. /*
  96099. * FLAC__lpc_window_data()
  96100. * --------------------------------------------------------------------
  96101. * Applies the given window to the data.
  96102. * OPT: asm implementation
  96103. *
  96104. * IN in[0,data_len-1]
  96105. * IN window[0,data_len-1]
  96106. * OUT out[0,lag-1]
  96107. * IN data_len
  96108. */
  96109. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len);
  96110. /*
  96111. * FLAC__lpc_compute_autocorrelation()
  96112. * --------------------------------------------------------------------
  96113. * Compute the autocorrelation for lags between 0 and lag-1.
  96114. * Assumes data[] outside of [0,data_len-1] == 0.
  96115. * Asserts that lag > 0.
  96116. *
  96117. * IN data[0,data_len-1]
  96118. * IN data_len
  96119. * IN 0 < lag <= data_len
  96120. * OUT autoc[0,lag-1]
  96121. */
  96122. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96123. #ifndef FLAC__NO_ASM
  96124. # ifdef FLAC__CPU_IA32
  96125. # ifdef FLAC__HAS_NASM
  96126. void FLAC__lpc_compute_autocorrelation_asm_ia32(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96127. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96128. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96129. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96130. void FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96131. # endif
  96132. # endif
  96133. #endif
  96134. /*
  96135. * FLAC__lpc_compute_lp_coefficients()
  96136. * --------------------------------------------------------------------
  96137. * Computes LP coefficients for orders 1..max_order.
  96138. * Do not call if autoc[0] == 0.0. This means the signal is zero
  96139. * and there is no point in calculating a predictor.
  96140. *
  96141. * IN autoc[0,max_order] autocorrelation values
  96142. * IN 0 < max_order <= FLAC__MAX_LPC_ORDER max LP order to compute
  96143. * OUT lp_coeff[0,max_order-1][0,max_order-1] LP coefficients for each order
  96144. * *** IMPORTANT:
  96145. * *** lp_coeff[0,max_order-1][max_order,FLAC__MAX_LPC_ORDER-1] are untouched
  96146. * OUT error[0,max_order-1] error for each order (more
  96147. * specifically, the variance of
  96148. * the error signal times # of
  96149. * samples in the signal)
  96150. *
  96151. * Example: if max_order is 9, the LP coefficients for order 9 will be
  96152. * in lp_coeff[8][0,8], the LP coefficients for order 8 will be
  96153. * in lp_coeff[7][0,7], etc.
  96154. */
  96155. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[]);
  96156. /*
  96157. * FLAC__lpc_quantize_coefficients()
  96158. * --------------------------------------------------------------------
  96159. * Quantizes the LP coefficients. NOTE: precision + bits_per_sample
  96160. * must be less than 32 (sizeof(FLAC__int32)*8).
  96161. *
  96162. * IN lp_coeff[0,order-1] LP coefficients
  96163. * IN order LP order
  96164. * IN FLAC__MIN_QLP_COEFF_PRECISION < precision
  96165. * desired precision (in bits, including sign
  96166. * bit) of largest coefficient
  96167. * OUT qlp_coeff[0,order-1] quantized coefficients
  96168. * OUT shift # of bits to shift right to get approximated
  96169. * LP coefficients. NOTE: could be negative.
  96170. * RETURN 0 => quantization OK
  96171. * 1 => coefficients require too much shifting for *shift to
  96172. * fit in the LPC subframe header. 'shift' is unset.
  96173. * 2 => coefficients are all zero, which is bad. 'shift' is
  96174. * unset.
  96175. */
  96176. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift);
  96177. /*
  96178. * FLAC__lpc_compute_residual_from_qlp_coefficients()
  96179. * --------------------------------------------------------------------
  96180. * Compute the residual signal obtained from sutracting the predicted
  96181. * signal from the original.
  96182. *
  96183. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  96184. * IN data_len length of original signal
  96185. * IN qlp_coeff[0,order-1] quantized LP coefficients
  96186. * IN order > 0 LP order
  96187. * IN lp_quantization quantization of LP coefficients in bits
  96188. * OUT residual[0,data_len-1] residual signal
  96189. */
  96190. 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[]);
  96191. 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[]);
  96192. #ifndef FLAC__NO_ASM
  96193. # ifdef FLAC__CPU_IA32
  96194. # ifdef FLAC__HAS_NASM
  96195. 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[]);
  96196. 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[]);
  96197. # endif
  96198. # endif
  96199. #endif
  96200. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  96201. /*
  96202. * FLAC__lpc_restore_signal()
  96203. * --------------------------------------------------------------------
  96204. * Restore the original signal by summing the residual and the
  96205. * predictor.
  96206. *
  96207. * IN residual[0,data_len-1] residual signal
  96208. * IN data_len length of original signal
  96209. * IN qlp_coeff[0,order-1] quantized LP coefficients
  96210. * IN order > 0 LP order
  96211. * IN lp_quantization quantization of LP coefficients in bits
  96212. * *** IMPORTANT: the caller must pass in the historical samples:
  96213. * IN data[-order,-1] previously-reconstructed historical samples
  96214. * OUT data[0,data_len-1] original signal
  96215. */
  96216. 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[]);
  96217. 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[]);
  96218. #ifndef FLAC__NO_ASM
  96219. # ifdef FLAC__CPU_IA32
  96220. # ifdef FLAC__HAS_NASM
  96221. 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[]);
  96222. 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[]);
  96223. # endif /* FLAC__HAS_NASM */
  96224. # elif defined FLAC__CPU_PPC
  96225. 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[]);
  96226. 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[]);
  96227. # endif/* FLAC__CPU_IA32 || FLAC__CPU_PPC */
  96228. #endif /* FLAC__NO_ASM */
  96229. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96230. /*
  96231. * FLAC__lpc_compute_expected_bits_per_residual_sample()
  96232. * --------------------------------------------------------------------
  96233. * Compute the expected number of bits per residual signal sample
  96234. * based on the LP error (which is related to the residual variance).
  96235. *
  96236. * IN lpc_error >= 0.0 error returned from calculating LP coefficients
  96237. * IN total_samples > 0 # of samples in residual signal
  96238. * RETURN expected bits per sample
  96239. */
  96240. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples);
  96241. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale);
  96242. /*
  96243. * FLAC__lpc_compute_best_order()
  96244. * --------------------------------------------------------------------
  96245. * Compute the best order from the array of signal errors returned
  96246. * during coefficient computation.
  96247. *
  96248. * IN lpc_error[0,max_order-1] >= 0.0 error returned from calculating LP coefficients
  96249. * IN max_order > 0 max LP order
  96250. * IN total_samples > 0 # of samples in residual signal
  96251. * IN overhead_bits_per_order # of bits overhead for each increased LP order
  96252. * (includes warmup sample size and quantized LP coefficient)
  96253. * RETURN [1,max_order] best order
  96254. */
  96255. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order);
  96256. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  96257. #endif
  96258. /*** End of inlined file: lpc.h ***/
  96259. #if defined DEBUG || defined FLAC__OVERFLOW_DETECT || defined FLAC__OVERFLOW_DETECT_VERBOSE
  96260. #include <stdio.h>
  96261. #endif
  96262. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96263. #ifndef M_LN2
  96264. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  96265. #define M_LN2 0.69314718055994530942
  96266. #endif
  96267. /* OPT: #undef'ing this may improve the speed on some architectures */
  96268. #define FLAC__LPC_UNROLLED_FILTER_LOOPS
  96269. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len)
  96270. {
  96271. unsigned i;
  96272. for(i = 0; i < data_len; i++)
  96273. out[i] = in[i] * window[i];
  96274. }
  96275. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
  96276. {
  96277. /* a readable, but slower, version */
  96278. #if 0
  96279. FLAC__real d;
  96280. unsigned i;
  96281. FLAC__ASSERT(lag > 0);
  96282. FLAC__ASSERT(lag <= data_len);
  96283. /*
  96284. * Technically we should subtract the mean first like so:
  96285. * for(i = 0; i < data_len; i++)
  96286. * data[i] -= mean;
  96287. * but it appears not to make enough of a difference to matter, and
  96288. * most signals are already closely centered around zero
  96289. */
  96290. while(lag--) {
  96291. for(i = lag, d = 0.0; i < data_len; i++)
  96292. d += data[i] * data[i - lag];
  96293. autoc[lag] = d;
  96294. }
  96295. #endif
  96296. /*
  96297. * this version tends to run faster because of better data locality
  96298. * ('data_len' is usually much larger than 'lag')
  96299. */
  96300. FLAC__real d;
  96301. unsigned sample, coeff;
  96302. const unsigned limit = data_len - lag;
  96303. FLAC__ASSERT(lag > 0);
  96304. FLAC__ASSERT(lag <= data_len);
  96305. for(coeff = 0; coeff < lag; coeff++)
  96306. autoc[coeff] = 0.0;
  96307. for(sample = 0; sample <= limit; sample++) {
  96308. d = data[sample];
  96309. for(coeff = 0; coeff < lag; coeff++)
  96310. autoc[coeff] += d * data[sample+coeff];
  96311. }
  96312. for(; sample < data_len; sample++) {
  96313. d = data[sample];
  96314. for(coeff = 0; coeff < data_len - sample; coeff++)
  96315. autoc[coeff] += d * data[sample+coeff];
  96316. }
  96317. }
  96318. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[])
  96319. {
  96320. unsigned i, j;
  96321. FLAC__double r, err, ref[FLAC__MAX_LPC_ORDER], lpc[FLAC__MAX_LPC_ORDER];
  96322. FLAC__ASSERT(0 != max_order);
  96323. FLAC__ASSERT(0 < *max_order);
  96324. FLAC__ASSERT(*max_order <= FLAC__MAX_LPC_ORDER);
  96325. FLAC__ASSERT(autoc[0] != 0.0);
  96326. err = autoc[0];
  96327. for(i = 0; i < *max_order; i++) {
  96328. /* Sum up this iteration's reflection coefficient. */
  96329. r = -autoc[i+1];
  96330. for(j = 0; j < i; j++)
  96331. r -= lpc[j] * autoc[i-j];
  96332. ref[i] = (r/=err);
  96333. /* Update LPC coefficients and total error. */
  96334. lpc[i]=r;
  96335. for(j = 0; j < (i>>1); j++) {
  96336. FLAC__double tmp = lpc[j];
  96337. lpc[j] += r * lpc[i-1-j];
  96338. lpc[i-1-j] += r * tmp;
  96339. }
  96340. if(i & 1)
  96341. lpc[j] += lpc[j] * r;
  96342. err *= (1.0 - r * r);
  96343. /* save this order */
  96344. for(j = 0; j <= i; j++)
  96345. lp_coeff[i][j] = (FLAC__real)(-lpc[j]); /* negate FIR filter coeff to get predictor coeff */
  96346. error[i] = err;
  96347. /* see SF bug #1601812 http://sourceforge.net/tracker/index.php?func=detail&aid=1601812&group_id=13478&atid=113478 */
  96348. if(err == 0.0) {
  96349. *max_order = i+1;
  96350. return;
  96351. }
  96352. }
  96353. }
  96354. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift)
  96355. {
  96356. unsigned i;
  96357. FLAC__double cmax;
  96358. FLAC__int32 qmax, qmin;
  96359. FLAC__ASSERT(precision > 0);
  96360. FLAC__ASSERT(precision >= FLAC__MIN_QLP_COEFF_PRECISION);
  96361. /* drop one bit for the sign; from here on out we consider only |lp_coeff[i]| */
  96362. precision--;
  96363. qmax = 1 << precision;
  96364. qmin = -qmax;
  96365. qmax--;
  96366. /* calc cmax = max( |lp_coeff[i]| ) */
  96367. cmax = 0.0;
  96368. for(i = 0; i < order; i++) {
  96369. const FLAC__double d = fabs(lp_coeff[i]);
  96370. if(d > cmax)
  96371. cmax = d;
  96372. }
  96373. if(cmax <= 0.0) {
  96374. /* => coefficients are all 0, which means our constant-detect didn't work */
  96375. return 2;
  96376. }
  96377. else {
  96378. const int max_shiftlimit = (1 << (FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN-1)) - 1;
  96379. const int min_shiftlimit = -max_shiftlimit - 1;
  96380. int log2cmax;
  96381. (void)frexp(cmax, &log2cmax);
  96382. log2cmax--;
  96383. *shift = (int)precision - log2cmax - 1;
  96384. if(*shift > max_shiftlimit)
  96385. *shift = max_shiftlimit;
  96386. else if(*shift < min_shiftlimit)
  96387. return 1;
  96388. }
  96389. if(*shift >= 0) {
  96390. FLAC__double error = 0.0;
  96391. FLAC__int32 q;
  96392. for(i = 0; i < order; i++) {
  96393. error += lp_coeff[i] * (1 << *shift);
  96394. #if 1 /* unfortunately lround() is C99 */
  96395. if(error >= 0.0)
  96396. q = (FLAC__int32)(error + 0.5);
  96397. else
  96398. q = (FLAC__int32)(error - 0.5);
  96399. #else
  96400. q = lround(error);
  96401. #endif
  96402. #ifdef FLAC__OVERFLOW_DETECT
  96403. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  96404. 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]);
  96405. else if(q < qmin)
  96406. 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]);
  96407. #endif
  96408. if(q > qmax)
  96409. q = qmax;
  96410. else if(q < qmin)
  96411. q = qmin;
  96412. error -= q;
  96413. qlp_coeff[i] = q;
  96414. }
  96415. }
  96416. /* negative shift is very rare but due to design flaw, negative shift is
  96417. * a NOP in the decoder, so it must be handled specially by scaling down
  96418. * coeffs
  96419. */
  96420. else {
  96421. const int nshift = -(*shift);
  96422. FLAC__double error = 0.0;
  96423. FLAC__int32 q;
  96424. #ifdef DEBUG
  96425. fprintf(stderr,"FLAC__lpc_quantize_coefficients: negative shift=%d order=%u cmax=%f\n", *shift, order, cmax);
  96426. #endif
  96427. for(i = 0; i < order; i++) {
  96428. error += lp_coeff[i] / (1 << nshift);
  96429. #if 1 /* unfortunately lround() is C99 */
  96430. if(error >= 0.0)
  96431. q = (FLAC__int32)(error + 0.5);
  96432. else
  96433. q = (FLAC__int32)(error - 0.5);
  96434. #else
  96435. q = lround(error);
  96436. #endif
  96437. #ifdef FLAC__OVERFLOW_DETECT
  96438. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  96439. 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]);
  96440. else if(q < qmin)
  96441. 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]);
  96442. #endif
  96443. if(q > qmax)
  96444. q = qmax;
  96445. else if(q < qmin)
  96446. q = qmin;
  96447. error -= q;
  96448. qlp_coeff[i] = q;
  96449. }
  96450. *shift = 0;
  96451. }
  96452. return 0;
  96453. }
  96454. 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[])
  96455. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  96456. {
  96457. FLAC__int64 sumo;
  96458. unsigned i, j;
  96459. FLAC__int32 sum;
  96460. const FLAC__int32 *history;
  96461. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  96462. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  96463. for(i=0;i<order;i++)
  96464. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  96465. fprintf(stderr,"\n");
  96466. #endif
  96467. FLAC__ASSERT(order > 0);
  96468. for(i = 0; i < data_len; i++) {
  96469. sumo = 0;
  96470. sum = 0;
  96471. history = data;
  96472. for(j = 0; j < order; j++) {
  96473. sum += qlp_coeff[j] * (*(--history));
  96474. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  96475. #if defined _MSC_VER
  96476. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  96477. 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);
  96478. #else
  96479. if(sumo > 2147483647ll || sumo < -2147483648ll)
  96480. 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);
  96481. #endif
  96482. }
  96483. *(residual++) = *(data++) - (sum >> lp_quantization);
  96484. }
  96485. /* Here's a slower but clearer version:
  96486. for(i = 0; i < data_len; i++) {
  96487. sum = 0;
  96488. for(j = 0; j < order; j++)
  96489. sum += qlp_coeff[j] * data[i-j-1];
  96490. residual[i] = data[i] - (sum >> lp_quantization);
  96491. }
  96492. */
  96493. }
  96494. #else /* fully unrolled version for normal use */
  96495. {
  96496. int i;
  96497. FLAC__int32 sum;
  96498. FLAC__ASSERT(order > 0);
  96499. FLAC__ASSERT(order <= 32);
  96500. /*
  96501. * We do unique versions up to 12th order since that's the subset limit.
  96502. * Also they are roughly ordered to match frequency of occurrence to
  96503. * minimize branching.
  96504. */
  96505. if(order <= 12) {
  96506. if(order > 8) {
  96507. if(order > 10) {
  96508. if(order == 12) {
  96509. for(i = 0; i < (int)data_len; i++) {
  96510. sum = 0;
  96511. sum += qlp_coeff[11] * data[i-12];
  96512. sum += qlp_coeff[10] * data[i-11];
  96513. sum += qlp_coeff[9] * data[i-10];
  96514. sum += qlp_coeff[8] * data[i-9];
  96515. sum += qlp_coeff[7] * data[i-8];
  96516. sum += qlp_coeff[6] * data[i-7];
  96517. sum += qlp_coeff[5] * data[i-6];
  96518. sum += qlp_coeff[4] * data[i-5];
  96519. sum += qlp_coeff[3] * data[i-4];
  96520. sum += qlp_coeff[2] * data[i-3];
  96521. sum += qlp_coeff[1] * data[i-2];
  96522. sum += qlp_coeff[0] * data[i-1];
  96523. residual[i] = data[i] - (sum >> lp_quantization);
  96524. }
  96525. }
  96526. else { /* order == 11 */
  96527. for(i = 0; i < (int)data_len; i++) {
  96528. sum = 0;
  96529. sum += qlp_coeff[10] * data[i-11];
  96530. sum += qlp_coeff[9] * data[i-10];
  96531. sum += qlp_coeff[8] * data[i-9];
  96532. sum += qlp_coeff[7] * data[i-8];
  96533. sum += qlp_coeff[6] * data[i-7];
  96534. sum += qlp_coeff[5] * data[i-6];
  96535. sum += qlp_coeff[4] * data[i-5];
  96536. sum += qlp_coeff[3] * data[i-4];
  96537. sum += qlp_coeff[2] * data[i-3];
  96538. sum += qlp_coeff[1] * data[i-2];
  96539. sum += qlp_coeff[0] * data[i-1];
  96540. residual[i] = data[i] - (sum >> lp_quantization);
  96541. }
  96542. }
  96543. }
  96544. else {
  96545. if(order == 10) {
  96546. for(i = 0; i < (int)data_len; i++) {
  96547. sum = 0;
  96548. sum += qlp_coeff[9] * data[i-10];
  96549. sum += qlp_coeff[8] * data[i-9];
  96550. sum += qlp_coeff[7] * data[i-8];
  96551. sum += qlp_coeff[6] * data[i-7];
  96552. sum += qlp_coeff[5] * data[i-6];
  96553. sum += qlp_coeff[4] * data[i-5];
  96554. sum += qlp_coeff[3] * data[i-4];
  96555. sum += qlp_coeff[2] * data[i-3];
  96556. sum += qlp_coeff[1] * data[i-2];
  96557. sum += qlp_coeff[0] * data[i-1];
  96558. residual[i] = data[i] - (sum >> lp_quantization);
  96559. }
  96560. }
  96561. else { /* order == 9 */
  96562. for(i = 0; i < (int)data_len; i++) {
  96563. sum = 0;
  96564. sum += qlp_coeff[8] * data[i-9];
  96565. sum += qlp_coeff[7] * data[i-8];
  96566. sum += qlp_coeff[6] * data[i-7];
  96567. sum += qlp_coeff[5] * data[i-6];
  96568. sum += qlp_coeff[4] * data[i-5];
  96569. sum += qlp_coeff[3] * data[i-4];
  96570. sum += qlp_coeff[2] * data[i-3];
  96571. sum += qlp_coeff[1] * data[i-2];
  96572. sum += qlp_coeff[0] * data[i-1];
  96573. residual[i] = data[i] - (sum >> lp_quantization);
  96574. }
  96575. }
  96576. }
  96577. }
  96578. else if(order > 4) {
  96579. if(order > 6) {
  96580. if(order == 8) {
  96581. for(i = 0; i < (int)data_len; i++) {
  96582. sum = 0;
  96583. sum += qlp_coeff[7] * data[i-8];
  96584. sum += qlp_coeff[6] * data[i-7];
  96585. sum += qlp_coeff[5] * data[i-6];
  96586. sum += qlp_coeff[4] * data[i-5];
  96587. sum += qlp_coeff[3] * data[i-4];
  96588. sum += qlp_coeff[2] * data[i-3];
  96589. sum += qlp_coeff[1] * data[i-2];
  96590. sum += qlp_coeff[0] * data[i-1];
  96591. residual[i] = data[i] - (sum >> lp_quantization);
  96592. }
  96593. }
  96594. else { /* order == 7 */
  96595. for(i = 0; i < (int)data_len; i++) {
  96596. sum = 0;
  96597. sum += qlp_coeff[6] * data[i-7];
  96598. sum += qlp_coeff[5] * data[i-6];
  96599. sum += qlp_coeff[4] * data[i-5];
  96600. sum += qlp_coeff[3] * data[i-4];
  96601. sum += qlp_coeff[2] * data[i-3];
  96602. sum += qlp_coeff[1] * data[i-2];
  96603. sum += qlp_coeff[0] * data[i-1];
  96604. residual[i] = data[i] - (sum >> lp_quantization);
  96605. }
  96606. }
  96607. }
  96608. else {
  96609. if(order == 6) {
  96610. for(i = 0; i < (int)data_len; i++) {
  96611. sum = 0;
  96612. sum += qlp_coeff[5] * data[i-6];
  96613. sum += qlp_coeff[4] * data[i-5];
  96614. sum += qlp_coeff[3] * data[i-4];
  96615. sum += qlp_coeff[2] * data[i-3];
  96616. sum += qlp_coeff[1] * data[i-2];
  96617. sum += qlp_coeff[0] * data[i-1];
  96618. residual[i] = data[i] - (sum >> lp_quantization);
  96619. }
  96620. }
  96621. else { /* order == 5 */
  96622. for(i = 0; i < (int)data_len; i++) {
  96623. sum = 0;
  96624. sum += qlp_coeff[4] * data[i-5];
  96625. sum += qlp_coeff[3] * data[i-4];
  96626. sum += qlp_coeff[2] * data[i-3];
  96627. sum += qlp_coeff[1] * data[i-2];
  96628. sum += qlp_coeff[0] * data[i-1];
  96629. residual[i] = data[i] - (sum >> lp_quantization);
  96630. }
  96631. }
  96632. }
  96633. }
  96634. else {
  96635. if(order > 2) {
  96636. if(order == 4) {
  96637. for(i = 0; i < (int)data_len; i++) {
  96638. sum = 0;
  96639. sum += qlp_coeff[3] * data[i-4];
  96640. sum += qlp_coeff[2] * data[i-3];
  96641. sum += qlp_coeff[1] * data[i-2];
  96642. sum += qlp_coeff[0] * data[i-1];
  96643. residual[i] = data[i] - (sum >> lp_quantization);
  96644. }
  96645. }
  96646. else { /* order == 3 */
  96647. for(i = 0; i < (int)data_len; i++) {
  96648. sum = 0;
  96649. sum += qlp_coeff[2] * data[i-3];
  96650. sum += qlp_coeff[1] * data[i-2];
  96651. sum += qlp_coeff[0] * data[i-1];
  96652. residual[i] = data[i] - (sum >> lp_quantization);
  96653. }
  96654. }
  96655. }
  96656. else {
  96657. if(order == 2) {
  96658. for(i = 0; i < (int)data_len; i++) {
  96659. sum = 0;
  96660. sum += qlp_coeff[1] * data[i-2];
  96661. sum += qlp_coeff[0] * data[i-1];
  96662. residual[i] = data[i] - (sum >> lp_quantization);
  96663. }
  96664. }
  96665. else { /* order == 1 */
  96666. for(i = 0; i < (int)data_len; i++)
  96667. residual[i] = data[i] - ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  96668. }
  96669. }
  96670. }
  96671. }
  96672. else { /* order > 12 */
  96673. for(i = 0; i < (int)data_len; i++) {
  96674. sum = 0;
  96675. switch(order) {
  96676. case 32: sum += qlp_coeff[31] * data[i-32];
  96677. case 31: sum += qlp_coeff[30] * data[i-31];
  96678. case 30: sum += qlp_coeff[29] * data[i-30];
  96679. case 29: sum += qlp_coeff[28] * data[i-29];
  96680. case 28: sum += qlp_coeff[27] * data[i-28];
  96681. case 27: sum += qlp_coeff[26] * data[i-27];
  96682. case 26: sum += qlp_coeff[25] * data[i-26];
  96683. case 25: sum += qlp_coeff[24] * data[i-25];
  96684. case 24: sum += qlp_coeff[23] * data[i-24];
  96685. case 23: sum += qlp_coeff[22] * data[i-23];
  96686. case 22: sum += qlp_coeff[21] * data[i-22];
  96687. case 21: sum += qlp_coeff[20] * data[i-21];
  96688. case 20: sum += qlp_coeff[19] * data[i-20];
  96689. case 19: sum += qlp_coeff[18] * data[i-19];
  96690. case 18: sum += qlp_coeff[17] * data[i-18];
  96691. case 17: sum += qlp_coeff[16] * data[i-17];
  96692. case 16: sum += qlp_coeff[15] * data[i-16];
  96693. case 15: sum += qlp_coeff[14] * data[i-15];
  96694. case 14: sum += qlp_coeff[13] * data[i-14];
  96695. case 13: sum += qlp_coeff[12] * data[i-13];
  96696. sum += qlp_coeff[11] * data[i-12];
  96697. sum += qlp_coeff[10] * data[i-11];
  96698. sum += qlp_coeff[ 9] * data[i-10];
  96699. sum += qlp_coeff[ 8] * data[i- 9];
  96700. sum += qlp_coeff[ 7] * data[i- 8];
  96701. sum += qlp_coeff[ 6] * data[i- 7];
  96702. sum += qlp_coeff[ 5] * data[i- 6];
  96703. sum += qlp_coeff[ 4] * data[i- 5];
  96704. sum += qlp_coeff[ 3] * data[i- 4];
  96705. sum += qlp_coeff[ 2] * data[i- 3];
  96706. sum += qlp_coeff[ 1] * data[i- 2];
  96707. sum += qlp_coeff[ 0] * data[i- 1];
  96708. }
  96709. residual[i] = data[i] - (sum >> lp_quantization);
  96710. }
  96711. }
  96712. }
  96713. #endif
  96714. 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[])
  96715. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  96716. {
  96717. unsigned i, j;
  96718. FLAC__int64 sum;
  96719. const FLAC__int32 *history;
  96720. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  96721. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  96722. for(i=0;i<order;i++)
  96723. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  96724. fprintf(stderr,"\n");
  96725. #endif
  96726. FLAC__ASSERT(order > 0);
  96727. for(i = 0; i < data_len; i++) {
  96728. sum = 0;
  96729. history = data;
  96730. for(j = 0; j < order; j++)
  96731. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  96732. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  96733. #if defined _MSC_VER
  96734. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  96735. #else
  96736. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  96737. #endif
  96738. break;
  96739. }
  96740. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*data) - (sum >> lp_quantization)) > 32) {
  96741. #if defined _MSC_VER
  96742. 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));
  96743. #else
  96744. 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)));
  96745. #endif
  96746. break;
  96747. }
  96748. *(residual++) = *(data++) - (FLAC__int32)(sum >> lp_quantization);
  96749. }
  96750. }
  96751. #else /* fully unrolled version for normal use */
  96752. {
  96753. int i;
  96754. FLAC__int64 sum;
  96755. FLAC__ASSERT(order > 0);
  96756. FLAC__ASSERT(order <= 32);
  96757. /*
  96758. * We do unique versions up to 12th order since that's the subset limit.
  96759. * Also they are roughly ordered to match frequency of occurrence to
  96760. * minimize branching.
  96761. */
  96762. if(order <= 12) {
  96763. if(order > 8) {
  96764. if(order > 10) {
  96765. if(order == 12) {
  96766. for(i = 0; i < (int)data_len; i++) {
  96767. sum = 0;
  96768. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  96769. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  96770. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  96771. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  96772. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  96773. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  96774. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  96775. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  96776. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  96777. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  96778. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  96779. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  96780. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  96781. }
  96782. }
  96783. else { /* order == 11 */
  96784. for(i = 0; i < (int)data_len; i++) {
  96785. sum = 0;
  96786. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  96787. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  96788. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  96789. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  96790. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  96791. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  96792. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  96793. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  96794. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  96795. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  96796. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  96797. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  96798. }
  96799. }
  96800. }
  96801. else {
  96802. if(order == 10) {
  96803. for(i = 0; i < (int)data_len; i++) {
  96804. sum = 0;
  96805. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  96806. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  96807. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  96808. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  96809. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  96810. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  96811. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  96812. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  96813. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  96814. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  96815. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  96816. }
  96817. }
  96818. else { /* order == 9 */
  96819. for(i = 0; i < (int)data_len; i++) {
  96820. sum = 0;
  96821. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  96822. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  96823. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  96824. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  96825. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  96826. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  96827. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  96828. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  96829. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  96830. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  96831. }
  96832. }
  96833. }
  96834. }
  96835. else if(order > 4) {
  96836. if(order > 6) {
  96837. if(order == 8) {
  96838. for(i = 0; i < (int)data_len; i++) {
  96839. sum = 0;
  96840. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  96841. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  96842. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  96843. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  96844. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  96845. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  96846. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  96847. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  96848. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  96849. }
  96850. }
  96851. else { /* order == 7 */
  96852. for(i = 0; i < (int)data_len; i++) {
  96853. sum = 0;
  96854. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  96855. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  96856. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  96857. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  96858. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  96859. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  96860. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  96861. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  96862. }
  96863. }
  96864. }
  96865. else {
  96866. if(order == 6) {
  96867. for(i = 0; i < (int)data_len; i++) {
  96868. sum = 0;
  96869. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  96870. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  96871. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  96872. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  96873. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  96874. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  96875. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  96876. }
  96877. }
  96878. else { /* order == 5 */
  96879. for(i = 0; i < (int)data_len; i++) {
  96880. sum = 0;
  96881. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  96882. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  96883. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  96884. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  96885. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  96886. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  96887. }
  96888. }
  96889. }
  96890. }
  96891. else {
  96892. if(order > 2) {
  96893. if(order == 4) {
  96894. for(i = 0; i < (int)data_len; i++) {
  96895. sum = 0;
  96896. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  96897. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  96898. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  96899. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  96900. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  96901. }
  96902. }
  96903. else { /* order == 3 */
  96904. for(i = 0; i < (int)data_len; i++) {
  96905. sum = 0;
  96906. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  96907. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  96908. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  96909. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  96910. }
  96911. }
  96912. }
  96913. else {
  96914. if(order == 2) {
  96915. for(i = 0; i < (int)data_len; i++) {
  96916. sum = 0;
  96917. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  96918. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  96919. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  96920. }
  96921. }
  96922. else { /* order == 1 */
  96923. for(i = 0; i < (int)data_len; i++)
  96924. residual[i] = data[i] - (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  96925. }
  96926. }
  96927. }
  96928. }
  96929. else { /* order > 12 */
  96930. for(i = 0; i < (int)data_len; i++) {
  96931. sum = 0;
  96932. switch(order) {
  96933. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  96934. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  96935. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  96936. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  96937. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  96938. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  96939. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  96940. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  96941. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  96942. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  96943. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  96944. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  96945. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  96946. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  96947. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  96948. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  96949. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  96950. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  96951. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  96952. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  96953. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  96954. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  96955. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  96956. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  96957. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  96958. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  96959. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  96960. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  96961. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  96962. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  96963. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  96964. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  96965. }
  96966. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  96967. }
  96968. }
  96969. }
  96970. #endif
  96971. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  96972. 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[])
  96973. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  96974. {
  96975. FLAC__int64 sumo;
  96976. unsigned i, j;
  96977. FLAC__int32 sum;
  96978. const FLAC__int32 *r = residual, *history;
  96979. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  96980. fprintf(stderr,"FLAC__lpc_restore_signal: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  96981. for(i=0;i<order;i++)
  96982. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  96983. fprintf(stderr,"\n");
  96984. #endif
  96985. FLAC__ASSERT(order > 0);
  96986. for(i = 0; i < data_len; i++) {
  96987. sumo = 0;
  96988. sum = 0;
  96989. history = data;
  96990. for(j = 0; j < order; j++) {
  96991. sum += qlp_coeff[j] * (*(--history));
  96992. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  96993. #if defined _MSC_VER
  96994. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  96995. 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);
  96996. #else
  96997. if(sumo > 2147483647ll || sumo < -2147483648ll)
  96998. 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);
  96999. #endif
  97000. }
  97001. *(data++) = *(r++) + (sum >> lp_quantization);
  97002. }
  97003. /* Here's a slower but clearer version:
  97004. for(i = 0; i < data_len; i++) {
  97005. sum = 0;
  97006. for(j = 0; j < order; j++)
  97007. sum += qlp_coeff[j] * data[i-j-1];
  97008. data[i] = residual[i] + (sum >> lp_quantization);
  97009. }
  97010. */
  97011. }
  97012. #else /* fully unrolled version for normal use */
  97013. {
  97014. int i;
  97015. FLAC__int32 sum;
  97016. FLAC__ASSERT(order > 0);
  97017. FLAC__ASSERT(order <= 32);
  97018. /*
  97019. * We do unique versions up to 12th order since that's the subset limit.
  97020. * Also they are roughly ordered to match frequency of occurrence to
  97021. * minimize branching.
  97022. */
  97023. if(order <= 12) {
  97024. if(order > 8) {
  97025. if(order > 10) {
  97026. if(order == 12) {
  97027. for(i = 0; i < (int)data_len; i++) {
  97028. sum = 0;
  97029. sum += qlp_coeff[11] * data[i-12];
  97030. sum += qlp_coeff[10] * data[i-11];
  97031. sum += qlp_coeff[9] * data[i-10];
  97032. sum += qlp_coeff[8] * data[i-9];
  97033. sum += qlp_coeff[7] * data[i-8];
  97034. sum += qlp_coeff[6] * data[i-7];
  97035. sum += qlp_coeff[5] * data[i-6];
  97036. sum += qlp_coeff[4] * data[i-5];
  97037. sum += qlp_coeff[3] * data[i-4];
  97038. sum += qlp_coeff[2] * data[i-3];
  97039. sum += qlp_coeff[1] * data[i-2];
  97040. sum += qlp_coeff[0] * data[i-1];
  97041. data[i] = residual[i] + (sum >> lp_quantization);
  97042. }
  97043. }
  97044. else { /* order == 11 */
  97045. for(i = 0; i < (int)data_len; i++) {
  97046. sum = 0;
  97047. sum += qlp_coeff[10] * data[i-11];
  97048. sum += qlp_coeff[9] * data[i-10];
  97049. sum += qlp_coeff[8] * data[i-9];
  97050. sum += qlp_coeff[7] * data[i-8];
  97051. sum += qlp_coeff[6] * data[i-7];
  97052. sum += qlp_coeff[5] * data[i-6];
  97053. sum += qlp_coeff[4] * data[i-5];
  97054. sum += qlp_coeff[3] * data[i-4];
  97055. sum += qlp_coeff[2] * data[i-3];
  97056. sum += qlp_coeff[1] * data[i-2];
  97057. sum += qlp_coeff[0] * data[i-1];
  97058. data[i] = residual[i] + (sum >> lp_quantization);
  97059. }
  97060. }
  97061. }
  97062. else {
  97063. if(order == 10) {
  97064. for(i = 0; i < (int)data_len; i++) {
  97065. sum = 0;
  97066. sum += qlp_coeff[9] * data[i-10];
  97067. sum += qlp_coeff[8] * data[i-9];
  97068. sum += qlp_coeff[7] * data[i-8];
  97069. sum += qlp_coeff[6] * data[i-7];
  97070. sum += qlp_coeff[5] * data[i-6];
  97071. sum += qlp_coeff[4] * data[i-5];
  97072. sum += qlp_coeff[3] * data[i-4];
  97073. sum += qlp_coeff[2] * data[i-3];
  97074. sum += qlp_coeff[1] * data[i-2];
  97075. sum += qlp_coeff[0] * data[i-1];
  97076. data[i] = residual[i] + (sum >> lp_quantization);
  97077. }
  97078. }
  97079. else { /* order == 9 */
  97080. for(i = 0; i < (int)data_len; i++) {
  97081. sum = 0;
  97082. sum += qlp_coeff[8] * data[i-9];
  97083. sum += qlp_coeff[7] * data[i-8];
  97084. sum += qlp_coeff[6] * data[i-7];
  97085. sum += qlp_coeff[5] * data[i-6];
  97086. sum += qlp_coeff[4] * data[i-5];
  97087. sum += qlp_coeff[3] * data[i-4];
  97088. sum += qlp_coeff[2] * data[i-3];
  97089. sum += qlp_coeff[1] * data[i-2];
  97090. sum += qlp_coeff[0] * data[i-1];
  97091. data[i] = residual[i] + (sum >> lp_quantization);
  97092. }
  97093. }
  97094. }
  97095. }
  97096. else if(order > 4) {
  97097. if(order > 6) {
  97098. if(order == 8) {
  97099. for(i = 0; i < (int)data_len; i++) {
  97100. sum = 0;
  97101. sum += qlp_coeff[7] * data[i-8];
  97102. sum += qlp_coeff[6] * data[i-7];
  97103. sum += qlp_coeff[5] * data[i-6];
  97104. sum += qlp_coeff[4] * data[i-5];
  97105. sum += qlp_coeff[3] * data[i-4];
  97106. sum += qlp_coeff[2] * data[i-3];
  97107. sum += qlp_coeff[1] * data[i-2];
  97108. sum += qlp_coeff[0] * data[i-1];
  97109. data[i] = residual[i] + (sum >> lp_quantization);
  97110. }
  97111. }
  97112. else { /* order == 7 */
  97113. for(i = 0; i < (int)data_len; i++) {
  97114. sum = 0;
  97115. sum += qlp_coeff[6] * data[i-7];
  97116. sum += qlp_coeff[5] * data[i-6];
  97117. sum += qlp_coeff[4] * data[i-5];
  97118. sum += qlp_coeff[3] * data[i-4];
  97119. sum += qlp_coeff[2] * data[i-3];
  97120. sum += qlp_coeff[1] * data[i-2];
  97121. sum += qlp_coeff[0] * data[i-1];
  97122. data[i] = residual[i] + (sum >> lp_quantization);
  97123. }
  97124. }
  97125. }
  97126. else {
  97127. if(order == 6) {
  97128. for(i = 0; i < (int)data_len; i++) {
  97129. sum = 0;
  97130. sum += qlp_coeff[5] * data[i-6];
  97131. sum += qlp_coeff[4] * data[i-5];
  97132. sum += qlp_coeff[3] * data[i-4];
  97133. sum += qlp_coeff[2] * data[i-3];
  97134. sum += qlp_coeff[1] * data[i-2];
  97135. sum += qlp_coeff[0] * data[i-1];
  97136. data[i] = residual[i] + (sum >> lp_quantization);
  97137. }
  97138. }
  97139. else { /* order == 5 */
  97140. for(i = 0; i < (int)data_len; i++) {
  97141. sum = 0;
  97142. sum += qlp_coeff[4] * data[i-5];
  97143. sum += qlp_coeff[3] * data[i-4];
  97144. sum += qlp_coeff[2] * data[i-3];
  97145. sum += qlp_coeff[1] * data[i-2];
  97146. sum += qlp_coeff[0] * data[i-1];
  97147. data[i] = residual[i] + (sum >> lp_quantization);
  97148. }
  97149. }
  97150. }
  97151. }
  97152. else {
  97153. if(order > 2) {
  97154. if(order == 4) {
  97155. for(i = 0; i < (int)data_len; i++) {
  97156. sum = 0;
  97157. sum += qlp_coeff[3] * data[i-4];
  97158. sum += qlp_coeff[2] * data[i-3];
  97159. sum += qlp_coeff[1] * data[i-2];
  97160. sum += qlp_coeff[0] * data[i-1];
  97161. data[i] = residual[i] + (sum >> lp_quantization);
  97162. }
  97163. }
  97164. else { /* order == 3 */
  97165. for(i = 0; i < (int)data_len; i++) {
  97166. sum = 0;
  97167. sum += qlp_coeff[2] * data[i-3];
  97168. sum += qlp_coeff[1] * data[i-2];
  97169. sum += qlp_coeff[0] * data[i-1];
  97170. data[i] = residual[i] + (sum >> lp_quantization);
  97171. }
  97172. }
  97173. }
  97174. else {
  97175. if(order == 2) {
  97176. for(i = 0; i < (int)data_len; i++) {
  97177. sum = 0;
  97178. sum += qlp_coeff[1] * data[i-2];
  97179. sum += qlp_coeff[0] * data[i-1];
  97180. data[i] = residual[i] + (sum >> lp_quantization);
  97181. }
  97182. }
  97183. else { /* order == 1 */
  97184. for(i = 0; i < (int)data_len; i++)
  97185. data[i] = residual[i] + ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  97186. }
  97187. }
  97188. }
  97189. }
  97190. else { /* order > 12 */
  97191. for(i = 0; i < (int)data_len; i++) {
  97192. sum = 0;
  97193. switch(order) {
  97194. case 32: sum += qlp_coeff[31] * data[i-32];
  97195. case 31: sum += qlp_coeff[30] * data[i-31];
  97196. case 30: sum += qlp_coeff[29] * data[i-30];
  97197. case 29: sum += qlp_coeff[28] * data[i-29];
  97198. case 28: sum += qlp_coeff[27] * data[i-28];
  97199. case 27: sum += qlp_coeff[26] * data[i-27];
  97200. case 26: sum += qlp_coeff[25] * data[i-26];
  97201. case 25: sum += qlp_coeff[24] * data[i-25];
  97202. case 24: sum += qlp_coeff[23] * data[i-24];
  97203. case 23: sum += qlp_coeff[22] * data[i-23];
  97204. case 22: sum += qlp_coeff[21] * data[i-22];
  97205. case 21: sum += qlp_coeff[20] * data[i-21];
  97206. case 20: sum += qlp_coeff[19] * data[i-20];
  97207. case 19: sum += qlp_coeff[18] * data[i-19];
  97208. case 18: sum += qlp_coeff[17] * data[i-18];
  97209. case 17: sum += qlp_coeff[16] * data[i-17];
  97210. case 16: sum += qlp_coeff[15] * data[i-16];
  97211. case 15: sum += qlp_coeff[14] * data[i-15];
  97212. case 14: sum += qlp_coeff[13] * data[i-14];
  97213. case 13: sum += qlp_coeff[12] * data[i-13];
  97214. sum += qlp_coeff[11] * data[i-12];
  97215. sum += qlp_coeff[10] * data[i-11];
  97216. sum += qlp_coeff[ 9] * data[i-10];
  97217. sum += qlp_coeff[ 8] * data[i- 9];
  97218. sum += qlp_coeff[ 7] * data[i- 8];
  97219. sum += qlp_coeff[ 6] * data[i- 7];
  97220. sum += qlp_coeff[ 5] * data[i- 6];
  97221. sum += qlp_coeff[ 4] * data[i- 5];
  97222. sum += qlp_coeff[ 3] * data[i- 4];
  97223. sum += qlp_coeff[ 2] * data[i- 3];
  97224. sum += qlp_coeff[ 1] * data[i- 2];
  97225. sum += qlp_coeff[ 0] * data[i- 1];
  97226. }
  97227. data[i] = residual[i] + (sum >> lp_quantization);
  97228. }
  97229. }
  97230. }
  97231. #endif
  97232. 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[])
  97233. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97234. {
  97235. unsigned i, j;
  97236. FLAC__int64 sum;
  97237. const FLAC__int32 *r = residual, *history;
  97238. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97239. fprintf(stderr,"FLAC__lpc_restore_signal_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97240. for(i=0;i<order;i++)
  97241. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97242. fprintf(stderr,"\n");
  97243. #endif
  97244. FLAC__ASSERT(order > 0);
  97245. for(i = 0; i < data_len; i++) {
  97246. sum = 0;
  97247. history = data;
  97248. for(j = 0; j < order; j++)
  97249. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  97250. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  97251. #ifdef _MSC_VER
  97252. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  97253. #else
  97254. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  97255. #endif
  97256. break;
  97257. }
  97258. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*r) + (sum >> lp_quantization)) > 32) {
  97259. #ifdef _MSC_VER
  97260. 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));
  97261. #else
  97262. 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)));
  97263. #endif
  97264. break;
  97265. }
  97266. *(data++) = *(r++) + (FLAC__int32)(sum >> lp_quantization);
  97267. }
  97268. }
  97269. #else /* fully unrolled version for normal use */
  97270. {
  97271. int i;
  97272. FLAC__int64 sum;
  97273. FLAC__ASSERT(order > 0);
  97274. FLAC__ASSERT(order <= 32);
  97275. /*
  97276. * We do unique versions up to 12th order since that's the subset limit.
  97277. * Also they are roughly ordered to match frequency of occurrence to
  97278. * minimize branching.
  97279. */
  97280. if(order <= 12) {
  97281. if(order > 8) {
  97282. if(order > 10) {
  97283. if(order == 12) {
  97284. for(i = 0; i < (int)data_len; i++) {
  97285. sum = 0;
  97286. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97287. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97288. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97289. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97290. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97291. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97292. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97293. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97294. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97295. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97296. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97297. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97298. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97299. }
  97300. }
  97301. else { /* order == 11 */
  97302. for(i = 0; i < (int)data_len; i++) {
  97303. sum = 0;
  97304. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97305. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97306. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97307. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97308. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97309. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97310. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97311. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97312. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97313. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97314. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97315. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97316. }
  97317. }
  97318. }
  97319. else {
  97320. if(order == 10) {
  97321. for(i = 0; i < (int)data_len; i++) {
  97322. sum = 0;
  97323. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97324. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97325. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97326. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97327. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97328. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97329. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97330. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97331. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97332. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97333. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97334. }
  97335. }
  97336. else { /* order == 9 */
  97337. for(i = 0; i < (int)data_len; i++) {
  97338. sum = 0;
  97339. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97340. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97341. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97342. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97343. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97344. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97345. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97346. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97347. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97348. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97349. }
  97350. }
  97351. }
  97352. }
  97353. else if(order > 4) {
  97354. if(order > 6) {
  97355. if(order == 8) {
  97356. for(i = 0; i < (int)data_len; i++) {
  97357. sum = 0;
  97358. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97359. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97360. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97361. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97362. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97363. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97364. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97365. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97366. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97367. }
  97368. }
  97369. else { /* order == 7 */
  97370. for(i = 0; i < (int)data_len; i++) {
  97371. sum = 0;
  97372. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97373. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97374. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97375. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97376. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97377. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97378. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97379. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97380. }
  97381. }
  97382. }
  97383. else {
  97384. if(order == 6) {
  97385. for(i = 0; i < (int)data_len; i++) {
  97386. sum = 0;
  97387. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97388. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97389. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97390. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97391. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97392. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97393. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97394. }
  97395. }
  97396. else { /* order == 5 */
  97397. for(i = 0; i < (int)data_len; i++) {
  97398. sum = 0;
  97399. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97400. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97401. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97402. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97403. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97404. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97405. }
  97406. }
  97407. }
  97408. }
  97409. else {
  97410. if(order > 2) {
  97411. if(order == 4) {
  97412. for(i = 0; i < (int)data_len; i++) {
  97413. sum = 0;
  97414. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97415. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97416. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97417. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97418. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97419. }
  97420. }
  97421. else { /* order == 3 */
  97422. for(i = 0; i < (int)data_len; i++) {
  97423. sum = 0;
  97424. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97425. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97426. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97427. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97428. }
  97429. }
  97430. }
  97431. else {
  97432. if(order == 2) {
  97433. for(i = 0; i < (int)data_len; i++) {
  97434. sum = 0;
  97435. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97436. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97437. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97438. }
  97439. }
  97440. else { /* order == 1 */
  97441. for(i = 0; i < (int)data_len; i++)
  97442. data[i] = residual[i] + (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  97443. }
  97444. }
  97445. }
  97446. }
  97447. else { /* order > 12 */
  97448. for(i = 0; i < (int)data_len; i++) {
  97449. sum = 0;
  97450. switch(order) {
  97451. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  97452. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  97453. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  97454. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  97455. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  97456. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  97457. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  97458. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  97459. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  97460. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  97461. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  97462. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  97463. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  97464. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  97465. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  97466. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  97467. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  97468. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  97469. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  97470. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  97471. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97472. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97473. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  97474. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  97475. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  97476. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  97477. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  97478. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  97479. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  97480. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  97481. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  97482. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  97483. }
  97484. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97485. }
  97486. }
  97487. }
  97488. #endif
  97489. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97490. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples)
  97491. {
  97492. FLAC__double error_scale;
  97493. FLAC__ASSERT(total_samples > 0);
  97494. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  97495. return FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error, error_scale);
  97496. }
  97497. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale)
  97498. {
  97499. if(lpc_error > 0.0) {
  97500. FLAC__double bps = (FLAC__double)0.5 * log(error_scale * lpc_error) / M_LN2;
  97501. if(bps >= 0.0)
  97502. return bps;
  97503. else
  97504. return 0.0;
  97505. }
  97506. else if(lpc_error < 0.0) { /* error should not be negative but can happen due to inadequate floating-point resolution */
  97507. return 1e32;
  97508. }
  97509. else {
  97510. return 0.0;
  97511. }
  97512. }
  97513. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order)
  97514. {
  97515. 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 */
  97516. FLAC__double bits, best_bits, error_scale;
  97517. FLAC__ASSERT(max_order > 0);
  97518. FLAC__ASSERT(total_samples > 0);
  97519. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  97520. best_index = 0;
  97521. best_bits = (unsigned)(-1);
  97522. for(index = 0, order = 1; index < max_order; index++, order++) {
  97523. 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);
  97524. if(bits < best_bits) {
  97525. best_index = index;
  97526. best_bits = bits;
  97527. }
  97528. }
  97529. return best_index+1; /* +1 since index of lpc_error[] is order-1 */
  97530. }
  97531. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97532. #endif
  97533. /*** End of inlined file: lpc_flac.c ***/
  97534. /*** Start of inlined file: md5.c ***/
  97535. /*** Start of inlined file: juce_FlacHeader.h ***/
  97536. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  97537. // tasks..
  97538. #define VERSION "1.2.1"
  97539. #define FLAC__NO_DLL 1
  97540. #if JUCE_MSVC
  97541. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  97542. #endif
  97543. #if JUCE_MAC
  97544. #define FLAC__SYS_DARWIN 1
  97545. #endif
  97546. /*** End of inlined file: juce_FlacHeader.h ***/
  97547. #if JUCE_USE_FLAC
  97548. #if HAVE_CONFIG_H
  97549. # include <config.h>
  97550. #endif
  97551. #include <stdlib.h> /* for malloc() */
  97552. #include <string.h> /* for memcpy() */
  97553. /*** Start of inlined file: md5.h ***/
  97554. #ifndef FLAC__PRIVATE__MD5_H
  97555. #define FLAC__PRIVATE__MD5_H
  97556. /*
  97557. * This is the header file for the MD5 message-digest algorithm.
  97558. * The algorithm is due to Ron Rivest. This code was
  97559. * written by Colin Plumb in 1993, no copyright is claimed.
  97560. * This code is in the public domain; do with it what you wish.
  97561. *
  97562. * Equivalent code is available from RSA Data Security, Inc.
  97563. * This code has been tested against that, and is equivalent,
  97564. * except that you don't need to include two pages of legalese
  97565. * with every copy.
  97566. *
  97567. * To compute the message digest of a chunk of bytes, declare an
  97568. * MD5Context structure, pass it to MD5Init, call MD5Update as
  97569. * needed on buffers full of bytes, and then call MD5Final, which
  97570. * will fill a supplied 16-byte array with the digest.
  97571. *
  97572. * Changed so as no longer to depend on Colin Plumb's `usual.h'
  97573. * header definitions; now uses stuff from dpkg's config.h
  97574. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  97575. * Still in the public domain.
  97576. *
  97577. * Josh Coalson: made some changes to integrate with libFLAC.
  97578. * Still in the public domain, with no warranty.
  97579. */
  97580. typedef struct {
  97581. FLAC__uint32 in[16];
  97582. FLAC__uint32 buf[4];
  97583. FLAC__uint32 bytes[2];
  97584. FLAC__byte *internal_buf;
  97585. size_t capacity;
  97586. } FLAC__MD5Context;
  97587. void FLAC__MD5Init(FLAC__MD5Context *context);
  97588. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *context);
  97589. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample);
  97590. #endif
  97591. /*** End of inlined file: md5.h ***/
  97592. #ifndef FLaC__INLINE
  97593. #define FLaC__INLINE
  97594. #endif
  97595. /*
  97596. * This code implements the MD5 message-digest algorithm.
  97597. * The algorithm is due to Ron Rivest. This code was
  97598. * written by Colin Plumb in 1993, no copyright is claimed.
  97599. * This code is in the public domain; do with it what you wish.
  97600. *
  97601. * Equivalent code is available from RSA Data Security, Inc.
  97602. * This code has been tested against that, and is equivalent,
  97603. * except that you don't need to include two pages of legalese
  97604. * with every copy.
  97605. *
  97606. * To compute the message digest of a chunk of bytes, declare an
  97607. * MD5Context structure, pass it to MD5Init, call MD5Update as
  97608. * needed on buffers full of bytes, and then call MD5Final, which
  97609. * will fill a supplied 16-byte array with the digest.
  97610. *
  97611. * Changed so as no longer to depend on Colin Plumb's `usual.h' header
  97612. * definitions; now uses stuff from dpkg's config.h.
  97613. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  97614. * Still in the public domain.
  97615. *
  97616. * Josh Coalson: made some changes to integrate with libFLAC.
  97617. * Still in the public domain.
  97618. */
  97619. /* The four core functions - F1 is optimized somewhat */
  97620. /* #define F1(x, y, z) (x & y | ~x & z) */
  97621. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  97622. #define F2(x, y, z) F1(z, x, y)
  97623. #define F3(x, y, z) (x ^ y ^ z)
  97624. #define F4(x, y, z) (y ^ (x | ~z))
  97625. /* This is the central step in the MD5 algorithm. */
  97626. #define MD5STEP(f,w,x,y,z,in,s) \
  97627. (w += f(x,y,z) + in, w = (w<<s | w>>(32-s)) + x)
  97628. /*
  97629. * The core of the MD5 algorithm, this alters an existing MD5 hash to
  97630. * reflect the addition of 16 longwords of new data. MD5Update blocks
  97631. * the data and converts bytes into longwords for this routine.
  97632. */
  97633. static void FLAC__MD5Transform(FLAC__uint32 buf[4], FLAC__uint32 const in[16])
  97634. {
  97635. register FLAC__uint32 a, b, c, d;
  97636. a = buf[0];
  97637. b = buf[1];
  97638. c = buf[2];
  97639. d = buf[3];
  97640. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  97641. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  97642. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  97643. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  97644. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  97645. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  97646. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  97647. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  97648. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  97649. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  97650. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  97651. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  97652. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  97653. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  97654. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  97655. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  97656. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  97657. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  97658. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  97659. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  97660. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  97661. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  97662. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  97663. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  97664. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  97665. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  97666. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  97667. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  97668. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  97669. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  97670. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  97671. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  97672. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  97673. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  97674. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  97675. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  97676. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  97677. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  97678. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  97679. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  97680. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  97681. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  97682. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  97683. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  97684. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  97685. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  97686. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  97687. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  97688. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  97689. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  97690. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  97691. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  97692. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  97693. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  97694. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  97695. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  97696. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  97697. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  97698. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  97699. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  97700. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  97701. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  97702. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  97703. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  97704. buf[0] += a;
  97705. buf[1] += b;
  97706. buf[2] += c;
  97707. buf[3] += d;
  97708. }
  97709. #if WORDS_BIGENDIAN
  97710. //@@@@@@ OPT: use bswap/intrinsics
  97711. static void byteSwap(FLAC__uint32 *buf, unsigned words)
  97712. {
  97713. register FLAC__uint32 x;
  97714. do {
  97715. x = *buf;
  97716. x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff);
  97717. *buf++ = (x >> 16) | (x << 16);
  97718. } while (--words);
  97719. }
  97720. static void byteSwapX16(FLAC__uint32 *buf)
  97721. {
  97722. register FLAC__uint32 x;
  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. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97737. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97738. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf = (x >> 16) | (x << 16);
  97739. }
  97740. #else
  97741. #define byteSwap(buf, words)
  97742. #define byteSwapX16(buf)
  97743. #endif
  97744. /*
  97745. * Update context to reflect the concatenation of another buffer full
  97746. * of bytes.
  97747. */
  97748. static void FLAC__MD5Update(FLAC__MD5Context *ctx, FLAC__byte const *buf, unsigned len)
  97749. {
  97750. FLAC__uint32 t;
  97751. /* Update byte count */
  97752. t = ctx->bytes[0];
  97753. if ((ctx->bytes[0] = t + len) < t)
  97754. ctx->bytes[1]++; /* Carry from low to high */
  97755. t = 64 - (t & 0x3f); /* Space available in ctx->in (at least 1) */
  97756. if (t > len) {
  97757. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, len);
  97758. return;
  97759. }
  97760. /* First chunk is an odd size */
  97761. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, t);
  97762. byteSwapX16(ctx->in);
  97763. FLAC__MD5Transform(ctx->buf, ctx->in);
  97764. buf += t;
  97765. len -= t;
  97766. /* Process data in 64-byte chunks */
  97767. while (len >= 64) {
  97768. memcpy(ctx->in, buf, 64);
  97769. byteSwapX16(ctx->in);
  97770. FLAC__MD5Transform(ctx->buf, ctx->in);
  97771. buf += 64;
  97772. len -= 64;
  97773. }
  97774. /* Handle any remaining bytes of data. */
  97775. memcpy(ctx->in, buf, len);
  97776. }
  97777. /*
  97778. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  97779. * initialization constants.
  97780. */
  97781. void FLAC__MD5Init(FLAC__MD5Context *ctx)
  97782. {
  97783. ctx->buf[0] = 0x67452301;
  97784. ctx->buf[1] = 0xefcdab89;
  97785. ctx->buf[2] = 0x98badcfe;
  97786. ctx->buf[3] = 0x10325476;
  97787. ctx->bytes[0] = 0;
  97788. ctx->bytes[1] = 0;
  97789. ctx->internal_buf = 0;
  97790. ctx->capacity = 0;
  97791. }
  97792. /*
  97793. * Final wrapup - pad to 64-byte boundary with the bit pattern
  97794. * 1 0* (64-bit count of bits processed, MSB-first)
  97795. */
  97796. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *ctx)
  97797. {
  97798. int count = ctx->bytes[0] & 0x3f; /* Number of bytes in ctx->in */
  97799. FLAC__byte *p = (FLAC__byte *)ctx->in + count;
  97800. /* Set the first char of padding to 0x80. There is always room. */
  97801. *p++ = 0x80;
  97802. /* Bytes of padding needed to make 56 bytes (-8..55) */
  97803. count = 56 - 1 - count;
  97804. if (count < 0) { /* Padding forces an extra block */
  97805. memset(p, 0, count + 8);
  97806. byteSwapX16(ctx->in);
  97807. FLAC__MD5Transform(ctx->buf, ctx->in);
  97808. p = (FLAC__byte *)ctx->in;
  97809. count = 56;
  97810. }
  97811. memset(p, 0, count);
  97812. byteSwap(ctx->in, 14);
  97813. /* Append length in bits and transform */
  97814. ctx->in[14] = ctx->bytes[0] << 3;
  97815. ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29;
  97816. FLAC__MD5Transform(ctx->buf, ctx->in);
  97817. byteSwap(ctx->buf, 4);
  97818. memcpy(digest, ctx->buf, 16);
  97819. memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */
  97820. if(0 != ctx->internal_buf) {
  97821. free(ctx->internal_buf);
  97822. ctx->internal_buf = 0;
  97823. ctx->capacity = 0;
  97824. }
  97825. }
  97826. /*
  97827. * Convert the incoming audio signal to a byte stream
  97828. */
  97829. static void format_input_(FLAC__byte *buf, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  97830. {
  97831. unsigned channel, sample;
  97832. register FLAC__int32 a_word;
  97833. register FLAC__byte *buf_ = buf;
  97834. #if WORDS_BIGENDIAN
  97835. #else
  97836. if(channels == 2 && bytes_per_sample == 2) {
  97837. FLAC__int16 *buf1_ = ((FLAC__int16*)buf_) + 1;
  97838. memcpy(buf_, signal[0], sizeof(FLAC__int32) * samples);
  97839. for(sample = 0; sample < samples; sample++, buf1_+=2)
  97840. *buf1_ = (FLAC__int16)signal[1][sample];
  97841. }
  97842. else if(channels == 1 && bytes_per_sample == 2) {
  97843. FLAC__int16 *buf1_ = (FLAC__int16*)buf_;
  97844. for(sample = 0; sample < samples; sample++)
  97845. *buf1_++ = (FLAC__int16)signal[0][sample];
  97846. }
  97847. else
  97848. #endif
  97849. if(bytes_per_sample == 2) {
  97850. if(channels == 2) {
  97851. for(sample = 0; sample < samples; sample++) {
  97852. a_word = signal[0][sample];
  97853. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97854. *buf_++ = (FLAC__byte)a_word;
  97855. a_word = signal[1][sample];
  97856. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97857. *buf_++ = (FLAC__byte)a_word;
  97858. }
  97859. }
  97860. else if(channels == 1) {
  97861. for(sample = 0; sample < samples; sample++) {
  97862. a_word = signal[0][sample];
  97863. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97864. *buf_++ = (FLAC__byte)a_word;
  97865. }
  97866. }
  97867. else {
  97868. for(sample = 0; sample < samples; sample++) {
  97869. for(channel = 0; channel < channels; channel++) {
  97870. a_word = signal[channel][sample];
  97871. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97872. *buf_++ = (FLAC__byte)a_word;
  97873. }
  97874. }
  97875. }
  97876. }
  97877. else if(bytes_per_sample == 3) {
  97878. if(channels == 2) {
  97879. for(sample = 0; sample < samples; sample++) {
  97880. a_word = signal[0][sample];
  97881. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97882. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97883. *buf_++ = (FLAC__byte)a_word;
  97884. a_word = signal[1][sample];
  97885. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97886. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97887. *buf_++ = (FLAC__byte)a_word;
  97888. }
  97889. }
  97890. else if(channels == 1) {
  97891. for(sample = 0; sample < samples; sample++) {
  97892. a_word = signal[0][sample];
  97893. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97894. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97895. *buf_++ = (FLAC__byte)a_word;
  97896. }
  97897. }
  97898. else {
  97899. for(sample = 0; sample < samples; sample++) {
  97900. for(channel = 0; channel < channels; channel++) {
  97901. a_word = signal[channel][sample];
  97902. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97903. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97904. *buf_++ = (FLAC__byte)a_word;
  97905. }
  97906. }
  97907. }
  97908. }
  97909. else if(bytes_per_sample == 1) {
  97910. if(channels == 2) {
  97911. for(sample = 0; sample < samples; sample++) {
  97912. a_word = signal[0][sample];
  97913. *buf_++ = (FLAC__byte)a_word;
  97914. a_word = signal[1][sample];
  97915. *buf_++ = (FLAC__byte)a_word;
  97916. }
  97917. }
  97918. else if(channels == 1) {
  97919. for(sample = 0; sample < samples; sample++) {
  97920. a_word = signal[0][sample];
  97921. *buf_++ = (FLAC__byte)a_word;
  97922. }
  97923. }
  97924. else {
  97925. for(sample = 0; sample < samples; sample++) {
  97926. for(channel = 0; channel < channels; channel++) {
  97927. a_word = signal[channel][sample];
  97928. *buf_++ = (FLAC__byte)a_word;
  97929. }
  97930. }
  97931. }
  97932. }
  97933. else { /* bytes_per_sample == 4, maybe optimize more later */
  97934. for(sample = 0; sample < samples; sample++) {
  97935. for(channel = 0; channel < channels; channel++) {
  97936. a_word = signal[channel][sample];
  97937. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97938. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97939. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97940. *buf_++ = (FLAC__byte)a_word;
  97941. }
  97942. }
  97943. }
  97944. }
  97945. /*
  97946. * Convert the incoming audio signal to a byte stream and FLAC__MD5Update it.
  97947. */
  97948. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  97949. {
  97950. const size_t bytes_needed = (size_t)channels * (size_t)samples * (size_t)bytes_per_sample;
  97951. /* overflow check */
  97952. if((size_t)channels > SIZE_MAX / (size_t)bytes_per_sample)
  97953. return false;
  97954. if((size_t)channels * (size_t)bytes_per_sample > SIZE_MAX / (size_t)samples)
  97955. return false;
  97956. if(ctx->capacity < bytes_needed) {
  97957. FLAC__byte *tmp = (FLAC__byte*)realloc(ctx->internal_buf, bytes_needed);
  97958. if(0 == tmp) {
  97959. free(ctx->internal_buf);
  97960. if(0 == (ctx->internal_buf = (FLAC__byte*)safe_malloc_(bytes_needed)))
  97961. return false;
  97962. }
  97963. ctx->internal_buf = tmp;
  97964. ctx->capacity = bytes_needed;
  97965. }
  97966. format_input_(ctx->internal_buf, signal, channels, samples, bytes_per_sample);
  97967. FLAC__MD5Update(ctx, ctx->internal_buf, bytes_needed);
  97968. return true;
  97969. }
  97970. #endif
  97971. /*** End of inlined file: md5.c ***/
  97972. /*** Start of inlined file: memory.c ***/
  97973. /*** Start of inlined file: juce_FlacHeader.h ***/
  97974. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  97975. // tasks..
  97976. #define VERSION "1.2.1"
  97977. #define FLAC__NO_DLL 1
  97978. #if JUCE_MSVC
  97979. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  97980. #endif
  97981. #if JUCE_MAC
  97982. #define FLAC__SYS_DARWIN 1
  97983. #endif
  97984. /*** End of inlined file: juce_FlacHeader.h ***/
  97985. #if JUCE_USE_FLAC
  97986. #if HAVE_CONFIG_H
  97987. # include <config.h>
  97988. #endif
  97989. /*** Start of inlined file: memory.h ***/
  97990. #ifndef FLAC__PRIVATE__MEMORY_H
  97991. #define FLAC__PRIVATE__MEMORY_H
  97992. #ifdef HAVE_CONFIG_H
  97993. #include <config.h>
  97994. #endif
  97995. #include <stdlib.h> /* for size_t */
  97996. /* Returns the unaligned address returned by malloc.
  97997. * Use free() on this address to deallocate.
  97998. */
  97999. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address);
  98000. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer);
  98001. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer);
  98002. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer);
  98003. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer);
  98004. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98005. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer);
  98006. #endif
  98007. #endif
  98008. /*** End of inlined file: memory.h ***/
  98009. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address)
  98010. {
  98011. void *x;
  98012. FLAC__ASSERT(0 != aligned_address);
  98013. #ifdef FLAC__ALIGN_MALLOC_DATA
  98014. /* align on 32-byte (256-bit) boundary */
  98015. x = safe_malloc_add_2op_(bytes, /*+*/31);
  98016. #ifdef SIZEOF_VOIDP
  98017. #if SIZEOF_VOIDP == 4
  98018. /* could do *aligned_address = x + ((unsigned) (32 - (((unsigned)x) & 31))) & 31; */
  98019. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  98020. #elif SIZEOF_VOIDP == 8
  98021. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  98022. #else
  98023. # error Unsupported sizeof(void*)
  98024. #endif
  98025. #else
  98026. /* there's got to be a better way to do this right for all archs */
  98027. if(sizeof(void*) == sizeof(unsigned))
  98028. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  98029. else if(sizeof(void*) == sizeof(FLAC__uint64))
  98030. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  98031. else
  98032. return 0;
  98033. #endif
  98034. #else
  98035. x = safe_malloc_(bytes);
  98036. *aligned_address = x;
  98037. #endif
  98038. return x;
  98039. }
  98040. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer)
  98041. {
  98042. FLAC__int32 *pu; /* unaligned pointer */
  98043. union { /* union needed to comply with C99 pointer aliasing rules */
  98044. FLAC__int32 *pa; /* aligned pointer */
  98045. void *pv; /* aligned pointer alias */
  98046. } u;
  98047. FLAC__ASSERT(elements > 0);
  98048. FLAC__ASSERT(0 != unaligned_pointer);
  98049. FLAC__ASSERT(0 != aligned_pointer);
  98050. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98051. pu = (FLAC__int32*)FLAC__memory_alloc_aligned(sizeof(*pu) * (size_t)elements, &u.pv);
  98052. if(0 == pu) {
  98053. return false;
  98054. }
  98055. else {
  98056. if(*unaligned_pointer != 0)
  98057. free(*unaligned_pointer);
  98058. *unaligned_pointer = pu;
  98059. *aligned_pointer = u.pa;
  98060. return true;
  98061. }
  98062. }
  98063. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer)
  98064. {
  98065. FLAC__uint32 *pu; /* unaligned pointer */
  98066. union { /* union needed to comply with C99 pointer aliasing rules */
  98067. FLAC__uint32 *pa; /* aligned pointer */
  98068. void *pv; /* aligned pointer alias */
  98069. } u;
  98070. FLAC__ASSERT(elements > 0);
  98071. FLAC__ASSERT(0 != unaligned_pointer);
  98072. FLAC__ASSERT(0 != aligned_pointer);
  98073. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98074. pu = (FLAC__uint32*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98075. if(0 == pu) {
  98076. return false;
  98077. }
  98078. else {
  98079. if(*unaligned_pointer != 0)
  98080. free(*unaligned_pointer);
  98081. *unaligned_pointer = pu;
  98082. *aligned_pointer = u.pa;
  98083. return true;
  98084. }
  98085. }
  98086. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer)
  98087. {
  98088. FLAC__uint64 *pu; /* unaligned pointer */
  98089. union { /* union needed to comply with C99 pointer aliasing rules */
  98090. FLAC__uint64 *pa; /* aligned pointer */
  98091. void *pv; /* aligned pointer alias */
  98092. } u;
  98093. FLAC__ASSERT(elements > 0);
  98094. FLAC__ASSERT(0 != unaligned_pointer);
  98095. FLAC__ASSERT(0 != aligned_pointer);
  98096. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98097. pu = (FLAC__uint64*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98098. if(0 == pu) {
  98099. return false;
  98100. }
  98101. else {
  98102. if(*unaligned_pointer != 0)
  98103. free(*unaligned_pointer);
  98104. *unaligned_pointer = pu;
  98105. *aligned_pointer = u.pa;
  98106. return true;
  98107. }
  98108. }
  98109. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer)
  98110. {
  98111. unsigned *pu; /* unaligned pointer */
  98112. union { /* union needed to comply with C99 pointer aliasing rules */
  98113. unsigned *pa; /* aligned pointer */
  98114. void *pv; /* aligned pointer alias */
  98115. } u;
  98116. FLAC__ASSERT(elements > 0);
  98117. FLAC__ASSERT(0 != unaligned_pointer);
  98118. FLAC__ASSERT(0 != aligned_pointer);
  98119. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98120. pu = (unsigned*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98121. if(0 == pu) {
  98122. return false;
  98123. }
  98124. else {
  98125. if(*unaligned_pointer != 0)
  98126. free(*unaligned_pointer);
  98127. *unaligned_pointer = pu;
  98128. *aligned_pointer = u.pa;
  98129. return true;
  98130. }
  98131. }
  98132. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98133. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer)
  98134. {
  98135. FLAC__real *pu; /* unaligned pointer */
  98136. union { /* union needed to comply with C99 pointer aliasing rules */
  98137. FLAC__real *pa; /* aligned pointer */
  98138. void *pv; /* aligned pointer alias */
  98139. } u;
  98140. FLAC__ASSERT(elements > 0);
  98141. FLAC__ASSERT(0 != unaligned_pointer);
  98142. FLAC__ASSERT(0 != aligned_pointer);
  98143. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98144. pu = (FLAC__real*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98145. if(0 == pu) {
  98146. return false;
  98147. }
  98148. else {
  98149. if(*unaligned_pointer != 0)
  98150. free(*unaligned_pointer);
  98151. *unaligned_pointer = pu;
  98152. *aligned_pointer = u.pa;
  98153. return true;
  98154. }
  98155. }
  98156. #endif
  98157. #endif
  98158. /*** End of inlined file: memory.c ***/
  98159. /*** Start of inlined file: stream_decoder.c ***/
  98160. /*** Start of inlined file: juce_FlacHeader.h ***/
  98161. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98162. // tasks..
  98163. #define VERSION "1.2.1"
  98164. #define FLAC__NO_DLL 1
  98165. #if JUCE_MSVC
  98166. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98167. #endif
  98168. #if JUCE_MAC
  98169. #define FLAC__SYS_DARWIN 1
  98170. #endif
  98171. /*** End of inlined file: juce_FlacHeader.h ***/
  98172. #if JUCE_USE_FLAC
  98173. #if HAVE_CONFIG_H
  98174. # include <config.h>
  98175. #endif
  98176. #if defined _MSC_VER || defined __MINGW32__
  98177. #include <io.h> /* for _setmode() */
  98178. #include <fcntl.h> /* for _O_BINARY */
  98179. #endif
  98180. #if defined __CYGWIN__ || defined __EMX__
  98181. #include <io.h> /* for setmode(), O_BINARY */
  98182. #include <fcntl.h> /* for _O_BINARY */
  98183. #endif
  98184. #include <stdio.h>
  98185. #include <stdlib.h> /* for malloc() */
  98186. #include <string.h> /* for memset/memcpy() */
  98187. #include <sys/stat.h> /* for stat() */
  98188. #include <sys/types.h> /* for off_t */
  98189. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  98190. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  98191. #define fseeko fseek
  98192. #define ftello ftell
  98193. #endif
  98194. #endif
  98195. /*** Start of inlined file: stream_decoder.h ***/
  98196. #ifndef FLAC__PROTECTED__STREAM_DECODER_H
  98197. #define FLAC__PROTECTED__STREAM_DECODER_H
  98198. #if FLAC__HAS_OGG
  98199. #include "include/private/ogg_decoder_aspect.h"
  98200. #endif
  98201. typedef struct FLAC__StreamDecoderProtected {
  98202. FLAC__StreamDecoderState state;
  98203. unsigned channels;
  98204. FLAC__ChannelAssignment channel_assignment;
  98205. unsigned bits_per_sample;
  98206. unsigned sample_rate; /* in Hz */
  98207. unsigned blocksize; /* in samples (per channel) */
  98208. FLAC__bool md5_checking; /* if true, generate MD5 signature of decoded data and compare against signature in the STREAMINFO metadata block */
  98209. #if FLAC__HAS_OGG
  98210. FLAC__OggDecoderAspect ogg_decoder_aspect;
  98211. #endif
  98212. } FLAC__StreamDecoderProtected;
  98213. /*
  98214. * return the number of input bytes consumed
  98215. */
  98216. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder);
  98217. #endif
  98218. /*** End of inlined file: stream_decoder.h ***/
  98219. #ifdef max
  98220. #undef max
  98221. #endif
  98222. #define max(a,b) ((a)>(b)?(a):(b))
  98223. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  98224. #ifdef _MSC_VER
  98225. #define FLAC__U64L(x) x
  98226. #else
  98227. #define FLAC__U64L(x) x##LLU
  98228. #endif
  98229. /* technically this should be in an "export.c" but this is convenient enough */
  98230. FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC =
  98231. #if FLAC__HAS_OGG
  98232. 1
  98233. #else
  98234. 0
  98235. #endif
  98236. ;
  98237. /***********************************************************************
  98238. *
  98239. * Private static data
  98240. *
  98241. ***********************************************************************/
  98242. static FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
  98243. /***********************************************************************
  98244. *
  98245. * Private class method prototypes
  98246. *
  98247. ***********************************************************************/
  98248. static void set_defaults_dec(FLAC__StreamDecoder *decoder);
  98249. static FILE *get_binary_stdin_(void);
  98250. static FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
  98251. static FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id);
  98252. static FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder);
  98253. static FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder);
  98254. static FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  98255. static FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  98256. static FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj);
  98257. static FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj);
  98258. static FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj);
  98259. static FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder);
  98260. static FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder);
  98261. static FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode);
  98262. static FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder);
  98263. static FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  98264. static FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  98265. static FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  98266. static FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  98267. static FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  98268. 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);
  98269. static FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder);
  98270. static FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data);
  98271. #if FLAC__HAS_OGG
  98272. static FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes);
  98273. static FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  98274. #endif
  98275. static FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
  98276. static void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status);
  98277. static FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  98278. #if FLAC__HAS_OGG
  98279. static FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  98280. #endif
  98281. static FLAC__StreamDecoderReadStatus file_read_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  98282. static FLAC__StreamDecoderSeekStatus file_seek_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  98283. static FLAC__StreamDecoderTellStatus file_tell_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  98284. static FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  98285. static FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data);
  98286. /***********************************************************************
  98287. *
  98288. * Private class data
  98289. *
  98290. ***********************************************************************/
  98291. typedef struct FLAC__StreamDecoderPrivate {
  98292. #if FLAC__HAS_OGG
  98293. FLAC__bool is_ogg;
  98294. #endif
  98295. FLAC__StreamDecoderReadCallback read_callback;
  98296. FLAC__StreamDecoderSeekCallback seek_callback;
  98297. FLAC__StreamDecoderTellCallback tell_callback;
  98298. FLAC__StreamDecoderLengthCallback length_callback;
  98299. FLAC__StreamDecoderEofCallback eof_callback;
  98300. FLAC__StreamDecoderWriteCallback write_callback;
  98301. FLAC__StreamDecoderMetadataCallback metadata_callback;
  98302. FLAC__StreamDecoderErrorCallback error_callback;
  98303. /* generic 32-bit datapath: */
  98304. 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[]);
  98305. /* generic 64-bit datapath: */
  98306. 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[]);
  98307. /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit): */
  98308. 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[]);
  98309. /* 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: */
  98310. 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[]);
  98311. FLAC__bool (*local_bitreader_read_rice_signed_block)(FLAC__BitReader *br, int* vals, unsigned nvals, unsigned parameter);
  98312. void *client_data;
  98313. FILE *file; /* only used if FLAC__stream_decoder_init_file()/FLAC__stream_decoder_init_file() called, else NULL */
  98314. FLAC__BitReader *input;
  98315. FLAC__int32 *output[FLAC__MAX_CHANNELS];
  98316. FLAC__int32 *residual[FLAC__MAX_CHANNELS]; /* WATCHOUT: these are the aligned pointers; the real pointers that should be free()'d are residual_unaligned[] below */
  98317. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents[FLAC__MAX_CHANNELS];
  98318. unsigned output_capacity, output_channels;
  98319. FLAC__uint32 fixed_block_size, next_fixed_block_size;
  98320. FLAC__uint64 samples_decoded;
  98321. FLAC__bool has_stream_info, has_seek_table;
  98322. FLAC__StreamMetadata stream_info;
  98323. FLAC__StreamMetadata seek_table;
  98324. FLAC__bool metadata_filter[128]; /* MAGIC number 128 == total number of metadata block types == 1 << 7 */
  98325. FLAC__byte *metadata_filter_ids;
  98326. size_t metadata_filter_ids_count, metadata_filter_ids_capacity; /* units for both are IDs, not bytes */
  98327. FLAC__Frame frame;
  98328. FLAC__bool cached; /* true if there is a byte in lookahead */
  98329. FLAC__CPUInfo cpuinfo;
  98330. FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */
  98331. FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
  98332. /* unaligned (original) pointers to allocated data */
  98333. FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS];
  98334. 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 */
  98335. FLAC__bool internal_reset_hack; /* used only during init() so we can call reset to set up the decoder without rewinding the input */
  98336. FLAC__bool is_seeking;
  98337. FLAC__MD5Context md5context;
  98338. FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
  98339. /* (the rest of these are only used for seeking) */
  98340. FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
  98341. FLAC__uint64 first_frame_offset; /* hint to the seek routine of where in the stream the first audio frame starts */
  98342. FLAC__uint64 target_sample;
  98343. unsigned unparseable_frame_count; /* used to tell whether we're decoding a future version of FLAC or just got a bad sync */
  98344. #if FLAC__HAS_OGG
  98345. FLAC__bool got_a_frame; /* hack needed in Ogg FLAC seek routine to check when process_single() actually writes a frame */
  98346. #endif
  98347. } FLAC__StreamDecoderPrivate;
  98348. /***********************************************************************
  98349. *
  98350. * Public static class data
  98351. *
  98352. ***********************************************************************/
  98353. FLAC_API const char * const FLAC__StreamDecoderStateString[] = {
  98354. "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
  98355. "FLAC__STREAM_DECODER_READ_METADATA",
  98356. "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
  98357. "FLAC__STREAM_DECODER_READ_FRAME",
  98358. "FLAC__STREAM_DECODER_END_OF_STREAM",
  98359. "FLAC__STREAM_DECODER_OGG_ERROR",
  98360. "FLAC__STREAM_DECODER_SEEK_ERROR",
  98361. "FLAC__STREAM_DECODER_ABORTED",
  98362. "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
  98363. "FLAC__STREAM_DECODER_UNINITIALIZED"
  98364. };
  98365. FLAC_API const char * const FLAC__StreamDecoderInitStatusString[] = {
  98366. "FLAC__STREAM_DECODER_INIT_STATUS_OK",
  98367. "FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  98368. "FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS",
  98369. "FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR",
  98370. "FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE",
  98371. "FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED"
  98372. };
  98373. FLAC_API const char * const FLAC__StreamDecoderReadStatusString[] = {
  98374. "FLAC__STREAM_DECODER_READ_STATUS_CONTINUE",
  98375. "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM",
  98376. "FLAC__STREAM_DECODER_READ_STATUS_ABORT"
  98377. };
  98378. FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[] = {
  98379. "FLAC__STREAM_DECODER_SEEK_STATUS_OK",
  98380. "FLAC__STREAM_DECODER_SEEK_STATUS_ERROR",
  98381. "FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED"
  98382. };
  98383. FLAC_API const char * const FLAC__StreamDecoderTellStatusString[] = {
  98384. "FLAC__STREAM_DECODER_TELL_STATUS_OK",
  98385. "FLAC__STREAM_DECODER_TELL_STATUS_ERROR",
  98386. "FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED"
  98387. };
  98388. FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[] = {
  98389. "FLAC__STREAM_DECODER_LENGTH_STATUS_OK",
  98390. "FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR",
  98391. "FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED"
  98392. };
  98393. FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = {
  98394. "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE",
  98395. "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"
  98396. };
  98397. FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[] = {
  98398. "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC",
  98399. "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER",
  98400. "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH",
  98401. "FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM"
  98402. };
  98403. /***********************************************************************
  98404. *
  98405. * Class constructor/destructor
  98406. *
  98407. ***********************************************************************/
  98408. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void)
  98409. {
  98410. FLAC__StreamDecoder *decoder;
  98411. unsigned i;
  98412. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  98413. decoder = (FLAC__StreamDecoder*)calloc(1, sizeof(FLAC__StreamDecoder));
  98414. if(decoder == 0) {
  98415. return 0;
  98416. }
  98417. decoder->protected_ = (FLAC__StreamDecoderProtected*)calloc(1, sizeof(FLAC__StreamDecoderProtected));
  98418. if(decoder->protected_ == 0) {
  98419. free(decoder);
  98420. return 0;
  98421. }
  98422. decoder->private_ = (FLAC__StreamDecoderPrivate*)calloc(1, sizeof(FLAC__StreamDecoderPrivate));
  98423. if(decoder->private_ == 0) {
  98424. free(decoder->protected_);
  98425. free(decoder);
  98426. return 0;
  98427. }
  98428. decoder->private_->input = FLAC__bitreader_new();
  98429. if(decoder->private_->input == 0) {
  98430. free(decoder->private_);
  98431. free(decoder->protected_);
  98432. free(decoder);
  98433. return 0;
  98434. }
  98435. decoder->private_->metadata_filter_ids_capacity = 16;
  98436. if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)malloc((FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) * decoder->private_->metadata_filter_ids_capacity))) {
  98437. FLAC__bitreader_delete(decoder->private_->input);
  98438. free(decoder->private_);
  98439. free(decoder->protected_);
  98440. free(decoder);
  98441. return 0;
  98442. }
  98443. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  98444. decoder->private_->output[i] = 0;
  98445. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  98446. }
  98447. decoder->private_->output_capacity = 0;
  98448. decoder->private_->output_channels = 0;
  98449. decoder->private_->has_seek_table = false;
  98450. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  98451. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&decoder->private_->partitioned_rice_contents[i]);
  98452. decoder->private_->file = 0;
  98453. set_defaults_dec(decoder);
  98454. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  98455. return decoder;
  98456. }
  98457. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder)
  98458. {
  98459. unsigned i;
  98460. FLAC__ASSERT(0 != decoder);
  98461. FLAC__ASSERT(0 != decoder->protected_);
  98462. FLAC__ASSERT(0 != decoder->private_);
  98463. FLAC__ASSERT(0 != decoder->private_->input);
  98464. (void)FLAC__stream_decoder_finish(decoder);
  98465. if(0 != decoder->private_->metadata_filter_ids)
  98466. free(decoder->private_->metadata_filter_ids);
  98467. FLAC__bitreader_delete(decoder->private_->input);
  98468. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  98469. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]);
  98470. free(decoder->private_);
  98471. free(decoder->protected_);
  98472. free(decoder);
  98473. }
  98474. /***********************************************************************
  98475. *
  98476. * Public class methods
  98477. *
  98478. ***********************************************************************/
  98479. static FLAC__StreamDecoderInitStatus init_stream_internal_dec(
  98480. FLAC__StreamDecoder *decoder,
  98481. FLAC__StreamDecoderReadCallback read_callback,
  98482. FLAC__StreamDecoderSeekCallback seek_callback,
  98483. FLAC__StreamDecoderTellCallback tell_callback,
  98484. FLAC__StreamDecoderLengthCallback length_callback,
  98485. FLAC__StreamDecoderEofCallback eof_callback,
  98486. FLAC__StreamDecoderWriteCallback write_callback,
  98487. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98488. FLAC__StreamDecoderErrorCallback error_callback,
  98489. void *client_data,
  98490. FLAC__bool is_ogg
  98491. )
  98492. {
  98493. FLAC__ASSERT(0 != decoder);
  98494. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  98495. return FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
  98496. #if !FLAC__HAS_OGG
  98497. if(is_ogg)
  98498. return FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  98499. #endif
  98500. if(
  98501. 0 == read_callback ||
  98502. 0 == write_callback ||
  98503. 0 == error_callback ||
  98504. (seek_callback && (0 == tell_callback || 0 == length_callback || 0 == eof_callback))
  98505. )
  98506. return FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
  98507. #if FLAC__HAS_OGG
  98508. decoder->private_->is_ogg = is_ogg;
  98509. if(is_ogg && !FLAC__ogg_decoder_aspect_init(&decoder->protected_->ogg_decoder_aspect))
  98510. return decoder->protected_->state = FLAC__STREAM_DECODER_OGG_ERROR;
  98511. #endif
  98512. /*
  98513. * get the CPU info and set the function pointers
  98514. */
  98515. FLAC__cpu_info(&decoder->private_->cpuinfo);
  98516. /* first default to the non-asm routines */
  98517. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal;
  98518. decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide;
  98519. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
  98520. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal;
  98521. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block;
  98522. /* now override with asm where appropriate */
  98523. #ifndef FLAC__NO_ASM
  98524. if(decoder->private_->cpuinfo.use_asm) {
  98525. #ifdef FLAC__CPU_IA32
  98526. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  98527. #ifdef FLAC__HAS_NASM
  98528. #if 1 /*@@@@@@ OPT: not clearly faster, needs more testing */
  98529. if(decoder->private_->cpuinfo.data.ia32.bswap)
  98530. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap;
  98531. #endif
  98532. if(decoder->private_->cpuinfo.data.ia32.mmx) {
  98533. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  98534. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32_mmx;
  98535. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32_mmx;
  98536. }
  98537. else {
  98538. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  98539. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32;
  98540. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32;
  98541. }
  98542. #endif
  98543. #elif defined FLAC__CPU_PPC
  98544. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_PPC);
  98545. if(decoder->private_->cpuinfo.data.ppc.altivec) {
  98546. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ppc_altivec_16;
  98547. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8;
  98548. }
  98549. #endif
  98550. }
  98551. #endif
  98552. /* from here on, errors are fatal */
  98553. if(!FLAC__bitreader_init(decoder->private_->input, decoder->private_->cpuinfo, read_callback_, decoder)) {
  98554. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  98555. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  98556. }
  98557. decoder->private_->read_callback = read_callback;
  98558. decoder->private_->seek_callback = seek_callback;
  98559. decoder->private_->tell_callback = tell_callback;
  98560. decoder->private_->length_callback = length_callback;
  98561. decoder->private_->eof_callback = eof_callback;
  98562. decoder->private_->write_callback = write_callback;
  98563. decoder->private_->metadata_callback = metadata_callback;
  98564. decoder->private_->error_callback = error_callback;
  98565. decoder->private_->client_data = client_data;
  98566. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  98567. decoder->private_->samples_decoded = 0;
  98568. decoder->private_->has_stream_info = false;
  98569. decoder->private_->cached = false;
  98570. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  98571. decoder->private_->is_seeking = false;
  98572. decoder->private_->internal_reset_hack = true; /* so the following reset does not try to rewind the input */
  98573. if(!FLAC__stream_decoder_reset(decoder)) {
  98574. /* above call sets the state for us */
  98575. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  98576. }
  98577. return FLAC__STREAM_DECODER_INIT_STATUS_OK;
  98578. }
  98579. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  98580. FLAC__StreamDecoder *decoder,
  98581. FLAC__StreamDecoderReadCallback read_callback,
  98582. FLAC__StreamDecoderSeekCallback seek_callback,
  98583. FLAC__StreamDecoderTellCallback tell_callback,
  98584. FLAC__StreamDecoderLengthCallback length_callback,
  98585. FLAC__StreamDecoderEofCallback eof_callback,
  98586. FLAC__StreamDecoderWriteCallback write_callback,
  98587. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98588. FLAC__StreamDecoderErrorCallback error_callback,
  98589. void *client_data
  98590. )
  98591. {
  98592. return init_stream_internal_dec(
  98593. decoder,
  98594. read_callback,
  98595. seek_callback,
  98596. tell_callback,
  98597. length_callback,
  98598. eof_callback,
  98599. write_callback,
  98600. metadata_callback,
  98601. error_callback,
  98602. client_data,
  98603. /*is_ogg=*/false
  98604. );
  98605. }
  98606. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  98607. FLAC__StreamDecoder *decoder,
  98608. FLAC__StreamDecoderReadCallback read_callback,
  98609. FLAC__StreamDecoderSeekCallback seek_callback,
  98610. FLAC__StreamDecoderTellCallback tell_callback,
  98611. FLAC__StreamDecoderLengthCallback length_callback,
  98612. FLAC__StreamDecoderEofCallback eof_callback,
  98613. FLAC__StreamDecoderWriteCallback write_callback,
  98614. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98615. FLAC__StreamDecoderErrorCallback error_callback,
  98616. void *client_data
  98617. )
  98618. {
  98619. return init_stream_internal_dec(
  98620. decoder,
  98621. read_callback,
  98622. seek_callback,
  98623. tell_callback,
  98624. length_callback,
  98625. eof_callback,
  98626. write_callback,
  98627. metadata_callback,
  98628. error_callback,
  98629. client_data,
  98630. /*is_ogg=*/true
  98631. );
  98632. }
  98633. static FLAC__StreamDecoderInitStatus init_FILE_internal_(
  98634. FLAC__StreamDecoder *decoder,
  98635. FILE *file,
  98636. FLAC__StreamDecoderWriteCallback write_callback,
  98637. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98638. FLAC__StreamDecoderErrorCallback error_callback,
  98639. void *client_data,
  98640. FLAC__bool is_ogg
  98641. )
  98642. {
  98643. FLAC__ASSERT(0 != decoder);
  98644. FLAC__ASSERT(0 != file);
  98645. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  98646. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  98647. if(0 == write_callback || 0 == error_callback)
  98648. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  98649. /*
  98650. * To make sure that our file does not go unclosed after an error, we
  98651. * must assign the FILE pointer before any further error can occur in
  98652. * this routine.
  98653. */
  98654. if(file == stdin)
  98655. file = get_binary_stdin_(); /* just to be safe */
  98656. decoder->private_->file = file;
  98657. return init_stream_internal_dec(
  98658. decoder,
  98659. file_read_callback_dec,
  98660. decoder->private_->file == stdin? 0: file_seek_callback_dec,
  98661. decoder->private_->file == stdin? 0: file_tell_callback_dec,
  98662. decoder->private_->file == stdin? 0: file_length_callback_,
  98663. file_eof_callback_,
  98664. write_callback,
  98665. metadata_callback,
  98666. error_callback,
  98667. client_data,
  98668. is_ogg
  98669. );
  98670. }
  98671. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  98672. FLAC__StreamDecoder *decoder,
  98673. FILE *file,
  98674. FLAC__StreamDecoderWriteCallback write_callback,
  98675. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98676. FLAC__StreamDecoderErrorCallback error_callback,
  98677. void *client_data
  98678. )
  98679. {
  98680. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  98681. }
  98682. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  98683. FLAC__StreamDecoder *decoder,
  98684. FILE *file,
  98685. FLAC__StreamDecoderWriteCallback write_callback,
  98686. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98687. FLAC__StreamDecoderErrorCallback error_callback,
  98688. void *client_data
  98689. )
  98690. {
  98691. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  98692. }
  98693. static FLAC__StreamDecoderInitStatus init_file_internal_(
  98694. FLAC__StreamDecoder *decoder,
  98695. const char *filename,
  98696. FLAC__StreamDecoderWriteCallback write_callback,
  98697. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98698. FLAC__StreamDecoderErrorCallback error_callback,
  98699. void *client_data,
  98700. FLAC__bool is_ogg
  98701. )
  98702. {
  98703. FILE *file;
  98704. FLAC__ASSERT(0 != decoder);
  98705. /*
  98706. * To make sure that our file does not go unclosed after an error, we
  98707. * have to do the same entrance checks here that are later performed
  98708. * in FLAC__stream_decoder_init_FILE() before the FILE* is assigned.
  98709. */
  98710. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  98711. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  98712. if(0 == write_callback || 0 == error_callback)
  98713. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  98714. file = filename? fopen(filename, "rb") : stdin;
  98715. if(0 == file)
  98716. return FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE;
  98717. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, is_ogg);
  98718. }
  98719. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  98720. FLAC__StreamDecoder *decoder,
  98721. const char *filename,
  98722. FLAC__StreamDecoderWriteCallback write_callback,
  98723. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98724. FLAC__StreamDecoderErrorCallback error_callback,
  98725. void *client_data
  98726. )
  98727. {
  98728. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  98729. }
  98730. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  98731. FLAC__StreamDecoder *decoder,
  98732. const char *filename,
  98733. FLAC__StreamDecoderWriteCallback write_callback,
  98734. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98735. FLAC__StreamDecoderErrorCallback error_callback,
  98736. void *client_data
  98737. )
  98738. {
  98739. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  98740. }
  98741. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
  98742. {
  98743. FLAC__bool md5_failed = false;
  98744. unsigned i;
  98745. FLAC__ASSERT(0 != decoder);
  98746. FLAC__ASSERT(0 != decoder->private_);
  98747. FLAC__ASSERT(0 != decoder->protected_);
  98748. if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
  98749. return true;
  98750. /* see the comment in FLAC__seekable_stream_decoder_reset() as to why we
  98751. * always call FLAC__MD5Final()
  98752. */
  98753. FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context);
  98754. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  98755. free(decoder->private_->seek_table.data.seek_table.points);
  98756. decoder->private_->seek_table.data.seek_table.points = 0;
  98757. decoder->private_->has_seek_table = false;
  98758. }
  98759. FLAC__bitreader_free(decoder->private_->input);
  98760. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  98761. /* WATCHOUT:
  98762. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  98763. * output arrays have a buffer of up to 3 zeroes in front
  98764. * (at negative indices) for alignment purposes; we use 4
  98765. * to keep the data well-aligned.
  98766. */
  98767. if(0 != decoder->private_->output[i]) {
  98768. free(decoder->private_->output[i]-4);
  98769. decoder->private_->output[i] = 0;
  98770. }
  98771. if(0 != decoder->private_->residual_unaligned[i]) {
  98772. free(decoder->private_->residual_unaligned[i]);
  98773. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  98774. }
  98775. }
  98776. decoder->private_->output_capacity = 0;
  98777. decoder->private_->output_channels = 0;
  98778. #if FLAC__HAS_OGG
  98779. if(decoder->private_->is_ogg)
  98780. FLAC__ogg_decoder_aspect_finish(&decoder->protected_->ogg_decoder_aspect);
  98781. #endif
  98782. if(0 != decoder->private_->file) {
  98783. if(decoder->private_->file != stdin)
  98784. fclose(decoder->private_->file);
  98785. decoder->private_->file = 0;
  98786. }
  98787. if(decoder->private_->do_md5_checking) {
  98788. if(memcmp(decoder->private_->stream_info.data.stream_info.md5sum, decoder->private_->computed_md5sum, 16))
  98789. md5_failed = true;
  98790. }
  98791. decoder->private_->is_seeking = false;
  98792. set_defaults_dec(decoder);
  98793. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  98794. return !md5_failed;
  98795. }
  98796. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long value)
  98797. {
  98798. FLAC__ASSERT(0 != decoder);
  98799. FLAC__ASSERT(0 != decoder->private_);
  98800. FLAC__ASSERT(0 != decoder->protected_);
  98801. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  98802. return false;
  98803. #if FLAC__HAS_OGG
  98804. /* can't check decoder->private_->is_ogg since that's not set until init time */
  98805. FLAC__ogg_decoder_aspect_set_serial_number(&decoder->protected_->ogg_decoder_aspect, value);
  98806. return true;
  98807. #else
  98808. (void)value;
  98809. return false;
  98810. #endif
  98811. }
  98812. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value)
  98813. {
  98814. FLAC__ASSERT(0 != decoder);
  98815. FLAC__ASSERT(0 != decoder->protected_);
  98816. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  98817. return false;
  98818. decoder->protected_->md5_checking = value;
  98819. return true;
  98820. }
  98821. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  98822. {
  98823. FLAC__ASSERT(0 != decoder);
  98824. FLAC__ASSERT(0 != decoder->private_);
  98825. FLAC__ASSERT(0 != decoder->protected_);
  98826. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  98827. /* double protection */
  98828. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  98829. return false;
  98830. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  98831. return false;
  98832. decoder->private_->metadata_filter[type] = true;
  98833. if(type == FLAC__METADATA_TYPE_APPLICATION)
  98834. decoder->private_->metadata_filter_ids_count = 0;
  98835. return true;
  98836. }
  98837. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  98838. {
  98839. FLAC__ASSERT(0 != decoder);
  98840. FLAC__ASSERT(0 != decoder->private_);
  98841. FLAC__ASSERT(0 != decoder->protected_);
  98842. FLAC__ASSERT(0 != id);
  98843. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  98844. return false;
  98845. if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  98846. return true;
  98847. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  98848. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  98849. 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))) {
  98850. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  98851. return false;
  98852. }
  98853. decoder->private_->metadata_filter_ids_capacity *= 2;
  98854. }
  98855. 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));
  98856. decoder->private_->metadata_filter_ids_count++;
  98857. return true;
  98858. }
  98859. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder)
  98860. {
  98861. unsigned i;
  98862. FLAC__ASSERT(0 != decoder);
  98863. FLAC__ASSERT(0 != decoder->private_);
  98864. FLAC__ASSERT(0 != decoder->protected_);
  98865. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  98866. return false;
  98867. for(i = 0; i < sizeof(decoder->private_->metadata_filter) / sizeof(decoder->private_->metadata_filter[0]); i++)
  98868. decoder->private_->metadata_filter[i] = true;
  98869. decoder->private_->metadata_filter_ids_count = 0;
  98870. return true;
  98871. }
  98872. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  98873. {
  98874. FLAC__ASSERT(0 != decoder);
  98875. FLAC__ASSERT(0 != decoder->private_);
  98876. FLAC__ASSERT(0 != decoder->protected_);
  98877. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  98878. /* double protection */
  98879. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  98880. return false;
  98881. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  98882. return false;
  98883. decoder->private_->metadata_filter[type] = false;
  98884. if(type == FLAC__METADATA_TYPE_APPLICATION)
  98885. decoder->private_->metadata_filter_ids_count = 0;
  98886. return true;
  98887. }
  98888. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  98889. {
  98890. FLAC__ASSERT(0 != decoder);
  98891. FLAC__ASSERT(0 != decoder->private_);
  98892. FLAC__ASSERT(0 != decoder->protected_);
  98893. FLAC__ASSERT(0 != id);
  98894. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  98895. return false;
  98896. if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  98897. return true;
  98898. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  98899. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  98900. 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))) {
  98901. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  98902. return false;
  98903. }
  98904. decoder->private_->metadata_filter_ids_capacity *= 2;
  98905. }
  98906. 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));
  98907. decoder->private_->metadata_filter_ids_count++;
  98908. return true;
  98909. }
  98910. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder)
  98911. {
  98912. FLAC__ASSERT(0 != decoder);
  98913. FLAC__ASSERT(0 != decoder->private_);
  98914. FLAC__ASSERT(0 != decoder->protected_);
  98915. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  98916. return false;
  98917. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  98918. decoder->private_->metadata_filter_ids_count = 0;
  98919. return true;
  98920. }
  98921. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder)
  98922. {
  98923. FLAC__ASSERT(0 != decoder);
  98924. FLAC__ASSERT(0 != decoder->protected_);
  98925. return decoder->protected_->state;
  98926. }
  98927. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
  98928. {
  98929. return FLAC__StreamDecoderStateString[decoder->protected_->state];
  98930. }
  98931. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder)
  98932. {
  98933. FLAC__ASSERT(0 != decoder);
  98934. FLAC__ASSERT(0 != decoder->protected_);
  98935. return decoder->protected_->md5_checking;
  98936. }
  98937. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder)
  98938. {
  98939. FLAC__ASSERT(0 != decoder);
  98940. FLAC__ASSERT(0 != decoder->protected_);
  98941. return decoder->private_->has_stream_info? decoder->private_->stream_info.data.stream_info.total_samples : 0;
  98942. }
  98943. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
  98944. {
  98945. FLAC__ASSERT(0 != decoder);
  98946. FLAC__ASSERT(0 != decoder->protected_);
  98947. return decoder->protected_->channels;
  98948. }
  98949. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
  98950. {
  98951. FLAC__ASSERT(0 != decoder);
  98952. FLAC__ASSERT(0 != decoder->protected_);
  98953. return decoder->protected_->channel_assignment;
  98954. }
  98955. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
  98956. {
  98957. FLAC__ASSERT(0 != decoder);
  98958. FLAC__ASSERT(0 != decoder->protected_);
  98959. return decoder->protected_->bits_per_sample;
  98960. }
  98961. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
  98962. {
  98963. FLAC__ASSERT(0 != decoder);
  98964. FLAC__ASSERT(0 != decoder->protected_);
  98965. return decoder->protected_->sample_rate;
  98966. }
  98967. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
  98968. {
  98969. FLAC__ASSERT(0 != decoder);
  98970. FLAC__ASSERT(0 != decoder->protected_);
  98971. return decoder->protected_->blocksize;
  98972. }
  98973. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position)
  98974. {
  98975. FLAC__ASSERT(0 != decoder);
  98976. FLAC__ASSERT(0 != decoder->private_);
  98977. FLAC__ASSERT(0 != position);
  98978. #if FLAC__HAS_OGG
  98979. if(decoder->private_->is_ogg)
  98980. return false;
  98981. #endif
  98982. if(0 == decoder->private_->tell_callback)
  98983. return false;
  98984. if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK)
  98985. return false;
  98986. /* should never happen since all FLAC frames and metadata blocks are byte aligned, but check just in case */
  98987. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input))
  98988. return false;
  98989. FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder));
  98990. *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
  98991. return true;
  98992. }
  98993. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
  98994. {
  98995. FLAC__ASSERT(0 != decoder);
  98996. FLAC__ASSERT(0 != decoder->private_);
  98997. FLAC__ASSERT(0 != decoder->protected_);
  98998. decoder->private_->samples_decoded = 0;
  98999. decoder->private_->do_md5_checking = false;
  99000. #if FLAC__HAS_OGG
  99001. if(decoder->private_->is_ogg)
  99002. FLAC__ogg_decoder_aspect_flush(&decoder->protected_->ogg_decoder_aspect);
  99003. #endif
  99004. if(!FLAC__bitreader_clear(decoder->private_->input)) {
  99005. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99006. return false;
  99007. }
  99008. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  99009. return true;
  99010. }
  99011. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
  99012. {
  99013. FLAC__ASSERT(0 != decoder);
  99014. FLAC__ASSERT(0 != decoder->private_);
  99015. FLAC__ASSERT(0 != decoder->protected_);
  99016. if(!FLAC__stream_decoder_flush(decoder)) {
  99017. /* above call sets the state for us */
  99018. return false;
  99019. }
  99020. #if FLAC__HAS_OGG
  99021. /*@@@ could go in !internal_reset_hack block below */
  99022. if(decoder->private_->is_ogg)
  99023. FLAC__ogg_decoder_aspect_reset(&decoder->protected_->ogg_decoder_aspect);
  99024. #endif
  99025. /* Rewind if necessary. If FLAC__stream_decoder_init() is calling us,
  99026. * (internal_reset_hack) don't try to rewind since we are already at
  99027. * the beginning of the stream and don't want to fail if the input is
  99028. * not seekable.
  99029. */
  99030. if(!decoder->private_->internal_reset_hack) {
  99031. if(decoder->private_->file == stdin)
  99032. return false; /* can't rewind stdin, reset fails */
  99033. if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR)
  99034. return false; /* seekable and seek fails, reset fails */
  99035. }
  99036. else
  99037. decoder->private_->internal_reset_hack = false;
  99038. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
  99039. decoder->private_->has_stream_info = false;
  99040. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  99041. free(decoder->private_->seek_table.data.seek_table.points);
  99042. decoder->private_->seek_table.data.seek_table.points = 0;
  99043. decoder->private_->has_seek_table = false;
  99044. }
  99045. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  99046. /*
  99047. * This goes in reset() and not flush() because according to the spec, a
  99048. * fixed-blocksize stream must stay that way through the whole stream.
  99049. */
  99050. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  99051. /* We initialize the FLAC__MD5Context even though we may never use it. This
  99052. * is because md5 checking may be turned on to start and then turned off if
  99053. * a seek occurs. So we init the context here and finalize it in
  99054. * FLAC__stream_decoder_finish() to make sure things are always cleaned up
  99055. * properly.
  99056. */
  99057. FLAC__MD5Init(&decoder->private_->md5context);
  99058. decoder->private_->first_frame_offset = 0;
  99059. decoder->private_->unparseable_frame_count = 0;
  99060. return true;
  99061. }
  99062. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
  99063. {
  99064. FLAC__bool got_a_frame;
  99065. FLAC__ASSERT(0 != decoder);
  99066. FLAC__ASSERT(0 != decoder->protected_);
  99067. while(1) {
  99068. switch(decoder->protected_->state) {
  99069. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99070. if(!find_metadata_(decoder))
  99071. return false; /* above function sets the status for us */
  99072. break;
  99073. case FLAC__STREAM_DECODER_READ_METADATA:
  99074. if(!read_metadata_(decoder))
  99075. return false; /* above function sets the status for us */
  99076. else
  99077. return true;
  99078. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99079. if(!frame_sync_(decoder))
  99080. return true; /* above function sets the status for us */
  99081. break;
  99082. case FLAC__STREAM_DECODER_READ_FRAME:
  99083. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true))
  99084. return false; /* above function sets the status for us */
  99085. if(got_a_frame)
  99086. return true; /* above function sets the status for us */
  99087. break;
  99088. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99089. case FLAC__STREAM_DECODER_ABORTED:
  99090. return true;
  99091. default:
  99092. FLAC__ASSERT(0);
  99093. return false;
  99094. }
  99095. }
  99096. }
  99097. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
  99098. {
  99099. FLAC__ASSERT(0 != decoder);
  99100. FLAC__ASSERT(0 != decoder->protected_);
  99101. while(1) {
  99102. switch(decoder->protected_->state) {
  99103. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99104. if(!find_metadata_(decoder))
  99105. return false; /* above function sets the status for us */
  99106. break;
  99107. case FLAC__STREAM_DECODER_READ_METADATA:
  99108. if(!read_metadata_(decoder))
  99109. return false; /* above function sets the status for us */
  99110. break;
  99111. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99112. case FLAC__STREAM_DECODER_READ_FRAME:
  99113. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99114. case FLAC__STREAM_DECODER_ABORTED:
  99115. return true;
  99116. default:
  99117. FLAC__ASSERT(0);
  99118. return false;
  99119. }
  99120. }
  99121. }
  99122. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
  99123. {
  99124. FLAC__bool dummy;
  99125. FLAC__ASSERT(0 != decoder);
  99126. FLAC__ASSERT(0 != decoder->protected_);
  99127. while(1) {
  99128. switch(decoder->protected_->state) {
  99129. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99130. if(!find_metadata_(decoder))
  99131. return false; /* above function sets the status for us */
  99132. break;
  99133. case FLAC__STREAM_DECODER_READ_METADATA:
  99134. if(!read_metadata_(decoder))
  99135. return false; /* above function sets the status for us */
  99136. break;
  99137. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99138. if(!frame_sync_(decoder))
  99139. return true; /* above function sets the status for us */
  99140. break;
  99141. case FLAC__STREAM_DECODER_READ_FRAME:
  99142. if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true))
  99143. return false; /* above function sets the status for us */
  99144. break;
  99145. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99146. case FLAC__STREAM_DECODER_ABORTED:
  99147. return true;
  99148. default:
  99149. FLAC__ASSERT(0);
  99150. return false;
  99151. }
  99152. }
  99153. }
  99154. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
  99155. {
  99156. FLAC__bool got_a_frame;
  99157. FLAC__ASSERT(0 != decoder);
  99158. FLAC__ASSERT(0 != decoder->protected_);
  99159. while(1) {
  99160. switch(decoder->protected_->state) {
  99161. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99162. case FLAC__STREAM_DECODER_READ_METADATA:
  99163. return false; /* above function sets the status for us */
  99164. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99165. if(!frame_sync_(decoder))
  99166. return true; /* above function sets the status for us */
  99167. break;
  99168. case FLAC__STREAM_DECODER_READ_FRAME:
  99169. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false))
  99170. return false; /* above function sets the status for us */
  99171. if(got_a_frame)
  99172. return true; /* above function sets the status for us */
  99173. break;
  99174. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99175. case FLAC__STREAM_DECODER_ABORTED:
  99176. return true;
  99177. default:
  99178. FLAC__ASSERT(0);
  99179. return false;
  99180. }
  99181. }
  99182. }
  99183. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample)
  99184. {
  99185. FLAC__uint64 length;
  99186. FLAC__ASSERT(0 != decoder);
  99187. if(
  99188. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA &&
  99189. decoder->protected_->state != FLAC__STREAM_DECODER_READ_METADATA &&
  99190. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC &&
  99191. decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME &&
  99192. decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM
  99193. )
  99194. return false;
  99195. if(0 == decoder->private_->seek_callback)
  99196. return false;
  99197. FLAC__ASSERT(decoder->private_->seek_callback);
  99198. FLAC__ASSERT(decoder->private_->tell_callback);
  99199. FLAC__ASSERT(decoder->private_->length_callback);
  99200. FLAC__ASSERT(decoder->private_->eof_callback);
  99201. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder))
  99202. return false;
  99203. decoder->private_->is_seeking = true;
  99204. /* turn off md5 checking if a seek is attempted */
  99205. decoder->private_->do_md5_checking = false;
  99206. /* 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) */
  99207. if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__STREAM_DECODER_LENGTH_STATUS_OK) {
  99208. decoder->private_->is_seeking = false;
  99209. return false;
  99210. }
  99211. /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */
  99212. if(
  99213. decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA ||
  99214. decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA
  99215. ) {
  99216. if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) {
  99217. /* above call sets the state for us */
  99218. decoder->private_->is_seeking = false;
  99219. return false;
  99220. }
  99221. /* check this again in case we didn't know total_samples the first time */
  99222. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) {
  99223. decoder->private_->is_seeking = false;
  99224. return false;
  99225. }
  99226. }
  99227. {
  99228. const FLAC__bool ok =
  99229. #if FLAC__HAS_OGG
  99230. decoder->private_->is_ogg?
  99231. seek_to_absolute_sample_ogg_(decoder, length, sample) :
  99232. #endif
  99233. seek_to_absolute_sample_(decoder, length, sample)
  99234. ;
  99235. decoder->private_->is_seeking = false;
  99236. return ok;
  99237. }
  99238. }
  99239. /***********************************************************************
  99240. *
  99241. * Protected class methods
  99242. *
  99243. ***********************************************************************/
  99244. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
  99245. {
  99246. FLAC__ASSERT(0 != decoder);
  99247. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99248. FLAC__ASSERT(!(FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) & 7));
  99249. return FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) / 8;
  99250. }
  99251. /***********************************************************************
  99252. *
  99253. * Private class methods
  99254. *
  99255. ***********************************************************************/
  99256. void set_defaults_dec(FLAC__StreamDecoder *decoder)
  99257. {
  99258. #if FLAC__HAS_OGG
  99259. decoder->private_->is_ogg = false;
  99260. #endif
  99261. decoder->private_->read_callback = 0;
  99262. decoder->private_->seek_callback = 0;
  99263. decoder->private_->tell_callback = 0;
  99264. decoder->private_->length_callback = 0;
  99265. decoder->private_->eof_callback = 0;
  99266. decoder->private_->write_callback = 0;
  99267. decoder->private_->metadata_callback = 0;
  99268. decoder->private_->error_callback = 0;
  99269. decoder->private_->client_data = 0;
  99270. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  99271. decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
  99272. decoder->private_->metadata_filter_ids_count = 0;
  99273. decoder->protected_->md5_checking = false;
  99274. #if FLAC__HAS_OGG
  99275. FLAC__ogg_decoder_aspect_set_defaults(&decoder->protected_->ogg_decoder_aspect);
  99276. #endif
  99277. }
  99278. /*
  99279. * This will forcibly set stdin to binary mode (for OSes that require it)
  99280. */
  99281. FILE *get_binary_stdin_(void)
  99282. {
  99283. /* if something breaks here it is probably due to the presence or
  99284. * absence of an underscore before the identifiers 'setmode',
  99285. * 'fileno', and/or 'O_BINARY'; check your system header files.
  99286. */
  99287. #if defined _MSC_VER || defined __MINGW32__
  99288. _setmode(_fileno(stdin), _O_BINARY);
  99289. #elif defined __CYGWIN__
  99290. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  99291. setmode(_fileno(stdin), _O_BINARY);
  99292. #elif defined __EMX__
  99293. setmode(fileno(stdin), O_BINARY);
  99294. #endif
  99295. return stdin;
  99296. }
  99297. FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
  99298. {
  99299. unsigned i;
  99300. FLAC__int32 *tmp;
  99301. if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
  99302. return true;
  99303. /* simply using realloc() is not practical because the number of channels may change mid-stream */
  99304. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99305. if(0 != decoder->private_->output[i]) {
  99306. free(decoder->private_->output[i]-4);
  99307. decoder->private_->output[i] = 0;
  99308. }
  99309. if(0 != decoder->private_->residual_unaligned[i]) {
  99310. free(decoder->private_->residual_unaligned[i]);
  99311. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99312. }
  99313. }
  99314. for(i = 0; i < channels; i++) {
  99315. /* WATCHOUT:
  99316. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  99317. * output arrays have a buffer of up to 3 zeroes in front
  99318. * (at negative indices) for alignment purposes; we use 4
  99319. * to keep the data well-aligned.
  99320. */
  99321. tmp = (FLAC__int32*)safe_malloc_muladd2_(sizeof(FLAC__int32), /*times (*/size, /*+*/4/*)*/);
  99322. if(tmp == 0) {
  99323. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99324. return false;
  99325. }
  99326. memset(tmp, 0, sizeof(FLAC__int32)*4);
  99327. decoder->private_->output[i] = tmp + 4;
  99328. /* WATCHOUT:
  99329. * minimum of quadword alignment for PPC vector optimizations is REQUIRED:
  99330. */
  99331. if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) {
  99332. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99333. return false;
  99334. }
  99335. }
  99336. decoder->private_->output_capacity = size;
  99337. decoder->private_->output_channels = channels;
  99338. return true;
  99339. }
  99340. FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
  99341. {
  99342. size_t i;
  99343. FLAC__ASSERT(0 != decoder);
  99344. FLAC__ASSERT(0 != decoder->private_);
  99345. for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
  99346. if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
  99347. return true;
  99348. return false;
  99349. }
  99350. FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
  99351. {
  99352. FLAC__uint32 x;
  99353. unsigned i, id_;
  99354. FLAC__bool first = true;
  99355. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99356. for(i = id_ = 0; i < 4; ) {
  99357. if(decoder->private_->cached) {
  99358. x = (FLAC__uint32)decoder->private_->lookahead;
  99359. decoder->private_->cached = false;
  99360. }
  99361. else {
  99362. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  99363. return false; /* read_callback_ sets the state for us */
  99364. }
  99365. if(x == FLAC__STREAM_SYNC_STRING[i]) {
  99366. first = true;
  99367. i++;
  99368. id_ = 0;
  99369. continue;
  99370. }
  99371. if(x == ID3V2_TAG_[id_]) {
  99372. id_++;
  99373. i = 0;
  99374. if(id_ == 3) {
  99375. if(!skip_id3v2_tag_(decoder))
  99376. return false; /* skip_id3v2_tag_ sets the state for us */
  99377. }
  99378. continue;
  99379. }
  99380. id_ = 0;
  99381. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  99382. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  99383. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  99384. return false; /* read_callback_ sets the state for us */
  99385. /* 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 */
  99386. /* else we have to check if the second byte is the end of a sync code */
  99387. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  99388. decoder->private_->lookahead = (FLAC__byte)x;
  99389. decoder->private_->cached = true;
  99390. }
  99391. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  99392. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  99393. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  99394. return true;
  99395. }
  99396. }
  99397. i = 0;
  99398. if(first) {
  99399. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  99400. first = false;
  99401. }
  99402. }
  99403. decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
  99404. return true;
  99405. }
  99406. FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
  99407. {
  99408. FLAC__bool is_last;
  99409. FLAC__uint32 i, x, type, length;
  99410. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99411. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN))
  99412. return false; /* read_callback_ sets the state for us */
  99413. is_last = x? true : false;
  99414. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN))
  99415. return false; /* read_callback_ sets the state for us */
  99416. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN))
  99417. return false; /* read_callback_ sets the state for us */
  99418. if(type == FLAC__METADATA_TYPE_STREAMINFO) {
  99419. if(!read_metadata_streaminfo_(decoder, is_last, length))
  99420. return false;
  99421. decoder->private_->has_stream_info = true;
  99422. 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))
  99423. decoder->private_->do_md5_checking = false;
  99424. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback)
  99425. decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
  99426. }
  99427. else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
  99428. if(!read_metadata_seektable_(decoder, is_last, length))
  99429. return false;
  99430. decoder->private_->has_seek_table = true;
  99431. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback)
  99432. decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
  99433. }
  99434. else {
  99435. FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
  99436. unsigned real_length = length;
  99437. FLAC__StreamMetadata block;
  99438. block.is_last = is_last;
  99439. block.type = (FLAC__MetadataType)type;
  99440. block.length = length;
  99441. if(type == FLAC__METADATA_TYPE_APPLICATION) {
  99442. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8))
  99443. return false; /* read_callback_ sets the state for us */
  99444. if(real_length < FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) { /* underflow check */
  99445. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;/*@@@@@@ maybe wrong error? need to resync?*/
  99446. return false;
  99447. }
  99448. real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
  99449. if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
  99450. skip_it = !skip_it;
  99451. }
  99452. if(skip_it) {
  99453. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  99454. return false; /* read_callback_ sets the state for us */
  99455. }
  99456. else {
  99457. switch(type) {
  99458. case FLAC__METADATA_TYPE_PADDING:
  99459. /* skip the padding bytes */
  99460. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  99461. return false; /* read_callback_ sets the state for us */
  99462. break;
  99463. case FLAC__METADATA_TYPE_APPLICATION:
  99464. /* remember, we read the ID already */
  99465. if(real_length > 0) {
  99466. if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
  99467. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99468. return false;
  99469. }
  99470. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length))
  99471. return false; /* read_callback_ sets the state for us */
  99472. }
  99473. else
  99474. block.data.application.data = 0;
  99475. break;
  99476. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  99477. if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
  99478. return false;
  99479. break;
  99480. case FLAC__METADATA_TYPE_CUESHEET:
  99481. if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
  99482. return false;
  99483. break;
  99484. case FLAC__METADATA_TYPE_PICTURE:
  99485. if(!read_metadata_picture_(decoder, &block.data.picture))
  99486. return false;
  99487. break;
  99488. case FLAC__METADATA_TYPE_STREAMINFO:
  99489. case FLAC__METADATA_TYPE_SEEKTABLE:
  99490. FLAC__ASSERT(0);
  99491. break;
  99492. default:
  99493. if(real_length > 0) {
  99494. if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
  99495. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99496. return false;
  99497. }
  99498. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length))
  99499. return false; /* read_callback_ sets the state for us */
  99500. }
  99501. else
  99502. block.data.unknown.data = 0;
  99503. break;
  99504. }
  99505. if(!decoder->private_->is_seeking && decoder->private_->metadata_callback)
  99506. decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
  99507. /* now we have to free any malloc()ed data in the block */
  99508. switch(type) {
  99509. case FLAC__METADATA_TYPE_PADDING:
  99510. break;
  99511. case FLAC__METADATA_TYPE_APPLICATION:
  99512. if(0 != block.data.application.data)
  99513. free(block.data.application.data);
  99514. break;
  99515. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  99516. if(0 != block.data.vorbis_comment.vendor_string.entry)
  99517. free(block.data.vorbis_comment.vendor_string.entry);
  99518. if(block.data.vorbis_comment.num_comments > 0)
  99519. for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
  99520. if(0 != block.data.vorbis_comment.comments[i].entry)
  99521. free(block.data.vorbis_comment.comments[i].entry);
  99522. if(0 != block.data.vorbis_comment.comments)
  99523. free(block.data.vorbis_comment.comments);
  99524. break;
  99525. case FLAC__METADATA_TYPE_CUESHEET:
  99526. if(block.data.cue_sheet.num_tracks > 0)
  99527. for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
  99528. if(0 != block.data.cue_sheet.tracks[i].indices)
  99529. free(block.data.cue_sheet.tracks[i].indices);
  99530. if(0 != block.data.cue_sheet.tracks)
  99531. free(block.data.cue_sheet.tracks);
  99532. break;
  99533. case FLAC__METADATA_TYPE_PICTURE:
  99534. if(0 != block.data.picture.mime_type)
  99535. free(block.data.picture.mime_type);
  99536. if(0 != block.data.picture.description)
  99537. free(block.data.picture.description);
  99538. if(0 != block.data.picture.data)
  99539. free(block.data.picture.data);
  99540. break;
  99541. case FLAC__METADATA_TYPE_STREAMINFO:
  99542. case FLAC__METADATA_TYPE_SEEKTABLE:
  99543. FLAC__ASSERT(0);
  99544. default:
  99545. if(0 != block.data.unknown.data)
  99546. free(block.data.unknown.data);
  99547. break;
  99548. }
  99549. }
  99550. }
  99551. if(is_last) {
  99552. /* if this fails, it's OK, it's just a hint for the seek routine */
  99553. if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset))
  99554. decoder->private_->first_frame_offset = 0;
  99555. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  99556. }
  99557. return true;
  99558. }
  99559. FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  99560. {
  99561. FLAC__uint32 x;
  99562. unsigned bits, used_bits = 0;
  99563. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99564. decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
  99565. decoder->private_->stream_info.is_last = is_last;
  99566. decoder->private_->stream_info.length = length;
  99567. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
  99568. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, bits))
  99569. return false; /* read_callback_ sets the state for us */
  99570. decoder->private_->stream_info.data.stream_info.min_blocksize = x;
  99571. used_bits += bits;
  99572. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
  99573. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  99574. return false; /* read_callback_ sets the state for us */
  99575. decoder->private_->stream_info.data.stream_info.max_blocksize = x;
  99576. used_bits += bits;
  99577. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
  99578. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  99579. return false; /* read_callback_ sets the state for us */
  99580. decoder->private_->stream_info.data.stream_info.min_framesize = x;
  99581. used_bits += bits;
  99582. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
  99583. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  99584. return false; /* read_callback_ sets the state for us */
  99585. decoder->private_->stream_info.data.stream_info.max_framesize = x;
  99586. used_bits += bits;
  99587. bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
  99588. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  99589. return false; /* read_callback_ sets the state for us */
  99590. decoder->private_->stream_info.data.stream_info.sample_rate = x;
  99591. used_bits += bits;
  99592. bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
  99593. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  99594. return false; /* read_callback_ sets the state for us */
  99595. decoder->private_->stream_info.data.stream_info.channels = x+1;
  99596. used_bits += bits;
  99597. bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
  99598. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  99599. return false; /* read_callback_ sets the state for us */
  99600. decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
  99601. used_bits += bits;
  99602. bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
  99603. 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))
  99604. return false; /* read_callback_ sets the state for us */
  99605. used_bits += bits;
  99606. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16))
  99607. return false; /* read_callback_ sets the state for us */
  99608. used_bits += 16*8;
  99609. /* skip the rest of the block */
  99610. FLAC__ASSERT(used_bits % 8 == 0);
  99611. length -= (used_bits / 8);
  99612. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  99613. return false; /* read_callback_ sets the state for us */
  99614. return true;
  99615. }
  99616. FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  99617. {
  99618. FLAC__uint32 i, x;
  99619. FLAC__uint64 xx;
  99620. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99621. decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
  99622. decoder->private_->seek_table.is_last = is_last;
  99623. decoder->private_->seek_table.length = length;
  99624. decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
  99625. /* use realloc since we may pass through here several times (e.g. after seeking) */
  99626. 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)))) {
  99627. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99628. return false;
  99629. }
  99630. for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
  99631. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  99632. return false; /* read_callback_ sets the state for us */
  99633. decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
  99634. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  99635. return false; /* read_callback_ sets the state for us */
  99636. decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
  99637. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  99638. return false; /* read_callback_ sets the state for us */
  99639. decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
  99640. }
  99641. length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
  99642. /* if there is a partial point left, skip over it */
  99643. if(length > 0) {
  99644. /*@@@ do a send_error_to_client_() here? there's an argument for either way */
  99645. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  99646. return false; /* read_callback_ sets the state for us */
  99647. }
  99648. return true;
  99649. }
  99650. FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
  99651. {
  99652. FLAC__uint32 i;
  99653. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99654. /* read vendor string */
  99655. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  99656. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length))
  99657. return false; /* read_callback_ sets the state for us */
  99658. if(obj->vendor_string.length > 0) {
  99659. if(0 == (obj->vendor_string.entry = (FLAC__byte*)safe_malloc_add_2op_(obj->vendor_string.length, /*+*/1))) {
  99660. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99661. return false;
  99662. }
  99663. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length))
  99664. return false; /* read_callback_ sets the state for us */
  99665. obj->vendor_string.entry[obj->vendor_string.length] = '\0';
  99666. }
  99667. else
  99668. obj->vendor_string.entry = 0;
  99669. /* read num comments */
  99670. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
  99671. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->num_comments))
  99672. return false; /* read_callback_ sets the state for us */
  99673. /* read comments */
  99674. if(obj->num_comments > 0) {
  99675. if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)safe_malloc_mul_2op_(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
  99676. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99677. return false;
  99678. }
  99679. for(i = 0; i < obj->num_comments; i++) {
  99680. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  99681. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->comments[i].length))
  99682. return false; /* read_callback_ sets the state for us */
  99683. if(obj->comments[i].length > 0) {
  99684. if(0 == (obj->comments[i].entry = (FLAC__byte*)safe_malloc_add_2op_(obj->comments[i].length, /*+*/1))) {
  99685. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99686. return false;
  99687. }
  99688. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length))
  99689. return false; /* read_callback_ sets the state for us */
  99690. obj->comments[i].entry[obj->comments[i].length] = '\0';
  99691. }
  99692. else
  99693. obj->comments[i].entry = 0;
  99694. }
  99695. }
  99696. else {
  99697. obj->comments = 0;
  99698. }
  99699. return true;
  99700. }
  99701. FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
  99702. {
  99703. FLAC__uint32 i, j, x;
  99704. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99705. memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
  99706. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  99707. 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))
  99708. return false; /* read_callback_ sets the state for us */
  99709. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  99710. return false; /* read_callback_ sets the state for us */
  99711. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  99712. return false; /* read_callback_ sets the state for us */
  99713. obj->is_cd = x? true : false;
  99714. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  99715. return false; /* read_callback_ sets the state for us */
  99716. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  99717. return false; /* read_callback_ sets the state for us */
  99718. obj->num_tracks = x;
  99719. if(obj->num_tracks > 0) {
  99720. if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)safe_calloc_(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
  99721. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99722. return false;
  99723. }
  99724. for(i = 0; i < obj->num_tracks; i++) {
  99725. FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
  99726. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  99727. return false; /* read_callback_ sets the state for us */
  99728. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  99729. return false; /* read_callback_ sets the state for us */
  99730. track->number = (FLAC__byte)x;
  99731. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  99732. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  99733. return false; /* read_callback_ sets the state for us */
  99734. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  99735. return false; /* read_callback_ sets the state for us */
  99736. track->type = x;
  99737. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  99738. return false; /* read_callback_ sets the state for us */
  99739. track->pre_emphasis = x;
  99740. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  99741. return false; /* read_callback_ sets the state for us */
  99742. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  99743. return false; /* read_callback_ sets the state for us */
  99744. track->num_indices = (FLAC__byte)x;
  99745. if(track->num_indices > 0) {
  99746. if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)safe_calloc_(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
  99747. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99748. return false;
  99749. }
  99750. for(j = 0; j < track->num_indices; j++) {
  99751. FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
  99752. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  99753. return false; /* read_callback_ sets the state for us */
  99754. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  99755. return false; /* read_callback_ sets the state for us */
  99756. index->number = (FLAC__byte)x;
  99757. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  99758. return false; /* read_callback_ sets the state for us */
  99759. }
  99760. }
  99761. }
  99762. }
  99763. return true;
  99764. }
  99765. FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj)
  99766. {
  99767. FLAC__uint32 x;
  99768. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99769. /* read type */
  99770. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  99771. return false; /* read_callback_ sets the state for us */
  99772. obj->type = (FLAC__StreamMetadata_Picture_Type) x;
  99773. /* read MIME type */
  99774. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  99775. return false; /* read_callback_ sets the state for us */
  99776. if(0 == (obj->mime_type = (char*)safe_malloc_add_2op_(x, /*+*/1))) {
  99777. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99778. return false;
  99779. }
  99780. if(x > 0) {
  99781. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->mime_type, x))
  99782. return false; /* read_callback_ sets the state for us */
  99783. }
  99784. obj->mime_type[x] = '\0';
  99785. /* read description */
  99786. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  99787. return false; /* read_callback_ sets the state for us */
  99788. if(0 == (obj->description = (FLAC__byte*)safe_malloc_add_2op_(x, /*+*/1))) {
  99789. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99790. return false;
  99791. }
  99792. if(x > 0) {
  99793. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->description, x))
  99794. return false; /* read_callback_ sets the state for us */
  99795. }
  99796. obj->description[x] = '\0';
  99797. /* read width */
  99798. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  99799. return false; /* read_callback_ sets the state for us */
  99800. /* read height */
  99801. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  99802. return false; /* read_callback_ sets the state for us */
  99803. /* read depth */
  99804. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  99805. return false; /* read_callback_ sets the state for us */
  99806. /* read colors */
  99807. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  99808. return false; /* read_callback_ sets the state for us */
  99809. /* read data */
  99810. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &(obj->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  99811. return false; /* read_callback_ sets the state for us */
  99812. if(0 == (obj->data = (FLAC__byte*)safe_malloc_(obj->data_length))) {
  99813. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99814. return false;
  99815. }
  99816. if(obj->data_length > 0) {
  99817. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->data, obj->data_length))
  99818. return false; /* read_callback_ sets the state for us */
  99819. }
  99820. return true;
  99821. }
  99822. FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
  99823. {
  99824. FLAC__uint32 x;
  99825. unsigned i, skip;
  99826. /* skip the version and flags bytes */
  99827. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 24))
  99828. return false; /* read_callback_ sets the state for us */
  99829. /* get the size (in bytes) to skip */
  99830. skip = 0;
  99831. for(i = 0; i < 4; i++) {
  99832. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  99833. return false; /* read_callback_ sets the state for us */
  99834. skip <<= 7;
  99835. skip |= (x & 0x7f);
  99836. }
  99837. /* skip the rest of the tag */
  99838. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, skip))
  99839. return false; /* read_callback_ sets the state for us */
  99840. return true;
  99841. }
  99842. FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
  99843. {
  99844. FLAC__uint32 x;
  99845. FLAC__bool first = true;
  99846. /* If we know the total number of samples in the stream, stop if we've read that many. */
  99847. /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
  99848. if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
  99849. if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
  99850. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  99851. return true;
  99852. }
  99853. }
  99854. /* make sure we're byte aligned */
  99855. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  99856. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  99857. return false; /* read_callback_ sets the state for us */
  99858. }
  99859. while(1) {
  99860. if(decoder->private_->cached) {
  99861. x = (FLAC__uint32)decoder->private_->lookahead;
  99862. decoder->private_->cached = false;
  99863. }
  99864. else {
  99865. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  99866. return false; /* read_callback_ sets the state for us */
  99867. }
  99868. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  99869. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  99870. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  99871. return false; /* read_callback_ sets the state for us */
  99872. /* 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 */
  99873. /* else we have to check if the second byte is the end of a sync code */
  99874. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  99875. decoder->private_->lookahead = (FLAC__byte)x;
  99876. decoder->private_->cached = true;
  99877. }
  99878. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  99879. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  99880. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  99881. return true;
  99882. }
  99883. }
  99884. if(first) {
  99885. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  99886. first = false;
  99887. }
  99888. }
  99889. return true;
  99890. }
  99891. FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
  99892. {
  99893. unsigned channel;
  99894. unsigned i;
  99895. FLAC__int32 mid, side;
  99896. unsigned frame_crc; /* the one we calculate from the input stream */
  99897. FLAC__uint32 x;
  99898. *got_a_frame = false;
  99899. /* init the CRC */
  99900. frame_crc = 0;
  99901. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
  99902. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
  99903. FLAC__bitreader_reset_read_crc16(decoder->private_->input, (FLAC__uint16)frame_crc);
  99904. if(!read_frame_header_(decoder))
  99905. return false;
  99906. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
  99907. return true;
  99908. if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
  99909. return false;
  99910. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  99911. /*
  99912. * first figure the correct bits-per-sample of the subframe
  99913. */
  99914. unsigned bps = decoder->private_->frame.header.bits_per_sample;
  99915. switch(decoder->private_->frame.header.channel_assignment) {
  99916. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  99917. /* no adjustment needed */
  99918. break;
  99919. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  99920. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  99921. if(channel == 1)
  99922. bps++;
  99923. break;
  99924. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  99925. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  99926. if(channel == 0)
  99927. bps++;
  99928. break;
  99929. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  99930. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  99931. if(channel == 1)
  99932. bps++;
  99933. break;
  99934. default:
  99935. FLAC__ASSERT(0);
  99936. }
  99937. /*
  99938. * now read it
  99939. */
  99940. if(!read_subframe_(decoder, channel, bps, do_full_decode))
  99941. return false;
  99942. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  99943. return true;
  99944. }
  99945. if(!read_zero_padding_(decoder))
  99946. return false;
  99947. 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) */
  99948. return true;
  99949. /*
  99950. * Read the frame CRC-16 from the footer and check
  99951. */
  99952. frame_crc = FLAC__bitreader_get_read_crc16(decoder->private_->input);
  99953. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN))
  99954. return false; /* read_callback_ sets the state for us */
  99955. if(frame_crc == x) {
  99956. if(do_full_decode) {
  99957. /* Undo any special channel coding */
  99958. switch(decoder->private_->frame.header.channel_assignment) {
  99959. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  99960. /* do nothing */
  99961. break;
  99962. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  99963. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  99964. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  99965. decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
  99966. break;
  99967. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  99968. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  99969. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  99970. decoder->private_->output[0][i] += decoder->private_->output[1][i];
  99971. break;
  99972. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  99973. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  99974. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  99975. #if 1
  99976. mid = decoder->private_->output[0][i];
  99977. side = decoder->private_->output[1][i];
  99978. mid <<= 1;
  99979. mid |= (side & 1); /* i.e. if 'side' is odd... */
  99980. decoder->private_->output[0][i] = (mid + side) >> 1;
  99981. decoder->private_->output[1][i] = (mid - side) >> 1;
  99982. #else
  99983. /* OPT: without 'side' temp variable */
  99984. mid = (decoder->private_->output[0][i] << 1) | (decoder->private_->output[1][i] & 1); /* i.e. if 'side' is odd... */
  99985. decoder->private_->output[0][i] = (mid + decoder->private_->output[1][i]) >> 1;
  99986. decoder->private_->output[1][i] = (mid - decoder->private_->output[1][i]) >> 1;
  99987. #endif
  99988. }
  99989. break;
  99990. default:
  99991. FLAC__ASSERT(0);
  99992. break;
  99993. }
  99994. }
  99995. }
  99996. else {
  99997. /* Bad frame, emit error and zero the output signal */
  99998. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
  99999. if(do_full_decode) {
  100000. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  100001. memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  100002. }
  100003. }
  100004. }
  100005. *got_a_frame = true;
  100006. /* we wait to update fixed_block_size until here, when we're sure we've got a proper frame and hence a correct blocksize */
  100007. if(decoder->private_->next_fixed_block_size)
  100008. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size;
  100009. /* put the latest values into the public section of the decoder instance */
  100010. decoder->protected_->channels = decoder->private_->frame.header.channels;
  100011. decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
  100012. decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
  100013. decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
  100014. decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
  100015. FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  100016. decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
  100017. /* write it */
  100018. if(do_full_decode) {
  100019. if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
  100020. return false;
  100021. }
  100022. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100023. return true;
  100024. }
  100025. FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
  100026. {
  100027. FLAC__uint32 x;
  100028. FLAC__uint64 xx;
  100029. unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
  100030. FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
  100031. unsigned raw_header_len;
  100032. FLAC__bool is_unparseable = false;
  100033. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100034. /* init the raw header with the saved bits from synchronization */
  100035. raw_header[0] = decoder->private_->header_warmup[0];
  100036. raw_header[1] = decoder->private_->header_warmup[1];
  100037. raw_header_len = 2;
  100038. /* check to make sure that reserved bit is 0 */
  100039. if(raw_header[1] & 0x02) /* MAGIC NUMBER */
  100040. is_unparseable = true;
  100041. /*
  100042. * Note that along the way as we read the header, we look for a sync
  100043. * code inside. If we find one it would indicate that our original
  100044. * sync was bad since there cannot be a sync code in a valid header.
  100045. *
  100046. * Three kinds of things can go wrong when reading the frame header:
  100047. * 1) We may have sync'ed incorrectly and not landed on a frame header.
  100048. * If we don't find a sync code, it can end up looking like we read
  100049. * a valid but unparseable header, until getting to the frame header
  100050. * CRC. Even then we could get a false positive on the CRC.
  100051. * 2) We may have sync'ed correctly but on an unparseable frame (from a
  100052. * future encoder).
  100053. * 3) We may be on a damaged frame which appears valid but unparseable.
  100054. *
  100055. * For all these reasons, we try and read a complete frame header as
  100056. * long as it seems valid, even if unparseable, up until the frame
  100057. * header CRC.
  100058. */
  100059. /*
  100060. * read in the raw header as bytes so we can CRC it, and parse it on the way
  100061. */
  100062. for(i = 0; i < 2; i++) {
  100063. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100064. return false; /* read_callback_ sets the state for us */
  100065. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100066. /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
  100067. decoder->private_->lookahead = (FLAC__byte)x;
  100068. decoder->private_->cached = true;
  100069. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100070. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100071. return true;
  100072. }
  100073. raw_header[raw_header_len++] = (FLAC__byte)x;
  100074. }
  100075. switch(x = raw_header[2] >> 4) {
  100076. case 0:
  100077. is_unparseable = true;
  100078. break;
  100079. case 1:
  100080. decoder->private_->frame.header.blocksize = 192;
  100081. break;
  100082. case 2:
  100083. case 3:
  100084. case 4:
  100085. case 5:
  100086. decoder->private_->frame.header.blocksize = 576 << (x-2);
  100087. break;
  100088. case 6:
  100089. case 7:
  100090. blocksize_hint = x;
  100091. break;
  100092. case 8:
  100093. case 9:
  100094. case 10:
  100095. case 11:
  100096. case 12:
  100097. case 13:
  100098. case 14:
  100099. case 15:
  100100. decoder->private_->frame.header.blocksize = 256 << (x-8);
  100101. break;
  100102. default:
  100103. FLAC__ASSERT(0);
  100104. break;
  100105. }
  100106. switch(x = raw_header[2] & 0x0f) {
  100107. case 0:
  100108. if(decoder->private_->has_stream_info)
  100109. decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
  100110. else
  100111. is_unparseable = true;
  100112. break;
  100113. case 1:
  100114. decoder->private_->frame.header.sample_rate = 88200;
  100115. break;
  100116. case 2:
  100117. decoder->private_->frame.header.sample_rate = 176400;
  100118. break;
  100119. case 3:
  100120. decoder->private_->frame.header.sample_rate = 192000;
  100121. break;
  100122. case 4:
  100123. decoder->private_->frame.header.sample_rate = 8000;
  100124. break;
  100125. case 5:
  100126. decoder->private_->frame.header.sample_rate = 16000;
  100127. break;
  100128. case 6:
  100129. decoder->private_->frame.header.sample_rate = 22050;
  100130. break;
  100131. case 7:
  100132. decoder->private_->frame.header.sample_rate = 24000;
  100133. break;
  100134. case 8:
  100135. decoder->private_->frame.header.sample_rate = 32000;
  100136. break;
  100137. case 9:
  100138. decoder->private_->frame.header.sample_rate = 44100;
  100139. break;
  100140. case 10:
  100141. decoder->private_->frame.header.sample_rate = 48000;
  100142. break;
  100143. case 11:
  100144. decoder->private_->frame.header.sample_rate = 96000;
  100145. break;
  100146. case 12:
  100147. case 13:
  100148. case 14:
  100149. sample_rate_hint = x;
  100150. break;
  100151. case 15:
  100152. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100153. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100154. return true;
  100155. default:
  100156. FLAC__ASSERT(0);
  100157. }
  100158. x = (unsigned)(raw_header[3] >> 4);
  100159. if(x & 8) {
  100160. decoder->private_->frame.header.channels = 2;
  100161. switch(x & 7) {
  100162. case 0:
  100163. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
  100164. break;
  100165. case 1:
  100166. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
  100167. break;
  100168. case 2:
  100169. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
  100170. break;
  100171. default:
  100172. is_unparseable = true;
  100173. break;
  100174. }
  100175. }
  100176. else {
  100177. decoder->private_->frame.header.channels = (unsigned)x + 1;
  100178. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  100179. }
  100180. switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
  100181. case 0:
  100182. if(decoder->private_->has_stream_info)
  100183. decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  100184. else
  100185. is_unparseable = true;
  100186. break;
  100187. case 1:
  100188. decoder->private_->frame.header.bits_per_sample = 8;
  100189. break;
  100190. case 2:
  100191. decoder->private_->frame.header.bits_per_sample = 12;
  100192. break;
  100193. case 4:
  100194. decoder->private_->frame.header.bits_per_sample = 16;
  100195. break;
  100196. case 5:
  100197. decoder->private_->frame.header.bits_per_sample = 20;
  100198. break;
  100199. case 6:
  100200. decoder->private_->frame.header.bits_per_sample = 24;
  100201. break;
  100202. case 3:
  100203. case 7:
  100204. is_unparseable = true;
  100205. break;
  100206. default:
  100207. FLAC__ASSERT(0);
  100208. break;
  100209. }
  100210. /* check to make sure that reserved bit is 0 */
  100211. if(raw_header[3] & 0x01) /* MAGIC NUMBER */
  100212. is_unparseable = true;
  100213. /* read the frame's starting sample number (or frame number as the case may be) */
  100214. if(
  100215. raw_header[1] & 0x01 ||
  100216. /*@@@ 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 */
  100217. (decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.min_blocksize != decoder->private_->stream_info.data.stream_info.max_blocksize)
  100218. ) { /* variable blocksize */
  100219. if(!FLAC__bitreader_read_utf8_uint64(decoder->private_->input, &xx, raw_header, &raw_header_len))
  100220. return false; /* read_callback_ sets the state for us */
  100221. if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
  100222. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  100223. decoder->private_->cached = true;
  100224. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100225. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100226. return true;
  100227. }
  100228. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  100229. decoder->private_->frame.header.number.sample_number = xx;
  100230. }
  100231. else { /* fixed blocksize */
  100232. if(!FLAC__bitreader_read_utf8_uint32(decoder->private_->input, &x, raw_header, &raw_header_len))
  100233. return false; /* read_callback_ sets the state for us */
  100234. if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
  100235. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  100236. decoder->private_->cached = true;
  100237. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100238. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100239. return true;
  100240. }
  100241. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  100242. decoder->private_->frame.header.number.frame_number = x;
  100243. }
  100244. if(blocksize_hint) {
  100245. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100246. return false; /* read_callback_ sets the state for us */
  100247. raw_header[raw_header_len++] = (FLAC__byte)x;
  100248. if(blocksize_hint == 7) {
  100249. FLAC__uint32 _x;
  100250. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  100251. return false; /* read_callback_ sets the state for us */
  100252. raw_header[raw_header_len++] = (FLAC__byte)_x;
  100253. x = (x << 8) | _x;
  100254. }
  100255. decoder->private_->frame.header.blocksize = x+1;
  100256. }
  100257. if(sample_rate_hint) {
  100258. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100259. return false; /* read_callback_ sets the state for us */
  100260. raw_header[raw_header_len++] = (FLAC__byte)x;
  100261. if(sample_rate_hint != 12) {
  100262. FLAC__uint32 _x;
  100263. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  100264. return false; /* read_callback_ sets the state for us */
  100265. raw_header[raw_header_len++] = (FLAC__byte)_x;
  100266. x = (x << 8) | _x;
  100267. }
  100268. if(sample_rate_hint == 12)
  100269. decoder->private_->frame.header.sample_rate = x*1000;
  100270. else if(sample_rate_hint == 13)
  100271. decoder->private_->frame.header.sample_rate = x;
  100272. else
  100273. decoder->private_->frame.header.sample_rate = x*10;
  100274. }
  100275. /* read the CRC-8 byte */
  100276. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100277. return false; /* read_callback_ sets the state for us */
  100278. crc8 = (FLAC__byte)x;
  100279. if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
  100280. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100281. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100282. return true;
  100283. }
  100284. /* calculate the sample number from the frame number if needed */
  100285. decoder->private_->next_fixed_block_size = 0;
  100286. if(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  100287. x = decoder->private_->frame.header.number.frame_number;
  100288. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  100289. if(decoder->private_->fixed_block_size)
  100290. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->fixed_block_size * (FLAC__uint64)x;
  100291. else if(decoder->private_->has_stream_info) {
  100292. if(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize) {
  100293. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
  100294. decoder->private_->next_fixed_block_size = decoder->private_->stream_info.data.stream_info.max_blocksize;
  100295. }
  100296. else
  100297. is_unparseable = true;
  100298. }
  100299. else if(x == 0) {
  100300. decoder->private_->frame.header.number.sample_number = 0;
  100301. decoder->private_->next_fixed_block_size = decoder->private_->frame.header.blocksize;
  100302. }
  100303. else {
  100304. /* can only get here if the stream has invalid frame numbering and no STREAMINFO, so assume it's not the last (possibly short) frame */
  100305. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
  100306. }
  100307. }
  100308. if(is_unparseable) {
  100309. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  100310. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100311. return true;
  100312. }
  100313. return true;
  100314. }
  100315. FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  100316. {
  100317. FLAC__uint32 x;
  100318. FLAC__bool wasted_bits;
  100319. unsigned i;
  100320. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) /* MAGIC NUMBER */
  100321. return false; /* read_callback_ sets the state for us */
  100322. wasted_bits = (x & 1);
  100323. x &= 0xfe;
  100324. if(wasted_bits) {
  100325. unsigned u;
  100326. if(!FLAC__bitreader_read_unary_unsigned(decoder->private_->input, &u))
  100327. return false; /* read_callback_ sets the state for us */
  100328. decoder->private_->frame.subframes[channel].wasted_bits = u+1;
  100329. bps -= decoder->private_->frame.subframes[channel].wasted_bits;
  100330. }
  100331. else
  100332. decoder->private_->frame.subframes[channel].wasted_bits = 0;
  100333. /*
  100334. * Lots of magic numbers here
  100335. */
  100336. if(x & 0x80) {
  100337. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100338. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100339. return true;
  100340. }
  100341. else if(x == 0) {
  100342. if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
  100343. return false;
  100344. }
  100345. else if(x == 2) {
  100346. if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
  100347. return false;
  100348. }
  100349. else if(x < 16) {
  100350. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  100351. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100352. return true;
  100353. }
  100354. else if(x <= 24) {
  100355. if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
  100356. return false;
  100357. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  100358. return true;
  100359. }
  100360. else if(x < 64) {
  100361. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  100362. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100363. return true;
  100364. }
  100365. else {
  100366. if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
  100367. return false;
  100368. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  100369. return true;
  100370. }
  100371. if(wasted_bits && do_full_decode) {
  100372. x = decoder->private_->frame.subframes[channel].wasted_bits;
  100373. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100374. decoder->private_->output[channel][i] <<= x;
  100375. }
  100376. return true;
  100377. }
  100378. FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  100379. {
  100380. FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
  100381. FLAC__int32 x;
  100382. unsigned i;
  100383. FLAC__int32 *output = decoder->private_->output[channel];
  100384. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
  100385. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  100386. return false; /* read_callback_ sets the state for us */
  100387. subframe->value = x;
  100388. /* decode the subframe */
  100389. if(do_full_decode) {
  100390. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100391. output[i] = x;
  100392. }
  100393. return true;
  100394. }
  100395. FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  100396. {
  100397. FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
  100398. FLAC__int32 i32;
  100399. FLAC__uint32 u32;
  100400. unsigned u;
  100401. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
  100402. subframe->residual = decoder->private_->residual[channel];
  100403. subframe->order = order;
  100404. /* read warm-up samples */
  100405. for(u = 0; u < order; u++) {
  100406. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  100407. return false; /* read_callback_ sets the state for us */
  100408. subframe->warmup[u] = i32;
  100409. }
  100410. /* read entropy coding method info */
  100411. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  100412. return false; /* read_callback_ sets the state for us */
  100413. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  100414. switch(subframe->entropy_coding_method.type) {
  100415. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  100416. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  100417. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  100418. return false; /* read_callback_ sets the state for us */
  100419. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  100420. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  100421. break;
  100422. default:
  100423. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  100424. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100425. return true;
  100426. }
  100427. /* read residual */
  100428. switch(subframe->entropy_coding_method.type) {
  100429. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  100430. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  100431. 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))
  100432. return false;
  100433. break;
  100434. default:
  100435. FLAC__ASSERT(0);
  100436. }
  100437. /* decode the subframe */
  100438. if(do_full_decode) {
  100439. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  100440. FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
  100441. }
  100442. return true;
  100443. }
  100444. FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  100445. {
  100446. FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
  100447. FLAC__int32 i32;
  100448. FLAC__uint32 u32;
  100449. unsigned u;
  100450. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
  100451. subframe->residual = decoder->private_->residual[channel];
  100452. subframe->order = order;
  100453. /* read warm-up samples */
  100454. for(u = 0; u < order; u++) {
  100455. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  100456. return false; /* read_callback_ sets the state for us */
  100457. subframe->warmup[u] = i32;
  100458. }
  100459. /* read qlp coeff precision */
  100460. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  100461. return false; /* read_callback_ sets the state for us */
  100462. if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
  100463. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100464. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100465. return true;
  100466. }
  100467. subframe->qlp_coeff_precision = u32+1;
  100468. /* read qlp shift */
  100469. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  100470. return false; /* read_callback_ sets the state for us */
  100471. subframe->quantization_level = i32;
  100472. /* read quantized lp coefficiencts */
  100473. for(u = 0; u < order; u++) {
  100474. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision))
  100475. return false; /* read_callback_ sets the state for us */
  100476. subframe->qlp_coeff[u] = i32;
  100477. }
  100478. /* read entropy coding method info */
  100479. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  100480. return false; /* read_callback_ sets the state for us */
  100481. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  100482. switch(subframe->entropy_coding_method.type) {
  100483. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  100484. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  100485. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  100486. return false; /* read_callback_ sets the state for us */
  100487. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  100488. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  100489. break;
  100490. default:
  100491. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  100492. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100493. return true;
  100494. }
  100495. /* read residual */
  100496. switch(subframe->entropy_coding_method.type) {
  100497. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  100498. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  100499. 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))
  100500. return false;
  100501. break;
  100502. default:
  100503. FLAC__ASSERT(0);
  100504. }
  100505. /* decode the subframe */
  100506. if(do_full_decode) {
  100507. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  100508. /*@@@@@@ technically not pessimistic enough, should be more like
  100509. if( (FLAC__uint64)order * ((((FLAC__uint64)1)<<bps)-1) * ((1<<subframe->qlp_coeff_precision)-1) < (((FLAC__uint64)-1) << 32) )
  100510. */
  100511. if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  100512. if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
  100513. if(order <= 8)
  100514. 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);
  100515. else
  100516. 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);
  100517. }
  100518. else
  100519. 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);
  100520. else
  100521. 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);
  100522. }
  100523. return true;
  100524. }
  100525. FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  100526. {
  100527. FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
  100528. FLAC__int32 x, *residual = decoder->private_->residual[channel];
  100529. unsigned i;
  100530. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
  100531. subframe->data = residual;
  100532. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  100533. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  100534. return false; /* read_callback_ sets the state for us */
  100535. residual[i] = x;
  100536. }
  100537. /* decode the subframe */
  100538. if(do_full_decode)
  100539. memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  100540. return true;
  100541. }
  100542. 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)
  100543. {
  100544. FLAC__uint32 rice_parameter;
  100545. int i;
  100546. unsigned partition, sample, u;
  100547. const unsigned partitions = 1u << partition_order;
  100548. const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
  100549. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  100550. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  100551. /* sanity checks */
  100552. if(partition_order == 0) {
  100553. if(decoder->private_->frame.header.blocksize < predictor_order) {
  100554. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100555. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100556. return true;
  100557. }
  100558. }
  100559. else {
  100560. if(partition_samples < predictor_order) {
  100561. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100562. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100563. return true;
  100564. }
  100565. }
  100566. if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
  100567. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100568. return false;
  100569. }
  100570. sample = 0;
  100571. for(partition = 0; partition < partitions; partition++) {
  100572. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, plen))
  100573. return false; /* read_callback_ sets the state for us */
  100574. partitioned_rice_contents->parameters[partition] = rice_parameter;
  100575. if(rice_parameter < pesc) {
  100576. partitioned_rice_contents->raw_bits[partition] = 0;
  100577. u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
  100578. if(!decoder->private_->local_bitreader_read_rice_signed_block(decoder->private_->input, (int*) residual + sample, u, rice_parameter))
  100579. return false; /* read_callback_ sets the state for us */
  100580. sample += u;
  100581. }
  100582. else {
  100583. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  100584. return false; /* read_callback_ sets the state for us */
  100585. partitioned_rice_contents->raw_bits[partition] = rice_parameter;
  100586. for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
  100587. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, (FLAC__int32*) &i, rice_parameter))
  100588. return false; /* read_callback_ sets the state for us */
  100589. residual[sample] = i;
  100590. }
  100591. }
  100592. }
  100593. return true;
  100594. }
  100595. FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
  100596. {
  100597. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  100598. FLAC__uint32 zero = 0;
  100599. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  100600. return false; /* read_callback_ sets the state for us */
  100601. if(zero != 0) {
  100602. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100603. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100604. }
  100605. }
  100606. return true;
  100607. }
  100608. FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data)
  100609. {
  100610. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
  100611. if(
  100612. #if FLAC__HAS_OGG
  100613. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  100614. !decoder->private_->is_ogg &&
  100615. #endif
  100616. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  100617. ) {
  100618. *bytes = 0;
  100619. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  100620. return false;
  100621. }
  100622. else if(*bytes > 0) {
  100623. /* While seeking, it is possible for our seek to land in the
  100624. * middle of audio data that looks exactly like a frame header
  100625. * from a future version of an encoder. When that happens, our
  100626. * error callback will get an
  100627. * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
  100628. * unparseable_frame_count. But there is a remote possibility
  100629. * that it is properly synced at such a "future-codec frame",
  100630. * so to make sure, we wait to see many "unparseable" errors in
  100631. * a row before bailing out.
  100632. */
  100633. if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
  100634. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  100635. return false;
  100636. }
  100637. else {
  100638. const FLAC__StreamDecoderReadStatus status =
  100639. #if FLAC__HAS_OGG
  100640. decoder->private_->is_ogg?
  100641. read_callback_ogg_aspect_(decoder, buffer, bytes) :
  100642. #endif
  100643. decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data)
  100644. ;
  100645. if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
  100646. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  100647. return false;
  100648. }
  100649. else if(*bytes == 0) {
  100650. if(
  100651. status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM ||
  100652. (
  100653. #if FLAC__HAS_OGG
  100654. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  100655. !decoder->private_->is_ogg &&
  100656. #endif
  100657. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  100658. )
  100659. ) {
  100660. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  100661. return false;
  100662. }
  100663. else
  100664. return true;
  100665. }
  100666. else
  100667. return true;
  100668. }
  100669. }
  100670. else {
  100671. /* abort to avoid a deadlock */
  100672. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  100673. return false;
  100674. }
  100675. /* [1] @@@ HACK NOTE: The end-of-stream checking has to be hacked around
  100676. * for Ogg FLAC. This is because the ogg decoder aspect can lose sync
  100677. * and at the same time hit the end of the stream (for example, seeking
  100678. * to a point that is after the beginning of the last Ogg page). There
  100679. * is no way to report an Ogg sync loss through the callbacks (see note
  100680. * in read_callback_ogg_aspect_()) so it returns CONTINUE with *bytes==0.
  100681. * So to keep the decoder from stopping at this point we gate the call
  100682. * to the eof_callback and let the Ogg decoder aspect set the
  100683. * end-of-stream state when it is needed.
  100684. */
  100685. }
  100686. #if FLAC__HAS_OGG
  100687. FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes)
  100688. {
  100689. switch(FLAC__ogg_decoder_aspect_read_callback_wrapper(&decoder->protected_->ogg_decoder_aspect, buffer, bytes, read_callback_proxy_, decoder, decoder->private_->client_data)) {
  100690. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK:
  100691. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  100692. /* we don't really have a way to handle lost sync via read
  100693. * callback so we'll let it pass and let the underlying
  100694. * FLAC decoder catch the error
  100695. */
  100696. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC:
  100697. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  100698. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM:
  100699. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  100700. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC:
  100701. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION:
  100702. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT:
  100703. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR:
  100704. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR:
  100705. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  100706. default:
  100707. FLAC__ASSERT(0);
  100708. /* double protection */
  100709. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  100710. }
  100711. }
  100712. FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  100713. {
  100714. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder*)void_decoder;
  100715. switch(decoder->private_->read_callback(decoder, buffer, bytes, client_data)) {
  100716. case FLAC__STREAM_DECODER_READ_STATUS_CONTINUE:
  100717. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK;
  100718. case FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM:
  100719. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM;
  100720. case FLAC__STREAM_DECODER_READ_STATUS_ABORT:
  100721. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  100722. default:
  100723. /* double protection: */
  100724. FLAC__ASSERT(0);
  100725. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  100726. }
  100727. }
  100728. #endif
  100729. FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
  100730. {
  100731. if(decoder->private_->is_seeking) {
  100732. FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
  100733. FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
  100734. FLAC__uint64 target_sample = decoder->private_->target_sample;
  100735. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  100736. #if FLAC__HAS_OGG
  100737. decoder->private_->got_a_frame = true;
  100738. #endif
  100739. decoder->private_->last_frame = *frame; /* save the frame */
  100740. if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
  100741. unsigned delta = (unsigned)(target_sample - this_frame_sample);
  100742. /* kick out of seek mode */
  100743. decoder->private_->is_seeking = false;
  100744. /* shift out the samples before target_sample */
  100745. if(delta > 0) {
  100746. unsigned channel;
  100747. const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
  100748. for(channel = 0; channel < frame->header.channels; channel++)
  100749. newbuffer[channel] = buffer[channel] + delta;
  100750. decoder->private_->last_frame.header.blocksize -= delta;
  100751. decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
  100752. /* write the relevant samples */
  100753. return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
  100754. }
  100755. else {
  100756. /* write the relevant samples */
  100757. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  100758. }
  100759. }
  100760. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  100761. }
  100762. /*
  100763. * If we never got STREAMINFO, turn off MD5 checking to save
  100764. * cycles since we don't have a sum to compare to anyway
  100765. */
  100766. if(!decoder->private_->has_stream_info)
  100767. decoder->private_->do_md5_checking = false;
  100768. if(decoder->private_->do_md5_checking) {
  100769. if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
  100770. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  100771. }
  100772. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  100773. }
  100774. void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
  100775. {
  100776. if(!decoder->private_->is_seeking)
  100777. decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
  100778. else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
  100779. decoder->private_->unparseable_frame_count++;
  100780. }
  100781. FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  100782. {
  100783. FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound, lower_bound_sample, upper_bound_sample, this_frame_sample;
  100784. FLAC__int64 pos = -1;
  100785. int i;
  100786. unsigned approx_bytes_per_frame;
  100787. FLAC__bool first_seek = true;
  100788. const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
  100789. const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
  100790. const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
  100791. const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
  100792. const unsigned min_framesize = decoder->private_->stream_info.data.stream_info.min_framesize;
  100793. /* take these from the current frame in case they've changed mid-stream */
  100794. unsigned channels = FLAC__stream_decoder_get_channels(decoder);
  100795. unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
  100796. const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
  100797. /* use values from stream info if we didn't decode a frame */
  100798. if(channels == 0)
  100799. channels = decoder->private_->stream_info.data.stream_info.channels;
  100800. if(bps == 0)
  100801. bps = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  100802. /* we are just guessing here */
  100803. if(max_framesize > 0)
  100804. approx_bytes_per_frame = (max_framesize + min_framesize) / 2 + 1;
  100805. /*
  100806. * Check if it's a known fixed-blocksize stream. Note that though
  100807. * the spec doesn't allow zeroes in the STREAMINFO block, we may
  100808. * never get a STREAMINFO block when decoding so the value of
  100809. * min_blocksize might be zero.
  100810. */
  100811. else if(min_blocksize == max_blocksize && min_blocksize > 0) {
  100812. /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
  100813. approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
  100814. }
  100815. else
  100816. approx_bytes_per_frame = 4096 * channels * bps/8 + 64;
  100817. /*
  100818. * First, we set an upper and lower bound on where in the
  100819. * stream we will search. For now we assume the worst case
  100820. * scenario, which is our best guess at the beginning of
  100821. * the first frame and end of the stream.
  100822. */
  100823. lower_bound = first_frame_offset;
  100824. lower_bound_sample = 0;
  100825. upper_bound = stream_length;
  100826. upper_bound_sample = total_samples > 0 ? total_samples : target_sample /*estimate it*/;
  100827. /*
  100828. * Now we refine the bounds if we have a seektable with
  100829. * suitable points. Note that according to the spec they
  100830. * must be ordered by ascending sample number.
  100831. *
  100832. * Note: to protect against invalid seek tables we will ignore points
  100833. * that have frame_samples==0 or sample_number>=total_samples
  100834. */
  100835. if(seek_table) {
  100836. FLAC__uint64 new_lower_bound = lower_bound;
  100837. FLAC__uint64 new_upper_bound = upper_bound;
  100838. FLAC__uint64 new_lower_bound_sample = lower_bound_sample;
  100839. FLAC__uint64 new_upper_bound_sample = upper_bound_sample;
  100840. /* find the closest seek point <= target_sample, if it exists */
  100841. for(i = (int)seek_table->num_points - 1; i >= 0; i--) {
  100842. if(
  100843. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  100844. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  100845. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  100846. seek_table->points[i].sample_number <= target_sample
  100847. )
  100848. break;
  100849. }
  100850. if(i >= 0) { /* i.e. we found a suitable seek point... */
  100851. new_lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
  100852. new_lower_bound_sample = seek_table->points[i].sample_number;
  100853. }
  100854. /* find the closest seek point > target_sample, if it exists */
  100855. for(i = 0; i < (int)seek_table->num_points; i++) {
  100856. if(
  100857. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  100858. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  100859. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  100860. seek_table->points[i].sample_number > target_sample
  100861. )
  100862. break;
  100863. }
  100864. if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
  100865. new_upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
  100866. new_upper_bound_sample = seek_table->points[i].sample_number;
  100867. }
  100868. /* final protection against unsorted seek tables; keep original values if bogus */
  100869. if(new_upper_bound >= new_lower_bound) {
  100870. lower_bound = new_lower_bound;
  100871. upper_bound = new_upper_bound;
  100872. lower_bound_sample = new_lower_bound_sample;
  100873. upper_bound_sample = new_upper_bound_sample;
  100874. }
  100875. }
  100876. FLAC__ASSERT(upper_bound_sample >= lower_bound_sample);
  100877. /* there are 2 insidious ways that the following equality occurs, which
  100878. * we need to fix:
  100879. * 1) total_samples is 0 (unknown) and target_sample is 0
  100880. * 2) total_samples is 0 (unknown) and target_sample happens to be
  100881. * exactly equal to the last seek point in the seek table; this
  100882. * means there is no seek point above it, and upper_bound_samples
  100883. * remains equal to the estimate (of target_samples) we made above
  100884. * in either case it does not hurt to move upper_bound_sample up by 1
  100885. */
  100886. if(upper_bound_sample == lower_bound_sample)
  100887. upper_bound_sample++;
  100888. decoder->private_->target_sample = target_sample;
  100889. while(1) {
  100890. /* check if the bounds are still ok */
  100891. if (lower_bound_sample >= upper_bound_sample || lower_bound > upper_bound) {
  100892. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  100893. return false;
  100894. }
  100895. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100896. #if defined _MSC_VER || defined __MINGW32__
  100897. /* with VC++ you have to spoon feed it the casting */
  100898. 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;
  100899. #else
  100900. 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;
  100901. #endif
  100902. #else
  100903. /* a little less accurate: */
  100904. if(upper_bound - lower_bound < 0xffffffff)
  100905. 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;
  100906. else /* @@@ WATCHOUT, ~2TB limit */
  100907. 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;
  100908. #endif
  100909. if(pos >= (FLAC__int64)upper_bound)
  100910. pos = (FLAC__int64)upper_bound - 1;
  100911. if(pos < (FLAC__int64)lower_bound)
  100912. pos = (FLAC__int64)lower_bound;
  100913. if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  100914. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  100915. return false;
  100916. }
  100917. if(!FLAC__stream_decoder_flush(decoder)) {
  100918. /* above call sets the state for us */
  100919. return false;
  100920. }
  100921. /* Now we need to get a frame. First we need to reset our
  100922. * unparseable_frame_count; if we get too many unparseable
  100923. * frames in a row, the read callback will return
  100924. * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing
  100925. * FLAC__stream_decoder_process_single() to return false.
  100926. */
  100927. decoder->private_->unparseable_frame_count = 0;
  100928. if(!FLAC__stream_decoder_process_single(decoder)) {
  100929. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  100930. return false;
  100931. }
  100932. /* our write callback will change the state when it gets to the target frame */
  100933. /* 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 */
  100934. #if 0
  100935. /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */
  100936. if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM)
  100937. break;
  100938. #endif
  100939. if(!decoder->private_->is_seeking)
  100940. break;
  100941. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  100942. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  100943. if (0 == decoder->private_->samples_decoded || (this_frame_sample + decoder->private_->last_frame.header.blocksize >= upper_bound_sample && !first_seek)) {
  100944. if (pos == (FLAC__int64)lower_bound) {
  100945. /* can't move back any more than the first frame, something is fatally wrong */
  100946. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  100947. return false;
  100948. }
  100949. /* our last move backwards wasn't big enough, try again */
  100950. approx_bytes_per_frame = approx_bytes_per_frame? approx_bytes_per_frame * 2 : 16;
  100951. continue;
  100952. }
  100953. /* allow one seek over upper bound, so we can get a correct upper_bound_sample for streams with unknown total_samples */
  100954. first_seek = false;
  100955. /* make sure we are not seeking in corrupted stream */
  100956. if (this_frame_sample < lower_bound_sample) {
  100957. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  100958. return false;
  100959. }
  100960. /* we need to narrow the search */
  100961. if(target_sample < this_frame_sample) {
  100962. upper_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  100963. /*@@@@@@ what will decode position be if at end of stream? */
  100964. if(!FLAC__stream_decoder_get_decode_position(decoder, &upper_bound)) {
  100965. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  100966. return false;
  100967. }
  100968. approx_bytes_per_frame = (unsigned)(2 * (upper_bound - pos) / 3 + 16);
  100969. }
  100970. else { /* target_sample >= this_frame_sample + this frame's blocksize */
  100971. lower_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  100972. if(!FLAC__stream_decoder_get_decode_position(decoder, &lower_bound)) {
  100973. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  100974. return false;
  100975. }
  100976. approx_bytes_per_frame = (unsigned)(2 * (lower_bound - pos) / 3 + 16);
  100977. }
  100978. }
  100979. return true;
  100980. }
  100981. #if FLAC__HAS_OGG
  100982. FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  100983. {
  100984. FLAC__uint64 left_pos = 0, right_pos = stream_length;
  100985. FLAC__uint64 left_sample = 0, right_sample = FLAC__stream_decoder_get_total_samples(decoder);
  100986. FLAC__uint64 this_frame_sample = (FLAC__uint64)0 - 1;
  100987. FLAC__uint64 pos = 0; /* only initialized to avoid compiler warning */
  100988. FLAC__bool did_a_seek;
  100989. unsigned iteration = 0;
  100990. /* In the first iterations, we will calculate the target byte position
  100991. * by the distance from the target sample to left_sample and
  100992. * right_sample (let's call it "proportional search"). After that, we
  100993. * will switch to binary search.
  100994. */
  100995. unsigned BINARY_SEARCH_AFTER_ITERATION = 2;
  100996. /* We will switch to a linear search once our current sample is less
  100997. * than this number of samples ahead of the target sample
  100998. */
  100999. static const FLAC__uint64 LINEAR_SEARCH_WITHIN_SAMPLES = FLAC__MAX_BLOCK_SIZE * 2;
  101000. /* If the total number of samples is unknown, use a large value, and
  101001. * force binary search immediately.
  101002. */
  101003. if(right_sample == 0) {
  101004. right_sample = (FLAC__uint64)(-1);
  101005. BINARY_SEARCH_AFTER_ITERATION = 0;
  101006. }
  101007. decoder->private_->target_sample = target_sample;
  101008. for( ; ; iteration++) {
  101009. if (iteration == 0 || this_frame_sample > target_sample || target_sample - this_frame_sample > LINEAR_SEARCH_WITHIN_SAMPLES) {
  101010. if (iteration >= BINARY_SEARCH_AFTER_ITERATION) {
  101011. pos = (right_pos + left_pos) / 2;
  101012. }
  101013. else {
  101014. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101015. #if defined _MSC_VER || defined __MINGW32__
  101016. /* with MSVC you have to spoon feed it the casting */
  101017. 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));
  101018. #else
  101019. pos = (FLAC__uint64)((FLAC__double)(target_sample - left_sample) / (FLAC__double)(right_sample - left_sample) * (FLAC__double)(right_pos - left_pos));
  101020. #endif
  101021. #else
  101022. /* a little less accurate: */
  101023. if ((target_sample-left_sample <= 0xffffffff) && (right_pos-left_pos <= 0xffffffff))
  101024. pos = (FLAC__int64)(((target_sample-left_sample) * (right_pos-left_pos)) / (right_sample-left_sample));
  101025. else /* @@@ WATCHOUT, ~2TB limit */
  101026. pos = (FLAC__int64)((((target_sample-left_sample)>>8) * ((right_pos-left_pos)>>8)) / ((right_sample-left_sample)>>16));
  101027. #endif
  101028. /* @@@ TODO: might want to limit pos to some distance
  101029. * before EOF, to make sure we land before the last frame,
  101030. * thereby getting a this_frame_sample and so having a better
  101031. * estimate.
  101032. */
  101033. }
  101034. /* physical seek */
  101035. if(decoder->private_->seek_callback((FLAC__StreamDecoder*)decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  101036. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101037. return false;
  101038. }
  101039. if(!FLAC__stream_decoder_flush(decoder)) {
  101040. /* above call sets the state for us */
  101041. return false;
  101042. }
  101043. did_a_seek = true;
  101044. }
  101045. else
  101046. did_a_seek = false;
  101047. decoder->private_->got_a_frame = false;
  101048. if(!FLAC__stream_decoder_process_single(decoder)) {
  101049. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101050. return false;
  101051. }
  101052. if(!decoder->private_->got_a_frame) {
  101053. if(did_a_seek) {
  101054. /* this can happen if we seek to a point after the last frame; we drop
  101055. * to binary search right away in this case to avoid any wasted
  101056. * iterations of proportional search.
  101057. */
  101058. right_pos = pos;
  101059. BINARY_SEARCH_AFTER_ITERATION = 0;
  101060. }
  101061. else {
  101062. /* this can probably only happen if total_samples is unknown and the
  101063. * target_sample is past the end of the stream
  101064. */
  101065. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101066. return false;
  101067. }
  101068. }
  101069. /* our write callback will change the state when it gets to the target frame */
  101070. else if(!decoder->private_->is_seeking) {
  101071. break;
  101072. }
  101073. else {
  101074. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  101075. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101076. if (did_a_seek) {
  101077. if (this_frame_sample <= target_sample) {
  101078. /* The 'equal' case should not happen, since
  101079. * FLAC__stream_decoder_process_single()
  101080. * should recognize that it has hit the
  101081. * target sample and we would exit through
  101082. * the 'break' above.
  101083. */
  101084. FLAC__ASSERT(this_frame_sample != target_sample);
  101085. left_sample = this_frame_sample;
  101086. /* sanity check to avoid infinite loop */
  101087. if (left_pos == pos) {
  101088. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101089. return false;
  101090. }
  101091. left_pos = pos;
  101092. }
  101093. else if(this_frame_sample > target_sample) {
  101094. right_sample = this_frame_sample;
  101095. /* sanity check to avoid infinite loop */
  101096. if (right_pos == pos) {
  101097. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101098. return false;
  101099. }
  101100. right_pos = pos;
  101101. }
  101102. }
  101103. }
  101104. }
  101105. return true;
  101106. }
  101107. #endif
  101108. FLAC__StreamDecoderReadStatus file_read_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  101109. {
  101110. (void)client_data;
  101111. if(*bytes > 0) {
  101112. *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file);
  101113. if(ferror(decoder->private_->file))
  101114. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101115. else if(*bytes == 0)
  101116. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  101117. else
  101118. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101119. }
  101120. else
  101121. return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
  101122. }
  101123. FLAC__StreamDecoderSeekStatus file_seek_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  101124. {
  101125. (void)client_data;
  101126. if(decoder->private_->file == stdin)
  101127. return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  101128. else if(fseeko(decoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  101129. return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  101130. else
  101131. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  101132. }
  101133. FLAC__StreamDecoderTellStatus file_tell_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  101134. {
  101135. off_t pos;
  101136. (void)client_data;
  101137. if(decoder->private_->file == stdin)
  101138. return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  101139. else if((pos = ftello(decoder->private_->file)) < 0)
  101140. return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  101141. else {
  101142. *absolute_byte_offset = (FLAC__uint64)pos;
  101143. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  101144. }
  101145. }
  101146. FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  101147. {
  101148. struct stat filestats;
  101149. (void)client_data;
  101150. if(decoder->private_->file == stdin)
  101151. return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  101152. else if(fstat(fileno(decoder->private_->file), &filestats) != 0)
  101153. return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  101154. else {
  101155. *stream_length = (FLAC__uint64)filestats.st_size;
  101156. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  101157. }
  101158. }
  101159. FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
  101160. {
  101161. (void)client_data;
  101162. return feof(decoder->private_->file)? true : false;
  101163. }
  101164. #endif
  101165. /*** End of inlined file: stream_decoder.c ***/
  101166. /*** Start of inlined file: stream_encoder.c ***/
  101167. /*** Start of inlined file: juce_FlacHeader.h ***/
  101168. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  101169. // tasks..
  101170. #define VERSION "1.2.1"
  101171. #define FLAC__NO_DLL 1
  101172. #if JUCE_MSVC
  101173. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  101174. #endif
  101175. #if JUCE_MAC
  101176. #define FLAC__SYS_DARWIN 1
  101177. #endif
  101178. /*** End of inlined file: juce_FlacHeader.h ***/
  101179. #if JUCE_USE_FLAC
  101180. #if HAVE_CONFIG_H
  101181. # include <config.h>
  101182. #endif
  101183. #if defined _MSC_VER || defined __MINGW32__
  101184. #include <io.h> /* for _setmode() */
  101185. #include <fcntl.h> /* for _O_BINARY */
  101186. #endif
  101187. #if defined __CYGWIN__ || defined __EMX__
  101188. #include <io.h> /* for setmode(), O_BINARY */
  101189. #include <fcntl.h> /* for _O_BINARY */
  101190. #endif
  101191. #include <limits.h>
  101192. #include <stdio.h>
  101193. #include <stdlib.h> /* for malloc() */
  101194. #include <string.h> /* for memcpy() */
  101195. #include <sys/types.h> /* for off_t */
  101196. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  101197. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  101198. #define fseeko fseek
  101199. #define ftello ftell
  101200. #endif
  101201. #endif
  101202. /*** Start of inlined file: stream_encoder.h ***/
  101203. #ifndef FLAC__PROTECTED__STREAM_ENCODER_H
  101204. #define FLAC__PROTECTED__STREAM_ENCODER_H
  101205. #if FLAC__HAS_OGG
  101206. #include "private/ogg_encoder_aspect.h"
  101207. #endif
  101208. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101209. #define FLAC__MAX_APODIZATION_FUNCTIONS 32
  101210. typedef enum {
  101211. FLAC__APODIZATION_BARTLETT,
  101212. FLAC__APODIZATION_BARTLETT_HANN,
  101213. FLAC__APODIZATION_BLACKMAN,
  101214. FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE,
  101215. FLAC__APODIZATION_CONNES,
  101216. FLAC__APODIZATION_FLATTOP,
  101217. FLAC__APODIZATION_GAUSS,
  101218. FLAC__APODIZATION_HAMMING,
  101219. FLAC__APODIZATION_HANN,
  101220. FLAC__APODIZATION_KAISER_BESSEL,
  101221. FLAC__APODIZATION_NUTTALL,
  101222. FLAC__APODIZATION_RECTANGLE,
  101223. FLAC__APODIZATION_TRIANGLE,
  101224. FLAC__APODIZATION_TUKEY,
  101225. FLAC__APODIZATION_WELCH
  101226. } FLAC__ApodizationFunction;
  101227. typedef struct {
  101228. FLAC__ApodizationFunction type;
  101229. union {
  101230. struct {
  101231. FLAC__real stddev;
  101232. } gauss;
  101233. struct {
  101234. FLAC__real p;
  101235. } tukey;
  101236. } parameters;
  101237. } FLAC__ApodizationSpecification;
  101238. #endif // #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101239. typedef struct FLAC__StreamEncoderProtected {
  101240. FLAC__StreamEncoderState state;
  101241. FLAC__bool verify;
  101242. FLAC__bool streamable_subset;
  101243. FLAC__bool do_md5;
  101244. FLAC__bool do_mid_side_stereo;
  101245. FLAC__bool loose_mid_side_stereo;
  101246. unsigned channels;
  101247. unsigned bits_per_sample;
  101248. unsigned sample_rate;
  101249. unsigned blocksize;
  101250. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101251. unsigned num_apodizations;
  101252. FLAC__ApodizationSpecification apodizations[FLAC__MAX_APODIZATION_FUNCTIONS];
  101253. #endif
  101254. unsigned max_lpc_order;
  101255. unsigned qlp_coeff_precision;
  101256. FLAC__bool do_qlp_coeff_prec_search;
  101257. FLAC__bool do_exhaustive_model_search;
  101258. FLAC__bool do_escape_coding;
  101259. unsigned min_residual_partition_order;
  101260. unsigned max_residual_partition_order;
  101261. unsigned rice_parameter_search_dist;
  101262. FLAC__uint64 total_samples_estimate;
  101263. FLAC__StreamMetadata **metadata;
  101264. unsigned num_metadata_blocks;
  101265. FLAC__uint64 streaminfo_offset, seektable_offset, audio_offset;
  101266. #if FLAC__HAS_OGG
  101267. FLAC__OggEncoderAspect ogg_encoder_aspect;
  101268. #endif
  101269. } FLAC__StreamEncoderProtected;
  101270. #endif
  101271. /*** End of inlined file: stream_encoder.h ***/
  101272. #if FLAC__HAS_OGG
  101273. #include "include/private/ogg_helper.h"
  101274. #include "include/private/ogg_mapping.h"
  101275. #endif
  101276. /*** Start of inlined file: stream_encoder_framing.h ***/
  101277. #ifndef FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  101278. #define FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  101279. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw);
  101280. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw);
  101281. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  101282. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  101283. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  101284. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  101285. #endif
  101286. /*** End of inlined file: stream_encoder_framing.h ***/
  101287. /*** Start of inlined file: window.h ***/
  101288. #ifndef FLAC__PRIVATE__WINDOW_H
  101289. #define FLAC__PRIVATE__WINDOW_H
  101290. #ifdef HAVE_CONFIG_H
  101291. #include <config.h>
  101292. #endif
  101293. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101294. /*
  101295. * FLAC__window_*()
  101296. * --------------------------------------------------------------------
  101297. * Calculates window coefficients according to different apodization
  101298. * functions.
  101299. *
  101300. * OUT window[0,L-1]
  101301. * IN L (number of points in window)
  101302. */
  101303. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L);
  101304. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L);
  101305. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L);
  101306. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L);
  101307. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L);
  101308. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L);
  101309. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev); /* 0.0 < stddev <= 0.5 */
  101310. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L);
  101311. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L);
  101312. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L);
  101313. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L);
  101314. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L);
  101315. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L);
  101316. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p);
  101317. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L);
  101318. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  101319. #endif
  101320. /*** End of inlined file: window.h ***/
  101321. #ifndef FLaC__INLINE
  101322. #define FLaC__INLINE
  101323. #endif
  101324. #ifdef min
  101325. #undef min
  101326. #endif
  101327. #define min(x,y) ((x)<(y)?(x):(y))
  101328. #ifdef max
  101329. #undef max
  101330. #endif
  101331. #define max(x,y) ((x)>(y)?(x):(y))
  101332. /* Exact Rice codeword length calculation is off by default. The simple
  101333. * (and fast) estimation (of how many bits a residual value will be
  101334. * encoded with) in this encoder is very good, almost always yielding
  101335. * compression within 0.1% of exact calculation.
  101336. */
  101337. #undef EXACT_RICE_BITS_CALCULATION
  101338. /* Rice parameter searching is off by default. The simple (and fast)
  101339. * parameter estimation in this encoder is very good, almost always
  101340. * yielding compression within 0.1% of the optimal parameters.
  101341. */
  101342. #undef ENABLE_RICE_PARAMETER_SEARCH
  101343. typedef struct {
  101344. FLAC__int32 *data[FLAC__MAX_CHANNELS];
  101345. unsigned size; /* of each data[] in samples */
  101346. unsigned tail;
  101347. } verify_input_fifo;
  101348. typedef struct {
  101349. const FLAC__byte *data;
  101350. unsigned capacity;
  101351. unsigned bytes;
  101352. } verify_output;
  101353. typedef enum {
  101354. ENCODER_IN_MAGIC = 0,
  101355. ENCODER_IN_METADATA = 1,
  101356. ENCODER_IN_AUDIO = 2
  101357. } EncoderStateHint;
  101358. static struct CompressionLevels {
  101359. FLAC__bool do_mid_side_stereo;
  101360. FLAC__bool loose_mid_side_stereo;
  101361. unsigned max_lpc_order;
  101362. unsigned qlp_coeff_precision;
  101363. FLAC__bool do_qlp_coeff_prec_search;
  101364. FLAC__bool do_escape_coding;
  101365. FLAC__bool do_exhaustive_model_search;
  101366. unsigned min_residual_partition_order;
  101367. unsigned max_residual_partition_order;
  101368. unsigned rice_parameter_search_dist;
  101369. } compression_levels_[] = {
  101370. { false, false, 0, 0, false, false, false, 0, 3, 0 },
  101371. { true , true , 0, 0, false, false, false, 0, 3, 0 },
  101372. { true , false, 0, 0, false, false, false, 0, 3, 0 },
  101373. { false, false, 6, 0, false, false, false, 0, 4, 0 },
  101374. { true , true , 8, 0, false, false, false, 0, 4, 0 },
  101375. { true , false, 8, 0, false, false, false, 0, 5, 0 },
  101376. { true , false, 8, 0, false, false, false, 0, 6, 0 },
  101377. { true , false, 8, 0, false, false, true , 0, 6, 0 },
  101378. { true , false, 12, 0, false, false, true , 0, 6, 0 }
  101379. };
  101380. /***********************************************************************
  101381. *
  101382. * Private class method prototypes
  101383. *
  101384. ***********************************************************************/
  101385. static void set_defaults_enc(FLAC__StreamEncoder *encoder);
  101386. static void free_(FLAC__StreamEncoder *encoder);
  101387. static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
  101388. static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
  101389. static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
  101390. static void update_metadata_(const FLAC__StreamEncoder *encoder);
  101391. #if FLAC__HAS_OGG
  101392. static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
  101393. #endif
  101394. static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
  101395. static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
  101396. static FLAC__bool process_subframe_(
  101397. FLAC__StreamEncoder *encoder,
  101398. unsigned min_partition_order,
  101399. unsigned max_partition_order,
  101400. const FLAC__FrameHeader *frame_header,
  101401. unsigned subframe_bps,
  101402. const FLAC__int32 integer_signal[],
  101403. FLAC__Subframe *subframe[2],
  101404. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  101405. FLAC__int32 *residual[2],
  101406. unsigned *best_subframe,
  101407. unsigned *best_bits
  101408. );
  101409. static FLAC__bool add_subframe_(
  101410. FLAC__StreamEncoder *encoder,
  101411. unsigned blocksize,
  101412. unsigned subframe_bps,
  101413. const FLAC__Subframe *subframe,
  101414. FLAC__BitWriter *frame
  101415. );
  101416. static unsigned evaluate_constant_subframe_(
  101417. FLAC__StreamEncoder *encoder,
  101418. const FLAC__int32 signal,
  101419. unsigned blocksize,
  101420. unsigned subframe_bps,
  101421. FLAC__Subframe *subframe
  101422. );
  101423. static unsigned evaluate_fixed_subframe_(
  101424. FLAC__StreamEncoder *encoder,
  101425. const FLAC__int32 signal[],
  101426. FLAC__int32 residual[],
  101427. FLAC__uint64 abs_residual_partition_sums[],
  101428. unsigned raw_bits_per_partition[],
  101429. unsigned blocksize,
  101430. unsigned subframe_bps,
  101431. unsigned order,
  101432. unsigned rice_parameter,
  101433. unsigned rice_parameter_limit,
  101434. unsigned min_partition_order,
  101435. unsigned max_partition_order,
  101436. FLAC__bool do_escape_coding,
  101437. unsigned rice_parameter_search_dist,
  101438. FLAC__Subframe *subframe,
  101439. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  101440. );
  101441. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101442. static unsigned evaluate_lpc_subframe_(
  101443. FLAC__StreamEncoder *encoder,
  101444. const FLAC__int32 signal[],
  101445. FLAC__int32 residual[],
  101446. FLAC__uint64 abs_residual_partition_sums[],
  101447. unsigned raw_bits_per_partition[],
  101448. const FLAC__real lp_coeff[],
  101449. unsigned blocksize,
  101450. unsigned subframe_bps,
  101451. unsigned order,
  101452. unsigned qlp_coeff_precision,
  101453. unsigned rice_parameter,
  101454. unsigned rice_parameter_limit,
  101455. unsigned min_partition_order,
  101456. unsigned max_partition_order,
  101457. FLAC__bool do_escape_coding,
  101458. unsigned rice_parameter_search_dist,
  101459. FLAC__Subframe *subframe,
  101460. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  101461. );
  101462. #endif
  101463. static unsigned evaluate_verbatim_subframe_(
  101464. FLAC__StreamEncoder *encoder,
  101465. const FLAC__int32 signal[],
  101466. unsigned blocksize,
  101467. unsigned subframe_bps,
  101468. FLAC__Subframe *subframe
  101469. );
  101470. static unsigned find_best_partition_order_(
  101471. struct FLAC__StreamEncoderPrivate *private_,
  101472. const FLAC__int32 residual[],
  101473. FLAC__uint64 abs_residual_partition_sums[],
  101474. unsigned raw_bits_per_partition[],
  101475. unsigned residual_samples,
  101476. unsigned predictor_order,
  101477. unsigned rice_parameter,
  101478. unsigned rice_parameter_limit,
  101479. unsigned min_partition_order,
  101480. unsigned max_partition_order,
  101481. unsigned bps,
  101482. FLAC__bool do_escape_coding,
  101483. unsigned rice_parameter_search_dist,
  101484. FLAC__EntropyCodingMethod *best_ecm
  101485. );
  101486. static void precompute_partition_info_sums_(
  101487. const FLAC__int32 residual[],
  101488. FLAC__uint64 abs_residual_partition_sums[],
  101489. unsigned residual_samples,
  101490. unsigned predictor_order,
  101491. unsigned min_partition_order,
  101492. unsigned max_partition_order,
  101493. unsigned bps
  101494. );
  101495. static void precompute_partition_info_escapes_(
  101496. const FLAC__int32 residual[],
  101497. unsigned raw_bits_per_partition[],
  101498. unsigned residual_samples,
  101499. unsigned predictor_order,
  101500. unsigned min_partition_order,
  101501. unsigned max_partition_order
  101502. );
  101503. static FLAC__bool set_partitioned_rice_(
  101504. #ifdef EXACT_RICE_BITS_CALCULATION
  101505. const FLAC__int32 residual[],
  101506. #endif
  101507. const FLAC__uint64 abs_residual_partition_sums[],
  101508. const unsigned raw_bits_per_partition[],
  101509. const unsigned residual_samples,
  101510. const unsigned predictor_order,
  101511. const unsigned suggested_rice_parameter,
  101512. const unsigned rice_parameter_limit,
  101513. const unsigned rice_parameter_search_dist,
  101514. const unsigned partition_order,
  101515. const FLAC__bool search_for_escapes,
  101516. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  101517. unsigned *bits
  101518. );
  101519. static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
  101520. /* verify-related routines: */
  101521. static void append_to_verify_fifo_(
  101522. verify_input_fifo *fifo,
  101523. const FLAC__int32 * const input[],
  101524. unsigned input_offset,
  101525. unsigned channels,
  101526. unsigned wide_samples
  101527. );
  101528. static void append_to_verify_fifo_interleaved_(
  101529. verify_input_fifo *fifo,
  101530. const FLAC__int32 input[],
  101531. unsigned input_offset,
  101532. unsigned channels,
  101533. unsigned wide_samples
  101534. );
  101535. static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  101536. static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  101537. static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  101538. static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  101539. static FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  101540. static FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  101541. static FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  101542. 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);
  101543. static FILE *get_binary_stdout_(void);
  101544. /***********************************************************************
  101545. *
  101546. * Private class data
  101547. *
  101548. ***********************************************************************/
  101549. typedef struct FLAC__StreamEncoderPrivate {
  101550. unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
  101551. FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
  101552. FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
  101553. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101554. FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) the floating-point version of the input signal */
  101555. FLAC__real *real_signal_mid_side[2]; /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
  101556. FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
  101557. FLAC__real *windowed_signal; /* the integer_signal[] * current window[] */
  101558. #endif
  101559. unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
  101560. unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
  101561. FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
  101562. FLAC__int32 *residual_workspace_mid_side[2][2];
  101563. FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
  101564. FLAC__Subframe subframe_workspace_mid_side[2][2];
  101565. FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
  101566. FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
  101567. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
  101568. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
  101569. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
  101570. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
  101571. unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */
  101572. unsigned best_subframe_mid_side[2];
  101573. unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
  101574. unsigned best_subframe_bits_mid_side[2];
  101575. FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
  101576. unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
  101577. FLAC__BitWriter *frame; /* the current frame being worked on */
  101578. unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
  101579. unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
  101580. FLAC__ChannelAssignment last_channel_assignment;
  101581. FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
  101582. FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
  101583. unsigned current_sample_number;
  101584. unsigned current_frame_number;
  101585. FLAC__MD5Context md5context;
  101586. FLAC__CPUInfo cpuinfo;
  101587. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101588. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  101589. #else
  101590. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  101591. #endif
  101592. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101593. void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  101594. 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[]);
  101595. 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[]);
  101596. 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[]);
  101597. #endif
  101598. FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
  101599. FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
  101600. FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
  101601. FLAC__bool disable_constant_subframes;
  101602. FLAC__bool disable_fixed_subframes;
  101603. FLAC__bool disable_verbatim_subframes;
  101604. #if FLAC__HAS_OGG
  101605. FLAC__bool is_ogg;
  101606. #endif
  101607. FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
  101608. FLAC__StreamEncoderSeekCallback seek_callback;
  101609. FLAC__StreamEncoderTellCallback tell_callback;
  101610. FLAC__StreamEncoderWriteCallback write_callback;
  101611. FLAC__StreamEncoderMetadataCallback metadata_callback;
  101612. FLAC__StreamEncoderProgressCallback progress_callback;
  101613. void *client_data;
  101614. unsigned first_seekpoint_to_check;
  101615. FILE *file; /* only used when encoding to a file */
  101616. FLAC__uint64 bytes_written;
  101617. FLAC__uint64 samples_written;
  101618. unsigned frames_written;
  101619. unsigned total_frames_estimate;
  101620. /* unaligned (original) pointers to allocated data */
  101621. FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
  101622. FLAC__int32 *integer_signal_mid_side_unaligned[2];
  101623. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101624. FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
  101625. FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
  101626. FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
  101627. FLAC__real *windowed_signal_unaligned;
  101628. #endif
  101629. FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
  101630. FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
  101631. FLAC__uint64 *abs_residual_partition_sums_unaligned;
  101632. unsigned *raw_bits_per_partition_unaligned;
  101633. /*
  101634. * These fields have been moved here from private function local
  101635. * declarations merely to save stack space during encoding.
  101636. */
  101637. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101638. FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
  101639. #endif
  101640. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
  101641. /*
  101642. * The data for the verify section
  101643. */
  101644. struct {
  101645. FLAC__StreamDecoder *decoder;
  101646. EncoderStateHint state_hint;
  101647. FLAC__bool needs_magic_hack;
  101648. verify_input_fifo input_fifo;
  101649. verify_output output;
  101650. struct {
  101651. FLAC__uint64 absolute_sample;
  101652. unsigned frame_number;
  101653. unsigned channel;
  101654. unsigned sample;
  101655. FLAC__int32 expected;
  101656. FLAC__int32 got;
  101657. } error_stats;
  101658. } verify;
  101659. FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
  101660. } FLAC__StreamEncoderPrivate;
  101661. /***********************************************************************
  101662. *
  101663. * Public static class data
  101664. *
  101665. ***********************************************************************/
  101666. FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
  101667. "FLAC__STREAM_ENCODER_OK",
  101668. "FLAC__STREAM_ENCODER_UNINITIALIZED",
  101669. "FLAC__STREAM_ENCODER_OGG_ERROR",
  101670. "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
  101671. "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
  101672. "FLAC__STREAM_ENCODER_CLIENT_ERROR",
  101673. "FLAC__STREAM_ENCODER_IO_ERROR",
  101674. "FLAC__STREAM_ENCODER_FRAMING_ERROR",
  101675. "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
  101676. };
  101677. FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
  101678. "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
  101679. "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
  101680. "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  101681. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
  101682. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
  101683. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
  101684. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
  101685. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
  101686. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
  101687. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
  101688. "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
  101689. "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
  101690. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
  101691. "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
  101692. };
  101693. FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
  101694. "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
  101695. "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
  101696. "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
  101697. "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
  101698. };
  101699. FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
  101700. "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
  101701. "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
  101702. };
  101703. FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
  101704. "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
  101705. "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
  101706. "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
  101707. };
  101708. FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
  101709. "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
  101710. "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
  101711. "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
  101712. };
  101713. /* Number of samples that will be overread to watch for end of stream. By
  101714. * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
  101715. * always try to read blocksize+1 samples before encoding a block, so that
  101716. * even if the stream has a total sample count that is an integral multiple
  101717. * of the blocksize, we will still notice when we are encoding the last
  101718. * block. This is needed, for example, to correctly set the end-of-stream
  101719. * marker in Ogg FLAC.
  101720. *
  101721. * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
  101722. * not really any reason to change it.
  101723. */
  101724. static const unsigned OVERREAD_ = 1;
  101725. /***********************************************************************
  101726. *
  101727. * Class constructor/destructor
  101728. *
  101729. */
  101730. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
  101731. {
  101732. FLAC__StreamEncoder *encoder;
  101733. unsigned i;
  101734. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  101735. encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
  101736. if(encoder == 0) {
  101737. return 0;
  101738. }
  101739. encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
  101740. if(encoder->protected_ == 0) {
  101741. free(encoder);
  101742. return 0;
  101743. }
  101744. encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
  101745. if(encoder->private_ == 0) {
  101746. free(encoder->protected_);
  101747. free(encoder);
  101748. return 0;
  101749. }
  101750. encoder->private_->frame = FLAC__bitwriter_new();
  101751. if(encoder->private_->frame == 0) {
  101752. free(encoder->private_);
  101753. free(encoder->protected_);
  101754. free(encoder);
  101755. return 0;
  101756. }
  101757. encoder->private_->file = 0;
  101758. set_defaults_enc(encoder);
  101759. encoder->private_->is_being_deleted = false;
  101760. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  101761. encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
  101762. encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
  101763. }
  101764. for(i = 0; i < 2; i++) {
  101765. encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
  101766. encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
  101767. }
  101768. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  101769. encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
  101770. encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
  101771. }
  101772. for(i = 0; i < 2; i++) {
  101773. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
  101774. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
  101775. }
  101776. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  101777. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  101778. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  101779. }
  101780. for(i = 0; i < 2; i++) {
  101781. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  101782. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  101783. }
  101784. for(i = 0; i < 2; i++)
  101785. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
  101786. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  101787. return encoder;
  101788. }
  101789. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
  101790. {
  101791. unsigned i;
  101792. FLAC__ASSERT(0 != encoder);
  101793. FLAC__ASSERT(0 != encoder->protected_);
  101794. FLAC__ASSERT(0 != encoder->private_);
  101795. FLAC__ASSERT(0 != encoder->private_->frame);
  101796. encoder->private_->is_being_deleted = true;
  101797. (void)FLAC__stream_encoder_finish(encoder);
  101798. if(0 != encoder->private_->verify.decoder)
  101799. FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
  101800. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  101801. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  101802. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  101803. }
  101804. for(i = 0; i < 2; i++) {
  101805. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  101806. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  101807. }
  101808. for(i = 0; i < 2; i++)
  101809. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
  101810. FLAC__bitwriter_delete(encoder->private_->frame);
  101811. free(encoder->private_);
  101812. free(encoder->protected_);
  101813. free(encoder);
  101814. }
  101815. /***********************************************************************
  101816. *
  101817. * Public class methods
  101818. *
  101819. ***********************************************************************/
  101820. static FLAC__StreamEncoderInitStatus init_stream_internal_enc(
  101821. FLAC__StreamEncoder *encoder,
  101822. FLAC__StreamEncoderReadCallback read_callback,
  101823. FLAC__StreamEncoderWriteCallback write_callback,
  101824. FLAC__StreamEncoderSeekCallback seek_callback,
  101825. FLAC__StreamEncoderTellCallback tell_callback,
  101826. FLAC__StreamEncoderMetadataCallback metadata_callback,
  101827. void *client_data,
  101828. FLAC__bool is_ogg
  101829. )
  101830. {
  101831. unsigned i;
  101832. FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
  101833. FLAC__ASSERT(0 != encoder);
  101834. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  101835. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  101836. #if !FLAC__HAS_OGG
  101837. if(is_ogg)
  101838. return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  101839. #endif
  101840. if(0 == write_callback || (seek_callback && 0 == tell_callback))
  101841. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
  101842. if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
  101843. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
  101844. if(encoder->protected_->channels != 2) {
  101845. encoder->protected_->do_mid_side_stereo = false;
  101846. encoder->protected_->loose_mid_side_stereo = false;
  101847. }
  101848. else if(!encoder->protected_->do_mid_side_stereo)
  101849. encoder->protected_->loose_mid_side_stereo = false;
  101850. if(encoder->protected_->bits_per_sample >= 32)
  101851. encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
  101852. if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
  101853. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
  101854. if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
  101855. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
  101856. if(encoder->protected_->blocksize == 0) {
  101857. if(encoder->protected_->max_lpc_order == 0)
  101858. encoder->protected_->blocksize = 1152;
  101859. else
  101860. encoder->protected_->blocksize = 4096;
  101861. }
  101862. if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
  101863. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
  101864. if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
  101865. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
  101866. if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
  101867. return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
  101868. if(encoder->protected_->qlp_coeff_precision == 0) {
  101869. if(encoder->protected_->bits_per_sample < 16) {
  101870. /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
  101871. /* @@@ until then we'll make a guess */
  101872. encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
  101873. }
  101874. else if(encoder->protected_->bits_per_sample == 16) {
  101875. if(encoder->protected_->blocksize <= 192)
  101876. encoder->protected_->qlp_coeff_precision = 7;
  101877. else if(encoder->protected_->blocksize <= 384)
  101878. encoder->protected_->qlp_coeff_precision = 8;
  101879. else if(encoder->protected_->blocksize <= 576)
  101880. encoder->protected_->qlp_coeff_precision = 9;
  101881. else if(encoder->protected_->blocksize <= 1152)
  101882. encoder->protected_->qlp_coeff_precision = 10;
  101883. else if(encoder->protected_->blocksize <= 2304)
  101884. encoder->protected_->qlp_coeff_precision = 11;
  101885. else if(encoder->protected_->blocksize <= 4608)
  101886. encoder->protected_->qlp_coeff_precision = 12;
  101887. else
  101888. encoder->protected_->qlp_coeff_precision = 13;
  101889. }
  101890. else {
  101891. if(encoder->protected_->blocksize <= 384)
  101892. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
  101893. else if(encoder->protected_->blocksize <= 1152)
  101894. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
  101895. else
  101896. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  101897. }
  101898. FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
  101899. }
  101900. else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
  101901. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
  101902. if(encoder->protected_->streamable_subset) {
  101903. if(
  101904. encoder->protected_->blocksize != 192 &&
  101905. encoder->protected_->blocksize != 576 &&
  101906. encoder->protected_->blocksize != 1152 &&
  101907. encoder->protected_->blocksize != 2304 &&
  101908. encoder->protected_->blocksize != 4608 &&
  101909. encoder->protected_->blocksize != 256 &&
  101910. encoder->protected_->blocksize != 512 &&
  101911. encoder->protected_->blocksize != 1024 &&
  101912. encoder->protected_->blocksize != 2048 &&
  101913. encoder->protected_->blocksize != 4096 &&
  101914. encoder->protected_->blocksize != 8192 &&
  101915. encoder->protected_->blocksize != 16384
  101916. )
  101917. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  101918. if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
  101919. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  101920. if(
  101921. encoder->protected_->bits_per_sample != 8 &&
  101922. encoder->protected_->bits_per_sample != 12 &&
  101923. encoder->protected_->bits_per_sample != 16 &&
  101924. encoder->protected_->bits_per_sample != 20 &&
  101925. encoder->protected_->bits_per_sample != 24
  101926. )
  101927. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  101928. if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
  101929. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  101930. if(
  101931. encoder->protected_->sample_rate <= 48000 &&
  101932. (
  101933. encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
  101934. encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
  101935. )
  101936. ) {
  101937. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  101938. }
  101939. }
  101940. if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  101941. encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
  101942. if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
  101943. encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
  101944. #if FLAC__HAS_OGG
  101945. /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
  101946. if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
  101947. unsigned i;
  101948. for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
  101949. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  101950. FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
  101951. for( ; i > 0; i--)
  101952. encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
  101953. encoder->protected_->metadata[0] = vc;
  101954. break;
  101955. }
  101956. }
  101957. }
  101958. #endif
  101959. /* keep track of any SEEKTABLE block */
  101960. if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
  101961. unsigned i;
  101962. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  101963. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  101964. encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
  101965. break; /* take only the first one */
  101966. }
  101967. }
  101968. }
  101969. /* validate metadata */
  101970. if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
  101971. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  101972. metadata_has_seektable = false;
  101973. metadata_has_vorbis_comment = false;
  101974. metadata_picture_has_type1 = false;
  101975. metadata_picture_has_type2 = false;
  101976. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  101977. const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
  101978. if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
  101979. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  101980. else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  101981. if(metadata_has_seektable) /* only one is allowed */
  101982. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  101983. metadata_has_seektable = true;
  101984. if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
  101985. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  101986. }
  101987. else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  101988. if(metadata_has_vorbis_comment) /* only one is allowed */
  101989. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  101990. metadata_has_vorbis_comment = true;
  101991. }
  101992. else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
  101993. if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
  101994. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  101995. }
  101996. else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
  101997. if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
  101998. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  101999. if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
  102000. if(metadata_picture_has_type1) /* there should only be 1 per stream */
  102001. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102002. metadata_picture_has_type1 = true;
  102003. /* standard icon must be 32x32 pixel PNG */
  102004. if(
  102005. m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
  102006. (
  102007. (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
  102008. m->data.picture.width != 32 ||
  102009. m->data.picture.height != 32
  102010. )
  102011. )
  102012. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102013. }
  102014. else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
  102015. if(metadata_picture_has_type2) /* there should only be 1 per stream */
  102016. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102017. metadata_picture_has_type2 = true;
  102018. }
  102019. }
  102020. }
  102021. encoder->private_->input_capacity = 0;
  102022. for(i = 0; i < encoder->protected_->channels; i++) {
  102023. encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
  102024. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102025. encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
  102026. #endif
  102027. }
  102028. for(i = 0; i < 2; i++) {
  102029. encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
  102030. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102031. encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
  102032. #endif
  102033. }
  102034. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102035. for(i = 0; i < encoder->protected_->num_apodizations; i++)
  102036. encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
  102037. encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
  102038. #endif
  102039. for(i = 0; i < encoder->protected_->channels; i++) {
  102040. encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
  102041. encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
  102042. encoder->private_->best_subframe[i] = 0;
  102043. }
  102044. for(i = 0; i < 2; i++) {
  102045. encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
  102046. encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
  102047. encoder->private_->best_subframe_mid_side[i] = 0;
  102048. }
  102049. encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
  102050. encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
  102051. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102052. encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
  102053. #else
  102054. /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
  102055. /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply&divide by hand */
  102056. FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
  102057. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
  102058. FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
  102059. FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
  102060. 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);
  102061. #endif
  102062. if(encoder->private_->loose_mid_side_stereo_frames == 0)
  102063. encoder->private_->loose_mid_side_stereo_frames = 1;
  102064. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  102065. encoder->private_->current_sample_number = 0;
  102066. encoder->private_->current_frame_number = 0;
  102067. encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
  102068. 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? */
  102069. encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
  102070. /*
  102071. * get the CPU info and set the function pointers
  102072. */
  102073. FLAC__cpu_info(&encoder->private_->cpuinfo);
  102074. /* first default to the non-asm routines */
  102075. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102076. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
  102077. #endif
  102078. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
  102079. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102080. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
  102081. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
  102082. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
  102083. #endif
  102084. /* now override with asm where appropriate */
  102085. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102086. # ifndef FLAC__NO_ASM
  102087. if(encoder->private_->cpuinfo.use_asm) {
  102088. # ifdef FLAC__CPU_IA32
  102089. FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  102090. # ifdef FLAC__HAS_NASM
  102091. if(encoder->private_->cpuinfo.data.ia32.sse) {
  102092. if(encoder->protected_->max_lpc_order < 4)
  102093. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
  102094. else if(encoder->protected_->max_lpc_order < 8)
  102095. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
  102096. else if(encoder->protected_->max_lpc_order < 12)
  102097. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
  102098. else
  102099. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  102100. }
  102101. else if(encoder->private_->cpuinfo.data.ia32._3dnow)
  102102. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
  102103. else
  102104. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  102105. if(encoder->private_->cpuinfo.data.ia32.mmx) {
  102106. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  102107. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
  102108. }
  102109. else {
  102110. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  102111. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  102112. }
  102113. if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
  102114. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
  102115. # endif /* FLAC__HAS_NASM */
  102116. # endif /* FLAC__CPU_IA32 */
  102117. }
  102118. # endif /* !FLAC__NO_ASM */
  102119. #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
  102120. /* finally override based on wide-ness if necessary */
  102121. if(encoder->private_->use_wide_by_block) {
  102122. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
  102123. }
  102124. /* set state to OK; from here on, errors are fatal and we'll override the state then */
  102125. encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
  102126. #if FLAC__HAS_OGG
  102127. encoder->private_->is_ogg = is_ogg;
  102128. if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
  102129. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  102130. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102131. }
  102132. #endif
  102133. encoder->private_->read_callback = read_callback;
  102134. encoder->private_->write_callback = write_callback;
  102135. encoder->private_->seek_callback = seek_callback;
  102136. encoder->private_->tell_callback = tell_callback;
  102137. encoder->private_->metadata_callback = metadata_callback;
  102138. encoder->private_->client_data = client_data;
  102139. if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
  102140. /* the above function sets the state for us in case of an error */
  102141. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102142. }
  102143. if(!FLAC__bitwriter_init(encoder->private_->frame)) {
  102144. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  102145. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102146. }
  102147. /*
  102148. * Set up the verify stuff if necessary
  102149. */
  102150. if(encoder->protected_->verify) {
  102151. /*
  102152. * First, set up the fifo which will hold the
  102153. * original signal to compare against
  102154. */
  102155. encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
  102156. for(i = 0; i < encoder->protected_->channels; i++) {
  102157. 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))) {
  102158. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  102159. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102160. }
  102161. }
  102162. encoder->private_->verify.input_fifo.tail = 0;
  102163. /*
  102164. * Now set up a stream decoder for verification
  102165. */
  102166. encoder->private_->verify.decoder = FLAC__stream_decoder_new();
  102167. if(0 == encoder->private_->verify.decoder) {
  102168. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  102169. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102170. }
  102171. 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) {
  102172. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  102173. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102174. }
  102175. }
  102176. encoder->private_->verify.error_stats.absolute_sample = 0;
  102177. encoder->private_->verify.error_stats.frame_number = 0;
  102178. encoder->private_->verify.error_stats.channel = 0;
  102179. encoder->private_->verify.error_stats.sample = 0;
  102180. encoder->private_->verify.error_stats.expected = 0;
  102181. encoder->private_->verify.error_stats.got = 0;
  102182. /*
  102183. * These must be done before we write any metadata, because that
  102184. * calls the write_callback, which uses these values.
  102185. */
  102186. encoder->private_->first_seekpoint_to_check = 0;
  102187. encoder->private_->samples_written = 0;
  102188. encoder->protected_->streaminfo_offset = 0;
  102189. encoder->protected_->seektable_offset = 0;
  102190. encoder->protected_->audio_offset = 0;
  102191. /*
  102192. * write the stream header
  102193. */
  102194. if(encoder->protected_->verify)
  102195. encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
  102196. if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
  102197. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102198. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102199. }
  102200. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  102201. /* the above function sets the state for us in case of an error */
  102202. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102203. }
  102204. /*
  102205. * write the STREAMINFO metadata block
  102206. */
  102207. if(encoder->protected_->verify)
  102208. encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
  102209. encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
  102210. encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
  102211. encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
  102212. encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
  102213. encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
  102214. encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
  102215. encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
  102216. encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
  102217. encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
  102218. encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
  102219. encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
  102220. memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
  102221. if(encoder->protected_->do_md5)
  102222. FLAC__MD5Init(&encoder->private_->md5context);
  102223. if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
  102224. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102225. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102226. }
  102227. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  102228. /* the above function sets the state for us in case of an error */
  102229. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102230. }
  102231. /*
  102232. * Now that the STREAMINFO block is written, we can init this to an
  102233. * absurdly-high value...
  102234. */
  102235. encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
  102236. /* ... and clear this to 0 */
  102237. encoder->private_->streaminfo.data.stream_info.total_samples = 0;
  102238. /*
  102239. * Check to see if the supplied metadata contains a VORBIS_COMMENT;
  102240. * if not, we will write an empty one (FLAC__add_metadata_block()
  102241. * automatically supplies the vendor string).
  102242. *
  102243. * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
  102244. * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
  102245. * true it will have already insured that the metadata list is properly
  102246. * ordered.)
  102247. */
  102248. if(!metadata_has_vorbis_comment) {
  102249. FLAC__StreamMetadata vorbis_comment;
  102250. vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
  102251. vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
  102252. vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
  102253. vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
  102254. vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
  102255. vorbis_comment.data.vorbis_comment.num_comments = 0;
  102256. vorbis_comment.data.vorbis_comment.comments = 0;
  102257. if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
  102258. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102259. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102260. }
  102261. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  102262. /* the above function sets the state for us in case of an error */
  102263. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102264. }
  102265. }
  102266. /*
  102267. * write the user's metadata blocks
  102268. */
  102269. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  102270. encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
  102271. if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
  102272. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102273. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102274. }
  102275. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  102276. /* the above function sets the state for us in case of an error */
  102277. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102278. }
  102279. }
  102280. /* now that all the metadata is written, we save the stream offset */
  102281. 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 */
  102282. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  102283. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102284. }
  102285. if(encoder->protected_->verify)
  102286. encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
  102287. return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  102288. }
  102289. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
  102290. FLAC__StreamEncoder *encoder,
  102291. FLAC__StreamEncoderWriteCallback write_callback,
  102292. FLAC__StreamEncoderSeekCallback seek_callback,
  102293. FLAC__StreamEncoderTellCallback tell_callback,
  102294. FLAC__StreamEncoderMetadataCallback metadata_callback,
  102295. void *client_data
  102296. )
  102297. {
  102298. return init_stream_internal_enc(
  102299. encoder,
  102300. /*read_callback=*/0,
  102301. write_callback,
  102302. seek_callback,
  102303. tell_callback,
  102304. metadata_callback,
  102305. client_data,
  102306. /*is_ogg=*/false
  102307. );
  102308. }
  102309. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
  102310. FLAC__StreamEncoder *encoder,
  102311. FLAC__StreamEncoderReadCallback read_callback,
  102312. FLAC__StreamEncoderWriteCallback write_callback,
  102313. FLAC__StreamEncoderSeekCallback seek_callback,
  102314. FLAC__StreamEncoderTellCallback tell_callback,
  102315. FLAC__StreamEncoderMetadataCallback metadata_callback,
  102316. void *client_data
  102317. )
  102318. {
  102319. return init_stream_internal_enc(
  102320. encoder,
  102321. read_callback,
  102322. write_callback,
  102323. seek_callback,
  102324. tell_callback,
  102325. metadata_callback,
  102326. client_data,
  102327. /*is_ogg=*/true
  102328. );
  102329. }
  102330. static FLAC__StreamEncoderInitStatus init_FILE_internal_enc(
  102331. FLAC__StreamEncoder *encoder,
  102332. FILE *file,
  102333. FLAC__StreamEncoderProgressCallback progress_callback,
  102334. void *client_data,
  102335. FLAC__bool is_ogg
  102336. )
  102337. {
  102338. FLAC__StreamEncoderInitStatus init_status;
  102339. FLAC__ASSERT(0 != encoder);
  102340. FLAC__ASSERT(0 != file);
  102341. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102342. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  102343. /* double protection */
  102344. if(file == 0) {
  102345. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  102346. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102347. }
  102348. /*
  102349. * To make sure that our file does not go unclosed after an error, we
  102350. * must assign the FILE pointer before any further error can occur in
  102351. * this routine.
  102352. */
  102353. if(file == stdout)
  102354. file = get_binary_stdout_(); /* just to be safe */
  102355. encoder->private_->file = file;
  102356. encoder->private_->progress_callback = progress_callback;
  102357. encoder->private_->bytes_written = 0;
  102358. encoder->private_->samples_written = 0;
  102359. encoder->private_->frames_written = 0;
  102360. init_status = init_stream_internal_enc(
  102361. encoder,
  102362. encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_enc : 0,
  102363. file_write_callback_,
  102364. encoder->private_->file == stdout? 0 : file_seek_callback_enc,
  102365. encoder->private_->file == stdout? 0 : file_tell_callback_enc,
  102366. /*metadata_callback=*/0,
  102367. client_data,
  102368. is_ogg
  102369. );
  102370. if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
  102371. /* the above function sets the state for us in case of an error */
  102372. return init_status;
  102373. }
  102374. {
  102375. unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  102376. FLAC__ASSERT(blocksize != 0);
  102377. encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
  102378. }
  102379. return init_status;
  102380. }
  102381. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
  102382. FLAC__StreamEncoder *encoder,
  102383. FILE *file,
  102384. FLAC__StreamEncoderProgressCallback progress_callback,
  102385. void *client_data
  102386. )
  102387. {
  102388. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
  102389. }
  102390. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
  102391. FLAC__StreamEncoder *encoder,
  102392. FILE *file,
  102393. FLAC__StreamEncoderProgressCallback progress_callback,
  102394. void *client_data
  102395. )
  102396. {
  102397. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
  102398. }
  102399. static FLAC__StreamEncoderInitStatus init_file_internal_enc(
  102400. FLAC__StreamEncoder *encoder,
  102401. const char *filename,
  102402. FLAC__StreamEncoderProgressCallback progress_callback,
  102403. void *client_data,
  102404. FLAC__bool is_ogg
  102405. )
  102406. {
  102407. FILE *file;
  102408. FLAC__ASSERT(0 != encoder);
  102409. /*
  102410. * To make sure that our file does not go unclosed after an error, we
  102411. * have to do the same entrance checks here that are later performed
  102412. * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
  102413. */
  102414. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102415. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  102416. file = filename? fopen(filename, "w+b") : stdout;
  102417. if(file == 0) {
  102418. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  102419. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102420. }
  102421. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, is_ogg);
  102422. }
  102423. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
  102424. FLAC__StreamEncoder *encoder,
  102425. const char *filename,
  102426. FLAC__StreamEncoderProgressCallback progress_callback,
  102427. void *client_data
  102428. )
  102429. {
  102430. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
  102431. }
  102432. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
  102433. FLAC__StreamEncoder *encoder,
  102434. const char *filename,
  102435. FLAC__StreamEncoderProgressCallback progress_callback,
  102436. void *client_data
  102437. )
  102438. {
  102439. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
  102440. }
  102441. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
  102442. {
  102443. FLAC__bool error = false;
  102444. FLAC__ASSERT(0 != encoder);
  102445. FLAC__ASSERT(0 != encoder->private_);
  102446. FLAC__ASSERT(0 != encoder->protected_);
  102447. if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
  102448. return true;
  102449. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
  102450. if(encoder->private_->current_sample_number != 0) {
  102451. const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
  102452. encoder->protected_->blocksize = encoder->private_->current_sample_number;
  102453. if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
  102454. error = true;
  102455. }
  102456. }
  102457. if(encoder->protected_->do_md5)
  102458. FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
  102459. if(!encoder->private_->is_being_deleted) {
  102460. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
  102461. if(encoder->private_->seek_callback) {
  102462. #if FLAC__HAS_OGG
  102463. if(encoder->private_->is_ogg)
  102464. update_ogg_metadata_(encoder);
  102465. else
  102466. #endif
  102467. update_metadata_(encoder);
  102468. /* check if an error occurred while updating metadata */
  102469. if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
  102470. error = true;
  102471. }
  102472. if(encoder->private_->metadata_callback)
  102473. encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
  102474. }
  102475. if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
  102476. if(!error)
  102477. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  102478. error = true;
  102479. }
  102480. }
  102481. if(0 != encoder->private_->file) {
  102482. if(encoder->private_->file != stdout)
  102483. fclose(encoder->private_->file);
  102484. encoder->private_->file = 0;
  102485. }
  102486. #if FLAC__HAS_OGG
  102487. if(encoder->private_->is_ogg)
  102488. FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
  102489. #endif
  102490. free_(encoder);
  102491. set_defaults_enc(encoder);
  102492. if(!error)
  102493. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  102494. return !error;
  102495. }
  102496. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
  102497. {
  102498. FLAC__ASSERT(0 != encoder);
  102499. FLAC__ASSERT(0 != encoder->private_);
  102500. FLAC__ASSERT(0 != encoder->protected_);
  102501. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102502. return false;
  102503. #if FLAC__HAS_OGG
  102504. /* can't check encoder->private_->is_ogg since that's not set until init time */
  102505. FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
  102506. return true;
  102507. #else
  102508. (void)value;
  102509. return false;
  102510. #endif
  102511. }
  102512. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102513. {
  102514. FLAC__ASSERT(0 != encoder);
  102515. FLAC__ASSERT(0 != encoder->private_);
  102516. FLAC__ASSERT(0 != encoder->protected_);
  102517. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102518. return false;
  102519. #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  102520. encoder->protected_->verify = value;
  102521. #endif
  102522. return true;
  102523. }
  102524. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102525. {
  102526. FLAC__ASSERT(0 != encoder);
  102527. FLAC__ASSERT(0 != encoder->private_);
  102528. FLAC__ASSERT(0 != encoder->protected_);
  102529. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102530. return false;
  102531. encoder->protected_->streamable_subset = value;
  102532. return true;
  102533. }
  102534. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102535. {
  102536. FLAC__ASSERT(0 != encoder);
  102537. FLAC__ASSERT(0 != encoder->private_);
  102538. FLAC__ASSERT(0 != encoder->protected_);
  102539. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102540. return false;
  102541. encoder->protected_->do_md5 = value;
  102542. return true;
  102543. }
  102544. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
  102545. {
  102546. FLAC__ASSERT(0 != encoder);
  102547. FLAC__ASSERT(0 != encoder->private_);
  102548. FLAC__ASSERT(0 != encoder->protected_);
  102549. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102550. return false;
  102551. encoder->protected_->channels = value;
  102552. return true;
  102553. }
  102554. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
  102555. {
  102556. FLAC__ASSERT(0 != encoder);
  102557. FLAC__ASSERT(0 != encoder->private_);
  102558. FLAC__ASSERT(0 != encoder->protected_);
  102559. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102560. return false;
  102561. encoder->protected_->bits_per_sample = value;
  102562. return true;
  102563. }
  102564. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
  102565. {
  102566. FLAC__ASSERT(0 != encoder);
  102567. FLAC__ASSERT(0 != encoder->private_);
  102568. FLAC__ASSERT(0 != encoder->protected_);
  102569. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102570. return false;
  102571. encoder->protected_->sample_rate = value;
  102572. return true;
  102573. }
  102574. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
  102575. {
  102576. FLAC__bool ok = true;
  102577. FLAC__ASSERT(0 != encoder);
  102578. FLAC__ASSERT(0 != encoder->private_);
  102579. FLAC__ASSERT(0 != encoder->protected_);
  102580. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102581. return false;
  102582. if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
  102583. value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
  102584. ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
  102585. ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
  102586. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102587. #if 0
  102588. /* was: */
  102589. ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
  102590. /* but it's too hard to specify the string in a locale-specific way */
  102591. #else
  102592. encoder->protected_->num_apodizations = 1;
  102593. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  102594. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  102595. #endif
  102596. #endif
  102597. ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
  102598. ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
  102599. ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
  102600. ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
  102601. ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
  102602. ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
  102603. ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
  102604. ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
  102605. return ok;
  102606. }
  102607. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
  102608. {
  102609. FLAC__ASSERT(0 != encoder);
  102610. FLAC__ASSERT(0 != encoder->private_);
  102611. FLAC__ASSERT(0 != encoder->protected_);
  102612. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102613. return false;
  102614. encoder->protected_->blocksize = value;
  102615. return true;
  102616. }
  102617. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102618. {
  102619. FLAC__ASSERT(0 != encoder);
  102620. FLAC__ASSERT(0 != encoder->private_);
  102621. FLAC__ASSERT(0 != encoder->protected_);
  102622. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102623. return false;
  102624. encoder->protected_->do_mid_side_stereo = value;
  102625. return true;
  102626. }
  102627. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102628. {
  102629. FLAC__ASSERT(0 != encoder);
  102630. FLAC__ASSERT(0 != encoder->private_);
  102631. FLAC__ASSERT(0 != encoder->protected_);
  102632. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102633. return false;
  102634. encoder->protected_->loose_mid_side_stereo = value;
  102635. return true;
  102636. }
  102637. /*@@@@add to tests*/
  102638. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
  102639. {
  102640. FLAC__ASSERT(0 != encoder);
  102641. FLAC__ASSERT(0 != encoder->private_);
  102642. FLAC__ASSERT(0 != encoder->protected_);
  102643. FLAC__ASSERT(0 != specification);
  102644. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102645. return false;
  102646. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  102647. (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
  102648. #else
  102649. encoder->protected_->num_apodizations = 0;
  102650. while(1) {
  102651. const char *s = strchr(specification, ';');
  102652. const size_t n = s? (size_t)(s - specification) : strlen(specification);
  102653. if (n==8 && 0 == strncmp("bartlett" , specification, n))
  102654. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
  102655. else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
  102656. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
  102657. else if(n==8 && 0 == strncmp("blackman" , specification, n))
  102658. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
  102659. else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
  102660. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
  102661. else if(n==6 && 0 == strncmp("connes" , specification, n))
  102662. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
  102663. else if(n==7 && 0 == strncmp("flattop" , specification, n))
  102664. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
  102665. else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
  102666. FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
  102667. if (stddev > 0.0 && stddev <= 0.5) {
  102668. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
  102669. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
  102670. }
  102671. }
  102672. else if(n==7 && 0 == strncmp("hamming" , specification, n))
  102673. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
  102674. else if(n==4 && 0 == strncmp("hann" , specification, n))
  102675. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
  102676. else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
  102677. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
  102678. else if(n==7 && 0 == strncmp("nuttall" , specification, n))
  102679. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
  102680. else if(n==9 && 0 == strncmp("rectangle" , specification, n))
  102681. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
  102682. else if(n==8 && 0 == strncmp("triangle" , specification, n))
  102683. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
  102684. else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
  102685. FLAC__real p = (FLAC__real)strtod(specification+6, 0);
  102686. if (p >= 0.0 && p <= 1.0) {
  102687. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
  102688. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
  102689. }
  102690. }
  102691. else if(n==5 && 0 == strncmp("welch" , specification, n))
  102692. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
  102693. if (encoder->protected_->num_apodizations == 32)
  102694. break;
  102695. if (s)
  102696. specification = s+1;
  102697. else
  102698. break;
  102699. }
  102700. if(encoder->protected_->num_apodizations == 0) {
  102701. encoder->protected_->num_apodizations = 1;
  102702. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  102703. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  102704. }
  102705. #endif
  102706. return true;
  102707. }
  102708. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
  102709. {
  102710. FLAC__ASSERT(0 != encoder);
  102711. FLAC__ASSERT(0 != encoder->private_);
  102712. FLAC__ASSERT(0 != encoder->protected_);
  102713. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102714. return false;
  102715. encoder->protected_->max_lpc_order = value;
  102716. return true;
  102717. }
  102718. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
  102719. {
  102720. FLAC__ASSERT(0 != encoder);
  102721. FLAC__ASSERT(0 != encoder->private_);
  102722. FLAC__ASSERT(0 != encoder->protected_);
  102723. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102724. return false;
  102725. encoder->protected_->qlp_coeff_precision = value;
  102726. return true;
  102727. }
  102728. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102729. {
  102730. FLAC__ASSERT(0 != encoder);
  102731. FLAC__ASSERT(0 != encoder->private_);
  102732. FLAC__ASSERT(0 != encoder->protected_);
  102733. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102734. return false;
  102735. encoder->protected_->do_qlp_coeff_prec_search = value;
  102736. return true;
  102737. }
  102738. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102739. {
  102740. FLAC__ASSERT(0 != encoder);
  102741. FLAC__ASSERT(0 != encoder->private_);
  102742. FLAC__ASSERT(0 != encoder->protected_);
  102743. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102744. return false;
  102745. #if 0
  102746. /*@@@ deprecated: */
  102747. encoder->protected_->do_escape_coding = value;
  102748. #else
  102749. (void)value;
  102750. #endif
  102751. return true;
  102752. }
  102753. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102754. {
  102755. FLAC__ASSERT(0 != encoder);
  102756. FLAC__ASSERT(0 != encoder->private_);
  102757. FLAC__ASSERT(0 != encoder->protected_);
  102758. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102759. return false;
  102760. encoder->protected_->do_exhaustive_model_search = value;
  102761. return true;
  102762. }
  102763. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  102764. {
  102765. FLAC__ASSERT(0 != encoder);
  102766. FLAC__ASSERT(0 != encoder->private_);
  102767. FLAC__ASSERT(0 != encoder->protected_);
  102768. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102769. return false;
  102770. encoder->protected_->min_residual_partition_order = value;
  102771. return true;
  102772. }
  102773. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  102774. {
  102775. FLAC__ASSERT(0 != encoder);
  102776. FLAC__ASSERT(0 != encoder->private_);
  102777. FLAC__ASSERT(0 != encoder->protected_);
  102778. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102779. return false;
  102780. encoder->protected_->max_residual_partition_order = value;
  102781. return true;
  102782. }
  102783. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
  102784. {
  102785. FLAC__ASSERT(0 != encoder);
  102786. FLAC__ASSERT(0 != encoder->private_);
  102787. FLAC__ASSERT(0 != encoder->protected_);
  102788. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102789. return false;
  102790. #if 0
  102791. /*@@@ deprecated: */
  102792. encoder->protected_->rice_parameter_search_dist = value;
  102793. #else
  102794. (void)value;
  102795. #endif
  102796. return true;
  102797. }
  102798. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
  102799. {
  102800. FLAC__ASSERT(0 != encoder);
  102801. FLAC__ASSERT(0 != encoder->private_);
  102802. FLAC__ASSERT(0 != encoder->protected_);
  102803. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102804. return false;
  102805. encoder->protected_->total_samples_estimate = value;
  102806. return true;
  102807. }
  102808. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
  102809. {
  102810. FLAC__ASSERT(0 != encoder);
  102811. FLAC__ASSERT(0 != encoder->private_);
  102812. FLAC__ASSERT(0 != encoder->protected_);
  102813. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102814. return false;
  102815. if(0 == metadata)
  102816. num_blocks = 0;
  102817. if(0 == num_blocks)
  102818. metadata = 0;
  102819. /* realloc() does not do exactly what we want so... */
  102820. if(encoder->protected_->metadata) {
  102821. free(encoder->protected_->metadata);
  102822. encoder->protected_->metadata = 0;
  102823. encoder->protected_->num_metadata_blocks = 0;
  102824. }
  102825. if(num_blocks) {
  102826. FLAC__StreamMetadata **m;
  102827. if(0 == (m = (FLAC__StreamMetadata**)safe_malloc_mul_2op_(sizeof(m[0]), /*times*/num_blocks)))
  102828. return false;
  102829. memcpy(m, metadata, sizeof(m[0]) * num_blocks);
  102830. encoder->protected_->metadata = m;
  102831. encoder->protected_->num_metadata_blocks = num_blocks;
  102832. }
  102833. #if FLAC__HAS_OGG
  102834. if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
  102835. return false;
  102836. #endif
  102837. return true;
  102838. }
  102839. /*
  102840. * These three functions are not static, but not publically exposed in
  102841. * include/FLAC/ either. They are used by the test suite.
  102842. */
  102843. FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102844. {
  102845. FLAC__ASSERT(0 != encoder);
  102846. FLAC__ASSERT(0 != encoder->private_);
  102847. FLAC__ASSERT(0 != encoder->protected_);
  102848. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102849. return false;
  102850. encoder->private_->disable_constant_subframes = value;
  102851. return true;
  102852. }
  102853. FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102854. {
  102855. FLAC__ASSERT(0 != encoder);
  102856. FLAC__ASSERT(0 != encoder->private_);
  102857. FLAC__ASSERT(0 != encoder->protected_);
  102858. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102859. return false;
  102860. encoder->private_->disable_fixed_subframes = value;
  102861. return true;
  102862. }
  102863. FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102864. {
  102865. FLAC__ASSERT(0 != encoder);
  102866. FLAC__ASSERT(0 != encoder->private_);
  102867. FLAC__ASSERT(0 != encoder->protected_);
  102868. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102869. return false;
  102870. encoder->private_->disable_verbatim_subframes = value;
  102871. return true;
  102872. }
  102873. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
  102874. {
  102875. FLAC__ASSERT(0 != encoder);
  102876. FLAC__ASSERT(0 != encoder->private_);
  102877. FLAC__ASSERT(0 != encoder->protected_);
  102878. return encoder->protected_->state;
  102879. }
  102880. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
  102881. {
  102882. FLAC__ASSERT(0 != encoder);
  102883. FLAC__ASSERT(0 != encoder->private_);
  102884. FLAC__ASSERT(0 != encoder->protected_);
  102885. if(encoder->protected_->verify)
  102886. return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
  102887. else
  102888. return FLAC__STREAM_DECODER_UNINITIALIZED;
  102889. }
  102890. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
  102891. {
  102892. FLAC__ASSERT(0 != encoder);
  102893. FLAC__ASSERT(0 != encoder->private_);
  102894. FLAC__ASSERT(0 != encoder->protected_);
  102895. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
  102896. return FLAC__StreamEncoderStateString[encoder->protected_->state];
  102897. else
  102898. return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
  102899. }
  102900. 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)
  102901. {
  102902. FLAC__ASSERT(0 != encoder);
  102903. FLAC__ASSERT(0 != encoder->private_);
  102904. FLAC__ASSERT(0 != encoder->protected_);
  102905. if(0 != absolute_sample)
  102906. *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
  102907. if(0 != frame_number)
  102908. *frame_number = encoder->private_->verify.error_stats.frame_number;
  102909. if(0 != channel)
  102910. *channel = encoder->private_->verify.error_stats.channel;
  102911. if(0 != sample)
  102912. *sample = encoder->private_->verify.error_stats.sample;
  102913. if(0 != expected)
  102914. *expected = encoder->private_->verify.error_stats.expected;
  102915. if(0 != got)
  102916. *got = encoder->private_->verify.error_stats.got;
  102917. }
  102918. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
  102919. {
  102920. FLAC__ASSERT(0 != encoder);
  102921. FLAC__ASSERT(0 != encoder->private_);
  102922. FLAC__ASSERT(0 != encoder->protected_);
  102923. return encoder->protected_->verify;
  102924. }
  102925. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
  102926. {
  102927. FLAC__ASSERT(0 != encoder);
  102928. FLAC__ASSERT(0 != encoder->private_);
  102929. FLAC__ASSERT(0 != encoder->protected_);
  102930. return encoder->protected_->streamable_subset;
  102931. }
  102932. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
  102933. {
  102934. FLAC__ASSERT(0 != encoder);
  102935. FLAC__ASSERT(0 != encoder->private_);
  102936. FLAC__ASSERT(0 != encoder->protected_);
  102937. return encoder->protected_->do_md5;
  102938. }
  102939. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
  102940. {
  102941. FLAC__ASSERT(0 != encoder);
  102942. FLAC__ASSERT(0 != encoder->private_);
  102943. FLAC__ASSERT(0 != encoder->protected_);
  102944. return encoder->protected_->channels;
  102945. }
  102946. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
  102947. {
  102948. FLAC__ASSERT(0 != encoder);
  102949. FLAC__ASSERT(0 != encoder->private_);
  102950. FLAC__ASSERT(0 != encoder->protected_);
  102951. return encoder->protected_->bits_per_sample;
  102952. }
  102953. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
  102954. {
  102955. FLAC__ASSERT(0 != encoder);
  102956. FLAC__ASSERT(0 != encoder->private_);
  102957. FLAC__ASSERT(0 != encoder->protected_);
  102958. return encoder->protected_->sample_rate;
  102959. }
  102960. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
  102961. {
  102962. FLAC__ASSERT(0 != encoder);
  102963. FLAC__ASSERT(0 != encoder->private_);
  102964. FLAC__ASSERT(0 != encoder->protected_);
  102965. return encoder->protected_->blocksize;
  102966. }
  102967. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  102968. {
  102969. FLAC__ASSERT(0 != encoder);
  102970. FLAC__ASSERT(0 != encoder->private_);
  102971. FLAC__ASSERT(0 != encoder->protected_);
  102972. return encoder->protected_->do_mid_side_stereo;
  102973. }
  102974. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  102975. {
  102976. FLAC__ASSERT(0 != encoder);
  102977. FLAC__ASSERT(0 != encoder->private_);
  102978. FLAC__ASSERT(0 != encoder->protected_);
  102979. return encoder->protected_->loose_mid_side_stereo;
  102980. }
  102981. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
  102982. {
  102983. FLAC__ASSERT(0 != encoder);
  102984. FLAC__ASSERT(0 != encoder->private_);
  102985. FLAC__ASSERT(0 != encoder->protected_);
  102986. return encoder->protected_->max_lpc_order;
  102987. }
  102988. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
  102989. {
  102990. FLAC__ASSERT(0 != encoder);
  102991. FLAC__ASSERT(0 != encoder->private_);
  102992. FLAC__ASSERT(0 != encoder->protected_);
  102993. return encoder->protected_->qlp_coeff_precision;
  102994. }
  102995. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
  102996. {
  102997. FLAC__ASSERT(0 != encoder);
  102998. FLAC__ASSERT(0 != encoder->private_);
  102999. FLAC__ASSERT(0 != encoder->protected_);
  103000. return encoder->protected_->do_qlp_coeff_prec_search;
  103001. }
  103002. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
  103003. {
  103004. FLAC__ASSERT(0 != encoder);
  103005. FLAC__ASSERT(0 != encoder->private_);
  103006. FLAC__ASSERT(0 != encoder->protected_);
  103007. return encoder->protected_->do_escape_coding;
  103008. }
  103009. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
  103010. {
  103011. FLAC__ASSERT(0 != encoder);
  103012. FLAC__ASSERT(0 != encoder->private_);
  103013. FLAC__ASSERT(0 != encoder->protected_);
  103014. return encoder->protected_->do_exhaustive_model_search;
  103015. }
  103016. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
  103017. {
  103018. FLAC__ASSERT(0 != encoder);
  103019. FLAC__ASSERT(0 != encoder->private_);
  103020. FLAC__ASSERT(0 != encoder->protected_);
  103021. return encoder->protected_->min_residual_partition_order;
  103022. }
  103023. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
  103024. {
  103025. FLAC__ASSERT(0 != encoder);
  103026. FLAC__ASSERT(0 != encoder->private_);
  103027. FLAC__ASSERT(0 != encoder->protected_);
  103028. return encoder->protected_->max_residual_partition_order;
  103029. }
  103030. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
  103031. {
  103032. FLAC__ASSERT(0 != encoder);
  103033. FLAC__ASSERT(0 != encoder->private_);
  103034. FLAC__ASSERT(0 != encoder->protected_);
  103035. return encoder->protected_->rice_parameter_search_dist;
  103036. }
  103037. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
  103038. {
  103039. FLAC__ASSERT(0 != encoder);
  103040. FLAC__ASSERT(0 != encoder->private_);
  103041. FLAC__ASSERT(0 != encoder->protected_);
  103042. return encoder->protected_->total_samples_estimate;
  103043. }
  103044. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
  103045. {
  103046. unsigned i, j = 0, channel;
  103047. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  103048. FLAC__ASSERT(0 != encoder);
  103049. FLAC__ASSERT(0 != encoder->private_);
  103050. FLAC__ASSERT(0 != encoder->protected_);
  103051. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  103052. do {
  103053. const unsigned n = min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
  103054. if(encoder->protected_->verify)
  103055. append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
  103056. for(channel = 0; channel < channels; channel++)
  103057. memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
  103058. if(encoder->protected_->do_mid_side_stereo) {
  103059. FLAC__ASSERT(channels == 2);
  103060. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  103061. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  103062. encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
  103063. 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' ! */
  103064. }
  103065. }
  103066. else
  103067. j += n;
  103068. encoder->private_->current_sample_number += n;
  103069. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  103070. if(encoder->private_->current_sample_number > blocksize) {
  103071. FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
  103072. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  103073. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  103074. return false;
  103075. /* move unprocessed overread samples to beginnings of arrays */
  103076. for(channel = 0; channel < channels; channel++)
  103077. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  103078. if(encoder->protected_->do_mid_side_stereo) {
  103079. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  103080. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  103081. }
  103082. encoder->private_->current_sample_number = 1;
  103083. }
  103084. } while(j < samples);
  103085. return true;
  103086. }
  103087. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
  103088. {
  103089. unsigned i, j, k, channel;
  103090. FLAC__int32 x, mid, side;
  103091. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  103092. FLAC__ASSERT(0 != encoder);
  103093. FLAC__ASSERT(0 != encoder->private_);
  103094. FLAC__ASSERT(0 != encoder->protected_);
  103095. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  103096. j = k = 0;
  103097. /*
  103098. * we have several flavors of the same basic loop, optimized for
  103099. * different conditions:
  103100. */
  103101. if(encoder->protected_->do_mid_side_stereo && channels == 2) {
  103102. /*
  103103. * stereo coding: unroll channel loop
  103104. */
  103105. do {
  103106. if(encoder->protected_->verify)
  103107. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  103108. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  103109. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  103110. encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
  103111. x = buffer[k++];
  103112. encoder->private_->integer_signal[1][i] = x;
  103113. mid += x;
  103114. side -= x;
  103115. mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
  103116. encoder->private_->integer_signal_mid_side[1][i] = side;
  103117. encoder->private_->integer_signal_mid_side[0][i] = mid;
  103118. }
  103119. encoder->private_->current_sample_number = i;
  103120. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  103121. if(i > blocksize) {
  103122. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  103123. return false;
  103124. /* move unprocessed overread samples to beginnings of arrays */
  103125. FLAC__ASSERT(i == blocksize+OVERREAD_);
  103126. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  103127. encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
  103128. encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
  103129. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  103130. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  103131. encoder->private_->current_sample_number = 1;
  103132. }
  103133. } while(j < samples);
  103134. }
  103135. else {
  103136. /*
  103137. * independent channel coding: buffer each channel in inner loop
  103138. */
  103139. do {
  103140. if(encoder->protected_->verify)
  103141. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  103142. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  103143. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  103144. for(channel = 0; channel < channels; channel++)
  103145. encoder->private_->integer_signal[channel][i] = buffer[k++];
  103146. }
  103147. encoder->private_->current_sample_number = i;
  103148. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  103149. if(i > blocksize) {
  103150. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  103151. return false;
  103152. /* move unprocessed overread samples to beginnings of arrays */
  103153. FLAC__ASSERT(i == blocksize+OVERREAD_);
  103154. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  103155. for(channel = 0; channel < channels; channel++)
  103156. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  103157. encoder->private_->current_sample_number = 1;
  103158. }
  103159. } while(j < samples);
  103160. }
  103161. return true;
  103162. }
  103163. /***********************************************************************
  103164. *
  103165. * Private class methods
  103166. *
  103167. ***********************************************************************/
  103168. void set_defaults_enc(FLAC__StreamEncoder *encoder)
  103169. {
  103170. FLAC__ASSERT(0 != encoder);
  103171. #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  103172. encoder->protected_->verify = true;
  103173. #else
  103174. encoder->protected_->verify = false;
  103175. #endif
  103176. encoder->protected_->streamable_subset = true;
  103177. encoder->protected_->do_md5 = true;
  103178. encoder->protected_->do_mid_side_stereo = false;
  103179. encoder->protected_->loose_mid_side_stereo = false;
  103180. encoder->protected_->channels = 2;
  103181. encoder->protected_->bits_per_sample = 16;
  103182. encoder->protected_->sample_rate = 44100;
  103183. encoder->protected_->blocksize = 0;
  103184. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103185. encoder->protected_->num_apodizations = 1;
  103186. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103187. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103188. #endif
  103189. encoder->protected_->max_lpc_order = 0;
  103190. encoder->protected_->qlp_coeff_precision = 0;
  103191. encoder->protected_->do_qlp_coeff_prec_search = false;
  103192. encoder->protected_->do_exhaustive_model_search = false;
  103193. encoder->protected_->do_escape_coding = false;
  103194. encoder->protected_->min_residual_partition_order = 0;
  103195. encoder->protected_->max_residual_partition_order = 0;
  103196. encoder->protected_->rice_parameter_search_dist = 0;
  103197. encoder->protected_->total_samples_estimate = 0;
  103198. encoder->protected_->metadata = 0;
  103199. encoder->protected_->num_metadata_blocks = 0;
  103200. encoder->private_->seek_table = 0;
  103201. encoder->private_->disable_constant_subframes = false;
  103202. encoder->private_->disable_fixed_subframes = false;
  103203. encoder->private_->disable_verbatim_subframes = false;
  103204. #if FLAC__HAS_OGG
  103205. encoder->private_->is_ogg = false;
  103206. #endif
  103207. encoder->private_->read_callback = 0;
  103208. encoder->private_->write_callback = 0;
  103209. encoder->private_->seek_callback = 0;
  103210. encoder->private_->tell_callback = 0;
  103211. encoder->private_->metadata_callback = 0;
  103212. encoder->private_->progress_callback = 0;
  103213. encoder->private_->client_data = 0;
  103214. #if FLAC__HAS_OGG
  103215. FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
  103216. #endif
  103217. }
  103218. void free_(FLAC__StreamEncoder *encoder)
  103219. {
  103220. unsigned i, channel;
  103221. FLAC__ASSERT(0 != encoder);
  103222. if(encoder->protected_->metadata) {
  103223. free(encoder->protected_->metadata);
  103224. encoder->protected_->metadata = 0;
  103225. encoder->protected_->num_metadata_blocks = 0;
  103226. }
  103227. for(i = 0; i < encoder->protected_->channels; i++) {
  103228. if(0 != encoder->private_->integer_signal_unaligned[i]) {
  103229. free(encoder->private_->integer_signal_unaligned[i]);
  103230. encoder->private_->integer_signal_unaligned[i] = 0;
  103231. }
  103232. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103233. if(0 != encoder->private_->real_signal_unaligned[i]) {
  103234. free(encoder->private_->real_signal_unaligned[i]);
  103235. encoder->private_->real_signal_unaligned[i] = 0;
  103236. }
  103237. #endif
  103238. }
  103239. for(i = 0; i < 2; i++) {
  103240. if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
  103241. free(encoder->private_->integer_signal_mid_side_unaligned[i]);
  103242. encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
  103243. }
  103244. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103245. if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
  103246. free(encoder->private_->real_signal_mid_side_unaligned[i]);
  103247. encoder->private_->real_signal_mid_side_unaligned[i] = 0;
  103248. }
  103249. #endif
  103250. }
  103251. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103252. for(i = 0; i < encoder->protected_->num_apodizations; i++) {
  103253. if(0 != encoder->private_->window_unaligned[i]) {
  103254. free(encoder->private_->window_unaligned[i]);
  103255. encoder->private_->window_unaligned[i] = 0;
  103256. }
  103257. }
  103258. if(0 != encoder->private_->windowed_signal_unaligned) {
  103259. free(encoder->private_->windowed_signal_unaligned);
  103260. encoder->private_->windowed_signal_unaligned = 0;
  103261. }
  103262. #endif
  103263. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  103264. for(i = 0; i < 2; i++) {
  103265. if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
  103266. free(encoder->private_->residual_workspace_unaligned[channel][i]);
  103267. encoder->private_->residual_workspace_unaligned[channel][i] = 0;
  103268. }
  103269. }
  103270. }
  103271. for(channel = 0; channel < 2; channel++) {
  103272. for(i = 0; i < 2; i++) {
  103273. if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
  103274. free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
  103275. encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
  103276. }
  103277. }
  103278. }
  103279. if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
  103280. free(encoder->private_->abs_residual_partition_sums_unaligned);
  103281. encoder->private_->abs_residual_partition_sums_unaligned = 0;
  103282. }
  103283. if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
  103284. free(encoder->private_->raw_bits_per_partition_unaligned);
  103285. encoder->private_->raw_bits_per_partition_unaligned = 0;
  103286. }
  103287. if(encoder->protected_->verify) {
  103288. for(i = 0; i < encoder->protected_->channels; i++) {
  103289. if(0 != encoder->private_->verify.input_fifo.data[i]) {
  103290. free(encoder->private_->verify.input_fifo.data[i]);
  103291. encoder->private_->verify.input_fifo.data[i] = 0;
  103292. }
  103293. }
  103294. }
  103295. FLAC__bitwriter_free(encoder->private_->frame);
  103296. }
  103297. FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
  103298. {
  103299. FLAC__bool ok;
  103300. unsigned i, channel;
  103301. FLAC__ASSERT(new_blocksize > 0);
  103302. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  103303. FLAC__ASSERT(encoder->private_->current_sample_number == 0);
  103304. /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
  103305. if(new_blocksize <= encoder->private_->input_capacity)
  103306. return true;
  103307. ok = true;
  103308. /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
  103309. * requires that the input arrays (in our case the integer signals)
  103310. * have a buffer of up to 3 zeroes in front (at negative indices) for
  103311. * alignment purposes; we use 4 in front to keep the data well-aligned.
  103312. */
  103313. for(i = 0; ok && i < encoder->protected_->channels; i++) {
  103314. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
  103315. memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
  103316. encoder->private_->integer_signal[i] += 4;
  103317. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103318. #if 0 /* @@@ currently unused */
  103319. if(encoder->protected_->max_lpc_order > 0)
  103320. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
  103321. #endif
  103322. #endif
  103323. }
  103324. for(i = 0; ok && i < 2; i++) {
  103325. 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]);
  103326. memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
  103327. encoder->private_->integer_signal_mid_side[i] += 4;
  103328. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103329. #if 0 /* @@@ currently unused */
  103330. if(encoder->protected_->max_lpc_order > 0)
  103331. 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]);
  103332. #endif
  103333. #endif
  103334. }
  103335. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103336. if(ok && encoder->protected_->max_lpc_order > 0) {
  103337. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
  103338. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
  103339. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
  103340. }
  103341. #endif
  103342. for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
  103343. for(i = 0; ok && i < 2; i++) {
  103344. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
  103345. }
  103346. }
  103347. for(channel = 0; ok && channel < 2; channel++) {
  103348. for(i = 0; ok && i < 2; i++) {
  103349. 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]);
  103350. }
  103351. }
  103352. /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
  103353. /*@@@ 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) */
  103354. ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
  103355. if(encoder->protected_->do_escape_coding)
  103356. ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
  103357. /* now adjust the windows if the blocksize has changed */
  103358. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103359. if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
  103360. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
  103361. switch(encoder->protected_->apodizations[i].type) {
  103362. case FLAC__APODIZATION_BARTLETT:
  103363. FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
  103364. break;
  103365. case FLAC__APODIZATION_BARTLETT_HANN:
  103366. FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
  103367. break;
  103368. case FLAC__APODIZATION_BLACKMAN:
  103369. FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
  103370. break;
  103371. case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
  103372. FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
  103373. break;
  103374. case FLAC__APODIZATION_CONNES:
  103375. FLAC__window_connes(encoder->private_->window[i], new_blocksize);
  103376. break;
  103377. case FLAC__APODIZATION_FLATTOP:
  103378. FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
  103379. break;
  103380. case FLAC__APODIZATION_GAUSS:
  103381. FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
  103382. break;
  103383. case FLAC__APODIZATION_HAMMING:
  103384. FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
  103385. break;
  103386. case FLAC__APODIZATION_HANN:
  103387. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  103388. break;
  103389. case FLAC__APODIZATION_KAISER_BESSEL:
  103390. FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
  103391. break;
  103392. case FLAC__APODIZATION_NUTTALL:
  103393. FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
  103394. break;
  103395. case FLAC__APODIZATION_RECTANGLE:
  103396. FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
  103397. break;
  103398. case FLAC__APODIZATION_TRIANGLE:
  103399. FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
  103400. break;
  103401. case FLAC__APODIZATION_TUKEY:
  103402. FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
  103403. break;
  103404. case FLAC__APODIZATION_WELCH:
  103405. FLAC__window_welch(encoder->private_->window[i], new_blocksize);
  103406. break;
  103407. default:
  103408. FLAC__ASSERT(0);
  103409. /* double protection */
  103410. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  103411. break;
  103412. }
  103413. }
  103414. }
  103415. #endif
  103416. if(ok)
  103417. encoder->private_->input_capacity = new_blocksize;
  103418. else
  103419. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103420. return ok;
  103421. }
  103422. FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
  103423. {
  103424. const FLAC__byte *buffer;
  103425. size_t bytes;
  103426. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  103427. if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
  103428. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103429. return false;
  103430. }
  103431. if(encoder->protected_->verify) {
  103432. encoder->private_->verify.output.data = buffer;
  103433. encoder->private_->verify.output.bytes = bytes;
  103434. if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
  103435. encoder->private_->verify.needs_magic_hack = true;
  103436. }
  103437. else {
  103438. if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
  103439. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  103440. FLAC__bitwriter_clear(encoder->private_->frame);
  103441. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
  103442. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  103443. return false;
  103444. }
  103445. }
  103446. }
  103447. if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  103448. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  103449. FLAC__bitwriter_clear(encoder->private_->frame);
  103450. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103451. return false;
  103452. }
  103453. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  103454. FLAC__bitwriter_clear(encoder->private_->frame);
  103455. if(samples > 0) {
  103456. encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
  103457. encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
  103458. }
  103459. return true;
  103460. }
  103461. FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
  103462. {
  103463. FLAC__StreamEncoderWriteStatus status;
  103464. FLAC__uint64 output_position = 0;
  103465. /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
  103466. if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
  103467. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103468. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  103469. }
  103470. /*
  103471. * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
  103472. */
  103473. if(samples == 0) {
  103474. FLAC__MetadataType type = (FLAC__MetadataType) (buffer[0] & 0x7f);
  103475. if(type == FLAC__METADATA_TYPE_STREAMINFO)
  103476. encoder->protected_->streaminfo_offset = output_position;
  103477. else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
  103478. encoder->protected_->seektable_offset = output_position;
  103479. }
  103480. /*
  103481. * Mark the current seek point if hit (if audio_offset == 0 that
  103482. * means we're still writing metadata and haven't hit the first
  103483. * frame yet)
  103484. */
  103485. if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
  103486. const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  103487. const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
  103488. const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
  103489. FLAC__uint64 test_sample;
  103490. unsigned i;
  103491. for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
  103492. test_sample = encoder->private_->seek_table->points[i].sample_number;
  103493. if(test_sample > frame_last_sample) {
  103494. break;
  103495. }
  103496. else if(test_sample >= frame_first_sample) {
  103497. encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
  103498. encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
  103499. encoder->private_->seek_table->points[i].frame_samples = blocksize;
  103500. encoder->private_->first_seekpoint_to_check++;
  103501. /* DO NOT: "break;" and here's why:
  103502. * The seektable template may contain more than one target
  103503. * sample for any given frame; we will keep looping, generating
  103504. * duplicate seekpoints for them, and we'll clean it up later,
  103505. * just before writing the seektable back to the metadata.
  103506. */
  103507. }
  103508. else {
  103509. encoder->private_->first_seekpoint_to_check++;
  103510. }
  103511. }
  103512. }
  103513. #if FLAC__HAS_OGG
  103514. if(encoder->private_->is_ogg) {
  103515. status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
  103516. &encoder->protected_->ogg_encoder_aspect,
  103517. buffer,
  103518. bytes,
  103519. samples,
  103520. encoder->private_->current_frame_number,
  103521. is_last_block,
  103522. (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
  103523. encoder,
  103524. encoder->private_->client_data
  103525. );
  103526. }
  103527. else
  103528. #endif
  103529. status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
  103530. if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  103531. encoder->private_->bytes_written += bytes;
  103532. encoder->private_->samples_written += samples;
  103533. /* we keep a high watermark on the number of frames written because
  103534. * when the encoder goes back to write metadata, 'current_frame'
  103535. * will drop back to 0.
  103536. */
  103537. encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
  103538. }
  103539. else
  103540. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103541. return status;
  103542. }
  103543. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  103544. void update_metadata_(const FLAC__StreamEncoder *encoder)
  103545. {
  103546. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  103547. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  103548. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  103549. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  103550. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  103551. const unsigned bps = metadata->data.stream_info.bits_per_sample;
  103552. FLAC__StreamEncoderSeekStatus seek_status;
  103553. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  103554. /* All this is based on intimate knowledge of the stream header
  103555. * layout, but a change to the header format that would break this
  103556. * would also break all streams encoded in the previous format.
  103557. */
  103558. /*
  103559. * Write MD5 signature
  103560. */
  103561. {
  103562. const unsigned md5_offset =
  103563. FLAC__STREAM_METADATA_HEADER_LENGTH +
  103564. (
  103565. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  103566. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  103567. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  103568. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  103569. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  103570. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  103571. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  103572. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  103573. ) / 8;
  103574. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  103575. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  103576. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103577. return;
  103578. }
  103579. if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  103580. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103581. return;
  103582. }
  103583. }
  103584. /*
  103585. * Write total samples
  103586. */
  103587. {
  103588. const unsigned total_samples_byte_offset =
  103589. FLAC__STREAM_METADATA_HEADER_LENGTH +
  103590. (
  103591. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  103592. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  103593. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  103594. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  103595. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  103596. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  103597. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  103598. - 4
  103599. ) / 8;
  103600. b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
  103601. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  103602. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  103603. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  103604. b[4] = (FLAC__byte)(samples & 0xFF);
  103605. 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) {
  103606. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  103607. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103608. return;
  103609. }
  103610. if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  103611. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103612. return;
  103613. }
  103614. }
  103615. /*
  103616. * Write min/max framesize
  103617. */
  103618. {
  103619. const unsigned min_framesize_offset =
  103620. FLAC__STREAM_METADATA_HEADER_LENGTH +
  103621. (
  103622. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  103623. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  103624. ) / 8;
  103625. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  103626. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  103627. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  103628. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  103629. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  103630. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  103631. 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) {
  103632. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  103633. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103634. return;
  103635. }
  103636. if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  103637. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103638. return;
  103639. }
  103640. }
  103641. /*
  103642. * Write seektable
  103643. */
  103644. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  103645. unsigned i;
  103646. FLAC__format_seektable_sort(encoder->private_->seek_table);
  103647. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  103648. 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) {
  103649. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  103650. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103651. return;
  103652. }
  103653. for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
  103654. FLAC__uint64 xx;
  103655. unsigned x;
  103656. xx = encoder->private_->seek_table->points[i].sample_number;
  103657. b[7] = (FLAC__byte)xx; xx >>= 8;
  103658. b[6] = (FLAC__byte)xx; xx >>= 8;
  103659. b[5] = (FLAC__byte)xx; xx >>= 8;
  103660. b[4] = (FLAC__byte)xx; xx >>= 8;
  103661. b[3] = (FLAC__byte)xx; xx >>= 8;
  103662. b[2] = (FLAC__byte)xx; xx >>= 8;
  103663. b[1] = (FLAC__byte)xx; xx >>= 8;
  103664. b[0] = (FLAC__byte)xx; xx >>= 8;
  103665. xx = encoder->private_->seek_table->points[i].stream_offset;
  103666. b[15] = (FLAC__byte)xx; xx >>= 8;
  103667. b[14] = (FLAC__byte)xx; xx >>= 8;
  103668. b[13] = (FLAC__byte)xx; xx >>= 8;
  103669. b[12] = (FLAC__byte)xx; xx >>= 8;
  103670. b[11] = (FLAC__byte)xx; xx >>= 8;
  103671. b[10] = (FLAC__byte)xx; xx >>= 8;
  103672. b[9] = (FLAC__byte)xx; xx >>= 8;
  103673. b[8] = (FLAC__byte)xx; xx >>= 8;
  103674. x = encoder->private_->seek_table->points[i].frame_samples;
  103675. b[17] = (FLAC__byte)x; x >>= 8;
  103676. b[16] = (FLAC__byte)x; x >>= 8;
  103677. if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  103678. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103679. return;
  103680. }
  103681. }
  103682. }
  103683. }
  103684. #if FLAC__HAS_OGG
  103685. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  103686. void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
  103687. {
  103688. /* the # of bytes in the 1st packet that precede the STREAMINFO */
  103689. static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
  103690. FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
  103691. FLAC__OGG_MAPPING_MAGIC_LENGTH +
  103692. FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
  103693. FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
  103694. FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
  103695. FLAC__STREAM_SYNC_LENGTH
  103696. ;
  103697. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  103698. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  103699. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  103700. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  103701. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  103702. ogg_page page;
  103703. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  103704. FLAC__ASSERT(0 != encoder->private_->seek_callback);
  103705. /* Pre-check that client supports seeking, since we don't want the
  103706. * ogg_helper code to ever have to deal with this condition.
  103707. */
  103708. if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
  103709. return;
  103710. /* All this is based on intimate knowledge of the stream header
  103711. * layout, but a change to the header format that would break this
  103712. * would also break all streams encoded in the previous format.
  103713. */
  103714. /**
  103715. ** Write STREAMINFO stats
  103716. **/
  103717. simple_ogg_page__init(&page);
  103718. if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  103719. simple_ogg_page__clear(&page);
  103720. return; /* state already set */
  103721. }
  103722. /*
  103723. * Write MD5 signature
  103724. */
  103725. {
  103726. const unsigned md5_offset =
  103727. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  103728. FLAC__STREAM_METADATA_HEADER_LENGTH +
  103729. (
  103730. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  103731. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  103732. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  103733. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  103734. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  103735. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  103736. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  103737. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  103738. ) / 8;
  103739. if(md5_offset + 16 > (unsigned)page.body_len) {
  103740. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  103741. simple_ogg_page__clear(&page);
  103742. return;
  103743. }
  103744. memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
  103745. }
  103746. /*
  103747. * Write total samples
  103748. */
  103749. {
  103750. const unsigned total_samples_byte_offset =
  103751. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  103752. FLAC__STREAM_METADATA_HEADER_LENGTH +
  103753. (
  103754. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  103755. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  103756. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  103757. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  103758. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  103759. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  103760. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  103761. - 4
  103762. ) / 8;
  103763. if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
  103764. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  103765. simple_ogg_page__clear(&page);
  103766. return;
  103767. }
  103768. b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
  103769. b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
  103770. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  103771. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  103772. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  103773. b[4] = (FLAC__byte)(samples & 0xFF);
  103774. memcpy(page.body + total_samples_byte_offset, b, 5);
  103775. }
  103776. /*
  103777. * Write min/max framesize
  103778. */
  103779. {
  103780. const unsigned min_framesize_offset =
  103781. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  103782. FLAC__STREAM_METADATA_HEADER_LENGTH +
  103783. (
  103784. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  103785. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  103786. ) / 8;
  103787. if(min_framesize_offset + 6 > (unsigned)page.body_len) {
  103788. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  103789. simple_ogg_page__clear(&page);
  103790. return;
  103791. }
  103792. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  103793. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  103794. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  103795. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  103796. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  103797. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  103798. memcpy(page.body + min_framesize_offset, b, 6);
  103799. }
  103800. if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  103801. simple_ogg_page__clear(&page);
  103802. return; /* state already set */
  103803. }
  103804. simple_ogg_page__clear(&page);
  103805. /*
  103806. * Write seektable
  103807. */
  103808. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  103809. unsigned i;
  103810. FLAC__byte *p;
  103811. FLAC__format_seektable_sort(encoder->private_->seek_table);
  103812. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  103813. simple_ogg_page__init(&page);
  103814. if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  103815. simple_ogg_page__clear(&page);
  103816. return; /* state already set */
  103817. }
  103818. if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
  103819. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  103820. simple_ogg_page__clear(&page);
  103821. return;
  103822. }
  103823. for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
  103824. FLAC__uint64 xx;
  103825. unsigned x;
  103826. xx = encoder->private_->seek_table->points[i].sample_number;
  103827. b[7] = (FLAC__byte)xx; xx >>= 8;
  103828. b[6] = (FLAC__byte)xx; xx >>= 8;
  103829. b[5] = (FLAC__byte)xx; xx >>= 8;
  103830. b[4] = (FLAC__byte)xx; xx >>= 8;
  103831. b[3] = (FLAC__byte)xx; xx >>= 8;
  103832. b[2] = (FLAC__byte)xx; xx >>= 8;
  103833. b[1] = (FLAC__byte)xx; xx >>= 8;
  103834. b[0] = (FLAC__byte)xx; xx >>= 8;
  103835. xx = encoder->private_->seek_table->points[i].stream_offset;
  103836. b[15] = (FLAC__byte)xx; xx >>= 8;
  103837. b[14] = (FLAC__byte)xx; xx >>= 8;
  103838. b[13] = (FLAC__byte)xx; xx >>= 8;
  103839. b[12] = (FLAC__byte)xx; xx >>= 8;
  103840. b[11] = (FLAC__byte)xx; xx >>= 8;
  103841. b[10] = (FLAC__byte)xx; xx >>= 8;
  103842. b[9] = (FLAC__byte)xx; xx >>= 8;
  103843. b[8] = (FLAC__byte)xx; xx >>= 8;
  103844. x = encoder->private_->seek_table->points[i].frame_samples;
  103845. b[17] = (FLAC__byte)x; x >>= 8;
  103846. b[16] = (FLAC__byte)x; x >>= 8;
  103847. memcpy(p, b, 18);
  103848. }
  103849. if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  103850. simple_ogg_page__clear(&page);
  103851. return; /* state already set */
  103852. }
  103853. simple_ogg_page__clear(&page);
  103854. }
  103855. }
  103856. #endif
  103857. FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
  103858. {
  103859. FLAC__uint16 crc;
  103860. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  103861. /*
  103862. * Accumulate raw signal to the MD5 signature
  103863. */
  103864. 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)) {
  103865. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103866. return false;
  103867. }
  103868. /*
  103869. * Process the frame header and subframes into the frame bitbuffer
  103870. */
  103871. if(!process_subframes_(encoder, is_fractional_block)) {
  103872. /* the above function sets the state for us in case of an error */
  103873. return false;
  103874. }
  103875. /*
  103876. * Zero-pad the frame to a byte_boundary
  103877. */
  103878. if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
  103879. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103880. return false;
  103881. }
  103882. /*
  103883. * CRC-16 the whole thing
  103884. */
  103885. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  103886. if(
  103887. !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
  103888. !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
  103889. ) {
  103890. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103891. return false;
  103892. }
  103893. /*
  103894. * Write it
  103895. */
  103896. if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
  103897. /* the above function sets the state for us in case of an error */
  103898. return false;
  103899. }
  103900. /*
  103901. * Get ready for the next frame
  103902. */
  103903. encoder->private_->current_sample_number = 0;
  103904. encoder->private_->current_frame_number++;
  103905. encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
  103906. return true;
  103907. }
  103908. FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
  103909. {
  103910. FLAC__FrameHeader frame_header;
  103911. unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
  103912. FLAC__bool do_independent, do_mid_side;
  103913. /*
  103914. * Calculate the min,max Rice partition orders
  103915. */
  103916. if(is_fractional_block) {
  103917. max_partition_order = 0;
  103918. }
  103919. else {
  103920. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
  103921. max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
  103922. }
  103923. min_partition_order = min(min_partition_order, max_partition_order);
  103924. /*
  103925. * Setup the frame
  103926. */
  103927. frame_header.blocksize = encoder->protected_->blocksize;
  103928. frame_header.sample_rate = encoder->protected_->sample_rate;
  103929. frame_header.channels = encoder->protected_->channels;
  103930. frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
  103931. frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
  103932. frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  103933. frame_header.number.frame_number = encoder->private_->current_frame_number;
  103934. /*
  103935. * Figure out what channel assignments to try
  103936. */
  103937. if(encoder->protected_->do_mid_side_stereo) {
  103938. if(encoder->protected_->loose_mid_side_stereo) {
  103939. if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
  103940. do_independent = true;
  103941. do_mid_side = true;
  103942. }
  103943. else {
  103944. do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
  103945. do_mid_side = !do_independent;
  103946. }
  103947. }
  103948. else {
  103949. do_independent = true;
  103950. do_mid_side = true;
  103951. }
  103952. }
  103953. else {
  103954. do_independent = true;
  103955. do_mid_side = false;
  103956. }
  103957. FLAC__ASSERT(do_independent || do_mid_side);
  103958. /*
  103959. * Check for wasted bits; set effective bps for each subframe
  103960. */
  103961. if(do_independent) {
  103962. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  103963. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
  103964. encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
  103965. encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
  103966. }
  103967. }
  103968. if(do_mid_side) {
  103969. FLAC__ASSERT(encoder->protected_->channels == 2);
  103970. for(channel = 0; channel < 2; channel++) {
  103971. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
  103972. encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
  103973. encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
  103974. }
  103975. }
  103976. /*
  103977. * First do a normal encoding pass of each independent channel
  103978. */
  103979. if(do_independent) {
  103980. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  103981. if(!
  103982. process_subframe_(
  103983. encoder,
  103984. min_partition_order,
  103985. max_partition_order,
  103986. &frame_header,
  103987. encoder->private_->subframe_bps[channel],
  103988. encoder->private_->integer_signal[channel],
  103989. encoder->private_->subframe_workspace_ptr[channel],
  103990. encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
  103991. encoder->private_->residual_workspace[channel],
  103992. encoder->private_->best_subframe+channel,
  103993. encoder->private_->best_subframe_bits+channel
  103994. )
  103995. )
  103996. return false;
  103997. }
  103998. }
  103999. /*
  104000. * Now do mid and side channels if requested
  104001. */
  104002. if(do_mid_side) {
  104003. FLAC__ASSERT(encoder->protected_->channels == 2);
  104004. for(channel = 0; channel < 2; channel++) {
  104005. if(!
  104006. process_subframe_(
  104007. encoder,
  104008. min_partition_order,
  104009. max_partition_order,
  104010. &frame_header,
  104011. encoder->private_->subframe_bps_mid_side[channel],
  104012. encoder->private_->integer_signal_mid_side[channel],
  104013. encoder->private_->subframe_workspace_ptr_mid_side[channel],
  104014. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
  104015. encoder->private_->residual_workspace_mid_side[channel],
  104016. encoder->private_->best_subframe_mid_side+channel,
  104017. encoder->private_->best_subframe_bits_mid_side+channel
  104018. )
  104019. )
  104020. return false;
  104021. }
  104022. }
  104023. /*
  104024. * Compose the frame bitbuffer
  104025. */
  104026. if(do_mid_side) {
  104027. unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
  104028. FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
  104029. FLAC__ChannelAssignment channel_assignment;
  104030. FLAC__ASSERT(encoder->protected_->channels == 2);
  104031. if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
  104032. channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
  104033. }
  104034. else {
  104035. unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
  104036. unsigned min_bits;
  104037. int ca;
  104038. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
  104039. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
  104040. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
  104041. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
  104042. FLAC__ASSERT(do_independent && do_mid_side);
  104043. /* We have to figure out which channel assignent results in the smallest frame */
  104044. bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
  104045. bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
  104046. bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
  104047. bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
  104048. channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  104049. min_bits = bits[channel_assignment];
  104050. for(ca = 1; ca <= 3; ca++) {
  104051. if(bits[ca] < min_bits) {
  104052. min_bits = bits[ca];
  104053. channel_assignment = (FLAC__ChannelAssignment)ca;
  104054. }
  104055. }
  104056. }
  104057. frame_header.channel_assignment = channel_assignment;
  104058. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  104059. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104060. return false;
  104061. }
  104062. switch(channel_assignment) {
  104063. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  104064. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  104065. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  104066. break;
  104067. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  104068. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  104069. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  104070. break;
  104071. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  104072. left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  104073. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  104074. break;
  104075. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  104076. left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
  104077. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  104078. break;
  104079. default:
  104080. FLAC__ASSERT(0);
  104081. }
  104082. switch(channel_assignment) {
  104083. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  104084. left_bps = encoder->private_->subframe_bps [0];
  104085. right_bps = encoder->private_->subframe_bps [1];
  104086. break;
  104087. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  104088. left_bps = encoder->private_->subframe_bps [0];
  104089. right_bps = encoder->private_->subframe_bps_mid_side[1];
  104090. break;
  104091. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  104092. left_bps = encoder->private_->subframe_bps_mid_side[1];
  104093. right_bps = encoder->private_->subframe_bps [1];
  104094. break;
  104095. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  104096. left_bps = encoder->private_->subframe_bps_mid_side[0];
  104097. right_bps = encoder->private_->subframe_bps_mid_side[1];
  104098. break;
  104099. default:
  104100. FLAC__ASSERT(0);
  104101. }
  104102. /* note that encoder_add_subframe_ sets the state for us in case of an error */
  104103. if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
  104104. return false;
  104105. if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
  104106. return false;
  104107. }
  104108. else {
  104109. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  104110. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104111. return false;
  104112. }
  104113. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104114. 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)) {
  104115. /* the above function sets the state for us in case of an error */
  104116. return false;
  104117. }
  104118. }
  104119. }
  104120. if(encoder->protected_->loose_mid_side_stereo) {
  104121. encoder->private_->loose_mid_side_stereo_frame_count++;
  104122. if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
  104123. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  104124. }
  104125. encoder->private_->last_channel_assignment = frame_header.channel_assignment;
  104126. return true;
  104127. }
  104128. FLAC__bool process_subframe_(
  104129. FLAC__StreamEncoder *encoder,
  104130. unsigned min_partition_order,
  104131. unsigned max_partition_order,
  104132. const FLAC__FrameHeader *frame_header,
  104133. unsigned subframe_bps,
  104134. const FLAC__int32 integer_signal[],
  104135. FLAC__Subframe *subframe[2],
  104136. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  104137. FLAC__int32 *residual[2],
  104138. unsigned *best_subframe,
  104139. unsigned *best_bits
  104140. )
  104141. {
  104142. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104143. FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  104144. #else
  104145. FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  104146. #endif
  104147. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104148. FLAC__double lpc_residual_bits_per_sample;
  104149. 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 */
  104150. FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
  104151. unsigned min_lpc_order, max_lpc_order, lpc_order;
  104152. unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
  104153. #endif
  104154. unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
  104155. unsigned rice_parameter;
  104156. unsigned _candidate_bits, _best_bits;
  104157. unsigned _best_subframe;
  104158. /* only use RICE2 partitions if stream bps > 16 */
  104159. 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;
  104160. FLAC__ASSERT(frame_header->blocksize > 0);
  104161. /* verbatim subframe is the baseline against which we measure other compressed subframes */
  104162. _best_subframe = 0;
  104163. if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
  104164. _best_bits = UINT_MAX;
  104165. else
  104166. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  104167. if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
  104168. unsigned signal_is_constant = false;
  104169. 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);
  104170. /* check for constant subframe */
  104171. if(
  104172. !encoder->private_->disable_constant_subframes &&
  104173. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104174. fixed_residual_bits_per_sample[1] == 0.0
  104175. #else
  104176. fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
  104177. #endif
  104178. ) {
  104179. /* the above means it's possible all samples are the same value; now double-check it: */
  104180. unsigned i;
  104181. signal_is_constant = true;
  104182. for(i = 1; i < frame_header->blocksize; i++) {
  104183. if(integer_signal[0] != integer_signal[i]) {
  104184. signal_is_constant = false;
  104185. break;
  104186. }
  104187. }
  104188. }
  104189. if(signal_is_constant) {
  104190. _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
  104191. if(_candidate_bits < _best_bits) {
  104192. _best_subframe = !_best_subframe;
  104193. _best_bits = _candidate_bits;
  104194. }
  104195. }
  104196. else {
  104197. if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
  104198. /* encode fixed */
  104199. if(encoder->protected_->do_exhaustive_model_search) {
  104200. min_fixed_order = 0;
  104201. max_fixed_order = FLAC__MAX_FIXED_ORDER;
  104202. }
  104203. else {
  104204. min_fixed_order = max_fixed_order = guess_fixed_order;
  104205. }
  104206. if(max_fixed_order >= frame_header->blocksize)
  104207. max_fixed_order = frame_header->blocksize - 1;
  104208. for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
  104209. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104210. if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
  104211. continue; /* don't even try */
  104212. 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 */
  104213. #else
  104214. if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
  104215. continue; /* don't even try */
  104216. 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 */
  104217. #endif
  104218. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  104219. if(rice_parameter >= rice_parameter_limit) {
  104220. #ifdef DEBUG_VERBOSE
  104221. fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
  104222. #endif
  104223. rice_parameter = rice_parameter_limit - 1;
  104224. }
  104225. _candidate_bits =
  104226. evaluate_fixed_subframe_(
  104227. encoder,
  104228. integer_signal,
  104229. residual[!_best_subframe],
  104230. encoder->private_->abs_residual_partition_sums,
  104231. encoder->private_->raw_bits_per_partition,
  104232. frame_header->blocksize,
  104233. subframe_bps,
  104234. fixed_order,
  104235. rice_parameter,
  104236. rice_parameter_limit,
  104237. min_partition_order,
  104238. max_partition_order,
  104239. encoder->protected_->do_escape_coding,
  104240. encoder->protected_->rice_parameter_search_dist,
  104241. subframe[!_best_subframe],
  104242. partitioned_rice_contents[!_best_subframe]
  104243. );
  104244. if(_candidate_bits < _best_bits) {
  104245. _best_subframe = !_best_subframe;
  104246. _best_bits = _candidate_bits;
  104247. }
  104248. }
  104249. }
  104250. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104251. /* encode lpc */
  104252. if(encoder->protected_->max_lpc_order > 0) {
  104253. if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
  104254. max_lpc_order = frame_header->blocksize-1;
  104255. else
  104256. max_lpc_order = encoder->protected_->max_lpc_order;
  104257. if(max_lpc_order > 0) {
  104258. unsigned a;
  104259. for (a = 0; a < encoder->protected_->num_apodizations; a++) {
  104260. FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
  104261. encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
  104262. /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
  104263. if(autoc[0] != 0.0) {
  104264. FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
  104265. if(encoder->protected_->do_exhaustive_model_search) {
  104266. min_lpc_order = 1;
  104267. }
  104268. else {
  104269. const unsigned guess_lpc_order =
  104270. FLAC__lpc_compute_best_order(
  104271. lpc_error,
  104272. max_lpc_order,
  104273. frame_header->blocksize,
  104274. subframe_bps + (
  104275. encoder->protected_->do_qlp_coeff_prec_search?
  104276. FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
  104277. encoder->protected_->qlp_coeff_precision
  104278. )
  104279. );
  104280. min_lpc_order = max_lpc_order = guess_lpc_order;
  104281. }
  104282. if(max_lpc_order >= frame_header->blocksize)
  104283. max_lpc_order = frame_header->blocksize - 1;
  104284. for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
  104285. lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
  104286. if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
  104287. continue; /* don't even try */
  104288. rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
  104289. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  104290. if(rice_parameter >= rice_parameter_limit) {
  104291. #ifdef DEBUG_VERBOSE
  104292. fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
  104293. #endif
  104294. rice_parameter = rice_parameter_limit - 1;
  104295. }
  104296. if(encoder->protected_->do_qlp_coeff_prec_search) {
  104297. min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
  104298. /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
  104299. if(subframe_bps <= 17) {
  104300. max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
  104301. max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
  104302. }
  104303. else
  104304. max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  104305. }
  104306. else {
  104307. min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
  104308. }
  104309. for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
  104310. _candidate_bits =
  104311. evaluate_lpc_subframe_(
  104312. encoder,
  104313. integer_signal,
  104314. residual[!_best_subframe],
  104315. encoder->private_->abs_residual_partition_sums,
  104316. encoder->private_->raw_bits_per_partition,
  104317. encoder->private_->lp_coeff[lpc_order-1],
  104318. frame_header->blocksize,
  104319. subframe_bps,
  104320. lpc_order,
  104321. qlp_coeff_precision,
  104322. rice_parameter,
  104323. rice_parameter_limit,
  104324. min_partition_order,
  104325. max_partition_order,
  104326. encoder->protected_->do_escape_coding,
  104327. encoder->protected_->rice_parameter_search_dist,
  104328. subframe[!_best_subframe],
  104329. partitioned_rice_contents[!_best_subframe]
  104330. );
  104331. if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
  104332. if(_candidate_bits < _best_bits) {
  104333. _best_subframe = !_best_subframe;
  104334. _best_bits = _candidate_bits;
  104335. }
  104336. }
  104337. }
  104338. }
  104339. }
  104340. }
  104341. }
  104342. }
  104343. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  104344. }
  104345. }
  104346. /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
  104347. if(_best_bits == UINT_MAX) {
  104348. FLAC__ASSERT(_best_subframe == 0);
  104349. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  104350. }
  104351. *best_subframe = _best_subframe;
  104352. *best_bits = _best_bits;
  104353. return true;
  104354. }
  104355. FLAC__bool add_subframe_(
  104356. FLAC__StreamEncoder *encoder,
  104357. unsigned blocksize,
  104358. unsigned subframe_bps,
  104359. const FLAC__Subframe *subframe,
  104360. FLAC__BitWriter *frame
  104361. )
  104362. {
  104363. switch(subframe->type) {
  104364. case FLAC__SUBFRAME_TYPE_CONSTANT:
  104365. if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
  104366. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104367. return false;
  104368. }
  104369. break;
  104370. case FLAC__SUBFRAME_TYPE_FIXED:
  104371. if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
  104372. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104373. return false;
  104374. }
  104375. break;
  104376. case FLAC__SUBFRAME_TYPE_LPC:
  104377. if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
  104378. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104379. return false;
  104380. }
  104381. break;
  104382. case FLAC__SUBFRAME_TYPE_VERBATIM:
  104383. if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
  104384. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104385. return false;
  104386. }
  104387. break;
  104388. default:
  104389. FLAC__ASSERT(0);
  104390. }
  104391. return true;
  104392. }
  104393. #define SPOTCHECK_ESTIMATE 0
  104394. #if SPOTCHECK_ESTIMATE
  104395. static void spotcheck_subframe_estimate_(
  104396. FLAC__StreamEncoder *encoder,
  104397. unsigned blocksize,
  104398. unsigned subframe_bps,
  104399. const FLAC__Subframe *subframe,
  104400. unsigned estimate
  104401. )
  104402. {
  104403. FLAC__bool ret;
  104404. FLAC__BitWriter *frame = FLAC__bitwriter_new();
  104405. if(frame == 0) {
  104406. fprintf(stderr, "EST: can't allocate frame\n");
  104407. return;
  104408. }
  104409. if(!FLAC__bitwriter_init(frame)) {
  104410. fprintf(stderr, "EST: can't init frame\n");
  104411. return;
  104412. }
  104413. ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
  104414. FLAC__ASSERT(ret);
  104415. {
  104416. const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
  104417. if(estimate != actual)
  104418. 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);
  104419. }
  104420. FLAC__bitwriter_delete(frame);
  104421. }
  104422. #endif
  104423. unsigned evaluate_constant_subframe_(
  104424. FLAC__StreamEncoder *encoder,
  104425. const FLAC__int32 signal,
  104426. unsigned blocksize,
  104427. unsigned subframe_bps,
  104428. FLAC__Subframe *subframe
  104429. )
  104430. {
  104431. unsigned estimate;
  104432. subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
  104433. subframe->data.constant.value = signal;
  104434. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
  104435. #if SPOTCHECK_ESTIMATE
  104436. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  104437. #else
  104438. (void)encoder, (void)blocksize;
  104439. #endif
  104440. return estimate;
  104441. }
  104442. unsigned evaluate_fixed_subframe_(
  104443. FLAC__StreamEncoder *encoder,
  104444. const FLAC__int32 signal[],
  104445. FLAC__int32 residual[],
  104446. FLAC__uint64 abs_residual_partition_sums[],
  104447. unsigned raw_bits_per_partition[],
  104448. unsigned blocksize,
  104449. unsigned subframe_bps,
  104450. unsigned order,
  104451. unsigned rice_parameter,
  104452. unsigned rice_parameter_limit,
  104453. unsigned min_partition_order,
  104454. unsigned max_partition_order,
  104455. FLAC__bool do_escape_coding,
  104456. unsigned rice_parameter_search_dist,
  104457. FLAC__Subframe *subframe,
  104458. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  104459. )
  104460. {
  104461. unsigned i, residual_bits, estimate;
  104462. const unsigned residual_samples = blocksize - order;
  104463. FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
  104464. subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
  104465. subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  104466. subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  104467. subframe->data.fixed.residual = residual;
  104468. residual_bits =
  104469. find_best_partition_order_(
  104470. encoder->private_,
  104471. residual,
  104472. abs_residual_partition_sums,
  104473. raw_bits_per_partition,
  104474. residual_samples,
  104475. order,
  104476. rice_parameter,
  104477. rice_parameter_limit,
  104478. min_partition_order,
  104479. max_partition_order,
  104480. subframe_bps,
  104481. do_escape_coding,
  104482. rice_parameter_search_dist,
  104483. &subframe->data.fixed.entropy_coding_method
  104484. );
  104485. subframe->data.fixed.order = order;
  104486. for(i = 0; i < order; i++)
  104487. subframe->data.fixed.warmup[i] = signal[i];
  104488. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
  104489. #if SPOTCHECK_ESTIMATE
  104490. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  104491. #endif
  104492. return estimate;
  104493. }
  104494. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104495. unsigned evaluate_lpc_subframe_(
  104496. FLAC__StreamEncoder *encoder,
  104497. const FLAC__int32 signal[],
  104498. FLAC__int32 residual[],
  104499. FLAC__uint64 abs_residual_partition_sums[],
  104500. unsigned raw_bits_per_partition[],
  104501. const FLAC__real lp_coeff[],
  104502. unsigned blocksize,
  104503. unsigned subframe_bps,
  104504. unsigned order,
  104505. unsigned qlp_coeff_precision,
  104506. unsigned rice_parameter,
  104507. unsigned rice_parameter_limit,
  104508. unsigned min_partition_order,
  104509. unsigned max_partition_order,
  104510. FLAC__bool do_escape_coding,
  104511. unsigned rice_parameter_search_dist,
  104512. FLAC__Subframe *subframe,
  104513. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  104514. )
  104515. {
  104516. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  104517. unsigned i, residual_bits, estimate;
  104518. int quantization, ret;
  104519. const unsigned residual_samples = blocksize - order;
  104520. /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
  104521. if(subframe_bps <= 16) {
  104522. FLAC__ASSERT(order > 0);
  104523. FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
  104524. qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
  104525. }
  104526. ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
  104527. if(ret != 0)
  104528. return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
  104529. if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  104530. if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
  104531. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  104532. else
  104533. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  104534. else
  104535. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  104536. subframe->type = FLAC__SUBFRAME_TYPE_LPC;
  104537. subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  104538. subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  104539. subframe->data.lpc.residual = residual;
  104540. residual_bits =
  104541. find_best_partition_order_(
  104542. encoder->private_,
  104543. residual,
  104544. abs_residual_partition_sums,
  104545. raw_bits_per_partition,
  104546. residual_samples,
  104547. order,
  104548. rice_parameter,
  104549. rice_parameter_limit,
  104550. min_partition_order,
  104551. max_partition_order,
  104552. subframe_bps,
  104553. do_escape_coding,
  104554. rice_parameter_search_dist,
  104555. &subframe->data.lpc.entropy_coding_method
  104556. );
  104557. subframe->data.lpc.order = order;
  104558. subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
  104559. subframe->data.lpc.quantization_level = quantization;
  104560. memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
  104561. for(i = 0; i < order; i++)
  104562. subframe->data.lpc.warmup[i] = signal[i];
  104563. 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;
  104564. #if SPOTCHECK_ESTIMATE
  104565. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  104566. #endif
  104567. return estimate;
  104568. }
  104569. #endif
  104570. unsigned evaluate_verbatim_subframe_(
  104571. FLAC__StreamEncoder *encoder,
  104572. const FLAC__int32 signal[],
  104573. unsigned blocksize,
  104574. unsigned subframe_bps,
  104575. FLAC__Subframe *subframe
  104576. )
  104577. {
  104578. unsigned estimate;
  104579. subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
  104580. subframe->data.verbatim.data = signal;
  104581. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
  104582. #if SPOTCHECK_ESTIMATE
  104583. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  104584. #else
  104585. (void)encoder;
  104586. #endif
  104587. return estimate;
  104588. }
  104589. unsigned find_best_partition_order_(
  104590. FLAC__StreamEncoderPrivate *private_,
  104591. const FLAC__int32 residual[],
  104592. FLAC__uint64 abs_residual_partition_sums[],
  104593. unsigned raw_bits_per_partition[],
  104594. unsigned residual_samples,
  104595. unsigned predictor_order,
  104596. unsigned rice_parameter,
  104597. unsigned rice_parameter_limit,
  104598. unsigned min_partition_order,
  104599. unsigned max_partition_order,
  104600. unsigned bps,
  104601. FLAC__bool do_escape_coding,
  104602. unsigned rice_parameter_search_dist,
  104603. FLAC__EntropyCodingMethod *best_ecm
  104604. )
  104605. {
  104606. unsigned residual_bits, best_residual_bits = 0;
  104607. unsigned best_parameters_index = 0;
  104608. unsigned best_partition_order = 0;
  104609. const unsigned blocksize = residual_samples + predictor_order;
  104610. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
  104611. min_partition_order = min(min_partition_order, max_partition_order);
  104612. precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
  104613. if(do_escape_coding)
  104614. precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
  104615. {
  104616. int partition_order;
  104617. unsigned sum;
  104618. for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
  104619. if(!
  104620. set_partitioned_rice_(
  104621. #ifdef EXACT_RICE_BITS_CALCULATION
  104622. residual,
  104623. #endif
  104624. abs_residual_partition_sums+sum,
  104625. raw_bits_per_partition+sum,
  104626. residual_samples,
  104627. predictor_order,
  104628. rice_parameter,
  104629. rice_parameter_limit,
  104630. rice_parameter_search_dist,
  104631. (unsigned)partition_order,
  104632. do_escape_coding,
  104633. &private_->partitioned_rice_contents_extra[!best_parameters_index],
  104634. &residual_bits
  104635. )
  104636. )
  104637. {
  104638. FLAC__ASSERT(best_residual_bits != 0);
  104639. break;
  104640. }
  104641. sum += 1u << partition_order;
  104642. if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
  104643. best_residual_bits = residual_bits;
  104644. best_parameters_index = !best_parameters_index;
  104645. best_partition_order = partition_order;
  104646. }
  104647. }
  104648. }
  104649. best_ecm->data.partitioned_rice.order = best_partition_order;
  104650. {
  104651. /*
  104652. * We are allowed to de-const the pointer based on our special
  104653. * knowledge; it is const to the outside world.
  104654. */
  104655. FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
  104656. unsigned partition;
  104657. /* save best parameters and raw_bits */
  104658. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, max(6, best_partition_order));
  104659. memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
  104660. if(do_escape_coding)
  104661. memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
  104662. /*
  104663. * Now need to check if the type should be changed to
  104664. * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
  104665. * size of the rice parameters.
  104666. */
  104667. for(partition = 0; partition < (1u<<best_partition_order); partition++) {
  104668. if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
  104669. best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
  104670. break;
  104671. }
  104672. }
  104673. }
  104674. return best_residual_bits;
  104675. }
  104676. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  104677. extern void precompute_partition_info_sums_32bit_asm_ia32_(
  104678. const FLAC__int32 residual[],
  104679. FLAC__uint64 abs_residual_partition_sums[],
  104680. unsigned blocksize,
  104681. unsigned predictor_order,
  104682. unsigned min_partition_order,
  104683. unsigned max_partition_order
  104684. );
  104685. #endif
  104686. void precompute_partition_info_sums_(
  104687. const FLAC__int32 residual[],
  104688. FLAC__uint64 abs_residual_partition_sums[],
  104689. unsigned residual_samples,
  104690. unsigned predictor_order,
  104691. unsigned min_partition_order,
  104692. unsigned max_partition_order,
  104693. unsigned bps
  104694. )
  104695. {
  104696. const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
  104697. unsigned partitions = 1u << max_partition_order;
  104698. FLAC__ASSERT(default_partition_samples > predictor_order);
  104699. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  104700. /* slightly pessimistic but still catches all common cases */
  104701. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  104702. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  104703. precompute_partition_info_sums_32bit_asm_ia32_(residual, abs_residual_partition_sums, residual_samples + predictor_order, predictor_order, min_partition_order, max_partition_order);
  104704. return;
  104705. }
  104706. #endif
  104707. /* first do max_partition_order */
  104708. {
  104709. unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
  104710. /* slightly pessimistic but still catches all common cases */
  104711. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  104712. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  104713. FLAC__uint32 abs_residual_partition_sum;
  104714. for(partition = residual_sample = 0; partition < partitions; partition++) {
  104715. end += default_partition_samples;
  104716. abs_residual_partition_sum = 0;
  104717. for( ; residual_sample < end; residual_sample++)
  104718. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  104719. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  104720. }
  104721. }
  104722. else { /* have to pessimistically use 64 bits for accumulator */
  104723. FLAC__uint64 abs_residual_partition_sum;
  104724. for(partition = residual_sample = 0; partition < partitions; partition++) {
  104725. end += default_partition_samples;
  104726. abs_residual_partition_sum = 0;
  104727. for( ; residual_sample < end; residual_sample++)
  104728. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  104729. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  104730. }
  104731. }
  104732. }
  104733. /* now merge partitions for lower orders */
  104734. {
  104735. unsigned from_partition = 0, to_partition = partitions;
  104736. int partition_order;
  104737. for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
  104738. unsigned i;
  104739. partitions >>= 1;
  104740. for(i = 0; i < partitions; i++) {
  104741. abs_residual_partition_sums[to_partition++] =
  104742. abs_residual_partition_sums[from_partition ] +
  104743. abs_residual_partition_sums[from_partition+1];
  104744. from_partition += 2;
  104745. }
  104746. }
  104747. }
  104748. }
  104749. void precompute_partition_info_escapes_(
  104750. const FLAC__int32 residual[],
  104751. unsigned raw_bits_per_partition[],
  104752. unsigned residual_samples,
  104753. unsigned predictor_order,
  104754. unsigned min_partition_order,
  104755. unsigned max_partition_order
  104756. )
  104757. {
  104758. int partition_order;
  104759. unsigned from_partition, to_partition = 0;
  104760. const unsigned blocksize = residual_samples + predictor_order;
  104761. /* first do max_partition_order */
  104762. for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
  104763. FLAC__int32 r;
  104764. FLAC__uint32 rmax;
  104765. unsigned partition, partition_sample, partition_samples, residual_sample;
  104766. const unsigned partitions = 1u << partition_order;
  104767. const unsigned default_partition_samples = blocksize >> partition_order;
  104768. FLAC__ASSERT(default_partition_samples > predictor_order);
  104769. for(partition = residual_sample = 0; partition < partitions; partition++) {
  104770. partition_samples = default_partition_samples;
  104771. if(partition == 0)
  104772. partition_samples -= predictor_order;
  104773. rmax = 0;
  104774. for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
  104775. r = residual[residual_sample++];
  104776. /* OPT: maybe faster: rmax |= r ^ (r>>31) */
  104777. if(r < 0)
  104778. rmax |= ~r;
  104779. else
  104780. rmax |= r;
  104781. }
  104782. /* now we know all residual values are in the range [-rmax-1,rmax] */
  104783. raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
  104784. }
  104785. to_partition = partitions;
  104786. break; /*@@@ yuck, should remove the 'for' loop instead */
  104787. }
  104788. /* now merge partitions for lower orders */
  104789. for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
  104790. unsigned m;
  104791. unsigned i;
  104792. const unsigned partitions = 1u << partition_order;
  104793. for(i = 0; i < partitions; i++) {
  104794. m = raw_bits_per_partition[from_partition];
  104795. from_partition++;
  104796. raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
  104797. from_partition++;
  104798. to_partition++;
  104799. }
  104800. }
  104801. }
  104802. #ifdef EXACT_RICE_BITS_CALCULATION
  104803. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  104804. const unsigned rice_parameter,
  104805. const unsigned partition_samples,
  104806. const FLAC__int32 *residual
  104807. )
  104808. {
  104809. unsigned i, partition_bits =
  104810. 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 */
  104811. (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
  104812. ;
  104813. for(i = 0; i < partition_samples; i++)
  104814. partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
  104815. return partition_bits;
  104816. }
  104817. #else
  104818. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  104819. const unsigned rice_parameter,
  104820. const unsigned partition_samples,
  104821. const FLAC__uint64 abs_residual_partition_sum
  104822. )
  104823. {
  104824. return
  104825. 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 */
  104826. (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
  104827. (
  104828. rice_parameter?
  104829. (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
  104830. : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
  104831. )
  104832. - (partition_samples >> 1)
  104833. /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
  104834. * The actual number of bits used is closer to the sum(for all i in the partition) of abs(residual[i])>>(rice_parameter-1)
  104835. * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
  104836. * So the subtraction term tries to guess how many extra bits were contributed.
  104837. * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
  104838. */
  104839. ;
  104840. }
  104841. #endif
  104842. FLAC__bool set_partitioned_rice_(
  104843. #ifdef EXACT_RICE_BITS_CALCULATION
  104844. const FLAC__int32 residual[],
  104845. #endif
  104846. const FLAC__uint64 abs_residual_partition_sums[],
  104847. const unsigned raw_bits_per_partition[],
  104848. const unsigned residual_samples,
  104849. const unsigned predictor_order,
  104850. const unsigned suggested_rice_parameter,
  104851. const unsigned rice_parameter_limit,
  104852. const unsigned rice_parameter_search_dist,
  104853. const unsigned partition_order,
  104854. const FLAC__bool search_for_escapes,
  104855. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  104856. unsigned *bits
  104857. )
  104858. {
  104859. unsigned rice_parameter, partition_bits;
  104860. unsigned best_partition_bits, best_rice_parameter = 0;
  104861. unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
  104862. unsigned *parameters, *raw_bits;
  104863. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  104864. unsigned min_rice_parameter, max_rice_parameter;
  104865. #else
  104866. (void)rice_parameter_search_dist;
  104867. #endif
  104868. FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  104869. FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  104870. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
  104871. parameters = partitioned_rice_contents->parameters;
  104872. raw_bits = partitioned_rice_contents->raw_bits;
  104873. if(partition_order == 0) {
  104874. best_partition_bits = (unsigned)(-1);
  104875. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  104876. if(rice_parameter_search_dist) {
  104877. if(suggested_rice_parameter < rice_parameter_search_dist)
  104878. min_rice_parameter = 0;
  104879. else
  104880. min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
  104881. max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
  104882. if(max_rice_parameter >= rice_parameter_limit) {
  104883. #ifdef DEBUG_VERBOSE
  104884. fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
  104885. #endif
  104886. max_rice_parameter = rice_parameter_limit - 1;
  104887. }
  104888. }
  104889. else
  104890. min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
  104891. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  104892. #else
  104893. rice_parameter = suggested_rice_parameter;
  104894. #endif
  104895. #ifdef EXACT_RICE_BITS_CALCULATION
  104896. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
  104897. #else
  104898. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
  104899. #endif
  104900. if(partition_bits < best_partition_bits) {
  104901. best_rice_parameter = rice_parameter;
  104902. best_partition_bits = partition_bits;
  104903. }
  104904. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  104905. }
  104906. #endif
  104907. if(search_for_escapes) {
  104908. 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;
  104909. if(partition_bits <= best_partition_bits) {
  104910. raw_bits[0] = raw_bits_per_partition[0];
  104911. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  104912. best_partition_bits = partition_bits;
  104913. }
  104914. else
  104915. raw_bits[0] = 0;
  104916. }
  104917. parameters[0] = best_rice_parameter;
  104918. bits_ += best_partition_bits;
  104919. }
  104920. else {
  104921. unsigned partition, residual_sample;
  104922. unsigned partition_samples;
  104923. FLAC__uint64 mean, k;
  104924. const unsigned partitions = 1u << partition_order;
  104925. for(partition = residual_sample = 0; partition < partitions; partition++) {
  104926. partition_samples = (residual_samples+predictor_order) >> partition_order;
  104927. if(partition == 0) {
  104928. if(partition_samples <= predictor_order)
  104929. return false;
  104930. else
  104931. partition_samples -= predictor_order;
  104932. }
  104933. mean = abs_residual_partition_sums[partition];
  104934. /* we are basically calculating the size in bits of the
  104935. * average residual magnitude in the partition:
  104936. * rice_parameter = floor(log2(mean/partition_samples))
  104937. * 'mean' is not a good name for the variable, it is
  104938. * actually the sum of magnitudes of all residual values
  104939. * in the partition, so the actual mean is
  104940. * mean/partition_samples
  104941. */
  104942. for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
  104943. ;
  104944. if(rice_parameter >= rice_parameter_limit) {
  104945. #ifdef DEBUG_VERBOSE
  104946. fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
  104947. #endif
  104948. rice_parameter = rice_parameter_limit - 1;
  104949. }
  104950. best_partition_bits = (unsigned)(-1);
  104951. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  104952. if(rice_parameter_search_dist) {
  104953. if(rice_parameter < rice_parameter_search_dist)
  104954. min_rice_parameter = 0;
  104955. else
  104956. min_rice_parameter = rice_parameter - rice_parameter_search_dist;
  104957. max_rice_parameter = rice_parameter + rice_parameter_search_dist;
  104958. if(max_rice_parameter >= rice_parameter_limit) {
  104959. #ifdef DEBUG_VERBOSE
  104960. fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
  104961. #endif
  104962. max_rice_parameter = rice_parameter_limit - 1;
  104963. }
  104964. }
  104965. else
  104966. min_rice_parameter = max_rice_parameter = rice_parameter;
  104967. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  104968. #endif
  104969. #ifdef EXACT_RICE_BITS_CALCULATION
  104970. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
  104971. #else
  104972. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
  104973. #endif
  104974. if(partition_bits < best_partition_bits) {
  104975. best_rice_parameter = rice_parameter;
  104976. best_partition_bits = partition_bits;
  104977. }
  104978. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  104979. }
  104980. #endif
  104981. if(search_for_escapes) {
  104982. 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;
  104983. if(partition_bits <= best_partition_bits) {
  104984. raw_bits[partition] = raw_bits_per_partition[partition];
  104985. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  104986. best_partition_bits = partition_bits;
  104987. }
  104988. else
  104989. raw_bits[partition] = 0;
  104990. }
  104991. parameters[partition] = best_rice_parameter;
  104992. bits_ += best_partition_bits;
  104993. residual_sample += partition_samples;
  104994. }
  104995. }
  104996. *bits = bits_;
  104997. return true;
  104998. }
  104999. unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
  105000. {
  105001. unsigned i, shift;
  105002. FLAC__int32 x = 0;
  105003. for(i = 0; i < samples && !(x&1); i++)
  105004. x |= signal[i];
  105005. if(x == 0) {
  105006. shift = 0;
  105007. }
  105008. else {
  105009. for(shift = 0; !(x&1); shift++)
  105010. x >>= 1;
  105011. }
  105012. if(shift > 0) {
  105013. for(i = 0; i < samples; i++)
  105014. signal[i] >>= shift;
  105015. }
  105016. return shift;
  105017. }
  105018. void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  105019. {
  105020. unsigned channel;
  105021. for(channel = 0; channel < channels; channel++)
  105022. memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
  105023. fifo->tail += wide_samples;
  105024. FLAC__ASSERT(fifo->tail <= fifo->size);
  105025. }
  105026. void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  105027. {
  105028. unsigned channel;
  105029. unsigned sample, wide_sample;
  105030. unsigned tail = fifo->tail;
  105031. sample = input_offset * channels;
  105032. for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
  105033. for(channel = 0; channel < channels; channel++)
  105034. fifo->data[channel][tail] = input[sample++];
  105035. tail++;
  105036. }
  105037. fifo->tail = tail;
  105038. FLAC__ASSERT(fifo->tail <= fifo->size);
  105039. }
  105040. FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  105041. {
  105042. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  105043. const size_t encoded_bytes = encoder->private_->verify.output.bytes;
  105044. (void)decoder;
  105045. if(encoder->private_->verify.needs_magic_hack) {
  105046. FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
  105047. *bytes = FLAC__STREAM_SYNC_LENGTH;
  105048. memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
  105049. encoder->private_->verify.needs_magic_hack = false;
  105050. }
  105051. else {
  105052. if(encoded_bytes == 0) {
  105053. /*
  105054. * If we get here, a FIFO underflow has occurred,
  105055. * which means there is a bug somewhere.
  105056. */
  105057. FLAC__ASSERT(0);
  105058. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  105059. }
  105060. else if(encoded_bytes < *bytes)
  105061. *bytes = encoded_bytes;
  105062. memcpy(buffer, encoder->private_->verify.output.data, *bytes);
  105063. encoder->private_->verify.output.data += *bytes;
  105064. encoder->private_->verify.output.bytes -= *bytes;
  105065. }
  105066. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  105067. }
  105068. FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
  105069. {
  105070. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
  105071. unsigned channel;
  105072. const unsigned channels = frame->header.channels;
  105073. const unsigned blocksize = frame->header.blocksize;
  105074. const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
  105075. (void)decoder;
  105076. for(channel = 0; channel < channels; channel++) {
  105077. if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
  105078. unsigned i, sample = 0;
  105079. FLAC__int32 expect = 0, got = 0;
  105080. for(i = 0; i < blocksize; i++) {
  105081. if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
  105082. sample = i;
  105083. expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
  105084. got = (FLAC__int32)buffer[channel][i];
  105085. break;
  105086. }
  105087. }
  105088. FLAC__ASSERT(i < blocksize);
  105089. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  105090. encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
  105091. encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
  105092. encoder->private_->verify.error_stats.channel = channel;
  105093. encoder->private_->verify.error_stats.sample = sample;
  105094. encoder->private_->verify.error_stats.expected = expect;
  105095. encoder->private_->verify.error_stats.got = got;
  105096. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  105097. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  105098. }
  105099. }
  105100. /* dequeue the frame from the fifo */
  105101. encoder->private_->verify.input_fifo.tail -= blocksize;
  105102. FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
  105103. for(channel = 0; channel < channels; channel++)
  105104. 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]));
  105105. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  105106. }
  105107. void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
  105108. {
  105109. (void)decoder, (void)metadata, (void)client_data;
  105110. }
  105111. void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
  105112. {
  105113. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  105114. (void)decoder, (void)status;
  105115. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  105116. }
  105117. FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  105118. {
  105119. (void)client_data;
  105120. *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
  105121. if (*bytes == 0) {
  105122. if (feof(encoder->private_->file))
  105123. return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  105124. else if (ferror(encoder->private_->file))
  105125. return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  105126. }
  105127. return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  105128. }
  105129. FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  105130. {
  105131. (void)client_data;
  105132. if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  105133. return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  105134. else
  105135. return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  105136. }
  105137. FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  105138. {
  105139. off_t offset;
  105140. (void)client_data;
  105141. offset = ftello(encoder->private_->file);
  105142. if(offset < 0) {
  105143. return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  105144. }
  105145. else {
  105146. *absolute_byte_offset = (FLAC__uint64)offset;
  105147. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  105148. }
  105149. }
  105150. #ifdef FLAC__VALGRIND_TESTING
  105151. static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
  105152. {
  105153. size_t ret = fwrite(ptr, size, nmemb, stream);
  105154. if(!ferror(stream))
  105155. fflush(stream);
  105156. return ret;
  105157. }
  105158. #else
  105159. #define local__fwrite fwrite
  105160. #endif
  105161. FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
  105162. {
  105163. (void)client_data, (void)current_frame;
  105164. if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
  105165. FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
  105166. #if FLAC__HAS_OGG
  105167. /* We would like to be able to use 'samples > 0' in the
  105168. * clause here but currently because of the nature of our
  105169. * Ogg writing implementation, 'samples' is always 0 (see
  105170. * ogg_encoder_aspect.c). The downside is extra progress
  105171. * callbacks.
  105172. */
  105173. encoder->private_->is_ogg? true :
  105174. #endif
  105175. samples > 0
  105176. );
  105177. if(call_it) {
  105178. /* NOTE: We have to add +bytes, +samples, and +1 to the stats
  105179. * because at this point in the callback chain, the stats
  105180. * have not been updated. Only after we return and control
  105181. * gets back to write_frame_() are the stats updated
  105182. */
  105183. 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);
  105184. }
  105185. return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
  105186. }
  105187. else
  105188. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  105189. }
  105190. /*
  105191. * This will forcibly set stdout to binary mode (for OSes that require it)
  105192. */
  105193. FILE *get_binary_stdout_(void)
  105194. {
  105195. /* if something breaks here it is probably due to the presence or
  105196. * absence of an underscore before the identifiers 'setmode',
  105197. * 'fileno', and/or 'O_BINARY'; check your system header files.
  105198. */
  105199. #if defined _MSC_VER || defined __MINGW32__
  105200. _setmode(_fileno(stdout), _O_BINARY);
  105201. #elif defined __CYGWIN__
  105202. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  105203. setmode(_fileno(stdout), _O_BINARY);
  105204. #elif defined __EMX__
  105205. setmode(fileno(stdout), O_BINARY);
  105206. #endif
  105207. return stdout;
  105208. }
  105209. #endif
  105210. /*** End of inlined file: stream_encoder.c ***/
  105211. /*** Start of inlined file: stream_encoder_framing.c ***/
  105212. /*** Start of inlined file: juce_FlacHeader.h ***/
  105213. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  105214. // tasks..
  105215. #define VERSION "1.2.1"
  105216. #define FLAC__NO_DLL 1
  105217. #if JUCE_MSVC
  105218. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  105219. #endif
  105220. #if JUCE_MAC
  105221. #define FLAC__SYS_DARWIN 1
  105222. #endif
  105223. /*** End of inlined file: juce_FlacHeader.h ***/
  105224. #if JUCE_USE_FLAC
  105225. #if HAVE_CONFIG_H
  105226. # include <config.h>
  105227. #endif
  105228. #include <stdio.h>
  105229. #include <string.h> /* for strlen() */
  105230. #ifdef max
  105231. #undef max
  105232. #endif
  105233. #define max(x,y) ((x)>(y)?(x):(y))
  105234. static FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method);
  105235. 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);
  105236. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw)
  105237. {
  105238. unsigned i, j;
  105239. const unsigned vendor_string_length = (unsigned)strlen(FLAC__VENDOR_STRING);
  105240. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->is_last, FLAC__STREAM_METADATA_IS_LAST_LEN))
  105241. return false;
  105242. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->type, FLAC__STREAM_METADATA_TYPE_LEN))
  105243. return false;
  105244. /*
  105245. * First, for VORBIS_COMMENTs, adjust the length to reflect our vendor string
  105246. */
  105247. i = metadata->length;
  105248. if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  105249. FLAC__ASSERT(metadata->data.vorbis_comment.vendor_string.length == 0 || 0 != metadata->data.vorbis_comment.vendor_string.entry);
  105250. i -= metadata->data.vorbis_comment.vendor_string.length;
  105251. i += vendor_string_length;
  105252. }
  105253. FLAC__ASSERT(i < (1u << FLAC__STREAM_METADATA_LENGTH_LEN));
  105254. if(!FLAC__bitwriter_write_raw_uint32(bw, i, FLAC__STREAM_METADATA_LENGTH_LEN))
  105255. return false;
  105256. switch(metadata->type) {
  105257. case FLAC__METADATA_TYPE_STREAMINFO:
  105258. FLAC__ASSERT(metadata->data.stream_info.min_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN));
  105259. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN))
  105260. return false;
  105261. FLAC__ASSERT(metadata->data.stream_info.max_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN));
  105262. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  105263. return false;
  105264. FLAC__ASSERT(metadata->data.stream_info.min_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN));
  105265. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_framesize, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  105266. return false;
  105267. FLAC__ASSERT(metadata->data.stream_info.max_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN));
  105268. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_framesize, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  105269. return false;
  105270. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(metadata->data.stream_info.sample_rate));
  105271. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.sample_rate, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  105272. return false;
  105273. FLAC__ASSERT(metadata->data.stream_info.channels > 0);
  105274. FLAC__ASSERT(metadata->data.stream_info.channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN));
  105275. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.channels-1, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  105276. return false;
  105277. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample > 0);
  105278. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  105279. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.bits_per_sample-1, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  105280. return false;
  105281. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN))
  105282. return false;
  105283. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.stream_info.md5sum, 16))
  105284. return false;
  105285. break;
  105286. case FLAC__METADATA_TYPE_PADDING:
  105287. if(!FLAC__bitwriter_write_zeroes(bw, metadata->length * 8))
  105288. return false;
  105289. break;
  105290. case FLAC__METADATA_TYPE_APPLICATION:
  105291. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8))
  105292. return false;
  105293. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.data, metadata->length - (FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8)))
  105294. return false;
  105295. break;
  105296. case FLAC__METADATA_TYPE_SEEKTABLE:
  105297. for(i = 0; i < metadata->data.seek_table.num_points; i++) {
  105298. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].sample_number, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  105299. return false;
  105300. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].stream_offset, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  105301. return false;
  105302. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.seek_table.points[i].frame_samples, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  105303. return false;
  105304. }
  105305. break;
  105306. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  105307. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, vendor_string_length))
  105308. return false;
  105309. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)FLAC__VENDOR_STRING, vendor_string_length))
  105310. return false;
  105311. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.num_comments))
  105312. return false;
  105313. for(i = 0; i < metadata->data.vorbis_comment.num_comments; i++) {
  105314. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.comments[i].length))
  105315. return false;
  105316. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.vorbis_comment.comments[i].entry, metadata->data.vorbis_comment.comments[i].length))
  105317. return false;
  105318. }
  105319. break;
  105320. case FLAC__METADATA_TYPE_CUESHEET:
  105321. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  105322. 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))
  105323. return false;
  105324. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.cue_sheet.lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  105325. return false;
  105326. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.is_cd? 1 : 0, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  105327. return false;
  105328. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  105329. return false;
  105330. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.num_tracks, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  105331. return false;
  105332. for(i = 0; i < metadata->data.cue_sheet.num_tracks; i++) {
  105333. const FLAC__StreamMetadata_CueSheet_Track *track = metadata->data.cue_sheet.tracks + i;
  105334. if(!FLAC__bitwriter_write_raw_uint64(bw, track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  105335. return false;
  105336. if(!FLAC__bitwriter_write_raw_uint32(bw, track->number, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  105337. return false;
  105338. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  105339. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  105340. return false;
  105341. if(!FLAC__bitwriter_write_raw_uint32(bw, track->type, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  105342. return false;
  105343. if(!FLAC__bitwriter_write_raw_uint32(bw, track->pre_emphasis, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  105344. return false;
  105345. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  105346. return false;
  105347. if(!FLAC__bitwriter_write_raw_uint32(bw, track->num_indices, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  105348. return false;
  105349. for(j = 0; j < track->num_indices; j++) {
  105350. const FLAC__StreamMetadata_CueSheet_Index *index = track->indices + j;
  105351. if(!FLAC__bitwriter_write_raw_uint64(bw, index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  105352. return false;
  105353. if(!FLAC__bitwriter_write_raw_uint32(bw, index->number, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  105354. return false;
  105355. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  105356. return false;
  105357. }
  105358. }
  105359. break;
  105360. case FLAC__METADATA_TYPE_PICTURE:
  105361. {
  105362. size_t len;
  105363. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.type, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  105364. return false;
  105365. len = strlen(metadata->data.picture.mime_type);
  105366. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  105367. return false;
  105368. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)metadata->data.picture.mime_type, len))
  105369. return false;
  105370. len = strlen((const char *)metadata->data.picture.description);
  105371. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  105372. return false;
  105373. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.description, len))
  105374. return false;
  105375. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  105376. return false;
  105377. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  105378. return false;
  105379. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  105380. return false;
  105381. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  105382. return false;
  105383. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.data_length, FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  105384. return false;
  105385. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.data, metadata->data.picture.data_length))
  105386. return false;
  105387. }
  105388. break;
  105389. default:
  105390. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.unknown.data, metadata->length))
  105391. return false;
  105392. break;
  105393. }
  105394. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  105395. return true;
  105396. }
  105397. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw)
  105398. {
  105399. unsigned u, blocksize_hint, sample_rate_hint;
  105400. FLAC__byte crc;
  105401. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  105402. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__FRAME_HEADER_SYNC, FLAC__FRAME_HEADER_SYNC_LEN))
  105403. return false;
  105404. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_RESERVED_LEN))
  105405. return false;
  105406. if(!FLAC__bitwriter_write_raw_uint32(bw, (header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER)? 0 : 1, FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN))
  105407. return false;
  105408. FLAC__ASSERT(header->blocksize > 0 && header->blocksize <= FLAC__MAX_BLOCK_SIZE);
  105409. /* when this assertion holds true, any legal blocksize can be expressed in the frame header */
  105410. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535u);
  105411. blocksize_hint = 0;
  105412. switch(header->blocksize) {
  105413. case 192: u = 1; break;
  105414. case 576: u = 2; break;
  105415. case 1152: u = 3; break;
  105416. case 2304: u = 4; break;
  105417. case 4608: u = 5; break;
  105418. case 256: u = 8; break;
  105419. case 512: u = 9; break;
  105420. case 1024: u = 10; break;
  105421. case 2048: u = 11; break;
  105422. case 4096: u = 12; break;
  105423. case 8192: u = 13; break;
  105424. case 16384: u = 14; break;
  105425. case 32768: u = 15; break;
  105426. default:
  105427. if(header->blocksize <= 0x100)
  105428. blocksize_hint = u = 6;
  105429. else
  105430. blocksize_hint = u = 7;
  105431. break;
  105432. }
  105433. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BLOCK_SIZE_LEN))
  105434. return false;
  105435. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(header->sample_rate));
  105436. sample_rate_hint = 0;
  105437. switch(header->sample_rate) {
  105438. case 88200: u = 1; break;
  105439. case 176400: u = 2; break;
  105440. case 192000: u = 3; break;
  105441. case 8000: u = 4; break;
  105442. case 16000: u = 5; break;
  105443. case 22050: u = 6; break;
  105444. case 24000: u = 7; break;
  105445. case 32000: u = 8; break;
  105446. case 44100: u = 9; break;
  105447. case 48000: u = 10; break;
  105448. case 96000: u = 11; break;
  105449. default:
  105450. if(header->sample_rate <= 255000 && header->sample_rate % 1000 == 0)
  105451. sample_rate_hint = u = 12;
  105452. else if(header->sample_rate % 10 == 0)
  105453. sample_rate_hint = u = 14;
  105454. else if(header->sample_rate <= 0xffff)
  105455. sample_rate_hint = u = 13;
  105456. else
  105457. u = 0;
  105458. break;
  105459. }
  105460. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_SAMPLE_RATE_LEN))
  105461. return false;
  105462. FLAC__ASSERT(header->channels > 0 && header->channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN) && header->channels <= FLAC__MAX_CHANNELS);
  105463. switch(header->channel_assignment) {
  105464. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  105465. u = header->channels - 1;
  105466. break;
  105467. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  105468. FLAC__ASSERT(header->channels == 2);
  105469. u = 8;
  105470. break;
  105471. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  105472. FLAC__ASSERT(header->channels == 2);
  105473. u = 9;
  105474. break;
  105475. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  105476. FLAC__ASSERT(header->channels == 2);
  105477. u = 10;
  105478. break;
  105479. default:
  105480. FLAC__ASSERT(0);
  105481. }
  105482. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN))
  105483. return false;
  105484. FLAC__ASSERT(header->bits_per_sample > 0 && header->bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  105485. switch(header->bits_per_sample) {
  105486. case 8 : u = 1; break;
  105487. case 12: u = 2; break;
  105488. case 16: u = 4; break;
  105489. case 20: u = 5; break;
  105490. case 24: u = 6; break;
  105491. default: u = 0; break;
  105492. }
  105493. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN))
  105494. return false;
  105495. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_ZERO_PAD_LEN))
  105496. return false;
  105497. if(header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  105498. if(!FLAC__bitwriter_write_utf8_uint32(bw, header->number.frame_number))
  105499. return false;
  105500. }
  105501. else {
  105502. if(!FLAC__bitwriter_write_utf8_uint64(bw, header->number.sample_number))
  105503. return false;
  105504. }
  105505. if(blocksize_hint)
  105506. if(!FLAC__bitwriter_write_raw_uint32(bw, header->blocksize-1, (blocksize_hint==6)? 8:16))
  105507. return false;
  105508. switch(sample_rate_hint) {
  105509. case 12:
  105510. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 1000, 8))
  105511. return false;
  105512. break;
  105513. case 13:
  105514. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate, 16))
  105515. return false;
  105516. break;
  105517. case 14:
  105518. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 10, 16))
  105519. return false;
  105520. break;
  105521. }
  105522. /* write the CRC */
  105523. if(!FLAC__bitwriter_get_write_crc8(bw, &crc))
  105524. return false;
  105525. if(!FLAC__bitwriter_write_raw_uint32(bw, crc, FLAC__FRAME_HEADER_CRC_LEN))
  105526. return false;
  105527. return true;
  105528. }
  105529. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  105530. {
  105531. FLAC__bool ok;
  105532. ok =
  105533. 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) &&
  105534. (wasted_bits? FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1) : true) &&
  105535. FLAC__bitwriter_write_raw_int32(bw, subframe->value, subframe_bps)
  105536. ;
  105537. return ok;
  105538. }
  105539. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  105540. {
  105541. unsigned i;
  105542. 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))
  105543. return false;
  105544. if(wasted_bits)
  105545. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  105546. return false;
  105547. for(i = 0; i < subframe->order; i++)
  105548. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  105549. return false;
  105550. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  105551. return false;
  105552. switch(subframe->entropy_coding_method.type) {
  105553. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  105554. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  105555. if(!add_residual_partitioned_rice_(
  105556. bw,
  105557. subframe->residual,
  105558. residual_samples,
  105559. subframe->order,
  105560. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  105561. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  105562. subframe->entropy_coding_method.data.partitioned_rice.order,
  105563. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  105564. ))
  105565. return false;
  105566. break;
  105567. default:
  105568. FLAC__ASSERT(0);
  105569. }
  105570. return true;
  105571. }
  105572. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  105573. {
  105574. unsigned i;
  105575. 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))
  105576. return false;
  105577. if(wasted_bits)
  105578. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  105579. return false;
  105580. for(i = 0; i < subframe->order; i++)
  105581. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  105582. return false;
  105583. if(!FLAC__bitwriter_write_raw_uint32(bw, subframe->qlp_coeff_precision-1, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  105584. return false;
  105585. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->quantization_level, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  105586. return false;
  105587. for(i = 0; i < subframe->order; i++)
  105588. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->qlp_coeff[i], subframe->qlp_coeff_precision))
  105589. return false;
  105590. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  105591. return false;
  105592. switch(subframe->entropy_coding_method.type) {
  105593. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  105594. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  105595. if(!add_residual_partitioned_rice_(
  105596. bw,
  105597. subframe->residual,
  105598. residual_samples,
  105599. subframe->order,
  105600. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  105601. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  105602. subframe->entropy_coding_method.data.partitioned_rice.order,
  105603. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  105604. ))
  105605. return false;
  105606. break;
  105607. default:
  105608. FLAC__ASSERT(0);
  105609. }
  105610. return true;
  105611. }
  105612. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  105613. {
  105614. unsigned i;
  105615. const FLAC__int32 *signal = subframe->data;
  105616. 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))
  105617. return false;
  105618. if(wasted_bits)
  105619. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  105620. return false;
  105621. for(i = 0; i < samples; i++)
  105622. if(!FLAC__bitwriter_write_raw_int32(bw, signal[i], subframe_bps))
  105623. return false;
  105624. return true;
  105625. }
  105626. FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method)
  105627. {
  105628. if(!FLAC__bitwriter_write_raw_uint32(bw, method->type, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  105629. return false;
  105630. switch(method->type) {
  105631. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  105632. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  105633. if(!FLAC__bitwriter_write_raw_uint32(bw, method->data.partitioned_rice.order, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  105634. return false;
  105635. break;
  105636. default:
  105637. FLAC__ASSERT(0);
  105638. }
  105639. return true;
  105640. }
  105641. 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)
  105642. {
  105643. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  105644. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  105645. if(partition_order == 0) {
  105646. unsigned i;
  105647. if(raw_bits[0] == 0) {
  105648. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[0], plen))
  105649. return false;
  105650. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual, residual_samples, rice_parameters[0]))
  105651. return false;
  105652. }
  105653. else {
  105654. FLAC__ASSERT(rice_parameters[0] == 0);
  105655. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  105656. return false;
  105657. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[0], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  105658. return false;
  105659. for(i = 0; i < residual_samples; i++) {
  105660. if(!FLAC__bitwriter_write_raw_int32(bw, residual[i], raw_bits[0]))
  105661. return false;
  105662. }
  105663. }
  105664. return true;
  105665. }
  105666. else {
  105667. unsigned i, j, k = 0, k_last = 0;
  105668. unsigned partition_samples;
  105669. const unsigned default_partition_samples = (residual_samples+predictor_order) >> partition_order;
  105670. for(i = 0; i < (1u<<partition_order); i++) {
  105671. partition_samples = default_partition_samples;
  105672. if(i == 0)
  105673. partition_samples -= predictor_order;
  105674. k += partition_samples;
  105675. if(raw_bits[i] == 0) {
  105676. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[i], plen))
  105677. return false;
  105678. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual+k_last, k-k_last, rice_parameters[i]))
  105679. return false;
  105680. }
  105681. else {
  105682. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  105683. return false;
  105684. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[i], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  105685. return false;
  105686. for(j = k_last; j < k; j++) {
  105687. if(!FLAC__bitwriter_write_raw_int32(bw, residual[j], raw_bits[i]))
  105688. return false;
  105689. }
  105690. }
  105691. k_last = k;
  105692. }
  105693. return true;
  105694. }
  105695. }
  105696. #endif
  105697. /*** End of inlined file: stream_encoder_framing.c ***/
  105698. /*** Start of inlined file: window_flac.c ***/
  105699. /*** Start of inlined file: juce_FlacHeader.h ***/
  105700. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  105701. // tasks..
  105702. #define VERSION "1.2.1"
  105703. #define FLAC__NO_DLL 1
  105704. #if JUCE_MSVC
  105705. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  105706. #endif
  105707. #if JUCE_MAC
  105708. #define FLAC__SYS_DARWIN 1
  105709. #endif
  105710. /*** End of inlined file: juce_FlacHeader.h ***/
  105711. #if JUCE_USE_FLAC
  105712. #if HAVE_CONFIG_H
  105713. # include <config.h>
  105714. #endif
  105715. #include <math.h>
  105716. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105717. #ifndef M_PI
  105718. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  105719. #define M_PI 3.14159265358979323846
  105720. #endif
  105721. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L)
  105722. {
  105723. const FLAC__int32 N = L - 1;
  105724. FLAC__int32 n;
  105725. if (L & 1) {
  105726. for (n = 0; n <= N/2; n++)
  105727. window[n] = 2.0f * n / (float)N;
  105728. for (; n <= N; n++)
  105729. window[n] = 2.0f - 2.0f * n / (float)N;
  105730. }
  105731. else {
  105732. for (n = 0; n <= L/2-1; n++)
  105733. window[n] = 2.0f * n / (float)N;
  105734. for (; n <= N; n++)
  105735. window[n] = 2.0f - 2.0f * (N-n) / (float)N;
  105736. }
  105737. }
  105738. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L)
  105739. {
  105740. const FLAC__int32 N = L - 1;
  105741. FLAC__int32 n;
  105742. for (n = 0; n < L; n++)
  105743. 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)));
  105744. }
  105745. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L)
  105746. {
  105747. const FLAC__int32 N = L - 1;
  105748. FLAC__int32 n;
  105749. for (n = 0; n < L; n++)
  105750. window[n] = (FLAC__real)(0.42f - 0.5f * cos(2.0f * M_PI * n / N) + 0.08f * cos(4.0f * M_PI * n / N));
  105751. }
  105752. /* 4-term -92dB side-lobe */
  105753. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L)
  105754. {
  105755. const FLAC__int32 N = L - 1;
  105756. FLAC__int32 n;
  105757. for (n = 0; n <= N; n++)
  105758. 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));
  105759. }
  105760. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L)
  105761. {
  105762. const FLAC__int32 N = L - 1;
  105763. const double N2 = (double)N / 2.;
  105764. FLAC__int32 n;
  105765. for (n = 0; n <= N; n++) {
  105766. double k = ((double)n - N2) / N2;
  105767. k = 1.0f - k * k;
  105768. window[n] = (FLAC__real)(k * k);
  105769. }
  105770. }
  105771. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L)
  105772. {
  105773. const FLAC__int32 N = L - 1;
  105774. FLAC__int32 n;
  105775. for (n = 0; n < L; n++)
  105776. 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));
  105777. }
  105778. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev)
  105779. {
  105780. const FLAC__int32 N = L - 1;
  105781. const double N2 = (double)N / 2.;
  105782. FLAC__int32 n;
  105783. for (n = 0; n <= N; n++) {
  105784. const double k = ((double)n - N2) / (stddev * N2);
  105785. window[n] = (FLAC__real)exp(-0.5f * k * k);
  105786. }
  105787. }
  105788. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L)
  105789. {
  105790. const FLAC__int32 N = L - 1;
  105791. FLAC__int32 n;
  105792. for (n = 0; n < L; n++)
  105793. window[n] = (FLAC__real)(0.54f - 0.46f * cos(2.0f * M_PI * n / N));
  105794. }
  105795. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L)
  105796. {
  105797. const FLAC__int32 N = L - 1;
  105798. FLAC__int32 n;
  105799. for (n = 0; n < L; n++)
  105800. window[n] = (FLAC__real)(0.5f - 0.5f * cos(2.0f * M_PI * n / N));
  105801. }
  105802. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L)
  105803. {
  105804. const FLAC__int32 N = L - 1;
  105805. FLAC__int32 n;
  105806. for (n = 0; n < L; n++)
  105807. 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));
  105808. }
  105809. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L)
  105810. {
  105811. const FLAC__int32 N = L - 1;
  105812. FLAC__int32 n;
  105813. for (n = 0; n < L; n++)
  105814. 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));
  105815. }
  105816. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L)
  105817. {
  105818. FLAC__int32 n;
  105819. for (n = 0; n < L; n++)
  105820. window[n] = 1.0f;
  105821. }
  105822. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L)
  105823. {
  105824. FLAC__int32 n;
  105825. if (L & 1) {
  105826. for (n = 1; n <= L+1/2; n++)
  105827. window[n-1] = 2.0f * n / ((float)L + 1.0f);
  105828. for (; n <= L; n++)
  105829. window[n-1] = - (float)(2 * (L - n + 1)) / ((float)L + 1.0f);
  105830. }
  105831. else {
  105832. for (n = 1; n <= L/2; n++)
  105833. window[n-1] = 2.0f * n / (float)L;
  105834. for (; n <= L; n++)
  105835. window[n-1] = ((float)(2 * (L - n)) + 1.0f) / (float)L;
  105836. }
  105837. }
  105838. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p)
  105839. {
  105840. if (p <= 0.0)
  105841. FLAC__window_rectangle(window, L);
  105842. else if (p >= 1.0)
  105843. FLAC__window_hann(window, L);
  105844. else {
  105845. const FLAC__int32 Np = (FLAC__int32)(p / 2.0f * L) - 1;
  105846. FLAC__int32 n;
  105847. /* start with rectangle... */
  105848. FLAC__window_rectangle(window, L);
  105849. /* ...replace ends with hann */
  105850. if (Np > 0) {
  105851. for (n = 0; n <= Np; n++) {
  105852. window[n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * n / Np));
  105853. window[L-Np-1+n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * (n+Np) / Np));
  105854. }
  105855. }
  105856. }
  105857. }
  105858. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L)
  105859. {
  105860. const FLAC__int32 N = L - 1;
  105861. const double N2 = (double)N / 2.;
  105862. FLAC__int32 n;
  105863. for (n = 0; n <= N; n++) {
  105864. const double k = ((double)n - N2) / N2;
  105865. window[n] = (FLAC__real)(1.0f - k * k);
  105866. }
  105867. }
  105868. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  105869. #endif
  105870. /*** End of inlined file: window_flac.c ***/
  105871. #else
  105872. #include <FLAC/all.h>
  105873. #endif
  105874. }
  105875. #undef max
  105876. #undef min
  105877. BEGIN_JUCE_NAMESPACE
  105878. static const char* const flacFormatName = "FLAC file";
  105879. static const char* const flacExtensions[] = { ".flac", 0 };
  105880. class FlacReader : public AudioFormatReader
  105881. {
  105882. public:
  105883. FlacReader (InputStream* const in)
  105884. : AudioFormatReader (in, TRANS (flacFormatName)),
  105885. reservoir (2, 0),
  105886. reservoirStart (0),
  105887. samplesInReservoir (0),
  105888. scanningForLength (false)
  105889. {
  105890. using namespace FlacNamespace;
  105891. lengthInSamples = 0;
  105892. decoder = FLAC__stream_decoder_new();
  105893. ok = FLAC__stream_decoder_init_stream (decoder,
  105894. readCallback_, seekCallback_, tellCallback_, lengthCallback_,
  105895. eofCallback_, writeCallback_, metadataCallback_, errorCallback_,
  105896. this) == FLAC__STREAM_DECODER_INIT_STATUS_OK;
  105897. if (ok)
  105898. {
  105899. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  105900. if (lengthInSamples == 0 && sampleRate > 0)
  105901. {
  105902. // the length hasn't been stored in the metadata, so we'll need to
  105903. // work it out the length the hard way, by scanning the whole file..
  105904. scanningForLength = true;
  105905. FLAC__stream_decoder_process_until_end_of_stream (decoder);
  105906. scanningForLength = false;
  105907. const int64 tempLength = lengthInSamples;
  105908. FLAC__stream_decoder_reset (decoder);
  105909. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  105910. lengthInSamples = tempLength;
  105911. }
  105912. }
  105913. }
  105914. ~FlacReader()
  105915. {
  105916. FlacNamespace::FLAC__stream_decoder_delete (decoder);
  105917. }
  105918. void useMetadata (const FlacNamespace::FLAC__StreamMetadata_StreamInfo& info)
  105919. {
  105920. sampleRate = info.sample_rate;
  105921. bitsPerSample = info.bits_per_sample;
  105922. lengthInSamples = (unsigned int) info.total_samples;
  105923. numChannels = info.channels;
  105924. reservoir.setSize (numChannels, 2 * info.max_blocksize, false, false, true);
  105925. }
  105926. // returns the number of samples read
  105927. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  105928. int64 startSampleInFile, int numSamples)
  105929. {
  105930. using namespace FlacNamespace;
  105931. if (! ok)
  105932. return false;
  105933. while (numSamples > 0)
  105934. {
  105935. if (startSampleInFile >= reservoirStart
  105936. && startSampleInFile < reservoirStart + samplesInReservoir)
  105937. {
  105938. const int num = (int) jmin ((int64) numSamples,
  105939. reservoirStart + samplesInReservoir - startSampleInFile);
  105940. jassert (num > 0);
  105941. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  105942. if (destSamples[i] != 0)
  105943. memcpy (destSamples[i] + startOffsetInDestBuffer,
  105944. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  105945. sizeof (int) * num);
  105946. startOffsetInDestBuffer += num;
  105947. startSampleInFile += num;
  105948. numSamples -= num;
  105949. }
  105950. else
  105951. {
  105952. if (startSampleInFile >= (int) lengthInSamples)
  105953. {
  105954. samplesInReservoir = 0;
  105955. }
  105956. else if (startSampleInFile < reservoirStart
  105957. || startSampleInFile > reservoirStart + jmax (samplesInReservoir, 511))
  105958. {
  105959. // had some problems with flac crashing if the read pos is aligned more
  105960. // accurately than this. Probably fixed in newer versions of the library, though.
  105961. reservoirStart = (int) (startSampleInFile & ~511);
  105962. samplesInReservoir = 0;
  105963. FLAC__stream_decoder_seek_absolute (decoder, (FLAC__uint64) reservoirStart);
  105964. }
  105965. else
  105966. {
  105967. reservoirStart += samplesInReservoir;
  105968. samplesInReservoir = 0;
  105969. FLAC__stream_decoder_process_single (decoder);
  105970. }
  105971. if (samplesInReservoir == 0)
  105972. break;
  105973. }
  105974. }
  105975. if (numSamples > 0)
  105976. {
  105977. for (int i = numDestChannels; --i >= 0;)
  105978. if (destSamples[i] != 0)
  105979. zeromem (destSamples[i] + startOffsetInDestBuffer,
  105980. sizeof (int) * numSamples);
  105981. }
  105982. return true;
  105983. }
  105984. void useSamples (const FlacNamespace::FLAC__int32* const buffer[], int numSamples)
  105985. {
  105986. if (scanningForLength)
  105987. {
  105988. lengthInSamples += numSamples;
  105989. }
  105990. else
  105991. {
  105992. if (numSamples > reservoir.getNumSamples())
  105993. reservoir.setSize (numChannels, numSamples, false, false, true);
  105994. const int bitsToShift = 32 - bitsPerSample;
  105995. for (int i = 0; i < (int) numChannels; ++i)
  105996. {
  105997. const FlacNamespace::FLAC__int32* src = buffer[i];
  105998. int n = i;
  105999. while (src == 0 && n > 0)
  106000. src = buffer [--n];
  106001. if (src != 0)
  106002. {
  106003. int* dest = (int*) reservoir.getSampleData(i);
  106004. for (int j = 0; j < numSamples; ++j)
  106005. dest[j] = src[j] << bitsToShift;
  106006. }
  106007. }
  106008. samplesInReservoir = numSamples;
  106009. }
  106010. }
  106011. static FlacNamespace::FLAC__StreamDecoderReadStatus readCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__byte buffer[], size_t* bytes, void* client_data)
  106012. {
  106013. using namespace FlacNamespace;
  106014. *bytes = (size_t) static_cast <const FlacReader*> (client_data)->input->read (buffer, (int) *bytes);
  106015. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  106016. }
  106017. static FlacNamespace::FLAC__StreamDecoderSeekStatus seekCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64 absolute_byte_offset, void* client_data)
  106018. {
  106019. using namespace FlacNamespace;
  106020. static_cast <const FlacReader*> (client_data)->input->setPosition ((int) absolute_byte_offset);
  106021. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  106022. }
  106023. static FlacNamespace::FLAC__StreamDecoderTellStatus tellCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  106024. {
  106025. using namespace FlacNamespace;
  106026. *absolute_byte_offset = static_cast <const FlacReader*> (client_data)->input->getPosition();
  106027. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  106028. }
  106029. static FlacNamespace::FLAC__StreamDecoderLengthStatus lengthCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* stream_length, void* client_data)
  106030. {
  106031. using namespace FlacNamespace;
  106032. *stream_length = static_cast <const FlacReader*> (client_data)->input->getTotalLength();
  106033. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  106034. }
  106035. static FlacNamespace::FLAC__bool eofCallback_ (const FlacNamespace::FLAC__StreamDecoder*, void* client_data)
  106036. {
  106037. return static_cast <const FlacReader*> (client_data)->input->isExhausted();
  106038. }
  106039. static FlacNamespace::FLAC__StreamDecoderWriteStatus writeCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  106040. const FlacNamespace::FLAC__Frame* frame,
  106041. const FlacNamespace::FLAC__int32* const buffer[],
  106042. void* client_data)
  106043. {
  106044. using namespace FlacNamespace;
  106045. static_cast <FlacReader*> (client_data)->useSamples (buffer, frame->header.blocksize);
  106046. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  106047. }
  106048. static void metadataCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  106049. const FlacNamespace::FLAC__StreamMetadata* metadata,
  106050. void* client_data)
  106051. {
  106052. static_cast <FlacReader*> (client_data)->useMetadata (metadata->data.stream_info);
  106053. }
  106054. static void errorCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__StreamDecoderErrorStatus, void*)
  106055. {
  106056. }
  106057. juce_UseDebuggingNewOperator
  106058. private:
  106059. FlacNamespace::FLAC__StreamDecoder* decoder;
  106060. AudioSampleBuffer reservoir;
  106061. int reservoirStart, samplesInReservoir;
  106062. bool ok, scanningForLength;
  106063. FlacReader (const FlacReader&);
  106064. FlacReader& operator= (const FlacReader&);
  106065. };
  106066. class FlacWriter : public AudioFormatWriter
  106067. {
  106068. public:
  106069. FlacWriter (OutputStream* const out,
  106070. const double sampleRate_,
  106071. const int numChannels_,
  106072. const int bitsPerSample_)
  106073. : AudioFormatWriter (out, TRANS (flacFormatName),
  106074. sampleRate_,
  106075. numChannels_,
  106076. bitsPerSample_)
  106077. {
  106078. using namespace FlacNamespace;
  106079. encoder = FLAC__stream_encoder_new();
  106080. FLAC__stream_encoder_set_do_mid_side_stereo (encoder, numChannels == 2);
  106081. FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, numChannels == 2);
  106082. FLAC__stream_encoder_set_channels (encoder, numChannels);
  106083. FLAC__stream_encoder_set_bits_per_sample (encoder, jmin ((unsigned int) 24, bitsPerSample));
  106084. FLAC__stream_encoder_set_sample_rate (encoder, (unsigned int) sampleRate);
  106085. FLAC__stream_encoder_set_blocksize (encoder, 2048);
  106086. FLAC__stream_encoder_set_do_escape_coding (encoder, true);
  106087. ok = FLAC__stream_encoder_init_stream (encoder,
  106088. encodeWriteCallback, encodeSeekCallback,
  106089. encodeTellCallback, encodeMetadataCallback,
  106090. this) == FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  106091. }
  106092. ~FlacWriter()
  106093. {
  106094. if (ok)
  106095. {
  106096. FlacNamespace::FLAC__stream_encoder_finish (encoder);
  106097. output->flush();
  106098. }
  106099. else
  106100. {
  106101. output = 0; // to stop the base class deleting this, as it needs to be returned
  106102. // to the caller of createWriter()
  106103. }
  106104. FlacNamespace::FLAC__stream_encoder_delete (encoder);
  106105. }
  106106. bool write (const int** samplesToWrite, int numSamples)
  106107. {
  106108. using namespace FlacNamespace;
  106109. if (! ok)
  106110. return false;
  106111. int* buf[3];
  106112. const int bitsToShift = 32 - bitsPerSample;
  106113. if (bitsToShift > 0)
  106114. {
  106115. const int numChannelsToWrite = (samplesToWrite[1] == 0) ? 1 : 2;
  106116. temp.setSize (sizeof (int) * numSamples * numChannelsToWrite);
  106117. buf[0] = (int*) temp.getData();
  106118. buf[1] = buf[0] + numSamples;
  106119. buf[2] = 0;
  106120. for (int i = numChannelsToWrite; --i >= 0;)
  106121. {
  106122. if (samplesToWrite[i] != 0)
  106123. {
  106124. for (int j = 0; j < numSamples; ++j)
  106125. buf [i][j] = (samplesToWrite [i][j] >> bitsToShift);
  106126. }
  106127. }
  106128. samplesToWrite = (const int**) buf;
  106129. }
  106130. return FLAC__stream_encoder_process (encoder,
  106131. (const FLAC__int32**) samplesToWrite,
  106132. numSamples) != 0;
  106133. }
  106134. bool writeData (const void* const data, const int size) const
  106135. {
  106136. return output->write (data, size);
  106137. }
  106138. static void packUint32 (FlacNamespace::FLAC__uint32 val, FlacNamespace::FLAC__byte* b, const int bytes)
  106139. {
  106140. using namespace FlacNamespace;
  106141. b += bytes;
  106142. for (int i = 0; i < bytes; ++i)
  106143. {
  106144. *(--b) = (FLAC__byte) (val & 0xff);
  106145. val >>= 8;
  106146. }
  106147. }
  106148. void writeMetaData (const FlacNamespace::FLAC__StreamMetadata* metadata)
  106149. {
  106150. using namespace FlacNamespace;
  106151. const FLAC__StreamMetadata_StreamInfo& info = metadata->data.stream_info;
  106152. unsigned char buffer [FLAC__STREAM_METADATA_STREAMINFO_LENGTH];
  106153. const unsigned int channelsMinus1 = info.channels - 1;
  106154. const unsigned int bitsMinus1 = info.bits_per_sample - 1;
  106155. packUint32 (info.min_blocksize, buffer, 2);
  106156. packUint32 (info.max_blocksize, buffer + 2, 2);
  106157. packUint32 (info.min_framesize, buffer + 4, 3);
  106158. packUint32 (info.max_framesize, buffer + 7, 3);
  106159. buffer[10] = (uint8) ((info.sample_rate >> 12) & 0xff);
  106160. buffer[11] = (uint8) ((info.sample_rate >> 4) & 0xff);
  106161. buffer[12] = (uint8) (((info.sample_rate & 0x0f) << 4) | (channelsMinus1 << 1) | (bitsMinus1 >> 4));
  106162. buffer[13] = (FLAC__byte) (((bitsMinus1 & 0x0f) << 4) | (unsigned int) ((info.total_samples >> 32) & 0x0f));
  106163. packUint32 ((FLAC__uint32) info.total_samples, buffer + 14, 4);
  106164. memcpy (buffer + 18, info.md5sum, 16);
  106165. const bool seekOk = output->setPosition (4);
  106166. (void) seekOk;
  106167. // if this fails, you've given it an output stream that can't seek! It needs
  106168. // to be able to seek back to write the header
  106169. jassert (seekOk);
  106170. output->writeIntBigEndian (FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  106171. output->write (buffer, FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  106172. }
  106173. static FlacNamespace::FLAC__StreamEncoderWriteStatus encodeWriteCallback (const FlacNamespace::FLAC__StreamEncoder*,
  106174. const FlacNamespace::FLAC__byte buffer[],
  106175. size_t bytes,
  106176. unsigned int /*samples*/,
  106177. unsigned int /*current_frame*/,
  106178. void* client_data)
  106179. {
  106180. using namespace FlacNamespace;
  106181. return static_cast <FlacWriter*> (client_data)->writeData (buffer, (int) bytes)
  106182. ? FLAC__STREAM_ENCODER_WRITE_STATUS_OK
  106183. : FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  106184. }
  106185. static FlacNamespace::FLAC__StreamEncoderSeekStatus encodeSeekCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64, void*)
  106186. {
  106187. using namespace FlacNamespace;
  106188. return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  106189. }
  106190. static FlacNamespace::FLAC__StreamEncoderTellStatus encodeTellCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  106191. {
  106192. using namespace FlacNamespace;
  106193. if (client_data == 0)
  106194. return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  106195. *absolute_byte_offset = (FLAC__uint64) static_cast <FlacWriter*> (client_data)->output->getPosition();
  106196. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  106197. }
  106198. static void encodeMetadataCallback (const FlacNamespace::FLAC__StreamEncoder*, const FlacNamespace::FLAC__StreamMetadata* metadata, void* client_data)
  106199. {
  106200. static_cast <FlacWriter*> (client_data)->writeMetaData (metadata);
  106201. }
  106202. juce_UseDebuggingNewOperator
  106203. bool ok;
  106204. private:
  106205. FlacNamespace::FLAC__StreamEncoder* encoder;
  106206. MemoryBlock temp;
  106207. FlacWriter (const FlacWriter&);
  106208. FlacWriter& operator= (const FlacWriter&);
  106209. };
  106210. FlacAudioFormat::FlacAudioFormat()
  106211. : AudioFormat (TRANS (flacFormatName), StringArray (flacExtensions))
  106212. {
  106213. }
  106214. FlacAudioFormat::~FlacAudioFormat()
  106215. {
  106216. }
  106217. const Array <int> FlacAudioFormat::getPossibleSampleRates()
  106218. {
  106219. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 0 };
  106220. return Array <int> (rates);
  106221. }
  106222. const Array <int> FlacAudioFormat::getPossibleBitDepths()
  106223. {
  106224. const int depths[] = { 16, 24, 0 };
  106225. return Array <int> (depths);
  106226. }
  106227. bool FlacAudioFormat::canDoStereo()
  106228. {
  106229. return true;
  106230. }
  106231. bool FlacAudioFormat::canDoMono()
  106232. {
  106233. return true;
  106234. }
  106235. bool FlacAudioFormat::isCompressed()
  106236. {
  106237. return true;
  106238. }
  106239. AudioFormatReader* FlacAudioFormat::createReaderFor (InputStream* in,
  106240. const bool deleteStreamIfOpeningFails)
  106241. {
  106242. ScopedPointer<FlacReader> r (new FlacReader (in));
  106243. if (r->sampleRate != 0)
  106244. return r.release();
  106245. if (! deleteStreamIfOpeningFails)
  106246. r->input = 0;
  106247. return 0;
  106248. }
  106249. AudioFormatWriter* FlacAudioFormat::createWriterFor (OutputStream* out,
  106250. double sampleRate,
  106251. unsigned int numberOfChannels,
  106252. int bitsPerSample,
  106253. const StringPairArray& /*metadataValues*/,
  106254. int /*qualityOptionIndex*/)
  106255. {
  106256. if (getPossibleBitDepths().contains (bitsPerSample))
  106257. {
  106258. ScopedPointer<FlacWriter> w (new FlacWriter (out, sampleRate, numberOfChannels, bitsPerSample));
  106259. if (w->ok)
  106260. return w.release();
  106261. }
  106262. return 0;
  106263. }
  106264. END_JUCE_NAMESPACE
  106265. #endif
  106266. /*** End of inlined file: juce_FlacAudioFormat.cpp ***/
  106267. /*** Start of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  106268. #if JUCE_USE_OGGVORBIS
  106269. #if JUCE_MAC
  106270. #define __MACOSX__ 1
  106271. #endif
  106272. namespace OggVorbisNamespace
  106273. {
  106274. #if JUCE_INCLUDE_OGGVORBIS_CODE
  106275. /*** Start of inlined file: vorbisenc.h ***/
  106276. #ifndef _OV_ENC_H_
  106277. #define _OV_ENC_H_
  106278. #ifdef __cplusplus
  106279. extern "C"
  106280. {
  106281. #endif /* __cplusplus */
  106282. /*** Start of inlined file: codec.h ***/
  106283. #ifndef _vorbis_codec_h_
  106284. #define _vorbis_codec_h_
  106285. #ifdef __cplusplus
  106286. extern "C"
  106287. {
  106288. #endif /* __cplusplus */
  106289. /*** Start of inlined file: ogg.h ***/
  106290. #ifndef _OGG_H
  106291. #define _OGG_H
  106292. #ifdef __cplusplus
  106293. extern "C" {
  106294. #endif
  106295. /*** Start of inlined file: os_types.h ***/
  106296. #ifndef _OS_TYPES_H
  106297. #define _OS_TYPES_H
  106298. /* make it easy on the folks that want to compile the libs with a
  106299. different malloc than stdlib */
  106300. #define _ogg_malloc malloc
  106301. #define _ogg_calloc calloc
  106302. #define _ogg_realloc realloc
  106303. #define _ogg_free free
  106304. #if defined(_WIN32)
  106305. # if defined(__CYGWIN__)
  106306. # include <_G_config.h>
  106307. typedef _G_int64_t ogg_int64_t;
  106308. typedef _G_int32_t ogg_int32_t;
  106309. typedef _G_uint32_t ogg_uint32_t;
  106310. typedef _G_int16_t ogg_int16_t;
  106311. typedef _G_uint16_t ogg_uint16_t;
  106312. # elif defined(__MINGW32__)
  106313. typedef short ogg_int16_t;
  106314. typedef unsigned short ogg_uint16_t;
  106315. typedef int ogg_int32_t;
  106316. typedef unsigned int ogg_uint32_t;
  106317. typedef long long ogg_int64_t;
  106318. typedef unsigned long long ogg_uint64_t;
  106319. # elif defined(__MWERKS__)
  106320. typedef long long ogg_int64_t;
  106321. typedef int ogg_int32_t;
  106322. typedef unsigned int ogg_uint32_t;
  106323. typedef short ogg_int16_t;
  106324. typedef unsigned short ogg_uint16_t;
  106325. # else
  106326. /* MSVC/Borland */
  106327. typedef __int64 ogg_int64_t;
  106328. typedef __int32 ogg_int32_t;
  106329. typedef unsigned __int32 ogg_uint32_t;
  106330. typedef __int16 ogg_int16_t;
  106331. typedef unsigned __int16 ogg_uint16_t;
  106332. # endif
  106333. #elif defined(__MACOS__)
  106334. # include <sys/types.h>
  106335. typedef SInt16 ogg_int16_t;
  106336. typedef UInt16 ogg_uint16_t;
  106337. typedef SInt32 ogg_int32_t;
  106338. typedef UInt32 ogg_uint32_t;
  106339. typedef SInt64 ogg_int64_t;
  106340. #elif defined(__MACOSX__) /* MacOS X Framework build */
  106341. # include <sys/types.h>
  106342. typedef int16_t ogg_int16_t;
  106343. typedef u_int16_t ogg_uint16_t;
  106344. typedef int32_t ogg_int32_t;
  106345. typedef u_int32_t ogg_uint32_t;
  106346. typedef int64_t ogg_int64_t;
  106347. #elif defined(__BEOS__)
  106348. /* Be */
  106349. # include <inttypes.h>
  106350. typedef int16_t ogg_int16_t;
  106351. typedef u_int16_t ogg_uint16_t;
  106352. typedef int32_t ogg_int32_t;
  106353. typedef u_int32_t ogg_uint32_t;
  106354. typedef int64_t ogg_int64_t;
  106355. #elif defined (__EMX__)
  106356. /* OS/2 GCC */
  106357. typedef short ogg_int16_t;
  106358. typedef unsigned short ogg_uint16_t;
  106359. typedef int ogg_int32_t;
  106360. typedef unsigned int ogg_uint32_t;
  106361. typedef long long ogg_int64_t;
  106362. #elif defined (DJGPP)
  106363. /* DJGPP */
  106364. typedef short ogg_int16_t;
  106365. typedef int ogg_int32_t;
  106366. typedef unsigned int ogg_uint32_t;
  106367. typedef long long ogg_int64_t;
  106368. #elif defined(R5900)
  106369. /* PS2 EE */
  106370. typedef long ogg_int64_t;
  106371. typedef int ogg_int32_t;
  106372. typedef unsigned ogg_uint32_t;
  106373. typedef short ogg_int16_t;
  106374. #elif defined(__SYMBIAN32__)
  106375. /* Symbian GCC */
  106376. typedef signed short ogg_int16_t;
  106377. typedef unsigned short ogg_uint16_t;
  106378. typedef signed int ogg_int32_t;
  106379. typedef unsigned int ogg_uint32_t;
  106380. typedef long long int ogg_int64_t;
  106381. #else
  106382. # include <sys/types.h>
  106383. /*** Start of inlined file: config_types.h ***/
  106384. #ifndef __CONFIG_TYPES_H__
  106385. #define __CONFIG_TYPES_H__
  106386. typedef int16_t ogg_int16_t;
  106387. typedef unsigned short ogg_uint16_t;
  106388. typedef int32_t ogg_int32_t;
  106389. typedef unsigned int ogg_uint32_t;
  106390. typedef int64_t ogg_int64_t;
  106391. #endif
  106392. /*** End of inlined file: config_types.h ***/
  106393. #endif
  106394. #endif /* _OS_TYPES_H */
  106395. /*** End of inlined file: os_types.h ***/
  106396. typedef struct {
  106397. long endbyte;
  106398. int endbit;
  106399. unsigned char *buffer;
  106400. unsigned char *ptr;
  106401. long storage;
  106402. } oggpack_buffer;
  106403. /* ogg_page is used to encapsulate the data in one Ogg bitstream page *****/
  106404. typedef struct {
  106405. unsigned char *header;
  106406. long header_len;
  106407. unsigned char *body;
  106408. long body_len;
  106409. } ogg_page;
  106410. ogg_uint32_t ogg_bitreverse(ogg_uint32_t x){
  106411. x= ((x>>16)&0x0000ffffUL) | ((x<<16)&0xffff0000UL);
  106412. x= ((x>> 8)&0x00ff00ffUL) | ((x<< 8)&0xff00ff00UL);
  106413. x= ((x>> 4)&0x0f0f0f0fUL) | ((x<< 4)&0xf0f0f0f0UL);
  106414. x= ((x>> 2)&0x33333333UL) | ((x<< 2)&0xccccccccUL);
  106415. return((x>> 1)&0x55555555UL) | ((x<< 1)&0xaaaaaaaaUL);
  106416. }
  106417. /* ogg_stream_state contains the current encode/decode state of a logical
  106418. Ogg bitstream **********************************************************/
  106419. typedef struct {
  106420. unsigned char *body_data; /* bytes from packet bodies */
  106421. long body_storage; /* storage elements allocated */
  106422. long body_fill; /* elements stored; fill mark */
  106423. long body_returned; /* elements of fill returned */
  106424. int *lacing_vals; /* The values that will go to the segment table */
  106425. ogg_int64_t *granule_vals; /* granulepos values for headers. Not compact
  106426. this way, but it is simple coupled to the
  106427. lacing fifo */
  106428. long lacing_storage;
  106429. long lacing_fill;
  106430. long lacing_packet;
  106431. long lacing_returned;
  106432. unsigned char header[282]; /* working space for header encode */
  106433. int header_fill;
  106434. int e_o_s; /* set when we have buffered the last packet in the
  106435. logical bitstream */
  106436. int b_o_s; /* set after we've written the initial page
  106437. of a logical bitstream */
  106438. long serialno;
  106439. long pageno;
  106440. ogg_int64_t packetno; /* sequence number for decode; the framing
  106441. knows where there's a hole in the data,
  106442. but we need coupling so that the codec
  106443. (which is in a seperate abstraction
  106444. layer) also knows about the gap */
  106445. ogg_int64_t granulepos;
  106446. } ogg_stream_state;
  106447. /* ogg_packet is used to encapsulate the data and metadata belonging
  106448. to a single raw Ogg/Vorbis packet *************************************/
  106449. typedef struct {
  106450. unsigned char *packet;
  106451. long bytes;
  106452. long b_o_s;
  106453. long e_o_s;
  106454. ogg_int64_t granulepos;
  106455. ogg_int64_t packetno; /* sequence number for decode; the framing
  106456. knows where there's a hole in the data,
  106457. but we need coupling so that the codec
  106458. (which is in a seperate abstraction
  106459. layer) also knows about the gap */
  106460. } ogg_packet;
  106461. typedef struct {
  106462. unsigned char *data;
  106463. int storage;
  106464. int fill;
  106465. int returned;
  106466. int unsynced;
  106467. int headerbytes;
  106468. int bodybytes;
  106469. } ogg_sync_state;
  106470. /* Ogg BITSTREAM PRIMITIVES: bitstream ************************/
  106471. extern void oggpack_writeinit(oggpack_buffer *b);
  106472. extern void oggpack_writetrunc(oggpack_buffer *b,long bits);
  106473. extern void oggpack_writealign(oggpack_buffer *b);
  106474. extern void oggpack_writecopy(oggpack_buffer *b,void *source,long bits);
  106475. extern void oggpack_reset(oggpack_buffer *b);
  106476. extern void oggpack_writeclear(oggpack_buffer *b);
  106477. extern void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  106478. extern void oggpack_write(oggpack_buffer *b,unsigned long value,int bits);
  106479. extern long oggpack_look(oggpack_buffer *b,int bits);
  106480. extern long oggpack_look1(oggpack_buffer *b);
  106481. extern void oggpack_adv(oggpack_buffer *b,int bits);
  106482. extern void oggpack_adv1(oggpack_buffer *b);
  106483. extern long oggpack_read(oggpack_buffer *b,int bits);
  106484. extern long oggpack_read1(oggpack_buffer *b);
  106485. extern long oggpack_bytes(oggpack_buffer *b);
  106486. extern long oggpack_bits(oggpack_buffer *b);
  106487. extern unsigned char *oggpack_get_buffer(oggpack_buffer *b);
  106488. extern void oggpackB_writeinit(oggpack_buffer *b);
  106489. extern void oggpackB_writetrunc(oggpack_buffer *b,long bits);
  106490. extern void oggpackB_writealign(oggpack_buffer *b);
  106491. extern void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits);
  106492. extern void oggpackB_reset(oggpack_buffer *b);
  106493. extern void oggpackB_writeclear(oggpack_buffer *b);
  106494. extern void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  106495. extern void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits);
  106496. extern long oggpackB_look(oggpack_buffer *b,int bits);
  106497. extern long oggpackB_look1(oggpack_buffer *b);
  106498. extern void oggpackB_adv(oggpack_buffer *b,int bits);
  106499. extern void oggpackB_adv1(oggpack_buffer *b);
  106500. extern long oggpackB_read(oggpack_buffer *b,int bits);
  106501. extern long oggpackB_read1(oggpack_buffer *b);
  106502. extern long oggpackB_bytes(oggpack_buffer *b);
  106503. extern long oggpackB_bits(oggpack_buffer *b);
  106504. extern unsigned char *oggpackB_get_buffer(oggpack_buffer *b);
  106505. /* Ogg BITSTREAM PRIMITIVES: encoding **************************/
  106506. extern int ogg_stream_packetin(ogg_stream_state *os, ogg_packet *op);
  106507. extern int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og);
  106508. extern int ogg_stream_flush(ogg_stream_state *os, ogg_page *og);
  106509. /* Ogg BITSTREAM PRIMITIVES: decoding **************************/
  106510. extern int ogg_sync_init(ogg_sync_state *oy);
  106511. extern int ogg_sync_clear(ogg_sync_state *oy);
  106512. extern int ogg_sync_reset(ogg_sync_state *oy);
  106513. extern int ogg_sync_destroy(ogg_sync_state *oy);
  106514. extern char *ogg_sync_buffer(ogg_sync_state *oy, long size);
  106515. extern int ogg_sync_wrote(ogg_sync_state *oy, long bytes);
  106516. extern long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og);
  106517. extern int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og);
  106518. extern int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og);
  106519. extern int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op);
  106520. extern int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op);
  106521. /* Ogg BITSTREAM PRIMITIVES: general ***************************/
  106522. extern int ogg_stream_init(ogg_stream_state *os,int serialno);
  106523. extern int ogg_stream_clear(ogg_stream_state *os);
  106524. extern int ogg_stream_reset(ogg_stream_state *os);
  106525. extern int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno);
  106526. extern int ogg_stream_destroy(ogg_stream_state *os);
  106527. extern int ogg_stream_eos(ogg_stream_state *os);
  106528. extern void ogg_page_checksum_set(ogg_page *og);
  106529. extern int ogg_page_version(ogg_page *og);
  106530. extern int ogg_page_continued(ogg_page *og);
  106531. extern int ogg_page_bos(ogg_page *og);
  106532. extern int ogg_page_eos(ogg_page *og);
  106533. extern ogg_int64_t ogg_page_granulepos(ogg_page *og);
  106534. extern int ogg_page_serialno(ogg_page *og);
  106535. extern long ogg_page_pageno(ogg_page *og);
  106536. extern int ogg_page_packets(ogg_page *og);
  106537. extern void ogg_packet_clear(ogg_packet *op);
  106538. #ifdef __cplusplus
  106539. }
  106540. #endif
  106541. #endif /* _OGG_H */
  106542. /*** End of inlined file: ogg.h ***/
  106543. typedef struct vorbis_info{
  106544. int version;
  106545. int channels;
  106546. long rate;
  106547. /* The below bitrate declarations are *hints*.
  106548. Combinations of the three values carry the following implications:
  106549. all three set to the same value:
  106550. implies a fixed rate bitstream
  106551. only nominal set:
  106552. implies a VBR stream that averages the nominal bitrate. No hard
  106553. upper/lower limit
  106554. upper and or lower set:
  106555. implies a VBR bitstream that obeys the bitrate limits. nominal
  106556. may also be set to give a nominal rate.
  106557. none set:
  106558. the coder does not care to speculate.
  106559. */
  106560. long bitrate_upper;
  106561. long bitrate_nominal;
  106562. long bitrate_lower;
  106563. long bitrate_window;
  106564. void *codec_setup;
  106565. } vorbis_info;
  106566. /* vorbis_dsp_state buffers the current vorbis audio
  106567. analysis/synthesis state. The DSP state belongs to a specific
  106568. logical bitstream ****************************************************/
  106569. typedef struct vorbis_dsp_state{
  106570. int analysisp;
  106571. vorbis_info *vi;
  106572. float **pcm;
  106573. float **pcmret;
  106574. int pcm_storage;
  106575. int pcm_current;
  106576. int pcm_returned;
  106577. int preextrapolate;
  106578. int eofflag;
  106579. long lW;
  106580. long W;
  106581. long nW;
  106582. long centerW;
  106583. ogg_int64_t granulepos;
  106584. ogg_int64_t sequence;
  106585. ogg_int64_t glue_bits;
  106586. ogg_int64_t time_bits;
  106587. ogg_int64_t floor_bits;
  106588. ogg_int64_t res_bits;
  106589. void *backend_state;
  106590. } vorbis_dsp_state;
  106591. typedef struct vorbis_block{
  106592. /* necessary stream state for linking to the framing abstraction */
  106593. float **pcm; /* this is a pointer into local storage */
  106594. oggpack_buffer opb;
  106595. long lW;
  106596. long W;
  106597. long nW;
  106598. int pcmend;
  106599. int mode;
  106600. int eofflag;
  106601. ogg_int64_t granulepos;
  106602. ogg_int64_t sequence;
  106603. vorbis_dsp_state *vd; /* For read-only access of configuration */
  106604. /* local storage to avoid remallocing; it's up to the mapping to
  106605. structure it */
  106606. void *localstore;
  106607. long localtop;
  106608. long localalloc;
  106609. long totaluse;
  106610. struct alloc_chain *reap;
  106611. /* bitmetrics for the frame */
  106612. long glue_bits;
  106613. long time_bits;
  106614. long floor_bits;
  106615. long res_bits;
  106616. void *internal;
  106617. } vorbis_block;
  106618. /* vorbis_block is a single block of data to be processed as part of
  106619. the analysis/synthesis stream; it belongs to a specific logical
  106620. bitstream, but is independant from other vorbis_blocks belonging to
  106621. that logical bitstream. *************************************************/
  106622. struct alloc_chain{
  106623. void *ptr;
  106624. struct alloc_chain *next;
  106625. };
  106626. /* vorbis_info contains all the setup information specific to the
  106627. specific compression/decompression mode in progress (eg,
  106628. psychoacoustic settings, channel setup, options, codebook
  106629. etc). vorbis_info and substructures are in backends.h.
  106630. *********************************************************************/
  106631. /* the comments are not part of vorbis_info so that vorbis_info can be
  106632. static storage */
  106633. typedef struct vorbis_comment{
  106634. /* unlimited user comment fields. libvorbis writes 'libvorbis'
  106635. whatever vendor is set to in encode */
  106636. char **user_comments;
  106637. int *comment_lengths;
  106638. int comments;
  106639. char *vendor;
  106640. } vorbis_comment;
  106641. /* libvorbis encodes in two abstraction layers; first we perform DSP
  106642. and produce a packet (see docs/analysis.txt). The packet is then
  106643. coded into a framed OggSquish bitstream by the second layer (see
  106644. docs/framing.txt). Decode is the reverse process; we sync/frame
  106645. the bitstream and extract individual packets, then decode the
  106646. packet back into PCM audio.
  106647. The extra framing/packetizing is used in streaming formats, such as
  106648. files. Over the net (such as with UDP), the framing and
  106649. packetization aren't necessary as they're provided by the transport
  106650. and the streaming layer is not used */
  106651. /* Vorbis PRIMITIVES: general ***************************************/
  106652. extern void vorbis_info_init(vorbis_info *vi);
  106653. extern void vorbis_info_clear(vorbis_info *vi);
  106654. extern int vorbis_info_blocksize(vorbis_info *vi,int zo);
  106655. extern void vorbis_comment_init(vorbis_comment *vc);
  106656. extern void vorbis_comment_add(vorbis_comment *vc, char *comment);
  106657. extern void vorbis_comment_add_tag(vorbis_comment *vc,
  106658. const char *tag, char *contents);
  106659. extern char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count);
  106660. extern int vorbis_comment_query_count(vorbis_comment *vc, char *tag);
  106661. extern void vorbis_comment_clear(vorbis_comment *vc);
  106662. extern int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb);
  106663. extern int vorbis_block_clear(vorbis_block *vb);
  106664. extern void vorbis_dsp_clear(vorbis_dsp_state *v);
  106665. extern double vorbis_granule_time(vorbis_dsp_state *v,
  106666. ogg_int64_t granulepos);
  106667. /* Vorbis PRIMITIVES: analysis/DSP layer ****************************/
  106668. extern int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi);
  106669. extern int vorbis_commentheader_out(vorbis_comment *vc, ogg_packet *op);
  106670. extern int vorbis_analysis_headerout(vorbis_dsp_state *v,
  106671. vorbis_comment *vc,
  106672. ogg_packet *op,
  106673. ogg_packet *op_comm,
  106674. ogg_packet *op_code);
  106675. extern float **vorbis_analysis_buffer(vorbis_dsp_state *v,int vals);
  106676. extern int vorbis_analysis_wrote(vorbis_dsp_state *v,int vals);
  106677. extern int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb);
  106678. extern int vorbis_analysis(vorbis_block *vb,ogg_packet *op);
  106679. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  106680. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,
  106681. ogg_packet *op);
  106682. /* Vorbis PRIMITIVES: synthesis layer *******************************/
  106683. extern int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,
  106684. ogg_packet *op);
  106685. extern int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi);
  106686. extern int vorbis_synthesis_restart(vorbis_dsp_state *v);
  106687. extern int vorbis_synthesis(vorbis_block *vb,ogg_packet *op);
  106688. extern int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op);
  106689. extern int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb);
  106690. extern int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm);
  106691. extern int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm);
  106692. extern int vorbis_synthesis_read(vorbis_dsp_state *v,int samples);
  106693. extern long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op);
  106694. extern int vorbis_synthesis_halfrate(vorbis_info *v,int flag);
  106695. extern int vorbis_synthesis_halfrate_p(vorbis_info *v);
  106696. /* Vorbis ERRORS and return codes ***********************************/
  106697. #define OV_FALSE -1
  106698. #define OV_EOF -2
  106699. #define OV_HOLE -3
  106700. #define OV_EREAD -128
  106701. #define OV_EFAULT -129
  106702. #define OV_EIMPL -130
  106703. #define OV_EINVAL -131
  106704. #define OV_ENOTVORBIS -132
  106705. #define OV_EBADHEADER -133
  106706. #define OV_EVERSION -134
  106707. #define OV_ENOTAUDIO -135
  106708. #define OV_EBADPACKET -136
  106709. #define OV_EBADLINK -137
  106710. #define OV_ENOSEEK -138
  106711. #ifdef __cplusplus
  106712. }
  106713. #endif /* __cplusplus */
  106714. #endif
  106715. /*** End of inlined file: codec.h ***/
  106716. extern int vorbis_encode_init(vorbis_info *vi,
  106717. long channels,
  106718. long rate,
  106719. long max_bitrate,
  106720. long nominal_bitrate,
  106721. long min_bitrate);
  106722. extern int vorbis_encode_setup_managed(vorbis_info *vi,
  106723. long channels,
  106724. long rate,
  106725. long max_bitrate,
  106726. long nominal_bitrate,
  106727. long min_bitrate);
  106728. extern int vorbis_encode_setup_vbr(vorbis_info *vi,
  106729. long channels,
  106730. long rate,
  106731. float quality /* quality level from 0. (lo) to 1. (hi) */
  106732. );
  106733. extern int vorbis_encode_init_vbr(vorbis_info *vi,
  106734. long channels,
  106735. long rate,
  106736. float base_quality /* quality level from 0. (lo) to 1. (hi) */
  106737. );
  106738. extern int vorbis_encode_setup_init(vorbis_info *vi);
  106739. extern int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg);
  106740. /* deprecated rate management supported only for compatability */
  106741. #define OV_ECTL_RATEMANAGE_GET 0x10
  106742. #define OV_ECTL_RATEMANAGE_SET 0x11
  106743. #define OV_ECTL_RATEMANAGE_AVG 0x12
  106744. #define OV_ECTL_RATEMANAGE_HARD 0x13
  106745. struct ovectl_ratemanage_arg {
  106746. int management_active;
  106747. long bitrate_hard_min;
  106748. long bitrate_hard_max;
  106749. double bitrate_hard_window;
  106750. long bitrate_av_lo;
  106751. long bitrate_av_hi;
  106752. double bitrate_av_window;
  106753. double bitrate_av_window_center;
  106754. };
  106755. /* new rate setup */
  106756. #define OV_ECTL_RATEMANAGE2_GET 0x14
  106757. #define OV_ECTL_RATEMANAGE2_SET 0x15
  106758. struct ovectl_ratemanage2_arg {
  106759. int management_active;
  106760. long bitrate_limit_min_kbps;
  106761. long bitrate_limit_max_kbps;
  106762. long bitrate_limit_reservoir_bits;
  106763. double bitrate_limit_reservoir_bias;
  106764. long bitrate_average_kbps;
  106765. double bitrate_average_damping;
  106766. };
  106767. #define OV_ECTL_LOWPASS_GET 0x20
  106768. #define OV_ECTL_LOWPASS_SET 0x21
  106769. #define OV_ECTL_IBLOCK_GET 0x30
  106770. #define OV_ECTL_IBLOCK_SET 0x31
  106771. #ifdef __cplusplus
  106772. }
  106773. #endif /* __cplusplus */
  106774. #endif
  106775. /*** End of inlined file: vorbisenc.h ***/
  106776. /*** Start of inlined file: vorbisfile.h ***/
  106777. #ifndef _OV_FILE_H_
  106778. #define _OV_FILE_H_
  106779. #ifdef __cplusplus
  106780. extern "C"
  106781. {
  106782. #endif /* __cplusplus */
  106783. #include <stdio.h>
  106784. /* The function prototypes for the callbacks are basically the same as for
  106785. * the stdio functions fread, fseek, fclose, ftell.
  106786. * The one difference is that the FILE * arguments have been replaced with
  106787. * a void * - this is to be used as a pointer to whatever internal data these
  106788. * functions might need. In the stdio case, it's just a FILE * cast to a void *
  106789. *
  106790. * If you use other functions, check the docs for these functions and return
  106791. * the right values. For seek_func(), you *MUST* return -1 if the stream is
  106792. * unseekable
  106793. */
  106794. typedef struct {
  106795. size_t (*read_func) (void *ptr, size_t size, size_t nmemb, void *datasource);
  106796. int (*seek_func) (void *datasource, ogg_int64_t offset, int whence);
  106797. int (*close_func) (void *datasource);
  106798. long (*tell_func) (void *datasource);
  106799. } ov_callbacks;
  106800. #define NOTOPEN 0
  106801. #define PARTOPEN 1
  106802. #define OPENED 2
  106803. #define STREAMSET 3
  106804. #define INITSET 4
  106805. typedef struct OggVorbis_File {
  106806. void *datasource; /* Pointer to a FILE *, etc. */
  106807. int seekable;
  106808. ogg_int64_t offset;
  106809. ogg_int64_t end;
  106810. ogg_sync_state oy;
  106811. /* If the FILE handle isn't seekable (eg, a pipe), only the current
  106812. stream appears */
  106813. int links;
  106814. ogg_int64_t *offsets;
  106815. ogg_int64_t *dataoffsets;
  106816. long *serialnos;
  106817. ogg_int64_t *pcmlengths; /* overloaded to maintain binary
  106818. compatability; x2 size, stores both
  106819. beginning and end values */
  106820. vorbis_info *vi;
  106821. vorbis_comment *vc;
  106822. /* Decoding working state local storage */
  106823. ogg_int64_t pcm_offset;
  106824. int ready_state;
  106825. long current_serialno;
  106826. int current_link;
  106827. double bittrack;
  106828. double samptrack;
  106829. ogg_stream_state os; /* take physical pages, weld into a logical
  106830. stream of packets */
  106831. vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */
  106832. vorbis_block vb; /* local working space for packet->PCM decode */
  106833. ov_callbacks callbacks;
  106834. } OggVorbis_File;
  106835. extern int ov_clear(OggVorbis_File *vf);
  106836. extern int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  106837. extern int ov_open_callbacks(void *datasource, OggVorbis_File *vf,
  106838. char *initial, long ibytes, ov_callbacks callbacks);
  106839. extern int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  106840. extern int ov_test_callbacks(void *datasource, OggVorbis_File *vf,
  106841. char *initial, long ibytes, ov_callbacks callbacks);
  106842. extern int ov_test_open(OggVorbis_File *vf);
  106843. extern long ov_bitrate(OggVorbis_File *vf,int i);
  106844. extern long ov_bitrate_instant(OggVorbis_File *vf);
  106845. extern long ov_streams(OggVorbis_File *vf);
  106846. extern long ov_seekable(OggVorbis_File *vf);
  106847. extern long ov_serialnumber(OggVorbis_File *vf,int i);
  106848. extern ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i);
  106849. extern ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i);
  106850. extern double ov_time_total(OggVorbis_File *vf,int i);
  106851. extern int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos);
  106852. extern int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos);
  106853. extern int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos);
  106854. extern int ov_time_seek(OggVorbis_File *vf,double pos);
  106855. extern int ov_time_seek_page(OggVorbis_File *vf,double pos);
  106856. extern int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  106857. extern int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  106858. extern int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos);
  106859. extern int ov_time_seek_lap(OggVorbis_File *vf,double pos);
  106860. extern int ov_time_seek_page_lap(OggVorbis_File *vf,double pos);
  106861. extern ogg_int64_t ov_raw_tell(OggVorbis_File *vf);
  106862. extern ogg_int64_t ov_pcm_tell(OggVorbis_File *vf);
  106863. extern double ov_time_tell(OggVorbis_File *vf);
  106864. extern vorbis_info *ov_info(OggVorbis_File *vf,int link);
  106865. extern vorbis_comment *ov_comment(OggVorbis_File *vf,int link);
  106866. extern long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int samples,
  106867. int *bitstream);
  106868. extern long ov_read(OggVorbis_File *vf,char *buffer,int length,
  106869. int bigendianp,int word,int sgned,int *bitstream);
  106870. extern int ov_crosslap(OggVorbis_File *vf1,OggVorbis_File *vf2);
  106871. extern int ov_halfrate(OggVorbis_File *vf,int flag);
  106872. extern int ov_halfrate_p(OggVorbis_File *vf);
  106873. #ifdef __cplusplus
  106874. }
  106875. #endif /* __cplusplus */
  106876. #endif
  106877. /*** End of inlined file: vorbisfile.h ***/
  106878. /*** Start of inlined file: bitwise.c ***/
  106879. /* We're 'LSb' endian; if we write a word but read individual bits,
  106880. then we'll read the lsb first */
  106881. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  106882. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  106883. // tasks..
  106884. #if JUCE_MSVC
  106885. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  106886. #endif
  106887. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  106888. #if JUCE_USE_OGGVORBIS
  106889. #include <string.h>
  106890. #include <stdlib.h>
  106891. #define BUFFER_INCREMENT 256
  106892. static const unsigned long mask[]=
  106893. {0x00000000,0x00000001,0x00000003,0x00000007,0x0000000f,
  106894. 0x0000001f,0x0000003f,0x0000007f,0x000000ff,0x000001ff,
  106895. 0x000003ff,0x000007ff,0x00000fff,0x00001fff,0x00003fff,
  106896. 0x00007fff,0x0000ffff,0x0001ffff,0x0003ffff,0x0007ffff,
  106897. 0x000fffff,0x001fffff,0x003fffff,0x007fffff,0x00ffffff,
  106898. 0x01ffffff,0x03ffffff,0x07ffffff,0x0fffffff,0x1fffffff,
  106899. 0x3fffffff,0x7fffffff,0xffffffff };
  106900. static const unsigned int mask8B[]=
  106901. {0x00,0x80,0xc0,0xe0,0xf0,0xf8,0xfc,0xfe,0xff};
  106902. void oggpack_writeinit(oggpack_buffer *b){
  106903. memset(b,0,sizeof(*b));
  106904. b->ptr=b->buffer=(unsigned char*) _ogg_malloc(BUFFER_INCREMENT);
  106905. b->buffer[0]='\0';
  106906. b->storage=BUFFER_INCREMENT;
  106907. }
  106908. void oggpackB_writeinit(oggpack_buffer *b){
  106909. oggpack_writeinit(b);
  106910. }
  106911. void oggpack_writetrunc(oggpack_buffer *b,long bits){
  106912. long bytes=bits>>3;
  106913. bits-=bytes*8;
  106914. b->ptr=b->buffer+bytes;
  106915. b->endbit=bits;
  106916. b->endbyte=bytes;
  106917. *b->ptr&=mask[bits];
  106918. }
  106919. void oggpackB_writetrunc(oggpack_buffer *b,long bits){
  106920. long bytes=bits>>3;
  106921. bits-=bytes*8;
  106922. b->ptr=b->buffer+bytes;
  106923. b->endbit=bits;
  106924. b->endbyte=bytes;
  106925. *b->ptr&=mask8B[bits];
  106926. }
  106927. /* Takes only up to 32 bits. */
  106928. void oggpack_write(oggpack_buffer *b,unsigned long value,int bits){
  106929. if(b->endbyte+4>=b->storage){
  106930. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  106931. b->storage+=BUFFER_INCREMENT;
  106932. b->ptr=b->buffer+b->endbyte;
  106933. }
  106934. value&=mask[bits];
  106935. bits+=b->endbit;
  106936. b->ptr[0]|=value<<b->endbit;
  106937. if(bits>=8){
  106938. b->ptr[1]=(unsigned char)(value>>(8-b->endbit));
  106939. if(bits>=16){
  106940. b->ptr[2]=(unsigned char)(value>>(16-b->endbit));
  106941. if(bits>=24){
  106942. b->ptr[3]=(unsigned char)(value>>(24-b->endbit));
  106943. if(bits>=32){
  106944. if(b->endbit)
  106945. b->ptr[4]=(unsigned char)(value>>(32-b->endbit));
  106946. else
  106947. b->ptr[4]=0;
  106948. }
  106949. }
  106950. }
  106951. }
  106952. b->endbyte+=bits/8;
  106953. b->ptr+=bits/8;
  106954. b->endbit=bits&7;
  106955. }
  106956. /* Takes only up to 32 bits. */
  106957. void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits){
  106958. if(b->endbyte+4>=b->storage){
  106959. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  106960. b->storage+=BUFFER_INCREMENT;
  106961. b->ptr=b->buffer+b->endbyte;
  106962. }
  106963. value=(value&mask[bits])<<(32-bits);
  106964. bits+=b->endbit;
  106965. b->ptr[0]|=value>>(24+b->endbit);
  106966. if(bits>=8){
  106967. b->ptr[1]=(unsigned char)(value>>(16+b->endbit));
  106968. if(bits>=16){
  106969. b->ptr[2]=(unsigned char)(value>>(8+b->endbit));
  106970. if(bits>=24){
  106971. b->ptr[3]=(unsigned char)(value>>(b->endbit));
  106972. if(bits>=32){
  106973. if(b->endbit)
  106974. b->ptr[4]=(unsigned char)(value<<(8-b->endbit));
  106975. else
  106976. b->ptr[4]=0;
  106977. }
  106978. }
  106979. }
  106980. }
  106981. b->endbyte+=bits/8;
  106982. b->ptr+=bits/8;
  106983. b->endbit=bits&7;
  106984. }
  106985. void oggpack_writealign(oggpack_buffer *b){
  106986. int bits=8-b->endbit;
  106987. if(bits<8)
  106988. oggpack_write(b,0,bits);
  106989. }
  106990. void oggpackB_writealign(oggpack_buffer *b){
  106991. int bits=8-b->endbit;
  106992. if(bits<8)
  106993. oggpackB_write(b,0,bits);
  106994. }
  106995. static void oggpack_writecopy_helper(oggpack_buffer *b,
  106996. void *source,
  106997. long bits,
  106998. void (*w)(oggpack_buffer *,
  106999. unsigned long,
  107000. int),
  107001. int msb){
  107002. unsigned char *ptr=(unsigned char *)source;
  107003. long bytes=bits/8;
  107004. bits-=bytes*8;
  107005. if(b->endbit){
  107006. int i;
  107007. /* unaligned copy. Do it the hard way. */
  107008. for(i=0;i<bytes;i++)
  107009. w(b,(unsigned long)(ptr[i]),8);
  107010. }else{
  107011. /* aligned block copy */
  107012. if(b->endbyte+bytes+1>=b->storage){
  107013. b->storage=b->endbyte+bytes+BUFFER_INCREMENT;
  107014. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage);
  107015. b->ptr=b->buffer+b->endbyte;
  107016. }
  107017. memmove(b->ptr,source,bytes);
  107018. b->ptr+=bytes;
  107019. b->endbyte+=bytes;
  107020. *b->ptr=0;
  107021. }
  107022. if(bits){
  107023. if(msb)
  107024. w(b,(unsigned long)(ptr[bytes]>>(8-bits)),bits);
  107025. else
  107026. w(b,(unsigned long)(ptr[bytes]),bits);
  107027. }
  107028. }
  107029. void oggpack_writecopy(oggpack_buffer *b,void *source,long bits){
  107030. oggpack_writecopy_helper(b,source,bits,oggpack_write,0);
  107031. }
  107032. void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits){
  107033. oggpack_writecopy_helper(b,source,bits,oggpackB_write,1);
  107034. }
  107035. void oggpack_reset(oggpack_buffer *b){
  107036. b->ptr=b->buffer;
  107037. b->buffer[0]=0;
  107038. b->endbit=b->endbyte=0;
  107039. }
  107040. void oggpackB_reset(oggpack_buffer *b){
  107041. oggpack_reset(b);
  107042. }
  107043. void oggpack_writeclear(oggpack_buffer *b){
  107044. _ogg_free(b->buffer);
  107045. memset(b,0,sizeof(*b));
  107046. }
  107047. void oggpackB_writeclear(oggpack_buffer *b){
  107048. oggpack_writeclear(b);
  107049. }
  107050. void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  107051. memset(b,0,sizeof(*b));
  107052. b->buffer=b->ptr=buf;
  107053. b->storage=bytes;
  107054. }
  107055. void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  107056. oggpack_readinit(b,buf,bytes);
  107057. }
  107058. /* Read in bits without advancing the bitptr; bits <= 32 */
  107059. long oggpack_look(oggpack_buffer *b,int bits){
  107060. unsigned long ret;
  107061. unsigned long m=mask[bits];
  107062. bits+=b->endbit;
  107063. if(b->endbyte+4>=b->storage){
  107064. /* not the main path */
  107065. if(b->endbyte*8+bits>b->storage*8)return(-1);
  107066. }
  107067. ret=b->ptr[0]>>b->endbit;
  107068. if(bits>8){
  107069. ret|=b->ptr[1]<<(8-b->endbit);
  107070. if(bits>16){
  107071. ret|=b->ptr[2]<<(16-b->endbit);
  107072. if(bits>24){
  107073. ret|=b->ptr[3]<<(24-b->endbit);
  107074. if(bits>32 && b->endbit)
  107075. ret|=b->ptr[4]<<(32-b->endbit);
  107076. }
  107077. }
  107078. }
  107079. return(m&ret);
  107080. }
  107081. /* Read in bits without advancing the bitptr; bits <= 32 */
  107082. long oggpackB_look(oggpack_buffer *b,int bits){
  107083. unsigned long ret;
  107084. int m=32-bits;
  107085. bits+=b->endbit;
  107086. if(b->endbyte+4>=b->storage){
  107087. /* not the main path */
  107088. if(b->endbyte*8+bits>b->storage*8)return(-1);
  107089. }
  107090. ret=b->ptr[0]<<(24+b->endbit);
  107091. if(bits>8){
  107092. ret|=b->ptr[1]<<(16+b->endbit);
  107093. if(bits>16){
  107094. ret|=b->ptr[2]<<(8+b->endbit);
  107095. if(bits>24){
  107096. ret|=b->ptr[3]<<(b->endbit);
  107097. if(bits>32 && b->endbit)
  107098. ret|=b->ptr[4]>>(8-b->endbit);
  107099. }
  107100. }
  107101. }
  107102. return ((ret&0xffffffff)>>(m>>1))>>((m+1)>>1);
  107103. }
  107104. long oggpack_look1(oggpack_buffer *b){
  107105. if(b->endbyte>=b->storage)return(-1);
  107106. return((b->ptr[0]>>b->endbit)&1);
  107107. }
  107108. long oggpackB_look1(oggpack_buffer *b){
  107109. if(b->endbyte>=b->storage)return(-1);
  107110. return((b->ptr[0]>>(7-b->endbit))&1);
  107111. }
  107112. void oggpack_adv(oggpack_buffer *b,int bits){
  107113. bits+=b->endbit;
  107114. b->ptr+=bits/8;
  107115. b->endbyte+=bits/8;
  107116. b->endbit=bits&7;
  107117. }
  107118. void oggpackB_adv(oggpack_buffer *b,int bits){
  107119. oggpack_adv(b,bits);
  107120. }
  107121. void oggpack_adv1(oggpack_buffer *b){
  107122. if(++(b->endbit)>7){
  107123. b->endbit=0;
  107124. b->ptr++;
  107125. b->endbyte++;
  107126. }
  107127. }
  107128. void oggpackB_adv1(oggpack_buffer *b){
  107129. oggpack_adv1(b);
  107130. }
  107131. /* bits <= 32 */
  107132. long oggpack_read(oggpack_buffer *b,int bits){
  107133. long ret;
  107134. unsigned long m=mask[bits];
  107135. bits+=b->endbit;
  107136. if(b->endbyte+4>=b->storage){
  107137. /* not the main path */
  107138. ret=-1L;
  107139. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  107140. }
  107141. ret=b->ptr[0]>>b->endbit;
  107142. if(bits>8){
  107143. ret|=b->ptr[1]<<(8-b->endbit);
  107144. if(bits>16){
  107145. ret|=b->ptr[2]<<(16-b->endbit);
  107146. if(bits>24){
  107147. ret|=b->ptr[3]<<(24-b->endbit);
  107148. if(bits>32 && b->endbit){
  107149. ret|=b->ptr[4]<<(32-b->endbit);
  107150. }
  107151. }
  107152. }
  107153. }
  107154. ret&=m;
  107155. overflow:
  107156. b->ptr+=bits/8;
  107157. b->endbyte+=bits/8;
  107158. b->endbit=bits&7;
  107159. return(ret);
  107160. }
  107161. /* bits <= 32 */
  107162. long oggpackB_read(oggpack_buffer *b,int bits){
  107163. long ret;
  107164. long m=32-bits;
  107165. bits+=b->endbit;
  107166. if(b->endbyte+4>=b->storage){
  107167. /* not the main path */
  107168. ret=-1L;
  107169. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  107170. }
  107171. ret=b->ptr[0]<<(24+b->endbit);
  107172. if(bits>8){
  107173. ret|=b->ptr[1]<<(16+b->endbit);
  107174. if(bits>16){
  107175. ret|=b->ptr[2]<<(8+b->endbit);
  107176. if(bits>24){
  107177. ret|=b->ptr[3]<<(b->endbit);
  107178. if(bits>32 && b->endbit)
  107179. ret|=b->ptr[4]>>(8-b->endbit);
  107180. }
  107181. }
  107182. }
  107183. ret=((ret&0xffffffffUL)>>(m>>1))>>((m+1)>>1);
  107184. overflow:
  107185. b->ptr+=bits/8;
  107186. b->endbyte+=bits/8;
  107187. b->endbit=bits&7;
  107188. return(ret);
  107189. }
  107190. long oggpack_read1(oggpack_buffer *b){
  107191. long ret;
  107192. if(b->endbyte>=b->storage){
  107193. /* not the main path */
  107194. ret=-1L;
  107195. goto overflow;
  107196. }
  107197. ret=(b->ptr[0]>>b->endbit)&1;
  107198. overflow:
  107199. b->endbit++;
  107200. if(b->endbit>7){
  107201. b->endbit=0;
  107202. b->ptr++;
  107203. b->endbyte++;
  107204. }
  107205. return(ret);
  107206. }
  107207. long oggpackB_read1(oggpack_buffer *b){
  107208. long ret;
  107209. if(b->endbyte>=b->storage){
  107210. /* not the main path */
  107211. ret=-1L;
  107212. goto overflow;
  107213. }
  107214. ret=(b->ptr[0]>>(7-b->endbit))&1;
  107215. overflow:
  107216. b->endbit++;
  107217. if(b->endbit>7){
  107218. b->endbit=0;
  107219. b->ptr++;
  107220. b->endbyte++;
  107221. }
  107222. return(ret);
  107223. }
  107224. long oggpack_bytes(oggpack_buffer *b){
  107225. return(b->endbyte+(b->endbit+7)/8);
  107226. }
  107227. long oggpack_bits(oggpack_buffer *b){
  107228. return(b->endbyte*8+b->endbit);
  107229. }
  107230. long oggpackB_bytes(oggpack_buffer *b){
  107231. return oggpack_bytes(b);
  107232. }
  107233. long oggpackB_bits(oggpack_buffer *b){
  107234. return oggpack_bits(b);
  107235. }
  107236. unsigned char *oggpack_get_buffer(oggpack_buffer *b){
  107237. return(b->buffer);
  107238. }
  107239. unsigned char *oggpackB_get_buffer(oggpack_buffer *b){
  107240. return oggpack_get_buffer(b);
  107241. }
  107242. /* Self test of the bitwise routines; everything else is based on
  107243. them, so they damned well better be solid. */
  107244. #ifdef _V_SELFTEST
  107245. #include <stdio.h>
  107246. static int ilog(unsigned int v){
  107247. int ret=0;
  107248. while(v){
  107249. ret++;
  107250. v>>=1;
  107251. }
  107252. return(ret);
  107253. }
  107254. oggpack_buffer o;
  107255. oggpack_buffer r;
  107256. void report(char *in){
  107257. fprintf(stderr,"%s",in);
  107258. exit(1);
  107259. }
  107260. void cliptest(unsigned long *b,int vals,int bits,int *comp,int compsize){
  107261. long bytes,i;
  107262. unsigned char *buffer;
  107263. oggpack_reset(&o);
  107264. for(i=0;i<vals;i++)
  107265. oggpack_write(&o,b[i],bits?bits:ilog(b[i]));
  107266. buffer=oggpack_get_buffer(&o);
  107267. bytes=oggpack_bytes(&o);
  107268. if(bytes!=compsize)report("wrong number of bytes!\n");
  107269. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  107270. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  107271. report("wrote incorrect value!\n");
  107272. }
  107273. oggpack_readinit(&r,buffer,bytes);
  107274. for(i=0;i<vals;i++){
  107275. int tbit=bits?bits:ilog(b[i]);
  107276. if(oggpack_look(&r,tbit)==-1)
  107277. report("out of data!\n");
  107278. if(oggpack_look(&r,tbit)!=(b[i]&mask[tbit]))
  107279. report("looked at incorrect value!\n");
  107280. if(tbit==1)
  107281. if(oggpack_look1(&r)!=(b[i]&mask[tbit]))
  107282. report("looked at single bit incorrect value!\n");
  107283. if(tbit==1){
  107284. if(oggpack_read1(&r)!=(b[i]&mask[tbit]))
  107285. report("read incorrect single bit value!\n");
  107286. }else{
  107287. if(oggpack_read(&r,tbit)!=(b[i]&mask[tbit]))
  107288. report("read incorrect value!\n");
  107289. }
  107290. }
  107291. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  107292. }
  107293. void cliptestB(unsigned long *b,int vals,int bits,int *comp,int compsize){
  107294. long bytes,i;
  107295. unsigned char *buffer;
  107296. oggpackB_reset(&o);
  107297. for(i=0;i<vals;i++)
  107298. oggpackB_write(&o,b[i],bits?bits:ilog(b[i]));
  107299. buffer=oggpackB_get_buffer(&o);
  107300. bytes=oggpackB_bytes(&o);
  107301. if(bytes!=compsize)report("wrong number of bytes!\n");
  107302. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  107303. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  107304. report("wrote incorrect value!\n");
  107305. }
  107306. oggpackB_readinit(&r,buffer,bytes);
  107307. for(i=0;i<vals;i++){
  107308. int tbit=bits?bits:ilog(b[i]);
  107309. if(oggpackB_look(&r,tbit)==-1)
  107310. report("out of data!\n");
  107311. if(oggpackB_look(&r,tbit)!=(b[i]&mask[tbit]))
  107312. report("looked at incorrect value!\n");
  107313. if(tbit==1)
  107314. if(oggpackB_look1(&r)!=(b[i]&mask[tbit]))
  107315. report("looked at single bit incorrect value!\n");
  107316. if(tbit==1){
  107317. if(oggpackB_read1(&r)!=(b[i]&mask[tbit]))
  107318. report("read incorrect single bit value!\n");
  107319. }else{
  107320. if(oggpackB_read(&r,tbit)!=(b[i]&mask[tbit]))
  107321. report("read incorrect value!\n");
  107322. }
  107323. }
  107324. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  107325. }
  107326. int main(void){
  107327. unsigned char *buffer;
  107328. long bytes,i;
  107329. static unsigned long testbuffer1[]=
  107330. {18,12,103948,4325,543,76,432,52,3,65,4,56,32,42,34,21,1,23,32,546,456,7,
  107331. 567,56,8,8,55,3,52,342,341,4,265,7,67,86,2199,21,7,1,5,1,4};
  107332. int test1size=43;
  107333. static unsigned long testbuffer2[]=
  107334. {216531625L,1237861823,56732452,131,3212421,12325343,34547562,12313212,
  107335. 1233432,534,5,346435231,14436467,7869299,76326614,167548585,
  107336. 85525151,0,12321,1,349528352};
  107337. int test2size=21;
  107338. static unsigned long testbuffer3[]=
  107339. {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,
  107340. 0,1,30,1,1,1,0,0,1,0,0,0,12,0,11,0,1,0,0,1};
  107341. int test3size=56;
  107342. static unsigned long large[]=
  107343. {2136531625L,2137861823,56732452,131,3212421,12325343,34547562,12313212,
  107344. 1233432,534,5,2146435231,14436467,7869299,76326614,167548585,
  107345. 85525151,0,12321,1,2146528352};
  107346. int onesize=33;
  107347. static int one[33]={146,25,44,151,195,15,153,176,233,131,196,65,85,172,47,40,
  107348. 34,242,223,136,35,222,211,86,171,50,225,135,214,75,172,
  107349. 223,4};
  107350. static int oneB[33]={150,101,131,33,203,15,204,216,105,193,156,65,84,85,222,
  107351. 8,139,145,227,126,34,55,244,171,85,100,39,195,173,18,
  107352. 245,251,128};
  107353. int twosize=6;
  107354. static int two[6]={61,255,255,251,231,29};
  107355. static int twoB[6]={247,63,255,253,249,120};
  107356. int threesize=54;
  107357. static int three[54]={169,2,232,252,91,132,156,36,89,13,123,176,144,32,254,
  107358. 142,224,85,59,121,144,79,124,23,67,90,90,216,79,23,83,
  107359. 58,135,196,61,55,129,183,54,101,100,170,37,127,126,10,
  107360. 100,52,4,14,18,86,77,1};
  107361. static int threeB[54]={206,128,42,153,57,8,183,251,13,89,36,30,32,144,183,
  107362. 130,59,240,121,59,85,223,19,228,180,134,33,107,74,98,
  107363. 233,253,196,135,63,2,110,114,50,155,90,127,37,170,104,
  107364. 200,20,254,4,58,106,176,144,0};
  107365. int foursize=38;
  107366. static int four[38]={18,6,163,252,97,194,104,131,32,1,7,82,137,42,129,11,72,
  107367. 132,60,220,112,8,196,109,64,179,86,9,137,195,208,122,169,
  107368. 28,2,133,0,1};
  107369. static int fourB[38]={36,48,102,83,243,24,52,7,4,35,132,10,145,21,2,93,2,41,
  107370. 1,219,184,16,33,184,54,149,170,132,18,30,29,98,229,67,
  107371. 129,10,4,32};
  107372. int fivesize=45;
  107373. static int five[45]={169,2,126,139,144,172,30,4,80,72,240,59,130,218,73,62,
  107374. 241,24,210,44,4,20,0,248,116,49,135,100,110,130,181,169,
  107375. 84,75,159,2,1,0,132,192,8,0,0,18,22};
  107376. static int fiveB[45]={1,84,145,111,245,100,128,8,56,36,40,71,126,78,213,226,
  107377. 124,105,12,0,133,128,0,162,233,242,67,152,77,205,77,
  107378. 172,150,169,129,79,128,0,6,4,32,0,27,9,0};
  107379. int sixsize=7;
  107380. static int six[7]={17,177,170,242,169,19,148};
  107381. static int sixB[7]={136,141,85,79,149,200,41};
  107382. /* Test read/write together */
  107383. /* Later we test against pregenerated bitstreams */
  107384. oggpack_writeinit(&o);
  107385. fprintf(stderr,"\nSmall preclipped packing (LSb): ");
  107386. cliptest(testbuffer1,test1size,0,one,onesize);
  107387. fprintf(stderr,"ok.");
  107388. fprintf(stderr,"\nNull bit call (LSb): ");
  107389. cliptest(testbuffer3,test3size,0,two,twosize);
  107390. fprintf(stderr,"ok.");
  107391. fprintf(stderr,"\nLarge preclipped packing (LSb): ");
  107392. cliptest(testbuffer2,test2size,0,three,threesize);
  107393. fprintf(stderr,"ok.");
  107394. fprintf(stderr,"\n32 bit preclipped packing (LSb): ");
  107395. oggpack_reset(&o);
  107396. for(i=0;i<test2size;i++)
  107397. oggpack_write(&o,large[i],32);
  107398. buffer=oggpack_get_buffer(&o);
  107399. bytes=oggpack_bytes(&o);
  107400. oggpack_readinit(&r,buffer,bytes);
  107401. for(i=0;i<test2size;i++){
  107402. if(oggpack_look(&r,32)==-1)report("out of data. failed!");
  107403. if(oggpack_look(&r,32)!=large[i]){
  107404. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpack_look(&r,32),large[i],
  107405. oggpack_look(&r,32),large[i]);
  107406. report("read incorrect value!\n");
  107407. }
  107408. oggpack_adv(&r,32);
  107409. }
  107410. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  107411. fprintf(stderr,"ok.");
  107412. fprintf(stderr,"\nSmall unclipped packing (LSb): ");
  107413. cliptest(testbuffer1,test1size,7,four,foursize);
  107414. fprintf(stderr,"ok.");
  107415. fprintf(stderr,"\nLarge unclipped packing (LSb): ");
  107416. cliptest(testbuffer2,test2size,17,five,fivesize);
  107417. fprintf(stderr,"ok.");
  107418. fprintf(stderr,"\nSingle bit unclipped packing (LSb): ");
  107419. cliptest(testbuffer3,test3size,1,six,sixsize);
  107420. fprintf(stderr,"ok.");
  107421. fprintf(stderr,"\nTesting read past end (LSb): ");
  107422. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  107423. for(i=0;i<64;i++){
  107424. if(oggpack_read(&r,1)!=0){
  107425. fprintf(stderr,"failed; got -1 prematurely.\n");
  107426. exit(1);
  107427. }
  107428. }
  107429. if(oggpack_look(&r,1)!=-1 ||
  107430. oggpack_read(&r,1)!=-1){
  107431. fprintf(stderr,"failed; read past end without -1.\n");
  107432. exit(1);
  107433. }
  107434. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  107435. if(oggpack_read(&r,30)!=0 || oggpack_read(&r,16)!=0){
  107436. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  107437. exit(1);
  107438. }
  107439. if(oggpack_look(&r,18)!=0 ||
  107440. oggpack_look(&r,18)!=0){
  107441. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  107442. exit(1);
  107443. }
  107444. if(oggpack_look(&r,19)!=-1 ||
  107445. oggpack_look(&r,19)!=-1){
  107446. fprintf(stderr,"failed; read past end without -1.\n");
  107447. exit(1);
  107448. }
  107449. if(oggpack_look(&r,32)!=-1 ||
  107450. oggpack_look(&r,32)!=-1){
  107451. fprintf(stderr,"failed; read past end without -1.\n");
  107452. exit(1);
  107453. }
  107454. oggpack_writeclear(&o);
  107455. fprintf(stderr,"ok.\n");
  107456. /********** lazy, cut-n-paste retest with MSb packing ***********/
  107457. /* Test read/write together */
  107458. /* Later we test against pregenerated bitstreams */
  107459. oggpackB_writeinit(&o);
  107460. fprintf(stderr,"\nSmall preclipped packing (MSb): ");
  107461. cliptestB(testbuffer1,test1size,0,oneB,onesize);
  107462. fprintf(stderr,"ok.");
  107463. fprintf(stderr,"\nNull bit call (MSb): ");
  107464. cliptestB(testbuffer3,test3size,0,twoB,twosize);
  107465. fprintf(stderr,"ok.");
  107466. fprintf(stderr,"\nLarge preclipped packing (MSb): ");
  107467. cliptestB(testbuffer2,test2size,0,threeB,threesize);
  107468. fprintf(stderr,"ok.");
  107469. fprintf(stderr,"\n32 bit preclipped packing (MSb): ");
  107470. oggpackB_reset(&o);
  107471. for(i=0;i<test2size;i++)
  107472. oggpackB_write(&o,large[i],32);
  107473. buffer=oggpackB_get_buffer(&o);
  107474. bytes=oggpackB_bytes(&o);
  107475. oggpackB_readinit(&r,buffer,bytes);
  107476. for(i=0;i<test2size;i++){
  107477. if(oggpackB_look(&r,32)==-1)report("out of data. failed!");
  107478. if(oggpackB_look(&r,32)!=large[i]){
  107479. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpackB_look(&r,32),large[i],
  107480. oggpackB_look(&r,32),large[i]);
  107481. report("read incorrect value!\n");
  107482. }
  107483. oggpackB_adv(&r,32);
  107484. }
  107485. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  107486. fprintf(stderr,"ok.");
  107487. fprintf(stderr,"\nSmall unclipped packing (MSb): ");
  107488. cliptestB(testbuffer1,test1size,7,fourB,foursize);
  107489. fprintf(stderr,"ok.");
  107490. fprintf(stderr,"\nLarge unclipped packing (MSb): ");
  107491. cliptestB(testbuffer2,test2size,17,fiveB,fivesize);
  107492. fprintf(stderr,"ok.");
  107493. fprintf(stderr,"\nSingle bit unclipped packing (MSb): ");
  107494. cliptestB(testbuffer3,test3size,1,sixB,sixsize);
  107495. fprintf(stderr,"ok.");
  107496. fprintf(stderr,"\nTesting read past end (MSb): ");
  107497. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  107498. for(i=0;i<64;i++){
  107499. if(oggpackB_read(&r,1)!=0){
  107500. fprintf(stderr,"failed; got -1 prematurely.\n");
  107501. exit(1);
  107502. }
  107503. }
  107504. if(oggpackB_look(&r,1)!=-1 ||
  107505. oggpackB_read(&r,1)!=-1){
  107506. fprintf(stderr,"failed; read past end without -1.\n");
  107507. exit(1);
  107508. }
  107509. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  107510. if(oggpackB_read(&r,30)!=0 || oggpackB_read(&r,16)!=0){
  107511. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  107512. exit(1);
  107513. }
  107514. if(oggpackB_look(&r,18)!=0 ||
  107515. oggpackB_look(&r,18)!=0){
  107516. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  107517. exit(1);
  107518. }
  107519. if(oggpackB_look(&r,19)!=-1 ||
  107520. oggpackB_look(&r,19)!=-1){
  107521. fprintf(stderr,"failed; read past end without -1.\n");
  107522. exit(1);
  107523. }
  107524. if(oggpackB_look(&r,32)!=-1 ||
  107525. oggpackB_look(&r,32)!=-1){
  107526. fprintf(stderr,"failed; read past end without -1.\n");
  107527. exit(1);
  107528. }
  107529. oggpackB_writeclear(&o);
  107530. fprintf(stderr,"ok.\n\n");
  107531. return(0);
  107532. }
  107533. #endif /* _V_SELFTEST */
  107534. #undef BUFFER_INCREMENT
  107535. #endif
  107536. /*** End of inlined file: bitwise.c ***/
  107537. /*** Start of inlined file: framing.c ***/
  107538. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  107539. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107540. // tasks..
  107541. #if JUCE_MSVC
  107542. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107543. #endif
  107544. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  107545. #if JUCE_USE_OGGVORBIS
  107546. #include <stdlib.h>
  107547. #include <string.h>
  107548. /* A complete description of Ogg framing exists in docs/framing.html */
  107549. int ogg_page_version(ogg_page *og){
  107550. return((int)(og->header[4]));
  107551. }
  107552. int ogg_page_continued(ogg_page *og){
  107553. return((int)(og->header[5]&0x01));
  107554. }
  107555. int ogg_page_bos(ogg_page *og){
  107556. return((int)(og->header[5]&0x02));
  107557. }
  107558. int ogg_page_eos(ogg_page *og){
  107559. return((int)(og->header[5]&0x04));
  107560. }
  107561. ogg_int64_t ogg_page_granulepos(ogg_page *og){
  107562. unsigned char *page=og->header;
  107563. ogg_int64_t granulepos=page[13]&(0xff);
  107564. granulepos= (granulepos<<8)|(page[12]&0xff);
  107565. granulepos= (granulepos<<8)|(page[11]&0xff);
  107566. granulepos= (granulepos<<8)|(page[10]&0xff);
  107567. granulepos= (granulepos<<8)|(page[9]&0xff);
  107568. granulepos= (granulepos<<8)|(page[8]&0xff);
  107569. granulepos= (granulepos<<8)|(page[7]&0xff);
  107570. granulepos= (granulepos<<8)|(page[6]&0xff);
  107571. return(granulepos);
  107572. }
  107573. int ogg_page_serialno(ogg_page *og){
  107574. return(og->header[14] |
  107575. (og->header[15]<<8) |
  107576. (og->header[16]<<16) |
  107577. (og->header[17]<<24));
  107578. }
  107579. long ogg_page_pageno(ogg_page *og){
  107580. return(og->header[18] |
  107581. (og->header[19]<<8) |
  107582. (og->header[20]<<16) |
  107583. (og->header[21]<<24));
  107584. }
  107585. /* returns the number of packets that are completed on this page (if
  107586. the leading packet is begun on a previous page, but ends on this
  107587. page, it's counted */
  107588. /* NOTE:
  107589. If a page consists of a packet begun on a previous page, and a new
  107590. packet begun (but not completed) on this page, the return will be:
  107591. ogg_page_packets(page) ==1,
  107592. ogg_page_continued(page) !=0
  107593. If a page happens to be a single packet that was begun on a
  107594. previous page, and spans to the next page (in the case of a three or
  107595. more page packet), the return will be:
  107596. ogg_page_packets(page) ==0,
  107597. ogg_page_continued(page) !=0
  107598. */
  107599. int ogg_page_packets(ogg_page *og){
  107600. int i,n=og->header[26],count=0;
  107601. for(i=0;i<n;i++)
  107602. if(og->header[27+i]<255)count++;
  107603. return(count);
  107604. }
  107605. #if 0
  107606. /* helper to initialize lookup for direct-table CRC (illustrative; we
  107607. use the static init below) */
  107608. static ogg_uint32_t _ogg_crc_entry(unsigned long index){
  107609. int i;
  107610. unsigned long r;
  107611. r = index << 24;
  107612. for (i=0; i<8; i++)
  107613. if (r & 0x80000000UL)
  107614. r = (r << 1) ^ 0x04c11db7; /* The same as the ethernet generator
  107615. polynomial, although we use an
  107616. unreflected alg and an init/final
  107617. of 0, not 0xffffffff */
  107618. else
  107619. r<<=1;
  107620. return (r & 0xffffffffUL);
  107621. }
  107622. #endif
  107623. static const ogg_uint32_t crc_lookup[256]={
  107624. 0x00000000,0x04c11db7,0x09823b6e,0x0d4326d9,
  107625. 0x130476dc,0x17c56b6b,0x1a864db2,0x1e475005,
  107626. 0x2608edb8,0x22c9f00f,0x2f8ad6d6,0x2b4bcb61,
  107627. 0x350c9b64,0x31cd86d3,0x3c8ea00a,0x384fbdbd,
  107628. 0x4c11db70,0x48d0c6c7,0x4593e01e,0x4152fda9,
  107629. 0x5f15adac,0x5bd4b01b,0x569796c2,0x52568b75,
  107630. 0x6a1936c8,0x6ed82b7f,0x639b0da6,0x675a1011,
  107631. 0x791d4014,0x7ddc5da3,0x709f7b7a,0x745e66cd,
  107632. 0x9823b6e0,0x9ce2ab57,0x91a18d8e,0x95609039,
  107633. 0x8b27c03c,0x8fe6dd8b,0x82a5fb52,0x8664e6e5,
  107634. 0xbe2b5b58,0xbaea46ef,0xb7a96036,0xb3687d81,
  107635. 0xad2f2d84,0xa9ee3033,0xa4ad16ea,0xa06c0b5d,
  107636. 0xd4326d90,0xd0f37027,0xddb056fe,0xd9714b49,
  107637. 0xc7361b4c,0xc3f706fb,0xceb42022,0xca753d95,
  107638. 0xf23a8028,0xf6fb9d9f,0xfbb8bb46,0xff79a6f1,
  107639. 0xe13ef6f4,0xe5ffeb43,0xe8bccd9a,0xec7dd02d,
  107640. 0x34867077,0x30476dc0,0x3d044b19,0x39c556ae,
  107641. 0x278206ab,0x23431b1c,0x2e003dc5,0x2ac12072,
  107642. 0x128e9dcf,0x164f8078,0x1b0ca6a1,0x1fcdbb16,
  107643. 0x018aeb13,0x054bf6a4,0x0808d07d,0x0cc9cdca,
  107644. 0x7897ab07,0x7c56b6b0,0x71159069,0x75d48dde,
  107645. 0x6b93dddb,0x6f52c06c,0x6211e6b5,0x66d0fb02,
  107646. 0x5e9f46bf,0x5a5e5b08,0x571d7dd1,0x53dc6066,
  107647. 0x4d9b3063,0x495a2dd4,0x44190b0d,0x40d816ba,
  107648. 0xaca5c697,0xa864db20,0xa527fdf9,0xa1e6e04e,
  107649. 0xbfa1b04b,0xbb60adfc,0xb6238b25,0xb2e29692,
  107650. 0x8aad2b2f,0x8e6c3698,0x832f1041,0x87ee0df6,
  107651. 0x99a95df3,0x9d684044,0x902b669d,0x94ea7b2a,
  107652. 0xe0b41de7,0xe4750050,0xe9362689,0xedf73b3e,
  107653. 0xf3b06b3b,0xf771768c,0xfa325055,0xfef34de2,
  107654. 0xc6bcf05f,0xc27dede8,0xcf3ecb31,0xcbffd686,
  107655. 0xd5b88683,0xd1799b34,0xdc3abded,0xd8fba05a,
  107656. 0x690ce0ee,0x6dcdfd59,0x608edb80,0x644fc637,
  107657. 0x7a089632,0x7ec98b85,0x738aad5c,0x774bb0eb,
  107658. 0x4f040d56,0x4bc510e1,0x46863638,0x42472b8f,
  107659. 0x5c007b8a,0x58c1663d,0x558240e4,0x51435d53,
  107660. 0x251d3b9e,0x21dc2629,0x2c9f00f0,0x285e1d47,
  107661. 0x36194d42,0x32d850f5,0x3f9b762c,0x3b5a6b9b,
  107662. 0x0315d626,0x07d4cb91,0x0a97ed48,0x0e56f0ff,
  107663. 0x1011a0fa,0x14d0bd4d,0x19939b94,0x1d528623,
  107664. 0xf12f560e,0xf5ee4bb9,0xf8ad6d60,0xfc6c70d7,
  107665. 0xe22b20d2,0xe6ea3d65,0xeba91bbc,0xef68060b,
  107666. 0xd727bbb6,0xd3e6a601,0xdea580d8,0xda649d6f,
  107667. 0xc423cd6a,0xc0e2d0dd,0xcda1f604,0xc960ebb3,
  107668. 0xbd3e8d7e,0xb9ff90c9,0xb4bcb610,0xb07daba7,
  107669. 0xae3afba2,0xaafbe615,0xa7b8c0cc,0xa379dd7b,
  107670. 0x9b3660c6,0x9ff77d71,0x92b45ba8,0x9675461f,
  107671. 0x8832161a,0x8cf30bad,0x81b02d74,0x857130c3,
  107672. 0x5d8a9099,0x594b8d2e,0x5408abf7,0x50c9b640,
  107673. 0x4e8ee645,0x4a4ffbf2,0x470cdd2b,0x43cdc09c,
  107674. 0x7b827d21,0x7f436096,0x7200464f,0x76c15bf8,
  107675. 0x68860bfd,0x6c47164a,0x61043093,0x65c52d24,
  107676. 0x119b4be9,0x155a565e,0x18197087,0x1cd86d30,
  107677. 0x029f3d35,0x065e2082,0x0b1d065b,0x0fdc1bec,
  107678. 0x3793a651,0x3352bbe6,0x3e119d3f,0x3ad08088,
  107679. 0x2497d08d,0x2056cd3a,0x2d15ebe3,0x29d4f654,
  107680. 0xc5a92679,0xc1683bce,0xcc2b1d17,0xc8ea00a0,
  107681. 0xd6ad50a5,0xd26c4d12,0xdf2f6bcb,0xdbee767c,
  107682. 0xe3a1cbc1,0xe760d676,0xea23f0af,0xeee2ed18,
  107683. 0xf0a5bd1d,0xf464a0aa,0xf9278673,0xfde69bc4,
  107684. 0x89b8fd09,0x8d79e0be,0x803ac667,0x84fbdbd0,
  107685. 0x9abc8bd5,0x9e7d9662,0x933eb0bb,0x97ffad0c,
  107686. 0xafb010b1,0xab710d06,0xa6322bdf,0xa2f33668,
  107687. 0xbcb4666d,0xb8757bda,0xb5365d03,0xb1f740b4};
  107688. /* init the encode/decode logical stream state */
  107689. int ogg_stream_init(ogg_stream_state *os,int serialno){
  107690. if(os){
  107691. memset(os,0,sizeof(*os));
  107692. os->body_storage=16*1024;
  107693. os->body_data=(unsigned char*) _ogg_malloc(os->body_storage*sizeof(*os->body_data));
  107694. os->lacing_storage=1024;
  107695. os->lacing_vals=(int*) _ogg_malloc(os->lacing_storage*sizeof(*os->lacing_vals));
  107696. os->granule_vals=(ogg_int64_t*) _ogg_malloc(os->lacing_storage*sizeof(*os->granule_vals));
  107697. os->serialno=serialno;
  107698. return(0);
  107699. }
  107700. return(-1);
  107701. }
  107702. /* _clear does not free os, only the non-flat storage within */
  107703. int ogg_stream_clear(ogg_stream_state *os){
  107704. if(os){
  107705. if(os->body_data)_ogg_free(os->body_data);
  107706. if(os->lacing_vals)_ogg_free(os->lacing_vals);
  107707. if(os->granule_vals)_ogg_free(os->granule_vals);
  107708. memset(os,0,sizeof(*os));
  107709. }
  107710. return(0);
  107711. }
  107712. int ogg_stream_destroy(ogg_stream_state *os){
  107713. if(os){
  107714. ogg_stream_clear(os);
  107715. _ogg_free(os);
  107716. }
  107717. return(0);
  107718. }
  107719. /* Helpers for ogg_stream_encode; this keeps the structure and
  107720. what's happening fairly clear */
  107721. static void _os_body_expand(ogg_stream_state *os,int needed){
  107722. if(os->body_storage<=os->body_fill+needed){
  107723. os->body_storage+=(needed+1024);
  107724. os->body_data=(unsigned char*) _ogg_realloc(os->body_data,os->body_storage*sizeof(*os->body_data));
  107725. }
  107726. }
  107727. static void _os_lacing_expand(ogg_stream_state *os,int needed){
  107728. if(os->lacing_storage<=os->lacing_fill+needed){
  107729. os->lacing_storage+=(needed+32);
  107730. os->lacing_vals=(int*)_ogg_realloc(os->lacing_vals,os->lacing_storage*sizeof(*os->lacing_vals));
  107731. os->granule_vals=(ogg_int64_t*)_ogg_realloc(os->granule_vals,os->lacing_storage*sizeof(*os->granule_vals));
  107732. }
  107733. }
  107734. /* checksum the page */
  107735. /* Direct table CRC; note that this will be faster in the future if we
  107736. perform the checksum silmultaneously with other copies */
  107737. void ogg_page_checksum_set(ogg_page *og){
  107738. if(og){
  107739. ogg_uint32_t crc_reg=0;
  107740. int i;
  107741. /* safety; needed for API behavior, but not framing code */
  107742. og->header[22]=0;
  107743. og->header[23]=0;
  107744. og->header[24]=0;
  107745. og->header[25]=0;
  107746. for(i=0;i<og->header_len;i++)
  107747. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->header[i]];
  107748. for(i=0;i<og->body_len;i++)
  107749. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->body[i]];
  107750. og->header[22]=(unsigned char)(crc_reg&0xff);
  107751. og->header[23]=(unsigned char)((crc_reg>>8)&0xff);
  107752. og->header[24]=(unsigned char)((crc_reg>>16)&0xff);
  107753. og->header[25]=(unsigned char)((crc_reg>>24)&0xff);
  107754. }
  107755. }
  107756. /* submit data to the internal buffer of the framing engine */
  107757. int ogg_stream_packetin(ogg_stream_state *os,ogg_packet *op){
  107758. int lacing_vals=op->bytes/255+1,i;
  107759. if(os->body_returned){
  107760. /* advance packet data according to the body_returned pointer. We
  107761. had to keep it around to return a pointer into the buffer last
  107762. call */
  107763. os->body_fill-=os->body_returned;
  107764. if(os->body_fill)
  107765. memmove(os->body_data,os->body_data+os->body_returned,
  107766. os->body_fill);
  107767. os->body_returned=0;
  107768. }
  107769. /* make sure we have the buffer storage */
  107770. _os_body_expand(os,op->bytes);
  107771. _os_lacing_expand(os,lacing_vals);
  107772. /* Copy in the submitted packet. Yes, the copy is a waste; this is
  107773. the liability of overly clean abstraction for the time being. It
  107774. will actually be fairly easy to eliminate the extra copy in the
  107775. future */
  107776. memcpy(os->body_data+os->body_fill,op->packet,op->bytes);
  107777. os->body_fill+=op->bytes;
  107778. /* Store lacing vals for this packet */
  107779. for(i=0;i<lacing_vals-1;i++){
  107780. os->lacing_vals[os->lacing_fill+i]=255;
  107781. os->granule_vals[os->lacing_fill+i]=os->granulepos;
  107782. }
  107783. os->lacing_vals[os->lacing_fill+i]=(op->bytes)%255;
  107784. os->granulepos=os->granule_vals[os->lacing_fill+i]=op->granulepos;
  107785. /* flag the first segment as the beginning of the packet */
  107786. os->lacing_vals[os->lacing_fill]|= 0x100;
  107787. os->lacing_fill+=lacing_vals;
  107788. /* for the sake of completeness */
  107789. os->packetno++;
  107790. if(op->e_o_s)os->e_o_s=1;
  107791. return(0);
  107792. }
  107793. /* This will flush remaining packets into a page (returning nonzero),
  107794. even if there is not enough data to trigger a flush normally
  107795. (undersized page). If there are no packets or partial packets to
  107796. flush, ogg_stream_flush returns 0. Note that ogg_stream_flush will
  107797. try to flush a normal sized page like ogg_stream_pageout; a call to
  107798. ogg_stream_flush does not guarantee that all packets have flushed.
  107799. Only a return value of 0 from ogg_stream_flush indicates all packet
  107800. data is flushed into pages.
  107801. since ogg_stream_flush will flush the last page in a stream even if
  107802. it's undersized, you almost certainly want to use ogg_stream_pageout
  107803. (and *not* ogg_stream_flush) unless you specifically need to flush
  107804. an page regardless of size in the middle of a stream. */
  107805. int ogg_stream_flush(ogg_stream_state *os,ogg_page *og){
  107806. int i;
  107807. int vals=0;
  107808. int maxvals=(os->lacing_fill>255?255:os->lacing_fill);
  107809. int bytes=0;
  107810. long acc=0;
  107811. ogg_int64_t granule_pos=-1;
  107812. if(maxvals==0)return(0);
  107813. /* construct a page */
  107814. /* decide how many segments to include */
  107815. /* If this is the initial header case, the first page must only include
  107816. the initial header packet */
  107817. if(os->b_o_s==0){ /* 'initial header page' case */
  107818. granule_pos=0;
  107819. for(vals=0;vals<maxvals;vals++){
  107820. if((os->lacing_vals[vals]&0x0ff)<255){
  107821. vals++;
  107822. break;
  107823. }
  107824. }
  107825. }else{
  107826. for(vals=0;vals<maxvals;vals++){
  107827. if(acc>4096)break;
  107828. acc+=os->lacing_vals[vals]&0x0ff;
  107829. if((os->lacing_vals[vals]&0xff)<255)
  107830. granule_pos=os->granule_vals[vals];
  107831. }
  107832. }
  107833. /* construct the header in temp storage */
  107834. memcpy(os->header,"OggS",4);
  107835. /* stream structure version */
  107836. os->header[4]=0x00;
  107837. /* continued packet flag? */
  107838. os->header[5]=0x00;
  107839. if((os->lacing_vals[0]&0x100)==0)os->header[5]|=0x01;
  107840. /* first page flag? */
  107841. if(os->b_o_s==0)os->header[5]|=0x02;
  107842. /* last page flag? */
  107843. if(os->e_o_s && os->lacing_fill==vals)os->header[5]|=0x04;
  107844. os->b_o_s=1;
  107845. /* 64 bits of PCM position */
  107846. for(i=6;i<14;i++){
  107847. os->header[i]=(unsigned char)(granule_pos&0xff);
  107848. granule_pos>>=8;
  107849. }
  107850. /* 32 bits of stream serial number */
  107851. {
  107852. long serialno=os->serialno;
  107853. for(i=14;i<18;i++){
  107854. os->header[i]=(unsigned char)(serialno&0xff);
  107855. serialno>>=8;
  107856. }
  107857. }
  107858. /* 32 bits of page counter (we have both counter and page header
  107859. because this val can roll over) */
  107860. if(os->pageno==-1)os->pageno=0; /* because someone called
  107861. stream_reset; this would be a
  107862. strange thing to do in an
  107863. encode stream, but it has
  107864. plausible uses */
  107865. {
  107866. long pageno=os->pageno++;
  107867. for(i=18;i<22;i++){
  107868. os->header[i]=(unsigned char)(pageno&0xff);
  107869. pageno>>=8;
  107870. }
  107871. }
  107872. /* zero for computation; filled in later */
  107873. os->header[22]=0;
  107874. os->header[23]=0;
  107875. os->header[24]=0;
  107876. os->header[25]=0;
  107877. /* segment table */
  107878. os->header[26]=(unsigned char)(vals&0xff);
  107879. for(i=0;i<vals;i++)
  107880. bytes+=os->header[i+27]=(unsigned char)(os->lacing_vals[i]&0xff);
  107881. /* set pointers in the ogg_page struct */
  107882. og->header=os->header;
  107883. og->header_len=os->header_fill=vals+27;
  107884. og->body=os->body_data+os->body_returned;
  107885. og->body_len=bytes;
  107886. /* advance the lacing data and set the body_returned pointer */
  107887. os->lacing_fill-=vals;
  107888. memmove(os->lacing_vals,os->lacing_vals+vals,os->lacing_fill*sizeof(*os->lacing_vals));
  107889. memmove(os->granule_vals,os->granule_vals+vals,os->lacing_fill*sizeof(*os->granule_vals));
  107890. os->body_returned+=bytes;
  107891. /* calculate the checksum */
  107892. ogg_page_checksum_set(og);
  107893. /* done */
  107894. return(1);
  107895. }
  107896. /* This constructs pages from buffered packet segments. The pointers
  107897. returned are to static buffers; do not free. The returned buffers are
  107898. good only until the next call (using the same ogg_stream_state) */
  107899. int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og){
  107900. if((os->e_o_s&&os->lacing_fill) || /* 'were done, now flush' case */
  107901. os->body_fill-os->body_returned > 4096 ||/* 'page nominal size' case */
  107902. os->lacing_fill>=255 || /* 'segment table full' case */
  107903. (os->lacing_fill&&!os->b_o_s)){ /* 'initial header page' case */
  107904. return(ogg_stream_flush(os,og));
  107905. }
  107906. /* not enough data to construct a page and not end of stream */
  107907. return(0);
  107908. }
  107909. int ogg_stream_eos(ogg_stream_state *os){
  107910. return os->e_o_s;
  107911. }
  107912. /* DECODING PRIMITIVES: packet streaming layer **********************/
  107913. /* This has two layers to place more of the multi-serialno and paging
  107914. control in the application's hands. First, we expose a data buffer
  107915. using ogg_sync_buffer(). The app either copies into the
  107916. buffer, or passes it directly to read(), etc. We then call
  107917. ogg_sync_wrote() to tell how many bytes we just added.
  107918. Pages are returned (pointers into the buffer in ogg_sync_state)
  107919. by ogg_sync_pageout(). The page is then submitted to
  107920. ogg_stream_pagein() along with the appropriate
  107921. ogg_stream_state* (ie, matching serialno). We then get raw
  107922. packets out calling ogg_stream_packetout() with a
  107923. ogg_stream_state. */
  107924. /* initialize the struct to a known state */
  107925. int ogg_sync_init(ogg_sync_state *oy){
  107926. if(oy){
  107927. memset(oy,0,sizeof(*oy));
  107928. }
  107929. return(0);
  107930. }
  107931. /* clear non-flat storage within */
  107932. int ogg_sync_clear(ogg_sync_state *oy){
  107933. if(oy){
  107934. if(oy->data)_ogg_free(oy->data);
  107935. ogg_sync_init(oy);
  107936. }
  107937. return(0);
  107938. }
  107939. int ogg_sync_destroy(ogg_sync_state *oy){
  107940. if(oy){
  107941. ogg_sync_clear(oy);
  107942. _ogg_free(oy);
  107943. }
  107944. return(0);
  107945. }
  107946. char *ogg_sync_buffer(ogg_sync_state *oy, long size){
  107947. /* first, clear out any space that has been previously returned */
  107948. if(oy->returned){
  107949. oy->fill-=oy->returned;
  107950. if(oy->fill>0)
  107951. memmove(oy->data,oy->data+oy->returned,oy->fill);
  107952. oy->returned=0;
  107953. }
  107954. if(size>oy->storage-oy->fill){
  107955. /* We need to extend the internal buffer */
  107956. long newsize=size+oy->fill+4096; /* an extra page to be nice */
  107957. if(oy->data)
  107958. oy->data=(unsigned char*) _ogg_realloc(oy->data,newsize);
  107959. else
  107960. oy->data=(unsigned char*) _ogg_malloc(newsize);
  107961. oy->storage=newsize;
  107962. }
  107963. /* expose a segment at least as large as requested at the fill mark */
  107964. return((char *)oy->data+oy->fill);
  107965. }
  107966. int ogg_sync_wrote(ogg_sync_state *oy, long bytes){
  107967. if(oy->fill+bytes>oy->storage)return(-1);
  107968. oy->fill+=bytes;
  107969. return(0);
  107970. }
  107971. /* sync the stream. This is meant to be useful for finding page
  107972. boundaries.
  107973. return values for this:
  107974. -n) skipped n bytes
  107975. 0) page not ready; more data (no bytes skipped)
  107976. n) page synced at current location; page length n bytes
  107977. */
  107978. long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og){
  107979. unsigned char *page=oy->data+oy->returned;
  107980. unsigned char *next;
  107981. long bytes=oy->fill-oy->returned;
  107982. if(oy->headerbytes==0){
  107983. int headerbytes,i;
  107984. if(bytes<27)return(0); /* not enough for a header */
  107985. /* verify capture pattern */
  107986. if(memcmp(page,"OggS",4))goto sync_fail;
  107987. headerbytes=page[26]+27;
  107988. if(bytes<headerbytes)return(0); /* not enough for header + seg table */
  107989. /* count up body length in the segment table */
  107990. for(i=0;i<page[26];i++)
  107991. oy->bodybytes+=page[27+i];
  107992. oy->headerbytes=headerbytes;
  107993. }
  107994. if(oy->bodybytes+oy->headerbytes>bytes)return(0);
  107995. /* The whole test page is buffered. Verify the checksum */
  107996. {
  107997. /* Grab the checksum bytes, set the header field to zero */
  107998. char chksum[4];
  107999. ogg_page log;
  108000. memcpy(chksum,page+22,4);
  108001. memset(page+22,0,4);
  108002. /* set up a temp page struct and recompute the checksum */
  108003. log.header=page;
  108004. log.header_len=oy->headerbytes;
  108005. log.body=page+oy->headerbytes;
  108006. log.body_len=oy->bodybytes;
  108007. ogg_page_checksum_set(&log);
  108008. /* Compare */
  108009. if(memcmp(chksum,page+22,4)){
  108010. /* D'oh. Mismatch! Corrupt page (or miscapture and not a page
  108011. at all) */
  108012. /* replace the computed checksum with the one actually read in */
  108013. memcpy(page+22,chksum,4);
  108014. /* Bad checksum. Lose sync */
  108015. goto sync_fail;
  108016. }
  108017. }
  108018. /* yes, have a whole page all ready to go */
  108019. {
  108020. unsigned char *page=oy->data+oy->returned;
  108021. long bytes;
  108022. if(og){
  108023. og->header=page;
  108024. og->header_len=oy->headerbytes;
  108025. og->body=page+oy->headerbytes;
  108026. og->body_len=oy->bodybytes;
  108027. }
  108028. oy->unsynced=0;
  108029. oy->returned+=(bytes=oy->headerbytes+oy->bodybytes);
  108030. oy->headerbytes=0;
  108031. oy->bodybytes=0;
  108032. return(bytes);
  108033. }
  108034. sync_fail:
  108035. oy->headerbytes=0;
  108036. oy->bodybytes=0;
  108037. /* search for possible capture */
  108038. next=(unsigned char*)memchr(page+1,'O',bytes-1);
  108039. if(!next)
  108040. next=oy->data+oy->fill;
  108041. oy->returned=next-oy->data;
  108042. return(-(next-page));
  108043. }
  108044. /* sync the stream and get a page. Keep trying until we find a page.
  108045. Supress 'sync errors' after reporting the first.
  108046. return values:
  108047. -1) recapture (hole in data)
  108048. 0) need more data
  108049. 1) page returned
  108050. Returns pointers into buffered data; invalidated by next call to
  108051. _stream, _clear, _init, or _buffer */
  108052. int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og){
  108053. /* all we need to do is verify a page at the head of the stream
  108054. buffer. If it doesn't verify, we look for the next potential
  108055. frame */
  108056. for(;;){
  108057. long ret=ogg_sync_pageseek(oy,og);
  108058. if(ret>0){
  108059. /* have a page */
  108060. return(1);
  108061. }
  108062. if(ret==0){
  108063. /* need more data */
  108064. return(0);
  108065. }
  108066. /* head did not start a synced page... skipped some bytes */
  108067. if(!oy->unsynced){
  108068. oy->unsynced=1;
  108069. return(-1);
  108070. }
  108071. /* loop. keep looking */
  108072. }
  108073. }
  108074. /* add the incoming page to the stream state; we decompose the page
  108075. into packet segments here as well. */
  108076. int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og){
  108077. unsigned char *header=og->header;
  108078. unsigned char *body=og->body;
  108079. long bodysize=og->body_len;
  108080. int segptr=0;
  108081. int version=ogg_page_version(og);
  108082. int continued=ogg_page_continued(og);
  108083. int bos=ogg_page_bos(og);
  108084. int eos=ogg_page_eos(og);
  108085. ogg_int64_t granulepos=ogg_page_granulepos(og);
  108086. int serialno=ogg_page_serialno(og);
  108087. long pageno=ogg_page_pageno(og);
  108088. int segments=header[26];
  108089. /* clean up 'returned data' */
  108090. {
  108091. long lr=os->lacing_returned;
  108092. long br=os->body_returned;
  108093. /* body data */
  108094. if(br){
  108095. os->body_fill-=br;
  108096. if(os->body_fill)
  108097. memmove(os->body_data,os->body_data+br,os->body_fill);
  108098. os->body_returned=0;
  108099. }
  108100. if(lr){
  108101. /* segment table */
  108102. if(os->lacing_fill-lr){
  108103. memmove(os->lacing_vals,os->lacing_vals+lr,
  108104. (os->lacing_fill-lr)*sizeof(*os->lacing_vals));
  108105. memmove(os->granule_vals,os->granule_vals+lr,
  108106. (os->lacing_fill-lr)*sizeof(*os->granule_vals));
  108107. }
  108108. os->lacing_fill-=lr;
  108109. os->lacing_packet-=lr;
  108110. os->lacing_returned=0;
  108111. }
  108112. }
  108113. /* check the serial number */
  108114. if(serialno!=os->serialno)return(-1);
  108115. if(version>0)return(-1);
  108116. _os_lacing_expand(os,segments+1);
  108117. /* are we in sequence? */
  108118. if(pageno!=os->pageno){
  108119. int i;
  108120. /* unroll previous partial packet (if any) */
  108121. for(i=os->lacing_packet;i<os->lacing_fill;i++)
  108122. os->body_fill-=os->lacing_vals[i]&0xff;
  108123. os->lacing_fill=os->lacing_packet;
  108124. /* make a note of dropped data in segment table */
  108125. if(os->pageno!=-1){
  108126. os->lacing_vals[os->lacing_fill++]=0x400;
  108127. os->lacing_packet++;
  108128. }
  108129. }
  108130. /* are we a 'continued packet' page? If so, we may need to skip
  108131. some segments */
  108132. if(continued){
  108133. if(os->lacing_fill<1 ||
  108134. os->lacing_vals[os->lacing_fill-1]==0x400){
  108135. bos=0;
  108136. for(;segptr<segments;segptr++){
  108137. int val=header[27+segptr];
  108138. body+=val;
  108139. bodysize-=val;
  108140. if(val<255){
  108141. segptr++;
  108142. break;
  108143. }
  108144. }
  108145. }
  108146. }
  108147. if(bodysize){
  108148. _os_body_expand(os,bodysize);
  108149. memcpy(os->body_data+os->body_fill,body,bodysize);
  108150. os->body_fill+=bodysize;
  108151. }
  108152. {
  108153. int saved=-1;
  108154. while(segptr<segments){
  108155. int val=header[27+segptr];
  108156. os->lacing_vals[os->lacing_fill]=val;
  108157. os->granule_vals[os->lacing_fill]=-1;
  108158. if(bos){
  108159. os->lacing_vals[os->lacing_fill]|=0x100;
  108160. bos=0;
  108161. }
  108162. if(val<255)saved=os->lacing_fill;
  108163. os->lacing_fill++;
  108164. segptr++;
  108165. if(val<255)os->lacing_packet=os->lacing_fill;
  108166. }
  108167. /* set the granulepos on the last granuleval of the last full packet */
  108168. if(saved!=-1){
  108169. os->granule_vals[saved]=granulepos;
  108170. }
  108171. }
  108172. if(eos){
  108173. os->e_o_s=1;
  108174. if(os->lacing_fill>0)
  108175. os->lacing_vals[os->lacing_fill-1]|=0x200;
  108176. }
  108177. os->pageno=pageno+1;
  108178. return(0);
  108179. }
  108180. /* clear things to an initial state. Good to call, eg, before seeking */
  108181. int ogg_sync_reset(ogg_sync_state *oy){
  108182. oy->fill=0;
  108183. oy->returned=0;
  108184. oy->unsynced=0;
  108185. oy->headerbytes=0;
  108186. oy->bodybytes=0;
  108187. return(0);
  108188. }
  108189. int ogg_stream_reset(ogg_stream_state *os){
  108190. os->body_fill=0;
  108191. os->body_returned=0;
  108192. os->lacing_fill=0;
  108193. os->lacing_packet=0;
  108194. os->lacing_returned=0;
  108195. os->header_fill=0;
  108196. os->e_o_s=0;
  108197. os->b_o_s=0;
  108198. os->pageno=-1;
  108199. os->packetno=0;
  108200. os->granulepos=0;
  108201. return(0);
  108202. }
  108203. int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno){
  108204. ogg_stream_reset(os);
  108205. os->serialno=serialno;
  108206. return(0);
  108207. }
  108208. static int _packetout(ogg_stream_state *os,ogg_packet *op,int adv){
  108209. /* The last part of decode. We have the stream broken into packet
  108210. segments. Now we need to group them into packets (or return the
  108211. out of sync markers) */
  108212. int ptr=os->lacing_returned;
  108213. if(os->lacing_packet<=ptr)return(0);
  108214. if(os->lacing_vals[ptr]&0x400){
  108215. /* we need to tell the codec there's a gap; it might need to
  108216. handle previous packet dependencies. */
  108217. os->lacing_returned++;
  108218. os->packetno++;
  108219. return(-1);
  108220. }
  108221. if(!op && !adv)return(1); /* just using peek as an inexpensive way
  108222. to ask if there's a whole packet
  108223. waiting */
  108224. /* Gather the whole packet. We'll have no holes or a partial packet */
  108225. {
  108226. int size=os->lacing_vals[ptr]&0xff;
  108227. int bytes=size;
  108228. int eos=os->lacing_vals[ptr]&0x200; /* last packet of the stream? */
  108229. int bos=os->lacing_vals[ptr]&0x100; /* first packet of the stream? */
  108230. while(size==255){
  108231. int val=os->lacing_vals[++ptr];
  108232. size=val&0xff;
  108233. if(val&0x200)eos=0x200;
  108234. bytes+=size;
  108235. }
  108236. if(op){
  108237. op->e_o_s=eos;
  108238. op->b_o_s=bos;
  108239. op->packet=os->body_data+os->body_returned;
  108240. op->packetno=os->packetno;
  108241. op->granulepos=os->granule_vals[ptr];
  108242. op->bytes=bytes;
  108243. }
  108244. if(adv){
  108245. os->body_returned+=bytes;
  108246. os->lacing_returned=ptr+1;
  108247. os->packetno++;
  108248. }
  108249. }
  108250. return(1);
  108251. }
  108252. int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op){
  108253. return _packetout(os,op,1);
  108254. }
  108255. int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op){
  108256. return _packetout(os,op,0);
  108257. }
  108258. void ogg_packet_clear(ogg_packet *op) {
  108259. _ogg_free(op->packet);
  108260. memset(op, 0, sizeof(*op));
  108261. }
  108262. #ifdef _V_SELFTEST
  108263. #include <stdio.h>
  108264. ogg_stream_state os_en, os_de;
  108265. ogg_sync_state oy;
  108266. void checkpacket(ogg_packet *op,int len, int no, int pos){
  108267. long j;
  108268. static int sequence=0;
  108269. static int lastno=0;
  108270. if(op->bytes!=len){
  108271. fprintf(stderr,"incorrect packet length!\n");
  108272. exit(1);
  108273. }
  108274. if(op->granulepos!=pos){
  108275. fprintf(stderr,"incorrect packet position!\n");
  108276. exit(1);
  108277. }
  108278. /* packet number just follows sequence/gap; adjust the input number
  108279. for that */
  108280. if(no==0){
  108281. sequence=0;
  108282. }else{
  108283. sequence++;
  108284. if(no>lastno+1)
  108285. sequence++;
  108286. }
  108287. lastno=no;
  108288. if(op->packetno!=sequence){
  108289. fprintf(stderr,"incorrect packet sequence %ld != %d\n",
  108290. (long)(op->packetno),sequence);
  108291. exit(1);
  108292. }
  108293. /* Test data */
  108294. for(j=0;j<op->bytes;j++)
  108295. if(op->packet[j]!=((j+no)&0xff)){
  108296. fprintf(stderr,"body data mismatch (1) at pos %ld: %x!=%lx!\n\n",
  108297. j,op->packet[j],(j+no)&0xff);
  108298. exit(1);
  108299. }
  108300. }
  108301. void check_page(unsigned char *data,const int *header,ogg_page *og){
  108302. long j;
  108303. /* Test data */
  108304. for(j=0;j<og->body_len;j++)
  108305. if(og->body[j]!=data[j]){
  108306. fprintf(stderr,"body data mismatch (2) at pos %ld: %x!=%x!\n\n",
  108307. j,data[j],og->body[j]);
  108308. exit(1);
  108309. }
  108310. /* Test header */
  108311. for(j=0;j<og->header_len;j++){
  108312. if(og->header[j]!=header[j]){
  108313. fprintf(stderr,"header content mismatch at pos %ld:\n",j);
  108314. for(j=0;j<header[26]+27;j++)
  108315. fprintf(stderr," (%ld)%02x:%02x",j,header[j],og->header[j]);
  108316. fprintf(stderr,"\n");
  108317. exit(1);
  108318. }
  108319. }
  108320. if(og->header_len!=header[26]+27){
  108321. fprintf(stderr,"header length incorrect! (%ld!=%d)\n",
  108322. og->header_len,header[26]+27);
  108323. exit(1);
  108324. }
  108325. }
  108326. void print_header(ogg_page *og){
  108327. int j;
  108328. fprintf(stderr,"\nHEADER:\n");
  108329. fprintf(stderr," capture: %c %c %c %c version: %d flags: %x\n",
  108330. og->header[0],og->header[1],og->header[2],og->header[3],
  108331. (int)og->header[4],(int)og->header[5]);
  108332. fprintf(stderr," granulepos: %d serialno: %d pageno: %ld\n",
  108333. (og->header[9]<<24)|(og->header[8]<<16)|
  108334. (og->header[7]<<8)|og->header[6],
  108335. (og->header[17]<<24)|(og->header[16]<<16)|
  108336. (og->header[15]<<8)|og->header[14],
  108337. ((long)(og->header[21])<<24)|(og->header[20]<<16)|
  108338. (og->header[19]<<8)|og->header[18]);
  108339. fprintf(stderr," checksum: %02x:%02x:%02x:%02x\n segments: %d (",
  108340. (int)og->header[22],(int)og->header[23],
  108341. (int)og->header[24],(int)og->header[25],
  108342. (int)og->header[26]);
  108343. for(j=27;j<og->header_len;j++)
  108344. fprintf(stderr,"%d ",(int)og->header[j]);
  108345. fprintf(stderr,")\n\n");
  108346. }
  108347. void copy_page(ogg_page *og){
  108348. unsigned char *temp=_ogg_malloc(og->header_len);
  108349. memcpy(temp,og->header,og->header_len);
  108350. og->header=temp;
  108351. temp=_ogg_malloc(og->body_len);
  108352. memcpy(temp,og->body,og->body_len);
  108353. og->body=temp;
  108354. }
  108355. void free_page(ogg_page *og){
  108356. _ogg_free (og->header);
  108357. _ogg_free (og->body);
  108358. }
  108359. void error(void){
  108360. fprintf(stderr,"error!\n");
  108361. exit(1);
  108362. }
  108363. /* 17 only */
  108364. const int head1_0[] = {0x4f,0x67,0x67,0x53,0,0x06,
  108365. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108366. 0x01,0x02,0x03,0x04,0,0,0,0,
  108367. 0x15,0xed,0xec,0x91,
  108368. 1,
  108369. 17};
  108370. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  108371. const int head1_1[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108372. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108373. 0x01,0x02,0x03,0x04,0,0,0,0,
  108374. 0x59,0x10,0x6c,0x2c,
  108375. 1,
  108376. 17};
  108377. const int head2_1[] = {0x4f,0x67,0x67,0x53,0,0x04,
  108378. 0x07,0x18,0x00,0x00,0x00,0x00,0x00,0x00,
  108379. 0x01,0x02,0x03,0x04,1,0,0,0,
  108380. 0x89,0x33,0x85,0xce,
  108381. 13,
  108382. 254,255,0,255,1,255,245,255,255,0,
  108383. 255,255,90};
  108384. /* nil packets; beginning,middle,end */
  108385. const int head1_2[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108386. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108387. 0x01,0x02,0x03,0x04,0,0,0,0,
  108388. 0xff,0x7b,0x23,0x17,
  108389. 1,
  108390. 0};
  108391. const int head2_2[] = {0x4f,0x67,0x67,0x53,0,0x04,
  108392. 0x07,0x28,0x00,0x00,0x00,0x00,0x00,0x00,
  108393. 0x01,0x02,0x03,0x04,1,0,0,0,
  108394. 0x5c,0x3f,0x66,0xcb,
  108395. 17,
  108396. 17,254,255,0,0,255,1,0,255,245,255,255,0,
  108397. 255,255,90,0};
  108398. /* large initial packet */
  108399. const int head1_3[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108400. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108401. 0x01,0x02,0x03,0x04,0,0,0,0,
  108402. 0x01,0x27,0x31,0xaa,
  108403. 18,
  108404. 255,255,255,255,255,255,255,255,
  108405. 255,255,255,255,255,255,255,255,255,10};
  108406. const int head2_3[] = {0x4f,0x67,0x67,0x53,0,0x04,
  108407. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  108408. 0x01,0x02,0x03,0x04,1,0,0,0,
  108409. 0x7f,0x4e,0x8a,0xd2,
  108410. 4,
  108411. 255,4,255,0};
  108412. /* continuing packet test */
  108413. const int head1_4[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108414. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108415. 0x01,0x02,0x03,0x04,0,0,0,0,
  108416. 0xff,0x7b,0x23,0x17,
  108417. 1,
  108418. 0};
  108419. const int head2_4[] = {0x4f,0x67,0x67,0x53,0,0x00,
  108420. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  108421. 0x01,0x02,0x03,0x04,1,0,0,0,
  108422. 0x54,0x05,0x51,0xc8,
  108423. 17,
  108424. 255,255,255,255,255,255,255,255,
  108425. 255,255,255,255,255,255,255,255,255};
  108426. const int head3_4[] = {0x4f,0x67,0x67,0x53,0,0x05,
  108427. 0x07,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,
  108428. 0x01,0x02,0x03,0x04,2,0,0,0,
  108429. 0xc8,0xc3,0xcb,0xed,
  108430. 5,
  108431. 10,255,4,255,0};
  108432. /* page with the 255 segment limit */
  108433. const int head1_5[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108434. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108435. 0x01,0x02,0x03,0x04,0,0,0,0,
  108436. 0xff,0x7b,0x23,0x17,
  108437. 1,
  108438. 0};
  108439. const int head2_5[] = {0x4f,0x67,0x67,0x53,0,0x00,
  108440. 0x07,0xfc,0x03,0x00,0x00,0x00,0x00,0x00,
  108441. 0x01,0x02,0x03,0x04,1,0,0,0,
  108442. 0xed,0x2a,0x2e,0xa7,
  108443. 255,
  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,10,
  108473. 10,10,10,10,10,10,10,10,
  108474. 10,10,10,10,10,10,10,10,
  108475. 10,10,10,10,10,10,10};
  108476. const int head3_5[] = {0x4f,0x67,0x67,0x53,0,0x04,
  108477. 0x07,0x00,0x04,0x00,0x00,0x00,0x00,0x00,
  108478. 0x01,0x02,0x03,0x04,2,0,0,0,
  108479. 0x6c,0x3b,0x82,0x3d,
  108480. 1,
  108481. 50};
  108482. /* packet that overspans over an entire page */
  108483. const int head1_6[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108484. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108485. 0x01,0x02,0x03,0x04,0,0,0,0,
  108486. 0xff,0x7b,0x23,0x17,
  108487. 1,
  108488. 0};
  108489. const int head2_6[] = {0x4f,0x67,0x67,0x53,0,0x00,
  108490. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  108491. 0x01,0x02,0x03,0x04,1,0,0,0,
  108492. 0x3c,0xd9,0x4d,0x3f,
  108493. 17,
  108494. 100,255,255,255,255,255,255,255,255,
  108495. 255,255,255,255,255,255,255,255};
  108496. const int head3_6[] = {0x4f,0x67,0x67,0x53,0,0x01,
  108497. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  108498. 0x01,0x02,0x03,0x04,2,0,0,0,
  108499. 0x01,0xd2,0xe5,0xe5,
  108500. 17,
  108501. 255,255,255,255,255,255,255,255,
  108502. 255,255,255,255,255,255,255,255,255};
  108503. const int head4_6[] = {0x4f,0x67,0x67,0x53,0,0x05,
  108504. 0x07,0x10,0x00,0x00,0x00,0x00,0x00,0x00,
  108505. 0x01,0x02,0x03,0x04,3,0,0,0,
  108506. 0xef,0xdd,0x88,0xde,
  108507. 7,
  108508. 255,255,75,255,4,255,0};
  108509. /* packet that overspans over an entire page */
  108510. const int head1_7[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108511. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108512. 0x01,0x02,0x03,0x04,0,0,0,0,
  108513. 0xff,0x7b,0x23,0x17,
  108514. 1,
  108515. 0};
  108516. const int head2_7[] = {0x4f,0x67,0x67,0x53,0,0x00,
  108517. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  108518. 0x01,0x02,0x03,0x04,1,0,0,0,
  108519. 0x3c,0xd9,0x4d,0x3f,
  108520. 17,
  108521. 100,255,255,255,255,255,255,255,255,
  108522. 255,255,255,255,255,255,255,255};
  108523. const int head3_7[] = {0x4f,0x67,0x67,0x53,0,0x05,
  108524. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  108525. 0x01,0x02,0x03,0x04,2,0,0,0,
  108526. 0xd4,0xe0,0x60,0xe5,
  108527. 1,0};
  108528. void test_pack(const int *pl, const int **headers, int byteskip,
  108529. int pageskip, int packetskip){
  108530. unsigned char *data=_ogg_malloc(1024*1024); /* for scripted test cases only */
  108531. long inptr=0;
  108532. long outptr=0;
  108533. long deptr=0;
  108534. long depacket=0;
  108535. long granule_pos=7,pageno=0;
  108536. int i,j,packets,pageout=pageskip;
  108537. int eosflag=0;
  108538. int bosflag=0;
  108539. int byteskipcount=0;
  108540. ogg_stream_reset(&os_en);
  108541. ogg_stream_reset(&os_de);
  108542. ogg_sync_reset(&oy);
  108543. for(packets=0;packets<packetskip;packets++)
  108544. depacket+=pl[packets];
  108545. for(packets=0;;packets++)if(pl[packets]==-1)break;
  108546. for(i=0;i<packets;i++){
  108547. /* construct a test packet */
  108548. ogg_packet op;
  108549. int len=pl[i];
  108550. op.packet=data+inptr;
  108551. op.bytes=len;
  108552. op.e_o_s=(pl[i+1]<0?1:0);
  108553. op.granulepos=granule_pos;
  108554. granule_pos+=1024;
  108555. for(j=0;j<len;j++)data[inptr++]=i+j;
  108556. /* submit the test packet */
  108557. ogg_stream_packetin(&os_en,&op);
  108558. /* retrieve any finished pages */
  108559. {
  108560. ogg_page og;
  108561. while(ogg_stream_pageout(&os_en,&og)){
  108562. /* We have a page. Check it carefully */
  108563. fprintf(stderr,"%ld, ",pageno);
  108564. if(headers[pageno]==NULL){
  108565. fprintf(stderr,"coded too many pages!\n");
  108566. exit(1);
  108567. }
  108568. check_page(data+outptr,headers[pageno],&og);
  108569. outptr+=og.body_len;
  108570. pageno++;
  108571. if(pageskip){
  108572. bosflag=1;
  108573. pageskip--;
  108574. deptr+=og.body_len;
  108575. }
  108576. /* have a complete page; submit it to sync/decode */
  108577. {
  108578. ogg_page og_de;
  108579. ogg_packet op_de,op_de2;
  108580. char *buf=ogg_sync_buffer(&oy,og.header_len+og.body_len);
  108581. char *next=buf;
  108582. byteskipcount+=og.header_len;
  108583. if(byteskipcount>byteskip){
  108584. memcpy(next,og.header,byteskipcount-byteskip);
  108585. next+=byteskipcount-byteskip;
  108586. byteskipcount=byteskip;
  108587. }
  108588. byteskipcount+=og.body_len;
  108589. if(byteskipcount>byteskip){
  108590. memcpy(next,og.body,byteskipcount-byteskip);
  108591. next+=byteskipcount-byteskip;
  108592. byteskipcount=byteskip;
  108593. }
  108594. ogg_sync_wrote(&oy,next-buf);
  108595. while(1){
  108596. int ret=ogg_sync_pageout(&oy,&og_de);
  108597. if(ret==0)break;
  108598. if(ret<0)continue;
  108599. /* got a page. Happy happy. Verify that it's good. */
  108600. fprintf(stderr,"(%ld), ",pageout);
  108601. check_page(data+deptr,headers[pageout],&og_de);
  108602. deptr+=og_de.body_len;
  108603. pageout++;
  108604. /* submit it to deconstitution */
  108605. ogg_stream_pagein(&os_de,&og_de);
  108606. /* packets out? */
  108607. while(ogg_stream_packetpeek(&os_de,&op_de2)>0){
  108608. ogg_stream_packetpeek(&os_de,NULL);
  108609. ogg_stream_packetout(&os_de,&op_de); /* just catching them all */
  108610. /* verify peek and out match */
  108611. if(memcmp(&op_de,&op_de2,sizeof(op_de))){
  108612. fprintf(stderr,"packetout != packetpeek! pos=%ld\n",
  108613. depacket);
  108614. exit(1);
  108615. }
  108616. /* verify the packet! */
  108617. /* check data */
  108618. if(memcmp(data+depacket,op_de.packet,op_de.bytes)){
  108619. fprintf(stderr,"packet data mismatch in decode! pos=%ld\n",
  108620. depacket);
  108621. exit(1);
  108622. }
  108623. /* check bos flag */
  108624. if(bosflag==0 && op_de.b_o_s==0){
  108625. fprintf(stderr,"b_o_s flag not set on packet!\n");
  108626. exit(1);
  108627. }
  108628. if(bosflag && op_de.b_o_s){
  108629. fprintf(stderr,"b_o_s flag incorrectly set on packet!\n");
  108630. exit(1);
  108631. }
  108632. bosflag=1;
  108633. depacket+=op_de.bytes;
  108634. /* check eos flag */
  108635. if(eosflag){
  108636. fprintf(stderr,"Multiple decoded packets with eos flag!\n");
  108637. exit(1);
  108638. }
  108639. if(op_de.e_o_s)eosflag=1;
  108640. /* check granulepos flag */
  108641. if(op_de.granulepos!=-1){
  108642. fprintf(stderr," granule:%ld ",(long)op_de.granulepos);
  108643. }
  108644. }
  108645. }
  108646. }
  108647. }
  108648. }
  108649. }
  108650. _ogg_free(data);
  108651. if(headers[pageno]!=NULL){
  108652. fprintf(stderr,"did not write last page!\n");
  108653. exit(1);
  108654. }
  108655. if(headers[pageout]!=NULL){
  108656. fprintf(stderr,"did not decode last page!\n");
  108657. exit(1);
  108658. }
  108659. if(inptr!=outptr){
  108660. fprintf(stderr,"encoded page data incomplete!\n");
  108661. exit(1);
  108662. }
  108663. if(inptr!=deptr){
  108664. fprintf(stderr,"decoded page data incomplete!\n");
  108665. exit(1);
  108666. }
  108667. if(inptr!=depacket){
  108668. fprintf(stderr,"decoded packet data incomplete!\n");
  108669. exit(1);
  108670. }
  108671. if(!eosflag){
  108672. fprintf(stderr,"Never got a packet with EOS set!\n");
  108673. exit(1);
  108674. }
  108675. fprintf(stderr,"ok.\n");
  108676. }
  108677. int main(void){
  108678. ogg_stream_init(&os_en,0x04030201);
  108679. ogg_stream_init(&os_de,0x04030201);
  108680. ogg_sync_init(&oy);
  108681. /* Exercise each code path in the framing code. Also verify that
  108682. the checksums are working. */
  108683. {
  108684. /* 17 only */
  108685. const int packets[]={17, -1};
  108686. const int *headret[]={head1_0,NULL};
  108687. fprintf(stderr,"testing single page encoding... ");
  108688. test_pack(packets,headret,0,0,0);
  108689. }
  108690. {
  108691. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  108692. const int packets[]={17, 254, 255, 256, 500, 510, 600, -1};
  108693. const int *headret[]={head1_1,head2_1,NULL};
  108694. fprintf(stderr,"testing basic page encoding... ");
  108695. test_pack(packets,headret,0,0,0);
  108696. }
  108697. {
  108698. /* nil packets; beginning,middle,end */
  108699. const int packets[]={0,17, 254, 255, 0, 256, 0, 500, 510, 600, 0, -1};
  108700. const int *headret[]={head1_2,head2_2,NULL};
  108701. fprintf(stderr,"testing basic nil packets... ");
  108702. test_pack(packets,headret,0,0,0);
  108703. }
  108704. {
  108705. /* large initial packet */
  108706. const int packets[]={4345,259,255,-1};
  108707. const int *headret[]={head1_3,head2_3,NULL};
  108708. fprintf(stderr,"testing initial-packet lacing > 4k... ");
  108709. test_pack(packets,headret,0,0,0);
  108710. }
  108711. {
  108712. /* continuing packet test */
  108713. const int packets[]={0,4345,259,255,-1};
  108714. const int *headret[]={head1_4,head2_4,head3_4,NULL};
  108715. fprintf(stderr,"testing single packet page span... ");
  108716. test_pack(packets,headret,0,0,0);
  108717. }
  108718. /* page with the 255 segment limit */
  108719. {
  108720. const int packets[]={0,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,10,
  108749. 10,10,10,10,10,10,10,10,
  108750. 10,10,10,10,10,10,10,10,
  108751. 10,10,10,10,10,10,10,50,-1};
  108752. const int *headret[]={head1_5,head2_5,head3_5,NULL};
  108753. fprintf(stderr,"testing max packet segments... ");
  108754. test_pack(packets,headret,0,0,0);
  108755. }
  108756. {
  108757. /* packet that overspans over an entire page */
  108758. const int packets[]={0,100,9000,259,255,-1};
  108759. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  108760. fprintf(stderr,"testing very large packets... ");
  108761. test_pack(packets,headret,0,0,0);
  108762. }
  108763. {
  108764. /* test for the libogg 1.1.1 resync in large continuation bug
  108765. found by Josh Coalson) */
  108766. const int packets[]={0,100,9000,259,255,-1};
  108767. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  108768. fprintf(stderr,"testing continuation resync in very large packets... ");
  108769. test_pack(packets,headret,100,2,3);
  108770. }
  108771. {
  108772. /* term only page. why not? */
  108773. const int packets[]={0,100,4080,-1};
  108774. const int *headret[]={head1_7,head2_7,head3_7,NULL};
  108775. fprintf(stderr,"testing zero data page (1 nil packet)... ");
  108776. test_pack(packets,headret,0,0,0);
  108777. }
  108778. {
  108779. /* build a bunch of pages for testing */
  108780. unsigned char *data=_ogg_malloc(1024*1024);
  108781. int pl[]={0,100,4079,2956,2057,76,34,912,0,234,1000,1000,1000,300,-1};
  108782. int inptr=0,i,j;
  108783. ogg_page og[5];
  108784. ogg_stream_reset(&os_en);
  108785. for(i=0;pl[i]!=-1;i++){
  108786. ogg_packet op;
  108787. int len=pl[i];
  108788. op.packet=data+inptr;
  108789. op.bytes=len;
  108790. op.e_o_s=(pl[i+1]<0?1:0);
  108791. op.granulepos=(i+1)*1000;
  108792. for(j=0;j<len;j++)data[inptr++]=i+j;
  108793. ogg_stream_packetin(&os_en,&op);
  108794. }
  108795. _ogg_free(data);
  108796. /* retrieve finished pages */
  108797. for(i=0;i<5;i++){
  108798. if(ogg_stream_pageout(&os_en,&og[i])==0){
  108799. fprintf(stderr,"Too few pages output building sync tests!\n");
  108800. exit(1);
  108801. }
  108802. copy_page(&og[i]);
  108803. }
  108804. /* Test lost pages on pagein/packetout: no rollback */
  108805. {
  108806. ogg_page temp;
  108807. ogg_packet test;
  108808. fprintf(stderr,"Testing loss of pages... ");
  108809. ogg_sync_reset(&oy);
  108810. ogg_stream_reset(&os_de);
  108811. for(i=0;i<5;i++){
  108812. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  108813. og[i].header_len);
  108814. ogg_sync_wrote(&oy,og[i].header_len);
  108815. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  108816. ogg_sync_wrote(&oy,og[i].body_len);
  108817. }
  108818. ogg_sync_pageout(&oy,&temp);
  108819. ogg_stream_pagein(&os_de,&temp);
  108820. ogg_sync_pageout(&oy,&temp);
  108821. ogg_stream_pagein(&os_de,&temp);
  108822. ogg_sync_pageout(&oy,&temp);
  108823. /* skip */
  108824. ogg_sync_pageout(&oy,&temp);
  108825. ogg_stream_pagein(&os_de,&temp);
  108826. /* do we get the expected results/packets? */
  108827. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  108828. checkpacket(&test,0,0,0);
  108829. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  108830. checkpacket(&test,100,1,-1);
  108831. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  108832. checkpacket(&test,4079,2,3000);
  108833. if(ogg_stream_packetout(&os_de,&test)!=-1){
  108834. fprintf(stderr,"Error: loss of page did not return error\n");
  108835. exit(1);
  108836. }
  108837. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  108838. checkpacket(&test,76,5,-1);
  108839. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  108840. checkpacket(&test,34,6,-1);
  108841. fprintf(stderr,"ok.\n");
  108842. }
  108843. /* Test lost pages on pagein/packetout: rollback with continuation */
  108844. {
  108845. ogg_page temp;
  108846. ogg_packet test;
  108847. fprintf(stderr,"Testing loss of pages (rollback required)... ");
  108848. ogg_sync_reset(&oy);
  108849. ogg_stream_reset(&os_de);
  108850. for(i=0;i<5;i++){
  108851. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  108852. og[i].header_len);
  108853. ogg_sync_wrote(&oy,og[i].header_len);
  108854. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  108855. ogg_sync_wrote(&oy,og[i].body_len);
  108856. }
  108857. ogg_sync_pageout(&oy,&temp);
  108858. ogg_stream_pagein(&os_de,&temp);
  108859. ogg_sync_pageout(&oy,&temp);
  108860. ogg_stream_pagein(&os_de,&temp);
  108861. ogg_sync_pageout(&oy,&temp);
  108862. ogg_stream_pagein(&os_de,&temp);
  108863. ogg_sync_pageout(&oy,&temp);
  108864. /* skip */
  108865. ogg_sync_pageout(&oy,&temp);
  108866. ogg_stream_pagein(&os_de,&temp);
  108867. /* do we get the expected results/packets? */
  108868. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  108869. checkpacket(&test,0,0,0);
  108870. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  108871. checkpacket(&test,100,1,-1);
  108872. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  108873. checkpacket(&test,4079,2,3000);
  108874. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  108875. checkpacket(&test,2956,3,4000);
  108876. if(ogg_stream_packetout(&os_de,&test)!=-1){
  108877. fprintf(stderr,"Error: loss of page did not return error\n");
  108878. exit(1);
  108879. }
  108880. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  108881. checkpacket(&test,300,13,14000);
  108882. fprintf(stderr,"ok.\n");
  108883. }
  108884. /* the rest only test sync */
  108885. {
  108886. ogg_page og_de;
  108887. /* Test fractional page inputs: incomplete capture */
  108888. fprintf(stderr,"Testing sync on partial inputs... ");
  108889. ogg_sync_reset(&oy);
  108890. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  108891. 3);
  108892. ogg_sync_wrote(&oy,3);
  108893. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  108894. /* Test fractional page inputs: incomplete fixed header */
  108895. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+3,
  108896. 20);
  108897. ogg_sync_wrote(&oy,20);
  108898. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  108899. /* Test fractional page inputs: incomplete header */
  108900. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+23,
  108901. 5);
  108902. ogg_sync_wrote(&oy,5);
  108903. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  108904. /* Test fractional page inputs: incomplete body */
  108905. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+28,
  108906. og[1].header_len-28);
  108907. ogg_sync_wrote(&oy,og[1].header_len-28);
  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. ogg_sync_wrote(&oy,1000);
  108911. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  108912. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body+1000,
  108913. og[1].body_len-1000);
  108914. ogg_sync_wrote(&oy,og[1].body_len-1000);
  108915. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  108916. fprintf(stderr,"ok.\n");
  108917. }
  108918. /* Test fractional page inputs: page + incomplete capture */
  108919. {
  108920. ogg_page og_de;
  108921. fprintf(stderr,"Testing sync on 1+partial inputs... ");
  108922. ogg_sync_reset(&oy);
  108923. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  108924. og[1].header_len);
  108925. ogg_sync_wrote(&oy,og[1].header_len);
  108926. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  108927. og[1].body_len);
  108928. ogg_sync_wrote(&oy,og[1].body_len);
  108929. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  108930. 20);
  108931. ogg_sync_wrote(&oy,20);
  108932. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  108933. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  108934. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+20,
  108935. og[1].header_len-20);
  108936. ogg_sync_wrote(&oy,og[1].header_len-20);
  108937. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  108938. og[1].body_len);
  108939. ogg_sync_wrote(&oy,og[1].body_len);
  108940. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  108941. fprintf(stderr,"ok.\n");
  108942. }
  108943. /* Test recapture: garbage + page */
  108944. {
  108945. ogg_page og_de;
  108946. fprintf(stderr,"Testing search for capture... ");
  108947. ogg_sync_reset(&oy);
  108948. /* 'garbage' */
  108949. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  108950. og[1].body_len);
  108951. ogg_sync_wrote(&oy,og[1].body_len);
  108952. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  108953. og[1].header_len);
  108954. ogg_sync_wrote(&oy,og[1].header_len);
  108955. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  108956. og[1].body_len);
  108957. ogg_sync_wrote(&oy,og[1].body_len);
  108958. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  108959. 20);
  108960. ogg_sync_wrote(&oy,20);
  108961. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  108962. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  108963. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  108964. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header+20,
  108965. og[2].header_len-20);
  108966. ogg_sync_wrote(&oy,og[2].header_len-20);
  108967. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  108968. og[2].body_len);
  108969. ogg_sync_wrote(&oy,og[2].body_len);
  108970. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  108971. fprintf(stderr,"ok.\n");
  108972. }
  108973. /* Test recapture: page + garbage + page */
  108974. {
  108975. ogg_page og_de;
  108976. fprintf(stderr,"Testing recapture... ");
  108977. ogg_sync_reset(&oy);
  108978. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  108979. og[1].header_len);
  108980. ogg_sync_wrote(&oy,og[1].header_len);
  108981. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  108982. og[1].body_len);
  108983. ogg_sync_wrote(&oy,og[1].body_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. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  108988. og[2].header_len);
  108989. ogg_sync_wrote(&oy,og[2].header_len);
  108990. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  108991. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  108992. og[2].body_len-5);
  108993. ogg_sync_wrote(&oy,og[2].body_len-5);
  108994. memcpy(ogg_sync_buffer(&oy,og[3].header_len),og[3].header,
  108995. og[3].header_len);
  108996. ogg_sync_wrote(&oy,og[3].header_len);
  108997. memcpy(ogg_sync_buffer(&oy,og[3].body_len),og[3].body,
  108998. og[3].body_len);
  108999. ogg_sync_wrote(&oy,og[3].body_len);
  109000. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109001. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109002. fprintf(stderr,"ok.\n");
  109003. }
  109004. /* Free page data that was previously copied */
  109005. {
  109006. for(i=0;i<5;i++){
  109007. free_page(&og[i]);
  109008. }
  109009. }
  109010. }
  109011. return(0);
  109012. }
  109013. #endif
  109014. #endif
  109015. /*** End of inlined file: framing.c ***/
  109016. /*** Start of inlined file: analysis.c ***/
  109017. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  109018. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109019. // tasks..
  109020. #if JUCE_MSVC
  109021. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109022. #endif
  109023. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  109024. #if JUCE_USE_OGGVORBIS
  109025. #include <stdio.h>
  109026. #include <string.h>
  109027. #include <math.h>
  109028. /*** Start of inlined file: codec_internal.h ***/
  109029. #ifndef _V_CODECI_H_
  109030. #define _V_CODECI_H_
  109031. /*** Start of inlined file: envelope.h ***/
  109032. #ifndef _V_ENVELOPE_
  109033. #define _V_ENVELOPE_
  109034. /*** Start of inlined file: mdct.h ***/
  109035. #ifndef _OGG_mdct_H_
  109036. #define _OGG_mdct_H_
  109037. /*#define MDCT_INTEGERIZED <- be warned there could be some hurt left here*/
  109038. #ifdef MDCT_INTEGERIZED
  109039. #define DATA_TYPE int
  109040. #define REG_TYPE register int
  109041. #define TRIGBITS 14
  109042. #define cPI3_8 6270
  109043. #define cPI2_8 11585
  109044. #define cPI1_8 15137
  109045. #define FLOAT_CONV(x) ((int)((x)*(1<<TRIGBITS)+.5))
  109046. #define MULT_NORM(x) ((x)>>TRIGBITS)
  109047. #define HALVE(x) ((x)>>1)
  109048. #else
  109049. #define DATA_TYPE float
  109050. #define REG_TYPE float
  109051. #define cPI3_8 .38268343236508977175F
  109052. #define cPI2_8 .70710678118654752441F
  109053. #define cPI1_8 .92387953251128675613F
  109054. #define FLOAT_CONV(x) (x)
  109055. #define MULT_NORM(x) (x)
  109056. #define HALVE(x) ((x)*.5f)
  109057. #endif
  109058. typedef struct {
  109059. int n;
  109060. int log2n;
  109061. DATA_TYPE *trig;
  109062. int *bitrev;
  109063. DATA_TYPE scale;
  109064. } mdct_lookup;
  109065. extern void mdct_init(mdct_lookup *lookup,int n);
  109066. extern void mdct_clear(mdct_lookup *l);
  109067. extern void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  109068. extern void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  109069. #endif
  109070. /*** End of inlined file: mdct.h ***/
  109071. #define VE_PRE 16
  109072. #define VE_WIN 4
  109073. #define VE_POST 2
  109074. #define VE_AMP (VE_PRE+VE_POST-1)
  109075. #define VE_BANDS 7
  109076. #define VE_NEARDC 15
  109077. #define VE_MINSTRETCH 2 /* a bit less than short block */
  109078. #define VE_MAXSTRETCH 12 /* one-third full block */
  109079. typedef struct {
  109080. float ampbuf[VE_AMP];
  109081. int ampptr;
  109082. float nearDC[VE_NEARDC];
  109083. float nearDC_acc;
  109084. float nearDC_partialacc;
  109085. int nearptr;
  109086. } envelope_filter_state;
  109087. typedef struct {
  109088. int begin;
  109089. int end;
  109090. float *window;
  109091. float total;
  109092. } envelope_band;
  109093. typedef struct {
  109094. int ch;
  109095. int winlength;
  109096. int searchstep;
  109097. float minenergy;
  109098. mdct_lookup mdct;
  109099. float *mdct_win;
  109100. envelope_band band[VE_BANDS];
  109101. envelope_filter_state *filter;
  109102. int stretch;
  109103. int *mark;
  109104. long storage;
  109105. long current;
  109106. long curmark;
  109107. long cursor;
  109108. } envelope_lookup;
  109109. extern void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi);
  109110. extern void _ve_envelope_clear(envelope_lookup *e);
  109111. extern long _ve_envelope_search(vorbis_dsp_state *v);
  109112. extern void _ve_envelope_shift(envelope_lookup *e,long shift);
  109113. extern int _ve_envelope_mark(vorbis_dsp_state *v);
  109114. #endif
  109115. /*** End of inlined file: envelope.h ***/
  109116. /*** Start of inlined file: codebook.h ***/
  109117. #ifndef _V_CODEBOOK_H_
  109118. #define _V_CODEBOOK_H_
  109119. /* This structure encapsulates huffman and VQ style encoding books; it
  109120. doesn't do anything specific to either.
  109121. valuelist/quantlist are nonNULL (and q_* significant) only if
  109122. there's entry->value mapping to be done.
  109123. If encode-side mapping must be done (and thus the entry needs to be
  109124. hunted), the auxiliary encode pointer will point to a decision
  109125. tree. This is true of both VQ and huffman, but is mostly useful
  109126. with VQ.
  109127. */
  109128. typedef struct static_codebook{
  109129. long dim; /* codebook dimensions (elements per vector) */
  109130. long entries; /* codebook entries */
  109131. long *lengthlist; /* codeword lengths in bits */
  109132. /* mapping ***************************************************************/
  109133. int maptype; /* 0=none
  109134. 1=implicitly populated values from map column
  109135. 2=listed arbitrary values */
  109136. /* The below does a linear, single monotonic sequence mapping. */
  109137. long q_min; /* packed 32 bit float; quant value 0 maps to minval */
  109138. long q_delta; /* packed 32 bit float; val 1 - val 0 == delta */
  109139. int q_quant; /* bits: 0 < quant <= 16 */
  109140. int q_sequencep; /* bitflag */
  109141. long *quantlist; /* map == 1: (int)(entries^(1/dim)) element column map
  109142. map == 2: list of dim*entries quantized entry vals
  109143. */
  109144. /* encode helpers ********************************************************/
  109145. struct encode_aux_nearestmatch *nearest_tree;
  109146. struct encode_aux_threshmatch *thresh_tree;
  109147. struct encode_aux_pigeonhole *pigeon_tree;
  109148. int allocedp;
  109149. } static_codebook;
  109150. /* this structures an arbitrary trained book to quickly find the
  109151. nearest cell match */
  109152. typedef struct encode_aux_nearestmatch{
  109153. /* pre-calculated partitioning tree */
  109154. long *ptr0;
  109155. long *ptr1;
  109156. long *p; /* decision points (each is an entry) */
  109157. long *q; /* decision points (each is an entry) */
  109158. long aux; /* number of tree entries */
  109159. long alloc;
  109160. } encode_aux_nearestmatch;
  109161. /* assumes a maptype of 1; encode side only, so that's OK */
  109162. typedef struct encode_aux_threshmatch{
  109163. float *quantthresh;
  109164. long *quantmap;
  109165. int quantvals;
  109166. int threshvals;
  109167. } encode_aux_threshmatch;
  109168. typedef struct encode_aux_pigeonhole{
  109169. float min;
  109170. float del;
  109171. int mapentries;
  109172. int quantvals;
  109173. long *pigeonmap;
  109174. long fittotal;
  109175. long *fitlist;
  109176. long *fitmap;
  109177. long *fitlength;
  109178. } encode_aux_pigeonhole;
  109179. typedef struct codebook{
  109180. long dim; /* codebook dimensions (elements per vector) */
  109181. long entries; /* codebook entries */
  109182. long used_entries; /* populated codebook entries */
  109183. const static_codebook *c;
  109184. /* for encode, the below are entry-ordered, fully populated */
  109185. /* for decode, the below are ordered by bitreversed codeword and only
  109186. used entries are populated */
  109187. float *valuelist; /* list of dim*entries actual entry values */
  109188. ogg_uint32_t *codelist; /* list of bitstream codewords for each entry */
  109189. int *dec_index; /* only used if sparseness collapsed */
  109190. char *dec_codelengths;
  109191. ogg_uint32_t *dec_firsttable;
  109192. int dec_firsttablen;
  109193. int dec_maxlength;
  109194. } codebook;
  109195. extern void vorbis_staticbook_clear(static_codebook *b);
  109196. extern void vorbis_staticbook_destroy(static_codebook *b);
  109197. extern int vorbis_book_init_encode(codebook *dest,const static_codebook *source);
  109198. extern int vorbis_book_init_decode(codebook *dest,const static_codebook *source);
  109199. extern void vorbis_book_clear(codebook *b);
  109200. extern float *_book_unquantize(const static_codebook *b,int n,int *map);
  109201. extern float *_book_logdist(const static_codebook *b,float *vals);
  109202. extern float _float32_unpack(long val);
  109203. extern long _float32_pack(float val);
  109204. extern int _best(codebook *book, float *a, int step);
  109205. extern int _ilog(unsigned int v);
  109206. extern long _book_maptype1_quantvals(const static_codebook *b);
  109207. extern int vorbis_book_besterror(codebook *book,float *a,int step,int addmul);
  109208. extern long vorbis_book_codeword(codebook *book,int entry);
  109209. extern long vorbis_book_codelen(codebook *book,int entry);
  109210. extern int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *b);
  109211. extern int vorbis_staticbook_unpack(oggpack_buffer *b,static_codebook *c);
  109212. extern int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b);
  109213. extern int vorbis_book_errorv(codebook *book, float *a);
  109214. extern int vorbis_book_encodev(codebook *book, int best,float *a,
  109215. oggpack_buffer *b);
  109216. extern long vorbis_book_decode(codebook *book, oggpack_buffer *b);
  109217. extern long vorbis_book_decodevs_add(codebook *book, float *a,
  109218. oggpack_buffer *b,int n);
  109219. extern long vorbis_book_decodev_set(codebook *book, float *a,
  109220. oggpack_buffer *b,int n);
  109221. extern long vorbis_book_decodev_add(codebook *book, float *a,
  109222. oggpack_buffer *b,int n);
  109223. extern long vorbis_book_decodevv_add(codebook *book, float **a,
  109224. long off,int ch,
  109225. oggpack_buffer *b,int n);
  109226. #endif
  109227. /*** End of inlined file: codebook.h ***/
  109228. #define BLOCKTYPE_IMPULSE 0
  109229. #define BLOCKTYPE_PADDING 1
  109230. #define BLOCKTYPE_TRANSITION 0
  109231. #define BLOCKTYPE_LONG 1
  109232. #define PACKETBLOBS 15
  109233. typedef struct vorbis_block_internal{
  109234. float **pcmdelay; /* this is a pointer into local storage */
  109235. float ampmax;
  109236. int blocktype;
  109237. oggpack_buffer *packetblob[PACKETBLOBS]; /* initialized, must be freed;
  109238. blob [PACKETBLOBS/2] points to
  109239. the oggpack_buffer in the
  109240. main vorbis_block */
  109241. } vorbis_block_internal;
  109242. typedef void vorbis_look_floor;
  109243. typedef void vorbis_look_residue;
  109244. typedef void vorbis_look_transform;
  109245. /* mode ************************************************************/
  109246. typedef struct {
  109247. int blockflag;
  109248. int windowtype;
  109249. int transformtype;
  109250. int mapping;
  109251. } vorbis_info_mode;
  109252. typedef void vorbis_info_floor;
  109253. typedef void vorbis_info_residue;
  109254. typedef void vorbis_info_mapping;
  109255. /*** Start of inlined file: psy.h ***/
  109256. #ifndef _V_PSY_H_
  109257. #define _V_PSY_H_
  109258. /*** Start of inlined file: smallft.h ***/
  109259. #ifndef _V_SMFT_H_
  109260. #define _V_SMFT_H_
  109261. typedef struct {
  109262. int n;
  109263. float *trigcache;
  109264. int *splitcache;
  109265. } drft_lookup;
  109266. extern void drft_forward(drft_lookup *l,float *data);
  109267. extern void drft_backward(drft_lookup *l,float *data);
  109268. extern void drft_init(drft_lookup *l,int n);
  109269. extern void drft_clear(drft_lookup *l);
  109270. #endif
  109271. /*** End of inlined file: smallft.h ***/
  109272. /*** Start of inlined file: backends.h ***/
  109273. /* this is exposed up here because we need it for static modes.
  109274. Lookups for each backend aren't exposed because there's no reason
  109275. to do so */
  109276. #ifndef _vorbis_backend_h_
  109277. #define _vorbis_backend_h_
  109278. /* this would all be simpler/shorter with templates, but.... */
  109279. /* Floor backend generic *****************************************/
  109280. typedef struct{
  109281. void (*pack) (vorbis_info_floor *,oggpack_buffer *);
  109282. vorbis_info_floor *(*unpack)(vorbis_info *,oggpack_buffer *);
  109283. vorbis_look_floor *(*look) (vorbis_dsp_state *,vorbis_info_floor *);
  109284. void (*free_info) (vorbis_info_floor *);
  109285. void (*free_look) (vorbis_look_floor *);
  109286. void *(*inverse1) (struct vorbis_block *,vorbis_look_floor *);
  109287. int (*inverse2) (struct vorbis_block *,vorbis_look_floor *,
  109288. void *buffer,float *);
  109289. } vorbis_func_floor;
  109290. typedef struct{
  109291. int order;
  109292. long rate;
  109293. long barkmap;
  109294. int ampbits;
  109295. int ampdB;
  109296. int numbooks; /* <= 16 */
  109297. int books[16];
  109298. float lessthan; /* encode-only config setting hacks for libvorbis */
  109299. float greaterthan; /* encode-only config setting hacks for libvorbis */
  109300. } vorbis_info_floor0;
  109301. #define VIF_POSIT 63
  109302. #define VIF_CLASS 16
  109303. #define VIF_PARTS 31
  109304. typedef struct{
  109305. int partitions; /* 0 to 31 */
  109306. int partitionclass[VIF_PARTS]; /* 0 to 15 */
  109307. int class_dim[VIF_CLASS]; /* 1 to 8 */
  109308. int class_subs[VIF_CLASS]; /* 0,1,2,3 (bits: 1<<n poss) */
  109309. int class_book[VIF_CLASS]; /* subs ^ dim entries */
  109310. int class_subbook[VIF_CLASS][8]; /* [VIF_CLASS][subs] */
  109311. int mult; /* 1 2 3 or 4 */
  109312. int postlist[VIF_POSIT+2]; /* first two implicit */
  109313. /* encode side analysis parameters */
  109314. float maxover;
  109315. float maxunder;
  109316. float maxerr;
  109317. float twofitweight;
  109318. float twofitatten;
  109319. int n;
  109320. } vorbis_info_floor1;
  109321. /* Residue backend generic *****************************************/
  109322. typedef struct{
  109323. void (*pack) (vorbis_info_residue *,oggpack_buffer *);
  109324. vorbis_info_residue *(*unpack)(vorbis_info *,oggpack_buffer *);
  109325. vorbis_look_residue *(*look) (vorbis_dsp_state *,
  109326. vorbis_info_residue *);
  109327. void (*free_info) (vorbis_info_residue *);
  109328. void (*free_look) (vorbis_look_residue *);
  109329. long **(*classx) (struct vorbis_block *,vorbis_look_residue *,
  109330. float **,int *,int);
  109331. int (*forward) (oggpack_buffer *,struct vorbis_block *,
  109332. vorbis_look_residue *,
  109333. float **,float **,int *,int,long **);
  109334. int (*inverse) (struct vorbis_block *,vorbis_look_residue *,
  109335. float **,int *,int);
  109336. } vorbis_func_residue;
  109337. typedef struct vorbis_info_residue0{
  109338. /* block-partitioned VQ coded straight residue */
  109339. long begin;
  109340. long end;
  109341. /* first stage (lossless partitioning) */
  109342. int grouping; /* group n vectors per partition */
  109343. int partitions; /* possible codebooks for a partition */
  109344. int groupbook; /* huffbook for partitioning */
  109345. int secondstages[64]; /* expanded out to pointers in lookup */
  109346. int booklist[256]; /* list of second stage books */
  109347. float classmetric1[64];
  109348. float classmetric2[64];
  109349. } vorbis_info_residue0;
  109350. /* Mapping backend generic *****************************************/
  109351. typedef struct{
  109352. void (*pack) (vorbis_info *,vorbis_info_mapping *,
  109353. oggpack_buffer *);
  109354. vorbis_info_mapping *(*unpack)(vorbis_info *,oggpack_buffer *);
  109355. void (*free_info) (vorbis_info_mapping *);
  109356. int (*forward) (struct vorbis_block *vb);
  109357. int (*inverse) (struct vorbis_block *vb,vorbis_info_mapping *);
  109358. } vorbis_func_mapping;
  109359. typedef struct vorbis_info_mapping0{
  109360. int submaps; /* <= 16 */
  109361. int chmuxlist[256]; /* up to 256 channels in a Vorbis stream */
  109362. int floorsubmap[16]; /* [mux] submap to floors */
  109363. int residuesubmap[16]; /* [mux] submap to residue */
  109364. int coupling_steps;
  109365. int coupling_mag[256];
  109366. int coupling_ang[256];
  109367. } vorbis_info_mapping0;
  109368. #endif
  109369. /*** End of inlined file: backends.h ***/
  109370. #ifndef EHMER_MAX
  109371. #define EHMER_MAX 56
  109372. #endif
  109373. /* psychoacoustic setup ********************************************/
  109374. #define P_BANDS 17 /* 62Hz to 16kHz */
  109375. #define P_LEVELS 8 /* 30dB to 100dB */
  109376. #define P_LEVEL_0 30. /* 30 dB */
  109377. #define P_NOISECURVES 3
  109378. #define NOISE_COMPAND_LEVELS 40
  109379. typedef struct vorbis_info_psy{
  109380. int blockflag;
  109381. float ath_adjatt;
  109382. float ath_maxatt;
  109383. float tone_masteratt[P_NOISECURVES];
  109384. float tone_centerboost;
  109385. float tone_decay;
  109386. float tone_abs_limit;
  109387. float toneatt[P_BANDS];
  109388. int noisemaskp;
  109389. float noisemaxsupp;
  109390. float noisewindowlo;
  109391. float noisewindowhi;
  109392. int noisewindowlomin;
  109393. int noisewindowhimin;
  109394. int noisewindowfixed;
  109395. float noiseoff[P_NOISECURVES][P_BANDS];
  109396. float noisecompand[NOISE_COMPAND_LEVELS];
  109397. float max_curve_dB;
  109398. int normal_channel_p;
  109399. int normal_point_p;
  109400. int normal_start;
  109401. int normal_partition;
  109402. double normal_thresh;
  109403. } vorbis_info_psy;
  109404. typedef struct{
  109405. int eighth_octave_lines;
  109406. /* for block long/short tuning; encode only */
  109407. float preecho_thresh[VE_BANDS];
  109408. float postecho_thresh[VE_BANDS];
  109409. float stretch_penalty;
  109410. float preecho_minenergy;
  109411. float ampmax_att_per_sec;
  109412. /* channel coupling config */
  109413. int coupling_pkHz[PACKETBLOBS];
  109414. int coupling_pointlimit[2][PACKETBLOBS];
  109415. int coupling_prepointamp[PACKETBLOBS];
  109416. int coupling_postpointamp[PACKETBLOBS];
  109417. int sliding_lowpass[2][PACKETBLOBS];
  109418. } vorbis_info_psy_global;
  109419. typedef struct {
  109420. float ampmax;
  109421. int channels;
  109422. vorbis_info_psy_global *gi;
  109423. int coupling_pointlimit[2][P_NOISECURVES];
  109424. } vorbis_look_psy_global;
  109425. typedef struct {
  109426. int n;
  109427. struct vorbis_info_psy *vi;
  109428. float ***tonecurves;
  109429. float **noiseoffset;
  109430. float *ath;
  109431. long *octave; /* in n.ocshift format */
  109432. long *bark;
  109433. long firstoc;
  109434. long shiftoc;
  109435. int eighth_octave_lines; /* power of two, please */
  109436. int total_octave_lines;
  109437. long rate; /* cache it */
  109438. float m_val; /* Masking compensation value */
  109439. } vorbis_look_psy;
  109440. extern void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  109441. vorbis_info_psy_global *gi,int n,long rate);
  109442. extern void _vp_psy_clear(vorbis_look_psy *p);
  109443. extern void *_vi_psy_dup(void *source);
  109444. extern void _vi_psy_free(vorbis_info_psy *i);
  109445. extern vorbis_info_psy *_vi_psy_copy(vorbis_info_psy *i);
  109446. extern void _vp_remove_floor(vorbis_look_psy *p,
  109447. float *mdct,
  109448. int *icodedflr,
  109449. float *residue,
  109450. int sliding_lowpass);
  109451. extern void _vp_noisemask(vorbis_look_psy *p,
  109452. float *logmdct,
  109453. float *logmask);
  109454. extern void _vp_tonemask(vorbis_look_psy *p,
  109455. float *logfft,
  109456. float *logmask,
  109457. float global_specmax,
  109458. float local_specmax);
  109459. extern void _vp_offset_and_mix(vorbis_look_psy *p,
  109460. float *noise,
  109461. float *tone,
  109462. int offset_select,
  109463. float *logmask,
  109464. float *mdct,
  109465. float *logmdct);
  109466. extern float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd);
  109467. extern float **_vp_quantize_couple_memo(vorbis_block *vb,
  109468. vorbis_info_psy_global *g,
  109469. vorbis_look_psy *p,
  109470. vorbis_info_mapping0 *vi,
  109471. float **mdct);
  109472. extern void _vp_couple(int blobno,
  109473. vorbis_info_psy_global *g,
  109474. vorbis_look_psy *p,
  109475. vorbis_info_mapping0 *vi,
  109476. float **res,
  109477. float **mag_memo,
  109478. int **mag_sort,
  109479. int **ifloor,
  109480. int *nonzero,
  109481. int sliding_lowpass);
  109482. extern void _vp_noise_normalize(vorbis_look_psy *p,
  109483. float *in,float *out,int *sortedindex);
  109484. extern void _vp_noise_normalize_sort(vorbis_look_psy *p,
  109485. float *magnitudes,int *sortedindex);
  109486. extern int **_vp_quantize_couple_sort(vorbis_block *vb,
  109487. vorbis_look_psy *p,
  109488. vorbis_info_mapping0 *vi,
  109489. float **mags);
  109490. extern void hf_reduction(vorbis_info_psy_global *g,
  109491. vorbis_look_psy *p,
  109492. vorbis_info_mapping0 *vi,
  109493. float **mdct);
  109494. #endif
  109495. /*** End of inlined file: psy.h ***/
  109496. /*** Start of inlined file: bitrate.h ***/
  109497. #ifndef _V_BITRATE_H_
  109498. #define _V_BITRATE_H_
  109499. /*** Start of inlined file: os.h ***/
  109500. #ifndef _OS_H
  109501. #define _OS_H
  109502. /********************************************************************
  109503. * *
  109504. * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
  109505. * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
  109506. * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
  109507. * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
  109508. * *
  109509. * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2002 *
  109510. * by the XIPHOPHORUS Company http://www.xiph.org/ *
  109511. * *
  109512. ********************************************************************
  109513. function: #ifdef jail to whip a few platforms into the UNIX ideal.
  109514. last mod: $Id: os.h,v 1.1 2007/06/07 17:49:18 jules_rms Exp $
  109515. ********************************************************************/
  109516. #ifdef HAVE_CONFIG_H
  109517. #include "config.h"
  109518. #endif
  109519. #include <math.h>
  109520. /*** Start of inlined file: misc.h ***/
  109521. #ifndef _V_RANDOM_H_
  109522. #define _V_RANDOM_H_
  109523. extern int analysis_noisy;
  109524. extern void *_vorbis_block_alloc(vorbis_block *vb,long bytes);
  109525. extern void _vorbis_block_ripcord(vorbis_block *vb);
  109526. extern void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  109527. ogg_int64_t off);
  109528. #ifdef DEBUG_MALLOC
  109529. #define _VDBG_GRAPHFILE "malloc.m"
  109530. extern void *_VDBG_malloc(void *ptr,long bytes,char *file,long line);
  109531. extern void _VDBG_free(void *ptr,char *file,long line);
  109532. #ifndef MISC_C
  109533. #undef _ogg_malloc
  109534. #undef _ogg_calloc
  109535. #undef _ogg_realloc
  109536. #undef _ogg_free
  109537. #define _ogg_malloc(x) _VDBG_malloc(NULL,(x),__FILE__,__LINE__)
  109538. #define _ogg_calloc(x,y) _VDBG_malloc(NULL,(x)*(y),__FILE__,__LINE__)
  109539. #define _ogg_realloc(x,y) _VDBG_malloc((x),(y),__FILE__,__LINE__)
  109540. #define _ogg_free(x) _VDBG_free((x),__FILE__,__LINE__)
  109541. #endif
  109542. #endif
  109543. #endif
  109544. /*** End of inlined file: misc.h ***/
  109545. #ifndef _V_IFDEFJAIL_H_
  109546. # define _V_IFDEFJAIL_H_
  109547. # ifdef __GNUC__
  109548. # define STIN static __inline__
  109549. # elif _WIN32
  109550. # define STIN static __inline
  109551. # else
  109552. # define STIN static
  109553. # endif
  109554. #ifdef DJGPP
  109555. # define rint(x) (floor((x)+0.5f))
  109556. #endif
  109557. #ifndef M_PI
  109558. # define M_PI (3.1415926536f)
  109559. #endif
  109560. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  109561. # include <malloc.h>
  109562. # define rint(x) (floor((x)+0.5f))
  109563. # define NO_FLOAT_MATH_LIB
  109564. # define FAST_HYPOT(a, b) sqrt((a)*(a) + (b)*(b))
  109565. #endif
  109566. #if defined(__SYMBIAN32__) && defined(__WINS__)
  109567. void *_alloca(size_t size);
  109568. # define alloca _alloca
  109569. #endif
  109570. #ifndef FAST_HYPOT
  109571. # define FAST_HYPOT hypot
  109572. #endif
  109573. #endif
  109574. #ifdef HAVE_ALLOCA_H
  109575. # include <alloca.h>
  109576. #endif
  109577. #ifdef USE_MEMORY_H
  109578. # include <memory.h>
  109579. #endif
  109580. #ifndef min
  109581. # define min(x,y) ((x)>(y)?(y):(x))
  109582. #endif
  109583. #ifndef max
  109584. # define max(x,y) ((x)<(y)?(y):(x))
  109585. #endif
  109586. #if defined(__i386__) && defined(__GNUC__) && !defined(__BEOS__)
  109587. # define VORBIS_FPU_CONTROL
  109588. /* both GCC and MSVC are kinda stupid about rounding/casting to int.
  109589. Because of encapsulation constraints (GCC can't see inside the asm
  109590. block and so we end up doing stupid things like a store/load that
  109591. is collectively a noop), we do it this way */
  109592. /* we must set up the fpu before this works!! */
  109593. typedef ogg_int16_t vorbis_fpu_control;
  109594. static inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  109595. ogg_int16_t ret;
  109596. ogg_int16_t temp;
  109597. __asm__ __volatile__("fnstcw %0\n\t"
  109598. "movw %0,%%dx\n\t"
  109599. "orw $62463,%%dx\n\t"
  109600. "movw %%dx,%1\n\t"
  109601. "fldcw %1\n\t":"=m"(ret):"m"(temp): "dx");
  109602. *fpu=ret;
  109603. }
  109604. static inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  109605. __asm__ __volatile__("fldcw %0":: "m"(fpu));
  109606. }
  109607. /* assumes the FPU is in round mode! */
  109608. static inline int vorbis_ftoi(double f){ /* yes, double! Otherwise,
  109609. we get extra fst/fld to
  109610. truncate precision */
  109611. int i;
  109612. __asm__("fistl %0": "=m"(i) : "t"(f));
  109613. return(i);
  109614. }
  109615. #endif
  109616. #if defined(_WIN32) && defined(_X86_) && !defined(__GNUC__) && !defined(__BORLANDC__)
  109617. # define VORBIS_FPU_CONTROL
  109618. typedef ogg_int16_t vorbis_fpu_control;
  109619. static __inline int vorbis_ftoi(double f){
  109620. int i;
  109621. __asm{
  109622. fld f
  109623. fistp i
  109624. }
  109625. return i;
  109626. }
  109627. static __inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  109628. }
  109629. static __inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  109630. }
  109631. #endif
  109632. #ifndef VORBIS_FPU_CONTROL
  109633. typedef int vorbis_fpu_control;
  109634. static int vorbis_ftoi(double f){
  109635. return (int)(f+.5);
  109636. }
  109637. /* We don't have special code for this compiler/arch, so do it the slow way */
  109638. # define vorbis_fpu_setround(vorbis_fpu_control) {}
  109639. # define vorbis_fpu_restore(vorbis_fpu_control) {}
  109640. #endif
  109641. #endif /* _OS_H */
  109642. /*** End of inlined file: os.h ***/
  109643. /* encode side bitrate tracking */
  109644. typedef struct bitrate_manager_state {
  109645. int managed;
  109646. long avg_reservoir;
  109647. long minmax_reservoir;
  109648. long avg_bitsper;
  109649. long min_bitsper;
  109650. long max_bitsper;
  109651. long short_per_long;
  109652. double avgfloat;
  109653. vorbis_block *vb;
  109654. int choice;
  109655. } bitrate_manager_state;
  109656. typedef struct bitrate_manager_info{
  109657. long avg_rate;
  109658. long min_rate;
  109659. long max_rate;
  109660. long reservoir_bits;
  109661. double reservoir_bias;
  109662. double slew_damp;
  109663. } bitrate_manager_info;
  109664. extern void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bs);
  109665. extern void vorbis_bitrate_clear(bitrate_manager_state *bs);
  109666. extern int vorbis_bitrate_managed(vorbis_block *vb);
  109667. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  109668. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd, ogg_packet *op);
  109669. #endif
  109670. /*** End of inlined file: bitrate.h ***/
  109671. static int ilog(unsigned int v){
  109672. int ret=0;
  109673. while(v){
  109674. ret++;
  109675. v>>=1;
  109676. }
  109677. return(ret);
  109678. }
  109679. static int ilog2(unsigned int v){
  109680. int ret=0;
  109681. if(v)--v;
  109682. while(v){
  109683. ret++;
  109684. v>>=1;
  109685. }
  109686. return(ret);
  109687. }
  109688. typedef struct private_state {
  109689. /* local lookup storage */
  109690. envelope_lookup *ve; /* envelope lookup */
  109691. int window[2];
  109692. vorbis_look_transform **transform[2]; /* block, type */
  109693. drft_lookup fft_look[2];
  109694. int modebits;
  109695. vorbis_look_floor **flr;
  109696. vorbis_look_residue **residue;
  109697. vorbis_look_psy *psy;
  109698. vorbis_look_psy_global *psy_g_look;
  109699. /* local storage, only used on the encoding side. This way the
  109700. application does not need to worry about freeing some packets'
  109701. memory and not others'; packet storage is always tracked.
  109702. Cleared next call to a _dsp_ function */
  109703. unsigned char *header;
  109704. unsigned char *header1;
  109705. unsigned char *header2;
  109706. bitrate_manager_state bms;
  109707. ogg_int64_t sample_count;
  109708. } private_state;
  109709. /* codec_setup_info contains all the setup information specific to the
  109710. specific compression/decompression mode in progress (eg,
  109711. psychoacoustic settings, channel setup, options, codebook
  109712. etc).
  109713. *********************************************************************/
  109714. /*** Start of inlined file: highlevel.h ***/
  109715. typedef struct highlevel_byblocktype {
  109716. double tone_mask_setting;
  109717. double tone_peaklimit_setting;
  109718. double noise_bias_setting;
  109719. double noise_compand_setting;
  109720. } highlevel_byblocktype;
  109721. typedef struct highlevel_encode_setup {
  109722. void *setup;
  109723. int set_in_stone;
  109724. double base_setting;
  109725. double long_setting;
  109726. double short_setting;
  109727. double impulse_noisetune;
  109728. int managed;
  109729. long bitrate_min;
  109730. long bitrate_av;
  109731. double bitrate_av_damp;
  109732. long bitrate_max;
  109733. long bitrate_reservoir;
  109734. double bitrate_reservoir_bias;
  109735. int impulse_block_p;
  109736. int noise_normalize_p;
  109737. double stereo_point_setting;
  109738. double lowpass_kHz;
  109739. double ath_floating_dB;
  109740. double ath_absolute_dB;
  109741. double amplitude_track_dBpersec;
  109742. double trigger_setting;
  109743. highlevel_byblocktype block[4]; /* padding, impulse, transition, long */
  109744. } highlevel_encode_setup;
  109745. /*** End of inlined file: highlevel.h ***/
  109746. typedef struct codec_setup_info {
  109747. /* Vorbis supports only short and long blocks, but allows the
  109748. encoder to choose the sizes */
  109749. long blocksizes[2];
  109750. /* modes are the primary means of supporting on-the-fly different
  109751. blocksizes, different channel mappings (LR or M/A),
  109752. different residue backends, etc. Each mode consists of a
  109753. blocksize flag and a mapping (along with the mapping setup */
  109754. int modes;
  109755. int maps;
  109756. int floors;
  109757. int residues;
  109758. int books;
  109759. int psys; /* encode only */
  109760. vorbis_info_mode *mode_param[64];
  109761. int map_type[64];
  109762. vorbis_info_mapping *map_param[64];
  109763. int floor_type[64];
  109764. vorbis_info_floor *floor_param[64];
  109765. int residue_type[64];
  109766. vorbis_info_residue *residue_param[64];
  109767. static_codebook *book_param[256];
  109768. codebook *fullbooks;
  109769. vorbis_info_psy *psy_param[4]; /* encode only */
  109770. vorbis_info_psy_global psy_g_param;
  109771. bitrate_manager_info bi;
  109772. highlevel_encode_setup hi; /* used only by vorbisenc.c. It's a
  109773. highly redundant structure, but
  109774. improves clarity of program flow. */
  109775. int halfrate_flag; /* painless downsample for decode */
  109776. } codec_setup_info;
  109777. extern vorbis_look_psy_global *_vp_global_look(vorbis_info *vi);
  109778. extern void _vp_global_free(vorbis_look_psy_global *look);
  109779. #endif
  109780. /*** End of inlined file: codec_internal.h ***/
  109781. /*** Start of inlined file: registry.h ***/
  109782. #ifndef _V_REG_H_
  109783. #define _V_REG_H_
  109784. #define VI_TRANSFORMB 1
  109785. #define VI_WINDOWB 1
  109786. #define VI_TIMEB 1
  109787. #define VI_FLOORB 2
  109788. #define VI_RESB 3
  109789. #define VI_MAPB 1
  109790. extern vorbis_func_floor *_floor_P[];
  109791. extern vorbis_func_residue *_residue_P[];
  109792. extern vorbis_func_mapping *_mapping_P[];
  109793. #endif
  109794. /*** End of inlined file: registry.h ***/
  109795. /*** Start of inlined file: scales.h ***/
  109796. #ifndef _V_SCALES_H_
  109797. #define _V_SCALES_H_
  109798. #include <math.h>
  109799. /* 20log10(x) */
  109800. #define VORBIS_IEEE_FLOAT32 1
  109801. #ifdef VORBIS_IEEE_FLOAT32
  109802. static float unitnorm(float x){
  109803. union {
  109804. ogg_uint32_t i;
  109805. float f;
  109806. } ix;
  109807. ix.f = x;
  109808. ix.i = (ix.i & 0x80000000U) | (0x3f800000U);
  109809. return ix.f;
  109810. }
  109811. /* Segher was off (too high) by ~ .3 decibel. Center the conversion correctly. */
  109812. static float todB(const float *x){
  109813. union {
  109814. ogg_uint32_t i;
  109815. float f;
  109816. } ix;
  109817. ix.f = *x;
  109818. ix.i = ix.i&0x7fffffff;
  109819. return (float)(ix.i * 7.17711438e-7f -764.6161886f);
  109820. }
  109821. #define todB_nn(x) todB(x)
  109822. #else
  109823. static float unitnorm(float x){
  109824. if(x<0)return(-1.f);
  109825. return(1.f);
  109826. }
  109827. #define todB(x) (*(x)==0?-400.f:log(*(x)**(x))*4.34294480f)
  109828. #define todB_nn(x) (*(x)==0.f?-400.f:log(*(x))*8.6858896f)
  109829. #endif
  109830. #define fromdB(x) (exp((x)*.11512925f))
  109831. /* The bark scale equations are approximations, since the original
  109832. table was somewhat hand rolled. The below are chosen to have the
  109833. best possible fit to the rolled tables, thus their somewhat odd
  109834. appearance (these are more accurate and over a longer range than
  109835. the oft-quoted bark equations found in the texts I have). The
  109836. approximations are valid from 0 - 30kHz (nyquist) or so.
  109837. all f in Hz, z in Bark */
  109838. #define toBARK(n) (13.1f*atan(.00074f*(n))+2.24f*atan((n)*(n)*1.85e-8f)+1e-4f*(n))
  109839. #define fromBARK(z) (102.f*(z)-2.f*pow(z,2.f)+.4f*pow(z,3.f)+pow(1.46f,z)-1.f)
  109840. #define toMEL(n) (log(1.f+(n)*.001f)*1442.695f)
  109841. #define fromMEL(m) (1000.f*exp((m)/1442.695f)-1000.f)
  109842. /* Frequency to octave. We arbitrarily declare 63.5 Hz to be octave
  109843. 0.0 */
  109844. #define toOC(n) (log(n)*1.442695f-5.965784f)
  109845. #define fromOC(o) (exp(((o)+5.965784f)*.693147f))
  109846. #endif
  109847. /*** End of inlined file: scales.h ***/
  109848. int analysis_noisy=1;
  109849. /* decides between modes, dispatches to the appropriate mapping. */
  109850. int vorbis_analysis(vorbis_block *vb, ogg_packet *op){
  109851. int ret,i;
  109852. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  109853. vb->glue_bits=0;
  109854. vb->time_bits=0;
  109855. vb->floor_bits=0;
  109856. vb->res_bits=0;
  109857. /* first things first. Make sure encode is ready */
  109858. for(i=0;i<PACKETBLOBS;i++)
  109859. oggpack_reset(vbi->packetblob[i]);
  109860. /* we only have one mapping type (0), and we let the mapping code
  109861. itself figure out what soft mode to use. This allows easier
  109862. bitrate management */
  109863. if((ret=_mapping_P[0]->forward(vb)))
  109864. return(ret);
  109865. if(op){
  109866. if(vorbis_bitrate_managed(vb))
  109867. /* The app is using a bitmanaged mode... but not using the
  109868. bitrate management interface. */
  109869. return(OV_EINVAL);
  109870. op->packet=oggpack_get_buffer(&vb->opb);
  109871. op->bytes=oggpack_bytes(&vb->opb);
  109872. op->b_o_s=0;
  109873. op->e_o_s=vb->eofflag;
  109874. op->granulepos=vb->granulepos;
  109875. op->packetno=vb->sequence; /* for sake of completeness */
  109876. }
  109877. return(0);
  109878. }
  109879. /* there was no great place to put this.... */
  109880. void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,ogg_int64_t off){
  109881. int j;
  109882. FILE *of;
  109883. char buffer[80];
  109884. /* if(i==5870){*/
  109885. sprintf(buffer,"%s_%d.m",base,i);
  109886. of=fopen(buffer,"w");
  109887. if(!of)perror("failed to open data dump file");
  109888. for(j=0;j<n;j++){
  109889. if(bark){
  109890. float b=toBARK((4000.f*j/n)+.25);
  109891. fprintf(of,"%f ",b);
  109892. }else
  109893. if(off!=0)
  109894. fprintf(of,"%f ",(double)(j+off)/8000.);
  109895. else
  109896. fprintf(of,"%f ",(double)j);
  109897. if(dB){
  109898. float val;
  109899. if(v[j]==0.)
  109900. val=-140.;
  109901. else
  109902. val=todB(v+j);
  109903. fprintf(of,"%f\n",val);
  109904. }else{
  109905. fprintf(of,"%f\n",v[j]);
  109906. }
  109907. }
  109908. fclose(of);
  109909. /* } */
  109910. }
  109911. void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  109912. ogg_int64_t off){
  109913. if(analysis_noisy)_analysis_output_always(base,i,v,n,bark,dB,off);
  109914. }
  109915. #endif
  109916. /*** End of inlined file: analysis.c ***/
  109917. /*** Start of inlined file: bitrate.c ***/
  109918. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  109919. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109920. // tasks..
  109921. #if JUCE_MSVC
  109922. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109923. #endif
  109924. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  109925. #if JUCE_USE_OGGVORBIS
  109926. #include <stdlib.h>
  109927. #include <string.h>
  109928. #include <math.h>
  109929. /* compute bitrate tracking setup */
  109930. void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bm){
  109931. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  109932. bitrate_manager_info *bi=&ci->bi;
  109933. memset(bm,0,sizeof(*bm));
  109934. if(bi && (bi->reservoir_bits>0)){
  109935. long ratesamples=vi->rate;
  109936. int halfsamples=ci->blocksizes[0]>>1;
  109937. bm->short_per_long=ci->blocksizes[1]/ci->blocksizes[0];
  109938. bm->managed=1;
  109939. bm->avg_bitsper= rint(1.*bi->avg_rate*halfsamples/ratesamples);
  109940. bm->min_bitsper= rint(1.*bi->min_rate*halfsamples/ratesamples);
  109941. bm->max_bitsper= rint(1.*bi->max_rate*halfsamples/ratesamples);
  109942. bm->avgfloat=PACKETBLOBS/2;
  109943. /* not a necessary fix, but one that leads to a more balanced
  109944. typical initialization */
  109945. {
  109946. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  109947. bm->minmax_reservoir=desired_fill;
  109948. bm->avg_reservoir=desired_fill;
  109949. }
  109950. }
  109951. }
  109952. void vorbis_bitrate_clear(bitrate_manager_state *bm){
  109953. memset(bm,0,sizeof(*bm));
  109954. return;
  109955. }
  109956. int vorbis_bitrate_managed(vorbis_block *vb){
  109957. vorbis_dsp_state *vd=vb->vd;
  109958. private_state *b=(private_state*)vd->backend_state;
  109959. bitrate_manager_state *bm=&b->bms;
  109960. if(bm && bm->managed)return(1);
  109961. return(0);
  109962. }
  109963. /* finish taking in the block we just processed */
  109964. int vorbis_bitrate_addblock(vorbis_block *vb){
  109965. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  109966. vorbis_dsp_state *vd=vb->vd;
  109967. private_state *b=(private_state*)vd->backend_state;
  109968. bitrate_manager_state *bm=&b->bms;
  109969. vorbis_info *vi=vd->vi;
  109970. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  109971. bitrate_manager_info *bi=&ci->bi;
  109972. int choice=rint(bm->avgfloat);
  109973. long this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  109974. long min_target_bits=(vb->W?bm->min_bitsper*bm->short_per_long:bm->min_bitsper);
  109975. long max_target_bits=(vb->W?bm->max_bitsper*bm->short_per_long:bm->max_bitsper);
  109976. int samples=ci->blocksizes[vb->W]>>1;
  109977. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  109978. if(!bm->managed){
  109979. /* not a bitrate managed stream, but for API simplicity, we'll
  109980. buffer the packet to keep the code path clean */
  109981. if(bm->vb)return(-1); /* one has been submitted without
  109982. being claimed */
  109983. bm->vb=vb;
  109984. return(0);
  109985. }
  109986. bm->vb=vb;
  109987. /* look ahead for avg floater */
  109988. if(bm->avg_bitsper>0){
  109989. double slew=0.;
  109990. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  109991. double slewlimit= 15./bi->slew_damp;
  109992. /* choosing a new floater:
  109993. if we're over target, we slew down
  109994. if we're under target, we slew up
  109995. choose slew as follows: look through packetblobs of this frame
  109996. and set slew as the first in the appropriate direction that
  109997. gives us the slew we want. This may mean no slew if delta is
  109998. already favorable.
  109999. Then limit slew to slew max */
  110000. if(bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  110001. while(choice>0 && this_bits>avg_target_bits &&
  110002. bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  110003. choice--;
  110004. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110005. }
  110006. }else if(bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  110007. while(choice+1<PACKETBLOBS && this_bits<avg_target_bits &&
  110008. bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  110009. choice++;
  110010. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110011. }
  110012. }
  110013. slew=rint(choice-bm->avgfloat)/samples*vi->rate;
  110014. if(slew<-slewlimit)slew=-slewlimit;
  110015. if(slew>slewlimit)slew=slewlimit;
  110016. choice=rint(bm->avgfloat+= slew/vi->rate*samples);
  110017. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110018. }
  110019. /* enforce min(if used) on the current floater (if used) */
  110020. if(bm->min_bitsper>0){
  110021. /* do we need to force the bitrate up? */
  110022. if(this_bits<min_target_bits){
  110023. while(bm->minmax_reservoir-(min_target_bits-this_bits)<0){
  110024. choice++;
  110025. if(choice>=PACKETBLOBS)break;
  110026. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110027. }
  110028. }
  110029. }
  110030. /* enforce max (if used) on the current floater (if used) */
  110031. if(bm->max_bitsper>0){
  110032. /* do we need to force the bitrate down? */
  110033. if(this_bits>max_target_bits){
  110034. while(bm->minmax_reservoir+(this_bits-max_target_bits)>bi->reservoir_bits){
  110035. choice--;
  110036. if(choice<0)break;
  110037. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110038. }
  110039. }
  110040. }
  110041. /* Choice of packetblobs now made based on floater, and min/max
  110042. requirements. Now boundary check extreme choices */
  110043. if(choice<0){
  110044. /* choosing a smaller packetblob is insufficient to trim bitrate.
  110045. frame will need to be truncated */
  110046. long maxsize=(max_target_bits+(bi->reservoir_bits-bm->minmax_reservoir))/8;
  110047. bm->choice=choice=0;
  110048. if(oggpack_bytes(vbi->packetblob[choice])>maxsize){
  110049. oggpack_writetrunc(vbi->packetblob[choice],maxsize*8);
  110050. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110051. }
  110052. }else{
  110053. long minsize=(min_target_bits-bm->minmax_reservoir+7)/8;
  110054. if(choice>=PACKETBLOBS)
  110055. choice=PACKETBLOBS-1;
  110056. bm->choice=choice;
  110057. /* prop up bitrate according to demand. pad this frame out with zeroes */
  110058. minsize-=oggpack_bytes(vbi->packetblob[choice]);
  110059. while(minsize-->0)oggpack_write(vbi->packetblob[choice],0,8);
  110060. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110061. }
  110062. /* now we have the final packet and the final packet size. Update statistics */
  110063. /* min and max reservoir */
  110064. if(bm->min_bitsper>0 || bm->max_bitsper>0){
  110065. if(max_target_bits>0 && this_bits>max_target_bits){
  110066. bm->minmax_reservoir+=(this_bits-max_target_bits);
  110067. }else if(min_target_bits>0 && this_bits<min_target_bits){
  110068. bm->minmax_reservoir+=(this_bits-min_target_bits);
  110069. }else{
  110070. /* inbetween; we want to take reservoir toward but not past desired_fill */
  110071. if(bm->minmax_reservoir>desired_fill){
  110072. if(max_target_bits>0){ /* logical bulletproofing against initialization state */
  110073. bm->minmax_reservoir+=(this_bits-max_target_bits);
  110074. if(bm->minmax_reservoir<desired_fill)bm->minmax_reservoir=desired_fill;
  110075. }else{
  110076. bm->minmax_reservoir=desired_fill;
  110077. }
  110078. }else{
  110079. if(min_target_bits>0){ /* logical bulletproofing against initialization state */
  110080. bm->minmax_reservoir+=(this_bits-min_target_bits);
  110081. if(bm->minmax_reservoir>desired_fill)bm->minmax_reservoir=desired_fill;
  110082. }else{
  110083. bm->minmax_reservoir=desired_fill;
  110084. }
  110085. }
  110086. }
  110087. }
  110088. /* avg reservoir */
  110089. if(bm->avg_bitsper>0){
  110090. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  110091. bm->avg_reservoir+=this_bits-avg_target_bits;
  110092. }
  110093. return(0);
  110094. }
  110095. int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,ogg_packet *op){
  110096. private_state *b=(private_state*)vd->backend_state;
  110097. bitrate_manager_state *bm=&b->bms;
  110098. vorbis_block *vb=bm->vb;
  110099. int choice=PACKETBLOBS/2;
  110100. if(!vb)return 0;
  110101. if(op){
  110102. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  110103. if(vorbis_bitrate_managed(vb))
  110104. choice=bm->choice;
  110105. op->packet=oggpack_get_buffer(vbi->packetblob[choice]);
  110106. op->bytes=oggpack_bytes(vbi->packetblob[choice]);
  110107. op->b_o_s=0;
  110108. op->e_o_s=vb->eofflag;
  110109. op->granulepos=vb->granulepos;
  110110. op->packetno=vb->sequence; /* for sake of completeness */
  110111. }
  110112. bm->vb=0;
  110113. return(1);
  110114. }
  110115. #endif
  110116. /*** End of inlined file: bitrate.c ***/
  110117. /*** Start of inlined file: block.c ***/
  110118. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110119. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110120. // tasks..
  110121. #if JUCE_MSVC
  110122. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110123. #endif
  110124. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110125. #if JUCE_USE_OGGVORBIS
  110126. #include <stdio.h>
  110127. #include <stdlib.h>
  110128. #include <string.h>
  110129. /*** Start of inlined file: window.h ***/
  110130. #ifndef _V_WINDOW_
  110131. #define _V_WINDOW_
  110132. extern float *_vorbis_window_get(int n);
  110133. extern void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  110134. int lW,int W,int nW);
  110135. #endif
  110136. /*** End of inlined file: window.h ***/
  110137. /*** Start of inlined file: lpc.h ***/
  110138. #ifndef _V_LPC_H_
  110139. #define _V_LPC_H_
  110140. /* simple linear scale LPC code */
  110141. extern float vorbis_lpc_from_data(float *data,float *lpc,int n,int m);
  110142. extern void vorbis_lpc_predict(float *coeff,float *prime,int m,
  110143. float *data,long n);
  110144. #endif
  110145. /*** End of inlined file: lpc.h ***/
  110146. /* pcm accumulator examples (not exhaustive):
  110147. <-------------- lW ---------------->
  110148. <--------------- W ---------------->
  110149. : .....|..... _______________ |
  110150. : .''' | '''_--- | |\ |
  110151. :.....''' |_____--- '''......| | \_______|
  110152. :.................|__________________|_______|__|______|
  110153. |<------ Sl ------>| > Sr < |endW
  110154. |beginSl |endSl | |endSr
  110155. |beginW |endlW |beginSr
  110156. |< lW >|
  110157. <--------------- W ---------------->
  110158. | | .. ______________ |
  110159. | | ' `/ | ---_ |
  110160. |___.'___/`. | ---_____|
  110161. |_______|__|_______|_________________|
  110162. | >|Sl|< |<------ Sr ----->|endW
  110163. | | |endSl |beginSr |endSr
  110164. |beginW | |endlW
  110165. mult[0] |beginSl mult[n]
  110166. <-------------- lW ----------------->
  110167. |<--W-->|
  110168. : .............. ___ | |
  110169. : .''' |`/ \ | |
  110170. :.....''' |/`....\|...|
  110171. :.........................|___|___|___|
  110172. |Sl |Sr |endW
  110173. | | |endSr
  110174. | |beginSr
  110175. | |endSl
  110176. |beginSl
  110177. |beginW
  110178. */
  110179. /* block abstraction setup *********************************************/
  110180. #ifndef WORD_ALIGN
  110181. #define WORD_ALIGN 8
  110182. #endif
  110183. int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb){
  110184. int i;
  110185. memset(vb,0,sizeof(*vb));
  110186. vb->vd=v;
  110187. vb->localalloc=0;
  110188. vb->localstore=NULL;
  110189. if(v->analysisp){
  110190. vorbis_block_internal *vbi=(vorbis_block_internal*)
  110191. (vb->internal=(vorbis_block_internal*)_ogg_calloc(1,sizeof(vorbis_block_internal)));
  110192. vbi->ampmax=-9999;
  110193. for(i=0;i<PACKETBLOBS;i++){
  110194. if(i==PACKETBLOBS/2){
  110195. vbi->packetblob[i]=&vb->opb;
  110196. }else{
  110197. vbi->packetblob[i]=
  110198. (oggpack_buffer*) _ogg_calloc(1,sizeof(oggpack_buffer));
  110199. }
  110200. oggpack_writeinit(vbi->packetblob[i]);
  110201. }
  110202. }
  110203. return(0);
  110204. }
  110205. void *_vorbis_block_alloc(vorbis_block *vb,long bytes){
  110206. bytes=(bytes+(WORD_ALIGN-1)) & ~(WORD_ALIGN-1);
  110207. if(bytes+vb->localtop>vb->localalloc){
  110208. /* can't just _ogg_realloc... there are outstanding pointers */
  110209. if(vb->localstore){
  110210. struct alloc_chain *link=(struct alloc_chain*)_ogg_malloc(sizeof(*link));
  110211. vb->totaluse+=vb->localtop;
  110212. link->next=vb->reap;
  110213. link->ptr=vb->localstore;
  110214. vb->reap=link;
  110215. }
  110216. /* highly conservative */
  110217. vb->localalloc=bytes;
  110218. vb->localstore=_ogg_malloc(vb->localalloc);
  110219. vb->localtop=0;
  110220. }
  110221. {
  110222. void *ret=(void *)(((char *)vb->localstore)+vb->localtop);
  110223. vb->localtop+=bytes;
  110224. return ret;
  110225. }
  110226. }
  110227. /* reap the chain, pull the ripcord */
  110228. void _vorbis_block_ripcord(vorbis_block *vb){
  110229. /* reap the chain */
  110230. struct alloc_chain *reap=vb->reap;
  110231. while(reap){
  110232. struct alloc_chain *next=reap->next;
  110233. _ogg_free(reap->ptr);
  110234. memset(reap,0,sizeof(*reap));
  110235. _ogg_free(reap);
  110236. reap=next;
  110237. }
  110238. /* consolidate storage */
  110239. if(vb->totaluse){
  110240. vb->localstore=_ogg_realloc(vb->localstore,vb->totaluse+vb->localalloc);
  110241. vb->localalloc+=vb->totaluse;
  110242. vb->totaluse=0;
  110243. }
  110244. /* pull the ripcord */
  110245. vb->localtop=0;
  110246. vb->reap=NULL;
  110247. }
  110248. int vorbis_block_clear(vorbis_block *vb){
  110249. int i;
  110250. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  110251. _vorbis_block_ripcord(vb);
  110252. if(vb->localstore)_ogg_free(vb->localstore);
  110253. if(vbi){
  110254. for(i=0;i<PACKETBLOBS;i++){
  110255. oggpack_writeclear(vbi->packetblob[i]);
  110256. if(i!=PACKETBLOBS/2)_ogg_free(vbi->packetblob[i]);
  110257. }
  110258. _ogg_free(vbi);
  110259. }
  110260. memset(vb,0,sizeof(*vb));
  110261. return(0);
  110262. }
  110263. /* Analysis side code, but directly related to blocking. Thus it's
  110264. here and not in analysis.c (which is for analysis transforms only).
  110265. The init is here because some of it is shared */
  110266. static int _vds_shared_init(vorbis_dsp_state *v,vorbis_info *vi,int encp){
  110267. int i;
  110268. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110269. private_state *b=NULL;
  110270. int hs;
  110271. if(ci==NULL) return 1;
  110272. hs=ci->halfrate_flag;
  110273. memset(v,0,sizeof(*v));
  110274. b=(private_state*) (v->backend_state=(private_state*)_ogg_calloc(1,sizeof(*b)));
  110275. v->vi=vi;
  110276. b->modebits=ilog2(ci->modes);
  110277. b->transform[0]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[0]));
  110278. b->transform[1]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[1]));
  110279. /* MDCT is tranform 0 */
  110280. b->transform[0][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  110281. b->transform[1][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  110282. mdct_init((mdct_lookup*)b->transform[0][0],ci->blocksizes[0]>>hs);
  110283. mdct_init((mdct_lookup*)b->transform[1][0],ci->blocksizes[1]>>hs);
  110284. /* Vorbis I uses only window type 0 */
  110285. b->window[0]=ilog2(ci->blocksizes[0])-6;
  110286. b->window[1]=ilog2(ci->blocksizes[1])-6;
  110287. if(encp){ /* encode/decode differ here */
  110288. /* analysis always needs an fft */
  110289. drft_init(&b->fft_look[0],ci->blocksizes[0]);
  110290. drft_init(&b->fft_look[1],ci->blocksizes[1]);
  110291. /* finish the codebooks */
  110292. if(!ci->fullbooks){
  110293. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  110294. for(i=0;i<ci->books;i++)
  110295. vorbis_book_init_encode(ci->fullbooks+i,ci->book_param[i]);
  110296. }
  110297. b->psy=(vorbis_look_psy*)_ogg_calloc(ci->psys,sizeof(*b->psy));
  110298. for(i=0;i<ci->psys;i++){
  110299. _vp_psy_init(b->psy+i,
  110300. ci->psy_param[i],
  110301. &ci->psy_g_param,
  110302. ci->blocksizes[ci->psy_param[i]->blockflag]/2,
  110303. vi->rate);
  110304. }
  110305. v->analysisp=1;
  110306. }else{
  110307. /* finish the codebooks */
  110308. if(!ci->fullbooks){
  110309. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  110310. for(i=0;i<ci->books;i++){
  110311. vorbis_book_init_decode(ci->fullbooks+i,ci->book_param[i]);
  110312. /* decode codebooks are now standalone after init */
  110313. vorbis_staticbook_destroy(ci->book_param[i]);
  110314. ci->book_param[i]=NULL;
  110315. }
  110316. }
  110317. }
  110318. /* initialize the storage vectors. blocksize[1] is small for encode,
  110319. but the correct size for decode */
  110320. v->pcm_storage=ci->blocksizes[1];
  110321. v->pcm=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcm));
  110322. v->pcmret=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcmret));
  110323. {
  110324. int i;
  110325. for(i=0;i<vi->channels;i++)
  110326. v->pcm[i]=(float*)_ogg_calloc(v->pcm_storage,sizeof(*v->pcm[i]));
  110327. }
  110328. /* all 1 (large block) or 0 (small block) */
  110329. /* explicitly set for the sake of clarity */
  110330. v->lW=0; /* previous window size */
  110331. v->W=0; /* current window size */
  110332. /* all vector indexes */
  110333. v->centerW=ci->blocksizes[1]/2;
  110334. v->pcm_current=v->centerW;
  110335. /* initialize all the backend lookups */
  110336. b->flr=(vorbis_look_floor**)_ogg_calloc(ci->floors,sizeof(*b->flr));
  110337. b->residue=(vorbis_look_residue**)_ogg_calloc(ci->residues,sizeof(*b->residue));
  110338. for(i=0;i<ci->floors;i++)
  110339. b->flr[i]=_floor_P[ci->floor_type[i]]->
  110340. look(v,ci->floor_param[i]);
  110341. for(i=0;i<ci->residues;i++)
  110342. b->residue[i]=_residue_P[ci->residue_type[i]]->
  110343. look(v,ci->residue_param[i]);
  110344. return 0;
  110345. }
  110346. /* arbitrary settings and spec-mandated numbers get filled in here */
  110347. int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi){
  110348. private_state *b=NULL;
  110349. if(_vds_shared_init(v,vi,1))return 1;
  110350. b=(private_state*)v->backend_state;
  110351. b->psy_g_look=_vp_global_look(vi);
  110352. /* Initialize the envelope state storage */
  110353. b->ve=(envelope_lookup*)_ogg_calloc(1,sizeof(*b->ve));
  110354. _ve_envelope_init(b->ve,vi);
  110355. vorbis_bitrate_init(vi,&b->bms);
  110356. /* compressed audio packets start after the headers
  110357. with sequence number 3 */
  110358. v->sequence=3;
  110359. return(0);
  110360. }
  110361. void vorbis_dsp_clear(vorbis_dsp_state *v){
  110362. int i;
  110363. if(v){
  110364. vorbis_info *vi=v->vi;
  110365. codec_setup_info *ci=(codec_setup_info*)(vi?vi->codec_setup:NULL);
  110366. private_state *b=(private_state*)v->backend_state;
  110367. if(b){
  110368. if(b->ve){
  110369. _ve_envelope_clear(b->ve);
  110370. _ogg_free(b->ve);
  110371. }
  110372. if(b->transform[0]){
  110373. mdct_clear((mdct_lookup*) b->transform[0][0]);
  110374. _ogg_free(b->transform[0][0]);
  110375. _ogg_free(b->transform[0]);
  110376. }
  110377. if(b->transform[1]){
  110378. mdct_clear((mdct_lookup*) b->transform[1][0]);
  110379. _ogg_free(b->transform[1][0]);
  110380. _ogg_free(b->transform[1]);
  110381. }
  110382. if(b->flr){
  110383. for(i=0;i<ci->floors;i++)
  110384. _floor_P[ci->floor_type[i]]->
  110385. free_look(b->flr[i]);
  110386. _ogg_free(b->flr);
  110387. }
  110388. if(b->residue){
  110389. for(i=0;i<ci->residues;i++)
  110390. _residue_P[ci->residue_type[i]]->
  110391. free_look(b->residue[i]);
  110392. _ogg_free(b->residue);
  110393. }
  110394. if(b->psy){
  110395. for(i=0;i<ci->psys;i++)
  110396. _vp_psy_clear(b->psy+i);
  110397. _ogg_free(b->psy);
  110398. }
  110399. if(b->psy_g_look)_vp_global_free(b->psy_g_look);
  110400. vorbis_bitrate_clear(&b->bms);
  110401. drft_clear(&b->fft_look[0]);
  110402. drft_clear(&b->fft_look[1]);
  110403. }
  110404. if(v->pcm){
  110405. for(i=0;i<vi->channels;i++)
  110406. if(v->pcm[i])_ogg_free(v->pcm[i]);
  110407. _ogg_free(v->pcm);
  110408. if(v->pcmret)_ogg_free(v->pcmret);
  110409. }
  110410. if(b){
  110411. /* free header, header1, header2 */
  110412. if(b->header)_ogg_free(b->header);
  110413. if(b->header1)_ogg_free(b->header1);
  110414. if(b->header2)_ogg_free(b->header2);
  110415. _ogg_free(b);
  110416. }
  110417. memset(v,0,sizeof(*v));
  110418. }
  110419. }
  110420. float **vorbis_analysis_buffer(vorbis_dsp_state *v, int vals){
  110421. int i;
  110422. vorbis_info *vi=v->vi;
  110423. private_state *b=(private_state*)v->backend_state;
  110424. /* free header, header1, header2 */
  110425. if(b->header)_ogg_free(b->header);b->header=NULL;
  110426. if(b->header1)_ogg_free(b->header1);b->header1=NULL;
  110427. if(b->header2)_ogg_free(b->header2);b->header2=NULL;
  110428. /* Do we have enough storage space for the requested buffer? If not,
  110429. expand the PCM (and envelope) storage */
  110430. if(v->pcm_current+vals>=v->pcm_storage){
  110431. v->pcm_storage=v->pcm_current+vals*2;
  110432. for(i=0;i<vi->channels;i++){
  110433. v->pcm[i]=(float*)_ogg_realloc(v->pcm[i],v->pcm_storage*sizeof(*v->pcm[i]));
  110434. }
  110435. }
  110436. for(i=0;i<vi->channels;i++)
  110437. v->pcmret[i]=v->pcm[i]+v->pcm_current;
  110438. return(v->pcmret);
  110439. }
  110440. static void _preextrapolate_helper(vorbis_dsp_state *v){
  110441. int i;
  110442. int order=32;
  110443. float *lpc=(float*)alloca(order*sizeof(*lpc));
  110444. float *work=(float*)alloca(v->pcm_current*sizeof(*work));
  110445. long j;
  110446. v->preextrapolate=1;
  110447. if(v->pcm_current-v->centerW>order*2){ /* safety */
  110448. for(i=0;i<v->vi->channels;i++){
  110449. /* need to run the extrapolation in reverse! */
  110450. for(j=0;j<v->pcm_current;j++)
  110451. work[j]=v->pcm[i][v->pcm_current-j-1];
  110452. /* prime as above */
  110453. vorbis_lpc_from_data(work,lpc,v->pcm_current-v->centerW,order);
  110454. /* run the predictor filter */
  110455. vorbis_lpc_predict(lpc,work+v->pcm_current-v->centerW-order,
  110456. order,
  110457. work+v->pcm_current-v->centerW,
  110458. v->centerW);
  110459. for(j=0;j<v->pcm_current;j++)
  110460. v->pcm[i][v->pcm_current-j-1]=work[j];
  110461. }
  110462. }
  110463. }
  110464. /* call with val<=0 to set eof */
  110465. int vorbis_analysis_wrote(vorbis_dsp_state *v, int vals){
  110466. vorbis_info *vi=v->vi;
  110467. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110468. if(vals<=0){
  110469. int order=32;
  110470. int i;
  110471. float *lpc=(float*) alloca(order*sizeof(*lpc));
  110472. /* if it wasn't done earlier (very short sample) */
  110473. if(!v->preextrapolate)
  110474. _preextrapolate_helper(v);
  110475. /* We're encoding the end of the stream. Just make sure we have
  110476. [at least] a few full blocks of zeroes at the end. */
  110477. /* actually, we don't want zeroes; that could drop a large
  110478. amplitude off a cliff, creating spread spectrum noise that will
  110479. suck to encode. Extrapolate for the sake of cleanliness. */
  110480. vorbis_analysis_buffer(v,ci->blocksizes[1]*3);
  110481. v->eofflag=v->pcm_current;
  110482. v->pcm_current+=ci->blocksizes[1]*3;
  110483. for(i=0;i<vi->channels;i++){
  110484. if(v->eofflag>order*2){
  110485. /* extrapolate with LPC to fill in */
  110486. long n;
  110487. /* make a predictor filter */
  110488. n=v->eofflag;
  110489. if(n>ci->blocksizes[1])n=ci->blocksizes[1];
  110490. vorbis_lpc_from_data(v->pcm[i]+v->eofflag-n,lpc,n,order);
  110491. /* run the predictor filter */
  110492. vorbis_lpc_predict(lpc,v->pcm[i]+v->eofflag-order,order,
  110493. v->pcm[i]+v->eofflag,v->pcm_current-v->eofflag);
  110494. }else{
  110495. /* not enough data to extrapolate (unlikely to happen due to
  110496. guarding the overlap, but bulletproof in case that
  110497. assumtion goes away). zeroes will do. */
  110498. memset(v->pcm[i]+v->eofflag,0,
  110499. (v->pcm_current-v->eofflag)*sizeof(*v->pcm[i]));
  110500. }
  110501. }
  110502. }else{
  110503. if(v->pcm_current+vals>v->pcm_storage)
  110504. return(OV_EINVAL);
  110505. v->pcm_current+=vals;
  110506. /* we may want to reverse extrapolate the beginning of a stream
  110507. too... in case we're beginning on a cliff! */
  110508. /* clumsy, but simple. It only runs once, so simple is good. */
  110509. if(!v->preextrapolate && v->pcm_current-v->centerW>ci->blocksizes[1])
  110510. _preextrapolate_helper(v);
  110511. }
  110512. return(0);
  110513. }
  110514. /* do the deltas, envelope shaping, pre-echo and determine the size of
  110515. the next block on which to continue analysis */
  110516. int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb){
  110517. int i;
  110518. vorbis_info *vi=v->vi;
  110519. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110520. private_state *b=(private_state*)v->backend_state;
  110521. vorbis_look_psy_global *g=b->psy_g_look;
  110522. long beginW=v->centerW-ci->blocksizes[v->W]/2,centerNext;
  110523. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  110524. /* check to see if we're started... */
  110525. if(!v->preextrapolate)return(0);
  110526. /* check to see if we're done... */
  110527. if(v->eofflag==-1)return(0);
  110528. /* By our invariant, we have lW, W and centerW set. Search for
  110529. the next boundary so we can determine nW (the next window size)
  110530. which lets us compute the shape of the current block's window */
  110531. /* we do an envelope search even on a single blocksize; we may still
  110532. be throwing more bits at impulses, and envelope search handles
  110533. marking impulses too. */
  110534. {
  110535. long bp=_ve_envelope_search(v);
  110536. if(bp==-1){
  110537. if(v->eofflag==0)return(0); /* not enough data currently to search for a
  110538. full long block */
  110539. v->nW=0;
  110540. }else{
  110541. if(ci->blocksizes[0]==ci->blocksizes[1])
  110542. v->nW=0;
  110543. else
  110544. v->nW=bp;
  110545. }
  110546. }
  110547. centerNext=v->centerW+ci->blocksizes[v->W]/4+ci->blocksizes[v->nW]/4;
  110548. {
  110549. /* center of next block + next block maximum right side. */
  110550. long blockbound=centerNext+ci->blocksizes[v->nW]/2;
  110551. if(v->pcm_current<blockbound)return(0); /* not enough data yet;
  110552. although this check is
  110553. less strict that the
  110554. _ve_envelope_search,
  110555. the search is not run
  110556. if we only use one
  110557. block size */
  110558. }
  110559. /* fill in the block. Note that for a short window, lW and nW are *short*
  110560. regardless of actual settings in the stream */
  110561. _vorbis_block_ripcord(vb);
  110562. vb->lW=v->lW;
  110563. vb->W=v->W;
  110564. vb->nW=v->nW;
  110565. if(v->W){
  110566. if(!v->lW || !v->nW){
  110567. vbi->blocktype=BLOCKTYPE_TRANSITION;
  110568. /*fprintf(stderr,"-");*/
  110569. }else{
  110570. vbi->blocktype=BLOCKTYPE_LONG;
  110571. /*fprintf(stderr,"_");*/
  110572. }
  110573. }else{
  110574. if(_ve_envelope_mark(v)){
  110575. vbi->blocktype=BLOCKTYPE_IMPULSE;
  110576. /*fprintf(stderr,"|");*/
  110577. }else{
  110578. vbi->blocktype=BLOCKTYPE_PADDING;
  110579. /*fprintf(stderr,".");*/
  110580. }
  110581. }
  110582. vb->vd=v;
  110583. vb->sequence=v->sequence++;
  110584. vb->granulepos=v->granulepos;
  110585. vb->pcmend=ci->blocksizes[v->W];
  110586. /* copy the vectors; this uses the local storage in vb */
  110587. /* this tracks 'strongest peak' for later psychoacoustics */
  110588. /* moved to the global psy state; clean this mess up */
  110589. if(vbi->ampmax>g->ampmax)g->ampmax=vbi->ampmax;
  110590. g->ampmax=_vp_ampmax_decay(g->ampmax,v);
  110591. vbi->ampmax=g->ampmax;
  110592. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  110593. vbi->pcmdelay=(float**)_vorbis_block_alloc(vb,sizeof(*vbi->pcmdelay)*vi->channels);
  110594. for(i=0;i<vi->channels;i++){
  110595. vbi->pcmdelay[i]=
  110596. (float*) _vorbis_block_alloc(vb,(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  110597. memcpy(vbi->pcmdelay[i],v->pcm[i],(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  110598. vb->pcm[i]=vbi->pcmdelay[i]+beginW;
  110599. /* before we added the delay
  110600. vb->pcm[i]=_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  110601. memcpy(vb->pcm[i],v->pcm[i]+beginW,ci->blocksizes[v->W]*sizeof(*vb->pcm[i]));
  110602. */
  110603. }
  110604. /* handle eof detection: eof==0 means that we've not yet received EOF
  110605. eof>0 marks the last 'real' sample in pcm[]
  110606. eof<0 'no more to do'; doesn't get here */
  110607. if(v->eofflag){
  110608. if(v->centerW>=v->eofflag){
  110609. v->eofflag=-1;
  110610. vb->eofflag=1;
  110611. return(1);
  110612. }
  110613. }
  110614. /* advance storage vectors and clean up */
  110615. {
  110616. int new_centerNext=ci->blocksizes[1]/2;
  110617. int movementW=centerNext-new_centerNext;
  110618. if(movementW>0){
  110619. _ve_envelope_shift(b->ve,movementW);
  110620. v->pcm_current-=movementW;
  110621. for(i=0;i<vi->channels;i++)
  110622. memmove(v->pcm[i],v->pcm[i]+movementW,
  110623. v->pcm_current*sizeof(*v->pcm[i]));
  110624. v->lW=v->W;
  110625. v->W=v->nW;
  110626. v->centerW=new_centerNext;
  110627. if(v->eofflag){
  110628. v->eofflag-=movementW;
  110629. if(v->eofflag<=0)v->eofflag=-1;
  110630. /* do not add padding to end of stream! */
  110631. if(v->centerW>=v->eofflag){
  110632. v->granulepos+=movementW-(v->centerW-v->eofflag);
  110633. }else{
  110634. v->granulepos+=movementW;
  110635. }
  110636. }else{
  110637. v->granulepos+=movementW;
  110638. }
  110639. }
  110640. }
  110641. /* done */
  110642. return(1);
  110643. }
  110644. int vorbis_synthesis_restart(vorbis_dsp_state *v){
  110645. vorbis_info *vi=v->vi;
  110646. codec_setup_info *ci;
  110647. int hs;
  110648. if(!v->backend_state)return -1;
  110649. if(!vi)return -1;
  110650. ci=(codec_setup_info*) vi->codec_setup;
  110651. if(!ci)return -1;
  110652. hs=ci->halfrate_flag;
  110653. v->centerW=ci->blocksizes[1]>>(hs+1);
  110654. v->pcm_current=v->centerW>>hs;
  110655. v->pcm_returned=-1;
  110656. v->granulepos=-1;
  110657. v->sequence=-1;
  110658. v->eofflag=0;
  110659. ((private_state *)(v->backend_state))->sample_count=-1;
  110660. return(0);
  110661. }
  110662. int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi){
  110663. if(_vds_shared_init(v,vi,0)) return 1;
  110664. vorbis_synthesis_restart(v);
  110665. return 0;
  110666. }
  110667. /* Unlike in analysis, the window is only partially applied for each
  110668. block. The time domain envelope is not yet handled at the point of
  110669. calling (as it relies on the previous block). */
  110670. int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb){
  110671. vorbis_info *vi=v->vi;
  110672. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110673. private_state *b=(private_state*)v->backend_state;
  110674. int hs=ci->halfrate_flag;
  110675. int i,j;
  110676. if(!vb)return(OV_EINVAL);
  110677. if(v->pcm_current>v->pcm_returned && v->pcm_returned!=-1)return(OV_EINVAL);
  110678. v->lW=v->W;
  110679. v->W=vb->W;
  110680. v->nW=-1;
  110681. if((v->sequence==-1)||
  110682. (v->sequence+1 != vb->sequence)){
  110683. v->granulepos=-1; /* out of sequence; lose count */
  110684. b->sample_count=-1;
  110685. }
  110686. v->sequence=vb->sequence;
  110687. if(vb->pcm){ /* no pcm to process if vorbis_synthesis_trackonly
  110688. was called on block */
  110689. int n=ci->blocksizes[v->W]>>(hs+1);
  110690. int n0=ci->blocksizes[0]>>(hs+1);
  110691. int n1=ci->blocksizes[1]>>(hs+1);
  110692. int thisCenter;
  110693. int prevCenter;
  110694. v->glue_bits+=vb->glue_bits;
  110695. v->time_bits+=vb->time_bits;
  110696. v->floor_bits+=vb->floor_bits;
  110697. v->res_bits+=vb->res_bits;
  110698. if(v->centerW){
  110699. thisCenter=n1;
  110700. prevCenter=0;
  110701. }else{
  110702. thisCenter=0;
  110703. prevCenter=n1;
  110704. }
  110705. /* v->pcm is now used like a two-stage double buffer. We don't want
  110706. to have to constantly shift *or* adjust memory usage. Don't
  110707. accept a new block until the old is shifted out */
  110708. for(j=0;j<vi->channels;j++){
  110709. /* the overlap/add section */
  110710. if(v->lW){
  110711. if(v->W){
  110712. /* large/large */
  110713. float *w=_vorbis_window_get(b->window[1]-hs);
  110714. float *pcm=v->pcm[j]+prevCenter;
  110715. float *p=vb->pcm[j];
  110716. for(i=0;i<n1;i++)
  110717. pcm[i]=pcm[i]*w[n1-i-1] + p[i]*w[i];
  110718. }else{
  110719. /* large/small */
  110720. float *w=_vorbis_window_get(b->window[0]-hs);
  110721. float *pcm=v->pcm[j]+prevCenter+n1/2-n0/2;
  110722. float *p=vb->pcm[j];
  110723. for(i=0;i<n0;i++)
  110724. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  110725. }
  110726. }else{
  110727. if(v->W){
  110728. /* small/large */
  110729. float *w=_vorbis_window_get(b->window[0]-hs);
  110730. float *pcm=v->pcm[j]+prevCenter;
  110731. float *p=vb->pcm[j]+n1/2-n0/2;
  110732. for(i=0;i<n0;i++)
  110733. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  110734. for(;i<n1/2+n0/2;i++)
  110735. pcm[i]=p[i];
  110736. }else{
  110737. /* small/small */
  110738. float *w=_vorbis_window_get(b->window[0]-hs);
  110739. float *pcm=v->pcm[j]+prevCenter;
  110740. float *p=vb->pcm[j];
  110741. for(i=0;i<n0;i++)
  110742. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  110743. }
  110744. }
  110745. /* the copy section */
  110746. {
  110747. float *pcm=v->pcm[j]+thisCenter;
  110748. float *p=vb->pcm[j]+n;
  110749. for(i=0;i<n;i++)
  110750. pcm[i]=p[i];
  110751. }
  110752. }
  110753. if(v->centerW)
  110754. v->centerW=0;
  110755. else
  110756. v->centerW=n1;
  110757. /* deal with initial packet state; we do this using the explicit
  110758. pcm_returned==-1 flag otherwise we're sensitive to first block
  110759. being short or long */
  110760. if(v->pcm_returned==-1){
  110761. v->pcm_returned=thisCenter;
  110762. v->pcm_current=thisCenter;
  110763. }else{
  110764. v->pcm_returned=prevCenter;
  110765. v->pcm_current=prevCenter+
  110766. ((ci->blocksizes[v->lW]/4+
  110767. ci->blocksizes[v->W]/4)>>hs);
  110768. }
  110769. }
  110770. /* track the frame number... This is for convenience, but also
  110771. making sure our last packet doesn't end with added padding. If
  110772. the last packet is partial, the number of samples we'll have to
  110773. return will be past the vb->granulepos.
  110774. This is not foolproof! It will be confused if we begin
  110775. decoding at the last page after a seek or hole. In that case,
  110776. we don't have a starting point to judge where the last frame
  110777. is. For this reason, vorbisfile will always try to make sure
  110778. it reads the last two marked pages in proper sequence */
  110779. if(b->sample_count==-1){
  110780. b->sample_count=0;
  110781. }else{
  110782. b->sample_count+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  110783. }
  110784. if(v->granulepos==-1){
  110785. if(vb->granulepos!=-1){ /* only set if we have a position to set to */
  110786. v->granulepos=vb->granulepos;
  110787. /* is this a short page? */
  110788. if(b->sample_count>v->granulepos){
  110789. /* corner case; if this is both the first and last audio page,
  110790. then spec says the end is cut, not beginning */
  110791. if(vb->eofflag){
  110792. /* trim the end */
  110793. /* no preceeding granulepos; assume we started at zero (we'd
  110794. have to in a short single-page stream) */
  110795. /* granulepos could be -1 due to a seek, but that would result
  110796. in a long count, not short count */
  110797. v->pcm_current-=(b->sample_count-v->granulepos)>>hs;
  110798. }else{
  110799. /* trim the beginning */
  110800. v->pcm_returned+=(b->sample_count-v->granulepos)>>hs;
  110801. if(v->pcm_returned>v->pcm_current)
  110802. v->pcm_returned=v->pcm_current;
  110803. }
  110804. }
  110805. }
  110806. }else{
  110807. v->granulepos+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  110808. if(vb->granulepos!=-1 && v->granulepos!=vb->granulepos){
  110809. if(v->granulepos>vb->granulepos){
  110810. long extra=v->granulepos-vb->granulepos;
  110811. if(extra)
  110812. if(vb->eofflag){
  110813. /* partial last frame. Strip the extra samples off */
  110814. v->pcm_current-=extra>>hs;
  110815. } /* else {Shouldn't happen *unless* the bitstream is out of
  110816. spec. Either way, believe the bitstream } */
  110817. } /* else {Shouldn't happen *unless* the bitstream is out of
  110818. spec. Either way, believe the bitstream } */
  110819. v->granulepos=vb->granulepos;
  110820. }
  110821. }
  110822. /* Update, cleanup */
  110823. if(vb->eofflag)v->eofflag=1;
  110824. return(0);
  110825. }
  110826. /* pcm==NULL indicates we just want the pending samples, no more */
  110827. int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm){
  110828. vorbis_info *vi=v->vi;
  110829. if(v->pcm_returned>-1 && v->pcm_returned<v->pcm_current){
  110830. if(pcm){
  110831. int i;
  110832. for(i=0;i<vi->channels;i++)
  110833. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  110834. *pcm=v->pcmret;
  110835. }
  110836. return(v->pcm_current-v->pcm_returned);
  110837. }
  110838. return(0);
  110839. }
  110840. int vorbis_synthesis_read(vorbis_dsp_state *v,int n){
  110841. if(n && v->pcm_returned+n>v->pcm_current)return(OV_EINVAL);
  110842. v->pcm_returned+=n;
  110843. return(0);
  110844. }
  110845. /* intended for use with a specific vorbisfile feature; we want access
  110846. to the [usually synthetic/postextrapolated] buffer and lapping at
  110847. the end of a decode cycle, specifically, a half-short-block worth.
  110848. This funtion works like pcmout above, except it will also expose
  110849. this implicit buffer data not normally decoded. */
  110850. int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm){
  110851. vorbis_info *vi=v->vi;
  110852. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  110853. int hs=ci->halfrate_flag;
  110854. int n=ci->blocksizes[v->W]>>(hs+1);
  110855. int n0=ci->blocksizes[0]>>(hs+1);
  110856. int n1=ci->blocksizes[1]>>(hs+1);
  110857. int i,j;
  110858. if(v->pcm_returned<0)return 0;
  110859. /* our returned data ends at pcm_returned; because the synthesis pcm
  110860. buffer is a two-fragment ring, that means our data block may be
  110861. fragmented by buffering, wrapping or a short block not filling
  110862. out a buffer. To simplify things, we unfragment if it's at all
  110863. possibly needed. Otherwise, we'd need to call lapout more than
  110864. once as well as hold additional dsp state. Opt for
  110865. simplicity. */
  110866. /* centerW was advanced by blockin; it would be the center of the
  110867. *next* block */
  110868. if(v->centerW==n1){
  110869. /* the data buffer wraps; swap the halves */
  110870. /* slow, sure, small */
  110871. for(j=0;j<vi->channels;j++){
  110872. float *p=v->pcm[j];
  110873. for(i=0;i<n1;i++){
  110874. float temp=p[i];
  110875. p[i]=p[i+n1];
  110876. p[i+n1]=temp;
  110877. }
  110878. }
  110879. v->pcm_current-=n1;
  110880. v->pcm_returned-=n1;
  110881. v->centerW=0;
  110882. }
  110883. /* solidify buffer into contiguous space */
  110884. if((v->lW^v->W)==1){
  110885. /* long/short or short/long */
  110886. for(j=0;j<vi->channels;j++){
  110887. float *s=v->pcm[j];
  110888. float *d=v->pcm[j]+(n1-n0)/2;
  110889. for(i=(n1+n0)/2-1;i>=0;--i)
  110890. d[i]=s[i];
  110891. }
  110892. v->pcm_returned+=(n1-n0)/2;
  110893. v->pcm_current+=(n1-n0)/2;
  110894. }else{
  110895. if(v->lW==0){
  110896. /* short/short */
  110897. for(j=0;j<vi->channels;j++){
  110898. float *s=v->pcm[j];
  110899. float *d=v->pcm[j]+n1-n0;
  110900. for(i=n0-1;i>=0;--i)
  110901. d[i]=s[i];
  110902. }
  110903. v->pcm_returned+=n1-n0;
  110904. v->pcm_current+=n1-n0;
  110905. }
  110906. }
  110907. if(pcm){
  110908. int i;
  110909. for(i=0;i<vi->channels;i++)
  110910. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  110911. *pcm=v->pcmret;
  110912. }
  110913. return(n1+n-v->pcm_returned);
  110914. }
  110915. float *vorbis_window(vorbis_dsp_state *v,int W){
  110916. vorbis_info *vi=v->vi;
  110917. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  110918. int hs=ci->halfrate_flag;
  110919. private_state *b=(private_state*)v->backend_state;
  110920. if(b->window[W]-1<0)return NULL;
  110921. return _vorbis_window_get(b->window[W]-hs);
  110922. }
  110923. #endif
  110924. /*** End of inlined file: block.c ***/
  110925. /*** Start of inlined file: codebook.c ***/
  110926. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110927. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110928. // tasks..
  110929. #if JUCE_MSVC
  110930. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110931. #endif
  110932. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110933. #if JUCE_USE_OGGVORBIS
  110934. #include <stdlib.h>
  110935. #include <string.h>
  110936. #include <math.h>
  110937. /* packs the given codebook into the bitstream **************************/
  110938. int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *opb){
  110939. long i,j;
  110940. int ordered=0;
  110941. /* first the basic parameters */
  110942. oggpack_write(opb,0x564342,24);
  110943. oggpack_write(opb,c->dim,16);
  110944. oggpack_write(opb,c->entries,24);
  110945. /* pack the codewords. There are two packings; length ordered and
  110946. length random. Decide between the two now. */
  110947. for(i=1;i<c->entries;i++)
  110948. if(c->lengthlist[i-1]==0 || c->lengthlist[i]<c->lengthlist[i-1])break;
  110949. if(i==c->entries)ordered=1;
  110950. if(ordered){
  110951. /* length ordered. We only need to say how many codewords of
  110952. each length. The actual codewords are generated
  110953. deterministically */
  110954. long count=0;
  110955. oggpack_write(opb,1,1); /* ordered */
  110956. oggpack_write(opb,c->lengthlist[0]-1,5); /* 1 to 32 */
  110957. for(i=1;i<c->entries;i++){
  110958. long thisx=c->lengthlist[i];
  110959. long last=c->lengthlist[i-1];
  110960. if(thisx>last){
  110961. for(j=last;j<thisx;j++){
  110962. oggpack_write(opb,i-count,_ilog(c->entries-count));
  110963. count=i;
  110964. }
  110965. }
  110966. }
  110967. oggpack_write(opb,i-count,_ilog(c->entries-count));
  110968. }else{
  110969. /* length random. Again, we don't code the codeword itself, just
  110970. the length. This time, though, we have to encode each length */
  110971. oggpack_write(opb,0,1); /* unordered */
  110972. /* algortihmic mapping has use for 'unused entries', which we tag
  110973. here. The algorithmic mapping happens as usual, but the unused
  110974. entry has no codeword. */
  110975. for(i=0;i<c->entries;i++)
  110976. if(c->lengthlist[i]==0)break;
  110977. if(i==c->entries){
  110978. oggpack_write(opb,0,1); /* no unused entries */
  110979. for(i=0;i<c->entries;i++)
  110980. oggpack_write(opb,c->lengthlist[i]-1,5);
  110981. }else{
  110982. oggpack_write(opb,1,1); /* we have unused entries; thus we tag */
  110983. for(i=0;i<c->entries;i++){
  110984. if(c->lengthlist[i]==0){
  110985. oggpack_write(opb,0,1);
  110986. }else{
  110987. oggpack_write(opb,1,1);
  110988. oggpack_write(opb,c->lengthlist[i]-1,5);
  110989. }
  110990. }
  110991. }
  110992. }
  110993. /* is the entry number the desired return value, or do we have a
  110994. mapping? If we have a mapping, what type? */
  110995. oggpack_write(opb,c->maptype,4);
  110996. switch(c->maptype){
  110997. case 0:
  110998. /* no mapping */
  110999. break;
  111000. case 1:case 2:
  111001. /* implicitly populated value mapping */
  111002. /* explicitly populated value mapping */
  111003. if(!c->quantlist){
  111004. /* no quantlist? error */
  111005. return(-1);
  111006. }
  111007. /* values that define the dequantization */
  111008. oggpack_write(opb,c->q_min,32);
  111009. oggpack_write(opb,c->q_delta,32);
  111010. oggpack_write(opb,c->q_quant-1,4);
  111011. oggpack_write(opb,c->q_sequencep,1);
  111012. {
  111013. int quantvals;
  111014. switch(c->maptype){
  111015. case 1:
  111016. /* a single column of (c->entries/c->dim) quantized values for
  111017. building a full value list algorithmically (square lattice) */
  111018. quantvals=_book_maptype1_quantvals(c);
  111019. break;
  111020. case 2:
  111021. /* every value (c->entries*c->dim total) specified explicitly */
  111022. quantvals=c->entries*c->dim;
  111023. break;
  111024. default: /* NOT_REACHABLE */
  111025. quantvals=-1;
  111026. }
  111027. /* quantized values */
  111028. for(i=0;i<quantvals;i++)
  111029. oggpack_write(opb,labs(c->quantlist[i]),c->q_quant);
  111030. }
  111031. break;
  111032. default:
  111033. /* error case; we don't have any other map types now */
  111034. return(-1);
  111035. }
  111036. return(0);
  111037. }
  111038. /* unpacks a codebook from the packet buffer into the codebook struct,
  111039. readies the codebook auxiliary structures for decode *************/
  111040. int vorbis_staticbook_unpack(oggpack_buffer *opb,static_codebook *s){
  111041. long i,j;
  111042. memset(s,0,sizeof(*s));
  111043. s->allocedp=1;
  111044. /* make sure alignment is correct */
  111045. if(oggpack_read(opb,24)!=0x564342)goto _eofout;
  111046. /* first the basic parameters */
  111047. s->dim=oggpack_read(opb,16);
  111048. s->entries=oggpack_read(opb,24);
  111049. if(s->entries==-1)goto _eofout;
  111050. /* codeword ordering.... length ordered or unordered? */
  111051. switch((int)oggpack_read(opb,1)){
  111052. case 0:
  111053. /* unordered */
  111054. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  111055. /* allocated but unused entries? */
  111056. if(oggpack_read(opb,1)){
  111057. /* yes, unused entries */
  111058. for(i=0;i<s->entries;i++){
  111059. if(oggpack_read(opb,1)){
  111060. long num=oggpack_read(opb,5);
  111061. if(num==-1)goto _eofout;
  111062. s->lengthlist[i]=num+1;
  111063. }else
  111064. s->lengthlist[i]=0;
  111065. }
  111066. }else{
  111067. /* all entries used; no tagging */
  111068. for(i=0;i<s->entries;i++){
  111069. long num=oggpack_read(opb,5);
  111070. if(num==-1)goto _eofout;
  111071. s->lengthlist[i]=num+1;
  111072. }
  111073. }
  111074. break;
  111075. case 1:
  111076. /* ordered */
  111077. {
  111078. long length=oggpack_read(opb,5)+1;
  111079. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  111080. for(i=0;i<s->entries;){
  111081. long num=oggpack_read(opb,_ilog(s->entries-i));
  111082. if(num==-1)goto _eofout;
  111083. for(j=0;j<num && i<s->entries;j++,i++)
  111084. s->lengthlist[i]=length;
  111085. length++;
  111086. }
  111087. }
  111088. break;
  111089. default:
  111090. /* EOF */
  111091. return(-1);
  111092. }
  111093. /* Do we have a mapping to unpack? */
  111094. switch((s->maptype=oggpack_read(opb,4))){
  111095. case 0:
  111096. /* no mapping */
  111097. break;
  111098. case 1: case 2:
  111099. /* implicitly populated value mapping */
  111100. /* explicitly populated value mapping */
  111101. s->q_min=oggpack_read(opb,32);
  111102. s->q_delta=oggpack_read(opb,32);
  111103. s->q_quant=oggpack_read(opb,4)+1;
  111104. s->q_sequencep=oggpack_read(opb,1);
  111105. {
  111106. int quantvals=0;
  111107. switch(s->maptype){
  111108. case 1:
  111109. quantvals=_book_maptype1_quantvals(s);
  111110. break;
  111111. case 2:
  111112. quantvals=s->entries*s->dim;
  111113. break;
  111114. }
  111115. /* quantized values */
  111116. s->quantlist=(long*)_ogg_malloc(sizeof(*s->quantlist)*quantvals);
  111117. for(i=0;i<quantvals;i++)
  111118. s->quantlist[i]=oggpack_read(opb,s->q_quant);
  111119. if(quantvals&&s->quantlist[quantvals-1]==-1)goto _eofout;
  111120. }
  111121. break;
  111122. default:
  111123. goto _errout;
  111124. }
  111125. /* all set */
  111126. return(0);
  111127. _errout:
  111128. _eofout:
  111129. vorbis_staticbook_clear(s);
  111130. return(-1);
  111131. }
  111132. /* returns the number of bits ************************************************/
  111133. int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b){
  111134. oggpack_write(b,book->codelist[a],book->c->lengthlist[a]);
  111135. return(book->c->lengthlist[a]);
  111136. }
  111137. /* One the encode side, our vector writers are each designed for a
  111138. specific purpose, and the encoder is not flexible without modification:
  111139. The LSP vector coder uses a single stage nearest-match with no
  111140. interleave, so no step and no error return. This is specced by floor0
  111141. and doesn't change.
  111142. Residue0 encoding interleaves, uses multiple stages, and each stage
  111143. peels of a specific amount of resolution from a lattice (thus we want
  111144. to match by threshold, not nearest match). Residue doesn't *have* to
  111145. be encoded that way, but to change it, one will need to add more
  111146. infrastructure on the encode side (decode side is specced and simpler) */
  111147. /* floor0 LSP (single stage, non interleaved, nearest match) */
  111148. /* returns entry number and *modifies a* to the quantization value *****/
  111149. int vorbis_book_errorv(codebook *book,float *a){
  111150. int dim=book->dim,k;
  111151. int best=_best(book,a,1);
  111152. for(k=0;k<dim;k++)
  111153. a[k]=(book->valuelist+best*dim)[k];
  111154. return(best);
  111155. }
  111156. /* returns the number of bits and *modifies a* to the quantization value *****/
  111157. int vorbis_book_encodev(codebook *book,int best,float *a,oggpack_buffer *b){
  111158. int k,dim=book->dim;
  111159. for(k=0;k<dim;k++)
  111160. a[k]=(book->valuelist+best*dim)[k];
  111161. return(vorbis_book_encode(book,best,b));
  111162. }
  111163. /* the 'eliminate the decode tree' optimization actually requires the
  111164. codewords to be MSb first, not LSb. This is an annoying inelegancy
  111165. (and one of the first places where carefully thought out design
  111166. turned out to be wrong; Vorbis II and future Ogg codecs should go
  111167. to an MSb bitpacker), but not actually the huge hit it appears to
  111168. be. The first-stage decode table catches most words so that
  111169. bitreverse is not in the main execution path. */
  111170. STIN long decode_packed_entry_number(codebook *book, oggpack_buffer *b){
  111171. int read=book->dec_maxlength;
  111172. long lo,hi;
  111173. long lok = oggpack_look(b,book->dec_firsttablen);
  111174. if (lok >= 0) {
  111175. long entry = book->dec_firsttable[lok];
  111176. if(entry&0x80000000UL){
  111177. lo=(entry>>15)&0x7fff;
  111178. hi=book->used_entries-(entry&0x7fff);
  111179. }else{
  111180. oggpack_adv(b, book->dec_codelengths[entry-1]);
  111181. return(entry-1);
  111182. }
  111183. }else{
  111184. lo=0;
  111185. hi=book->used_entries;
  111186. }
  111187. lok = oggpack_look(b, read);
  111188. while(lok<0 && read>1)
  111189. lok = oggpack_look(b, --read);
  111190. if(lok<0)return -1;
  111191. /* bisect search for the codeword in the ordered list */
  111192. {
  111193. ogg_uint32_t testword=ogg_bitreverse((ogg_uint32_t)lok);
  111194. while(hi-lo>1){
  111195. long p=(hi-lo)>>1;
  111196. long test=book->codelist[lo+p]>testword;
  111197. lo+=p&(test-1);
  111198. hi-=p&(-test);
  111199. }
  111200. if(book->dec_codelengths[lo]<=read){
  111201. oggpack_adv(b, book->dec_codelengths[lo]);
  111202. return(lo);
  111203. }
  111204. }
  111205. oggpack_adv(b, read);
  111206. return(-1);
  111207. }
  111208. /* Decode side is specced and easier, because we don't need to find
  111209. matches using different criteria; we simply read and map. There are
  111210. two things we need to do 'depending':
  111211. We may need to support interleave. We don't really, but it's
  111212. convenient to do it here rather than rebuild the vector later.
  111213. Cascades may be additive or multiplicitive; this is not inherent in
  111214. the codebook, but set in the code using the codebook. Like
  111215. interleaving, it's easiest to do it here.
  111216. addmul==0 -> declarative (set the value)
  111217. addmul==1 -> additive
  111218. addmul==2 -> multiplicitive */
  111219. /* returns the [original, not compacted] entry number or -1 on eof *********/
  111220. long vorbis_book_decode(codebook *book, oggpack_buffer *b){
  111221. long packed_entry=decode_packed_entry_number(book,b);
  111222. if(packed_entry>=0)
  111223. return(book->dec_index[packed_entry]);
  111224. /* if there's no dec_index, the codebook unpacking isn't collapsed */
  111225. return(packed_entry);
  111226. }
  111227. /* returns 0 on OK or -1 on eof *************************************/
  111228. long vorbis_book_decodevs_add(codebook *book,float *a,oggpack_buffer *b,int n){
  111229. int step=n/book->dim;
  111230. long *entry = (long*)alloca(sizeof(*entry)*step);
  111231. float **t = (float**)alloca(sizeof(*t)*step);
  111232. int i,j,o;
  111233. for (i = 0; i < step; i++) {
  111234. entry[i]=decode_packed_entry_number(book,b);
  111235. if(entry[i]==-1)return(-1);
  111236. t[i] = book->valuelist+entry[i]*book->dim;
  111237. }
  111238. for(i=0,o=0;i<book->dim;i++,o+=step)
  111239. for (j=0;j<step;j++)
  111240. a[o+j]+=t[j][i];
  111241. return(0);
  111242. }
  111243. long vorbis_book_decodev_add(codebook *book,float *a,oggpack_buffer *b,int n){
  111244. int i,j,entry;
  111245. float *t;
  111246. if(book->dim>8){
  111247. for(i=0;i<n;){
  111248. entry = decode_packed_entry_number(book,b);
  111249. if(entry==-1)return(-1);
  111250. t = book->valuelist+entry*book->dim;
  111251. for (j=0;j<book->dim;)
  111252. a[i++]+=t[j++];
  111253. }
  111254. }else{
  111255. for(i=0;i<n;){
  111256. entry = decode_packed_entry_number(book,b);
  111257. if(entry==-1)return(-1);
  111258. t = book->valuelist+entry*book->dim;
  111259. j=0;
  111260. switch((int)book->dim){
  111261. case 8:
  111262. a[i++]+=t[j++];
  111263. case 7:
  111264. a[i++]+=t[j++];
  111265. case 6:
  111266. a[i++]+=t[j++];
  111267. case 5:
  111268. a[i++]+=t[j++];
  111269. case 4:
  111270. a[i++]+=t[j++];
  111271. case 3:
  111272. a[i++]+=t[j++];
  111273. case 2:
  111274. a[i++]+=t[j++];
  111275. case 1:
  111276. a[i++]+=t[j++];
  111277. case 0:
  111278. break;
  111279. }
  111280. }
  111281. }
  111282. return(0);
  111283. }
  111284. long vorbis_book_decodev_set(codebook *book,float *a,oggpack_buffer *b,int n){
  111285. int i,j,entry;
  111286. float *t;
  111287. for(i=0;i<n;){
  111288. entry = decode_packed_entry_number(book,b);
  111289. if(entry==-1)return(-1);
  111290. t = book->valuelist+entry*book->dim;
  111291. for (j=0;j<book->dim;)
  111292. a[i++]=t[j++];
  111293. }
  111294. return(0);
  111295. }
  111296. long vorbis_book_decodevv_add(codebook *book,float **a,long offset,int ch,
  111297. oggpack_buffer *b,int n){
  111298. long i,j,entry;
  111299. int chptr=0;
  111300. for(i=offset/ch;i<(offset+n)/ch;){
  111301. entry = decode_packed_entry_number(book,b);
  111302. if(entry==-1)return(-1);
  111303. {
  111304. const float *t = book->valuelist+entry*book->dim;
  111305. for (j=0;j<book->dim;j++){
  111306. a[chptr++][i]+=t[j];
  111307. if(chptr==ch){
  111308. chptr=0;
  111309. i++;
  111310. }
  111311. }
  111312. }
  111313. }
  111314. return(0);
  111315. }
  111316. #ifdef _V_SELFTEST
  111317. /* Simple enough; pack a few candidate codebooks, unpack them. Code a
  111318. number of vectors through (keeping track of the quantized values),
  111319. and decode using the unpacked book. quantized version of in should
  111320. exactly equal out */
  111321. #include <stdio.h>
  111322. #include "vorbis/book/lsp20_0.vqh"
  111323. #include "vorbis/book/res0a_13.vqh"
  111324. #define TESTSIZE 40
  111325. float test1[TESTSIZE]={
  111326. 0.105939f,
  111327. 0.215373f,
  111328. 0.429117f,
  111329. 0.587974f,
  111330. 0.181173f,
  111331. 0.296583f,
  111332. 0.515707f,
  111333. 0.715261f,
  111334. 0.162327f,
  111335. 0.263834f,
  111336. 0.342876f,
  111337. 0.406025f,
  111338. 0.103571f,
  111339. 0.223561f,
  111340. 0.368513f,
  111341. 0.540313f,
  111342. 0.136672f,
  111343. 0.395882f,
  111344. 0.587183f,
  111345. 0.652476f,
  111346. 0.114338f,
  111347. 0.417300f,
  111348. 0.525486f,
  111349. 0.698679f,
  111350. 0.147492f,
  111351. 0.324481f,
  111352. 0.643089f,
  111353. 0.757582f,
  111354. 0.139556f,
  111355. 0.215795f,
  111356. 0.324559f,
  111357. 0.399387f,
  111358. 0.120236f,
  111359. 0.267420f,
  111360. 0.446940f,
  111361. 0.608760f,
  111362. 0.115587f,
  111363. 0.287234f,
  111364. 0.571081f,
  111365. 0.708603f,
  111366. };
  111367. float test3[TESTSIZE]={
  111368. 0,1,-2,3,4,-5,6,7,8,9,
  111369. 8,-2,7,-1,4,6,8,3,1,-9,
  111370. 10,11,12,13,14,15,26,17,18,19,
  111371. 30,-25,-30,-1,-5,-32,4,3,-2,0};
  111372. static_codebook *testlist[]={&_vq_book_lsp20_0,
  111373. &_vq_book_res0a_13,NULL};
  111374. float *testvec[]={test1,test3};
  111375. int main(){
  111376. oggpack_buffer write;
  111377. oggpack_buffer read;
  111378. long ptr=0,i;
  111379. oggpack_writeinit(&write);
  111380. fprintf(stderr,"Testing codebook abstraction...:\n");
  111381. while(testlist[ptr]){
  111382. codebook c;
  111383. static_codebook s;
  111384. float *qv=alloca(sizeof(*qv)*TESTSIZE);
  111385. float *iv=alloca(sizeof(*iv)*TESTSIZE);
  111386. memcpy(qv,testvec[ptr],sizeof(*qv)*TESTSIZE);
  111387. memset(iv,0,sizeof(*iv)*TESTSIZE);
  111388. fprintf(stderr,"\tpacking/coding %ld... ",ptr);
  111389. /* pack the codebook, write the testvector */
  111390. oggpack_reset(&write);
  111391. vorbis_book_init_encode(&c,testlist[ptr]); /* get it into memory
  111392. we can write */
  111393. vorbis_staticbook_pack(testlist[ptr],&write);
  111394. fprintf(stderr,"Codebook size %ld bytes... ",oggpack_bytes(&write));
  111395. for(i=0;i<TESTSIZE;i+=c.dim){
  111396. int best=_best(&c,qv+i,1);
  111397. vorbis_book_encodev(&c,best,qv+i,&write);
  111398. }
  111399. vorbis_book_clear(&c);
  111400. fprintf(stderr,"OK.\n");
  111401. fprintf(stderr,"\tunpacking/decoding %ld... ",ptr);
  111402. /* transfer the write data to a read buffer and unpack/read */
  111403. oggpack_readinit(&read,oggpack_get_buffer(&write),oggpack_bytes(&write));
  111404. if(vorbis_staticbook_unpack(&read,&s)){
  111405. fprintf(stderr,"Error unpacking codebook.\n");
  111406. exit(1);
  111407. }
  111408. if(vorbis_book_init_decode(&c,&s)){
  111409. fprintf(stderr,"Error initializing codebook.\n");
  111410. exit(1);
  111411. }
  111412. for(i=0;i<TESTSIZE;i+=c.dim)
  111413. if(vorbis_book_decodev_set(&c,iv+i,&read,c.dim)==-1){
  111414. fprintf(stderr,"Error reading codebook test data (EOP).\n");
  111415. exit(1);
  111416. }
  111417. for(i=0;i<TESTSIZE;i++)
  111418. if(fabs(qv[i]-iv[i])>.000001){
  111419. fprintf(stderr,"read (%g) != written (%g) at position (%ld)\n",
  111420. iv[i],qv[i],i);
  111421. exit(1);
  111422. }
  111423. fprintf(stderr,"OK\n");
  111424. ptr++;
  111425. }
  111426. /* The above is the trivial stuff; now try unquantizing a log scale codebook */
  111427. exit(0);
  111428. }
  111429. #endif
  111430. #endif
  111431. /*** End of inlined file: codebook.c ***/
  111432. /*** Start of inlined file: envelope.c ***/
  111433. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111434. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111435. // tasks..
  111436. #if JUCE_MSVC
  111437. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111438. #endif
  111439. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111440. #if JUCE_USE_OGGVORBIS
  111441. #include <stdlib.h>
  111442. #include <string.h>
  111443. #include <stdio.h>
  111444. #include <math.h>
  111445. void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi){
  111446. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111447. vorbis_info_psy_global *gi=&ci->psy_g_param;
  111448. int ch=vi->channels;
  111449. int i,j;
  111450. int n=e->winlength=128;
  111451. e->searchstep=64; /* not random */
  111452. e->minenergy=gi->preecho_minenergy;
  111453. e->ch=ch;
  111454. e->storage=128;
  111455. e->cursor=ci->blocksizes[1]/2;
  111456. e->mdct_win=(float*)_ogg_calloc(n,sizeof(*e->mdct_win));
  111457. mdct_init(&e->mdct,n);
  111458. for(i=0;i<n;i++){
  111459. e->mdct_win[i]=sin(i/(n-1.)*M_PI);
  111460. e->mdct_win[i]*=e->mdct_win[i];
  111461. }
  111462. /* magic follows */
  111463. e->band[0].begin=2; e->band[0].end=4;
  111464. e->band[1].begin=4; e->band[1].end=5;
  111465. e->band[2].begin=6; e->band[2].end=6;
  111466. e->band[3].begin=9; e->band[3].end=8;
  111467. e->band[4].begin=13; e->band[4].end=8;
  111468. e->band[5].begin=17; e->band[5].end=8;
  111469. e->band[6].begin=22; e->band[6].end=8;
  111470. for(j=0;j<VE_BANDS;j++){
  111471. n=e->band[j].end;
  111472. e->band[j].window=(float*)_ogg_malloc(n*sizeof(*e->band[0].window));
  111473. for(i=0;i<n;i++){
  111474. e->band[j].window[i]=sin((i+.5)/n*M_PI);
  111475. e->band[j].total+=e->band[j].window[i];
  111476. }
  111477. e->band[j].total=1./e->band[j].total;
  111478. }
  111479. e->filter=(envelope_filter_state*)_ogg_calloc(VE_BANDS*ch,sizeof(*e->filter));
  111480. e->mark=(int*)_ogg_calloc(e->storage,sizeof(*e->mark));
  111481. }
  111482. void _ve_envelope_clear(envelope_lookup *e){
  111483. int i;
  111484. mdct_clear(&e->mdct);
  111485. for(i=0;i<VE_BANDS;i++)
  111486. _ogg_free(e->band[i].window);
  111487. _ogg_free(e->mdct_win);
  111488. _ogg_free(e->filter);
  111489. _ogg_free(e->mark);
  111490. memset(e,0,sizeof(*e));
  111491. }
  111492. /* fairly straight threshhold-by-band based until we find something
  111493. that works better and isn't patented. */
  111494. static int _ve_amp(envelope_lookup *ve,
  111495. vorbis_info_psy_global *gi,
  111496. float *data,
  111497. envelope_band *bands,
  111498. envelope_filter_state *filters,
  111499. long pos){
  111500. long n=ve->winlength;
  111501. int ret=0;
  111502. long i,j;
  111503. float decay;
  111504. /* we want to have a 'minimum bar' for energy, else we're just
  111505. basing blocks on quantization noise that outweighs the signal
  111506. itself (for low power signals) */
  111507. float minV=ve->minenergy;
  111508. float *vec=(float*) alloca(n*sizeof(*vec));
  111509. /* stretch is used to gradually lengthen the number of windows
  111510. considered prevoius-to-potential-trigger */
  111511. int stretch=max(VE_MINSTRETCH,ve->stretch/2);
  111512. float penalty=gi->stretch_penalty-(ve->stretch/2-VE_MINSTRETCH);
  111513. if(penalty<0.f)penalty=0.f;
  111514. if(penalty>gi->stretch_penalty)penalty=gi->stretch_penalty;
  111515. /*_analysis_output_always("lpcm",seq2,data,n,0,0,
  111516. totalshift+pos*ve->searchstep);*/
  111517. /* window and transform */
  111518. for(i=0;i<n;i++)
  111519. vec[i]=data[i]*ve->mdct_win[i];
  111520. mdct_forward(&ve->mdct,vec,vec);
  111521. /*_analysis_output_always("mdct",seq2,vec,n/2,0,1,0); */
  111522. /* near-DC spreading function; this has nothing to do with
  111523. psychoacoustics, just sidelobe leakage and window size */
  111524. {
  111525. float temp=vec[0]*vec[0]+.7*vec[1]*vec[1]+.2*vec[2]*vec[2];
  111526. int ptr=filters->nearptr;
  111527. /* the accumulation is regularly refreshed from scratch to avoid
  111528. floating point creep */
  111529. if(ptr==0){
  111530. decay=filters->nearDC_acc=filters->nearDC_partialacc+temp;
  111531. filters->nearDC_partialacc=temp;
  111532. }else{
  111533. decay=filters->nearDC_acc+=temp;
  111534. filters->nearDC_partialacc+=temp;
  111535. }
  111536. filters->nearDC_acc-=filters->nearDC[ptr];
  111537. filters->nearDC[ptr]=temp;
  111538. decay*=(1./(VE_NEARDC+1));
  111539. filters->nearptr++;
  111540. if(filters->nearptr>=VE_NEARDC)filters->nearptr=0;
  111541. decay=todB(&decay)*.5-15.f;
  111542. }
  111543. /* perform spreading and limiting, also smooth the spectrum. yes,
  111544. the MDCT results in all real coefficients, but it still *behaves*
  111545. like real/imaginary pairs */
  111546. for(i=0;i<n/2;i+=2){
  111547. float val=vec[i]*vec[i]+vec[i+1]*vec[i+1];
  111548. val=todB(&val)*.5f;
  111549. if(val<decay)val=decay;
  111550. if(val<minV)val=minV;
  111551. vec[i>>1]=val;
  111552. decay-=8.;
  111553. }
  111554. /*_analysis_output_always("spread",seq2++,vec,n/4,0,0,0);*/
  111555. /* perform preecho/postecho triggering by band */
  111556. for(j=0;j<VE_BANDS;j++){
  111557. float acc=0.;
  111558. float valmax,valmin;
  111559. /* accumulate amplitude */
  111560. for(i=0;i<bands[j].end;i++)
  111561. acc+=vec[i+bands[j].begin]*bands[j].window[i];
  111562. acc*=bands[j].total;
  111563. /* convert amplitude to delta */
  111564. {
  111565. int p,thisx=filters[j].ampptr;
  111566. float postmax,postmin,premax=-99999.f,premin=99999.f;
  111567. p=thisx;
  111568. p--;
  111569. if(p<0)p+=VE_AMP;
  111570. postmax=max(acc,filters[j].ampbuf[p]);
  111571. postmin=min(acc,filters[j].ampbuf[p]);
  111572. for(i=0;i<stretch;i++){
  111573. p--;
  111574. if(p<0)p+=VE_AMP;
  111575. premax=max(premax,filters[j].ampbuf[p]);
  111576. premin=min(premin,filters[j].ampbuf[p]);
  111577. }
  111578. valmin=postmin-premin;
  111579. valmax=postmax-premax;
  111580. /*filters[j].markers[pos]=valmax;*/
  111581. filters[j].ampbuf[thisx]=acc;
  111582. filters[j].ampptr++;
  111583. if(filters[j].ampptr>=VE_AMP)filters[j].ampptr=0;
  111584. }
  111585. /* look at min/max, decide trigger */
  111586. if(valmax>gi->preecho_thresh[j]+penalty){
  111587. ret|=1;
  111588. ret|=4;
  111589. }
  111590. if(valmin<gi->postecho_thresh[j]-penalty)ret|=2;
  111591. }
  111592. return(ret);
  111593. }
  111594. #if 0
  111595. static int seq=0;
  111596. static ogg_int64_t totalshift=-1024;
  111597. #endif
  111598. long _ve_envelope_search(vorbis_dsp_state *v){
  111599. vorbis_info *vi=v->vi;
  111600. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  111601. vorbis_info_psy_global *gi=&ci->psy_g_param;
  111602. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  111603. long i,j;
  111604. int first=ve->current/ve->searchstep;
  111605. int last=v->pcm_current/ve->searchstep-VE_WIN;
  111606. if(first<0)first=0;
  111607. /* make sure we have enough storage to match the PCM */
  111608. if(last+VE_WIN+VE_POST>ve->storage){
  111609. ve->storage=last+VE_WIN+VE_POST; /* be sure */
  111610. ve->mark=(int*)_ogg_realloc(ve->mark,ve->storage*sizeof(*ve->mark));
  111611. }
  111612. for(j=first;j<last;j++){
  111613. int ret=0;
  111614. ve->stretch++;
  111615. if(ve->stretch>VE_MAXSTRETCH*2)
  111616. ve->stretch=VE_MAXSTRETCH*2;
  111617. for(i=0;i<ve->ch;i++){
  111618. float *pcm=v->pcm[i]+ve->searchstep*(j);
  111619. ret|=_ve_amp(ve,gi,pcm,ve->band,ve->filter+i*VE_BANDS,j);
  111620. }
  111621. ve->mark[j+VE_POST]=0;
  111622. if(ret&1){
  111623. ve->mark[j]=1;
  111624. ve->mark[j+1]=1;
  111625. }
  111626. if(ret&2){
  111627. ve->mark[j]=1;
  111628. if(j>0)ve->mark[j-1]=1;
  111629. }
  111630. if(ret&4)ve->stretch=-1;
  111631. }
  111632. ve->current=last*ve->searchstep;
  111633. {
  111634. long centerW=v->centerW;
  111635. long testW=
  111636. centerW+
  111637. ci->blocksizes[v->W]/4+
  111638. ci->blocksizes[1]/2+
  111639. ci->blocksizes[0]/4;
  111640. j=ve->cursor;
  111641. while(j<ve->current-(ve->searchstep)){/* account for postecho
  111642. working back one window */
  111643. if(j>=testW)return(1);
  111644. ve->cursor=j;
  111645. if(ve->mark[j/ve->searchstep]){
  111646. if(j>centerW){
  111647. #if 0
  111648. if(j>ve->curmark){
  111649. float *marker=alloca(v->pcm_current*sizeof(*marker));
  111650. int l,m;
  111651. memset(marker,0,sizeof(*marker)*v->pcm_current);
  111652. fprintf(stderr,"mark! seq=%d, cursor:%fs time:%fs\n",
  111653. seq,
  111654. (totalshift+ve->cursor)/44100.,
  111655. (totalshift+j)/44100.);
  111656. _analysis_output_always("pcmL",seq,v->pcm[0],v->pcm_current,0,0,totalshift);
  111657. _analysis_output_always("pcmR",seq,v->pcm[1],v->pcm_current,0,0,totalshift);
  111658. _analysis_output_always("markL",seq,v->pcm[0],j,0,0,totalshift);
  111659. _analysis_output_always("markR",seq,v->pcm[1],j,0,0,totalshift);
  111660. for(m=0;m<VE_BANDS;m++){
  111661. char buf[80];
  111662. sprintf(buf,"delL%d",m);
  111663. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m].markers[l]*.1;
  111664. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  111665. }
  111666. for(m=0;m<VE_BANDS;m++){
  111667. char buf[80];
  111668. sprintf(buf,"delR%d",m);
  111669. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m+VE_BANDS].markers[l]*.1;
  111670. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  111671. }
  111672. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->mark[l]*.4;
  111673. _analysis_output_always("mark",seq,marker,v->pcm_current,0,0,totalshift);
  111674. seq++;
  111675. }
  111676. #endif
  111677. ve->curmark=j;
  111678. if(j>=testW)return(1);
  111679. return(0);
  111680. }
  111681. }
  111682. j+=ve->searchstep;
  111683. }
  111684. }
  111685. return(-1);
  111686. }
  111687. int _ve_envelope_mark(vorbis_dsp_state *v){
  111688. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  111689. vorbis_info *vi=v->vi;
  111690. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111691. long centerW=v->centerW;
  111692. long beginW=centerW-ci->blocksizes[v->W]/4;
  111693. long endW=centerW+ci->blocksizes[v->W]/4;
  111694. if(v->W){
  111695. beginW-=ci->blocksizes[v->lW]/4;
  111696. endW+=ci->blocksizes[v->nW]/4;
  111697. }else{
  111698. beginW-=ci->blocksizes[0]/4;
  111699. endW+=ci->blocksizes[0]/4;
  111700. }
  111701. if(ve->curmark>=beginW && ve->curmark<endW)return(1);
  111702. {
  111703. long first=beginW/ve->searchstep;
  111704. long last=endW/ve->searchstep;
  111705. long i;
  111706. for(i=first;i<last;i++)
  111707. if(ve->mark[i])return(1);
  111708. }
  111709. return(0);
  111710. }
  111711. void _ve_envelope_shift(envelope_lookup *e,long shift){
  111712. int smallsize=e->current/e->searchstep+VE_POST; /* adjust for placing marks
  111713. ahead of ve->current */
  111714. int smallshift=shift/e->searchstep;
  111715. memmove(e->mark,e->mark+smallshift,(smallsize-smallshift)*sizeof(*e->mark));
  111716. #if 0
  111717. for(i=0;i<VE_BANDS*e->ch;i++)
  111718. memmove(e->filter[i].markers,
  111719. e->filter[i].markers+smallshift,
  111720. (1024-smallshift)*sizeof(*(*e->filter).markers));
  111721. totalshift+=shift;
  111722. #endif
  111723. e->current-=shift;
  111724. if(e->curmark>=0)
  111725. e->curmark-=shift;
  111726. e->cursor-=shift;
  111727. }
  111728. #endif
  111729. /*** End of inlined file: envelope.c ***/
  111730. /*** Start of inlined file: floor0.c ***/
  111731. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111732. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111733. // tasks..
  111734. #if JUCE_MSVC
  111735. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111736. #endif
  111737. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111738. #if JUCE_USE_OGGVORBIS
  111739. #include <stdlib.h>
  111740. #include <string.h>
  111741. #include <math.h>
  111742. /*** Start of inlined file: lsp.h ***/
  111743. #ifndef _V_LSP_H_
  111744. #define _V_LSP_H_
  111745. extern int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m);
  111746. extern void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,
  111747. float *lsp,int m,
  111748. float amp,float ampoffset);
  111749. #endif
  111750. /*** End of inlined file: lsp.h ***/
  111751. #include <stdio.h>
  111752. typedef struct {
  111753. int ln;
  111754. int m;
  111755. int **linearmap;
  111756. int n[2];
  111757. vorbis_info_floor0 *vi;
  111758. long bits;
  111759. long frames;
  111760. } vorbis_look_floor0;
  111761. /***********************************************/
  111762. static void floor0_free_info(vorbis_info_floor *i){
  111763. vorbis_info_floor0 *info=(vorbis_info_floor0 *)i;
  111764. if(info){
  111765. memset(info,0,sizeof(*info));
  111766. _ogg_free(info);
  111767. }
  111768. }
  111769. static void floor0_free_look(vorbis_look_floor *i){
  111770. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  111771. if(look){
  111772. if(look->linearmap){
  111773. if(look->linearmap[0])_ogg_free(look->linearmap[0]);
  111774. if(look->linearmap[1])_ogg_free(look->linearmap[1]);
  111775. _ogg_free(look->linearmap);
  111776. }
  111777. memset(look,0,sizeof(*look));
  111778. _ogg_free(look);
  111779. }
  111780. }
  111781. static vorbis_info_floor *floor0_unpack (vorbis_info *vi,oggpack_buffer *opb){
  111782. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111783. int j;
  111784. vorbis_info_floor0 *info=(vorbis_info_floor0*)_ogg_malloc(sizeof(*info));
  111785. info->order=oggpack_read(opb,8);
  111786. info->rate=oggpack_read(opb,16);
  111787. info->barkmap=oggpack_read(opb,16);
  111788. info->ampbits=oggpack_read(opb,6);
  111789. info->ampdB=oggpack_read(opb,8);
  111790. info->numbooks=oggpack_read(opb,4)+1;
  111791. if(info->order<1)goto err_out;
  111792. if(info->rate<1)goto err_out;
  111793. if(info->barkmap<1)goto err_out;
  111794. if(info->numbooks<1)goto err_out;
  111795. for(j=0;j<info->numbooks;j++){
  111796. info->books[j]=oggpack_read(opb,8);
  111797. if(info->books[j]<0 || info->books[j]>=ci->books)goto err_out;
  111798. }
  111799. return(info);
  111800. err_out:
  111801. floor0_free_info(info);
  111802. return(NULL);
  111803. }
  111804. /* initialize Bark scale and normalization lookups. We could do this
  111805. with static tables, but Vorbis allows a number of possible
  111806. combinations, so it's best to do it computationally.
  111807. The below is authoritative in terms of defining scale mapping.
  111808. Note that the scale depends on the sampling rate as well as the
  111809. linear block and mapping sizes */
  111810. static void floor0_map_lazy_init(vorbis_block *vb,
  111811. vorbis_info_floor *infoX,
  111812. vorbis_look_floor0 *look){
  111813. if(!look->linearmap[vb->W]){
  111814. vorbis_dsp_state *vd=vb->vd;
  111815. vorbis_info *vi=vd->vi;
  111816. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111817. vorbis_info_floor0 *info=(vorbis_info_floor0 *)infoX;
  111818. int W=vb->W;
  111819. int n=ci->blocksizes[W]/2,j;
  111820. /* we choose a scaling constant so that:
  111821. floor(bark(rate/2-1)*C)=mapped-1
  111822. floor(bark(rate/2)*C)=mapped */
  111823. float scale=look->ln/toBARK(info->rate/2.f);
  111824. /* the mapping from a linear scale to a smaller bark scale is
  111825. straightforward. We do *not* make sure that the linear mapping
  111826. does not skip bark-scale bins; the decoder simply skips them and
  111827. the encoder may do what it wishes in filling them. They're
  111828. necessary in some mapping combinations to keep the scale spacing
  111829. accurate */
  111830. look->linearmap[W]=(int*)_ogg_malloc((n+1)*sizeof(**look->linearmap));
  111831. for(j=0;j<n;j++){
  111832. int val=floor( toBARK((info->rate/2.f)/n*j)
  111833. *scale); /* bark numbers represent band edges */
  111834. if(val>=look->ln)val=look->ln-1; /* guard against the approximation */
  111835. look->linearmap[W][j]=val;
  111836. }
  111837. look->linearmap[W][j]=-1;
  111838. look->n[W]=n;
  111839. }
  111840. }
  111841. static vorbis_look_floor *floor0_look(vorbis_dsp_state *vd,
  111842. vorbis_info_floor *i){
  111843. vorbis_info_floor0 *info=(vorbis_info_floor0*)i;
  111844. vorbis_look_floor0 *look=(vorbis_look_floor0*)_ogg_calloc(1,sizeof(*look));
  111845. look->m=info->order;
  111846. look->ln=info->barkmap;
  111847. look->vi=info;
  111848. look->linearmap=(int**)_ogg_calloc(2,sizeof(*look->linearmap));
  111849. return look;
  111850. }
  111851. static void *floor0_inverse1(vorbis_block *vb,vorbis_look_floor *i){
  111852. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  111853. vorbis_info_floor0 *info=look->vi;
  111854. int j,k;
  111855. int ampraw=oggpack_read(&vb->opb,info->ampbits);
  111856. if(ampraw>0){ /* also handles the -1 out of data case */
  111857. long maxval=(1<<info->ampbits)-1;
  111858. float amp=(float)ampraw/maxval*info->ampdB;
  111859. int booknum=oggpack_read(&vb->opb,_ilog(info->numbooks));
  111860. if(booknum!=-1 && booknum<info->numbooks){ /* be paranoid */
  111861. codec_setup_info *ci=(codec_setup_info *)vb->vd->vi->codec_setup;
  111862. codebook *b=ci->fullbooks+info->books[booknum];
  111863. float last=0.f;
  111864. /* the additional b->dim is a guard against any possible stack
  111865. smash; b->dim is provably more than we can overflow the
  111866. vector */
  111867. float *lsp=(float*)_vorbis_block_alloc(vb,sizeof(*lsp)*(look->m+b->dim+1));
  111868. for(j=0;j<look->m;j+=b->dim)
  111869. if(vorbis_book_decodev_set(b,lsp+j,&vb->opb,b->dim)==-1)goto eop;
  111870. for(j=0;j<look->m;){
  111871. for(k=0;k<b->dim;k++,j++)lsp[j]+=last;
  111872. last=lsp[j-1];
  111873. }
  111874. lsp[look->m]=amp;
  111875. return(lsp);
  111876. }
  111877. }
  111878. eop:
  111879. return(NULL);
  111880. }
  111881. static int floor0_inverse2(vorbis_block *vb,vorbis_look_floor *i,
  111882. void *memo,float *out){
  111883. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  111884. vorbis_info_floor0 *info=look->vi;
  111885. floor0_map_lazy_init(vb,info,look);
  111886. if(memo){
  111887. float *lsp=(float *)memo;
  111888. float amp=lsp[look->m];
  111889. /* take the coefficients back to a spectral envelope curve */
  111890. vorbis_lsp_to_curve(out,
  111891. look->linearmap[vb->W],
  111892. look->n[vb->W],
  111893. look->ln,
  111894. lsp,look->m,amp,(float)info->ampdB);
  111895. return(1);
  111896. }
  111897. memset(out,0,sizeof(*out)*look->n[vb->W]);
  111898. return(0);
  111899. }
  111900. /* export hooks */
  111901. vorbis_func_floor floor0_exportbundle={
  111902. NULL,&floor0_unpack,&floor0_look,&floor0_free_info,
  111903. &floor0_free_look,&floor0_inverse1,&floor0_inverse2
  111904. };
  111905. #endif
  111906. /*** End of inlined file: floor0.c ***/
  111907. /*** Start of inlined file: floor1.c ***/
  111908. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111909. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111910. // tasks..
  111911. #if JUCE_MSVC
  111912. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111913. #endif
  111914. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111915. #if JUCE_USE_OGGVORBIS
  111916. #include <stdlib.h>
  111917. #include <string.h>
  111918. #include <math.h>
  111919. #include <stdio.h>
  111920. #define floor1_rangedB 140 /* floor 1 fixed at -140dB to 0dB range */
  111921. typedef struct {
  111922. int sorted_index[VIF_POSIT+2];
  111923. int forward_index[VIF_POSIT+2];
  111924. int reverse_index[VIF_POSIT+2];
  111925. int hineighbor[VIF_POSIT];
  111926. int loneighbor[VIF_POSIT];
  111927. int posts;
  111928. int n;
  111929. int quant_q;
  111930. vorbis_info_floor1 *vi;
  111931. long phrasebits;
  111932. long postbits;
  111933. long frames;
  111934. } vorbis_look_floor1;
  111935. typedef struct lsfit_acc{
  111936. long x0;
  111937. long x1;
  111938. long xa;
  111939. long ya;
  111940. long x2a;
  111941. long y2a;
  111942. long xya;
  111943. long an;
  111944. } lsfit_acc;
  111945. /***********************************************/
  111946. static void floor1_free_info(vorbis_info_floor *i){
  111947. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  111948. if(info){
  111949. memset(info,0,sizeof(*info));
  111950. _ogg_free(info);
  111951. }
  111952. }
  111953. static void floor1_free_look(vorbis_look_floor *i){
  111954. vorbis_look_floor1 *look=(vorbis_look_floor1 *)i;
  111955. if(look){
  111956. /*fprintf(stderr,"floor 1 bit usage %f:%f (%f total)\n",
  111957. (float)look->phrasebits/look->frames,
  111958. (float)look->postbits/look->frames,
  111959. (float)(look->postbits+look->phrasebits)/look->frames);*/
  111960. memset(look,0,sizeof(*look));
  111961. _ogg_free(look);
  111962. }
  111963. }
  111964. static void floor1_pack (vorbis_info_floor *i,oggpack_buffer *opb){
  111965. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  111966. int j,k;
  111967. int count=0;
  111968. int rangebits;
  111969. int maxposit=info->postlist[1];
  111970. int maxclass=-1;
  111971. /* save out partitions */
  111972. oggpack_write(opb,info->partitions,5); /* only 0 to 31 legal */
  111973. for(j=0;j<info->partitions;j++){
  111974. oggpack_write(opb,info->partitionclass[j],4); /* only 0 to 15 legal */
  111975. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  111976. }
  111977. /* save out partition classes */
  111978. for(j=0;j<maxclass+1;j++){
  111979. oggpack_write(opb,info->class_dim[j]-1,3); /* 1 to 8 */
  111980. oggpack_write(opb,info->class_subs[j],2); /* 0 to 3 */
  111981. if(info->class_subs[j])oggpack_write(opb,info->class_book[j],8);
  111982. for(k=0;k<(1<<info->class_subs[j]);k++)
  111983. oggpack_write(opb,info->class_subbook[j][k]+1,8);
  111984. }
  111985. /* save out the post list */
  111986. oggpack_write(opb,info->mult-1,2); /* only 1,2,3,4 legal now */
  111987. oggpack_write(opb,ilog2(maxposit),4);
  111988. rangebits=ilog2(maxposit);
  111989. for(j=0,k=0;j<info->partitions;j++){
  111990. count+=info->class_dim[info->partitionclass[j]];
  111991. for(;k<count;k++)
  111992. oggpack_write(opb,info->postlist[k+2],rangebits);
  111993. }
  111994. }
  111995. static vorbis_info_floor *floor1_unpack (vorbis_info *vi,oggpack_buffer *opb){
  111996. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111997. int j,k,count=0,maxclass=-1,rangebits;
  111998. vorbis_info_floor1 *info=(vorbis_info_floor1*)_ogg_calloc(1,sizeof(*info));
  111999. /* read partitions */
  112000. info->partitions=oggpack_read(opb,5); /* only 0 to 31 legal */
  112001. for(j=0;j<info->partitions;j++){
  112002. info->partitionclass[j]=oggpack_read(opb,4); /* only 0 to 15 legal */
  112003. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  112004. }
  112005. /* read partition classes */
  112006. for(j=0;j<maxclass+1;j++){
  112007. info->class_dim[j]=oggpack_read(opb,3)+1; /* 1 to 8 */
  112008. info->class_subs[j]=oggpack_read(opb,2); /* 0,1,2,3 bits */
  112009. if(info->class_subs[j]<0)
  112010. goto err_out;
  112011. if(info->class_subs[j])info->class_book[j]=oggpack_read(opb,8);
  112012. if(info->class_book[j]<0 || info->class_book[j]>=ci->books)
  112013. goto err_out;
  112014. for(k=0;k<(1<<info->class_subs[j]);k++){
  112015. info->class_subbook[j][k]=oggpack_read(opb,8)-1;
  112016. if(info->class_subbook[j][k]<-1 || info->class_subbook[j][k]>=ci->books)
  112017. goto err_out;
  112018. }
  112019. }
  112020. /* read the post list */
  112021. info->mult=oggpack_read(opb,2)+1; /* only 1,2,3,4 legal now */
  112022. rangebits=oggpack_read(opb,4);
  112023. for(j=0,k=0;j<info->partitions;j++){
  112024. count+=info->class_dim[info->partitionclass[j]];
  112025. for(;k<count;k++){
  112026. int t=info->postlist[k+2]=oggpack_read(opb,rangebits);
  112027. if(t<0 || t>=(1<<rangebits))
  112028. goto err_out;
  112029. }
  112030. }
  112031. info->postlist[0]=0;
  112032. info->postlist[1]=1<<rangebits;
  112033. return(info);
  112034. err_out:
  112035. floor1_free_info(info);
  112036. return(NULL);
  112037. }
  112038. static int icomp(const void *a,const void *b){
  112039. return(**(int **)a-**(int **)b);
  112040. }
  112041. static vorbis_look_floor *floor1_look(vorbis_dsp_state *vd,
  112042. vorbis_info_floor *in){
  112043. int *sortpointer[VIF_POSIT+2];
  112044. vorbis_info_floor1 *info=(vorbis_info_floor1*)in;
  112045. vorbis_look_floor1 *look=(vorbis_look_floor1*)_ogg_calloc(1,sizeof(*look));
  112046. int i,j,n=0;
  112047. look->vi=info;
  112048. look->n=info->postlist[1];
  112049. /* we drop each position value in-between already decoded values,
  112050. and use linear interpolation to predict each new value past the
  112051. edges. The positions are read in the order of the position
  112052. list... we precompute the bounding positions in the lookup. Of
  112053. course, the neighbors can change (if a position is declined), but
  112054. this is an initial mapping */
  112055. for(i=0;i<info->partitions;i++)n+=info->class_dim[info->partitionclass[i]];
  112056. n+=2;
  112057. look->posts=n;
  112058. /* also store a sorted position index */
  112059. for(i=0;i<n;i++)sortpointer[i]=info->postlist+i;
  112060. qsort(sortpointer,n,sizeof(*sortpointer),icomp);
  112061. /* points from sort order back to range number */
  112062. for(i=0;i<n;i++)look->forward_index[i]=sortpointer[i]-info->postlist;
  112063. /* points from range order to sorted position */
  112064. for(i=0;i<n;i++)look->reverse_index[look->forward_index[i]]=i;
  112065. /* we actually need the post values too */
  112066. for(i=0;i<n;i++)look->sorted_index[i]=info->postlist[look->forward_index[i]];
  112067. /* quantize values to multiplier spec */
  112068. switch(info->mult){
  112069. case 1: /* 1024 -> 256 */
  112070. look->quant_q=256;
  112071. break;
  112072. case 2: /* 1024 -> 128 */
  112073. look->quant_q=128;
  112074. break;
  112075. case 3: /* 1024 -> 86 */
  112076. look->quant_q=86;
  112077. break;
  112078. case 4: /* 1024 -> 64 */
  112079. look->quant_q=64;
  112080. break;
  112081. }
  112082. /* discover our neighbors for decode where we don't use fit flags
  112083. (that would push the neighbors outward) */
  112084. for(i=0;i<n-2;i++){
  112085. int lo=0;
  112086. int hi=1;
  112087. int lx=0;
  112088. int hx=look->n;
  112089. int currentx=info->postlist[i+2];
  112090. for(j=0;j<i+2;j++){
  112091. int x=info->postlist[j];
  112092. if(x>lx && x<currentx){
  112093. lo=j;
  112094. lx=x;
  112095. }
  112096. if(x<hx && x>currentx){
  112097. hi=j;
  112098. hx=x;
  112099. }
  112100. }
  112101. look->loneighbor[i]=lo;
  112102. look->hineighbor[i]=hi;
  112103. }
  112104. return(look);
  112105. }
  112106. static int render_point(int x0,int x1,int y0,int y1,int x){
  112107. y0&=0x7fff; /* mask off flag */
  112108. y1&=0x7fff;
  112109. {
  112110. int dy=y1-y0;
  112111. int adx=x1-x0;
  112112. int ady=abs(dy);
  112113. int err=ady*(x-x0);
  112114. int off=err/adx;
  112115. if(dy<0)return(y0-off);
  112116. return(y0+off);
  112117. }
  112118. }
  112119. static int vorbis_dBquant(const float *x){
  112120. int i= *x*7.3142857f+1023.5f;
  112121. if(i>1023)return(1023);
  112122. if(i<0)return(0);
  112123. return i;
  112124. }
  112125. static float FLOOR1_fromdB_LOOKUP[256]={
  112126. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  112127. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  112128. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  112129. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  112130. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  112131. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  112132. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  112133. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  112134. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  112135. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  112136. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  112137. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  112138. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  112139. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  112140. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  112141. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  112142. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  112143. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  112144. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  112145. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  112146. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  112147. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  112148. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  112149. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  112150. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  112151. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  112152. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  112153. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  112154. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  112155. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  112156. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  112157. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  112158. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  112159. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  112160. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  112161. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  112162. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  112163. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  112164. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  112165. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  112166. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  112167. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  112168. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  112169. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  112170. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  112171. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  112172. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  112173. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  112174. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  112175. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  112176. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  112177. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  112178. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  112179. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  112180. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  112181. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  112182. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  112183. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  112184. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  112185. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  112186. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  112187. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  112188. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  112189. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  112190. };
  112191. static void render_line(int x0,int x1,int y0,int y1,float *d){
  112192. int dy=y1-y0;
  112193. int adx=x1-x0;
  112194. int ady=abs(dy);
  112195. int base=dy/adx;
  112196. int sy=(dy<0?base-1:base+1);
  112197. int x=x0;
  112198. int y=y0;
  112199. int err=0;
  112200. ady-=abs(base*adx);
  112201. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  112202. while(++x<x1){
  112203. err=err+ady;
  112204. if(err>=adx){
  112205. err-=adx;
  112206. y+=sy;
  112207. }else{
  112208. y+=base;
  112209. }
  112210. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  112211. }
  112212. }
  112213. static void render_line0(int x0,int x1,int y0,int y1,int *d){
  112214. int dy=y1-y0;
  112215. int adx=x1-x0;
  112216. int ady=abs(dy);
  112217. int base=dy/adx;
  112218. int sy=(dy<0?base-1:base+1);
  112219. int x=x0;
  112220. int y=y0;
  112221. int err=0;
  112222. ady-=abs(base*adx);
  112223. d[x]=y;
  112224. while(++x<x1){
  112225. err=err+ady;
  112226. if(err>=adx){
  112227. err-=adx;
  112228. y+=sy;
  112229. }else{
  112230. y+=base;
  112231. }
  112232. d[x]=y;
  112233. }
  112234. }
  112235. /* the floor has already been filtered to only include relevant sections */
  112236. static int accumulate_fit(const float *flr,const float *mdct,
  112237. int x0, int x1,lsfit_acc *a,
  112238. int n,vorbis_info_floor1 *info){
  112239. long i;
  112240. 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;
  112241. memset(a,0,sizeof(*a));
  112242. a->x0=x0;
  112243. a->x1=x1;
  112244. if(x1>=n)x1=n-1;
  112245. for(i=x0;i<=x1;i++){
  112246. int quantized=vorbis_dBquant(flr+i);
  112247. if(quantized){
  112248. if(mdct[i]+info->twofitatten>=flr[i]){
  112249. xa += i;
  112250. ya += quantized;
  112251. x2a += i*i;
  112252. y2a += quantized*quantized;
  112253. xya += i*quantized;
  112254. na++;
  112255. }else{
  112256. xb += i;
  112257. yb += quantized;
  112258. x2b += i*i;
  112259. y2b += quantized*quantized;
  112260. xyb += i*quantized;
  112261. nb++;
  112262. }
  112263. }
  112264. }
  112265. xb+=xa;
  112266. yb+=ya;
  112267. x2b+=x2a;
  112268. y2b+=y2a;
  112269. xyb+=xya;
  112270. nb+=na;
  112271. /* weight toward the actually used frequencies if we meet the threshhold */
  112272. {
  112273. int weight=nb*info->twofitweight/(na+1);
  112274. a->xa=xa*weight+xb;
  112275. a->ya=ya*weight+yb;
  112276. a->x2a=x2a*weight+x2b;
  112277. a->y2a=y2a*weight+y2b;
  112278. a->xya=xya*weight+xyb;
  112279. a->an=na*weight+nb;
  112280. }
  112281. return(na);
  112282. }
  112283. static void fit_line(lsfit_acc *a,int fits,int *y0,int *y1){
  112284. long x=0,y=0,x2=0,y2=0,xy=0,an=0,i;
  112285. long x0=a[0].x0;
  112286. long x1=a[fits-1].x1;
  112287. for(i=0;i<fits;i++){
  112288. x+=a[i].xa;
  112289. y+=a[i].ya;
  112290. x2+=a[i].x2a;
  112291. y2+=a[i].y2a;
  112292. xy+=a[i].xya;
  112293. an+=a[i].an;
  112294. }
  112295. if(*y0>=0){
  112296. x+= x0;
  112297. y+= *y0;
  112298. x2+= x0 * x0;
  112299. y2+= *y0 * *y0;
  112300. xy+= *y0 * x0;
  112301. an++;
  112302. }
  112303. if(*y1>=0){
  112304. x+= x1;
  112305. y+= *y1;
  112306. x2+= x1 * x1;
  112307. y2+= *y1 * *y1;
  112308. xy+= *y1 * x1;
  112309. an++;
  112310. }
  112311. if(an){
  112312. /* need 64 bit multiplies, which C doesn't give portably as int */
  112313. double fx=x;
  112314. double fy=y;
  112315. double fx2=x2;
  112316. double fxy=xy;
  112317. double denom=1./(an*fx2-fx*fx);
  112318. double a=(fy*fx2-fxy*fx)*denom;
  112319. double b=(an*fxy-fx*fy)*denom;
  112320. *y0=rint(a+b*x0);
  112321. *y1=rint(a+b*x1);
  112322. /* limit to our range! */
  112323. if(*y0>1023)*y0=1023;
  112324. if(*y1>1023)*y1=1023;
  112325. if(*y0<0)*y0=0;
  112326. if(*y1<0)*y1=0;
  112327. }else{
  112328. *y0=0;
  112329. *y1=0;
  112330. }
  112331. }
  112332. /*static void fit_line_point(lsfit_acc *a,int fits,int *y0,int *y1){
  112333. long y=0;
  112334. int i;
  112335. for(i=0;i<fits && y==0;i++)
  112336. y+=a[i].ya;
  112337. *y0=*y1=y;
  112338. }*/
  112339. static int inspect_error(int x0,int x1,int y0,int y1,const float *mask,
  112340. const float *mdct,
  112341. vorbis_info_floor1 *info){
  112342. int dy=y1-y0;
  112343. int adx=x1-x0;
  112344. int ady=abs(dy);
  112345. int base=dy/adx;
  112346. int sy=(dy<0?base-1:base+1);
  112347. int x=x0;
  112348. int y=y0;
  112349. int err=0;
  112350. int val=vorbis_dBquant(mask+x);
  112351. int mse=0;
  112352. int n=0;
  112353. ady-=abs(base*adx);
  112354. mse=(y-val);
  112355. mse*=mse;
  112356. n++;
  112357. if(mdct[x]+info->twofitatten>=mask[x]){
  112358. if(y+info->maxover<val)return(1);
  112359. if(y-info->maxunder>val)return(1);
  112360. }
  112361. while(++x<x1){
  112362. err=err+ady;
  112363. if(err>=adx){
  112364. err-=adx;
  112365. y+=sy;
  112366. }else{
  112367. y+=base;
  112368. }
  112369. val=vorbis_dBquant(mask+x);
  112370. mse+=((y-val)*(y-val));
  112371. n++;
  112372. if(mdct[x]+info->twofitatten>=mask[x]){
  112373. if(val){
  112374. if(y+info->maxover<val)return(1);
  112375. if(y-info->maxunder>val)return(1);
  112376. }
  112377. }
  112378. }
  112379. if(info->maxover*info->maxover/n>info->maxerr)return(0);
  112380. if(info->maxunder*info->maxunder/n>info->maxerr)return(0);
  112381. if(mse/n>info->maxerr)return(1);
  112382. return(0);
  112383. }
  112384. static int post_Y(int *A,int *B,int pos){
  112385. if(A[pos]<0)
  112386. return B[pos];
  112387. if(B[pos]<0)
  112388. return A[pos];
  112389. return (A[pos]+B[pos])>>1;
  112390. }
  112391. int *floor1_fit(vorbis_block *vb,void *look_,
  112392. const float *logmdct, /* in */
  112393. const float *logmask){
  112394. long i,j;
  112395. vorbis_look_floor1 *look = (vorbis_look_floor1*) look_;
  112396. vorbis_info_floor1 *info=look->vi;
  112397. long n=look->n;
  112398. long posts=look->posts;
  112399. long nonzero=0;
  112400. lsfit_acc fits[VIF_POSIT+1];
  112401. int fit_valueA[VIF_POSIT+2]; /* index by range list position */
  112402. int fit_valueB[VIF_POSIT+2]; /* index by range list position */
  112403. int loneighbor[VIF_POSIT+2]; /* sorted index of range list position (+2) */
  112404. int hineighbor[VIF_POSIT+2];
  112405. int *output=NULL;
  112406. int memo[VIF_POSIT+2];
  112407. for(i=0;i<posts;i++)fit_valueA[i]=-200; /* mark all unused */
  112408. for(i=0;i<posts;i++)fit_valueB[i]=-200; /* mark all unused */
  112409. for(i=0;i<posts;i++)loneighbor[i]=0; /* 0 for the implicit 0 post */
  112410. for(i=0;i<posts;i++)hineighbor[i]=1; /* 1 for the implicit post at n */
  112411. for(i=0;i<posts;i++)memo[i]=-1; /* no neighbor yet */
  112412. /* quantize the relevant floor points and collect them into line fit
  112413. structures (one per minimal division) at the same time */
  112414. if(posts==0){
  112415. nonzero+=accumulate_fit(logmask,logmdct,0,n,fits,n,info);
  112416. }else{
  112417. for(i=0;i<posts-1;i++)
  112418. nonzero+=accumulate_fit(logmask,logmdct,look->sorted_index[i],
  112419. look->sorted_index[i+1],fits+i,
  112420. n,info);
  112421. }
  112422. if(nonzero){
  112423. /* start by fitting the implicit base case.... */
  112424. int y0=-200;
  112425. int y1=-200;
  112426. fit_line(fits,posts-1,&y0,&y1);
  112427. fit_valueA[0]=y0;
  112428. fit_valueB[0]=y0;
  112429. fit_valueB[1]=y1;
  112430. fit_valueA[1]=y1;
  112431. /* Non degenerate case */
  112432. /* start progressive splitting. This is a greedy, non-optimal
  112433. algorithm, but simple and close enough to the best
  112434. answer. */
  112435. for(i=2;i<posts;i++){
  112436. int sortpos=look->reverse_index[i];
  112437. int ln=loneighbor[sortpos];
  112438. int hn=hineighbor[sortpos];
  112439. /* eliminate repeat searches of a particular range with a memo */
  112440. if(memo[ln]!=hn){
  112441. /* haven't performed this error search yet */
  112442. int lsortpos=look->reverse_index[ln];
  112443. int hsortpos=look->reverse_index[hn];
  112444. memo[ln]=hn;
  112445. {
  112446. /* A note: we want to bound/minimize *local*, not global, error */
  112447. int lx=info->postlist[ln];
  112448. int hx=info->postlist[hn];
  112449. int ly=post_Y(fit_valueA,fit_valueB,ln);
  112450. int hy=post_Y(fit_valueA,fit_valueB,hn);
  112451. if(ly==-1 || hy==-1){
  112452. exit(1);
  112453. }
  112454. if(inspect_error(lx,hx,ly,hy,logmask,logmdct,info)){
  112455. /* outside error bounds/begin search area. Split it. */
  112456. int ly0=-200;
  112457. int ly1=-200;
  112458. int hy0=-200;
  112459. int hy1=-200;
  112460. fit_line(fits+lsortpos,sortpos-lsortpos,&ly0,&ly1);
  112461. fit_line(fits+sortpos,hsortpos-sortpos,&hy0,&hy1);
  112462. /* store new edge values */
  112463. fit_valueB[ln]=ly0;
  112464. if(ln==0)fit_valueA[ln]=ly0;
  112465. fit_valueA[i]=ly1;
  112466. fit_valueB[i]=hy0;
  112467. fit_valueA[hn]=hy1;
  112468. if(hn==1)fit_valueB[hn]=hy1;
  112469. if(ly1>=0 || hy0>=0){
  112470. /* store new neighbor values */
  112471. for(j=sortpos-1;j>=0;j--)
  112472. if(hineighbor[j]==hn)
  112473. hineighbor[j]=i;
  112474. else
  112475. break;
  112476. for(j=sortpos+1;j<posts;j++)
  112477. if(loneighbor[j]==ln)
  112478. loneighbor[j]=i;
  112479. else
  112480. break;
  112481. }
  112482. }else{
  112483. fit_valueA[i]=-200;
  112484. fit_valueB[i]=-200;
  112485. }
  112486. }
  112487. }
  112488. }
  112489. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  112490. output[0]=post_Y(fit_valueA,fit_valueB,0);
  112491. output[1]=post_Y(fit_valueA,fit_valueB,1);
  112492. /* fill in posts marked as not using a fit; we will zero
  112493. back out to 'unused' when encoding them so long as curve
  112494. interpolation doesn't force them into use */
  112495. for(i=2;i<posts;i++){
  112496. int ln=look->loneighbor[i-2];
  112497. int hn=look->hineighbor[i-2];
  112498. int x0=info->postlist[ln];
  112499. int x1=info->postlist[hn];
  112500. int y0=output[ln];
  112501. int y1=output[hn];
  112502. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  112503. int vx=post_Y(fit_valueA,fit_valueB,i);
  112504. if(vx>=0 && predicted!=vx){
  112505. output[i]=vx;
  112506. }else{
  112507. output[i]= predicted|0x8000;
  112508. }
  112509. }
  112510. }
  112511. return(output);
  112512. }
  112513. int *floor1_interpolate_fit(vorbis_block *vb,void *look_,
  112514. int *A,int *B,
  112515. int del){
  112516. long i;
  112517. vorbis_look_floor1* look = (vorbis_look_floor1*) look_;
  112518. long posts=look->posts;
  112519. int *output=NULL;
  112520. if(A && B){
  112521. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  112522. for(i=0;i<posts;i++){
  112523. output[i]=((65536-del)*(A[i]&0x7fff)+del*(B[i]&0x7fff)+32768)>>16;
  112524. if(A[i]&0x8000 && B[i]&0x8000)output[i]|=0x8000;
  112525. }
  112526. }
  112527. return(output);
  112528. }
  112529. int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  112530. void*look_,
  112531. int *post,int *ilogmask){
  112532. long i,j;
  112533. vorbis_look_floor1 *look = (vorbis_look_floor1 *) look_;
  112534. vorbis_info_floor1 *info=look->vi;
  112535. long posts=look->posts;
  112536. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  112537. int out[VIF_POSIT+2];
  112538. static_codebook **sbooks=ci->book_param;
  112539. codebook *books=ci->fullbooks;
  112540. static long seq=0;
  112541. /* quantize values to multiplier spec */
  112542. if(post){
  112543. for(i=0;i<posts;i++){
  112544. int val=post[i]&0x7fff;
  112545. switch(info->mult){
  112546. case 1: /* 1024 -> 256 */
  112547. val>>=2;
  112548. break;
  112549. case 2: /* 1024 -> 128 */
  112550. val>>=3;
  112551. break;
  112552. case 3: /* 1024 -> 86 */
  112553. val/=12;
  112554. break;
  112555. case 4: /* 1024 -> 64 */
  112556. val>>=4;
  112557. break;
  112558. }
  112559. post[i]=val | (post[i]&0x8000);
  112560. }
  112561. out[0]=post[0];
  112562. out[1]=post[1];
  112563. /* find prediction values for each post and subtract them */
  112564. for(i=2;i<posts;i++){
  112565. int ln=look->loneighbor[i-2];
  112566. int hn=look->hineighbor[i-2];
  112567. int x0=info->postlist[ln];
  112568. int x1=info->postlist[hn];
  112569. int y0=post[ln];
  112570. int y1=post[hn];
  112571. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  112572. if((post[i]&0x8000) || (predicted==post[i])){
  112573. post[i]=predicted|0x8000; /* in case there was roundoff jitter
  112574. in interpolation */
  112575. out[i]=0;
  112576. }else{
  112577. int headroom=(look->quant_q-predicted<predicted?
  112578. look->quant_q-predicted:predicted);
  112579. int val=post[i]-predicted;
  112580. /* at this point the 'deviation' value is in the range +/- max
  112581. range, but the real, unique range can always be mapped to
  112582. only [0-maxrange). So we want to wrap the deviation into
  112583. this limited range, but do it in the way that least screws
  112584. an essentially gaussian probability distribution. */
  112585. if(val<0)
  112586. if(val<-headroom)
  112587. val=headroom-val-1;
  112588. else
  112589. val=-1-(val<<1);
  112590. else
  112591. if(val>=headroom)
  112592. val= val+headroom;
  112593. else
  112594. val<<=1;
  112595. out[i]=val;
  112596. post[ln]&=0x7fff;
  112597. post[hn]&=0x7fff;
  112598. }
  112599. }
  112600. /* we have everything we need. pack it out */
  112601. /* mark nontrivial floor */
  112602. oggpack_write(opb,1,1);
  112603. /* beginning/end post */
  112604. look->frames++;
  112605. look->postbits+=ilog(look->quant_q-1)*2;
  112606. oggpack_write(opb,out[0],ilog(look->quant_q-1));
  112607. oggpack_write(opb,out[1],ilog(look->quant_q-1));
  112608. /* partition by partition */
  112609. for(i=0,j=2;i<info->partitions;i++){
  112610. int classx=info->partitionclass[i];
  112611. int cdim=info->class_dim[classx];
  112612. int csubbits=info->class_subs[classx];
  112613. int csub=1<<csubbits;
  112614. int bookas[8]={0,0,0,0,0,0,0,0};
  112615. int cval=0;
  112616. int cshift=0;
  112617. int k,l;
  112618. /* generate the partition's first stage cascade value */
  112619. if(csubbits){
  112620. int maxval[8];
  112621. for(k=0;k<csub;k++){
  112622. int booknum=info->class_subbook[classx][k];
  112623. if(booknum<0){
  112624. maxval[k]=1;
  112625. }else{
  112626. maxval[k]=sbooks[info->class_subbook[classx][k]]->entries;
  112627. }
  112628. }
  112629. for(k=0;k<cdim;k++){
  112630. for(l=0;l<csub;l++){
  112631. int val=out[j+k];
  112632. if(val<maxval[l]){
  112633. bookas[k]=l;
  112634. break;
  112635. }
  112636. }
  112637. cval|= bookas[k]<<cshift;
  112638. cshift+=csubbits;
  112639. }
  112640. /* write it */
  112641. look->phrasebits+=
  112642. vorbis_book_encode(books+info->class_book[classx],cval,opb);
  112643. #ifdef TRAIN_FLOOR1
  112644. {
  112645. FILE *of;
  112646. char buffer[80];
  112647. sprintf(buffer,"line_%dx%ld_class%d.vqd",
  112648. vb->pcmend/2,posts-2,class);
  112649. of=fopen(buffer,"a");
  112650. fprintf(of,"%d\n",cval);
  112651. fclose(of);
  112652. }
  112653. #endif
  112654. }
  112655. /* write post values */
  112656. for(k=0;k<cdim;k++){
  112657. int book=info->class_subbook[classx][bookas[k]];
  112658. if(book>=0){
  112659. /* hack to allow training with 'bad' books */
  112660. if(out[j+k]<(books+book)->entries)
  112661. look->postbits+=vorbis_book_encode(books+book,
  112662. out[j+k],opb);
  112663. /*else
  112664. fprintf(stderr,"+!");*/
  112665. #ifdef TRAIN_FLOOR1
  112666. {
  112667. FILE *of;
  112668. char buffer[80];
  112669. sprintf(buffer,"line_%dx%ld_%dsub%d.vqd",
  112670. vb->pcmend/2,posts-2,class,bookas[k]);
  112671. of=fopen(buffer,"a");
  112672. fprintf(of,"%d\n",out[j+k]);
  112673. fclose(of);
  112674. }
  112675. #endif
  112676. }
  112677. }
  112678. j+=cdim;
  112679. }
  112680. {
  112681. /* generate quantized floor equivalent to what we'd unpack in decode */
  112682. /* render the lines */
  112683. int hx=0;
  112684. int lx=0;
  112685. int ly=post[0]*info->mult;
  112686. for(j=1;j<look->posts;j++){
  112687. int current=look->forward_index[j];
  112688. int hy=post[current]&0x7fff;
  112689. if(hy==post[current]){
  112690. hy*=info->mult;
  112691. hx=info->postlist[current];
  112692. render_line0(lx,hx,ly,hy,ilogmask);
  112693. lx=hx;
  112694. ly=hy;
  112695. }
  112696. }
  112697. for(j=hx;j<vb->pcmend/2;j++)ilogmask[j]=ly; /* be certain */
  112698. seq++;
  112699. return(1);
  112700. }
  112701. }else{
  112702. oggpack_write(opb,0,1);
  112703. memset(ilogmask,0,vb->pcmend/2*sizeof(*ilogmask));
  112704. seq++;
  112705. return(0);
  112706. }
  112707. }
  112708. static void *floor1_inverse1(vorbis_block *vb,vorbis_look_floor *in){
  112709. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  112710. vorbis_info_floor1 *info=look->vi;
  112711. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  112712. int i,j,k;
  112713. codebook *books=ci->fullbooks;
  112714. /* unpack wrapped/predicted values from stream */
  112715. if(oggpack_read(&vb->opb,1)==1){
  112716. int *fit_value=(int*)_vorbis_block_alloc(vb,(look->posts)*sizeof(*fit_value));
  112717. fit_value[0]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  112718. fit_value[1]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  112719. /* partition by partition */
  112720. for(i=0,j=2;i<info->partitions;i++){
  112721. int classx=info->partitionclass[i];
  112722. int cdim=info->class_dim[classx];
  112723. int csubbits=info->class_subs[classx];
  112724. int csub=1<<csubbits;
  112725. int cval=0;
  112726. /* decode the partition's first stage cascade value */
  112727. if(csubbits){
  112728. cval=vorbis_book_decode(books+info->class_book[classx],&vb->opb);
  112729. if(cval==-1)goto eop;
  112730. }
  112731. for(k=0;k<cdim;k++){
  112732. int book=info->class_subbook[classx][cval&(csub-1)];
  112733. cval>>=csubbits;
  112734. if(book>=0){
  112735. if((fit_value[j+k]=vorbis_book_decode(books+book,&vb->opb))==-1)
  112736. goto eop;
  112737. }else{
  112738. fit_value[j+k]=0;
  112739. }
  112740. }
  112741. j+=cdim;
  112742. }
  112743. /* unwrap positive values and reconsitute via linear interpolation */
  112744. for(i=2;i<look->posts;i++){
  112745. int predicted=render_point(info->postlist[look->loneighbor[i-2]],
  112746. info->postlist[look->hineighbor[i-2]],
  112747. fit_value[look->loneighbor[i-2]],
  112748. fit_value[look->hineighbor[i-2]],
  112749. info->postlist[i]);
  112750. int hiroom=look->quant_q-predicted;
  112751. int loroom=predicted;
  112752. int room=(hiroom<loroom?hiroom:loroom)<<1;
  112753. int val=fit_value[i];
  112754. if(val){
  112755. if(val>=room){
  112756. if(hiroom>loroom){
  112757. val = val-loroom;
  112758. }else{
  112759. val = -1-(val-hiroom);
  112760. }
  112761. }else{
  112762. if(val&1){
  112763. val= -((val+1)>>1);
  112764. }else{
  112765. val>>=1;
  112766. }
  112767. }
  112768. fit_value[i]=val+predicted;
  112769. fit_value[look->loneighbor[i-2]]&=0x7fff;
  112770. fit_value[look->hineighbor[i-2]]&=0x7fff;
  112771. }else{
  112772. fit_value[i]=predicted|0x8000;
  112773. }
  112774. }
  112775. return(fit_value);
  112776. }
  112777. eop:
  112778. return(NULL);
  112779. }
  112780. static int floor1_inverse2(vorbis_block *vb,vorbis_look_floor *in,void *memo,
  112781. float *out){
  112782. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  112783. vorbis_info_floor1 *info=look->vi;
  112784. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  112785. int n=ci->blocksizes[vb->W]/2;
  112786. int j;
  112787. if(memo){
  112788. /* render the lines */
  112789. int *fit_value=(int *)memo;
  112790. int hx=0;
  112791. int lx=0;
  112792. int ly=fit_value[0]*info->mult;
  112793. for(j=1;j<look->posts;j++){
  112794. int current=look->forward_index[j];
  112795. int hy=fit_value[current]&0x7fff;
  112796. if(hy==fit_value[current]){
  112797. hy*=info->mult;
  112798. hx=info->postlist[current];
  112799. render_line(lx,hx,ly,hy,out);
  112800. lx=hx;
  112801. ly=hy;
  112802. }
  112803. }
  112804. for(j=hx;j<n;j++)out[j]*=FLOOR1_fromdB_LOOKUP[ly]; /* be certain */
  112805. return(1);
  112806. }
  112807. memset(out,0,sizeof(*out)*n);
  112808. return(0);
  112809. }
  112810. /* export hooks */
  112811. vorbis_func_floor floor1_exportbundle={
  112812. &floor1_pack,&floor1_unpack,&floor1_look,&floor1_free_info,
  112813. &floor1_free_look,&floor1_inverse1,&floor1_inverse2
  112814. };
  112815. #endif
  112816. /*** End of inlined file: floor1.c ***/
  112817. /*** Start of inlined file: info.c ***/
  112818. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112819. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112820. // tasks..
  112821. #if JUCE_MSVC
  112822. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112823. #endif
  112824. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112825. #if JUCE_USE_OGGVORBIS
  112826. /* general handling of the header and the vorbis_info structure (and
  112827. substructures) */
  112828. #include <stdlib.h>
  112829. #include <string.h>
  112830. #include <ctype.h>
  112831. static void _v_writestring(oggpack_buffer *o, const char *s, int bytes){
  112832. while(bytes--){
  112833. oggpack_write(o,*s++,8);
  112834. }
  112835. }
  112836. static void _v_readstring(oggpack_buffer *o,char *buf,int bytes){
  112837. while(bytes--){
  112838. *buf++=oggpack_read(o,8);
  112839. }
  112840. }
  112841. void vorbis_comment_init(vorbis_comment *vc){
  112842. memset(vc,0,sizeof(*vc));
  112843. }
  112844. void vorbis_comment_add(vorbis_comment *vc,char *comment){
  112845. vc->user_comments=(char**)_ogg_realloc(vc->user_comments,
  112846. (vc->comments+2)*sizeof(*vc->user_comments));
  112847. vc->comment_lengths=(int*)_ogg_realloc(vc->comment_lengths,
  112848. (vc->comments+2)*sizeof(*vc->comment_lengths));
  112849. vc->comment_lengths[vc->comments]=strlen(comment);
  112850. vc->user_comments[vc->comments]=(char*)_ogg_malloc(vc->comment_lengths[vc->comments]+1);
  112851. strcpy(vc->user_comments[vc->comments], comment);
  112852. vc->comments++;
  112853. vc->user_comments[vc->comments]=NULL;
  112854. }
  112855. void vorbis_comment_add_tag(vorbis_comment *vc, const char *tag, char *contents){
  112856. char *comment=(char*)alloca(strlen(tag)+strlen(contents)+2); /* +2 for = and \0 */
  112857. strcpy(comment, tag);
  112858. strcat(comment, "=");
  112859. strcat(comment, contents);
  112860. vorbis_comment_add(vc, comment);
  112861. }
  112862. /* This is more or less the same as strncasecmp - but that doesn't exist
  112863. * everywhere, and this is a fairly trivial function, so we include it */
  112864. static int tagcompare(const char *s1, const char *s2, int n){
  112865. int c=0;
  112866. while(c < n){
  112867. if(toupper(s1[c]) != toupper(s2[c]))
  112868. return !0;
  112869. c++;
  112870. }
  112871. return 0;
  112872. }
  112873. char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count){
  112874. long i;
  112875. int found = 0;
  112876. int taglen = strlen(tag)+1; /* +1 for the = we append */
  112877. char *fulltag = (char*)alloca(taglen+ 1);
  112878. strcpy(fulltag, tag);
  112879. strcat(fulltag, "=");
  112880. for(i=0;i<vc->comments;i++){
  112881. if(!tagcompare(vc->user_comments[i], fulltag, taglen)){
  112882. if(count == found)
  112883. /* We return a pointer to the data, not a copy */
  112884. return vc->user_comments[i] + taglen;
  112885. else
  112886. found++;
  112887. }
  112888. }
  112889. return NULL; /* didn't find anything */
  112890. }
  112891. int vorbis_comment_query_count(vorbis_comment *vc, char *tag){
  112892. int i,count=0;
  112893. int taglen = strlen(tag)+1; /* +1 for the = we append */
  112894. char *fulltag = (char*)alloca(taglen+1);
  112895. strcpy(fulltag,tag);
  112896. strcat(fulltag, "=");
  112897. for(i=0;i<vc->comments;i++){
  112898. if(!tagcompare(vc->user_comments[i], fulltag, taglen))
  112899. count++;
  112900. }
  112901. return count;
  112902. }
  112903. void vorbis_comment_clear(vorbis_comment *vc){
  112904. if(vc){
  112905. long i;
  112906. for(i=0;i<vc->comments;i++)
  112907. if(vc->user_comments[i])_ogg_free(vc->user_comments[i]);
  112908. if(vc->user_comments)_ogg_free(vc->user_comments);
  112909. if(vc->comment_lengths)_ogg_free(vc->comment_lengths);
  112910. if(vc->vendor)_ogg_free(vc->vendor);
  112911. }
  112912. memset(vc,0,sizeof(*vc));
  112913. }
  112914. /* blocksize 0 is guaranteed to be short, 1 is guarantted to be long.
  112915. They may be equal, but short will never ge greater than long */
  112916. int vorbis_info_blocksize(vorbis_info *vi,int zo){
  112917. codec_setup_info *ci = (codec_setup_info*)vi->codec_setup;
  112918. return ci ? ci->blocksizes[zo] : -1;
  112919. }
  112920. /* used by synthesis, which has a full, alloced vi */
  112921. void vorbis_info_init(vorbis_info *vi){
  112922. memset(vi,0,sizeof(*vi));
  112923. vi->codec_setup=_ogg_calloc(1,sizeof(codec_setup_info));
  112924. }
  112925. void vorbis_info_clear(vorbis_info *vi){
  112926. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112927. int i;
  112928. if(ci){
  112929. for(i=0;i<ci->modes;i++)
  112930. if(ci->mode_param[i])_ogg_free(ci->mode_param[i]);
  112931. for(i=0;i<ci->maps;i++) /* unpack does the range checking */
  112932. _mapping_P[ci->map_type[i]]->free_info(ci->map_param[i]);
  112933. for(i=0;i<ci->floors;i++) /* unpack does the range checking */
  112934. _floor_P[ci->floor_type[i]]->free_info(ci->floor_param[i]);
  112935. for(i=0;i<ci->residues;i++) /* unpack does the range checking */
  112936. _residue_P[ci->residue_type[i]]->free_info(ci->residue_param[i]);
  112937. for(i=0;i<ci->books;i++){
  112938. if(ci->book_param[i]){
  112939. /* knows if the book was not alloced */
  112940. vorbis_staticbook_destroy(ci->book_param[i]);
  112941. }
  112942. if(ci->fullbooks)
  112943. vorbis_book_clear(ci->fullbooks+i);
  112944. }
  112945. if(ci->fullbooks)
  112946. _ogg_free(ci->fullbooks);
  112947. for(i=0;i<ci->psys;i++)
  112948. _vi_psy_free(ci->psy_param[i]);
  112949. _ogg_free(ci);
  112950. }
  112951. memset(vi,0,sizeof(*vi));
  112952. }
  112953. /* Header packing/unpacking ********************************************/
  112954. static int _vorbis_unpack_info(vorbis_info *vi,oggpack_buffer *opb){
  112955. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112956. if(!ci)return(OV_EFAULT);
  112957. vi->version=oggpack_read(opb,32);
  112958. if(vi->version!=0)return(OV_EVERSION);
  112959. vi->channels=oggpack_read(opb,8);
  112960. vi->rate=oggpack_read(opb,32);
  112961. vi->bitrate_upper=oggpack_read(opb,32);
  112962. vi->bitrate_nominal=oggpack_read(opb,32);
  112963. vi->bitrate_lower=oggpack_read(opb,32);
  112964. ci->blocksizes[0]=1<<oggpack_read(opb,4);
  112965. ci->blocksizes[1]=1<<oggpack_read(opb,4);
  112966. if(vi->rate<1)goto err_out;
  112967. if(vi->channels<1)goto err_out;
  112968. if(ci->blocksizes[0]<8)goto err_out;
  112969. if(ci->blocksizes[1]<ci->blocksizes[0])goto err_out;
  112970. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  112971. return(0);
  112972. err_out:
  112973. vorbis_info_clear(vi);
  112974. return(OV_EBADHEADER);
  112975. }
  112976. static int _vorbis_unpack_comment(vorbis_comment *vc,oggpack_buffer *opb){
  112977. int i;
  112978. int vendorlen=oggpack_read(opb,32);
  112979. if(vendorlen<0)goto err_out;
  112980. vc->vendor=(char*)_ogg_calloc(vendorlen+1,1);
  112981. _v_readstring(opb,vc->vendor,vendorlen);
  112982. vc->comments=oggpack_read(opb,32);
  112983. if(vc->comments<0)goto err_out;
  112984. vc->user_comments=(char**)_ogg_calloc(vc->comments+1,sizeof(*vc->user_comments));
  112985. vc->comment_lengths=(int*)_ogg_calloc(vc->comments+1, sizeof(*vc->comment_lengths));
  112986. for(i=0;i<vc->comments;i++){
  112987. int len=oggpack_read(opb,32);
  112988. if(len<0)goto err_out;
  112989. vc->comment_lengths[i]=len;
  112990. vc->user_comments[i]=(char*)_ogg_calloc(len+1,1);
  112991. _v_readstring(opb,vc->user_comments[i],len);
  112992. }
  112993. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  112994. return(0);
  112995. err_out:
  112996. vorbis_comment_clear(vc);
  112997. return(OV_EBADHEADER);
  112998. }
  112999. /* all of the real encoding details are here. The modes, books,
  113000. everything */
  113001. static int _vorbis_unpack_books(vorbis_info *vi,oggpack_buffer *opb){
  113002. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113003. int i;
  113004. if(!ci)return(OV_EFAULT);
  113005. /* codebooks */
  113006. ci->books=oggpack_read(opb,8)+1;
  113007. /*ci->book_param=_ogg_calloc(ci->books,sizeof(*ci->book_param));*/
  113008. for(i=0;i<ci->books;i++){
  113009. ci->book_param[i]=(static_codebook*)_ogg_calloc(1,sizeof(*ci->book_param[i]));
  113010. if(vorbis_staticbook_unpack(opb,ci->book_param[i]))goto err_out;
  113011. }
  113012. /* time backend settings; hooks are unused */
  113013. {
  113014. int times=oggpack_read(opb,6)+1;
  113015. for(i=0;i<times;i++){
  113016. int test=oggpack_read(opb,16);
  113017. if(test<0 || test>=VI_TIMEB)goto err_out;
  113018. }
  113019. }
  113020. /* floor backend settings */
  113021. ci->floors=oggpack_read(opb,6)+1;
  113022. /*ci->floor_type=_ogg_malloc(ci->floors*sizeof(*ci->floor_type));*/
  113023. /*ci->floor_param=_ogg_calloc(ci->floors,sizeof(void *));*/
  113024. for(i=0;i<ci->floors;i++){
  113025. ci->floor_type[i]=oggpack_read(opb,16);
  113026. if(ci->floor_type[i]<0 || ci->floor_type[i]>=VI_FLOORB)goto err_out;
  113027. ci->floor_param[i]=_floor_P[ci->floor_type[i]]->unpack(vi,opb);
  113028. if(!ci->floor_param[i])goto err_out;
  113029. }
  113030. /* residue backend settings */
  113031. ci->residues=oggpack_read(opb,6)+1;
  113032. /*ci->residue_type=_ogg_malloc(ci->residues*sizeof(*ci->residue_type));*/
  113033. /*ci->residue_param=_ogg_calloc(ci->residues,sizeof(void *));*/
  113034. for(i=0;i<ci->residues;i++){
  113035. ci->residue_type[i]=oggpack_read(opb,16);
  113036. if(ci->residue_type[i]<0 || ci->residue_type[i]>=VI_RESB)goto err_out;
  113037. ci->residue_param[i]=_residue_P[ci->residue_type[i]]->unpack(vi,opb);
  113038. if(!ci->residue_param[i])goto err_out;
  113039. }
  113040. /* map backend settings */
  113041. ci->maps=oggpack_read(opb,6)+1;
  113042. /*ci->map_type=_ogg_malloc(ci->maps*sizeof(*ci->map_type));*/
  113043. /*ci->map_param=_ogg_calloc(ci->maps,sizeof(void *));*/
  113044. for(i=0;i<ci->maps;i++){
  113045. ci->map_type[i]=oggpack_read(opb,16);
  113046. if(ci->map_type[i]<0 || ci->map_type[i]>=VI_MAPB)goto err_out;
  113047. ci->map_param[i]=_mapping_P[ci->map_type[i]]->unpack(vi,opb);
  113048. if(!ci->map_param[i])goto err_out;
  113049. }
  113050. /* mode settings */
  113051. ci->modes=oggpack_read(opb,6)+1;
  113052. /*vi->mode_param=_ogg_calloc(vi->modes,sizeof(void *));*/
  113053. for(i=0;i<ci->modes;i++){
  113054. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*ci->mode_param[i]));
  113055. ci->mode_param[i]->blockflag=oggpack_read(opb,1);
  113056. ci->mode_param[i]->windowtype=oggpack_read(opb,16);
  113057. ci->mode_param[i]->transformtype=oggpack_read(opb,16);
  113058. ci->mode_param[i]->mapping=oggpack_read(opb,8);
  113059. if(ci->mode_param[i]->windowtype>=VI_WINDOWB)goto err_out;
  113060. if(ci->mode_param[i]->transformtype>=VI_WINDOWB)goto err_out;
  113061. if(ci->mode_param[i]->mapping>=ci->maps)goto err_out;
  113062. }
  113063. if(oggpack_read(opb,1)!=1)goto err_out; /* top level EOP check */
  113064. return(0);
  113065. err_out:
  113066. vorbis_info_clear(vi);
  113067. return(OV_EBADHEADER);
  113068. }
  113069. /* The Vorbis header is in three packets; the initial small packet in
  113070. the first page that identifies basic parameters, a second packet
  113071. with bitstream comments and a third packet that holds the
  113072. codebook. */
  113073. int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,ogg_packet *op){
  113074. oggpack_buffer opb;
  113075. if(op){
  113076. oggpack_readinit(&opb,op->packet,op->bytes);
  113077. /* Which of the three types of header is this? */
  113078. /* Also verify header-ness, vorbis */
  113079. {
  113080. char buffer[6];
  113081. int packtype=oggpack_read(&opb,8);
  113082. memset(buffer,0,6);
  113083. _v_readstring(&opb,buffer,6);
  113084. if(memcmp(buffer,"vorbis",6)){
  113085. /* not a vorbis header */
  113086. return(OV_ENOTVORBIS);
  113087. }
  113088. switch(packtype){
  113089. case 0x01: /* least significant *bit* is read first */
  113090. if(!op->b_o_s){
  113091. /* Not the initial packet */
  113092. return(OV_EBADHEADER);
  113093. }
  113094. if(vi->rate!=0){
  113095. /* previously initialized info header */
  113096. return(OV_EBADHEADER);
  113097. }
  113098. return(_vorbis_unpack_info(vi,&opb));
  113099. case 0x03: /* least significant *bit* is read first */
  113100. if(vi->rate==0){
  113101. /* um... we didn't get the initial header */
  113102. return(OV_EBADHEADER);
  113103. }
  113104. return(_vorbis_unpack_comment(vc,&opb));
  113105. case 0x05: /* least significant *bit* is read first */
  113106. if(vi->rate==0 || vc->vendor==NULL){
  113107. /* um... we didn;t get the initial header or comments yet */
  113108. return(OV_EBADHEADER);
  113109. }
  113110. return(_vorbis_unpack_books(vi,&opb));
  113111. default:
  113112. /* Not a valid vorbis header type */
  113113. return(OV_EBADHEADER);
  113114. break;
  113115. }
  113116. }
  113117. }
  113118. return(OV_EBADHEADER);
  113119. }
  113120. /* pack side **********************************************************/
  113121. static int _vorbis_pack_info(oggpack_buffer *opb,vorbis_info *vi){
  113122. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113123. if(!ci)return(OV_EFAULT);
  113124. /* preamble */
  113125. oggpack_write(opb,0x01,8);
  113126. _v_writestring(opb,"vorbis", 6);
  113127. /* basic information about the stream */
  113128. oggpack_write(opb,0x00,32);
  113129. oggpack_write(opb,vi->channels,8);
  113130. oggpack_write(opb,vi->rate,32);
  113131. oggpack_write(opb,vi->bitrate_upper,32);
  113132. oggpack_write(opb,vi->bitrate_nominal,32);
  113133. oggpack_write(opb,vi->bitrate_lower,32);
  113134. oggpack_write(opb,ilog2(ci->blocksizes[0]),4);
  113135. oggpack_write(opb,ilog2(ci->blocksizes[1]),4);
  113136. oggpack_write(opb,1,1);
  113137. return(0);
  113138. }
  113139. static int _vorbis_pack_comment(oggpack_buffer *opb,vorbis_comment *vc){
  113140. char temp[]="Xiph.Org libVorbis I 20050304";
  113141. int bytes = strlen(temp);
  113142. /* preamble */
  113143. oggpack_write(opb,0x03,8);
  113144. _v_writestring(opb,"vorbis", 6);
  113145. /* vendor */
  113146. oggpack_write(opb,bytes,32);
  113147. _v_writestring(opb,temp, bytes);
  113148. /* comments */
  113149. oggpack_write(opb,vc->comments,32);
  113150. if(vc->comments){
  113151. int i;
  113152. for(i=0;i<vc->comments;i++){
  113153. if(vc->user_comments[i]){
  113154. oggpack_write(opb,vc->comment_lengths[i],32);
  113155. _v_writestring(opb,vc->user_comments[i], vc->comment_lengths[i]);
  113156. }else{
  113157. oggpack_write(opb,0,32);
  113158. }
  113159. }
  113160. }
  113161. oggpack_write(opb,1,1);
  113162. return(0);
  113163. }
  113164. static int _vorbis_pack_books(oggpack_buffer *opb,vorbis_info *vi){
  113165. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113166. int i;
  113167. if(!ci)return(OV_EFAULT);
  113168. oggpack_write(opb,0x05,8);
  113169. _v_writestring(opb,"vorbis", 6);
  113170. /* books */
  113171. oggpack_write(opb,ci->books-1,8);
  113172. for(i=0;i<ci->books;i++)
  113173. if(vorbis_staticbook_pack(ci->book_param[i],opb))goto err_out;
  113174. /* times; hook placeholders */
  113175. oggpack_write(opb,0,6);
  113176. oggpack_write(opb,0,16);
  113177. /* floors */
  113178. oggpack_write(opb,ci->floors-1,6);
  113179. for(i=0;i<ci->floors;i++){
  113180. oggpack_write(opb,ci->floor_type[i],16);
  113181. if(_floor_P[ci->floor_type[i]]->pack)
  113182. _floor_P[ci->floor_type[i]]->pack(ci->floor_param[i],opb);
  113183. else
  113184. goto err_out;
  113185. }
  113186. /* residues */
  113187. oggpack_write(opb,ci->residues-1,6);
  113188. for(i=0;i<ci->residues;i++){
  113189. oggpack_write(opb,ci->residue_type[i],16);
  113190. _residue_P[ci->residue_type[i]]->pack(ci->residue_param[i],opb);
  113191. }
  113192. /* maps */
  113193. oggpack_write(opb,ci->maps-1,6);
  113194. for(i=0;i<ci->maps;i++){
  113195. oggpack_write(opb,ci->map_type[i],16);
  113196. _mapping_P[ci->map_type[i]]->pack(vi,ci->map_param[i],opb);
  113197. }
  113198. /* modes */
  113199. oggpack_write(opb,ci->modes-1,6);
  113200. for(i=0;i<ci->modes;i++){
  113201. oggpack_write(opb,ci->mode_param[i]->blockflag,1);
  113202. oggpack_write(opb,ci->mode_param[i]->windowtype,16);
  113203. oggpack_write(opb,ci->mode_param[i]->transformtype,16);
  113204. oggpack_write(opb,ci->mode_param[i]->mapping,8);
  113205. }
  113206. oggpack_write(opb,1,1);
  113207. return(0);
  113208. err_out:
  113209. return(-1);
  113210. }
  113211. int vorbis_commentheader_out(vorbis_comment *vc,
  113212. ogg_packet *op){
  113213. oggpack_buffer opb;
  113214. oggpack_writeinit(&opb);
  113215. if(_vorbis_pack_comment(&opb,vc)) return OV_EIMPL;
  113216. op->packet = (unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  113217. memcpy(op->packet, opb.buffer, oggpack_bytes(&opb));
  113218. op->bytes=oggpack_bytes(&opb);
  113219. op->b_o_s=0;
  113220. op->e_o_s=0;
  113221. op->granulepos=0;
  113222. op->packetno=1;
  113223. return 0;
  113224. }
  113225. int vorbis_analysis_headerout(vorbis_dsp_state *v,
  113226. vorbis_comment *vc,
  113227. ogg_packet *op,
  113228. ogg_packet *op_comm,
  113229. ogg_packet *op_code){
  113230. int ret=OV_EIMPL;
  113231. vorbis_info *vi=v->vi;
  113232. oggpack_buffer opb;
  113233. private_state *b=(private_state*)v->backend_state;
  113234. if(!b){
  113235. ret=OV_EFAULT;
  113236. goto err_out;
  113237. }
  113238. /* first header packet **********************************************/
  113239. oggpack_writeinit(&opb);
  113240. if(_vorbis_pack_info(&opb,vi))goto err_out;
  113241. /* build the packet */
  113242. if(b->header)_ogg_free(b->header);
  113243. b->header=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  113244. memcpy(b->header,opb.buffer,oggpack_bytes(&opb));
  113245. op->packet=b->header;
  113246. op->bytes=oggpack_bytes(&opb);
  113247. op->b_o_s=1;
  113248. op->e_o_s=0;
  113249. op->granulepos=0;
  113250. op->packetno=0;
  113251. /* second header packet (comments) **********************************/
  113252. oggpack_reset(&opb);
  113253. if(_vorbis_pack_comment(&opb,vc))goto err_out;
  113254. if(b->header1)_ogg_free(b->header1);
  113255. b->header1=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  113256. memcpy(b->header1,opb.buffer,oggpack_bytes(&opb));
  113257. op_comm->packet=b->header1;
  113258. op_comm->bytes=oggpack_bytes(&opb);
  113259. op_comm->b_o_s=0;
  113260. op_comm->e_o_s=0;
  113261. op_comm->granulepos=0;
  113262. op_comm->packetno=1;
  113263. /* third header packet (modes/codebooks) ****************************/
  113264. oggpack_reset(&opb);
  113265. if(_vorbis_pack_books(&opb,vi))goto err_out;
  113266. if(b->header2)_ogg_free(b->header2);
  113267. b->header2=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  113268. memcpy(b->header2,opb.buffer,oggpack_bytes(&opb));
  113269. op_code->packet=b->header2;
  113270. op_code->bytes=oggpack_bytes(&opb);
  113271. op_code->b_o_s=0;
  113272. op_code->e_o_s=0;
  113273. op_code->granulepos=0;
  113274. op_code->packetno=2;
  113275. oggpack_writeclear(&opb);
  113276. return(0);
  113277. err_out:
  113278. oggpack_writeclear(&opb);
  113279. memset(op,0,sizeof(*op));
  113280. memset(op_comm,0,sizeof(*op_comm));
  113281. memset(op_code,0,sizeof(*op_code));
  113282. if(b->header)_ogg_free(b->header);
  113283. if(b->header1)_ogg_free(b->header1);
  113284. if(b->header2)_ogg_free(b->header2);
  113285. b->header=NULL;
  113286. b->header1=NULL;
  113287. b->header2=NULL;
  113288. return(ret);
  113289. }
  113290. double vorbis_granule_time(vorbis_dsp_state *v,ogg_int64_t granulepos){
  113291. if(granulepos>=0)
  113292. return((double)granulepos/v->vi->rate);
  113293. return(-1);
  113294. }
  113295. #endif
  113296. /*** End of inlined file: info.c ***/
  113297. /*** Start of inlined file: lpc.c ***/
  113298. /* Some of these routines (autocorrelator, LPC coefficient estimator)
  113299. are derived from code written by Jutta Degener and Carsten Bormann;
  113300. thus we include their copyright below. The entirety of this file
  113301. is freely redistributable on the condition that both of these
  113302. copyright notices are preserved without modification. */
  113303. /* Preserved Copyright: *********************************************/
  113304. /* Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann,
  113305. Technische Universita"t Berlin
  113306. Any use of this software is permitted provided that this notice is not
  113307. removed and that neither the authors nor the Technische Universita"t
  113308. Berlin are deemed to have made any representations as to the
  113309. suitability of this software for any purpose nor are held responsible
  113310. for any defects of this software. THERE IS ABSOLUTELY NO WARRANTY FOR
  113311. THIS SOFTWARE.
  113312. As a matter of courtesy, the authors request to be informed about uses
  113313. this software has found, about bugs in this software, and about any
  113314. improvements that may be of general interest.
  113315. Berlin, 28.11.1994
  113316. Jutta Degener
  113317. Carsten Bormann
  113318. *********************************************************************/
  113319. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113320. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113321. // tasks..
  113322. #if JUCE_MSVC
  113323. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113324. #endif
  113325. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113326. #if JUCE_USE_OGGVORBIS
  113327. #include <stdlib.h>
  113328. #include <string.h>
  113329. #include <math.h>
  113330. /* Autocorrelation LPC coeff generation algorithm invented by
  113331. N. Levinson in 1947, modified by J. Durbin in 1959. */
  113332. /* Input : n elements of time doamin data
  113333. Output: m lpc coefficients, excitation energy */
  113334. float vorbis_lpc_from_data(float *data,float *lpci,int n,int m){
  113335. double *aut=(double*)alloca(sizeof(*aut)*(m+1));
  113336. double *lpc=(double*)alloca(sizeof(*lpc)*(m));
  113337. double error;
  113338. int i,j;
  113339. /* autocorrelation, p+1 lag coefficients */
  113340. j=m+1;
  113341. while(j--){
  113342. double d=0; /* double needed for accumulator depth */
  113343. for(i=j;i<n;i++)d+=(double)data[i]*data[i-j];
  113344. aut[j]=d;
  113345. }
  113346. /* Generate lpc coefficients from autocorr values */
  113347. error=aut[0];
  113348. for(i=0;i<m;i++){
  113349. double r= -aut[i+1];
  113350. if(error==0){
  113351. memset(lpci,0,m*sizeof(*lpci));
  113352. return 0;
  113353. }
  113354. /* Sum up this iteration's reflection coefficient; note that in
  113355. Vorbis we don't save it. If anyone wants to recycle this code
  113356. and needs reflection coefficients, save the results of 'r' from
  113357. each iteration. */
  113358. for(j=0;j<i;j++)r-=lpc[j]*aut[i-j];
  113359. r/=error;
  113360. /* Update LPC coefficients and total error */
  113361. lpc[i]=r;
  113362. for(j=0;j<i/2;j++){
  113363. double tmp=lpc[j];
  113364. lpc[j]+=r*lpc[i-1-j];
  113365. lpc[i-1-j]+=r*tmp;
  113366. }
  113367. if(i%2)lpc[j]+=lpc[j]*r;
  113368. error*=1.f-r*r;
  113369. }
  113370. for(j=0;j<m;j++)lpci[j]=(float)lpc[j];
  113371. /* we need the error value to know how big an impulse to hit the
  113372. filter with later */
  113373. return error;
  113374. }
  113375. void vorbis_lpc_predict(float *coeff,float *prime,int m,
  113376. float *data,long n){
  113377. /* in: coeff[0...m-1] LPC coefficients
  113378. prime[0...m-1] initial values (allocated size of n+m-1)
  113379. out: data[0...n-1] data samples */
  113380. long i,j,o,p;
  113381. float y;
  113382. float *work=(float*)alloca(sizeof(*work)*(m+n));
  113383. if(!prime)
  113384. for(i=0;i<m;i++)
  113385. work[i]=0.f;
  113386. else
  113387. for(i=0;i<m;i++)
  113388. work[i]=prime[i];
  113389. for(i=0;i<n;i++){
  113390. y=0;
  113391. o=i;
  113392. p=m;
  113393. for(j=0;j<m;j++)
  113394. y-=work[o++]*coeff[--p];
  113395. data[i]=work[o]=y;
  113396. }
  113397. }
  113398. #endif
  113399. /*** End of inlined file: lpc.c ***/
  113400. /*** Start of inlined file: lsp.c ***/
  113401. /* Note that the lpc-lsp conversion finds the roots of polynomial with
  113402. an iterative root polisher (CACM algorithm 283). It *is* possible
  113403. to confuse this algorithm into not converging; that should only
  113404. happen with absurdly closely spaced roots (very sharp peaks in the
  113405. LPC f response) which in turn should be impossible in our use of
  113406. the code. If this *does* happen anyway, it's a bug in the floor
  113407. finder; find the cause of the confusion (probably a single bin
  113408. spike or accidental near-float-limit resolution problems) and
  113409. correct it. */
  113410. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113411. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113412. // tasks..
  113413. #if JUCE_MSVC
  113414. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113415. #endif
  113416. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113417. #if JUCE_USE_OGGVORBIS
  113418. #include <math.h>
  113419. #include <string.h>
  113420. #include <stdlib.h>
  113421. /*** Start of inlined file: lookup.h ***/
  113422. #ifndef _V_LOOKUP_H_
  113423. #ifdef FLOAT_LOOKUP
  113424. extern float vorbis_coslook(float a);
  113425. extern float vorbis_invsqlook(float a);
  113426. extern float vorbis_invsq2explook(int a);
  113427. extern float vorbis_fromdBlook(float a);
  113428. #endif
  113429. #ifdef INT_LOOKUP
  113430. extern long vorbis_invsqlook_i(long a,long e);
  113431. extern long vorbis_coslook_i(long a);
  113432. extern float vorbis_fromdBlook_i(long a);
  113433. #endif
  113434. #endif
  113435. /*** End of inlined file: lookup.h ***/
  113436. /* three possible LSP to f curve functions; the exact computation
  113437. (float), a lookup based float implementation, and an integer
  113438. implementation. The float lookup is likely the optimal choice on
  113439. any machine with an FPU. The integer implementation is *not* fixed
  113440. point (due to the need for a large dynamic range and thus a
  113441. seperately tracked exponent) and thus much more complex than the
  113442. relatively simple float implementations. It's mostly for future
  113443. work on a fully fixed point implementation for processors like the
  113444. ARM family. */
  113445. /* undefine both for the 'old' but more precise implementation */
  113446. #define FLOAT_LOOKUP
  113447. #undef INT_LOOKUP
  113448. #ifdef FLOAT_LOOKUP
  113449. /*** Start of inlined file: lookup.c ***/
  113450. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113451. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113452. // tasks..
  113453. #if JUCE_MSVC
  113454. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113455. #endif
  113456. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113457. #if JUCE_USE_OGGVORBIS
  113458. #include <math.h>
  113459. /*** Start of inlined file: lookup.h ***/
  113460. #ifndef _V_LOOKUP_H_
  113461. #ifdef FLOAT_LOOKUP
  113462. extern float vorbis_coslook(float a);
  113463. extern float vorbis_invsqlook(float a);
  113464. extern float vorbis_invsq2explook(int a);
  113465. extern float vorbis_fromdBlook(float a);
  113466. #endif
  113467. #ifdef INT_LOOKUP
  113468. extern long vorbis_invsqlook_i(long a,long e);
  113469. extern long vorbis_coslook_i(long a);
  113470. extern float vorbis_fromdBlook_i(long a);
  113471. #endif
  113472. #endif
  113473. /*** End of inlined file: lookup.h ***/
  113474. /*** Start of inlined file: lookup_data.h ***/
  113475. #ifndef _V_LOOKUP_DATA_H_
  113476. #ifdef FLOAT_LOOKUP
  113477. #define COS_LOOKUP_SZ 128
  113478. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  113479. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  113480. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  113481. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  113482. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  113483. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  113484. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  113485. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  113486. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  113487. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  113488. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  113489. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  113490. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  113491. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  113492. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  113493. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  113494. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  113495. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  113496. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  113497. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  113498. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  113499. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  113500. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  113501. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  113502. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  113503. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  113504. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  113505. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  113506. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  113507. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  113508. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  113509. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  113510. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  113511. -1.0000000000000f,
  113512. };
  113513. #define INVSQ_LOOKUP_SZ 32
  113514. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  113515. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  113516. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  113517. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  113518. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  113519. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  113520. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  113521. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  113522. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  113523. 1.000000000000f,
  113524. };
  113525. #define INVSQ2EXP_LOOKUP_MIN (-32)
  113526. #define INVSQ2EXP_LOOKUP_MAX 32
  113527. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  113528. INVSQ2EXP_LOOKUP_MIN+1]={
  113529. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  113530. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  113531. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  113532. 1024.f, 724.0773439f, 512.f, 362.038672f,
  113533. 256.f, 181.019336f, 128.f, 90.50966799f,
  113534. 64.f, 45.254834f, 32.f, 22.627417f,
  113535. 16.f, 11.3137085f, 8.f, 5.656854249f,
  113536. 4.f, 2.828427125f, 2.f, 1.414213562f,
  113537. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  113538. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  113539. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  113540. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  113541. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  113542. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  113543. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  113544. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  113545. 1.525878906e-05f,
  113546. };
  113547. #endif
  113548. #define FROMdB_LOOKUP_SZ 35
  113549. #define FROMdB2_LOOKUP_SZ 32
  113550. #define FROMdB_SHIFT 5
  113551. #define FROMdB2_SHIFT 3
  113552. #define FROMdB2_MASK 31
  113553. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  113554. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  113555. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  113556. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  113557. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  113558. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  113559. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  113560. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  113561. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  113562. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  113563. };
  113564. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  113565. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  113566. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  113567. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  113568. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  113569. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  113570. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  113571. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  113572. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  113573. };
  113574. #ifdef INT_LOOKUP
  113575. #define INVSQ_LOOKUP_I_SHIFT 10
  113576. #define INVSQ_LOOKUP_I_MASK 1023
  113577. static long INVSQ_LOOKUP_I[64+1]={
  113578. 92682l, 91966l, 91267l, 90583l,
  113579. 89915l, 89261l, 88621l, 87995l,
  113580. 87381l, 86781l, 86192l, 85616l,
  113581. 85051l, 84497l, 83953l, 83420l,
  113582. 82897l, 82384l, 81880l, 81385l,
  113583. 80899l, 80422l, 79953l, 79492l,
  113584. 79039l, 78594l, 78156l, 77726l,
  113585. 77302l, 76885l, 76475l, 76072l,
  113586. 75674l, 75283l, 74898l, 74519l,
  113587. 74146l, 73778l, 73415l, 73058l,
  113588. 72706l, 72359l, 72016l, 71679l,
  113589. 71347l, 71019l, 70695l, 70376l,
  113590. 70061l, 69750l, 69444l, 69141l,
  113591. 68842l, 68548l, 68256l, 67969l,
  113592. 67685l, 67405l, 67128l, 66855l,
  113593. 66585l, 66318l, 66054l, 65794l,
  113594. 65536l,
  113595. };
  113596. #define COS_LOOKUP_I_SHIFT 9
  113597. #define COS_LOOKUP_I_MASK 511
  113598. #define COS_LOOKUP_I_SZ 128
  113599. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  113600. 16384l, 16379l, 16364l, 16340l,
  113601. 16305l, 16261l, 16207l, 16143l,
  113602. 16069l, 15986l, 15893l, 15791l,
  113603. 15679l, 15557l, 15426l, 15286l,
  113604. 15137l, 14978l, 14811l, 14635l,
  113605. 14449l, 14256l, 14053l, 13842l,
  113606. 13623l, 13395l, 13160l, 12916l,
  113607. 12665l, 12406l, 12140l, 11866l,
  113608. 11585l, 11297l, 11003l, 10702l,
  113609. 10394l, 10080l, 9760l, 9434l,
  113610. 9102l, 8765l, 8423l, 8076l,
  113611. 7723l, 7366l, 7005l, 6639l,
  113612. 6270l, 5897l, 5520l, 5139l,
  113613. 4756l, 4370l, 3981l, 3590l,
  113614. 3196l, 2801l, 2404l, 2006l,
  113615. 1606l, 1205l, 804l, 402l,
  113616. 0l, -401l, -803l, -1204l,
  113617. -1605l, -2005l, -2403l, -2800l,
  113618. -3195l, -3589l, -3980l, -4369l,
  113619. -4755l, -5138l, -5519l, -5896l,
  113620. -6269l, -6638l, -7004l, -7365l,
  113621. -7722l, -8075l, -8422l, -8764l,
  113622. -9101l, -9433l, -9759l, -10079l,
  113623. -10393l, -10701l, -11002l, -11296l,
  113624. -11584l, -11865l, -12139l, -12405l,
  113625. -12664l, -12915l, -13159l, -13394l,
  113626. -13622l, -13841l, -14052l, -14255l,
  113627. -14448l, -14634l, -14810l, -14977l,
  113628. -15136l, -15285l, -15425l, -15556l,
  113629. -15678l, -15790l, -15892l, -15985l,
  113630. -16068l, -16142l, -16206l, -16260l,
  113631. -16304l, -16339l, -16363l, -16378l,
  113632. -16383l,
  113633. };
  113634. #endif
  113635. #endif
  113636. /*** End of inlined file: lookup_data.h ***/
  113637. #ifdef FLOAT_LOOKUP
  113638. /* interpolated lookup based cos function, domain 0 to PI only */
  113639. float vorbis_coslook(float a){
  113640. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  113641. int i=vorbis_ftoi(d-.5);
  113642. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  113643. }
  113644. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  113645. float vorbis_invsqlook(float a){
  113646. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  113647. int i=vorbis_ftoi(d-.5f);
  113648. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  113649. }
  113650. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  113651. float vorbis_invsq2explook(int a){
  113652. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  113653. }
  113654. #include <stdio.h>
  113655. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  113656. float vorbis_fromdBlook(float a){
  113657. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  113658. return (i<0)?1.f:
  113659. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  113660. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  113661. }
  113662. #endif
  113663. #ifdef INT_LOOKUP
  113664. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  113665. 16.16 format
  113666. returns in m.8 format */
  113667. long vorbis_invsqlook_i(long a,long e){
  113668. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  113669. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  113670. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  113671. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  113672. d)>>16); /* result 1.16 */
  113673. e+=32;
  113674. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  113675. e=(e>>1)-8;
  113676. return(val>>e);
  113677. }
  113678. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  113679. /* a is in n.12 format */
  113680. float vorbis_fromdBlook_i(long a){
  113681. int i=(-a)>>(12-FROMdB2_SHIFT);
  113682. return (i<0)?1.f:
  113683. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  113684. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  113685. }
  113686. /* interpolated lookup based cos function, domain 0 to PI only */
  113687. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  113688. long vorbis_coslook_i(long a){
  113689. int i=a>>COS_LOOKUP_I_SHIFT;
  113690. int d=a&COS_LOOKUP_I_MASK;
  113691. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  113692. COS_LOOKUP_I_SHIFT);
  113693. }
  113694. #endif
  113695. #endif
  113696. /*** End of inlined file: lookup.c ***/
  113697. /* catch this in the build system; we #include for
  113698. compilers (like gcc) that can't inline across
  113699. modules */
  113700. /* side effect: changes *lsp to cosines of lsp */
  113701. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  113702. float amp,float ampoffset){
  113703. int i;
  113704. float wdel=M_PI/ln;
  113705. vorbis_fpu_control fpu;
  113706. (void) fpu; // to avoid an unused variable warning
  113707. vorbis_fpu_setround(&fpu);
  113708. for(i=0;i<m;i++)lsp[i]=vorbis_coslook(lsp[i]);
  113709. i=0;
  113710. while(i<n){
  113711. int k=map[i];
  113712. int qexp;
  113713. float p=.7071067812f;
  113714. float q=.7071067812f;
  113715. float w=vorbis_coslook(wdel*k);
  113716. float *ftmp=lsp;
  113717. int c=m>>1;
  113718. do{
  113719. q*=ftmp[0]-w;
  113720. p*=ftmp[1]-w;
  113721. ftmp+=2;
  113722. }while(--c);
  113723. if(m&1){
  113724. /* odd order filter; slightly assymetric */
  113725. /* the last coefficient */
  113726. q*=ftmp[0]-w;
  113727. q*=q;
  113728. p*=p*(1.f-w*w);
  113729. }else{
  113730. /* even order filter; still symmetric */
  113731. q*=q*(1.f+w);
  113732. p*=p*(1.f-w);
  113733. }
  113734. q=frexp(p+q,&qexp);
  113735. q=vorbis_fromdBlook(amp*
  113736. vorbis_invsqlook(q)*
  113737. vorbis_invsq2explook(qexp+m)-
  113738. ampoffset);
  113739. do{
  113740. curve[i++]*=q;
  113741. }while(map[i]==k);
  113742. }
  113743. vorbis_fpu_restore(fpu);
  113744. }
  113745. #else
  113746. #ifdef INT_LOOKUP
  113747. /*** Start of inlined file: lookup.c ***/
  113748. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113749. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113750. // tasks..
  113751. #if JUCE_MSVC
  113752. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113753. #endif
  113754. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113755. #if JUCE_USE_OGGVORBIS
  113756. #include <math.h>
  113757. /*** Start of inlined file: lookup.h ***/
  113758. #ifndef _V_LOOKUP_H_
  113759. #ifdef FLOAT_LOOKUP
  113760. extern float vorbis_coslook(float a);
  113761. extern float vorbis_invsqlook(float a);
  113762. extern float vorbis_invsq2explook(int a);
  113763. extern float vorbis_fromdBlook(float a);
  113764. #endif
  113765. #ifdef INT_LOOKUP
  113766. extern long vorbis_invsqlook_i(long a,long e);
  113767. extern long vorbis_coslook_i(long a);
  113768. extern float vorbis_fromdBlook_i(long a);
  113769. #endif
  113770. #endif
  113771. /*** End of inlined file: lookup.h ***/
  113772. /*** Start of inlined file: lookup_data.h ***/
  113773. #ifndef _V_LOOKUP_DATA_H_
  113774. #ifdef FLOAT_LOOKUP
  113775. #define COS_LOOKUP_SZ 128
  113776. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  113777. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  113778. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  113779. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  113780. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  113781. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  113782. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  113783. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  113784. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  113785. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  113786. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  113787. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  113788. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  113789. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  113790. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  113791. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  113792. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  113793. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  113794. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  113795. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  113796. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  113797. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  113798. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  113799. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  113800. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  113801. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  113802. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  113803. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  113804. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  113805. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  113806. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  113807. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  113808. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  113809. -1.0000000000000f,
  113810. };
  113811. #define INVSQ_LOOKUP_SZ 32
  113812. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  113813. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  113814. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  113815. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  113816. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  113817. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  113818. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  113819. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  113820. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  113821. 1.000000000000f,
  113822. };
  113823. #define INVSQ2EXP_LOOKUP_MIN (-32)
  113824. #define INVSQ2EXP_LOOKUP_MAX 32
  113825. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  113826. INVSQ2EXP_LOOKUP_MIN+1]={
  113827. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  113828. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  113829. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  113830. 1024.f, 724.0773439f, 512.f, 362.038672f,
  113831. 256.f, 181.019336f, 128.f, 90.50966799f,
  113832. 64.f, 45.254834f, 32.f, 22.627417f,
  113833. 16.f, 11.3137085f, 8.f, 5.656854249f,
  113834. 4.f, 2.828427125f, 2.f, 1.414213562f,
  113835. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  113836. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  113837. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  113838. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  113839. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  113840. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  113841. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  113842. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  113843. 1.525878906e-05f,
  113844. };
  113845. #endif
  113846. #define FROMdB_LOOKUP_SZ 35
  113847. #define FROMdB2_LOOKUP_SZ 32
  113848. #define FROMdB_SHIFT 5
  113849. #define FROMdB2_SHIFT 3
  113850. #define FROMdB2_MASK 31
  113851. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  113852. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  113853. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  113854. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  113855. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  113856. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  113857. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  113858. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  113859. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  113860. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  113861. };
  113862. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  113863. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  113864. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  113865. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  113866. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  113867. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  113868. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  113869. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  113870. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  113871. };
  113872. #ifdef INT_LOOKUP
  113873. #define INVSQ_LOOKUP_I_SHIFT 10
  113874. #define INVSQ_LOOKUP_I_MASK 1023
  113875. static long INVSQ_LOOKUP_I[64+1]={
  113876. 92682l, 91966l, 91267l, 90583l,
  113877. 89915l, 89261l, 88621l, 87995l,
  113878. 87381l, 86781l, 86192l, 85616l,
  113879. 85051l, 84497l, 83953l, 83420l,
  113880. 82897l, 82384l, 81880l, 81385l,
  113881. 80899l, 80422l, 79953l, 79492l,
  113882. 79039l, 78594l, 78156l, 77726l,
  113883. 77302l, 76885l, 76475l, 76072l,
  113884. 75674l, 75283l, 74898l, 74519l,
  113885. 74146l, 73778l, 73415l, 73058l,
  113886. 72706l, 72359l, 72016l, 71679l,
  113887. 71347l, 71019l, 70695l, 70376l,
  113888. 70061l, 69750l, 69444l, 69141l,
  113889. 68842l, 68548l, 68256l, 67969l,
  113890. 67685l, 67405l, 67128l, 66855l,
  113891. 66585l, 66318l, 66054l, 65794l,
  113892. 65536l,
  113893. };
  113894. #define COS_LOOKUP_I_SHIFT 9
  113895. #define COS_LOOKUP_I_MASK 511
  113896. #define COS_LOOKUP_I_SZ 128
  113897. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  113898. 16384l, 16379l, 16364l, 16340l,
  113899. 16305l, 16261l, 16207l, 16143l,
  113900. 16069l, 15986l, 15893l, 15791l,
  113901. 15679l, 15557l, 15426l, 15286l,
  113902. 15137l, 14978l, 14811l, 14635l,
  113903. 14449l, 14256l, 14053l, 13842l,
  113904. 13623l, 13395l, 13160l, 12916l,
  113905. 12665l, 12406l, 12140l, 11866l,
  113906. 11585l, 11297l, 11003l, 10702l,
  113907. 10394l, 10080l, 9760l, 9434l,
  113908. 9102l, 8765l, 8423l, 8076l,
  113909. 7723l, 7366l, 7005l, 6639l,
  113910. 6270l, 5897l, 5520l, 5139l,
  113911. 4756l, 4370l, 3981l, 3590l,
  113912. 3196l, 2801l, 2404l, 2006l,
  113913. 1606l, 1205l, 804l, 402l,
  113914. 0l, -401l, -803l, -1204l,
  113915. -1605l, -2005l, -2403l, -2800l,
  113916. -3195l, -3589l, -3980l, -4369l,
  113917. -4755l, -5138l, -5519l, -5896l,
  113918. -6269l, -6638l, -7004l, -7365l,
  113919. -7722l, -8075l, -8422l, -8764l,
  113920. -9101l, -9433l, -9759l, -10079l,
  113921. -10393l, -10701l, -11002l, -11296l,
  113922. -11584l, -11865l, -12139l, -12405l,
  113923. -12664l, -12915l, -13159l, -13394l,
  113924. -13622l, -13841l, -14052l, -14255l,
  113925. -14448l, -14634l, -14810l, -14977l,
  113926. -15136l, -15285l, -15425l, -15556l,
  113927. -15678l, -15790l, -15892l, -15985l,
  113928. -16068l, -16142l, -16206l, -16260l,
  113929. -16304l, -16339l, -16363l, -16378l,
  113930. -16383l,
  113931. };
  113932. #endif
  113933. #endif
  113934. /*** End of inlined file: lookup_data.h ***/
  113935. #ifdef FLOAT_LOOKUP
  113936. /* interpolated lookup based cos function, domain 0 to PI only */
  113937. float vorbis_coslook(float a){
  113938. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  113939. int i=vorbis_ftoi(d-.5);
  113940. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  113941. }
  113942. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  113943. float vorbis_invsqlook(float a){
  113944. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  113945. int i=vorbis_ftoi(d-.5f);
  113946. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  113947. }
  113948. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  113949. float vorbis_invsq2explook(int a){
  113950. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  113951. }
  113952. #include <stdio.h>
  113953. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  113954. float vorbis_fromdBlook(float a){
  113955. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  113956. return (i<0)?1.f:
  113957. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  113958. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  113959. }
  113960. #endif
  113961. #ifdef INT_LOOKUP
  113962. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  113963. 16.16 format
  113964. returns in m.8 format */
  113965. long vorbis_invsqlook_i(long a,long e){
  113966. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  113967. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  113968. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  113969. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  113970. d)>>16); /* result 1.16 */
  113971. e+=32;
  113972. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  113973. e=(e>>1)-8;
  113974. return(val>>e);
  113975. }
  113976. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  113977. /* a is in n.12 format */
  113978. float vorbis_fromdBlook_i(long a){
  113979. int i=(-a)>>(12-FROMdB2_SHIFT);
  113980. return (i<0)?1.f:
  113981. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  113982. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  113983. }
  113984. /* interpolated lookup based cos function, domain 0 to PI only */
  113985. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  113986. long vorbis_coslook_i(long a){
  113987. int i=a>>COS_LOOKUP_I_SHIFT;
  113988. int d=a&COS_LOOKUP_I_MASK;
  113989. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  113990. COS_LOOKUP_I_SHIFT);
  113991. }
  113992. #endif
  113993. #endif
  113994. /*** End of inlined file: lookup.c ***/
  113995. /* catch this in the build system; we #include for
  113996. compilers (like gcc) that can't inline across
  113997. modules */
  113998. static int MLOOP_1[64]={
  113999. 0,10,11,11, 12,12,12,12, 13,13,13,13, 13,13,13,13,
  114000. 14,14,14,14, 14,14,14,14, 14,14,14,14, 14,14,14,14,
  114001. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  114002. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  114003. };
  114004. static int MLOOP_2[64]={
  114005. 0,4,5,5, 6,6,6,6, 7,7,7,7, 7,7,7,7,
  114006. 8,8,8,8, 8,8,8,8, 8,8,8,8, 8,8,8,8,
  114007. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  114008. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  114009. };
  114010. static int MLOOP_3[8]={0,1,2,2,3,3,3,3};
  114011. /* side effect: changes *lsp to cosines of lsp */
  114012. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114013. float amp,float ampoffset){
  114014. /* 0 <= m < 256 */
  114015. /* set up for using all int later */
  114016. int i;
  114017. int ampoffseti=rint(ampoffset*4096.f);
  114018. int ampi=rint(amp*16.f);
  114019. long *ilsp=alloca(m*sizeof(*ilsp));
  114020. for(i=0;i<m;i++)ilsp[i]=vorbis_coslook_i(lsp[i]/M_PI*65536.f+.5f);
  114021. i=0;
  114022. while(i<n){
  114023. int j,k=map[i];
  114024. unsigned long pi=46341; /* 2**-.5 in 0.16 */
  114025. unsigned long qi=46341;
  114026. int qexp=0,shift;
  114027. long wi=vorbis_coslook_i(k*65536/ln);
  114028. qi*=labs(ilsp[0]-wi);
  114029. pi*=labs(ilsp[1]-wi);
  114030. for(j=3;j<m;j+=2){
  114031. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114032. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114033. shift=MLOOP_3[(pi|qi)>>16];
  114034. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  114035. pi=(pi>>shift)*labs(ilsp[j]-wi);
  114036. qexp+=shift;
  114037. }
  114038. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114039. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114040. shift=MLOOP_3[(pi|qi)>>16];
  114041. /* pi,qi normalized collectively, both tracked using qexp */
  114042. if(m&1){
  114043. /* odd order filter; slightly assymetric */
  114044. /* the last coefficient */
  114045. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  114046. pi=(pi>>shift)<<14;
  114047. qexp+=shift;
  114048. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114049. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114050. shift=MLOOP_3[(pi|qi)>>16];
  114051. pi>>=shift;
  114052. qi>>=shift;
  114053. qexp+=shift-14*((m+1)>>1);
  114054. pi=((pi*pi)>>16);
  114055. qi=((qi*qi)>>16);
  114056. qexp=qexp*2+m;
  114057. pi*=(1<<14)-((wi*wi)>>14);
  114058. qi+=pi>>14;
  114059. }else{
  114060. /* even order filter; still symmetric */
  114061. /* p*=p(1-w), q*=q(1+w), let normalization drift because it isn't
  114062. worth tracking step by step */
  114063. pi>>=shift;
  114064. qi>>=shift;
  114065. qexp+=shift-7*m;
  114066. pi=((pi*pi)>>16);
  114067. qi=((qi*qi)>>16);
  114068. qexp=qexp*2+m;
  114069. pi*=(1<<14)-wi;
  114070. qi*=(1<<14)+wi;
  114071. qi=(qi+pi)>>14;
  114072. }
  114073. /* we've let the normalization drift because it wasn't important;
  114074. however, for the lookup, things must be normalized again. We
  114075. need at most one right shift or a number of left shifts */
  114076. if(qi&0xffff0000){ /* checks for 1.xxxxxxxxxxxxxxxx */
  114077. qi>>=1; qexp++;
  114078. }else
  114079. while(qi && !(qi&0x8000)){ /* checks for 0.0xxxxxxxxxxxxxxx or less*/
  114080. qi<<=1; qexp--;
  114081. }
  114082. amp=vorbis_fromdBlook_i(ampi* /* n.4 */
  114083. vorbis_invsqlook_i(qi,qexp)-
  114084. /* m.8, m+n<=8 */
  114085. ampoffseti); /* 8.12[0] */
  114086. curve[i]*=amp;
  114087. while(map[++i]==k)curve[i]*=amp;
  114088. }
  114089. }
  114090. #else
  114091. /* old, nonoptimized but simple version for any poor sap who needs to
  114092. figure out what the hell this code does, or wants the other
  114093. fraction of a dB precision */
  114094. /* side effect: changes *lsp to cosines of lsp */
  114095. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114096. float amp,float ampoffset){
  114097. int i;
  114098. float wdel=M_PI/ln;
  114099. for(i=0;i<m;i++)lsp[i]=2.f*cos(lsp[i]);
  114100. i=0;
  114101. while(i<n){
  114102. int j,k=map[i];
  114103. float p=.5f;
  114104. float q=.5f;
  114105. float w=2.f*cos(wdel*k);
  114106. for(j=1;j<m;j+=2){
  114107. q *= w-lsp[j-1];
  114108. p *= w-lsp[j];
  114109. }
  114110. if(j==m){
  114111. /* odd order filter; slightly assymetric */
  114112. /* the last coefficient */
  114113. q*=w-lsp[j-1];
  114114. p*=p*(4.f-w*w);
  114115. q*=q;
  114116. }else{
  114117. /* even order filter; still symmetric */
  114118. p*=p*(2.f-w);
  114119. q*=q*(2.f+w);
  114120. }
  114121. q=fromdB(amp/sqrt(p+q)-ampoffset);
  114122. curve[i]*=q;
  114123. while(map[++i]==k)curve[i]*=q;
  114124. }
  114125. }
  114126. #endif
  114127. #endif
  114128. static void cheby(float *g, int ord) {
  114129. int i, j;
  114130. g[0] *= .5f;
  114131. for(i=2; i<= ord; i++) {
  114132. for(j=ord; j >= i; j--) {
  114133. g[j-2] -= g[j];
  114134. g[j] += g[j];
  114135. }
  114136. }
  114137. }
  114138. static int comp(const void *a,const void *b){
  114139. return (*(float *)a<*(float *)b)-(*(float *)a>*(float *)b);
  114140. }
  114141. /* Newton-Raphson-Maehly actually functioned as a decent root finder,
  114142. but there are root sets for which it gets into limit cycles
  114143. (exacerbated by zero suppression) and fails. We can't afford to
  114144. fail, even if the failure is 1 in 100,000,000, so we now use
  114145. Laguerre and later polish with Newton-Raphson (which can then
  114146. afford to fail) */
  114147. #define EPSILON 10e-7
  114148. static int Laguerre_With_Deflation(float *a,int ord,float *r){
  114149. int i,m;
  114150. double lastdelta=0.f;
  114151. double *defl=(double*)alloca(sizeof(*defl)*(ord+1));
  114152. for(i=0;i<=ord;i++)defl[i]=a[i];
  114153. for(m=ord;m>0;m--){
  114154. double newx=0.f,delta;
  114155. /* iterate a root */
  114156. while(1){
  114157. double p=defl[m],pp=0.f,ppp=0.f,denom;
  114158. /* eval the polynomial and its first two derivatives */
  114159. for(i=m;i>0;i--){
  114160. ppp = newx*ppp + pp;
  114161. pp = newx*pp + p;
  114162. p = newx*p + defl[i-1];
  114163. }
  114164. /* Laguerre's method */
  114165. denom=(m-1) * ((m-1)*pp*pp - m*p*ppp);
  114166. if(denom<0)
  114167. return(-1); /* complex root! The LPC generator handed us a bad filter */
  114168. if(pp>0){
  114169. denom = pp + sqrt(denom);
  114170. if(denom<EPSILON)denom=EPSILON;
  114171. }else{
  114172. denom = pp - sqrt(denom);
  114173. if(denom>-(EPSILON))denom=-(EPSILON);
  114174. }
  114175. delta = m*p/denom;
  114176. newx -= delta;
  114177. if(delta<0.f)delta*=-1;
  114178. if(fabs(delta/newx)<10e-12)break;
  114179. lastdelta=delta;
  114180. }
  114181. r[m-1]=newx;
  114182. /* forward deflation */
  114183. for(i=m;i>0;i--)
  114184. defl[i-1]+=newx*defl[i];
  114185. defl++;
  114186. }
  114187. return(0);
  114188. }
  114189. /* for spit-and-polish only */
  114190. static int Newton_Raphson(float *a,int ord,float *r){
  114191. int i, k, count=0;
  114192. double error=1.f;
  114193. double *root=(double*)alloca(ord*sizeof(*root));
  114194. for(i=0; i<ord;i++) root[i] = r[i];
  114195. while(error>1e-20){
  114196. error=0;
  114197. for(i=0; i<ord; i++) { /* Update each point. */
  114198. double pp=0.,delta;
  114199. double rooti=root[i];
  114200. double p=a[ord];
  114201. for(k=ord-1; k>= 0; k--) {
  114202. pp= pp* rooti + p;
  114203. p = p * rooti + a[k];
  114204. }
  114205. delta = p/pp;
  114206. root[i] -= delta;
  114207. error+= delta*delta;
  114208. }
  114209. if(count>40)return(-1);
  114210. count++;
  114211. }
  114212. /* Replaced the original bubble sort with a real sort. With your
  114213. help, we can eliminate the bubble sort in our lifetime. --Monty */
  114214. for(i=0; i<ord;i++) r[i] = root[i];
  114215. return(0);
  114216. }
  114217. /* Convert lpc coefficients to lsp coefficients */
  114218. int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m){
  114219. int order2=(m+1)>>1;
  114220. int g1_order,g2_order;
  114221. float *g1=(float*)alloca(sizeof(*g1)*(order2+1));
  114222. float *g2=(float*)alloca(sizeof(*g2)*(order2+1));
  114223. float *g1r=(float*)alloca(sizeof(*g1r)*(order2+1));
  114224. float *g2r=(float*)alloca(sizeof(*g2r)*(order2+1));
  114225. int i;
  114226. /* even and odd are slightly different base cases */
  114227. g1_order=(m+1)>>1;
  114228. g2_order=(m) >>1;
  114229. /* Compute the lengths of the x polynomials. */
  114230. /* Compute the first half of K & R F1 & F2 polynomials. */
  114231. /* Compute half of the symmetric and antisymmetric polynomials. */
  114232. /* Remove the roots at +1 and -1. */
  114233. g1[g1_order] = 1.f;
  114234. for(i=1;i<=g1_order;i++) g1[g1_order-i] = lpc[i-1]+lpc[m-i];
  114235. g2[g2_order] = 1.f;
  114236. for(i=1;i<=g2_order;i++) g2[g2_order-i] = lpc[i-1]-lpc[m-i];
  114237. if(g1_order>g2_order){
  114238. for(i=2; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+2];
  114239. }else{
  114240. for(i=1; i<=g1_order;i++) g1[g1_order-i] -= g1[g1_order-i+1];
  114241. for(i=1; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+1];
  114242. }
  114243. /* Convert into polynomials in cos(alpha) */
  114244. cheby(g1,g1_order);
  114245. cheby(g2,g2_order);
  114246. /* Find the roots of the 2 even polynomials.*/
  114247. if(Laguerre_With_Deflation(g1,g1_order,g1r) ||
  114248. Laguerre_With_Deflation(g2,g2_order,g2r))
  114249. return(-1);
  114250. Newton_Raphson(g1,g1_order,g1r); /* if it fails, it leaves g1r alone */
  114251. Newton_Raphson(g2,g2_order,g2r); /* if it fails, it leaves g2r alone */
  114252. qsort(g1r,g1_order,sizeof(*g1r),comp);
  114253. qsort(g2r,g2_order,sizeof(*g2r),comp);
  114254. for(i=0;i<g1_order;i++)
  114255. lsp[i*2] = acos(g1r[i]);
  114256. for(i=0;i<g2_order;i++)
  114257. lsp[i*2+1] = acos(g2r[i]);
  114258. return(0);
  114259. }
  114260. #endif
  114261. /*** End of inlined file: lsp.c ***/
  114262. /*** Start of inlined file: mapping0.c ***/
  114263. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114264. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114265. // tasks..
  114266. #if JUCE_MSVC
  114267. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114268. #endif
  114269. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114270. #if JUCE_USE_OGGVORBIS
  114271. #include <stdlib.h>
  114272. #include <stdio.h>
  114273. #include <string.h>
  114274. #include <math.h>
  114275. /* simplistic, wasteful way of doing this (unique lookup for each
  114276. mode/submapping); there should be a central repository for
  114277. identical lookups. That will require minor work, so I'm putting it
  114278. off as low priority.
  114279. Why a lookup for each backend in a given mode? Because the
  114280. blocksize is set by the mode, and low backend lookups may require
  114281. parameters from other areas of the mode/mapping */
  114282. static void mapping0_free_info(vorbis_info_mapping *i){
  114283. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)i;
  114284. if(info){
  114285. memset(info,0,sizeof(*info));
  114286. _ogg_free(info);
  114287. }
  114288. }
  114289. static int ilog3(unsigned int v){
  114290. int ret=0;
  114291. if(v)--v;
  114292. while(v){
  114293. ret++;
  114294. v>>=1;
  114295. }
  114296. return(ret);
  114297. }
  114298. static void mapping0_pack(vorbis_info *vi,vorbis_info_mapping *vm,
  114299. oggpack_buffer *opb){
  114300. int i;
  114301. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)vm;
  114302. /* another 'we meant to do it this way' hack... up to beta 4, we
  114303. packed 4 binary zeros here to signify one submapping in use. We
  114304. now redefine that to mean four bitflags that indicate use of
  114305. deeper features; bit0:submappings, bit1:coupling,
  114306. bit2,3:reserved. This is backward compatable with all actual uses
  114307. of the beta code. */
  114308. if(info->submaps>1){
  114309. oggpack_write(opb,1,1);
  114310. oggpack_write(opb,info->submaps-1,4);
  114311. }else
  114312. oggpack_write(opb,0,1);
  114313. if(info->coupling_steps>0){
  114314. oggpack_write(opb,1,1);
  114315. oggpack_write(opb,info->coupling_steps-1,8);
  114316. for(i=0;i<info->coupling_steps;i++){
  114317. oggpack_write(opb,info->coupling_mag[i],ilog3(vi->channels));
  114318. oggpack_write(opb,info->coupling_ang[i],ilog3(vi->channels));
  114319. }
  114320. }else
  114321. oggpack_write(opb,0,1);
  114322. oggpack_write(opb,0,2); /* 2,3:reserved */
  114323. /* we don't write the channel submappings if we only have one... */
  114324. if(info->submaps>1){
  114325. for(i=0;i<vi->channels;i++)
  114326. oggpack_write(opb,info->chmuxlist[i],4);
  114327. }
  114328. for(i=0;i<info->submaps;i++){
  114329. oggpack_write(opb,0,8); /* time submap unused */
  114330. oggpack_write(opb,info->floorsubmap[i],8);
  114331. oggpack_write(opb,info->residuesubmap[i],8);
  114332. }
  114333. }
  114334. /* also responsible for range checking */
  114335. static vorbis_info_mapping *mapping0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  114336. int i;
  114337. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)_ogg_calloc(1,sizeof(*info));
  114338. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114339. memset(info,0,sizeof(*info));
  114340. if(oggpack_read(opb,1))
  114341. info->submaps=oggpack_read(opb,4)+1;
  114342. else
  114343. info->submaps=1;
  114344. if(oggpack_read(opb,1)){
  114345. info->coupling_steps=oggpack_read(opb,8)+1;
  114346. for(i=0;i<info->coupling_steps;i++){
  114347. int testM=info->coupling_mag[i]=oggpack_read(opb,ilog3(vi->channels));
  114348. int testA=info->coupling_ang[i]=oggpack_read(opb,ilog3(vi->channels));
  114349. if(testM<0 ||
  114350. testA<0 ||
  114351. testM==testA ||
  114352. testM>=vi->channels ||
  114353. testA>=vi->channels) goto err_out;
  114354. }
  114355. }
  114356. if(oggpack_read(opb,2)>0)goto err_out; /* 2,3:reserved */
  114357. if(info->submaps>1){
  114358. for(i=0;i<vi->channels;i++){
  114359. info->chmuxlist[i]=oggpack_read(opb,4);
  114360. if(info->chmuxlist[i]>=info->submaps)goto err_out;
  114361. }
  114362. }
  114363. for(i=0;i<info->submaps;i++){
  114364. oggpack_read(opb,8); /* time submap unused */
  114365. info->floorsubmap[i]=oggpack_read(opb,8);
  114366. if(info->floorsubmap[i]>=ci->floors)goto err_out;
  114367. info->residuesubmap[i]=oggpack_read(opb,8);
  114368. if(info->residuesubmap[i]>=ci->residues)goto err_out;
  114369. }
  114370. return info;
  114371. err_out:
  114372. mapping0_free_info(info);
  114373. return(NULL);
  114374. }
  114375. #if 0
  114376. static long seq=0;
  114377. static ogg_int64_t total=0;
  114378. static float FLOOR1_fromdB_LOOKUP[256]={
  114379. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  114380. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  114381. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  114382. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  114383. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  114384. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  114385. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  114386. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  114387. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  114388. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  114389. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  114390. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  114391. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  114392. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  114393. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  114394. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  114395. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  114396. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  114397. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  114398. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  114399. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  114400. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  114401. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  114402. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  114403. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  114404. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  114405. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  114406. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  114407. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  114408. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  114409. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  114410. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  114411. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  114412. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  114413. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  114414. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  114415. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  114416. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  114417. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  114418. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  114419. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  114420. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  114421. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  114422. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  114423. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  114424. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  114425. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  114426. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  114427. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  114428. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  114429. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  114430. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  114431. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  114432. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  114433. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  114434. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  114435. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  114436. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  114437. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  114438. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  114439. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  114440. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  114441. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  114442. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  114443. };
  114444. #endif
  114445. extern int *floor1_fit(vorbis_block *vb,void *look,
  114446. const float *logmdct, /* in */
  114447. const float *logmask);
  114448. extern int *floor1_interpolate_fit(vorbis_block *vb,void *look,
  114449. int *A,int *B,
  114450. int del);
  114451. extern int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  114452. void*look,
  114453. int *post,int *ilogmask);
  114454. static int mapping0_forward(vorbis_block *vb){
  114455. vorbis_dsp_state *vd=vb->vd;
  114456. vorbis_info *vi=vd->vi;
  114457. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114458. private_state *b=(private_state*)vb->vd->backend_state;
  114459. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  114460. int n=vb->pcmend;
  114461. int i,j,k;
  114462. int *nonzero = (int*) alloca(sizeof(*nonzero)*vi->channels);
  114463. float **gmdct = (float**) _vorbis_block_alloc(vb,vi->channels*sizeof(*gmdct));
  114464. int **ilogmaskch= (int**) _vorbis_block_alloc(vb,vi->channels*sizeof(*ilogmaskch));
  114465. int ***floor_posts = (int***) _vorbis_block_alloc(vb,vi->channels*sizeof(*floor_posts));
  114466. float global_ampmax=vbi->ampmax;
  114467. float *local_ampmax=(float*)alloca(sizeof(*local_ampmax)*vi->channels);
  114468. int blocktype=vbi->blocktype;
  114469. int modenumber=vb->W;
  114470. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)ci->map_param[modenumber];
  114471. vorbis_look_psy *psy_look=
  114472. b->psy+blocktype+(vb->W?2:0);
  114473. vb->mode=modenumber;
  114474. for(i=0;i<vi->channels;i++){
  114475. float scale=4.f/n;
  114476. float scale_dB;
  114477. float *pcm =vb->pcm[i];
  114478. float *logfft =pcm;
  114479. gmdct[i]=(float*)_vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  114480. scale_dB=todB(&scale) + .345; /* + .345 is a hack; the original
  114481. todB estimation used on IEEE 754
  114482. compliant machines had a bug that
  114483. returned dB values about a third
  114484. of a decibel too high. The bug
  114485. was harmless because tunings
  114486. implicitly took that into
  114487. account. However, fixing the bug
  114488. in the estimator requires
  114489. changing all the tunings as well.
  114490. For now, it's easier to sync
  114491. things back up here, and
  114492. recalibrate the tunings in the
  114493. next major model upgrade. */
  114494. #if 0
  114495. if(vi->channels==2)
  114496. if(i==0)
  114497. _analysis_output("pcmL",seq,pcm,n,0,0,total-n/2);
  114498. else
  114499. _analysis_output("pcmR",seq,pcm,n,0,0,total-n/2);
  114500. #endif
  114501. /* window the PCM data */
  114502. _vorbis_apply_window(pcm,b->window,ci->blocksizes,vb->lW,vb->W,vb->nW);
  114503. #if 0
  114504. if(vi->channels==2)
  114505. if(i==0)
  114506. _analysis_output("windowedL",seq,pcm,n,0,0,total-n/2);
  114507. else
  114508. _analysis_output("windowedR",seq,pcm,n,0,0,total-n/2);
  114509. #endif
  114510. /* transform the PCM data */
  114511. /* only MDCT right now.... */
  114512. mdct_forward((mdct_lookup*) b->transform[vb->W][0],pcm,gmdct[i]);
  114513. /* FFT yields more accurate tonal estimation (not phase sensitive) */
  114514. drft_forward(&b->fft_look[vb->W],pcm);
  114515. logfft[0]=scale_dB+todB(pcm) + .345; /* + .345 is a hack; the
  114516. original todB estimation used on
  114517. IEEE 754 compliant machines had a
  114518. bug that returned dB values about
  114519. a third of a decibel too high.
  114520. The bug was harmless because
  114521. tunings implicitly took that into
  114522. account. However, fixing the bug
  114523. in the estimator requires
  114524. changing all the tunings as well.
  114525. For now, it's easier to sync
  114526. things back up here, and
  114527. recalibrate the tunings in the
  114528. next major model upgrade. */
  114529. local_ampmax[i]=logfft[0];
  114530. for(j=1;j<n-1;j+=2){
  114531. float temp=pcm[j]*pcm[j]+pcm[j+1]*pcm[j+1];
  114532. temp=logfft[(j+1)>>1]=scale_dB+.5f*todB(&temp) + .345; /* +
  114533. .345 is a hack; the original todB
  114534. estimation used on IEEE 754
  114535. compliant machines had a bug that
  114536. returned dB values about a third
  114537. of a decibel too high. The bug
  114538. was harmless because tunings
  114539. implicitly took that into
  114540. account. However, fixing the bug
  114541. in the estimator requires
  114542. changing all the tunings as well.
  114543. For now, it's easier to sync
  114544. things back up here, and
  114545. recalibrate the tunings in the
  114546. next major model upgrade. */
  114547. if(temp>local_ampmax[i])local_ampmax[i]=temp;
  114548. }
  114549. if(local_ampmax[i]>0.f)local_ampmax[i]=0.f;
  114550. if(local_ampmax[i]>global_ampmax)global_ampmax=local_ampmax[i];
  114551. #if 0
  114552. if(vi->channels==2){
  114553. if(i==0){
  114554. _analysis_output("fftL",seq,logfft,n/2,1,0,0);
  114555. }else{
  114556. _analysis_output("fftR",seq,logfft,n/2,1,0,0);
  114557. }
  114558. }
  114559. #endif
  114560. }
  114561. {
  114562. float *noise = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*noise));
  114563. float *tone = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*tone));
  114564. for(i=0;i<vi->channels;i++){
  114565. /* the encoder setup assumes that all the modes used by any
  114566. specific bitrate tweaking use the same floor */
  114567. int submap=info->chmuxlist[i];
  114568. /* the following makes things clearer to *me* anyway */
  114569. float *mdct =gmdct[i];
  114570. float *logfft =vb->pcm[i];
  114571. float *logmdct =logfft+n/2;
  114572. float *logmask =logfft;
  114573. vb->mode=modenumber;
  114574. floor_posts[i]=(int**) _vorbis_block_alloc(vb,PACKETBLOBS*sizeof(**floor_posts));
  114575. memset(floor_posts[i],0,sizeof(**floor_posts)*PACKETBLOBS);
  114576. for(j=0;j<n/2;j++)
  114577. logmdct[j]=todB(mdct+j) + .345; /* + .345 is a hack; the original
  114578. todB estimation used on IEEE 754
  114579. compliant machines had a bug that
  114580. returned dB values about a third
  114581. of a decibel too high. The bug
  114582. was harmless because tunings
  114583. implicitly took that into
  114584. account. However, fixing the bug
  114585. in the estimator requires
  114586. changing all the tunings as well.
  114587. For now, it's easier to sync
  114588. things back up here, and
  114589. recalibrate the tunings in the
  114590. next major model upgrade. */
  114591. #if 0
  114592. if(vi->channels==2){
  114593. if(i==0)
  114594. _analysis_output("mdctL",seq,logmdct,n/2,1,0,0);
  114595. else
  114596. _analysis_output("mdctR",seq,logmdct,n/2,1,0,0);
  114597. }else{
  114598. _analysis_output("mdct",seq,logmdct,n/2,1,0,0);
  114599. }
  114600. #endif
  114601. /* first step; noise masking. Not only does 'noise masking'
  114602. give us curves from which we can decide how much resolution
  114603. to give noise parts of the spectrum, it also implicitly hands
  114604. us a tonality estimate (the larger the value in the
  114605. 'noise_depth' vector, the more tonal that area is) */
  114606. _vp_noisemask(psy_look,
  114607. logmdct,
  114608. noise); /* noise does not have by-frequency offset
  114609. bias applied yet */
  114610. #if 0
  114611. if(vi->channels==2){
  114612. if(i==0)
  114613. _analysis_output("noiseL",seq,noise,n/2,1,0,0);
  114614. else
  114615. _analysis_output("noiseR",seq,noise,n/2,1,0,0);
  114616. }
  114617. #endif
  114618. /* second step: 'all the other crap'; all the stuff that isn't
  114619. computed/fit for bitrate management goes in the second psy
  114620. vector. This includes tone masking, peak limiting and ATH */
  114621. _vp_tonemask(psy_look,
  114622. logfft,
  114623. tone,
  114624. global_ampmax,
  114625. local_ampmax[i]);
  114626. #if 0
  114627. if(vi->channels==2){
  114628. if(i==0)
  114629. _analysis_output("toneL",seq,tone,n/2,1,0,0);
  114630. else
  114631. _analysis_output("toneR",seq,tone,n/2,1,0,0);
  114632. }
  114633. #endif
  114634. /* third step; we offset the noise vectors, overlay tone
  114635. masking. We then do a floor1-specific line fit. If we're
  114636. performing bitrate management, the line fit is performed
  114637. multiple times for up/down tweakage on demand. */
  114638. #if 0
  114639. {
  114640. float aotuv[psy_look->n];
  114641. #endif
  114642. _vp_offset_and_mix(psy_look,
  114643. noise,
  114644. tone,
  114645. 1,
  114646. logmask,
  114647. mdct,
  114648. logmdct);
  114649. #if 0
  114650. if(vi->channels==2){
  114651. if(i==0)
  114652. _analysis_output("aotuvM1_L",seq,aotuv,psy_look->n,1,1,0);
  114653. else
  114654. _analysis_output("aotuvM1_R",seq,aotuv,psy_look->n,1,1,0);
  114655. }
  114656. }
  114657. #endif
  114658. #if 0
  114659. if(vi->channels==2){
  114660. if(i==0)
  114661. _analysis_output("mask1L",seq,logmask,n/2,1,0,0);
  114662. else
  114663. _analysis_output("mask1R",seq,logmask,n/2,1,0,0);
  114664. }
  114665. #endif
  114666. /* this algorithm is hardwired to floor 1 for now; abort out if
  114667. we're *not* floor1. This won't happen unless someone has
  114668. broken the encode setup lib. Guard it anyway. */
  114669. if(ci->floor_type[info->floorsubmap[submap]]!=1)return(-1);
  114670. floor_posts[i][PACKETBLOBS/2]=
  114671. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  114672. logmdct,
  114673. logmask);
  114674. /* are we managing bitrate? If so, perform two more fits for
  114675. later rate tweaking (fits represent hi/lo) */
  114676. if(vorbis_bitrate_managed(vb) && floor_posts[i][PACKETBLOBS/2]){
  114677. /* higher rate by way of lower noise curve */
  114678. _vp_offset_and_mix(psy_look,
  114679. noise,
  114680. tone,
  114681. 2,
  114682. logmask,
  114683. mdct,
  114684. logmdct);
  114685. #if 0
  114686. if(vi->channels==2){
  114687. if(i==0)
  114688. _analysis_output("mask2L",seq,logmask,n/2,1,0,0);
  114689. else
  114690. _analysis_output("mask2R",seq,logmask,n/2,1,0,0);
  114691. }
  114692. #endif
  114693. floor_posts[i][PACKETBLOBS-1]=
  114694. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  114695. logmdct,
  114696. logmask);
  114697. /* lower rate by way of higher noise curve */
  114698. _vp_offset_and_mix(psy_look,
  114699. noise,
  114700. tone,
  114701. 0,
  114702. logmask,
  114703. mdct,
  114704. logmdct);
  114705. #if 0
  114706. if(vi->channels==2)
  114707. if(i==0)
  114708. _analysis_output("mask0L",seq,logmask,n/2,1,0,0);
  114709. else
  114710. _analysis_output("mask0R",seq,logmask,n/2,1,0,0);
  114711. #endif
  114712. floor_posts[i][0]=
  114713. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  114714. logmdct,
  114715. logmask);
  114716. /* we also interpolate a range of intermediate curves for
  114717. intermediate rates */
  114718. for(k=1;k<PACKETBLOBS/2;k++)
  114719. floor_posts[i][k]=
  114720. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  114721. floor_posts[i][0],
  114722. floor_posts[i][PACKETBLOBS/2],
  114723. k*65536/(PACKETBLOBS/2));
  114724. for(k=PACKETBLOBS/2+1;k<PACKETBLOBS-1;k++)
  114725. floor_posts[i][k]=
  114726. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  114727. floor_posts[i][PACKETBLOBS/2],
  114728. floor_posts[i][PACKETBLOBS-1],
  114729. (k-PACKETBLOBS/2)*65536/(PACKETBLOBS/2));
  114730. }
  114731. }
  114732. }
  114733. vbi->ampmax=global_ampmax;
  114734. /*
  114735. the next phases are performed once for vbr-only and PACKETBLOB
  114736. times for bitrate managed modes.
  114737. 1) encode actual mode being used
  114738. 2) encode the floor for each channel, compute coded mask curve/res
  114739. 3) normalize and couple.
  114740. 4) encode residue
  114741. 5) save packet bytes to the packetblob vector
  114742. */
  114743. /* iterate over the many masking curve fits we've created */
  114744. {
  114745. float **res_bundle=(float**) alloca(sizeof(*res_bundle)*vi->channels);
  114746. float **couple_bundle=(float**) alloca(sizeof(*couple_bundle)*vi->channels);
  114747. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  114748. int **sortindex=(int**) alloca(sizeof(*sortindex)*vi->channels);
  114749. float **mag_memo;
  114750. int **mag_sort;
  114751. if(info->coupling_steps){
  114752. mag_memo=_vp_quantize_couple_memo(vb,
  114753. &ci->psy_g_param,
  114754. psy_look,
  114755. info,
  114756. gmdct);
  114757. mag_sort=_vp_quantize_couple_sort(vb,
  114758. psy_look,
  114759. info,
  114760. mag_memo);
  114761. hf_reduction(&ci->psy_g_param,
  114762. psy_look,
  114763. info,
  114764. mag_memo);
  114765. }
  114766. memset(sortindex,0,sizeof(*sortindex)*vi->channels);
  114767. if(psy_look->vi->normal_channel_p){
  114768. for(i=0;i<vi->channels;i++){
  114769. float *mdct =gmdct[i];
  114770. sortindex[i]=(int*) alloca(sizeof(**sortindex)*n/2);
  114771. _vp_noise_normalize_sort(psy_look,mdct,sortindex[i]);
  114772. }
  114773. }
  114774. for(k=(vorbis_bitrate_managed(vb)?0:PACKETBLOBS/2);
  114775. k<=(vorbis_bitrate_managed(vb)?PACKETBLOBS-1:PACKETBLOBS/2);
  114776. k++){
  114777. oggpack_buffer *opb=vbi->packetblob[k];
  114778. /* start out our new packet blob with packet type and mode */
  114779. /* Encode the packet type */
  114780. oggpack_write(opb,0,1);
  114781. /* Encode the modenumber */
  114782. /* Encode frame mode, pre,post windowsize, then dispatch */
  114783. oggpack_write(opb,modenumber,b->modebits);
  114784. if(vb->W){
  114785. oggpack_write(opb,vb->lW,1);
  114786. oggpack_write(opb,vb->nW,1);
  114787. }
  114788. /* encode floor, compute masking curve, sep out residue */
  114789. for(i=0;i<vi->channels;i++){
  114790. int submap=info->chmuxlist[i];
  114791. float *mdct =gmdct[i];
  114792. float *res =vb->pcm[i];
  114793. int *ilogmask=ilogmaskch[i]=
  114794. (int*) _vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  114795. nonzero[i]=floor1_encode(opb,vb,b->flr[info->floorsubmap[submap]],
  114796. floor_posts[i][k],
  114797. ilogmask);
  114798. #if 0
  114799. {
  114800. char buf[80];
  114801. sprintf(buf,"maskI%c%d",i?'R':'L',k);
  114802. float work[n/2];
  114803. for(j=0;j<n/2;j++)
  114804. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]];
  114805. _analysis_output(buf,seq,work,n/2,1,1,0);
  114806. }
  114807. #endif
  114808. _vp_remove_floor(psy_look,
  114809. mdct,
  114810. ilogmask,
  114811. res,
  114812. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  114813. _vp_noise_normalize(psy_look,res,res+n/2,sortindex[i]);
  114814. #if 0
  114815. {
  114816. char buf[80];
  114817. float work[n/2];
  114818. for(j=0;j<n/2;j++)
  114819. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]]*(res+n/2)[j];
  114820. sprintf(buf,"resI%c%d",i?'R':'L',k);
  114821. _analysis_output(buf,seq,work,n/2,1,1,0);
  114822. }
  114823. #endif
  114824. }
  114825. /* our iteration is now based on masking curve, not prequant and
  114826. coupling. Only one prequant/coupling step */
  114827. /* quantize/couple */
  114828. /* incomplete implementation that assumes the tree is all depth
  114829. one, or no tree at all */
  114830. if(info->coupling_steps){
  114831. _vp_couple(k,
  114832. &ci->psy_g_param,
  114833. psy_look,
  114834. info,
  114835. vb->pcm,
  114836. mag_memo,
  114837. mag_sort,
  114838. ilogmaskch,
  114839. nonzero,
  114840. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  114841. }
  114842. /* classify and encode by submap */
  114843. for(i=0;i<info->submaps;i++){
  114844. int ch_in_bundle=0;
  114845. long **classifications;
  114846. int resnum=info->residuesubmap[i];
  114847. for(j=0;j<vi->channels;j++){
  114848. if(info->chmuxlist[j]==i){
  114849. zerobundle[ch_in_bundle]=0;
  114850. if(nonzero[j])zerobundle[ch_in_bundle]=1;
  114851. res_bundle[ch_in_bundle]=vb->pcm[j];
  114852. couple_bundle[ch_in_bundle++]=vb->pcm[j]+n/2;
  114853. }
  114854. }
  114855. classifications=_residue_P[ci->residue_type[resnum]]->
  114856. classx(vb,b->residue[resnum],couple_bundle,zerobundle,ch_in_bundle);
  114857. _residue_P[ci->residue_type[resnum]]->
  114858. forward(opb,vb,b->residue[resnum],
  114859. couple_bundle,NULL,zerobundle,ch_in_bundle,classifications);
  114860. }
  114861. /* ok, done encoding. Next protopacket. */
  114862. }
  114863. }
  114864. #if 0
  114865. seq++;
  114866. total+=ci->blocksizes[vb->W]/4+ci->blocksizes[vb->nW]/4;
  114867. #endif
  114868. return(0);
  114869. }
  114870. static int mapping0_inverse(vorbis_block *vb,vorbis_info_mapping *l){
  114871. vorbis_dsp_state *vd=vb->vd;
  114872. vorbis_info *vi=vd->vi;
  114873. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  114874. private_state *b=(private_state*)vd->backend_state;
  114875. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)l;
  114876. int i,j;
  114877. long n=vb->pcmend=ci->blocksizes[vb->W];
  114878. float **pcmbundle=(float**) alloca(sizeof(*pcmbundle)*vi->channels);
  114879. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  114880. int *nonzero =(int*) alloca(sizeof(*nonzero)*vi->channels);
  114881. void **floormemo=(void**) alloca(sizeof(*floormemo)*vi->channels);
  114882. /* recover the spectral envelope; store it in the PCM vector for now */
  114883. for(i=0;i<vi->channels;i++){
  114884. int submap=info->chmuxlist[i];
  114885. floormemo[i]=_floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  114886. inverse1(vb,b->flr[info->floorsubmap[submap]]);
  114887. if(floormemo[i])
  114888. nonzero[i]=1;
  114889. else
  114890. nonzero[i]=0;
  114891. memset(vb->pcm[i],0,sizeof(*vb->pcm[i])*n/2);
  114892. }
  114893. /* channel coupling can 'dirty' the nonzero listing */
  114894. for(i=0;i<info->coupling_steps;i++){
  114895. if(nonzero[info->coupling_mag[i]] ||
  114896. nonzero[info->coupling_ang[i]]){
  114897. nonzero[info->coupling_mag[i]]=1;
  114898. nonzero[info->coupling_ang[i]]=1;
  114899. }
  114900. }
  114901. /* recover the residue into our working vectors */
  114902. for(i=0;i<info->submaps;i++){
  114903. int ch_in_bundle=0;
  114904. for(j=0;j<vi->channels;j++){
  114905. if(info->chmuxlist[j]==i){
  114906. if(nonzero[j])
  114907. zerobundle[ch_in_bundle]=1;
  114908. else
  114909. zerobundle[ch_in_bundle]=0;
  114910. pcmbundle[ch_in_bundle++]=vb->pcm[j];
  114911. }
  114912. }
  114913. _residue_P[ci->residue_type[info->residuesubmap[i]]]->
  114914. inverse(vb,b->residue[info->residuesubmap[i]],
  114915. pcmbundle,zerobundle,ch_in_bundle);
  114916. }
  114917. /* channel coupling */
  114918. for(i=info->coupling_steps-1;i>=0;i--){
  114919. float *pcmM=vb->pcm[info->coupling_mag[i]];
  114920. float *pcmA=vb->pcm[info->coupling_ang[i]];
  114921. for(j=0;j<n/2;j++){
  114922. float mag=pcmM[j];
  114923. float ang=pcmA[j];
  114924. if(mag>0)
  114925. if(ang>0){
  114926. pcmM[j]=mag;
  114927. pcmA[j]=mag-ang;
  114928. }else{
  114929. pcmA[j]=mag;
  114930. pcmM[j]=mag+ang;
  114931. }
  114932. else
  114933. if(ang>0){
  114934. pcmM[j]=mag;
  114935. pcmA[j]=mag+ang;
  114936. }else{
  114937. pcmA[j]=mag;
  114938. pcmM[j]=mag-ang;
  114939. }
  114940. }
  114941. }
  114942. /* compute and apply spectral envelope */
  114943. for(i=0;i<vi->channels;i++){
  114944. float *pcm=vb->pcm[i];
  114945. int submap=info->chmuxlist[i];
  114946. _floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  114947. inverse2(vb,b->flr[info->floorsubmap[submap]],
  114948. floormemo[i],pcm);
  114949. }
  114950. /* transform the PCM data; takes PCM vector, vb; modifies PCM vector */
  114951. /* only MDCT right now.... */
  114952. for(i=0;i<vi->channels;i++){
  114953. float *pcm=vb->pcm[i];
  114954. mdct_backward((mdct_lookup*) b->transform[vb->W][0],pcm,pcm);
  114955. }
  114956. /* all done! */
  114957. return(0);
  114958. }
  114959. /* export hooks */
  114960. vorbis_func_mapping mapping0_exportbundle={
  114961. &mapping0_pack,
  114962. &mapping0_unpack,
  114963. &mapping0_free_info,
  114964. &mapping0_forward,
  114965. &mapping0_inverse
  114966. };
  114967. #endif
  114968. /*** End of inlined file: mapping0.c ***/
  114969. /*** Start of inlined file: mdct.c ***/
  114970. /* this can also be run as an integer transform by uncommenting a
  114971. define in mdct.h; the integerization is a first pass and although
  114972. it's likely stable for Vorbis, the dynamic range is constrained and
  114973. roundoff isn't done (so it's noisy). Consider it functional, but
  114974. only a starting point. There's no point on a machine with an FPU */
  114975. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114976. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114977. // tasks..
  114978. #if JUCE_MSVC
  114979. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114980. #endif
  114981. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114982. #if JUCE_USE_OGGVORBIS
  114983. #include <stdio.h>
  114984. #include <stdlib.h>
  114985. #include <string.h>
  114986. #include <math.h>
  114987. /* build lookups for trig functions; also pre-figure scaling and
  114988. some window function algebra. */
  114989. void mdct_init(mdct_lookup *lookup,int n){
  114990. int *bitrev=(int*) _ogg_malloc(sizeof(*bitrev)*(n/4));
  114991. DATA_TYPE *T=(DATA_TYPE*) _ogg_malloc(sizeof(*T)*(n+n/4));
  114992. int i;
  114993. int n2=n>>1;
  114994. int log2n=lookup->log2n=rint(log((float)n)/log(2.f));
  114995. lookup->n=n;
  114996. lookup->trig=T;
  114997. lookup->bitrev=bitrev;
  114998. /* trig lookups... */
  114999. for(i=0;i<n/4;i++){
  115000. T[i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i)));
  115001. T[i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i)));
  115002. T[n2+i*2]=FLOAT_CONV(cos((M_PI/(2*n))*(2*i+1)));
  115003. T[n2+i*2+1]=FLOAT_CONV(sin((M_PI/(2*n))*(2*i+1)));
  115004. }
  115005. for(i=0;i<n/8;i++){
  115006. T[n+i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i+2))*.5);
  115007. T[n+i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i+2))*.5);
  115008. }
  115009. /* bitreverse lookup... */
  115010. {
  115011. int mask=(1<<(log2n-1))-1,i,j;
  115012. int msb=1<<(log2n-2);
  115013. for(i=0;i<n/8;i++){
  115014. int acc=0;
  115015. for(j=0;msb>>j;j++)
  115016. if((msb>>j)&i)acc|=1<<j;
  115017. bitrev[i*2]=((~acc)&mask)-1;
  115018. bitrev[i*2+1]=acc;
  115019. }
  115020. }
  115021. lookup->scale=FLOAT_CONV(4.f/n);
  115022. }
  115023. /* 8 point butterfly (in place, 4 register) */
  115024. STIN void mdct_butterfly_8(DATA_TYPE *x){
  115025. REG_TYPE r0 = x[6] + x[2];
  115026. REG_TYPE r1 = x[6] - x[2];
  115027. REG_TYPE r2 = x[4] + x[0];
  115028. REG_TYPE r3 = x[4] - x[0];
  115029. x[6] = r0 + r2;
  115030. x[4] = r0 - r2;
  115031. r0 = x[5] - x[1];
  115032. r2 = x[7] - x[3];
  115033. x[0] = r1 + r0;
  115034. x[2] = r1 - r0;
  115035. r0 = x[5] + x[1];
  115036. r1 = x[7] + x[3];
  115037. x[3] = r2 + r3;
  115038. x[1] = r2 - r3;
  115039. x[7] = r1 + r0;
  115040. x[5] = r1 - r0;
  115041. }
  115042. /* 16 point butterfly (in place, 4 register) */
  115043. STIN void mdct_butterfly_16(DATA_TYPE *x){
  115044. REG_TYPE r0 = x[1] - x[9];
  115045. REG_TYPE r1 = x[0] - x[8];
  115046. x[8] += x[0];
  115047. x[9] += x[1];
  115048. x[0] = MULT_NORM((r0 + r1) * cPI2_8);
  115049. x[1] = MULT_NORM((r0 - r1) * cPI2_8);
  115050. r0 = x[3] - x[11];
  115051. r1 = x[10] - x[2];
  115052. x[10] += x[2];
  115053. x[11] += x[3];
  115054. x[2] = r0;
  115055. x[3] = r1;
  115056. r0 = x[12] - x[4];
  115057. r1 = x[13] - x[5];
  115058. x[12] += x[4];
  115059. x[13] += x[5];
  115060. x[4] = MULT_NORM((r0 - r1) * cPI2_8);
  115061. x[5] = MULT_NORM((r0 + r1) * cPI2_8);
  115062. r0 = x[14] - x[6];
  115063. r1 = x[15] - x[7];
  115064. x[14] += x[6];
  115065. x[15] += x[7];
  115066. x[6] = r0;
  115067. x[7] = r1;
  115068. mdct_butterfly_8(x);
  115069. mdct_butterfly_8(x+8);
  115070. }
  115071. /* 32 point butterfly (in place, 4 register) */
  115072. STIN void mdct_butterfly_32(DATA_TYPE *x){
  115073. REG_TYPE r0 = x[30] - x[14];
  115074. REG_TYPE r1 = x[31] - x[15];
  115075. x[30] += x[14];
  115076. x[31] += x[15];
  115077. x[14] = r0;
  115078. x[15] = r1;
  115079. r0 = x[28] - x[12];
  115080. r1 = x[29] - x[13];
  115081. x[28] += x[12];
  115082. x[29] += x[13];
  115083. x[12] = MULT_NORM( r0 * cPI1_8 - r1 * cPI3_8 );
  115084. x[13] = MULT_NORM( r0 * cPI3_8 + r1 * cPI1_8 );
  115085. r0 = x[26] - x[10];
  115086. r1 = x[27] - x[11];
  115087. x[26] += x[10];
  115088. x[27] += x[11];
  115089. x[10] = MULT_NORM(( r0 - r1 ) * cPI2_8);
  115090. x[11] = MULT_NORM(( r0 + r1 ) * cPI2_8);
  115091. r0 = x[24] - x[8];
  115092. r1 = x[25] - x[9];
  115093. x[24] += x[8];
  115094. x[25] += x[9];
  115095. x[8] = MULT_NORM( r0 * cPI3_8 - r1 * cPI1_8 );
  115096. x[9] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  115097. r0 = x[22] - x[6];
  115098. r1 = x[7] - x[23];
  115099. x[22] += x[6];
  115100. x[23] += x[7];
  115101. x[6] = r1;
  115102. x[7] = r0;
  115103. r0 = x[4] - x[20];
  115104. r1 = x[5] - x[21];
  115105. x[20] += x[4];
  115106. x[21] += x[5];
  115107. x[4] = MULT_NORM( r1 * cPI1_8 + r0 * cPI3_8 );
  115108. x[5] = MULT_NORM( r1 * cPI3_8 - r0 * cPI1_8 );
  115109. r0 = x[2] - x[18];
  115110. r1 = x[3] - x[19];
  115111. x[18] += x[2];
  115112. x[19] += x[3];
  115113. x[2] = MULT_NORM(( r1 + r0 ) * cPI2_8);
  115114. x[3] = MULT_NORM(( r1 - r0 ) * cPI2_8);
  115115. r0 = x[0] - x[16];
  115116. r1 = x[1] - x[17];
  115117. x[16] += x[0];
  115118. x[17] += x[1];
  115119. x[0] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  115120. x[1] = MULT_NORM( r1 * cPI1_8 - r0 * cPI3_8 );
  115121. mdct_butterfly_16(x);
  115122. mdct_butterfly_16(x+16);
  115123. }
  115124. /* N point first stage butterfly (in place, 2 register) */
  115125. STIN void mdct_butterfly_first(DATA_TYPE *T,
  115126. DATA_TYPE *x,
  115127. int points){
  115128. DATA_TYPE *x1 = x + points - 8;
  115129. DATA_TYPE *x2 = x + (points>>1) - 8;
  115130. REG_TYPE r0;
  115131. REG_TYPE r1;
  115132. do{
  115133. r0 = x1[6] - x2[6];
  115134. r1 = x1[7] - x2[7];
  115135. x1[6] += x2[6];
  115136. x1[7] += x2[7];
  115137. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115138. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115139. r0 = x1[4] - x2[4];
  115140. r1 = x1[5] - x2[5];
  115141. x1[4] += x2[4];
  115142. x1[5] += x2[5];
  115143. x2[4] = MULT_NORM(r1 * T[5] + r0 * T[4]);
  115144. x2[5] = MULT_NORM(r1 * T[4] - r0 * T[5]);
  115145. r0 = x1[2] - x2[2];
  115146. r1 = x1[3] - x2[3];
  115147. x1[2] += x2[2];
  115148. x1[3] += x2[3];
  115149. x2[2] = MULT_NORM(r1 * T[9] + r0 * T[8]);
  115150. x2[3] = MULT_NORM(r1 * T[8] - r0 * T[9]);
  115151. r0 = x1[0] - x2[0];
  115152. r1 = x1[1] - x2[1];
  115153. x1[0] += x2[0];
  115154. x1[1] += x2[1];
  115155. x2[0] = MULT_NORM(r1 * T[13] + r0 * T[12]);
  115156. x2[1] = MULT_NORM(r1 * T[12] - r0 * T[13]);
  115157. x1-=8;
  115158. x2-=8;
  115159. T+=16;
  115160. }while(x2>=x);
  115161. }
  115162. /* N/stage point generic N stage butterfly (in place, 2 register) */
  115163. STIN void mdct_butterfly_generic(DATA_TYPE *T,
  115164. DATA_TYPE *x,
  115165. int points,
  115166. int trigint){
  115167. DATA_TYPE *x1 = x + points - 8;
  115168. DATA_TYPE *x2 = x + (points>>1) - 8;
  115169. REG_TYPE r0;
  115170. REG_TYPE r1;
  115171. do{
  115172. r0 = x1[6] - x2[6];
  115173. r1 = x1[7] - x2[7];
  115174. x1[6] += x2[6];
  115175. x1[7] += x2[7];
  115176. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115177. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115178. T+=trigint;
  115179. r0 = x1[4] - x2[4];
  115180. r1 = x1[5] - x2[5];
  115181. x1[4] += x2[4];
  115182. x1[5] += x2[5];
  115183. x2[4] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115184. x2[5] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115185. T+=trigint;
  115186. r0 = x1[2] - x2[2];
  115187. r1 = x1[3] - x2[3];
  115188. x1[2] += x2[2];
  115189. x1[3] += x2[3];
  115190. x2[2] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115191. x2[3] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115192. T+=trigint;
  115193. r0 = x1[0] - x2[0];
  115194. r1 = x1[1] - x2[1];
  115195. x1[0] += x2[0];
  115196. x1[1] += x2[1];
  115197. x2[0] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115198. x2[1] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115199. T+=trigint;
  115200. x1-=8;
  115201. x2-=8;
  115202. }while(x2>=x);
  115203. }
  115204. STIN void mdct_butterflies(mdct_lookup *init,
  115205. DATA_TYPE *x,
  115206. int points){
  115207. DATA_TYPE *T=init->trig;
  115208. int stages=init->log2n-5;
  115209. int i,j;
  115210. if(--stages>0){
  115211. mdct_butterfly_first(T,x,points);
  115212. }
  115213. for(i=1;--stages>0;i++){
  115214. for(j=0;j<(1<<i);j++)
  115215. mdct_butterfly_generic(T,x+(points>>i)*j,points>>i,4<<i);
  115216. }
  115217. for(j=0;j<points;j+=32)
  115218. mdct_butterfly_32(x+j);
  115219. }
  115220. void mdct_clear(mdct_lookup *l){
  115221. if(l){
  115222. if(l->trig)_ogg_free(l->trig);
  115223. if(l->bitrev)_ogg_free(l->bitrev);
  115224. memset(l,0,sizeof(*l));
  115225. }
  115226. }
  115227. STIN void mdct_bitreverse(mdct_lookup *init,
  115228. DATA_TYPE *x){
  115229. int n = init->n;
  115230. int *bit = init->bitrev;
  115231. DATA_TYPE *w0 = x;
  115232. DATA_TYPE *w1 = x = w0+(n>>1);
  115233. DATA_TYPE *T = init->trig+n;
  115234. do{
  115235. DATA_TYPE *x0 = x+bit[0];
  115236. DATA_TYPE *x1 = x+bit[1];
  115237. REG_TYPE r0 = x0[1] - x1[1];
  115238. REG_TYPE r1 = x0[0] + x1[0];
  115239. REG_TYPE r2 = MULT_NORM(r1 * T[0] + r0 * T[1]);
  115240. REG_TYPE r3 = MULT_NORM(r1 * T[1] - r0 * T[0]);
  115241. w1 -= 4;
  115242. r0 = HALVE(x0[1] + x1[1]);
  115243. r1 = HALVE(x0[0] - x1[0]);
  115244. w0[0] = r0 + r2;
  115245. w1[2] = r0 - r2;
  115246. w0[1] = r1 + r3;
  115247. w1[3] = r3 - r1;
  115248. x0 = x+bit[2];
  115249. x1 = x+bit[3];
  115250. r0 = x0[1] - x1[1];
  115251. r1 = x0[0] + x1[0];
  115252. r2 = MULT_NORM(r1 * T[2] + r0 * T[3]);
  115253. r3 = MULT_NORM(r1 * T[3] - r0 * T[2]);
  115254. r0 = HALVE(x0[1] + x1[1]);
  115255. r1 = HALVE(x0[0] - x1[0]);
  115256. w0[2] = r0 + r2;
  115257. w1[0] = r0 - r2;
  115258. w0[3] = r1 + r3;
  115259. w1[1] = r3 - r1;
  115260. T += 4;
  115261. bit += 4;
  115262. w0 += 4;
  115263. }while(w0<w1);
  115264. }
  115265. void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  115266. int n=init->n;
  115267. int n2=n>>1;
  115268. int n4=n>>2;
  115269. /* rotate */
  115270. DATA_TYPE *iX = in+n2-7;
  115271. DATA_TYPE *oX = out+n2+n4;
  115272. DATA_TYPE *T = init->trig+n4;
  115273. do{
  115274. oX -= 4;
  115275. oX[0] = MULT_NORM(-iX[2] * T[3] - iX[0] * T[2]);
  115276. oX[1] = MULT_NORM (iX[0] * T[3] - iX[2] * T[2]);
  115277. oX[2] = MULT_NORM(-iX[6] * T[1] - iX[4] * T[0]);
  115278. oX[3] = MULT_NORM (iX[4] * T[1] - iX[6] * T[0]);
  115279. iX -= 8;
  115280. T += 4;
  115281. }while(iX>=in);
  115282. iX = in+n2-8;
  115283. oX = out+n2+n4;
  115284. T = init->trig+n4;
  115285. do{
  115286. T -= 4;
  115287. oX[0] = MULT_NORM (iX[4] * T[3] + iX[6] * T[2]);
  115288. oX[1] = MULT_NORM (iX[4] * T[2] - iX[6] * T[3]);
  115289. oX[2] = MULT_NORM (iX[0] * T[1] + iX[2] * T[0]);
  115290. oX[3] = MULT_NORM (iX[0] * T[0] - iX[2] * T[1]);
  115291. iX -= 8;
  115292. oX += 4;
  115293. }while(iX>=in);
  115294. mdct_butterflies(init,out+n2,n2);
  115295. mdct_bitreverse(init,out);
  115296. /* roatate + window */
  115297. {
  115298. DATA_TYPE *oX1=out+n2+n4;
  115299. DATA_TYPE *oX2=out+n2+n4;
  115300. DATA_TYPE *iX =out;
  115301. T =init->trig+n2;
  115302. do{
  115303. oX1-=4;
  115304. oX1[3] = MULT_NORM (iX[0] * T[1] - iX[1] * T[0]);
  115305. oX2[0] = -MULT_NORM (iX[0] * T[0] + iX[1] * T[1]);
  115306. oX1[2] = MULT_NORM (iX[2] * T[3] - iX[3] * T[2]);
  115307. oX2[1] = -MULT_NORM (iX[2] * T[2] + iX[3] * T[3]);
  115308. oX1[1] = MULT_NORM (iX[4] * T[5] - iX[5] * T[4]);
  115309. oX2[2] = -MULT_NORM (iX[4] * T[4] + iX[5] * T[5]);
  115310. oX1[0] = MULT_NORM (iX[6] * T[7] - iX[7] * T[6]);
  115311. oX2[3] = -MULT_NORM (iX[6] * T[6] + iX[7] * T[7]);
  115312. oX2+=4;
  115313. iX += 8;
  115314. T += 8;
  115315. }while(iX<oX1);
  115316. iX=out+n2+n4;
  115317. oX1=out+n4;
  115318. oX2=oX1;
  115319. do{
  115320. oX1-=4;
  115321. iX-=4;
  115322. oX2[0] = -(oX1[3] = iX[3]);
  115323. oX2[1] = -(oX1[2] = iX[2]);
  115324. oX2[2] = -(oX1[1] = iX[1]);
  115325. oX2[3] = -(oX1[0] = iX[0]);
  115326. oX2+=4;
  115327. }while(oX2<iX);
  115328. iX=out+n2+n4;
  115329. oX1=out+n2+n4;
  115330. oX2=out+n2;
  115331. do{
  115332. oX1-=4;
  115333. oX1[0]= iX[3];
  115334. oX1[1]= iX[2];
  115335. oX1[2]= iX[1];
  115336. oX1[3]= iX[0];
  115337. iX+=4;
  115338. }while(oX1>oX2);
  115339. }
  115340. }
  115341. void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  115342. int n=init->n;
  115343. int n2=n>>1;
  115344. int n4=n>>2;
  115345. int n8=n>>3;
  115346. DATA_TYPE *w=(DATA_TYPE*) alloca(n*sizeof(*w)); /* forward needs working space */
  115347. DATA_TYPE *w2=w+n2;
  115348. /* rotate */
  115349. /* window + rotate + step 1 */
  115350. REG_TYPE r0;
  115351. REG_TYPE r1;
  115352. DATA_TYPE *x0=in+n2+n4;
  115353. DATA_TYPE *x1=x0+1;
  115354. DATA_TYPE *T=init->trig+n2;
  115355. int i=0;
  115356. for(i=0;i<n8;i+=2){
  115357. x0 -=4;
  115358. T-=2;
  115359. r0= x0[2] + x1[0];
  115360. r1= x0[0] + x1[2];
  115361. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  115362. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  115363. x1 +=4;
  115364. }
  115365. x1=in+1;
  115366. for(;i<n2-n8;i+=2){
  115367. T-=2;
  115368. x0 -=4;
  115369. r0= x0[2] - x1[0];
  115370. r1= x0[0] - x1[2];
  115371. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  115372. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  115373. x1 +=4;
  115374. }
  115375. x0=in+n;
  115376. for(;i<n2;i+=2){
  115377. T-=2;
  115378. x0 -=4;
  115379. r0= -x0[2] - x1[0];
  115380. r1= -x0[0] - x1[2];
  115381. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  115382. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  115383. x1 +=4;
  115384. }
  115385. mdct_butterflies(init,w+n2,n2);
  115386. mdct_bitreverse(init,w);
  115387. /* roatate + window */
  115388. T=init->trig+n2;
  115389. x0=out+n2;
  115390. for(i=0;i<n4;i++){
  115391. x0--;
  115392. out[i] =MULT_NORM((w[0]*T[0]+w[1]*T[1])*init->scale);
  115393. x0[0] =MULT_NORM((w[0]*T[1]-w[1]*T[0])*init->scale);
  115394. w+=2;
  115395. T+=2;
  115396. }
  115397. }
  115398. #endif
  115399. /*** End of inlined file: mdct.c ***/
  115400. /*** Start of inlined file: psy.c ***/
  115401. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115402. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115403. // tasks..
  115404. #if JUCE_MSVC
  115405. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115406. #endif
  115407. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115408. #if JUCE_USE_OGGVORBIS
  115409. #include <stdlib.h>
  115410. #include <math.h>
  115411. #include <string.h>
  115412. /*** Start of inlined file: masking.h ***/
  115413. #ifndef _V_MASKING_H_
  115414. #define _V_MASKING_H_
  115415. /* more detailed ATH; the bass if flat to save stressing the floor
  115416. overly for only a bin or two of savings. */
  115417. #define MAX_ATH 88
  115418. static float ATH[]={
  115419. /*15*/ -51, -52, -53, -54, -55, -56, -57, -58,
  115420. /*31*/ -59, -60, -61, -62, -63, -64, -65, -66,
  115421. /*63*/ -67, -68, -69, -70, -71, -72, -73, -74,
  115422. /*125*/ -75, -76, -77, -78, -80, -81, -82, -83,
  115423. /*250*/ -84, -85, -86, -87, -88, -88, -89, -89,
  115424. /*500*/ -90, -91, -91, -92, -93, -94, -95, -96,
  115425. /*1k*/ -96, -97, -98, -98, -99, -99,-100,-100,
  115426. /*2k*/ -101,-102,-103,-104,-106,-107,-107,-107,
  115427. /*4k*/ -107,-105,-103,-102,-101, -99, -98, -96,
  115428. /*8k*/ -95, -95, -96, -97, -96, -95, -93, -90,
  115429. /*16k*/ -80, -70, -50, -40, -30, -30, -30, -30
  115430. };
  115431. /* The tone masking curves from Ehmer's and Fielder's papers have been
  115432. replaced by an empirically collected data set. The previously
  115433. published values were, far too often, simply on crack. */
  115434. #define EHMER_OFFSET 16
  115435. #define EHMER_MAX 56
  115436. /* masking tones from -50 to 0dB, 62.5 through 16kHz at half octaves
  115437. test tones from -2 octaves to +5 octaves sampled at eighth octaves */
  115438. /* (Vorbis 0dB, the loudest possible tone, is assumed to be ~100dB SPL
  115439. for collection of these curves) */
  115440. static float tonemasks[P_BANDS][6][EHMER_MAX]={
  115441. /* 62.5 Hz */
  115442. {{ -60, -60, -60, -60, -60, -60, -60, -60,
  115443. -60, -60, -60, -60, -62, -62, -65, -73,
  115444. -69, -68, -68, -67, -70, -70, -72, -74,
  115445. -75, -79, -79, -80, -83, -88, -93, -100,
  115446. -110, -999, -999, -999, -999, -999, -999, -999,
  115447. -999, -999, -999, -999, -999, -999, -999, -999,
  115448. -999, -999, -999, -999, -999, -999, -999, -999},
  115449. { -48, -48, -48, -48, -48, -48, -48, -48,
  115450. -48, -48, -48, -48, -48, -53, -61, -66,
  115451. -66, -68, -67, -70, -76, -76, -72, -73,
  115452. -75, -76, -78, -79, -83, -88, -93, -100,
  115453. -110, -999, -999, -999, -999, -999, -999, -999,
  115454. -999, -999, -999, -999, -999, -999, -999, -999,
  115455. -999, -999, -999, -999, -999, -999, -999, -999},
  115456. { -37, -37, -37, -37, -37, -37, -37, -37,
  115457. -38, -40, -42, -46, -48, -53, -55, -62,
  115458. -65, -58, -56, -56, -61, -60, -65, -67,
  115459. -69, -71, -77, -77, -78, -80, -82, -84,
  115460. -88, -93, -98, -106, -112, -999, -999, -999,
  115461. -999, -999, -999, -999, -999, -999, -999, -999,
  115462. -999, -999, -999, -999, -999, -999, -999, -999},
  115463. { -25, -25, -25, -25, -25, -25, -25, -25,
  115464. -25, -26, -27, -29, -32, -38, -48, -52,
  115465. -52, -50, -48, -48, -51, -52, -54, -60,
  115466. -67, -67, -66, -68, -69, -73, -73, -76,
  115467. -80, -81, -81, -85, -85, -86, -88, -93,
  115468. -100, -110, -999, -999, -999, -999, -999, -999,
  115469. -999, -999, -999, -999, -999, -999, -999, -999},
  115470. { -16, -16, -16, -16, -16, -16, -16, -16,
  115471. -17, -19, -20, -22, -26, -28, -31, -40,
  115472. -47, -39, -39, -40, -42, -43, -47, -51,
  115473. -57, -52, -55, -55, -60, -58, -62, -63,
  115474. -70, -67, -69, -72, -73, -77, -80, -82,
  115475. -83, -87, -90, -94, -98, -104, -115, -999,
  115476. -999, -999, -999, -999, -999, -999, -999, -999},
  115477. { -8, -8, -8, -8, -8, -8, -8, -8,
  115478. -8, -8, -10, -11, -15, -19, -25, -30,
  115479. -34, -31, -30, -31, -29, -32, -35, -42,
  115480. -48, -42, -44, -46, -50, -50, -51, -52,
  115481. -59, -54, -55, -55, -58, -62, -63, -66,
  115482. -72, -73, -76, -75, -78, -80, -80, -81,
  115483. -84, -88, -90, -94, -98, -101, -106, -110}},
  115484. /* 88Hz */
  115485. {{ -66, -66, -66, -66, -66, -66, -66, -66,
  115486. -66, -66, -66, -66, -66, -67, -67, -67,
  115487. -76, -72, -71, -74, -76, -76, -75, -78,
  115488. -79, -79, -81, -83, -86, -89, -93, -97,
  115489. -100, -105, -110, -999, -999, -999, -999, -999,
  115490. -999, -999, -999, -999, -999, -999, -999, -999,
  115491. -999, -999, -999, -999, -999, -999, -999, -999},
  115492. { -47, -47, -47, -47, -47, -47, -47, -47,
  115493. -47, -47, -47, -48, -51, -55, -59, -66,
  115494. -66, -66, -67, -66, -68, -69, -70, -74,
  115495. -79, -77, -77, -78, -80, -81, -82, -84,
  115496. -86, -88, -91, -95, -100, -108, -116, -999,
  115497. -999, -999, -999, -999, -999, -999, -999, -999,
  115498. -999, -999, -999, -999, -999, -999, -999, -999},
  115499. { -36, -36, -36, -36, -36, -36, -36, -36,
  115500. -36, -37, -37, -41, -44, -48, -51, -58,
  115501. -62, -60, -57, -59, -59, -60, -63, -65,
  115502. -72, -71, -70, -72, -74, -77, -76, -78,
  115503. -81, -81, -80, -83, -86, -91, -96, -100,
  115504. -105, -110, -999, -999, -999, -999, -999, -999,
  115505. -999, -999, -999, -999, -999, -999, -999, -999},
  115506. { -28, -28, -28, -28, -28, -28, -28, -28,
  115507. -28, -30, -32, -32, -33, -35, -41, -49,
  115508. -50, -49, -47, -48, -48, -52, -51, -57,
  115509. -65, -61, -59, -61, -64, -69, -70, -74,
  115510. -77, -77, -78, -81, -84, -85, -87, -90,
  115511. -92, -96, -100, -107, -112, -999, -999, -999,
  115512. -999, -999, -999, -999, -999, -999, -999, -999},
  115513. { -19, -19, -19, -19, -19, -19, -19, -19,
  115514. -20, -21, -23, -27, -30, -35, -36, -41,
  115515. -46, -44, -42, -40, -41, -41, -43, -48,
  115516. -55, -53, -52, -53, -56, -59, -58, -60,
  115517. -67, -66, -69, -71, -72, -75, -79, -81,
  115518. -84, -87, -90, -93, -97, -101, -107, -114,
  115519. -999, -999, -999, -999, -999, -999, -999, -999},
  115520. { -9, -9, -9, -9, -9, -9, -9, -9,
  115521. -11, -12, -12, -15, -16, -20, -23, -30,
  115522. -37, -34, -33, -34, -31, -32, -32, -38,
  115523. -47, -44, -41, -40, -47, -49, -46, -46,
  115524. -58, -50, -50, -54, -58, -62, -64, -67,
  115525. -67, -70, -72, -76, -79, -83, -87, -91,
  115526. -96, -100, -104, -110, -999, -999, -999, -999}},
  115527. /* 125 Hz */
  115528. {{ -62, -62, -62, -62, -62, -62, -62, -62,
  115529. -62, -62, -63, -64, -66, -67, -66, -68,
  115530. -75, -72, -76, -75, -76, -78, -79, -82,
  115531. -84, -85, -90, -94, -101, -110, -999, -999,
  115532. -999, -999, -999, -999, -999, -999, -999, -999,
  115533. -999, -999, -999, -999, -999, -999, -999, -999,
  115534. -999, -999, -999, -999, -999, -999, -999, -999},
  115535. { -59, -59, -59, -59, -59, -59, -59, -59,
  115536. -59, -59, -59, -60, -60, -61, -63, -66,
  115537. -71, -68, -70, -70, -71, -72, -72, -75,
  115538. -81, -78, -79, -82, -83, -86, -90, -97,
  115539. -103, -113, -999, -999, -999, -999, -999, -999,
  115540. -999, -999, -999, -999, -999, -999, -999, -999,
  115541. -999, -999, -999, -999, -999, -999, -999, -999},
  115542. { -53, -53, -53, -53, -53, -53, -53, -53,
  115543. -53, -54, -55, -57, -56, -57, -55, -61,
  115544. -65, -60, -60, -62, -63, -63, -66, -68,
  115545. -74, -73, -75, -75, -78, -80, -80, -82,
  115546. -85, -90, -96, -101, -108, -999, -999, -999,
  115547. -999, -999, -999, -999, -999, -999, -999, -999,
  115548. -999, -999, -999, -999, -999, -999, -999, -999},
  115549. { -46, -46, -46, -46, -46, -46, -46, -46,
  115550. -46, -46, -47, -47, -47, -47, -48, -51,
  115551. -57, -51, -49, -50, -51, -53, -54, -59,
  115552. -66, -60, -62, -67, -67, -70, -72, -75,
  115553. -76, -78, -81, -85, -88, -94, -97, -104,
  115554. -112, -999, -999, -999, -999, -999, -999, -999,
  115555. -999, -999, -999, -999, -999, -999, -999, -999},
  115556. { -36, -36, -36, -36, -36, -36, -36, -36,
  115557. -39, -41, -42, -42, -39, -38, -41, -43,
  115558. -52, -44, -40, -39, -37, -37, -40, -47,
  115559. -54, -50, -48, -50, -55, -61, -59, -62,
  115560. -66, -66, -66, -69, -69, -73, -74, -74,
  115561. -75, -77, -79, -82, -87, -91, -95, -100,
  115562. -108, -115, -999, -999, -999, -999, -999, -999},
  115563. { -28, -26, -24, -22, -20, -20, -23, -29,
  115564. -30, -31, -28, -27, -28, -28, -28, -35,
  115565. -40, -33, -32, -29, -30, -30, -30, -37,
  115566. -45, -41, -37, -38, -45, -47, -47, -48,
  115567. -53, -49, -48, -50, -49, -49, -51, -52,
  115568. -58, -56, -57, -56, -60, -61, -62, -70,
  115569. -72, -74, -78, -83, -88, -93, -100, -106}},
  115570. /* 177 Hz */
  115571. {{-999, -999, -999, -999, -999, -999, -999, -999,
  115572. -999, -110, -105, -100, -95, -91, -87, -83,
  115573. -80, -78, -76, -78, -78, -81, -83, -85,
  115574. -86, -85, -86, -87, -90, -97, -107, -999,
  115575. -999, -999, -999, -999, -999, -999, -999, -999,
  115576. -999, -999, -999, -999, -999, -999, -999, -999,
  115577. -999, -999, -999, -999, -999, -999, -999, -999},
  115578. {-999, -999, -999, -110, -105, -100, -95, -90,
  115579. -85, -81, -77, -73, -70, -67, -67, -68,
  115580. -75, -73, -70, -69, -70, -72, -75, -79,
  115581. -84, -83, -84, -86, -88, -89, -89, -93,
  115582. -98, -105, -112, -999, -999, -999, -999, -999,
  115583. -999, -999, -999, -999, -999, -999, -999, -999,
  115584. -999, -999, -999, -999, -999, -999, -999, -999},
  115585. {-105, -100, -95, -90, -85, -80, -76, -71,
  115586. -68, -68, -65, -63, -63, -62, -62, -64,
  115587. -65, -64, -61, -62, -63, -64, -66, -68,
  115588. -73, -73, -74, -75, -76, -81, -83, -85,
  115589. -88, -89, -92, -95, -100, -108, -999, -999,
  115590. -999, -999, -999, -999, -999, -999, -999, -999,
  115591. -999, -999, -999, -999, -999, -999, -999, -999},
  115592. { -80, -75, -71, -68, -65, -63, -62, -61,
  115593. -61, -61, -61, -59, -56, -57, -53, -50,
  115594. -58, -52, -50, -50, -52, -53, -54, -58,
  115595. -67, -63, -67, -68, -72, -75, -78, -80,
  115596. -81, -81, -82, -85, -89, -90, -93, -97,
  115597. -101, -107, -114, -999, -999, -999, -999, -999,
  115598. -999, -999, -999, -999, -999, -999, -999, -999},
  115599. { -65, -61, -59, -57, -56, -55, -55, -56,
  115600. -56, -57, -55, -53, -52, -47, -44, -44,
  115601. -50, -44, -41, -39, -39, -42, -40, -46,
  115602. -51, -49, -50, -53, -54, -63, -60, -61,
  115603. -62, -66, -66, -66, -70, -73, -74, -75,
  115604. -76, -75, -79, -85, -89, -91, -96, -102,
  115605. -110, -999, -999, -999, -999, -999, -999, -999},
  115606. { -52, -50, -49, -49, -48, -48, -48, -49,
  115607. -50, -50, -49, -46, -43, -39, -35, -33,
  115608. -38, -36, -32, -29, -32, -32, -32, -35,
  115609. -44, -39, -38, -38, -46, -50, -45, -46,
  115610. -53, -50, -50, -50, -54, -54, -53, -53,
  115611. -56, -57, -59, -66, -70, -72, -74, -79,
  115612. -83, -85, -90, -97, -114, -999, -999, -999}},
  115613. /* 250 Hz */
  115614. {{-999, -999, -999, -999, -999, -999, -110, -105,
  115615. -100, -95, -90, -86, -80, -75, -75, -79,
  115616. -80, -79, -80, -81, -82, -88, -95, -103,
  115617. -110, -999, -999, -999, -999, -999, -999, -999,
  115618. -999, -999, -999, -999, -999, -999, -999, -999,
  115619. -999, -999, -999, -999, -999, -999, -999, -999,
  115620. -999, -999, -999, -999, -999, -999, -999, -999},
  115621. {-999, -999, -999, -999, -108, -103, -98, -93,
  115622. -88, -83, -79, -78, -75, -71, -67, -68,
  115623. -73, -73, -72, -73, -75, -77, -80, -82,
  115624. -88, -93, -100, -107, -114, -999, -999, -999,
  115625. -999, -999, -999, -999, -999, -999, -999, -999,
  115626. -999, -999, -999, -999, -999, -999, -999, -999,
  115627. -999, -999, -999, -999, -999, -999, -999, -999},
  115628. {-999, -999, -999, -110, -105, -101, -96, -90,
  115629. -86, -81, -77, -73, -69, -66, -61, -62,
  115630. -66, -64, -62, -65, -66, -70, -72, -76,
  115631. -81, -80, -84, -90, -95, -102, -110, -999,
  115632. -999, -999, -999, -999, -999, -999, -999, -999,
  115633. -999, -999, -999, -999, -999, -999, -999, -999,
  115634. -999, -999, -999, -999, -999, -999, -999, -999},
  115635. {-999, -999, -999, -107, -103, -97, -92, -88,
  115636. -83, -79, -74, -70, -66, -59, -53, -58,
  115637. -62, -55, -54, -54, -54, -58, -61, -62,
  115638. -72, -70, -72, -75, -78, -80, -81, -80,
  115639. -83, -83, -88, -93, -100, -107, -115, -999,
  115640. -999, -999, -999, -999, -999, -999, -999, -999,
  115641. -999, -999, -999, -999, -999, -999, -999, -999},
  115642. {-999, -999, -999, -105, -100, -95, -90, -85,
  115643. -80, -75, -70, -66, -62, -56, -48, -44,
  115644. -48, -46, -46, -43, -46, -48, -48, -51,
  115645. -58, -58, -59, -60, -62, -62, -61, -61,
  115646. -65, -64, -65, -68, -70, -74, -75, -78,
  115647. -81, -86, -95, -110, -999, -999, -999, -999,
  115648. -999, -999, -999, -999, -999, -999, -999, -999},
  115649. {-999, -999, -105, -100, -95, -90, -85, -80,
  115650. -75, -70, -65, -61, -55, -49, -39, -33,
  115651. -40, -35, -32, -38, -40, -33, -35, -37,
  115652. -46, -41, -45, -44, -46, -42, -45, -46,
  115653. -52, -50, -50, -50, -54, -54, -55, -57,
  115654. -62, -64, -66, -68, -70, -76, -81, -90,
  115655. -100, -110, -999, -999, -999, -999, -999, -999}},
  115656. /* 354 hz */
  115657. {{-999, -999, -999, -999, -999, -999, -999, -999,
  115658. -105, -98, -90, -85, -82, -83, -80, -78,
  115659. -84, -79, -80, -83, -87, -89, -91, -93,
  115660. -99, -106, -117, -999, -999, -999, -999, -999,
  115661. -999, -999, -999, -999, -999, -999, -999, -999,
  115662. -999, -999, -999, -999, -999, -999, -999, -999,
  115663. -999, -999, -999, -999, -999, -999, -999, -999},
  115664. {-999, -999, -999, -999, -999, -999, -999, -999,
  115665. -105, -98, -90, -85, -80, -75, -70, -68,
  115666. -74, -72, -74, -77, -80, -82, -85, -87,
  115667. -92, -89, -91, -95, -100, -106, -112, -999,
  115668. -999, -999, -999, -999, -999, -999, -999, -999,
  115669. -999, -999, -999, -999, -999, -999, -999, -999,
  115670. -999, -999, -999, -999, -999, -999, -999, -999},
  115671. {-999, -999, -999, -999, -999, -999, -999, -999,
  115672. -105, -98, -90, -83, -75, -71, -63, -64,
  115673. -67, -62, -64, -67, -70, -73, -77, -81,
  115674. -84, -83, -85, -89, -90, -93, -98, -104,
  115675. -109, -114, -999, -999, -999, -999, -999, -999,
  115676. -999, -999, -999, -999, -999, -999, -999, -999,
  115677. -999, -999, -999, -999, -999, -999, -999, -999},
  115678. {-999, -999, -999, -999, -999, -999, -999, -999,
  115679. -103, -96, -88, -81, -75, -68, -58, -54,
  115680. -56, -54, -56, -56, -58, -60, -63, -66,
  115681. -74, -69, -72, -72, -75, -74, -77, -81,
  115682. -81, -82, -84, -87, -93, -96, -99, -104,
  115683. -110, -999, -999, -999, -999, -999, -999, -999,
  115684. -999, -999, -999, -999, -999, -999, -999, -999},
  115685. {-999, -999, -999, -999, -999, -108, -102, -96,
  115686. -91, -85, -80, -74, -68, -60, -51, -46,
  115687. -48, -46, -43, -45, -47, -47, -49, -48,
  115688. -56, -53, -55, -58, -57, -63, -58, -60,
  115689. -66, -64, -67, -70, -70, -74, -77, -84,
  115690. -86, -89, -91, -93, -94, -101, -109, -118,
  115691. -999, -999, -999, -999, -999, -999, -999, -999},
  115692. {-999, -999, -999, -108, -103, -98, -93, -88,
  115693. -83, -78, -73, -68, -60, -53, -44, -35,
  115694. -38, -38, -34, -34, -36, -40, -41, -44,
  115695. -51, -45, -46, -47, -46, -54, -50, -49,
  115696. -50, -50, -50, -51, -54, -57, -58, -60,
  115697. -66, -66, -66, -64, -65, -68, -77, -82,
  115698. -87, -95, -110, -999, -999, -999, -999, -999}},
  115699. /* 500 Hz */
  115700. {{-999, -999, -999, -999, -999, -999, -999, -999,
  115701. -107, -102, -97, -92, -87, -83, -78, -75,
  115702. -82, -79, -83, -85, -89, -92, -95, -98,
  115703. -101, -105, -109, -113, -999, -999, -999, -999,
  115704. -999, -999, -999, -999, -999, -999, -999, -999,
  115705. -999, -999, -999, -999, -999, -999, -999, -999,
  115706. -999, -999, -999, -999, -999, -999, -999, -999},
  115707. {-999, -999, -999, -999, -999, -999, -999, -106,
  115708. -100, -95, -90, -86, -81, -78, -74, -69,
  115709. -74, -74, -76, -79, -83, -84, -86, -89,
  115710. -92, -97, -93, -100, -103, -107, -110, -999,
  115711. -999, -999, -999, -999, -999, -999, -999, -999,
  115712. -999, -999, -999, -999, -999, -999, -999, -999,
  115713. -999, -999, -999, -999, -999, -999, -999, -999},
  115714. {-999, -999, -999, -999, -999, -999, -106, -100,
  115715. -95, -90, -87, -83, -80, -75, -69, -60,
  115716. -66, -66, -68, -70, -74, -78, -79, -81,
  115717. -81, -83, -84, -87, -93, -96, -99, -103,
  115718. -107, -110, -999, -999, -999, -999, -999, -999,
  115719. -999, -999, -999, -999, -999, -999, -999, -999,
  115720. -999, -999, -999, -999, -999, -999, -999, -999},
  115721. {-999, -999, -999, -999, -999, -108, -103, -98,
  115722. -93, -89, -85, -82, -78, -71, -62, -55,
  115723. -58, -58, -54, -54, -55, -59, -61, -62,
  115724. -70, -66, -66, -67, -70, -72, -75, -78,
  115725. -84, -84, -84, -88, -91, -90, -95, -98,
  115726. -102, -103, -106, -110, -999, -999, -999, -999,
  115727. -999, -999, -999, -999, -999, -999, -999, -999},
  115728. {-999, -999, -999, -999, -108, -103, -98, -94,
  115729. -90, -87, -82, -79, -73, -67, -58, -47,
  115730. -50, -45, -41, -45, -48, -44, -44, -49,
  115731. -54, -51, -48, -47, -49, -50, -51, -57,
  115732. -58, -60, -63, -69, -70, -69, -71, -74,
  115733. -78, -82, -90, -95, -101, -105, -110, -999,
  115734. -999, -999, -999, -999, -999, -999, -999, -999},
  115735. {-999, -999, -999, -105, -101, -97, -93, -90,
  115736. -85, -80, -77, -72, -65, -56, -48, -37,
  115737. -40, -36, -34, -40, -50, -47, -38, -41,
  115738. -47, -38, -35, -39, -38, -43, -40, -45,
  115739. -50, -45, -44, -47, -50, -55, -48, -48,
  115740. -52, -66, -70, -76, -82, -90, -97, -105,
  115741. -110, -999, -999, -999, -999, -999, -999, -999}},
  115742. /* 707 Hz */
  115743. {{-999, -999, -999, -999, -999, -999, -999, -999,
  115744. -999, -108, -103, -98, -93, -86, -79, -76,
  115745. -83, -81, -85, -87, -89, -93, -98, -102,
  115746. -107, -112, -999, -999, -999, -999, -999, -999,
  115747. -999, -999, -999, -999, -999, -999, -999, -999,
  115748. -999, -999, -999, -999, -999, -999, -999, -999,
  115749. -999, -999, -999, -999, -999, -999, -999, -999},
  115750. {-999, -999, -999, -999, -999, -999, -999, -999,
  115751. -999, -108, -103, -98, -93, -86, -79, -71,
  115752. -77, -74, -77, -79, -81, -84, -85, -90,
  115753. -92, -93, -92, -98, -101, -108, -112, -999,
  115754. -999, -999, -999, -999, -999, -999, -999, -999,
  115755. -999, -999, -999, -999, -999, -999, -999, -999,
  115756. -999, -999, -999, -999, -999, -999, -999, -999},
  115757. {-999, -999, -999, -999, -999, -999, -999, -999,
  115758. -108, -103, -98, -93, -87, -78, -68, -65,
  115759. -66, -62, -65, -67, -70, -73, -75, -78,
  115760. -82, -82, -83, -84, -91, -93, -98, -102,
  115761. -106, -110, -999, -999, -999, -999, -999, -999,
  115762. -999, -999, -999, -999, -999, -999, -999, -999,
  115763. -999, -999, -999, -999, -999, -999, -999, -999},
  115764. {-999, -999, -999, -999, -999, -999, -999, -999,
  115765. -105, -100, -95, -90, -82, -74, -62, -57,
  115766. -58, -56, -51, -52, -52, -54, -54, -58,
  115767. -66, -59, -60, -63, -66, -69, -73, -79,
  115768. -83, -84, -80, -81, -81, -82, -88, -92,
  115769. -98, -105, -113, -999, -999, -999, -999, -999,
  115770. -999, -999, -999, -999, -999, -999, -999, -999},
  115771. {-999, -999, -999, -999, -999, -999, -999, -107,
  115772. -102, -97, -92, -84, -79, -69, -57, -47,
  115773. -52, -47, -44, -45, -50, -52, -42, -42,
  115774. -53, -43, -43, -48, -51, -56, -55, -52,
  115775. -57, -59, -61, -62, -67, -71, -78, -83,
  115776. -86, -94, -98, -103, -110, -999, -999, -999,
  115777. -999, -999, -999, -999, -999, -999, -999, -999},
  115778. {-999, -999, -999, -999, -999, -999, -105, -100,
  115779. -95, -90, -84, -78, -70, -61, -51, -41,
  115780. -40, -38, -40, -46, -52, -51, -41, -40,
  115781. -46, -40, -38, -38, -41, -46, -41, -46,
  115782. -47, -43, -43, -45, -41, -45, -56, -67,
  115783. -68, -83, -87, -90, -95, -102, -107, -113,
  115784. -999, -999, -999, -999, -999, -999, -999, -999}},
  115785. /* 1000 Hz */
  115786. {{-999, -999, -999, -999, -999, -999, -999, -999,
  115787. -999, -109, -105, -101, -96, -91, -84, -77,
  115788. -82, -82, -85, -89, -94, -100, -106, -110,
  115789. -999, -999, -999, -999, -999, -999, -999, -999,
  115790. -999, -999, -999, -999, -999, -999, -999, -999,
  115791. -999, -999, -999, -999, -999, -999, -999, -999,
  115792. -999, -999, -999, -999, -999, -999, -999, -999},
  115793. {-999, -999, -999, -999, -999, -999, -999, -999,
  115794. -999, -106, -103, -98, -92, -85, -80, -71,
  115795. -75, -72, -76, -80, -84, -86, -89, -93,
  115796. -100, -107, -113, -999, -999, -999, -999, -999,
  115797. -999, -999, -999, -999, -999, -999, -999, -999,
  115798. -999, -999, -999, -999, -999, -999, -999, -999,
  115799. -999, -999, -999, -999, -999, -999, -999, -999},
  115800. {-999, -999, -999, -999, -999, -999, -999, -107,
  115801. -104, -101, -97, -92, -88, -84, -80, -64,
  115802. -66, -63, -64, -66, -69, -73, -77, -83,
  115803. -83, -86, -91, -98, -104, -111, -999, -999,
  115804. -999, -999, -999, -999, -999, -999, -999, -999,
  115805. -999, -999, -999, -999, -999, -999, -999, -999,
  115806. -999, -999, -999, -999, -999, -999, -999, -999},
  115807. {-999, -999, -999, -999, -999, -999, -999, -107,
  115808. -104, -101, -97, -92, -90, -84, -74, -57,
  115809. -58, -52, -55, -54, -50, -52, -50, -52,
  115810. -63, -62, -69, -76, -77, -78, -78, -79,
  115811. -82, -88, -94, -100, -106, -111, -999, -999,
  115812. -999, -999, -999, -999, -999, -999, -999, -999,
  115813. -999, -999, -999, -999, -999, -999, -999, -999},
  115814. {-999, -999, -999, -999, -999, -999, -106, -102,
  115815. -98, -95, -90, -85, -83, -78, -70, -50,
  115816. -50, -41, -44, -49, -47, -50, -50, -44,
  115817. -55, -46, -47, -48, -48, -54, -49, -49,
  115818. -58, -62, -71, -81, -87, -92, -97, -102,
  115819. -108, -114, -999, -999, -999, -999, -999, -999,
  115820. -999, -999, -999, -999, -999, -999, -999, -999},
  115821. {-999, -999, -999, -999, -999, -999, -106, -102,
  115822. -98, -95, -90, -85, -83, -78, -70, -45,
  115823. -43, -41, -47, -50, -51, -50, -49, -45,
  115824. -47, -41, -44, -41, -39, -43, -38, -37,
  115825. -40, -41, -44, -50, -58, -65, -73, -79,
  115826. -85, -92, -97, -101, -105, -109, -113, -999,
  115827. -999, -999, -999, -999, -999, -999, -999, -999}},
  115828. /* 1414 Hz */
  115829. {{-999, -999, -999, -999, -999, -999, -999, -999,
  115830. -999, -999, -999, -107, -100, -95, -87, -81,
  115831. -85, -83, -88, -93, -100, -107, -114, -999,
  115832. -999, -999, -999, -999, -999, -999, -999, -999,
  115833. -999, -999, -999, -999, -999, -999, -999, -999,
  115834. -999, -999, -999, -999, -999, -999, -999, -999,
  115835. -999, -999, -999, -999, -999, -999, -999, -999},
  115836. {-999, -999, -999, -999, -999, -999, -999, -999,
  115837. -999, -999, -107, -101, -95, -88, -83, -76,
  115838. -73, -72, -79, -84, -90, -95, -100, -105,
  115839. -110, -115, -999, -999, -999, -999, -999, -999,
  115840. -999, -999, -999, -999, -999, -999, -999, -999,
  115841. -999, -999, -999, -999, -999, -999, -999, -999,
  115842. -999, -999, -999, -999, -999, -999, -999, -999},
  115843. {-999, -999, -999, -999, -999, -999, -999, -999,
  115844. -999, -999, -104, -98, -92, -87, -81, -70,
  115845. -65, -62, -67, -71, -74, -80, -85, -91,
  115846. -95, -99, -103, -108, -111, -114, -999, -999,
  115847. -999, -999, -999, -999, -999, -999, -999, -999,
  115848. -999, -999, -999, -999, -999, -999, -999, -999,
  115849. -999, -999, -999, -999, -999, -999, -999, -999},
  115850. {-999, -999, -999, -999, -999, -999, -999, -999,
  115851. -999, -999, -103, -97, -90, -85, -76, -60,
  115852. -56, -54, -60, -62, -61, -56, -63, -65,
  115853. -73, -74, -77, -75, -78, -81, -86, -87,
  115854. -88, -91, -94, -98, -103, -110, -999, -999,
  115855. -999, -999, -999, -999, -999, -999, -999, -999,
  115856. -999, -999, -999, -999, -999, -999, -999, -999},
  115857. {-999, -999, -999, -999, -999, -999, -999, -105,
  115858. -100, -97, -92, -86, -81, -79, -70, -57,
  115859. -51, -47, -51, -58, -60, -56, -53, -50,
  115860. -58, -52, -50, -50, -53, -55, -64, -69,
  115861. -71, -85, -82, -78, -81, -85, -95, -102,
  115862. -112, -999, -999, -999, -999, -999, -999, -999,
  115863. -999, -999, -999, -999, -999, -999, -999, -999},
  115864. {-999, -999, -999, -999, -999, -999, -999, -105,
  115865. -100, -97, -92, -85, -83, -79, -72, -49,
  115866. -40, -43, -43, -54, -56, -51, -50, -40,
  115867. -43, -38, -36, -35, -37, -38, -37, -44,
  115868. -54, -60, -57, -60, -70, -75, -84, -92,
  115869. -103, -112, -999, -999, -999, -999, -999, -999,
  115870. -999, -999, -999, -999, -999, -999, -999, -999}},
  115871. /* 2000 Hz */
  115872. {{-999, -999, -999, -999, -999, -999, -999, -999,
  115873. -999, -999, -999, -110, -102, -95, -89, -82,
  115874. -83, -84, -90, -92, -99, -107, -113, -999,
  115875. -999, -999, -999, -999, -999, -999, -999, -999,
  115876. -999, -999, -999, -999, -999, -999, -999, -999,
  115877. -999, -999, -999, -999, -999, -999, -999, -999,
  115878. -999, -999, -999, -999, -999, -999, -999, -999},
  115879. {-999, -999, -999, -999, -999, -999, -999, -999,
  115880. -999, -999, -107, -101, -95, -89, -83, -72,
  115881. -74, -78, -85, -88, -88, -90, -92, -98,
  115882. -105, -111, -999, -999, -999, -999, -999, -999,
  115883. -999, -999, -999, -999, -999, -999, -999, -999,
  115884. -999, -999, -999, -999, -999, -999, -999, -999,
  115885. -999, -999, -999, -999, -999, -999, -999, -999},
  115886. {-999, -999, -999, -999, -999, -999, -999, -999,
  115887. -999, -109, -103, -97, -93, -87, -81, -70,
  115888. -70, -67, -75, -73, -76, -79, -81, -83,
  115889. -88, -89, -97, -103, -110, -999, -999, -999,
  115890. -999, -999, -999, -999, -999, -999, -999, -999,
  115891. -999, -999, -999, -999, -999, -999, -999, -999,
  115892. -999, -999, -999, -999, -999, -999, -999, -999},
  115893. {-999, -999, -999, -999, -999, -999, -999, -999,
  115894. -999, -107, -100, -94, -88, -83, -75, -63,
  115895. -59, -59, -63, -66, -60, -62, -67, -67,
  115896. -77, -76, -81, -88, -86, -92, -96, -102,
  115897. -109, -116, -999, -999, -999, -999, -999, -999,
  115898. -999, -999, -999, -999, -999, -999, -999, -999,
  115899. -999, -999, -999, -999, -999, -999, -999, -999},
  115900. {-999, -999, -999, -999, -999, -999, -999, -999,
  115901. -999, -105, -98, -92, -86, -81, -73, -56,
  115902. -52, -47, -55, -60, -58, -52, -51, -45,
  115903. -49, -50, -53, -54, -61, -71, -70, -69,
  115904. -78, -79, -87, -90, -96, -104, -112, -999,
  115905. -999, -999, -999, -999, -999, -999, -999, -999,
  115906. -999, -999, -999, -999, -999, -999, -999, -999},
  115907. {-999, -999, -999, -999, -999, -999, -999, -999,
  115908. -999, -103, -96, -90, -86, -78, -70, -51,
  115909. -42, -47, -48, -55, -54, -54, -53, -42,
  115910. -35, -28, -33, -38, -37, -44, -47, -49,
  115911. -54, -63, -68, -78, -82, -89, -94, -99,
  115912. -104, -109, -114, -999, -999, -999, -999, -999,
  115913. -999, -999, -999, -999, -999, -999, -999, -999}},
  115914. /* 2828 Hz */
  115915. {{-999, -999, -999, -999, -999, -999, -999, -999,
  115916. -999, -999, -999, -999, -110, -100, -90, -79,
  115917. -85, -81, -82, -82, -89, -94, -99, -103,
  115918. -109, -115, -999, -999, -999, -999, -999, -999,
  115919. -999, -999, -999, -999, -999, -999, -999, -999,
  115920. -999, -999, -999, -999, -999, -999, -999, -999,
  115921. -999, -999, -999, -999, -999, -999, -999, -999},
  115922. {-999, -999, -999, -999, -999, -999, -999, -999,
  115923. -999, -999, -999, -999, -105, -97, -85, -72,
  115924. -74, -70, -70, -70, -76, -85, -91, -93,
  115925. -97, -103, -109, -115, -999, -999, -999, -999,
  115926. -999, -999, -999, -999, -999, -999, -999, -999,
  115927. -999, -999, -999, -999, -999, -999, -999, -999,
  115928. -999, -999, -999, -999, -999, -999, -999, -999},
  115929. {-999, -999, -999, -999, -999, -999, -999, -999,
  115930. -999, -999, -999, -999, -112, -93, -81, -68,
  115931. -62, -60, -60, -57, -63, -70, -77, -82,
  115932. -90, -93, -98, -104, -109, -113, -999, -999,
  115933. -999, -999, -999, -999, -999, -999, -999, -999,
  115934. -999, -999, -999, -999, -999, -999, -999, -999,
  115935. -999, -999, -999, -999, -999, -999, -999, -999},
  115936. {-999, -999, -999, -999, -999, -999, -999, -999,
  115937. -999, -999, -999, -113, -100, -93, -84, -63,
  115938. -58, -48, -53, -54, -52, -52, -57, -64,
  115939. -66, -76, -83, -81, -85, -85, -90, -95,
  115940. -98, -101, -103, -106, -108, -111, -999, -999,
  115941. -999, -999, -999, -999, -999, -999, -999, -999,
  115942. -999, -999, -999, -999, -999, -999, -999, -999},
  115943. {-999, -999, -999, -999, -999, -999, -999, -999,
  115944. -999, -999, -999, -105, -95, -86, -74, -53,
  115945. -50, -38, -43, -49, -43, -42, -39, -39,
  115946. -46, -52, -57, -56, -72, -69, -74, -81,
  115947. -87, -92, -94, -97, -99, -102, -105, -108,
  115948. -999, -999, -999, -999, -999, -999, -999, -999,
  115949. -999, -999, -999, -999, -999, -999, -999, -999},
  115950. {-999, -999, -999, -999, -999, -999, -999, -999,
  115951. -999, -999, -108, -99, -90, -76, -66, -45,
  115952. -43, -41, -44, -47, -43, -47, -40, -30,
  115953. -31, -31, -39, -33, -40, -41, -43, -53,
  115954. -59, -70, -73, -77, -79, -82, -84, -87,
  115955. -999, -999, -999, -999, -999, -999, -999, -999,
  115956. -999, -999, -999, -999, -999, -999, -999, -999}},
  115957. /* 4000 Hz */
  115958. {{-999, -999, -999, -999, -999, -999, -999, -999,
  115959. -999, -999, -999, -999, -999, -110, -91, -76,
  115960. -75, -85, -93, -98, -104, -110, -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, -999, -999, -999,
  115964. -999, -999, -999, -999, -999, -999, -999, -999},
  115965. {-999, -999, -999, -999, -999, -999, -999, -999,
  115966. -999, -999, -999, -999, -999, -110, -91, -70,
  115967. -70, -75, -86, -89, -94, -98, -101, -106,
  115968. -110, -999, -999, -999, -999, -999, -999, -999,
  115969. -999, -999, -999, -999, -999, -999, -999, -999,
  115970. -999, -999, -999, -999, -999, -999, -999, -999,
  115971. -999, -999, -999, -999, -999, -999, -999, -999},
  115972. {-999, -999, -999, -999, -999, -999, -999, -999,
  115973. -999, -999, -999, -999, -110, -95, -80, -60,
  115974. -65, -64, -74, -83, -88, -91, -95, -99,
  115975. -103, -107, -110, -999, -999, -999, -999, -999,
  115976. -999, -999, -999, -999, -999, -999, -999, -999,
  115977. -999, -999, -999, -999, -999, -999, -999, -999,
  115978. -999, -999, -999, -999, -999, -999, -999, -999},
  115979. {-999, -999, -999, -999, -999, -999, -999, -999,
  115980. -999, -999, -999, -999, -110, -95, -80, -58,
  115981. -55, -49, -66, -68, -71, -78, -78, -80,
  115982. -88, -85, -89, -97, -100, -105, -110, -999,
  115983. -999, -999, -999, -999, -999, -999, -999, -999,
  115984. -999, -999, -999, -999, -999, -999, -999, -999,
  115985. -999, -999, -999, -999, -999, -999, -999, -999},
  115986. {-999, -999, -999, -999, -999, -999, -999, -999,
  115987. -999, -999, -999, -999, -110, -95, -80, -53,
  115988. -52, -41, -59, -59, -49, -58, -56, -63,
  115989. -86, -79, -90, -93, -98, -103, -107, -112,
  115990. -999, -999, -999, -999, -999, -999, -999, -999,
  115991. -999, -999, -999, -999, -999, -999, -999, -999,
  115992. -999, -999, -999, -999, -999, -999, -999, -999},
  115993. {-999, -999, -999, -999, -999, -999, -999, -999,
  115994. -999, -999, -999, -110, -97, -91, -73, -45,
  115995. -40, -33, -53, -61, -49, -54, -50, -50,
  115996. -60, -52, -67, -74, -81, -92, -96, -100,
  115997. -105, -110, -999, -999, -999, -999, -999, -999,
  115998. -999, -999, -999, -999, -999, -999, -999, -999,
  115999. -999, -999, -999, -999, -999, -999, -999, -999}},
  116000. /* 5657 Hz */
  116001. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116002. -999, -999, -999, -113, -106, -99, -92, -77,
  116003. -80, -88, -97, -106, -115, -999, -999, -999,
  116004. -999, -999, -999, -999, -999, -999, -999, -999,
  116005. -999, -999, -999, -999, -999, -999, -999, -999,
  116006. -999, -999, -999, -999, -999, -999, -999, -999,
  116007. -999, -999, -999, -999, -999, -999, -999, -999},
  116008. {-999, -999, -999, -999, -999, -999, -999, -999,
  116009. -999, -999, -116, -109, -102, -95, -89, -74,
  116010. -72, -88, -87, -95, -102, -109, -116, -999,
  116011. -999, -999, -999, -999, -999, -999, -999, -999,
  116012. -999, -999, -999, -999, -999, -999, -999, -999,
  116013. -999, -999, -999, -999, -999, -999, -999, -999,
  116014. -999, -999, -999, -999, -999, -999, -999, -999},
  116015. {-999, -999, -999, -999, -999, -999, -999, -999,
  116016. -999, -999, -116, -109, -102, -95, -89, -75,
  116017. -66, -74, -77, -78, -86, -87, -90, -96,
  116018. -105, -115, -999, -999, -999, -999, -999, -999,
  116019. -999, -999, -999, -999, -999, -999, -999, -999,
  116020. -999, -999, -999, -999, -999, -999, -999, -999,
  116021. -999, -999, -999, -999, -999, -999, -999, -999},
  116022. {-999, -999, -999, -999, -999, -999, -999, -999,
  116023. -999, -999, -115, -108, -101, -94, -88, -66,
  116024. -56, -61, -70, -65, -78, -72, -83, -84,
  116025. -93, -98, -105, -110, -999, -999, -999, -999,
  116026. -999, -999, -999, -999, -999, -999, -999, -999,
  116027. -999, -999, -999, -999, -999, -999, -999, -999,
  116028. -999, -999, -999, -999, -999, -999, -999, -999},
  116029. {-999, -999, -999, -999, -999, -999, -999, -999,
  116030. -999, -999, -110, -105, -95, -89, -82, -57,
  116031. -52, -52, -59, -56, -59, -58, -69, -67,
  116032. -88, -82, -82, -89, -94, -100, -108, -999,
  116033. -999, -999, -999, -999, -999, -999, -999, -999,
  116034. -999, -999, -999, -999, -999, -999, -999, -999,
  116035. -999, -999, -999, -999, -999, -999, -999, -999},
  116036. {-999, -999, -999, -999, -999, -999, -999, -999,
  116037. -999, -110, -101, -96, -90, -83, -77, -54,
  116038. -43, -38, -50, -48, -52, -48, -42, -42,
  116039. -51, -52, -53, -59, -65, -71, -78, -85,
  116040. -95, -999, -999, -999, -999, -999, -999, -999,
  116041. -999, -999, -999, -999, -999, -999, -999, -999,
  116042. -999, -999, -999, -999, -999, -999, -999, -999}},
  116043. /* 8000 Hz */
  116044. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116045. -999, -999, -999, -999, -120, -105, -86, -68,
  116046. -78, -79, -90, -100, -110, -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, -999, -999, -999, -999,
  116050. -999, -999, -999, -999, -999, -999, -999, -999},
  116051. {-999, -999, -999, -999, -999, -999, -999, -999,
  116052. -999, -999, -999, -999, -120, -105, -86, -66,
  116053. -73, -77, -88, -96, -105, -115, -999, -999,
  116054. -999, -999, -999, -999, -999, -999, -999, -999,
  116055. -999, -999, -999, -999, -999, -999, -999, -999,
  116056. -999, -999, -999, -999, -999, -999, -999, -999,
  116057. -999, -999, -999, -999, -999, -999, -999, -999},
  116058. {-999, -999, -999, -999, -999, -999, -999, -999,
  116059. -999, -999, -999, -120, -105, -92, -80, -61,
  116060. -64, -68, -80, -87, -92, -100, -110, -999,
  116061. -999, -999, -999, -999, -999, -999, -999, -999,
  116062. -999, -999, -999, -999, -999, -999, -999, -999,
  116063. -999, -999, -999, -999, -999, -999, -999, -999,
  116064. -999, -999, -999, -999, -999, -999, -999, -999},
  116065. {-999, -999, -999, -999, -999, -999, -999, -999,
  116066. -999, -999, -999, -120, -104, -91, -79, -52,
  116067. -60, -54, -64, -69, -77, -80, -82, -84,
  116068. -85, -87, -88, -90, -999, -999, -999, -999,
  116069. -999, -999, -999, -999, -999, -999, -999, -999,
  116070. -999, -999, -999, -999, -999, -999, -999, -999,
  116071. -999, -999, -999, -999, -999, -999, -999, -999},
  116072. {-999, -999, -999, -999, -999, -999, -999, -999,
  116073. -999, -999, -999, -118, -100, -87, -77, -49,
  116074. -50, -44, -58, -61, -61, -67, -65, -62,
  116075. -62, -62, -65, -68, -999, -999, -999, -999,
  116076. -999, -999, -999, -999, -999, -999, -999, -999,
  116077. -999, -999, -999, -999, -999, -999, -999, -999,
  116078. -999, -999, -999, -999, -999, -999, -999, -999},
  116079. {-999, -999, -999, -999, -999, -999, -999, -999,
  116080. -999, -999, -999, -115, -98, -84, -62, -49,
  116081. -44, -38, -46, -49, -49, -46, -39, -37,
  116082. -39, -40, -42, -43, -999, -999, -999, -999,
  116083. -999, -999, -999, -999, -999, -999, -999, -999,
  116084. -999, -999, -999, -999, -999, -999, -999, -999,
  116085. -999, -999, -999, -999, -999, -999, -999, -999}},
  116086. /* 11314 Hz */
  116087. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116088. -999, -999, -999, -999, -999, -110, -88, -74,
  116089. -77, -82, -82, -85, -90, -94, -99, -104,
  116090. -999, -999, -999, -999, -999, -999, -999, -999,
  116091. -999, -999, -999, -999, -999, -999, -999, -999,
  116092. -999, -999, -999, -999, -999, -999, -999, -999,
  116093. -999, -999, -999, -999, -999, -999, -999, -999},
  116094. {-999, -999, -999, -999, -999, -999, -999, -999,
  116095. -999, -999, -999, -999, -999, -110, -88, -66,
  116096. -70, -81, -80, -81, -84, -88, -91, -93,
  116097. -999, -999, -999, -999, -999, -999, -999, -999,
  116098. -999, -999, -999, -999, -999, -999, -999, -999,
  116099. -999, -999, -999, -999, -999, -999, -999, -999,
  116100. -999, -999, -999, -999, -999, -999, -999, -999},
  116101. {-999, -999, -999, -999, -999, -999, -999, -999,
  116102. -999, -999, -999, -999, -999, -110, -88, -61,
  116103. -63, -70, -71, -74, -77, -80, -83, -85,
  116104. -999, -999, -999, -999, -999, -999, -999, -999,
  116105. -999, -999, -999, -999, -999, -999, -999, -999,
  116106. -999, -999, -999, -999, -999, -999, -999, -999,
  116107. -999, -999, -999, -999, -999, -999, -999, -999},
  116108. {-999, -999, -999, -999, -999, -999, -999, -999,
  116109. -999, -999, -999, -999, -999, -110, -86, -62,
  116110. -63, -62, -62, -58, -52, -50, -50, -52,
  116111. -54, -999, -999, -999, -999, -999, -999, -999,
  116112. -999, -999, -999, -999, -999, -999, -999, -999,
  116113. -999, -999, -999, -999, -999, -999, -999, -999,
  116114. -999, -999, -999, -999, -999, -999, -999, -999},
  116115. {-999, -999, -999, -999, -999, -999, -999, -999,
  116116. -999, -999, -999, -999, -118, -108, -84, -53,
  116117. -50, -50, -50, -55, -47, -45, -40, -40,
  116118. -40, -999, -999, -999, -999, -999, -999, -999,
  116119. -999, -999, -999, -999, -999, -999, -999, -999,
  116120. -999, -999, -999, -999, -999, -999, -999, -999,
  116121. -999, -999, -999, -999, -999, -999, -999, -999},
  116122. {-999, -999, -999, -999, -999, -999, -999, -999,
  116123. -999, -999, -999, -999, -118, -100, -73, -43,
  116124. -37, -42, -43, -53, -38, -37, -35, -35,
  116125. -38, -999, -999, -999, -999, -999, -999, -999,
  116126. -999, -999, -999, -999, -999, -999, -999, -999,
  116127. -999, -999, -999, -999, -999, -999, -999, -999,
  116128. -999, -999, -999, -999, -999, -999, -999, -999}},
  116129. /* 16000 Hz */
  116130. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116131. -999, -999, -999, -110, -100, -91, -84, -74,
  116132. -80, -80, -80, -80, -80, -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, -999, -999, -999, -999, -999,
  116136. -999, -999, -999, -999, -999, -999, -999, -999},
  116137. {-999, -999, -999, -999, -999, -999, -999, -999,
  116138. -999, -999, -999, -110, -100, -91, -84, -74,
  116139. -68, -68, -68, -68, -68, -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, -999, -999, -999, -999, -999,
  116143. -999, -999, -999, -999, -999, -999, -999, -999},
  116144. {-999, -999, -999, -999, -999, -999, -999, -999,
  116145. -999, -999, -999, -110, -100, -86, -78, -70,
  116146. -60, -45, -30, -21, -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, -999, -999, -999, -999, -999,
  116150. -999, -999, -999, -999, -999, -999, -999, -999},
  116151. {-999, -999, -999, -999, -999, -999, -999, -999,
  116152. -999, -999, -999, -110, -100, -87, -78, -67,
  116153. -48, -38, -29, -21, -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, -999, -999, -999, -999, -999,
  116157. -999, -999, -999, -999, -999, -999, -999, -999},
  116158. {-999, -999, -999, -999, -999, -999, -999, -999,
  116159. -999, -999, -999, -110, -100, -86, -69, -56,
  116160. -45, -35, -33, -29, -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, -999, -999, -999, -999, -999,
  116164. -999, -999, -999, -999, -999, -999, -999, -999},
  116165. {-999, -999, -999, -999, -999, -999, -999, -999,
  116166. -999, -999, -999, -110, -100, -83, -71, -48,
  116167. -27, -38, -37, -34, -999, -999, -999, -999,
  116168. -999, -999, -999, -999, -999, -999, -999, -999,
  116169. -999, -999, -999, -999, -999, -999, -999, -999,
  116170. -999, -999, -999, -999, -999, -999, -999, -999,
  116171. -999, -999, -999, -999, -999, -999, -999, -999}}
  116172. };
  116173. #endif
  116174. /*** End of inlined file: masking.h ***/
  116175. #define NEGINF -9999.f
  116176. static double stereo_threshholds[]={0.0, .5, 1.0, 1.5, 2.5, 4.5, 8.5, 16.5, 9e10};
  116177. static double stereo_threshholds_limited[]={0.0, .5, 1.0, 1.5, 2.0, 2.5, 4.5, 8.5, 9e10};
  116178. vorbis_look_psy_global *_vp_global_look(vorbis_info *vi){
  116179. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  116180. vorbis_info_psy_global *gi=&ci->psy_g_param;
  116181. vorbis_look_psy_global *look=(vorbis_look_psy_global*)_ogg_calloc(1,sizeof(*look));
  116182. look->channels=vi->channels;
  116183. look->ampmax=-9999.;
  116184. look->gi=gi;
  116185. return(look);
  116186. }
  116187. void _vp_global_free(vorbis_look_psy_global *look){
  116188. if(look){
  116189. memset(look,0,sizeof(*look));
  116190. _ogg_free(look);
  116191. }
  116192. }
  116193. void _vi_gpsy_free(vorbis_info_psy_global *i){
  116194. if(i){
  116195. memset(i,0,sizeof(*i));
  116196. _ogg_free(i);
  116197. }
  116198. }
  116199. void _vi_psy_free(vorbis_info_psy *i){
  116200. if(i){
  116201. memset(i,0,sizeof(*i));
  116202. _ogg_free(i);
  116203. }
  116204. }
  116205. static void min_curve(float *c,
  116206. float *c2){
  116207. int i;
  116208. for(i=0;i<EHMER_MAX;i++)if(c2[i]<c[i])c[i]=c2[i];
  116209. }
  116210. static void max_curve(float *c,
  116211. float *c2){
  116212. int i;
  116213. for(i=0;i<EHMER_MAX;i++)if(c2[i]>c[i])c[i]=c2[i];
  116214. }
  116215. static void attenuate_curve(float *c,float att){
  116216. int i;
  116217. for(i=0;i<EHMER_MAX;i++)
  116218. c[i]+=att;
  116219. }
  116220. static float ***setup_tone_curves(float curveatt_dB[P_BANDS],float binHz,int n,
  116221. float center_boost, float center_decay_rate){
  116222. int i,j,k,m;
  116223. float ath[EHMER_MAX];
  116224. float workc[P_BANDS][P_LEVELS][EHMER_MAX];
  116225. float athc[P_LEVELS][EHMER_MAX];
  116226. float *brute_buffer=(float*) alloca(n*sizeof(*brute_buffer));
  116227. float ***ret=(float***) _ogg_malloc(sizeof(*ret)*P_BANDS);
  116228. memset(workc,0,sizeof(workc));
  116229. for(i=0;i<P_BANDS;i++){
  116230. /* we add back in the ATH to avoid low level curves falling off to
  116231. -infinity and unnecessarily cutting off high level curves in the
  116232. curve limiting (last step). */
  116233. /* A half-band's settings must be valid over the whole band, and
  116234. it's better to mask too little than too much */
  116235. int ath_offset=i*4;
  116236. for(j=0;j<EHMER_MAX;j++){
  116237. float min=999.;
  116238. for(k=0;k<4;k++)
  116239. if(j+k+ath_offset<MAX_ATH){
  116240. if(min>ATH[j+k+ath_offset])min=ATH[j+k+ath_offset];
  116241. }else{
  116242. if(min>ATH[MAX_ATH-1])min=ATH[MAX_ATH-1];
  116243. }
  116244. ath[j]=min;
  116245. }
  116246. /* copy curves into working space, replicate the 50dB curve to 30
  116247. and 40, replicate the 100dB curve to 110 */
  116248. for(j=0;j<6;j++)
  116249. memcpy(workc[i][j+2],tonemasks[i][j],EHMER_MAX*sizeof(*tonemasks[i][j]));
  116250. memcpy(workc[i][0],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  116251. memcpy(workc[i][1],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  116252. /* apply centered curve boost/decay */
  116253. for(j=0;j<P_LEVELS;j++){
  116254. for(k=0;k<EHMER_MAX;k++){
  116255. float adj=center_boost+abs(EHMER_OFFSET-k)*center_decay_rate;
  116256. if(adj<0. && center_boost>0)adj=0.;
  116257. if(adj>0. && center_boost<0)adj=0.;
  116258. workc[i][j][k]+=adj;
  116259. }
  116260. }
  116261. /* normalize curves so the driving amplitude is 0dB */
  116262. /* make temp curves with the ATH overlayed */
  116263. for(j=0;j<P_LEVELS;j++){
  116264. attenuate_curve(workc[i][j],curveatt_dB[i]+100.-(j<2?2:j)*10.-P_LEVEL_0);
  116265. memcpy(athc[j],ath,EHMER_MAX*sizeof(**athc));
  116266. attenuate_curve(athc[j],+100.-j*10.f-P_LEVEL_0);
  116267. max_curve(athc[j],workc[i][j]);
  116268. }
  116269. /* Now limit the louder curves.
  116270. the idea is this: We don't know what the playback attenuation
  116271. will be; 0dB SL moves every time the user twiddles the volume
  116272. knob. So that means we have to use a single 'most pessimal' curve
  116273. for all masking amplitudes, right? Wrong. The *loudest* sound
  116274. can be in (we assume) a range of ...+100dB] SL. However, sounds
  116275. 20dB down will be in a range ...+80], 40dB down is from ...+60],
  116276. etc... */
  116277. for(j=1;j<P_LEVELS;j++){
  116278. min_curve(athc[j],athc[j-1]);
  116279. min_curve(workc[i][j],athc[j]);
  116280. }
  116281. }
  116282. for(i=0;i<P_BANDS;i++){
  116283. int hi_curve,lo_curve,bin;
  116284. ret[i]=(float**)_ogg_malloc(sizeof(**ret)*P_LEVELS);
  116285. /* low frequency curves are measured with greater resolution than
  116286. the MDCT/FFT will actually give us; we want the curve applied
  116287. to the tone data to be pessimistic and thus apply the minimum
  116288. masking possible for a given bin. That means that a single bin
  116289. could span more than one octave and that the curve will be a
  116290. composite of multiple octaves. It also may mean that a single
  116291. bin may span > an eighth of an octave and that the eighth
  116292. octave values may also be composited. */
  116293. /* which octave curves will we be compositing? */
  116294. bin=floor(fromOC(i*.5)/binHz);
  116295. lo_curve= ceil(toOC(bin*binHz+1)*2);
  116296. hi_curve= floor(toOC((bin+1)*binHz)*2);
  116297. if(lo_curve>i)lo_curve=i;
  116298. if(lo_curve<0)lo_curve=0;
  116299. if(hi_curve>=P_BANDS)hi_curve=P_BANDS-1;
  116300. for(m=0;m<P_LEVELS;m++){
  116301. ret[i][m]=(float*)_ogg_malloc(sizeof(***ret)*(EHMER_MAX+2));
  116302. for(j=0;j<n;j++)brute_buffer[j]=999.;
  116303. /* render the curve into bins, then pull values back into curve.
  116304. The point is that any inherent subsampling aliasing results in
  116305. a safe minimum */
  116306. for(k=lo_curve;k<=hi_curve;k++){
  116307. int l=0;
  116308. for(j=0;j<EHMER_MAX;j++){
  116309. int lo_bin= fromOC(j*.125+k*.5-2.0625)/binHz;
  116310. int hi_bin= fromOC(j*.125+k*.5-1.9375)/binHz+1;
  116311. if(lo_bin<0)lo_bin=0;
  116312. if(lo_bin>n)lo_bin=n;
  116313. if(lo_bin<l)l=lo_bin;
  116314. if(hi_bin<0)hi_bin=0;
  116315. if(hi_bin>n)hi_bin=n;
  116316. for(;l<hi_bin && l<n;l++)
  116317. if(brute_buffer[l]>workc[k][m][j])
  116318. brute_buffer[l]=workc[k][m][j];
  116319. }
  116320. for(;l<n;l++)
  116321. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  116322. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  116323. }
  116324. /* be equally paranoid about being valid up to next half ocatve */
  116325. if(i+1<P_BANDS){
  116326. int l=0;
  116327. k=i+1;
  116328. for(j=0;j<EHMER_MAX;j++){
  116329. int lo_bin= fromOC(j*.125+i*.5-2.0625)/binHz;
  116330. int hi_bin= fromOC(j*.125+i*.5-1.9375)/binHz+1;
  116331. if(lo_bin<0)lo_bin=0;
  116332. if(lo_bin>n)lo_bin=n;
  116333. if(lo_bin<l)l=lo_bin;
  116334. if(hi_bin<0)hi_bin=0;
  116335. if(hi_bin>n)hi_bin=n;
  116336. for(;l<hi_bin && l<n;l++)
  116337. if(brute_buffer[l]>workc[k][m][j])
  116338. brute_buffer[l]=workc[k][m][j];
  116339. }
  116340. for(;l<n;l++)
  116341. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  116342. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  116343. }
  116344. for(j=0;j<EHMER_MAX;j++){
  116345. int bin=fromOC(j*.125+i*.5-2.)/binHz;
  116346. if(bin<0){
  116347. ret[i][m][j+2]=-999.;
  116348. }else{
  116349. if(bin>=n){
  116350. ret[i][m][j+2]=-999.;
  116351. }else{
  116352. ret[i][m][j+2]=brute_buffer[bin];
  116353. }
  116354. }
  116355. }
  116356. /* add fenceposts */
  116357. for(j=0;j<EHMER_OFFSET;j++)
  116358. if(ret[i][m][j+2]>-200.f)break;
  116359. ret[i][m][0]=j;
  116360. for(j=EHMER_MAX-1;j>EHMER_OFFSET+1;j--)
  116361. if(ret[i][m][j+2]>-200.f)
  116362. break;
  116363. ret[i][m][1]=j;
  116364. }
  116365. }
  116366. return(ret);
  116367. }
  116368. void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  116369. vorbis_info_psy_global *gi,int n,long rate){
  116370. long i,j,lo=-99,hi=1;
  116371. long maxoc;
  116372. memset(p,0,sizeof(*p));
  116373. p->eighth_octave_lines=gi->eighth_octave_lines;
  116374. p->shiftoc=rint(log(gi->eighth_octave_lines*8.f)/log(2.f))-1;
  116375. p->firstoc=toOC(.25f*rate*.5/n)*(1<<(p->shiftoc+1))-gi->eighth_octave_lines;
  116376. maxoc=toOC((n+.25f)*rate*.5/n)*(1<<(p->shiftoc+1))+.5f;
  116377. p->total_octave_lines=maxoc-p->firstoc+1;
  116378. p->ath=(float*)_ogg_malloc(n*sizeof(*p->ath));
  116379. p->octave=(long*)_ogg_malloc(n*sizeof(*p->octave));
  116380. p->bark=(long*)_ogg_malloc(n*sizeof(*p->bark));
  116381. p->vi=vi;
  116382. p->n=n;
  116383. p->rate=rate;
  116384. /* AoTuV HF weighting */
  116385. p->m_val = 1.;
  116386. if(rate < 26000) p->m_val = 0;
  116387. else if(rate < 38000) p->m_val = .94; /* 32kHz */
  116388. else if(rate > 46000) p->m_val = 1.275; /* 48kHz */
  116389. /* set up the lookups for a given blocksize and sample rate */
  116390. for(i=0,j=0;i<MAX_ATH-1;i++){
  116391. int endpos=rint(fromOC((i+1)*.125-2.)*2*n/rate);
  116392. float base=ATH[i];
  116393. if(j<endpos){
  116394. float delta=(ATH[i+1]-base)/(endpos-j);
  116395. for(;j<endpos && j<n;j++){
  116396. p->ath[j]=base+100.;
  116397. base+=delta;
  116398. }
  116399. }
  116400. }
  116401. for(i=0;i<n;i++){
  116402. float bark=toBARK(rate/(2*n)*i);
  116403. for(;lo+vi->noisewindowlomin<i &&
  116404. toBARK(rate/(2*n)*lo)<(bark-vi->noisewindowlo);lo++);
  116405. for(;hi<=n && (hi<i+vi->noisewindowhimin ||
  116406. toBARK(rate/(2*n)*hi)<(bark+vi->noisewindowhi));hi++);
  116407. p->bark[i]=((lo-1)<<16)+(hi-1);
  116408. }
  116409. for(i=0;i<n;i++)
  116410. p->octave[i]=toOC((i+.25f)*.5*rate/n)*(1<<(p->shiftoc+1))+.5f;
  116411. p->tonecurves=setup_tone_curves(vi->toneatt,rate*.5/n,n,
  116412. vi->tone_centerboost,vi->tone_decay);
  116413. /* set up rolling noise median */
  116414. p->noiseoffset=(float**)_ogg_malloc(P_NOISECURVES*sizeof(*p->noiseoffset));
  116415. for(i=0;i<P_NOISECURVES;i++)
  116416. p->noiseoffset[i]=(float*)_ogg_malloc(n*sizeof(**p->noiseoffset));
  116417. for(i=0;i<n;i++){
  116418. float halfoc=toOC((i+.5)*rate/(2.*n))*2.;
  116419. int inthalfoc;
  116420. float del;
  116421. if(halfoc<0)halfoc=0;
  116422. if(halfoc>=P_BANDS-1)halfoc=P_BANDS-1;
  116423. inthalfoc=(int)halfoc;
  116424. del=halfoc-inthalfoc;
  116425. for(j=0;j<P_NOISECURVES;j++)
  116426. p->noiseoffset[j][i]=
  116427. p->vi->noiseoff[j][inthalfoc]*(1.-del) +
  116428. p->vi->noiseoff[j][inthalfoc+1]*del;
  116429. }
  116430. #if 0
  116431. {
  116432. static int ls=0;
  116433. _analysis_output_always("noiseoff0",ls,p->noiseoffset[0],n,1,0,0);
  116434. _analysis_output_always("noiseoff1",ls,p->noiseoffset[1],n,1,0,0);
  116435. _analysis_output_always("noiseoff2",ls++,p->noiseoffset[2],n,1,0,0);
  116436. }
  116437. #endif
  116438. }
  116439. void _vp_psy_clear(vorbis_look_psy *p){
  116440. int i,j;
  116441. if(p){
  116442. if(p->ath)_ogg_free(p->ath);
  116443. if(p->octave)_ogg_free(p->octave);
  116444. if(p->bark)_ogg_free(p->bark);
  116445. if(p->tonecurves){
  116446. for(i=0;i<P_BANDS;i++){
  116447. for(j=0;j<P_LEVELS;j++){
  116448. _ogg_free(p->tonecurves[i][j]);
  116449. }
  116450. _ogg_free(p->tonecurves[i]);
  116451. }
  116452. _ogg_free(p->tonecurves);
  116453. }
  116454. if(p->noiseoffset){
  116455. for(i=0;i<P_NOISECURVES;i++){
  116456. _ogg_free(p->noiseoffset[i]);
  116457. }
  116458. _ogg_free(p->noiseoffset);
  116459. }
  116460. memset(p,0,sizeof(*p));
  116461. }
  116462. }
  116463. /* octave/(8*eighth_octave_lines) x scale and dB y scale */
  116464. static void seed_curve(float *seed,
  116465. const float **curves,
  116466. float amp,
  116467. int oc, int n,
  116468. int linesper,float dBoffset){
  116469. int i,post1;
  116470. int seedptr;
  116471. const float *posts,*curve;
  116472. int choice=(int)((amp+dBoffset-P_LEVEL_0)*.1f);
  116473. choice=max(choice,0);
  116474. choice=min(choice,P_LEVELS-1);
  116475. posts=curves[choice];
  116476. curve=posts+2;
  116477. post1=(int)posts[1];
  116478. seedptr=oc+(posts[0]-EHMER_OFFSET)*linesper-(linesper>>1);
  116479. for(i=posts[0];i<post1;i++){
  116480. if(seedptr>0){
  116481. float lin=amp+curve[i];
  116482. if(seed[seedptr]<lin)seed[seedptr]=lin;
  116483. }
  116484. seedptr+=linesper;
  116485. if(seedptr>=n)break;
  116486. }
  116487. }
  116488. static void seed_loop(vorbis_look_psy *p,
  116489. const float ***curves,
  116490. const float *f,
  116491. const float *flr,
  116492. float *seed,
  116493. float specmax){
  116494. vorbis_info_psy *vi=p->vi;
  116495. long n=p->n,i;
  116496. float dBoffset=vi->max_curve_dB-specmax;
  116497. /* prime the working vector with peak values */
  116498. for(i=0;i<n;i++){
  116499. float max=f[i];
  116500. long oc=p->octave[i];
  116501. while(i+1<n && p->octave[i+1]==oc){
  116502. i++;
  116503. if(f[i]>max)max=f[i];
  116504. }
  116505. if(max+6.f>flr[i]){
  116506. oc=oc>>p->shiftoc;
  116507. if(oc>=P_BANDS)oc=P_BANDS-1;
  116508. if(oc<0)oc=0;
  116509. seed_curve(seed,
  116510. curves[oc],
  116511. max,
  116512. p->octave[i]-p->firstoc,
  116513. p->total_octave_lines,
  116514. p->eighth_octave_lines,
  116515. dBoffset);
  116516. }
  116517. }
  116518. }
  116519. static void seed_chase(float *seeds, int linesper, long n){
  116520. long *posstack=(long*)alloca(n*sizeof(*posstack));
  116521. float *ampstack=(float*)alloca(n*sizeof(*ampstack));
  116522. long stack=0;
  116523. long pos=0;
  116524. long i;
  116525. for(i=0;i<n;i++){
  116526. if(stack<2){
  116527. posstack[stack]=i;
  116528. ampstack[stack++]=seeds[i];
  116529. }else{
  116530. while(1){
  116531. if(seeds[i]<ampstack[stack-1]){
  116532. posstack[stack]=i;
  116533. ampstack[stack++]=seeds[i];
  116534. break;
  116535. }else{
  116536. if(i<posstack[stack-1]+linesper){
  116537. if(stack>1 && ampstack[stack-1]<=ampstack[stack-2] &&
  116538. i<posstack[stack-2]+linesper){
  116539. /* we completely overlap, making stack-1 irrelevant. pop it */
  116540. stack--;
  116541. continue;
  116542. }
  116543. }
  116544. posstack[stack]=i;
  116545. ampstack[stack++]=seeds[i];
  116546. break;
  116547. }
  116548. }
  116549. }
  116550. }
  116551. /* the stack now contains only the positions that are relevant. Scan
  116552. 'em straight through */
  116553. for(i=0;i<stack;i++){
  116554. long endpos;
  116555. if(i<stack-1 && ampstack[i+1]>ampstack[i]){
  116556. endpos=posstack[i+1];
  116557. }else{
  116558. endpos=posstack[i]+linesper+1; /* +1 is important, else bin 0 is
  116559. discarded in short frames */
  116560. }
  116561. if(endpos>n)endpos=n;
  116562. for(;pos<endpos;pos++)
  116563. seeds[pos]=ampstack[i];
  116564. }
  116565. /* there. Linear time. I now remember this was on a problem set I
  116566. had in Grad Skool... I didn't solve it at the time ;-) */
  116567. }
  116568. /* bleaugh, this is more complicated than it needs to be */
  116569. #include<stdio.h>
  116570. static void max_seeds(vorbis_look_psy *p,
  116571. float *seed,
  116572. float *flr){
  116573. long n=p->total_octave_lines;
  116574. int linesper=p->eighth_octave_lines;
  116575. long linpos=0;
  116576. long pos;
  116577. seed_chase(seed,linesper,n); /* for masking */
  116578. pos=p->octave[0]-p->firstoc-(linesper>>1);
  116579. while(linpos+1<p->n){
  116580. float minV=seed[pos];
  116581. long end=((p->octave[linpos]+p->octave[linpos+1])>>1)-p->firstoc;
  116582. if(minV>p->vi->tone_abs_limit)minV=p->vi->tone_abs_limit;
  116583. while(pos+1<=end){
  116584. pos++;
  116585. if((seed[pos]>NEGINF && seed[pos]<minV) || minV==NEGINF)
  116586. minV=seed[pos];
  116587. }
  116588. end=pos+p->firstoc;
  116589. for(;linpos<p->n && p->octave[linpos]<=end;linpos++)
  116590. if(flr[linpos]<minV)flr[linpos]=minV;
  116591. }
  116592. {
  116593. float minV=seed[p->total_octave_lines-1];
  116594. for(;linpos<p->n;linpos++)
  116595. if(flr[linpos]<minV)flr[linpos]=minV;
  116596. }
  116597. }
  116598. static void bark_noise_hybridmp(int n,const long *b,
  116599. const float *f,
  116600. float *noise,
  116601. const float offset,
  116602. const int fixed){
  116603. float *N=(float*) alloca(n*sizeof(*N));
  116604. float *X=(float*) alloca(n*sizeof(*N));
  116605. float *XX=(float*) alloca(n*sizeof(*N));
  116606. float *Y=(float*) alloca(n*sizeof(*N));
  116607. float *XY=(float*) alloca(n*sizeof(*N));
  116608. float tN, tX, tXX, tY, tXY;
  116609. int i;
  116610. int lo, hi;
  116611. float R, A, B, D;
  116612. float w, x, y;
  116613. tN = tX = tXX = tY = tXY = 0.f;
  116614. y = f[0] + offset;
  116615. if (y < 1.f) y = 1.f;
  116616. w = y * y * .5;
  116617. tN += w;
  116618. tX += w;
  116619. tY += w * y;
  116620. N[0] = tN;
  116621. X[0] = tX;
  116622. XX[0] = tXX;
  116623. Y[0] = tY;
  116624. XY[0] = tXY;
  116625. for (i = 1, x = 1.f; i < n; i++, x += 1.f) {
  116626. y = f[i] + offset;
  116627. if (y < 1.f) y = 1.f;
  116628. w = y * y;
  116629. tN += w;
  116630. tX += w * x;
  116631. tXX += w * x * x;
  116632. tY += w * y;
  116633. tXY += w * x * y;
  116634. N[i] = tN;
  116635. X[i] = tX;
  116636. XX[i] = tXX;
  116637. Y[i] = tY;
  116638. XY[i] = tXY;
  116639. }
  116640. for (i = 0, x = 0.f;; i++, x += 1.f) {
  116641. lo = b[i] >> 16;
  116642. if( lo>=0 ) break;
  116643. hi = b[i] & 0xffff;
  116644. tN = N[hi] + N[-lo];
  116645. tX = X[hi] - X[-lo];
  116646. tXX = XX[hi] + XX[-lo];
  116647. tY = Y[hi] + Y[-lo];
  116648. tXY = XY[hi] - XY[-lo];
  116649. A = tY * tXX - tX * tXY;
  116650. B = tN * tXY - tX * tY;
  116651. D = tN * tXX - tX * tX;
  116652. R = (A + x * B) / D;
  116653. if (R < 0.f)
  116654. R = 0.f;
  116655. noise[i] = R - offset;
  116656. }
  116657. for ( ;; i++, x += 1.f) {
  116658. lo = b[i] >> 16;
  116659. hi = b[i] & 0xffff;
  116660. if(hi>=n)break;
  116661. tN = N[hi] - N[lo];
  116662. tX = X[hi] - X[lo];
  116663. tXX = XX[hi] - XX[lo];
  116664. tY = Y[hi] - Y[lo];
  116665. tXY = XY[hi] - XY[lo];
  116666. A = tY * tXX - tX * tXY;
  116667. B = tN * tXY - tX * tY;
  116668. D = tN * tXX - tX * tX;
  116669. R = (A + x * B) / D;
  116670. if (R < 0.f) R = 0.f;
  116671. noise[i] = R - offset;
  116672. }
  116673. for ( ; i < n; i++, x += 1.f) {
  116674. R = (A + x * B) / D;
  116675. if (R < 0.f) R = 0.f;
  116676. noise[i] = R - offset;
  116677. }
  116678. if (fixed <= 0) return;
  116679. for (i = 0, x = 0.f;; i++, x += 1.f) {
  116680. hi = i + fixed / 2;
  116681. lo = hi - fixed;
  116682. if(lo>=0)break;
  116683. tN = N[hi] + N[-lo];
  116684. tX = X[hi] - X[-lo];
  116685. tXX = XX[hi] + XX[-lo];
  116686. tY = Y[hi] + Y[-lo];
  116687. tXY = XY[hi] - XY[-lo];
  116688. A = tY * tXX - tX * tXY;
  116689. B = tN * tXY - tX * tY;
  116690. D = tN * tXX - tX * tX;
  116691. R = (A + x * B) / D;
  116692. if (R - offset < noise[i]) noise[i] = R - offset;
  116693. }
  116694. for ( ;; i++, x += 1.f) {
  116695. hi = i + fixed / 2;
  116696. lo = hi - fixed;
  116697. if(hi>=n)break;
  116698. tN = N[hi] - N[lo];
  116699. tX = X[hi] - X[lo];
  116700. tXX = XX[hi] - XX[lo];
  116701. tY = Y[hi] - Y[lo];
  116702. tXY = XY[hi] - XY[lo];
  116703. A = tY * tXX - tX * tXY;
  116704. B = tN * tXY - tX * tY;
  116705. D = tN * tXX - tX * tX;
  116706. R = (A + x * B) / D;
  116707. if (R - offset < noise[i]) noise[i] = R - offset;
  116708. }
  116709. for ( ; i < n; i++, x += 1.f) {
  116710. R = (A + x * B) / D;
  116711. if (R - offset < noise[i]) noise[i] = R - offset;
  116712. }
  116713. }
  116714. static float FLOOR1_fromdB_INV_LOOKUP[256]={
  116715. 0.F, 8.81683e+06F, 8.27882e+06F, 7.77365e+06F,
  116716. 7.29930e+06F, 6.85389e+06F, 6.43567e+06F, 6.04296e+06F,
  116717. 5.67422e+06F, 5.32798e+06F, 5.00286e+06F, 4.69759e+06F,
  116718. 4.41094e+06F, 4.14178e+06F, 3.88905e+06F, 3.65174e+06F,
  116719. 3.42891e+06F, 3.21968e+06F, 3.02321e+06F, 2.83873e+06F,
  116720. 2.66551e+06F, 2.50286e+06F, 2.35014e+06F, 2.20673e+06F,
  116721. 2.07208e+06F, 1.94564e+06F, 1.82692e+06F, 1.71544e+06F,
  116722. 1.61076e+06F, 1.51247e+06F, 1.42018e+06F, 1.33352e+06F,
  116723. 1.25215e+06F, 1.17574e+06F, 1.10400e+06F, 1.03663e+06F,
  116724. 973377.F, 913981.F, 858210.F, 805842.F,
  116725. 756669.F, 710497.F, 667142.F, 626433.F,
  116726. 588208.F, 552316.F, 518613.F, 486967.F,
  116727. 457252.F, 429351.F, 403152.F, 378551.F,
  116728. 355452.F, 333762.F, 313396.F, 294273.F,
  116729. 276316.F, 259455.F, 243623.F, 228757.F,
  116730. 214798.F, 201691.F, 189384.F, 177828.F,
  116731. 166977.F, 156788.F, 147221.F, 138237.F,
  116732. 129802.F, 121881.F, 114444.F, 107461.F,
  116733. 100903.F, 94746.3F, 88964.9F, 83536.2F,
  116734. 78438.8F, 73652.5F, 69158.2F, 64938.1F,
  116735. 60975.6F, 57254.9F, 53761.2F, 50480.6F,
  116736. 47400.3F, 44507.9F, 41792.0F, 39241.9F,
  116737. 36847.3F, 34598.9F, 32487.7F, 30505.3F,
  116738. 28643.8F, 26896.0F, 25254.8F, 23713.7F,
  116739. 22266.7F, 20908.0F, 19632.2F, 18434.2F,
  116740. 17309.4F, 16253.1F, 15261.4F, 14330.1F,
  116741. 13455.7F, 12634.6F, 11863.7F, 11139.7F,
  116742. 10460.0F, 9821.72F, 9222.39F, 8659.64F,
  116743. 8131.23F, 7635.06F, 7169.17F, 6731.70F,
  116744. 6320.93F, 5935.23F, 5573.06F, 5232.99F,
  116745. 4913.67F, 4613.84F, 4332.30F, 4067.94F,
  116746. 3819.72F, 3586.64F, 3367.78F, 3162.28F,
  116747. 2969.31F, 2788.13F, 2617.99F, 2458.24F,
  116748. 2308.24F, 2167.39F, 2035.14F, 1910.95F,
  116749. 1794.35F, 1684.85F, 1582.04F, 1485.51F,
  116750. 1394.86F, 1309.75F, 1229.83F, 1154.78F,
  116751. 1084.32F, 1018.15F, 956.024F, 897.687F,
  116752. 842.910F, 791.475F, 743.179F, 697.830F,
  116753. 655.249F, 615.265F, 577.722F, 542.469F,
  116754. 509.367F, 478.286F, 449.101F, 421.696F,
  116755. 395.964F, 371.803F, 349.115F, 327.812F,
  116756. 307.809F, 289.026F, 271.390F, 254.830F,
  116757. 239.280F, 224.679F, 210.969F, 198.096F,
  116758. 186.008F, 174.658F, 164.000F, 153.993F,
  116759. 144.596F, 135.773F, 127.488F, 119.708F,
  116760. 112.404F, 105.545F, 99.1046F, 93.0572F,
  116761. 87.3788F, 82.0469F, 77.0404F, 72.3394F,
  116762. 67.9252F, 63.7804F, 59.8885F, 56.2341F,
  116763. 52.8027F, 49.5807F, 46.5553F, 43.7144F,
  116764. 41.0470F, 38.5423F, 36.1904F, 33.9821F,
  116765. 31.9085F, 29.9614F, 28.1332F, 26.4165F,
  116766. 24.8045F, 23.2910F, 21.8697F, 20.5352F,
  116767. 19.2822F, 18.1056F, 17.0008F, 15.9634F,
  116768. 14.9893F, 14.0746F, 13.2158F, 12.4094F,
  116769. 11.6522F, 10.9411F, 10.2735F, 9.64662F,
  116770. 9.05798F, 8.50526F, 7.98626F, 7.49894F,
  116771. 7.04135F, 6.61169F, 6.20824F, 5.82941F,
  116772. 5.47370F, 5.13970F, 4.82607F, 4.53158F,
  116773. 4.25507F, 3.99542F, 3.75162F, 3.52269F,
  116774. 3.30774F, 3.10590F, 2.91638F, 2.73842F,
  116775. 2.57132F, 2.41442F, 2.26709F, 2.12875F,
  116776. 1.99885F, 1.87688F, 1.76236F, 1.65482F,
  116777. 1.55384F, 1.45902F, 1.36999F, 1.28640F,
  116778. 1.20790F, 1.13419F, 1.06499F, 1.F
  116779. };
  116780. void _vp_remove_floor(vorbis_look_psy *p,
  116781. float *mdct,
  116782. int *codedflr,
  116783. float *residue,
  116784. int sliding_lowpass){
  116785. int i,n=p->n;
  116786. if(sliding_lowpass>n)sliding_lowpass=n;
  116787. for(i=0;i<sliding_lowpass;i++){
  116788. residue[i]=
  116789. mdct[i]*FLOOR1_fromdB_INV_LOOKUP[codedflr[i]];
  116790. }
  116791. for(;i<n;i++)
  116792. residue[i]=0.;
  116793. }
  116794. void _vp_noisemask(vorbis_look_psy *p,
  116795. float *logmdct,
  116796. float *logmask){
  116797. int i,n=p->n;
  116798. float *work=(float*) alloca(n*sizeof(*work));
  116799. bark_noise_hybridmp(n,p->bark,logmdct,logmask,
  116800. 140.,-1);
  116801. for(i=0;i<n;i++)work[i]=logmdct[i]-logmask[i];
  116802. bark_noise_hybridmp(n,p->bark,work,logmask,0.,
  116803. p->vi->noisewindowfixed);
  116804. for(i=0;i<n;i++)work[i]=logmdct[i]-work[i];
  116805. #if 0
  116806. {
  116807. static int seq=0;
  116808. float work2[n];
  116809. for(i=0;i<n;i++){
  116810. work2[i]=logmask[i]+work[i];
  116811. }
  116812. if(seq&1)
  116813. _analysis_output("median2R",seq/2,work,n,1,0,0);
  116814. else
  116815. _analysis_output("median2L",seq/2,work,n,1,0,0);
  116816. if(seq&1)
  116817. _analysis_output("envelope2R",seq/2,work2,n,1,0,0);
  116818. else
  116819. _analysis_output("envelope2L",seq/2,work2,n,1,0,0);
  116820. seq++;
  116821. }
  116822. #endif
  116823. for(i=0;i<n;i++){
  116824. int dB=logmask[i]+.5;
  116825. if(dB>=NOISE_COMPAND_LEVELS)dB=NOISE_COMPAND_LEVELS-1;
  116826. if(dB<0)dB=0;
  116827. logmask[i]= work[i]+p->vi->noisecompand[dB];
  116828. }
  116829. }
  116830. void _vp_tonemask(vorbis_look_psy *p,
  116831. float *logfft,
  116832. float *logmask,
  116833. float global_specmax,
  116834. float local_specmax){
  116835. int i,n=p->n;
  116836. float *seed=(float*) alloca(sizeof(*seed)*p->total_octave_lines);
  116837. float att=local_specmax+p->vi->ath_adjatt;
  116838. for(i=0;i<p->total_octave_lines;i++)seed[i]=NEGINF;
  116839. /* set the ATH (floating below localmax, not global max by a
  116840. specified att) */
  116841. if(att<p->vi->ath_maxatt)att=p->vi->ath_maxatt;
  116842. for(i=0;i<n;i++)
  116843. logmask[i]=p->ath[i]+att;
  116844. /* tone masking */
  116845. seed_loop(p,(const float ***)p->tonecurves,logfft,logmask,seed,global_specmax);
  116846. max_seeds(p,seed,logmask);
  116847. }
  116848. void _vp_offset_and_mix(vorbis_look_psy *p,
  116849. float *noise,
  116850. float *tone,
  116851. int offset_select,
  116852. float *logmask,
  116853. float *mdct,
  116854. float *logmdct){
  116855. int i,n=p->n;
  116856. float de, coeffi, cx;/* AoTuV */
  116857. float toneatt=p->vi->tone_masteratt[offset_select];
  116858. cx = p->m_val;
  116859. for(i=0;i<n;i++){
  116860. float val= noise[i]+p->noiseoffset[offset_select][i];
  116861. if(val>p->vi->noisemaxsupp)val=p->vi->noisemaxsupp;
  116862. logmask[i]=max(val,tone[i]+toneatt);
  116863. /* AoTuV */
  116864. /** @ M1 **
  116865. The following codes improve a noise problem.
  116866. A fundamental idea uses the value of masking and carries out
  116867. the relative compensation of the MDCT.
  116868. However, this code is not perfect and all noise problems cannot be solved.
  116869. by Aoyumi @ 2004/04/18
  116870. */
  116871. if(offset_select == 1) {
  116872. coeffi = -17.2; /* coeffi is a -17.2dB threshold */
  116873. val = val - logmdct[i]; /* val == mdct line value relative to floor in dB */
  116874. if(val > coeffi){
  116875. /* mdct value is > -17.2 dB below floor */
  116876. de = 1.0-((val-coeffi)*0.005*cx);
  116877. /* pro-rated attenuation:
  116878. -0.00 dB boost if mdct value is -17.2dB (relative to floor)
  116879. -0.77 dB boost if mdct value is 0dB (relative to floor)
  116880. -1.64 dB boost if mdct value is +17.2dB (relative to floor)
  116881. etc... */
  116882. if(de < 0) de = 0.0001;
  116883. }else
  116884. /* mdct value is <= -17.2 dB below floor */
  116885. de = 1.0-((val-coeffi)*0.0003*cx);
  116886. /* pro-rated attenuation:
  116887. +0.00 dB atten if mdct value is -17.2dB (relative to floor)
  116888. +0.45 dB atten if mdct value is -34.4dB (relative to floor)
  116889. etc... */
  116890. mdct[i] *= de;
  116891. }
  116892. }
  116893. }
  116894. float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd){
  116895. vorbis_info *vi=vd->vi;
  116896. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  116897. vorbis_info_psy_global *gi=&ci->psy_g_param;
  116898. int n=ci->blocksizes[vd->W]/2;
  116899. float secs=(float)n/vi->rate;
  116900. amp+=secs*gi->ampmax_att_per_sec;
  116901. if(amp<-9999)amp=-9999;
  116902. return(amp);
  116903. }
  116904. static void couple_lossless(float A, float B,
  116905. float *qA, float *qB){
  116906. int test1=fabs(*qA)>fabs(*qB);
  116907. test1-= fabs(*qA)<fabs(*qB);
  116908. if(!test1)test1=((fabs(A)>fabs(B))<<1)-1;
  116909. if(test1==1){
  116910. *qB=(*qA>0.f?*qA-*qB:*qB-*qA);
  116911. }else{
  116912. float temp=*qB;
  116913. *qB=(*qB>0.f?*qA-*qB:*qB-*qA);
  116914. *qA=temp;
  116915. }
  116916. if(*qB>fabs(*qA)*1.9999f){
  116917. *qB= -fabs(*qA)*2.f;
  116918. *qA= -*qA;
  116919. }
  116920. }
  116921. static float hypot_lookup[32]={
  116922. -0.009935, -0.011245, -0.012726, -0.014397,
  116923. -0.016282, -0.018407, -0.020800, -0.023494,
  116924. -0.026522, -0.029923, -0.033737, -0.038010,
  116925. -0.042787, -0.048121, -0.054064, -0.060671,
  116926. -0.068000, -0.076109, -0.085054, -0.094892,
  116927. -0.105675, -0.117451, -0.130260, -0.144134,
  116928. -0.159093, -0.175146, -0.192286, -0.210490,
  116929. -0.229718, -0.249913, -0.271001, -0.292893};
  116930. static void precomputed_couple_point(float premag,
  116931. int floorA,int floorB,
  116932. float *mag, float *ang){
  116933. int test=(floorA>floorB)-1;
  116934. int offset=31-abs(floorA-floorB);
  116935. float floormag=hypot_lookup[((offset<0)-1)&offset]+1.f;
  116936. floormag*=FLOOR1_fromdB_INV_LOOKUP[(floorB&test)|(floorA&(~test))];
  116937. *mag=premag*floormag;
  116938. *ang=0.f;
  116939. }
  116940. /* just like below, this is currently set up to only do
  116941. single-step-depth coupling. Otherwise, we'd have to do more
  116942. copying (which will be inevitable later) */
  116943. /* doing the real circular magnitude calculation is audibly superior
  116944. to (A+B)/sqrt(2) */
  116945. static float dipole_hypot(float a, float b){
  116946. if(a>0.){
  116947. if(b>0.)return sqrt(a*a+b*b);
  116948. if(a>-b)return sqrt(a*a-b*b);
  116949. return -sqrt(b*b-a*a);
  116950. }
  116951. if(b<0.)return -sqrt(a*a+b*b);
  116952. if(-a>b)return -sqrt(a*a-b*b);
  116953. return sqrt(b*b-a*a);
  116954. }
  116955. static float round_hypot(float a, float b){
  116956. if(a>0.){
  116957. if(b>0.)return sqrt(a*a+b*b);
  116958. if(a>-b)return sqrt(a*a+b*b);
  116959. return -sqrt(b*b+a*a);
  116960. }
  116961. if(b<0.)return -sqrt(a*a+b*b);
  116962. if(-a>b)return -sqrt(a*a+b*b);
  116963. return sqrt(b*b+a*a);
  116964. }
  116965. /* revert to round hypot for now */
  116966. float **_vp_quantize_couple_memo(vorbis_block *vb,
  116967. vorbis_info_psy_global *g,
  116968. vorbis_look_psy *p,
  116969. vorbis_info_mapping0 *vi,
  116970. float **mdct){
  116971. int i,j,n=p->n;
  116972. float **ret=(float**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  116973. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  116974. for(i=0;i<vi->coupling_steps;i++){
  116975. float *mdctM=mdct[vi->coupling_mag[i]];
  116976. float *mdctA=mdct[vi->coupling_ang[i]];
  116977. ret[i]=(float*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  116978. for(j=0;j<limit;j++)
  116979. ret[i][j]=dipole_hypot(mdctM[j],mdctA[j]);
  116980. for(;j<n;j++)
  116981. ret[i][j]=round_hypot(mdctM[j],mdctA[j]);
  116982. }
  116983. return(ret);
  116984. }
  116985. /* this is for per-channel noise normalization */
  116986. static int apsort(const void *a, const void *b){
  116987. float f1=fabs(**(float**)a);
  116988. float f2=fabs(**(float**)b);
  116989. return (f1<f2)-(f1>f2);
  116990. }
  116991. int **_vp_quantize_couple_sort(vorbis_block *vb,
  116992. vorbis_look_psy *p,
  116993. vorbis_info_mapping0 *vi,
  116994. float **mags){
  116995. if(p->vi->normal_point_p){
  116996. int i,j,k,n=p->n;
  116997. int **ret=(int**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  116998. int partition=p->vi->normal_partition;
  116999. float **work=(float**) alloca(sizeof(*work)*partition);
  117000. for(i=0;i<vi->coupling_steps;i++){
  117001. ret[i]=(int*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  117002. for(j=0;j<n;j+=partition){
  117003. for(k=0;k<partition;k++)work[k]=mags[i]+k+j;
  117004. qsort(work,partition,sizeof(*work),apsort);
  117005. for(k=0;k<partition;k++)ret[i][k+j]=work[k]-mags[i];
  117006. }
  117007. }
  117008. return(ret);
  117009. }
  117010. return(NULL);
  117011. }
  117012. void _vp_noise_normalize_sort(vorbis_look_psy *p,
  117013. float *magnitudes,int *sortedindex){
  117014. int i,j,n=p->n;
  117015. vorbis_info_psy *vi=p->vi;
  117016. int partition=vi->normal_partition;
  117017. float **work=(float**) alloca(sizeof(*work)*partition);
  117018. int start=vi->normal_start;
  117019. for(j=start;j<n;j+=partition){
  117020. if(j+partition>n)partition=n-j;
  117021. for(i=0;i<partition;i++)work[i]=magnitudes+i+j;
  117022. qsort(work,partition,sizeof(*work),apsort);
  117023. for(i=0;i<partition;i++){
  117024. sortedindex[i+j-start]=work[i]-magnitudes;
  117025. }
  117026. }
  117027. }
  117028. void _vp_noise_normalize(vorbis_look_psy *p,
  117029. float *in,float *out,int *sortedindex){
  117030. int flag=0,i,j=0,n=p->n;
  117031. vorbis_info_psy *vi=p->vi;
  117032. int partition=vi->normal_partition;
  117033. int start=vi->normal_start;
  117034. if(start>n)start=n;
  117035. if(vi->normal_channel_p){
  117036. for(;j<start;j++)
  117037. out[j]=rint(in[j]);
  117038. for(;j+partition<=n;j+=partition){
  117039. float acc=0.;
  117040. int k;
  117041. for(i=j;i<j+partition;i++)
  117042. acc+=in[i]*in[i];
  117043. for(i=0;i<partition;i++){
  117044. k=sortedindex[i+j-start];
  117045. if(in[k]*in[k]>=.25f){
  117046. out[k]=rint(in[k]);
  117047. acc-=in[k]*in[k];
  117048. flag=1;
  117049. }else{
  117050. if(acc<vi->normal_thresh)break;
  117051. out[k]=unitnorm(in[k]);
  117052. acc-=1.;
  117053. }
  117054. }
  117055. for(;i<partition;i++){
  117056. k=sortedindex[i+j-start];
  117057. out[k]=0.;
  117058. }
  117059. }
  117060. }
  117061. for(;j<n;j++)
  117062. out[j]=rint(in[j]);
  117063. }
  117064. void _vp_couple(int blobno,
  117065. vorbis_info_psy_global *g,
  117066. vorbis_look_psy *p,
  117067. vorbis_info_mapping0 *vi,
  117068. float **res,
  117069. float **mag_memo,
  117070. int **mag_sort,
  117071. int **ifloor,
  117072. int *nonzero,
  117073. int sliding_lowpass){
  117074. int i,j,k,n=p->n;
  117075. /* perform any requested channel coupling */
  117076. /* point stereo can only be used in a first stage (in this encoder)
  117077. because of the dependency on floor lookups */
  117078. for(i=0;i<vi->coupling_steps;i++){
  117079. /* once we're doing multistage coupling in which a channel goes
  117080. through more than one coupling step, the floor vector
  117081. magnitudes will also have to be recalculated an propogated
  117082. along with PCM. Right now, we're not (that will wait until 5.1
  117083. most likely), so the code isn't here yet. The memory management
  117084. here is all assuming single depth couplings anyway. */
  117085. /* make sure coupling a zero and a nonzero channel results in two
  117086. nonzero channels. */
  117087. if(nonzero[vi->coupling_mag[i]] ||
  117088. nonzero[vi->coupling_ang[i]]){
  117089. float *rM=res[vi->coupling_mag[i]];
  117090. float *rA=res[vi->coupling_ang[i]];
  117091. float *qM=rM+n;
  117092. float *qA=rA+n;
  117093. int *floorM=ifloor[vi->coupling_mag[i]];
  117094. int *floorA=ifloor[vi->coupling_ang[i]];
  117095. float prepoint=stereo_threshholds[g->coupling_prepointamp[blobno]];
  117096. float postpoint=stereo_threshholds[g->coupling_postpointamp[blobno]];
  117097. int partition=(p->vi->normal_point_p?p->vi->normal_partition:p->n);
  117098. int limit=g->coupling_pointlimit[p->vi->blockflag][blobno];
  117099. int pointlimit=limit;
  117100. nonzero[vi->coupling_mag[i]]=1;
  117101. nonzero[vi->coupling_ang[i]]=1;
  117102. /* The threshold of a stereo is changed with the size of n */
  117103. if(n > 1000)
  117104. postpoint=stereo_threshholds_limited[g->coupling_postpointamp[blobno]];
  117105. for(j=0;j<p->n;j+=partition){
  117106. float acc=0.f;
  117107. for(k=0;k<partition;k++){
  117108. int l=k+j;
  117109. if(l<sliding_lowpass){
  117110. if((l>=limit && fabs(rM[l])<postpoint && fabs(rA[l])<postpoint) ||
  117111. (fabs(rM[l])<prepoint && fabs(rA[l])<prepoint)){
  117112. precomputed_couple_point(mag_memo[i][l],
  117113. floorM[l],floorA[l],
  117114. qM+l,qA+l);
  117115. if(rint(qM[l])==0.f)acc+=qM[l]*qM[l];
  117116. }else{
  117117. couple_lossless(rM[l],rA[l],qM+l,qA+l);
  117118. }
  117119. }else{
  117120. qM[l]=0.;
  117121. qA[l]=0.;
  117122. }
  117123. }
  117124. if(p->vi->normal_point_p){
  117125. for(k=0;k<partition && acc>=p->vi->normal_thresh;k++){
  117126. int l=mag_sort[i][j+k];
  117127. if(l<sliding_lowpass && l>=pointlimit && rint(qM[l])==0.f){
  117128. qM[l]=unitnorm(qM[l]);
  117129. acc-=1.f;
  117130. }
  117131. }
  117132. }
  117133. }
  117134. }
  117135. }
  117136. }
  117137. /* AoTuV */
  117138. /** @ M2 **
  117139. The boost problem by the combination of noise normalization and point stereo is eased.
  117140. However, this is a temporary patch.
  117141. by Aoyumi @ 2004/04/18
  117142. */
  117143. void hf_reduction(vorbis_info_psy_global *g,
  117144. vorbis_look_psy *p,
  117145. vorbis_info_mapping0 *vi,
  117146. float **mdct){
  117147. int i,j,n=p->n, de=0.3*p->m_val;
  117148. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  117149. for(i=0; i<vi->coupling_steps; i++){
  117150. /* for(j=start; j<limit; j++){} // ???*/
  117151. for(j=limit; j<n; j++)
  117152. mdct[i][j] *= (1.0 - de*((float)(j-limit) / (float)(n-limit)));
  117153. }
  117154. }
  117155. #endif
  117156. /*** End of inlined file: psy.c ***/
  117157. /*** Start of inlined file: registry.c ***/
  117158. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  117159. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  117160. // tasks..
  117161. #if JUCE_MSVC
  117162. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  117163. #endif
  117164. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  117165. #if JUCE_USE_OGGVORBIS
  117166. /* seems like major overkill now; the backend numbers will grow into
  117167. the infrastructure soon enough */
  117168. extern vorbis_func_floor floor0_exportbundle;
  117169. extern vorbis_func_floor floor1_exportbundle;
  117170. extern vorbis_func_residue residue0_exportbundle;
  117171. extern vorbis_func_residue residue1_exportbundle;
  117172. extern vorbis_func_residue residue2_exportbundle;
  117173. extern vorbis_func_mapping mapping0_exportbundle;
  117174. vorbis_func_floor *_floor_P[]={
  117175. &floor0_exportbundle,
  117176. &floor1_exportbundle,
  117177. };
  117178. vorbis_func_residue *_residue_P[]={
  117179. &residue0_exportbundle,
  117180. &residue1_exportbundle,
  117181. &residue2_exportbundle,
  117182. };
  117183. vorbis_func_mapping *_mapping_P[]={
  117184. &mapping0_exportbundle,
  117185. };
  117186. #endif
  117187. /*** End of inlined file: registry.c ***/
  117188. /*** Start of inlined file: res0.c ***/
  117189. /* Slow, slow, slow, simpleminded and did I mention it was slow? The
  117190. encode/decode loops are coded for clarity and performance is not
  117191. yet even a nagging little idea lurking in the shadows. Oh and BTW,
  117192. it's slow. */
  117193. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  117194. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  117195. // tasks..
  117196. #if JUCE_MSVC
  117197. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  117198. #endif
  117199. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  117200. #if JUCE_USE_OGGVORBIS
  117201. #include <stdlib.h>
  117202. #include <string.h>
  117203. #include <math.h>
  117204. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  117205. #include <stdio.h>
  117206. #endif
  117207. typedef struct {
  117208. vorbis_info_residue0 *info;
  117209. int parts;
  117210. int stages;
  117211. codebook *fullbooks;
  117212. codebook *phrasebook;
  117213. codebook ***partbooks;
  117214. int partvals;
  117215. int **decodemap;
  117216. long postbits;
  117217. long phrasebits;
  117218. long frames;
  117219. #if defined(TRAIN_RES) || defined(TRAIN_RESAUX)
  117220. int train_seq;
  117221. long *training_data[8][64];
  117222. float training_max[8][64];
  117223. float training_min[8][64];
  117224. float tmin;
  117225. float tmax;
  117226. #endif
  117227. } vorbis_look_residue0;
  117228. void res0_free_info(vorbis_info_residue *i){
  117229. vorbis_info_residue0 *info=(vorbis_info_residue0 *)i;
  117230. if(info){
  117231. memset(info,0,sizeof(*info));
  117232. _ogg_free(info);
  117233. }
  117234. }
  117235. void res0_free_look(vorbis_look_residue *i){
  117236. int j;
  117237. if(i){
  117238. vorbis_look_residue0 *look=(vorbis_look_residue0 *)i;
  117239. #ifdef TRAIN_RES
  117240. {
  117241. int j,k,l;
  117242. for(j=0;j<look->parts;j++){
  117243. /*fprintf(stderr,"partition %d: ",j);*/
  117244. for(k=0;k<8;k++)
  117245. if(look->training_data[k][j]){
  117246. char buffer[80];
  117247. FILE *of;
  117248. codebook *statebook=look->partbooks[j][k];
  117249. /* long and short into the same bucket by current convention */
  117250. sprintf(buffer,"res_part%d_pass%d.vqd",j,k);
  117251. of=fopen(buffer,"a");
  117252. for(l=0;l<statebook->entries;l++)
  117253. fprintf(of,"%d:%ld\n",l,look->training_data[k][j][l]);
  117254. fclose(of);
  117255. /*fprintf(stderr,"%d(%.2f|%.2f) ",k,
  117256. look->training_min[k][j],look->training_max[k][j]);*/
  117257. _ogg_free(look->training_data[k][j]);
  117258. look->training_data[k][j]=NULL;
  117259. }
  117260. /*fprintf(stderr,"\n");*/
  117261. }
  117262. }
  117263. fprintf(stderr,"min/max residue: %g::%g\n",look->tmin,look->tmax);
  117264. /*fprintf(stderr,"residue bit usage %f:%f (%f total)\n",
  117265. (float)look->phrasebits/look->frames,
  117266. (float)look->postbits/look->frames,
  117267. (float)(look->postbits+look->phrasebits)/look->frames);*/
  117268. #endif
  117269. /*vorbis_info_residue0 *info=look->info;
  117270. fprintf(stderr,
  117271. "%ld frames encoded in %ld phrasebits and %ld residue bits "
  117272. "(%g/frame) \n",look->frames,look->phrasebits,
  117273. look->resbitsflat,
  117274. (look->phrasebits+look->resbitsflat)/(float)look->frames);
  117275. for(j=0;j<look->parts;j++){
  117276. long acc=0;
  117277. fprintf(stderr,"\t[%d] == ",j);
  117278. for(k=0;k<look->stages;k++)
  117279. if((info->secondstages[j]>>k)&1){
  117280. fprintf(stderr,"%ld,",look->resbits[j][k]);
  117281. acc+=look->resbits[j][k];
  117282. }
  117283. fprintf(stderr,":: (%ld vals) %1.2fbits/sample\n",look->resvals[j],
  117284. acc?(float)acc/(look->resvals[j]*info->grouping):0);
  117285. }
  117286. fprintf(stderr,"\n");*/
  117287. for(j=0;j<look->parts;j++)
  117288. if(look->partbooks[j])_ogg_free(look->partbooks[j]);
  117289. _ogg_free(look->partbooks);
  117290. for(j=0;j<look->partvals;j++)
  117291. _ogg_free(look->decodemap[j]);
  117292. _ogg_free(look->decodemap);
  117293. memset(look,0,sizeof(*look));
  117294. _ogg_free(look);
  117295. }
  117296. }
  117297. static int icount(unsigned int v){
  117298. int ret=0;
  117299. while(v){
  117300. ret+=v&1;
  117301. v>>=1;
  117302. }
  117303. return(ret);
  117304. }
  117305. void res0_pack(vorbis_info_residue *vr,oggpack_buffer *opb){
  117306. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  117307. int j,acc=0;
  117308. oggpack_write(opb,info->begin,24);
  117309. oggpack_write(opb,info->end,24);
  117310. oggpack_write(opb,info->grouping-1,24); /* residue vectors to group and
  117311. code with a partitioned book */
  117312. oggpack_write(opb,info->partitions-1,6); /* possible partition choices */
  117313. oggpack_write(opb,info->groupbook,8); /* group huffman book */
  117314. /* secondstages is a bitmask; as encoding progresses pass by pass, a
  117315. bitmask of one indicates this partition class has bits to write
  117316. this pass */
  117317. for(j=0;j<info->partitions;j++){
  117318. if(ilog(info->secondstages[j])>3){
  117319. /* yes, this is a minor hack due to not thinking ahead */
  117320. oggpack_write(opb,info->secondstages[j],3);
  117321. oggpack_write(opb,1,1);
  117322. oggpack_write(opb,info->secondstages[j]>>3,5);
  117323. }else
  117324. oggpack_write(opb,info->secondstages[j],4); /* trailing zero */
  117325. acc+=icount(info->secondstages[j]);
  117326. }
  117327. for(j=0;j<acc;j++)
  117328. oggpack_write(opb,info->booklist[j],8);
  117329. }
  117330. /* vorbis_info is for range checking */
  117331. vorbis_info_residue *res0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  117332. int j,acc=0;
  117333. vorbis_info_residue0 *info=(vorbis_info_residue0*) _ogg_calloc(1,sizeof(*info));
  117334. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  117335. info->begin=oggpack_read(opb,24);
  117336. info->end=oggpack_read(opb,24);
  117337. info->grouping=oggpack_read(opb,24)+1;
  117338. info->partitions=oggpack_read(opb,6)+1;
  117339. info->groupbook=oggpack_read(opb,8);
  117340. for(j=0;j<info->partitions;j++){
  117341. int cascade=oggpack_read(opb,3);
  117342. if(oggpack_read(opb,1))
  117343. cascade|=(oggpack_read(opb,5)<<3);
  117344. info->secondstages[j]=cascade;
  117345. acc+=icount(cascade);
  117346. }
  117347. for(j=0;j<acc;j++)
  117348. info->booklist[j]=oggpack_read(opb,8);
  117349. if(info->groupbook>=ci->books)goto errout;
  117350. for(j=0;j<acc;j++)
  117351. if(info->booklist[j]>=ci->books)goto errout;
  117352. return(info);
  117353. errout:
  117354. res0_free_info(info);
  117355. return(NULL);
  117356. }
  117357. vorbis_look_residue *res0_look(vorbis_dsp_state *vd,
  117358. vorbis_info_residue *vr){
  117359. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  117360. vorbis_look_residue0 *look=(vorbis_look_residue0 *)_ogg_calloc(1,sizeof(*look));
  117361. codec_setup_info *ci=(codec_setup_info*)vd->vi->codec_setup;
  117362. int j,k,acc=0;
  117363. int dim;
  117364. int maxstage=0;
  117365. look->info=info;
  117366. look->parts=info->partitions;
  117367. look->fullbooks=ci->fullbooks;
  117368. look->phrasebook=ci->fullbooks+info->groupbook;
  117369. dim=look->phrasebook->dim;
  117370. look->partbooks=(codebook***)_ogg_calloc(look->parts,sizeof(*look->partbooks));
  117371. for(j=0;j<look->parts;j++){
  117372. int stages=ilog(info->secondstages[j]);
  117373. if(stages){
  117374. if(stages>maxstage)maxstage=stages;
  117375. look->partbooks[j]=(codebook**) _ogg_calloc(stages,sizeof(*look->partbooks[j]));
  117376. for(k=0;k<stages;k++)
  117377. if(info->secondstages[j]&(1<<k)){
  117378. look->partbooks[j][k]=ci->fullbooks+info->booklist[acc++];
  117379. #ifdef TRAIN_RES
  117380. look->training_data[k][j]=_ogg_calloc(look->partbooks[j][k]->entries,
  117381. sizeof(***look->training_data));
  117382. #endif
  117383. }
  117384. }
  117385. }
  117386. look->partvals=rint(pow((float)look->parts,(float)dim));
  117387. look->stages=maxstage;
  117388. look->decodemap=(int**)_ogg_malloc(look->partvals*sizeof(*look->decodemap));
  117389. for(j=0;j<look->partvals;j++){
  117390. long val=j;
  117391. long mult=look->partvals/look->parts;
  117392. look->decodemap[j]=(int*)_ogg_malloc(dim*sizeof(*look->decodemap[j]));
  117393. for(k=0;k<dim;k++){
  117394. long deco=val/mult;
  117395. val-=deco*mult;
  117396. mult/=look->parts;
  117397. look->decodemap[j][k]=deco;
  117398. }
  117399. }
  117400. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  117401. {
  117402. static int train_seq=0;
  117403. look->train_seq=train_seq++;
  117404. }
  117405. #endif
  117406. return(look);
  117407. }
  117408. /* break an abstraction and copy some code for performance purposes */
  117409. static int local_book_besterror(codebook *book,float *a){
  117410. int dim=book->dim,i,k,o;
  117411. int best=0;
  117412. encode_aux_threshmatch *tt=book->c->thresh_tree;
  117413. /* find the quant val of each scalar */
  117414. for(k=0,o=dim;k<dim;++k){
  117415. float val=a[--o];
  117416. i=tt->threshvals>>1;
  117417. if(val<tt->quantthresh[i]){
  117418. if(val<tt->quantthresh[i-1]){
  117419. for(--i;i>0;--i)
  117420. if(val>=tt->quantthresh[i-1])
  117421. break;
  117422. }
  117423. }else{
  117424. for(++i;i<tt->threshvals-1;++i)
  117425. if(val<tt->quantthresh[i])break;
  117426. }
  117427. best=(best*tt->quantvals)+tt->quantmap[i];
  117428. }
  117429. /* regular lattices are easy :-) */
  117430. if(book->c->lengthlist[best]<=0){
  117431. const static_codebook *c=book->c;
  117432. int i,j;
  117433. float bestf=0.f;
  117434. float *e=book->valuelist;
  117435. best=-1;
  117436. for(i=0;i<book->entries;i++){
  117437. if(c->lengthlist[i]>0){
  117438. float thisx=0.f;
  117439. for(j=0;j<dim;j++){
  117440. float val=(e[j]-a[j]);
  117441. thisx+=val*val;
  117442. }
  117443. if(best==-1 || thisx<bestf){
  117444. bestf=thisx;
  117445. best=i;
  117446. }
  117447. }
  117448. e+=dim;
  117449. }
  117450. }
  117451. {
  117452. float *ptr=book->valuelist+best*dim;
  117453. for(i=0;i<dim;i++)
  117454. *a++ -= *ptr++;
  117455. }
  117456. return(best);
  117457. }
  117458. static int _encodepart(oggpack_buffer *opb,float *vec, int n,
  117459. codebook *book,long *acc){
  117460. int i,bits=0;
  117461. int dim=book->dim;
  117462. int step=n/dim;
  117463. for(i=0;i<step;i++){
  117464. int entry=local_book_besterror(book,vec+i*dim);
  117465. #ifdef TRAIN_RES
  117466. acc[entry]++;
  117467. #endif
  117468. bits+=vorbis_book_encode(book,entry,opb);
  117469. }
  117470. return(bits);
  117471. }
  117472. static long **_01class(vorbis_block *vb,vorbis_look_residue *vl,
  117473. float **in,int ch){
  117474. long i,j,k;
  117475. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  117476. vorbis_info_residue0 *info=look->info;
  117477. /* move all this setup out later */
  117478. int samples_per_partition=info->grouping;
  117479. int possible_partitions=info->partitions;
  117480. int n=info->end-info->begin;
  117481. int partvals=n/samples_per_partition;
  117482. long **partword=(long**)_vorbis_block_alloc(vb,ch*sizeof(*partword));
  117483. float scale=100./samples_per_partition;
  117484. /* we find the partition type for each partition of each
  117485. channel. We'll go back and do the interleaved encoding in a
  117486. bit. For now, clarity */
  117487. for(i=0;i<ch;i++){
  117488. partword[i]=(long*)_vorbis_block_alloc(vb,n/samples_per_partition*sizeof(*partword[i]));
  117489. memset(partword[i],0,n/samples_per_partition*sizeof(*partword[i]));
  117490. }
  117491. for(i=0;i<partvals;i++){
  117492. int offset=i*samples_per_partition+info->begin;
  117493. for(j=0;j<ch;j++){
  117494. float max=0.;
  117495. float ent=0.;
  117496. for(k=0;k<samples_per_partition;k++){
  117497. if(fabs(in[j][offset+k])>max)max=fabs(in[j][offset+k]);
  117498. ent+=fabs(rint(in[j][offset+k]));
  117499. }
  117500. ent*=scale;
  117501. for(k=0;k<possible_partitions-1;k++)
  117502. if(max<=info->classmetric1[k] &&
  117503. (info->classmetric2[k]<0 || (int)ent<info->classmetric2[k]))
  117504. break;
  117505. partword[j][i]=k;
  117506. }
  117507. }
  117508. #ifdef TRAIN_RESAUX
  117509. {
  117510. FILE *of;
  117511. char buffer[80];
  117512. for(i=0;i<ch;i++){
  117513. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  117514. of=fopen(buffer,"a");
  117515. for(j=0;j<partvals;j++)
  117516. fprintf(of,"%ld, ",partword[i][j]);
  117517. fprintf(of,"\n");
  117518. fclose(of);
  117519. }
  117520. }
  117521. #endif
  117522. look->frames++;
  117523. return(partword);
  117524. }
  117525. /* designed for stereo or other modes where the partition size is an
  117526. integer multiple of the number of channels encoded in the current
  117527. submap */
  117528. static long **_2class(vorbis_block *vb,vorbis_look_residue *vl,float **in,
  117529. int ch){
  117530. long i,j,k,l;
  117531. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  117532. vorbis_info_residue0 *info=look->info;
  117533. /* move all this setup out later */
  117534. int samples_per_partition=info->grouping;
  117535. int possible_partitions=info->partitions;
  117536. int n=info->end-info->begin;
  117537. int partvals=n/samples_per_partition;
  117538. long **partword=(long**)_vorbis_block_alloc(vb,sizeof(*partword));
  117539. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  117540. FILE *of;
  117541. char buffer[80];
  117542. #endif
  117543. partword[0]=(long*)_vorbis_block_alloc(vb,n*ch/samples_per_partition*sizeof(*partword[0]));
  117544. memset(partword[0],0,n*ch/samples_per_partition*sizeof(*partword[0]));
  117545. for(i=0,l=info->begin/ch;i<partvals;i++){
  117546. float magmax=0.f;
  117547. float angmax=0.f;
  117548. for(j=0;j<samples_per_partition;j+=ch){
  117549. if(fabs(in[0][l])>magmax)magmax=fabs(in[0][l]);
  117550. for(k=1;k<ch;k++)
  117551. if(fabs(in[k][l])>angmax)angmax=fabs(in[k][l]);
  117552. l++;
  117553. }
  117554. for(j=0;j<possible_partitions-1;j++)
  117555. if(magmax<=info->classmetric1[j] &&
  117556. angmax<=info->classmetric2[j])
  117557. break;
  117558. partword[0][i]=j;
  117559. }
  117560. #ifdef TRAIN_RESAUX
  117561. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  117562. of=fopen(buffer,"a");
  117563. for(i=0;i<partvals;i++)
  117564. fprintf(of,"%ld, ",partword[0][i]);
  117565. fprintf(of,"\n");
  117566. fclose(of);
  117567. #endif
  117568. look->frames++;
  117569. return(partword);
  117570. }
  117571. static int _01forward(oggpack_buffer *opb,
  117572. vorbis_block *vb,vorbis_look_residue *vl,
  117573. float **in,int ch,
  117574. long **partword,
  117575. int (*encode)(oggpack_buffer *,float *,int,
  117576. codebook *,long *)){
  117577. long i,j,k,s;
  117578. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  117579. vorbis_info_residue0 *info=look->info;
  117580. /* move all this setup out later */
  117581. int samples_per_partition=info->grouping;
  117582. int possible_partitions=info->partitions;
  117583. int partitions_per_word=look->phrasebook->dim;
  117584. int n=info->end-info->begin;
  117585. int partvals=n/samples_per_partition;
  117586. long resbits[128];
  117587. long resvals[128];
  117588. #ifdef TRAIN_RES
  117589. for(i=0;i<ch;i++)
  117590. for(j=info->begin;j<info->end;j++){
  117591. if(in[i][j]>look->tmax)look->tmax=in[i][j];
  117592. if(in[i][j]<look->tmin)look->tmin=in[i][j];
  117593. }
  117594. #endif
  117595. memset(resbits,0,sizeof(resbits));
  117596. memset(resvals,0,sizeof(resvals));
  117597. /* we code the partition words for each channel, then the residual
  117598. words for a partition per channel until we've written all the
  117599. residual words for that partition word. Then write the next
  117600. partition channel words... */
  117601. for(s=0;s<look->stages;s++){
  117602. for(i=0;i<partvals;){
  117603. /* first we encode a partition codeword for each channel */
  117604. if(s==0){
  117605. for(j=0;j<ch;j++){
  117606. long val=partword[j][i];
  117607. for(k=1;k<partitions_per_word;k++){
  117608. val*=possible_partitions;
  117609. if(i+k<partvals)
  117610. val+=partword[j][i+k];
  117611. }
  117612. /* training hack */
  117613. if(val<look->phrasebook->entries)
  117614. look->phrasebits+=vorbis_book_encode(look->phrasebook,val,opb);
  117615. #if 0 /*def TRAIN_RES*/
  117616. else
  117617. fprintf(stderr,"!");
  117618. #endif
  117619. }
  117620. }
  117621. /* now we encode interleaved residual values for the partitions */
  117622. for(k=0;k<partitions_per_word && i<partvals;k++,i++){
  117623. long offset=i*samples_per_partition+info->begin;
  117624. for(j=0;j<ch;j++){
  117625. if(s==0)resvals[partword[j][i]]+=samples_per_partition;
  117626. if(info->secondstages[partword[j][i]]&(1<<s)){
  117627. codebook *statebook=look->partbooks[partword[j][i]][s];
  117628. if(statebook){
  117629. int ret;
  117630. long *accumulator=NULL;
  117631. #ifdef TRAIN_RES
  117632. accumulator=look->training_data[s][partword[j][i]];
  117633. {
  117634. int l;
  117635. float *samples=in[j]+offset;
  117636. for(l=0;l<samples_per_partition;l++){
  117637. if(samples[l]<look->training_min[s][partword[j][i]])
  117638. look->training_min[s][partword[j][i]]=samples[l];
  117639. if(samples[l]>look->training_max[s][partword[j][i]])
  117640. look->training_max[s][partword[j][i]]=samples[l];
  117641. }
  117642. }
  117643. #endif
  117644. ret=encode(opb,in[j]+offset,samples_per_partition,
  117645. statebook,accumulator);
  117646. look->postbits+=ret;
  117647. resbits[partword[j][i]]+=ret;
  117648. }
  117649. }
  117650. }
  117651. }
  117652. }
  117653. }
  117654. /*{
  117655. long total=0;
  117656. long totalbits=0;
  117657. fprintf(stderr,"%d :: ",vb->mode);
  117658. for(k=0;k<possible_partitions;k++){
  117659. fprintf(stderr,"%ld/%1.2g, ",resvals[k],(float)resbits[k]/resvals[k]);
  117660. total+=resvals[k];
  117661. totalbits+=resbits[k];
  117662. }
  117663. fprintf(stderr,":: %ld:%1.2g\n",total,(double)totalbits/total);
  117664. }*/
  117665. return(0);
  117666. }
  117667. /* a truncated packet here just means 'stop working'; it's not an error */
  117668. static int _01inverse(vorbis_block *vb,vorbis_look_residue *vl,
  117669. float **in,int ch,
  117670. long (*decodepart)(codebook *, float *,
  117671. oggpack_buffer *,int)){
  117672. long i,j,k,l,s;
  117673. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  117674. vorbis_info_residue0 *info=look->info;
  117675. /* move all this setup out later */
  117676. int samples_per_partition=info->grouping;
  117677. int partitions_per_word=look->phrasebook->dim;
  117678. int n=info->end-info->begin;
  117679. int partvals=n/samples_per_partition;
  117680. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  117681. int ***partword=(int***)alloca(ch*sizeof(*partword));
  117682. for(j=0;j<ch;j++)
  117683. partword[j]=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword[j]));
  117684. for(s=0;s<look->stages;s++){
  117685. /* each loop decodes on partition codeword containing
  117686. partitions_pre_word partitions */
  117687. for(i=0,l=0;i<partvals;l++){
  117688. if(s==0){
  117689. /* fetch the partition word for each channel */
  117690. for(j=0;j<ch;j++){
  117691. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  117692. if(temp==-1)goto eopbreak;
  117693. partword[j][l]=look->decodemap[temp];
  117694. if(partword[j][l]==NULL)goto errout;
  117695. }
  117696. }
  117697. /* now we decode residual values for the partitions */
  117698. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  117699. for(j=0;j<ch;j++){
  117700. long offset=info->begin+i*samples_per_partition;
  117701. if(info->secondstages[partword[j][l][k]]&(1<<s)){
  117702. codebook *stagebook=look->partbooks[partword[j][l][k]][s];
  117703. if(stagebook){
  117704. if(decodepart(stagebook,in[j]+offset,&vb->opb,
  117705. samples_per_partition)==-1)goto eopbreak;
  117706. }
  117707. }
  117708. }
  117709. }
  117710. }
  117711. errout:
  117712. eopbreak:
  117713. return(0);
  117714. }
  117715. #if 0
  117716. /* residue 0 and 1 are just slight variants of one another. 0 is
  117717. interleaved, 1 is not */
  117718. long **res0_class(vorbis_block *vb,vorbis_look_residue *vl,
  117719. float **in,int *nonzero,int ch){
  117720. /* we encode only the nonzero parts of a bundle */
  117721. int i,used=0;
  117722. for(i=0;i<ch;i++)
  117723. if(nonzero[i])
  117724. in[used++]=in[i];
  117725. if(used)
  117726. /*return(_01class(vb,vl,in,used,_interleaved_testhack));*/
  117727. return(_01class(vb,vl,in,used));
  117728. else
  117729. return(0);
  117730. }
  117731. int res0_forward(vorbis_block *vb,vorbis_look_residue *vl,
  117732. float **in,float **out,int *nonzero,int ch,
  117733. long **partword){
  117734. /* we encode only the nonzero parts of a bundle */
  117735. int i,j,used=0,n=vb->pcmend/2;
  117736. for(i=0;i<ch;i++)
  117737. if(nonzero[i]){
  117738. if(out)
  117739. for(j=0;j<n;j++)
  117740. out[i][j]+=in[i][j];
  117741. in[used++]=in[i];
  117742. }
  117743. if(used){
  117744. int ret=_01forward(vb,vl,in,used,partword,
  117745. _interleaved_encodepart);
  117746. if(out){
  117747. used=0;
  117748. for(i=0;i<ch;i++)
  117749. if(nonzero[i]){
  117750. for(j=0;j<n;j++)
  117751. out[i][j]-=in[used][j];
  117752. used++;
  117753. }
  117754. }
  117755. return(ret);
  117756. }else{
  117757. return(0);
  117758. }
  117759. }
  117760. #endif
  117761. int res0_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  117762. float **in,int *nonzero,int ch){
  117763. int i,used=0;
  117764. for(i=0;i<ch;i++)
  117765. if(nonzero[i])
  117766. in[used++]=in[i];
  117767. if(used)
  117768. return(_01inverse(vb,vl,in,used,vorbis_book_decodevs_add));
  117769. else
  117770. return(0);
  117771. }
  117772. int res1_forward(oggpack_buffer *opb,vorbis_block *vb,vorbis_look_residue *vl,
  117773. float **in,float **out,int *nonzero,int ch,
  117774. long **partword){
  117775. int i,j,used=0,n=vb->pcmend/2;
  117776. for(i=0;i<ch;i++)
  117777. if(nonzero[i]){
  117778. if(out)
  117779. for(j=0;j<n;j++)
  117780. out[i][j]+=in[i][j];
  117781. in[used++]=in[i];
  117782. }
  117783. if(used){
  117784. int ret=_01forward(opb,vb,vl,in,used,partword,_encodepart);
  117785. if(out){
  117786. used=0;
  117787. for(i=0;i<ch;i++)
  117788. if(nonzero[i]){
  117789. for(j=0;j<n;j++)
  117790. out[i][j]-=in[used][j];
  117791. used++;
  117792. }
  117793. }
  117794. return(ret);
  117795. }else{
  117796. return(0);
  117797. }
  117798. }
  117799. long **res1_class(vorbis_block *vb,vorbis_look_residue *vl,
  117800. float **in,int *nonzero,int ch){
  117801. int i,used=0;
  117802. for(i=0;i<ch;i++)
  117803. if(nonzero[i])
  117804. in[used++]=in[i];
  117805. if(used)
  117806. return(_01class(vb,vl,in,used));
  117807. else
  117808. return(0);
  117809. }
  117810. int res1_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  117811. float **in,int *nonzero,int ch){
  117812. int i,used=0;
  117813. for(i=0;i<ch;i++)
  117814. if(nonzero[i])
  117815. in[used++]=in[i];
  117816. if(used)
  117817. return(_01inverse(vb,vl,in,used,vorbis_book_decodev_add));
  117818. else
  117819. return(0);
  117820. }
  117821. long **res2_class(vorbis_block *vb,vorbis_look_residue *vl,
  117822. float **in,int *nonzero,int ch){
  117823. int i,used=0;
  117824. for(i=0;i<ch;i++)
  117825. if(nonzero[i])used++;
  117826. if(used)
  117827. return(_2class(vb,vl,in,ch));
  117828. else
  117829. return(0);
  117830. }
  117831. /* res2 is slightly more different; all the channels are interleaved
  117832. into a single vector and encoded. */
  117833. int res2_forward(oggpack_buffer *opb,
  117834. vorbis_block *vb,vorbis_look_residue *vl,
  117835. float **in,float **out,int *nonzero,int ch,
  117836. long **partword){
  117837. long i,j,k,n=vb->pcmend/2,used=0;
  117838. /* don't duplicate the code; use a working vector hack for now and
  117839. reshape ourselves into a single channel res1 */
  117840. /* ugly; reallocs for each coupling pass :-( */
  117841. float *work=(float*)_vorbis_block_alloc(vb,ch*n*sizeof(*work));
  117842. for(i=0;i<ch;i++){
  117843. float *pcm=in[i];
  117844. if(nonzero[i])used++;
  117845. for(j=0,k=i;j<n;j++,k+=ch)
  117846. work[k]=pcm[j];
  117847. }
  117848. if(used){
  117849. int ret=_01forward(opb,vb,vl,&work,1,partword,_encodepart);
  117850. /* update the sofar vector */
  117851. if(out){
  117852. for(i=0;i<ch;i++){
  117853. float *pcm=in[i];
  117854. float *sofar=out[i];
  117855. for(j=0,k=i;j<n;j++,k+=ch)
  117856. sofar[j]+=pcm[j]-work[k];
  117857. }
  117858. }
  117859. return(ret);
  117860. }else{
  117861. return(0);
  117862. }
  117863. }
  117864. /* duplicate code here as speed is somewhat more important */
  117865. int res2_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  117866. float **in,int *nonzero,int ch){
  117867. long i,k,l,s;
  117868. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  117869. vorbis_info_residue0 *info=look->info;
  117870. /* move all this setup out later */
  117871. int samples_per_partition=info->grouping;
  117872. int partitions_per_word=look->phrasebook->dim;
  117873. int n=info->end-info->begin;
  117874. int partvals=n/samples_per_partition;
  117875. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  117876. int **partword=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword));
  117877. for(i=0;i<ch;i++)if(nonzero[i])break;
  117878. if(i==ch)return(0); /* no nonzero vectors */
  117879. for(s=0;s<look->stages;s++){
  117880. for(i=0,l=0;i<partvals;l++){
  117881. if(s==0){
  117882. /* fetch the partition word */
  117883. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  117884. if(temp==-1)goto eopbreak;
  117885. partword[l]=look->decodemap[temp];
  117886. if(partword[l]==NULL)goto errout;
  117887. }
  117888. /* now we decode residual values for the partitions */
  117889. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  117890. if(info->secondstages[partword[l][k]]&(1<<s)){
  117891. codebook *stagebook=look->partbooks[partword[l][k]][s];
  117892. if(stagebook){
  117893. if(vorbis_book_decodevv_add(stagebook,in,
  117894. i*samples_per_partition+info->begin,ch,
  117895. &vb->opb,samples_per_partition)==-1)
  117896. goto eopbreak;
  117897. }
  117898. }
  117899. }
  117900. }
  117901. errout:
  117902. eopbreak:
  117903. return(0);
  117904. }
  117905. vorbis_func_residue residue0_exportbundle={
  117906. NULL,
  117907. &res0_unpack,
  117908. &res0_look,
  117909. &res0_free_info,
  117910. &res0_free_look,
  117911. NULL,
  117912. NULL,
  117913. &res0_inverse
  117914. };
  117915. vorbis_func_residue residue1_exportbundle={
  117916. &res0_pack,
  117917. &res0_unpack,
  117918. &res0_look,
  117919. &res0_free_info,
  117920. &res0_free_look,
  117921. &res1_class,
  117922. &res1_forward,
  117923. &res1_inverse
  117924. };
  117925. vorbis_func_residue residue2_exportbundle={
  117926. &res0_pack,
  117927. &res0_unpack,
  117928. &res0_look,
  117929. &res0_free_info,
  117930. &res0_free_look,
  117931. &res2_class,
  117932. &res2_forward,
  117933. &res2_inverse
  117934. };
  117935. #endif
  117936. /*** End of inlined file: res0.c ***/
  117937. /*** Start of inlined file: sharedbook.c ***/
  117938. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  117939. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  117940. // tasks..
  117941. #if JUCE_MSVC
  117942. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  117943. #endif
  117944. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  117945. #if JUCE_USE_OGGVORBIS
  117946. #include <stdlib.h>
  117947. #include <math.h>
  117948. #include <string.h>
  117949. /**** pack/unpack helpers ******************************************/
  117950. int _ilog(unsigned int v){
  117951. int ret=0;
  117952. while(v){
  117953. ret++;
  117954. v>>=1;
  117955. }
  117956. return(ret);
  117957. }
  117958. /* 32 bit float (not IEEE; nonnormalized mantissa +
  117959. biased exponent) : neeeeeee eeemmmmm mmmmmmmm mmmmmmmm
  117960. Why not IEEE? It's just not that important here. */
  117961. #define VQ_FEXP 10
  117962. #define VQ_FMAN 21
  117963. #define VQ_FEXP_BIAS 768 /* bias toward values smaller than 1. */
  117964. /* doesn't currently guard under/overflow */
  117965. long _float32_pack(float val){
  117966. int sign=0;
  117967. long exp;
  117968. long mant;
  117969. if(val<0){
  117970. sign=0x80000000;
  117971. val= -val;
  117972. }
  117973. exp= floor(log(val)/log(2.f));
  117974. mant=rint(ldexp(val,(VQ_FMAN-1)-exp));
  117975. exp=(exp+VQ_FEXP_BIAS)<<VQ_FMAN;
  117976. return(sign|exp|mant);
  117977. }
  117978. float _float32_unpack(long val){
  117979. double mant=val&0x1fffff;
  117980. int sign=val&0x80000000;
  117981. long exp =(val&0x7fe00000L)>>VQ_FMAN;
  117982. if(sign)mant= -mant;
  117983. return(ldexp(mant,exp-(VQ_FMAN-1)-VQ_FEXP_BIAS));
  117984. }
  117985. /* given a list of word lengths, generate a list of codewords. Works
  117986. for length ordered or unordered, always assigns the lowest valued
  117987. codewords first. Extended to handle unused entries (length 0) */
  117988. ogg_uint32_t *_make_words(long *l,long n,long sparsecount){
  117989. long i,j,count=0;
  117990. ogg_uint32_t marker[33];
  117991. ogg_uint32_t *r=(ogg_uint32_t*)_ogg_malloc((sparsecount?sparsecount:n)*sizeof(*r));
  117992. memset(marker,0,sizeof(marker));
  117993. for(i=0;i<n;i++){
  117994. long length=l[i];
  117995. if(length>0){
  117996. ogg_uint32_t entry=marker[length];
  117997. /* when we claim a node for an entry, we also claim the nodes
  117998. below it (pruning off the imagined tree that may have dangled
  117999. from it) as well as blocking the use of any nodes directly
  118000. above for leaves */
  118001. /* update ourself */
  118002. if(length<32 && (entry>>length)){
  118003. /* error condition; the lengths must specify an overpopulated tree */
  118004. _ogg_free(r);
  118005. return(NULL);
  118006. }
  118007. r[count++]=entry;
  118008. /* Look to see if the next shorter marker points to the node
  118009. above. if so, update it and repeat. */
  118010. {
  118011. for(j=length;j>0;j--){
  118012. if(marker[j]&1){
  118013. /* have to jump branches */
  118014. if(j==1)
  118015. marker[1]++;
  118016. else
  118017. marker[j]=marker[j-1]<<1;
  118018. break; /* invariant says next upper marker would already
  118019. have been moved if it was on the same path */
  118020. }
  118021. marker[j]++;
  118022. }
  118023. }
  118024. /* prune the tree; the implicit invariant says all the longer
  118025. markers were dangling from our just-taken node. Dangle them
  118026. from our *new* node. */
  118027. for(j=length+1;j<33;j++)
  118028. if((marker[j]>>1) == entry){
  118029. entry=marker[j];
  118030. marker[j]=marker[j-1]<<1;
  118031. }else
  118032. break;
  118033. }else
  118034. if(sparsecount==0)count++;
  118035. }
  118036. /* bitreverse the words because our bitwise packer/unpacker is LSb
  118037. endian */
  118038. for(i=0,count=0;i<n;i++){
  118039. ogg_uint32_t temp=0;
  118040. for(j=0;j<l[i];j++){
  118041. temp<<=1;
  118042. temp|=(r[count]>>j)&1;
  118043. }
  118044. if(sparsecount){
  118045. if(l[i])
  118046. r[count++]=temp;
  118047. }else
  118048. r[count++]=temp;
  118049. }
  118050. return(r);
  118051. }
  118052. /* there might be a straightforward one-line way to do the below
  118053. that's portable and totally safe against roundoff, but I haven't
  118054. thought of it. Therefore, we opt on the side of caution */
  118055. long _book_maptype1_quantvals(const static_codebook *b){
  118056. long vals=floor(pow((float)b->entries,1.f/b->dim));
  118057. /* the above *should* be reliable, but we'll not assume that FP is
  118058. ever reliable when bitstream sync is at stake; verify via integer
  118059. means that vals really is the greatest value of dim for which
  118060. vals^b->bim <= b->entries */
  118061. /* treat the above as an initial guess */
  118062. while(1){
  118063. long acc=1;
  118064. long acc1=1;
  118065. int i;
  118066. for(i=0;i<b->dim;i++){
  118067. acc*=vals;
  118068. acc1*=vals+1;
  118069. }
  118070. if(acc<=b->entries && acc1>b->entries){
  118071. return(vals);
  118072. }else{
  118073. if(acc>b->entries){
  118074. vals--;
  118075. }else{
  118076. vals++;
  118077. }
  118078. }
  118079. }
  118080. }
  118081. /* unpack the quantized list of values for encode/decode ***********/
  118082. /* we need to deal with two map types: in map type 1, the values are
  118083. generated algorithmically (each column of the vector counts through
  118084. the values in the quant vector). in map type 2, all the values came
  118085. in in an explicit list. Both value lists must be unpacked */
  118086. float *_book_unquantize(const static_codebook *b,int n,int *sparsemap){
  118087. long j,k,count=0;
  118088. if(b->maptype==1 || b->maptype==2){
  118089. int quantvals;
  118090. float mindel=_float32_unpack(b->q_min);
  118091. float delta=_float32_unpack(b->q_delta);
  118092. float *r=(float*)_ogg_calloc(n*b->dim,sizeof(*r));
  118093. /* maptype 1 and 2 both use a quantized value vector, but
  118094. different sizes */
  118095. switch(b->maptype){
  118096. case 1:
  118097. /* most of the time, entries%dimensions == 0, but we need to be
  118098. well defined. We define that the possible vales at each
  118099. scalar is values == entries/dim. If entries%dim != 0, we'll
  118100. have 'too few' values (values*dim<entries), which means that
  118101. we'll have 'left over' entries; left over entries use zeroed
  118102. values (and are wasted). So don't generate codebooks like
  118103. that */
  118104. quantvals=_book_maptype1_quantvals(b);
  118105. for(j=0;j<b->entries;j++){
  118106. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  118107. float last=0.f;
  118108. int indexdiv=1;
  118109. for(k=0;k<b->dim;k++){
  118110. int index= (j/indexdiv)%quantvals;
  118111. float val=b->quantlist[index];
  118112. val=fabs(val)*delta+mindel+last;
  118113. if(b->q_sequencep)last=val;
  118114. if(sparsemap)
  118115. r[sparsemap[count]*b->dim+k]=val;
  118116. else
  118117. r[count*b->dim+k]=val;
  118118. indexdiv*=quantvals;
  118119. }
  118120. count++;
  118121. }
  118122. }
  118123. break;
  118124. case 2:
  118125. for(j=0;j<b->entries;j++){
  118126. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  118127. float last=0.f;
  118128. for(k=0;k<b->dim;k++){
  118129. float val=b->quantlist[j*b->dim+k];
  118130. val=fabs(val)*delta+mindel+last;
  118131. if(b->q_sequencep)last=val;
  118132. if(sparsemap)
  118133. r[sparsemap[count]*b->dim+k]=val;
  118134. else
  118135. r[count*b->dim+k]=val;
  118136. }
  118137. count++;
  118138. }
  118139. }
  118140. break;
  118141. }
  118142. return(r);
  118143. }
  118144. return(NULL);
  118145. }
  118146. void vorbis_staticbook_clear(static_codebook *b){
  118147. if(b->allocedp){
  118148. if(b->quantlist)_ogg_free(b->quantlist);
  118149. if(b->lengthlist)_ogg_free(b->lengthlist);
  118150. if(b->nearest_tree){
  118151. _ogg_free(b->nearest_tree->ptr0);
  118152. _ogg_free(b->nearest_tree->ptr1);
  118153. _ogg_free(b->nearest_tree->p);
  118154. _ogg_free(b->nearest_tree->q);
  118155. memset(b->nearest_tree,0,sizeof(*b->nearest_tree));
  118156. _ogg_free(b->nearest_tree);
  118157. }
  118158. if(b->thresh_tree){
  118159. _ogg_free(b->thresh_tree->quantthresh);
  118160. _ogg_free(b->thresh_tree->quantmap);
  118161. memset(b->thresh_tree,0,sizeof(*b->thresh_tree));
  118162. _ogg_free(b->thresh_tree);
  118163. }
  118164. memset(b,0,sizeof(*b));
  118165. }
  118166. }
  118167. void vorbis_staticbook_destroy(static_codebook *b){
  118168. if(b->allocedp){
  118169. vorbis_staticbook_clear(b);
  118170. _ogg_free(b);
  118171. }
  118172. }
  118173. void vorbis_book_clear(codebook *b){
  118174. /* static book is not cleared; we're likely called on the lookup and
  118175. the static codebook belongs to the info struct */
  118176. if(b->valuelist)_ogg_free(b->valuelist);
  118177. if(b->codelist)_ogg_free(b->codelist);
  118178. if(b->dec_index)_ogg_free(b->dec_index);
  118179. if(b->dec_codelengths)_ogg_free(b->dec_codelengths);
  118180. if(b->dec_firsttable)_ogg_free(b->dec_firsttable);
  118181. memset(b,0,sizeof(*b));
  118182. }
  118183. int vorbis_book_init_encode(codebook *c,const static_codebook *s){
  118184. memset(c,0,sizeof(*c));
  118185. c->c=s;
  118186. c->entries=s->entries;
  118187. c->used_entries=s->entries;
  118188. c->dim=s->dim;
  118189. c->codelist=_make_words(s->lengthlist,s->entries,0);
  118190. c->valuelist=_book_unquantize(s,s->entries,NULL);
  118191. return(0);
  118192. }
  118193. static int sort32a(const void *a,const void *b){
  118194. return ( **(ogg_uint32_t **)a>**(ogg_uint32_t **)b)-
  118195. ( **(ogg_uint32_t **)a<**(ogg_uint32_t **)b);
  118196. }
  118197. /* decode codebook arrangement is more heavily optimized than encode */
  118198. int vorbis_book_init_decode(codebook *c,const static_codebook *s){
  118199. int i,j,n=0,tabn;
  118200. int *sortindex;
  118201. memset(c,0,sizeof(*c));
  118202. /* count actually used entries */
  118203. for(i=0;i<s->entries;i++)
  118204. if(s->lengthlist[i]>0)
  118205. n++;
  118206. c->entries=s->entries;
  118207. c->used_entries=n;
  118208. c->dim=s->dim;
  118209. /* two different remappings go on here.
  118210. First, we collapse the likely sparse codebook down only to
  118211. actually represented values/words. This collapsing needs to be
  118212. indexed as map-valueless books are used to encode original entry
  118213. positions as integers.
  118214. Second, we reorder all vectors, including the entry index above,
  118215. by sorted bitreversed codeword to allow treeless decode. */
  118216. {
  118217. /* perform sort */
  118218. ogg_uint32_t *codes=_make_words(s->lengthlist,s->entries,c->used_entries);
  118219. ogg_uint32_t **codep=(ogg_uint32_t**)alloca(sizeof(*codep)*n);
  118220. if(codes==NULL)goto err_out;
  118221. for(i=0;i<n;i++){
  118222. codes[i]=ogg_bitreverse(codes[i]);
  118223. codep[i]=codes+i;
  118224. }
  118225. qsort(codep,n,sizeof(*codep),sort32a);
  118226. sortindex=(int*)alloca(n*sizeof(*sortindex));
  118227. c->codelist=(ogg_uint32_t*)_ogg_malloc(n*sizeof(*c->codelist));
  118228. /* the index is a reverse index */
  118229. for(i=0;i<n;i++){
  118230. int position=codep[i]-codes;
  118231. sortindex[position]=i;
  118232. }
  118233. for(i=0;i<n;i++)
  118234. c->codelist[sortindex[i]]=codes[i];
  118235. _ogg_free(codes);
  118236. }
  118237. c->valuelist=_book_unquantize(s,n,sortindex);
  118238. c->dec_index=(int*)_ogg_malloc(n*sizeof(*c->dec_index));
  118239. for(n=0,i=0;i<s->entries;i++)
  118240. if(s->lengthlist[i]>0)
  118241. c->dec_index[sortindex[n++]]=i;
  118242. c->dec_codelengths=(char*)_ogg_malloc(n*sizeof(*c->dec_codelengths));
  118243. for(n=0,i=0;i<s->entries;i++)
  118244. if(s->lengthlist[i]>0)
  118245. c->dec_codelengths[sortindex[n++]]=s->lengthlist[i];
  118246. c->dec_firsttablen=_ilog(c->used_entries)-4; /* this is magic */
  118247. if(c->dec_firsttablen<5)c->dec_firsttablen=5;
  118248. if(c->dec_firsttablen>8)c->dec_firsttablen=8;
  118249. tabn=1<<c->dec_firsttablen;
  118250. c->dec_firsttable=(ogg_uint32_t*)_ogg_calloc(tabn,sizeof(*c->dec_firsttable));
  118251. c->dec_maxlength=0;
  118252. for(i=0;i<n;i++){
  118253. if(c->dec_maxlength<c->dec_codelengths[i])
  118254. c->dec_maxlength=c->dec_codelengths[i];
  118255. if(c->dec_codelengths[i]<=c->dec_firsttablen){
  118256. ogg_uint32_t orig=ogg_bitreverse(c->codelist[i]);
  118257. for(j=0;j<(1<<(c->dec_firsttablen-c->dec_codelengths[i]));j++)
  118258. c->dec_firsttable[orig|(j<<c->dec_codelengths[i])]=i+1;
  118259. }
  118260. }
  118261. /* now fill in 'unused' entries in the firsttable with hi/lo search
  118262. hints for the non-direct-hits */
  118263. {
  118264. ogg_uint32_t mask=0xfffffffeUL<<(31-c->dec_firsttablen);
  118265. long lo=0,hi=0;
  118266. for(i=0;i<tabn;i++){
  118267. ogg_uint32_t word=i<<(32-c->dec_firsttablen);
  118268. if(c->dec_firsttable[ogg_bitreverse(word)]==0){
  118269. while((lo+1)<n && c->codelist[lo+1]<=word)lo++;
  118270. while( hi<n && word>=(c->codelist[hi]&mask))hi++;
  118271. /* we only actually have 15 bits per hint to play with here.
  118272. In order to overflow gracefully (nothing breaks, efficiency
  118273. just drops), encode as the difference from the extremes. */
  118274. {
  118275. unsigned long loval=lo;
  118276. unsigned long hival=n-hi;
  118277. if(loval>0x7fff)loval=0x7fff;
  118278. if(hival>0x7fff)hival=0x7fff;
  118279. c->dec_firsttable[ogg_bitreverse(word)]=
  118280. 0x80000000UL | (loval<<15) | hival;
  118281. }
  118282. }
  118283. }
  118284. }
  118285. return(0);
  118286. err_out:
  118287. vorbis_book_clear(c);
  118288. return(-1);
  118289. }
  118290. static float _dist(int el,float *ref, float *b,int step){
  118291. int i;
  118292. float acc=0.f;
  118293. for(i=0;i<el;i++){
  118294. float val=(ref[i]-b[i*step]);
  118295. acc+=val*val;
  118296. }
  118297. return(acc);
  118298. }
  118299. int _best(codebook *book, float *a, int step){
  118300. encode_aux_threshmatch *tt=book->c->thresh_tree;
  118301. #if 0
  118302. encode_aux_nearestmatch *nt=book->c->nearest_tree;
  118303. encode_aux_pigeonhole *pt=book->c->pigeon_tree;
  118304. #endif
  118305. int dim=book->dim;
  118306. int k,o;
  118307. /*int savebest=-1;
  118308. float saverr;*/
  118309. /* do we have a threshhold encode hint? */
  118310. if(tt){
  118311. int index=0,i;
  118312. /* find the quant val of each scalar */
  118313. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  118314. i=tt->threshvals>>1;
  118315. if(a[o]<tt->quantthresh[i]){
  118316. for(;i>0;i--)
  118317. if(a[o]>=tt->quantthresh[i-1])
  118318. break;
  118319. }else{
  118320. for(i++;i<tt->threshvals-1;i++)
  118321. if(a[o]<tt->quantthresh[i])break;
  118322. }
  118323. index=(index*tt->quantvals)+tt->quantmap[i];
  118324. }
  118325. /* regular lattices are easy :-) */
  118326. if(book->c->lengthlist[index]>0) /* is this unused? If so, we'll
  118327. use a decision tree after all
  118328. and fall through*/
  118329. return(index);
  118330. }
  118331. #if 0
  118332. /* do we have a pigeonhole encode hint? */
  118333. if(pt){
  118334. const static_codebook *c=book->c;
  118335. int i,besti=-1;
  118336. float best=0.f;
  118337. int entry=0;
  118338. /* dealing with sequentialness is a pain in the ass */
  118339. if(c->q_sequencep){
  118340. int pv;
  118341. long mul=1;
  118342. float qlast=0;
  118343. for(k=0,o=0;k<dim;k++,o+=step){
  118344. pv=(int)((a[o]-qlast-pt->min)/pt->del);
  118345. if(pv<0 || pv>=pt->mapentries)break;
  118346. entry+=pt->pigeonmap[pv]*mul;
  118347. mul*=pt->quantvals;
  118348. qlast+=pv*pt->del+pt->min;
  118349. }
  118350. }else{
  118351. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  118352. int pv=(int)((a[o]-pt->min)/pt->del);
  118353. if(pv<0 || pv>=pt->mapentries)break;
  118354. entry=entry*pt->quantvals+pt->pigeonmap[pv];
  118355. }
  118356. }
  118357. /* must be within the pigeonholable range; if we quant outside (or
  118358. in an entry that we define no list for), brute force it */
  118359. if(k==dim && pt->fitlength[entry]){
  118360. /* search the abbreviated list */
  118361. long *list=pt->fitlist+pt->fitmap[entry];
  118362. for(i=0;i<pt->fitlength[entry];i++){
  118363. float this=_dist(dim,book->valuelist+list[i]*dim,a,step);
  118364. if(besti==-1 || this<best){
  118365. best=this;
  118366. besti=list[i];
  118367. }
  118368. }
  118369. return(besti);
  118370. }
  118371. }
  118372. if(nt){
  118373. /* optimized using the decision tree */
  118374. while(1){
  118375. float c=0.f;
  118376. float *p=book->valuelist+nt->p[ptr];
  118377. float *q=book->valuelist+nt->q[ptr];
  118378. for(k=0,o=0;k<dim;k++,o+=step)
  118379. c+=(p[k]-q[k])*(a[o]-(p[k]+q[k])*.5);
  118380. if(c>0.f) /* in A */
  118381. ptr= -nt->ptr0[ptr];
  118382. else /* in B */
  118383. ptr= -nt->ptr1[ptr];
  118384. if(ptr<=0)break;
  118385. }
  118386. return(-ptr);
  118387. }
  118388. #endif
  118389. /* brute force it! */
  118390. {
  118391. const static_codebook *c=book->c;
  118392. int i,besti=-1;
  118393. float best=0.f;
  118394. float *e=book->valuelist;
  118395. for(i=0;i<book->entries;i++){
  118396. if(c->lengthlist[i]>0){
  118397. float thisx=_dist(dim,e,a,step);
  118398. if(besti==-1 || thisx<best){
  118399. best=thisx;
  118400. besti=i;
  118401. }
  118402. }
  118403. e+=dim;
  118404. }
  118405. /*if(savebest!=-1 && savebest!=besti){
  118406. fprintf(stderr,"brute force/pigeonhole disagreement:\n"
  118407. "original:");
  118408. for(i=0;i<dim*step;i+=step)fprintf(stderr,"%g,",a[i]);
  118409. fprintf(stderr,"\n"
  118410. "pigeonhole (entry %d, err %g):",savebest,saverr);
  118411. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  118412. (book->valuelist+savebest*dim)[i]);
  118413. fprintf(stderr,"\n"
  118414. "bruteforce (entry %d, err %g):",besti,best);
  118415. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  118416. (book->valuelist+besti*dim)[i]);
  118417. fprintf(stderr,"\n");
  118418. }*/
  118419. return(besti);
  118420. }
  118421. }
  118422. long vorbis_book_codeword(codebook *book,int entry){
  118423. if(book->c) /* only use with encode; decode optimizations are
  118424. allowed to break this */
  118425. return book->codelist[entry];
  118426. return -1;
  118427. }
  118428. long vorbis_book_codelen(codebook *book,int entry){
  118429. if(book->c) /* only use with encode; decode optimizations are
  118430. allowed to break this */
  118431. return book->c->lengthlist[entry];
  118432. return -1;
  118433. }
  118434. #ifdef _V_SELFTEST
  118435. /* Unit tests of the dequantizer; this stuff will be OK
  118436. cross-platform, I simply want to be sure that special mapping cases
  118437. actually work properly; a bug could go unnoticed for a while */
  118438. #include <stdio.h>
  118439. /* cases:
  118440. no mapping
  118441. full, explicit mapping
  118442. algorithmic mapping
  118443. nonsequential
  118444. sequential
  118445. */
  118446. static long full_quantlist1[]={0,1,2,3, 4,5,6,7, 8,3,6,1};
  118447. static long partial_quantlist1[]={0,7,2};
  118448. /* no mapping */
  118449. static_codebook test1={
  118450. 4,16,
  118451. NULL,
  118452. 0,
  118453. 0,0,0,0,
  118454. NULL,
  118455. NULL,NULL
  118456. };
  118457. static float *test1_result=NULL;
  118458. /* linear, full mapping, nonsequential */
  118459. static_codebook test2={
  118460. 4,3,
  118461. NULL,
  118462. 2,
  118463. -533200896,1611661312,4,0,
  118464. full_quantlist1,
  118465. NULL,NULL
  118466. };
  118467. static float test2_result[]={-3,-2,-1,0, 1,2,3,4, 5,0,3,-2};
  118468. /* linear, full mapping, sequential */
  118469. static_codebook test3={
  118470. 4,3,
  118471. NULL,
  118472. 2,
  118473. -533200896,1611661312,4,1,
  118474. full_quantlist1,
  118475. NULL,NULL
  118476. };
  118477. static float test3_result[]={-3,-5,-6,-6, 1,3,6,10, 5,5,8,6};
  118478. /* linear, algorithmic mapping, nonsequential */
  118479. static_codebook test4={
  118480. 3,27,
  118481. NULL,
  118482. 1,
  118483. -533200896,1611661312,4,0,
  118484. partial_quantlist1,
  118485. NULL,NULL
  118486. };
  118487. static float test4_result[]={-3,-3,-3, 4,-3,-3, -1,-3,-3,
  118488. -3, 4,-3, 4, 4,-3, -1, 4,-3,
  118489. -3,-1,-3, 4,-1,-3, -1,-1,-3,
  118490. -3,-3, 4, 4,-3, 4, -1,-3, 4,
  118491. -3, 4, 4, 4, 4, 4, -1, 4, 4,
  118492. -3,-1, 4, 4,-1, 4, -1,-1, 4,
  118493. -3,-3,-1, 4,-3,-1, -1,-3,-1,
  118494. -3, 4,-1, 4, 4,-1, -1, 4,-1,
  118495. -3,-1,-1, 4,-1,-1, -1,-1,-1};
  118496. /* linear, algorithmic mapping, sequential */
  118497. static_codebook test5={
  118498. 3,27,
  118499. NULL,
  118500. 1,
  118501. -533200896,1611661312,4,1,
  118502. partial_quantlist1,
  118503. NULL,NULL
  118504. };
  118505. static float test5_result[]={-3,-6,-9, 4, 1,-2, -1,-4,-7,
  118506. -3, 1,-2, 4, 8, 5, -1, 3, 0,
  118507. -3,-4,-7, 4, 3, 0, -1,-2,-5,
  118508. -3,-6,-2, 4, 1, 5, -1,-4, 0,
  118509. -3, 1, 5, 4, 8,12, -1, 3, 7,
  118510. -3,-4, 0, 4, 3, 7, -1,-2, 2,
  118511. -3,-6,-7, 4, 1, 0, -1,-4,-5,
  118512. -3, 1, 0, 4, 8, 7, -1, 3, 2,
  118513. -3,-4,-5, 4, 3, 2, -1,-2,-3};
  118514. void run_test(static_codebook *b,float *comp){
  118515. float *out=_book_unquantize(b,b->entries,NULL);
  118516. int i;
  118517. if(comp){
  118518. if(!out){
  118519. fprintf(stderr,"_book_unquantize incorrectly returned NULL\n");
  118520. exit(1);
  118521. }
  118522. for(i=0;i<b->entries*b->dim;i++)
  118523. if(fabs(out[i]-comp[i])>.0001){
  118524. fprintf(stderr,"disagreement in unquantized and reference data:\n"
  118525. "position %d, %g != %g\n",i,out[i],comp[i]);
  118526. exit(1);
  118527. }
  118528. }else{
  118529. if(out){
  118530. fprintf(stderr,"_book_unquantize returned a value array: \n"
  118531. " correct result should have been NULL\n");
  118532. exit(1);
  118533. }
  118534. }
  118535. }
  118536. int main(){
  118537. /* run the nine dequant tests, and compare to the hand-rolled results */
  118538. fprintf(stderr,"Dequant test 1... ");
  118539. run_test(&test1,test1_result);
  118540. fprintf(stderr,"OK\nDequant test 2... ");
  118541. run_test(&test2,test2_result);
  118542. fprintf(stderr,"OK\nDequant test 3... ");
  118543. run_test(&test3,test3_result);
  118544. fprintf(stderr,"OK\nDequant test 4... ");
  118545. run_test(&test4,test4_result);
  118546. fprintf(stderr,"OK\nDequant test 5... ");
  118547. run_test(&test5,test5_result);
  118548. fprintf(stderr,"OK\n\n");
  118549. return(0);
  118550. }
  118551. #endif
  118552. #endif
  118553. /*** End of inlined file: sharedbook.c ***/
  118554. /*** Start of inlined file: smallft.c ***/
  118555. /* FFT implementation from OggSquish, minus cosine transforms,
  118556. * minus all but radix 2/4 case. In Vorbis we only need this
  118557. * cut-down version.
  118558. *
  118559. * To do more than just power-of-two sized vectors, see the full
  118560. * version I wrote for NetLib.
  118561. *
  118562. * Note that the packing is a little strange; rather than the FFT r/i
  118563. * packing following R_0, I_n, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1,
  118564. * it follows R_0, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1, I_n like the
  118565. * FORTRAN version
  118566. */
  118567. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  118568. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118569. // tasks..
  118570. #if JUCE_MSVC
  118571. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118572. #endif
  118573. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118574. #if JUCE_USE_OGGVORBIS
  118575. #include <stdlib.h>
  118576. #include <string.h>
  118577. #include <math.h>
  118578. static void drfti1(int n, float *wa, int *ifac){
  118579. static int ntryh[4] = { 4,2,3,5 };
  118580. static float tpi = 6.28318530717958648f;
  118581. float arg,argh,argld,fi;
  118582. int ntry=0,i,j=-1;
  118583. int k1, l1, l2, ib;
  118584. int ld, ii, ip, is, nq, nr;
  118585. int ido, ipm, nfm1;
  118586. int nl=n;
  118587. int nf=0;
  118588. L101:
  118589. j++;
  118590. if (j < 4)
  118591. ntry=ntryh[j];
  118592. else
  118593. ntry+=2;
  118594. L104:
  118595. nq=nl/ntry;
  118596. nr=nl-ntry*nq;
  118597. if (nr!=0) goto L101;
  118598. nf++;
  118599. ifac[nf+1]=ntry;
  118600. nl=nq;
  118601. if(ntry!=2)goto L107;
  118602. if(nf==1)goto L107;
  118603. for (i=1;i<nf;i++){
  118604. ib=nf-i+1;
  118605. ifac[ib+1]=ifac[ib];
  118606. }
  118607. ifac[2] = 2;
  118608. L107:
  118609. if(nl!=1)goto L104;
  118610. ifac[0]=n;
  118611. ifac[1]=nf;
  118612. argh=tpi/n;
  118613. is=0;
  118614. nfm1=nf-1;
  118615. l1=1;
  118616. if(nfm1==0)return;
  118617. for (k1=0;k1<nfm1;k1++){
  118618. ip=ifac[k1+2];
  118619. ld=0;
  118620. l2=l1*ip;
  118621. ido=n/l2;
  118622. ipm=ip-1;
  118623. for (j=0;j<ipm;j++){
  118624. ld+=l1;
  118625. i=is;
  118626. argld=(float)ld*argh;
  118627. fi=0.f;
  118628. for (ii=2;ii<ido;ii+=2){
  118629. fi+=1.f;
  118630. arg=fi*argld;
  118631. wa[i++]=cos(arg);
  118632. wa[i++]=sin(arg);
  118633. }
  118634. is+=ido;
  118635. }
  118636. l1=l2;
  118637. }
  118638. }
  118639. static void fdrffti(int n, float *wsave, int *ifac){
  118640. if (n == 1) return;
  118641. drfti1(n, wsave+n, ifac);
  118642. }
  118643. static void dradf2(int ido,int l1,float *cc,float *ch,float *wa1){
  118644. int i,k;
  118645. float ti2,tr2;
  118646. int t0,t1,t2,t3,t4,t5,t6;
  118647. t1=0;
  118648. t0=(t2=l1*ido);
  118649. t3=ido<<1;
  118650. for(k=0;k<l1;k++){
  118651. ch[t1<<1]=cc[t1]+cc[t2];
  118652. ch[(t1<<1)+t3-1]=cc[t1]-cc[t2];
  118653. t1+=ido;
  118654. t2+=ido;
  118655. }
  118656. if(ido<2)return;
  118657. if(ido==2)goto L105;
  118658. t1=0;
  118659. t2=t0;
  118660. for(k=0;k<l1;k++){
  118661. t3=t2;
  118662. t4=(t1<<1)+(ido<<1);
  118663. t5=t1;
  118664. t6=t1+t1;
  118665. for(i=2;i<ido;i+=2){
  118666. t3+=2;
  118667. t4-=2;
  118668. t5+=2;
  118669. t6+=2;
  118670. tr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  118671. ti2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  118672. ch[t6]=cc[t5]+ti2;
  118673. ch[t4]=ti2-cc[t5];
  118674. ch[t6-1]=cc[t5-1]+tr2;
  118675. ch[t4-1]=cc[t5-1]-tr2;
  118676. }
  118677. t1+=ido;
  118678. t2+=ido;
  118679. }
  118680. if(ido%2==1)return;
  118681. L105:
  118682. t3=(t2=(t1=ido)-1);
  118683. t2+=t0;
  118684. for(k=0;k<l1;k++){
  118685. ch[t1]=-cc[t2];
  118686. ch[t1-1]=cc[t3];
  118687. t1+=ido<<1;
  118688. t2+=ido;
  118689. t3+=ido;
  118690. }
  118691. }
  118692. static void dradf4(int ido,int l1,float *cc,float *ch,float *wa1,
  118693. float *wa2,float *wa3){
  118694. static float hsqt2 = .70710678118654752f;
  118695. int i,k,t0,t1,t2,t3,t4,t5,t6;
  118696. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  118697. t0=l1*ido;
  118698. t1=t0;
  118699. t4=t1<<1;
  118700. t2=t1+(t1<<1);
  118701. t3=0;
  118702. for(k=0;k<l1;k++){
  118703. tr1=cc[t1]+cc[t2];
  118704. tr2=cc[t3]+cc[t4];
  118705. ch[t5=t3<<2]=tr1+tr2;
  118706. ch[(ido<<2)+t5-1]=tr2-tr1;
  118707. ch[(t5+=(ido<<1))-1]=cc[t3]-cc[t4];
  118708. ch[t5]=cc[t2]-cc[t1];
  118709. t1+=ido;
  118710. t2+=ido;
  118711. t3+=ido;
  118712. t4+=ido;
  118713. }
  118714. if(ido<2)return;
  118715. if(ido==2)goto L105;
  118716. t1=0;
  118717. for(k=0;k<l1;k++){
  118718. t2=t1;
  118719. t4=t1<<2;
  118720. t5=(t6=ido<<1)+t4;
  118721. for(i=2;i<ido;i+=2){
  118722. t3=(t2+=2);
  118723. t4+=2;
  118724. t5-=2;
  118725. t3+=t0;
  118726. cr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  118727. ci2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  118728. t3+=t0;
  118729. cr3=wa2[i-2]*cc[t3-1]+wa2[i-1]*cc[t3];
  118730. ci3=wa2[i-2]*cc[t3]-wa2[i-1]*cc[t3-1];
  118731. t3+=t0;
  118732. cr4=wa3[i-2]*cc[t3-1]+wa3[i-1]*cc[t3];
  118733. ci4=wa3[i-2]*cc[t3]-wa3[i-1]*cc[t3-1];
  118734. tr1=cr2+cr4;
  118735. tr4=cr4-cr2;
  118736. ti1=ci2+ci4;
  118737. ti4=ci2-ci4;
  118738. ti2=cc[t2]+ci3;
  118739. ti3=cc[t2]-ci3;
  118740. tr2=cc[t2-1]+cr3;
  118741. tr3=cc[t2-1]-cr3;
  118742. ch[t4-1]=tr1+tr2;
  118743. ch[t4]=ti1+ti2;
  118744. ch[t5-1]=tr3-ti4;
  118745. ch[t5]=tr4-ti3;
  118746. ch[t4+t6-1]=ti4+tr3;
  118747. ch[t4+t6]=tr4+ti3;
  118748. ch[t5+t6-1]=tr2-tr1;
  118749. ch[t5+t6]=ti1-ti2;
  118750. }
  118751. t1+=ido;
  118752. }
  118753. if(ido&1)return;
  118754. L105:
  118755. t2=(t1=t0+ido-1)+(t0<<1);
  118756. t3=ido<<2;
  118757. t4=ido;
  118758. t5=ido<<1;
  118759. t6=ido;
  118760. for(k=0;k<l1;k++){
  118761. ti1=-hsqt2*(cc[t1]+cc[t2]);
  118762. tr1=hsqt2*(cc[t1]-cc[t2]);
  118763. ch[t4-1]=tr1+cc[t6-1];
  118764. ch[t4+t5-1]=cc[t6-1]-tr1;
  118765. ch[t4]=ti1-cc[t1+t0];
  118766. ch[t4+t5]=ti1+cc[t1+t0];
  118767. t1+=ido;
  118768. t2+=ido;
  118769. t4+=t3;
  118770. t6+=ido;
  118771. }
  118772. }
  118773. static void dradfg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  118774. float *c2,float *ch,float *ch2,float *wa){
  118775. static float tpi=6.283185307179586f;
  118776. int idij,ipph,i,j,k,l,ic,ik,is;
  118777. int t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  118778. float dc2,ai1,ai2,ar1,ar2,ds2;
  118779. int nbd;
  118780. float dcp,arg,dsp,ar1h,ar2h;
  118781. int idp2,ipp2;
  118782. arg=tpi/(float)ip;
  118783. dcp=cos(arg);
  118784. dsp=sin(arg);
  118785. ipph=(ip+1)>>1;
  118786. ipp2=ip;
  118787. idp2=ido;
  118788. nbd=(ido-1)>>1;
  118789. t0=l1*ido;
  118790. t10=ip*ido;
  118791. if(ido==1)goto L119;
  118792. for(ik=0;ik<idl1;ik++)ch2[ik]=c2[ik];
  118793. t1=0;
  118794. for(j=1;j<ip;j++){
  118795. t1+=t0;
  118796. t2=t1;
  118797. for(k=0;k<l1;k++){
  118798. ch[t2]=c1[t2];
  118799. t2+=ido;
  118800. }
  118801. }
  118802. is=-ido;
  118803. t1=0;
  118804. if(nbd>l1){
  118805. for(j=1;j<ip;j++){
  118806. t1+=t0;
  118807. is+=ido;
  118808. t2= -ido+t1;
  118809. for(k=0;k<l1;k++){
  118810. idij=is-1;
  118811. t2+=ido;
  118812. t3=t2;
  118813. for(i=2;i<ido;i+=2){
  118814. idij+=2;
  118815. t3+=2;
  118816. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  118817. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  118818. }
  118819. }
  118820. }
  118821. }else{
  118822. for(j=1;j<ip;j++){
  118823. is+=ido;
  118824. idij=is-1;
  118825. t1+=t0;
  118826. t2=t1;
  118827. for(i=2;i<ido;i+=2){
  118828. idij+=2;
  118829. t2+=2;
  118830. t3=t2;
  118831. for(k=0;k<l1;k++){
  118832. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  118833. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  118834. t3+=ido;
  118835. }
  118836. }
  118837. }
  118838. }
  118839. t1=0;
  118840. t2=ipp2*t0;
  118841. if(nbd<l1){
  118842. for(j=1;j<ipph;j++){
  118843. t1+=t0;
  118844. t2-=t0;
  118845. t3=t1;
  118846. t4=t2;
  118847. for(i=2;i<ido;i+=2){
  118848. t3+=2;
  118849. t4+=2;
  118850. t5=t3-ido;
  118851. t6=t4-ido;
  118852. for(k=0;k<l1;k++){
  118853. t5+=ido;
  118854. t6+=ido;
  118855. c1[t5-1]=ch[t5-1]+ch[t6-1];
  118856. c1[t6-1]=ch[t5]-ch[t6];
  118857. c1[t5]=ch[t5]+ch[t6];
  118858. c1[t6]=ch[t6-1]-ch[t5-1];
  118859. }
  118860. }
  118861. }
  118862. }else{
  118863. for(j=1;j<ipph;j++){
  118864. t1+=t0;
  118865. t2-=t0;
  118866. t3=t1;
  118867. t4=t2;
  118868. for(k=0;k<l1;k++){
  118869. t5=t3;
  118870. t6=t4;
  118871. for(i=2;i<ido;i+=2){
  118872. t5+=2;
  118873. t6+=2;
  118874. c1[t5-1]=ch[t5-1]+ch[t6-1];
  118875. c1[t6-1]=ch[t5]-ch[t6];
  118876. c1[t5]=ch[t5]+ch[t6];
  118877. c1[t6]=ch[t6-1]-ch[t5-1];
  118878. }
  118879. t3+=ido;
  118880. t4+=ido;
  118881. }
  118882. }
  118883. }
  118884. L119:
  118885. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  118886. t1=0;
  118887. t2=ipp2*idl1;
  118888. for(j=1;j<ipph;j++){
  118889. t1+=t0;
  118890. t2-=t0;
  118891. t3=t1-ido;
  118892. t4=t2-ido;
  118893. for(k=0;k<l1;k++){
  118894. t3+=ido;
  118895. t4+=ido;
  118896. c1[t3]=ch[t3]+ch[t4];
  118897. c1[t4]=ch[t4]-ch[t3];
  118898. }
  118899. }
  118900. ar1=1.f;
  118901. ai1=0.f;
  118902. t1=0;
  118903. t2=ipp2*idl1;
  118904. t3=(ip-1)*idl1;
  118905. for(l=1;l<ipph;l++){
  118906. t1+=idl1;
  118907. t2-=idl1;
  118908. ar1h=dcp*ar1-dsp*ai1;
  118909. ai1=dcp*ai1+dsp*ar1;
  118910. ar1=ar1h;
  118911. t4=t1;
  118912. t5=t2;
  118913. t6=t3;
  118914. t7=idl1;
  118915. for(ik=0;ik<idl1;ik++){
  118916. ch2[t4++]=c2[ik]+ar1*c2[t7++];
  118917. ch2[t5++]=ai1*c2[t6++];
  118918. }
  118919. dc2=ar1;
  118920. ds2=ai1;
  118921. ar2=ar1;
  118922. ai2=ai1;
  118923. t4=idl1;
  118924. t5=(ipp2-1)*idl1;
  118925. for(j=2;j<ipph;j++){
  118926. t4+=idl1;
  118927. t5-=idl1;
  118928. ar2h=dc2*ar2-ds2*ai2;
  118929. ai2=dc2*ai2+ds2*ar2;
  118930. ar2=ar2h;
  118931. t6=t1;
  118932. t7=t2;
  118933. t8=t4;
  118934. t9=t5;
  118935. for(ik=0;ik<idl1;ik++){
  118936. ch2[t6++]+=ar2*c2[t8++];
  118937. ch2[t7++]+=ai2*c2[t9++];
  118938. }
  118939. }
  118940. }
  118941. t1=0;
  118942. for(j=1;j<ipph;j++){
  118943. t1+=idl1;
  118944. t2=t1;
  118945. for(ik=0;ik<idl1;ik++)ch2[ik]+=c2[t2++];
  118946. }
  118947. if(ido<l1)goto L132;
  118948. t1=0;
  118949. t2=0;
  118950. for(k=0;k<l1;k++){
  118951. t3=t1;
  118952. t4=t2;
  118953. for(i=0;i<ido;i++)cc[t4++]=ch[t3++];
  118954. t1+=ido;
  118955. t2+=t10;
  118956. }
  118957. goto L135;
  118958. L132:
  118959. for(i=0;i<ido;i++){
  118960. t1=i;
  118961. t2=i;
  118962. for(k=0;k<l1;k++){
  118963. cc[t2]=ch[t1];
  118964. t1+=ido;
  118965. t2+=t10;
  118966. }
  118967. }
  118968. L135:
  118969. t1=0;
  118970. t2=ido<<1;
  118971. t3=0;
  118972. t4=ipp2*t0;
  118973. for(j=1;j<ipph;j++){
  118974. t1+=t2;
  118975. t3+=t0;
  118976. t4-=t0;
  118977. t5=t1;
  118978. t6=t3;
  118979. t7=t4;
  118980. for(k=0;k<l1;k++){
  118981. cc[t5-1]=ch[t6];
  118982. cc[t5]=ch[t7];
  118983. t5+=t10;
  118984. t6+=ido;
  118985. t7+=ido;
  118986. }
  118987. }
  118988. if(ido==1)return;
  118989. if(nbd<l1)goto L141;
  118990. t1=-ido;
  118991. t3=0;
  118992. t4=0;
  118993. t5=ipp2*t0;
  118994. for(j=1;j<ipph;j++){
  118995. t1+=t2;
  118996. t3+=t2;
  118997. t4+=t0;
  118998. t5-=t0;
  118999. t6=t1;
  119000. t7=t3;
  119001. t8=t4;
  119002. t9=t5;
  119003. for(k=0;k<l1;k++){
  119004. for(i=2;i<ido;i+=2){
  119005. ic=idp2-i;
  119006. cc[i+t7-1]=ch[i+t8-1]+ch[i+t9-1];
  119007. cc[ic+t6-1]=ch[i+t8-1]-ch[i+t9-1];
  119008. cc[i+t7]=ch[i+t8]+ch[i+t9];
  119009. cc[ic+t6]=ch[i+t9]-ch[i+t8];
  119010. }
  119011. t6+=t10;
  119012. t7+=t10;
  119013. t8+=ido;
  119014. t9+=ido;
  119015. }
  119016. }
  119017. return;
  119018. L141:
  119019. t1=-ido;
  119020. t3=0;
  119021. t4=0;
  119022. t5=ipp2*t0;
  119023. for(j=1;j<ipph;j++){
  119024. t1+=t2;
  119025. t3+=t2;
  119026. t4+=t0;
  119027. t5-=t0;
  119028. for(i=2;i<ido;i+=2){
  119029. t6=idp2+t1-i;
  119030. t7=i+t3;
  119031. t8=i+t4;
  119032. t9=i+t5;
  119033. for(k=0;k<l1;k++){
  119034. cc[t7-1]=ch[t8-1]+ch[t9-1];
  119035. cc[t6-1]=ch[t8-1]-ch[t9-1];
  119036. cc[t7]=ch[t8]+ch[t9];
  119037. cc[t6]=ch[t9]-ch[t8];
  119038. t6+=t10;
  119039. t7+=t10;
  119040. t8+=ido;
  119041. t9+=ido;
  119042. }
  119043. }
  119044. }
  119045. }
  119046. static void drftf1(int n,float *c,float *ch,float *wa,int *ifac){
  119047. int i,k1,l1,l2;
  119048. int na,kh,nf;
  119049. int ip,iw,ido,idl1,ix2,ix3;
  119050. nf=ifac[1];
  119051. na=1;
  119052. l2=n;
  119053. iw=n;
  119054. for(k1=0;k1<nf;k1++){
  119055. kh=nf-k1;
  119056. ip=ifac[kh+1];
  119057. l1=l2/ip;
  119058. ido=n/l2;
  119059. idl1=ido*l1;
  119060. iw-=(ip-1)*ido;
  119061. na=1-na;
  119062. if(ip!=4)goto L102;
  119063. ix2=iw+ido;
  119064. ix3=ix2+ido;
  119065. if(na!=0)
  119066. dradf4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  119067. else
  119068. dradf4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  119069. goto L110;
  119070. L102:
  119071. if(ip!=2)goto L104;
  119072. if(na!=0)goto L103;
  119073. dradf2(ido,l1,c,ch,wa+iw-1);
  119074. goto L110;
  119075. L103:
  119076. dradf2(ido,l1,ch,c,wa+iw-1);
  119077. goto L110;
  119078. L104:
  119079. if(ido==1)na=1-na;
  119080. if(na!=0)goto L109;
  119081. dradfg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  119082. na=1;
  119083. goto L110;
  119084. L109:
  119085. dradfg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  119086. na=0;
  119087. L110:
  119088. l2=l1;
  119089. }
  119090. if(na==1)return;
  119091. for(i=0;i<n;i++)c[i]=ch[i];
  119092. }
  119093. static void dradb2(int ido,int l1,float *cc,float *ch,float *wa1){
  119094. int i,k,t0,t1,t2,t3,t4,t5,t6;
  119095. float ti2,tr2;
  119096. t0=l1*ido;
  119097. t1=0;
  119098. t2=0;
  119099. t3=(ido<<1)-1;
  119100. for(k=0;k<l1;k++){
  119101. ch[t1]=cc[t2]+cc[t3+t2];
  119102. ch[t1+t0]=cc[t2]-cc[t3+t2];
  119103. t2=(t1+=ido)<<1;
  119104. }
  119105. if(ido<2)return;
  119106. if(ido==2)goto L105;
  119107. t1=0;
  119108. t2=0;
  119109. for(k=0;k<l1;k++){
  119110. t3=t1;
  119111. t5=(t4=t2)+(ido<<1);
  119112. t6=t0+t1;
  119113. for(i=2;i<ido;i+=2){
  119114. t3+=2;
  119115. t4+=2;
  119116. t5-=2;
  119117. t6+=2;
  119118. ch[t3-1]=cc[t4-1]+cc[t5-1];
  119119. tr2=cc[t4-1]-cc[t5-1];
  119120. ch[t3]=cc[t4]-cc[t5];
  119121. ti2=cc[t4]+cc[t5];
  119122. ch[t6-1]=wa1[i-2]*tr2-wa1[i-1]*ti2;
  119123. ch[t6]=wa1[i-2]*ti2+wa1[i-1]*tr2;
  119124. }
  119125. t2=(t1+=ido)<<1;
  119126. }
  119127. if(ido%2==1)return;
  119128. L105:
  119129. t1=ido-1;
  119130. t2=ido-1;
  119131. for(k=0;k<l1;k++){
  119132. ch[t1]=cc[t2]+cc[t2];
  119133. ch[t1+t0]=-(cc[t2+1]+cc[t2+1]);
  119134. t1+=ido;
  119135. t2+=ido<<1;
  119136. }
  119137. }
  119138. static void dradb3(int ido,int l1,float *cc,float *ch,float *wa1,
  119139. float *wa2){
  119140. static float taur = -.5f;
  119141. static float taui = .8660254037844386f;
  119142. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  119143. float ci2,ci3,di2,di3,cr2,cr3,dr2,dr3,ti2,tr2;
  119144. t0=l1*ido;
  119145. t1=0;
  119146. t2=t0<<1;
  119147. t3=ido<<1;
  119148. t4=ido+(ido<<1);
  119149. t5=0;
  119150. for(k=0;k<l1;k++){
  119151. tr2=cc[t3-1]+cc[t3-1];
  119152. cr2=cc[t5]+(taur*tr2);
  119153. ch[t1]=cc[t5]+tr2;
  119154. ci3=taui*(cc[t3]+cc[t3]);
  119155. ch[t1+t0]=cr2-ci3;
  119156. ch[t1+t2]=cr2+ci3;
  119157. t1+=ido;
  119158. t3+=t4;
  119159. t5+=t4;
  119160. }
  119161. if(ido==1)return;
  119162. t1=0;
  119163. t3=ido<<1;
  119164. for(k=0;k<l1;k++){
  119165. t7=t1+(t1<<1);
  119166. t6=(t5=t7+t3);
  119167. t8=t1;
  119168. t10=(t9=t1+t0)+t0;
  119169. for(i=2;i<ido;i+=2){
  119170. t5+=2;
  119171. t6-=2;
  119172. t7+=2;
  119173. t8+=2;
  119174. t9+=2;
  119175. t10+=2;
  119176. tr2=cc[t5-1]+cc[t6-1];
  119177. cr2=cc[t7-1]+(taur*tr2);
  119178. ch[t8-1]=cc[t7-1]+tr2;
  119179. ti2=cc[t5]-cc[t6];
  119180. ci2=cc[t7]+(taur*ti2);
  119181. ch[t8]=cc[t7]+ti2;
  119182. cr3=taui*(cc[t5-1]-cc[t6-1]);
  119183. ci3=taui*(cc[t5]+cc[t6]);
  119184. dr2=cr2-ci3;
  119185. dr3=cr2+ci3;
  119186. di2=ci2+cr3;
  119187. di3=ci2-cr3;
  119188. ch[t9-1]=wa1[i-2]*dr2-wa1[i-1]*di2;
  119189. ch[t9]=wa1[i-2]*di2+wa1[i-1]*dr2;
  119190. ch[t10-1]=wa2[i-2]*dr3-wa2[i-1]*di3;
  119191. ch[t10]=wa2[i-2]*di3+wa2[i-1]*dr3;
  119192. }
  119193. t1+=ido;
  119194. }
  119195. }
  119196. static void dradb4(int ido,int l1,float *cc,float *ch,float *wa1,
  119197. float *wa2,float *wa3){
  119198. static float sqrt2=1.414213562373095f;
  119199. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8;
  119200. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  119201. t0=l1*ido;
  119202. t1=0;
  119203. t2=ido<<2;
  119204. t3=0;
  119205. t6=ido<<1;
  119206. for(k=0;k<l1;k++){
  119207. t4=t3+t6;
  119208. t5=t1;
  119209. tr3=cc[t4-1]+cc[t4-1];
  119210. tr4=cc[t4]+cc[t4];
  119211. tr1=cc[t3]-cc[(t4+=t6)-1];
  119212. tr2=cc[t3]+cc[t4-1];
  119213. ch[t5]=tr2+tr3;
  119214. ch[t5+=t0]=tr1-tr4;
  119215. ch[t5+=t0]=tr2-tr3;
  119216. ch[t5+=t0]=tr1+tr4;
  119217. t1+=ido;
  119218. t3+=t2;
  119219. }
  119220. if(ido<2)return;
  119221. if(ido==2)goto L105;
  119222. t1=0;
  119223. for(k=0;k<l1;k++){
  119224. t5=(t4=(t3=(t2=t1<<2)+t6))+t6;
  119225. t7=t1;
  119226. for(i=2;i<ido;i+=2){
  119227. t2+=2;
  119228. t3+=2;
  119229. t4-=2;
  119230. t5-=2;
  119231. t7+=2;
  119232. ti1=cc[t2]+cc[t5];
  119233. ti2=cc[t2]-cc[t5];
  119234. ti3=cc[t3]-cc[t4];
  119235. tr4=cc[t3]+cc[t4];
  119236. tr1=cc[t2-1]-cc[t5-1];
  119237. tr2=cc[t2-1]+cc[t5-1];
  119238. ti4=cc[t3-1]-cc[t4-1];
  119239. tr3=cc[t3-1]+cc[t4-1];
  119240. ch[t7-1]=tr2+tr3;
  119241. cr3=tr2-tr3;
  119242. ch[t7]=ti2+ti3;
  119243. ci3=ti2-ti3;
  119244. cr2=tr1-tr4;
  119245. cr4=tr1+tr4;
  119246. ci2=ti1+ti4;
  119247. ci4=ti1-ti4;
  119248. ch[(t8=t7+t0)-1]=wa1[i-2]*cr2-wa1[i-1]*ci2;
  119249. ch[t8]=wa1[i-2]*ci2+wa1[i-1]*cr2;
  119250. ch[(t8+=t0)-1]=wa2[i-2]*cr3-wa2[i-1]*ci3;
  119251. ch[t8]=wa2[i-2]*ci3+wa2[i-1]*cr3;
  119252. ch[(t8+=t0)-1]=wa3[i-2]*cr4-wa3[i-1]*ci4;
  119253. ch[t8]=wa3[i-2]*ci4+wa3[i-1]*cr4;
  119254. }
  119255. t1+=ido;
  119256. }
  119257. if(ido%2 == 1)return;
  119258. L105:
  119259. t1=ido;
  119260. t2=ido<<2;
  119261. t3=ido-1;
  119262. t4=ido+(ido<<1);
  119263. for(k=0;k<l1;k++){
  119264. t5=t3;
  119265. ti1=cc[t1]+cc[t4];
  119266. ti2=cc[t4]-cc[t1];
  119267. tr1=cc[t1-1]-cc[t4-1];
  119268. tr2=cc[t1-1]+cc[t4-1];
  119269. ch[t5]=tr2+tr2;
  119270. ch[t5+=t0]=sqrt2*(tr1-ti1);
  119271. ch[t5+=t0]=ti2+ti2;
  119272. ch[t5+=t0]=-sqrt2*(tr1+ti1);
  119273. t3+=ido;
  119274. t1+=t2;
  119275. t4+=t2;
  119276. }
  119277. }
  119278. static void dradbg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  119279. float *c2,float *ch,float *ch2,float *wa){
  119280. static float tpi=6.283185307179586f;
  119281. int idij,ipph,i,j,k,l,ik,is,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,
  119282. t11,t12;
  119283. float dc2,ai1,ai2,ar1,ar2,ds2;
  119284. int nbd;
  119285. float dcp,arg,dsp,ar1h,ar2h;
  119286. int ipp2;
  119287. t10=ip*ido;
  119288. t0=l1*ido;
  119289. arg=tpi/(float)ip;
  119290. dcp=cos(arg);
  119291. dsp=sin(arg);
  119292. nbd=(ido-1)>>1;
  119293. ipp2=ip;
  119294. ipph=(ip+1)>>1;
  119295. if(ido<l1)goto L103;
  119296. t1=0;
  119297. t2=0;
  119298. for(k=0;k<l1;k++){
  119299. t3=t1;
  119300. t4=t2;
  119301. for(i=0;i<ido;i++){
  119302. ch[t3]=cc[t4];
  119303. t3++;
  119304. t4++;
  119305. }
  119306. t1+=ido;
  119307. t2+=t10;
  119308. }
  119309. goto L106;
  119310. L103:
  119311. t1=0;
  119312. for(i=0;i<ido;i++){
  119313. t2=t1;
  119314. t3=t1;
  119315. for(k=0;k<l1;k++){
  119316. ch[t2]=cc[t3];
  119317. t2+=ido;
  119318. t3+=t10;
  119319. }
  119320. t1++;
  119321. }
  119322. L106:
  119323. t1=0;
  119324. t2=ipp2*t0;
  119325. t7=(t5=ido<<1);
  119326. for(j=1;j<ipph;j++){
  119327. t1+=t0;
  119328. t2-=t0;
  119329. t3=t1;
  119330. t4=t2;
  119331. t6=t5;
  119332. for(k=0;k<l1;k++){
  119333. ch[t3]=cc[t6-1]+cc[t6-1];
  119334. ch[t4]=cc[t6]+cc[t6];
  119335. t3+=ido;
  119336. t4+=ido;
  119337. t6+=t10;
  119338. }
  119339. t5+=t7;
  119340. }
  119341. if (ido == 1)goto L116;
  119342. if(nbd<l1)goto L112;
  119343. t1=0;
  119344. t2=ipp2*t0;
  119345. t7=0;
  119346. for(j=1;j<ipph;j++){
  119347. t1+=t0;
  119348. t2-=t0;
  119349. t3=t1;
  119350. t4=t2;
  119351. t7+=(ido<<1);
  119352. t8=t7;
  119353. for(k=0;k<l1;k++){
  119354. t5=t3;
  119355. t6=t4;
  119356. t9=t8;
  119357. t11=t8;
  119358. for(i=2;i<ido;i+=2){
  119359. t5+=2;
  119360. t6+=2;
  119361. t9+=2;
  119362. t11-=2;
  119363. ch[t5-1]=cc[t9-1]+cc[t11-1];
  119364. ch[t6-1]=cc[t9-1]-cc[t11-1];
  119365. ch[t5]=cc[t9]-cc[t11];
  119366. ch[t6]=cc[t9]+cc[t11];
  119367. }
  119368. t3+=ido;
  119369. t4+=ido;
  119370. t8+=t10;
  119371. }
  119372. }
  119373. goto L116;
  119374. L112:
  119375. t1=0;
  119376. t2=ipp2*t0;
  119377. t7=0;
  119378. for(j=1;j<ipph;j++){
  119379. t1+=t0;
  119380. t2-=t0;
  119381. t3=t1;
  119382. t4=t2;
  119383. t7+=(ido<<1);
  119384. t8=t7;
  119385. t9=t7;
  119386. for(i=2;i<ido;i+=2){
  119387. t3+=2;
  119388. t4+=2;
  119389. t8+=2;
  119390. t9-=2;
  119391. t5=t3;
  119392. t6=t4;
  119393. t11=t8;
  119394. t12=t9;
  119395. for(k=0;k<l1;k++){
  119396. ch[t5-1]=cc[t11-1]+cc[t12-1];
  119397. ch[t6-1]=cc[t11-1]-cc[t12-1];
  119398. ch[t5]=cc[t11]-cc[t12];
  119399. ch[t6]=cc[t11]+cc[t12];
  119400. t5+=ido;
  119401. t6+=ido;
  119402. t11+=t10;
  119403. t12+=t10;
  119404. }
  119405. }
  119406. }
  119407. L116:
  119408. ar1=1.f;
  119409. ai1=0.f;
  119410. t1=0;
  119411. t9=(t2=ipp2*idl1);
  119412. t3=(ip-1)*idl1;
  119413. for(l=1;l<ipph;l++){
  119414. t1+=idl1;
  119415. t2-=idl1;
  119416. ar1h=dcp*ar1-dsp*ai1;
  119417. ai1=dcp*ai1+dsp*ar1;
  119418. ar1=ar1h;
  119419. t4=t1;
  119420. t5=t2;
  119421. t6=0;
  119422. t7=idl1;
  119423. t8=t3;
  119424. for(ik=0;ik<idl1;ik++){
  119425. c2[t4++]=ch2[t6++]+ar1*ch2[t7++];
  119426. c2[t5++]=ai1*ch2[t8++];
  119427. }
  119428. dc2=ar1;
  119429. ds2=ai1;
  119430. ar2=ar1;
  119431. ai2=ai1;
  119432. t6=idl1;
  119433. t7=t9-idl1;
  119434. for(j=2;j<ipph;j++){
  119435. t6+=idl1;
  119436. t7-=idl1;
  119437. ar2h=dc2*ar2-ds2*ai2;
  119438. ai2=dc2*ai2+ds2*ar2;
  119439. ar2=ar2h;
  119440. t4=t1;
  119441. t5=t2;
  119442. t11=t6;
  119443. t12=t7;
  119444. for(ik=0;ik<idl1;ik++){
  119445. c2[t4++]+=ar2*ch2[t11++];
  119446. c2[t5++]+=ai2*ch2[t12++];
  119447. }
  119448. }
  119449. }
  119450. t1=0;
  119451. for(j=1;j<ipph;j++){
  119452. t1+=idl1;
  119453. t2=t1;
  119454. for(ik=0;ik<idl1;ik++)ch2[ik]+=ch2[t2++];
  119455. }
  119456. t1=0;
  119457. t2=ipp2*t0;
  119458. for(j=1;j<ipph;j++){
  119459. t1+=t0;
  119460. t2-=t0;
  119461. t3=t1;
  119462. t4=t2;
  119463. for(k=0;k<l1;k++){
  119464. ch[t3]=c1[t3]-c1[t4];
  119465. ch[t4]=c1[t3]+c1[t4];
  119466. t3+=ido;
  119467. t4+=ido;
  119468. }
  119469. }
  119470. if(ido==1)goto L132;
  119471. if(nbd<l1)goto L128;
  119472. t1=0;
  119473. t2=ipp2*t0;
  119474. for(j=1;j<ipph;j++){
  119475. t1+=t0;
  119476. t2-=t0;
  119477. t3=t1;
  119478. t4=t2;
  119479. for(k=0;k<l1;k++){
  119480. t5=t3;
  119481. t6=t4;
  119482. for(i=2;i<ido;i+=2){
  119483. t5+=2;
  119484. t6+=2;
  119485. ch[t5-1]=c1[t5-1]-c1[t6];
  119486. ch[t6-1]=c1[t5-1]+c1[t6];
  119487. ch[t5]=c1[t5]+c1[t6-1];
  119488. ch[t6]=c1[t5]-c1[t6-1];
  119489. }
  119490. t3+=ido;
  119491. t4+=ido;
  119492. }
  119493. }
  119494. goto L132;
  119495. L128:
  119496. t1=0;
  119497. t2=ipp2*t0;
  119498. for(j=1;j<ipph;j++){
  119499. t1+=t0;
  119500. t2-=t0;
  119501. t3=t1;
  119502. t4=t2;
  119503. for(i=2;i<ido;i+=2){
  119504. t3+=2;
  119505. t4+=2;
  119506. t5=t3;
  119507. t6=t4;
  119508. for(k=0;k<l1;k++){
  119509. ch[t5-1]=c1[t5-1]-c1[t6];
  119510. ch[t6-1]=c1[t5-1]+c1[t6];
  119511. ch[t5]=c1[t5]+c1[t6-1];
  119512. ch[t6]=c1[t5]-c1[t6-1];
  119513. t5+=ido;
  119514. t6+=ido;
  119515. }
  119516. }
  119517. }
  119518. L132:
  119519. if(ido==1)return;
  119520. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  119521. t1=0;
  119522. for(j=1;j<ip;j++){
  119523. t2=(t1+=t0);
  119524. for(k=0;k<l1;k++){
  119525. c1[t2]=ch[t2];
  119526. t2+=ido;
  119527. }
  119528. }
  119529. if(nbd>l1)goto L139;
  119530. is= -ido-1;
  119531. t1=0;
  119532. for(j=1;j<ip;j++){
  119533. is+=ido;
  119534. t1+=t0;
  119535. idij=is;
  119536. t2=t1;
  119537. for(i=2;i<ido;i+=2){
  119538. t2+=2;
  119539. idij+=2;
  119540. t3=t2;
  119541. for(k=0;k<l1;k++){
  119542. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  119543. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  119544. t3+=ido;
  119545. }
  119546. }
  119547. }
  119548. return;
  119549. L139:
  119550. is= -ido-1;
  119551. t1=0;
  119552. for(j=1;j<ip;j++){
  119553. is+=ido;
  119554. t1+=t0;
  119555. t2=t1;
  119556. for(k=0;k<l1;k++){
  119557. idij=is;
  119558. t3=t2;
  119559. for(i=2;i<ido;i+=2){
  119560. idij+=2;
  119561. t3+=2;
  119562. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  119563. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  119564. }
  119565. t2+=ido;
  119566. }
  119567. }
  119568. }
  119569. static void drftb1(int n, float *c, float *ch, float *wa, int *ifac){
  119570. int i,k1,l1,l2;
  119571. int na;
  119572. int nf,ip,iw,ix2,ix3,ido,idl1;
  119573. nf=ifac[1];
  119574. na=0;
  119575. l1=1;
  119576. iw=1;
  119577. for(k1=0;k1<nf;k1++){
  119578. ip=ifac[k1 + 2];
  119579. l2=ip*l1;
  119580. ido=n/l2;
  119581. idl1=ido*l1;
  119582. if(ip!=4)goto L103;
  119583. ix2=iw+ido;
  119584. ix3=ix2+ido;
  119585. if(na!=0)
  119586. dradb4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  119587. else
  119588. dradb4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  119589. na=1-na;
  119590. goto L115;
  119591. L103:
  119592. if(ip!=2)goto L106;
  119593. if(na!=0)
  119594. dradb2(ido,l1,ch,c,wa+iw-1);
  119595. else
  119596. dradb2(ido,l1,c,ch,wa+iw-1);
  119597. na=1-na;
  119598. goto L115;
  119599. L106:
  119600. if(ip!=3)goto L109;
  119601. ix2=iw+ido;
  119602. if(na!=0)
  119603. dradb3(ido,l1,ch,c,wa+iw-1,wa+ix2-1);
  119604. else
  119605. dradb3(ido,l1,c,ch,wa+iw-1,wa+ix2-1);
  119606. na=1-na;
  119607. goto L115;
  119608. L109:
  119609. /* The radix five case can be translated later..... */
  119610. /* if(ip!=5)goto L112;
  119611. ix2=iw+ido;
  119612. ix3=ix2+ido;
  119613. ix4=ix3+ido;
  119614. if(na!=0)
  119615. dradb5(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  119616. else
  119617. dradb5(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  119618. na=1-na;
  119619. goto L115;
  119620. L112:*/
  119621. if(na!=0)
  119622. dradbg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  119623. else
  119624. dradbg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  119625. if(ido==1)na=1-na;
  119626. L115:
  119627. l1=l2;
  119628. iw+=(ip-1)*ido;
  119629. }
  119630. if(na==0)return;
  119631. for(i=0;i<n;i++)c[i]=ch[i];
  119632. }
  119633. void drft_forward(drft_lookup *l,float *data){
  119634. if(l->n==1)return;
  119635. drftf1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  119636. }
  119637. void drft_backward(drft_lookup *l,float *data){
  119638. if (l->n==1)return;
  119639. drftb1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  119640. }
  119641. void drft_init(drft_lookup *l,int n){
  119642. l->n=n;
  119643. l->trigcache=(float*)_ogg_calloc(3*n,sizeof(*l->trigcache));
  119644. l->splitcache=(int*)_ogg_calloc(32,sizeof(*l->splitcache));
  119645. fdrffti(n, l->trigcache, l->splitcache);
  119646. }
  119647. void drft_clear(drft_lookup *l){
  119648. if(l){
  119649. if(l->trigcache)_ogg_free(l->trigcache);
  119650. if(l->splitcache)_ogg_free(l->splitcache);
  119651. memset(l,0,sizeof(*l));
  119652. }
  119653. }
  119654. #endif
  119655. /*** End of inlined file: smallft.c ***/
  119656. /*** Start of inlined file: synthesis.c ***/
  119657. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  119658. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  119659. // tasks..
  119660. #if JUCE_MSVC
  119661. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  119662. #endif
  119663. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  119664. #if JUCE_USE_OGGVORBIS
  119665. #include <stdio.h>
  119666. int vorbis_synthesis(vorbis_block *vb,ogg_packet *op){
  119667. vorbis_dsp_state *vd=vb->vd;
  119668. private_state *b=(private_state*)vd->backend_state;
  119669. vorbis_info *vi=vd->vi;
  119670. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  119671. oggpack_buffer *opb=&vb->opb;
  119672. int type,mode,i;
  119673. /* first things first. Make sure decode is ready */
  119674. _vorbis_block_ripcord(vb);
  119675. oggpack_readinit(opb,op->packet,op->bytes);
  119676. /* Check the packet type */
  119677. if(oggpack_read(opb,1)!=0){
  119678. /* Oops. This is not an audio data packet */
  119679. return(OV_ENOTAUDIO);
  119680. }
  119681. /* read our mode and pre/post windowsize */
  119682. mode=oggpack_read(opb,b->modebits);
  119683. if(mode==-1)return(OV_EBADPACKET);
  119684. vb->mode=mode;
  119685. vb->W=ci->mode_param[mode]->blockflag;
  119686. if(vb->W){
  119687. /* this doesn;t get mapped through mode selection as it's used
  119688. only for window selection */
  119689. vb->lW=oggpack_read(opb,1);
  119690. vb->nW=oggpack_read(opb,1);
  119691. if(vb->nW==-1) return(OV_EBADPACKET);
  119692. }else{
  119693. vb->lW=0;
  119694. vb->nW=0;
  119695. }
  119696. /* more setup */
  119697. vb->granulepos=op->granulepos;
  119698. vb->sequence=op->packetno;
  119699. vb->eofflag=op->e_o_s;
  119700. /* alloc pcm passback storage */
  119701. vb->pcmend=ci->blocksizes[vb->W];
  119702. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  119703. for(i=0;i<vi->channels;i++)
  119704. vb->pcm[i]=(float*)_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  119705. /* unpack_header enforces range checking */
  119706. type=ci->map_type[ci->mode_param[mode]->mapping];
  119707. return(_mapping_P[type]->inverse(vb,ci->map_param[ci->mode_param[mode]->
  119708. mapping]));
  119709. }
  119710. /* used to track pcm position without actually performing decode.
  119711. Useful for sequential 'fast forward' */
  119712. int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op){
  119713. vorbis_dsp_state *vd=vb->vd;
  119714. private_state *b=(private_state*)vd->backend_state;
  119715. vorbis_info *vi=vd->vi;
  119716. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  119717. oggpack_buffer *opb=&vb->opb;
  119718. int mode;
  119719. /* first things first. Make sure decode is ready */
  119720. _vorbis_block_ripcord(vb);
  119721. oggpack_readinit(opb,op->packet,op->bytes);
  119722. /* Check the packet type */
  119723. if(oggpack_read(opb,1)!=0){
  119724. /* Oops. This is not an audio data packet */
  119725. return(OV_ENOTAUDIO);
  119726. }
  119727. /* read our mode and pre/post windowsize */
  119728. mode=oggpack_read(opb,b->modebits);
  119729. if(mode==-1)return(OV_EBADPACKET);
  119730. vb->mode=mode;
  119731. vb->W=ci->mode_param[mode]->blockflag;
  119732. if(vb->W){
  119733. vb->lW=oggpack_read(opb,1);
  119734. vb->nW=oggpack_read(opb,1);
  119735. if(vb->nW==-1) return(OV_EBADPACKET);
  119736. }else{
  119737. vb->lW=0;
  119738. vb->nW=0;
  119739. }
  119740. /* more setup */
  119741. vb->granulepos=op->granulepos;
  119742. vb->sequence=op->packetno;
  119743. vb->eofflag=op->e_o_s;
  119744. /* no pcm */
  119745. vb->pcmend=0;
  119746. vb->pcm=NULL;
  119747. return(0);
  119748. }
  119749. long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op){
  119750. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  119751. oggpack_buffer opb;
  119752. int mode;
  119753. oggpack_readinit(&opb,op->packet,op->bytes);
  119754. /* Check the packet type */
  119755. if(oggpack_read(&opb,1)!=0){
  119756. /* Oops. This is not an audio data packet */
  119757. return(OV_ENOTAUDIO);
  119758. }
  119759. {
  119760. int modebits=0;
  119761. int v=ci->modes;
  119762. while(v>1){
  119763. modebits++;
  119764. v>>=1;
  119765. }
  119766. /* read our mode and pre/post windowsize */
  119767. mode=oggpack_read(&opb,modebits);
  119768. }
  119769. if(mode==-1)return(OV_EBADPACKET);
  119770. return(ci->blocksizes[ci->mode_param[mode]->blockflag]);
  119771. }
  119772. int vorbis_synthesis_halfrate(vorbis_info *vi,int flag){
  119773. /* set / clear half-sample-rate mode */
  119774. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  119775. /* right now, our MDCT can't handle < 64 sample windows. */
  119776. if(ci->blocksizes[0]<=64 && flag)return -1;
  119777. ci->halfrate_flag=(flag?1:0);
  119778. return 0;
  119779. }
  119780. int vorbis_synthesis_halfrate_p(vorbis_info *vi){
  119781. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  119782. return ci->halfrate_flag;
  119783. }
  119784. #endif
  119785. /*** End of inlined file: synthesis.c ***/
  119786. /*** Start of inlined file: vorbisenc.c ***/
  119787. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  119788. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  119789. // tasks..
  119790. #if JUCE_MSVC
  119791. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  119792. #endif
  119793. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  119794. #if JUCE_USE_OGGVORBIS
  119795. #include <stdlib.h>
  119796. #include <string.h>
  119797. #include <math.h>
  119798. /* careful with this; it's using static array sizing to make managing
  119799. all the modes a little less annoying. If we use a residue backend
  119800. with > 12 partition types, or a different division of iteration,
  119801. this needs to be updated. */
  119802. typedef struct {
  119803. static_codebook *books[12][3];
  119804. } static_bookblock;
  119805. typedef struct {
  119806. int res_type;
  119807. int limit_type; /* 0 lowpass limited, 1 point stereo limited */
  119808. vorbis_info_residue0 *res;
  119809. static_codebook *book_aux;
  119810. static_codebook *book_aux_managed;
  119811. static_bookblock *books_base;
  119812. static_bookblock *books_base_managed;
  119813. } vorbis_residue_template;
  119814. typedef struct {
  119815. vorbis_info_mapping0 *map;
  119816. vorbis_residue_template *res;
  119817. } vorbis_mapping_template;
  119818. typedef struct vp_adjblock{
  119819. int block[P_BANDS];
  119820. } vp_adjblock;
  119821. typedef struct {
  119822. int data[NOISE_COMPAND_LEVELS];
  119823. } compandblock;
  119824. /* high level configuration information for setting things up
  119825. step-by-step with the detailed vorbis_encode_ctl interface.
  119826. There's a fair amount of redundancy such that interactive setup
  119827. does not directly deal with any vorbis_info or codec_setup_info
  119828. initialization; it's all stored (until full init) in this highlevel
  119829. setup, then flushed out to the real codec setup structs later. */
  119830. typedef struct {
  119831. int att[P_NOISECURVES];
  119832. float boost;
  119833. float decay;
  119834. } att3;
  119835. typedef struct { int data[P_NOISECURVES]; } adj3;
  119836. typedef struct {
  119837. int pre[PACKETBLOBS];
  119838. int post[PACKETBLOBS];
  119839. float kHz[PACKETBLOBS];
  119840. float lowpasskHz[PACKETBLOBS];
  119841. } adj_stereo;
  119842. typedef struct {
  119843. int lo;
  119844. int hi;
  119845. int fixed;
  119846. } noiseguard;
  119847. typedef struct {
  119848. int data[P_NOISECURVES][17];
  119849. } noise3;
  119850. typedef struct {
  119851. int mappings;
  119852. double *rate_mapping;
  119853. double *quality_mapping;
  119854. int coupling_restriction;
  119855. long samplerate_min_restriction;
  119856. long samplerate_max_restriction;
  119857. int *blocksize_short;
  119858. int *blocksize_long;
  119859. att3 *psy_tone_masteratt;
  119860. int *psy_tone_0dB;
  119861. int *psy_tone_dBsuppress;
  119862. vp_adjblock *psy_tone_adj_impulse;
  119863. vp_adjblock *psy_tone_adj_long;
  119864. vp_adjblock *psy_tone_adj_other;
  119865. noiseguard *psy_noiseguards;
  119866. noise3 *psy_noise_bias_impulse;
  119867. noise3 *psy_noise_bias_padding;
  119868. noise3 *psy_noise_bias_trans;
  119869. noise3 *psy_noise_bias_long;
  119870. int *psy_noise_dBsuppress;
  119871. compandblock *psy_noise_compand;
  119872. double *psy_noise_compand_short_mapping;
  119873. double *psy_noise_compand_long_mapping;
  119874. int *psy_noise_normal_start[2];
  119875. int *psy_noise_normal_partition[2];
  119876. double *psy_noise_normal_thresh;
  119877. int *psy_ath_float;
  119878. int *psy_ath_abs;
  119879. double *psy_lowpass;
  119880. vorbis_info_psy_global *global_params;
  119881. double *global_mapping;
  119882. adj_stereo *stereo_modes;
  119883. static_codebook ***floor_books;
  119884. vorbis_info_floor1 *floor_params;
  119885. int *floor_short_mapping;
  119886. int *floor_long_mapping;
  119887. vorbis_mapping_template *maps;
  119888. } ve_setup_data_template;
  119889. /* a few static coder conventions */
  119890. static vorbis_info_mode _mode_template[2]={
  119891. {0,0,0,0},
  119892. {1,0,0,1}
  119893. };
  119894. static vorbis_info_mapping0 _map_nominal[2]={
  119895. {1, {0,0}, {0}, {0}, 1,{0},{1}},
  119896. {1, {0,0}, {1}, {1}, 1,{0},{1}}
  119897. };
  119898. /*** Start of inlined file: setup_44.h ***/
  119899. /*** Start of inlined file: floor_all.h ***/
  119900. /*** Start of inlined file: floor_books.h ***/
  119901. static long _huff_lengthlist_line_256x7_0sub1[] = {
  119902. 0, 2, 3, 3, 3, 3, 4, 3, 4,
  119903. };
  119904. static static_codebook _huff_book_line_256x7_0sub1 = {
  119905. 1, 9,
  119906. _huff_lengthlist_line_256x7_0sub1,
  119907. 0, 0, 0, 0, 0,
  119908. NULL,
  119909. NULL,
  119910. NULL,
  119911. NULL,
  119912. 0
  119913. };
  119914. static long _huff_lengthlist_line_256x7_0sub2[] = {
  119915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 4, 3, 5, 3,
  119916. 6, 3, 6, 4, 6, 4, 7, 5, 7,
  119917. };
  119918. static static_codebook _huff_book_line_256x7_0sub2 = {
  119919. 1, 25,
  119920. _huff_lengthlist_line_256x7_0sub2,
  119921. 0, 0, 0, 0, 0,
  119922. NULL,
  119923. NULL,
  119924. NULL,
  119925. NULL,
  119926. 0
  119927. };
  119928. static long _huff_lengthlist_line_256x7_0sub3[] = {
  119929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 2, 5, 3, 5, 3,
  119931. 6, 3, 6, 4, 7, 6, 7, 8, 7, 9, 8, 9, 9, 9,10, 9,
  119932. 11,13,11,13,10,10,13,13,13,13,13,13,12,12,12,12,
  119933. };
  119934. static static_codebook _huff_book_line_256x7_0sub3 = {
  119935. 1, 64,
  119936. _huff_lengthlist_line_256x7_0sub3,
  119937. 0, 0, 0, 0, 0,
  119938. NULL,
  119939. NULL,
  119940. NULL,
  119941. NULL,
  119942. 0
  119943. };
  119944. static long _huff_lengthlist_line_256x7_1sub1[] = {
  119945. 0, 3, 3, 3, 3, 2, 4, 3, 4,
  119946. };
  119947. static static_codebook _huff_book_line_256x7_1sub1 = {
  119948. 1, 9,
  119949. _huff_lengthlist_line_256x7_1sub1,
  119950. 0, 0, 0, 0, 0,
  119951. NULL,
  119952. NULL,
  119953. NULL,
  119954. NULL,
  119955. 0
  119956. };
  119957. static long _huff_lengthlist_line_256x7_1sub2[] = {
  119958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 3, 4, 3, 4, 4,
  119959. 5, 4, 6, 5, 6, 7, 6, 8, 8,
  119960. };
  119961. static static_codebook _huff_book_line_256x7_1sub2 = {
  119962. 1, 25,
  119963. _huff_lengthlist_line_256x7_1sub2,
  119964. 0, 0, 0, 0, 0,
  119965. NULL,
  119966. NULL,
  119967. NULL,
  119968. NULL,
  119969. 0
  119970. };
  119971. static long _huff_lengthlist_line_256x7_1sub3[] = {
  119972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 4, 3, 6, 3, 7,
  119974. 3, 8, 5, 8, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  119975. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7,
  119976. };
  119977. static static_codebook _huff_book_line_256x7_1sub3 = {
  119978. 1, 64,
  119979. _huff_lengthlist_line_256x7_1sub3,
  119980. 0, 0, 0, 0, 0,
  119981. NULL,
  119982. NULL,
  119983. NULL,
  119984. NULL,
  119985. 0
  119986. };
  119987. static long _huff_lengthlist_line_256x7_class0[] = {
  119988. 7, 5, 5, 9, 9, 6, 6, 9,12, 8, 7, 8,11, 8, 9,15,
  119989. 6, 3, 3, 7, 7, 4, 3, 6, 9, 6, 5, 6, 8, 6, 8,15,
  119990. 8, 5, 5, 9, 8, 5, 4, 6,10, 7, 5, 5,11, 8, 7,15,
  119991. 14,15,13,13,13,13, 8,11,15,10, 7, 6,11, 9,10,15,
  119992. };
  119993. static static_codebook _huff_book_line_256x7_class0 = {
  119994. 1, 64,
  119995. _huff_lengthlist_line_256x7_class0,
  119996. 0, 0, 0, 0, 0,
  119997. NULL,
  119998. NULL,
  119999. NULL,
  120000. NULL,
  120001. 0
  120002. };
  120003. static long _huff_lengthlist_line_256x7_class1[] = {
  120004. 5, 6, 8,15, 6, 9,10,15,10,11,12,15,15,15,15,15,
  120005. 4, 6, 7,15, 6, 7, 8,15, 9, 8, 9,15,15,15,15,15,
  120006. 6, 8, 9,15, 7, 7, 8,15,10, 9,10,15,15,15,15,15,
  120007. 15,13,15,15,15,10,11,15,15,13,13,15,15,15,15,15,
  120008. 4, 6, 7,15, 6, 8, 9,15,10,10,12,15,15,15,15,15,
  120009. 2, 5, 6,15, 5, 6, 7,15, 8, 6, 7,15,15,15,15,15,
  120010. 5, 6, 8,15, 5, 6, 7,15, 9, 6, 7,15,15,15,15,15,
  120011. 14,12,13,15,12,10,11,15,15,15,15,15,15,15,15,15,
  120012. 7, 8, 9,15, 9,10,10,15,15,14,14,15,15,15,15,15,
  120013. 5, 6, 7,15, 7, 8, 9,15,12, 9,10,15,15,15,15,15,
  120014. 7, 7, 9,15, 7, 7, 8,15,12, 8, 9,15,15,15,15,15,
  120015. 13,13,14,15,12,11,12,15,15,15,15,15,15,15,15,15,
  120016. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120017. 13,13,13,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120018. 15,12,13,15,15,12,13,15,15,14,15,15,15,15,15,15,
  120019. 15,15,15,15,15,15,13,15,15,15,15,15,15,15,15,15,
  120020. };
  120021. static static_codebook _huff_book_line_256x7_class1 = {
  120022. 1, 256,
  120023. _huff_lengthlist_line_256x7_class1,
  120024. 0, 0, 0, 0, 0,
  120025. NULL,
  120026. NULL,
  120027. NULL,
  120028. NULL,
  120029. 0
  120030. };
  120031. static long _huff_lengthlist_line_512x17_0sub0[] = {
  120032. 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  120033. 5, 6, 5, 6, 6, 6, 6, 5, 6, 6, 7, 6, 7, 6, 7, 6,
  120034. 7, 6, 8, 7, 8, 7, 8, 7, 8, 7, 8, 7, 9, 7, 9, 7,
  120035. 9, 7, 9, 8, 9, 8,10, 8,10, 8,10, 7,10, 6,10, 8,
  120036. 10, 8,11, 7,10, 7,11, 8,11,11,12,12,11,11,12,11,
  120037. 13,11,13,11,13,12,15,12,13,13,14,14,14,14,14,15,
  120038. 15,15,16,14,17,19,19,18,18,18,18,18,18,18,18,18,
  120039. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  120040. };
  120041. static static_codebook _huff_book_line_512x17_0sub0 = {
  120042. 1, 128,
  120043. _huff_lengthlist_line_512x17_0sub0,
  120044. 0, 0, 0, 0, 0,
  120045. NULL,
  120046. NULL,
  120047. NULL,
  120048. NULL,
  120049. 0
  120050. };
  120051. static long _huff_lengthlist_line_512x17_1sub0[] = {
  120052. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  120053. 6, 5, 6, 6, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 8, 7,
  120054. };
  120055. static static_codebook _huff_book_line_512x17_1sub0 = {
  120056. 1, 32,
  120057. _huff_lengthlist_line_512x17_1sub0,
  120058. 0, 0, 0, 0, 0,
  120059. NULL,
  120060. NULL,
  120061. NULL,
  120062. NULL,
  120063. 0
  120064. };
  120065. static long _huff_lengthlist_line_512x17_1sub1[] = {
  120066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120068. 4, 3, 5, 3, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 6, 5,
  120069. 6, 5, 7, 5, 8, 6, 8, 6, 8, 6, 8, 6, 8, 7, 9, 7,
  120070. 9, 7,11, 9,11,11,12,11,14,12,14,16,14,16,13,16,
  120071. 14,16,12,15,13,16,14,16,13,14,12,15,13,15,13,13,
  120072. 13,15,12,14,14,15,13,15,12,15,15,15,15,15,15,15,
  120073. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120074. };
  120075. static static_codebook _huff_book_line_512x17_1sub1 = {
  120076. 1, 128,
  120077. _huff_lengthlist_line_512x17_1sub1,
  120078. 0, 0, 0, 0, 0,
  120079. NULL,
  120080. NULL,
  120081. NULL,
  120082. NULL,
  120083. 0
  120084. };
  120085. static long _huff_lengthlist_line_512x17_2sub1[] = {
  120086. 0, 4, 5, 4, 4, 4, 5, 4, 4, 4, 5, 4, 5, 4, 5, 3,
  120087. 5, 3,
  120088. };
  120089. static static_codebook _huff_book_line_512x17_2sub1 = {
  120090. 1, 18,
  120091. _huff_lengthlist_line_512x17_2sub1,
  120092. 0, 0, 0, 0, 0,
  120093. NULL,
  120094. NULL,
  120095. NULL,
  120096. NULL,
  120097. 0
  120098. };
  120099. static long _huff_lengthlist_line_512x17_2sub2[] = {
  120100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120101. 0, 0, 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 6, 4, 6, 5,
  120102. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 7, 8, 7, 9, 7,
  120103. 9, 8,
  120104. };
  120105. static static_codebook _huff_book_line_512x17_2sub2 = {
  120106. 1, 50,
  120107. _huff_lengthlist_line_512x17_2sub2,
  120108. 0, 0, 0, 0, 0,
  120109. NULL,
  120110. NULL,
  120111. NULL,
  120112. NULL,
  120113. 0
  120114. };
  120115. static long _huff_lengthlist_line_512x17_2sub3[] = {
  120116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120119. 0, 0, 3, 3, 3, 3, 4, 3, 4, 4, 5, 5, 6, 6, 7, 7,
  120120. 7, 8, 8,11, 8, 9, 9, 9,10,11,11,11, 9,10,10,11,
  120121. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120122. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120123. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120124. };
  120125. static static_codebook _huff_book_line_512x17_2sub3 = {
  120126. 1, 128,
  120127. _huff_lengthlist_line_512x17_2sub3,
  120128. 0, 0, 0, 0, 0,
  120129. NULL,
  120130. NULL,
  120131. NULL,
  120132. NULL,
  120133. 0
  120134. };
  120135. static long _huff_lengthlist_line_512x17_3sub1[] = {
  120136. 0, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 5, 4, 5,
  120137. 5, 5,
  120138. };
  120139. static static_codebook _huff_book_line_512x17_3sub1 = {
  120140. 1, 18,
  120141. _huff_lengthlist_line_512x17_3sub1,
  120142. 0, 0, 0, 0, 0,
  120143. NULL,
  120144. NULL,
  120145. NULL,
  120146. NULL,
  120147. 0
  120148. };
  120149. static long _huff_lengthlist_line_512x17_3sub2[] = {
  120150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120151. 0, 0, 2, 3, 3, 4, 3, 5, 4, 6, 4, 6, 5, 7, 6, 7,
  120152. 6, 8, 6, 8, 7, 9, 8,10, 8,12, 9,13,10,15,10,15,
  120153. 11,14,
  120154. };
  120155. static static_codebook _huff_book_line_512x17_3sub2 = {
  120156. 1, 50,
  120157. _huff_lengthlist_line_512x17_3sub2,
  120158. 0, 0, 0, 0, 0,
  120159. NULL,
  120160. NULL,
  120161. NULL,
  120162. NULL,
  120163. 0
  120164. };
  120165. static long _huff_lengthlist_line_512x17_3sub3[] = {
  120166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120169. 0, 0, 4, 8, 4, 8, 4, 8, 4, 8, 5, 8, 5, 8, 6, 8,
  120170. 4, 8, 4, 8, 5, 8, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120171. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120172. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120173. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120174. };
  120175. static static_codebook _huff_book_line_512x17_3sub3 = {
  120176. 1, 128,
  120177. _huff_lengthlist_line_512x17_3sub3,
  120178. 0, 0, 0, 0, 0,
  120179. NULL,
  120180. NULL,
  120181. NULL,
  120182. NULL,
  120183. 0
  120184. };
  120185. static long _huff_lengthlist_line_512x17_class1[] = {
  120186. 1, 2, 3, 6, 5, 4, 7, 7,
  120187. };
  120188. static static_codebook _huff_book_line_512x17_class1 = {
  120189. 1, 8,
  120190. _huff_lengthlist_line_512x17_class1,
  120191. 0, 0, 0, 0, 0,
  120192. NULL,
  120193. NULL,
  120194. NULL,
  120195. NULL,
  120196. 0
  120197. };
  120198. static long _huff_lengthlist_line_512x17_class2[] = {
  120199. 3, 3, 3,14, 5, 4, 4,11, 8, 6, 6,10,17,12,11,17,
  120200. 6, 5, 5,15, 5, 3, 4,11, 8, 5, 5, 8,16, 9,10,14,
  120201. 10, 8, 9,17, 8, 6, 6,13,10, 7, 7,10,16,11,13,14,
  120202. 17,17,17,17,17,16,16,16,16,15,16,16,16,16,16,16,
  120203. };
  120204. static static_codebook _huff_book_line_512x17_class2 = {
  120205. 1, 64,
  120206. _huff_lengthlist_line_512x17_class2,
  120207. 0, 0, 0, 0, 0,
  120208. NULL,
  120209. NULL,
  120210. NULL,
  120211. NULL,
  120212. 0
  120213. };
  120214. static long _huff_lengthlist_line_512x17_class3[] = {
  120215. 2, 4, 6,17, 4, 5, 7,17, 8, 7,10,17,17,17,17,17,
  120216. 3, 4, 6,15, 3, 3, 6,15, 7, 6, 9,17,17,17,17,17,
  120217. 6, 8,10,17, 6, 6, 8,16, 9, 8,10,17,17,15,16,17,
  120218. 17,17,17,17,12,15,15,16,12,15,15,16,16,16,16,16,
  120219. };
  120220. static static_codebook _huff_book_line_512x17_class3 = {
  120221. 1, 64,
  120222. _huff_lengthlist_line_512x17_class3,
  120223. 0, 0, 0, 0, 0,
  120224. NULL,
  120225. NULL,
  120226. NULL,
  120227. NULL,
  120228. 0
  120229. };
  120230. static long _huff_lengthlist_line_128x4_class0[] = {
  120231. 7, 7, 7,11, 6, 6, 7,11, 7, 6, 6,10,12,10,10,13,
  120232. 7, 7, 8,11, 7, 7, 7,11, 7, 6, 7,10,11,10,10,13,
  120233. 10,10, 9,12, 9, 9, 9,11, 8, 8, 8,11,13,11,10,14,
  120234. 15,15,14,15,15,14,13,14,15,12,12,17,17,17,17,17,
  120235. 7, 7, 6, 9, 6, 6, 6, 9, 7, 6, 6, 8,11,11,10,12,
  120236. 7, 7, 7, 9, 7, 6, 6, 9, 7, 6, 6, 9,13,10,10,11,
  120237. 10, 9, 8,10, 9, 8, 8,10, 8, 8, 7, 9,13,12,10,11,
  120238. 17,14,14,13,15,14,12,13,17,13,12,15,17,17,14,17,
  120239. 7, 6, 6, 7, 6, 6, 5, 7, 6, 6, 6, 6,11, 9, 9, 9,
  120240. 7, 7, 6, 7, 7, 6, 6, 7, 6, 6, 6, 6,10, 9, 8, 9,
  120241. 10, 9, 8, 8, 9, 8, 7, 8, 8, 7, 6, 8,11,10, 9,10,
  120242. 17,17,12,15,15,15,12,14,14,14,10,12,15,13,12,13,
  120243. 11,10, 8,10,11,10, 8, 8,10, 9, 7, 7,10, 9, 9,11,
  120244. 11,11, 9,10,11,10, 8, 9,10, 8, 6, 8,10, 9, 9,11,
  120245. 14,13,10,12,12,11,10,10, 8, 7, 8,10,10,11,11,12,
  120246. 17,17,15,17,17,17,17,17,17,13,12,17,17,17,14,17,
  120247. };
  120248. static static_codebook _huff_book_line_128x4_class0 = {
  120249. 1, 256,
  120250. _huff_lengthlist_line_128x4_class0,
  120251. 0, 0, 0, 0, 0,
  120252. NULL,
  120253. NULL,
  120254. NULL,
  120255. NULL,
  120256. 0
  120257. };
  120258. static long _huff_lengthlist_line_128x4_0sub0[] = {
  120259. 2, 2, 2, 2,
  120260. };
  120261. static static_codebook _huff_book_line_128x4_0sub0 = {
  120262. 1, 4,
  120263. _huff_lengthlist_line_128x4_0sub0,
  120264. 0, 0, 0, 0, 0,
  120265. NULL,
  120266. NULL,
  120267. NULL,
  120268. NULL,
  120269. 0
  120270. };
  120271. static long _huff_lengthlist_line_128x4_0sub1[] = {
  120272. 0, 0, 0, 0, 3, 2, 3, 2, 3, 3,
  120273. };
  120274. static static_codebook _huff_book_line_128x4_0sub1 = {
  120275. 1, 10,
  120276. _huff_lengthlist_line_128x4_0sub1,
  120277. 0, 0, 0, 0, 0,
  120278. NULL,
  120279. NULL,
  120280. NULL,
  120281. NULL,
  120282. 0
  120283. };
  120284. static long _huff_lengthlist_line_128x4_0sub2[] = {
  120285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 3, 4, 3,
  120286. 4, 4, 5, 4, 5, 4, 6, 5, 6,
  120287. };
  120288. static static_codebook _huff_book_line_128x4_0sub2 = {
  120289. 1, 25,
  120290. _huff_lengthlist_line_128x4_0sub2,
  120291. 0, 0, 0, 0, 0,
  120292. NULL,
  120293. NULL,
  120294. NULL,
  120295. NULL,
  120296. 0
  120297. };
  120298. static long _huff_lengthlist_line_128x4_0sub3[] = {
  120299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  120301. 5, 4, 6, 5, 6, 5, 7, 6, 6, 7, 7, 9, 9,11,11,16,
  120302. 11,14,10,11,11,13,16,15,15,15,15,15,15,15,15,15,
  120303. };
  120304. static static_codebook _huff_book_line_128x4_0sub3 = {
  120305. 1, 64,
  120306. _huff_lengthlist_line_128x4_0sub3,
  120307. 0, 0, 0, 0, 0,
  120308. NULL,
  120309. NULL,
  120310. NULL,
  120311. NULL,
  120312. 0
  120313. };
  120314. static long _huff_lengthlist_line_256x4_class0[] = {
  120315. 6, 7, 7,12, 6, 6, 7,12, 7, 6, 6,10,15,12,11,13,
  120316. 7, 7, 8,13, 7, 7, 8,12, 7, 7, 7,11,12,12,11,13,
  120317. 10, 9, 9,11, 9, 9, 9,10,10, 8, 8,12,14,12,12,14,
  120318. 11,11,12,14,11,12,11,15,15,12,13,15,15,15,15,15,
  120319. 6, 6, 7,10, 6, 6, 6,11, 7, 6, 6, 9,14,12,11,13,
  120320. 7, 7, 7,10, 6, 6, 7, 9, 7, 7, 6,10,13,12,10,12,
  120321. 9, 9, 9,11, 9, 9, 8, 9, 9, 8, 8,10,13,12,10,12,
  120322. 12,12,11,13,12,12,11,12,15,13,12,15,15,15,14,14,
  120323. 6, 6, 6, 8, 6, 6, 5, 6, 7, 7, 6, 5,11,10, 9, 8,
  120324. 7, 6, 6, 7, 6, 6, 5, 6, 7, 7, 6, 6,11,10, 9, 8,
  120325. 8, 8, 8, 9, 8, 8, 7, 8, 8, 8, 6, 7,11,10, 9, 9,
  120326. 14,11,10,14,14,11,10,15,13,11, 9,11,15,12,12,11,
  120327. 11, 9, 8, 8,10, 9, 8, 9,11,10, 9, 8,12,11,12,11,
  120328. 13,10, 8, 9,11,10, 8, 9,10, 9, 8, 9,10, 8,12,12,
  120329. 15,11,10,10,13,11,10,10, 8, 8, 7,12,10, 9,11,12,
  120330. 15,12,11,15,13,11,11,15,12,14,11,13,15,15,13,13,
  120331. };
  120332. static static_codebook _huff_book_line_256x4_class0 = {
  120333. 1, 256,
  120334. _huff_lengthlist_line_256x4_class0,
  120335. 0, 0, 0, 0, 0,
  120336. NULL,
  120337. NULL,
  120338. NULL,
  120339. NULL,
  120340. 0
  120341. };
  120342. static long _huff_lengthlist_line_256x4_0sub0[] = {
  120343. 2, 2, 2, 2,
  120344. };
  120345. static static_codebook _huff_book_line_256x4_0sub0 = {
  120346. 1, 4,
  120347. _huff_lengthlist_line_256x4_0sub0,
  120348. 0, 0, 0, 0, 0,
  120349. NULL,
  120350. NULL,
  120351. NULL,
  120352. NULL,
  120353. 0
  120354. };
  120355. static long _huff_lengthlist_line_256x4_0sub1[] = {
  120356. 0, 0, 0, 0, 2, 2, 3, 3, 3, 3,
  120357. };
  120358. static static_codebook _huff_book_line_256x4_0sub1 = {
  120359. 1, 10,
  120360. _huff_lengthlist_line_256x4_0sub1,
  120361. 0, 0, 0, 0, 0,
  120362. NULL,
  120363. NULL,
  120364. NULL,
  120365. NULL,
  120366. 0
  120367. };
  120368. static long _huff_lengthlist_line_256x4_0sub2[] = {
  120369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 3, 4, 3, 4, 3,
  120370. 5, 3, 5, 4, 5, 4, 6, 4, 6,
  120371. };
  120372. static static_codebook _huff_book_line_256x4_0sub2 = {
  120373. 1, 25,
  120374. _huff_lengthlist_line_256x4_0sub2,
  120375. 0, 0, 0, 0, 0,
  120376. NULL,
  120377. NULL,
  120378. NULL,
  120379. NULL,
  120380. 0
  120381. };
  120382. static long _huff_lengthlist_line_256x4_0sub3[] = {
  120383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  120385. 6, 4, 7, 4, 7, 5, 7, 6, 7, 6, 7, 8,10,13,13,13,
  120386. 13,13,13,13,13,13,13,13,13,13,13,12,12,12,12,12,
  120387. };
  120388. static static_codebook _huff_book_line_256x4_0sub3 = {
  120389. 1, 64,
  120390. _huff_lengthlist_line_256x4_0sub3,
  120391. 0, 0, 0, 0, 0,
  120392. NULL,
  120393. NULL,
  120394. NULL,
  120395. NULL,
  120396. 0
  120397. };
  120398. static long _huff_lengthlist_line_128x7_class0[] = {
  120399. 10, 7, 8,13, 9, 6, 7,11,10, 8, 8,12,17,17,17,17,
  120400. 7, 5, 5, 9, 6, 4, 4, 8, 8, 5, 5, 8,16,14,13,16,
  120401. 7, 5, 5, 7, 6, 3, 3, 5, 8, 5, 4, 7,14,12,12,15,
  120402. 10, 7, 8, 9, 7, 5, 5, 6, 9, 6, 5, 5,15,12, 9,10,
  120403. };
  120404. static static_codebook _huff_book_line_128x7_class0 = {
  120405. 1, 64,
  120406. _huff_lengthlist_line_128x7_class0,
  120407. 0, 0, 0, 0, 0,
  120408. NULL,
  120409. NULL,
  120410. NULL,
  120411. NULL,
  120412. 0
  120413. };
  120414. static long _huff_lengthlist_line_128x7_class1[] = {
  120415. 8,13,17,17, 8,11,17,17,11,13,17,17,17,17,17,17,
  120416. 6,10,16,17, 6,10,15,17, 8,10,16,17,17,17,17,17,
  120417. 9,13,15,17, 8,11,17,17,10,12,17,17,17,17,17,17,
  120418. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  120419. 6,11,15,17, 7,10,15,17, 8,10,17,17,17,15,17,17,
  120420. 4, 8,13,17, 4, 7,13,17, 6, 8,15,17,16,15,17,17,
  120421. 6,11,15,17, 6, 9,13,17, 8,10,17,17,15,17,17,17,
  120422. 16,17,17,17,12,14,15,17,13,14,15,17,17,17,17,17,
  120423. 5,10,14,17, 5, 9,14,17, 7, 9,15,17,15,15,17,17,
  120424. 3, 7,12,17, 3, 6,11,17, 5, 7,13,17,12,12,17,17,
  120425. 5, 9,14,17, 3, 7,11,17, 5, 8,13,17,13,11,16,17,
  120426. 12,17,17,17, 9,14,15,17,10,11,14,17,16,14,17,17,
  120427. 8,12,17,17, 8,12,17,17,10,12,17,17,17,17,17,17,
  120428. 5,10,17,17, 5, 9,15,17, 7, 9,17,17,13,13,17,17,
  120429. 7,11,17,17, 6,10,15,17, 7, 9,15,17,12,11,17,17,
  120430. 12,15,17,17,11,14,17,17,11,10,15,17,17,16,17,17,
  120431. };
  120432. static static_codebook _huff_book_line_128x7_class1 = {
  120433. 1, 256,
  120434. _huff_lengthlist_line_128x7_class1,
  120435. 0, 0, 0, 0, 0,
  120436. NULL,
  120437. NULL,
  120438. NULL,
  120439. NULL,
  120440. 0
  120441. };
  120442. static long _huff_lengthlist_line_128x7_0sub1[] = {
  120443. 0, 3, 3, 3, 3, 3, 3, 3, 3,
  120444. };
  120445. static static_codebook _huff_book_line_128x7_0sub1 = {
  120446. 1, 9,
  120447. _huff_lengthlist_line_128x7_0sub1,
  120448. 0, 0, 0, 0, 0,
  120449. NULL,
  120450. NULL,
  120451. NULL,
  120452. NULL,
  120453. 0
  120454. };
  120455. static long _huff_lengthlist_line_128x7_0sub2[] = {
  120456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 4, 4, 4,
  120457. 5, 4, 5, 4, 5, 4, 6, 4, 6,
  120458. };
  120459. static static_codebook _huff_book_line_128x7_0sub2 = {
  120460. 1, 25,
  120461. _huff_lengthlist_line_128x7_0sub2,
  120462. 0, 0, 0, 0, 0,
  120463. NULL,
  120464. NULL,
  120465. NULL,
  120466. NULL,
  120467. 0
  120468. };
  120469. static long _huff_lengthlist_line_128x7_0sub3[] = {
  120470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 3, 5, 3, 5, 4,
  120472. 5, 4, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  120473. 7, 8, 9,11,13,13,13,13,13,13,13,13,13,13,13,13,
  120474. };
  120475. static static_codebook _huff_book_line_128x7_0sub3 = {
  120476. 1, 64,
  120477. _huff_lengthlist_line_128x7_0sub3,
  120478. 0, 0, 0, 0, 0,
  120479. NULL,
  120480. NULL,
  120481. NULL,
  120482. NULL,
  120483. 0
  120484. };
  120485. static long _huff_lengthlist_line_128x7_1sub1[] = {
  120486. 0, 3, 3, 2, 3, 3, 4, 3, 4,
  120487. };
  120488. static static_codebook _huff_book_line_128x7_1sub1 = {
  120489. 1, 9,
  120490. _huff_lengthlist_line_128x7_1sub1,
  120491. 0, 0, 0, 0, 0,
  120492. NULL,
  120493. NULL,
  120494. NULL,
  120495. NULL,
  120496. 0
  120497. };
  120498. static long _huff_lengthlist_line_128x7_1sub2[] = {
  120499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 6, 3, 6, 3,
  120500. 6, 3, 7, 3, 8, 4, 9, 4, 9,
  120501. };
  120502. static static_codebook _huff_book_line_128x7_1sub2 = {
  120503. 1, 25,
  120504. _huff_lengthlist_line_128x7_1sub2,
  120505. 0, 0, 0, 0, 0,
  120506. NULL,
  120507. NULL,
  120508. NULL,
  120509. NULL,
  120510. 0
  120511. };
  120512. static long _huff_lengthlist_line_128x7_1sub3[] = {
  120513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7, 2, 7, 3, 8, 4,
  120515. 9, 5, 9, 8,10,11,11,12,14,14,14,14,14,14,14,14,
  120516. 14,14,14,14,14,14,14,14,14,14,14,14,13,13,13,13,
  120517. };
  120518. static static_codebook _huff_book_line_128x7_1sub3 = {
  120519. 1, 64,
  120520. _huff_lengthlist_line_128x7_1sub3,
  120521. 0, 0, 0, 0, 0,
  120522. NULL,
  120523. NULL,
  120524. NULL,
  120525. NULL,
  120526. 0
  120527. };
  120528. static long _huff_lengthlist_line_128x11_class1[] = {
  120529. 1, 6, 3, 7, 2, 4, 5, 7,
  120530. };
  120531. static static_codebook _huff_book_line_128x11_class1 = {
  120532. 1, 8,
  120533. _huff_lengthlist_line_128x11_class1,
  120534. 0, 0, 0, 0, 0,
  120535. NULL,
  120536. NULL,
  120537. NULL,
  120538. NULL,
  120539. 0
  120540. };
  120541. static long _huff_lengthlist_line_128x11_class2[] = {
  120542. 1, 6,12,16, 4,12,15,16, 9,15,16,16,16,16,16,16,
  120543. 2, 5,11,16, 5,11,13,16, 9,13,16,16,16,16,16,16,
  120544. 4, 8,12,16, 5, 9,12,16, 9,13,15,16,16,16,16,16,
  120545. 15,16,16,16,11,14,13,16,12,15,16,16,16,16,16,15,
  120546. };
  120547. static static_codebook _huff_book_line_128x11_class2 = {
  120548. 1, 64,
  120549. _huff_lengthlist_line_128x11_class2,
  120550. 0, 0, 0, 0, 0,
  120551. NULL,
  120552. NULL,
  120553. NULL,
  120554. NULL,
  120555. 0
  120556. };
  120557. static long _huff_lengthlist_line_128x11_class3[] = {
  120558. 7, 6, 9,17, 7, 6, 8,17,12, 9,11,16,16,16,16,16,
  120559. 5, 4, 7,16, 5, 3, 6,14, 9, 6, 8,15,16,16,16,16,
  120560. 5, 4, 6,13, 3, 2, 4,11, 7, 4, 6,13,16,11,10,14,
  120561. 12,12,12,16, 9, 7,10,15,12, 9,11,16,16,15,15,16,
  120562. };
  120563. static static_codebook _huff_book_line_128x11_class3 = {
  120564. 1, 64,
  120565. _huff_lengthlist_line_128x11_class3,
  120566. 0, 0, 0, 0, 0,
  120567. NULL,
  120568. NULL,
  120569. NULL,
  120570. NULL,
  120571. 0
  120572. };
  120573. static long _huff_lengthlist_line_128x11_0sub0[] = {
  120574. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  120575. 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 6, 6, 6, 7, 6,
  120576. 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6, 8, 7,
  120577. 8, 7, 8, 7, 8, 7, 9, 7, 9, 8, 9, 8, 9, 8,10, 8,
  120578. 10, 9,10, 9,10, 9,11, 9,11, 9,10,10,11,10,11,10,
  120579. 11,11,11,11,11,11,12,13,14,14,14,15,15,16,16,16,
  120580. 17,15,16,15,16,16,17,17,16,17,17,17,17,17,17,17,
  120581. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  120582. };
  120583. static static_codebook _huff_book_line_128x11_0sub0 = {
  120584. 1, 128,
  120585. _huff_lengthlist_line_128x11_0sub0,
  120586. 0, 0, 0, 0, 0,
  120587. NULL,
  120588. NULL,
  120589. NULL,
  120590. NULL,
  120591. 0
  120592. };
  120593. static long _huff_lengthlist_line_128x11_1sub0[] = {
  120594. 2, 5, 5, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  120595. 6, 5, 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6,
  120596. };
  120597. static static_codebook _huff_book_line_128x11_1sub0 = {
  120598. 1, 32,
  120599. _huff_lengthlist_line_128x11_1sub0,
  120600. 0, 0, 0, 0, 0,
  120601. NULL,
  120602. NULL,
  120603. NULL,
  120604. NULL,
  120605. 0
  120606. };
  120607. static long _huff_lengthlist_line_128x11_1sub1[] = {
  120608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120610. 5, 3, 5, 3, 6, 4, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  120611. 8, 4, 9, 5, 9, 5, 9, 5, 9, 6,10, 6,10, 6,11, 7,
  120612. 10, 7,10, 8,11, 9,11, 9,11,10,11,11,12,11,11,12,
  120613. 15,15,12,14,11,14,12,14,11,14,13,14,12,14,11,14,
  120614. 11,14,12,14,11,14,11,14,13,13,14,14,14,14,14,14,
  120615. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  120616. };
  120617. static static_codebook _huff_book_line_128x11_1sub1 = {
  120618. 1, 128,
  120619. _huff_lengthlist_line_128x11_1sub1,
  120620. 0, 0, 0, 0, 0,
  120621. NULL,
  120622. NULL,
  120623. NULL,
  120624. NULL,
  120625. 0
  120626. };
  120627. static long _huff_lengthlist_line_128x11_2sub1[] = {
  120628. 0, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4,
  120629. 5, 5,
  120630. };
  120631. static static_codebook _huff_book_line_128x11_2sub1 = {
  120632. 1, 18,
  120633. _huff_lengthlist_line_128x11_2sub1,
  120634. 0, 0, 0, 0, 0,
  120635. NULL,
  120636. NULL,
  120637. NULL,
  120638. NULL,
  120639. 0
  120640. };
  120641. static long _huff_lengthlist_line_128x11_2sub2[] = {
  120642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120643. 0, 0, 3, 3, 3, 4, 4, 4, 4, 5, 4, 5, 4, 6, 5, 7,
  120644. 5, 7, 6, 8, 6, 8, 6, 9, 7, 9, 7,10, 7, 9, 8,11,
  120645. 8,11,
  120646. };
  120647. static static_codebook _huff_book_line_128x11_2sub2 = {
  120648. 1, 50,
  120649. _huff_lengthlist_line_128x11_2sub2,
  120650. 0, 0, 0, 0, 0,
  120651. NULL,
  120652. NULL,
  120653. NULL,
  120654. NULL,
  120655. 0
  120656. };
  120657. static long _huff_lengthlist_line_128x11_2sub3[] = {
  120658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120661. 0, 0, 4, 8, 3, 8, 4, 8, 4, 8, 6, 8, 5, 8, 4, 8,
  120662. 4, 8, 6, 8, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120663. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120664. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120665. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120666. };
  120667. static static_codebook _huff_book_line_128x11_2sub3 = {
  120668. 1, 128,
  120669. _huff_lengthlist_line_128x11_2sub3,
  120670. 0, 0, 0, 0, 0,
  120671. NULL,
  120672. NULL,
  120673. NULL,
  120674. NULL,
  120675. 0
  120676. };
  120677. static long _huff_lengthlist_line_128x11_3sub1[] = {
  120678. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4,
  120679. 5, 4,
  120680. };
  120681. static static_codebook _huff_book_line_128x11_3sub1 = {
  120682. 1, 18,
  120683. _huff_lengthlist_line_128x11_3sub1,
  120684. 0, 0, 0, 0, 0,
  120685. NULL,
  120686. NULL,
  120687. NULL,
  120688. NULL,
  120689. 0
  120690. };
  120691. static long _huff_lengthlist_line_128x11_3sub2[] = {
  120692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120693. 0, 0, 5, 3, 5, 4, 6, 4, 6, 4, 7, 4, 7, 4, 8, 4,
  120694. 8, 4, 9, 4, 9, 4,10, 4,10, 5,10, 5,11, 5,12, 6,
  120695. 12, 6,
  120696. };
  120697. static static_codebook _huff_book_line_128x11_3sub2 = {
  120698. 1, 50,
  120699. _huff_lengthlist_line_128x11_3sub2,
  120700. 0, 0, 0, 0, 0,
  120701. NULL,
  120702. NULL,
  120703. NULL,
  120704. NULL,
  120705. 0
  120706. };
  120707. static long _huff_lengthlist_line_128x11_3sub3[] = {
  120708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120711. 0, 0, 7, 1, 6, 3, 7, 3, 8, 4, 8, 5, 8, 8, 8, 9,
  120712. 7, 8, 8, 7, 7, 7, 8, 9,10, 9, 9,10,10,10,10,10,
  120713. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120714. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120715. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  120716. };
  120717. static static_codebook _huff_book_line_128x11_3sub3 = {
  120718. 1, 128,
  120719. _huff_lengthlist_line_128x11_3sub3,
  120720. 0, 0, 0, 0, 0,
  120721. NULL,
  120722. NULL,
  120723. NULL,
  120724. NULL,
  120725. 0
  120726. };
  120727. static long _huff_lengthlist_line_128x17_class1[] = {
  120728. 1, 3, 4, 7, 2, 5, 6, 7,
  120729. };
  120730. static static_codebook _huff_book_line_128x17_class1 = {
  120731. 1, 8,
  120732. _huff_lengthlist_line_128x17_class1,
  120733. 0, 0, 0, 0, 0,
  120734. NULL,
  120735. NULL,
  120736. NULL,
  120737. NULL,
  120738. 0
  120739. };
  120740. static long _huff_lengthlist_line_128x17_class2[] = {
  120741. 1, 4,10,19, 3, 8,13,19, 7,12,19,19,19,19,19,19,
  120742. 2, 6,11,19, 8,13,19,19, 9,11,19,19,19,19,19,19,
  120743. 6, 7,13,19, 9,13,19,19,10,13,18,18,18,18,18,18,
  120744. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  120745. };
  120746. static static_codebook _huff_book_line_128x17_class2 = {
  120747. 1, 64,
  120748. _huff_lengthlist_line_128x17_class2,
  120749. 0, 0, 0, 0, 0,
  120750. NULL,
  120751. NULL,
  120752. NULL,
  120753. NULL,
  120754. 0
  120755. };
  120756. static long _huff_lengthlist_line_128x17_class3[] = {
  120757. 3, 6,10,17, 4, 8,11,20, 8,10,11,20,20,20,20,20,
  120758. 2, 4, 8,18, 4, 6, 8,17, 7, 8,10,20,20,17,20,20,
  120759. 3, 5, 8,17, 3, 4, 6,17, 8, 8,10,17,17,12,16,20,
  120760. 13,13,15,20,10,10,12,20,15,14,15,20,20,20,19,19,
  120761. };
  120762. static static_codebook _huff_book_line_128x17_class3 = {
  120763. 1, 64,
  120764. _huff_lengthlist_line_128x17_class3,
  120765. 0, 0, 0, 0, 0,
  120766. NULL,
  120767. NULL,
  120768. NULL,
  120769. NULL,
  120770. 0
  120771. };
  120772. static long _huff_lengthlist_line_128x17_0sub0[] = {
  120773. 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  120774. 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5,
  120775. 8, 5, 8, 5, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6, 9, 6,
  120776. 9, 6, 9, 7, 9, 7, 9, 7, 9, 7,10, 7,10, 8,10, 8,
  120777. 10, 8,10, 8,10, 8,11, 8,11, 8,11, 8,11, 8,11, 9,
  120778. 12, 9,12, 9,12, 9,12, 9,12,10,12,10,13,11,13,11,
  120779. 14,12,14,13,15,14,16,14,17,15,18,16,20,20,20,20,
  120780. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  120781. };
  120782. static static_codebook _huff_book_line_128x17_0sub0 = {
  120783. 1, 128,
  120784. _huff_lengthlist_line_128x17_0sub0,
  120785. 0, 0, 0, 0, 0,
  120786. NULL,
  120787. NULL,
  120788. NULL,
  120789. NULL,
  120790. 0
  120791. };
  120792. static long _huff_lengthlist_line_128x17_1sub0[] = {
  120793. 2, 5, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  120794. 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7,
  120795. };
  120796. static static_codebook _huff_book_line_128x17_1sub0 = {
  120797. 1, 32,
  120798. _huff_lengthlist_line_128x17_1sub0,
  120799. 0, 0, 0, 0, 0,
  120800. NULL,
  120801. NULL,
  120802. NULL,
  120803. NULL,
  120804. 0
  120805. };
  120806. static long _huff_lengthlist_line_128x17_1sub1[] = {
  120807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120809. 4, 3, 5, 3, 5, 3, 6, 3, 6, 4, 6, 4, 7, 4, 7, 5,
  120810. 8, 5, 8, 6, 9, 7, 9, 7, 9, 8,10, 9,10, 9,11,10,
  120811. 11,11,11,11,11,11,12,12,12,13,12,13,12,14,12,15,
  120812. 12,14,12,16,13,17,13,17,14,17,14,16,13,17,14,17,
  120813. 14,17,15,17,15,15,16,17,17,17,17,17,17,17,17,17,
  120814. 17,17,17,17,17,17,16,16,16,16,16,16,16,16,16,16,
  120815. };
  120816. static static_codebook _huff_book_line_128x17_1sub1 = {
  120817. 1, 128,
  120818. _huff_lengthlist_line_128x17_1sub1,
  120819. 0, 0, 0, 0, 0,
  120820. NULL,
  120821. NULL,
  120822. NULL,
  120823. NULL,
  120824. 0
  120825. };
  120826. static long _huff_lengthlist_line_128x17_2sub1[] = {
  120827. 0, 4, 5, 4, 6, 4, 8, 3, 9, 3, 9, 2, 9, 3, 8, 4,
  120828. 9, 4,
  120829. };
  120830. static static_codebook _huff_book_line_128x17_2sub1 = {
  120831. 1, 18,
  120832. _huff_lengthlist_line_128x17_2sub1,
  120833. 0, 0, 0, 0, 0,
  120834. NULL,
  120835. NULL,
  120836. NULL,
  120837. NULL,
  120838. 0
  120839. };
  120840. static long _huff_lengthlist_line_128x17_2sub2[] = {
  120841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120842. 0, 0, 5, 1, 5, 3, 5, 3, 5, 4, 7, 5,10, 7,10, 7,
  120843. 12,10,14,10,14, 9,14,11,14,14,14,13,13,13,13,13,
  120844. 13,13,
  120845. };
  120846. static static_codebook _huff_book_line_128x17_2sub2 = {
  120847. 1, 50,
  120848. _huff_lengthlist_line_128x17_2sub2,
  120849. 0, 0, 0, 0, 0,
  120850. NULL,
  120851. NULL,
  120852. NULL,
  120853. NULL,
  120854. 0
  120855. };
  120856. static long _huff_lengthlist_line_128x17_2sub3[] = {
  120857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120860. 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120861. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6,
  120862. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  120863. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  120864. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  120865. };
  120866. static static_codebook _huff_book_line_128x17_2sub3 = {
  120867. 1, 128,
  120868. _huff_lengthlist_line_128x17_2sub3,
  120869. 0, 0, 0, 0, 0,
  120870. NULL,
  120871. NULL,
  120872. NULL,
  120873. NULL,
  120874. 0
  120875. };
  120876. static long _huff_lengthlist_line_128x17_3sub1[] = {
  120877. 0, 4, 4, 4, 4, 4, 4, 4, 5, 3, 5, 3, 5, 4, 6, 4,
  120878. 6, 4,
  120879. };
  120880. static static_codebook _huff_book_line_128x17_3sub1 = {
  120881. 1, 18,
  120882. _huff_lengthlist_line_128x17_3sub1,
  120883. 0, 0, 0, 0, 0,
  120884. NULL,
  120885. NULL,
  120886. NULL,
  120887. NULL,
  120888. 0
  120889. };
  120890. static long _huff_lengthlist_line_128x17_3sub2[] = {
  120891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120892. 0, 0, 5, 3, 6, 3, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  120893. 8, 4, 8, 4, 8, 4, 9, 4, 9, 5,10, 5,10, 7,10, 8,
  120894. 10, 8,
  120895. };
  120896. static static_codebook _huff_book_line_128x17_3sub2 = {
  120897. 1, 50,
  120898. _huff_lengthlist_line_128x17_3sub2,
  120899. 0, 0, 0, 0, 0,
  120900. NULL,
  120901. NULL,
  120902. NULL,
  120903. NULL,
  120904. 0
  120905. };
  120906. static long _huff_lengthlist_line_128x17_3sub3[] = {
  120907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120910. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 4, 7, 5, 8, 5,11,
  120911. 6,10, 6,12, 7,12, 7,12, 8,12, 8,12,10,12,12,12,
  120912. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  120913. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  120914. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  120915. };
  120916. static static_codebook _huff_book_line_128x17_3sub3 = {
  120917. 1, 128,
  120918. _huff_lengthlist_line_128x17_3sub3,
  120919. 0, 0, 0, 0, 0,
  120920. NULL,
  120921. NULL,
  120922. NULL,
  120923. NULL,
  120924. 0
  120925. };
  120926. static long _huff_lengthlist_line_1024x27_class1[] = {
  120927. 2,10, 8,14, 7,12,11,14, 1, 5, 3, 7, 4, 9, 7,13,
  120928. };
  120929. static static_codebook _huff_book_line_1024x27_class1 = {
  120930. 1, 16,
  120931. _huff_lengthlist_line_1024x27_class1,
  120932. 0, 0, 0, 0, 0,
  120933. NULL,
  120934. NULL,
  120935. NULL,
  120936. NULL,
  120937. 0
  120938. };
  120939. static long _huff_lengthlist_line_1024x27_class2[] = {
  120940. 1, 4, 2, 6, 3, 7, 5, 7,
  120941. };
  120942. static static_codebook _huff_book_line_1024x27_class2 = {
  120943. 1, 8,
  120944. _huff_lengthlist_line_1024x27_class2,
  120945. 0, 0, 0, 0, 0,
  120946. NULL,
  120947. NULL,
  120948. NULL,
  120949. NULL,
  120950. 0
  120951. };
  120952. static long _huff_lengthlist_line_1024x27_class3[] = {
  120953. 1, 5, 7,21, 5, 8, 9,21,10, 9,12,20,20,16,20,20,
  120954. 4, 8, 9,20, 6, 8, 9,20,11,11,13,20,20,15,17,20,
  120955. 9,11,14,20, 8,10,15,20,11,13,15,20,20,20,20,20,
  120956. 20,20,20,20,13,20,20,20,18,18,20,20,20,20,20,20,
  120957. 3, 6, 8,20, 6, 7, 9,20,10, 9,12,20,20,20,20,20,
  120958. 5, 7, 9,20, 6, 6, 9,20,10, 9,12,20,20,20,20,20,
  120959. 8,10,13,20, 8, 9,12,20,11,10,12,20,20,20,20,20,
  120960. 18,20,20,20,15,17,18,20,18,17,18,20,20,20,20,20,
  120961. 7,10,12,20, 8, 9,11,20,14,13,14,20,20,20,20,20,
  120962. 6, 9,12,20, 7, 8,11,20,12,11,13,20,20,20,20,20,
  120963. 9,11,15,20, 8,10,14,20,12,11,14,20,20,20,20,20,
  120964. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  120965. 11,16,18,20,15,15,17,20,20,17,20,20,20,20,20,20,
  120966. 9,14,16,20,12,12,15,20,17,15,18,20,20,20,20,20,
  120967. 16,19,18,20,15,16,20,20,17,17,20,20,20,20,20,20,
  120968. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  120969. };
  120970. static static_codebook _huff_book_line_1024x27_class3 = {
  120971. 1, 256,
  120972. _huff_lengthlist_line_1024x27_class3,
  120973. 0, 0, 0, 0, 0,
  120974. NULL,
  120975. NULL,
  120976. NULL,
  120977. NULL,
  120978. 0
  120979. };
  120980. static long _huff_lengthlist_line_1024x27_class4[] = {
  120981. 2, 3, 7,13, 4, 4, 7,15, 8, 6, 9,17,21,16,15,21,
  120982. 2, 5, 7,11, 5, 5, 7,14, 9, 7,10,16,17,15,16,21,
  120983. 4, 7,10,17, 7, 7, 9,15,11, 9,11,16,21,18,15,21,
  120984. 18,21,21,21,15,17,17,19,21,19,18,20,21,21,21,20,
  120985. };
  120986. static static_codebook _huff_book_line_1024x27_class4 = {
  120987. 1, 64,
  120988. _huff_lengthlist_line_1024x27_class4,
  120989. 0, 0, 0, 0, 0,
  120990. NULL,
  120991. NULL,
  120992. NULL,
  120993. NULL,
  120994. 0
  120995. };
  120996. static long _huff_lengthlist_line_1024x27_0sub0[] = {
  120997. 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  120998. 6, 5, 6, 5, 6, 5, 6, 5, 7, 5, 7, 5, 7, 5, 7, 5,
  120999. 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,10, 6,10, 6,11, 6,
  121000. 11, 7,11, 7,12, 7,12, 7,12, 7,12, 7,12, 7,12, 7,
  121001. 12, 7,12, 8,13, 8,12, 8,12, 8,13, 8,13, 9,13, 9,
  121002. 13, 9,13, 9,12,10,12,10,13,10,14,11,14,12,14,13,
  121003. 14,13,14,14,15,16,15,15,15,14,15,17,21,22,22,21,
  121004. 22,22,22,22,22,22,21,21,21,21,21,21,21,21,21,21,
  121005. };
  121006. static static_codebook _huff_book_line_1024x27_0sub0 = {
  121007. 1, 128,
  121008. _huff_lengthlist_line_1024x27_0sub0,
  121009. 0, 0, 0, 0, 0,
  121010. NULL,
  121011. NULL,
  121012. NULL,
  121013. NULL,
  121014. 0
  121015. };
  121016. static long _huff_lengthlist_line_1024x27_1sub0[] = {
  121017. 2, 5, 5, 4, 5, 4, 5, 4, 5, 4, 6, 5, 6, 5, 6, 5,
  121018. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,
  121019. };
  121020. static static_codebook _huff_book_line_1024x27_1sub0 = {
  121021. 1, 32,
  121022. _huff_lengthlist_line_1024x27_1sub0,
  121023. 0, 0, 0, 0, 0,
  121024. NULL,
  121025. NULL,
  121026. NULL,
  121027. NULL,
  121028. 0
  121029. };
  121030. static long _huff_lengthlist_line_1024x27_1sub1[] = {
  121031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121033. 8, 5, 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4,
  121034. 9, 4, 9, 4, 9, 4, 8, 4, 8, 4, 9, 5, 9, 5, 9, 5,
  121035. 9, 5, 9, 6,10, 6,10, 7,10, 8,11, 9,11,11,12,13,
  121036. 12,14,13,15,13,15,14,16,14,17,15,17,15,15,16,16,
  121037. 15,16,16,16,15,18,16,15,17,17,19,19,19,19,19,19,
  121038. 19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,
  121039. };
  121040. static static_codebook _huff_book_line_1024x27_1sub1 = {
  121041. 1, 128,
  121042. _huff_lengthlist_line_1024x27_1sub1,
  121043. 0, 0, 0, 0, 0,
  121044. NULL,
  121045. NULL,
  121046. NULL,
  121047. NULL,
  121048. 0
  121049. };
  121050. static long _huff_lengthlist_line_1024x27_2sub0[] = {
  121051. 1, 5, 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121052. 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 9, 8,10, 9,10, 9,
  121053. };
  121054. static static_codebook _huff_book_line_1024x27_2sub0 = {
  121055. 1, 32,
  121056. _huff_lengthlist_line_1024x27_2sub0,
  121057. 0, 0, 0, 0, 0,
  121058. NULL,
  121059. NULL,
  121060. NULL,
  121061. NULL,
  121062. 0
  121063. };
  121064. static long _huff_lengthlist_line_1024x27_2sub1[] = {
  121065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121067. 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 5, 5, 6, 5, 6, 5,
  121068. 7, 5, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 9, 8, 9, 9,
  121069. 9, 9,10,10,10,11, 9,12, 9,12, 9,15,10,14, 9,13,
  121070. 10,13,10,12,10,12,10,13,10,12,11,13,11,14,12,13,
  121071. 13,14,14,13,14,15,14,16,13,13,14,16,16,16,16,16,
  121072. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,15,15,
  121073. };
  121074. static static_codebook _huff_book_line_1024x27_2sub1 = {
  121075. 1, 128,
  121076. _huff_lengthlist_line_1024x27_2sub1,
  121077. 0, 0, 0, 0, 0,
  121078. NULL,
  121079. NULL,
  121080. NULL,
  121081. NULL,
  121082. 0
  121083. };
  121084. static long _huff_lengthlist_line_1024x27_3sub1[] = {
  121085. 0, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4, 4, 5,
  121086. 5, 5,
  121087. };
  121088. static static_codebook _huff_book_line_1024x27_3sub1 = {
  121089. 1, 18,
  121090. _huff_lengthlist_line_1024x27_3sub1,
  121091. 0, 0, 0, 0, 0,
  121092. NULL,
  121093. NULL,
  121094. NULL,
  121095. NULL,
  121096. 0
  121097. };
  121098. static long _huff_lengthlist_line_1024x27_3sub2[] = {
  121099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121100. 0, 0, 3, 3, 4, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6,
  121101. 5, 7, 5, 8, 6, 8, 6, 9, 7,10, 7,10, 8,10, 8,11,
  121102. 9,11,
  121103. };
  121104. static static_codebook _huff_book_line_1024x27_3sub2 = {
  121105. 1, 50,
  121106. _huff_lengthlist_line_1024x27_3sub2,
  121107. 0, 0, 0, 0, 0,
  121108. NULL,
  121109. NULL,
  121110. NULL,
  121111. NULL,
  121112. 0
  121113. };
  121114. static long _huff_lengthlist_line_1024x27_3sub3[] = {
  121115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121118. 0, 0, 3, 7, 3, 8, 3,10, 3, 8, 3, 9, 3, 8, 4, 9,
  121119. 4, 9, 5, 9, 6,10, 6, 9, 7,11, 7,12, 9,13,10,13,
  121120. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121121. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121122. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121123. };
  121124. static static_codebook _huff_book_line_1024x27_3sub3 = {
  121125. 1, 128,
  121126. _huff_lengthlist_line_1024x27_3sub3,
  121127. 0, 0, 0, 0, 0,
  121128. NULL,
  121129. NULL,
  121130. NULL,
  121131. NULL,
  121132. 0
  121133. };
  121134. static long _huff_lengthlist_line_1024x27_4sub1[] = {
  121135. 0, 4, 5, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4,
  121136. 5, 4,
  121137. };
  121138. static static_codebook _huff_book_line_1024x27_4sub1 = {
  121139. 1, 18,
  121140. _huff_lengthlist_line_1024x27_4sub1,
  121141. 0, 0, 0, 0, 0,
  121142. NULL,
  121143. NULL,
  121144. NULL,
  121145. NULL,
  121146. 0
  121147. };
  121148. static long _huff_lengthlist_line_1024x27_4sub2[] = {
  121149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121150. 0, 0, 4, 2, 4, 2, 5, 3, 5, 4, 6, 6, 6, 7, 7, 8,
  121151. 7, 8, 7, 8, 7, 9, 8, 9, 8, 9, 8,10, 8,11, 9,12,
  121152. 9,12,
  121153. };
  121154. static static_codebook _huff_book_line_1024x27_4sub2 = {
  121155. 1, 50,
  121156. _huff_lengthlist_line_1024x27_4sub2,
  121157. 0, 0, 0, 0, 0,
  121158. NULL,
  121159. NULL,
  121160. NULL,
  121161. NULL,
  121162. 0
  121163. };
  121164. static long _huff_lengthlist_line_1024x27_4sub3[] = {
  121165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121168. 0, 0, 2, 5, 2, 6, 3, 6, 4, 7, 4, 7, 5, 9, 5,11,
  121169. 6,11, 6,11, 7,11, 6,11, 6,11, 9,11, 8,11,11,11,
  121170. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121171. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121172. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  121173. };
  121174. static static_codebook _huff_book_line_1024x27_4sub3 = {
  121175. 1, 128,
  121176. _huff_lengthlist_line_1024x27_4sub3,
  121177. 0, 0, 0, 0, 0,
  121178. NULL,
  121179. NULL,
  121180. NULL,
  121181. NULL,
  121182. 0
  121183. };
  121184. static long _huff_lengthlist_line_2048x27_class1[] = {
  121185. 2, 6, 8, 9, 7,11,13,13, 1, 3, 5, 5, 6, 6,12,10,
  121186. };
  121187. static static_codebook _huff_book_line_2048x27_class1 = {
  121188. 1, 16,
  121189. _huff_lengthlist_line_2048x27_class1,
  121190. 0, 0, 0, 0, 0,
  121191. NULL,
  121192. NULL,
  121193. NULL,
  121194. NULL,
  121195. 0
  121196. };
  121197. static long _huff_lengthlist_line_2048x27_class2[] = {
  121198. 1, 2, 3, 6, 4, 7, 5, 7,
  121199. };
  121200. static static_codebook _huff_book_line_2048x27_class2 = {
  121201. 1, 8,
  121202. _huff_lengthlist_line_2048x27_class2,
  121203. 0, 0, 0, 0, 0,
  121204. NULL,
  121205. NULL,
  121206. NULL,
  121207. NULL,
  121208. 0
  121209. };
  121210. static long _huff_lengthlist_line_2048x27_class3[] = {
  121211. 3, 3, 6,16, 5, 5, 7,16, 9, 8,11,16,16,16,16,16,
  121212. 5, 5, 8,16, 5, 5, 7,16, 8, 7, 9,16,16,16,16,16,
  121213. 9, 9,12,16, 6, 8,11,16, 9,10,11,16,16,16,16,16,
  121214. 16,16,16,16,13,16,16,16,15,16,16,16,16,16,16,16,
  121215. 5, 4, 7,16, 6, 5, 8,16, 9, 8,10,16,16,16,16,16,
  121216. 5, 5, 7,15, 5, 4, 6,15, 7, 6, 8,16,16,16,16,16,
  121217. 9, 9,11,15, 7, 7, 9,16, 8, 8, 9,16,16,16,16,16,
  121218. 16,16,16,16,15,15,15,16,15,15,14,16,16,16,16,16,
  121219. 8, 8,11,16, 8, 9,10,16,11,10,14,16,16,16,16,16,
  121220. 6, 8,10,16, 6, 7,10,16, 8, 8,11,16,14,16,16,16,
  121221. 10,11,14,16, 9, 9,11,16,10,10,11,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,15,16,16,16,16,16,16,16,16,16,16,16,
  121224. 12,16,15,16,12,14,16,16,16,16,16,16,16,16,16,16,
  121225. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  121226. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  121227. };
  121228. static static_codebook _huff_book_line_2048x27_class3 = {
  121229. 1, 256,
  121230. _huff_lengthlist_line_2048x27_class3,
  121231. 0, 0, 0, 0, 0,
  121232. NULL,
  121233. NULL,
  121234. NULL,
  121235. NULL,
  121236. 0
  121237. };
  121238. static long _huff_lengthlist_line_2048x27_class4[] = {
  121239. 2, 4, 7,13, 4, 5, 7,15, 8, 7,10,16,16,14,16,16,
  121240. 2, 4, 7,16, 3, 4, 7,14, 8, 8,10,16,16,16,15,16,
  121241. 6, 8,11,16, 7, 7, 9,16,11, 9,13,16,16,16,15,16,
  121242. 16,16,16,16,14,16,16,16,16,16,16,16,16,16,16,16,
  121243. };
  121244. static static_codebook _huff_book_line_2048x27_class4 = {
  121245. 1, 64,
  121246. _huff_lengthlist_line_2048x27_class4,
  121247. 0, 0, 0, 0, 0,
  121248. NULL,
  121249. NULL,
  121250. NULL,
  121251. NULL,
  121252. 0
  121253. };
  121254. static long _huff_lengthlist_line_2048x27_0sub0[] = {
  121255. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121256. 6, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5, 8, 5, 9, 5,
  121257. 9, 6,10, 6,10, 6,11, 6,11, 6,11, 6,11, 6,11, 6,
  121258. 11, 6,11, 6,12, 7,11, 7,11, 7,11, 7,11, 7,10, 7,
  121259. 11, 7,11, 7,12, 7,11, 8,11, 8,11, 8,11, 8,13, 8,
  121260. 12, 9,11, 9,11, 9,11,10,12,10,12, 9,12,10,12,11,
  121261. 14,12,16,12,12,11,14,16,17,17,17,17,17,17,17,17,
  121262. 17,17,17,17,17,17,17,17,17,17,17,17,16,16,16,16,
  121263. };
  121264. static static_codebook _huff_book_line_2048x27_0sub0 = {
  121265. 1, 128,
  121266. _huff_lengthlist_line_2048x27_0sub0,
  121267. 0, 0, 0, 0, 0,
  121268. NULL,
  121269. NULL,
  121270. NULL,
  121271. NULL,
  121272. 0
  121273. };
  121274. static long _huff_lengthlist_line_2048x27_1sub0[] = {
  121275. 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  121276. 5, 5, 6, 6, 6, 6, 6, 6, 7, 6, 7, 6, 7, 6, 7, 6,
  121277. };
  121278. static static_codebook _huff_book_line_2048x27_1sub0 = {
  121279. 1, 32,
  121280. _huff_lengthlist_line_2048x27_1sub0,
  121281. 0, 0, 0, 0, 0,
  121282. NULL,
  121283. NULL,
  121284. NULL,
  121285. NULL,
  121286. 0
  121287. };
  121288. static long _huff_lengthlist_line_2048x27_1sub1[] = {
  121289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121291. 6, 5, 7, 5, 7, 4, 7, 4, 8, 4, 8, 4, 8, 4, 8, 3,
  121292. 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 5, 9, 5, 9, 6,
  121293. 9, 7, 9, 8, 9, 9, 9,10, 9,11, 9,14, 9,15,10,15,
  121294. 10,15,10,15,10,15,11,15,10,14,12,14,11,14,13,14,
  121295. 13,15,15,15,12,15,15,15,13,15,13,15,13,15,15,15,
  121296. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,14,
  121297. };
  121298. static static_codebook _huff_book_line_2048x27_1sub1 = {
  121299. 1, 128,
  121300. _huff_lengthlist_line_2048x27_1sub1,
  121301. 0, 0, 0, 0, 0,
  121302. NULL,
  121303. NULL,
  121304. NULL,
  121305. NULL,
  121306. 0
  121307. };
  121308. static long _huff_lengthlist_line_2048x27_2sub0[] = {
  121309. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  121310. 6, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  121311. };
  121312. static static_codebook _huff_book_line_2048x27_2sub0 = {
  121313. 1, 32,
  121314. _huff_lengthlist_line_2048x27_2sub0,
  121315. 0, 0, 0, 0, 0,
  121316. NULL,
  121317. NULL,
  121318. NULL,
  121319. NULL,
  121320. 0
  121321. };
  121322. static long _huff_lengthlist_line_2048x27_2sub1[] = {
  121323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121325. 3, 4, 3, 4, 3, 4, 4, 5, 4, 5, 5, 5, 6, 6, 6, 7,
  121326. 6, 8, 6, 8, 6, 9, 7,10, 7,10, 7,10, 7,12, 7,12,
  121327. 7,12, 9,12,11,12,10,12,10,12,11,12,12,12,10,12,
  121328. 10,12,10,12, 9,12,11,12,12,12,12,12,11,12,11,12,
  121329. 12,12,12,12,12,12,12,12,10,10,12,12,12,12,12,10,
  121330. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121331. };
  121332. static static_codebook _huff_book_line_2048x27_2sub1 = {
  121333. 1, 128,
  121334. _huff_lengthlist_line_2048x27_2sub1,
  121335. 0, 0, 0, 0, 0,
  121336. NULL,
  121337. NULL,
  121338. NULL,
  121339. NULL,
  121340. 0
  121341. };
  121342. static long _huff_lengthlist_line_2048x27_3sub1[] = {
  121343. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  121344. 5, 5,
  121345. };
  121346. static static_codebook _huff_book_line_2048x27_3sub1 = {
  121347. 1, 18,
  121348. _huff_lengthlist_line_2048x27_3sub1,
  121349. 0, 0, 0, 0, 0,
  121350. NULL,
  121351. NULL,
  121352. NULL,
  121353. NULL,
  121354. 0
  121355. };
  121356. static long _huff_lengthlist_line_2048x27_3sub2[] = {
  121357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121358. 0, 0, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6,
  121359. 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7, 9, 9,11, 9,12,
  121360. 10,12,
  121361. };
  121362. static static_codebook _huff_book_line_2048x27_3sub2 = {
  121363. 1, 50,
  121364. _huff_lengthlist_line_2048x27_3sub2,
  121365. 0, 0, 0, 0, 0,
  121366. NULL,
  121367. NULL,
  121368. NULL,
  121369. NULL,
  121370. 0
  121371. };
  121372. static long _huff_lengthlist_line_2048x27_3sub3[] = {
  121373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121376. 0, 0, 3, 6, 3, 7, 3, 7, 5, 7, 7, 7, 7, 7, 6, 7,
  121377. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121378. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121379. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121380. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121381. };
  121382. static static_codebook _huff_book_line_2048x27_3sub3 = {
  121383. 1, 128,
  121384. _huff_lengthlist_line_2048x27_3sub3,
  121385. 0, 0, 0, 0, 0,
  121386. NULL,
  121387. NULL,
  121388. NULL,
  121389. NULL,
  121390. 0
  121391. };
  121392. static long _huff_lengthlist_line_2048x27_4sub1[] = {
  121393. 0, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4, 5, 4, 5, 4,
  121394. 4, 5,
  121395. };
  121396. static static_codebook _huff_book_line_2048x27_4sub1 = {
  121397. 1, 18,
  121398. _huff_lengthlist_line_2048x27_4sub1,
  121399. 0, 0, 0, 0, 0,
  121400. NULL,
  121401. NULL,
  121402. NULL,
  121403. NULL,
  121404. 0
  121405. };
  121406. static long _huff_lengthlist_line_2048x27_4sub2[] = {
  121407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121408. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 5, 6, 5, 6, 5, 7,
  121409. 6, 6, 6, 7, 7, 7, 8, 9, 9, 9,12,10,11,10,10,12,
  121410. 10,10,
  121411. };
  121412. static static_codebook _huff_book_line_2048x27_4sub2 = {
  121413. 1, 50,
  121414. _huff_lengthlist_line_2048x27_4sub2,
  121415. 0, 0, 0, 0, 0,
  121416. NULL,
  121417. NULL,
  121418. NULL,
  121419. NULL,
  121420. 0
  121421. };
  121422. static long _huff_lengthlist_line_2048x27_4sub3[] = {
  121423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121426. 0, 0, 3, 6, 5, 7, 5, 7, 7, 7, 7, 7, 5, 7, 5, 7,
  121427. 5, 7, 5, 7, 7, 7, 7, 7, 4, 7, 7, 7, 7, 7, 7, 7,
  121428. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121429. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121430. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121431. };
  121432. static static_codebook _huff_book_line_2048x27_4sub3 = {
  121433. 1, 128,
  121434. _huff_lengthlist_line_2048x27_4sub3,
  121435. 0, 0, 0, 0, 0,
  121436. NULL,
  121437. NULL,
  121438. NULL,
  121439. NULL,
  121440. 0
  121441. };
  121442. static long _huff_lengthlist_line_256x4low_class0[] = {
  121443. 4, 5, 6,11, 5, 5, 6,10, 7, 7, 6, 6,14,13, 9, 9,
  121444. 6, 6, 6,10, 6, 6, 6, 9, 8, 7, 7, 9,14,12, 8,11,
  121445. 8, 7, 7,11, 8, 8, 7,11, 9, 9, 7, 9,13,11, 9,13,
  121446. 19,19,18,19,15,16,16,19,11,11,10,13,10,10, 9,15,
  121447. 5, 5, 6,13, 6, 6, 6,11, 8, 7, 6, 7,14,11,10,11,
  121448. 6, 6, 6,12, 7, 6, 6,11, 8, 7, 7,11,13,11, 9,11,
  121449. 9, 7, 6,12, 8, 7, 6,12, 9, 8, 8,11,13,10, 7,13,
  121450. 19,19,17,19,17,14,14,19,12,10, 8,12,13,10, 9,16,
  121451. 7, 8, 7,12, 7, 7, 7,11, 8, 7, 7, 8,12,12,11,11,
  121452. 8, 8, 7,12, 8, 7, 6,11, 8, 7, 7,10,10,11,10,11,
  121453. 9, 8, 8,13, 9, 8, 7,12,10, 9, 7,11, 9, 8, 7,11,
  121454. 18,18,15,18,18,16,17,18,15,11,10,18,11, 9, 9,18,
  121455. 16,16,13,16,12,11,10,16,12,11, 9, 6,15,12,11,13,
  121456. 16,16,14,14,13,11,12,16,12, 9, 9,13,13,10,10,12,
  121457. 17,18,17,17,14,15,14,16,14,12,14,15,12,10,11,12,
  121458. 18,18,18,18,18,18,18,18,18,12,13,18,16,11, 9,18,
  121459. };
  121460. static static_codebook _huff_book_line_256x4low_class0 = {
  121461. 1, 256,
  121462. _huff_lengthlist_line_256x4low_class0,
  121463. 0, 0, 0, 0, 0,
  121464. NULL,
  121465. NULL,
  121466. NULL,
  121467. NULL,
  121468. 0
  121469. };
  121470. static long _huff_lengthlist_line_256x4low_0sub0[] = {
  121471. 1, 3, 2, 3,
  121472. };
  121473. static static_codebook _huff_book_line_256x4low_0sub0 = {
  121474. 1, 4,
  121475. _huff_lengthlist_line_256x4low_0sub0,
  121476. 0, 0, 0, 0, 0,
  121477. NULL,
  121478. NULL,
  121479. NULL,
  121480. NULL,
  121481. 0
  121482. };
  121483. static long _huff_lengthlist_line_256x4low_0sub1[] = {
  121484. 0, 0, 0, 0, 2, 3, 2, 3, 3, 3,
  121485. };
  121486. static static_codebook _huff_book_line_256x4low_0sub1 = {
  121487. 1, 10,
  121488. _huff_lengthlist_line_256x4low_0sub1,
  121489. 0, 0, 0, 0, 0,
  121490. NULL,
  121491. NULL,
  121492. NULL,
  121493. NULL,
  121494. 0
  121495. };
  121496. static long _huff_lengthlist_line_256x4low_0sub2[] = {
  121497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 3, 4,
  121498. 4, 4, 4, 4, 5, 5, 5, 6, 6,
  121499. };
  121500. static static_codebook _huff_book_line_256x4low_0sub2 = {
  121501. 1, 25,
  121502. _huff_lengthlist_line_256x4low_0sub2,
  121503. 0, 0, 0, 0, 0,
  121504. NULL,
  121505. NULL,
  121506. NULL,
  121507. NULL,
  121508. 0
  121509. };
  121510. static long _huff_lengthlist_line_256x4low_0sub3[] = {
  121511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 2, 4, 3, 5, 4,
  121513. 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 7, 8, 6, 9,
  121514. 7,12,11,16,13,16,12,15,13,15,12,14,12,15,15,15,
  121515. };
  121516. static static_codebook _huff_book_line_256x4low_0sub3 = {
  121517. 1, 64,
  121518. _huff_lengthlist_line_256x4low_0sub3,
  121519. 0, 0, 0, 0, 0,
  121520. NULL,
  121521. NULL,
  121522. NULL,
  121523. NULL,
  121524. 0
  121525. };
  121526. /*** End of inlined file: floor_books.h ***/
  121527. static static_codebook *_floor_128x4_books[]={
  121528. &_huff_book_line_128x4_class0,
  121529. &_huff_book_line_128x4_0sub0,
  121530. &_huff_book_line_128x4_0sub1,
  121531. &_huff_book_line_128x4_0sub2,
  121532. &_huff_book_line_128x4_0sub3,
  121533. };
  121534. static static_codebook *_floor_256x4_books[]={
  121535. &_huff_book_line_256x4_class0,
  121536. &_huff_book_line_256x4_0sub0,
  121537. &_huff_book_line_256x4_0sub1,
  121538. &_huff_book_line_256x4_0sub2,
  121539. &_huff_book_line_256x4_0sub3,
  121540. };
  121541. static static_codebook *_floor_128x7_books[]={
  121542. &_huff_book_line_128x7_class0,
  121543. &_huff_book_line_128x7_class1,
  121544. &_huff_book_line_128x7_0sub1,
  121545. &_huff_book_line_128x7_0sub2,
  121546. &_huff_book_line_128x7_0sub3,
  121547. &_huff_book_line_128x7_1sub1,
  121548. &_huff_book_line_128x7_1sub2,
  121549. &_huff_book_line_128x7_1sub3,
  121550. };
  121551. static static_codebook *_floor_256x7_books[]={
  121552. &_huff_book_line_256x7_class0,
  121553. &_huff_book_line_256x7_class1,
  121554. &_huff_book_line_256x7_0sub1,
  121555. &_huff_book_line_256x7_0sub2,
  121556. &_huff_book_line_256x7_0sub3,
  121557. &_huff_book_line_256x7_1sub1,
  121558. &_huff_book_line_256x7_1sub2,
  121559. &_huff_book_line_256x7_1sub3,
  121560. };
  121561. static static_codebook *_floor_128x11_books[]={
  121562. &_huff_book_line_128x11_class1,
  121563. &_huff_book_line_128x11_class2,
  121564. &_huff_book_line_128x11_class3,
  121565. &_huff_book_line_128x11_0sub0,
  121566. &_huff_book_line_128x11_1sub0,
  121567. &_huff_book_line_128x11_1sub1,
  121568. &_huff_book_line_128x11_2sub1,
  121569. &_huff_book_line_128x11_2sub2,
  121570. &_huff_book_line_128x11_2sub3,
  121571. &_huff_book_line_128x11_3sub1,
  121572. &_huff_book_line_128x11_3sub2,
  121573. &_huff_book_line_128x11_3sub3,
  121574. };
  121575. static static_codebook *_floor_128x17_books[]={
  121576. &_huff_book_line_128x17_class1,
  121577. &_huff_book_line_128x17_class2,
  121578. &_huff_book_line_128x17_class3,
  121579. &_huff_book_line_128x17_0sub0,
  121580. &_huff_book_line_128x17_1sub0,
  121581. &_huff_book_line_128x17_1sub1,
  121582. &_huff_book_line_128x17_2sub1,
  121583. &_huff_book_line_128x17_2sub2,
  121584. &_huff_book_line_128x17_2sub3,
  121585. &_huff_book_line_128x17_3sub1,
  121586. &_huff_book_line_128x17_3sub2,
  121587. &_huff_book_line_128x17_3sub3,
  121588. };
  121589. static static_codebook *_floor_256x4low_books[]={
  121590. &_huff_book_line_256x4low_class0,
  121591. &_huff_book_line_256x4low_0sub0,
  121592. &_huff_book_line_256x4low_0sub1,
  121593. &_huff_book_line_256x4low_0sub2,
  121594. &_huff_book_line_256x4low_0sub3,
  121595. };
  121596. static static_codebook *_floor_1024x27_books[]={
  121597. &_huff_book_line_1024x27_class1,
  121598. &_huff_book_line_1024x27_class2,
  121599. &_huff_book_line_1024x27_class3,
  121600. &_huff_book_line_1024x27_class4,
  121601. &_huff_book_line_1024x27_0sub0,
  121602. &_huff_book_line_1024x27_1sub0,
  121603. &_huff_book_line_1024x27_1sub1,
  121604. &_huff_book_line_1024x27_2sub0,
  121605. &_huff_book_line_1024x27_2sub1,
  121606. &_huff_book_line_1024x27_3sub1,
  121607. &_huff_book_line_1024x27_3sub2,
  121608. &_huff_book_line_1024x27_3sub3,
  121609. &_huff_book_line_1024x27_4sub1,
  121610. &_huff_book_line_1024x27_4sub2,
  121611. &_huff_book_line_1024x27_4sub3,
  121612. };
  121613. static static_codebook *_floor_2048x27_books[]={
  121614. &_huff_book_line_2048x27_class1,
  121615. &_huff_book_line_2048x27_class2,
  121616. &_huff_book_line_2048x27_class3,
  121617. &_huff_book_line_2048x27_class4,
  121618. &_huff_book_line_2048x27_0sub0,
  121619. &_huff_book_line_2048x27_1sub0,
  121620. &_huff_book_line_2048x27_1sub1,
  121621. &_huff_book_line_2048x27_2sub0,
  121622. &_huff_book_line_2048x27_2sub1,
  121623. &_huff_book_line_2048x27_3sub1,
  121624. &_huff_book_line_2048x27_3sub2,
  121625. &_huff_book_line_2048x27_3sub3,
  121626. &_huff_book_line_2048x27_4sub1,
  121627. &_huff_book_line_2048x27_4sub2,
  121628. &_huff_book_line_2048x27_4sub3,
  121629. };
  121630. static static_codebook *_floor_512x17_books[]={
  121631. &_huff_book_line_512x17_class1,
  121632. &_huff_book_line_512x17_class2,
  121633. &_huff_book_line_512x17_class3,
  121634. &_huff_book_line_512x17_0sub0,
  121635. &_huff_book_line_512x17_1sub0,
  121636. &_huff_book_line_512x17_1sub1,
  121637. &_huff_book_line_512x17_2sub1,
  121638. &_huff_book_line_512x17_2sub2,
  121639. &_huff_book_line_512x17_2sub3,
  121640. &_huff_book_line_512x17_3sub1,
  121641. &_huff_book_line_512x17_3sub2,
  121642. &_huff_book_line_512x17_3sub3,
  121643. };
  121644. static static_codebook **_floor_books[10]={
  121645. _floor_128x4_books,
  121646. _floor_256x4_books,
  121647. _floor_128x7_books,
  121648. _floor_256x7_books,
  121649. _floor_128x11_books,
  121650. _floor_128x17_books,
  121651. _floor_256x4low_books,
  121652. _floor_1024x27_books,
  121653. _floor_2048x27_books,
  121654. _floor_512x17_books,
  121655. };
  121656. static vorbis_info_floor1 _floor[10]={
  121657. /* 128 x 4 */
  121658. {
  121659. 1,{0},{4},{2},{0},
  121660. {{1,2,3,4}},
  121661. 4,{0,128, 33,8,16,70},
  121662. 60,30,500, 1.,18., -1
  121663. },
  121664. /* 256 x 4 */
  121665. {
  121666. 1,{0},{4},{2},{0},
  121667. {{1,2,3,4}},
  121668. 4,{0,256, 66,16,32,140},
  121669. 60,30,500, 1.,18., -1
  121670. },
  121671. /* 128 x 7 */
  121672. {
  121673. 2,{0,1},{3,4},{2,2},{0,1},
  121674. {{-1,2,3,4},{-1,5,6,7}},
  121675. 4,{0,128, 14,4,58, 2,8,28,90},
  121676. 60,30,500, 1.,18., -1
  121677. },
  121678. /* 256 x 7 */
  121679. {
  121680. 2,{0,1},{3,4},{2,2},{0,1},
  121681. {{-1,2,3,4},{-1,5,6,7}},
  121682. 4,{0,256, 28,8,116, 4,16,56,180},
  121683. 60,30,500, 1.,18., -1
  121684. },
  121685. /* 128 x 11 */
  121686. {
  121687. 4,{0,1,2,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  121688. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  121689. 2,{0,128, 8,33, 4,16,70, 2,6,12, 23,46,90},
  121690. 60,30,500, 1,18., -1
  121691. },
  121692. /* 128 x 17 */
  121693. {
  121694. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  121695. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  121696. 2,{0,128, 12,46, 4,8,16, 23,33,70, 2,6,10, 14,19,28, 39,58,90},
  121697. 60,30,500, 1,18., -1
  121698. },
  121699. /* 256 x 4 (low bitrate version) */
  121700. {
  121701. 1,{0},{4},{2},{0},
  121702. {{1,2,3,4}},
  121703. 4,{0,256, 66,16,32,140},
  121704. 60,30,500, 1.,18., -1
  121705. },
  121706. /* 1024 x 27 */
  121707. {
  121708. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  121709. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  121710. 2,{0,1024, 93,23,372, 6,46,186,750, 14,33,65, 130,260,556,
  121711. 3,10,18,28, 39,55,79,111, 158,220,312, 464,650,850},
  121712. 60,30,500, 3,18., -1 /* lowpass */
  121713. },
  121714. /* 2048 x 27 */
  121715. {
  121716. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  121717. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  121718. 2,{0,2048, 186,46,744, 12,92,372,1500, 28,66,130, 260,520,1112,
  121719. 6,20,36,56, 78,110,158,222, 316,440,624, 928,1300,1700},
  121720. 60,30,500, 3,18., -1 /* lowpass */
  121721. },
  121722. /* 512 x 17 */
  121723. {
  121724. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  121725. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  121726. 2,{0,512, 46,186, 16,33,65, 93,130,278,
  121727. 7,23,39, 55,79,110, 156,232,360},
  121728. 60,30,500, 1,18., -1 /* lowpass! */
  121729. },
  121730. };
  121731. /*** End of inlined file: floor_all.h ***/
  121732. /*** Start of inlined file: residue_44.h ***/
  121733. /*** Start of inlined file: res_books_stereo.h ***/
  121734. static long _vq_quantlist__16c0_s_p1_0[] = {
  121735. 1,
  121736. 0,
  121737. 2,
  121738. };
  121739. static long _vq_lengthlist__16c0_s_p1_0[] = {
  121740. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  121741. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121743. 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0,
  121746. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121748. 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  121751. 0, 0, 0, 0, 7, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0,
  121783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  121786. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  121787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7,10,10, 0, 0, 0,
  121791. 0, 0, 0, 9, 9,12, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  121792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 7,10,10, 0, 0,
  121796. 0, 0, 0, 0, 9,12,10, 0, 0, 0, 0, 0, 0,10,11,12,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121829. 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  121832. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121836. 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  121837. 0, 0, 0, 0, 0, 9,10,12, 0, 0, 0, 0, 0, 0, 0, 0,
  121838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,12,
  121842. 0, 0, 0, 0, 0, 0, 9,12, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122150. 0,
  122151. };
  122152. static float _vq_quantthresh__16c0_s_p1_0[] = {
  122153. -0.5, 0.5,
  122154. };
  122155. static long _vq_quantmap__16c0_s_p1_0[] = {
  122156. 1, 0, 2,
  122157. };
  122158. static encode_aux_threshmatch _vq_auxt__16c0_s_p1_0 = {
  122159. _vq_quantthresh__16c0_s_p1_0,
  122160. _vq_quantmap__16c0_s_p1_0,
  122161. 3,
  122162. 3
  122163. };
  122164. static static_codebook _16c0_s_p1_0 = {
  122165. 8, 6561,
  122166. _vq_lengthlist__16c0_s_p1_0,
  122167. 1, -535822336, 1611661312, 2, 0,
  122168. _vq_quantlist__16c0_s_p1_0,
  122169. NULL,
  122170. &_vq_auxt__16c0_s_p1_0,
  122171. NULL,
  122172. 0
  122173. };
  122174. static long _vq_quantlist__16c0_s_p2_0[] = {
  122175. 2,
  122176. 1,
  122177. 3,
  122178. 0,
  122179. 4,
  122180. };
  122181. static long _vq_lengthlist__16c0_s_p2_0[] = {
  122182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122221. 0,
  122222. };
  122223. static float _vq_quantthresh__16c0_s_p2_0[] = {
  122224. -1.5, -0.5, 0.5, 1.5,
  122225. };
  122226. static long _vq_quantmap__16c0_s_p2_0[] = {
  122227. 3, 1, 0, 2, 4,
  122228. };
  122229. static encode_aux_threshmatch _vq_auxt__16c0_s_p2_0 = {
  122230. _vq_quantthresh__16c0_s_p2_0,
  122231. _vq_quantmap__16c0_s_p2_0,
  122232. 5,
  122233. 5
  122234. };
  122235. static static_codebook _16c0_s_p2_0 = {
  122236. 4, 625,
  122237. _vq_lengthlist__16c0_s_p2_0,
  122238. 1, -533725184, 1611661312, 3, 0,
  122239. _vq_quantlist__16c0_s_p2_0,
  122240. NULL,
  122241. &_vq_auxt__16c0_s_p2_0,
  122242. NULL,
  122243. 0
  122244. };
  122245. static long _vq_quantlist__16c0_s_p3_0[] = {
  122246. 2,
  122247. 1,
  122248. 3,
  122249. 0,
  122250. 4,
  122251. };
  122252. static long _vq_lengthlist__16c0_s_p3_0[] = {
  122253. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 7, 6, 0, 0,
  122255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122256. 0, 0, 4, 6, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  122258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122259. 0, 0, 0, 0, 6, 6, 6, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  122260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122292. 0,
  122293. };
  122294. static float _vq_quantthresh__16c0_s_p3_0[] = {
  122295. -1.5, -0.5, 0.5, 1.5,
  122296. };
  122297. static long _vq_quantmap__16c0_s_p3_0[] = {
  122298. 3, 1, 0, 2, 4,
  122299. };
  122300. static encode_aux_threshmatch _vq_auxt__16c0_s_p3_0 = {
  122301. _vq_quantthresh__16c0_s_p3_0,
  122302. _vq_quantmap__16c0_s_p3_0,
  122303. 5,
  122304. 5
  122305. };
  122306. static static_codebook _16c0_s_p3_0 = {
  122307. 4, 625,
  122308. _vq_lengthlist__16c0_s_p3_0,
  122309. 1, -533725184, 1611661312, 3, 0,
  122310. _vq_quantlist__16c0_s_p3_0,
  122311. NULL,
  122312. &_vq_auxt__16c0_s_p3_0,
  122313. NULL,
  122314. 0
  122315. };
  122316. static long _vq_quantlist__16c0_s_p4_0[] = {
  122317. 4,
  122318. 3,
  122319. 5,
  122320. 2,
  122321. 6,
  122322. 1,
  122323. 7,
  122324. 0,
  122325. 8,
  122326. };
  122327. static long _vq_lengthlist__16c0_s_p4_0[] = {
  122328. 1, 3, 2, 7, 8, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  122329. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  122330. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  122331. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  122332. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122333. 0,
  122334. };
  122335. static float _vq_quantthresh__16c0_s_p4_0[] = {
  122336. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  122337. };
  122338. static long _vq_quantmap__16c0_s_p4_0[] = {
  122339. 7, 5, 3, 1, 0, 2, 4, 6,
  122340. 8,
  122341. };
  122342. static encode_aux_threshmatch _vq_auxt__16c0_s_p4_0 = {
  122343. _vq_quantthresh__16c0_s_p4_0,
  122344. _vq_quantmap__16c0_s_p4_0,
  122345. 9,
  122346. 9
  122347. };
  122348. static static_codebook _16c0_s_p4_0 = {
  122349. 2, 81,
  122350. _vq_lengthlist__16c0_s_p4_0,
  122351. 1, -531628032, 1611661312, 4, 0,
  122352. _vq_quantlist__16c0_s_p4_0,
  122353. NULL,
  122354. &_vq_auxt__16c0_s_p4_0,
  122355. NULL,
  122356. 0
  122357. };
  122358. static long _vq_quantlist__16c0_s_p5_0[] = {
  122359. 4,
  122360. 3,
  122361. 5,
  122362. 2,
  122363. 6,
  122364. 1,
  122365. 7,
  122366. 0,
  122367. 8,
  122368. };
  122369. static long _vq_lengthlist__16c0_s_p5_0[] = {
  122370. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  122371. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 8, 0, 0, 0, 7, 7,
  122372. 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0, 0, 0,
  122373. 8, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  122374. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  122375. 10,
  122376. };
  122377. static float _vq_quantthresh__16c0_s_p5_0[] = {
  122378. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  122379. };
  122380. static long _vq_quantmap__16c0_s_p5_0[] = {
  122381. 7, 5, 3, 1, 0, 2, 4, 6,
  122382. 8,
  122383. };
  122384. static encode_aux_threshmatch _vq_auxt__16c0_s_p5_0 = {
  122385. _vq_quantthresh__16c0_s_p5_0,
  122386. _vq_quantmap__16c0_s_p5_0,
  122387. 9,
  122388. 9
  122389. };
  122390. static static_codebook _16c0_s_p5_0 = {
  122391. 2, 81,
  122392. _vq_lengthlist__16c0_s_p5_0,
  122393. 1, -531628032, 1611661312, 4, 0,
  122394. _vq_quantlist__16c0_s_p5_0,
  122395. NULL,
  122396. &_vq_auxt__16c0_s_p5_0,
  122397. NULL,
  122398. 0
  122399. };
  122400. static long _vq_quantlist__16c0_s_p6_0[] = {
  122401. 8,
  122402. 7,
  122403. 9,
  122404. 6,
  122405. 10,
  122406. 5,
  122407. 11,
  122408. 4,
  122409. 12,
  122410. 3,
  122411. 13,
  122412. 2,
  122413. 14,
  122414. 1,
  122415. 15,
  122416. 0,
  122417. 16,
  122418. };
  122419. static long _vq_lengthlist__16c0_s_p6_0[] = {
  122420. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  122421. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  122422. 11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  122423. 11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  122424. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  122425. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  122426. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  122427. 10,11,11,12,12,12,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  122428. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10,10,10,
  122429. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  122430. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  122431. 9,10,10,11,11,12,12,13,13,13,14, 0, 0, 0, 0, 0,
  122432. 10,10,10,11,11,11,12,12,13,13,13,14, 0, 0, 0, 0,
  122433. 0, 0, 0,10,10,11,11,12,12,13,13,14,14, 0, 0, 0,
  122434. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  122435. 0, 0, 0, 0, 0,11,11,12,12,12,13,13,14,15,14, 0,
  122436. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,14,14,15,
  122437. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,13,14,
  122438. 14,
  122439. };
  122440. static float _vq_quantthresh__16c0_s_p6_0[] = {
  122441. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  122442. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  122443. };
  122444. static long _vq_quantmap__16c0_s_p6_0[] = {
  122445. 15, 13, 11, 9, 7, 5, 3, 1,
  122446. 0, 2, 4, 6, 8, 10, 12, 14,
  122447. 16,
  122448. };
  122449. static encode_aux_threshmatch _vq_auxt__16c0_s_p6_0 = {
  122450. _vq_quantthresh__16c0_s_p6_0,
  122451. _vq_quantmap__16c0_s_p6_0,
  122452. 17,
  122453. 17
  122454. };
  122455. static static_codebook _16c0_s_p6_0 = {
  122456. 2, 289,
  122457. _vq_lengthlist__16c0_s_p6_0,
  122458. 1, -529530880, 1611661312, 5, 0,
  122459. _vq_quantlist__16c0_s_p6_0,
  122460. NULL,
  122461. &_vq_auxt__16c0_s_p6_0,
  122462. NULL,
  122463. 0
  122464. };
  122465. static long _vq_quantlist__16c0_s_p7_0[] = {
  122466. 1,
  122467. 0,
  122468. 2,
  122469. };
  122470. static long _vq_lengthlist__16c0_s_p7_0[] = {
  122471. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,11,10,10,11,
  122472. 11,10, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  122473. 11,11,11,10, 6, 9, 9,11,12,12,11, 9, 9, 6, 9,10,
  122474. 11,12,12,11, 9,10, 7,11,11,11,11,11,12,13,12, 6,
  122475. 9,10,11,10,10,12,13,13, 6,10, 9,11,10,10,11,12,
  122476. 13,
  122477. };
  122478. static float _vq_quantthresh__16c0_s_p7_0[] = {
  122479. -5.5, 5.5,
  122480. };
  122481. static long _vq_quantmap__16c0_s_p7_0[] = {
  122482. 1, 0, 2,
  122483. };
  122484. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_0 = {
  122485. _vq_quantthresh__16c0_s_p7_0,
  122486. _vq_quantmap__16c0_s_p7_0,
  122487. 3,
  122488. 3
  122489. };
  122490. static static_codebook _16c0_s_p7_0 = {
  122491. 4, 81,
  122492. _vq_lengthlist__16c0_s_p7_0,
  122493. 1, -529137664, 1618345984, 2, 0,
  122494. _vq_quantlist__16c0_s_p7_0,
  122495. NULL,
  122496. &_vq_auxt__16c0_s_p7_0,
  122497. NULL,
  122498. 0
  122499. };
  122500. static long _vq_quantlist__16c0_s_p7_1[] = {
  122501. 5,
  122502. 4,
  122503. 6,
  122504. 3,
  122505. 7,
  122506. 2,
  122507. 8,
  122508. 1,
  122509. 9,
  122510. 0,
  122511. 10,
  122512. };
  122513. static long _vq_lengthlist__16c0_s_p7_1[] = {
  122514. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7,
  122515. 8, 8, 8, 9, 9, 9,10,10,10, 6, 7, 8, 8, 8, 8, 9,
  122516. 8,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10, 7,
  122517. 7, 8, 8, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9, 9,
  122518. 9, 9,11,11,11, 8, 8, 9, 9, 9, 9, 9,10,10,11,11,
  122519. 9, 9, 9, 9, 9, 9, 9,10,11,11,11,10,11, 9, 9, 9,
  122520. 9,10, 9,11,11,11,10,11,10,10, 9, 9,10,10,11,11,
  122521. 11,11,11, 9, 9, 9, 9,10,10,
  122522. };
  122523. static float _vq_quantthresh__16c0_s_p7_1[] = {
  122524. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  122525. 3.5, 4.5,
  122526. };
  122527. static long _vq_quantmap__16c0_s_p7_1[] = {
  122528. 9, 7, 5, 3, 1, 0, 2, 4,
  122529. 6, 8, 10,
  122530. };
  122531. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_1 = {
  122532. _vq_quantthresh__16c0_s_p7_1,
  122533. _vq_quantmap__16c0_s_p7_1,
  122534. 11,
  122535. 11
  122536. };
  122537. static static_codebook _16c0_s_p7_1 = {
  122538. 2, 121,
  122539. _vq_lengthlist__16c0_s_p7_1,
  122540. 1, -531365888, 1611661312, 4, 0,
  122541. _vq_quantlist__16c0_s_p7_1,
  122542. NULL,
  122543. &_vq_auxt__16c0_s_p7_1,
  122544. NULL,
  122545. 0
  122546. };
  122547. static long _vq_quantlist__16c0_s_p8_0[] = {
  122548. 6,
  122549. 5,
  122550. 7,
  122551. 4,
  122552. 8,
  122553. 3,
  122554. 9,
  122555. 2,
  122556. 10,
  122557. 1,
  122558. 11,
  122559. 0,
  122560. 12,
  122561. };
  122562. static long _vq_lengthlist__16c0_s_p8_0[] = {
  122563. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8,10,10, 6, 5, 6,
  122564. 8, 8, 8, 8, 8, 8, 8, 9,10,10, 7, 6, 6, 8, 8, 8,
  122565. 8, 8, 8, 8, 8,10,10, 0, 8, 8, 8, 8, 9, 8, 9, 9,
  122566. 9,10,10,10, 0, 9, 8, 8, 8, 9, 9, 8, 8, 9, 9,10,
  122567. 10, 0,12,11, 8, 8, 9, 9, 9, 9,10,10,11,10, 0,12,
  122568. 13, 8, 8, 9,10, 9, 9,11,11,11,12, 0, 0, 0, 8, 8,
  122569. 8, 8,10, 9,12,13,12,14, 0, 0, 0, 8, 8, 8, 9,10,
  122570. 10,12,12,13,14, 0, 0, 0,13,13, 9, 9,11,11, 0, 0,
  122571. 14, 0, 0, 0, 0,14,14,10,10,12,11,12,14,14,14, 0,
  122572. 0, 0, 0, 0,11,11,13,13,14,13,14,14, 0, 0, 0, 0,
  122573. 0,12,13,13,12,13,14,14,14,
  122574. };
  122575. static float _vq_quantthresh__16c0_s_p8_0[] = {
  122576. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  122577. 12.5, 17.5, 22.5, 27.5,
  122578. };
  122579. static long _vq_quantmap__16c0_s_p8_0[] = {
  122580. 11, 9, 7, 5, 3, 1, 0, 2,
  122581. 4, 6, 8, 10, 12,
  122582. };
  122583. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_0 = {
  122584. _vq_quantthresh__16c0_s_p8_0,
  122585. _vq_quantmap__16c0_s_p8_0,
  122586. 13,
  122587. 13
  122588. };
  122589. static static_codebook _16c0_s_p8_0 = {
  122590. 2, 169,
  122591. _vq_lengthlist__16c0_s_p8_0,
  122592. 1, -526516224, 1616117760, 4, 0,
  122593. _vq_quantlist__16c0_s_p8_0,
  122594. NULL,
  122595. &_vq_auxt__16c0_s_p8_0,
  122596. NULL,
  122597. 0
  122598. };
  122599. static long _vq_quantlist__16c0_s_p8_1[] = {
  122600. 2,
  122601. 1,
  122602. 3,
  122603. 0,
  122604. 4,
  122605. };
  122606. static long _vq_lengthlist__16c0_s_p8_1[] = {
  122607. 1, 4, 3, 5, 5, 7, 7, 7, 6, 6, 7, 7, 7, 5, 5, 7,
  122608. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  122609. };
  122610. static float _vq_quantthresh__16c0_s_p8_1[] = {
  122611. -1.5, -0.5, 0.5, 1.5,
  122612. };
  122613. static long _vq_quantmap__16c0_s_p8_1[] = {
  122614. 3, 1, 0, 2, 4,
  122615. };
  122616. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_1 = {
  122617. _vq_quantthresh__16c0_s_p8_1,
  122618. _vq_quantmap__16c0_s_p8_1,
  122619. 5,
  122620. 5
  122621. };
  122622. static static_codebook _16c0_s_p8_1 = {
  122623. 2, 25,
  122624. _vq_lengthlist__16c0_s_p8_1,
  122625. 1, -533725184, 1611661312, 3, 0,
  122626. _vq_quantlist__16c0_s_p8_1,
  122627. NULL,
  122628. &_vq_auxt__16c0_s_p8_1,
  122629. NULL,
  122630. 0
  122631. };
  122632. static long _vq_quantlist__16c0_s_p9_0[] = {
  122633. 1,
  122634. 0,
  122635. 2,
  122636. };
  122637. static long _vq_lengthlist__16c0_s_p9_0[] = {
  122638. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  122639. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  122640. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122641. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122642. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122643. 7,
  122644. };
  122645. static float _vq_quantthresh__16c0_s_p9_0[] = {
  122646. -157.5, 157.5,
  122647. };
  122648. static long _vq_quantmap__16c0_s_p9_0[] = {
  122649. 1, 0, 2,
  122650. };
  122651. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_0 = {
  122652. _vq_quantthresh__16c0_s_p9_0,
  122653. _vq_quantmap__16c0_s_p9_0,
  122654. 3,
  122655. 3
  122656. };
  122657. static static_codebook _16c0_s_p9_0 = {
  122658. 4, 81,
  122659. _vq_lengthlist__16c0_s_p9_0,
  122660. 1, -518803456, 1628680192, 2, 0,
  122661. _vq_quantlist__16c0_s_p9_0,
  122662. NULL,
  122663. &_vq_auxt__16c0_s_p9_0,
  122664. NULL,
  122665. 0
  122666. };
  122667. static long _vq_quantlist__16c0_s_p9_1[] = {
  122668. 7,
  122669. 6,
  122670. 8,
  122671. 5,
  122672. 9,
  122673. 4,
  122674. 10,
  122675. 3,
  122676. 11,
  122677. 2,
  122678. 12,
  122679. 1,
  122680. 13,
  122681. 0,
  122682. 14,
  122683. };
  122684. static long _vq_lengthlist__16c0_s_p9_1[] = {
  122685. 1, 5, 5, 5, 5, 9,11,11,10,10,10,10,10,10,10, 7,
  122686. 6, 6, 6, 6,10,10,10,10,10,10,10,10,10,10, 7, 6,
  122687. 6, 6, 6,10, 9,10,10,10,10,10,10,10,10,10, 7, 7,
  122688. 8, 9,10,10,10,10,10,10,10,10,10,10,10, 8, 7,10,
  122689. 10,10, 9,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,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122697. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122698. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122699. 10,
  122700. };
  122701. static float _vq_quantthresh__16c0_s_p9_1[] = {
  122702. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  122703. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  122704. };
  122705. static long _vq_quantmap__16c0_s_p9_1[] = {
  122706. 13, 11, 9, 7, 5, 3, 1, 0,
  122707. 2, 4, 6, 8, 10, 12, 14,
  122708. };
  122709. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_1 = {
  122710. _vq_quantthresh__16c0_s_p9_1,
  122711. _vq_quantmap__16c0_s_p9_1,
  122712. 15,
  122713. 15
  122714. };
  122715. static static_codebook _16c0_s_p9_1 = {
  122716. 2, 225,
  122717. _vq_lengthlist__16c0_s_p9_1,
  122718. 1, -520986624, 1620377600, 4, 0,
  122719. _vq_quantlist__16c0_s_p9_1,
  122720. NULL,
  122721. &_vq_auxt__16c0_s_p9_1,
  122722. NULL,
  122723. 0
  122724. };
  122725. static long _vq_quantlist__16c0_s_p9_2[] = {
  122726. 10,
  122727. 9,
  122728. 11,
  122729. 8,
  122730. 12,
  122731. 7,
  122732. 13,
  122733. 6,
  122734. 14,
  122735. 5,
  122736. 15,
  122737. 4,
  122738. 16,
  122739. 3,
  122740. 17,
  122741. 2,
  122742. 18,
  122743. 1,
  122744. 19,
  122745. 0,
  122746. 20,
  122747. };
  122748. static long _vq_lengthlist__16c0_s_p9_2[] = {
  122749. 1, 5, 5, 7, 8, 8, 7, 9, 9, 9,12,12,11,12,12,10,
  122750. 10,11,12,12,12,11,12,12, 8, 9, 8, 7, 9,10,10,11,
  122751. 11,10,11,12,10,12,10,12,12,12,11,12,11, 9, 8, 8,
  122752. 9,10, 9, 8, 9,10,12,12,11,11,12,11,10,11,12,11,
  122753. 12,12, 8, 9, 9, 9,10,11,12,11,12,11,11,11,11,12,
  122754. 12,11,11,12,12,11,11, 9, 9, 8, 9, 9,11, 9, 9,10,
  122755. 9,11,11,11,11,12,11,11,10,12,12,12, 9,12,11,10,
  122756. 11,11,11,11,12,12,12,11,11,11,12,10,12,12,12,10,
  122757. 10, 9,10, 9,10,10, 9, 9, 9,10,10,12,10,11,11, 9,
  122758. 11,11,10,11,11,11,10,10,10, 9, 9,10,10, 9, 9,10,
  122759. 11,11,10,11,10,11,10,11,11,10,11,11,11,10, 9,10,
  122760. 10, 9,10, 9, 9,11, 9, 9,11,10,10,11,11,10,10,11,
  122761. 10,11, 8, 9,11,11,10, 9,10,11,11,10,11,11,10,10,
  122762. 10,11,10, 9,10,10,11, 9,10,10, 9,11,10,10,10,10,
  122763. 11,10,11,11, 9,11,10,11,10,10,11,11,10,10,10, 9,
  122764. 10,10,11,11,11, 9,10,10,10,10,10,11,10,10,10, 9,
  122765. 10,10,11,10,10,10,10,10, 9,10,11,10,10,10,10,11,
  122766. 11,11,10,10,10,10,10,11,10,11,10,11,10,10,10, 9,
  122767. 11,11,10,10,10,11,11,10,10,10,10,10,10,10,10,11,
  122768. 11, 9,10,10,10,11,10,11,10,10,10,11, 9,10,11,10,
  122769. 11,10,10, 9,10,10,10,11,10,11,10,10,10,10,10,11,
  122770. 11,10,11,11,10,10,11,11,10, 9, 9,10,10,10,10,10,
  122771. 9,11, 9,10,10,10,11,11,10,10,10,10,11,11,11,10,
  122772. 9, 9,10,10,11,10,10,10,10,10,11,11,11,10,10,10,
  122773. 11,11,11, 9,10,10,10,10, 9,10, 9,10,11,10,11,10,
  122774. 10,11,11,10,11,11,11,11,11,10,11,10,10,10, 9,11,
  122775. 11,10,11,11,11,11,11,11,11,11,11,10,11,10,10,10,
  122776. 10,11,10,10,11, 9,10,10,10,
  122777. };
  122778. static float _vq_quantthresh__16c0_s_p9_2[] = {
  122779. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  122780. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  122781. 6.5, 7.5, 8.5, 9.5,
  122782. };
  122783. static long _vq_quantmap__16c0_s_p9_2[] = {
  122784. 19, 17, 15, 13, 11, 9, 7, 5,
  122785. 3, 1, 0, 2, 4, 6, 8, 10,
  122786. 12, 14, 16, 18, 20,
  122787. };
  122788. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_2 = {
  122789. _vq_quantthresh__16c0_s_p9_2,
  122790. _vq_quantmap__16c0_s_p9_2,
  122791. 21,
  122792. 21
  122793. };
  122794. static static_codebook _16c0_s_p9_2 = {
  122795. 2, 441,
  122796. _vq_lengthlist__16c0_s_p9_2,
  122797. 1, -529268736, 1611661312, 5, 0,
  122798. _vq_quantlist__16c0_s_p9_2,
  122799. NULL,
  122800. &_vq_auxt__16c0_s_p9_2,
  122801. NULL,
  122802. 0
  122803. };
  122804. static long _huff_lengthlist__16c0_s_single[] = {
  122805. 3, 4,19, 7, 9, 7, 8,11, 9,12, 4, 1,19, 6, 7, 7,
  122806. 8,10,11,13,18,18,18,18,18,18,18,18,18,18, 8, 6,
  122807. 18, 8, 9, 9,11,12,14,18, 9, 6,18, 9, 7, 8, 9,11,
  122808. 12,18, 7, 6,18, 8, 7, 7, 7, 9,11,17, 8, 8,18, 9,
  122809. 7, 6, 6, 8,11,17,10,10,18,12, 9, 8, 7, 9,12,18,
  122810. 13,15,18,15,13,11,10,11,15,18,14,18,18,18,18,18,
  122811. 16,16,18,18,
  122812. };
  122813. static static_codebook _huff_book__16c0_s_single = {
  122814. 2, 100,
  122815. _huff_lengthlist__16c0_s_single,
  122816. 0, 0, 0, 0, 0,
  122817. NULL,
  122818. NULL,
  122819. NULL,
  122820. NULL,
  122821. 0
  122822. };
  122823. static long _huff_lengthlist__16c1_s_long[] = {
  122824. 2, 5,20, 7,10, 7, 8,10,11,11, 4, 2,20, 5, 8, 6,
  122825. 7, 9,10,10,20,20,20,20,19,19,19,19,19,19, 7, 5,
  122826. 19, 6,10, 7, 9,11,13,17,11, 8,19,10, 7, 7, 8,10,
  122827. 11,15, 7, 5,19, 7, 7, 5, 6, 9,11,16, 7, 6,19, 8,
  122828. 7, 6, 6, 7, 9,13, 9, 9,19,11, 9, 8, 6, 7, 8,13,
  122829. 12,14,19,16,13,10, 9, 8, 9,13,14,17,19,18,18,17,
  122830. 12,11,11,13,
  122831. };
  122832. static static_codebook _huff_book__16c1_s_long = {
  122833. 2, 100,
  122834. _huff_lengthlist__16c1_s_long,
  122835. 0, 0, 0, 0, 0,
  122836. NULL,
  122837. NULL,
  122838. NULL,
  122839. NULL,
  122840. 0
  122841. };
  122842. static long _vq_quantlist__16c1_s_p1_0[] = {
  122843. 1,
  122844. 0,
  122845. 2,
  122846. };
  122847. static long _vq_lengthlist__16c1_s_p1_0[] = {
  122848. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  122849. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122853. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  122854. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122858. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  122859. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  122894. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  122895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  122899. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  122900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  122904. 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  122905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122939. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  122940. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122944. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  122945. 0, 0, 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  122946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122949. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  122950. 0, 0, 0, 0, 0, 0, 9,11, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123258. 0,
  123259. };
  123260. static float _vq_quantthresh__16c1_s_p1_0[] = {
  123261. -0.5, 0.5,
  123262. };
  123263. static long _vq_quantmap__16c1_s_p1_0[] = {
  123264. 1, 0, 2,
  123265. };
  123266. static encode_aux_threshmatch _vq_auxt__16c1_s_p1_0 = {
  123267. _vq_quantthresh__16c1_s_p1_0,
  123268. _vq_quantmap__16c1_s_p1_0,
  123269. 3,
  123270. 3
  123271. };
  123272. static static_codebook _16c1_s_p1_0 = {
  123273. 8, 6561,
  123274. _vq_lengthlist__16c1_s_p1_0,
  123275. 1, -535822336, 1611661312, 2, 0,
  123276. _vq_quantlist__16c1_s_p1_0,
  123277. NULL,
  123278. &_vq_auxt__16c1_s_p1_0,
  123279. NULL,
  123280. 0
  123281. };
  123282. static long _vq_quantlist__16c1_s_p2_0[] = {
  123283. 2,
  123284. 1,
  123285. 3,
  123286. 0,
  123287. 4,
  123288. };
  123289. static long _vq_lengthlist__16c1_s_p2_0[] = {
  123290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123329. 0,
  123330. };
  123331. static float _vq_quantthresh__16c1_s_p2_0[] = {
  123332. -1.5, -0.5, 0.5, 1.5,
  123333. };
  123334. static long _vq_quantmap__16c1_s_p2_0[] = {
  123335. 3, 1, 0, 2, 4,
  123336. };
  123337. static encode_aux_threshmatch _vq_auxt__16c1_s_p2_0 = {
  123338. _vq_quantthresh__16c1_s_p2_0,
  123339. _vq_quantmap__16c1_s_p2_0,
  123340. 5,
  123341. 5
  123342. };
  123343. static static_codebook _16c1_s_p2_0 = {
  123344. 4, 625,
  123345. _vq_lengthlist__16c1_s_p2_0,
  123346. 1, -533725184, 1611661312, 3, 0,
  123347. _vq_quantlist__16c1_s_p2_0,
  123348. NULL,
  123349. &_vq_auxt__16c1_s_p2_0,
  123350. NULL,
  123351. 0
  123352. };
  123353. static long _vq_quantlist__16c1_s_p3_0[] = {
  123354. 2,
  123355. 1,
  123356. 3,
  123357. 0,
  123358. 4,
  123359. };
  123360. static long _vq_lengthlist__16c1_s_p3_0[] = {
  123361. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  123363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123364. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 9, 9,
  123366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123367. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  123368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123400. 0,
  123401. };
  123402. static float _vq_quantthresh__16c1_s_p3_0[] = {
  123403. -1.5, -0.5, 0.5, 1.5,
  123404. };
  123405. static long _vq_quantmap__16c1_s_p3_0[] = {
  123406. 3, 1, 0, 2, 4,
  123407. };
  123408. static encode_aux_threshmatch _vq_auxt__16c1_s_p3_0 = {
  123409. _vq_quantthresh__16c1_s_p3_0,
  123410. _vq_quantmap__16c1_s_p3_0,
  123411. 5,
  123412. 5
  123413. };
  123414. static static_codebook _16c1_s_p3_0 = {
  123415. 4, 625,
  123416. _vq_lengthlist__16c1_s_p3_0,
  123417. 1, -533725184, 1611661312, 3, 0,
  123418. _vq_quantlist__16c1_s_p3_0,
  123419. NULL,
  123420. &_vq_auxt__16c1_s_p3_0,
  123421. NULL,
  123422. 0
  123423. };
  123424. static long _vq_quantlist__16c1_s_p4_0[] = {
  123425. 4,
  123426. 3,
  123427. 5,
  123428. 2,
  123429. 6,
  123430. 1,
  123431. 7,
  123432. 0,
  123433. 8,
  123434. };
  123435. static long _vq_lengthlist__16c1_s_p4_0[] = {
  123436. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  123437. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  123438. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  123439. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 0, 0, 0,
  123440. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123441. 0,
  123442. };
  123443. static float _vq_quantthresh__16c1_s_p4_0[] = {
  123444. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123445. };
  123446. static long _vq_quantmap__16c1_s_p4_0[] = {
  123447. 7, 5, 3, 1, 0, 2, 4, 6,
  123448. 8,
  123449. };
  123450. static encode_aux_threshmatch _vq_auxt__16c1_s_p4_0 = {
  123451. _vq_quantthresh__16c1_s_p4_0,
  123452. _vq_quantmap__16c1_s_p4_0,
  123453. 9,
  123454. 9
  123455. };
  123456. static static_codebook _16c1_s_p4_0 = {
  123457. 2, 81,
  123458. _vq_lengthlist__16c1_s_p4_0,
  123459. 1, -531628032, 1611661312, 4, 0,
  123460. _vq_quantlist__16c1_s_p4_0,
  123461. NULL,
  123462. &_vq_auxt__16c1_s_p4_0,
  123463. NULL,
  123464. 0
  123465. };
  123466. static long _vq_quantlist__16c1_s_p5_0[] = {
  123467. 4,
  123468. 3,
  123469. 5,
  123470. 2,
  123471. 6,
  123472. 1,
  123473. 7,
  123474. 0,
  123475. 8,
  123476. };
  123477. static long _vq_lengthlist__16c1_s_p5_0[] = {
  123478. 1, 3, 3, 5, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  123479. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 8, 8,
  123480. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  123481. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  123482. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  123483. 10,
  123484. };
  123485. static float _vq_quantthresh__16c1_s_p5_0[] = {
  123486. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123487. };
  123488. static long _vq_quantmap__16c1_s_p5_0[] = {
  123489. 7, 5, 3, 1, 0, 2, 4, 6,
  123490. 8,
  123491. };
  123492. static encode_aux_threshmatch _vq_auxt__16c1_s_p5_0 = {
  123493. _vq_quantthresh__16c1_s_p5_0,
  123494. _vq_quantmap__16c1_s_p5_0,
  123495. 9,
  123496. 9
  123497. };
  123498. static static_codebook _16c1_s_p5_0 = {
  123499. 2, 81,
  123500. _vq_lengthlist__16c1_s_p5_0,
  123501. 1, -531628032, 1611661312, 4, 0,
  123502. _vq_quantlist__16c1_s_p5_0,
  123503. NULL,
  123504. &_vq_auxt__16c1_s_p5_0,
  123505. NULL,
  123506. 0
  123507. };
  123508. static long _vq_quantlist__16c1_s_p6_0[] = {
  123509. 8,
  123510. 7,
  123511. 9,
  123512. 6,
  123513. 10,
  123514. 5,
  123515. 11,
  123516. 4,
  123517. 12,
  123518. 3,
  123519. 13,
  123520. 2,
  123521. 14,
  123522. 1,
  123523. 15,
  123524. 0,
  123525. 16,
  123526. };
  123527. static long _vq_lengthlist__16c1_s_p6_0[] = {
  123528. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,12,
  123529. 12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  123530. 12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  123531. 11,12,12, 0, 0, 0, 8, 8, 8, 9,10, 9,10,10,10,10,
  123532. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,11,
  123533. 11,11,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  123534. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  123535. 10,11,11,12,12,13,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  123536. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  123537. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  123538. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  123539. 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0,
  123540. 10,10,11,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0,
  123541. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  123542. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  123543. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0,
  123544. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  123545. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  123546. 14,
  123547. };
  123548. static float _vq_quantthresh__16c1_s_p6_0[] = {
  123549. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  123550. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  123551. };
  123552. static long _vq_quantmap__16c1_s_p6_0[] = {
  123553. 15, 13, 11, 9, 7, 5, 3, 1,
  123554. 0, 2, 4, 6, 8, 10, 12, 14,
  123555. 16,
  123556. };
  123557. static encode_aux_threshmatch _vq_auxt__16c1_s_p6_0 = {
  123558. _vq_quantthresh__16c1_s_p6_0,
  123559. _vq_quantmap__16c1_s_p6_0,
  123560. 17,
  123561. 17
  123562. };
  123563. static static_codebook _16c1_s_p6_0 = {
  123564. 2, 289,
  123565. _vq_lengthlist__16c1_s_p6_0,
  123566. 1, -529530880, 1611661312, 5, 0,
  123567. _vq_quantlist__16c1_s_p6_0,
  123568. NULL,
  123569. &_vq_auxt__16c1_s_p6_0,
  123570. NULL,
  123571. 0
  123572. };
  123573. static long _vq_quantlist__16c1_s_p7_0[] = {
  123574. 1,
  123575. 0,
  123576. 2,
  123577. };
  123578. static long _vq_lengthlist__16c1_s_p7_0[] = {
  123579. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9,10,10,
  123580. 10, 9, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  123581. 11,11,10,10, 6,10, 9,11,11,11,11,10,10, 6,10,10,
  123582. 11,11,11,11,10,10, 7,11,11,11,11,11,12,12,11, 6,
  123583. 10,10,11,10,10,11,11,11, 6,10,10,10,11,10,11,11,
  123584. 11,
  123585. };
  123586. static float _vq_quantthresh__16c1_s_p7_0[] = {
  123587. -5.5, 5.5,
  123588. };
  123589. static long _vq_quantmap__16c1_s_p7_0[] = {
  123590. 1, 0, 2,
  123591. };
  123592. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_0 = {
  123593. _vq_quantthresh__16c1_s_p7_0,
  123594. _vq_quantmap__16c1_s_p7_0,
  123595. 3,
  123596. 3
  123597. };
  123598. static static_codebook _16c1_s_p7_0 = {
  123599. 4, 81,
  123600. _vq_lengthlist__16c1_s_p7_0,
  123601. 1, -529137664, 1618345984, 2, 0,
  123602. _vq_quantlist__16c1_s_p7_0,
  123603. NULL,
  123604. &_vq_auxt__16c1_s_p7_0,
  123605. NULL,
  123606. 0
  123607. };
  123608. static long _vq_quantlist__16c1_s_p7_1[] = {
  123609. 5,
  123610. 4,
  123611. 6,
  123612. 3,
  123613. 7,
  123614. 2,
  123615. 8,
  123616. 1,
  123617. 9,
  123618. 0,
  123619. 10,
  123620. };
  123621. static long _vq_lengthlist__16c1_s_p7_1[] = {
  123622. 2, 3, 3, 5, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  123623. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  123624. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  123625. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  123626. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  123627. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  123628. 8, 9, 9,10,10,10,10,10, 9, 9, 8, 8, 9, 9,10,10,
  123629. 10,10,10, 8, 8, 8, 8, 9, 9,
  123630. };
  123631. static float _vq_quantthresh__16c1_s_p7_1[] = {
  123632. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  123633. 3.5, 4.5,
  123634. };
  123635. static long _vq_quantmap__16c1_s_p7_1[] = {
  123636. 9, 7, 5, 3, 1, 0, 2, 4,
  123637. 6, 8, 10,
  123638. };
  123639. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_1 = {
  123640. _vq_quantthresh__16c1_s_p7_1,
  123641. _vq_quantmap__16c1_s_p7_1,
  123642. 11,
  123643. 11
  123644. };
  123645. static static_codebook _16c1_s_p7_1 = {
  123646. 2, 121,
  123647. _vq_lengthlist__16c1_s_p7_1,
  123648. 1, -531365888, 1611661312, 4, 0,
  123649. _vq_quantlist__16c1_s_p7_1,
  123650. NULL,
  123651. &_vq_auxt__16c1_s_p7_1,
  123652. NULL,
  123653. 0
  123654. };
  123655. static long _vq_quantlist__16c1_s_p8_0[] = {
  123656. 6,
  123657. 5,
  123658. 7,
  123659. 4,
  123660. 8,
  123661. 3,
  123662. 9,
  123663. 2,
  123664. 10,
  123665. 1,
  123666. 11,
  123667. 0,
  123668. 12,
  123669. };
  123670. static long _vq_lengthlist__16c1_s_p8_0[] = {
  123671. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  123672. 7, 8, 8, 9, 8, 8, 9, 9,10,11, 6, 5, 5, 8, 8, 9,
  123673. 9, 8, 8, 9,10,10,11, 0, 8, 8, 8, 9, 9, 9, 9, 9,
  123674. 10,10,11,11, 0, 9, 9, 9, 8, 9, 9, 9, 9,10,10,11,
  123675. 11, 0,13,13, 9, 9,10,10,10,10,11,11,12,12, 0,14,
  123676. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  123677. 9, 9,11,11,12,12,13,12, 0, 0, 0,10,10, 9, 9,10,
  123678. 10,12,12,13,13, 0, 0, 0,13,14,11,10,11,11,12,12,
  123679. 13,14, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  123680. 0, 0, 0, 0,12,12,12,12,13,13,14,15, 0, 0, 0, 0,
  123681. 0,12,12,12,12,13,13,14,15,
  123682. };
  123683. static float _vq_quantthresh__16c1_s_p8_0[] = {
  123684. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  123685. 12.5, 17.5, 22.5, 27.5,
  123686. };
  123687. static long _vq_quantmap__16c1_s_p8_0[] = {
  123688. 11, 9, 7, 5, 3, 1, 0, 2,
  123689. 4, 6, 8, 10, 12,
  123690. };
  123691. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_0 = {
  123692. _vq_quantthresh__16c1_s_p8_0,
  123693. _vq_quantmap__16c1_s_p8_0,
  123694. 13,
  123695. 13
  123696. };
  123697. static static_codebook _16c1_s_p8_0 = {
  123698. 2, 169,
  123699. _vq_lengthlist__16c1_s_p8_0,
  123700. 1, -526516224, 1616117760, 4, 0,
  123701. _vq_quantlist__16c1_s_p8_0,
  123702. NULL,
  123703. &_vq_auxt__16c1_s_p8_0,
  123704. NULL,
  123705. 0
  123706. };
  123707. static long _vq_quantlist__16c1_s_p8_1[] = {
  123708. 2,
  123709. 1,
  123710. 3,
  123711. 0,
  123712. 4,
  123713. };
  123714. static long _vq_lengthlist__16c1_s_p8_1[] = {
  123715. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  123716. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  123717. };
  123718. static float _vq_quantthresh__16c1_s_p8_1[] = {
  123719. -1.5, -0.5, 0.5, 1.5,
  123720. };
  123721. static long _vq_quantmap__16c1_s_p8_1[] = {
  123722. 3, 1, 0, 2, 4,
  123723. };
  123724. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_1 = {
  123725. _vq_quantthresh__16c1_s_p8_1,
  123726. _vq_quantmap__16c1_s_p8_1,
  123727. 5,
  123728. 5
  123729. };
  123730. static static_codebook _16c1_s_p8_1 = {
  123731. 2, 25,
  123732. _vq_lengthlist__16c1_s_p8_1,
  123733. 1, -533725184, 1611661312, 3, 0,
  123734. _vq_quantlist__16c1_s_p8_1,
  123735. NULL,
  123736. &_vq_auxt__16c1_s_p8_1,
  123737. NULL,
  123738. 0
  123739. };
  123740. static long _vq_quantlist__16c1_s_p9_0[] = {
  123741. 6,
  123742. 5,
  123743. 7,
  123744. 4,
  123745. 8,
  123746. 3,
  123747. 9,
  123748. 2,
  123749. 10,
  123750. 1,
  123751. 11,
  123752. 0,
  123753. 12,
  123754. };
  123755. static long _vq_lengthlist__16c1_s_p9_0[] = {
  123756. 1, 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, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  123759. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  123760. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  123761. 9, 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, 8, 8, 8, 8, 8, 8, 8,
  123764. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123765. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123766. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123767. };
  123768. static float _vq_quantthresh__16c1_s_p9_0[] = {
  123769. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  123770. 787.5, 1102.5, 1417.5, 1732.5,
  123771. };
  123772. static long _vq_quantmap__16c1_s_p9_0[] = {
  123773. 11, 9, 7, 5, 3, 1, 0, 2,
  123774. 4, 6, 8, 10, 12,
  123775. };
  123776. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_0 = {
  123777. _vq_quantthresh__16c1_s_p9_0,
  123778. _vq_quantmap__16c1_s_p9_0,
  123779. 13,
  123780. 13
  123781. };
  123782. static static_codebook _16c1_s_p9_0 = {
  123783. 2, 169,
  123784. _vq_lengthlist__16c1_s_p9_0,
  123785. 1, -513964032, 1628680192, 4, 0,
  123786. _vq_quantlist__16c1_s_p9_0,
  123787. NULL,
  123788. &_vq_auxt__16c1_s_p9_0,
  123789. NULL,
  123790. 0
  123791. };
  123792. static long _vq_quantlist__16c1_s_p9_1[] = {
  123793. 7,
  123794. 6,
  123795. 8,
  123796. 5,
  123797. 9,
  123798. 4,
  123799. 10,
  123800. 3,
  123801. 11,
  123802. 2,
  123803. 12,
  123804. 1,
  123805. 13,
  123806. 0,
  123807. 14,
  123808. };
  123809. static long _vq_lengthlist__16c1_s_p9_1[] = {
  123810. 1, 4, 4, 4, 4, 8, 8,12,13,14,14,14,14,14,14, 6,
  123811. 6, 6, 6, 6,10, 9,14,14,14,14,14,14,14,14, 7, 6,
  123812. 5, 6, 6,10, 9,12,13,13,13,13,13,13,13,13, 7, 7,
  123813. 9, 9,11,11,12,13,13,13,13,13,13,13,13, 7, 7, 8,
  123814. 8,11,12,13,13,13,13,13,13,13,13,13,12,12,10,10,
  123815. 13,12,13,13,13,13,13,13,13,13,13,12,12,10,10,13,
  123816. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,13,12,
  123817. 13,13,13,13,13,13,13,13,13,13,13,13,12,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,13,13,13,12,13,13,13,
  123820. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  123821. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  123822. 13,13,13,13,13,13,13,13,13,12,13,13,13,13,13,13,
  123823. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  123824. 13,
  123825. };
  123826. static float _vq_quantthresh__16c1_s_p9_1[] = {
  123827. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  123828. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  123829. };
  123830. static long _vq_quantmap__16c1_s_p9_1[] = {
  123831. 13, 11, 9, 7, 5, 3, 1, 0,
  123832. 2, 4, 6, 8, 10, 12, 14,
  123833. };
  123834. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_1 = {
  123835. _vq_quantthresh__16c1_s_p9_1,
  123836. _vq_quantmap__16c1_s_p9_1,
  123837. 15,
  123838. 15
  123839. };
  123840. static static_codebook _16c1_s_p9_1 = {
  123841. 2, 225,
  123842. _vq_lengthlist__16c1_s_p9_1,
  123843. 1, -520986624, 1620377600, 4, 0,
  123844. _vq_quantlist__16c1_s_p9_1,
  123845. NULL,
  123846. &_vq_auxt__16c1_s_p9_1,
  123847. NULL,
  123848. 0
  123849. };
  123850. static long _vq_quantlist__16c1_s_p9_2[] = {
  123851. 10,
  123852. 9,
  123853. 11,
  123854. 8,
  123855. 12,
  123856. 7,
  123857. 13,
  123858. 6,
  123859. 14,
  123860. 5,
  123861. 15,
  123862. 4,
  123863. 16,
  123864. 3,
  123865. 17,
  123866. 2,
  123867. 18,
  123868. 1,
  123869. 19,
  123870. 0,
  123871. 20,
  123872. };
  123873. static long _vq_lengthlist__16c1_s_p9_2[] = {
  123874. 1, 4, 4, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9,10,
  123875. 10,10, 9,10,10,11,12,12, 8, 8, 8, 8, 9, 9, 9, 9,
  123876. 10,10,10,10,10,11,11,10,12,11,11,13,11, 7, 7, 8,
  123877. 8, 8, 8, 9, 9, 9,10,10,10,10, 9,10,10,11,11,12,
  123878. 11,11, 8, 8, 8, 8, 9, 9,10,10,10,10,11,11,11,11,
  123879. 11,11,11,12,11,12,12, 8, 8, 9, 9, 9, 9, 9,10,10,
  123880. 10,10,10,10,11,11,11,11,11,11,12,11, 9, 9, 9, 9,
  123881. 10,10,10,10,11,10,11,11,11,11,11,11,12,12,12,12,
  123882. 11, 9, 9, 9, 9,10,10,10,10,11,11,11,11,11,11,11,
  123883. 11,11,12,12,12,13, 9,10,10, 9,11,10,10,10,10,11,
  123884. 11,11,11,11,10,11,12,11,12,12,11,12,11,10, 9,10,
  123885. 10,11,10,11,11,11,11,11,11,11,11,11,12,12,11,12,
  123886. 12,12,10,10,10,11,10,11,11,11,11,11,11,11,11,11,
  123887. 11,11,12,13,12,12,11, 9,10,10,11,11,10,11,11,11,
  123888. 12,11,11,11,11,11,12,12,13,13,12,13,10,10,12,10,
  123889. 11,11,11,11,11,11,11,11,11,12,12,11,13,12,12,12,
  123890. 12,13,12,11,11,11,11,11,11,12,11,12,11,11,11,11,
  123891. 12,12,13,12,11,12,12,11,11,11,11,11,12,11,11,11,
  123892. 11,12,11,11,12,11,12,13,13,12,12,12,12,11,11,11,
  123893. 11,11,12,11,11,12,11,12,11,11,11,11,13,12,12,12,
  123894. 12,13,11,11,11,12,12,11,11,11,12,11,12,12,12,11,
  123895. 12,13,12,11,11,12,12,11,12,11,11,11,12,12,11,12,
  123896. 11,11,11,12,12,12,12,13,12,13,12,12,12,12,11,11,
  123897. 12,11,11,11,11,11,11,12,12,12,13,12,11,13,13,12,
  123898. 12,11,12,10,11,11,11,11,12,11,12,12,11,12,12,13,
  123899. 12,12,13,12,12,12,12,12,11,12,12,12,11,12,11,11,
  123900. 11,12,13,12,13,13,13,13,13,12,13,13,12,12,13,11,
  123901. 11,11,11,11,12,11,11,12,11,
  123902. };
  123903. static float _vq_quantthresh__16c1_s_p9_2[] = {
  123904. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  123905. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  123906. 6.5, 7.5, 8.5, 9.5,
  123907. };
  123908. static long _vq_quantmap__16c1_s_p9_2[] = {
  123909. 19, 17, 15, 13, 11, 9, 7, 5,
  123910. 3, 1, 0, 2, 4, 6, 8, 10,
  123911. 12, 14, 16, 18, 20,
  123912. };
  123913. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_2 = {
  123914. _vq_quantthresh__16c1_s_p9_2,
  123915. _vq_quantmap__16c1_s_p9_2,
  123916. 21,
  123917. 21
  123918. };
  123919. static static_codebook _16c1_s_p9_2 = {
  123920. 2, 441,
  123921. _vq_lengthlist__16c1_s_p9_2,
  123922. 1, -529268736, 1611661312, 5, 0,
  123923. _vq_quantlist__16c1_s_p9_2,
  123924. NULL,
  123925. &_vq_auxt__16c1_s_p9_2,
  123926. NULL,
  123927. 0
  123928. };
  123929. static long _huff_lengthlist__16c1_s_short[] = {
  123930. 5, 6,17, 8,12, 9,10,10,12,13, 5, 2,17, 4, 9, 5,
  123931. 7, 8,11,13,16,16,16,16,16,16,16,16,16,16, 6, 4,
  123932. 16, 5,10, 5, 7,10,14,16,13, 9,16,11, 8, 7, 8, 9,
  123933. 13,16, 7, 4,16, 5, 7, 4, 6, 8,11,13, 8, 6,16, 7,
  123934. 8, 5, 5, 7, 9,13, 9, 8,16, 9, 8, 6, 6, 7, 9,13,
  123935. 11,11,16,10,10, 7, 7, 7, 9,13,13,13,16,13,13, 9,
  123936. 9, 9,10,13,
  123937. };
  123938. static static_codebook _huff_book__16c1_s_short = {
  123939. 2, 100,
  123940. _huff_lengthlist__16c1_s_short,
  123941. 0, 0, 0, 0, 0,
  123942. NULL,
  123943. NULL,
  123944. NULL,
  123945. NULL,
  123946. 0
  123947. };
  123948. static long _huff_lengthlist__16c2_s_long[] = {
  123949. 4, 7, 9, 9, 9, 8, 9,10,15,19, 5, 4, 5, 6, 7, 7,
  123950. 8, 9,14,16, 6, 5, 4, 5, 6, 7, 8,10,12,19, 7, 6,
  123951. 5, 4, 5, 6, 7, 9,11,18, 8, 7, 6, 5, 5, 5, 7, 9,
  123952. 10,17, 8, 7, 7, 5, 5, 5, 6, 7,12,18, 8, 8, 8, 7,
  123953. 7, 5, 5, 7,12,18, 8, 9,10, 9, 9, 7, 6, 7,12,17,
  123954. 14,18,16,16,15,12,11,10,12,18,15,17,18,18,18,15,
  123955. 14,14,16,18,
  123956. };
  123957. static static_codebook _huff_book__16c2_s_long = {
  123958. 2, 100,
  123959. _huff_lengthlist__16c2_s_long,
  123960. 0, 0, 0, 0, 0,
  123961. NULL,
  123962. NULL,
  123963. NULL,
  123964. NULL,
  123965. 0
  123966. };
  123967. static long _vq_quantlist__16c2_s_p1_0[] = {
  123968. 1,
  123969. 0,
  123970. 2,
  123971. };
  123972. static long _vq_lengthlist__16c2_s_p1_0[] = {
  123973. 1, 3, 3, 0, 0, 0, 0, 0, 0, 4, 5, 5, 0, 0, 0, 0,
  123974. 0, 0, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123978. 0,
  123979. };
  123980. static float _vq_quantthresh__16c2_s_p1_0[] = {
  123981. -0.5, 0.5,
  123982. };
  123983. static long _vq_quantmap__16c2_s_p1_0[] = {
  123984. 1, 0, 2,
  123985. };
  123986. static encode_aux_threshmatch _vq_auxt__16c2_s_p1_0 = {
  123987. _vq_quantthresh__16c2_s_p1_0,
  123988. _vq_quantmap__16c2_s_p1_0,
  123989. 3,
  123990. 3
  123991. };
  123992. static static_codebook _16c2_s_p1_0 = {
  123993. 4, 81,
  123994. _vq_lengthlist__16c2_s_p1_0,
  123995. 1, -535822336, 1611661312, 2, 0,
  123996. _vq_quantlist__16c2_s_p1_0,
  123997. NULL,
  123998. &_vq_auxt__16c2_s_p1_0,
  123999. NULL,
  124000. 0
  124001. };
  124002. static long _vq_quantlist__16c2_s_p2_0[] = {
  124003. 2,
  124004. 1,
  124005. 3,
  124006. 0,
  124007. 4,
  124008. };
  124009. static long _vq_lengthlist__16c2_s_p2_0[] = {
  124010. 2, 4, 3, 7, 7, 0, 0, 0, 7, 8, 0, 0, 0, 8, 8, 0,
  124011. 0, 0, 8, 8, 0, 0, 0, 8, 8, 4, 5, 4, 8, 8, 0, 0,
  124012. 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0,
  124013. 9, 9, 4, 4, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8,
  124014. 8, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 7, 8, 8,10,10,
  124015. 0, 0, 0,12,11, 0, 0, 0,11,11, 0, 0, 0,14,13, 0,
  124016. 0, 0,14,13, 7, 8, 8, 9,10, 0, 0, 0,11,12, 0, 0,
  124017. 0,11,11, 0, 0, 0,14,14, 0, 0, 0,13,14, 0, 0, 0,
  124018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124022. 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8,11,11, 0, 0, 0,
  124023. 11,11, 0, 0, 0,12,11, 0, 0, 0,12,12, 0, 0, 0,13,
  124024. 13, 8, 8, 8,11,11, 0, 0, 0,11,11, 0, 0, 0,11,12,
  124025. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  124026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124030. 0, 0, 0, 0, 0, 8, 8, 8,12,11, 0, 0, 0,12,11, 0,
  124031. 0, 0,11,11, 0, 0, 0,13,13, 0, 0, 0,13,12, 8, 8,
  124032. 8,11,12, 0, 0, 0,11,12, 0, 0, 0,11,11, 0, 0, 0,
  124033. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124038. 0, 0, 8, 9, 9,14,13, 0, 0, 0,13,12, 0, 0, 0,13,
  124039. 13, 0, 0, 0,13,12, 0, 0, 0,13,13, 8, 9, 9,13,14,
  124040. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,13, 0,
  124041. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8,
  124046. 9, 9,14,13, 0, 0, 0,13,13, 0, 0, 0,13,12, 0, 0,
  124047. 0,13,13, 0, 0, 0,13,12, 8, 9, 9,14,14, 0, 0, 0,
  124048. 13,13, 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,
  124049. 13,
  124050. };
  124051. static float _vq_quantthresh__16c2_s_p2_0[] = {
  124052. -1.5, -0.5, 0.5, 1.5,
  124053. };
  124054. static long _vq_quantmap__16c2_s_p2_0[] = {
  124055. 3, 1, 0, 2, 4,
  124056. };
  124057. static encode_aux_threshmatch _vq_auxt__16c2_s_p2_0 = {
  124058. _vq_quantthresh__16c2_s_p2_0,
  124059. _vq_quantmap__16c2_s_p2_0,
  124060. 5,
  124061. 5
  124062. };
  124063. static static_codebook _16c2_s_p2_0 = {
  124064. 4, 625,
  124065. _vq_lengthlist__16c2_s_p2_0,
  124066. 1, -533725184, 1611661312, 3, 0,
  124067. _vq_quantlist__16c2_s_p2_0,
  124068. NULL,
  124069. &_vq_auxt__16c2_s_p2_0,
  124070. NULL,
  124071. 0
  124072. };
  124073. static long _vq_quantlist__16c2_s_p3_0[] = {
  124074. 4,
  124075. 3,
  124076. 5,
  124077. 2,
  124078. 6,
  124079. 1,
  124080. 7,
  124081. 0,
  124082. 8,
  124083. };
  124084. static long _vq_lengthlist__16c2_s_p3_0[] = {
  124085. 1, 3, 3, 6, 6, 7, 7, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  124086. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  124087. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  124088. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 9, 9,10,10, 0,
  124089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124090. 0,
  124091. };
  124092. static float _vq_quantthresh__16c2_s_p3_0[] = {
  124093. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124094. };
  124095. static long _vq_quantmap__16c2_s_p3_0[] = {
  124096. 7, 5, 3, 1, 0, 2, 4, 6,
  124097. 8,
  124098. };
  124099. static encode_aux_threshmatch _vq_auxt__16c2_s_p3_0 = {
  124100. _vq_quantthresh__16c2_s_p3_0,
  124101. _vq_quantmap__16c2_s_p3_0,
  124102. 9,
  124103. 9
  124104. };
  124105. static static_codebook _16c2_s_p3_0 = {
  124106. 2, 81,
  124107. _vq_lengthlist__16c2_s_p3_0,
  124108. 1, -531628032, 1611661312, 4, 0,
  124109. _vq_quantlist__16c2_s_p3_0,
  124110. NULL,
  124111. &_vq_auxt__16c2_s_p3_0,
  124112. NULL,
  124113. 0
  124114. };
  124115. static long _vq_quantlist__16c2_s_p4_0[] = {
  124116. 8,
  124117. 7,
  124118. 9,
  124119. 6,
  124120. 10,
  124121. 5,
  124122. 11,
  124123. 4,
  124124. 12,
  124125. 3,
  124126. 13,
  124127. 2,
  124128. 14,
  124129. 1,
  124130. 15,
  124131. 0,
  124132. 16,
  124133. };
  124134. static long _vq_lengthlist__16c2_s_p4_0[] = {
  124135. 2, 3, 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,
  124136. 10, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  124137. 11,11, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  124138. 10,10,11, 0, 0, 0, 6, 6, 8, 8, 8, 8, 9, 9,10,10,
  124139. 10,11,11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,
  124140. 10,11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,
  124141. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9,
  124142. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  124143. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  124144. 9,10,10,11,11,12,12,12,12, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124153. 0,
  124154. };
  124155. static float _vq_quantthresh__16c2_s_p4_0[] = {
  124156. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124157. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124158. };
  124159. static long _vq_quantmap__16c2_s_p4_0[] = {
  124160. 15, 13, 11, 9, 7, 5, 3, 1,
  124161. 0, 2, 4, 6, 8, 10, 12, 14,
  124162. 16,
  124163. };
  124164. static encode_aux_threshmatch _vq_auxt__16c2_s_p4_0 = {
  124165. _vq_quantthresh__16c2_s_p4_0,
  124166. _vq_quantmap__16c2_s_p4_0,
  124167. 17,
  124168. 17
  124169. };
  124170. static static_codebook _16c2_s_p4_0 = {
  124171. 2, 289,
  124172. _vq_lengthlist__16c2_s_p4_0,
  124173. 1, -529530880, 1611661312, 5, 0,
  124174. _vq_quantlist__16c2_s_p4_0,
  124175. NULL,
  124176. &_vq_auxt__16c2_s_p4_0,
  124177. NULL,
  124178. 0
  124179. };
  124180. static long _vq_quantlist__16c2_s_p5_0[] = {
  124181. 1,
  124182. 0,
  124183. 2,
  124184. };
  124185. static long _vq_lengthlist__16c2_s_p5_0[] = {
  124186. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6,10,10,10,10,
  124187. 10,10, 4, 7, 6,10,10,10,10,10,10, 5, 9, 9, 9,12,
  124188. 11,10,11,12, 7,10,10,12,12,12,12,12,12, 7,10,10,
  124189. 11,12,12,12,12,13, 6,10,10,10,12,12,10,12,12, 7,
  124190. 10,10,11,13,12,12,12,12, 7,10,10,11,12,12,12,12,
  124191. 12,
  124192. };
  124193. static float _vq_quantthresh__16c2_s_p5_0[] = {
  124194. -5.5, 5.5,
  124195. };
  124196. static long _vq_quantmap__16c2_s_p5_0[] = {
  124197. 1, 0, 2,
  124198. };
  124199. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_0 = {
  124200. _vq_quantthresh__16c2_s_p5_0,
  124201. _vq_quantmap__16c2_s_p5_0,
  124202. 3,
  124203. 3
  124204. };
  124205. static static_codebook _16c2_s_p5_0 = {
  124206. 4, 81,
  124207. _vq_lengthlist__16c2_s_p5_0,
  124208. 1, -529137664, 1618345984, 2, 0,
  124209. _vq_quantlist__16c2_s_p5_0,
  124210. NULL,
  124211. &_vq_auxt__16c2_s_p5_0,
  124212. NULL,
  124213. 0
  124214. };
  124215. static long _vq_quantlist__16c2_s_p5_1[] = {
  124216. 5,
  124217. 4,
  124218. 6,
  124219. 3,
  124220. 7,
  124221. 2,
  124222. 8,
  124223. 1,
  124224. 9,
  124225. 0,
  124226. 10,
  124227. };
  124228. static long _vq_lengthlist__16c2_s_p5_1[] = {
  124229. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11, 6, 6,
  124230. 7, 7, 8, 8, 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8,
  124231. 8,11,11,11, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  124232. 6, 8, 8, 8, 8, 9, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  124233. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 9,11,11,11,
  124234. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,11,11, 8, 8, 8,
  124235. 8, 8, 8,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  124236. 11,11,11, 7, 7, 8, 8, 8, 8,
  124237. };
  124238. static float _vq_quantthresh__16c2_s_p5_1[] = {
  124239. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124240. 3.5, 4.5,
  124241. };
  124242. static long _vq_quantmap__16c2_s_p5_1[] = {
  124243. 9, 7, 5, 3, 1, 0, 2, 4,
  124244. 6, 8, 10,
  124245. };
  124246. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_1 = {
  124247. _vq_quantthresh__16c2_s_p5_1,
  124248. _vq_quantmap__16c2_s_p5_1,
  124249. 11,
  124250. 11
  124251. };
  124252. static static_codebook _16c2_s_p5_1 = {
  124253. 2, 121,
  124254. _vq_lengthlist__16c2_s_p5_1,
  124255. 1, -531365888, 1611661312, 4, 0,
  124256. _vq_quantlist__16c2_s_p5_1,
  124257. NULL,
  124258. &_vq_auxt__16c2_s_p5_1,
  124259. NULL,
  124260. 0
  124261. };
  124262. static long _vq_quantlist__16c2_s_p6_0[] = {
  124263. 6,
  124264. 5,
  124265. 7,
  124266. 4,
  124267. 8,
  124268. 3,
  124269. 9,
  124270. 2,
  124271. 10,
  124272. 1,
  124273. 11,
  124274. 0,
  124275. 12,
  124276. };
  124277. static long _vq_lengthlist__16c2_s_p6_0[] = {
  124278. 1, 4, 4, 7, 6, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  124279. 7, 7, 9, 9, 9, 9,11,11,12,12, 6, 5, 5, 7, 7, 9,
  124280. 9,10,10,11,11,12,12, 0, 6, 6, 7, 7, 9, 9,10,10,
  124281. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,12,12,
  124282. 12, 0,11,11, 8, 8,10,10,11,11,12,12,13,13, 0,11,
  124283. 12, 8, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  124284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124288. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124289. };
  124290. static float _vq_quantthresh__16c2_s_p6_0[] = {
  124291. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  124292. 12.5, 17.5, 22.5, 27.5,
  124293. };
  124294. static long _vq_quantmap__16c2_s_p6_0[] = {
  124295. 11, 9, 7, 5, 3, 1, 0, 2,
  124296. 4, 6, 8, 10, 12,
  124297. };
  124298. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_0 = {
  124299. _vq_quantthresh__16c2_s_p6_0,
  124300. _vq_quantmap__16c2_s_p6_0,
  124301. 13,
  124302. 13
  124303. };
  124304. static static_codebook _16c2_s_p6_0 = {
  124305. 2, 169,
  124306. _vq_lengthlist__16c2_s_p6_0,
  124307. 1, -526516224, 1616117760, 4, 0,
  124308. _vq_quantlist__16c2_s_p6_0,
  124309. NULL,
  124310. &_vq_auxt__16c2_s_p6_0,
  124311. NULL,
  124312. 0
  124313. };
  124314. static long _vq_quantlist__16c2_s_p6_1[] = {
  124315. 2,
  124316. 1,
  124317. 3,
  124318. 0,
  124319. 4,
  124320. };
  124321. static long _vq_lengthlist__16c2_s_p6_1[] = {
  124322. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  124323. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  124324. };
  124325. static float _vq_quantthresh__16c2_s_p6_1[] = {
  124326. -1.5, -0.5, 0.5, 1.5,
  124327. };
  124328. static long _vq_quantmap__16c2_s_p6_1[] = {
  124329. 3, 1, 0, 2, 4,
  124330. };
  124331. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_1 = {
  124332. _vq_quantthresh__16c2_s_p6_1,
  124333. _vq_quantmap__16c2_s_p6_1,
  124334. 5,
  124335. 5
  124336. };
  124337. static static_codebook _16c2_s_p6_1 = {
  124338. 2, 25,
  124339. _vq_lengthlist__16c2_s_p6_1,
  124340. 1, -533725184, 1611661312, 3, 0,
  124341. _vq_quantlist__16c2_s_p6_1,
  124342. NULL,
  124343. &_vq_auxt__16c2_s_p6_1,
  124344. NULL,
  124345. 0
  124346. };
  124347. static long _vq_quantlist__16c2_s_p7_0[] = {
  124348. 6,
  124349. 5,
  124350. 7,
  124351. 4,
  124352. 8,
  124353. 3,
  124354. 9,
  124355. 2,
  124356. 10,
  124357. 1,
  124358. 11,
  124359. 0,
  124360. 12,
  124361. };
  124362. static long _vq_lengthlist__16c2_s_p7_0[] = {
  124363. 1, 4, 4, 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  124364. 8, 8, 9, 9,10,10,11,11,12,12, 6, 5, 5, 8, 8, 9,
  124365. 9,10,10,11,11,12,13,18, 6, 6, 7, 7, 9, 9,10,10,
  124366. 12,12,13,13,18, 6, 6, 7, 7, 9, 9,10,10,12,12,13,
  124367. 13,18,11,10, 8, 8,10,10,11,11,12,12,13,13,18,11,
  124368. 11, 8, 8,10,10,11,11,12,13,13,13,18,18,18,10,11,
  124369. 11,11,12,12,13,13,14,14,18,18,18,11,11,11,11,12,
  124370. 12,13,13,14,14,18,18,18,14,14,12,12,12,12,14,14,
  124371. 15,14,18,18,18,15,15,11,12,12,12,13,13,15,15,18,
  124372. 18,18,18,18,13,13,13,13,13,14,17,16,18,18,18,18,
  124373. 18,13,14,13,13,14,13,15,14,
  124374. };
  124375. static float _vq_quantthresh__16c2_s_p7_0[] = {
  124376. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  124377. 27.5, 38.5, 49.5, 60.5,
  124378. };
  124379. static long _vq_quantmap__16c2_s_p7_0[] = {
  124380. 11, 9, 7, 5, 3, 1, 0, 2,
  124381. 4, 6, 8, 10, 12,
  124382. };
  124383. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_0 = {
  124384. _vq_quantthresh__16c2_s_p7_0,
  124385. _vq_quantmap__16c2_s_p7_0,
  124386. 13,
  124387. 13
  124388. };
  124389. static static_codebook _16c2_s_p7_0 = {
  124390. 2, 169,
  124391. _vq_lengthlist__16c2_s_p7_0,
  124392. 1, -523206656, 1618345984, 4, 0,
  124393. _vq_quantlist__16c2_s_p7_0,
  124394. NULL,
  124395. &_vq_auxt__16c2_s_p7_0,
  124396. NULL,
  124397. 0
  124398. };
  124399. static long _vq_quantlist__16c2_s_p7_1[] = {
  124400. 5,
  124401. 4,
  124402. 6,
  124403. 3,
  124404. 7,
  124405. 2,
  124406. 8,
  124407. 1,
  124408. 9,
  124409. 0,
  124410. 10,
  124411. };
  124412. static long _vq_lengthlist__16c2_s_p7_1[] = {
  124413. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 9, 9, 6, 6,
  124414. 7, 7, 8, 8, 8, 8, 9, 9, 9, 6, 6, 7, 7, 8, 8, 8,
  124415. 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7,
  124416. 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  124417. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  124418. 7, 7, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 9, 7, 7, 7,
  124419. 7, 8, 8, 9, 9, 9, 9, 9, 8, 8, 7, 7, 8, 8, 9, 9,
  124420. 9, 9, 9, 7, 7, 7, 7, 8, 8,
  124421. };
  124422. static float _vq_quantthresh__16c2_s_p7_1[] = {
  124423. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124424. 3.5, 4.5,
  124425. };
  124426. static long _vq_quantmap__16c2_s_p7_1[] = {
  124427. 9, 7, 5, 3, 1, 0, 2, 4,
  124428. 6, 8, 10,
  124429. };
  124430. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_1 = {
  124431. _vq_quantthresh__16c2_s_p7_1,
  124432. _vq_quantmap__16c2_s_p7_1,
  124433. 11,
  124434. 11
  124435. };
  124436. static static_codebook _16c2_s_p7_1 = {
  124437. 2, 121,
  124438. _vq_lengthlist__16c2_s_p7_1,
  124439. 1, -531365888, 1611661312, 4, 0,
  124440. _vq_quantlist__16c2_s_p7_1,
  124441. NULL,
  124442. &_vq_auxt__16c2_s_p7_1,
  124443. NULL,
  124444. 0
  124445. };
  124446. static long _vq_quantlist__16c2_s_p8_0[] = {
  124447. 7,
  124448. 6,
  124449. 8,
  124450. 5,
  124451. 9,
  124452. 4,
  124453. 10,
  124454. 3,
  124455. 11,
  124456. 2,
  124457. 12,
  124458. 1,
  124459. 13,
  124460. 0,
  124461. 14,
  124462. };
  124463. static long _vq_lengthlist__16c2_s_p8_0[] = {
  124464. 1, 4, 4, 7, 6, 7, 7, 6, 6, 8, 8, 9, 9,10,10, 6,
  124465. 6, 6, 8, 8, 9, 8, 8, 8, 9, 9,11,10,11,11, 7, 6,
  124466. 6, 8, 8, 9, 8, 7, 7, 9, 9,10,10,12,11,14, 8, 8,
  124467. 8, 9, 9, 9, 9, 9,10, 9,10,10,11,13,14, 8, 8, 8,
  124468. 8, 9, 9, 8, 8, 9, 9,10,10,11,12,14,13,11, 9, 9,
  124469. 9, 9, 9, 9, 9,10,11,10,13,12,14,11,13, 8, 9, 9,
  124470. 9, 9, 9,10,10,11,10,13,12,14,14,14, 8, 9, 9, 9,
  124471. 11,11,11,11,11,12,13,13,14,14,14, 9, 8, 9, 9,10,
  124472. 10,12,10,11,12,12,14,14,14,14,11,12,10,10,12,12,
  124473. 12,12,13,14,12,12,14,14,14,12,12, 9,10,11,11,12,
  124474. 14,12,14,14,14,14,14,14,14,14,11,11,12,11,12,14,
  124475. 14,14,14,14,14,14,14,14,14,12,11,11,11,11,14,14,
  124476. 14,14,14,14,14,14,14,14,14,14,13,12,14,14,14,14,
  124477. 14,14,14,14,14,14,14,14,14,12,12,12,13,14,14,13,
  124478. 13,
  124479. };
  124480. static float _vq_quantthresh__16c2_s_p8_0[] = {
  124481. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  124482. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  124483. };
  124484. static long _vq_quantmap__16c2_s_p8_0[] = {
  124485. 13, 11, 9, 7, 5, 3, 1, 0,
  124486. 2, 4, 6, 8, 10, 12, 14,
  124487. };
  124488. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_0 = {
  124489. _vq_quantthresh__16c2_s_p8_0,
  124490. _vq_quantmap__16c2_s_p8_0,
  124491. 15,
  124492. 15
  124493. };
  124494. static static_codebook _16c2_s_p8_0 = {
  124495. 2, 225,
  124496. _vq_lengthlist__16c2_s_p8_0,
  124497. 1, -520986624, 1620377600, 4, 0,
  124498. _vq_quantlist__16c2_s_p8_0,
  124499. NULL,
  124500. &_vq_auxt__16c2_s_p8_0,
  124501. NULL,
  124502. 0
  124503. };
  124504. static long _vq_quantlist__16c2_s_p8_1[] = {
  124505. 10,
  124506. 9,
  124507. 11,
  124508. 8,
  124509. 12,
  124510. 7,
  124511. 13,
  124512. 6,
  124513. 14,
  124514. 5,
  124515. 15,
  124516. 4,
  124517. 16,
  124518. 3,
  124519. 17,
  124520. 2,
  124521. 18,
  124522. 1,
  124523. 19,
  124524. 0,
  124525. 20,
  124526. };
  124527. static long _vq_lengthlist__16c2_s_p8_1[] = {
  124528. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  124529. 8, 8, 8, 8, 8,11,12,11, 7, 7, 8, 8, 8, 8, 9, 9,
  124530. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,11,11,10, 7, 7, 8,
  124531. 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  124532. 11,11, 8, 7, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 9,10,
  124533. 10, 9,10,10,11,11,12, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  124534. 9, 9, 9,10, 9,10,10,10,10,11,11,11, 8, 8, 9, 9,
  124535. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  124536. 11, 8, 8, 9, 8, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,
  124537. 10, 9,10,11,11,11, 9, 9, 9, 9,10, 9, 9, 9,10,10,
  124538. 9,10, 9,10,10,10,10,10,11,12,11,11,11, 9, 9, 9,
  124539. 9, 9,10,10, 9,10,10,10,10,10,10,10,10,12,11,13,
  124540. 13,11, 9, 9, 9, 9,10,10, 9,10,10,10,10,11,10,10,
  124541. 10,10,11,12,11,12,11, 9, 9, 9,10,10, 9,10,10,10,
  124542. 10,10,10,10,10,10,10,11,11,11,12,11, 9,10,10,10,
  124543. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,12,12,
  124544. 11,11,11,10, 9,10,10,10,10,10,10,10,10,11,10,10,
  124545. 10,11,11,11,11,11,11,11,10,10,10,11,10,10,10,10,
  124546. 10,10,10,10,10,10,11,11,11,11,12,12,11,10,10,10,
  124547. 10,10,10,10,10,11,10,10,10,11,10,12,11,11,12,11,
  124548. 11,11,10,10,10,10,10,11,10,10,10,10,10,11,10,10,
  124549. 11,11,11,12,11,12,11,11,12,10,10,10,10,10,10,10,
  124550. 11,10,10,11,10,12,11,11,11,12,11,11,11,11,10,10,
  124551. 10,10,10,10,10,11,11,11,10,11,12,11,11,11,12,11,
  124552. 12,11,12,10,11,10,10,10,10,11,10,10,10,10,10,10,
  124553. 12,11,11,11,11,11,12,12,10,10,10,10,10,11,10,10,
  124554. 11,10,11,11,11,11,11,11,11,11,11,11,11,11,12,11,
  124555. 10,11,10,10,10,10,10,10,10,
  124556. };
  124557. static float _vq_quantthresh__16c2_s_p8_1[] = {
  124558. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  124559. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  124560. 6.5, 7.5, 8.5, 9.5,
  124561. };
  124562. static long _vq_quantmap__16c2_s_p8_1[] = {
  124563. 19, 17, 15, 13, 11, 9, 7, 5,
  124564. 3, 1, 0, 2, 4, 6, 8, 10,
  124565. 12, 14, 16, 18, 20,
  124566. };
  124567. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_1 = {
  124568. _vq_quantthresh__16c2_s_p8_1,
  124569. _vq_quantmap__16c2_s_p8_1,
  124570. 21,
  124571. 21
  124572. };
  124573. static static_codebook _16c2_s_p8_1 = {
  124574. 2, 441,
  124575. _vq_lengthlist__16c2_s_p8_1,
  124576. 1, -529268736, 1611661312, 5, 0,
  124577. _vq_quantlist__16c2_s_p8_1,
  124578. NULL,
  124579. &_vq_auxt__16c2_s_p8_1,
  124580. NULL,
  124581. 0
  124582. };
  124583. static long _vq_quantlist__16c2_s_p9_0[] = {
  124584. 6,
  124585. 5,
  124586. 7,
  124587. 4,
  124588. 8,
  124589. 3,
  124590. 9,
  124591. 2,
  124592. 10,
  124593. 1,
  124594. 11,
  124595. 0,
  124596. 12,
  124597. };
  124598. static long _vq_lengthlist__16c2_s_p9_0[] = {
  124599. 1, 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, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124602. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124603. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124604. 9, 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, 8, 8, 8, 8, 8, 8, 8,
  124607. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124608. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124609. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124610. };
  124611. static float _vq_quantthresh__16c2_s_p9_0[] = {
  124612. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5,
  124613. 2327.5, 3258.5, 4189.5, 5120.5,
  124614. };
  124615. static long _vq_quantmap__16c2_s_p9_0[] = {
  124616. 11, 9, 7, 5, 3, 1, 0, 2,
  124617. 4, 6, 8, 10, 12,
  124618. };
  124619. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_0 = {
  124620. _vq_quantthresh__16c2_s_p9_0,
  124621. _vq_quantmap__16c2_s_p9_0,
  124622. 13,
  124623. 13
  124624. };
  124625. static static_codebook _16c2_s_p9_0 = {
  124626. 2, 169,
  124627. _vq_lengthlist__16c2_s_p9_0,
  124628. 1, -510275072, 1631393792, 4, 0,
  124629. _vq_quantlist__16c2_s_p9_0,
  124630. NULL,
  124631. &_vq_auxt__16c2_s_p9_0,
  124632. NULL,
  124633. 0
  124634. };
  124635. static long _vq_quantlist__16c2_s_p9_1[] = {
  124636. 8,
  124637. 7,
  124638. 9,
  124639. 6,
  124640. 10,
  124641. 5,
  124642. 11,
  124643. 4,
  124644. 12,
  124645. 3,
  124646. 13,
  124647. 2,
  124648. 14,
  124649. 1,
  124650. 15,
  124651. 0,
  124652. 16,
  124653. };
  124654. static long _vq_lengthlist__16c2_s_p9_1[] = {
  124655. 1, 5, 5, 9, 8, 7, 7, 7, 6,10,11,11,11,11,11,11,
  124656. 11, 8, 7, 6, 8, 8,10, 9,10,10,10, 9,11,10,10,10,
  124657. 10,10, 8, 6, 6, 8, 8, 9, 8, 9, 8, 9,10,10,10,10,
  124658. 10,10,10,10, 8,10, 9, 9, 9, 9,10,10,10,10,10,10,
  124659. 10,10,10,10,10, 8, 9, 9, 9,10,10, 9,10,10,10,10,
  124660. 10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,10,10,10,
  124661. 10,10,10,10,10,10,10,10, 9, 8, 8, 9, 9,10,10,10,
  124662. 10,10,10,10,10,10,10,10,10,10, 9,10, 9, 9,10,10,
  124663. 10,10,10,10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,
  124664. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  124665. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124666. 8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124667. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124668. 10,10,10,10,10,10,10,10,10,10,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,10,10,10, 9,10, 9,10,10,10,10,10,10,10,10,10,
  124671. 10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,
  124672. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124673. 10,
  124674. };
  124675. static float _vq_quantthresh__16c2_s_p9_1[] = {
  124676. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -24.5,
  124677. 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5, 367.5,
  124678. };
  124679. static long _vq_quantmap__16c2_s_p9_1[] = {
  124680. 15, 13, 11, 9, 7, 5, 3, 1,
  124681. 0, 2, 4, 6, 8, 10, 12, 14,
  124682. 16,
  124683. };
  124684. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_1 = {
  124685. _vq_quantthresh__16c2_s_p9_1,
  124686. _vq_quantmap__16c2_s_p9_1,
  124687. 17,
  124688. 17
  124689. };
  124690. static static_codebook _16c2_s_p9_1 = {
  124691. 2, 289,
  124692. _vq_lengthlist__16c2_s_p9_1,
  124693. 1, -518488064, 1622704128, 5, 0,
  124694. _vq_quantlist__16c2_s_p9_1,
  124695. NULL,
  124696. &_vq_auxt__16c2_s_p9_1,
  124697. NULL,
  124698. 0
  124699. };
  124700. static long _vq_quantlist__16c2_s_p9_2[] = {
  124701. 13,
  124702. 12,
  124703. 14,
  124704. 11,
  124705. 15,
  124706. 10,
  124707. 16,
  124708. 9,
  124709. 17,
  124710. 8,
  124711. 18,
  124712. 7,
  124713. 19,
  124714. 6,
  124715. 20,
  124716. 5,
  124717. 21,
  124718. 4,
  124719. 22,
  124720. 3,
  124721. 23,
  124722. 2,
  124723. 24,
  124724. 1,
  124725. 25,
  124726. 0,
  124727. 26,
  124728. };
  124729. static long _vq_lengthlist__16c2_s_p9_2[] = {
  124730. 1, 4, 4, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  124731. 7, 7, 7, 7, 8, 7, 8, 7, 7, 4, 4,
  124732. };
  124733. static float _vq_quantthresh__16c2_s_p9_2[] = {
  124734. -12.5, -11.5, -10.5, -9.5, -8.5, -7.5, -6.5, -5.5,
  124735. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124736. 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5,
  124737. 11.5, 12.5,
  124738. };
  124739. static long _vq_quantmap__16c2_s_p9_2[] = {
  124740. 25, 23, 21, 19, 17, 15, 13, 11,
  124741. 9, 7, 5, 3, 1, 0, 2, 4,
  124742. 6, 8, 10, 12, 14, 16, 18, 20,
  124743. 22, 24, 26,
  124744. };
  124745. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_2 = {
  124746. _vq_quantthresh__16c2_s_p9_2,
  124747. _vq_quantmap__16c2_s_p9_2,
  124748. 27,
  124749. 27
  124750. };
  124751. static static_codebook _16c2_s_p9_2 = {
  124752. 1, 27,
  124753. _vq_lengthlist__16c2_s_p9_2,
  124754. 1, -528875520, 1611661312, 5, 0,
  124755. _vq_quantlist__16c2_s_p9_2,
  124756. NULL,
  124757. &_vq_auxt__16c2_s_p9_2,
  124758. NULL,
  124759. 0
  124760. };
  124761. static long _huff_lengthlist__16c2_s_short[] = {
  124762. 7,10,11,11,11,14,15,15,17,14, 8, 6, 7, 7, 8, 9,
  124763. 11,11,14,17, 9, 6, 6, 6, 7, 7,10,11,15,16, 9, 6,
  124764. 6, 4, 4, 5, 8, 9,12,16,10, 6, 6, 4, 4, 4, 6, 9,
  124765. 13,16,10, 7, 6, 5, 4, 3, 5, 7,13,16,11, 9, 8, 7,
  124766. 6, 5, 5, 6,12,15,10,10,10, 9, 7, 6, 6, 7,11,15,
  124767. 13,13,13,13,11,10,10, 9,12,16,16,16,16,14,16,15,
  124768. 15,12,14,14,
  124769. };
  124770. static static_codebook _huff_book__16c2_s_short = {
  124771. 2, 100,
  124772. _huff_lengthlist__16c2_s_short,
  124773. 0, 0, 0, 0, 0,
  124774. NULL,
  124775. NULL,
  124776. NULL,
  124777. NULL,
  124778. 0
  124779. };
  124780. static long _vq_quantlist__8c0_s_p1_0[] = {
  124781. 1,
  124782. 0,
  124783. 2,
  124784. };
  124785. static long _vq_lengthlist__8c0_s_p1_0[] = {
  124786. 1, 5, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  124787. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124791. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  124792. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124796. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  124797. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  124832. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  124833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  124837. 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  124838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9,10, 0, 0,
  124842. 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  124843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124877. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  124878. 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124882. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  124883. 0, 0, 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 0, 0,
  124884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124887. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  124888. 0, 0, 0, 0, 0, 0, 8,11, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125196. 0,
  125197. };
  125198. static float _vq_quantthresh__8c0_s_p1_0[] = {
  125199. -0.5, 0.5,
  125200. };
  125201. static long _vq_quantmap__8c0_s_p1_0[] = {
  125202. 1, 0, 2,
  125203. };
  125204. static encode_aux_threshmatch _vq_auxt__8c0_s_p1_0 = {
  125205. _vq_quantthresh__8c0_s_p1_0,
  125206. _vq_quantmap__8c0_s_p1_0,
  125207. 3,
  125208. 3
  125209. };
  125210. static static_codebook _8c0_s_p1_0 = {
  125211. 8, 6561,
  125212. _vq_lengthlist__8c0_s_p1_0,
  125213. 1, -535822336, 1611661312, 2, 0,
  125214. _vq_quantlist__8c0_s_p1_0,
  125215. NULL,
  125216. &_vq_auxt__8c0_s_p1_0,
  125217. NULL,
  125218. 0
  125219. };
  125220. static long _vq_quantlist__8c0_s_p2_0[] = {
  125221. 2,
  125222. 1,
  125223. 3,
  125224. 0,
  125225. 4,
  125226. };
  125227. static long _vq_lengthlist__8c0_s_p2_0[] = {
  125228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125267. 0,
  125268. };
  125269. static float _vq_quantthresh__8c0_s_p2_0[] = {
  125270. -1.5, -0.5, 0.5, 1.5,
  125271. };
  125272. static long _vq_quantmap__8c0_s_p2_0[] = {
  125273. 3, 1, 0, 2, 4,
  125274. };
  125275. static encode_aux_threshmatch _vq_auxt__8c0_s_p2_0 = {
  125276. _vq_quantthresh__8c0_s_p2_0,
  125277. _vq_quantmap__8c0_s_p2_0,
  125278. 5,
  125279. 5
  125280. };
  125281. static static_codebook _8c0_s_p2_0 = {
  125282. 4, 625,
  125283. _vq_lengthlist__8c0_s_p2_0,
  125284. 1, -533725184, 1611661312, 3, 0,
  125285. _vq_quantlist__8c0_s_p2_0,
  125286. NULL,
  125287. &_vq_auxt__8c0_s_p2_0,
  125288. NULL,
  125289. 0
  125290. };
  125291. static long _vq_quantlist__8c0_s_p3_0[] = {
  125292. 2,
  125293. 1,
  125294. 3,
  125295. 0,
  125296. 4,
  125297. };
  125298. static long _vq_lengthlist__8c0_s_p3_0[] = {
  125299. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 6, 7, 7, 0, 0,
  125301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125302. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 8, 8,
  125304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125305. 0, 0, 0, 0, 6, 7, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  125306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125338. 0,
  125339. };
  125340. static float _vq_quantthresh__8c0_s_p3_0[] = {
  125341. -1.5, -0.5, 0.5, 1.5,
  125342. };
  125343. static long _vq_quantmap__8c0_s_p3_0[] = {
  125344. 3, 1, 0, 2, 4,
  125345. };
  125346. static encode_aux_threshmatch _vq_auxt__8c0_s_p3_0 = {
  125347. _vq_quantthresh__8c0_s_p3_0,
  125348. _vq_quantmap__8c0_s_p3_0,
  125349. 5,
  125350. 5
  125351. };
  125352. static static_codebook _8c0_s_p3_0 = {
  125353. 4, 625,
  125354. _vq_lengthlist__8c0_s_p3_0,
  125355. 1, -533725184, 1611661312, 3, 0,
  125356. _vq_quantlist__8c0_s_p3_0,
  125357. NULL,
  125358. &_vq_auxt__8c0_s_p3_0,
  125359. NULL,
  125360. 0
  125361. };
  125362. static long _vq_quantlist__8c0_s_p4_0[] = {
  125363. 4,
  125364. 3,
  125365. 5,
  125366. 2,
  125367. 6,
  125368. 1,
  125369. 7,
  125370. 0,
  125371. 8,
  125372. };
  125373. static long _vq_lengthlist__8c0_s_p4_0[] = {
  125374. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  125375. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  125376. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  125377. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  125378. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125379. 0,
  125380. };
  125381. static float _vq_quantthresh__8c0_s_p4_0[] = {
  125382. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125383. };
  125384. static long _vq_quantmap__8c0_s_p4_0[] = {
  125385. 7, 5, 3, 1, 0, 2, 4, 6,
  125386. 8,
  125387. };
  125388. static encode_aux_threshmatch _vq_auxt__8c0_s_p4_0 = {
  125389. _vq_quantthresh__8c0_s_p4_0,
  125390. _vq_quantmap__8c0_s_p4_0,
  125391. 9,
  125392. 9
  125393. };
  125394. static static_codebook _8c0_s_p4_0 = {
  125395. 2, 81,
  125396. _vq_lengthlist__8c0_s_p4_0,
  125397. 1, -531628032, 1611661312, 4, 0,
  125398. _vq_quantlist__8c0_s_p4_0,
  125399. NULL,
  125400. &_vq_auxt__8c0_s_p4_0,
  125401. NULL,
  125402. 0
  125403. };
  125404. static long _vq_quantlist__8c0_s_p5_0[] = {
  125405. 4,
  125406. 3,
  125407. 5,
  125408. 2,
  125409. 6,
  125410. 1,
  125411. 7,
  125412. 0,
  125413. 8,
  125414. };
  125415. static long _vq_lengthlist__8c0_s_p5_0[] = {
  125416. 1, 3, 3, 5, 5, 7, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  125417. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 9, 0, 0, 0, 8, 8,
  125418. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8, 9, 9, 0, 0, 0,
  125419. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  125420. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  125421. 10,
  125422. };
  125423. static float _vq_quantthresh__8c0_s_p5_0[] = {
  125424. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125425. };
  125426. static long _vq_quantmap__8c0_s_p5_0[] = {
  125427. 7, 5, 3, 1, 0, 2, 4, 6,
  125428. 8,
  125429. };
  125430. static encode_aux_threshmatch _vq_auxt__8c0_s_p5_0 = {
  125431. _vq_quantthresh__8c0_s_p5_0,
  125432. _vq_quantmap__8c0_s_p5_0,
  125433. 9,
  125434. 9
  125435. };
  125436. static static_codebook _8c0_s_p5_0 = {
  125437. 2, 81,
  125438. _vq_lengthlist__8c0_s_p5_0,
  125439. 1, -531628032, 1611661312, 4, 0,
  125440. _vq_quantlist__8c0_s_p5_0,
  125441. NULL,
  125442. &_vq_auxt__8c0_s_p5_0,
  125443. NULL,
  125444. 0
  125445. };
  125446. static long _vq_quantlist__8c0_s_p6_0[] = {
  125447. 8,
  125448. 7,
  125449. 9,
  125450. 6,
  125451. 10,
  125452. 5,
  125453. 11,
  125454. 4,
  125455. 12,
  125456. 3,
  125457. 13,
  125458. 2,
  125459. 14,
  125460. 1,
  125461. 15,
  125462. 0,
  125463. 16,
  125464. };
  125465. static long _vq_lengthlist__8c0_s_p6_0[] = {
  125466. 1, 3, 3, 6, 6, 8, 8, 9, 9, 8, 8,10, 9,10,10,11,
  125467. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  125468. 11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  125469. 11,12,11, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,10,10,
  125470. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,11,
  125471. 10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,10,
  125472. 11,11,11,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,
  125473. 10,11,11,12,12,13,13, 0, 0, 0,10,10,10,10,11,11,
  125474. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10, 9,10,
  125475. 11,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  125476. 10, 9,10,11,12,12,13,13,14,13, 0, 0, 0, 0, 0, 9,
  125477. 9, 9,10,10,10,11,11,13,12,13,13, 0, 0, 0, 0, 0,
  125478. 10,10,10,10,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  125479. 0, 0, 0,10,10,11,11,12,12,13,13,13,14, 0, 0, 0,
  125480. 0, 0, 0, 0,11,11,11,11,12,12,13,14,14,14, 0, 0,
  125481. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,14,13, 0,
  125482. 0, 0, 0, 0, 0, 0,11,11,12,12,13,13,14,14,14,14,
  125483. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  125484. 14,
  125485. };
  125486. static float _vq_quantthresh__8c0_s_p6_0[] = {
  125487. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  125488. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  125489. };
  125490. static long _vq_quantmap__8c0_s_p6_0[] = {
  125491. 15, 13, 11, 9, 7, 5, 3, 1,
  125492. 0, 2, 4, 6, 8, 10, 12, 14,
  125493. 16,
  125494. };
  125495. static encode_aux_threshmatch _vq_auxt__8c0_s_p6_0 = {
  125496. _vq_quantthresh__8c0_s_p6_0,
  125497. _vq_quantmap__8c0_s_p6_0,
  125498. 17,
  125499. 17
  125500. };
  125501. static static_codebook _8c0_s_p6_0 = {
  125502. 2, 289,
  125503. _vq_lengthlist__8c0_s_p6_0,
  125504. 1, -529530880, 1611661312, 5, 0,
  125505. _vq_quantlist__8c0_s_p6_0,
  125506. NULL,
  125507. &_vq_auxt__8c0_s_p6_0,
  125508. NULL,
  125509. 0
  125510. };
  125511. static long _vq_quantlist__8c0_s_p7_0[] = {
  125512. 1,
  125513. 0,
  125514. 2,
  125515. };
  125516. static long _vq_lengthlist__8c0_s_p7_0[] = {
  125517. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,11, 9,10,12,
  125518. 9,10, 4, 7, 7,10,10,10,11, 9, 9, 6,11,10,11,11,
  125519. 12,11,11,11, 6,10,10,11,11,12,11,10,10, 6, 9,10,
  125520. 11,11,11,11,10,10, 7,10,11,12,11,11,12,11,12, 6,
  125521. 9, 9,10, 9, 9,11,10,10, 6, 9, 9,10,10,10,11,10,
  125522. 10,
  125523. };
  125524. static float _vq_quantthresh__8c0_s_p7_0[] = {
  125525. -5.5, 5.5,
  125526. };
  125527. static long _vq_quantmap__8c0_s_p7_0[] = {
  125528. 1, 0, 2,
  125529. };
  125530. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_0 = {
  125531. _vq_quantthresh__8c0_s_p7_0,
  125532. _vq_quantmap__8c0_s_p7_0,
  125533. 3,
  125534. 3
  125535. };
  125536. static static_codebook _8c0_s_p7_0 = {
  125537. 4, 81,
  125538. _vq_lengthlist__8c0_s_p7_0,
  125539. 1, -529137664, 1618345984, 2, 0,
  125540. _vq_quantlist__8c0_s_p7_0,
  125541. NULL,
  125542. &_vq_auxt__8c0_s_p7_0,
  125543. NULL,
  125544. 0
  125545. };
  125546. static long _vq_quantlist__8c0_s_p7_1[] = {
  125547. 5,
  125548. 4,
  125549. 6,
  125550. 3,
  125551. 7,
  125552. 2,
  125553. 8,
  125554. 1,
  125555. 9,
  125556. 0,
  125557. 10,
  125558. };
  125559. static long _vq_lengthlist__8c0_s_p7_1[] = {
  125560. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10, 7, 7,
  125561. 8, 8, 9, 9, 9, 9,10,10, 9, 7, 7, 8, 8, 9, 9, 9,
  125562. 9,10,10,10, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10, 8,
  125563. 8, 9, 9, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9,10,
  125564. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,11,10,11,
  125565. 9, 9, 9, 9,10,10,10,10,11,11,11,10,10, 9, 9,10,
  125566. 10,10, 9,11,10,10,10,10,10,10, 9, 9,10,10,11,11,
  125567. 10,10,10, 9, 9, 9,10,10,10,
  125568. };
  125569. static float _vq_quantthresh__8c0_s_p7_1[] = {
  125570. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125571. 3.5, 4.5,
  125572. };
  125573. static long _vq_quantmap__8c0_s_p7_1[] = {
  125574. 9, 7, 5, 3, 1, 0, 2, 4,
  125575. 6, 8, 10,
  125576. };
  125577. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_1 = {
  125578. _vq_quantthresh__8c0_s_p7_1,
  125579. _vq_quantmap__8c0_s_p7_1,
  125580. 11,
  125581. 11
  125582. };
  125583. static static_codebook _8c0_s_p7_1 = {
  125584. 2, 121,
  125585. _vq_lengthlist__8c0_s_p7_1,
  125586. 1, -531365888, 1611661312, 4, 0,
  125587. _vq_quantlist__8c0_s_p7_1,
  125588. NULL,
  125589. &_vq_auxt__8c0_s_p7_1,
  125590. NULL,
  125591. 0
  125592. };
  125593. static long _vq_quantlist__8c0_s_p8_0[] = {
  125594. 6,
  125595. 5,
  125596. 7,
  125597. 4,
  125598. 8,
  125599. 3,
  125600. 9,
  125601. 2,
  125602. 10,
  125603. 1,
  125604. 11,
  125605. 0,
  125606. 12,
  125607. };
  125608. static long _vq_lengthlist__8c0_s_p8_0[] = {
  125609. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 6, 6,
  125610. 7, 7, 8, 8, 7, 7, 8, 9,10,10, 7, 6, 6, 7, 7, 8,
  125611. 7, 7, 7, 9, 9,10,12, 0, 8, 8, 8, 8, 8, 9, 8, 8,
  125612. 9, 9,10,10, 0, 8, 8, 8, 8, 8, 9, 8, 9, 9, 9,11,
  125613. 10, 0, 0,13, 9, 8, 9, 9, 9, 9,10,10,11,11, 0,13,
  125614. 0, 9, 9, 9, 9, 9, 9,11,10,11,11, 0, 0, 0, 8, 9,
  125615. 10, 9,10,10,13,11,12,12, 0, 0, 0, 8, 9, 9, 9,10,
  125616. 10,13,12,12,13, 0, 0, 0,12, 0,10,10,12,11,10,11,
  125617. 12,12, 0, 0, 0,13,13,10,10,10,11,12, 0,13, 0, 0,
  125618. 0, 0, 0, 0,13,11, 0,12,12,12,13,12, 0, 0, 0, 0,
  125619. 0, 0,13,13,11,13,13,11,12,
  125620. };
  125621. static float _vq_quantthresh__8c0_s_p8_0[] = {
  125622. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  125623. 12.5, 17.5, 22.5, 27.5,
  125624. };
  125625. static long _vq_quantmap__8c0_s_p8_0[] = {
  125626. 11, 9, 7, 5, 3, 1, 0, 2,
  125627. 4, 6, 8, 10, 12,
  125628. };
  125629. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_0 = {
  125630. _vq_quantthresh__8c0_s_p8_0,
  125631. _vq_quantmap__8c0_s_p8_0,
  125632. 13,
  125633. 13
  125634. };
  125635. static static_codebook _8c0_s_p8_0 = {
  125636. 2, 169,
  125637. _vq_lengthlist__8c0_s_p8_0,
  125638. 1, -526516224, 1616117760, 4, 0,
  125639. _vq_quantlist__8c0_s_p8_0,
  125640. NULL,
  125641. &_vq_auxt__8c0_s_p8_0,
  125642. NULL,
  125643. 0
  125644. };
  125645. static long _vq_quantlist__8c0_s_p8_1[] = {
  125646. 2,
  125647. 1,
  125648. 3,
  125649. 0,
  125650. 4,
  125651. };
  125652. static long _vq_lengthlist__8c0_s_p8_1[] = {
  125653. 1, 3, 4, 5, 5, 7, 6, 6, 6, 5, 7, 7, 7, 6, 6, 7,
  125654. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  125655. };
  125656. static float _vq_quantthresh__8c0_s_p8_1[] = {
  125657. -1.5, -0.5, 0.5, 1.5,
  125658. };
  125659. static long _vq_quantmap__8c0_s_p8_1[] = {
  125660. 3, 1, 0, 2, 4,
  125661. };
  125662. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_1 = {
  125663. _vq_quantthresh__8c0_s_p8_1,
  125664. _vq_quantmap__8c0_s_p8_1,
  125665. 5,
  125666. 5
  125667. };
  125668. static static_codebook _8c0_s_p8_1 = {
  125669. 2, 25,
  125670. _vq_lengthlist__8c0_s_p8_1,
  125671. 1, -533725184, 1611661312, 3, 0,
  125672. _vq_quantlist__8c0_s_p8_1,
  125673. NULL,
  125674. &_vq_auxt__8c0_s_p8_1,
  125675. NULL,
  125676. 0
  125677. };
  125678. static long _vq_quantlist__8c0_s_p9_0[] = {
  125679. 1,
  125680. 0,
  125681. 2,
  125682. };
  125683. static long _vq_lengthlist__8c0_s_p9_0[] = {
  125684. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125685. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125686. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  125687. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  125688. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  125689. 7,
  125690. };
  125691. static float _vq_quantthresh__8c0_s_p9_0[] = {
  125692. -157.5, 157.5,
  125693. };
  125694. static long _vq_quantmap__8c0_s_p9_0[] = {
  125695. 1, 0, 2,
  125696. };
  125697. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_0 = {
  125698. _vq_quantthresh__8c0_s_p9_0,
  125699. _vq_quantmap__8c0_s_p9_0,
  125700. 3,
  125701. 3
  125702. };
  125703. static static_codebook _8c0_s_p9_0 = {
  125704. 4, 81,
  125705. _vq_lengthlist__8c0_s_p9_0,
  125706. 1, -518803456, 1628680192, 2, 0,
  125707. _vq_quantlist__8c0_s_p9_0,
  125708. NULL,
  125709. &_vq_auxt__8c0_s_p9_0,
  125710. NULL,
  125711. 0
  125712. };
  125713. static long _vq_quantlist__8c0_s_p9_1[] = {
  125714. 7,
  125715. 6,
  125716. 8,
  125717. 5,
  125718. 9,
  125719. 4,
  125720. 10,
  125721. 3,
  125722. 11,
  125723. 2,
  125724. 12,
  125725. 1,
  125726. 13,
  125727. 0,
  125728. 14,
  125729. };
  125730. static long _vq_lengthlist__8c0_s_p9_1[] = {
  125731. 1, 4, 4, 5, 5,10, 8,11,11,11,11,11,11,11,11, 6,
  125732. 6, 6, 7, 6,11,10,11,11,11,11,11,11,11,11, 7, 5,
  125733. 6, 6, 6, 8, 7,11,11,11,11,11,11,11,11,11, 7, 8,
  125734. 8, 8, 9, 9,11,11,11,11,11,11,11,11,11, 9, 8, 7,
  125735. 8, 9,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  125736. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,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,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125743. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125744. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125745. 11,
  125746. };
  125747. static float _vq_quantthresh__8c0_s_p9_1[] = {
  125748. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  125749. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  125750. };
  125751. static long _vq_quantmap__8c0_s_p9_1[] = {
  125752. 13, 11, 9, 7, 5, 3, 1, 0,
  125753. 2, 4, 6, 8, 10, 12, 14,
  125754. };
  125755. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_1 = {
  125756. _vq_quantthresh__8c0_s_p9_1,
  125757. _vq_quantmap__8c0_s_p9_1,
  125758. 15,
  125759. 15
  125760. };
  125761. static static_codebook _8c0_s_p9_1 = {
  125762. 2, 225,
  125763. _vq_lengthlist__8c0_s_p9_1,
  125764. 1, -520986624, 1620377600, 4, 0,
  125765. _vq_quantlist__8c0_s_p9_1,
  125766. NULL,
  125767. &_vq_auxt__8c0_s_p9_1,
  125768. NULL,
  125769. 0
  125770. };
  125771. static long _vq_quantlist__8c0_s_p9_2[] = {
  125772. 10,
  125773. 9,
  125774. 11,
  125775. 8,
  125776. 12,
  125777. 7,
  125778. 13,
  125779. 6,
  125780. 14,
  125781. 5,
  125782. 15,
  125783. 4,
  125784. 16,
  125785. 3,
  125786. 17,
  125787. 2,
  125788. 18,
  125789. 1,
  125790. 19,
  125791. 0,
  125792. 20,
  125793. };
  125794. static long _vq_lengthlist__8c0_s_p9_2[] = {
  125795. 1, 5, 5, 7, 7, 8, 7, 8, 8,10,10, 9, 9,10,10,10,
  125796. 11,11,10,12,11,12,12,12, 9, 8, 8, 8, 8, 8, 9,10,
  125797. 10,10,10,11,11,11,10,11,11,12,12,11,12, 8, 8, 7,
  125798. 7, 8, 9,10,10,10, 9,10,10, 9,10,10,11,11,11,11,
  125799. 11,11, 9, 9, 9, 9, 8, 9,10,10,11,10,10,11,11,12,
  125800. 10,10,12,12,11,11,10, 9, 9,10, 8, 9,10,10,10, 9,
  125801. 10,10,11,11,10,11,10,10,10,12,12,12, 9,10, 9,10,
  125802. 9, 9,10,10,11,11,11,11,10,10,10,11,12,11,12,11,
  125803. 12,10,11,10,11, 9,10, 9,10, 9,10,10, 9,10,10,11,
  125804. 10,11,11,11,11,12,11, 9,10,10,10,10,11,11,11,11,
  125805. 11,10,11,11,11,11,10,12,10,12,12,11,12,10,10,11,
  125806. 10, 9,11,10,11, 9,10,11,10,10,10,11,11,11,11,12,
  125807. 12,10, 9, 9,11,10, 9,12,11,10,12,12,11,11,11,11,
  125808. 10,11,11,12,11,10,12, 9,11,10,11,10,10,11,10,11,
  125809. 9,10,10,10,11,12,11,11,12,11,10,10,11,11, 9,10,
  125810. 10,12,10,11,10,10,10, 9,10,10,10,10, 9,10,10,11,
  125811. 11,11,11,12,11,10,10,10,10,11,11,10,11,11, 9,11,
  125812. 10,12,10,12,11,10,11,10,10,10,11,10,10,11,11,10,
  125813. 11,10,10,10,10,11,11,12,10,10,10,11,10,11,12,11,
  125814. 10,11,10,10,11,11,10,12,10, 9,10,10,11,11,11,10,
  125815. 12,10,10,11,11,11,10,10,11,10,10,10,11,10,11,10,
  125816. 12,11,11,10,10,10,12,10,10,11, 9,10,11,11,11,10,
  125817. 10,11,10,10, 9,11,11,12,12,11,12,11,11,11,11,11,
  125818. 11, 9,10,11,10,12,10,10,10,10,11,10,10,11,10,10,
  125819. 12,10,10,10,10,10, 9,12,10,10,10,10,12, 9,11,10,
  125820. 10,11,10,12,12,10,12,12,12,10,10,10,10, 9,10,11,
  125821. 10,10,12,10,10,12,11,10,11,10,10,12,11,10,12,10,
  125822. 10,11, 9,11,10, 9,10, 9,10,
  125823. };
  125824. static float _vq_quantthresh__8c0_s_p9_2[] = {
  125825. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  125826. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  125827. 6.5, 7.5, 8.5, 9.5,
  125828. };
  125829. static long _vq_quantmap__8c0_s_p9_2[] = {
  125830. 19, 17, 15, 13, 11, 9, 7, 5,
  125831. 3, 1, 0, 2, 4, 6, 8, 10,
  125832. 12, 14, 16, 18, 20,
  125833. };
  125834. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_2 = {
  125835. _vq_quantthresh__8c0_s_p9_2,
  125836. _vq_quantmap__8c0_s_p9_2,
  125837. 21,
  125838. 21
  125839. };
  125840. static static_codebook _8c0_s_p9_2 = {
  125841. 2, 441,
  125842. _vq_lengthlist__8c0_s_p9_2,
  125843. 1, -529268736, 1611661312, 5, 0,
  125844. _vq_quantlist__8c0_s_p9_2,
  125845. NULL,
  125846. &_vq_auxt__8c0_s_p9_2,
  125847. NULL,
  125848. 0
  125849. };
  125850. static long _huff_lengthlist__8c0_s_single[] = {
  125851. 4, 5,18, 7,10, 6, 7, 8, 9,10, 5, 2,18, 5, 7, 5,
  125852. 6, 7, 8,11,17,17,17,17,17,17,17,17,17,17, 7, 4,
  125853. 17, 6, 9, 6, 8,10,12,15,11, 7,17, 9, 6, 6, 7, 9,
  125854. 11,15, 6, 4,17, 6, 6, 4, 5, 8,11,16, 6, 6,17, 8,
  125855. 6, 5, 6, 9,13,16, 8, 9,17,11, 9, 8, 8,11,13,17,
  125856. 9,12,17,15,14,13,12,13,14,17,12,15,17,17,17,17,
  125857. 17,16,17,17,
  125858. };
  125859. static static_codebook _huff_book__8c0_s_single = {
  125860. 2, 100,
  125861. _huff_lengthlist__8c0_s_single,
  125862. 0, 0, 0, 0, 0,
  125863. NULL,
  125864. NULL,
  125865. NULL,
  125866. NULL,
  125867. 0
  125868. };
  125869. static long _vq_quantlist__8c1_s_p1_0[] = {
  125870. 1,
  125871. 0,
  125872. 2,
  125873. };
  125874. static long _vq_lengthlist__8c1_s_p1_0[] = {
  125875. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  125876. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125878. 0, 0, 0, 0, 0, 0, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  125881. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125883. 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  125886. 0, 0, 0, 0, 7, 9, 8, 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, 0, 0, 0, 0, 0, 0, 0,
  125918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0,
  125921. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  125922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7, 9, 9, 0, 0, 0,
  125926. 0, 0, 0, 8, 8,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  125927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 7, 9, 9, 0, 0,
  125931. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125966. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  125967. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125971. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  125972. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  125973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125976. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  125977. 0, 0, 0, 0, 0, 0, 8,10, 8, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126285. 0,
  126286. };
  126287. static float _vq_quantthresh__8c1_s_p1_0[] = {
  126288. -0.5, 0.5,
  126289. };
  126290. static long _vq_quantmap__8c1_s_p1_0[] = {
  126291. 1, 0, 2,
  126292. };
  126293. static encode_aux_threshmatch _vq_auxt__8c1_s_p1_0 = {
  126294. _vq_quantthresh__8c1_s_p1_0,
  126295. _vq_quantmap__8c1_s_p1_0,
  126296. 3,
  126297. 3
  126298. };
  126299. static static_codebook _8c1_s_p1_0 = {
  126300. 8, 6561,
  126301. _vq_lengthlist__8c1_s_p1_0,
  126302. 1, -535822336, 1611661312, 2, 0,
  126303. _vq_quantlist__8c1_s_p1_0,
  126304. NULL,
  126305. &_vq_auxt__8c1_s_p1_0,
  126306. NULL,
  126307. 0
  126308. };
  126309. static long _vq_quantlist__8c1_s_p2_0[] = {
  126310. 2,
  126311. 1,
  126312. 3,
  126313. 0,
  126314. 4,
  126315. };
  126316. static long _vq_lengthlist__8c1_s_p2_0[] = {
  126317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126356. 0,
  126357. };
  126358. static float _vq_quantthresh__8c1_s_p2_0[] = {
  126359. -1.5, -0.5, 0.5, 1.5,
  126360. };
  126361. static long _vq_quantmap__8c1_s_p2_0[] = {
  126362. 3, 1, 0, 2, 4,
  126363. };
  126364. static encode_aux_threshmatch _vq_auxt__8c1_s_p2_0 = {
  126365. _vq_quantthresh__8c1_s_p2_0,
  126366. _vq_quantmap__8c1_s_p2_0,
  126367. 5,
  126368. 5
  126369. };
  126370. static static_codebook _8c1_s_p2_0 = {
  126371. 4, 625,
  126372. _vq_lengthlist__8c1_s_p2_0,
  126373. 1, -533725184, 1611661312, 3, 0,
  126374. _vq_quantlist__8c1_s_p2_0,
  126375. NULL,
  126376. &_vq_auxt__8c1_s_p2_0,
  126377. NULL,
  126378. 0
  126379. };
  126380. static long _vq_quantlist__8c1_s_p3_0[] = {
  126381. 2,
  126382. 1,
  126383. 3,
  126384. 0,
  126385. 4,
  126386. };
  126387. static long _vq_lengthlist__8c1_s_p3_0[] = {
  126388. 2, 4, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  126390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126391. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 7, 7,
  126393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126394. 0, 0, 0, 0, 6, 6, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  126395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126427. 0,
  126428. };
  126429. static float _vq_quantthresh__8c1_s_p3_0[] = {
  126430. -1.5, -0.5, 0.5, 1.5,
  126431. };
  126432. static long _vq_quantmap__8c1_s_p3_0[] = {
  126433. 3, 1, 0, 2, 4,
  126434. };
  126435. static encode_aux_threshmatch _vq_auxt__8c1_s_p3_0 = {
  126436. _vq_quantthresh__8c1_s_p3_0,
  126437. _vq_quantmap__8c1_s_p3_0,
  126438. 5,
  126439. 5
  126440. };
  126441. static static_codebook _8c1_s_p3_0 = {
  126442. 4, 625,
  126443. _vq_lengthlist__8c1_s_p3_0,
  126444. 1, -533725184, 1611661312, 3, 0,
  126445. _vq_quantlist__8c1_s_p3_0,
  126446. NULL,
  126447. &_vq_auxt__8c1_s_p3_0,
  126448. NULL,
  126449. 0
  126450. };
  126451. static long _vq_quantlist__8c1_s_p4_0[] = {
  126452. 4,
  126453. 3,
  126454. 5,
  126455. 2,
  126456. 6,
  126457. 1,
  126458. 7,
  126459. 0,
  126460. 8,
  126461. };
  126462. static long _vq_lengthlist__8c1_s_p4_0[] = {
  126463. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  126464. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  126465. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  126466. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  126467. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126468. 0,
  126469. };
  126470. static float _vq_quantthresh__8c1_s_p4_0[] = {
  126471. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126472. };
  126473. static long _vq_quantmap__8c1_s_p4_0[] = {
  126474. 7, 5, 3, 1, 0, 2, 4, 6,
  126475. 8,
  126476. };
  126477. static encode_aux_threshmatch _vq_auxt__8c1_s_p4_0 = {
  126478. _vq_quantthresh__8c1_s_p4_0,
  126479. _vq_quantmap__8c1_s_p4_0,
  126480. 9,
  126481. 9
  126482. };
  126483. static static_codebook _8c1_s_p4_0 = {
  126484. 2, 81,
  126485. _vq_lengthlist__8c1_s_p4_0,
  126486. 1, -531628032, 1611661312, 4, 0,
  126487. _vq_quantlist__8c1_s_p4_0,
  126488. NULL,
  126489. &_vq_auxt__8c1_s_p4_0,
  126490. NULL,
  126491. 0
  126492. };
  126493. static long _vq_quantlist__8c1_s_p5_0[] = {
  126494. 4,
  126495. 3,
  126496. 5,
  126497. 2,
  126498. 6,
  126499. 1,
  126500. 7,
  126501. 0,
  126502. 8,
  126503. };
  126504. static long _vq_lengthlist__8c1_s_p5_0[] = {
  126505. 1, 3, 3, 4, 5, 6, 6, 8, 8, 0, 0, 0, 8, 8, 7, 7,
  126506. 9, 9, 0, 0, 0, 8, 8, 7, 7, 9, 9, 0, 0, 0, 9,10,
  126507. 8, 8, 9, 9, 0, 0, 0,10,10, 8, 8, 9, 9, 0, 0, 0,
  126508. 11,10, 8, 8,10,10, 0, 0, 0,11,11, 8, 8,10,10, 0,
  126509. 0, 0,12,12, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  126510. 10,
  126511. };
  126512. static float _vq_quantthresh__8c1_s_p5_0[] = {
  126513. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126514. };
  126515. static long _vq_quantmap__8c1_s_p5_0[] = {
  126516. 7, 5, 3, 1, 0, 2, 4, 6,
  126517. 8,
  126518. };
  126519. static encode_aux_threshmatch _vq_auxt__8c1_s_p5_0 = {
  126520. _vq_quantthresh__8c1_s_p5_0,
  126521. _vq_quantmap__8c1_s_p5_0,
  126522. 9,
  126523. 9
  126524. };
  126525. static static_codebook _8c1_s_p5_0 = {
  126526. 2, 81,
  126527. _vq_lengthlist__8c1_s_p5_0,
  126528. 1, -531628032, 1611661312, 4, 0,
  126529. _vq_quantlist__8c1_s_p5_0,
  126530. NULL,
  126531. &_vq_auxt__8c1_s_p5_0,
  126532. NULL,
  126533. 0
  126534. };
  126535. static long _vq_quantlist__8c1_s_p6_0[] = {
  126536. 8,
  126537. 7,
  126538. 9,
  126539. 6,
  126540. 10,
  126541. 5,
  126542. 11,
  126543. 4,
  126544. 12,
  126545. 3,
  126546. 13,
  126547. 2,
  126548. 14,
  126549. 1,
  126550. 15,
  126551. 0,
  126552. 16,
  126553. };
  126554. static long _vq_lengthlist__8c1_s_p6_0[] = {
  126555. 1, 3, 3, 5, 5, 8, 8, 8, 8, 9, 9,10,10,11,11,11,
  126556. 11, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11,
  126557. 12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  126558. 11,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,11,
  126559. 12,12,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,
  126560. 11,12,12,12,12, 0, 0, 0,10,10, 9, 9,10,10,10,10,
  126561. 11,11,12,12,13,13, 0, 0, 0,10,10, 9, 9,10,10,10,
  126562. 10,11,11,12,12,13,13, 0, 0, 0,11,11, 9, 9,10,10,
  126563. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  126564. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  126565. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  126566. 9,10,10,11,11,12,11,12,12,13,13, 0, 0, 0, 0, 0,
  126567. 10,10,11,11,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  126568. 0, 0, 0,11,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  126569. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  126570. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,13, 0,
  126571. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  126572. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  126573. 14,
  126574. };
  126575. static float _vq_quantthresh__8c1_s_p6_0[] = {
  126576. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  126577. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  126578. };
  126579. static long _vq_quantmap__8c1_s_p6_0[] = {
  126580. 15, 13, 11, 9, 7, 5, 3, 1,
  126581. 0, 2, 4, 6, 8, 10, 12, 14,
  126582. 16,
  126583. };
  126584. static encode_aux_threshmatch _vq_auxt__8c1_s_p6_0 = {
  126585. _vq_quantthresh__8c1_s_p6_0,
  126586. _vq_quantmap__8c1_s_p6_0,
  126587. 17,
  126588. 17
  126589. };
  126590. static static_codebook _8c1_s_p6_0 = {
  126591. 2, 289,
  126592. _vq_lengthlist__8c1_s_p6_0,
  126593. 1, -529530880, 1611661312, 5, 0,
  126594. _vq_quantlist__8c1_s_p6_0,
  126595. NULL,
  126596. &_vq_auxt__8c1_s_p6_0,
  126597. NULL,
  126598. 0
  126599. };
  126600. static long _vq_quantlist__8c1_s_p7_0[] = {
  126601. 1,
  126602. 0,
  126603. 2,
  126604. };
  126605. static long _vq_lengthlist__8c1_s_p7_0[] = {
  126606. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  126607. 9, 9, 5, 7, 7,10, 9, 9,10, 9, 9, 6,10,10,10,10,
  126608. 10,11,10,10, 6, 9, 9,10, 9,10,11,10,10, 6, 9, 9,
  126609. 10, 9, 9,11, 9,10, 7,10,10,11,11,11,11,10,10, 6,
  126610. 9, 9,10,10,10,11, 9, 9, 6, 9, 9,10,10,10,10, 9,
  126611. 9,
  126612. };
  126613. static float _vq_quantthresh__8c1_s_p7_0[] = {
  126614. -5.5, 5.5,
  126615. };
  126616. static long _vq_quantmap__8c1_s_p7_0[] = {
  126617. 1, 0, 2,
  126618. };
  126619. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_0 = {
  126620. _vq_quantthresh__8c1_s_p7_0,
  126621. _vq_quantmap__8c1_s_p7_0,
  126622. 3,
  126623. 3
  126624. };
  126625. static static_codebook _8c1_s_p7_0 = {
  126626. 4, 81,
  126627. _vq_lengthlist__8c1_s_p7_0,
  126628. 1, -529137664, 1618345984, 2, 0,
  126629. _vq_quantlist__8c1_s_p7_0,
  126630. NULL,
  126631. &_vq_auxt__8c1_s_p7_0,
  126632. NULL,
  126633. 0
  126634. };
  126635. static long _vq_quantlist__8c1_s_p7_1[] = {
  126636. 5,
  126637. 4,
  126638. 6,
  126639. 3,
  126640. 7,
  126641. 2,
  126642. 8,
  126643. 1,
  126644. 9,
  126645. 0,
  126646. 10,
  126647. };
  126648. static long _vq_lengthlist__8c1_s_p7_1[] = {
  126649. 2, 3, 3, 5, 5, 7, 7, 7, 7, 7, 7,10,10, 9, 7, 7,
  126650. 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8,
  126651. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  126652. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  126653. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  126654. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  126655. 8, 8, 8,10,10,10,10,10, 8, 8, 8, 8, 8, 8,10,10,
  126656. 10,10,10, 8, 8, 8, 8, 8, 8,
  126657. };
  126658. static float _vq_quantthresh__8c1_s_p7_1[] = {
  126659. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  126660. 3.5, 4.5,
  126661. };
  126662. static long _vq_quantmap__8c1_s_p7_1[] = {
  126663. 9, 7, 5, 3, 1, 0, 2, 4,
  126664. 6, 8, 10,
  126665. };
  126666. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_1 = {
  126667. _vq_quantthresh__8c1_s_p7_1,
  126668. _vq_quantmap__8c1_s_p7_1,
  126669. 11,
  126670. 11
  126671. };
  126672. static static_codebook _8c1_s_p7_1 = {
  126673. 2, 121,
  126674. _vq_lengthlist__8c1_s_p7_1,
  126675. 1, -531365888, 1611661312, 4, 0,
  126676. _vq_quantlist__8c1_s_p7_1,
  126677. NULL,
  126678. &_vq_auxt__8c1_s_p7_1,
  126679. NULL,
  126680. 0
  126681. };
  126682. static long _vq_quantlist__8c1_s_p8_0[] = {
  126683. 6,
  126684. 5,
  126685. 7,
  126686. 4,
  126687. 8,
  126688. 3,
  126689. 9,
  126690. 2,
  126691. 10,
  126692. 1,
  126693. 11,
  126694. 0,
  126695. 12,
  126696. };
  126697. static long _vq_lengthlist__8c1_s_p8_0[] = {
  126698. 1, 4, 4, 6, 6, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5,
  126699. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  126700. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  126701. 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  126702. 11, 0,12,12, 9, 9, 9, 9,10, 9,10,11,11,11, 0,13,
  126703. 12, 9, 8, 9, 9,10,10,11,11,12,11, 0, 0, 0, 9, 9,
  126704. 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10, 9, 9,10,
  126705. 10,11,11,12,12, 0, 0, 0,13,13,10,10,11,11,12,11,
  126706. 13,12, 0, 0, 0,14,14,10,10,11,10,11,11,12,12, 0,
  126707. 0, 0, 0, 0,12,12,11,11,12,12,13,13, 0, 0, 0, 0,
  126708. 0,12,12,11,10,12,11,13,12,
  126709. };
  126710. static float _vq_quantthresh__8c1_s_p8_0[] = {
  126711. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  126712. 12.5, 17.5, 22.5, 27.5,
  126713. };
  126714. static long _vq_quantmap__8c1_s_p8_0[] = {
  126715. 11, 9, 7, 5, 3, 1, 0, 2,
  126716. 4, 6, 8, 10, 12,
  126717. };
  126718. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_0 = {
  126719. _vq_quantthresh__8c1_s_p8_0,
  126720. _vq_quantmap__8c1_s_p8_0,
  126721. 13,
  126722. 13
  126723. };
  126724. static static_codebook _8c1_s_p8_0 = {
  126725. 2, 169,
  126726. _vq_lengthlist__8c1_s_p8_0,
  126727. 1, -526516224, 1616117760, 4, 0,
  126728. _vq_quantlist__8c1_s_p8_0,
  126729. NULL,
  126730. &_vq_auxt__8c1_s_p8_0,
  126731. NULL,
  126732. 0
  126733. };
  126734. static long _vq_quantlist__8c1_s_p8_1[] = {
  126735. 2,
  126736. 1,
  126737. 3,
  126738. 0,
  126739. 4,
  126740. };
  126741. static long _vq_lengthlist__8c1_s_p8_1[] = {
  126742. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  126743. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  126744. };
  126745. static float _vq_quantthresh__8c1_s_p8_1[] = {
  126746. -1.5, -0.5, 0.5, 1.5,
  126747. };
  126748. static long _vq_quantmap__8c1_s_p8_1[] = {
  126749. 3, 1, 0, 2, 4,
  126750. };
  126751. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_1 = {
  126752. _vq_quantthresh__8c1_s_p8_1,
  126753. _vq_quantmap__8c1_s_p8_1,
  126754. 5,
  126755. 5
  126756. };
  126757. static static_codebook _8c1_s_p8_1 = {
  126758. 2, 25,
  126759. _vq_lengthlist__8c1_s_p8_1,
  126760. 1, -533725184, 1611661312, 3, 0,
  126761. _vq_quantlist__8c1_s_p8_1,
  126762. NULL,
  126763. &_vq_auxt__8c1_s_p8_1,
  126764. NULL,
  126765. 0
  126766. };
  126767. static long _vq_quantlist__8c1_s_p9_0[] = {
  126768. 6,
  126769. 5,
  126770. 7,
  126771. 4,
  126772. 8,
  126773. 3,
  126774. 9,
  126775. 2,
  126776. 10,
  126777. 1,
  126778. 11,
  126779. 0,
  126780. 12,
  126781. };
  126782. static long _vq_lengthlist__8c1_s_p9_0[] = {
  126783. 1, 3, 3,10,10,10,10,10,10,10,10,10,10, 5, 6, 6,
  126784. 10,10,10,10,10,10,10,10,10,10, 6, 7, 8,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,10,10,10,10,10,10,10,10,10,10,10,
  126791. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126792. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126793. 10,10,10,10,10, 9, 9, 9, 9,
  126794. };
  126795. static float _vq_quantthresh__8c1_s_p9_0[] = {
  126796. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  126797. 787.5, 1102.5, 1417.5, 1732.5,
  126798. };
  126799. static long _vq_quantmap__8c1_s_p9_0[] = {
  126800. 11, 9, 7, 5, 3, 1, 0, 2,
  126801. 4, 6, 8, 10, 12,
  126802. };
  126803. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_0 = {
  126804. _vq_quantthresh__8c1_s_p9_0,
  126805. _vq_quantmap__8c1_s_p9_0,
  126806. 13,
  126807. 13
  126808. };
  126809. static static_codebook _8c1_s_p9_0 = {
  126810. 2, 169,
  126811. _vq_lengthlist__8c1_s_p9_0,
  126812. 1, -513964032, 1628680192, 4, 0,
  126813. _vq_quantlist__8c1_s_p9_0,
  126814. NULL,
  126815. &_vq_auxt__8c1_s_p9_0,
  126816. NULL,
  126817. 0
  126818. };
  126819. static long _vq_quantlist__8c1_s_p9_1[] = {
  126820. 7,
  126821. 6,
  126822. 8,
  126823. 5,
  126824. 9,
  126825. 4,
  126826. 10,
  126827. 3,
  126828. 11,
  126829. 2,
  126830. 12,
  126831. 1,
  126832. 13,
  126833. 0,
  126834. 14,
  126835. };
  126836. static long _vq_lengthlist__8c1_s_p9_1[] = {
  126837. 1, 4, 4, 5, 5, 7, 7, 9, 9,11,11,12,12,13,13, 6,
  126838. 5, 5, 6, 6, 9, 9,10,10,12,12,12,13,15,14, 6, 5,
  126839. 5, 7, 7, 9, 9,10,10,12,12,12,13,14,13,17, 7, 7,
  126840. 8, 8,10,10,11,11,12,13,13,13,13,13,17, 7, 7, 8,
  126841. 8,10,10,11,11,13,13,13,13,14,14,17,11,11, 9, 9,
  126842. 11,11,12,12,12,13,13,14,15,13,17,12,12, 9, 9,11,
  126843. 11,12,12,13,13,13,13,14,16,17,17,17,11,12,12,12,
  126844. 13,13,13,14,15,14,15,15,17,17,17,12,12,11,11,13,
  126845. 13,14,14,15,14,15,15,17,17,17,15,15,13,13,14,14,
  126846. 15,14,15,15,16,15,17,17,17,15,15,13,13,13,14,14,
  126847. 15,15,15,15,16,17,17,17,17,16,14,15,14,14,15,14,
  126848. 14,15,15,15,17,17,17,17,17,14,14,16,14,15,15,15,
  126849. 15,15,15,17,17,17,17,17,17,16,16,15,17,15,15,14,
  126850. 17,15,17,16,17,17,17,17,16,15,14,15,15,15,15,15,
  126851. 15,
  126852. };
  126853. static float _vq_quantthresh__8c1_s_p9_1[] = {
  126854. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  126855. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  126856. };
  126857. static long _vq_quantmap__8c1_s_p9_1[] = {
  126858. 13, 11, 9, 7, 5, 3, 1, 0,
  126859. 2, 4, 6, 8, 10, 12, 14,
  126860. };
  126861. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_1 = {
  126862. _vq_quantthresh__8c1_s_p9_1,
  126863. _vq_quantmap__8c1_s_p9_1,
  126864. 15,
  126865. 15
  126866. };
  126867. static static_codebook _8c1_s_p9_1 = {
  126868. 2, 225,
  126869. _vq_lengthlist__8c1_s_p9_1,
  126870. 1, -520986624, 1620377600, 4, 0,
  126871. _vq_quantlist__8c1_s_p9_1,
  126872. NULL,
  126873. &_vq_auxt__8c1_s_p9_1,
  126874. NULL,
  126875. 0
  126876. };
  126877. static long _vq_quantlist__8c1_s_p9_2[] = {
  126878. 10,
  126879. 9,
  126880. 11,
  126881. 8,
  126882. 12,
  126883. 7,
  126884. 13,
  126885. 6,
  126886. 14,
  126887. 5,
  126888. 15,
  126889. 4,
  126890. 16,
  126891. 3,
  126892. 17,
  126893. 2,
  126894. 18,
  126895. 1,
  126896. 19,
  126897. 0,
  126898. 20,
  126899. };
  126900. static long _vq_lengthlist__8c1_s_p9_2[] = {
  126901. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  126902. 9, 9, 9, 9, 9,11,11,12, 7, 7, 7, 7, 8, 8, 9, 9,
  126903. 9, 9,10,10,10,10,10,10,10,10,11,11,11, 7, 7, 7,
  126904. 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,11,
  126905. 11,12, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,
  126906. 10,10,10,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  126907. 9,10,10,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  126908. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,11,11,
  126909. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  126910. 10,10,10,11,12,11, 9, 9, 8, 9, 9, 9, 9, 9,10,10,
  126911. 10,10,10,10,10,10,10,10,11,11,11,11,11, 8, 8, 9,
  126912. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,11,12,11,
  126913. 12,11, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  126914. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  126915. 10,10,10,10,10,10,10,12,11,12,11,11, 9, 9, 9,10,
  126916. 10,10,10,10,10,10,10,10,10,10,10,10,12,11,11,11,
  126917. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126918. 11,11,11,12,11,11,12,11,10,10,10,10,10,10,10,10,
  126919. 10,10,10,10,11,10,11,11,11,11,11,11,11,10,10,10,
  126920. 10,10,10,10,10,10,10,10,10,10,10,11,11,12,11,12,
  126921. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126922. 11,11,12,11,12,11,11,11,11,10,10,10,10,10,10,10,
  126923. 10,10,10,10,10,11,11,12,11,11,12,11,11,12,10,10,
  126924. 11,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  126925. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,12,
  126926. 12,11,12,11,11,12,12,12,11,11,10,10,10,10,10,10,
  126927. 10,10,10,11,12,12,11,12,12,11,12,11,11,11,11,10,
  126928. 10,10,10,10,10,10,10,10,10,
  126929. };
  126930. static float _vq_quantthresh__8c1_s_p9_2[] = {
  126931. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  126932. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  126933. 6.5, 7.5, 8.5, 9.5,
  126934. };
  126935. static long _vq_quantmap__8c1_s_p9_2[] = {
  126936. 19, 17, 15, 13, 11, 9, 7, 5,
  126937. 3, 1, 0, 2, 4, 6, 8, 10,
  126938. 12, 14, 16, 18, 20,
  126939. };
  126940. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_2 = {
  126941. _vq_quantthresh__8c1_s_p9_2,
  126942. _vq_quantmap__8c1_s_p9_2,
  126943. 21,
  126944. 21
  126945. };
  126946. static static_codebook _8c1_s_p9_2 = {
  126947. 2, 441,
  126948. _vq_lengthlist__8c1_s_p9_2,
  126949. 1, -529268736, 1611661312, 5, 0,
  126950. _vq_quantlist__8c1_s_p9_2,
  126951. NULL,
  126952. &_vq_auxt__8c1_s_p9_2,
  126953. NULL,
  126954. 0
  126955. };
  126956. static long _huff_lengthlist__8c1_s_single[] = {
  126957. 4, 6,18, 8,11, 8, 8, 9, 9,10, 4, 4,18, 5, 9, 5,
  126958. 6, 7, 8,10,18,18,18,18,17,17,17,17,17,17, 7, 5,
  126959. 17, 6,11, 6, 7, 8, 9,12,12, 9,17,12, 8, 8, 9,10,
  126960. 10,13, 7, 5,17, 6, 8, 4, 5, 6, 8,10, 6, 5,17, 6,
  126961. 8, 5, 4, 5, 7, 9, 7, 7,17, 8, 9, 6, 5, 5, 6, 8,
  126962. 8, 8,17, 9,11, 8, 6, 6, 6, 7, 9,10,17,12,12,10,
  126963. 9, 7, 7, 8,
  126964. };
  126965. static static_codebook _huff_book__8c1_s_single = {
  126966. 2, 100,
  126967. _huff_lengthlist__8c1_s_single,
  126968. 0, 0, 0, 0, 0,
  126969. NULL,
  126970. NULL,
  126971. NULL,
  126972. NULL,
  126973. 0
  126974. };
  126975. static long _huff_lengthlist__44c2_s_long[] = {
  126976. 6, 6,12,10,10,10, 9,10,12,12, 6, 1,10, 5, 6, 6,
  126977. 7, 9,11,14,12, 9, 8,11, 7, 8, 9,11,13,15,10, 5,
  126978. 12, 7, 8, 7, 9,12,14,15,10, 6, 7, 8, 5, 6, 7, 9,
  126979. 12,14, 9, 6, 8, 7, 6, 6, 7, 9,12,12, 9, 7, 9, 9,
  126980. 7, 6, 6, 7,10,10,10, 9,10,11, 8, 7, 6, 6, 8,10,
  126981. 12,11,13,13,11,10, 8, 8, 8,10,11,13,15,15,14,13,
  126982. 10, 8, 8, 9,
  126983. };
  126984. static static_codebook _huff_book__44c2_s_long = {
  126985. 2, 100,
  126986. _huff_lengthlist__44c2_s_long,
  126987. 0, 0, 0, 0, 0,
  126988. NULL,
  126989. NULL,
  126990. NULL,
  126991. NULL,
  126992. 0
  126993. };
  126994. static long _vq_quantlist__44c2_s_p1_0[] = {
  126995. 1,
  126996. 0,
  126997. 2,
  126998. };
  126999. static long _vq_lengthlist__44c2_s_p1_0[] = {
  127000. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  127001. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127003. 0, 0, 0, 0, 0, 0, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  127006. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127008. 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  127011. 0, 0, 0, 0, 7, 8, 8, 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, 0, 0, 0, 0, 0, 0, 0,
  127043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 7, 0, 0, 0, 0,
  127046. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  127047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7, 8, 8, 0, 0, 0,
  127051. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  127052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 6, 8, 8, 0, 0,
  127056. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127091. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  127092. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127096. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  127097. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  127098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127101. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  127102. 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127410. 0,
  127411. };
  127412. static float _vq_quantthresh__44c2_s_p1_0[] = {
  127413. -0.5, 0.5,
  127414. };
  127415. static long _vq_quantmap__44c2_s_p1_0[] = {
  127416. 1, 0, 2,
  127417. };
  127418. static encode_aux_threshmatch _vq_auxt__44c2_s_p1_0 = {
  127419. _vq_quantthresh__44c2_s_p1_0,
  127420. _vq_quantmap__44c2_s_p1_0,
  127421. 3,
  127422. 3
  127423. };
  127424. static static_codebook _44c2_s_p1_0 = {
  127425. 8, 6561,
  127426. _vq_lengthlist__44c2_s_p1_0,
  127427. 1, -535822336, 1611661312, 2, 0,
  127428. _vq_quantlist__44c2_s_p1_0,
  127429. NULL,
  127430. &_vq_auxt__44c2_s_p1_0,
  127431. NULL,
  127432. 0
  127433. };
  127434. static long _vq_quantlist__44c2_s_p2_0[] = {
  127435. 2,
  127436. 1,
  127437. 3,
  127438. 0,
  127439. 4,
  127440. };
  127441. static long _vq_lengthlist__44c2_s_p2_0[] = {
  127442. 1, 4, 4, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0,
  127443. 8, 8, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  127444. 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  127445. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0,
  127446. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127451. 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,11,11, 0, 0,
  127452. 0,11,11, 0, 0, 0,12,11, 0, 0, 0, 0, 0, 0, 0, 7,
  127453. 8, 8, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0, 0,11,
  127454. 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127459. 0, 0, 0, 6, 8, 8, 0, 0, 0,11,11, 0, 0, 0,11,11,
  127460. 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0,
  127461. 0, 0,10,11, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0,
  127462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127467. 8, 9, 9, 0, 0, 0,11,12, 0, 0, 0,11,12, 0, 0, 0,
  127468. 12,11, 0, 0, 0, 0, 0, 0, 0, 8,10, 9, 0, 0, 0,12,
  127469. 11, 0, 0, 0,12,11, 0, 0, 0,11,12, 0, 0, 0, 0, 0,
  127470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127481. 0,
  127482. };
  127483. static float _vq_quantthresh__44c2_s_p2_0[] = {
  127484. -1.5, -0.5, 0.5, 1.5,
  127485. };
  127486. static long _vq_quantmap__44c2_s_p2_0[] = {
  127487. 3, 1, 0, 2, 4,
  127488. };
  127489. static encode_aux_threshmatch _vq_auxt__44c2_s_p2_0 = {
  127490. _vq_quantthresh__44c2_s_p2_0,
  127491. _vq_quantmap__44c2_s_p2_0,
  127492. 5,
  127493. 5
  127494. };
  127495. static static_codebook _44c2_s_p2_0 = {
  127496. 4, 625,
  127497. _vq_lengthlist__44c2_s_p2_0,
  127498. 1, -533725184, 1611661312, 3, 0,
  127499. _vq_quantlist__44c2_s_p2_0,
  127500. NULL,
  127501. &_vq_auxt__44c2_s_p2_0,
  127502. NULL,
  127503. 0
  127504. };
  127505. static long _vq_quantlist__44c2_s_p3_0[] = {
  127506. 2,
  127507. 1,
  127508. 3,
  127509. 0,
  127510. 4,
  127511. };
  127512. static long _vq_lengthlist__44c2_s_p3_0[] = {
  127513. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  127515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127516. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  127518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127519. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  127520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127552. 0,
  127553. };
  127554. static float _vq_quantthresh__44c2_s_p3_0[] = {
  127555. -1.5, -0.5, 0.5, 1.5,
  127556. };
  127557. static long _vq_quantmap__44c2_s_p3_0[] = {
  127558. 3, 1, 0, 2, 4,
  127559. };
  127560. static encode_aux_threshmatch _vq_auxt__44c2_s_p3_0 = {
  127561. _vq_quantthresh__44c2_s_p3_0,
  127562. _vq_quantmap__44c2_s_p3_0,
  127563. 5,
  127564. 5
  127565. };
  127566. static static_codebook _44c2_s_p3_0 = {
  127567. 4, 625,
  127568. _vq_lengthlist__44c2_s_p3_0,
  127569. 1, -533725184, 1611661312, 3, 0,
  127570. _vq_quantlist__44c2_s_p3_0,
  127571. NULL,
  127572. &_vq_auxt__44c2_s_p3_0,
  127573. NULL,
  127574. 0
  127575. };
  127576. static long _vq_quantlist__44c2_s_p4_0[] = {
  127577. 4,
  127578. 3,
  127579. 5,
  127580. 2,
  127581. 6,
  127582. 1,
  127583. 7,
  127584. 0,
  127585. 8,
  127586. };
  127587. static long _vq_lengthlist__44c2_s_p4_0[] = {
  127588. 1, 3, 3, 6, 6, 0, 0, 0, 0, 0, 6, 6, 6, 6, 0, 0,
  127589. 0, 0, 0, 6, 6, 6, 6, 0, 0, 0, 0, 0, 7, 7, 6, 6,
  127590. 0, 0, 0, 0, 0, 0, 0, 6, 7, 0, 0, 0, 0, 0, 0, 0,
  127591. 7, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  127592. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127593. 0,
  127594. };
  127595. static float _vq_quantthresh__44c2_s_p4_0[] = {
  127596. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127597. };
  127598. static long _vq_quantmap__44c2_s_p4_0[] = {
  127599. 7, 5, 3, 1, 0, 2, 4, 6,
  127600. 8,
  127601. };
  127602. static encode_aux_threshmatch _vq_auxt__44c2_s_p4_0 = {
  127603. _vq_quantthresh__44c2_s_p4_0,
  127604. _vq_quantmap__44c2_s_p4_0,
  127605. 9,
  127606. 9
  127607. };
  127608. static static_codebook _44c2_s_p4_0 = {
  127609. 2, 81,
  127610. _vq_lengthlist__44c2_s_p4_0,
  127611. 1, -531628032, 1611661312, 4, 0,
  127612. _vq_quantlist__44c2_s_p4_0,
  127613. NULL,
  127614. &_vq_auxt__44c2_s_p4_0,
  127615. NULL,
  127616. 0
  127617. };
  127618. static long _vq_quantlist__44c2_s_p5_0[] = {
  127619. 4,
  127620. 3,
  127621. 5,
  127622. 2,
  127623. 6,
  127624. 1,
  127625. 7,
  127626. 0,
  127627. 8,
  127628. };
  127629. static long _vq_lengthlist__44c2_s_p5_0[] = {
  127630. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 7, 7, 7, 7, 7, 7,
  127631. 9, 9, 0, 7, 7, 7, 7, 7, 7, 9, 9, 0, 8, 8, 7, 7,
  127632. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  127633. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  127634. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  127635. 11,
  127636. };
  127637. static float _vq_quantthresh__44c2_s_p5_0[] = {
  127638. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127639. };
  127640. static long _vq_quantmap__44c2_s_p5_0[] = {
  127641. 7, 5, 3, 1, 0, 2, 4, 6,
  127642. 8,
  127643. };
  127644. static encode_aux_threshmatch _vq_auxt__44c2_s_p5_0 = {
  127645. _vq_quantthresh__44c2_s_p5_0,
  127646. _vq_quantmap__44c2_s_p5_0,
  127647. 9,
  127648. 9
  127649. };
  127650. static static_codebook _44c2_s_p5_0 = {
  127651. 2, 81,
  127652. _vq_lengthlist__44c2_s_p5_0,
  127653. 1, -531628032, 1611661312, 4, 0,
  127654. _vq_quantlist__44c2_s_p5_0,
  127655. NULL,
  127656. &_vq_auxt__44c2_s_p5_0,
  127657. NULL,
  127658. 0
  127659. };
  127660. static long _vq_quantlist__44c2_s_p6_0[] = {
  127661. 8,
  127662. 7,
  127663. 9,
  127664. 6,
  127665. 10,
  127666. 5,
  127667. 11,
  127668. 4,
  127669. 12,
  127670. 3,
  127671. 13,
  127672. 2,
  127673. 14,
  127674. 1,
  127675. 15,
  127676. 0,
  127677. 16,
  127678. };
  127679. static long _vq_lengthlist__44c2_s_p6_0[] = {
  127680. 1, 4, 3, 6, 6, 8, 8, 9, 9, 9, 9, 9, 9,10,10,11,
  127681. 11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  127682. 12,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  127683. 11,11,12, 0, 8, 8, 7, 7, 9, 9,10,10, 9, 9,10,10,
  127684. 11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10, 9,10,
  127685. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  127686. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  127687. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  127688. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  127689. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  127690. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  127691. 9,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  127692. 10,10,10,10,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  127693. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  127694. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  127695. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  127696. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  127697. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  127698. 14,
  127699. };
  127700. static float _vq_quantthresh__44c2_s_p6_0[] = {
  127701. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  127702. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  127703. };
  127704. static long _vq_quantmap__44c2_s_p6_0[] = {
  127705. 15, 13, 11, 9, 7, 5, 3, 1,
  127706. 0, 2, 4, 6, 8, 10, 12, 14,
  127707. 16,
  127708. };
  127709. static encode_aux_threshmatch _vq_auxt__44c2_s_p6_0 = {
  127710. _vq_quantthresh__44c2_s_p6_0,
  127711. _vq_quantmap__44c2_s_p6_0,
  127712. 17,
  127713. 17
  127714. };
  127715. static static_codebook _44c2_s_p6_0 = {
  127716. 2, 289,
  127717. _vq_lengthlist__44c2_s_p6_0,
  127718. 1, -529530880, 1611661312, 5, 0,
  127719. _vq_quantlist__44c2_s_p6_0,
  127720. NULL,
  127721. &_vq_auxt__44c2_s_p6_0,
  127722. NULL,
  127723. 0
  127724. };
  127725. static long _vq_quantlist__44c2_s_p7_0[] = {
  127726. 1,
  127727. 0,
  127728. 2,
  127729. };
  127730. static long _vq_lengthlist__44c2_s_p7_0[] = {
  127731. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  127732. 9, 9, 4, 7, 7,10, 9, 9,10, 9, 9, 7,10,10,11,10,
  127733. 11,11,10,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  127734. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 6,
  127735. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,12,10,
  127736. 11,
  127737. };
  127738. static float _vq_quantthresh__44c2_s_p7_0[] = {
  127739. -5.5, 5.5,
  127740. };
  127741. static long _vq_quantmap__44c2_s_p7_0[] = {
  127742. 1, 0, 2,
  127743. };
  127744. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_0 = {
  127745. _vq_quantthresh__44c2_s_p7_0,
  127746. _vq_quantmap__44c2_s_p7_0,
  127747. 3,
  127748. 3
  127749. };
  127750. static static_codebook _44c2_s_p7_0 = {
  127751. 4, 81,
  127752. _vq_lengthlist__44c2_s_p7_0,
  127753. 1, -529137664, 1618345984, 2, 0,
  127754. _vq_quantlist__44c2_s_p7_0,
  127755. NULL,
  127756. &_vq_auxt__44c2_s_p7_0,
  127757. NULL,
  127758. 0
  127759. };
  127760. static long _vq_quantlist__44c2_s_p7_1[] = {
  127761. 5,
  127762. 4,
  127763. 6,
  127764. 3,
  127765. 7,
  127766. 2,
  127767. 8,
  127768. 1,
  127769. 9,
  127770. 0,
  127771. 10,
  127772. };
  127773. static long _vq_lengthlist__44c2_s_p7_1[] = {
  127774. 2, 3, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 7, 7, 6, 6,
  127775. 7, 7, 8, 8, 8, 8, 9, 6, 6, 6, 6, 7, 7, 8, 8, 8,
  127776. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  127777. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  127778. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  127779. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  127780. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  127781. 10,10,10, 8, 8, 8, 8, 8, 8,
  127782. };
  127783. static float _vq_quantthresh__44c2_s_p7_1[] = {
  127784. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  127785. 3.5, 4.5,
  127786. };
  127787. static long _vq_quantmap__44c2_s_p7_1[] = {
  127788. 9, 7, 5, 3, 1, 0, 2, 4,
  127789. 6, 8, 10,
  127790. };
  127791. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_1 = {
  127792. _vq_quantthresh__44c2_s_p7_1,
  127793. _vq_quantmap__44c2_s_p7_1,
  127794. 11,
  127795. 11
  127796. };
  127797. static static_codebook _44c2_s_p7_1 = {
  127798. 2, 121,
  127799. _vq_lengthlist__44c2_s_p7_1,
  127800. 1, -531365888, 1611661312, 4, 0,
  127801. _vq_quantlist__44c2_s_p7_1,
  127802. NULL,
  127803. &_vq_auxt__44c2_s_p7_1,
  127804. NULL,
  127805. 0
  127806. };
  127807. static long _vq_quantlist__44c2_s_p8_0[] = {
  127808. 6,
  127809. 5,
  127810. 7,
  127811. 4,
  127812. 8,
  127813. 3,
  127814. 9,
  127815. 2,
  127816. 10,
  127817. 1,
  127818. 11,
  127819. 0,
  127820. 12,
  127821. };
  127822. static long _vq_lengthlist__44c2_s_p8_0[] = {
  127823. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  127824. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  127825. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  127826. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127827. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  127828. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  127829. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  127830. 11,12,12,12,12, 0, 0, 0,14,14,10,11,11,11,12,12,
  127831. 13,13, 0, 0, 0,14,14,11,10,11,11,13,12,13,13, 0,
  127832. 0, 0, 0, 0,12,12,11,12,13,12,14,14, 0, 0, 0, 0,
  127833. 0,12,12,12,12,13,12,14,14,
  127834. };
  127835. static float _vq_quantthresh__44c2_s_p8_0[] = {
  127836. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  127837. 12.5, 17.5, 22.5, 27.5,
  127838. };
  127839. static long _vq_quantmap__44c2_s_p8_0[] = {
  127840. 11, 9, 7, 5, 3, 1, 0, 2,
  127841. 4, 6, 8, 10, 12,
  127842. };
  127843. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_0 = {
  127844. _vq_quantthresh__44c2_s_p8_0,
  127845. _vq_quantmap__44c2_s_p8_0,
  127846. 13,
  127847. 13
  127848. };
  127849. static static_codebook _44c2_s_p8_0 = {
  127850. 2, 169,
  127851. _vq_lengthlist__44c2_s_p8_0,
  127852. 1, -526516224, 1616117760, 4, 0,
  127853. _vq_quantlist__44c2_s_p8_0,
  127854. NULL,
  127855. &_vq_auxt__44c2_s_p8_0,
  127856. NULL,
  127857. 0
  127858. };
  127859. static long _vq_quantlist__44c2_s_p8_1[] = {
  127860. 2,
  127861. 1,
  127862. 3,
  127863. 0,
  127864. 4,
  127865. };
  127866. static long _vq_lengthlist__44c2_s_p8_1[] = {
  127867. 2, 4, 4, 5, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  127868. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  127869. };
  127870. static float _vq_quantthresh__44c2_s_p8_1[] = {
  127871. -1.5, -0.5, 0.5, 1.5,
  127872. };
  127873. static long _vq_quantmap__44c2_s_p8_1[] = {
  127874. 3, 1, 0, 2, 4,
  127875. };
  127876. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_1 = {
  127877. _vq_quantthresh__44c2_s_p8_1,
  127878. _vq_quantmap__44c2_s_p8_1,
  127879. 5,
  127880. 5
  127881. };
  127882. static static_codebook _44c2_s_p8_1 = {
  127883. 2, 25,
  127884. _vq_lengthlist__44c2_s_p8_1,
  127885. 1, -533725184, 1611661312, 3, 0,
  127886. _vq_quantlist__44c2_s_p8_1,
  127887. NULL,
  127888. &_vq_auxt__44c2_s_p8_1,
  127889. NULL,
  127890. 0
  127891. };
  127892. static long _vq_quantlist__44c2_s_p9_0[] = {
  127893. 6,
  127894. 5,
  127895. 7,
  127896. 4,
  127897. 8,
  127898. 3,
  127899. 9,
  127900. 2,
  127901. 10,
  127902. 1,
  127903. 11,
  127904. 0,
  127905. 12,
  127906. };
  127907. static long _vq_lengthlist__44c2_s_p9_0[] = {
  127908. 1, 5, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  127909. 11,11,11,11,11,11,11,11,11,11, 2, 8, 7,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,10,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,11,11,11,11,11,11,11,
  127916. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127917. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127918. 11,11,11,11,11,11,11,11,11,
  127919. };
  127920. static float _vq_quantthresh__44c2_s_p9_0[] = {
  127921. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  127922. 552.5, 773.5, 994.5, 1215.5,
  127923. };
  127924. static long _vq_quantmap__44c2_s_p9_0[] = {
  127925. 11, 9, 7, 5, 3, 1, 0, 2,
  127926. 4, 6, 8, 10, 12,
  127927. };
  127928. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_0 = {
  127929. _vq_quantthresh__44c2_s_p9_0,
  127930. _vq_quantmap__44c2_s_p9_0,
  127931. 13,
  127932. 13
  127933. };
  127934. static static_codebook _44c2_s_p9_0 = {
  127935. 2, 169,
  127936. _vq_lengthlist__44c2_s_p9_0,
  127937. 1, -514541568, 1627103232, 4, 0,
  127938. _vq_quantlist__44c2_s_p9_0,
  127939. NULL,
  127940. &_vq_auxt__44c2_s_p9_0,
  127941. NULL,
  127942. 0
  127943. };
  127944. static long _vq_quantlist__44c2_s_p9_1[] = {
  127945. 6,
  127946. 5,
  127947. 7,
  127948. 4,
  127949. 8,
  127950. 3,
  127951. 9,
  127952. 2,
  127953. 10,
  127954. 1,
  127955. 11,
  127956. 0,
  127957. 12,
  127958. };
  127959. static long _vq_lengthlist__44c2_s_p9_1[] = {
  127960. 1, 4, 4, 6, 6, 7, 6, 8, 8,10, 9,10,10, 6, 5, 5,
  127961. 7, 7, 8, 7,10, 9,11,11,12,13, 6, 5, 5, 7, 7, 8,
  127962. 8,10,10,11,11,13,13,18, 8, 8, 8, 8, 9, 9,10,10,
  127963. 12,12,12,13,18, 8, 8, 8, 8, 9, 9,10,10,12,12,13,
  127964. 13,18,11,11, 8, 8,10,10,11,11,12,11,13,12,18,11,
  127965. 11, 9, 7,10,10,11,11,11,12,12,13,17,17,17,10,10,
  127966. 11,11,12,12,12,10,12,12,17,17,17,11,10,11,10,13,
  127967. 12,11,12,12,12,17,17,17,15,14,11,11,12,11,13,10,
  127968. 13,12,17,17,17,14,14,12,10,11,11,13,13,13,13,17,
  127969. 17,16,17,16,13,13,12,10,13,10,14,13,17,16,17,16,
  127970. 17,13,12,12,10,13,11,14,14,
  127971. };
  127972. static float _vq_quantthresh__44c2_s_p9_1[] = {
  127973. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  127974. 42.5, 59.5, 76.5, 93.5,
  127975. };
  127976. static long _vq_quantmap__44c2_s_p9_1[] = {
  127977. 11, 9, 7, 5, 3, 1, 0, 2,
  127978. 4, 6, 8, 10, 12,
  127979. };
  127980. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_1 = {
  127981. _vq_quantthresh__44c2_s_p9_1,
  127982. _vq_quantmap__44c2_s_p9_1,
  127983. 13,
  127984. 13
  127985. };
  127986. static static_codebook _44c2_s_p9_1 = {
  127987. 2, 169,
  127988. _vq_lengthlist__44c2_s_p9_1,
  127989. 1, -522616832, 1620115456, 4, 0,
  127990. _vq_quantlist__44c2_s_p9_1,
  127991. NULL,
  127992. &_vq_auxt__44c2_s_p9_1,
  127993. NULL,
  127994. 0
  127995. };
  127996. static long _vq_quantlist__44c2_s_p9_2[] = {
  127997. 8,
  127998. 7,
  127999. 9,
  128000. 6,
  128001. 10,
  128002. 5,
  128003. 11,
  128004. 4,
  128005. 12,
  128006. 3,
  128007. 13,
  128008. 2,
  128009. 14,
  128010. 1,
  128011. 15,
  128012. 0,
  128013. 16,
  128014. };
  128015. static long _vq_lengthlist__44c2_s_p9_2[] = {
  128016. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  128017. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  128018. 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  128019. 9, 9, 9,10, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  128020. 9, 9, 9, 9,10,10,10, 8, 7, 8, 8, 8, 8, 9, 9, 9,
  128021. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  128022. 9, 9,10, 9, 9, 9,10,11,10, 8, 8, 8, 8, 9, 9, 9,
  128023. 9, 9, 9, 9,10,10,10,10,11,10, 8, 8, 9, 9, 9, 9,
  128024. 9, 9,10, 9, 9,10, 9,10,11,10,11,11,11, 8, 8, 9,
  128025. 9, 9, 9, 9, 9, 9, 9,10,10,11,11,11,11,11, 9, 9,
  128026. 9, 9, 9, 9,10, 9, 9, 9,10,10,11,11,11,11,11, 9,
  128027. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,11,11,11,11,11,
  128028. 9, 9, 9, 9,10,10, 9, 9, 9,10,10,10,11,11,11,11,
  128029. 11,11,11, 9, 9, 9,10, 9, 9,10,10,10,10,11,11,10,
  128030. 11,11,11,11,10, 9,10,10, 9, 9, 9, 9,10,10,11,10,
  128031. 11,11,11,11,11, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  128032. 10,11,11,11,11,11,10,10, 9, 9,10, 9,10,10,10,10,
  128033. 10,10,10,11,11,11,11,11,11, 9, 9,10, 9,10, 9,10,
  128034. 10,
  128035. };
  128036. static float _vq_quantthresh__44c2_s_p9_2[] = {
  128037. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128038. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128039. };
  128040. static long _vq_quantmap__44c2_s_p9_2[] = {
  128041. 15, 13, 11, 9, 7, 5, 3, 1,
  128042. 0, 2, 4, 6, 8, 10, 12, 14,
  128043. 16,
  128044. };
  128045. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_2 = {
  128046. _vq_quantthresh__44c2_s_p9_2,
  128047. _vq_quantmap__44c2_s_p9_2,
  128048. 17,
  128049. 17
  128050. };
  128051. static static_codebook _44c2_s_p9_2 = {
  128052. 2, 289,
  128053. _vq_lengthlist__44c2_s_p9_2,
  128054. 1, -529530880, 1611661312, 5, 0,
  128055. _vq_quantlist__44c2_s_p9_2,
  128056. NULL,
  128057. &_vq_auxt__44c2_s_p9_2,
  128058. NULL,
  128059. 0
  128060. };
  128061. static long _huff_lengthlist__44c2_s_short[] = {
  128062. 11, 9,13,12,12,11,12,12,13,15, 8, 2,11, 4, 8, 5,
  128063. 7,10,12,15,13, 7,10, 9, 8, 8,10,13,17,17,11, 4,
  128064. 12, 5, 9, 5, 8,11,14,16,12, 6, 8, 7, 6, 6, 8,11,
  128065. 13,16,11, 4, 9, 5, 6, 4, 6,10,13,16,11, 6,11, 7,
  128066. 7, 6, 7,10,13,15,13, 9,12, 9, 8, 6, 8,10,12,14,
  128067. 14,10,10, 8, 6, 5, 6, 9,11,13,15,11,11, 9, 6, 5,
  128068. 6, 8, 9,12,
  128069. };
  128070. static static_codebook _huff_book__44c2_s_short = {
  128071. 2, 100,
  128072. _huff_lengthlist__44c2_s_short,
  128073. 0, 0, 0, 0, 0,
  128074. NULL,
  128075. NULL,
  128076. NULL,
  128077. NULL,
  128078. 0
  128079. };
  128080. static long _huff_lengthlist__44c3_s_long[] = {
  128081. 5, 6,11,11,11,11,10,10,12,11, 5, 2,11, 5, 6, 6,
  128082. 7, 9,11,13,13,10, 7,11, 6, 7, 8, 9,10,12,11, 5,
  128083. 11, 6, 8, 7, 9,11,14,15,11, 6, 6, 8, 4, 5, 7, 8,
  128084. 10,13,10, 5, 7, 7, 5, 5, 6, 8,10,11,10, 7, 7, 8,
  128085. 6, 5, 5, 7, 9, 9,11, 8, 8,11, 8, 7, 6, 6, 7, 9,
  128086. 12,11,10,13, 9, 9, 7, 7, 7, 9,11,13,12,15,12,11,
  128087. 9, 8, 8, 8,
  128088. };
  128089. static static_codebook _huff_book__44c3_s_long = {
  128090. 2, 100,
  128091. _huff_lengthlist__44c3_s_long,
  128092. 0, 0, 0, 0, 0,
  128093. NULL,
  128094. NULL,
  128095. NULL,
  128096. NULL,
  128097. 0
  128098. };
  128099. static long _vq_quantlist__44c3_s_p1_0[] = {
  128100. 1,
  128101. 0,
  128102. 2,
  128103. };
  128104. static long _vq_lengthlist__44c3_s_p1_0[] = {
  128105. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  128106. 0, 0, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128108. 0, 0, 0, 0, 0, 0, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  128111. 0, 0, 0, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128113. 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  128116. 0, 0, 0, 0, 7, 8, 8, 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, 0, 0, 0, 0, 0, 0, 0,
  128148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 7, 0, 0, 0, 0,
  128151. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  128152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7, 8, 8, 0, 0, 0,
  128156. 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  128157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 6, 8, 8, 0, 0,
  128161. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128194. 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  128197. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128201. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  128202. 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  128203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128206. 0, 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  128207. 0, 0, 0, 0, 0, 0, 8, 9, 8, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128515. 0,
  128516. };
  128517. static float _vq_quantthresh__44c3_s_p1_0[] = {
  128518. -0.5, 0.5,
  128519. };
  128520. static long _vq_quantmap__44c3_s_p1_0[] = {
  128521. 1, 0, 2,
  128522. };
  128523. static encode_aux_threshmatch _vq_auxt__44c3_s_p1_0 = {
  128524. _vq_quantthresh__44c3_s_p1_0,
  128525. _vq_quantmap__44c3_s_p1_0,
  128526. 3,
  128527. 3
  128528. };
  128529. static static_codebook _44c3_s_p1_0 = {
  128530. 8, 6561,
  128531. _vq_lengthlist__44c3_s_p1_0,
  128532. 1, -535822336, 1611661312, 2, 0,
  128533. _vq_quantlist__44c3_s_p1_0,
  128534. NULL,
  128535. &_vq_auxt__44c3_s_p1_0,
  128536. NULL,
  128537. 0
  128538. };
  128539. static long _vq_quantlist__44c3_s_p2_0[] = {
  128540. 2,
  128541. 1,
  128542. 3,
  128543. 0,
  128544. 4,
  128545. };
  128546. static long _vq_lengthlist__44c3_s_p2_0[] = {
  128547. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  128548. 7, 8, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  128549. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  128550. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  128551. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128556. 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0,
  128557. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  128558. 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  128559. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128564. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  128565. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  128566. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  128567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128572. 8,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  128573. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  128574. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  128575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128586. 0,
  128587. };
  128588. static float _vq_quantthresh__44c3_s_p2_0[] = {
  128589. -1.5, -0.5, 0.5, 1.5,
  128590. };
  128591. static long _vq_quantmap__44c3_s_p2_0[] = {
  128592. 3, 1, 0, 2, 4,
  128593. };
  128594. static encode_aux_threshmatch _vq_auxt__44c3_s_p2_0 = {
  128595. _vq_quantthresh__44c3_s_p2_0,
  128596. _vq_quantmap__44c3_s_p2_0,
  128597. 5,
  128598. 5
  128599. };
  128600. static static_codebook _44c3_s_p2_0 = {
  128601. 4, 625,
  128602. _vq_lengthlist__44c3_s_p2_0,
  128603. 1, -533725184, 1611661312, 3, 0,
  128604. _vq_quantlist__44c3_s_p2_0,
  128605. NULL,
  128606. &_vq_auxt__44c3_s_p2_0,
  128607. NULL,
  128608. 0
  128609. };
  128610. static long _vq_quantlist__44c3_s_p3_0[] = {
  128611. 2,
  128612. 1,
  128613. 3,
  128614. 0,
  128615. 4,
  128616. };
  128617. static long _vq_lengthlist__44c3_s_p3_0[] = {
  128618. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  128620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128621. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  128623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128624. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  128625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128657. 0,
  128658. };
  128659. static float _vq_quantthresh__44c3_s_p3_0[] = {
  128660. -1.5, -0.5, 0.5, 1.5,
  128661. };
  128662. static long _vq_quantmap__44c3_s_p3_0[] = {
  128663. 3, 1, 0, 2, 4,
  128664. };
  128665. static encode_aux_threshmatch _vq_auxt__44c3_s_p3_0 = {
  128666. _vq_quantthresh__44c3_s_p3_0,
  128667. _vq_quantmap__44c3_s_p3_0,
  128668. 5,
  128669. 5
  128670. };
  128671. static static_codebook _44c3_s_p3_0 = {
  128672. 4, 625,
  128673. _vq_lengthlist__44c3_s_p3_0,
  128674. 1, -533725184, 1611661312, 3, 0,
  128675. _vq_quantlist__44c3_s_p3_0,
  128676. NULL,
  128677. &_vq_auxt__44c3_s_p3_0,
  128678. NULL,
  128679. 0
  128680. };
  128681. static long _vq_quantlist__44c3_s_p4_0[] = {
  128682. 4,
  128683. 3,
  128684. 5,
  128685. 2,
  128686. 6,
  128687. 1,
  128688. 7,
  128689. 0,
  128690. 8,
  128691. };
  128692. static long _vq_lengthlist__44c3_s_p4_0[] = {
  128693. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  128694. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  128695. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  128696. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  128697. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128698. 0,
  128699. };
  128700. static float _vq_quantthresh__44c3_s_p4_0[] = {
  128701. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128702. };
  128703. static long _vq_quantmap__44c3_s_p4_0[] = {
  128704. 7, 5, 3, 1, 0, 2, 4, 6,
  128705. 8,
  128706. };
  128707. static encode_aux_threshmatch _vq_auxt__44c3_s_p4_0 = {
  128708. _vq_quantthresh__44c3_s_p4_0,
  128709. _vq_quantmap__44c3_s_p4_0,
  128710. 9,
  128711. 9
  128712. };
  128713. static static_codebook _44c3_s_p4_0 = {
  128714. 2, 81,
  128715. _vq_lengthlist__44c3_s_p4_0,
  128716. 1, -531628032, 1611661312, 4, 0,
  128717. _vq_quantlist__44c3_s_p4_0,
  128718. NULL,
  128719. &_vq_auxt__44c3_s_p4_0,
  128720. NULL,
  128721. 0
  128722. };
  128723. static long _vq_quantlist__44c3_s_p5_0[] = {
  128724. 4,
  128725. 3,
  128726. 5,
  128727. 2,
  128728. 6,
  128729. 1,
  128730. 7,
  128731. 0,
  128732. 8,
  128733. };
  128734. static long _vq_lengthlist__44c3_s_p5_0[] = {
  128735. 1, 3, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 7, 8,
  128736. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  128737. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  128738. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  128739. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  128740. 11,
  128741. };
  128742. static float _vq_quantthresh__44c3_s_p5_0[] = {
  128743. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128744. };
  128745. static long _vq_quantmap__44c3_s_p5_0[] = {
  128746. 7, 5, 3, 1, 0, 2, 4, 6,
  128747. 8,
  128748. };
  128749. static encode_aux_threshmatch _vq_auxt__44c3_s_p5_0 = {
  128750. _vq_quantthresh__44c3_s_p5_0,
  128751. _vq_quantmap__44c3_s_p5_0,
  128752. 9,
  128753. 9
  128754. };
  128755. static static_codebook _44c3_s_p5_0 = {
  128756. 2, 81,
  128757. _vq_lengthlist__44c3_s_p5_0,
  128758. 1, -531628032, 1611661312, 4, 0,
  128759. _vq_quantlist__44c3_s_p5_0,
  128760. NULL,
  128761. &_vq_auxt__44c3_s_p5_0,
  128762. NULL,
  128763. 0
  128764. };
  128765. static long _vq_quantlist__44c3_s_p6_0[] = {
  128766. 8,
  128767. 7,
  128768. 9,
  128769. 6,
  128770. 10,
  128771. 5,
  128772. 11,
  128773. 4,
  128774. 12,
  128775. 3,
  128776. 13,
  128777. 2,
  128778. 14,
  128779. 1,
  128780. 15,
  128781. 0,
  128782. 16,
  128783. };
  128784. static long _vq_lengthlist__44c3_s_p6_0[] = {
  128785. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  128786. 10, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  128787. 11,11, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  128788. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  128789. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  128790. 10,11,11,11,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  128791. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  128792. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  128793. 10,10,11,10,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  128794. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 8,
  128795. 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8,
  128796. 8, 9, 9,10,10,11,11,12,11,12,12, 0, 0, 0, 0, 0,
  128797. 9,10,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0,
  128798. 0, 0, 0,10,10,10,10,11,11,12,12,13,13, 0, 0, 0,
  128799. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  128800. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  128801. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13,
  128802. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  128803. 13,
  128804. };
  128805. static float _vq_quantthresh__44c3_s_p6_0[] = {
  128806. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128807. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128808. };
  128809. static long _vq_quantmap__44c3_s_p6_0[] = {
  128810. 15, 13, 11, 9, 7, 5, 3, 1,
  128811. 0, 2, 4, 6, 8, 10, 12, 14,
  128812. 16,
  128813. };
  128814. static encode_aux_threshmatch _vq_auxt__44c3_s_p6_0 = {
  128815. _vq_quantthresh__44c3_s_p6_0,
  128816. _vq_quantmap__44c3_s_p6_0,
  128817. 17,
  128818. 17
  128819. };
  128820. static static_codebook _44c3_s_p6_0 = {
  128821. 2, 289,
  128822. _vq_lengthlist__44c3_s_p6_0,
  128823. 1, -529530880, 1611661312, 5, 0,
  128824. _vq_quantlist__44c3_s_p6_0,
  128825. NULL,
  128826. &_vq_auxt__44c3_s_p6_0,
  128827. NULL,
  128828. 0
  128829. };
  128830. static long _vq_quantlist__44c3_s_p7_0[] = {
  128831. 1,
  128832. 0,
  128833. 2,
  128834. };
  128835. static long _vq_lengthlist__44c3_s_p7_0[] = {
  128836. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  128837. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  128838. 10,12,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  128839. 11,10,10,11,10,10, 7,11,11,11,11,11,12,11,11, 6,
  128840. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  128841. 10,
  128842. };
  128843. static float _vq_quantthresh__44c3_s_p7_0[] = {
  128844. -5.5, 5.5,
  128845. };
  128846. static long _vq_quantmap__44c3_s_p7_0[] = {
  128847. 1, 0, 2,
  128848. };
  128849. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_0 = {
  128850. _vq_quantthresh__44c3_s_p7_0,
  128851. _vq_quantmap__44c3_s_p7_0,
  128852. 3,
  128853. 3
  128854. };
  128855. static static_codebook _44c3_s_p7_0 = {
  128856. 4, 81,
  128857. _vq_lengthlist__44c3_s_p7_0,
  128858. 1, -529137664, 1618345984, 2, 0,
  128859. _vq_quantlist__44c3_s_p7_0,
  128860. NULL,
  128861. &_vq_auxt__44c3_s_p7_0,
  128862. NULL,
  128863. 0
  128864. };
  128865. static long _vq_quantlist__44c3_s_p7_1[] = {
  128866. 5,
  128867. 4,
  128868. 6,
  128869. 3,
  128870. 7,
  128871. 2,
  128872. 8,
  128873. 1,
  128874. 9,
  128875. 0,
  128876. 10,
  128877. };
  128878. static long _vq_lengthlist__44c3_s_p7_1[] = {
  128879. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  128880. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  128881. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  128882. 7, 8, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  128883. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  128884. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  128885. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  128886. 10,10,10, 8, 8, 8, 8, 8, 8,
  128887. };
  128888. static float _vq_quantthresh__44c3_s_p7_1[] = {
  128889. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  128890. 3.5, 4.5,
  128891. };
  128892. static long _vq_quantmap__44c3_s_p7_1[] = {
  128893. 9, 7, 5, 3, 1, 0, 2, 4,
  128894. 6, 8, 10,
  128895. };
  128896. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_1 = {
  128897. _vq_quantthresh__44c3_s_p7_1,
  128898. _vq_quantmap__44c3_s_p7_1,
  128899. 11,
  128900. 11
  128901. };
  128902. static static_codebook _44c3_s_p7_1 = {
  128903. 2, 121,
  128904. _vq_lengthlist__44c3_s_p7_1,
  128905. 1, -531365888, 1611661312, 4, 0,
  128906. _vq_quantlist__44c3_s_p7_1,
  128907. NULL,
  128908. &_vq_auxt__44c3_s_p7_1,
  128909. NULL,
  128910. 0
  128911. };
  128912. static long _vq_quantlist__44c3_s_p8_0[] = {
  128913. 6,
  128914. 5,
  128915. 7,
  128916. 4,
  128917. 8,
  128918. 3,
  128919. 9,
  128920. 2,
  128921. 10,
  128922. 1,
  128923. 11,
  128924. 0,
  128925. 12,
  128926. };
  128927. static long _vq_lengthlist__44c3_s_p8_0[] = {
  128928. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  128929. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  128930. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  128931. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  128932. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,12, 0,13,
  128933. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  128934. 10,10,11,11,12,12,12,12, 0, 0, 0,10,10,10,10,11,
  128935. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  128936. 13,13, 0, 0, 0,14,14,11,11,11,11,12,12,13,13, 0,
  128937. 0, 0, 0, 0,12,12,12,12,13,13,14,13, 0, 0, 0, 0,
  128938. 0,13,13,12,12,13,12,14,13,
  128939. };
  128940. static float _vq_quantthresh__44c3_s_p8_0[] = {
  128941. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  128942. 12.5, 17.5, 22.5, 27.5,
  128943. };
  128944. static long _vq_quantmap__44c3_s_p8_0[] = {
  128945. 11, 9, 7, 5, 3, 1, 0, 2,
  128946. 4, 6, 8, 10, 12,
  128947. };
  128948. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_0 = {
  128949. _vq_quantthresh__44c3_s_p8_0,
  128950. _vq_quantmap__44c3_s_p8_0,
  128951. 13,
  128952. 13
  128953. };
  128954. static static_codebook _44c3_s_p8_0 = {
  128955. 2, 169,
  128956. _vq_lengthlist__44c3_s_p8_0,
  128957. 1, -526516224, 1616117760, 4, 0,
  128958. _vq_quantlist__44c3_s_p8_0,
  128959. NULL,
  128960. &_vq_auxt__44c3_s_p8_0,
  128961. NULL,
  128962. 0
  128963. };
  128964. static long _vq_quantlist__44c3_s_p8_1[] = {
  128965. 2,
  128966. 1,
  128967. 3,
  128968. 0,
  128969. 4,
  128970. };
  128971. static long _vq_lengthlist__44c3_s_p8_1[] = {
  128972. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  128973. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  128974. };
  128975. static float _vq_quantthresh__44c3_s_p8_1[] = {
  128976. -1.5, -0.5, 0.5, 1.5,
  128977. };
  128978. static long _vq_quantmap__44c3_s_p8_1[] = {
  128979. 3, 1, 0, 2, 4,
  128980. };
  128981. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_1 = {
  128982. _vq_quantthresh__44c3_s_p8_1,
  128983. _vq_quantmap__44c3_s_p8_1,
  128984. 5,
  128985. 5
  128986. };
  128987. static static_codebook _44c3_s_p8_1 = {
  128988. 2, 25,
  128989. _vq_lengthlist__44c3_s_p8_1,
  128990. 1, -533725184, 1611661312, 3, 0,
  128991. _vq_quantlist__44c3_s_p8_1,
  128992. NULL,
  128993. &_vq_auxt__44c3_s_p8_1,
  128994. NULL,
  128995. 0
  128996. };
  128997. static long _vq_quantlist__44c3_s_p9_0[] = {
  128998. 6,
  128999. 5,
  129000. 7,
  129001. 4,
  129002. 8,
  129003. 3,
  129004. 9,
  129005. 2,
  129006. 10,
  129007. 1,
  129008. 11,
  129009. 0,
  129010. 12,
  129011. };
  129012. static long _vq_lengthlist__44c3_s_p9_0[] = {
  129013. 1, 4, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  129014. 12,12,12,12,12,12,12,12,12,12, 2, 9, 7,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,11,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,12,12,12,12,12,12,
  129019. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129020. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129021. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  129022. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129023. 11,11,11,11,11,11,11,11,11,
  129024. };
  129025. static float _vq_quantthresh__44c3_s_p9_0[] = {
  129026. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  129027. 637.5, 892.5, 1147.5, 1402.5,
  129028. };
  129029. static long _vq_quantmap__44c3_s_p9_0[] = {
  129030. 11, 9, 7, 5, 3, 1, 0, 2,
  129031. 4, 6, 8, 10, 12,
  129032. };
  129033. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_0 = {
  129034. _vq_quantthresh__44c3_s_p9_0,
  129035. _vq_quantmap__44c3_s_p9_0,
  129036. 13,
  129037. 13
  129038. };
  129039. static static_codebook _44c3_s_p9_0 = {
  129040. 2, 169,
  129041. _vq_lengthlist__44c3_s_p9_0,
  129042. 1, -514332672, 1627381760, 4, 0,
  129043. _vq_quantlist__44c3_s_p9_0,
  129044. NULL,
  129045. &_vq_auxt__44c3_s_p9_0,
  129046. NULL,
  129047. 0
  129048. };
  129049. static long _vq_quantlist__44c3_s_p9_1[] = {
  129050. 7,
  129051. 6,
  129052. 8,
  129053. 5,
  129054. 9,
  129055. 4,
  129056. 10,
  129057. 3,
  129058. 11,
  129059. 2,
  129060. 12,
  129061. 1,
  129062. 13,
  129063. 0,
  129064. 14,
  129065. };
  129066. static long _vq_lengthlist__44c3_s_p9_1[] = {
  129067. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 9,10,10,10,10, 6,
  129068. 5, 5, 7, 7, 8, 8,10, 8,11,10,12,12,13,13, 6, 5,
  129069. 5, 7, 7, 8, 8,10, 9,11,11,12,12,13,12,18, 8, 8,
  129070. 8, 8, 9, 9,10, 9,11,10,12,12,13,13,18, 8, 8, 8,
  129071. 8, 9, 9,10,10,11,11,13,12,14,13,18,11,11, 9, 9,
  129072. 10,10,11,11,11,12,13,12,13,14,18,11,11, 9, 8,11,
  129073. 10,11,11,11,11,12,12,14,13,18,18,18,10,11,10,11,
  129074. 12,12,12,12,13,12,14,13,18,18,18,10,11,11, 9,12,
  129075. 11,12,12,12,13,13,13,18,18,17,14,14,11,11,12,12,
  129076. 13,12,14,12,14,13,18,18,18,14,14,11,10,12, 9,12,
  129077. 13,13,13,13,13,18,18,17,16,18,13,13,12,12,13,11,
  129078. 14,12,14,14,17,18,18,17,18,13,12,13,10,12,11,14,
  129079. 14,14,14,17,18,18,18,18,15,16,12,12,13,10,14,12,
  129080. 14,15,18,18,18,16,17,16,14,12,11,13,10,13,13,14,
  129081. 15,
  129082. };
  129083. static float _vq_quantthresh__44c3_s_p9_1[] = {
  129084. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  129085. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  129086. };
  129087. static long _vq_quantmap__44c3_s_p9_1[] = {
  129088. 13, 11, 9, 7, 5, 3, 1, 0,
  129089. 2, 4, 6, 8, 10, 12, 14,
  129090. };
  129091. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_1 = {
  129092. _vq_quantthresh__44c3_s_p9_1,
  129093. _vq_quantmap__44c3_s_p9_1,
  129094. 15,
  129095. 15
  129096. };
  129097. static static_codebook _44c3_s_p9_1 = {
  129098. 2, 225,
  129099. _vq_lengthlist__44c3_s_p9_1,
  129100. 1, -522338304, 1620115456, 4, 0,
  129101. _vq_quantlist__44c3_s_p9_1,
  129102. NULL,
  129103. &_vq_auxt__44c3_s_p9_1,
  129104. NULL,
  129105. 0
  129106. };
  129107. static long _vq_quantlist__44c3_s_p9_2[] = {
  129108. 8,
  129109. 7,
  129110. 9,
  129111. 6,
  129112. 10,
  129113. 5,
  129114. 11,
  129115. 4,
  129116. 12,
  129117. 3,
  129118. 13,
  129119. 2,
  129120. 14,
  129121. 1,
  129122. 15,
  129123. 0,
  129124. 16,
  129125. };
  129126. static long _vq_lengthlist__44c3_s_p9_2[] = {
  129127. 2, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  129128. 8,10, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 8, 9, 9, 9,
  129129. 9, 9,10, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  129130. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  129131. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  129132. 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  129133. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  129134. 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 9, 9, 9, 9, 9,
  129135. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 9, 9, 9,
  129136. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  129137. 9, 9, 9, 9,10,10, 9, 9,10, 9,11,10,11,11,11, 9,
  129138. 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,11,11,11,11,11,
  129139. 9, 9, 9, 9,10,10, 9, 9, 9, 9,10, 9,11,11,11,11,
  129140. 11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11,
  129141. 11,11,11,11,10, 9,10,10, 9,10, 9, 9,10, 9,11,10,
  129142. 10,11,11,11,11, 9,10, 9, 9, 9, 9,10,10,10,10,11,
  129143. 11,11,11,11,11,10,10,10, 9, 9,10, 9,10, 9,10,10,
  129144. 10,10,11,11,11,11,11,11,11, 9, 9, 9, 9, 9,10,10,
  129145. 10,
  129146. };
  129147. static float _vq_quantthresh__44c3_s_p9_2[] = {
  129148. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129149. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129150. };
  129151. static long _vq_quantmap__44c3_s_p9_2[] = {
  129152. 15, 13, 11, 9, 7, 5, 3, 1,
  129153. 0, 2, 4, 6, 8, 10, 12, 14,
  129154. 16,
  129155. };
  129156. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_2 = {
  129157. _vq_quantthresh__44c3_s_p9_2,
  129158. _vq_quantmap__44c3_s_p9_2,
  129159. 17,
  129160. 17
  129161. };
  129162. static static_codebook _44c3_s_p9_2 = {
  129163. 2, 289,
  129164. _vq_lengthlist__44c3_s_p9_2,
  129165. 1, -529530880, 1611661312, 5, 0,
  129166. _vq_quantlist__44c3_s_p9_2,
  129167. NULL,
  129168. &_vq_auxt__44c3_s_p9_2,
  129169. NULL,
  129170. 0
  129171. };
  129172. static long _huff_lengthlist__44c3_s_short[] = {
  129173. 10, 9,13,11,14,10,12,13,13,14, 7, 2,12, 5,10, 5,
  129174. 7,10,12,14,12, 6, 9, 8, 7, 7, 9,11,13,16,10, 4,
  129175. 12, 5,10, 6, 8,12,14,16,12, 6, 8, 7, 6, 5, 7,11,
  129176. 12,16,10, 4, 8, 5, 6, 4, 6, 9,13,16,10, 6,10, 7,
  129177. 7, 6, 7, 9,13,15,12, 9,11, 9, 8, 6, 7,10,12,14,
  129178. 14,11,10, 9, 6, 5, 6, 9,11,13,15,13,11,10, 6, 5,
  129179. 6, 8, 9,11,
  129180. };
  129181. static static_codebook _huff_book__44c3_s_short = {
  129182. 2, 100,
  129183. _huff_lengthlist__44c3_s_short,
  129184. 0, 0, 0, 0, 0,
  129185. NULL,
  129186. NULL,
  129187. NULL,
  129188. NULL,
  129189. 0
  129190. };
  129191. static long _huff_lengthlist__44c4_s_long[] = {
  129192. 4, 7,11,11,11,11,10,11,12,11, 5, 2,11, 5, 6, 6,
  129193. 7, 9,11,12,11, 9, 6,10, 6, 7, 8, 9,10,11,11, 5,
  129194. 11, 7, 8, 8, 9,11,13,14,11, 6, 5, 8, 4, 5, 7, 8,
  129195. 10,11,10, 6, 7, 7, 5, 5, 6, 8, 9,11,10, 7, 8, 9,
  129196. 6, 6, 6, 7, 8, 9,11, 9, 9,11, 7, 7, 6, 6, 7, 9,
  129197. 12,12,10,13, 9, 8, 7, 7, 7, 8,11,13,11,14,11,10,
  129198. 9, 8, 7, 7,
  129199. };
  129200. static static_codebook _huff_book__44c4_s_long = {
  129201. 2, 100,
  129202. _huff_lengthlist__44c4_s_long,
  129203. 0, 0, 0, 0, 0,
  129204. NULL,
  129205. NULL,
  129206. NULL,
  129207. NULL,
  129208. 0
  129209. };
  129210. static long _vq_quantlist__44c4_s_p1_0[] = {
  129211. 1,
  129212. 0,
  129213. 2,
  129214. };
  129215. static long _vq_lengthlist__44c4_s_p1_0[] = {
  129216. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  129217. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129221. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  129222. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129226. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  129227. 0, 0, 0, 0, 7, 8, 8, 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, 0, 0, 0, 0, 0, 0, 0,
  129259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  129262. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  129263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  129267. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  129268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  129272. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129307. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  129308. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129312. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  129313. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  129314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129317. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  129318. 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129626. 0,
  129627. };
  129628. static float _vq_quantthresh__44c4_s_p1_0[] = {
  129629. -0.5, 0.5,
  129630. };
  129631. static long _vq_quantmap__44c4_s_p1_0[] = {
  129632. 1, 0, 2,
  129633. };
  129634. static encode_aux_threshmatch _vq_auxt__44c4_s_p1_0 = {
  129635. _vq_quantthresh__44c4_s_p1_0,
  129636. _vq_quantmap__44c4_s_p1_0,
  129637. 3,
  129638. 3
  129639. };
  129640. static static_codebook _44c4_s_p1_0 = {
  129641. 8, 6561,
  129642. _vq_lengthlist__44c4_s_p1_0,
  129643. 1, -535822336, 1611661312, 2, 0,
  129644. _vq_quantlist__44c4_s_p1_0,
  129645. NULL,
  129646. &_vq_auxt__44c4_s_p1_0,
  129647. NULL,
  129648. 0
  129649. };
  129650. static long _vq_quantlist__44c4_s_p2_0[] = {
  129651. 2,
  129652. 1,
  129653. 3,
  129654. 0,
  129655. 4,
  129656. };
  129657. static long _vq_lengthlist__44c4_s_p2_0[] = {
  129658. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  129659. 7, 7, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  129660. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  129661. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  129662. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129667. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 7, 7, 0, 0,
  129668. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  129669. 7, 8, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  129670. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129675. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  129676. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  129677. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  129678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129683. 7,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  129684. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  129685. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  129686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129697. 0,
  129698. };
  129699. static float _vq_quantthresh__44c4_s_p2_0[] = {
  129700. -1.5, -0.5, 0.5, 1.5,
  129701. };
  129702. static long _vq_quantmap__44c4_s_p2_0[] = {
  129703. 3, 1, 0, 2, 4,
  129704. };
  129705. static encode_aux_threshmatch _vq_auxt__44c4_s_p2_0 = {
  129706. _vq_quantthresh__44c4_s_p2_0,
  129707. _vq_quantmap__44c4_s_p2_0,
  129708. 5,
  129709. 5
  129710. };
  129711. static static_codebook _44c4_s_p2_0 = {
  129712. 4, 625,
  129713. _vq_lengthlist__44c4_s_p2_0,
  129714. 1, -533725184, 1611661312, 3, 0,
  129715. _vq_quantlist__44c4_s_p2_0,
  129716. NULL,
  129717. &_vq_auxt__44c4_s_p2_0,
  129718. NULL,
  129719. 0
  129720. };
  129721. static long _vq_quantlist__44c4_s_p3_0[] = {
  129722. 2,
  129723. 1,
  129724. 3,
  129725. 0,
  129726. 4,
  129727. };
  129728. static long _vq_lengthlist__44c4_s_p3_0[] = {
  129729. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 4, 6, 6, 0, 0,
  129731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129732. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  129734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129735. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  129736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129768. 0,
  129769. };
  129770. static float _vq_quantthresh__44c4_s_p3_0[] = {
  129771. -1.5, -0.5, 0.5, 1.5,
  129772. };
  129773. static long _vq_quantmap__44c4_s_p3_0[] = {
  129774. 3, 1, 0, 2, 4,
  129775. };
  129776. static encode_aux_threshmatch _vq_auxt__44c4_s_p3_0 = {
  129777. _vq_quantthresh__44c4_s_p3_0,
  129778. _vq_quantmap__44c4_s_p3_0,
  129779. 5,
  129780. 5
  129781. };
  129782. static static_codebook _44c4_s_p3_0 = {
  129783. 4, 625,
  129784. _vq_lengthlist__44c4_s_p3_0,
  129785. 1, -533725184, 1611661312, 3, 0,
  129786. _vq_quantlist__44c4_s_p3_0,
  129787. NULL,
  129788. &_vq_auxt__44c4_s_p3_0,
  129789. NULL,
  129790. 0
  129791. };
  129792. static long _vq_quantlist__44c4_s_p4_0[] = {
  129793. 4,
  129794. 3,
  129795. 5,
  129796. 2,
  129797. 6,
  129798. 1,
  129799. 7,
  129800. 0,
  129801. 8,
  129802. };
  129803. static long _vq_lengthlist__44c4_s_p4_0[] = {
  129804. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  129805. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  129806. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  129807. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  129808. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129809. 0,
  129810. };
  129811. static float _vq_quantthresh__44c4_s_p4_0[] = {
  129812. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129813. };
  129814. static long _vq_quantmap__44c4_s_p4_0[] = {
  129815. 7, 5, 3, 1, 0, 2, 4, 6,
  129816. 8,
  129817. };
  129818. static encode_aux_threshmatch _vq_auxt__44c4_s_p4_0 = {
  129819. _vq_quantthresh__44c4_s_p4_0,
  129820. _vq_quantmap__44c4_s_p4_0,
  129821. 9,
  129822. 9
  129823. };
  129824. static static_codebook _44c4_s_p4_0 = {
  129825. 2, 81,
  129826. _vq_lengthlist__44c4_s_p4_0,
  129827. 1, -531628032, 1611661312, 4, 0,
  129828. _vq_quantlist__44c4_s_p4_0,
  129829. NULL,
  129830. &_vq_auxt__44c4_s_p4_0,
  129831. NULL,
  129832. 0
  129833. };
  129834. static long _vq_quantlist__44c4_s_p5_0[] = {
  129835. 4,
  129836. 3,
  129837. 5,
  129838. 2,
  129839. 6,
  129840. 1,
  129841. 7,
  129842. 0,
  129843. 8,
  129844. };
  129845. static long _vq_lengthlist__44c4_s_p5_0[] = {
  129846. 2, 3, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  129847. 9, 9, 0, 4, 5, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  129848. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10, 9, 0, 0, 0,
  129849. 9, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  129850. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,10,
  129851. 10,
  129852. };
  129853. static float _vq_quantthresh__44c4_s_p5_0[] = {
  129854. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129855. };
  129856. static long _vq_quantmap__44c4_s_p5_0[] = {
  129857. 7, 5, 3, 1, 0, 2, 4, 6,
  129858. 8,
  129859. };
  129860. static encode_aux_threshmatch _vq_auxt__44c4_s_p5_0 = {
  129861. _vq_quantthresh__44c4_s_p5_0,
  129862. _vq_quantmap__44c4_s_p5_0,
  129863. 9,
  129864. 9
  129865. };
  129866. static static_codebook _44c4_s_p5_0 = {
  129867. 2, 81,
  129868. _vq_lengthlist__44c4_s_p5_0,
  129869. 1, -531628032, 1611661312, 4, 0,
  129870. _vq_quantlist__44c4_s_p5_0,
  129871. NULL,
  129872. &_vq_auxt__44c4_s_p5_0,
  129873. NULL,
  129874. 0
  129875. };
  129876. static long _vq_quantlist__44c4_s_p6_0[] = {
  129877. 8,
  129878. 7,
  129879. 9,
  129880. 6,
  129881. 10,
  129882. 5,
  129883. 11,
  129884. 4,
  129885. 12,
  129886. 3,
  129887. 13,
  129888. 2,
  129889. 14,
  129890. 1,
  129891. 15,
  129892. 0,
  129893. 16,
  129894. };
  129895. static long _vq_lengthlist__44c4_s_p6_0[] = {
  129896. 2, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  129897. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  129898. 11,11, 0, 4, 4, 7, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  129899. 11,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  129900. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  129901. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  129902. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  129903. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  129904. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  129905. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  129906. 9,10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9,
  129907. 9, 9, 9,10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0,
  129908. 10,10,10,10,11,11,11,11,12,12,13,12, 0, 0, 0, 0,
  129909. 0, 0, 0,10,10,11,11,11,11,12,12,12,12, 0, 0, 0,
  129910. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  129911. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  129912. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,13,13,
  129913. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,
  129914. 13,
  129915. };
  129916. static float _vq_quantthresh__44c4_s_p6_0[] = {
  129917. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129918. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129919. };
  129920. static long _vq_quantmap__44c4_s_p6_0[] = {
  129921. 15, 13, 11, 9, 7, 5, 3, 1,
  129922. 0, 2, 4, 6, 8, 10, 12, 14,
  129923. 16,
  129924. };
  129925. static encode_aux_threshmatch _vq_auxt__44c4_s_p6_0 = {
  129926. _vq_quantthresh__44c4_s_p6_0,
  129927. _vq_quantmap__44c4_s_p6_0,
  129928. 17,
  129929. 17
  129930. };
  129931. static static_codebook _44c4_s_p6_0 = {
  129932. 2, 289,
  129933. _vq_lengthlist__44c4_s_p6_0,
  129934. 1, -529530880, 1611661312, 5, 0,
  129935. _vq_quantlist__44c4_s_p6_0,
  129936. NULL,
  129937. &_vq_auxt__44c4_s_p6_0,
  129938. NULL,
  129939. 0
  129940. };
  129941. static long _vq_quantlist__44c4_s_p7_0[] = {
  129942. 1,
  129943. 0,
  129944. 2,
  129945. };
  129946. static long _vq_lengthlist__44c4_s_p7_0[] = {
  129947. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  129948. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  129949. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  129950. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  129951. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  129952. 10,
  129953. };
  129954. static float _vq_quantthresh__44c4_s_p7_0[] = {
  129955. -5.5, 5.5,
  129956. };
  129957. static long _vq_quantmap__44c4_s_p7_0[] = {
  129958. 1, 0, 2,
  129959. };
  129960. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_0 = {
  129961. _vq_quantthresh__44c4_s_p7_0,
  129962. _vq_quantmap__44c4_s_p7_0,
  129963. 3,
  129964. 3
  129965. };
  129966. static static_codebook _44c4_s_p7_0 = {
  129967. 4, 81,
  129968. _vq_lengthlist__44c4_s_p7_0,
  129969. 1, -529137664, 1618345984, 2, 0,
  129970. _vq_quantlist__44c4_s_p7_0,
  129971. NULL,
  129972. &_vq_auxt__44c4_s_p7_0,
  129973. NULL,
  129974. 0
  129975. };
  129976. static long _vq_quantlist__44c4_s_p7_1[] = {
  129977. 5,
  129978. 4,
  129979. 6,
  129980. 3,
  129981. 7,
  129982. 2,
  129983. 8,
  129984. 1,
  129985. 9,
  129986. 0,
  129987. 10,
  129988. };
  129989. static long _vq_lengthlist__44c4_s_p7_1[] = {
  129990. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  129991. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  129992. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  129993. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  129994. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  129995. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  129996. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  129997. 10,10,10, 8, 8, 8, 8, 9, 9,
  129998. };
  129999. static float _vq_quantthresh__44c4_s_p7_1[] = {
  130000. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  130001. 3.5, 4.5,
  130002. };
  130003. static long _vq_quantmap__44c4_s_p7_1[] = {
  130004. 9, 7, 5, 3, 1, 0, 2, 4,
  130005. 6, 8, 10,
  130006. };
  130007. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_1 = {
  130008. _vq_quantthresh__44c4_s_p7_1,
  130009. _vq_quantmap__44c4_s_p7_1,
  130010. 11,
  130011. 11
  130012. };
  130013. static static_codebook _44c4_s_p7_1 = {
  130014. 2, 121,
  130015. _vq_lengthlist__44c4_s_p7_1,
  130016. 1, -531365888, 1611661312, 4, 0,
  130017. _vq_quantlist__44c4_s_p7_1,
  130018. NULL,
  130019. &_vq_auxt__44c4_s_p7_1,
  130020. NULL,
  130021. 0
  130022. };
  130023. static long _vq_quantlist__44c4_s_p8_0[] = {
  130024. 6,
  130025. 5,
  130026. 7,
  130027. 4,
  130028. 8,
  130029. 3,
  130030. 9,
  130031. 2,
  130032. 10,
  130033. 1,
  130034. 11,
  130035. 0,
  130036. 12,
  130037. };
  130038. static long _vq_lengthlist__44c4_s_p8_0[] = {
  130039. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  130040. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  130041. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130042. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  130043. 11, 0,12,12, 9, 9, 9, 9,10,10,10,10,11,11, 0,13,
  130044. 13, 9, 9,10, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  130045. 10,10,10,10,11,11,12,12, 0, 0, 0,10,10,10,10,10,
  130046. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  130047. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,13, 0,
  130048. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  130049. 0,13,12,12,12,12,12,13,13,
  130050. };
  130051. static float _vq_quantthresh__44c4_s_p8_0[] = {
  130052. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  130053. 12.5, 17.5, 22.5, 27.5,
  130054. };
  130055. static long _vq_quantmap__44c4_s_p8_0[] = {
  130056. 11, 9, 7, 5, 3, 1, 0, 2,
  130057. 4, 6, 8, 10, 12,
  130058. };
  130059. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_0 = {
  130060. _vq_quantthresh__44c4_s_p8_0,
  130061. _vq_quantmap__44c4_s_p8_0,
  130062. 13,
  130063. 13
  130064. };
  130065. static static_codebook _44c4_s_p8_0 = {
  130066. 2, 169,
  130067. _vq_lengthlist__44c4_s_p8_0,
  130068. 1, -526516224, 1616117760, 4, 0,
  130069. _vq_quantlist__44c4_s_p8_0,
  130070. NULL,
  130071. &_vq_auxt__44c4_s_p8_0,
  130072. NULL,
  130073. 0
  130074. };
  130075. static long _vq_quantlist__44c4_s_p8_1[] = {
  130076. 2,
  130077. 1,
  130078. 3,
  130079. 0,
  130080. 4,
  130081. };
  130082. static long _vq_lengthlist__44c4_s_p8_1[] = {
  130083. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 5, 4, 5, 5, 6,
  130084. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  130085. };
  130086. static float _vq_quantthresh__44c4_s_p8_1[] = {
  130087. -1.5, -0.5, 0.5, 1.5,
  130088. };
  130089. static long _vq_quantmap__44c4_s_p8_1[] = {
  130090. 3, 1, 0, 2, 4,
  130091. };
  130092. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_1 = {
  130093. _vq_quantthresh__44c4_s_p8_1,
  130094. _vq_quantmap__44c4_s_p8_1,
  130095. 5,
  130096. 5
  130097. };
  130098. static static_codebook _44c4_s_p8_1 = {
  130099. 2, 25,
  130100. _vq_lengthlist__44c4_s_p8_1,
  130101. 1, -533725184, 1611661312, 3, 0,
  130102. _vq_quantlist__44c4_s_p8_1,
  130103. NULL,
  130104. &_vq_auxt__44c4_s_p8_1,
  130105. NULL,
  130106. 0
  130107. };
  130108. static long _vq_quantlist__44c4_s_p9_0[] = {
  130109. 6,
  130110. 5,
  130111. 7,
  130112. 4,
  130113. 8,
  130114. 3,
  130115. 9,
  130116. 2,
  130117. 10,
  130118. 1,
  130119. 11,
  130120. 0,
  130121. 12,
  130122. };
  130123. static long _vq_lengthlist__44c4_s_p9_0[] = {
  130124. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 4, 7, 7,
  130125. 12,12,12,12,12,12,12,12,12,12, 3, 8, 8,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,12,12,12,12,12,12,12,
  130132. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130133. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130134. 12,12,12,12,12,12,12,12,12,
  130135. };
  130136. static float _vq_quantthresh__44c4_s_p9_0[] = {
  130137. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  130138. 787.5, 1102.5, 1417.5, 1732.5,
  130139. };
  130140. static long _vq_quantmap__44c4_s_p9_0[] = {
  130141. 11, 9, 7, 5, 3, 1, 0, 2,
  130142. 4, 6, 8, 10, 12,
  130143. };
  130144. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_0 = {
  130145. _vq_quantthresh__44c4_s_p9_0,
  130146. _vq_quantmap__44c4_s_p9_0,
  130147. 13,
  130148. 13
  130149. };
  130150. static static_codebook _44c4_s_p9_0 = {
  130151. 2, 169,
  130152. _vq_lengthlist__44c4_s_p9_0,
  130153. 1, -513964032, 1628680192, 4, 0,
  130154. _vq_quantlist__44c4_s_p9_0,
  130155. NULL,
  130156. &_vq_auxt__44c4_s_p9_0,
  130157. NULL,
  130158. 0
  130159. };
  130160. static long _vq_quantlist__44c4_s_p9_1[] = {
  130161. 7,
  130162. 6,
  130163. 8,
  130164. 5,
  130165. 9,
  130166. 4,
  130167. 10,
  130168. 3,
  130169. 11,
  130170. 2,
  130171. 12,
  130172. 1,
  130173. 13,
  130174. 0,
  130175. 14,
  130176. };
  130177. static long _vq_lengthlist__44c4_s_p9_1[] = {
  130178. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,10,10, 6,
  130179. 5, 5, 7, 7, 9, 8,10, 9,11,10,12,12,13,13, 6, 5,
  130180. 5, 7, 7, 9, 9,10,10,11,11,12,12,12,13,19, 8, 8,
  130181. 8, 8, 9, 9,10,10,12,11,12,12,13,13,19, 8, 8, 8,
  130182. 8, 9, 9,11,11,12,12,13,13,13,13,19,12,12, 9, 9,
  130183. 11,11,11,11,12,11,13,12,13,13,18,12,12, 9, 9,11,
  130184. 10,11,11,12,12,12,13,13,14,19,18,18,11,11,11,11,
  130185. 12,12,13,12,13,13,14,14,16,18,18,11,11,11,10,12,
  130186. 11,13,13,13,13,13,14,17,18,18,14,15,11,12,12,13,
  130187. 13,13,13,14,14,14,18,18,18,15,15,12,10,13,10,13,
  130188. 13,13,13,13,14,18,17,18,17,18,12,13,12,13,13,13,
  130189. 14,14,16,14,18,17,18,18,17,13,12,13,10,12,12,14,
  130190. 14,14,14,17,18,18,18,18,14,15,12,12,13,12,14,14,
  130191. 15,15,18,18,18,17,18,15,14,12,11,12,12,14,14,14,
  130192. 15,
  130193. };
  130194. static float _vq_quantthresh__44c4_s_p9_1[] = {
  130195. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  130196. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  130197. };
  130198. static long _vq_quantmap__44c4_s_p9_1[] = {
  130199. 13, 11, 9, 7, 5, 3, 1, 0,
  130200. 2, 4, 6, 8, 10, 12, 14,
  130201. };
  130202. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_1 = {
  130203. _vq_quantthresh__44c4_s_p9_1,
  130204. _vq_quantmap__44c4_s_p9_1,
  130205. 15,
  130206. 15
  130207. };
  130208. static static_codebook _44c4_s_p9_1 = {
  130209. 2, 225,
  130210. _vq_lengthlist__44c4_s_p9_1,
  130211. 1, -520986624, 1620377600, 4, 0,
  130212. _vq_quantlist__44c4_s_p9_1,
  130213. NULL,
  130214. &_vq_auxt__44c4_s_p9_1,
  130215. NULL,
  130216. 0
  130217. };
  130218. static long _vq_quantlist__44c4_s_p9_2[] = {
  130219. 10,
  130220. 9,
  130221. 11,
  130222. 8,
  130223. 12,
  130224. 7,
  130225. 13,
  130226. 6,
  130227. 14,
  130228. 5,
  130229. 15,
  130230. 4,
  130231. 16,
  130232. 3,
  130233. 17,
  130234. 2,
  130235. 18,
  130236. 1,
  130237. 19,
  130238. 0,
  130239. 20,
  130240. };
  130241. static long _vq_lengthlist__44c4_s_p9_2[] = {
  130242. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  130243. 8, 9, 9, 9, 9,11, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  130244. 9, 9, 9, 9, 9, 9,10,10,10,10,11, 6, 6, 7, 7, 8,
  130245. 8, 8, 8, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  130246. 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  130247. 10,10,10,10,12,11,11, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  130248. 9,10,10,10,10,10,10,10,10,12,11,12, 8, 8, 8, 8,
  130249. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  130250. 11, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,
  130251. 10,10,10,11,11,12, 9, 9, 9, 9, 9, 9,10, 9,10,10,
  130252. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  130253. 9,10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,
  130254. 11,11, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  130255. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  130256. 10,10,10,10,10,10,10,11,11,11,12,12,10,10,10,10,
  130257. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,12,
  130258. 11,11,11, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  130259. 10,11,12,11,11,11,11,11,10,10,10,10,10,10,10,10,
  130260. 10,10,10,10,10,10,11,11,11,12,11,11,11,10,10,10,
  130261. 10,10,10,10,10,10,10,10,10,10,10,12,11,11,12,11,
  130262. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130263. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  130264. 10,10,10,10,10,11,11,11,11,12,12,11,11,11,11,11,
  130265. 11,11,10,10,10,10,10,10,10,10,12,12,12,11,11,11,
  130266. 12,11,11,11,10,10,10,10,10,10,10,10,10,10,10,12,
  130267. 11,12,12,12,12,12,11,12,11,11,10,10,10,10,10,10,
  130268. 10,10,10,10,12,12,12,12,11,11,11,11,11,11,11,10,
  130269. 10,10,10,10,10,10,10,10,10,
  130270. };
  130271. static float _vq_quantthresh__44c4_s_p9_2[] = {
  130272. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  130273. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  130274. 6.5, 7.5, 8.5, 9.5,
  130275. };
  130276. static long _vq_quantmap__44c4_s_p9_2[] = {
  130277. 19, 17, 15, 13, 11, 9, 7, 5,
  130278. 3, 1, 0, 2, 4, 6, 8, 10,
  130279. 12, 14, 16, 18, 20,
  130280. };
  130281. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_2 = {
  130282. _vq_quantthresh__44c4_s_p9_2,
  130283. _vq_quantmap__44c4_s_p9_2,
  130284. 21,
  130285. 21
  130286. };
  130287. static static_codebook _44c4_s_p9_2 = {
  130288. 2, 441,
  130289. _vq_lengthlist__44c4_s_p9_2,
  130290. 1, -529268736, 1611661312, 5, 0,
  130291. _vq_quantlist__44c4_s_p9_2,
  130292. NULL,
  130293. &_vq_auxt__44c4_s_p9_2,
  130294. NULL,
  130295. 0
  130296. };
  130297. static long _huff_lengthlist__44c4_s_short[] = {
  130298. 4, 7,14,10,15,10,12,15,16,15, 4, 2,11, 5,10, 6,
  130299. 8,11,14,14,14,10, 7,11, 6, 8,10,11,13,15, 9, 4,
  130300. 11, 5, 9, 6, 9,12,14,15,14, 9, 6, 9, 4, 5, 7,10,
  130301. 12,13, 9, 5, 7, 6, 5, 5, 7,10,13,13,10, 8, 9, 8,
  130302. 7, 6, 8,10,14,14,13,11,10,10, 7, 7, 8,11,14,15,
  130303. 13,12, 9, 9, 6, 5, 7,10,14,17,15,13,11,10, 6, 6,
  130304. 7, 9,12,17,
  130305. };
  130306. static static_codebook _huff_book__44c4_s_short = {
  130307. 2, 100,
  130308. _huff_lengthlist__44c4_s_short,
  130309. 0, 0, 0, 0, 0,
  130310. NULL,
  130311. NULL,
  130312. NULL,
  130313. NULL,
  130314. 0
  130315. };
  130316. static long _huff_lengthlist__44c5_s_long[] = {
  130317. 3, 8, 9,13,10,12,12,12,12,12, 6, 4, 6, 8, 6, 8,
  130318. 10,10,11,12, 8, 5, 4,10, 4, 7, 8, 9,10,11,13, 8,
  130319. 10, 8, 9, 9,11,12,13,14,10, 6, 4, 9, 3, 5, 6, 8,
  130320. 10,11,11, 8, 6, 9, 5, 5, 6, 7, 9,11,12, 9, 7,11,
  130321. 6, 6, 6, 7, 8,10,12,11, 9,12, 7, 7, 6, 6, 7, 9,
  130322. 13,12,10,13, 9, 8, 7, 7, 7, 8,11,15,11,15,11,10,
  130323. 9, 8, 7, 7,
  130324. };
  130325. static static_codebook _huff_book__44c5_s_long = {
  130326. 2, 100,
  130327. _huff_lengthlist__44c5_s_long,
  130328. 0, 0, 0, 0, 0,
  130329. NULL,
  130330. NULL,
  130331. NULL,
  130332. NULL,
  130333. 0
  130334. };
  130335. static long _vq_quantlist__44c5_s_p1_0[] = {
  130336. 1,
  130337. 0,
  130338. 2,
  130339. };
  130340. static long _vq_lengthlist__44c5_s_p1_0[] = {
  130341. 2, 4, 4, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  130342. 0, 0, 4, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130346. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  130347. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130351. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  130352. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  130387. 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  130388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  130392. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  130393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  130397. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  130398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130432. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  130433. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130437. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  130438. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  130439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130442. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  130443. 0, 0, 0, 0, 0, 0, 9,11,10, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130751. 0,
  130752. };
  130753. static float _vq_quantthresh__44c5_s_p1_0[] = {
  130754. -0.5, 0.5,
  130755. };
  130756. static long _vq_quantmap__44c5_s_p1_0[] = {
  130757. 1, 0, 2,
  130758. };
  130759. static encode_aux_threshmatch _vq_auxt__44c5_s_p1_0 = {
  130760. _vq_quantthresh__44c5_s_p1_0,
  130761. _vq_quantmap__44c5_s_p1_0,
  130762. 3,
  130763. 3
  130764. };
  130765. static static_codebook _44c5_s_p1_0 = {
  130766. 8, 6561,
  130767. _vq_lengthlist__44c5_s_p1_0,
  130768. 1, -535822336, 1611661312, 2, 0,
  130769. _vq_quantlist__44c5_s_p1_0,
  130770. NULL,
  130771. &_vq_auxt__44c5_s_p1_0,
  130772. NULL,
  130773. 0
  130774. };
  130775. static long _vq_quantlist__44c5_s_p2_0[] = {
  130776. 2,
  130777. 1,
  130778. 3,
  130779. 0,
  130780. 4,
  130781. };
  130782. static long _vq_lengthlist__44c5_s_p2_0[] = {
  130783. 2, 4, 4, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  130784. 8, 7, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  130785. 8, 0, 0, 0, 8, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  130786. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 7, 8, 0,
  130787. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130792. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 8, 8, 0, 0,
  130793. 0, 8, 8, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5,
  130794. 7, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,
  130795. 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130800. 0, 0, 0, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8,
  130801. 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0,
  130802. 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,10, 0, 0,
  130803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130808. 8,10,10, 0, 0, 0,10,10, 0, 0, 0, 9,10, 0, 0, 0,
  130809. 11,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0,10,
  130810. 10, 0, 0, 0,10,10, 0, 0, 0,10,11, 0, 0, 0, 0, 0,
  130811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130822. 0,
  130823. };
  130824. static float _vq_quantthresh__44c5_s_p2_0[] = {
  130825. -1.5, -0.5, 0.5, 1.5,
  130826. };
  130827. static long _vq_quantmap__44c5_s_p2_0[] = {
  130828. 3, 1, 0, 2, 4,
  130829. };
  130830. static encode_aux_threshmatch _vq_auxt__44c5_s_p2_0 = {
  130831. _vq_quantthresh__44c5_s_p2_0,
  130832. _vq_quantmap__44c5_s_p2_0,
  130833. 5,
  130834. 5
  130835. };
  130836. static static_codebook _44c5_s_p2_0 = {
  130837. 4, 625,
  130838. _vq_lengthlist__44c5_s_p2_0,
  130839. 1, -533725184, 1611661312, 3, 0,
  130840. _vq_quantlist__44c5_s_p2_0,
  130841. NULL,
  130842. &_vq_auxt__44c5_s_p2_0,
  130843. NULL,
  130844. 0
  130845. };
  130846. static long _vq_quantlist__44c5_s_p3_0[] = {
  130847. 2,
  130848. 1,
  130849. 3,
  130850. 0,
  130851. 4,
  130852. };
  130853. static long _vq_lengthlist__44c5_s_p3_0[] = {
  130854. 2, 4, 3, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 6, 6, 0, 0,
  130856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130857. 0, 0, 3, 5, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  130859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130860. 0, 0, 0, 0, 5, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  130861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130893. 0,
  130894. };
  130895. static float _vq_quantthresh__44c5_s_p3_0[] = {
  130896. -1.5, -0.5, 0.5, 1.5,
  130897. };
  130898. static long _vq_quantmap__44c5_s_p3_0[] = {
  130899. 3, 1, 0, 2, 4,
  130900. };
  130901. static encode_aux_threshmatch _vq_auxt__44c5_s_p3_0 = {
  130902. _vq_quantthresh__44c5_s_p3_0,
  130903. _vq_quantmap__44c5_s_p3_0,
  130904. 5,
  130905. 5
  130906. };
  130907. static static_codebook _44c5_s_p3_0 = {
  130908. 4, 625,
  130909. _vq_lengthlist__44c5_s_p3_0,
  130910. 1, -533725184, 1611661312, 3, 0,
  130911. _vq_quantlist__44c5_s_p3_0,
  130912. NULL,
  130913. &_vq_auxt__44c5_s_p3_0,
  130914. NULL,
  130915. 0
  130916. };
  130917. static long _vq_quantlist__44c5_s_p4_0[] = {
  130918. 4,
  130919. 3,
  130920. 5,
  130921. 2,
  130922. 6,
  130923. 1,
  130924. 7,
  130925. 0,
  130926. 8,
  130927. };
  130928. static long _vq_lengthlist__44c5_s_p4_0[] = {
  130929. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  130930. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  130931. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  130932. 7, 7, 0, 0, 0, 0, 0, 0, 0, 8, 7, 0, 0, 0, 0, 0,
  130933. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130934. 0,
  130935. };
  130936. static float _vq_quantthresh__44c5_s_p4_0[] = {
  130937. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130938. };
  130939. static long _vq_quantmap__44c5_s_p4_0[] = {
  130940. 7, 5, 3, 1, 0, 2, 4, 6,
  130941. 8,
  130942. };
  130943. static encode_aux_threshmatch _vq_auxt__44c5_s_p4_0 = {
  130944. _vq_quantthresh__44c5_s_p4_0,
  130945. _vq_quantmap__44c5_s_p4_0,
  130946. 9,
  130947. 9
  130948. };
  130949. static static_codebook _44c5_s_p4_0 = {
  130950. 2, 81,
  130951. _vq_lengthlist__44c5_s_p4_0,
  130952. 1, -531628032, 1611661312, 4, 0,
  130953. _vq_quantlist__44c5_s_p4_0,
  130954. NULL,
  130955. &_vq_auxt__44c5_s_p4_0,
  130956. NULL,
  130957. 0
  130958. };
  130959. static long _vq_quantlist__44c5_s_p5_0[] = {
  130960. 4,
  130961. 3,
  130962. 5,
  130963. 2,
  130964. 6,
  130965. 1,
  130966. 7,
  130967. 0,
  130968. 8,
  130969. };
  130970. static long _vq_lengthlist__44c5_s_p5_0[] = {
  130971. 2, 4, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  130972. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  130973. 7, 7, 9, 9, 0, 0, 0, 7, 6, 7, 7, 9, 9, 0, 0, 0,
  130974. 8, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  130975. 0, 0, 9, 9, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  130976. 10,
  130977. };
  130978. static float _vq_quantthresh__44c5_s_p5_0[] = {
  130979. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130980. };
  130981. static long _vq_quantmap__44c5_s_p5_0[] = {
  130982. 7, 5, 3, 1, 0, 2, 4, 6,
  130983. 8,
  130984. };
  130985. static encode_aux_threshmatch _vq_auxt__44c5_s_p5_0 = {
  130986. _vq_quantthresh__44c5_s_p5_0,
  130987. _vq_quantmap__44c5_s_p5_0,
  130988. 9,
  130989. 9
  130990. };
  130991. static static_codebook _44c5_s_p5_0 = {
  130992. 2, 81,
  130993. _vq_lengthlist__44c5_s_p5_0,
  130994. 1, -531628032, 1611661312, 4, 0,
  130995. _vq_quantlist__44c5_s_p5_0,
  130996. NULL,
  130997. &_vq_auxt__44c5_s_p5_0,
  130998. NULL,
  130999. 0
  131000. };
  131001. static long _vq_quantlist__44c5_s_p6_0[] = {
  131002. 8,
  131003. 7,
  131004. 9,
  131005. 6,
  131006. 10,
  131007. 5,
  131008. 11,
  131009. 4,
  131010. 12,
  131011. 3,
  131012. 13,
  131013. 2,
  131014. 14,
  131015. 1,
  131016. 15,
  131017. 0,
  131018. 16,
  131019. };
  131020. static long _vq_lengthlist__44c5_s_p6_0[] = {
  131021. 2, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,11,
  131022. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  131023. 12,12, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  131024. 11,12,12, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  131025. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  131026. 10,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  131027. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 9,10,10,10,
  131028. 10,11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,
  131029. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  131030. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  131031. 10,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9,
  131032. 9, 9,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  131033. 10,10,10,10,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  131034. 0, 0, 0,10,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  131035. 0, 0, 0, 0,11,11,11,11,12,12,12,13,13,13, 0, 0,
  131036. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  131037. 0, 0, 0, 0, 0, 0,12,12,12,12,13,12,13,13,13,13,
  131038. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  131039. 13,
  131040. };
  131041. static float _vq_quantthresh__44c5_s_p6_0[] = {
  131042. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131043. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131044. };
  131045. static long _vq_quantmap__44c5_s_p6_0[] = {
  131046. 15, 13, 11, 9, 7, 5, 3, 1,
  131047. 0, 2, 4, 6, 8, 10, 12, 14,
  131048. 16,
  131049. };
  131050. static encode_aux_threshmatch _vq_auxt__44c5_s_p6_0 = {
  131051. _vq_quantthresh__44c5_s_p6_0,
  131052. _vq_quantmap__44c5_s_p6_0,
  131053. 17,
  131054. 17
  131055. };
  131056. static static_codebook _44c5_s_p6_0 = {
  131057. 2, 289,
  131058. _vq_lengthlist__44c5_s_p6_0,
  131059. 1, -529530880, 1611661312, 5, 0,
  131060. _vq_quantlist__44c5_s_p6_0,
  131061. NULL,
  131062. &_vq_auxt__44c5_s_p6_0,
  131063. NULL,
  131064. 0
  131065. };
  131066. static long _vq_quantlist__44c5_s_p7_0[] = {
  131067. 1,
  131068. 0,
  131069. 2,
  131070. };
  131071. static long _vq_lengthlist__44c5_s_p7_0[] = {
  131072. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  131073. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  131074. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  131075. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  131076. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  131077. 10,
  131078. };
  131079. static float _vq_quantthresh__44c5_s_p7_0[] = {
  131080. -5.5, 5.5,
  131081. };
  131082. static long _vq_quantmap__44c5_s_p7_0[] = {
  131083. 1, 0, 2,
  131084. };
  131085. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_0 = {
  131086. _vq_quantthresh__44c5_s_p7_0,
  131087. _vq_quantmap__44c5_s_p7_0,
  131088. 3,
  131089. 3
  131090. };
  131091. static static_codebook _44c5_s_p7_0 = {
  131092. 4, 81,
  131093. _vq_lengthlist__44c5_s_p7_0,
  131094. 1, -529137664, 1618345984, 2, 0,
  131095. _vq_quantlist__44c5_s_p7_0,
  131096. NULL,
  131097. &_vq_auxt__44c5_s_p7_0,
  131098. NULL,
  131099. 0
  131100. };
  131101. static long _vq_quantlist__44c5_s_p7_1[] = {
  131102. 5,
  131103. 4,
  131104. 6,
  131105. 3,
  131106. 7,
  131107. 2,
  131108. 8,
  131109. 1,
  131110. 9,
  131111. 0,
  131112. 10,
  131113. };
  131114. static long _vq_lengthlist__44c5_s_p7_1[] = {
  131115. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6,
  131116. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  131117. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  131118. 7, 8, 8, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  131119. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  131120. 8, 8, 8, 8, 8, 8, 8, 9,10,10,10,10,10, 8, 8, 8,
  131121. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  131122. 10,10,10, 8, 8, 8, 8, 8, 8,
  131123. };
  131124. static float _vq_quantthresh__44c5_s_p7_1[] = {
  131125. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  131126. 3.5, 4.5,
  131127. };
  131128. static long _vq_quantmap__44c5_s_p7_1[] = {
  131129. 9, 7, 5, 3, 1, 0, 2, 4,
  131130. 6, 8, 10,
  131131. };
  131132. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_1 = {
  131133. _vq_quantthresh__44c5_s_p7_1,
  131134. _vq_quantmap__44c5_s_p7_1,
  131135. 11,
  131136. 11
  131137. };
  131138. static static_codebook _44c5_s_p7_1 = {
  131139. 2, 121,
  131140. _vq_lengthlist__44c5_s_p7_1,
  131141. 1, -531365888, 1611661312, 4, 0,
  131142. _vq_quantlist__44c5_s_p7_1,
  131143. NULL,
  131144. &_vq_auxt__44c5_s_p7_1,
  131145. NULL,
  131146. 0
  131147. };
  131148. static long _vq_quantlist__44c5_s_p8_0[] = {
  131149. 6,
  131150. 5,
  131151. 7,
  131152. 4,
  131153. 8,
  131154. 3,
  131155. 9,
  131156. 2,
  131157. 10,
  131158. 1,
  131159. 11,
  131160. 0,
  131161. 12,
  131162. };
  131163. static long _vq_lengthlist__44c5_s_p8_0[] = {
  131164. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  131165. 7, 7, 8, 8, 8, 9,10,10,10,10, 7, 5, 5, 7, 7, 8,
  131166. 8, 9, 9,10,10,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  131167. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  131168. 11, 0,12,12, 9, 9, 9,10,10,10,10,10,11,11, 0,13,
  131169. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  131170. 10,10,10,10,11,11,11,11, 0, 0, 0,10,10,10,10,10,
  131171. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  131172. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,12, 0,
  131173. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  131174. 0,12,12,12,12,12,12,13,13,
  131175. };
  131176. static float _vq_quantthresh__44c5_s_p8_0[] = {
  131177. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  131178. 12.5, 17.5, 22.5, 27.5,
  131179. };
  131180. static long _vq_quantmap__44c5_s_p8_0[] = {
  131181. 11, 9, 7, 5, 3, 1, 0, 2,
  131182. 4, 6, 8, 10, 12,
  131183. };
  131184. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_0 = {
  131185. _vq_quantthresh__44c5_s_p8_0,
  131186. _vq_quantmap__44c5_s_p8_0,
  131187. 13,
  131188. 13
  131189. };
  131190. static static_codebook _44c5_s_p8_0 = {
  131191. 2, 169,
  131192. _vq_lengthlist__44c5_s_p8_0,
  131193. 1, -526516224, 1616117760, 4, 0,
  131194. _vq_quantlist__44c5_s_p8_0,
  131195. NULL,
  131196. &_vq_auxt__44c5_s_p8_0,
  131197. NULL,
  131198. 0
  131199. };
  131200. static long _vq_quantlist__44c5_s_p8_1[] = {
  131201. 2,
  131202. 1,
  131203. 3,
  131204. 0,
  131205. 4,
  131206. };
  131207. static long _vq_lengthlist__44c5_s_p8_1[] = {
  131208. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  131209. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  131210. };
  131211. static float _vq_quantthresh__44c5_s_p8_1[] = {
  131212. -1.5, -0.5, 0.5, 1.5,
  131213. };
  131214. static long _vq_quantmap__44c5_s_p8_1[] = {
  131215. 3, 1, 0, 2, 4,
  131216. };
  131217. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_1 = {
  131218. _vq_quantthresh__44c5_s_p8_1,
  131219. _vq_quantmap__44c5_s_p8_1,
  131220. 5,
  131221. 5
  131222. };
  131223. static static_codebook _44c5_s_p8_1 = {
  131224. 2, 25,
  131225. _vq_lengthlist__44c5_s_p8_1,
  131226. 1, -533725184, 1611661312, 3, 0,
  131227. _vq_quantlist__44c5_s_p8_1,
  131228. NULL,
  131229. &_vq_auxt__44c5_s_p8_1,
  131230. NULL,
  131231. 0
  131232. };
  131233. static long _vq_quantlist__44c5_s_p9_0[] = {
  131234. 7,
  131235. 6,
  131236. 8,
  131237. 5,
  131238. 9,
  131239. 4,
  131240. 10,
  131241. 3,
  131242. 11,
  131243. 2,
  131244. 12,
  131245. 1,
  131246. 13,
  131247. 0,
  131248. 14,
  131249. };
  131250. static long _vq_lengthlist__44c5_s_p9_0[] = {
  131251. 1, 3, 3,13,13,13,13,13,13,13,13,13,13,13,13, 4,
  131252. 7, 7,13,13,13,13,13,13,13,13,13,13,13,13, 3, 8,
  131253. 6,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,13,13,13,13,13,13,13,
  131262. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131263. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131264. 13,13,13,13,13,13,13,13,13,12,12,12,12,12,12,12,
  131265. 12,
  131266. };
  131267. static float _vq_quantthresh__44c5_s_p9_0[] = {
  131268. -2320.5, -1963.5, -1606.5, -1249.5, -892.5, -535.5, -178.5, 178.5,
  131269. 535.5, 892.5, 1249.5, 1606.5, 1963.5, 2320.5,
  131270. };
  131271. static long _vq_quantmap__44c5_s_p9_0[] = {
  131272. 13, 11, 9, 7, 5, 3, 1, 0,
  131273. 2, 4, 6, 8, 10, 12, 14,
  131274. };
  131275. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_0 = {
  131276. _vq_quantthresh__44c5_s_p9_0,
  131277. _vq_quantmap__44c5_s_p9_0,
  131278. 15,
  131279. 15
  131280. };
  131281. static static_codebook _44c5_s_p9_0 = {
  131282. 2, 225,
  131283. _vq_lengthlist__44c5_s_p9_0,
  131284. 1, -512522752, 1628852224, 4, 0,
  131285. _vq_quantlist__44c5_s_p9_0,
  131286. NULL,
  131287. &_vq_auxt__44c5_s_p9_0,
  131288. NULL,
  131289. 0
  131290. };
  131291. static long _vq_quantlist__44c5_s_p9_1[] = {
  131292. 8,
  131293. 7,
  131294. 9,
  131295. 6,
  131296. 10,
  131297. 5,
  131298. 11,
  131299. 4,
  131300. 12,
  131301. 3,
  131302. 13,
  131303. 2,
  131304. 14,
  131305. 1,
  131306. 15,
  131307. 0,
  131308. 16,
  131309. };
  131310. static long _vq_lengthlist__44c5_s_p9_1[] = {
  131311. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,11,10,11,
  131312. 11, 6, 5, 5, 7, 7, 8, 9,10,10,11,10,12,11,12,11,
  131313. 13,12, 6, 5, 5, 7, 7, 9, 9,10,10,11,11,12,12,13,
  131314. 12,13,13,18, 8, 8, 8, 8, 9, 9,10,11,11,11,12,11,
  131315. 13,11,13,12,18, 8, 8, 8, 8,10,10,11,11,12,12,13,
  131316. 13,13,13,13,14,18,12,12, 9, 9,11,11,11,11,12,12,
  131317. 13,12,13,12,13,13,20,13,12, 9, 9,11,11,11,11,12,
  131318. 12,13,13,13,14,14,13,20,18,19,11,12,11,11,12,12,
  131319. 13,13,13,13,13,13,14,13,18,19,19,12,11,11,11,12,
  131320. 12,13,12,13,13,13,14,14,13,18,17,19,14,15,12,12,
  131321. 12,13,13,13,14,14,14,14,14,14,19,19,19,16,15,12,
  131322. 11,13,12,14,14,14,13,13,14,14,14,19,18,19,18,19,
  131323. 13,13,13,13,14,14,14,13,14,14,14,14,18,17,19,19,
  131324. 19,13,13,13,11,13,11,13,14,14,14,14,14,19,17,17,
  131325. 18,18,16,16,13,13,13,13,14,13,15,15,14,14,19,19,
  131326. 17,17,18,16,16,13,11,14,10,13,12,14,14,14,14,19,
  131327. 19,19,19,19,18,17,13,14,13,11,14,13,14,14,15,15,
  131328. 19,19,19,17,19,18,18,14,13,12,11,14,11,15,15,15,
  131329. 15,
  131330. };
  131331. static float _vq_quantthresh__44c5_s_p9_1[] = {
  131332. -157.5, -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5,
  131333. 10.5, 31.5, 52.5, 73.5, 94.5, 115.5, 136.5, 157.5,
  131334. };
  131335. static long _vq_quantmap__44c5_s_p9_1[] = {
  131336. 15, 13, 11, 9, 7, 5, 3, 1,
  131337. 0, 2, 4, 6, 8, 10, 12, 14,
  131338. 16,
  131339. };
  131340. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_1 = {
  131341. _vq_quantthresh__44c5_s_p9_1,
  131342. _vq_quantmap__44c5_s_p9_1,
  131343. 17,
  131344. 17
  131345. };
  131346. static static_codebook _44c5_s_p9_1 = {
  131347. 2, 289,
  131348. _vq_lengthlist__44c5_s_p9_1,
  131349. 1, -520814592, 1620377600, 5, 0,
  131350. _vq_quantlist__44c5_s_p9_1,
  131351. NULL,
  131352. &_vq_auxt__44c5_s_p9_1,
  131353. NULL,
  131354. 0
  131355. };
  131356. static long _vq_quantlist__44c5_s_p9_2[] = {
  131357. 10,
  131358. 9,
  131359. 11,
  131360. 8,
  131361. 12,
  131362. 7,
  131363. 13,
  131364. 6,
  131365. 14,
  131366. 5,
  131367. 15,
  131368. 4,
  131369. 16,
  131370. 3,
  131371. 17,
  131372. 2,
  131373. 18,
  131374. 1,
  131375. 19,
  131376. 0,
  131377. 20,
  131378. };
  131379. static long _vq_lengthlist__44c5_s_p9_2[] = {
  131380. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  131381. 8, 8, 8, 8, 9,11, 5, 6, 7, 7, 8, 7, 8, 8, 8, 8,
  131382. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11, 5, 5, 7, 7, 7,
  131383. 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  131384. 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  131385. 9,10, 9,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  131386. 9, 9, 9,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  131387. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,11,11,
  131388. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  131389. 10,10,10,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131390. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  131391. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,11,11,11,
  131392. 11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,
  131393. 10,10,11,11,11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,
  131394. 10,10,10,10,10,10,10,11,11,11,11,11, 9, 9,10, 9,
  131395. 10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,
  131396. 11,11,11, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  131397. 10,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  131398. 10,10,10,10,10,10,11,11,11,11,11,11,11,10,10,10,
  131399. 10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,
  131400. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131401. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  131402. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  131403. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  131404. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,11,
  131405. 11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  131406. 10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,10,
  131407. 10,10,10,10,10,10,10,10,10,
  131408. };
  131409. static float _vq_quantthresh__44c5_s_p9_2[] = {
  131410. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  131411. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  131412. 6.5, 7.5, 8.5, 9.5,
  131413. };
  131414. static long _vq_quantmap__44c5_s_p9_2[] = {
  131415. 19, 17, 15, 13, 11, 9, 7, 5,
  131416. 3, 1, 0, 2, 4, 6, 8, 10,
  131417. 12, 14, 16, 18, 20,
  131418. };
  131419. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_2 = {
  131420. _vq_quantthresh__44c5_s_p9_2,
  131421. _vq_quantmap__44c5_s_p9_2,
  131422. 21,
  131423. 21
  131424. };
  131425. static static_codebook _44c5_s_p9_2 = {
  131426. 2, 441,
  131427. _vq_lengthlist__44c5_s_p9_2,
  131428. 1, -529268736, 1611661312, 5, 0,
  131429. _vq_quantlist__44c5_s_p9_2,
  131430. NULL,
  131431. &_vq_auxt__44c5_s_p9_2,
  131432. NULL,
  131433. 0
  131434. };
  131435. static long _huff_lengthlist__44c5_s_short[] = {
  131436. 5, 8,10,14,11,11,12,16,15,17, 5, 5, 7, 9, 7, 8,
  131437. 10,13,17,17, 7, 5, 5,10, 5, 7, 8,11,13,15,10, 8,
  131438. 10, 8, 8, 8,11,15,18,18, 8, 5, 5, 8, 3, 4, 6,10,
  131439. 14,16, 9, 7, 6, 7, 4, 3, 5, 9,14,18,10, 9, 8,10,
  131440. 6, 5, 6, 9,14,18,12,12,11,12, 8, 7, 8,11,14,18,
  131441. 14,13,12,10, 7, 5, 6, 9,14,18,14,14,13,10, 6, 5,
  131442. 6, 8,11,16,
  131443. };
  131444. static static_codebook _huff_book__44c5_s_short = {
  131445. 2, 100,
  131446. _huff_lengthlist__44c5_s_short,
  131447. 0, 0, 0, 0, 0,
  131448. NULL,
  131449. NULL,
  131450. NULL,
  131451. NULL,
  131452. 0
  131453. };
  131454. static long _huff_lengthlist__44c6_s_long[] = {
  131455. 3, 8,11,13,14,14,13,13,16,14, 6, 3, 4, 7, 9, 9,
  131456. 10,11,14,13,10, 4, 3, 5, 7, 7, 9,10,13,15,12, 7,
  131457. 4, 4, 6, 6, 8,10,13,15,12, 8, 6, 6, 6, 6, 8,10,
  131458. 13,14,11, 9, 7, 6, 6, 6, 7, 8,12,11,13,10, 9, 8,
  131459. 7, 6, 6, 7,11,11,13,11,10, 9, 9, 7, 7, 6,10,11,
  131460. 13,13,13,13,13,11, 9, 8,10,12,12,15,15,16,15,12,
  131461. 11,10,10,12,
  131462. };
  131463. static static_codebook _huff_book__44c6_s_long = {
  131464. 2, 100,
  131465. _huff_lengthlist__44c6_s_long,
  131466. 0, 0, 0, 0, 0,
  131467. NULL,
  131468. NULL,
  131469. NULL,
  131470. NULL,
  131471. 0
  131472. };
  131473. static long _vq_quantlist__44c6_s_p1_0[] = {
  131474. 1,
  131475. 0,
  131476. 2,
  131477. };
  131478. static long _vq_lengthlist__44c6_s_p1_0[] = {
  131479. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  131480. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  131481. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  131482. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  131483. 9, 9, 0, 8, 8, 0, 8, 8, 5, 9, 9, 0, 8, 8, 0, 8,
  131484. 8,
  131485. };
  131486. static float _vq_quantthresh__44c6_s_p1_0[] = {
  131487. -0.5, 0.5,
  131488. };
  131489. static long _vq_quantmap__44c6_s_p1_0[] = {
  131490. 1, 0, 2,
  131491. };
  131492. static encode_aux_threshmatch _vq_auxt__44c6_s_p1_0 = {
  131493. _vq_quantthresh__44c6_s_p1_0,
  131494. _vq_quantmap__44c6_s_p1_0,
  131495. 3,
  131496. 3
  131497. };
  131498. static static_codebook _44c6_s_p1_0 = {
  131499. 4, 81,
  131500. _vq_lengthlist__44c6_s_p1_0,
  131501. 1, -535822336, 1611661312, 2, 0,
  131502. _vq_quantlist__44c6_s_p1_0,
  131503. NULL,
  131504. &_vq_auxt__44c6_s_p1_0,
  131505. NULL,
  131506. 0
  131507. };
  131508. static long _vq_quantlist__44c6_s_p2_0[] = {
  131509. 2,
  131510. 1,
  131511. 3,
  131512. 0,
  131513. 4,
  131514. };
  131515. static long _vq_lengthlist__44c6_s_p2_0[] = {
  131516. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  131517. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  131518. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  131519. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  131520. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,11,
  131521. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  131522. 0, 0,14,13, 8, 9, 9,11,11, 0,11,11,12,12, 0,10,
  131523. 11,12,12, 0,14,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  131524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131525. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  131526. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  131527. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  131528. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  131529. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  131530. 13, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,12,12,
  131531. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  131532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131533. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  131534. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,11,
  131535. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,11,
  131536. 0, 0, 0,10,11, 8,10,10,12,12, 0,10,10,12,12, 0,
  131537. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,14,13, 8,10,
  131538. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  131539. 13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131541. 7,10,10,14,13, 0, 9, 9,13,12, 0, 9, 9,12,12, 0,
  131542. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  131543. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  131544. 12,12, 9,11,11,14,13, 0,11,10,14,13, 0,11,11,13,
  131545. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  131546. 0,10,11,13,14, 0,11,11,13,13, 0,12,12,13,13, 0,
  131547. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  131552. 11,11,14,14, 0,11,11,13,13, 0,11,10,13,13, 0,12,
  131553. 12,13,13, 0, 0, 0,13,13, 9,11,11,14,14, 0,11,11,
  131554. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  131555. 13,
  131556. };
  131557. static float _vq_quantthresh__44c6_s_p2_0[] = {
  131558. -1.5, -0.5, 0.5, 1.5,
  131559. };
  131560. static long _vq_quantmap__44c6_s_p2_0[] = {
  131561. 3, 1, 0, 2, 4,
  131562. };
  131563. static encode_aux_threshmatch _vq_auxt__44c6_s_p2_0 = {
  131564. _vq_quantthresh__44c6_s_p2_0,
  131565. _vq_quantmap__44c6_s_p2_0,
  131566. 5,
  131567. 5
  131568. };
  131569. static static_codebook _44c6_s_p2_0 = {
  131570. 4, 625,
  131571. _vq_lengthlist__44c6_s_p2_0,
  131572. 1, -533725184, 1611661312, 3, 0,
  131573. _vq_quantlist__44c6_s_p2_0,
  131574. NULL,
  131575. &_vq_auxt__44c6_s_p2_0,
  131576. NULL,
  131577. 0
  131578. };
  131579. static long _vq_quantlist__44c6_s_p3_0[] = {
  131580. 4,
  131581. 3,
  131582. 5,
  131583. 2,
  131584. 6,
  131585. 1,
  131586. 7,
  131587. 0,
  131588. 8,
  131589. };
  131590. static long _vq_lengthlist__44c6_s_p3_0[] = {
  131591. 2, 3, 4, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  131592. 9,10, 0, 4, 4, 6, 6, 7, 7,10, 9, 0, 5, 5, 7, 7,
  131593. 8, 8,10,10, 0, 0, 0, 7, 6, 8, 8,10,10, 0, 0, 0,
  131594. 7, 7, 9, 9,11,11, 0, 0, 0, 7, 7, 9, 9,11,11, 0,
  131595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131596. 0,
  131597. };
  131598. static float _vq_quantthresh__44c6_s_p3_0[] = {
  131599. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131600. };
  131601. static long _vq_quantmap__44c6_s_p3_0[] = {
  131602. 7, 5, 3, 1, 0, 2, 4, 6,
  131603. 8,
  131604. };
  131605. static encode_aux_threshmatch _vq_auxt__44c6_s_p3_0 = {
  131606. _vq_quantthresh__44c6_s_p3_0,
  131607. _vq_quantmap__44c6_s_p3_0,
  131608. 9,
  131609. 9
  131610. };
  131611. static static_codebook _44c6_s_p3_0 = {
  131612. 2, 81,
  131613. _vq_lengthlist__44c6_s_p3_0,
  131614. 1, -531628032, 1611661312, 4, 0,
  131615. _vq_quantlist__44c6_s_p3_0,
  131616. NULL,
  131617. &_vq_auxt__44c6_s_p3_0,
  131618. NULL,
  131619. 0
  131620. };
  131621. static long _vq_quantlist__44c6_s_p4_0[] = {
  131622. 8,
  131623. 7,
  131624. 9,
  131625. 6,
  131626. 10,
  131627. 5,
  131628. 11,
  131629. 4,
  131630. 12,
  131631. 3,
  131632. 13,
  131633. 2,
  131634. 14,
  131635. 1,
  131636. 15,
  131637. 0,
  131638. 16,
  131639. };
  131640. static long _vq_lengthlist__44c6_s_p4_0[] = {
  131641. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,10,10,
  131642. 10, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  131643. 11,11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  131644. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  131645. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  131646. 10,11,11,11,11, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  131647. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,
  131648. 10,11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  131649. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  131650. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  131651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131659. 0,
  131660. };
  131661. static float _vq_quantthresh__44c6_s_p4_0[] = {
  131662. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131663. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131664. };
  131665. static long _vq_quantmap__44c6_s_p4_0[] = {
  131666. 15, 13, 11, 9, 7, 5, 3, 1,
  131667. 0, 2, 4, 6, 8, 10, 12, 14,
  131668. 16,
  131669. };
  131670. static encode_aux_threshmatch _vq_auxt__44c6_s_p4_0 = {
  131671. _vq_quantthresh__44c6_s_p4_0,
  131672. _vq_quantmap__44c6_s_p4_0,
  131673. 17,
  131674. 17
  131675. };
  131676. static static_codebook _44c6_s_p4_0 = {
  131677. 2, 289,
  131678. _vq_lengthlist__44c6_s_p4_0,
  131679. 1, -529530880, 1611661312, 5, 0,
  131680. _vq_quantlist__44c6_s_p4_0,
  131681. NULL,
  131682. &_vq_auxt__44c6_s_p4_0,
  131683. NULL,
  131684. 0
  131685. };
  131686. static long _vq_quantlist__44c6_s_p5_0[] = {
  131687. 1,
  131688. 0,
  131689. 2,
  131690. };
  131691. static long _vq_lengthlist__44c6_s_p5_0[] = {
  131692. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6, 9, 9,10,10,
  131693. 10, 9, 4, 6, 6, 9,10, 9,10, 9,10, 6, 9, 9,10,12,
  131694. 11,10,11,11, 7,10, 9,11,12,12,12,12,12, 7,10,10,
  131695. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  131696. 9,10,11,12,12,12,12,12, 7,10, 9,12,12,12,12,12,
  131697. 12,
  131698. };
  131699. static float _vq_quantthresh__44c6_s_p5_0[] = {
  131700. -5.5, 5.5,
  131701. };
  131702. static long _vq_quantmap__44c6_s_p5_0[] = {
  131703. 1, 0, 2,
  131704. };
  131705. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_0 = {
  131706. _vq_quantthresh__44c6_s_p5_0,
  131707. _vq_quantmap__44c6_s_p5_0,
  131708. 3,
  131709. 3
  131710. };
  131711. static static_codebook _44c6_s_p5_0 = {
  131712. 4, 81,
  131713. _vq_lengthlist__44c6_s_p5_0,
  131714. 1, -529137664, 1618345984, 2, 0,
  131715. _vq_quantlist__44c6_s_p5_0,
  131716. NULL,
  131717. &_vq_auxt__44c6_s_p5_0,
  131718. NULL,
  131719. 0
  131720. };
  131721. static long _vq_quantlist__44c6_s_p5_1[] = {
  131722. 5,
  131723. 4,
  131724. 6,
  131725. 3,
  131726. 7,
  131727. 2,
  131728. 8,
  131729. 1,
  131730. 9,
  131731. 0,
  131732. 10,
  131733. };
  131734. static long _vq_lengthlist__44c6_s_p5_1[] = {
  131735. 3, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  131736. 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6, 7, 7, 8, 8, 8,
  131737. 8,11, 6, 6, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  131738. 6, 7, 8, 8, 8, 8, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  131739. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 8,11,11,11,
  131740. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,10,10, 8, 8, 8,
  131741. 8, 8, 8,11,11,11,10,10, 8, 8, 8, 8, 8, 8,11,11,
  131742. 11,10,10, 7, 7, 8, 8, 8, 8,
  131743. };
  131744. static float _vq_quantthresh__44c6_s_p5_1[] = {
  131745. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  131746. 3.5, 4.5,
  131747. };
  131748. static long _vq_quantmap__44c6_s_p5_1[] = {
  131749. 9, 7, 5, 3, 1, 0, 2, 4,
  131750. 6, 8, 10,
  131751. };
  131752. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_1 = {
  131753. _vq_quantthresh__44c6_s_p5_1,
  131754. _vq_quantmap__44c6_s_p5_1,
  131755. 11,
  131756. 11
  131757. };
  131758. static static_codebook _44c6_s_p5_1 = {
  131759. 2, 121,
  131760. _vq_lengthlist__44c6_s_p5_1,
  131761. 1, -531365888, 1611661312, 4, 0,
  131762. _vq_quantlist__44c6_s_p5_1,
  131763. NULL,
  131764. &_vq_auxt__44c6_s_p5_1,
  131765. NULL,
  131766. 0
  131767. };
  131768. static long _vq_quantlist__44c6_s_p6_0[] = {
  131769. 6,
  131770. 5,
  131771. 7,
  131772. 4,
  131773. 8,
  131774. 3,
  131775. 9,
  131776. 2,
  131777. 10,
  131778. 1,
  131779. 11,
  131780. 0,
  131781. 12,
  131782. };
  131783. static long _vq_lengthlist__44c6_s_p6_0[] = {
  131784. 1, 4, 4, 6, 6, 8, 8, 8, 8,10, 9,10,10, 6, 5, 5,
  131785. 7, 7, 9, 9, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 9,
  131786. 9,10, 9,11,10,11,11, 0, 6, 6, 7, 7, 9, 9,10,10,
  131787. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  131788. 12, 0,11,11, 8, 8,10,10,11,11,12,12,12,12, 0,11,
  131789. 12, 9, 8,10,10,11,11,12,12,13,13, 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, 0, 0, 0, 0, 0, 0, 0,
  131792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131794. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131795. };
  131796. static float _vq_quantthresh__44c6_s_p6_0[] = {
  131797. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  131798. 12.5, 17.5, 22.5, 27.5,
  131799. };
  131800. static long _vq_quantmap__44c6_s_p6_0[] = {
  131801. 11, 9, 7, 5, 3, 1, 0, 2,
  131802. 4, 6, 8, 10, 12,
  131803. };
  131804. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_0 = {
  131805. _vq_quantthresh__44c6_s_p6_0,
  131806. _vq_quantmap__44c6_s_p6_0,
  131807. 13,
  131808. 13
  131809. };
  131810. static static_codebook _44c6_s_p6_0 = {
  131811. 2, 169,
  131812. _vq_lengthlist__44c6_s_p6_0,
  131813. 1, -526516224, 1616117760, 4, 0,
  131814. _vq_quantlist__44c6_s_p6_0,
  131815. NULL,
  131816. &_vq_auxt__44c6_s_p6_0,
  131817. NULL,
  131818. 0
  131819. };
  131820. static long _vq_quantlist__44c6_s_p6_1[] = {
  131821. 2,
  131822. 1,
  131823. 3,
  131824. 0,
  131825. 4,
  131826. };
  131827. static long _vq_lengthlist__44c6_s_p6_1[] = {
  131828. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  131829. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  131830. };
  131831. static float _vq_quantthresh__44c6_s_p6_1[] = {
  131832. -1.5, -0.5, 0.5, 1.5,
  131833. };
  131834. static long _vq_quantmap__44c6_s_p6_1[] = {
  131835. 3, 1, 0, 2, 4,
  131836. };
  131837. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_1 = {
  131838. _vq_quantthresh__44c6_s_p6_1,
  131839. _vq_quantmap__44c6_s_p6_1,
  131840. 5,
  131841. 5
  131842. };
  131843. static static_codebook _44c6_s_p6_1 = {
  131844. 2, 25,
  131845. _vq_lengthlist__44c6_s_p6_1,
  131846. 1, -533725184, 1611661312, 3, 0,
  131847. _vq_quantlist__44c6_s_p6_1,
  131848. NULL,
  131849. &_vq_auxt__44c6_s_p6_1,
  131850. NULL,
  131851. 0
  131852. };
  131853. static long _vq_quantlist__44c6_s_p7_0[] = {
  131854. 6,
  131855. 5,
  131856. 7,
  131857. 4,
  131858. 8,
  131859. 3,
  131860. 9,
  131861. 2,
  131862. 10,
  131863. 1,
  131864. 11,
  131865. 0,
  131866. 12,
  131867. };
  131868. static long _vq_lengthlist__44c6_s_p7_0[] = {
  131869. 1, 4, 4, 6, 6, 8, 8, 8, 8,10,10,11,10, 6, 5, 5,
  131870. 7, 7, 8, 8, 9, 9,10,10,12,11, 6, 5, 5, 7, 7, 8,
  131871. 8, 9, 9,10,10,12,11,21, 7, 7, 7, 7, 9, 9,10,10,
  131872. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  131873. 12,21,12,12, 9, 9,10,10,11,11,11,11,12,12,21,12,
  131874. 12, 9, 9,10,10,11,11,12,12,12,12,21,21,21,11,11,
  131875. 10,10,11,12,12,12,13,13,21,21,21,11,11,10,10,12,
  131876. 12,12,12,13,13,21,21,21,15,15,11,11,12,12,13,13,
  131877. 13,13,21,21,21,15,16,11,11,12,12,13,13,14,14,21,
  131878. 21,21,21,20,13,13,13,13,13,13,14,14,20,20,20,20,
  131879. 20,13,13,13,13,13,13,14,14,
  131880. };
  131881. static float _vq_quantthresh__44c6_s_p7_0[] = {
  131882. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  131883. 27.5, 38.5, 49.5, 60.5,
  131884. };
  131885. static long _vq_quantmap__44c6_s_p7_0[] = {
  131886. 11, 9, 7, 5, 3, 1, 0, 2,
  131887. 4, 6, 8, 10, 12,
  131888. };
  131889. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_0 = {
  131890. _vq_quantthresh__44c6_s_p7_0,
  131891. _vq_quantmap__44c6_s_p7_0,
  131892. 13,
  131893. 13
  131894. };
  131895. static static_codebook _44c6_s_p7_0 = {
  131896. 2, 169,
  131897. _vq_lengthlist__44c6_s_p7_0,
  131898. 1, -523206656, 1618345984, 4, 0,
  131899. _vq_quantlist__44c6_s_p7_0,
  131900. NULL,
  131901. &_vq_auxt__44c6_s_p7_0,
  131902. NULL,
  131903. 0
  131904. };
  131905. static long _vq_quantlist__44c6_s_p7_1[] = {
  131906. 5,
  131907. 4,
  131908. 6,
  131909. 3,
  131910. 7,
  131911. 2,
  131912. 8,
  131913. 1,
  131914. 9,
  131915. 0,
  131916. 10,
  131917. };
  131918. static long _vq_lengthlist__44c6_s_p7_1[] = {
  131919. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 9, 5, 5, 6, 6,
  131920. 7, 7, 7, 7, 8, 7, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7,
  131921. 7, 9, 6, 6, 7, 7, 7, 7, 8, 7, 7, 8, 9, 9, 9, 7,
  131922. 7, 7, 7, 7, 7, 7, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  131923. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  131924. 8, 8, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 8, 8, 8, 7,
  131925. 7, 8, 8, 9, 9, 9, 8, 8, 8, 8, 7, 7, 8, 8, 9, 9,
  131926. 9, 8, 8, 7, 7, 7, 7, 8, 8,
  131927. };
  131928. static float _vq_quantthresh__44c6_s_p7_1[] = {
  131929. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  131930. 3.5, 4.5,
  131931. };
  131932. static long _vq_quantmap__44c6_s_p7_1[] = {
  131933. 9, 7, 5, 3, 1, 0, 2, 4,
  131934. 6, 8, 10,
  131935. };
  131936. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_1 = {
  131937. _vq_quantthresh__44c6_s_p7_1,
  131938. _vq_quantmap__44c6_s_p7_1,
  131939. 11,
  131940. 11
  131941. };
  131942. static static_codebook _44c6_s_p7_1 = {
  131943. 2, 121,
  131944. _vq_lengthlist__44c6_s_p7_1,
  131945. 1, -531365888, 1611661312, 4, 0,
  131946. _vq_quantlist__44c6_s_p7_1,
  131947. NULL,
  131948. &_vq_auxt__44c6_s_p7_1,
  131949. NULL,
  131950. 0
  131951. };
  131952. static long _vq_quantlist__44c6_s_p8_0[] = {
  131953. 7,
  131954. 6,
  131955. 8,
  131956. 5,
  131957. 9,
  131958. 4,
  131959. 10,
  131960. 3,
  131961. 11,
  131962. 2,
  131963. 12,
  131964. 1,
  131965. 13,
  131966. 0,
  131967. 14,
  131968. };
  131969. static long _vq_lengthlist__44c6_s_p8_0[] = {
  131970. 1, 4, 4, 7, 7, 8, 8, 7, 7, 8, 7, 9, 8,10, 9, 6,
  131971. 5, 5, 8, 8, 9, 9, 8, 8, 9, 9,11,10,11,10, 6, 5,
  131972. 5, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,11,18, 8, 8,
  131973. 9, 8,10,10, 9, 9,10,10,10,10,11,10,18, 8, 8, 9,
  131974. 9,10,10, 9, 9,10,10,11,11,12,12,18,12,13, 9,10,
  131975. 10,10, 9,10,10,10,11,11,12,11,18,13,13, 9, 9,10,
  131976. 10,10,10,10,10,11,11,12,12,18,18,18,10,10, 9, 9,
  131977. 11,11,11,11,11,12,12,12,18,18,18,10, 9,10, 9,11,
  131978. 10,11,11,11,11,13,12,18,18,18,14,13,10,10,11,11,
  131979. 12,12,12,12,12,12,18,18,18,14,13,10,10,11,10,12,
  131980. 12,12,12,12,12,18,18,18,18,18,12,12,11,11,12,12,
  131981. 13,13,13,14,18,18,18,18,18,12,12,11,11,12,11,13,
  131982. 13,14,13,18,18,18,18,18,16,16,11,12,12,13,13,13,
  131983. 14,13,18,18,18,18,18,16,15,12,11,12,11,13,11,15,
  131984. 14,
  131985. };
  131986. static float _vq_quantthresh__44c6_s_p8_0[] = {
  131987. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  131988. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  131989. };
  131990. static long _vq_quantmap__44c6_s_p8_0[] = {
  131991. 13, 11, 9, 7, 5, 3, 1, 0,
  131992. 2, 4, 6, 8, 10, 12, 14,
  131993. };
  131994. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_0 = {
  131995. _vq_quantthresh__44c6_s_p8_0,
  131996. _vq_quantmap__44c6_s_p8_0,
  131997. 15,
  131998. 15
  131999. };
  132000. static static_codebook _44c6_s_p8_0 = {
  132001. 2, 225,
  132002. _vq_lengthlist__44c6_s_p8_0,
  132003. 1, -520986624, 1620377600, 4, 0,
  132004. _vq_quantlist__44c6_s_p8_0,
  132005. NULL,
  132006. &_vq_auxt__44c6_s_p8_0,
  132007. NULL,
  132008. 0
  132009. };
  132010. static long _vq_quantlist__44c6_s_p8_1[] = {
  132011. 10,
  132012. 9,
  132013. 11,
  132014. 8,
  132015. 12,
  132016. 7,
  132017. 13,
  132018. 6,
  132019. 14,
  132020. 5,
  132021. 15,
  132022. 4,
  132023. 16,
  132024. 3,
  132025. 17,
  132026. 2,
  132027. 18,
  132028. 1,
  132029. 19,
  132030. 0,
  132031. 20,
  132032. };
  132033. static long _vq_lengthlist__44c6_s_p8_1[] = {
  132034. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  132035. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,
  132036. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  132037. 8, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10,
  132038. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132039. 9, 9, 9, 9,10,11,11, 8, 7, 8, 8, 8, 9, 9, 9, 9,
  132040. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8,
  132041. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,
  132042. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132043. 9, 9, 9,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132044. 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9, 9,
  132045. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,
  132046. 11,11, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9,10, 9, 9,
  132047. 10, 9,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,10,10,
  132048. 10,10, 9,10,10, 9,10,11,11,11,11,11, 9, 9, 9, 9,
  132049. 10,10,10, 9,10,10,10,10, 9,10,10, 9,11,11,11,11,
  132050. 11,11,11, 9, 9, 9, 9,10,10,10,10, 9,10,10,10,10,
  132051. 10,11,11,11,11,11,11,11,10, 9,10,10,10,10,10,10,
  132052. 10, 9,10, 9,10,10,11,11,11,11,11,11,11,10, 9,10,
  132053. 9,10,10, 9,10,10,10,10,10,10,10,11,11,11,11,11,
  132054. 11,11,10,10,10,10,10,10,10, 9,10,10,10,10,10, 9,
  132055. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  132056. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  132057. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  132058. 11,11,11,10,10,10,10,10,10,10,10,10, 9,10,10,11,
  132059. 11,11,11,11,11,11,11,11,10,10,10, 9,10,10,10,10,
  132060. 10,10,10,10,10,11,11,11,11,11,11,11,11,10,11, 9,
  132061. 10,10,10,10,10,10,10,10,10,
  132062. };
  132063. static float _vq_quantthresh__44c6_s_p8_1[] = {
  132064. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  132065. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  132066. 6.5, 7.5, 8.5, 9.5,
  132067. };
  132068. static long _vq_quantmap__44c6_s_p8_1[] = {
  132069. 19, 17, 15, 13, 11, 9, 7, 5,
  132070. 3, 1, 0, 2, 4, 6, 8, 10,
  132071. 12, 14, 16, 18, 20,
  132072. };
  132073. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_1 = {
  132074. _vq_quantthresh__44c6_s_p8_1,
  132075. _vq_quantmap__44c6_s_p8_1,
  132076. 21,
  132077. 21
  132078. };
  132079. static static_codebook _44c6_s_p8_1 = {
  132080. 2, 441,
  132081. _vq_lengthlist__44c6_s_p8_1,
  132082. 1, -529268736, 1611661312, 5, 0,
  132083. _vq_quantlist__44c6_s_p8_1,
  132084. NULL,
  132085. &_vq_auxt__44c6_s_p8_1,
  132086. NULL,
  132087. 0
  132088. };
  132089. static long _vq_quantlist__44c6_s_p9_0[] = {
  132090. 6,
  132091. 5,
  132092. 7,
  132093. 4,
  132094. 8,
  132095. 3,
  132096. 9,
  132097. 2,
  132098. 10,
  132099. 1,
  132100. 11,
  132101. 0,
  132102. 12,
  132103. };
  132104. static long _vq_lengthlist__44c6_s_p9_0[] = {
  132105. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 7, 7,
  132106. 11,11,11,11,11,11,11,11,11,11, 5, 8, 9,11,11,11,
  132107. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132108. 11,11,11,11,11,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,10,10,10,10,10,10,10,
  132113. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132114. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132115. 10,10,10,10,10,10,10,10,10,
  132116. };
  132117. static float _vq_quantthresh__44c6_s_p9_0[] = {
  132118. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  132119. 1592.5, 2229.5, 2866.5, 3503.5,
  132120. };
  132121. static long _vq_quantmap__44c6_s_p9_0[] = {
  132122. 11, 9, 7, 5, 3, 1, 0, 2,
  132123. 4, 6, 8, 10, 12,
  132124. };
  132125. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_0 = {
  132126. _vq_quantthresh__44c6_s_p9_0,
  132127. _vq_quantmap__44c6_s_p9_0,
  132128. 13,
  132129. 13
  132130. };
  132131. static static_codebook _44c6_s_p9_0 = {
  132132. 2, 169,
  132133. _vq_lengthlist__44c6_s_p9_0,
  132134. 1, -511845376, 1630791680, 4, 0,
  132135. _vq_quantlist__44c6_s_p9_0,
  132136. NULL,
  132137. &_vq_auxt__44c6_s_p9_0,
  132138. NULL,
  132139. 0
  132140. };
  132141. static long _vq_quantlist__44c6_s_p9_1[] = {
  132142. 6,
  132143. 5,
  132144. 7,
  132145. 4,
  132146. 8,
  132147. 3,
  132148. 9,
  132149. 2,
  132150. 10,
  132151. 1,
  132152. 11,
  132153. 0,
  132154. 12,
  132155. };
  132156. static long _vq_lengthlist__44c6_s_p9_1[] = {
  132157. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  132158. 8, 8, 8, 8, 8, 7, 9, 8,10,10, 5, 6, 6, 8, 8, 9,
  132159. 9, 8, 8,10,10,10,10,16, 9, 9, 9, 9, 9, 9, 9, 8,
  132160. 10, 9,11,11,16, 8, 9, 9, 9, 9, 9, 9, 9,10,10,11,
  132161. 11,16,13,13, 9, 9,10, 9, 9,10,11,11,11,12,16,13,
  132162. 14, 9, 8,10, 8, 9, 9,10,10,12,11,16,14,16, 9, 9,
  132163. 9, 9,11,11,12,11,12,11,16,16,16, 9, 7, 9, 6,11,
  132164. 11,11,10,11,11,16,16,16,11,12, 9,10,11,11,12,11,
  132165. 13,13,16,16,16,12,11,10, 7,12,10,12,12,12,12,16,
  132166. 16,15,16,16,10,11,10,11,13,13,14,12,16,16,16,15,
  132167. 15,12,10,11,11,13,11,12,13,
  132168. };
  132169. static float _vq_quantthresh__44c6_s_p9_1[] = {
  132170. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  132171. 122.5, 171.5, 220.5, 269.5,
  132172. };
  132173. static long _vq_quantmap__44c6_s_p9_1[] = {
  132174. 11, 9, 7, 5, 3, 1, 0, 2,
  132175. 4, 6, 8, 10, 12,
  132176. };
  132177. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_1 = {
  132178. _vq_quantthresh__44c6_s_p9_1,
  132179. _vq_quantmap__44c6_s_p9_1,
  132180. 13,
  132181. 13
  132182. };
  132183. static static_codebook _44c6_s_p9_1 = {
  132184. 2, 169,
  132185. _vq_lengthlist__44c6_s_p9_1,
  132186. 1, -518889472, 1622704128, 4, 0,
  132187. _vq_quantlist__44c6_s_p9_1,
  132188. NULL,
  132189. &_vq_auxt__44c6_s_p9_1,
  132190. NULL,
  132191. 0
  132192. };
  132193. static long _vq_quantlist__44c6_s_p9_2[] = {
  132194. 24,
  132195. 23,
  132196. 25,
  132197. 22,
  132198. 26,
  132199. 21,
  132200. 27,
  132201. 20,
  132202. 28,
  132203. 19,
  132204. 29,
  132205. 18,
  132206. 30,
  132207. 17,
  132208. 31,
  132209. 16,
  132210. 32,
  132211. 15,
  132212. 33,
  132213. 14,
  132214. 34,
  132215. 13,
  132216. 35,
  132217. 12,
  132218. 36,
  132219. 11,
  132220. 37,
  132221. 10,
  132222. 38,
  132223. 9,
  132224. 39,
  132225. 8,
  132226. 40,
  132227. 7,
  132228. 41,
  132229. 6,
  132230. 42,
  132231. 5,
  132232. 43,
  132233. 4,
  132234. 44,
  132235. 3,
  132236. 45,
  132237. 2,
  132238. 46,
  132239. 1,
  132240. 47,
  132241. 0,
  132242. 48,
  132243. };
  132244. static long _vq_lengthlist__44c6_s_p9_2[] = {
  132245. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  132246. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  132247. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  132248. 7,
  132249. };
  132250. static float _vq_quantthresh__44c6_s_p9_2[] = {
  132251. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  132252. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  132253. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132254. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132255. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  132256. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  132257. };
  132258. static long _vq_quantmap__44c6_s_p9_2[] = {
  132259. 47, 45, 43, 41, 39, 37, 35, 33,
  132260. 31, 29, 27, 25, 23, 21, 19, 17,
  132261. 15, 13, 11, 9, 7, 5, 3, 1,
  132262. 0, 2, 4, 6, 8, 10, 12, 14,
  132263. 16, 18, 20, 22, 24, 26, 28, 30,
  132264. 32, 34, 36, 38, 40, 42, 44, 46,
  132265. 48,
  132266. };
  132267. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_2 = {
  132268. _vq_quantthresh__44c6_s_p9_2,
  132269. _vq_quantmap__44c6_s_p9_2,
  132270. 49,
  132271. 49
  132272. };
  132273. static static_codebook _44c6_s_p9_2 = {
  132274. 1, 49,
  132275. _vq_lengthlist__44c6_s_p9_2,
  132276. 1, -526909440, 1611661312, 6, 0,
  132277. _vq_quantlist__44c6_s_p9_2,
  132278. NULL,
  132279. &_vq_auxt__44c6_s_p9_2,
  132280. NULL,
  132281. 0
  132282. };
  132283. static long _huff_lengthlist__44c6_s_short[] = {
  132284. 3, 9,11,11,13,14,19,17,17,19, 5, 4, 5, 8,10,10,
  132285. 13,16,18,19, 7, 4, 4, 5, 8, 9,12,14,17,19, 8, 6,
  132286. 5, 5, 7, 7,10,13,16,18,10, 8, 7, 6, 5, 5, 8,11,
  132287. 17,19,11, 9, 7, 7, 5, 4, 5, 8,17,19,13,11, 8, 7,
  132288. 7, 5, 5, 7,16,18,14,13, 8, 6, 6, 5, 5, 7,16,18,
  132289. 18,16,10, 8, 8, 7, 7, 9,16,18,18,18,12,10,10, 9,
  132290. 9,10,17,18,
  132291. };
  132292. static static_codebook _huff_book__44c6_s_short = {
  132293. 2, 100,
  132294. _huff_lengthlist__44c6_s_short,
  132295. 0, 0, 0, 0, 0,
  132296. NULL,
  132297. NULL,
  132298. NULL,
  132299. NULL,
  132300. 0
  132301. };
  132302. static long _huff_lengthlist__44c7_s_long[] = {
  132303. 3, 8,11,13,15,14,14,13,15,14, 6, 4, 5, 7, 9,10,
  132304. 11,11,14,13,10, 4, 3, 5, 7, 8, 9,10,13,13,12, 7,
  132305. 4, 4, 5, 6, 8, 9,12,14,13, 9, 6, 5, 5, 6, 8, 9,
  132306. 12,14,12, 9, 7, 6, 5, 5, 6, 8,11,11,12,11, 9, 8,
  132307. 7, 6, 6, 7,10,11,13,11,10, 9, 8, 7, 6, 6, 9,11,
  132308. 13,13,12,12,12,10, 9, 8, 9,11,12,14,15,15,14,12,
  132309. 11,10,10,12,
  132310. };
  132311. static static_codebook _huff_book__44c7_s_long = {
  132312. 2, 100,
  132313. _huff_lengthlist__44c7_s_long,
  132314. 0, 0, 0, 0, 0,
  132315. NULL,
  132316. NULL,
  132317. NULL,
  132318. NULL,
  132319. 0
  132320. };
  132321. static long _vq_quantlist__44c7_s_p1_0[] = {
  132322. 1,
  132323. 0,
  132324. 2,
  132325. };
  132326. static long _vq_lengthlist__44c7_s_p1_0[] = {
  132327. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  132328. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  132329. 0, 0, 0, 0, 5, 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  132330. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  132331. 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  132332. 8,
  132333. };
  132334. static float _vq_quantthresh__44c7_s_p1_0[] = {
  132335. -0.5, 0.5,
  132336. };
  132337. static long _vq_quantmap__44c7_s_p1_0[] = {
  132338. 1, 0, 2,
  132339. };
  132340. static encode_aux_threshmatch _vq_auxt__44c7_s_p1_0 = {
  132341. _vq_quantthresh__44c7_s_p1_0,
  132342. _vq_quantmap__44c7_s_p1_0,
  132343. 3,
  132344. 3
  132345. };
  132346. static static_codebook _44c7_s_p1_0 = {
  132347. 4, 81,
  132348. _vq_lengthlist__44c7_s_p1_0,
  132349. 1, -535822336, 1611661312, 2, 0,
  132350. _vq_quantlist__44c7_s_p1_0,
  132351. NULL,
  132352. &_vq_auxt__44c7_s_p1_0,
  132353. NULL,
  132354. 0
  132355. };
  132356. static long _vq_quantlist__44c7_s_p2_0[] = {
  132357. 2,
  132358. 1,
  132359. 3,
  132360. 0,
  132361. 4,
  132362. };
  132363. static long _vq_lengthlist__44c7_s_p2_0[] = {
  132364. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  132365. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  132366. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  132367. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  132368. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  132369. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  132370. 0, 0,14,13, 8, 9, 9,10,11, 0,11,11,12,12, 0,10,
  132371. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  132372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132373. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  132374. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  132375. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  132376. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  132377. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  132378. 13, 8, 9,10,12,12, 0,10,10,12,12, 0,10,10,11,12,
  132379. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  132380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132381. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  132382. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,10,
  132383. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,10,
  132384. 0, 0, 0,10,11, 9,10,10,12,12, 0,10,10,12,12, 0,
  132385. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,13,12, 9,10,
  132386. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  132387. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132389. 7,10,10,14,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  132390. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  132391. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  132392. 12,12, 9,11,11,14,13, 0,11,10,13,12, 0,11,11,13,
  132393. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  132394. 0,10,11,12,13, 0,11,11,13,13, 0,12,12,13,13, 0,
  132395. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  132400. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,12,
  132401. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  132402. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  132403. 13,
  132404. };
  132405. static float _vq_quantthresh__44c7_s_p2_0[] = {
  132406. -1.5, -0.5, 0.5, 1.5,
  132407. };
  132408. static long _vq_quantmap__44c7_s_p2_0[] = {
  132409. 3, 1, 0, 2, 4,
  132410. };
  132411. static encode_aux_threshmatch _vq_auxt__44c7_s_p2_0 = {
  132412. _vq_quantthresh__44c7_s_p2_0,
  132413. _vq_quantmap__44c7_s_p2_0,
  132414. 5,
  132415. 5
  132416. };
  132417. static static_codebook _44c7_s_p2_0 = {
  132418. 4, 625,
  132419. _vq_lengthlist__44c7_s_p2_0,
  132420. 1, -533725184, 1611661312, 3, 0,
  132421. _vq_quantlist__44c7_s_p2_0,
  132422. NULL,
  132423. &_vq_auxt__44c7_s_p2_0,
  132424. NULL,
  132425. 0
  132426. };
  132427. static long _vq_quantlist__44c7_s_p3_0[] = {
  132428. 4,
  132429. 3,
  132430. 5,
  132431. 2,
  132432. 6,
  132433. 1,
  132434. 7,
  132435. 0,
  132436. 8,
  132437. };
  132438. static long _vq_lengthlist__44c7_s_p3_0[] = {
  132439. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  132440. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  132441. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  132442. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  132443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132444. 0,
  132445. };
  132446. static float _vq_quantthresh__44c7_s_p3_0[] = {
  132447. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132448. };
  132449. static long _vq_quantmap__44c7_s_p3_0[] = {
  132450. 7, 5, 3, 1, 0, 2, 4, 6,
  132451. 8,
  132452. };
  132453. static encode_aux_threshmatch _vq_auxt__44c7_s_p3_0 = {
  132454. _vq_quantthresh__44c7_s_p3_0,
  132455. _vq_quantmap__44c7_s_p3_0,
  132456. 9,
  132457. 9
  132458. };
  132459. static static_codebook _44c7_s_p3_0 = {
  132460. 2, 81,
  132461. _vq_lengthlist__44c7_s_p3_0,
  132462. 1, -531628032, 1611661312, 4, 0,
  132463. _vq_quantlist__44c7_s_p3_0,
  132464. NULL,
  132465. &_vq_auxt__44c7_s_p3_0,
  132466. NULL,
  132467. 0
  132468. };
  132469. static long _vq_quantlist__44c7_s_p4_0[] = {
  132470. 8,
  132471. 7,
  132472. 9,
  132473. 6,
  132474. 10,
  132475. 5,
  132476. 11,
  132477. 4,
  132478. 12,
  132479. 3,
  132480. 13,
  132481. 2,
  132482. 14,
  132483. 1,
  132484. 15,
  132485. 0,
  132486. 16,
  132487. };
  132488. static long _vq_lengthlist__44c7_s_p4_0[] = {
  132489. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  132490. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  132491. 12,12, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  132492. 11,12,12, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,
  132493. 11,12,12,12, 0, 0, 0, 6, 6, 8, 7, 9, 9, 9, 9,10,
  132494. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  132495. 11,11,12,12,13,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  132496. 10,11,11,12,12,12,13, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  132497. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  132498. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  132499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132507. 0,
  132508. };
  132509. static float _vq_quantthresh__44c7_s_p4_0[] = {
  132510. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132511. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132512. };
  132513. static long _vq_quantmap__44c7_s_p4_0[] = {
  132514. 15, 13, 11, 9, 7, 5, 3, 1,
  132515. 0, 2, 4, 6, 8, 10, 12, 14,
  132516. 16,
  132517. };
  132518. static encode_aux_threshmatch _vq_auxt__44c7_s_p4_0 = {
  132519. _vq_quantthresh__44c7_s_p4_0,
  132520. _vq_quantmap__44c7_s_p4_0,
  132521. 17,
  132522. 17
  132523. };
  132524. static static_codebook _44c7_s_p4_0 = {
  132525. 2, 289,
  132526. _vq_lengthlist__44c7_s_p4_0,
  132527. 1, -529530880, 1611661312, 5, 0,
  132528. _vq_quantlist__44c7_s_p4_0,
  132529. NULL,
  132530. &_vq_auxt__44c7_s_p4_0,
  132531. NULL,
  132532. 0
  132533. };
  132534. static long _vq_quantlist__44c7_s_p5_0[] = {
  132535. 1,
  132536. 0,
  132537. 2,
  132538. };
  132539. static long _vq_lengthlist__44c7_s_p5_0[] = {
  132540. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 7,10,10,10,10,
  132541. 10, 9, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  132542. 12,10,11,12, 7,10,10,11,12,12,12,12,12, 7,10,10,
  132543. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  132544. 10,10,12,12,12,12,11,12, 7,10,10,11,12,12,12,12,
  132545. 12,
  132546. };
  132547. static float _vq_quantthresh__44c7_s_p5_0[] = {
  132548. -5.5, 5.5,
  132549. };
  132550. static long _vq_quantmap__44c7_s_p5_0[] = {
  132551. 1, 0, 2,
  132552. };
  132553. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_0 = {
  132554. _vq_quantthresh__44c7_s_p5_0,
  132555. _vq_quantmap__44c7_s_p5_0,
  132556. 3,
  132557. 3
  132558. };
  132559. static static_codebook _44c7_s_p5_0 = {
  132560. 4, 81,
  132561. _vq_lengthlist__44c7_s_p5_0,
  132562. 1, -529137664, 1618345984, 2, 0,
  132563. _vq_quantlist__44c7_s_p5_0,
  132564. NULL,
  132565. &_vq_auxt__44c7_s_p5_0,
  132566. NULL,
  132567. 0
  132568. };
  132569. static long _vq_quantlist__44c7_s_p5_1[] = {
  132570. 5,
  132571. 4,
  132572. 6,
  132573. 3,
  132574. 7,
  132575. 2,
  132576. 8,
  132577. 1,
  132578. 9,
  132579. 0,
  132580. 10,
  132581. };
  132582. static long _vq_lengthlist__44c7_s_p5_1[] = {
  132583. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  132584. 7, 7, 8, 8, 9, 9,11, 4, 4, 6, 6, 7, 7, 8, 8, 9,
  132585. 9,12, 5, 5, 6, 6, 7, 7, 9, 9, 9, 9,12,12,12, 6,
  132586. 6, 7, 7, 9, 9, 9, 9,11,11,11, 7, 7, 7, 7, 8, 8,
  132587. 9, 9,11,11,11, 7, 7, 7, 7, 8, 8, 9, 9,11,11,11,
  132588. 7, 7, 8, 8, 8, 8, 9, 9,11,11,11,11,11, 8, 8, 8,
  132589. 8, 8, 9,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  132590. 11,11,11, 7, 7, 8, 8, 8, 8,
  132591. };
  132592. static float _vq_quantthresh__44c7_s_p5_1[] = {
  132593. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132594. 3.5, 4.5,
  132595. };
  132596. static long _vq_quantmap__44c7_s_p5_1[] = {
  132597. 9, 7, 5, 3, 1, 0, 2, 4,
  132598. 6, 8, 10,
  132599. };
  132600. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_1 = {
  132601. _vq_quantthresh__44c7_s_p5_1,
  132602. _vq_quantmap__44c7_s_p5_1,
  132603. 11,
  132604. 11
  132605. };
  132606. static static_codebook _44c7_s_p5_1 = {
  132607. 2, 121,
  132608. _vq_lengthlist__44c7_s_p5_1,
  132609. 1, -531365888, 1611661312, 4, 0,
  132610. _vq_quantlist__44c7_s_p5_1,
  132611. NULL,
  132612. &_vq_auxt__44c7_s_p5_1,
  132613. NULL,
  132614. 0
  132615. };
  132616. static long _vq_quantlist__44c7_s_p6_0[] = {
  132617. 6,
  132618. 5,
  132619. 7,
  132620. 4,
  132621. 8,
  132622. 3,
  132623. 9,
  132624. 2,
  132625. 10,
  132626. 1,
  132627. 11,
  132628. 0,
  132629. 12,
  132630. };
  132631. static long _vq_lengthlist__44c7_s_p6_0[] = {
  132632. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 8,10,10, 6, 5, 5,
  132633. 7, 7, 8, 8, 9, 9, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  132634. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 8, 9, 9,
  132635. 10,10,11,11, 0, 8, 8, 7, 7, 8, 9, 9, 9,10,10,11,
  132636. 11, 0,11,11, 9, 9,10,10,11,10,11,11,12,12, 0,12,
  132637. 12, 9, 9,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0,
  132638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132642. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132643. };
  132644. static float _vq_quantthresh__44c7_s_p6_0[] = {
  132645. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132646. 12.5, 17.5, 22.5, 27.5,
  132647. };
  132648. static long _vq_quantmap__44c7_s_p6_0[] = {
  132649. 11, 9, 7, 5, 3, 1, 0, 2,
  132650. 4, 6, 8, 10, 12,
  132651. };
  132652. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_0 = {
  132653. _vq_quantthresh__44c7_s_p6_0,
  132654. _vq_quantmap__44c7_s_p6_0,
  132655. 13,
  132656. 13
  132657. };
  132658. static static_codebook _44c7_s_p6_0 = {
  132659. 2, 169,
  132660. _vq_lengthlist__44c7_s_p6_0,
  132661. 1, -526516224, 1616117760, 4, 0,
  132662. _vq_quantlist__44c7_s_p6_0,
  132663. NULL,
  132664. &_vq_auxt__44c7_s_p6_0,
  132665. NULL,
  132666. 0
  132667. };
  132668. static long _vq_quantlist__44c7_s_p6_1[] = {
  132669. 2,
  132670. 1,
  132671. 3,
  132672. 0,
  132673. 4,
  132674. };
  132675. static long _vq_lengthlist__44c7_s_p6_1[] = {
  132676. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  132677. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  132678. };
  132679. static float _vq_quantthresh__44c7_s_p6_1[] = {
  132680. -1.5, -0.5, 0.5, 1.5,
  132681. };
  132682. static long _vq_quantmap__44c7_s_p6_1[] = {
  132683. 3, 1, 0, 2, 4,
  132684. };
  132685. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_1 = {
  132686. _vq_quantthresh__44c7_s_p6_1,
  132687. _vq_quantmap__44c7_s_p6_1,
  132688. 5,
  132689. 5
  132690. };
  132691. static static_codebook _44c7_s_p6_1 = {
  132692. 2, 25,
  132693. _vq_lengthlist__44c7_s_p6_1,
  132694. 1, -533725184, 1611661312, 3, 0,
  132695. _vq_quantlist__44c7_s_p6_1,
  132696. NULL,
  132697. &_vq_auxt__44c7_s_p6_1,
  132698. NULL,
  132699. 0
  132700. };
  132701. static long _vq_quantlist__44c7_s_p7_0[] = {
  132702. 6,
  132703. 5,
  132704. 7,
  132705. 4,
  132706. 8,
  132707. 3,
  132708. 9,
  132709. 2,
  132710. 10,
  132711. 1,
  132712. 11,
  132713. 0,
  132714. 12,
  132715. };
  132716. static long _vq_lengthlist__44c7_s_p7_0[] = {
  132717. 1, 4, 4, 6, 6, 7, 8, 9, 9,10,10,12,11, 6, 5, 5,
  132718. 7, 7, 8, 8, 9,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  132719. 8,10,10,11,11,12,12,20, 7, 7, 7, 7, 8, 9,10,10,
  132720. 11,11,12,13,20, 7, 7, 7, 7, 9, 9,10,10,11,12,13,
  132721. 13,20,11,11, 8, 8, 9, 9,11,11,12,12,13,13,20,11,
  132722. 11, 8, 8, 9, 9,11,11,12,12,13,13,20,20,20,10,10,
  132723. 10,10,12,12,13,13,13,13,20,20,20,10,10,10,10,12,
  132724. 12,13,13,13,14,20,20,20,14,14,11,11,12,12,13,13,
  132725. 14,14,20,20,20,14,14,11,11,12,12,13,13,14,14,20,
  132726. 20,20,20,19,13,13,13,13,14,14,15,14,19,19,19,19,
  132727. 19,13,13,13,13,14,14,15,15,
  132728. };
  132729. static float _vq_quantthresh__44c7_s_p7_0[] = {
  132730. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  132731. 27.5, 38.5, 49.5, 60.5,
  132732. };
  132733. static long _vq_quantmap__44c7_s_p7_0[] = {
  132734. 11, 9, 7, 5, 3, 1, 0, 2,
  132735. 4, 6, 8, 10, 12,
  132736. };
  132737. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_0 = {
  132738. _vq_quantthresh__44c7_s_p7_0,
  132739. _vq_quantmap__44c7_s_p7_0,
  132740. 13,
  132741. 13
  132742. };
  132743. static static_codebook _44c7_s_p7_0 = {
  132744. 2, 169,
  132745. _vq_lengthlist__44c7_s_p7_0,
  132746. 1, -523206656, 1618345984, 4, 0,
  132747. _vq_quantlist__44c7_s_p7_0,
  132748. NULL,
  132749. &_vq_auxt__44c7_s_p7_0,
  132750. NULL,
  132751. 0
  132752. };
  132753. static long _vq_quantlist__44c7_s_p7_1[] = {
  132754. 5,
  132755. 4,
  132756. 6,
  132757. 3,
  132758. 7,
  132759. 2,
  132760. 8,
  132761. 1,
  132762. 9,
  132763. 0,
  132764. 10,
  132765. };
  132766. static long _vq_lengthlist__44c7_s_p7_1[] = {
  132767. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 7, 7,
  132768. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  132769. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  132770. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  132771. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  132772. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  132773. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  132774. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  132775. };
  132776. static float _vq_quantthresh__44c7_s_p7_1[] = {
  132777. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132778. 3.5, 4.5,
  132779. };
  132780. static long _vq_quantmap__44c7_s_p7_1[] = {
  132781. 9, 7, 5, 3, 1, 0, 2, 4,
  132782. 6, 8, 10,
  132783. };
  132784. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_1 = {
  132785. _vq_quantthresh__44c7_s_p7_1,
  132786. _vq_quantmap__44c7_s_p7_1,
  132787. 11,
  132788. 11
  132789. };
  132790. static static_codebook _44c7_s_p7_1 = {
  132791. 2, 121,
  132792. _vq_lengthlist__44c7_s_p7_1,
  132793. 1, -531365888, 1611661312, 4, 0,
  132794. _vq_quantlist__44c7_s_p7_1,
  132795. NULL,
  132796. &_vq_auxt__44c7_s_p7_1,
  132797. NULL,
  132798. 0
  132799. };
  132800. static long _vq_quantlist__44c7_s_p8_0[] = {
  132801. 7,
  132802. 6,
  132803. 8,
  132804. 5,
  132805. 9,
  132806. 4,
  132807. 10,
  132808. 3,
  132809. 11,
  132810. 2,
  132811. 12,
  132812. 1,
  132813. 13,
  132814. 0,
  132815. 14,
  132816. };
  132817. static long _vq_lengthlist__44c7_s_p8_0[] = {
  132818. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8, 9, 9,10,10, 6,
  132819. 5, 5, 7, 7, 9, 9, 8, 8,10, 9,11,10,12,11, 6, 5,
  132820. 5, 8, 7, 9, 9, 8, 8,10,10,11,11,12,11,19, 8, 8,
  132821. 8, 8,10,10, 9, 9,10,10,11,11,12,11,19, 8, 8, 8,
  132822. 8,10,10, 9, 9,10,10,11,11,12,12,19,12,12, 9, 9,
  132823. 10,10, 9,10,10,10,11,11,12,12,19,12,12, 9, 9,10,
  132824. 10,10,10,10,10,12,12,12,12,19,19,19, 9, 9, 9, 9,
  132825. 11,10,11,11,12,11,13,13,19,19,19, 9, 9, 9, 9,11,
  132826. 10,11,11,11,12,13,13,19,19,19,13,13,10,10,11,11,
  132827. 12,12,12,12,13,12,19,19,19,14,13,10,10,11,11,12,
  132828. 12,12,13,13,13,19,19,19,19,19,12,12,12,11,12,13,
  132829. 14,13,13,13,19,19,19,19,19,12,12,12,11,12,12,13,
  132830. 14,13,14,19,19,19,19,19,16,16,12,13,12,13,13,14,
  132831. 15,14,19,18,18,18,18,16,15,12,11,12,11,14,12,14,
  132832. 14,
  132833. };
  132834. static float _vq_quantthresh__44c7_s_p8_0[] = {
  132835. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  132836. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  132837. };
  132838. static long _vq_quantmap__44c7_s_p8_0[] = {
  132839. 13, 11, 9, 7, 5, 3, 1, 0,
  132840. 2, 4, 6, 8, 10, 12, 14,
  132841. };
  132842. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_0 = {
  132843. _vq_quantthresh__44c7_s_p8_0,
  132844. _vq_quantmap__44c7_s_p8_0,
  132845. 15,
  132846. 15
  132847. };
  132848. static static_codebook _44c7_s_p8_0 = {
  132849. 2, 225,
  132850. _vq_lengthlist__44c7_s_p8_0,
  132851. 1, -520986624, 1620377600, 4, 0,
  132852. _vq_quantlist__44c7_s_p8_0,
  132853. NULL,
  132854. &_vq_auxt__44c7_s_p8_0,
  132855. NULL,
  132856. 0
  132857. };
  132858. static long _vq_quantlist__44c7_s_p8_1[] = {
  132859. 10,
  132860. 9,
  132861. 11,
  132862. 8,
  132863. 12,
  132864. 7,
  132865. 13,
  132866. 6,
  132867. 14,
  132868. 5,
  132869. 15,
  132870. 4,
  132871. 16,
  132872. 3,
  132873. 17,
  132874. 2,
  132875. 18,
  132876. 1,
  132877. 19,
  132878. 0,
  132879. 20,
  132880. };
  132881. static long _vq_lengthlist__44c7_s_p8_1[] = {
  132882. 3, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  132883. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  132884. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  132885. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  132886. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132887. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  132888. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  132889. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  132890. 10, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132891. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132892. 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,10,10, 9, 9, 9,
  132893. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9, 9,10,11,10,
  132894. 11,10, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9, 9,
  132895. 9, 9,11,10,11,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,
  132896. 10, 9, 9,10, 9, 9,10,11,10,10,11,10, 9, 9, 9, 9,
  132897. 9,10,10, 9,10,10,10,10, 9,10,10,10,10,10,10,11,
  132898. 11,11,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  132899. 10,10,10,11,11,10,10,10,10,10,10,10,10,10,10,10,
  132900. 10, 9,10,10, 9,10,11,11,10,11,10,11,10, 9,10,10,
  132901. 9,10,10,10,10,10,10,10,10,10,10,11,11,11,11,10,
  132902. 11,11,10,10,10,10,10,10, 9,10, 9,10,10, 9,10, 9,
  132903. 10,10,10,11,10,11,10,11,11,10,10,10,10,10,10, 9,
  132904. 10,10,10,10,10,10,10,11,10,10,10,10,10,10,10,10,
  132905. 10,10,10,10,10,10,10,10,10,10,10,10,10,11,10,11,
  132906. 11,10,10,10,10, 9, 9,10,10, 9, 9,10, 9,10,10,10,
  132907. 10,11,11,10,10,10,10,10,10,10, 9, 9,10,10,10, 9,
  132908. 9,10,10,10,10,10,11,10,11,10,10,10,10,10,10, 9,
  132909. 10,10,10,10,10,10,10,10,10,
  132910. };
  132911. static float _vq_quantthresh__44c7_s_p8_1[] = {
  132912. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  132913. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  132914. 6.5, 7.5, 8.5, 9.5,
  132915. };
  132916. static long _vq_quantmap__44c7_s_p8_1[] = {
  132917. 19, 17, 15, 13, 11, 9, 7, 5,
  132918. 3, 1, 0, 2, 4, 6, 8, 10,
  132919. 12, 14, 16, 18, 20,
  132920. };
  132921. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_1 = {
  132922. _vq_quantthresh__44c7_s_p8_1,
  132923. _vq_quantmap__44c7_s_p8_1,
  132924. 21,
  132925. 21
  132926. };
  132927. static static_codebook _44c7_s_p8_1 = {
  132928. 2, 441,
  132929. _vq_lengthlist__44c7_s_p8_1,
  132930. 1, -529268736, 1611661312, 5, 0,
  132931. _vq_quantlist__44c7_s_p8_1,
  132932. NULL,
  132933. &_vq_auxt__44c7_s_p8_1,
  132934. NULL,
  132935. 0
  132936. };
  132937. static long _vq_quantlist__44c7_s_p9_0[] = {
  132938. 6,
  132939. 5,
  132940. 7,
  132941. 4,
  132942. 8,
  132943. 3,
  132944. 9,
  132945. 2,
  132946. 10,
  132947. 1,
  132948. 11,
  132949. 0,
  132950. 12,
  132951. };
  132952. static long _vq_lengthlist__44c7_s_p9_0[] = {
  132953. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 6, 6,
  132954. 11,11,11,11,11,11,11,11,11,11, 4, 7, 7,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,11,11,11,11,11,11,11,
  132961. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132962. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132963. 11,11,11,11,11,11,11,11,11,
  132964. };
  132965. static float _vq_quantthresh__44c7_s_p9_0[] = {
  132966. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  132967. 1592.5, 2229.5, 2866.5, 3503.5,
  132968. };
  132969. static long _vq_quantmap__44c7_s_p9_0[] = {
  132970. 11, 9, 7, 5, 3, 1, 0, 2,
  132971. 4, 6, 8, 10, 12,
  132972. };
  132973. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_0 = {
  132974. _vq_quantthresh__44c7_s_p9_0,
  132975. _vq_quantmap__44c7_s_p9_0,
  132976. 13,
  132977. 13
  132978. };
  132979. static static_codebook _44c7_s_p9_0 = {
  132980. 2, 169,
  132981. _vq_lengthlist__44c7_s_p9_0,
  132982. 1, -511845376, 1630791680, 4, 0,
  132983. _vq_quantlist__44c7_s_p9_0,
  132984. NULL,
  132985. &_vq_auxt__44c7_s_p9_0,
  132986. NULL,
  132987. 0
  132988. };
  132989. static long _vq_quantlist__44c7_s_p9_1[] = {
  132990. 6,
  132991. 5,
  132992. 7,
  132993. 4,
  132994. 8,
  132995. 3,
  132996. 9,
  132997. 2,
  132998. 10,
  132999. 1,
  133000. 11,
  133001. 0,
  133002. 12,
  133003. };
  133004. static long _vq_lengthlist__44c7_s_p9_1[] = {
  133005. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  133006. 8, 8, 9, 8, 8, 7, 9, 8,11,10, 5, 6, 6, 8, 8, 9,
  133007. 8, 8, 8,10, 9,11,11,16, 8, 8, 9, 8, 9, 9, 9, 8,
  133008. 10, 9,11,10,16, 8, 8, 9, 9,10,10, 9, 9,10,10,11,
  133009. 11,16,13,13, 9, 9,10,10, 9,10,11,11,12,11,16,13,
  133010. 13, 9, 8,10, 9,10,10,10,10,11,11,16,14,16, 8, 9,
  133011. 9, 9,11,10,11,11,12,11,16,16,16, 9, 7,10, 7,11,
  133012. 10,11,11,12,11,16,16,16,12,12, 9,10,11,11,12,11,
  133013. 12,12,16,16,16,12,10,10, 7,11, 8,12,11,12,12,16,
  133014. 16,15,16,16,11,12,10,10,12,11,12,12,16,16,16,15,
  133015. 15,11,11,10,10,12,12,12,12,
  133016. };
  133017. static float _vq_quantthresh__44c7_s_p9_1[] = {
  133018. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  133019. 122.5, 171.5, 220.5, 269.5,
  133020. };
  133021. static long _vq_quantmap__44c7_s_p9_1[] = {
  133022. 11, 9, 7, 5, 3, 1, 0, 2,
  133023. 4, 6, 8, 10, 12,
  133024. };
  133025. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_1 = {
  133026. _vq_quantthresh__44c7_s_p9_1,
  133027. _vq_quantmap__44c7_s_p9_1,
  133028. 13,
  133029. 13
  133030. };
  133031. static static_codebook _44c7_s_p9_1 = {
  133032. 2, 169,
  133033. _vq_lengthlist__44c7_s_p9_1,
  133034. 1, -518889472, 1622704128, 4, 0,
  133035. _vq_quantlist__44c7_s_p9_1,
  133036. NULL,
  133037. &_vq_auxt__44c7_s_p9_1,
  133038. NULL,
  133039. 0
  133040. };
  133041. static long _vq_quantlist__44c7_s_p9_2[] = {
  133042. 24,
  133043. 23,
  133044. 25,
  133045. 22,
  133046. 26,
  133047. 21,
  133048. 27,
  133049. 20,
  133050. 28,
  133051. 19,
  133052. 29,
  133053. 18,
  133054. 30,
  133055. 17,
  133056. 31,
  133057. 16,
  133058. 32,
  133059. 15,
  133060. 33,
  133061. 14,
  133062. 34,
  133063. 13,
  133064. 35,
  133065. 12,
  133066. 36,
  133067. 11,
  133068. 37,
  133069. 10,
  133070. 38,
  133071. 9,
  133072. 39,
  133073. 8,
  133074. 40,
  133075. 7,
  133076. 41,
  133077. 6,
  133078. 42,
  133079. 5,
  133080. 43,
  133081. 4,
  133082. 44,
  133083. 3,
  133084. 45,
  133085. 2,
  133086. 46,
  133087. 1,
  133088. 47,
  133089. 0,
  133090. 48,
  133091. };
  133092. static long _vq_lengthlist__44c7_s_p9_2[] = {
  133093. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  133094. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133095. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133096. 7,
  133097. };
  133098. static float _vq_quantthresh__44c7_s_p9_2[] = {
  133099. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  133100. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  133101. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133102. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133103. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  133104. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  133105. };
  133106. static long _vq_quantmap__44c7_s_p9_2[] = {
  133107. 47, 45, 43, 41, 39, 37, 35, 33,
  133108. 31, 29, 27, 25, 23, 21, 19, 17,
  133109. 15, 13, 11, 9, 7, 5, 3, 1,
  133110. 0, 2, 4, 6, 8, 10, 12, 14,
  133111. 16, 18, 20, 22, 24, 26, 28, 30,
  133112. 32, 34, 36, 38, 40, 42, 44, 46,
  133113. 48,
  133114. };
  133115. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_2 = {
  133116. _vq_quantthresh__44c7_s_p9_2,
  133117. _vq_quantmap__44c7_s_p9_2,
  133118. 49,
  133119. 49
  133120. };
  133121. static static_codebook _44c7_s_p9_2 = {
  133122. 1, 49,
  133123. _vq_lengthlist__44c7_s_p9_2,
  133124. 1, -526909440, 1611661312, 6, 0,
  133125. _vq_quantlist__44c7_s_p9_2,
  133126. NULL,
  133127. &_vq_auxt__44c7_s_p9_2,
  133128. NULL,
  133129. 0
  133130. };
  133131. static long _huff_lengthlist__44c7_s_short[] = {
  133132. 4,11,12,14,15,15,17,17,18,18, 5, 6, 6, 8, 9,10,
  133133. 13,17,18,19, 7, 5, 4, 6, 8, 9,11,15,19,19, 8, 6,
  133134. 5, 5, 6, 7,11,14,16,17, 9, 7, 7, 6, 7, 7,10,13,
  133135. 15,19,10, 8, 7, 6, 7, 6, 7, 9,14,16,12,10, 9, 7,
  133136. 7, 6, 4, 5,10,15,14,13,11, 7, 6, 6, 4, 2, 7,13,
  133137. 16,16,15, 9, 8, 8, 8, 6, 9,13,19,19,17,12,11,10,
  133138. 10, 9,11,14,
  133139. };
  133140. static static_codebook _huff_book__44c7_s_short = {
  133141. 2, 100,
  133142. _huff_lengthlist__44c7_s_short,
  133143. 0, 0, 0, 0, 0,
  133144. NULL,
  133145. NULL,
  133146. NULL,
  133147. NULL,
  133148. 0
  133149. };
  133150. static long _huff_lengthlist__44c8_s_long[] = {
  133151. 3, 8,12,13,14,14,14,13,14,14, 6, 4, 5, 8,10,10,
  133152. 11,11,14,13, 9, 5, 4, 5, 7, 8, 9,10,13,13,12, 7,
  133153. 5, 4, 5, 6, 8, 9,12,13,13, 9, 6, 5, 5, 5, 7, 9,
  133154. 11,14,12,10, 7, 6, 5, 4, 6, 7,10,11,12,11, 9, 8,
  133155. 7, 5, 5, 6,10,10,13,12,10, 9, 8, 6, 6, 5, 8,10,
  133156. 14,13,12,12,11,10, 9, 7, 8,10,12,13,14,14,13,12,
  133157. 11, 9, 9,10,
  133158. };
  133159. static static_codebook _huff_book__44c8_s_long = {
  133160. 2, 100,
  133161. _huff_lengthlist__44c8_s_long,
  133162. 0, 0, 0, 0, 0,
  133163. NULL,
  133164. NULL,
  133165. NULL,
  133166. NULL,
  133167. 0
  133168. };
  133169. static long _vq_quantlist__44c8_s_p1_0[] = {
  133170. 1,
  133171. 0,
  133172. 2,
  133173. };
  133174. static long _vq_lengthlist__44c8_s_p1_0[] = {
  133175. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 7, 7, 0, 9, 8, 0,
  133176. 9, 8, 6, 7, 7, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  133177. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  133178. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  133179. 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  133180. 8,
  133181. };
  133182. static float _vq_quantthresh__44c8_s_p1_0[] = {
  133183. -0.5, 0.5,
  133184. };
  133185. static long _vq_quantmap__44c8_s_p1_0[] = {
  133186. 1, 0, 2,
  133187. };
  133188. static encode_aux_threshmatch _vq_auxt__44c8_s_p1_0 = {
  133189. _vq_quantthresh__44c8_s_p1_0,
  133190. _vq_quantmap__44c8_s_p1_0,
  133191. 3,
  133192. 3
  133193. };
  133194. static static_codebook _44c8_s_p1_0 = {
  133195. 4, 81,
  133196. _vq_lengthlist__44c8_s_p1_0,
  133197. 1, -535822336, 1611661312, 2, 0,
  133198. _vq_quantlist__44c8_s_p1_0,
  133199. NULL,
  133200. &_vq_auxt__44c8_s_p1_0,
  133201. NULL,
  133202. 0
  133203. };
  133204. static long _vq_quantlist__44c8_s_p2_0[] = {
  133205. 2,
  133206. 1,
  133207. 3,
  133208. 0,
  133209. 4,
  133210. };
  133211. static long _vq_lengthlist__44c8_s_p2_0[] = {
  133212. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  133213. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  133214. 7,10, 9, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  133215. 11,11, 5, 7, 7, 9, 9, 0, 7, 8, 9,10, 0, 7, 8, 9,
  133216. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  133217. 0,11,10,12,11, 0,11,10,12,12, 0,13,13,14,14, 0,
  133218. 0, 0,14,13, 8, 9, 9,10,11, 0,10,11,12,12, 0,10,
  133219. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  133220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133221. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  133222. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,11,10, 5,
  133223. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  133224. 9,10,10, 0, 0, 0,10,10, 8,10, 9,12,12, 0,10,10,
  133225. 12,11, 0,10,10,12,12, 0,12,12,13,12, 0, 0, 0,13,
  133226. 12, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,11,12,
  133227. 0,12,12,13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0,
  133228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133229. 0, 0, 0, 6, 8, 7,11,10, 0, 7, 7,10,10, 0, 7, 7,
  133230. 10,10, 0, 9, 9,10,11, 0, 0, 0,10,10, 6, 7, 8,10,
  133231. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,10,10,
  133232. 0, 0, 0,10,10, 9,10, 9,12,12, 0,10,10,12,12, 0,
  133233. 10,10,12,11, 0,12,12,13,13, 0, 0, 0,13,12, 8, 9,
  133234. 10,12,12, 0,10,10,12,12, 0,10,10,11,12, 0,12,12,
  133235. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133237. 7,10,10,13,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  133238. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,13, 0, 9,
  133239. 9,12,12, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  133240. 12,12, 9,11,11,14,13, 0,10,10,13,12, 0,11,10,13,
  133241. 12, 0,12,12,13,12, 0, 0, 0,13,13, 9,11,11,13,14,
  133242. 0,10,11,12,13, 0,10,11,13,13, 0,12,12,12,13, 0,
  133243. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  133248. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,11,
  133249. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  133250. 13,13, 0,10,11,13,13, 0,12,12,13,13, 0, 0, 0,12,
  133251. 13,
  133252. };
  133253. static float _vq_quantthresh__44c8_s_p2_0[] = {
  133254. -1.5, -0.5, 0.5, 1.5,
  133255. };
  133256. static long _vq_quantmap__44c8_s_p2_0[] = {
  133257. 3, 1, 0, 2, 4,
  133258. };
  133259. static encode_aux_threshmatch _vq_auxt__44c8_s_p2_0 = {
  133260. _vq_quantthresh__44c8_s_p2_0,
  133261. _vq_quantmap__44c8_s_p2_0,
  133262. 5,
  133263. 5
  133264. };
  133265. static static_codebook _44c8_s_p2_0 = {
  133266. 4, 625,
  133267. _vq_lengthlist__44c8_s_p2_0,
  133268. 1, -533725184, 1611661312, 3, 0,
  133269. _vq_quantlist__44c8_s_p2_0,
  133270. NULL,
  133271. &_vq_auxt__44c8_s_p2_0,
  133272. NULL,
  133273. 0
  133274. };
  133275. static long _vq_quantlist__44c8_s_p3_0[] = {
  133276. 4,
  133277. 3,
  133278. 5,
  133279. 2,
  133280. 6,
  133281. 1,
  133282. 7,
  133283. 0,
  133284. 8,
  133285. };
  133286. static long _vq_lengthlist__44c8_s_p3_0[] = {
  133287. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  133288. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  133289. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  133290. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  133291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133292. 0,
  133293. };
  133294. static float _vq_quantthresh__44c8_s_p3_0[] = {
  133295. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133296. };
  133297. static long _vq_quantmap__44c8_s_p3_0[] = {
  133298. 7, 5, 3, 1, 0, 2, 4, 6,
  133299. 8,
  133300. };
  133301. static encode_aux_threshmatch _vq_auxt__44c8_s_p3_0 = {
  133302. _vq_quantthresh__44c8_s_p3_0,
  133303. _vq_quantmap__44c8_s_p3_0,
  133304. 9,
  133305. 9
  133306. };
  133307. static static_codebook _44c8_s_p3_0 = {
  133308. 2, 81,
  133309. _vq_lengthlist__44c8_s_p3_0,
  133310. 1, -531628032, 1611661312, 4, 0,
  133311. _vq_quantlist__44c8_s_p3_0,
  133312. NULL,
  133313. &_vq_auxt__44c8_s_p3_0,
  133314. NULL,
  133315. 0
  133316. };
  133317. static long _vq_quantlist__44c8_s_p4_0[] = {
  133318. 8,
  133319. 7,
  133320. 9,
  133321. 6,
  133322. 10,
  133323. 5,
  133324. 11,
  133325. 4,
  133326. 12,
  133327. 3,
  133328. 13,
  133329. 2,
  133330. 14,
  133331. 1,
  133332. 15,
  133333. 0,
  133334. 16,
  133335. };
  133336. static long _vq_lengthlist__44c8_s_p4_0[] = {
  133337. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  133338. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 8,10,10,11,11,
  133339. 11,11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  133340. 11,11,11, 0, 6, 5, 6, 6, 7, 7, 9, 9, 9, 9,10,10,
  133341. 11,11,12,12, 0, 0, 0, 6, 6, 7, 7, 9, 9, 9, 9,10,
  133342. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  133343. 11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  133344. 10,11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  133345. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  133346. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  133347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133355. 0,
  133356. };
  133357. static float _vq_quantthresh__44c8_s_p4_0[] = {
  133358. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133359. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133360. };
  133361. static long _vq_quantmap__44c8_s_p4_0[] = {
  133362. 15, 13, 11, 9, 7, 5, 3, 1,
  133363. 0, 2, 4, 6, 8, 10, 12, 14,
  133364. 16,
  133365. };
  133366. static encode_aux_threshmatch _vq_auxt__44c8_s_p4_0 = {
  133367. _vq_quantthresh__44c8_s_p4_0,
  133368. _vq_quantmap__44c8_s_p4_0,
  133369. 17,
  133370. 17
  133371. };
  133372. static static_codebook _44c8_s_p4_0 = {
  133373. 2, 289,
  133374. _vq_lengthlist__44c8_s_p4_0,
  133375. 1, -529530880, 1611661312, 5, 0,
  133376. _vq_quantlist__44c8_s_p4_0,
  133377. NULL,
  133378. &_vq_auxt__44c8_s_p4_0,
  133379. NULL,
  133380. 0
  133381. };
  133382. static long _vq_quantlist__44c8_s_p5_0[] = {
  133383. 1,
  133384. 0,
  133385. 2,
  133386. };
  133387. static long _vq_lengthlist__44c8_s_p5_0[] = {
  133388. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6,10,10,10,10,
  133389. 10,10, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  133390. 11,10,11,11, 7,10,10,11,12,12,12,12,12, 7,10,10,
  133391. 11,12,12,12,12,12, 6,10,10,10,12,12,10,12,12, 7,
  133392. 10,10,11,12,12,12,12,12, 7,10,10,11,12,12,12,12,
  133393. 12,
  133394. };
  133395. static float _vq_quantthresh__44c8_s_p5_0[] = {
  133396. -5.5, 5.5,
  133397. };
  133398. static long _vq_quantmap__44c8_s_p5_0[] = {
  133399. 1, 0, 2,
  133400. };
  133401. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_0 = {
  133402. _vq_quantthresh__44c8_s_p5_0,
  133403. _vq_quantmap__44c8_s_p5_0,
  133404. 3,
  133405. 3
  133406. };
  133407. static static_codebook _44c8_s_p5_0 = {
  133408. 4, 81,
  133409. _vq_lengthlist__44c8_s_p5_0,
  133410. 1, -529137664, 1618345984, 2, 0,
  133411. _vq_quantlist__44c8_s_p5_0,
  133412. NULL,
  133413. &_vq_auxt__44c8_s_p5_0,
  133414. NULL,
  133415. 0
  133416. };
  133417. static long _vq_quantlist__44c8_s_p5_1[] = {
  133418. 5,
  133419. 4,
  133420. 6,
  133421. 3,
  133422. 7,
  133423. 2,
  133424. 8,
  133425. 1,
  133426. 9,
  133427. 0,
  133428. 10,
  133429. };
  133430. static long _vq_lengthlist__44c8_s_p5_1[] = {
  133431. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 5, 6, 6,
  133432. 7, 7, 8, 8, 8, 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  133433. 9,12, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,12,12,12, 6,
  133434. 6, 7, 7, 8, 8, 9, 9,11,11,11, 6, 6, 7, 7, 8, 8,
  133435. 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11,
  133436. 7, 7, 7, 8, 8, 8, 8, 8,11,11,11,11,11, 7, 7, 8,
  133437. 8, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 8, 8,11,11,
  133438. 11,11,11, 7, 7, 7, 7, 8, 8,
  133439. };
  133440. static float _vq_quantthresh__44c8_s_p5_1[] = {
  133441. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133442. 3.5, 4.5,
  133443. };
  133444. static long _vq_quantmap__44c8_s_p5_1[] = {
  133445. 9, 7, 5, 3, 1, 0, 2, 4,
  133446. 6, 8, 10,
  133447. };
  133448. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_1 = {
  133449. _vq_quantthresh__44c8_s_p5_1,
  133450. _vq_quantmap__44c8_s_p5_1,
  133451. 11,
  133452. 11
  133453. };
  133454. static static_codebook _44c8_s_p5_1 = {
  133455. 2, 121,
  133456. _vq_lengthlist__44c8_s_p5_1,
  133457. 1, -531365888, 1611661312, 4, 0,
  133458. _vq_quantlist__44c8_s_p5_1,
  133459. NULL,
  133460. &_vq_auxt__44c8_s_p5_1,
  133461. NULL,
  133462. 0
  133463. };
  133464. static long _vq_quantlist__44c8_s_p6_0[] = {
  133465. 6,
  133466. 5,
  133467. 7,
  133468. 4,
  133469. 8,
  133470. 3,
  133471. 9,
  133472. 2,
  133473. 10,
  133474. 1,
  133475. 11,
  133476. 0,
  133477. 12,
  133478. };
  133479. static long _vq_lengthlist__44c8_s_p6_0[] = {
  133480. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  133481. 7, 7, 8, 8, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 8,
  133482. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,
  133483. 10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,10,10,11,
  133484. 11, 0,11,11, 9, 9,10,10,11,11,11,11,12,12, 0,12,
  133485. 12, 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  133486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133490. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133491. };
  133492. static float _vq_quantthresh__44c8_s_p6_0[] = {
  133493. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  133494. 12.5, 17.5, 22.5, 27.5,
  133495. };
  133496. static long _vq_quantmap__44c8_s_p6_0[] = {
  133497. 11, 9, 7, 5, 3, 1, 0, 2,
  133498. 4, 6, 8, 10, 12,
  133499. };
  133500. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_0 = {
  133501. _vq_quantthresh__44c8_s_p6_0,
  133502. _vq_quantmap__44c8_s_p6_0,
  133503. 13,
  133504. 13
  133505. };
  133506. static static_codebook _44c8_s_p6_0 = {
  133507. 2, 169,
  133508. _vq_lengthlist__44c8_s_p6_0,
  133509. 1, -526516224, 1616117760, 4, 0,
  133510. _vq_quantlist__44c8_s_p6_0,
  133511. NULL,
  133512. &_vq_auxt__44c8_s_p6_0,
  133513. NULL,
  133514. 0
  133515. };
  133516. static long _vq_quantlist__44c8_s_p6_1[] = {
  133517. 2,
  133518. 1,
  133519. 3,
  133520. 0,
  133521. 4,
  133522. };
  133523. static long _vq_lengthlist__44c8_s_p6_1[] = {
  133524. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  133525. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  133526. };
  133527. static float _vq_quantthresh__44c8_s_p6_1[] = {
  133528. -1.5, -0.5, 0.5, 1.5,
  133529. };
  133530. static long _vq_quantmap__44c8_s_p6_1[] = {
  133531. 3, 1, 0, 2, 4,
  133532. };
  133533. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_1 = {
  133534. _vq_quantthresh__44c8_s_p6_1,
  133535. _vq_quantmap__44c8_s_p6_1,
  133536. 5,
  133537. 5
  133538. };
  133539. static static_codebook _44c8_s_p6_1 = {
  133540. 2, 25,
  133541. _vq_lengthlist__44c8_s_p6_1,
  133542. 1, -533725184, 1611661312, 3, 0,
  133543. _vq_quantlist__44c8_s_p6_1,
  133544. NULL,
  133545. &_vq_auxt__44c8_s_p6_1,
  133546. NULL,
  133547. 0
  133548. };
  133549. static long _vq_quantlist__44c8_s_p7_0[] = {
  133550. 6,
  133551. 5,
  133552. 7,
  133553. 4,
  133554. 8,
  133555. 3,
  133556. 9,
  133557. 2,
  133558. 10,
  133559. 1,
  133560. 11,
  133561. 0,
  133562. 12,
  133563. };
  133564. static long _vq_lengthlist__44c8_s_p7_0[] = {
  133565. 1, 4, 4, 6, 6, 8, 7, 9, 9,10,10,12,12, 6, 5, 5,
  133566. 7, 7, 8, 8,10,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  133567. 8,10,10,11,11,12,12,21, 7, 7, 7, 7, 8, 9,10,10,
  133568. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,12,12,13,
  133569. 13,21,11,11, 8, 8, 9, 9,11,11,12,12,13,13,21,11,
  133570. 11, 8, 8, 9, 9,11,11,12,12,13,13,21,21,21,10,10,
  133571. 10,10,11,11,12,13,13,13,21,21,21,10,10,10,10,11,
  133572. 11,13,13,14,13,21,21,21,13,13,11,11,12,12,13,13,
  133573. 14,14,21,21,21,14,14,11,11,12,12,13,13,14,14,21,
  133574. 21,21,21,20,13,13,13,12,14,14,16,15,20,20,20,20,
  133575. 20,13,13,13,13,14,13,15,15,
  133576. };
  133577. static float _vq_quantthresh__44c8_s_p7_0[] = {
  133578. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  133579. 27.5, 38.5, 49.5, 60.5,
  133580. };
  133581. static long _vq_quantmap__44c8_s_p7_0[] = {
  133582. 11, 9, 7, 5, 3, 1, 0, 2,
  133583. 4, 6, 8, 10, 12,
  133584. };
  133585. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_0 = {
  133586. _vq_quantthresh__44c8_s_p7_0,
  133587. _vq_quantmap__44c8_s_p7_0,
  133588. 13,
  133589. 13
  133590. };
  133591. static static_codebook _44c8_s_p7_0 = {
  133592. 2, 169,
  133593. _vq_lengthlist__44c8_s_p7_0,
  133594. 1, -523206656, 1618345984, 4, 0,
  133595. _vq_quantlist__44c8_s_p7_0,
  133596. NULL,
  133597. &_vq_auxt__44c8_s_p7_0,
  133598. NULL,
  133599. 0
  133600. };
  133601. static long _vq_quantlist__44c8_s_p7_1[] = {
  133602. 5,
  133603. 4,
  133604. 6,
  133605. 3,
  133606. 7,
  133607. 2,
  133608. 8,
  133609. 1,
  133610. 9,
  133611. 0,
  133612. 10,
  133613. };
  133614. static long _vq_lengthlist__44c8_s_p7_1[] = {
  133615. 4, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7,
  133616. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  133617. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  133618. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133619. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  133620. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  133621. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  133622. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133623. };
  133624. static float _vq_quantthresh__44c8_s_p7_1[] = {
  133625. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133626. 3.5, 4.5,
  133627. };
  133628. static long _vq_quantmap__44c8_s_p7_1[] = {
  133629. 9, 7, 5, 3, 1, 0, 2, 4,
  133630. 6, 8, 10,
  133631. };
  133632. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_1 = {
  133633. _vq_quantthresh__44c8_s_p7_1,
  133634. _vq_quantmap__44c8_s_p7_1,
  133635. 11,
  133636. 11
  133637. };
  133638. static static_codebook _44c8_s_p7_1 = {
  133639. 2, 121,
  133640. _vq_lengthlist__44c8_s_p7_1,
  133641. 1, -531365888, 1611661312, 4, 0,
  133642. _vq_quantlist__44c8_s_p7_1,
  133643. NULL,
  133644. &_vq_auxt__44c8_s_p7_1,
  133645. NULL,
  133646. 0
  133647. };
  133648. static long _vq_quantlist__44c8_s_p8_0[] = {
  133649. 7,
  133650. 6,
  133651. 8,
  133652. 5,
  133653. 9,
  133654. 4,
  133655. 10,
  133656. 3,
  133657. 11,
  133658. 2,
  133659. 12,
  133660. 1,
  133661. 13,
  133662. 0,
  133663. 14,
  133664. };
  133665. static long _vq_lengthlist__44c8_s_p8_0[] = {
  133666. 1, 4, 4, 7, 6, 8, 8, 8, 7, 9, 8,10,10,11,10, 6,
  133667. 5, 5, 7, 7, 9, 9, 8, 8,10,10,11,11,12,11, 6, 5,
  133668. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8,
  133669. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8, 8,
  133670. 8,10, 9, 9, 9,10,10,11,11,12,12,20,12,12, 9, 9,
  133671. 10,10,10,10,10,11,12,12,12,12,20,12,12, 9, 9,10,
  133672. 10,10,10,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,
  133673. 11,10,11,11,12,12,12,13,20,19,19, 9, 9, 9, 9,11,
  133674. 11,11,12,12,12,13,13,19,19,19,13,13,10,10,11,11,
  133675. 12,12,13,13,13,13,19,19,19,14,13,11,10,11,11,12,
  133676. 12,12,13,13,13,19,19,19,19,19,12,12,12,12,13,13,
  133677. 13,13,14,13,19,19,19,19,19,12,12,12,11,12,12,13,
  133678. 14,14,14,19,19,19,19,19,16,15,13,12,13,13,13,14,
  133679. 14,14,19,19,19,19,19,17,17,13,12,13,11,14,13,15,
  133680. 15,
  133681. };
  133682. static float _vq_quantthresh__44c8_s_p8_0[] = {
  133683. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  133684. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  133685. };
  133686. static long _vq_quantmap__44c8_s_p8_0[] = {
  133687. 13, 11, 9, 7, 5, 3, 1, 0,
  133688. 2, 4, 6, 8, 10, 12, 14,
  133689. };
  133690. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_0 = {
  133691. _vq_quantthresh__44c8_s_p8_0,
  133692. _vq_quantmap__44c8_s_p8_0,
  133693. 15,
  133694. 15
  133695. };
  133696. static static_codebook _44c8_s_p8_0 = {
  133697. 2, 225,
  133698. _vq_lengthlist__44c8_s_p8_0,
  133699. 1, -520986624, 1620377600, 4, 0,
  133700. _vq_quantlist__44c8_s_p8_0,
  133701. NULL,
  133702. &_vq_auxt__44c8_s_p8_0,
  133703. NULL,
  133704. 0
  133705. };
  133706. static long _vq_quantlist__44c8_s_p8_1[] = {
  133707. 10,
  133708. 9,
  133709. 11,
  133710. 8,
  133711. 12,
  133712. 7,
  133713. 13,
  133714. 6,
  133715. 14,
  133716. 5,
  133717. 15,
  133718. 4,
  133719. 16,
  133720. 3,
  133721. 17,
  133722. 2,
  133723. 18,
  133724. 1,
  133725. 19,
  133726. 0,
  133727. 20,
  133728. };
  133729. static long _vq_lengthlist__44c8_s_p8_1[] = {
  133730. 4, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  133731. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  133732. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  133733. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  133734. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133735. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  133736. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  133737. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  133738. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133739. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133740. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  133741. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  133742. 10,10, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9,
  133743. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133744. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  133745. 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,10,10,10,10,
  133746. 10,10,10, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  133747. 9,10,10,10,10,10,10,10, 9,10,10, 9,10,10,10,10,
  133748. 9,10, 9,10,10, 9,10,10,10,10,10,10,10, 9,10,10,
  133749. 10,10,10,10, 9, 9,10,10, 9,10,10,10,10,10,10,10,
  133750. 10,10,10,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9, 9,
  133751. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  133752. 10, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  133753. 10,10,10,10, 9, 9,10, 9, 9, 9,10,10,10,10,10,10,
  133754. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,10,10,
  133755. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10, 9,
  133756. 9,10, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  133757. 10, 9, 9,10,10, 9,10, 9, 9,
  133758. };
  133759. static float _vq_quantthresh__44c8_s_p8_1[] = {
  133760. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  133761. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  133762. 6.5, 7.5, 8.5, 9.5,
  133763. };
  133764. static long _vq_quantmap__44c8_s_p8_1[] = {
  133765. 19, 17, 15, 13, 11, 9, 7, 5,
  133766. 3, 1, 0, 2, 4, 6, 8, 10,
  133767. 12, 14, 16, 18, 20,
  133768. };
  133769. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_1 = {
  133770. _vq_quantthresh__44c8_s_p8_1,
  133771. _vq_quantmap__44c8_s_p8_1,
  133772. 21,
  133773. 21
  133774. };
  133775. static static_codebook _44c8_s_p8_1 = {
  133776. 2, 441,
  133777. _vq_lengthlist__44c8_s_p8_1,
  133778. 1, -529268736, 1611661312, 5, 0,
  133779. _vq_quantlist__44c8_s_p8_1,
  133780. NULL,
  133781. &_vq_auxt__44c8_s_p8_1,
  133782. NULL,
  133783. 0
  133784. };
  133785. static long _vq_quantlist__44c8_s_p9_0[] = {
  133786. 8,
  133787. 7,
  133788. 9,
  133789. 6,
  133790. 10,
  133791. 5,
  133792. 11,
  133793. 4,
  133794. 12,
  133795. 3,
  133796. 13,
  133797. 2,
  133798. 14,
  133799. 1,
  133800. 15,
  133801. 0,
  133802. 16,
  133803. };
  133804. static long _vq_lengthlist__44c8_s_p9_0[] = {
  133805. 1, 4, 3,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133806. 11, 4, 7, 7,11,11,11,11,11,11,11,11,11,11,11,11,
  133807. 11,11, 4, 8,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,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133817. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133818. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133819. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133820. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133821. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133822. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133823. 10,
  133824. };
  133825. static float _vq_quantthresh__44c8_s_p9_0[] = {
  133826. -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5,
  133827. 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5, 6982.5,
  133828. };
  133829. static long _vq_quantmap__44c8_s_p9_0[] = {
  133830. 15, 13, 11, 9, 7, 5, 3, 1,
  133831. 0, 2, 4, 6, 8, 10, 12, 14,
  133832. 16,
  133833. };
  133834. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_0 = {
  133835. _vq_quantthresh__44c8_s_p9_0,
  133836. _vq_quantmap__44c8_s_p9_0,
  133837. 17,
  133838. 17
  133839. };
  133840. static static_codebook _44c8_s_p9_0 = {
  133841. 2, 289,
  133842. _vq_lengthlist__44c8_s_p9_0,
  133843. 1, -509798400, 1631393792, 5, 0,
  133844. _vq_quantlist__44c8_s_p9_0,
  133845. NULL,
  133846. &_vq_auxt__44c8_s_p9_0,
  133847. NULL,
  133848. 0
  133849. };
  133850. static long _vq_quantlist__44c8_s_p9_1[] = {
  133851. 9,
  133852. 8,
  133853. 10,
  133854. 7,
  133855. 11,
  133856. 6,
  133857. 12,
  133858. 5,
  133859. 13,
  133860. 4,
  133861. 14,
  133862. 3,
  133863. 15,
  133864. 2,
  133865. 16,
  133866. 1,
  133867. 17,
  133868. 0,
  133869. 18,
  133870. };
  133871. static long _vq_lengthlist__44c8_s_p9_1[] = {
  133872. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,10,10,
  133873. 10,11,11, 6, 6, 6, 8, 8, 9, 8, 8, 7,10, 8,11,10,
  133874. 12,11,12,12,13,13, 5, 5, 6, 8, 8, 9, 9, 8, 8,10,
  133875. 9,11,11,12,12,13,13,13,13,17, 8, 8, 9, 9, 9, 9,
  133876. 9, 9,10, 9,12,10,12,12,13,12,13,13,17, 9, 8, 9,
  133877. 9, 9, 9, 9, 9,10,10,12,12,12,12,13,13,13,13,17,
  133878. 13,13, 9, 9,10,10,10,10,11,11,12,11,13,12,13,13,
  133879. 14,15,17,13,13, 9, 8,10, 9,10,10,11,11,12,12,14,
  133880. 13,15,13,14,15,17,17,17, 9,10, 9,10,11,11,12,12,
  133881. 12,12,13,13,14,14,15,15,17,17,17, 9, 8, 9, 8,11,
  133882. 11,12,12,12,12,14,13,14,14,14,15,17,17,17,12,14,
  133883. 9,10,11,11,12,12,14,13,13,14,15,13,15,15,17,17,
  133884. 17,13,11,10, 8,11, 9,13,12,13,13,13,13,13,14,14,
  133885. 14,17,17,17,17,17,11,12,11,11,13,13,14,13,15,14,
  133886. 13,15,16,15,17,17,17,17,17,11,11,12, 8,13,12,14,
  133887. 13,17,14,15,14,15,14,17,17,17,17,17,15,15,12,12,
  133888. 12,12,13,14,14,14,15,14,17,14,17,17,17,17,17,16,
  133889. 17,12,12,13,12,13,13,14,14,14,14,14,14,17,17,17,
  133890. 17,17,17,17,14,14,13,12,13,13,15,15,14,13,15,17,
  133891. 17,17,17,17,17,17,17,13,14,13,13,13,13,14,15,15,
  133892. 15,14,15,17,17,17,17,17,17,17,16,15,13,14,13,13,
  133893. 14,14,15,14,14,16,17,17,17,17,17,17,17,16,16,13,
  133894. 14,13,13,14,14,15,14,15,14,
  133895. };
  133896. static float _vq_quantthresh__44c8_s_p9_1[] = {
  133897. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  133898. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  133899. 367.5, 416.5,
  133900. };
  133901. static long _vq_quantmap__44c8_s_p9_1[] = {
  133902. 17, 15, 13, 11, 9, 7, 5, 3,
  133903. 1, 0, 2, 4, 6, 8, 10, 12,
  133904. 14, 16, 18,
  133905. };
  133906. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_1 = {
  133907. _vq_quantthresh__44c8_s_p9_1,
  133908. _vq_quantmap__44c8_s_p9_1,
  133909. 19,
  133910. 19
  133911. };
  133912. static static_codebook _44c8_s_p9_1 = {
  133913. 2, 361,
  133914. _vq_lengthlist__44c8_s_p9_1,
  133915. 1, -518287360, 1622704128, 5, 0,
  133916. _vq_quantlist__44c8_s_p9_1,
  133917. NULL,
  133918. &_vq_auxt__44c8_s_p9_1,
  133919. NULL,
  133920. 0
  133921. };
  133922. static long _vq_quantlist__44c8_s_p9_2[] = {
  133923. 24,
  133924. 23,
  133925. 25,
  133926. 22,
  133927. 26,
  133928. 21,
  133929. 27,
  133930. 20,
  133931. 28,
  133932. 19,
  133933. 29,
  133934. 18,
  133935. 30,
  133936. 17,
  133937. 31,
  133938. 16,
  133939. 32,
  133940. 15,
  133941. 33,
  133942. 14,
  133943. 34,
  133944. 13,
  133945. 35,
  133946. 12,
  133947. 36,
  133948. 11,
  133949. 37,
  133950. 10,
  133951. 38,
  133952. 9,
  133953. 39,
  133954. 8,
  133955. 40,
  133956. 7,
  133957. 41,
  133958. 6,
  133959. 42,
  133960. 5,
  133961. 43,
  133962. 4,
  133963. 44,
  133964. 3,
  133965. 45,
  133966. 2,
  133967. 46,
  133968. 1,
  133969. 47,
  133970. 0,
  133971. 48,
  133972. };
  133973. static long _vq_lengthlist__44c8_s_p9_2[] = {
  133974. 2, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  133975. 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133976. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133977. 7,
  133978. };
  133979. static float _vq_quantthresh__44c8_s_p9_2[] = {
  133980. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  133981. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  133982. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133983. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133984. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  133985. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  133986. };
  133987. static long _vq_quantmap__44c8_s_p9_2[] = {
  133988. 47, 45, 43, 41, 39, 37, 35, 33,
  133989. 31, 29, 27, 25, 23, 21, 19, 17,
  133990. 15, 13, 11, 9, 7, 5, 3, 1,
  133991. 0, 2, 4, 6, 8, 10, 12, 14,
  133992. 16, 18, 20, 22, 24, 26, 28, 30,
  133993. 32, 34, 36, 38, 40, 42, 44, 46,
  133994. 48,
  133995. };
  133996. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_2 = {
  133997. _vq_quantthresh__44c8_s_p9_2,
  133998. _vq_quantmap__44c8_s_p9_2,
  133999. 49,
  134000. 49
  134001. };
  134002. static static_codebook _44c8_s_p9_2 = {
  134003. 1, 49,
  134004. _vq_lengthlist__44c8_s_p9_2,
  134005. 1, -526909440, 1611661312, 6, 0,
  134006. _vq_quantlist__44c8_s_p9_2,
  134007. NULL,
  134008. &_vq_auxt__44c8_s_p9_2,
  134009. NULL,
  134010. 0
  134011. };
  134012. static long _huff_lengthlist__44c8_s_short[] = {
  134013. 4,11,13,14,15,15,18,17,19,17, 5, 6, 8, 9,10,10,
  134014. 12,15,19,19, 6, 6, 6, 6, 8, 8,11,14,18,19, 8, 6,
  134015. 5, 4, 6, 7,10,13,16,17, 9, 7, 6, 5, 6, 7, 9,12,
  134016. 15,19,10, 8, 7, 6, 6, 6, 7, 9,13,15,12,10, 9, 8,
  134017. 7, 6, 4, 5,10,15,13,13,11, 8, 6, 6, 4, 2, 7,12,
  134018. 17,15,16,10, 8, 8, 7, 6, 9,12,19,18,17,13,11,10,
  134019. 10, 9,11,14,
  134020. };
  134021. static static_codebook _huff_book__44c8_s_short = {
  134022. 2, 100,
  134023. _huff_lengthlist__44c8_s_short,
  134024. 0, 0, 0, 0, 0,
  134025. NULL,
  134026. NULL,
  134027. NULL,
  134028. NULL,
  134029. 0
  134030. };
  134031. static long _huff_lengthlist__44c9_s_long[] = {
  134032. 3, 8,12,14,15,15,15,13,15,15, 6, 5, 8,10,12,12,
  134033. 13,12,14,13,10, 6, 5, 6, 8, 9,11,11,13,13,13, 8,
  134034. 5, 4, 5, 6, 8,10,11,13,14,10, 7, 5, 4, 5, 7, 9,
  134035. 11,12,13,11, 8, 6, 5, 4, 5, 7, 9,11,12,11,10, 8,
  134036. 7, 5, 4, 5, 9,10,13,13,11,10, 8, 6, 5, 4, 7, 9,
  134037. 15,14,13,12,10, 9, 8, 7, 8, 9,12,12,14,13,12,11,
  134038. 10, 9, 8, 9,
  134039. };
  134040. static static_codebook _huff_book__44c9_s_long = {
  134041. 2, 100,
  134042. _huff_lengthlist__44c9_s_long,
  134043. 0, 0, 0, 0, 0,
  134044. NULL,
  134045. NULL,
  134046. NULL,
  134047. NULL,
  134048. 0
  134049. };
  134050. static long _vq_quantlist__44c9_s_p1_0[] = {
  134051. 1,
  134052. 0,
  134053. 2,
  134054. };
  134055. static long _vq_lengthlist__44c9_s_p1_0[] = {
  134056. 1, 5, 5, 0, 5, 5, 0, 5, 5, 6, 8, 8, 0, 9, 8, 0,
  134057. 9, 8, 6, 8, 8, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  134058. 0, 0, 0, 0, 5, 8, 8, 0, 7, 7, 0, 8, 8, 5, 8, 8,
  134059. 0, 7, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  134060. 9, 8, 0, 8, 8, 0, 7, 7, 5, 8, 9, 0, 8, 8, 0, 7,
  134061. 7,
  134062. };
  134063. static float _vq_quantthresh__44c9_s_p1_0[] = {
  134064. -0.5, 0.5,
  134065. };
  134066. static long _vq_quantmap__44c9_s_p1_0[] = {
  134067. 1, 0, 2,
  134068. };
  134069. static encode_aux_threshmatch _vq_auxt__44c9_s_p1_0 = {
  134070. _vq_quantthresh__44c9_s_p1_0,
  134071. _vq_quantmap__44c9_s_p1_0,
  134072. 3,
  134073. 3
  134074. };
  134075. static static_codebook _44c9_s_p1_0 = {
  134076. 4, 81,
  134077. _vq_lengthlist__44c9_s_p1_0,
  134078. 1, -535822336, 1611661312, 2, 0,
  134079. _vq_quantlist__44c9_s_p1_0,
  134080. NULL,
  134081. &_vq_auxt__44c9_s_p1_0,
  134082. NULL,
  134083. 0
  134084. };
  134085. static long _vq_quantlist__44c9_s_p2_0[] = {
  134086. 2,
  134087. 1,
  134088. 3,
  134089. 0,
  134090. 4,
  134091. };
  134092. static long _vq_lengthlist__44c9_s_p2_0[] = {
  134093. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  134094. 7, 7, 9, 9, 0, 0, 0, 9, 9, 6, 7, 7, 9, 8, 0, 8,
  134095. 8, 9, 9, 0, 8, 7, 9, 9, 0, 9,10,10,10, 0, 0, 0,
  134096. 11,10, 6, 7, 7, 8, 9, 0, 8, 8, 9, 9, 0, 7, 8, 9,
  134097. 9, 0,10, 9,11,10, 0, 0, 0,10,10, 8, 9, 8,10,10,
  134098. 0,10,10,12,11, 0,10,10,11,11, 0,12,13,13,13, 0,
  134099. 0, 0,13,12, 8, 8, 9,10,10, 0,10,10,11,12, 0,10,
  134100. 10,11,11, 0,13,12,13,13, 0, 0, 0,13,13, 0, 0, 0,
  134101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134102. 0, 0, 0, 0, 0, 0, 6, 8, 7,10,10, 0, 7, 7,10, 9,
  134103. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,10,10, 6,
  134104. 7, 8,10,10, 0, 7, 7, 9,10, 0, 7, 7,10,10, 0, 9,
  134105. 9,10,10, 0, 0, 0,10,10, 8, 9, 9,11,11, 0,10,10,
  134106. 11,11, 0,10,10,11,11, 0,12,12,12,12, 0, 0, 0,12,
  134107. 12, 8, 9,10,11,11, 0, 9,10,11,11, 0,10,10,11,11,
  134108. 0,12,12,12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0,
  134109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134110. 0, 0, 0, 5, 8, 7,10,10, 0, 7, 7,10,10, 0, 7, 7,
  134111. 10, 9, 0, 9, 9,10,10, 0, 0, 0,10,10, 6, 7, 8,10,
  134112. 10, 0, 7, 7,10,10, 0, 7, 7, 9,10, 0, 9, 9,10,10,
  134113. 0, 0, 0,10,10, 8,10, 9,12,11, 0,10,10,12,11, 0,
  134114. 10, 9,11,11, 0,11,12,12,12, 0, 0, 0,12,12, 8, 9,
  134115. 10,11,12, 0,10,10,11,11, 0, 9,10,11,11, 0,12,11,
  134116. 12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134118. 7,10, 9,12,12, 0, 9, 9,12,11, 0, 9, 9,11,11, 0,
  134119. 10,10,12,11, 0, 0, 0,11,12, 7, 9,10,12,12, 0, 9,
  134120. 9,11,12, 0, 9, 9,11,11, 0,10,10,11,12, 0, 0, 0,
  134121. 11,11, 9,11,10,13,12, 0,10,10,12,12, 0,10,10,12,
  134122. 12, 0,11,11,12,12, 0, 0, 0,13,12, 9,10,11,12,13,
  134123. 0,10,10,12,12, 0,10,10,12,12, 0,11,12,12,12, 0,
  134124. 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  134129. 11,10,13,13, 0,10,10,12,12, 0,10,10,12,12, 0,11,
  134130. 12,12,12, 0, 0, 0,12,12, 9,10,11,13,13, 0,10,10,
  134131. 12,12, 0,10,10,12,12, 0,12,11,13,12, 0, 0, 0,12,
  134132. 12,
  134133. };
  134134. static float _vq_quantthresh__44c9_s_p2_0[] = {
  134135. -1.5, -0.5, 0.5, 1.5,
  134136. };
  134137. static long _vq_quantmap__44c9_s_p2_0[] = {
  134138. 3, 1, 0, 2, 4,
  134139. };
  134140. static encode_aux_threshmatch _vq_auxt__44c9_s_p2_0 = {
  134141. _vq_quantthresh__44c9_s_p2_0,
  134142. _vq_quantmap__44c9_s_p2_0,
  134143. 5,
  134144. 5
  134145. };
  134146. static static_codebook _44c9_s_p2_0 = {
  134147. 4, 625,
  134148. _vq_lengthlist__44c9_s_p2_0,
  134149. 1, -533725184, 1611661312, 3, 0,
  134150. _vq_quantlist__44c9_s_p2_0,
  134151. NULL,
  134152. &_vq_auxt__44c9_s_p2_0,
  134153. NULL,
  134154. 0
  134155. };
  134156. static long _vq_quantlist__44c9_s_p3_0[] = {
  134157. 4,
  134158. 3,
  134159. 5,
  134160. 2,
  134161. 6,
  134162. 1,
  134163. 7,
  134164. 0,
  134165. 8,
  134166. };
  134167. static long _vq_lengthlist__44c9_s_p3_0[] = {
  134168. 3, 4, 4, 5, 5, 6, 6, 8, 8, 0, 4, 4, 5, 5, 6, 7,
  134169. 8, 8, 0, 4, 4, 5, 5, 7, 7, 8, 8, 0, 5, 5, 6, 6,
  134170. 7, 7, 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0,
  134171. 7, 7, 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0,
  134172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134173. 0,
  134174. };
  134175. static float _vq_quantthresh__44c9_s_p3_0[] = {
  134176. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134177. };
  134178. static long _vq_quantmap__44c9_s_p3_0[] = {
  134179. 7, 5, 3, 1, 0, 2, 4, 6,
  134180. 8,
  134181. };
  134182. static encode_aux_threshmatch _vq_auxt__44c9_s_p3_0 = {
  134183. _vq_quantthresh__44c9_s_p3_0,
  134184. _vq_quantmap__44c9_s_p3_0,
  134185. 9,
  134186. 9
  134187. };
  134188. static static_codebook _44c9_s_p3_0 = {
  134189. 2, 81,
  134190. _vq_lengthlist__44c9_s_p3_0,
  134191. 1, -531628032, 1611661312, 4, 0,
  134192. _vq_quantlist__44c9_s_p3_0,
  134193. NULL,
  134194. &_vq_auxt__44c9_s_p3_0,
  134195. NULL,
  134196. 0
  134197. };
  134198. static long _vq_quantlist__44c9_s_p4_0[] = {
  134199. 8,
  134200. 7,
  134201. 9,
  134202. 6,
  134203. 10,
  134204. 5,
  134205. 11,
  134206. 4,
  134207. 12,
  134208. 3,
  134209. 13,
  134210. 2,
  134211. 14,
  134212. 1,
  134213. 15,
  134214. 0,
  134215. 16,
  134216. };
  134217. static long _vq_lengthlist__44c9_s_p4_0[] = {
  134218. 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,10,
  134219. 10, 0, 5, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  134220. 11,11, 0, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  134221. 10,11,11, 0, 6, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,
  134222. 11,11,11,12, 0, 0, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,
  134223. 10,11,11,12,12, 0, 0, 0, 7, 7, 7, 7, 9, 9, 9, 9,
  134224. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 7, 8, 9, 9, 9,
  134225. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  134226. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  134227. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  134228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134236. 0,
  134237. };
  134238. static float _vq_quantthresh__44c9_s_p4_0[] = {
  134239. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134240. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134241. };
  134242. static long _vq_quantmap__44c9_s_p4_0[] = {
  134243. 15, 13, 11, 9, 7, 5, 3, 1,
  134244. 0, 2, 4, 6, 8, 10, 12, 14,
  134245. 16,
  134246. };
  134247. static encode_aux_threshmatch _vq_auxt__44c9_s_p4_0 = {
  134248. _vq_quantthresh__44c9_s_p4_0,
  134249. _vq_quantmap__44c9_s_p4_0,
  134250. 17,
  134251. 17
  134252. };
  134253. static static_codebook _44c9_s_p4_0 = {
  134254. 2, 289,
  134255. _vq_lengthlist__44c9_s_p4_0,
  134256. 1, -529530880, 1611661312, 5, 0,
  134257. _vq_quantlist__44c9_s_p4_0,
  134258. NULL,
  134259. &_vq_auxt__44c9_s_p4_0,
  134260. NULL,
  134261. 0
  134262. };
  134263. static long _vq_quantlist__44c9_s_p5_0[] = {
  134264. 1,
  134265. 0,
  134266. 2,
  134267. };
  134268. static long _vq_lengthlist__44c9_s_p5_0[] = {
  134269. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6, 9,10,10,10,
  134270. 10, 9, 4, 6, 7, 9,10,10,10, 9,10, 5, 9, 9, 9,11,
  134271. 11,10,11,11, 7,10, 9,11,12,11,12,12,12, 7, 9,10,
  134272. 11,11,12,12,12,12, 6,10,10,10,12,12,10,12,11, 7,
  134273. 10,10,11,12,12,11,12,12, 7,10,10,11,12,12,12,12,
  134274. 12,
  134275. };
  134276. static float _vq_quantthresh__44c9_s_p5_0[] = {
  134277. -5.5, 5.5,
  134278. };
  134279. static long _vq_quantmap__44c9_s_p5_0[] = {
  134280. 1, 0, 2,
  134281. };
  134282. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_0 = {
  134283. _vq_quantthresh__44c9_s_p5_0,
  134284. _vq_quantmap__44c9_s_p5_0,
  134285. 3,
  134286. 3
  134287. };
  134288. static static_codebook _44c9_s_p5_0 = {
  134289. 4, 81,
  134290. _vq_lengthlist__44c9_s_p5_0,
  134291. 1, -529137664, 1618345984, 2, 0,
  134292. _vq_quantlist__44c9_s_p5_0,
  134293. NULL,
  134294. &_vq_auxt__44c9_s_p5_0,
  134295. NULL,
  134296. 0
  134297. };
  134298. static long _vq_quantlist__44c9_s_p5_1[] = {
  134299. 5,
  134300. 4,
  134301. 6,
  134302. 3,
  134303. 7,
  134304. 2,
  134305. 8,
  134306. 1,
  134307. 9,
  134308. 0,
  134309. 10,
  134310. };
  134311. static long _vq_lengthlist__44c9_s_p5_1[] = {
  134312. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7,11, 5, 5, 6, 6,
  134313. 7, 7, 7, 7, 8, 8,11, 5, 5, 6, 6, 7, 7, 7, 7, 8,
  134314. 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11, 6,
  134315. 6, 7, 7, 7, 8, 8, 8,11,11,11, 6, 6, 7, 7, 7, 8,
  134316. 8, 8,11,11,11, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11,
  134317. 7, 7, 7, 7, 7, 7, 8, 8,11,11,11,10,10, 7, 7, 7,
  134318. 7, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 7, 7,11,11,
  134319. 11,11,11, 7, 7, 7, 7, 7, 7,
  134320. };
  134321. static float _vq_quantthresh__44c9_s_p5_1[] = {
  134322. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134323. 3.5, 4.5,
  134324. };
  134325. static long _vq_quantmap__44c9_s_p5_1[] = {
  134326. 9, 7, 5, 3, 1, 0, 2, 4,
  134327. 6, 8, 10,
  134328. };
  134329. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_1 = {
  134330. _vq_quantthresh__44c9_s_p5_1,
  134331. _vq_quantmap__44c9_s_p5_1,
  134332. 11,
  134333. 11
  134334. };
  134335. static static_codebook _44c9_s_p5_1 = {
  134336. 2, 121,
  134337. _vq_lengthlist__44c9_s_p5_1,
  134338. 1, -531365888, 1611661312, 4, 0,
  134339. _vq_quantlist__44c9_s_p5_1,
  134340. NULL,
  134341. &_vq_auxt__44c9_s_p5_1,
  134342. NULL,
  134343. 0
  134344. };
  134345. static long _vq_quantlist__44c9_s_p6_0[] = {
  134346. 6,
  134347. 5,
  134348. 7,
  134349. 4,
  134350. 8,
  134351. 3,
  134352. 9,
  134353. 2,
  134354. 10,
  134355. 1,
  134356. 11,
  134357. 0,
  134358. 12,
  134359. };
  134360. static long _vq_lengthlist__44c9_s_p6_0[] = {
  134361. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 5, 4, 4,
  134362. 6, 6, 8, 8, 9, 9, 9, 9,10,10, 6, 4, 4, 6, 6, 8,
  134363. 8, 9, 9, 9, 9,10,10, 0, 6, 6, 7, 7, 8, 8, 9, 9,
  134364. 10,10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  134365. 11, 0,10,10, 8, 8, 9, 9,10,10,11,11,12,12, 0,11,
  134366. 11, 8, 8, 9, 9,10,10,11,11,12,12, 0, 0, 0, 0, 0,
  134367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134371. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134372. };
  134373. static float _vq_quantthresh__44c9_s_p6_0[] = {
  134374. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  134375. 12.5, 17.5, 22.5, 27.5,
  134376. };
  134377. static long _vq_quantmap__44c9_s_p6_0[] = {
  134378. 11, 9, 7, 5, 3, 1, 0, 2,
  134379. 4, 6, 8, 10, 12,
  134380. };
  134381. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_0 = {
  134382. _vq_quantthresh__44c9_s_p6_0,
  134383. _vq_quantmap__44c9_s_p6_0,
  134384. 13,
  134385. 13
  134386. };
  134387. static static_codebook _44c9_s_p6_0 = {
  134388. 2, 169,
  134389. _vq_lengthlist__44c9_s_p6_0,
  134390. 1, -526516224, 1616117760, 4, 0,
  134391. _vq_quantlist__44c9_s_p6_0,
  134392. NULL,
  134393. &_vq_auxt__44c9_s_p6_0,
  134394. NULL,
  134395. 0
  134396. };
  134397. static long _vq_quantlist__44c9_s_p6_1[] = {
  134398. 2,
  134399. 1,
  134400. 3,
  134401. 0,
  134402. 4,
  134403. };
  134404. static long _vq_lengthlist__44c9_s_p6_1[] = {
  134405. 4, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5,
  134406. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  134407. };
  134408. static float _vq_quantthresh__44c9_s_p6_1[] = {
  134409. -1.5, -0.5, 0.5, 1.5,
  134410. };
  134411. static long _vq_quantmap__44c9_s_p6_1[] = {
  134412. 3, 1, 0, 2, 4,
  134413. };
  134414. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_1 = {
  134415. _vq_quantthresh__44c9_s_p6_1,
  134416. _vq_quantmap__44c9_s_p6_1,
  134417. 5,
  134418. 5
  134419. };
  134420. static static_codebook _44c9_s_p6_1 = {
  134421. 2, 25,
  134422. _vq_lengthlist__44c9_s_p6_1,
  134423. 1, -533725184, 1611661312, 3, 0,
  134424. _vq_quantlist__44c9_s_p6_1,
  134425. NULL,
  134426. &_vq_auxt__44c9_s_p6_1,
  134427. NULL,
  134428. 0
  134429. };
  134430. static long _vq_quantlist__44c9_s_p7_0[] = {
  134431. 6,
  134432. 5,
  134433. 7,
  134434. 4,
  134435. 8,
  134436. 3,
  134437. 9,
  134438. 2,
  134439. 10,
  134440. 1,
  134441. 11,
  134442. 0,
  134443. 12,
  134444. };
  134445. static long _vq_lengthlist__44c9_s_p7_0[] = {
  134446. 2, 4, 4, 6, 6, 7, 7, 8, 8,10,10,11,11, 6, 4, 4,
  134447. 6, 6, 8, 8, 9, 9,10,10,12,12, 6, 4, 5, 6, 6, 8,
  134448. 8, 9, 9,10,10,12,12,20, 6, 6, 6, 6, 8, 8, 9,10,
  134449. 11,11,12,12,20, 6, 6, 6, 6, 8, 8,10,10,11,11,12,
  134450. 12,20,10,10, 7, 7, 9, 9,10,10,11,11,12,12,20,11,
  134451. 11, 7, 7, 9, 9,10,10,11,11,12,12,20,20,20, 9, 9,
  134452. 9, 9,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,11,
  134453. 11,12,12,13,13,20,20,20,13,13,10,10,11,11,12,13,
  134454. 13,13,20,20,20,13,13,10,10,11,11,12,13,13,13,20,
  134455. 20,20,20,19,12,12,12,12,13,13,14,15,19,19,19,19,
  134456. 19,12,12,12,12,13,13,14,14,
  134457. };
  134458. static float _vq_quantthresh__44c9_s_p7_0[] = {
  134459. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  134460. 27.5, 38.5, 49.5, 60.5,
  134461. };
  134462. static long _vq_quantmap__44c9_s_p7_0[] = {
  134463. 11, 9, 7, 5, 3, 1, 0, 2,
  134464. 4, 6, 8, 10, 12,
  134465. };
  134466. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_0 = {
  134467. _vq_quantthresh__44c9_s_p7_0,
  134468. _vq_quantmap__44c9_s_p7_0,
  134469. 13,
  134470. 13
  134471. };
  134472. static static_codebook _44c9_s_p7_0 = {
  134473. 2, 169,
  134474. _vq_lengthlist__44c9_s_p7_0,
  134475. 1, -523206656, 1618345984, 4, 0,
  134476. _vq_quantlist__44c9_s_p7_0,
  134477. NULL,
  134478. &_vq_auxt__44c9_s_p7_0,
  134479. NULL,
  134480. 0
  134481. };
  134482. static long _vq_quantlist__44c9_s_p7_1[] = {
  134483. 5,
  134484. 4,
  134485. 6,
  134486. 3,
  134487. 7,
  134488. 2,
  134489. 8,
  134490. 1,
  134491. 9,
  134492. 0,
  134493. 10,
  134494. };
  134495. static long _vq_lengthlist__44c9_s_p7_1[] = {
  134496. 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,
  134497. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  134498. 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 6,
  134499. 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134500. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  134501. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  134502. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  134503. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134504. };
  134505. static float _vq_quantthresh__44c9_s_p7_1[] = {
  134506. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134507. 3.5, 4.5,
  134508. };
  134509. static long _vq_quantmap__44c9_s_p7_1[] = {
  134510. 9, 7, 5, 3, 1, 0, 2, 4,
  134511. 6, 8, 10,
  134512. };
  134513. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_1 = {
  134514. _vq_quantthresh__44c9_s_p7_1,
  134515. _vq_quantmap__44c9_s_p7_1,
  134516. 11,
  134517. 11
  134518. };
  134519. static static_codebook _44c9_s_p7_1 = {
  134520. 2, 121,
  134521. _vq_lengthlist__44c9_s_p7_1,
  134522. 1, -531365888, 1611661312, 4, 0,
  134523. _vq_quantlist__44c9_s_p7_1,
  134524. NULL,
  134525. &_vq_auxt__44c9_s_p7_1,
  134526. NULL,
  134527. 0
  134528. };
  134529. static long _vq_quantlist__44c9_s_p8_0[] = {
  134530. 7,
  134531. 6,
  134532. 8,
  134533. 5,
  134534. 9,
  134535. 4,
  134536. 10,
  134537. 3,
  134538. 11,
  134539. 2,
  134540. 12,
  134541. 1,
  134542. 13,
  134543. 0,
  134544. 14,
  134545. };
  134546. static long _vq_lengthlist__44c9_s_p8_0[] = {
  134547. 1, 4, 4, 7, 6, 8, 8, 8, 8, 9, 9,10,10,11,10, 6,
  134548. 5, 5, 7, 7, 9, 9, 8, 9,10,10,11,11,12,12, 6, 5,
  134549. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,21, 7, 8,
  134550. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,21, 8, 8, 8,
  134551. 8, 9, 9, 9, 9,10,10,11,11,12,12,21,11,12, 9, 9,
  134552. 10,10,10,10,10,11,11,12,12,12,21,12,12, 9, 8,10,
  134553. 10,10,10,11,11,12,12,13,13,21,21,21, 9, 9, 9, 9,
  134554. 11,11,11,11,12,12,12,13,21,20,20, 9, 9, 9, 9,10,
  134555. 11,11,11,12,12,13,13,20,20,20,13,13,10,10,11,11,
  134556. 12,12,13,13,13,13,20,20,20,13,13,10,10,11,11,12,
  134557. 12,13,13,13,13,20,20,20,20,20,12,12,12,12,12,12,
  134558. 13,13,14,14,20,20,20,20,20,12,12,12,11,13,12,13,
  134559. 13,14,14,20,20,20,20,20,15,16,13,12,13,13,14,13,
  134560. 14,14,20,20,20,20,20,16,15,12,12,13,12,14,13,14,
  134561. 14,
  134562. };
  134563. static float _vq_quantthresh__44c9_s_p8_0[] = {
  134564. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  134565. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  134566. };
  134567. static long _vq_quantmap__44c9_s_p8_0[] = {
  134568. 13, 11, 9, 7, 5, 3, 1, 0,
  134569. 2, 4, 6, 8, 10, 12, 14,
  134570. };
  134571. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_0 = {
  134572. _vq_quantthresh__44c9_s_p8_0,
  134573. _vq_quantmap__44c9_s_p8_0,
  134574. 15,
  134575. 15
  134576. };
  134577. static static_codebook _44c9_s_p8_0 = {
  134578. 2, 225,
  134579. _vq_lengthlist__44c9_s_p8_0,
  134580. 1, -520986624, 1620377600, 4, 0,
  134581. _vq_quantlist__44c9_s_p8_0,
  134582. NULL,
  134583. &_vq_auxt__44c9_s_p8_0,
  134584. NULL,
  134585. 0
  134586. };
  134587. static long _vq_quantlist__44c9_s_p8_1[] = {
  134588. 10,
  134589. 9,
  134590. 11,
  134591. 8,
  134592. 12,
  134593. 7,
  134594. 13,
  134595. 6,
  134596. 14,
  134597. 5,
  134598. 15,
  134599. 4,
  134600. 16,
  134601. 3,
  134602. 17,
  134603. 2,
  134604. 18,
  134605. 1,
  134606. 19,
  134607. 0,
  134608. 20,
  134609. };
  134610. static long _vq_lengthlist__44c9_s_p8_1[] = {
  134611. 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  134612. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  134613. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  134614. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  134615. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134616. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  134617. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8,
  134618. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  134619. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134620. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134621. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  134622. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  134623. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134624. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134625. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  134626. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,
  134627. 10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,
  134628. 9,10,10,10,10,10,10,10, 9, 9, 9,10,10,10,10,10,
  134629. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10, 9, 9,10,
  134630. 9,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  134631. 10,10,10,10, 9, 9,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  134632. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  134633. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  134634. 10,10, 9, 9,10, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  134635. 10,10,10,10,10, 9, 9,10,10, 9, 9,10, 9, 9, 9,10,
  134636. 10,10,10,10,10,10,10,10,10,10, 9, 9,10, 9, 9, 9,
  134637. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9,
  134638. 9, 9, 9,10, 9, 9, 9, 9, 9,
  134639. };
  134640. static float _vq_quantthresh__44c9_s_p8_1[] = {
  134641. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  134642. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  134643. 6.5, 7.5, 8.5, 9.5,
  134644. };
  134645. static long _vq_quantmap__44c9_s_p8_1[] = {
  134646. 19, 17, 15, 13, 11, 9, 7, 5,
  134647. 3, 1, 0, 2, 4, 6, 8, 10,
  134648. 12, 14, 16, 18, 20,
  134649. };
  134650. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_1 = {
  134651. _vq_quantthresh__44c9_s_p8_1,
  134652. _vq_quantmap__44c9_s_p8_1,
  134653. 21,
  134654. 21
  134655. };
  134656. static static_codebook _44c9_s_p8_1 = {
  134657. 2, 441,
  134658. _vq_lengthlist__44c9_s_p8_1,
  134659. 1, -529268736, 1611661312, 5, 0,
  134660. _vq_quantlist__44c9_s_p8_1,
  134661. NULL,
  134662. &_vq_auxt__44c9_s_p8_1,
  134663. NULL,
  134664. 0
  134665. };
  134666. static long _vq_quantlist__44c9_s_p9_0[] = {
  134667. 9,
  134668. 8,
  134669. 10,
  134670. 7,
  134671. 11,
  134672. 6,
  134673. 12,
  134674. 5,
  134675. 13,
  134676. 4,
  134677. 14,
  134678. 3,
  134679. 15,
  134680. 2,
  134681. 16,
  134682. 1,
  134683. 17,
  134684. 0,
  134685. 18,
  134686. };
  134687. static long _vq_lengthlist__44c9_s_p9_0[] = {
  134688. 1, 4, 3,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134689. 12,12,12, 4, 5, 6,12,12,12,12,12,12,12,12,12,12,
  134690. 12,12,12,12,12,12, 4, 6, 6,12,12,12,12,12,12,12,
  134691. 12,12,12,12,12,12,12,12,12,12,12,11,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,12,12,12,12,12,12,
  134702. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134703. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134704. 12,12,12,12,12,12,12,12,12,12,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,11,11,11,11,11,11,11,
  134708. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134709. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134710. 11,11,11,11,11,11,11,11,11,
  134711. };
  134712. static float _vq_quantthresh__44c9_s_p9_0[] = {
  134713. -7913.5, -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5,
  134714. -465.5, 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  134715. 6982.5, 7913.5,
  134716. };
  134717. static long _vq_quantmap__44c9_s_p9_0[] = {
  134718. 17, 15, 13, 11, 9, 7, 5, 3,
  134719. 1, 0, 2, 4, 6, 8, 10, 12,
  134720. 14, 16, 18,
  134721. };
  134722. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_0 = {
  134723. _vq_quantthresh__44c9_s_p9_0,
  134724. _vq_quantmap__44c9_s_p9_0,
  134725. 19,
  134726. 19
  134727. };
  134728. static static_codebook _44c9_s_p9_0 = {
  134729. 2, 361,
  134730. _vq_lengthlist__44c9_s_p9_0,
  134731. 1, -508535424, 1631393792, 5, 0,
  134732. _vq_quantlist__44c9_s_p9_0,
  134733. NULL,
  134734. &_vq_auxt__44c9_s_p9_0,
  134735. NULL,
  134736. 0
  134737. };
  134738. static long _vq_quantlist__44c9_s_p9_1[] = {
  134739. 9,
  134740. 8,
  134741. 10,
  134742. 7,
  134743. 11,
  134744. 6,
  134745. 12,
  134746. 5,
  134747. 13,
  134748. 4,
  134749. 14,
  134750. 3,
  134751. 15,
  134752. 2,
  134753. 16,
  134754. 1,
  134755. 17,
  134756. 0,
  134757. 18,
  134758. };
  134759. static long _vq_lengthlist__44c9_s_p9_1[] = {
  134760. 1, 4, 4, 7, 7, 7, 7, 8, 7, 9, 8, 9, 9,10,10,11,
  134761. 11,11,11, 6, 5, 5, 8, 8, 9, 9, 9, 8,10, 9,11,10,
  134762. 12,12,13,12,13,13, 5, 5, 5, 8, 8, 9, 9, 9, 9,10,
  134763. 10,11,11,12,12,13,12,13,13,17, 8, 8, 9, 9, 9, 9,
  134764. 9, 9,10,10,12,11,13,12,13,13,13,13,18, 8, 8, 9,
  134765. 9, 9, 9, 9, 9,11,11,12,12,13,13,13,13,13,13,17,
  134766. 13,12, 9, 9,10,10,10,10,11,11,12,12,12,13,13,13,
  134767. 14,14,18,13,12, 9, 9,10,10,10,10,11,11,12,12,13,
  134768. 13,13,14,14,14,17,18,18,10,10,10,10,11,11,11,12,
  134769. 12,12,14,13,14,13,13,14,18,18,18,10, 9,10, 9,11,
  134770. 11,12,12,12,12,13,13,15,14,14,14,18,18,16,13,14,
  134771. 10,11,11,11,12,13,13,13,13,14,13,13,14,14,18,18,
  134772. 18,14,12,11, 9,11,10,13,12,13,13,13,14,14,14,13,
  134773. 14,18,18,17,18,18,11,12,12,12,13,13,14,13,14,14,
  134774. 13,14,14,14,18,18,18,18,17,12,10,12, 9,13,11,13,
  134775. 14,14,14,14,14,15,14,18,18,17,17,18,14,15,12,13,
  134776. 13,13,14,13,14,14,15,14,15,14,18,17,18,18,18,15,
  134777. 15,12,10,14,10,14,14,13,13,14,14,14,14,18,16,18,
  134778. 18,18,18,17,14,14,13,14,14,13,13,14,14,14,15,15,
  134779. 18,18,18,18,17,17,17,14,14,14,12,14,13,14,14,15,
  134780. 14,15,14,18,18,18,18,18,18,18,17,16,13,13,13,14,
  134781. 14,14,14,15,16,15,18,18,18,18,18,18,18,17,17,13,
  134782. 13,13,13,14,13,14,15,15,15,
  134783. };
  134784. static float _vq_quantthresh__44c9_s_p9_1[] = {
  134785. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  134786. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  134787. 367.5, 416.5,
  134788. };
  134789. static long _vq_quantmap__44c9_s_p9_1[] = {
  134790. 17, 15, 13, 11, 9, 7, 5, 3,
  134791. 1, 0, 2, 4, 6, 8, 10, 12,
  134792. 14, 16, 18,
  134793. };
  134794. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_1 = {
  134795. _vq_quantthresh__44c9_s_p9_1,
  134796. _vq_quantmap__44c9_s_p9_1,
  134797. 19,
  134798. 19
  134799. };
  134800. static static_codebook _44c9_s_p9_1 = {
  134801. 2, 361,
  134802. _vq_lengthlist__44c9_s_p9_1,
  134803. 1, -518287360, 1622704128, 5, 0,
  134804. _vq_quantlist__44c9_s_p9_1,
  134805. NULL,
  134806. &_vq_auxt__44c9_s_p9_1,
  134807. NULL,
  134808. 0
  134809. };
  134810. static long _vq_quantlist__44c9_s_p9_2[] = {
  134811. 24,
  134812. 23,
  134813. 25,
  134814. 22,
  134815. 26,
  134816. 21,
  134817. 27,
  134818. 20,
  134819. 28,
  134820. 19,
  134821. 29,
  134822. 18,
  134823. 30,
  134824. 17,
  134825. 31,
  134826. 16,
  134827. 32,
  134828. 15,
  134829. 33,
  134830. 14,
  134831. 34,
  134832. 13,
  134833. 35,
  134834. 12,
  134835. 36,
  134836. 11,
  134837. 37,
  134838. 10,
  134839. 38,
  134840. 9,
  134841. 39,
  134842. 8,
  134843. 40,
  134844. 7,
  134845. 41,
  134846. 6,
  134847. 42,
  134848. 5,
  134849. 43,
  134850. 4,
  134851. 44,
  134852. 3,
  134853. 45,
  134854. 2,
  134855. 46,
  134856. 1,
  134857. 47,
  134858. 0,
  134859. 48,
  134860. };
  134861. static long _vq_lengthlist__44c9_s_p9_2[] = {
  134862. 2, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  134863. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  134864. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134865. 7,
  134866. };
  134867. static float _vq_quantthresh__44c9_s_p9_2[] = {
  134868. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  134869. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  134870. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134871. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134872. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  134873. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  134874. };
  134875. static long _vq_quantmap__44c9_s_p9_2[] = {
  134876. 47, 45, 43, 41, 39, 37, 35, 33,
  134877. 31, 29, 27, 25, 23, 21, 19, 17,
  134878. 15, 13, 11, 9, 7, 5, 3, 1,
  134879. 0, 2, 4, 6, 8, 10, 12, 14,
  134880. 16, 18, 20, 22, 24, 26, 28, 30,
  134881. 32, 34, 36, 38, 40, 42, 44, 46,
  134882. 48,
  134883. };
  134884. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_2 = {
  134885. _vq_quantthresh__44c9_s_p9_2,
  134886. _vq_quantmap__44c9_s_p9_2,
  134887. 49,
  134888. 49
  134889. };
  134890. static static_codebook _44c9_s_p9_2 = {
  134891. 1, 49,
  134892. _vq_lengthlist__44c9_s_p9_2,
  134893. 1, -526909440, 1611661312, 6, 0,
  134894. _vq_quantlist__44c9_s_p9_2,
  134895. NULL,
  134896. &_vq_auxt__44c9_s_p9_2,
  134897. NULL,
  134898. 0
  134899. };
  134900. static long _huff_lengthlist__44c9_s_short[] = {
  134901. 5,13,18,16,17,17,19,18,19,19, 5, 7,10,11,12,12,
  134902. 13,16,17,18, 6, 6, 7, 7, 9, 9,10,14,17,19, 8, 7,
  134903. 6, 5, 6, 7, 9,12,19,17, 8, 7, 7, 6, 5, 6, 8,11,
  134904. 15,19, 9, 8, 7, 6, 5, 5, 6, 8,13,15,11,10, 8, 8,
  134905. 7, 5, 4, 4,10,14,12,13,11, 9, 7, 6, 4, 2, 6,12,
  134906. 18,16,16,13, 8, 7, 7, 5, 8,13,16,17,18,15,11, 9,
  134907. 9, 8,10,13,
  134908. };
  134909. static static_codebook _huff_book__44c9_s_short = {
  134910. 2, 100,
  134911. _huff_lengthlist__44c9_s_short,
  134912. 0, 0, 0, 0, 0,
  134913. NULL,
  134914. NULL,
  134915. NULL,
  134916. NULL,
  134917. 0
  134918. };
  134919. static long _huff_lengthlist__44c0_s_long[] = {
  134920. 5, 4, 8, 9, 8, 9,10,12,15, 4, 1, 5, 5, 6, 8,11,
  134921. 12,12, 8, 5, 8, 9, 9,11,13,12,12, 9, 5, 8, 5, 7,
  134922. 9,12,13,13, 8, 6, 8, 7, 7, 9,11,11,11, 9, 7, 9,
  134923. 7, 7, 7, 7,10,12,10,10,11, 9, 8, 7, 7, 9,11,11,
  134924. 12,13,12,11, 9, 8, 9,11,13,16,16,15,15,12,10,11,
  134925. 12,
  134926. };
  134927. static static_codebook _huff_book__44c0_s_long = {
  134928. 2, 81,
  134929. _huff_lengthlist__44c0_s_long,
  134930. 0, 0, 0, 0, 0,
  134931. NULL,
  134932. NULL,
  134933. NULL,
  134934. NULL,
  134935. 0
  134936. };
  134937. static long _vq_quantlist__44c0_s_p1_0[] = {
  134938. 1,
  134939. 0,
  134940. 2,
  134941. };
  134942. static long _vq_lengthlist__44c0_s_p1_0[] = {
  134943. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  134944. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134948. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  134949. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134953. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  134954. 0, 0, 0, 0, 7, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0,
  134986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  134989. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  134990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  134994. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  134995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  134999. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  135000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135034. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135035. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135039. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  135040. 0, 0, 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  135041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135044. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,11,
  135045. 0, 0, 0, 0, 0, 0, 9,11,10, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135353. 0,
  135354. };
  135355. static float _vq_quantthresh__44c0_s_p1_0[] = {
  135356. -0.5, 0.5,
  135357. };
  135358. static long _vq_quantmap__44c0_s_p1_0[] = {
  135359. 1, 0, 2,
  135360. };
  135361. static encode_aux_threshmatch _vq_auxt__44c0_s_p1_0 = {
  135362. _vq_quantthresh__44c0_s_p1_0,
  135363. _vq_quantmap__44c0_s_p1_0,
  135364. 3,
  135365. 3
  135366. };
  135367. static static_codebook _44c0_s_p1_0 = {
  135368. 8, 6561,
  135369. _vq_lengthlist__44c0_s_p1_0,
  135370. 1, -535822336, 1611661312, 2, 0,
  135371. _vq_quantlist__44c0_s_p1_0,
  135372. NULL,
  135373. &_vq_auxt__44c0_s_p1_0,
  135374. NULL,
  135375. 0
  135376. };
  135377. static long _vq_quantlist__44c0_s_p2_0[] = {
  135378. 2,
  135379. 1,
  135380. 3,
  135381. 0,
  135382. 4,
  135383. };
  135384. static long _vq_lengthlist__44c0_s_p2_0[] = {
  135385. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 6, 0, 0,
  135387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135388. 0, 0, 4, 5, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  135390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135391. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  135392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135424. 0,
  135425. };
  135426. static float _vq_quantthresh__44c0_s_p2_0[] = {
  135427. -1.5, -0.5, 0.5, 1.5,
  135428. };
  135429. static long _vq_quantmap__44c0_s_p2_0[] = {
  135430. 3, 1, 0, 2, 4,
  135431. };
  135432. static encode_aux_threshmatch _vq_auxt__44c0_s_p2_0 = {
  135433. _vq_quantthresh__44c0_s_p2_0,
  135434. _vq_quantmap__44c0_s_p2_0,
  135435. 5,
  135436. 5
  135437. };
  135438. static static_codebook _44c0_s_p2_0 = {
  135439. 4, 625,
  135440. _vq_lengthlist__44c0_s_p2_0,
  135441. 1, -533725184, 1611661312, 3, 0,
  135442. _vq_quantlist__44c0_s_p2_0,
  135443. NULL,
  135444. &_vq_auxt__44c0_s_p2_0,
  135445. NULL,
  135446. 0
  135447. };
  135448. static long _vq_quantlist__44c0_s_p3_0[] = {
  135449. 4,
  135450. 3,
  135451. 5,
  135452. 2,
  135453. 6,
  135454. 1,
  135455. 7,
  135456. 0,
  135457. 8,
  135458. };
  135459. static long _vq_lengthlist__44c0_s_p3_0[] = {
  135460. 1, 3, 2, 8, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  135461. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  135462. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  135463. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  135464. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135465. 0,
  135466. };
  135467. static float _vq_quantthresh__44c0_s_p3_0[] = {
  135468. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  135469. };
  135470. static long _vq_quantmap__44c0_s_p3_0[] = {
  135471. 7, 5, 3, 1, 0, 2, 4, 6,
  135472. 8,
  135473. };
  135474. static encode_aux_threshmatch _vq_auxt__44c0_s_p3_0 = {
  135475. _vq_quantthresh__44c0_s_p3_0,
  135476. _vq_quantmap__44c0_s_p3_0,
  135477. 9,
  135478. 9
  135479. };
  135480. static static_codebook _44c0_s_p3_0 = {
  135481. 2, 81,
  135482. _vq_lengthlist__44c0_s_p3_0,
  135483. 1, -531628032, 1611661312, 4, 0,
  135484. _vq_quantlist__44c0_s_p3_0,
  135485. NULL,
  135486. &_vq_auxt__44c0_s_p3_0,
  135487. NULL,
  135488. 0
  135489. };
  135490. static long _vq_quantlist__44c0_s_p4_0[] = {
  135491. 4,
  135492. 3,
  135493. 5,
  135494. 2,
  135495. 6,
  135496. 1,
  135497. 7,
  135498. 0,
  135499. 8,
  135500. };
  135501. static long _vq_lengthlist__44c0_s_p4_0[] = {
  135502. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  135503. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  135504. 7, 8, 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0,
  135505. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 9, 8, 8,10,10, 0,
  135506. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  135507. 10,
  135508. };
  135509. static float _vq_quantthresh__44c0_s_p4_0[] = {
  135510. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  135511. };
  135512. static long _vq_quantmap__44c0_s_p4_0[] = {
  135513. 7, 5, 3, 1, 0, 2, 4, 6,
  135514. 8,
  135515. };
  135516. static encode_aux_threshmatch _vq_auxt__44c0_s_p4_0 = {
  135517. _vq_quantthresh__44c0_s_p4_0,
  135518. _vq_quantmap__44c0_s_p4_0,
  135519. 9,
  135520. 9
  135521. };
  135522. static static_codebook _44c0_s_p4_0 = {
  135523. 2, 81,
  135524. _vq_lengthlist__44c0_s_p4_0,
  135525. 1, -531628032, 1611661312, 4, 0,
  135526. _vq_quantlist__44c0_s_p4_0,
  135527. NULL,
  135528. &_vq_auxt__44c0_s_p4_0,
  135529. NULL,
  135530. 0
  135531. };
  135532. static long _vq_quantlist__44c0_s_p5_0[] = {
  135533. 8,
  135534. 7,
  135535. 9,
  135536. 6,
  135537. 10,
  135538. 5,
  135539. 11,
  135540. 4,
  135541. 12,
  135542. 3,
  135543. 13,
  135544. 2,
  135545. 14,
  135546. 1,
  135547. 15,
  135548. 0,
  135549. 16,
  135550. };
  135551. static long _vq_lengthlist__44c0_s_p5_0[] = {
  135552. 1, 4, 3, 6, 6, 8, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  135553. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9, 9,10,10,10,
  135554. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  135555. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  135556. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  135557. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  135558. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  135559. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  135560. 10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  135561. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  135562. 10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  135563. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  135564. 10,10,11,11,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  135565. 0, 0, 0,11,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  135566. 0, 0, 0, 0,11,11,12,11,12,12,12,12,13,13, 0, 0,
  135567. 0, 0, 0, 0, 0,11,11,11,12,12,12,12,13,13,13, 0,
  135568. 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,13,14,14,
  135569. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  135570. 14,
  135571. };
  135572. static float _vq_quantthresh__44c0_s_p5_0[] = {
  135573. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135574. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135575. };
  135576. static long _vq_quantmap__44c0_s_p5_0[] = {
  135577. 15, 13, 11, 9, 7, 5, 3, 1,
  135578. 0, 2, 4, 6, 8, 10, 12, 14,
  135579. 16,
  135580. };
  135581. static encode_aux_threshmatch _vq_auxt__44c0_s_p5_0 = {
  135582. _vq_quantthresh__44c0_s_p5_0,
  135583. _vq_quantmap__44c0_s_p5_0,
  135584. 17,
  135585. 17
  135586. };
  135587. static static_codebook _44c0_s_p5_0 = {
  135588. 2, 289,
  135589. _vq_lengthlist__44c0_s_p5_0,
  135590. 1, -529530880, 1611661312, 5, 0,
  135591. _vq_quantlist__44c0_s_p5_0,
  135592. NULL,
  135593. &_vq_auxt__44c0_s_p5_0,
  135594. NULL,
  135595. 0
  135596. };
  135597. static long _vq_quantlist__44c0_s_p6_0[] = {
  135598. 1,
  135599. 0,
  135600. 2,
  135601. };
  135602. static long _vq_lengthlist__44c0_s_p6_0[] = {
  135603. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  135604. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  135605. 11,12,10,11, 6, 9, 9,11,10,11,11,10,10, 6, 9, 9,
  135606. 11,10,11,11,10,10, 7,11,10,12,11,11,11,11,11, 7,
  135607. 9, 9,10,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  135608. 10,
  135609. };
  135610. static float _vq_quantthresh__44c0_s_p6_0[] = {
  135611. -5.5, 5.5,
  135612. };
  135613. static long _vq_quantmap__44c0_s_p6_0[] = {
  135614. 1, 0, 2,
  135615. };
  135616. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_0 = {
  135617. _vq_quantthresh__44c0_s_p6_0,
  135618. _vq_quantmap__44c0_s_p6_0,
  135619. 3,
  135620. 3
  135621. };
  135622. static static_codebook _44c0_s_p6_0 = {
  135623. 4, 81,
  135624. _vq_lengthlist__44c0_s_p6_0,
  135625. 1, -529137664, 1618345984, 2, 0,
  135626. _vq_quantlist__44c0_s_p6_0,
  135627. NULL,
  135628. &_vq_auxt__44c0_s_p6_0,
  135629. NULL,
  135630. 0
  135631. };
  135632. static long _vq_quantlist__44c0_s_p6_1[] = {
  135633. 5,
  135634. 4,
  135635. 6,
  135636. 3,
  135637. 7,
  135638. 2,
  135639. 8,
  135640. 1,
  135641. 9,
  135642. 0,
  135643. 10,
  135644. };
  135645. static long _vq_lengthlist__44c0_s_p6_1[] = {
  135646. 2, 3, 3, 6, 6, 7, 7, 7, 7, 7, 8,10,10,10, 6, 6,
  135647. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  135648. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  135649. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  135650. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  135651. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  135652. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  135653. 10,10,10, 8, 8, 8, 8, 8, 8,
  135654. };
  135655. static float _vq_quantthresh__44c0_s_p6_1[] = {
  135656. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135657. 3.5, 4.5,
  135658. };
  135659. static long _vq_quantmap__44c0_s_p6_1[] = {
  135660. 9, 7, 5, 3, 1, 0, 2, 4,
  135661. 6, 8, 10,
  135662. };
  135663. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_1 = {
  135664. _vq_quantthresh__44c0_s_p6_1,
  135665. _vq_quantmap__44c0_s_p6_1,
  135666. 11,
  135667. 11
  135668. };
  135669. static static_codebook _44c0_s_p6_1 = {
  135670. 2, 121,
  135671. _vq_lengthlist__44c0_s_p6_1,
  135672. 1, -531365888, 1611661312, 4, 0,
  135673. _vq_quantlist__44c0_s_p6_1,
  135674. NULL,
  135675. &_vq_auxt__44c0_s_p6_1,
  135676. NULL,
  135677. 0
  135678. };
  135679. static long _vq_quantlist__44c0_s_p7_0[] = {
  135680. 6,
  135681. 5,
  135682. 7,
  135683. 4,
  135684. 8,
  135685. 3,
  135686. 9,
  135687. 2,
  135688. 10,
  135689. 1,
  135690. 11,
  135691. 0,
  135692. 12,
  135693. };
  135694. static long _vq_lengthlist__44c0_s_p7_0[] = {
  135695. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  135696. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  135697. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  135698. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  135699. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  135700. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  135701. 10,10,11,11,11,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  135702. 11,11,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  135703. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  135704. 0, 0, 0, 0,11,11,11,11,13,12,13,13, 0, 0, 0, 0,
  135705. 0,12,12,11,11,12,12,13,13,
  135706. };
  135707. static float _vq_quantthresh__44c0_s_p7_0[] = {
  135708. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  135709. 12.5, 17.5, 22.5, 27.5,
  135710. };
  135711. static long _vq_quantmap__44c0_s_p7_0[] = {
  135712. 11, 9, 7, 5, 3, 1, 0, 2,
  135713. 4, 6, 8, 10, 12,
  135714. };
  135715. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_0 = {
  135716. _vq_quantthresh__44c0_s_p7_0,
  135717. _vq_quantmap__44c0_s_p7_0,
  135718. 13,
  135719. 13
  135720. };
  135721. static static_codebook _44c0_s_p7_0 = {
  135722. 2, 169,
  135723. _vq_lengthlist__44c0_s_p7_0,
  135724. 1, -526516224, 1616117760, 4, 0,
  135725. _vq_quantlist__44c0_s_p7_0,
  135726. NULL,
  135727. &_vq_auxt__44c0_s_p7_0,
  135728. NULL,
  135729. 0
  135730. };
  135731. static long _vq_quantlist__44c0_s_p7_1[] = {
  135732. 2,
  135733. 1,
  135734. 3,
  135735. 0,
  135736. 4,
  135737. };
  135738. static long _vq_lengthlist__44c0_s_p7_1[] = {
  135739. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  135740. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  135741. };
  135742. static float _vq_quantthresh__44c0_s_p7_1[] = {
  135743. -1.5, -0.5, 0.5, 1.5,
  135744. };
  135745. static long _vq_quantmap__44c0_s_p7_1[] = {
  135746. 3, 1, 0, 2, 4,
  135747. };
  135748. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_1 = {
  135749. _vq_quantthresh__44c0_s_p7_1,
  135750. _vq_quantmap__44c0_s_p7_1,
  135751. 5,
  135752. 5
  135753. };
  135754. static static_codebook _44c0_s_p7_1 = {
  135755. 2, 25,
  135756. _vq_lengthlist__44c0_s_p7_1,
  135757. 1, -533725184, 1611661312, 3, 0,
  135758. _vq_quantlist__44c0_s_p7_1,
  135759. NULL,
  135760. &_vq_auxt__44c0_s_p7_1,
  135761. NULL,
  135762. 0
  135763. };
  135764. static long _vq_quantlist__44c0_s_p8_0[] = {
  135765. 2,
  135766. 1,
  135767. 3,
  135768. 0,
  135769. 4,
  135770. };
  135771. static long _vq_lengthlist__44c0_s_p8_0[] = {
  135772. 1, 5, 5,10,10, 6, 9, 8,10,10, 6,10, 9,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,10,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, 8,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,10,10,10,10,10,10,10,10,
  135782. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135783. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135784. 10,10,10,10,10,10,10,10,11,11,11,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,10,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,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135809. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135810. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135811. 11,
  135812. };
  135813. static float _vq_quantthresh__44c0_s_p8_0[] = {
  135814. -331.5, -110.5, 110.5, 331.5,
  135815. };
  135816. static long _vq_quantmap__44c0_s_p8_0[] = {
  135817. 3, 1, 0, 2, 4,
  135818. };
  135819. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_0 = {
  135820. _vq_quantthresh__44c0_s_p8_0,
  135821. _vq_quantmap__44c0_s_p8_0,
  135822. 5,
  135823. 5
  135824. };
  135825. static static_codebook _44c0_s_p8_0 = {
  135826. 4, 625,
  135827. _vq_lengthlist__44c0_s_p8_0,
  135828. 1, -518283264, 1627103232, 3, 0,
  135829. _vq_quantlist__44c0_s_p8_0,
  135830. NULL,
  135831. &_vq_auxt__44c0_s_p8_0,
  135832. NULL,
  135833. 0
  135834. };
  135835. static long _vq_quantlist__44c0_s_p8_1[] = {
  135836. 6,
  135837. 5,
  135838. 7,
  135839. 4,
  135840. 8,
  135841. 3,
  135842. 9,
  135843. 2,
  135844. 10,
  135845. 1,
  135846. 11,
  135847. 0,
  135848. 12,
  135849. };
  135850. static long _vq_lengthlist__44c0_s_p8_1[] = {
  135851. 1, 4, 4, 6, 6, 7, 7, 9, 9,11,12,13,12, 6, 5, 5,
  135852. 7, 7, 8, 8,10, 9,12,12,12,12, 6, 5, 5, 7, 7, 8,
  135853. 8,10, 9,12,11,11,13,16, 7, 7, 8, 8, 9, 9,10,10,
  135854. 12,12,13,12,16, 7, 7, 8, 7, 9, 9,10,10,11,12,12,
  135855. 13,16,10,10, 8, 8,10,10,11,12,12,12,13,13,16,11,
  135856. 10, 8, 7,11,10,11,11,12,11,13,13,16,16,16,10,10,
  135857. 10,10,11,11,13,12,13,13,16,16,16,11, 9,11, 9,15,
  135858. 13,12,13,13,13,16,16,16,15,13,11,11,12,13,12,12,
  135859. 14,13,16,16,16,14,13,11,11,13,12,14,13,13,13,16,
  135860. 16,16,16,16,13,13,13,12,14,13,14,14,16,16,16,16,
  135861. 16,13,13,12,12,14,14,15,13,
  135862. };
  135863. static float _vq_quantthresh__44c0_s_p8_1[] = {
  135864. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  135865. 42.5, 59.5, 76.5, 93.5,
  135866. };
  135867. static long _vq_quantmap__44c0_s_p8_1[] = {
  135868. 11, 9, 7, 5, 3, 1, 0, 2,
  135869. 4, 6, 8, 10, 12,
  135870. };
  135871. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_1 = {
  135872. _vq_quantthresh__44c0_s_p8_1,
  135873. _vq_quantmap__44c0_s_p8_1,
  135874. 13,
  135875. 13
  135876. };
  135877. static static_codebook _44c0_s_p8_1 = {
  135878. 2, 169,
  135879. _vq_lengthlist__44c0_s_p8_1,
  135880. 1, -522616832, 1620115456, 4, 0,
  135881. _vq_quantlist__44c0_s_p8_1,
  135882. NULL,
  135883. &_vq_auxt__44c0_s_p8_1,
  135884. NULL,
  135885. 0
  135886. };
  135887. static long _vq_quantlist__44c0_s_p8_2[] = {
  135888. 8,
  135889. 7,
  135890. 9,
  135891. 6,
  135892. 10,
  135893. 5,
  135894. 11,
  135895. 4,
  135896. 12,
  135897. 3,
  135898. 13,
  135899. 2,
  135900. 14,
  135901. 1,
  135902. 15,
  135903. 0,
  135904. 16,
  135905. };
  135906. static long _vq_lengthlist__44c0_s_p8_2[] = {
  135907. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  135908. 8,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  135909. 9, 9,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  135910. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  135911. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  135912. 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 8, 9, 9,
  135913. 9, 9, 9,10, 9,10,10,10,10, 7, 7, 8, 8, 9, 9, 9,
  135914. 9, 9, 9,10, 9,10,10,10,10,10, 8, 8, 8, 9, 9, 9,
  135915. 9, 9, 9, 9,10,10,10, 9,11,10,10,10,10, 8, 8, 9,
  135916. 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,11,11, 9, 9,
  135917. 9, 9, 9, 9, 9, 9,10, 9, 9,10,11,10,10,11,11, 9,
  135918. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  135919. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,10,11,
  135920. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  135921. 11,11,11,11, 9,10, 9,10, 9, 9, 9, 9,10, 9,10,11,
  135922. 10,11,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9,10,11,
  135923. 11,10,11,11,10,11,10,10,10, 9, 9, 9, 9,10, 9, 9,
  135924. 10,11,10,11,11,11,11,10,11,10,10, 9,10, 9, 9, 9,
  135925. 10,
  135926. };
  135927. static float _vq_quantthresh__44c0_s_p8_2[] = {
  135928. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135929. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135930. };
  135931. static long _vq_quantmap__44c0_s_p8_2[] = {
  135932. 15, 13, 11, 9, 7, 5, 3, 1,
  135933. 0, 2, 4, 6, 8, 10, 12, 14,
  135934. 16,
  135935. };
  135936. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_2 = {
  135937. _vq_quantthresh__44c0_s_p8_2,
  135938. _vq_quantmap__44c0_s_p8_2,
  135939. 17,
  135940. 17
  135941. };
  135942. static static_codebook _44c0_s_p8_2 = {
  135943. 2, 289,
  135944. _vq_lengthlist__44c0_s_p8_2,
  135945. 1, -529530880, 1611661312, 5, 0,
  135946. _vq_quantlist__44c0_s_p8_2,
  135947. NULL,
  135948. &_vq_auxt__44c0_s_p8_2,
  135949. NULL,
  135950. 0
  135951. };
  135952. static long _huff_lengthlist__44c0_s_short[] = {
  135953. 9, 8,12,11,12,13,14,14,16, 6, 1, 5, 6, 6, 9,12,
  135954. 14,17, 9, 4, 5, 9, 7, 9,13,15,16, 8, 5, 8, 6, 8,
  135955. 10,13,17,17, 9, 6, 7, 7, 8, 9,13,15,17,11, 8, 9,
  135956. 9, 9,10,12,16,16,13, 7, 8, 7, 7, 9,12,14,15,13,
  135957. 6, 7, 5, 5, 7,10,13,13,14, 7, 8, 5, 6, 7, 9,10,
  135958. 12,
  135959. };
  135960. static static_codebook _huff_book__44c0_s_short = {
  135961. 2, 81,
  135962. _huff_lengthlist__44c0_s_short,
  135963. 0, 0, 0, 0, 0,
  135964. NULL,
  135965. NULL,
  135966. NULL,
  135967. NULL,
  135968. 0
  135969. };
  135970. static long _huff_lengthlist__44c0_sm_long[] = {
  135971. 5, 4, 9,10, 9,10,11,12,13, 4, 1, 5, 7, 7, 9,11,
  135972. 12,14, 8, 5, 7, 9, 8,10,13,13,13,10, 7, 9, 4, 6,
  135973. 7,10,12,14, 9, 6, 7, 6, 6, 7,10,12,12, 9, 8, 9,
  135974. 7, 6, 7, 8,11,12,11,11,11, 9, 8, 7, 8,10,12,12,
  135975. 13,14,12,11, 9, 9, 9,12,12,17,17,15,16,12,10,11,
  135976. 13,
  135977. };
  135978. static static_codebook _huff_book__44c0_sm_long = {
  135979. 2, 81,
  135980. _huff_lengthlist__44c0_sm_long,
  135981. 0, 0, 0, 0, 0,
  135982. NULL,
  135983. NULL,
  135984. NULL,
  135985. NULL,
  135986. 0
  135987. };
  135988. static long _vq_quantlist__44c0_sm_p1_0[] = {
  135989. 1,
  135990. 0,
  135991. 2,
  135992. };
  135993. static long _vq_lengthlist__44c0_sm_p1_0[] = {
  135994. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  135995. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135997. 0, 0, 0, 0, 0, 0, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  136000. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136002. 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  136005. 0, 0, 0, 0, 7, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0,
  136037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  136040. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  136041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  136045. 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  136046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136050. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  136051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136085. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136086. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136090. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  136091. 0, 0, 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  136092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136095. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  136096. 0, 0, 0, 0, 0, 0, 9,10,10, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136404. 0,
  136405. };
  136406. static float _vq_quantthresh__44c0_sm_p1_0[] = {
  136407. -0.5, 0.5,
  136408. };
  136409. static long _vq_quantmap__44c0_sm_p1_0[] = {
  136410. 1, 0, 2,
  136411. };
  136412. static encode_aux_threshmatch _vq_auxt__44c0_sm_p1_0 = {
  136413. _vq_quantthresh__44c0_sm_p1_0,
  136414. _vq_quantmap__44c0_sm_p1_0,
  136415. 3,
  136416. 3
  136417. };
  136418. static static_codebook _44c0_sm_p1_0 = {
  136419. 8, 6561,
  136420. _vq_lengthlist__44c0_sm_p1_0,
  136421. 1, -535822336, 1611661312, 2, 0,
  136422. _vq_quantlist__44c0_sm_p1_0,
  136423. NULL,
  136424. &_vq_auxt__44c0_sm_p1_0,
  136425. NULL,
  136426. 0
  136427. };
  136428. static long _vq_quantlist__44c0_sm_p2_0[] = {
  136429. 2,
  136430. 1,
  136431. 3,
  136432. 0,
  136433. 4,
  136434. };
  136435. static long _vq_lengthlist__44c0_sm_p2_0[] = {
  136436. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  136438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136439. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  136441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136442. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  136443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136475. 0,
  136476. };
  136477. static float _vq_quantthresh__44c0_sm_p2_0[] = {
  136478. -1.5, -0.5, 0.5, 1.5,
  136479. };
  136480. static long _vq_quantmap__44c0_sm_p2_0[] = {
  136481. 3, 1, 0, 2, 4,
  136482. };
  136483. static encode_aux_threshmatch _vq_auxt__44c0_sm_p2_0 = {
  136484. _vq_quantthresh__44c0_sm_p2_0,
  136485. _vq_quantmap__44c0_sm_p2_0,
  136486. 5,
  136487. 5
  136488. };
  136489. static static_codebook _44c0_sm_p2_0 = {
  136490. 4, 625,
  136491. _vq_lengthlist__44c0_sm_p2_0,
  136492. 1, -533725184, 1611661312, 3, 0,
  136493. _vq_quantlist__44c0_sm_p2_0,
  136494. NULL,
  136495. &_vq_auxt__44c0_sm_p2_0,
  136496. NULL,
  136497. 0
  136498. };
  136499. static long _vq_quantlist__44c0_sm_p3_0[] = {
  136500. 4,
  136501. 3,
  136502. 5,
  136503. 2,
  136504. 6,
  136505. 1,
  136506. 7,
  136507. 0,
  136508. 8,
  136509. };
  136510. static long _vq_lengthlist__44c0_sm_p3_0[] = {
  136511. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 4, 7, 7, 0, 0,
  136512. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  136513. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  136514. 9,10, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  136515. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136516. 0,
  136517. };
  136518. static float _vq_quantthresh__44c0_sm_p3_0[] = {
  136519. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136520. };
  136521. static long _vq_quantmap__44c0_sm_p3_0[] = {
  136522. 7, 5, 3, 1, 0, 2, 4, 6,
  136523. 8,
  136524. };
  136525. static encode_aux_threshmatch _vq_auxt__44c0_sm_p3_0 = {
  136526. _vq_quantthresh__44c0_sm_p3_0,
  136527. _vq_quantmap__44c0_sm_p3_0,
  136528. 9,
  136529. 9
  136530. };
  136531. static static_codebook _44c0_sm_p3_0 = {
  136532. 2, 81,
  136533. _vq_lengthlist__44c0_sm_p3_0,
  136534. 1, -531628032, 1611661312, 4, 0,
  136535. _vq_quantlist__44c0_sm_p3_0,
  136536. NULL,
  136537. &_vq_auxt__44c0_sm_p3_0,
  136538. NULL,
  136539. 0
  136540. };
  136541. static long _vq_quantlist__44c0_sm_p4_0[] = {
  136542. 4,
  136543. 3,
  136544. 5,
  136545. 2,
  136546. 6,
  136547. 1,
  136548. 7,
  136549. 0,
  136550. 8,
  136551. };
  136552. static long _vq_lengthlist__44c0_sm_p4_0[] = {
  136553. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  136554. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  136555. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  136556. 9, 9, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  136557. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  136558. 11,
  136559. };
  136560. static float _vq_quantthresh__44c0_sm_p4_0[] = {
  136561. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136562. };
  136563. static long _vq_quantmap__44c0_sm_p4_0[] = {
  136564. 7, 5, 3, 1, 0, 2, 4, 6,
  136565. 8,
  136566. };
  136567. static encode_aux_threshmatch _vq_auxt__44c0_sm_p4_0 = {
  136568. _vq_quantthresh__44c0_sm_p4_0,
  136569. _vq_quantmap__44c0_sm_p4_0,
  136570. 9,
  136571. 9
  136572. };
  136573. static static_codebook _44c0_sm_p4_0 = {
  136574. 2, 81,
  136575. _vq_lengthlist__44c0_sm_p4_0,
  136576. 1, -531628032, 1611661312, 4, 0,
  136577. _vq_quantlist__44c0_sm_p4_0,
  136578. NULL,
  136579. &_vq_auxt__44c0_sm_p4_0,
  136580. NULL,
  136581. 0
  136582. };
  136583. static long _vq_quantlist__44c0_sm_p5_0[] = {
  136584. 8,
  136585. 7,
  136586. 9,
  136587. 6,
  136588. 10,
  136589. 5,
  136590. 11,
  136591. 4,
  136592. 12,
  136593. 3,
  136594. 13,
  136595. 2,
  136596. 14,
  136597. 1,
  136598. 15,
  136599. 0,
  136600. 16,
  136601. };
  136602. static long _vq_lengthlist__44c0_sm_p5_0[] = {
  136603. 1, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 9, 9,10,10,11,
  136604. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  136605. 11,11, 0, 5, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  136606. 11,11,11, 0, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  136607. 11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,
  136608. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  136609. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  136610. 10,11,11,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  136611. 10,10,11,11,12,12,12,13, 0, 0, 0, 0, 0, 9, 9,10,
  136612. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  136613. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  136614. 9,10,10,11,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  136615. 10,10,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0,
  136616. 0, 0, 0,10,10,11,11,12,12,12,13,13,13, 0, 0, 0,
  136617. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  136618. 0, 0, 0, 0, 0,11,11,12,11,12,12,13,13,13,13, 0,
  136619. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  136620. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  136621. 14,
  136622. };
  136623. static float _vq_quantthresh__44c0_sm_p5_0[] = {
  136624. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136625. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136626. };
  136627. static long _vq_quantmap__44c0_sm_p5_0[] = {
  136628. 15, 13, 11, 9, 7, 5, 3, 1,
  136629. 0, 2, 4, 6, 8, 10, 12, 14,
  136630. 16,
  136631. };
  136632. static encode_aux_threshmatch _vq_auxt__44c0_sm_p5_0 = {
  136633. _vq_quantthresh__44c0_sm_p5_0,
  136634. _vq_quantmap__44c0_sm_p5_0,
  136635. 17,
  136636. 17
  136637. };
  136638. static static_codebook _44c0_sm_p5_0 = {
  136639. 2, 289,
  136640. _vq_lengthlist__44c0_sm_p5_0,
  136641. 1, -529530880, 1611661312, 5, 0,
  136642. _vq_quantlist__44c0_sm_p5_0,
  136643. NULL,
  136644. &_vq_auxt__44c0_sm_p5_0,
  136645. NULL,
  136646. 0
  136647. };
  136648. static long _vq_quantlist__44c0_sm_p6_0[] = {
  136649. 1,
  136650. 0,
  136651. 2,
  136652. };
  136653. static long _vq_lengthlist__44c0_sm_p6_0[] = {
  136654. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  136655. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  136656. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  136657. 11,10,11,11,10,10, 7,11,10,11,11,11,11,11,11, 6,
  136658. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  136659. 11,
  136660. };
  136661. static float _vq_quantthresh__44c0_sm_p6_0[] = {
  136662. -5.5, 5.5,
  136663. };
  136664. static long _vq_quantmap__44c0_sm_p6_0[] = {
  136665. 1, 0, 2,
  136666. };
  136667. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_0 = {
  136668. _vq_quantthresh__44c0_sm_p6_0,
  136669. _vq_quantmap__44c0_sm_p6_0,
  136670. 3,
  136671. 3
  136672. };
  136673. static static_codebook _44c0_sm_p6_0 = {
  136674. 4, 81,
  136675. _vq_lengthlist__44c0_sm_p6_0,
  136676. 1, -529137664, 1618345984, 2, 0,
  136677. _vq_quantlist__44c0_sm_p6_0,
  136678. NULL,
  136679. &_vq_auxt__44c0_sm_p6_0,
  136680. NULL,
  136681. 0
  136682. };
  136683. static long _vq_quantlist__44c0_sm_p6_1[] = {
  136684. 5,
  136685. 4,
  136686. 6,
  136687. 3,
  136688. 7,
  136689. 2,
  136690. 8,
  136691. 1,
  136692. 9,
  136693. 0,
  136694. 10,
  136695. };
  136696. static long _vq_lengthlist__44c0_sm_p6_1[] = {
  136697. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 8, 9, 5, 5, 6, 6,
  136698. 7, 7, 8, 8, 8, 8, 9, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  136699. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  136700. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  136701. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  136702. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  136703. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  136704. 10,10,10, 8, 8, 8, 8, 8, 8,
  136705. };
  136706. static float _vq_quantthresh__44c0_sm_p6_1[] = {
  136707. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  136708. 3.5, 4.5,
  136709. };
  136710. static long _vq_quantmap__44c0_sm_p6_1[] = {
  136711. 9, 7, 5, 3, 1, 0, 2, 4,
  136712. 6, 8, 10,
  136713. };
  136714. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_1 = {
  136715. _vq_quantthresh__44c0_sm_p6_1,
  136716. _vq_quantmap__44c0_sm_p6_1,
  136717. 11,
  136718. 11
  136719. };
  136720. static static_codebook _44c0_sm_p6_1 = {
  136721. 2, 121,
  136722. _vq_lengthlist__44c0_sm_p6_1,
  136723. 1, -531365888, 1611661312, 4, 0,
  136724. _vq_quantlist__44c0_sm_p6_1,
  136725. NULL,
  136726. &_vq_auxt__44c0_sm_p6_1,
  136727. NULL,
  136728. 0
  136729. };
  136730. static long _vq_quantlist__44c0_sm_p7_0[] = {
  136731. 6,
  136732. 5,
  136733. 7,
  136734. 4,
  136735. 8,
  136736. 3,
  136737. 9,
  136738. 2,
  136739. 10,
  136740. 1,
  136741. 11,
  136742. 0,
  136743. 12,
  136744. };
  136745. static long _vq_lengthlist__44c0_sm_p7_0[] = {
  136746. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  136747. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  136748. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  136749. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  136750. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  136751. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0, 9,10,
  136752. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  136753. 11,12,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  136754. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  136755. 0, 0, 0, 0,11,12,11,11,13,12,13,13, 0, 0, 0, 0,
  136756. 0,12,12,11,11,13,12,14,14,
  136757. };
  136758. static float _vq_quantthresh__44c0_sm_p7_0[] = {
  136759. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  136760. 12.5, 17.5, 22.5, 27.5,
  136761. };
  136762. static long _vq_quantmap__44c0_sm_p7_0[] = {
  136763. 11, 9, 7, 5, 3, 1, 0, 2,
  136764. 4, 6, 8, 10, 12,
  136765. };
  136766. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_0 = {
  136767. _vq_quantthresh__44c0_sm_p7_0,
  136768. _vq_quantmap__44c0_sm_p7_0,
  136769. 13,
  136770. 13
  136771. };
  136772. static static_codebook _44c0_sm_p7_0 = {
  136773. 2, 169,
  136774. _vq_lengthlist__44c0_sm_p7_0,
  136775. 1, -526516224, 1616117760, 4, 0,
  136776. _vq_quantlist__44c0_sm_p7_0,
  136777. NULL,
  136778. &_vq_auxt__44c0_sm_p7_0,
  136779. NULL,
  136780. 0
  136781. };
  136782. static long _vq_quantlist__44c0_sm_p7_1[] = {
  136783. 2,
  136784. 1,
  136785. 3,
  136786. 0,
  136787. 4,
  136788. };
  136789. static long _vq_lengthlist__44c0_sm_p7_1[] = {
  136790. 2, 4, 4, 4, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  136791. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  136792. };
  136793. static float _vq_quantthresh__44c0_sm_p7_1[] = {
  136794. -1.5, -0.5, 0.5, 1.5,
  136795. };
  136796. static long _vq_quantmap__44c0_sm_p7_1[] = {
  136797. 3, 1, 0, 2, 4,
  136798. };
  136799. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_1 = {
  136800. _vq_quantthresh__44c0_sm_p7_1,
  136801. _vq_quantmap__44c0_sm_p7_1,
  136802. 5,
  136803. 5
  136804. };
  136805. static static_codebook _44c0_sm_p7_1 = {
  136806. 2, 25,
  136807. _vq_lengthlist__44c0_sm_p7_1,
  136808. 1, -533725184, 1611661312, 3, 0,
  136809. _vq_quantlist__44c0_sm_p7_1,
  136810. NULL,
  136811. &_vq_auxt__44c0_sm_p7_1,
  136812. NULL,
  136813. 0
  136814. };
  136815. static long _vq_quantlist__44c0_sm_p8_0[] = {
  136816. 4,
  136817. 3,
  136818. 5,
  136819. 2,
  136820. 6,
  136821. 1,
  136822. 7,
  136823. 0,
  136824. 8,
  136825. };
  136826. static long _vq_lengthlist__44c0_sm_p8_0[] = {
  136827. 1, 3, 3,11,11,11,11,11,11, 3, 7, 6,11,11,11,11,
  136828. 11,11, 4, 8, 7,11,11,11,11,11,11,11,11,11,11,11,
  136829. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136830. 11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  136831. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  136832. 12,
  136833. };
  136834. static float _vq_quantthresh__44c0_sm_p8_0[] = {
  136835. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  136836. };
  136837. static long _vq_quantmap__44c0_sm_p8_0[] = {
  136838. 7, 5, 3, 1, 0, 2, 4, 6,
  136839. 8,
  136840. };
  136841. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_0 = {
  136842. _vq_quantthresh__44c0_sm_p8_0,
  136843. _vq_quantmap__44c0_sm_p8_0,
  136844. 9,
  136845. 9
  136846. };
  136847. static static_codebook _44c0_sm_p8_0 = {
  136848. 2, 81,
  136849. _vq_lengthlist__44c0_sm_p8_0,
  136850. 1, -516186112, 1627103232, 4, 0,
  136851. _vq_quantlist__44c0_sm_p8_0,
  136852. NULL,
  136853. &_vq_auxt__44c0_sm_p8_0,
  136854. NULL,
  136855. 0
  136856. };
  136857. static long _vq_quantlist__44c0_sm_p8_1[] = {
  136858. 6,
  136859. 5,
  136860. 7,
  136861. 4,
  136862. 8,
  136863. 3,
  136864. 9,
  136865. 2,
  136866. 10,
  136867. 1,
  136868. 11,
  136869. 0,
  136870. 12,
  136871. };
  136872. static long _vq_lengthlist__44c0_sm_p8_1[] = {
  136873. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  136874. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  136875. 8,10,10,12,11,12,12,17, 7, 7, 8, 8, 9, 9,10,10,
  136876. 12,12,13,13,18, 7, 7, 8, 7, 9, 9,10,10,12,12,12,
  136877. 13,19,10,10, 8, 8,10,10,11,11,12,12,13,14,19,11,
  136878. 10, 8, 7,10,10,11,11,12,12,13,12,19,19,19,10,10,
  136879. 10,10,11,11,12,12,13,13,19,19,19,11, 9,11, 9,14,
  136880. 12,13,12,13,13,19,20,18,13,14,11,11,12,12,13,13,
  136881. 14,13,20,20,20,15,13,11,10,13,11,13,13,14,13,20,
  136882. 20,20,20,20,13,14,12,12,13,13,13,13,20,20,20,20,
  136883. 20,13,13,12,12,16,13,15,13,
  136884. };
  136885. static float _vq_quantthresh__44c0_sm_p8_1[] = {
  136886. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  136887. 42.5, 59.5, 76.5, 93.5,
  136888. };
  136889. static long _vq_quantmap__44c0_sm_p8_1[] = {
  136890. 11, 9, 7, 5, 3, 1, 0, 2,
  136891. 4, 6, 8, 10, 12,
  136892. };
  136893. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_1 = {
  136894. _vq_quantthresh__44c0_sm_p8_1,
  136895. _vq_quantmap__44c0_sm_p8_1,
  136896. 13,
  136897. 13
  136898. };
  136899. static static_codebook _44c0_sm_p8_1 = {
  136900. 2, 169,
  136901. _vq_lengthlist__44c0_sm_p8_1,
  136902. 1, -522616832, 1620115456, 4, 0,
  136903. _vq_quantlist__44c0_sm_p8_1,
  136904. NULL,
  136905. &_vq_auxt__44c0_sm_p8_1,
  136906. NULL,
  136907. 0
  136908. };
  136909. static long _vq_quantlist__44c0_sm_p8_2[] = {
  136910. 8,
  136911. 7,
  136912. 9,
  136913. 6,
  136914. 10,
  136915. 5,
  136916. 11,
  136917. 4,
  136918. 12,
  136919. 3,
  136920. 13,
  136921. 2,
  136922. 14,
  136923. 1,
  136924. 15,
  136925. 0,
  136926. 16,
  136927. };
  136928. static long _vq_lengthlist__44c0_sm_p8_2[] = {
  136929. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  136930. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  136931. 9, 9,10, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  136932. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  136933. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  136934. 9,10, 9, 9,10,10,10,11, 8, 8, 8, 8, 9, 9, 9, 9,
  136935. 9, 9, 9,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  136936. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  136937. 9, 9, 9, 9, 9, 9,10,10,10,10,10,11,11, 8, 8, 9,
  136938. 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,11,11,11, 9, 9,
  136939. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,10,11,11, 9,
  136940. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  136941. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,11,11,
  136942. 11,11,11, 9, 9,10, 9, 9, 9, 9, 9, 9, 9,10,11,10,
  136943. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  136944. 11,11,11,11,11, 9,10, 9, 9, 9, 9, 9, 9, 9, 9,11,
  136945. 11,10,11,11,11,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  136946. 10,11,10,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  136947. 9,
  136948. };
  136949. static float _vq_quantthresh__44c0_sm_p8_2[] = {
  136950. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136951. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136952. };
  136953. static long _vq_quantmap__44c0_sm_p8_2[] = {
  136954. 15, 13, 11, 9, 7, 5, 3, 1,
  136955. 0, 2, 4, 6, 8, 10, 12, 14,
  136956. 16,
  136957. };
  136958. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_2 = {
  136959. _vq_quantthresh__44c0_sm_p8_2,
  136960. _vq_quantmap__44c0_sm_p8_2,
  136961. 17,
  136962. 17
  136963. };
  136964. static static_codebook _44c0_sm_p8_2 = {
  136965. 2, 289,
  136966. _vq_lengthlist__44c0_sm_p8_2,
  136967. 1, -529530880, 1611661312, 5, 0,
  136968. _vq_quantlist__44c0_sm_p8_2,
  136969. NULL,
  136970. &_vq_auxt__44c0_sm_p8_2,
  136971. NULL,
  136972. 0
  136973. };
  136974. static long _huff_lengthlist__44c0_sm_short[] = {
  136975. 6, 6,12,13,13,14,16,17,17, 4, 2, 5, 8, 7, 9,12,
  136976. 15,15, 9, 4, 5, 9, 7, 9,12,16,18,11, 6, 7, 4, 6,
  136977. 8,11,14,18,10, 5, 6, 5, 5, 7,10,14,17,10, 5, 7,
  136978. 7, 6, 7,10,13,16,11, 5, 7, 7, 7, 8,10,12,15,13,
  136979. 6, 7, 5, 5, 7, 9,12,13,16, 8, 9, 6, 6, 7, 9,10,
  136980. 12,
  136981. };
  136982. static static_codebook _huff_book__44c0_sm_short = {
  136983. 2, 81,
  136984. _huff_lengthlist__44c0_sm_short,
  136985. 0, 0, 0, 0, 0,
  136986. NULL,
  136987. NULL,
  136988. NULL,
  136989. NULL,
  136990. 0
  136991. };
  136992. static long _huff_lengthlist__44c1_s_long[] = {
  136993. 5, 5, 9,10, 9, 9,10,11,12, 5, 1, 5, 6, 6, 7,10,
  136994. 12,14, 9, 5, 6, 8, 8,10,12,14,14,10, 5, 8, 5, 6,
  136995. 8,11,13,14, 9, 5, 7, 6, 6, 8,10,12,11, 9, 7, 9,
  136996. 7, 6, 6, 7,10,10,10, 9,12, 9, 8, 7, 7,10,12,11,
  136997. 11,13,12,10, 9, 8, 9,11,11,14,15,15,13,11, 9, 9,
  136998. 11,
  136999. };
  137000. static static_codebook _huff_book__44c1_s_long = {
  137001. 2, 81,
  137002. _huff_lengthlist__44c1_s_long,
  137003. 0, 0, 0, 0, 0,
  137004. NULL,
  137005. NULL,
  137006. NULL,
  137007. NULL,
  137008. 0
  137009. };
  137010. static long _vq_quantlist__44c1_s_p1_0[] = {
  137011. 1,
  137012. 0,
  137013. 2,
  137014. };
  137015. static long _vq_lengthlist__44c1_s_p1_0[] = {
  137016. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 6, 0, 0, 0, 0,
  137017. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137021. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  137022. 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137026. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  137027. 0, 0, 0, 0, 7, 8, 8, 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, 0, 0, 0, 0, 0, 0, 0,
  137059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  137062. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  137063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  137067. 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  137068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  137072. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  137073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137107. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  137108. 0, 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137112. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8,10, 9, 0,
  137113. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  137114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137117. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  137118. 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137426. 0,
  137427. };
  137428. static float _vq_quantthresh__44c1_s_p1_0[] = {
  137429. -0.5, 0.5,
  137430. };
  137431. static long _vq_quantmap__44c1_s_p1_0[] = {
  137432. 1, 0, 2,
  137433. };
  137434. static encode_aux_threshmatch _vq_auxt__44c1_s_p1_0 = {
  137435. _vq_quantthresh__44c1_s_p1_0,
  137436. _vq_quantmap__44c1_s_p1_0,
  137437. 3,
  137438. 3
  137439. };
  137440. static static_codebook _44c1_s_p1_0 = {
  137441. 8, 6561,
  137442. _vq_lengthlist__44c1_s_p1_0,
  137443. 1, -535822336, 1611661312, 2, 0,
  137444. _vq_quantlist__44c1_s_p1_0,
  137445. NULL,
  137446. &_vq_auxt__44c1_s_p1_0,
  137447. NULL,
  137448. 0
  137449. };
  137450. static long _vq_quantlist__44c1_s_p2_0[] = {
  137451. 2,
  137452. 1,
  137453. 3,
  137454. 0,
  137455. 4,
  137456. };
  137457. static long _vq_lengthlist__44c1_s_p2_0[] = {
  137458. 2, 3, 4, 6, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  137460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137461. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  137463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137464. 0, 0, 0, 0, 6, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  137465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137497. 0,
  137498. };
  137499. static float _vq_quantthresh__44c1_s_p2_0[] = {
  137500. -1.5, -0.5, 0.5, 1.5,
  137501. };
  137502. static long _vq_quantmap__44c1_s_p2_0[] = {
  137503. 3, 1, 0, 2, 4,
  137504. };
  137505. static encode_aux_threshmatch _vq_auxt__44c1_s_p2_0 = {
  137506. _vq_quantthresh__44c1_s_p2_0,
  137507. _vq_quantmap__44c1_s_p2_0,
  137508. 5,
  137509. 5
  137510. };
  137511. static static_codebook _44c1_s_p2_0 = {
  137512. 4, 625,
  137513. _vq_lengthlist__44c1_s_p2_0,
  137514. 1, -533725184, 1611661312, 3, 0,
  137515. _vq_quantlist__44c1_s_p2_0,
  137516. NULL,
  137517. &_vq_auxt__44c1_s_p2_0,
  137518. NULL,
  137519. 0
  137520. };
  137521. static long _vq_quantlist__44c1_s_p3_0[] = {
  137522. 4,
  137523. 3,
  137524. 5,
  137525. 2,
  137526. 6,
  137527. 1,
  137528. 7,
  137529. 0,
  137530. 8,
  137531. };
  137532. static long _vq_lengthlist__44c1_s_p3_0[] = {
  137533. 1, 3, 2, 7, 7, 0, 0, 0, 0, 0,13,13, 6, 6, 0, 0,
  137534. 0, 0, 0,12, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  137535. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  137536. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  137537. 0, 0,11,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137538. 0,
  137539. };
  137540. static float _vq_quantthresh__44c1_s_p3_0[] = {
  137541. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137542. };
  137543. static long _vq_quantmap__44c1_s_p3_0[] = {
  137544. 7, 5, 3, 1, 0, 2, 4, 6,
  137545. 8,
  137546. };
  137547. static encode_aux_threshmatch _vq_auxt__44c1_s_p3_0 = {
  137548. _vq_quantthresh__44c1_s_p3_0,
  137549. _vq_quantmap__44c1_s_p3_0,
  137550. 9,
  137551. 9
  137552. };
  137553. static static_codebook _44c1_s_p3_0 = {
  137554. 2, 81,
  137555. _vq_lengthlist__44c1_s_p3_0,
  137556. 1, -531628032, 1611661312, 4, 0,
  137557. _vq_quantlist__44c1_s_p3_0,
  137558. NULL,
  137559. &_vq_auxt__44c1_s_p3_0,
  137560. NULL,
  137561. 0
  137562. };
  137563. static long _vq_quantlist__44c1_s_p4_0[] = {
  137564. 4,
  137565. 3,
  137566. 5,
  137567. 2,
  137568. 6,
  137569. 1,
  137570. 7,
  137571. 0,
  137572. 8,
  137573. };
  137574. static long _vq_lengthlist__44c1_s_p4_0[] = {
  137575. 1, 3, 3, 6, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  137576. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  137577. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  137578. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  137579. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  137580. 11,
  137581. };
  137582. static float _vq_quantthresh__44c1_s_p4_0[] = {
  137583. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137584. };
  137585. static long _vq_quantmap__44c1_s_p4_0[] = {
  137586. 7, 5, 3, 1, 0, 2, 4, 6,
  137587. 8,
  137588. };
  137589. static encode_aux_threshmatch _vq_auxt__44c1_s_p4_0 = {
  137590. _vq_quantthresh__44c1_s_p4_0,
  137591. _vq_quantmap__44c1_s_p4_0,
  137592. 9,
  137593. 9
  137594. };
  137595. static static_codebook _44c1_s_p4_0 = {
  137596. 2, 81,
  137597. _vq_lengthlist__44c1_s_p4_0,
  137598. 1, -531628032, 1611661312, 4, 0,
  137599. _vq_quantlist__44c1_s_p4_0,
  137600. NULL,
  137601. &_vq_auxt__44c1_s_p4_0,
  137602. NULL,
  137603. 0
  137604. };
  137605. static long _vq_quantlist__44c1_s_p5_0[] = {
  137606. 8,
  137607. 7,
  137608. 9,
  137609. 6,
  137610. 10,
  137611. 5,
  137612. 11,
  137613. 4,
  137614. 12,
  137615. 3,
  137616. 13,
  137617. 2,
  137618. 14,
  137619. 1,
  137620. 15,
  137621. 0,
  137622. 16,
  137623. };
  137624. static long _vq_lengthlist__44c1_s_p5_0[] = {
  137625. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  137626. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  137627. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  137628. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  137629. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  137630. 10,11,11,12,11, 0, 0, 0, 8, 8, 9, 9, 9,10,10,10,
  137631. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10, 9,10,
  137632. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  137633. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  137634. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  137635. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  137636. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  137637. 10,10,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  137638. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  137639. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13, 0, 0,
  137640. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  137641. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,14,14,
  137642. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  137643. 14,
  137644. };
  137645. static float _vq_quantthresh__44c1_s_p5_0[] = {
  137646. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137647. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137648. };
  137649. static long _vq_quantmap__44c1_s_p5_0[] = {
  137650. 15, 13, 11, 9, 7, 5, 3, 1,
  137651. 0, 2, 4, 6, 8, 10, 12, 14,
  137652. 16,
  137653. };
  137654. static encode_aux_threshmatch _vq_auxt__44c1_s_p5_0 = {
  137655. _vq_quantthresh__44c1_s_p5_0,
  137656. _vq_quantmap__44c1_s_p5_0,
  137657. 17,
  137658. 17
  137659. };
  137660. static static_codebook _44c1_s_p5_0 = {
  137661. 2, 289,
  137662. _vq_lengthlist__44c1_s_p5_0,
  137663. 1, -529530880, 1611661312, 5, 0,
  137664. _vq_quantlist__44c1_s_p5_0,
  137665. NULL,
  137666. &_vq_auxt__44c1_s_p5_0,
  137667. NULL,
  137668. 0
  137669. };
  137670. static long _vq_quantlist__44c1_s_p6_0[] = {
  137671. 1,
  137672. 0,
  137673. 2,
  137674. };
  137675. static long _vq_lengthlist__44c1_s_p6_0[] = {
  137676. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  137677. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 6,10,10,11,11,
  137678. 11,11,10,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  137679. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 7,
  137680. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,12,10,
  137681. 11,
  137682. };
  137683. static float _vq_quantthresh__44c1_s_p6_0[] = {
  137684. -5.5, 5.5,
  137685. };
  137686. static long _vq_quantmap__44c1_s_p6_0[] = {
  137687. 1, 0, 2,
  137688. };
  137689. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_0 = {
  137690. _vq_quantthresh__44c1_s_p6_0,
  137691. _vq_quantmap__44c1_s_p6_0,
  137692. 3,
  137693. 3
  137694. };
  137695. static static_codebook _44c1_s_p6_0 = {
  137696. 4, 81,
  137697. _vq_lengthlist__44c1_s_p6_0,
  137698. 1, -529137664, 1618345984, 2, 0,
  137699. _vq_quantlist__44c1_s_p6_0,
  137700. NULL,
  137701. &_vq_auxt__44c1_s_p6_0,
  137702. NULL,
  137703. 0
  137704. };
  137705. static long _vq_quantlist__44c1_s_p6_1[] = {
  137706. 5,
  137707. 4,
  137708. 6,
  137709. 3,
  137710. 7,
  137711. 2,
  137712. 8,
  137713. 1,
  137714. 9,
  137715. 0,
  137716. 10,
  137717. };
  137718. static long _vq_lengthlist__44c1_s_p6_1[] = {
  137719. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  137720. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  137721. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  137722. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  137723. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  137724. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  137725. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  137726. 10,10,10, 8, 8, 8, 8, 8, 8,
  137727. };
  137728. static float _vq_quantthresh__44c1_s_p6_1[] = {
  137729. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  137730. 3.5, 4.5,
  137731. };
  137732. static long _vq_quantmap__44c1_s_p6_1[] = {
  137733. 9, 7, 5, 3, 1, 0, 2, 4,
  137734. 6, 8, 10,
  137735. };
  137736. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_1 = {
  137737. _vq_quantthresh__44c1_s_p6_1,
  137738. _vq_quantmap__44c1_s_p6_1,
  137739. 11,
  137740. 11
  137741. };
  137742. static static_codebook _44c1_s_p6_1 = {
  137743. 2, 121,
  137744. _vq_lengthlist__44c1_s_p6_1,
  137745. 1, -531365888, 1611661312, 4, 0,
  137746. _vq_quantlist__44c1_s_p6_1,
  137747. NULL,
  137748. &_vq_auxt__44c1_s_p6_1,
  137749. NULL,
  137750. 0
  137751. };
  137752. static long _vq_quantlist__44c1_s_p7_0[] = {
  137753. 6,
  137754. 5,
  137755. 7,
  137756. 4,
  137757. 8,
  137758. 3,
  137759. 9,
  137760. 2,
  137761. 10,
  137762. 1,
  137763. 11,
  137764. 0,
  137765. 12,
  137766. };
  137767. static long _vq_lengthlist__44c1_s_p7_0[] = {
  137768. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 9, 7, 5, 6,
  137769. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  137770. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  137771. 10,10,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  137772. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,11, 0,13,
  137773. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  137774. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10,10, 9,11,
  137775. 11,12,11,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  137776. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  137777. 0, 0, 0, 0,11,12,11,11,12,12,14,13, 0, 0, 0, 0,
  137778. 0,12,11,11,11,13,10,14,13,
  137779. };
  137780. static float _vq_quantthresh__44c1_s_p7_0[] = {
  137781. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  137782. 12.5, 17.5, 22.5, 27.5,
  137783. };
  137784. static long _vq_quantmap__44c1_s_p7_0[] = {
  137785. 11, 9, 7, 5, 3, 1, 0, 2,
  137786. 4, 6, 8, 10, 12,
  137787. };
  137788. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_0 = {
  137789. _vq_quantthresh__44c1_s_p7_0,
  137790. _vq_quantmap__44c1_s_p7_0,
  137791. 13,
  137792. 13
  137793. };
  137794. static static_codebook _44c1_s_p7_0 = {
  137795. 2, 169,
  137796. _vq_lengthlist__44c1_s_p7_0,
  137797. 1, -526516224, 1616117760, 4, 0,
  137798. _vq_quantlist__44c1_s_p7_0,
  137799. NULL,
  137800. &_vq_auxt__44c1_s_p7_0,
  137801. NULL,
  137802. 0
  137803. };
  137804. static long _vq_quantlist__44c1_s_p7_1[] = {
  137805. 2,
  137806. 1,
  137807. 3,
  137808. 0,
  137809. 4,
  137810. };
  137811. static long _vq_lengthlist__44c1_s_p7_1[] = {
  137812. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  137813. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  137814. };
  137815. static float _vq_quantthresh__44c1_s_p7_1[] = {
  137816. -1.5, -0.5, 0.5, 1.5,
  137817. };
  137818. static long _vq_quantmap__44c1_s_p7_1[] = {
  137819. 3, 1, 0, 2, 4,
  137820. };
  137821. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_1 = {
  137822. _vq_quantthresh__44c1_s_p7_1,
  137823. _vq_quantmap__44c1_s_p7_1,
  137824. 5,
  137825. 5
  137826. };
  137827. static static_codebook _44c1_s_p7_1 = {
  137828. 2, 25,
  137829. _vq_lengthlist__44c1_s_p7_1,
  137830. 1, -533725184, 1611661312, 3, 0,
  137831. _vq_quantlist__44c1_s_p7_1,
  137832. NULL,
  137833. &_vq_auxt__44c1_s_p7_1,
  137834. NULL,
  137835. 0
  137836. };
  137837. static long _vq_quantlist__44c1_s_p8_0[] = {
  137838. 6,
  137839. 5,
  137840. 7,
  137841. 4,
  137842. 8,
  137843. 3,
  137844. 9,
  137845. 2,
  137846. 10,
  137847. 1,
  137848. 11,
  137849. 0,
  137850. 12,
  137851. };
  137852. static long _vq_lengthlist__44c1_s_p8_0[] = {
  137853. 1, 4, 3,10,10,10,10,10,10,10,10,10,10, 4, 8, 6,
  137854. 10,10,10,10,10,10,10,10,10,10, 4, 8, 7,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,10,10,10,10,10,10,10,
  137861. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137862. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137863. 10,10,10,10,10,10,10,10,10,
  137864. };
  137865. static float _vq_quantthresh__44c1_s_p8_0[] = {
  137866. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  137867. 552.5, 773.5, 994.5, 1215.5,
  137868. };
  137869. static long _vq_quantmap__44c1_s_p8_0[] = {
  137870. 11, 9, 7, 5, 3, 1, 0, 2,
  137871. 4, 6, 8, 10, 12,
  137872. };
  137873. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_0 = {
  137874. _vq_quantthresh__44c1_s_p8_0,
  137875. _vq_quantmap__44c1_s_p8_0,
  137876. 13,
  137877. 13
  137878. };
  137879. static static_codebook _44c1_s_p8_0 = {
  137880. 2, 169,
  137881. _vq_lengthlist__44c1_s_p8_0,
  137882. 1, -514541568, 1627103232, 4, 0,
  137883. _vq_quantlist__44c1_s_p8_0,
  137884. NULL,
  137885. &_vq_auxt__44c1_s_p8_0,
  137886. NULL,
  137887. 0
  137888. };
  137889. static long _vq_quantlist__44c1_s_p8_1[] = {
  137890. 6,
  137891. 5,
  137892. 7,
  137893. 4,
  137894. 8,
  137895. 3,
  137896. 9,
  137897. 2,
  137898. 10,
  137899. 1,
  137900. 11,
  137901. 0,
  137902. 12,
  137903. };
  137904. static long _vq_lengthlist__44c1_s_p8_1[] = {
  137905. 1, 4, 4, 6, 5, 7, 7, 9, 9,10,10,12,12, 6, 5, 5,
  137906. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  137907. 8,10,10,11,11,12,12,15, 7, 7, 8, 8, 9, 9,11,11,
  137908. 12,12,13,12,15, 8, 8, 8, 7, 9, 9,10,10,12,12,13,
  137909. 13,16,11,10, 8, 8,10,10,11,11,12,12,13,13,16,11,
  137910. 11, 9, 8,11,10,11,11,12,12,13,12,16,16,16,10,11,
  137911. 10,11,12,12,12,12,13,13,16,16,16,11, 9,11, 9,14,
  137912. 12,12,12,13,13,16,16,16,12,14,11,12,12,12,13,13,
  137913. 14,13,16,16,16,15,13,12,10,13,10,13,14,13,13,16,
  137914. 16,16,16,16,13,14,12,13,13,12,13,13,16,16,16,16,
  137915. 16,13,12,12,11,14,12,15,13,
  137916. };
  137917. static float _vq_quantthresh__44c1_s_p8_1[] = {
  137918. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  137919. 42.5, 59.5, 76.5, 93.5,
  137920. };
  137921. static long _vq_quantmap__44c1_s_p8_1[] = {
  137922. 11, 9, 7, 5, 3, 1, 0, 2,
  137923. 4, 6, 8, 10, 12,
  137924. };
  137925. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_1 = {
  137926. _vq_quantthresh__44c1_s_p8_1,
  137927. _vq_quantmap__44c1_s_p8_1,
  137928. 13,
  137929. 13
  137930. };
  137931. static static_codebook _44c1_s_p8_1 = {
  137932. 2, 169,
  137933. _vq_lengthlist__44c1_s_p8_1,
  137934. 1, -522616832, 1620115456, 4, 0,
  137935. _vq_quantlist__44c1_s_p8_1,
  137936. NULL,
  137937. &_vq_auxt__44c1_s_p8_1,
  137938. NULL,
  137939. 0
  137940. };
  137941. static long _vq_quantlist__44c1_s_p8_2[] = {
  137942. 8,
  137943. 7,
  137944. 9,
  137945. 6,
  137946. 10,
  137947. 5,
  137948. 11,
  137949. 4,
  137950. 12,
  137951. 3,
  137952. 13,
  137953. 2,
  137954. 14,
  137955. 1,
  137956. 15,
  137957. 0,
  137958. 16,
  137959. };
  137960. static long _vq_lengthlist__44c1_s_p8_2[] = {
  137961. 2, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  137962. 8,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  137963. 9, 9,10,10,10, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  137964. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  137965. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  137966. 9,10, 9, 9,10,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  137967. 9, 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  137968. 9, 9, 9, 9, 9,10,10,11,11,11, 8, 8, 9, 9, 9, 9,
  137969. 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11, 8, 8, 9,
  137970. 9, 9, 9,10, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  137971. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 9,
  137972. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  137973. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10,11,11,
  137974. 11,11,11, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,10,11,11,
  137975. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  137976. 11,11,11,11,11, 9,10, 9, 9, 9, 9,10, 9, 9, 9,11,
  137977. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  137978. 11,11,10,11,11,11,11,10,11, 9, 9, 9, 9, 9, 9, 9,
  137979. 9,
  137980. };
  137981. static float _vq_quantthresh__44c1_s_p8_2[] = {
  137982. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137983. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137984. };
  137985. static long _vq_quantmap__44c1_s_p8_2[] = {
  137986. 15, 13, 11, 9, 7, 5, 3, 1,
  137987. 0, 2, 4, 6, 8, 10, 12, 14,
  137988. 16,
  137989. };
  137990. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_2 = {
  137991. _vq_quantthresh__44c1_s_p8_2,
  137992. _vq_quantmap__44c1_s_p8_2,
  137993. 17,
  137994. 17
  137995. };
  137996. static static_codebook _44c1_s_p8_2 = {
  137997. 2, 289,
  137998. _vq_lengthlist__44c1_s_p8_2,
  137999. 1, -529530880, 1611661312, 5, 0,
  138000. _vq_quantlist__44c1_s_p8_2,
  138001. NULL,
  138002. &_vq_auxt__44c1_s_p8_2,
  138003. NULL,
  138004. 0
  138005. };
  138006. static long _huff_lengthlist__44c1_s_short[] = {
  138007. 6, 8,13,12,13,14,15,16,16, 4, 2, 4, 7, 6, 8,11,
  138008. 13,15,10, 4, 4, 8, 6, 8,11,14,17,11, 5, 6, 5, 6,
  138009. 8,12,14,17,11, 5, 5, 6, 5, 7,10,13,16,12, 6, 7,
  138010. 8, 7, 8,10,13,15,13, 8, 8, 7, 7, 8,10,12,15,15,
  138011. 7, 7, 5, 5, 7, 9,12,14,15, 8, 8, 6, 6, 7, 8,10,
  138012. 11,
  138013. };
  138014. static static_codebook _huff_book__44c1_s_short = {
  138015. 2, 81,
  138016. _huff_lengthlist__44c1_s_short,
  138017. 0, 0, 0, 0, 0,
  138018. NULL,
  138019. NULL,
  138020. NULL,
  138021. NULL,
  138022. 0
  138023. };
  138024. static long _huff_lengthlist__44c1_sm_long[] = {
  138025. 5, 4, 8,10, 9, 9,10,11,12, 4, 2, 5, 6, 6, 8,10,
  138026. 11,13, 8, 4, 6, 8, 7, 9,12,12,14,10, 6, 8, 4, 5,
  138027. 6, 9,11,12, 9, 5, 6, 5, 5, 6, 9,11,11, 9, 7, 9,
  138028. 6, 5, 5, 7,10,10,10, 9,11, 8, 7, 6, 7, 9,11,11,
  138029. 12,13,10,10, 9, 8, 9,11,11,15,15,12,13,11, 9,10,
  138030. 11,
  138031. };
  138032. static static_codebook _huff_book__44c1_sm_long = {
  138033. 2, 81,
  138034. _huff_lengthlist__44c1_sm_long,
  138035. 0, 0, 0, 0, 0,
  138036. NULL,
  138037. NULL,
  138038. NULL,
  138039. NULL,
  138040. 0
  138041. };
  138042. static long _vq_quantlist__44c1_sm_p1_0[] = {
  138043. 1,
  138044. 0,
  138045. 2,
  138046. };
  138047. static long _vq_lengthlist__44c1_sm_p1_0[] = {
  138048. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  138049. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138053. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  138054. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138058. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  138059. 0, 0, 0, 0, 7, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0,
  138091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  138094. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  138095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  138099. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  138100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  138104. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  138105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138139. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  138140. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138144. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  138145. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  138146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138149. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  138150. 0, 0, 0, 0, 0, 0, 9,10, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138458. 0,
  138459. };
  138460. static float _vq_quantthresh__44c1_sm_p1_0[] = {
  138461. -0.5, 0.5,
  138462. };
  138463. static long _vq_quantmap__44c1_sm_p1_0[] = {
  138464. 1, 0, 2,
  138465. };
  138466. static encode_aux_threshmatch _vq_auxt__44c1_sm_p1_0 = {
  138467. _vq_quantthresh__44c1_sm_p1_0,
  138468. _vq_quantmap__44c1_sm_p1_0,
  138469. 3,
  138470. 3
  138471. };
  138472. static static_codebook _44c1_sm_p1_0 = {
  138473. 8, 6561,
  138474. _vq_lengthlist__44c1_sm_p1_0,
  138475. 1, -535822336, 1611661312, 2, 0,
  138476. _vq_quantlist__44c1_sm_p1_0,
  138477. NULL,
  138478. &_vq_auxt__44c1_sm_p1_0,
  138479. NULL,
  138480. 0
  138481. };
  138482. static long _vq_quantlist__44c1_sm_p2_0[] = {
  138483. 2,
  138484. 1,
  138485. 3,
  138486. 0,
  138487. 4,
  138488. };
  138489. static long _vq_lengthlist__44c1_sm_p2_0[] = {
  138490. 2, 3, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  138492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138493. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  138495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138496. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  138497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138529. 0,
  138530. };
  138531. static float _vq_quantthresh__44c1_sm_p2_0[] = {
  138532. -1.5, -0.5, 0.5, 1.5,
  138533. };
  138534. static long _vq_quantmap__44c1_sm_p2_0[] = {
  138535. 3, 1, 0, 2, 4,
  138536. };
  138537. static encode_aux_threshmatch _vq_auxt__44c1_sm_p2_0 = {
  138538. _vq_quantthresh__44c1_sm_p2_0,
  138539. _vq_quantmap__44c1_sm_p2_0,
  138540. 5,
  138541. 5
  138542. };
  138543. static static_codebook _44c1_sm_p2_0 = {
  138544. 4, 625,
  138545. _vq_lengthlist__44c1_sm_p2_0,
  138546. 1, -533725184, 1611661312, 3, 0,
  138547. _vq_quantlist__44c1_sm_p2_0,
  138548. NULL,
  138549. &_vq_auxt__44c1_sm_p2_0,
  138550. NULL,
  138551. 0
  138552. };
  138553. static long _vq_quantlist__44c1_sm_p3_0[] = {
  138554. 4,
  138555. 3,
  138556. 5,
  138557. 2,
  138558. 6,
  138559. 1,
  138560. 7,
  138561. 0,
  138562. 8,
  138563. };
  138564. static long _vq_lengthlist__44c1_sm_p3_0[] = {
  138565. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 5, 6, 6, 0, 0,
  138566. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 7, 7, 7, 7,
  138567. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  138568. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  138569. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138570. 0,
  138571. };
  138572. static float _vq_quantthresh__44c1_sm_p3_0[] = {
  138573. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138574. };
  138575. static long _vq_quantmap__44c1_sm_p3_0[] = {
  138576. 7, 5, 3, 1, 0, 2, 4, 6,
  138577. 8,
  138578. };
  138579. static encode_aux_threshmatch _vq_auxt__44c1_sm_p3_0 = {
  138580. _vq_quantthresh__44c1_sm_p3_0,
  138581. _vq_quantmap__44c1_sm_p3_0,
  138582. 9,
  138583. 9
  138584. };
  138585. static static_codebook _44c1_sm_p3_0 = {
  138586. 2, 81,
  138587. _vq_lengthlist__44c1_sm_p3_0,
  138588. 1, -531628032, 1611661312, 4, 0,
  138589. _vq_quantlist__44c1_sm_p3_0,
  138590. NULL,
  138591. &_vq_auxt__44c1_sm_p3_0,
  138592. NULL,
  138593. 0
  138594. };
  138595. static long _vq_quantlist__44c1_sm_p4_0[] = {
  138596. 4,
  138597. 3,
  138598. 5,
  138599. 2,
  138600. 6,
  138601. 1,
  138602. 7,
  138603. 0,
  138604. 8,
  138605. };
  138606. static long _vq_lengthlist__44c1_sm_p4_0[] = {
  138607. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7, 8, 8,
  138608. 9, 9, 0, 6, 6, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  138609. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  138610. 8, 8, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  138611. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  138612. 11,
  138613. };
  138614. static float _vq_quantthresh__44c1_sm_p4_0[] = {
  138615. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138616. };
  138617. static long _vq_quantmap__44c1_sm_p4_0[] = {
  138618. 7, 5, 3, 1, 0, 2, 4, 6,
  138619. 8,
  138620. };
  138621. static encode_aux_threshmatch _vq_auxt__44c1_sm_p4_0 = {
  138622. _vq_quantthresh__44c1_sm_p4_0,
  138623. _vq_quantmap__44c1_sm_p4_0,
  138624. 9,
  138625. 9
  138626. };
  138627. static static_codebook _44c1_sm_p4_0 = {
  138628. 2, 81,
  138629. _vq_lengthlist__44c1_sm_p4_0,
  138630. 1, -531628032, 1611661312, 4, 0,
  138631. _vq_quantlist__44c1_sm_p4_0,
  138632. NULL,
  138633. &_vq_auxt__44c1_sm_p4_0,
  138634. NULL,
  138635. 0
  138636. };
  138637. static long _vq_quantlist__44c1_sm_p5_0[] = {
  138638. 8,
  138639. 7,
  138640. 9,
  138641. 6,
  138642. 10,
  138643. 5,
  138644. 11,
  138645. 4,
  138646. 12,
  138647. 3,
  138648. 13,
  138649. 2,
  138650. 14,
  138651. 1,
  138652. 15,
  138653. 0,
  138654. 16,
  138655. };
  138656. static long _vq_lengthlist__44c1_sm_p5_0[] = {
  138657. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  138658. 11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  138659. 11,11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  138660. 10,11,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  138661. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  138662. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,10,
  138663. 10,11,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,
  138664. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  138665. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  138666. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  138667. 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  138668. 9, 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  138669. 9, 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  138670. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  138671. 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0, 0,
  138672. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  138673. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14,
  138674. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  138675. 14,
  138676. };
  138677. static float _vq_quantthresh__44c1_sm_p5_0[] = {
  138678. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138679. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138680. };
  138681. static long _vq_quantmap__44c1_sm_p5_0[] = {
  138682. 15, 13, 11, 9, 7, 5, 3, 1,
  138683. 0, 2, 4, 6, 8, 10, 12, 14,
  138684. 16,
  138685. };
  138686. static encode_aux_threshmatch _vq_auxt__44c1_sm_p5_0 = {
  138687. _vq_quantthresh__44c1_sm_p5_0,
  138688. _vq_quantmap__44c1_sm_p5_0,
  138689. 17,
  138690. 17
  138691. };
  138692. static static_codebook _44c1_sm_p5_0 = {
  138693. 2, 289,
  138694. _vq_lengthlist__44c1_sm_p5_0,
  138695. 1, -529530880, 1611661312, 5, 0,
  138696. _vq_quantlist__44c1_sm_p5_0,
  138697. NULL,
  138698. &_vq_auxt__44c1_sm_p5_0,
  138699. NULL,
  138700. 0
  138701. };
  138702. static long _vq_quantlist__44c1_sm_p6_0[] = {
  138703. 1,
  138704. 0,
  138705. 2,
  138706. };
  138707. static long _vq_lengthlist__44c1_sm_p6_0[] = {
  138708. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  138709. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  138710. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  138711. 11,10,11,11,10,10, 7,11,11,11,11,11,11,11,11, 6,
  138712. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,11,10,
  138713. 11,
  138714. };
  138715. static float _vq_quantthresh__44c1_sm_p6_0[] = {
  138716. -5.5, 5.5,
  138717. };
  138718. static long _vq_quantmap__44c1_sm_p6_0[] = {
  138719. 1, 0, 2,
  138720. };
  138721. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_0 = {
  138722. _vq_quantthresh__44c1_sm_p6_0,
  138723. _vq_quantmap__44c1_sm_p6_0,
  138724. 3,
  138725. 3
  138726. };
  138727. static static_codebook _44c1_sm_p6_0 = {
  138728. 4, 81,
  138729. _vq_lengthlist__44c1_sm_p6_0,
  138730. 1, -529137664, 1618345984, 2, 0,
  138731. _vq_quantlist__44c1_sm_p6_0,
  138732. NULL,
  138733. &_vq_auxt__44c1_sm_p6_0,
  138734. NULL,
  138735. 0
  138736. };
  138737. static long _vq_quantlist__44c1_sm_p6_1[] = {
  138738. 5,
  138739. 4,
  138740. 6,
  138741. 3,
  138742. 7,
  138743. 2,
  138744. 8,
  138745. 1,
  138746. 9,
  138747. 0,
  138748. 10,
  138749. };
  138750. static long _vq_lengthlist__44c1_sm_p6_1[] = {
  138751. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  138752. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  138753. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  138754. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  138755. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  138756. 8, 8, 8, 8, 8, 8, 9, 8,10,10,10,10,10, 8, 8, 8,
  138757. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  138758. 10,10,10, 8, 8, 8, 8, 8, 8,
  138759. };
  138760. static float _vq_quantthresh__44c1_sm_p6_1[] = {
  138761. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  138762. 3.5, 4.5,
  138763. };
  138764. static long _vq_quantmap__44c1_sm_p6_1[] = {
  138765. 9, 7, 5, 3, 1, 0, 2, 4,
  138766. 6, 8, 10,
  138767. };
  138768. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_1 = {
  138769. _vq_quantthresh__44c1_sm_p6_1,
  138770. _vq_quantmap__44c1_sm_p6_1,
  138771. 11,
  138772. 11
  138773. };
  138774. static static_codebook _44c1_sm_p6_1 = {
  138775. 2, 121,
  138776. _vq_lengthlist__44c1_sm_p6_1,
  138777. 1, -531365888, 1611661312, 4, 0,
  138778. _vq_quantlist__44c1_sm_p6_1,
  138779. NULL,
  138780. &_vq_auxt__44c1_sm_p6_1,
  138781. NULL,
  138782. 0
  138783. };
  138784. static long _vq_quantlist__44c1_sm_p7_0[] = {
  138785. 6,
  138786. 5,
  138787. 7,
  138788. 4,
  138789. 8,
  138790. 3,
  138791. 9,
  138792. 2,
  138793. 10,
  138794. 1,
  138795. 11,
  138796. 0,
  138797. 12,
  138798. };
  138799. static long _vq_lengthlist__44c1_sm_p7_0[] = {
  138800. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  138801. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  138802. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  138803. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  138804. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  138805. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0, 9,10,
  138806. 9,10,11,11,12,11,13,12, 0, 0, 0,10,10, 9, 9,11,
  138807. 11,12,12,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  138808. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  138809. 0, 0, 0, 0,11,12,11,11,12,13,14,13, 0, 0, 0, 0,
  138810. 0,12,12,11,11,13,12,14,13,
  138811. };
  138812. static float _vq_quantthresh__44c1_sm_p7_0[] = {
  138813. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  138814. 12.5, 17.5, 22.5, 27.5,
  138815. };
  138816. static long _vq_quantmap__44c1_sm_p7_0[] = {
  138817. 11, 9, 7, 5, 3, 1, 0, 2,
  138818. 4, 6, 8, 10, 12,
  138819. };
  138820. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_0 = {
  138821. _vq_quantthresh__44c1_sm_p7_0,
  138822. _vq_quantmap__44c1_sm_p7_0,
  138823. 13,
  138824. 13
  138825. };
  138826. static static_codebook _44c1_sm_p7_0 = {
  138827. 2, 169,
  138828. _vq_lengthlist__44c1_sm_p7_0,
  138829. 1, -526516224, 1616117760, 4, 0,
  138830. _vq_quantlist__44c1_sm_p7_0,
  138831. NULL,
  138832. &_vq_auxt__44c1_sm_p7_0,
  138833. NULL,
  138834. 0
  138835. };
  138836. static long _vq_quantlist__44c1_sm_p7_1[] = {
  138837. 2,
  138838. 1,
  138839. 3,
  138840. 0,
  138841. 4,
  138842. };
  138843. static long _vq_lengthlist__44c1_sm_p7_1[] = {
  138844. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  138845. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  138846. };
  138847. static float _vq_quantthresh__44c1_sm_p7_1[] = {
  138848. -1.5, -0.5, 0.5, 1.5,
  138849. };
  138850. static long _vq_quantmap__44c1_sm_p7_1[] = {
  138851. 3, 1, 0, 2, 4,
  138852. };
  138853. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_1 = {
  138854. _vq_quantthresh__44c1_sm_p7_1,
  138855. _vq_quantmap__44c1_sm_p7_1,
  138856. 5,
  138857. 5
  138858. };
  138859. static static_codebook _44c1_sm_p7_1 = {
  138860. 2, 25,
  138861. _vq_lengthlist__44c1_sm_p7_1,
  138862. 1, -533725184, 1611661312, 3, 0,
  138863. _vq_quantlist__44c1_sm_p7_1,
  138864. NULL,
  138865. &_vq_auxt__44c1_sm_p7_1,
  138866. NULL,
  138867. 0
  138868. };
  138869. static long _vq_quantlist__44c1_sm_p8_0[] = {
  138870. 6,
  138871. 5,
  138872. 7,
  138873. 4,
  138874. 8,
  138875. 3,
  138876. 9,
  138877. 2,
  138878. 10,
  138879. 1,
  138880. 11,
  138881. 0,
  138882. 12,
  138883. };
  138884. static long _vq_lengthlist__44c1_sm_p8_0[] = {
  138885. 1, 3, 3,13,13,13,13,13,13,13,13,13,13, 3, 6, 6,
  138886. 13,13,13,13,13,13,13,13,13,13, 4, 8, 7,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,13,13,13,13,13,13,13,
  138893. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  138894. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  138895. 13,13,13,13,13,13,13,13,13,
  138896. };
  138897. static float _vq_quantthresh__44c1_sm_p8_0[] = {
  138898. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  138899. 552.5, 773.5, 994.5, 1215.5,
  138900. };
  138901. static long _vq_quantmap__44c1_sm_p8_0[] = {
  138902. 11, 9, 7, 5, 3, 1, 0, 2,
  138903. 4, 6, 8, 10, 12,
  138904. };
  138905. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_0 = {
  138906. _vq_quantthresh__44c1_sm_p8_0,
  138907. _vq_quantmap__44c1_sm_p8_0,
  138908. 13,
  138909. 13
  138910. };
  138911. static static_codebook _44c1_sm_p8_0 = {
  138912. 2, 169,
  138913. _vq_lengthlist__44c1_sm_p8_0,
  138914. 1, -514541568, 1627103232, 4, 0,
  138915. _vq_quantlist__44c1_sm_p8_0,
  138916. NULL,
  138917. &_vq_auxt__44c1_sm_p8_0,
  138918. NULL,
  138919. 0
  138920. };
  138921. static long _vq_quantlist__44c1_sm_p8_1[] = {
  138922. 6,
  138923. 5,
  138924. 7,
  138925. 4,
  138926. 8,
  138927. 3,
  138928. 9,
  138929. 2,
  138930. 10,
  138931. 1,
  138932. 11,
  138933. 0,
  138934. 12,
  138935. };
  138936. static long _vq_lengthlist__44c1_sm_p8_1[] = {
  138937. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  138938. 7, 7, 8, 7,10,10,11,11,12,12, 6, 5, 5, 7, 7, 8,
  138939. 8,10,10,11,11,12,12,16, 7, 7, 8, 8, 9, 9,11,11,
  138940. 12,12,13,13,17, 7, 7, 8, 7, 9, 9,11,10,12,12,13,
  138941. 13,19,11,10, 8, 8,10,10,11,11,12,12,13,13,19,11,
  138942. 11, 9, 7,11,10,11,11,12,12,13,12,19,19,19,10,10,
  138943. 10,10,11,12,12,12,13,14,18,19,19,11, 9,11, 9,13,
  138944. 12,12,12,13,13,19,20,19,13,15,11,11,12,12,13,13,
  138945. 14,13,18,19,20,15,13,12,10,13,10,13,13,13,14,20,
  138946. 20,20,20,20,13,14,12,12,13,12,13,13,20,20,20,20,
  138947. 20,13,12,12,12,14,12,14,13,
  138948. };
  138949. static float _vq_quantthresh__44c1_sm_p8_1[] = {
  138950. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  138951. 42.5, 59.5, 76.5, 93.5,
  138952. };
  138953. static long _vq_quantmap__44c1_sm_p8_1[] = {
  138954. 11, 9, 7, 5, 3, 1, 0, 2,
  138955. 4, 6, 8, 10, 12,
  138956. };
  138957. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_1 = {
  138958. _vq_quantthresh__44c1_sm_p8_1,
  138959. _vq_quantmap__44c1_sm_p8_1,
  138960. 13,
  138961. 13
  138962. };
  138963. static static_codebook _44c1_sm_p8_1 = {
  138964. 2, 169,
  138965. _vq_lengthlist__44c1_sm_p8_1,
  138966. 1, -522616832, 1620115456, 4, 0,
  138967. _vq_quantlist__44c1_sm_p8_1,
  138968. NULL,
  138969. &_vq_auxt__44c1_sm_p8_1,
  138970. NULL,
  138971. 0
  138972. };
  138973. static long _vq_quantlist__44c1_sm_p8_2[] = {
  138974. 8,
  138975. 7,
  138976. 9,
  138977. 6,
  138978. 10,
  138979. 5,
  138980. 11,
  138981. 4,
  138982. 12,
  138983. 3,
  138984. 13,
  138985. 2,
  138986. 14,
  138987. 1,
  138988. 15,
  138989. 0,
  138990. 16,
  138991. };
  138992. static long _vq_lengthlist__44c1_sm_p8_2[] = {
  138993. 2, 5, 5, 6, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  138994. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  138995. 9, 9,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  138996. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  138997. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  138998. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  138999. 9, 9,10,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  139000. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  139001. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 8, 8, 9,
  139002. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  139003. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,11,11,11, 9,
  139004. 8, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,10,11,11,
  139005. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,11,
  139006. 11,11,11, 9, 9,10, 9, 9, 9, 9,10, 9,10,10,11,10,
  139007. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  139008. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,
  139009. 11,10,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  139010. 10,11,10,11,11,11,11,11,11, 9, 9,10, 9, 9, 9, 9,
  139011. 9,
  139012. };
  139013. static float _vq_quantthresh__44c1_sm_p8_2[] = {
  139014. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139015. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139016. };
  139017. static long _vq_quantmap__44c1_sm_p8_2[] = {
  139018. 15, 13, 11, 9, 7, 5, 3, 1,
  139019. 0, 2, 4, 6, 8, 10, 12, 14,
  139020. 16,
  139021. };
  139022. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_2 = {
  139023. _vq_quantthresh__44c1_sm_p8_2,
  139024. _vq_quantmap__44c1_sm_p8_2,
  139025. 17,
  139026. 17
  139027. };
  139028. static static_codebook _44c1_sm_p8_2 = {
  139029. 2, 289,
  139030. _vq_lengthlist__44c1_sm_p8_2,
  139031. 1, -529530880, 1611661312, 5, 0,
  139032. _vq_quantlist__44c1_sm_p8_2,
  139033. NULL,
  139034. &_vq_auxt__44c1_sm_p8_2,
  139035. NULL,
  139036. 0
  139037. };
  139038. static long _huff_lengthlist__44c1_sm_short[] = {
  139039. 4, 7,13,14,14,15,16,18,18, 4, 2, 5, 8, 7, 9,12,
  139040. 15,15,10, 4, 5,10, 6, 8,11,15,17,12, 5, 7, 5, 6,
  139041. 8,11,14,17,11, 5, 6, 6, 5, 6, 9,13,17,12, 6, 7,
  139042. 6, 5, 6, 8,12,14,14, 7, 8, 6, 6, 7, 9,11,14,14,
  139043. 8, 9, 6, 5, 6, 9,11,13,16,10,10, 7, 6, 7, 8,10,
  139044. 11,
  139045. };
  139046. static static_codebook _huff_book__44c1_sm_short = {
  139047. 2, 81,
  139048. _huff_lengthlist__44c1_sm_short,
  139049. 0, 0, 0, 0, 0,
  139050. NULL,
  139051. NULL,
  139052. NULL,
  139053. NULL,
  139054. 0
  139055. };
  139056. static long _huff_lengthlist__44cn1_s_long[] = {
  139057. 4, 4, 7, 8, 7, 8,10,12,17, 3, 1, 6, 6, 7, 8,10,
  139058. 12,15, 7, 6, 9, 9, 9,11,12,14,17, 8, 6, 9, 6, 7,
  139059. 9,11,13,17, 7, 6, 9, 7, 7, 8, 9,12,15, 8, 8,10,
  139060. 8, 7, 7, 7,10,14, 9,10,12,10, 8, 8, 8,10,14,11,
  139061. 13,15,13,12,11,11,12,16,17,18,18,19,20,18,16,16,
  139062. 20,
  139063. };
  139064. static static_codebook _huff_book__44cn1_s_long = {
  139065. 2, 81,
  139066. _huff_lengthlist__44cn1_s_long,
  139067. 0, 0, 0, 0, 0,
  139068. NULL,
  139069. NULL,
  139070. NULL,
  139071. NULL,
  139072. 0
  139073. };
  139074. static long _vq_quantlist__44cn1_s_p1_0[] = {
  139075. 1,
  139076. 0,
  139077. 2,
  139078. };
  139079. static long _vq_lengthlist__44cn1_s_p1_0[] = {
  139080. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  139081. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139083. 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  139086. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139088. 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0,
  139091. 0, 0, 0, 0, 8,10, 9, 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, 0, 0, 0, 0, 0, 0, 0,
  139123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0,
  139126. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0,
  139127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7,10,10, 0, 0, 0,
  139131. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  139132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 7,10,10, 0, 0,
  139136. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0,10,11,11,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139169. 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  139172. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139174. 0, 0, 0, 0, 0, 0, 0, 0, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  139177. 0, 0, 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  139178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11,
  139182. 0, 0, 0, 0, 0, 0, 9,11, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139490. 0,
  139491. };
  139492. static float _vq_quantthresh__44cn1_s_p1_0[] = {
  139493. -0.5, 0.5,
  139494. };
  139495. static long _vq_quantmap__44cn1_s_p1_0[] = {
  139496. 1, 0, 2,
  139497. };
  139498. static encode_aux_threshmatch _vq_auxt__44cn1_s_p1_0 = {
  139499. _vq_quantthresh__44cn1_s_p1_0,
  139500. _vq_quantmap__44cn1_s_p1_0,
  139501. 3,
  139502. 3
  139503. };
  139504. static static_codebook _44cn1_s_p1_0 = {
  139505. 8, 6561,
  139506. _vq_lengthlist__44cn1_s_p1_0,
  139507. 1, -535822336, 1611661312, 2, 0,
  139508. _vq_quantlist__44cn1_s_p1_0,
  139509. NULL,
  139510. &_vq_auxt__44cn1_s_p1_0,
  139511. NULL,
  139512. 0
  139513. };
  139514. static long _vq_quantlist__44cn1_s_p2_0[] = {
  139515. 2,
  139516. 1,
  139517. 3,
  139518. 0,
  139519. 4,
  139520. };
  139521. static long _vq_lengthlist__44cn1_s_p2_0[] = {
  139522. 1, 4, 4, 7, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  139524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139525. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  139527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139528. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  139529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139561. 0,
  139562. };
  139563. static float _vq_quantthresh__44cn1_s_p2_0[] = {
  139564. -1.5, -0.5, 0.5, 1.5,
  139565. };
  139566. static long _vq_quantmap__44cn1_s_p2_0[] = {
  139567. 3, 1, 0, 2, 4,
  139568. };
  139569. static encode_aux_threshmatch _vq_auxt__44cn1_s_p2_0 = {
  139570. _vq_quantthresh__44cn1_s_p2_0,
  139571. _vq_quantmap__44cn1_s_p2_0,
  139572. 5,
  139573. 5
  139574. };
  139575. static static_codebook _44cn1_s_p2_0 = {
  139576. 4, 625,
  139577. _vq_lengthlist__44cn1_s_p2_0,
  139578. 1, -533725184, 1611661312, 3, 0,
  139579. _vq_quantlist__44cn1_s_p2_0,
  139580. NULL,
  139581. &_vq_auxt__44cn1_s_p2_0,
  139582. NULL,
  139583. 0
  139584. };
  139585. static long _vq_quantlist__44cn1_s_p3_0[] = {
  139586. 4,
  139587. 3,
  139588. 5,
  139589. 2,
  139590. 6,
  139591. 1,
  139592. 7,
  139593. 0,
  139594. 8,
  139595. };
  139596. static long _vq_lengthlist__44cn1_s_p3_0[] = {
  139597. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  139598. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  139599. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  139600. 9, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  139601. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139602. 0,
  139603. };
  139604. static float _vq_quantthresh__44cn1_s_p3_0[] = {
  139605. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139606. };
  139607. static long _vq_quantmap__44cn1_s_p3_0[] = {
  139608. 7, 5, 3, 1, 0, 2, 4, 6,
  139609. 8,
  139610. };
  139611. static encode_aux_threshmatch _vq_auxt__44cn1_s_p3_0 = {
  139612. _vq_quantthresh__44cn1_s_p3_0,
  139613. _vq_quantmap__44cn1_s_p3_0,
  139614. 9,
  139615. 9
  139616. };
  139617. static static_codebook _44cn1_s_p3_0 = {
  139618. 2, 81,
  139619. _vq_lengthlist__44cn1_s_p3_0,
  139620. 1, -531628032, 1611661312, 4, 0,
  139621. _vq_quantlist__44cn1_s_p3_0,
  139622. NULL,
  139623. &_vq_auxt__44cn1_s_p3_0,
  139624. NULL,
  139625. 0
  139626. };
  139627. static long _vq_quantlist__44cn1_s_p4_0[] = {
  139628. 4,
  139629. 3,
  139630. 5,
  139631. 2,
  139632. 6,
  139633. 1,
  139634. 7,
  139635. 0,
  139636. 8,
  139637. };
  139638. static long _vq_lengthlist__44cn1_s_p4_0[] = {
  139639. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  139640. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  139641. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  139642. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  139643. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  139644. 11,
  139645. };
  139646. static float _vq_quantthresh__44cn1_s_p4_0[] = {
  139647. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139648. };
  139649. static long _vq_quantmap__44cn1_s_p4_0[] = {
  139650. 7, 5, 3, 1, 0, 2, 4, 6,
  139651. 8,
  139652. };
  139653. static encode_aux_threshmatch _vq_auxt__44cn1_s_p4_0 = {
  139654. _vq_quantthresh__44cn1_s_p4_0,
  139655. _vq_quantmap__44cn1_s_p4_0,
  139656. 9,
  139657. 9
  139658. };
  139659. static static_codebook _44cn1_s_p4_0 = {
  139660. 2, 81,
  139661. _vq_lengthlist__44cn1_s_p4_0,
  139662. 1, -531628032, 1611661312, 4, 0,
  139663. _vq_quantlist__44cn1_s_p4_0,
  139664. NULL,
  139665. &_vq_auxt__44cn1_s_p4_0,
  139666. NULL,
  139667. 0
  139668. };
  139669. static long _vq_quantlist__44cn1_s_p5_0[] = {
  139670. 8,
  139671. 7,
  139672. 9,
  139673. 6,
  139674. 10,
  139675. 5,
  139676. 11,
  139677. 4,
  139678. 12,
  139679. 3,
  139680. 13,
  139681. 2,
  139682. 14,
  139683. 1,
  139684. 15,
  139685. 0,
  139686. 16,
  139687. };
  139688. static long _vq_lengthlist__44cn1_s_p5_0[] = {
  139689. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  139690. 10, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  139691. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  139692. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  139693. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  139694. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  139695. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  139696. 10,10,11,11,11,12,12, 0, 0, 0, 9, 9,10, 9,10,10,
  139697. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  139698. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  139699. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  139700. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  139701. 10,10,11,10,11,11,11,12,13,12,13,13, 0, 0, 0, 0,
  139702. 0, 0, 0,11,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  139703. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  139704. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  139705. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,13,13,14,14,
  139706. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,12,13,13,14,
  139707. 14,
  139708. };
  139709. static float _vq_quantthresh__44cn1_s_p5_0[] = {
  139710. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139711. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139712. };
  139713. static long _vq_quantmap__44cn1_s_p5_0[] = {
  139714. 15, 13, 11, 9, 7, 5, 3, 1,
  139715. 0, 2, 4, 6, 8, 10, 12, 14,
  139716. 16,
  139717. };
  139718. static encode_aux_threshmatch _vq_auxt__44cn1_s_p5_0 = {
  139719. _vq_quantthresh__44cn1_s_p5_0,
  139720. _vq_quantmap__44cn1_s_p5_0,
  139721. 17,
  139722. 17
  139723. };
  139724. static static_codebook _44cn1_s_p5_0 = {
  139725. 2, 289,
  139726. _vq_lengthlist__44cn1_s_p5_0,
  139727. 1, -529530880, 1611661312, 5, 0,
  139728. _vq_quantlist__44cn1_s_p5_0,
  139729. NULL,
  139730. &_vq_auxt__44cn1_s_p5_0,
  139731. NULL,
  139732. 0
  139733. };
  139734. static long _vq_quantlist__44cn1_s_p6_0[] = {
  139735. 1,
  139736. 0,
  139737. 2,
  139738. };
  139739. static long _vq_lengthlist__44cn1_s_p6_0[] = {
  139740. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 6, 6,10, 9, 9,11,
  139741. 9, 9, 4, 6, 6,10, 9, 9,10, 9, 9, 7,10,10,11,11,
  139742. 11,12,11,11, 7, 9, 9,11,11,10,11,10,10, 7, 9, 9,
  139743. 11,10,11,11,10,10, 7,10,10,11,11,11,12,11,11, 7,
  139744. 9, 9,11,10,10,11,10,10, 7, 9, 9,11,10,10,11,10,
  139745. 10,
  139746. };
  139747. static float _vq_quantthresh__44cn1_s_p6_0[] = {
  139748. -5.5, 5.5,
  139749. };
  139750. static long _vq_quantmap__44cn1_s_p6_0[] = {
  139751. 1, 0, 2,
  139752. };
  139753. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_0 = {
  139754. _vq_quantthresh__44cn1_s_p6_0,
  139755. _vq_quantmap__44cn1_s_p6_0,
  139756. 3,
  139757. 3
  139758. };
  139759. static static_codebook _44cn1_s_p6_0 = {
  139760. 4, 81,
  139761. _vq_lengthlist__44cn1_s_p6_0,
  139762. 1, -529137664, 1618345984, 2, 0,
  139763. _vq_quantlist__44cn1_s_p6_0,
  139764. NULL,
  139765. &_vq_auxt__44cn1_s_p6_0,
  139766. NULL,
  139767. 0
  139768. };
  139769. static long _vq_quantlist__44cn1_s_p6_1[] = {
  139770. 5,
  139771. 4,
  139772. 6,
  139773. 3,
  139774. 7,
  139775. 2,
  139776. 8,
  139777. 1,
  139778. 9,
  139779. 0,
  139780. 10,
  139781. };
  139782. static long _vq_lengthlist__44cn1_s_p6_1[] = {
  139783. 1, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 6,
  139784. 8, 8, 8, 8, 8, 8,10,10,10, 7, 6, 7, 7, 8, 8, 8,
  139785. 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  139786. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 9, 9,
  139787. 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,
  139788. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  139789. 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,
  139790. 10,10,10, 9, 9, 9, 9, 9, 9,
  139791. };
  139792. static float _vq_quantthresh__44cn1_s_p6_1[] = {
  139793. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  139794. 3.5, 4.5,
  139795. };
  139796. static long _vq_quantmap__44cn1_s_p6_1[] = {
  139797. 9, 7, 5, 3, 1, 0, 2, 4,
  139798. 6, 8, 10,
  139799. };
  139800. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_1 = {
  139801. _vq_quantthresh__44cn1_s_p6_1,
  139802. _vq_quantmap__44cn1_s_p6_1,
  139803. 11,
  139804. 11
  139805. };
  139806. static static_codebook _44cn1_s_p6_1 = {
  139807. 2, 121,
  139808. _vq_lengthlist__44cn1_s_p6_1,
  139809. 1, -531365888, 1611661312, 4, 0,
  139810. _vq_quantlist__44cn1_s_p6_1,
  139811. NULL,
  139812. &_vq_auxt__44cn1_s_p6_1,
  139813. NULL,
  139814. 0
  139815. };
  139816. static long _vq_quantlist__44cn1_s_p7_0[] = {
  139817. 6,
  139818. 5,
  139819. 7,
  139820. 4,
  139821. 8,
  139822. 3,
  139823. 9,
  139824. 2,
  139825. 10,
  139826. 1,
  139827. 11,
  139828. 0,
  139829. 12,
  139830. };
  139831. static long _vq_lengthlist__44cn1_s_p7_0[] = {
  139832. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  139833. 7, 7, 8, 8, 8, 8, 9, 9,11,11, 7, 5, 5, 7, 7, 8,
  139834. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  139835. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  139836. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,12, 0,13,
  139837. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  139838. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  139839. 11,12,12,13,12, 0, 0, 0,14,14,11,10,11,12,12,13,
  139840. 13,14, 0, 0, 0,15,15,11,11,12,11,12,12,14,13, 0,
  139841. 0, 0, 0, 0,12,12,12,12,13,13,14,14, 0, 0, 0, 0,
  139842. 0,13,13,12,12,13,13,13,14,
  139843. };
  139844. static float _vq_quantthresh__44cn1_s_p7_0[] = {
  139845. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  139846. 12.5, 17.5, 22.5, 27.5,
  139847. };
  139848. static long _vq_quantmap__44cn1_s_p7_0[] = {
  139849. 11, 9, 7, 5, 3, 1, 0, 2,
  139850. 4, 6, 8, 10, 12,
  139851. };
  139852. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_0 = {
  139853. _vq_quantthresh__44cn1_s_p7_0,
  139854. _vq_quantmap__44cn1_s_p7_0,
  139855. 13,
  139856. 13
  139857. };
  139858. static static_codebook _44cn1_s_p7_0 = {
  139859. 2, 169,
  139860. _vq_lengthlist__44cn1_s_p7_0,
  139861. 1, -526516224, 1616117760, 4, 0,
  139862. _vq_quantlist__44cn1_s_p7_0,
  139863. NULL,
  139864. &_vq_auxt__44cn1_s_p7_0,
  139865. NULL,
  139866. 0
  139867. };
  139868. static long _vq_quantlist__44cn1_s_p7_1[] = {
  139869. 2,
  139870. 1,
  139871. 3,
  139872. 0,
  139873. 4,
  139874. };
  139875. static long _vq_lengthlist__44cn1_s_p7_1[] = {
  139876. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  139877. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  139878. };
  139879. static float _vq_quantthresh__44cn1_s_p7_1[] = {
  139880. -1.5, -0.5, 0.5, 1.5,
  139881. };
  139882. static long _vq_quantmap__44cn1_s_p7_1[] = {
  139883. 3, 1, 0, 2, 4,
  139884. };
  139885. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_1 = {
  139886. _vq_quantthresh__44cn1_s_p7_1,
  139887. _vq_quantmap__44cn1_s_p7_1,
  139888. 5,
  139889. 5
  139890. };
  139891. static static_codebook _44cn1_s_p7_1 = {
  139892. 2, 25,
  139893. _vq_lengthlist__44cn1_s_p7_1,
  139894. 1, -533725184, 1611661312, 3, 0,
  139895. _vq_quantlist__44cn1_s_p7_1,
  139896. NULL,
  139897. &_vq_auxt__44cn1_s_p7_1,
  139898. NULL,
  139899. 0
  139900. };
  139901. static long _vq_quantlist__44cn1_s_p8_0[] = {
  139902. 2,
  139903. 1,
  139904. 3,
  139905. 0,
  139906. 4,
  139907. };
  139908. static long _vq_lengthlist__44cn1_s_p8_0[] = {
  139909. 1, 7, 7,11,11, 8,11,11,11,11, 4,11, 3,11,11,11,
  139910. 11,11,11,11,11,11,11,11,11,11,11,10,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,10,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,11,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,11,11,11,11,11,11,11,11,11,11,
  139916. 11,11,11,11,11,11,11,11,11,11,11,11,11, 7,11,11,
  139917. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139918. 11,11,11,11,11,11,10,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,10,
  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,11,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, 8,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,11,11,11,11,11,11,11,11,11,
  139940. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139941. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139942. 11,11,11,11,11,11,11,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,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  139946. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  139947. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  139948. 12,
  139949. };
  139950. static float _vq_quantthresh__44cn1_s_p8_0[] = {
  139951. -331.5, -110.5, 110.5, 331.5,
  139952. };
  139953. static long _vq_quantmap__44cn1_s_p8_0[] = {
  139954. 3, 1, 0, 2, 4,
  139955. };
  139956. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_0 = {
  139957. _vq_quantthresh__44cn1_s_p8_0,
  139958. _vq_quantmap__44cn1_s_p8_0,
  139959. 5,
  139960. 5
  139961. };
  139962. static static_codebook _44cn1_s_p8_0 = {
  139963. 4, 625,
  139964. _vq_lengthlist__44cn1_s_p8_0,
  139965. 1, -518283264, 1627103232, 3, 0,
  139966. _vq_quantlist__44cn1_s_p8_0,
  139967. NULL,
  139968. &_vq_auxt__44cn1_s_p8_0,
  139969. NULL,
  139970. 0
  139971. };
  139972. static long _vq_quantlist__44cn1_s_p8_1[] = {
  139973. 6,
  139974. 5,
  139975. 7,
  139976. 4,
  139977. 8,
  139978. 3,
  139979. 9,
  139980. 2,
  139981. 10,
  139982. 1,
  139983. 11,
  139984. 0,
  139985. 12,
  139986. };
  139987. static long _vq_lengthlist__44cn1_s_p8_1[] = {
  139988. 1, 4, 4, 6, 6, 8, 8, 9,10,10,11,11,11, 6, 5, 5,
  139989. 7, 7, 8, 8, 9,10, 9,11,11,12, 5, 5, 5, 7, 7, 8,
  139990. 9,10,10,12,12,14,13,15, 7, 7, 8, 8, 9,10,11,11,
  139991. 10,12,10,11,15, 7, 8, 8, 8, 9, 9,11,11,13,12,12,
  139992. 13,15,10,10, 8, 8,10,10,12,12,11,14,10,10,15,11,
  139993. 11, 8, 8,10,10,12,13,13,14,15,13,15,15,15,10,10,
  139994. 10,10,12,12,13,12,13,10,15,15,15,10,10,11,10,13,
  139995. 11,13,13,15,13,15,15,15,13,13,10,11,11,11,12,10,
  139996. 14,11,15,15,14,14,13,10,10,12,11,13,13,14,14,15,
  139997. 15,15,15,15,11,11,11,11,12,11,15,12,15,15,15,15,
  139998. 15,12,12,11,11,14,12,13,14,
  139999. };
  140000. static float _vq_quantthresh__44cn1_s_p8_1[] = {
  140001. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  140002. 42.5, 59.5, 76.5, 93.5,
  140003. };
  140004. static long _vq_quantmap__44cn1_s_p8_1[] = {
  140005. 11, 9, 7, 5, 3, 1, 0, 2,
  140006. 4, 6, 8, 10, 12,
  140007. };
  140008. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_1 = {
  140009. _vq_quantthresh__44cn1_s_p8_1,
  140010. _vq_quantmap__44cn1_s_p8_1,
  140011. 13,
  140012. 13
  140013. };
  140014. static static_codebook _44cn1_s_p8_1 = {
  140015. 2, 169,
  140016. _vq_lengthlist__44cn1_s_p8_1,
  140017. 1, -522616832, 1620115456, 4, 0,
  140018. _vq_quantlist__44cn1_s_p8_1,
  140019. NULL,
  140020. &_vq_auxt__44cn1_s_p8_1,
  140021. NULL,
  140022. 0
  140023. };
  140024. static long _vq_quantlist__44cn1_s_p8_2[] = {
  140025. 8,
  140026. 7,
  140027. 9,
  140028. 6,
  140029. 10,
  140030. 5,
  140031. 11,
  140032. 4,
  140033. 12,
  140034. 3,
  140035. 13,
  140036. 2,
  140037. 14,
  140038. 1,
  140039. 15,
  140040. 0,
  140041. 16,
  140042. };
  140043. static long _vq_lengthlist__44cn1_s_p8_2[] = {
  140044. 3, 4, 3, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  140045. 9,10,11,11, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  140046. 9, 9,10,10,10, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  140047. 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  140048. 9, 9,10, 9,10,11,10, 7, 6, 7, 7, 8, 8, 9, 9, 9,
  140049. 9, 9, 9, 9,10,10,10,11, 7, 7, 8, 8, 8, 8, 9, 9,
  140050. 9, 9, 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9,
  140051. 9, 9, 9, 9, 9, 9,10,11,11,11, 8, 8, 8, 8, 8, 8,
  140052. 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 8, 8, 8,
  140053. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,11, 9, 9,
  140054. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,10,11,11, 9,
  140055. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  140056. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,
  140057. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11,
  140058. 10,11,11,11, 9,10,10, 9, 9, 9, 9, 9, 9, 9,10,11,
  140059. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  140060. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  140061. 11,11,11,10,11,11,11,11,11, 9, 9, 9,10, 9, 9, 9,
  140062. 9,
  140063. };
  140064. static float _vq_quantthresh__44cn1_s_p8_2[] = {
  140065. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140066. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140067. };
  140068. static long _vq_quantmap__44cn1_s_p8_2[] = {
  140069. 15, 13, 11, 9, 7, 5, 3, 1,
  140070. 0, 2, 4, 6, 8, 10, 12, 14,
  140071. 16,
  140072. };
  140073. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_2 = {
  140074. _vq_quantthresh__44cn1_s_p8_2,
  140075. _vq_quantmap__44cn1_s_p8_2,
  140076. 17,
  140077. 17
  140078. };
  140079. static static_codebook _44cn1_s_p8_2 = {
  140080. 2, 289,
  140081. _vq_lengthlist__44cn1_s_p8_2,
  140082. 1, -529530880, 1611661312, 5, 0,
  140083. _vq_quantlist__44cn1_s_p8_2,
  140084. NULL,
  140085. &_vq_auxt__44cn1_s_p8_2,
  140086. NULL,
  140087. 0
  140088. };
  140089. static long _huff_lengthlist__44cn1_s_short[] = {
  140090. 10, 9,12,15,12,13,16,14,16, 7, 1, 5,14, 7,10,13,
  140091. 16,16, 9, 4, 6,16, 8,11,16,16,16,14, 4, 7,16, 9,
  140092. 12,14,16,16,10, 5, 7,14, 9,12,14,15,15,13, 8, 9,
  140093. 14,10,12,13,14,15,13, 9, 9, 7, 6, 8,11,12,12,14,
  140094. 8, 8, 5, 4, 5, 8,11,12,16,10,10, 6, 5, 6, 8, 9,
  140095. 10,
  140096. };
  140097. static static_codebook _huff_book__44cn1_s_short = {
  140098. 2, 81,
  140099. _huff_lengthlist__44cn1_s_short,
  140100. 0, 0, 0, 0, 0,
  140101. NULL,
  140102. NULL,
  140103. NULL,
  140104. NULL,
  140105. 0
  140106. };
  140107. static long _huff_lengthlist__44cn1_sm_long[] = {
  140108. 3, 3, 8, 8, 8, 8,10,12,14, 3, 2, 6, 7, 7, 8,10,
  140109. 12,16, 7, 6, 7, 9, 8,10,12,14,16, 8, 6, 8, 4, 5,
  140110. 7, 9,11,13, 7, 6, 8, 5, 6, 7, 9,11,14, 8, 8,10,
  140111. 7, 7, 6, 8,10,13, 9,11,12, 9, 9, 7, 8,10,12,10,
  140112. 13,15,11,11,10, 9,10,13,13,16,17,14,15,14,13,14,
  140113. 17,
  140114. };
  140115. static static_codebook _huff_book__44cn1_sm_long = {
  140116. 2, 81,
  140117. _huff_lengthlist__44cn1_sm_long,
  140118. 0, 0, 0, 0, 0,
  140119. NULL,
  140120. NULL,
  140121. NULL,
  140122. NULL,
  140123. 0
  140124. };
  140125. static long _vq_quantlist__44cn1_sm_p1_0[] = {
  140126. 1,
  140127. 0,
  140128. 2,
  140129. };
  140130. static long _vq_lengthlist__44cn1_sm_p1_0[] = {
  140131. 1, 4, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  140132. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140134. 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  140137. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140139. 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  140142. 0, 0, 0, 0, 8, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0,
  140174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0,
  140177. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  140178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7,10, 9, 0, 0, 0,
  140182. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  140183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 7, 9, 9, 0, 0,
  140187. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140220. 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  140223. 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140225. 0, 0, 0, 0, 0, 0, 0, 0, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  140228. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  140229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10,
  140233. 0, 0, 0, 0, 0, 0, 9,10, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140541. 0,
  140542. };
  140543. static float _vq_quantthresh__44cn1_sm_p1_0[] = {
  140544. -0.5, 0.5,
  140545. };
  140546. static long _vq_quantmap__44cn1_sm_p1_0[] = {
  140547. 1, 0, 2,
  140548. };
  140549. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p1_0 = {
  140550. _vq_quantthresh__44cn1_sm_p1_0,
  140551. _vq_quantmap__44cn1_sm_p1_0,
  140552. 3,
  140553. 3
  140554. };
  140555. static static_codebook _44cn1_sm_p1_0 = {
  140556. 8, 6561,
  140557. _vq_lengthlist__44cn1_sm_p1_0,
  140558. 1, -535822336, 1611661312, 2, 0,
  140559. _vq_quantlist__44cn1_sm_p1_0,
  140560. NULL,
  140561. &_vq_auxt__44cn1_sm_p1_0,
  140562. NULL,
  140563. 0
  140564. };
  140565. static long _vq_quantlist__44cn1_sm_p2_0[] = {
  140566. 2,
  140567. 1,
  140568. 3,
  140569. 0,
  140570. 4,
  140571. };
  140572. static long _vq_lengthlist__44cn1_sm_p2_0[] = {
  140573. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  140575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140576. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  140578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140579. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  140580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140612. 0,
  140613. };
  140614. static float _vq_quantthresh__44cn1_sm_p2_0[] = {
  140615. -1.5, -0.5, 0.5, 1.5,
  140616. };
  140617. static long _vq_quantmap__44cn1_sm_p2_0[] = {
  140618. 3, 1, 0, 2, 4,
  140619. };
  140620. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p2_0 = {
  140621. _vq_quantthresh__44cn1_sm_p2_0,
  140622. _vq_quantmap__44cn1_sm_p2_0,
  140623. 5,
  140624. 5
  140625. };
  140626. static static_codebook _44cn1_sm_p2_0 = {
  140627. 4, 625,
  140628. _vq_lengthlist__44cn1_sm_p2_0,
  140629. 1, -533725184, 1611661312, 3, 0,
  140630. _vq_quantlist__44cn1_sm_p2_0,
  140631. NULL,
  140632. &_vq_auxt__44cn1_sm_p2_0,
  140633. NULL,
  140634. 0
  140635. };
  140636. static long _vq_quantlist__44cn1_sm_p3_0[] = {
  140637. 4,
  140638. 3,
  140639. 5,
  140640. 2,
  140641. 6,
  140642. 1,
  140643. 7,
  140644. 0,
  140645. 8,
  140646. };
  140647. static long _vq_lengthlist__44cn1_sm_p3_0[] = {
  140648. 1, 3, 4, 7, 7, 0, 0, 0, 0, 0, 4, 4, 7, 7, 0, 0,
  140649. 0, 0, 0, 4, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  140650. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  140651. 9, 9, 0, 0, 0, 0, 0, 0, 0,10, 9, 0, 0, 0, 0, 0,
  140652. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140653. 0,
  140654. };
  140655. static float _vq_quantthresh__44cn1_sm_p3_0[] = {
  140656. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140657. };
  140658. static long _vq_quantmap__44cn1_sm_p3_0[] = {
  140659. 7, 5, 3, 1, 0, 2, 4, 6,
  140660. 8,
  140661. };
  140662. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p3_0 = {
  140663. _vq_quantthresh__44cn1_sm_p3_0,
  140664. _vq_quantmap__44cn1_sm_p3_0,
  140665. 9,
  140666. 9
  140667. };
  140668. static static_codebook _44cn1_sm_p3_0 = {
  140669. 2, 81,
  140670. _vq_lengthlist__44cn1_sm_p3_0,
  140671. 1, -531628032, 1611661312, 4, 0,
  140672. _vq_quantlist__44cn1_sm_p3_0,
  140673. NULL,
  140674. &_vq_auxt__44cn1_sm_p3_0,
  140675. NULL,
  140676. 0
  140677. };
  140678. static long _vq_quantlist__44cn1_sm_p4_0[] = {
  140679. 4,
  140680. 3,
  140681. 5,
  140682. 2,
  140683. 6,
  140684. 1,
  140685. 7,
  140686. 0,
  140687. 8,
  140688. };
  140689. static long _vq_lengthlist__44cn1_sm_p4_0[] = {
  140690. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  140691. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  140692. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  140693. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  140694. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  140695. 11,
  140696. };
  140697. static float _vq_quantthresh__44cn1_sm_p4_0[] = {
  140698. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140699. };
  140700. static long _vq_quantmap__44cn1_sm_p4_0[] = {
  140701. 7, 5, 3, 1, 0, 2, 4, 6,
  140702. 8,
  140703. };
  140704. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p4_0 = {
  140705. _vq_quantthresh__44cn1_sm_p4_0,
  140706. _vq_quantmap__44cn1_sm_p4_0,
  140707. 9,
  140708. 9
  140709. };
  140710. static static_codebook _44cn1_sm_p4_0 = {
  140711. 2, 81,
  140712. _vq_lengthlist__44cn1_sm_p4_0,
  140713. 1, -531628032, 1611661312, 4, 0,
  140714. _vq_quantlist__44cn1_sm_p4_0,
  140715. NULL,
  140716. &_vq_auxt__44cn1_sm_p4_0,
  140717. NULL,
  140718. 0
  140719. };
  140720. static long _vq_quantlist__44cn1_sm_p5_0[] = {
  140721. 8,
  140722. 7,
  140723. 9,
  140724. 6,
  140725. 10,
  140726. 5,
  140727. 11,
  140728. 4,
  140729. 12,
  140730. 3,
  140731. 13,
  140732. 2,
  140733. 14,
  140734. 1,
  140735. 15,
  140736. 0,
  140737. 16,
  140738. };
  140739. static long _vq_lengthlist__44cn1_sm_p5_0[] = {
  140740. 1, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  140741. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  140742. 12,12, 0, 6, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  140743. 11,12,12, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  140744. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,11,
  140745. 11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  140746. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  140747. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  140748. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  140749. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  140750. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  140751. 9,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0, 0,
  140752. 10,10,11,11,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  140753. 0, 0, 0,11,11,11,11,12,12,13,13,14,14, 0, 0, 0,
  140754. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  140755. 0, 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0,
  140756. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,14,14,14,14,
  140757. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,14,14,
  140758. 14,
  140759. };
  140760. static float _vq_quantthresh__44cn1_sm_p5_0[] = {
  140761. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140762. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140763. };
  140764. static long _vq_quantmap__44cn1_sm_p5_0[] = {
  140765. 15, 13, 11, 9, 7, 5, 3, 1,
  140766. 0, 2, 4, 6, 8, 10, 12, 14,
  140767. 16,
  140768. };
  140769. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p5_0 = {
  140770. _vq_quantthresh__44cn1_sm_p5_0,
  140771. _vq_quantmap__44cn1_sm_p5_0,
  140772. 17,
  140773. 17
  140774. };
  140775. static static_codebook _44cn1_sm_p5_0 = {
  140776. 2, 289,
  140777. _vq_lengthlist__44cn1_sm_p5_0,
  140778. 1, -529530880, 1611661312, 5, 0,
  140779. _vq_quantlist__44cn1_sm_p5_0,
  140780. NULL,
  140781. &_vq_auxt__44cn1_sm_p5_0,
  140782. NULL,
  140783. 0
  140784. };
  140785. static long _vq_quantlist__44cn1_sm_p6_0[] = {
  140786. 1,
  140787. 0,
  140788. 2,
  140789. };
  140790. static long _vq_lengthlist__44cn1_sm_p6_0[] = {
  140791. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 6,10, 9, 9,11,
  140792. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  140793. 11,11,11,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  140794. 11,10,11,11,10,10, 7,11,11,11,11,11,12,11,11, 7,
  140795. 9, 9,11,10,10,12,10,10, 7, 9, 9,11,10,10,11,10,
  140796. 10,
  140797. };
  140798. static float _vq_quantthresh__44cn1_sm_p6_0[] = {
  140799. -5.5, 5.5,
  140800. };
  140801. static long _vq_quantmap__44cn1_sm_p6_0[] = {
  140802. 1, 0, 2,
  140803. };
  140804. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_0 = {
  140805. _vq_quantthresh__44cn1_sm_p6_0,
  140806. _vq_quantmap__44cn1_sm_p6_0,
  140807. 3,
  140808. 3
  140809. };
  140810. static static_codebook _44cn1_sm_p6_0 = {
  140811. 4, 81,
  140812. _vq_lengthlist__44cn1_sm_p6_0,
  140813. 1, -529137664, 1618345984, 2, 0,
  140814. _vq_quantlist__44cn1_sm_p6_0,
  140815. NULL,
  140816. &_vq_auxt__44cn1_sm_p6_0,
  140817. NULL,
  140818. 0
  140819. };
  140820. static long _vq_quantlist__44cn1_sm_p6_1[] = {
  140821. 5,
  140822. 4,
  140823. 6,
  140824. 3,
  140825. 7,
  140826. 2,
  140827. 8,
  140828. 1,
  140829. 9,
  140830. 0,
  140831. 10,
  140832. };
  140833. static long _vq_lengthlist__44cn1_sm_p6_1[] = {
  140834. 2, 4, 4, 5, 5, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  140835. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  140836. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  140837. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  140838. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  140839. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  140840. 8, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 8, 9,10,10,
  140841. 10,10,10, 8, 9, 8, 8, 9, 8,
  140842. };
  140843. static float _vq_quantthresh__44cn1_sm_p6_1[] = {
  140844. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  140845. 3.5, 4.5,
  140846. };
  140847. static long _vq_quantmap__44cn1_sm_p6_1[] = {
  140848. 9, 7, 5, 3, 1, 0, 2, 4,
  140849. 6, 8, 10,
  140850. };
  140851. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_1 = {
  140852. _vq_quantthresh__44cn1_sm_p6_1,
  140853. _vq_quantmap__44cn1_sm_p6_1,
  140854. 11,
  140855. 11
  140856. };
  140857. static static_codebook _44cn1_sm_p6_1 = {
  140858. 2, 121,
  140859. _vq_lengthlist__44cn1_sm_p6_1,
  140860. 1, -531365888, 1611661312, 4, 0,
  140861. _vq_quantlist__44cn1_sm_p6_1,
  140862. NULL,
  140863. &_vq_auxt__44cn1_sm_p6_1,
  140864. NULL,
  140865. 0
  140866. };
  140867. static long _vq_quantlist__44cn1_sm_p7_0[] = {
  140868. 6,
  140869. 5,
  140870. 7,
  140871. 4,
  140872. 8,
  140873. 3,
  140874. 9,
  140875. 2,
  140876. 10,
  140877. 1,
  140878. 11,
  140879. 0,
  140880. 12,
  140881. };
  140882. static long _vq_lengthlist__44cn1_sm_p7_0[] = {
  140883. 1, 4, 4, 6, 6, 7, 7, 7, 7, 9, 9,10,10, 7, 5, 5,
  140884. 7, 7, 8, 8, 8, 8,10, 9,11,10, 7, 5, 5, 7, 7, 8,
  140885. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  140886. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  140887. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,12,12, 0,13,
  140888. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10,
  140889. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  140890. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,13,
  140891. 13,13, 0, 0, 0,14,14,11,10,11,11,12,12,13,13, 0,
  140892. 0, 0, 0, 0,12,12,12,12,13,13,13,14, 0, 0, 0, 0,
  140893. 0,13,12,12,12,13,13,13,14,
  140894. };
  140895. static float _vq_quantthresh__44cn1_sm_p7_0[] = {
  140896. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  140897. 12.5, 17.5, 22.5, 27.5,
  140898. };
  140899. static long _vq_quantmap__44cn1_sm_p7_0[] = {
  140900. 11, 9, 7, 5, 3, 1, 0, 2,
  140901. 4, 6, 8, 10, 12,
  140902. };
  140903. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_0 = {
  140904. _vq_quantthresh__44cn1_sm_p7_0,
  140905. _vq_quantmap__44cn1_sm_p7_0,
  140906. 13,
  140907. 13
  140908. };
  140909. static static_codebook _44cn1_sm_p7_0 = {
  140910. 2, 169,
  140911. _vq_lengthlist__44cn1_sm_p7_0,
  140912. 1, -526516224, 1616117760, 4, 0,
  140913. _vq_quantlist__44cn1_sm_p7_0,
  140914. NULL,
  140915. &_vq_auxt__44cn1_sm_p7_0,
  140916. NULL,
  140917. 0
  140918. };
  140919. static long _vq_quantlist__44cn1_sm_p7_1[] = {
  140920. 2,
  140921. 1,
  140922. 3,
  140923. 0,
  140924. 4,
  140925. };
  140926. static long _vq_lengthlist__44cn1_sm_p7_1[] = {
  140927. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  140928. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  140929. };
  140930. static float _vq_quantthresh__44cn1_sm_p7_1[] = {
  140931. -1.5, -0.5, 0.5, 1.5,
  140932. };
  140933. static long _vq_quantmap__44cn1_sm_p7_1[] = {
  140934. 3, 1, 0, 2, 4,
  140935. };
  140936. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_1 = {
  140937. _vq_quantthresh__44cn1_sm_p7_1,
  140938. _vq_quantmap__44cn1_sm_p7_1,
  140939. 5,
  140940. 5
  140941. };
  140942. static static_codebook _44cn1_sm_p7_1 = {
  140943. 2, 25,
  140944. _vq_lengthlist__44cn1_sm_p7_1,
  140945. 1, -533725184, 1611661312, 3, 0,
  140946. _vq_quantlist__44cn1_sm_p7_1,
  140947. NULL,
  140948. &_vq_auxt__44cn1_sm_p7_1,
  140949. NULL,
  140950. 0
  140951. };
  140952. static long _vq_quantlist__44cn1_sm_p8_0[] = {
  140953. 4,
  140954. 3,
  140955. 5,
  140956. 2,
  140957. 6,
  140958. 1,
  140959. 7,
  140960. 0,
  140961. 8,
  140962. };
  140963. static long _vq_lengthlist__44cn1_sm_p8_0[] = {
  140964. 1, 4, 4,12,11,13,13,14,14, 4, 7, 7,11,13,14,14,
  140965. 14,14, 3, 8, 3,14,14,14,14,14,14,14,10,12,14,14,
  140966. 14,14,14,14,14,14, 5,14, 8,14,14,14,14,14,12,14,
  140967. 13,14,14,14,14,14,14,14,13,14,10,14,14,14,14,14,
  140968. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  140969. 14,
  140970. };
  140971. static float _vq_quantthresh__44cn1_sm_p8_0[] = {
  140972. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  140973. };
  140974. static long _vq_quantmap__44cn1_sm_p8_0[] = {
  140975. 7, 5, 3, 1, 0, 2, 4, 6,
  140976. 8,
  140977. };
  140978. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_0 = {
  140979. _vq_quantthresh__44cn1_sm_p8_0,
  140980. _vq_quantmap__44cn1_sm_p8_0,
  140981. 9,
  140982. 9
  140983. };
  140984. static static_codebook _44cn1_sm_p8_0 = {
  140985. 2, 81,
  140986. _vq_lengthlist__44cn1_sm_p8_0,
  140987. 1, -516186112, 1627103232, 4, 0,
  140988. _vq_quantlist__44cn1_sm_p8_0,
  140989. NULL,
  140990. &_vq_auxt__44cn1_sm_p8_0,
  140991. NULL,
  140992. 0
  140993. };
  140994. static long _vq_quantlist__44cn1_sm_p8_1[] = {
  140995. 6,
  140996. 5,
  140997. 7,
  140998. 4,
  140999. 8,
  141000. 3,
  141001. 9,
  141002. 2,
  141003. 10,
  141004. 1,
  141005. 11,
  141006. 0,
  141007. 12,
  141008. };
  141009. static long _vq_lengthlist__44cn1_sm_p8_1[] = {
  141010. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,11,11, 6, 5, 5,
  141011. 7, 7, 8, 8,10,10,10,11,11,11, 6, 5, 5, 7, 7, 8,
  141012. 8,10,10,11,12,12,12,14, 7, 7, 7, 8, 9, 9,11,11,
  141013. 11,12,11,12,17, 7, 7, 8, 7, 9, 9,11,11,12,12,12,
  141014. 12,14,11,11, 8, 8,10,10,11,12,12,13,11,12,14,11,
  141015. 11, 8, 8,10,10,11,12,12,13,13,12,14,15,14,10,10,
  141016. 10,10,11,12,12,12,12,11,14,13,16,10,10,10, 9,12,
  141017. 11,12,12,13,14,14,15,14,14,13,10,10,11,11,12,11,
  141018. 13,11,14,12,15,13,14,11,10,12,10,12,12,13,13,13,
  141019. 13,14,15,15,12,12,11,11,12,11,13,12,14,14,14,14,
  141020. 17,12,12,11,10,13,11,13,13,
  141021. };
  141022. static float _vq_quantthresh__44cn1_sm_p8_1[] = {
  141023. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  141024. 42.5, 59.5, 76.5, 93.5,
  141025. };
  141026. static long _vq_quantmap__44cn1_sm_p8_1[] = {
  141027. 11, 9, 7, 5, 3, 1, 0, 2,
  141028. 4, 6, 8, 10, 12,
  141029. };
  141030. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_1 = {
  141031. _vq_quantthresh__44cn1_sm_p8_1,
  141032. _vq_quantmap__44cn1_sm_p8_1,
  141033. 13,
  141034. 13
  141035. };
  141036. static static_codebook _44cn1_sm_p8_1 = {
  141037. 2, 169,
  141038. _vq_lengthlist__44cn1_sm_p8_1,
  141039. 1, -522616832, 1620115456, 4, 0,
  141040. _vq_quantlist__44cn1_sm_p8_1,
  141041. NULL,
  141042. &_vq_auxt__44cn1_sm_p8_1,
  141043. NULL,
  141044. 0
  141045. };
  141046. static long _vq_quantlist__44cn1_sm_p8_2[] = {
  141047. 8,
  141048. 7,
  141049. 9,
  141050. 6,
  141051. 10,
  141052. 5,
  141053. 11,
  141054. 4,
  141055. 12,
  141056. 3,
  141057. 13,
  141058. 2,
  141059. 14,
  141060. 1,
  141061. 15,
  141062. 0,
  141063. 16,
  141064. };
  141065. static long _vq_lengthlist__44cn1_sm_p8_2[] = {
  141066. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  141067. 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  141068. 9, 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  141069. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  141070. 9, 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,
  141071. 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9, 9,
  141072. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9,
  141073. 9, 9, 9, 9, 9, 9, 9,11,10,11, 8, 8, 8, 8, 8, 8,
  141074. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11, 8, 8, 8,
  141075. 8, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  141076. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,11,11, 9,
  141077. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,10,11,11,
  141078. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,
  141079. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,
  141080. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,11,10,
  141081. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  141082. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  141083. 10,11,11,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  141084. 9,
  141085. };
  141086. static float _vq_quantthresh__44cn1_sm_p8_2[] = {
  141087. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141088. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141089. };
  141090. static long _vq_quantmap__44cn1_sm_p8_2[] = {
  141091. 15, 13, 11, 9, 7, 5, 3, 1,
  141092. 0, 2, 4, 6, 8, 10, 12, 14,
  141093. 16,
  141094. };
  141095. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_2 = {
  141096. _vq_quantthresh__44cn1_sm_p8_2,
  141097. _vq_quantmap__44cn1_sm_p8_2,
  141098. 17,
  141099. 17
  141100. };
  141101. static static_codebook _44cn1_sm_p8_2 = {
  141102. 2, 289,
  141103. _vq_lengthlist__44cn1_sm_p8_2,
  141104. 1, -529530880, 1611661312, 5, 0,
  141105. _vq_quantlist__44cn1_sm_p8_2,
  141106. NULL,
  141107. &_vq_auxt__44cn1_sm_p8_2,
  141108. NULL,
  141109. 0
  141110. };
  141111. static long _huff_lengthlist__44cn1_sm_short[] = {
  141112. 5, 6,12,14,12,14,16,17,18, 4, 2, 5,11, 7,10,12,
  141113. 14,15, 9, 4, 5,11, 7,10,13,15,18,15, 6, 7, 5, 6,
  141114. 8,11,13,16,11, 5, 6, 5, 5, 6, 9,13,15,12, 5, 7,
  141115. 6, 5, 6, 9,12,14,12, 6, 7, 8, 6, 7, 9,12,13,14,
  141116. 8, 8, 7, 5, 5, 8,10,12,16, 9, 9, 8, 6, 6, 7, 9,
  141117. 9,
  141118. };
  141119. static static_codebook _huff_book__44cn1_sm_short = {
  141120. 2, 81,
  141121. _huff_lengthlist__44cn1_sm_short,
  141122. 0, 0, 0, 0, 0,
  141123. NULL,
  141124. NULL,
  141125. NULL,
  141126. NULL,
  141127. 0
  141128. };
  141129. /*** End of inlined file: res_books_stereo.h ***/
  141130. /***** residue backends *********************************************/
  141131. static vorbis_info_residue0 _residue_44_low={
  141132. 0,-1, -1, 9,-1,
  141133. /* 0 1 2 3 4 5 6 7 */
  141134. {0},
  141135. {-1},
  141136. { .5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  141137. { .5, .5, .5, 999., 4.5, 8.5, 16.5, 32.5},
  141138. };
  141139. static vorbis_info_residue0 _residue_44_mid={
  141140. 0,-1, -1, 10,-1,
  141141. /* 0 1 2 3 4 5 6 7 8 */
  141142. {0},
  141143. {-1},
  141144. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  141145. { .5, .5, 999., .5, 999., 4.5, 8.5, 16.5, 32.5},
  141146. };
  141147. static vorbis_info_residue0 _residue_44_high={
  141148. 0,-1, -1, 10,-1,
  141149. /* 0 1 2 3 4 5 6 7 8 */
  141150. {0},
  141151. {-1},
  141152. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  141153. { .5, 1.5, 2.5, 3.5, 4.5, 8.5, 16.5, 71.5,157.5},
  141154. };
  141155. static static_bookblock _resbook_44s_n1={
  141156. {
  141157. {0},{0,0,&_44cn1_s_p1_0},{0,0,&_44cn1_s_p2_0},
  141158. {0,0,&_44cn1_s_p3_0},{0,0,&_44cn1_s_p4_0},{0,0,&_44cn1_s_p5_0},
  141159. {&_44cn1_s_p6_0,&_44cn1_s_p6_1},{&_44cn1_s_p7_0,&_44cn1_s_p7_1},
  141160. {&_44cn1_s_p8_0,&_44cn1_s_p8_1,&_44cn1_s_p8_2}
  141161. }
  141162. };
  141163. static static_bookblock _resbook_44sm_n1={
  141164. {
  141165. {0},{0,0,&_44cn1_sm_p1_0},{0,0,&_44cn1_sm_p2_0},
  141166. {0,0,&_44cn1_sm_p3_0},{0,0,&_44cn1_sm_p4_0},{0,0,&_44cn1_sm_p5_0},
  141167. {&_44cn1_sm_p6_0,&_44cn1_sm_p6_1},{&_44cn1_sm_p7_0,&_44cn1_sm_p7_1},
  141168. {&_44cn1_sm_p8_0,&_44cn1_sm_p8_1,&_44cn1_sm_p8_2}
  141169. }
  141170. };
  141171. static static_bookblock _resbook_44s_0={
  141172. {
  141173. {0},{0,0,&_44c0_s_p1_0},{0,0,&_44c0_s_p2_0},
  141174. {0,0,&_44c0_s_p3_0},{0,0,&_44c0_s_p4_0},{0,0,&_44c0_s_p5_0},
  141175. {&_44c0_s_p6_0,&_44c0_s_p6_1},{&_44c0_s_p7_0,&_44c0_s_p7_1},
  141176. {&_44c0_s_p8_0,&_44c0_s_p8_1,&_44c0_s_p8_2}
  141177. }
  141178. };
  141179. static static_bookblock _resbook_44sm_0={
  141180. {
  141181. {0},{0,0,&_44c0_sm_p1_0},{0,0,&_44c0_sm_p2_0},
  141182. {0,0,&_44c0_sm_p3_0},{0,0,&_44c0_sm_p4_0},{0,0,&_44c0_sm_p5_0},
  141183. {&_44c0_sm_p6_0,&_44c0_sm_p6_1},{&_44c0_sm_p7_0,&_44c0_sm_p7_1},
  141184. {&_44c0_sm_p8_0,&_44c0_sm_p8_1,&_44c0_sm_p8_2}
  141185. }
  141186. };
  141187. static static_bookblock _resbook_44s_1={
  141188. {
  141189. {0},{0,0,&_44c1_s_p1_0},{0,0,&_44c1_s_p2_0},
  141190. {0,0,&_44c1_s_p3_0},{0,0,&_44c1_s_p4_0},{0,0,&_44c1_s_p5_0},
  141191. {&_44c1_s_p6_0,&_44c1_s_p6_1},{&_44c1_s_p7_0,&_44c1_s_p7_1},
  141192. {&_44c1_s_p8_0,&_44c1_s_p8_1,&_44c1_s_p8_2}
  141193. }
  141194. };
  141195. static static_bookblock _resbook_44sm_1={
  141196. {
  141197. {0},{0,0,&_44c1_sm_p1_0},{0,0,&_44c1_sm_p2_0},
  141198. {0,0,&_44c1_sm_p3_0},{0,0,&_44c1_sm_p4_0},{0,0,&_44c1_sm_p5_0},
  141199. {&_44c1_sm_p6_0,&_44c1_sm_p6_1},{&_44c1_sm_p7_0,&_44c1_sm_p7_1},
  141200. {&_44c1_sm_p8_0,&_44c1_sm_p8_1,&_44c1_sm_p8_2}
  141201. }
  141202. };
  141203. static static_bookblock _resbook_44s_2={
  141204. {
  141205. {0},{0,0,&_44c2_s_p1_0},{0,0,&_44c2_s_p2_0},{0,0,&_44c2_s_p3_0},
  141206. {0,0,&_44c2_s_p4_0},{0,0,&_44c2_s_p5_0},{0,0,&_44c2_s_p6_0},
  141207. {&_44c2_s_p7_0,&_44c2_s_p7_1},{&_44c2_s_p8_0,&_44c2_s_p8_1},
  141208. {&_44c2_s_p9_0,&_44c2_s_p9_1,&_44c2_s_p9_2}
  141209. }
  141210. };
  141211. static static_bookblock _resbook_44s_3={
  141212. {
  141213. {0},{0,0,&_44c3_s_p1_0},{0,0,&_44c3_s_p2_0},{0,0,&_44c3_s_p3_0},
  141214. {0,0,&_44c3_s_p4_0},{0,0,&_44c3_s_p5_0},{0,0,&_44c3_s_p6_0},
  141215. {&_44c3_s_p7_0,&_44c3_s_p7_1},{&_44c3_s_p8_0,&_44c3_s_p8_1},
  141216. {&_44c3_s_p9_0,&_44c3_s_p9_1,&_44c3_s_p9_2}
  141217. }
  141218. };
  141219. static static_bookblock _resbook_44s_4={
  141220. {
  141221. {0},{0,0,&_44c4_s_p1_0},{0,0,&_44c4_s_p2_0},{0,0,&_44c4_s_p3_0},
  141222. {0,0,&_44c4_s_p4_0},{0,0,&_44c4_s_p5_0},{0,0,&_44c4_s_p6_0},
  141223. {&_44c4_s_p7_0,&_44c4_s_p7_1},{&_44c4_s_p8_0,&_44c4_s_p8_1},
  141224. {&_44c4_s_p9_0,&_44c4_s_p9_1,&_44c4_s_p9_2}
  141225. }
  141226. };
  141227. static static_bookblock _resbook_44s_5={
  141228. {
  141229. {0},{0,0,&_44c5_s_p1_0},{0,0,&_44c5_s_p2_0},{0,0,&_44c5_s_p3_0},
  141230. {0,0,&_44c5_s_p4_0},{0,0,&_44c5_s_p5_0},{0,0,&_44c5_s_p6_0},
  141231. {&_44c5_s_p7_0,&_44c5_s_p7_1},{&_44c5_s_p8_0,&_44c5_s_p8_1},
  141232. {&_44c5_s_p9_0,&_44c5_s_p9_1,&_44c5_s_p9_2}
  141233. }
  141234. };
  141235. static static_bookblock _resbook_44s_6={
  141236. {
  141237. {0},{0,0,&_44c6_s_p1_0},{0,0,&_44c6_s_p2_0},{0,0,&_44c6_s_p3_0},
  141238. {0,0,&_44c6_s_p4_0},
  141239. {&_44c6_s_p5_0,&_44c6_s_p5_1},
  141240. {&_44c6_s_p6_0,&_44c6_s_p6_1},
  141241. {&_44c6_s_p7_0,&_44c6_s_p7_1},
  141242. {&_44c6_s_p8_0,&_44c6_s_p8_1},
  141243. {&_44c6_s_p9_0,&_44c6_s_p9_1,&_44c6_s_p9_2}
  141244. }
  141245. };
  141246. static static_bookblock _resbook_44s_7={
  141247. {
  141248. {0},{0,0,&_44c7_s_p1_0},{0,0,&_44c7_s_p2_0},{0,0,&_44c7_s_p3_0},
  141249. {0,0,&_44c7_s_p4_0},
  141250. {&_44c7_s_p5_0,&_44c7_s_p5_1},
  141251. {&_44c7_s_p6_0,&_44c7_s_p6_1},
  141252. {&_44c7_s_p7_0,&_44c7_s_p7_1},
  141253. {&_44c7_s_p8_0,&_44c7_s_p8_1},
  141254. {&_44c7_s_p9_0,&_44c7_s_p9_1,&_44c7_s_p9_2}
  141255. }
  141256. };
  141257. static static_bookblock _resbook_44s_8={
  141258. {
  141259. {0},{0,0,&_44c8_s_p1_0},{0,0,&_44c8_s_p2_0},{0,0,&_44c8_s_p3_0},
  141260. {0,0,&_44c8_s_p4_0},
  141261. {&_44c8_s_p5_0,&_44c8_s_p5_1},
  141262. {&_44c8_s_p6_0,&_44c8_s_p6_1},
  141263. {&_44c8_s_p7_0,&_44c8_s_p7_1},
  141264. {&_44c8_s_p8_0,&_44c8_s_p8_1},
  141265. {&_44c8_s_p9_0,&_44c8_s_p9_1,&_44c8_s_p9_2}
  141266. }
  141267. };
  141268. static static_bookblock _resbook_44s_9={
  141269. {
  141270. {0},{0,0,&_44c9_s_p1_0},{0,0,&_44c9_s_p2_0},{0,0,&_44c9_s_p3_0},
  141271. {0,0,&_44c9_s_p4_0},
  141272. {&_44c9_s_p5_0,&_44c9_s_p5_1},
  141273. {&_44c9_s_p6_0,&_44c9_s_p6_1},
  141274. {&_44c9_s_p7_0,&_44c9_s_p7_1},
  141275. {&_44c9_s_p8_0,&_44c9_s_p8_1},
  141276. {&_44c9_s_p9_0,&_44c9_s_p9_1,&_44c9_s_p9_2}
  141277. }
  141278. };
  141279. static vorbis_residue_template _res_44s_n1[]={
  141280. {2,0, &_residue_44_low,
  141281. &_huff_book__44cn1_s_short,&_huff_book__44cn1_sm_short,
  141282. &_resbook_44s_n1,&_resbook_44sm_n1},
  141283. {2,0, &_residue_44_low,
  141284. &_huff_book__44cn1_s_long,&_huff_book__44cn1_sm_long,
  141285. &_resbook_44s_n1,&_resbook_44sm_n1}
  141286. };
  141287. static vorbis_residue_template _res_44s_0[]={
  141288. {2,0, &_residue_44_low,
  141289. &_huff_book__44c0_s_short,&_huff_book__44c0_sm_short,
  141290. &_resbook_44s_0,&_resbook_44sm_0},
  141291. {2,0, &_residue_44_low,
  141292. &_huff_book__44c0_s_long,&_huff_book__44c0_sm_long,
  141293. &_resbook_44s_0,&_resbook_44sm_0}
  141294. };
  141295. static vorbis_residue_template _res_44s_1[]={
  141296. {2,0, &_residue_44_low,
  141297. &_huff_book__44c1_s_short,&_huff_book__44c1_sm_short,
  141298. &_resbook_44s_1,&_resbook_44sm_1},
  141299. {2,0, &_residue_44_low,
  141300. &_huff_book__44c1_s_long,&_huff_book__44c1_sm_long,
  141301. &_resbook_44s_1,&_resbook_44sm_1}
  141302. };
  141303. static vorbis_residue_template _res_44s_2[]={
  141304. {2,0, &_residue_44_mid,
  141305. &_huff_book__44c2_s_short,&_huff_book__44c2_s_short,
  141306. &_resbook_44s_2,&_resbook_44s_2},
  141307. {2,0, &_residue_44_mid,
  141308. &_huff_book__44c2_s_long,&_huff_book__44c2_s_long,
  141309. &_resbook_44s_2,&_resbook_44s_2}
  141310. };
  141311. static vorbis_residue_template _res_44s_3[]={
  141312. {2,0, &_residue_44_mid,
  141313. &_huff_book__44c3_s_short,&_huff_book__44c3_s_short,
  141314. &_resbook_44s_3,&_resbook_44s_3},
  141315. {2,0, &_residue_44_mid,
  141316. &_huff_book__44c3_s_long,&_huff_book__44c3_s_long,
  141317. &_resbook_44s_3,&_resbook_44s_3}
  141318. };
  141319. static vorbis_residue_template _res_44s_4[]={
  141320. {2,0, &_residue_44_mid,
  141321. &_huff_book__44c4_s_short,&_huff_book__44c4_s_short,
  141322. &_resbook_44s_4,&_resbook_44s_4},
  141323. {2,0, &_residue_44_mid,
  141324. &_huff_book__44c4_s_long,&_huff_book__44c4_s_long,
  141325. &_resbook_44s_4,&_resbook_44s_4}
  141326. };
  141327. static vorbis_residue_template _res_44s_5[]={
  141328. {2,0, &_residue_44_mid,
  141329. &_huff_book__44c5_s_short,&_huff_book__44c5_s_short,
  141330. &_resbook_44s_5,&_resbook_44s_5},
  141331. {2,0, &_residue_44_mid,
  141332. &_huff_book__44c5_s_long,&_huff_book__44c5_s_long,
  141333. &_resbook_44s_5,&_resbook_44s_5}
  141334. };
  141335. static vorbis_residue_template _res_44s_6[]={
  141336. {2,0, &_residue_44_high,
  141337. &_huff_book__44c6_s_short,&_huff_book__44c6_s_short,
  141338. &_resbook_44s_6,&_resbook_44s_6},
  141339. {2,0, &_residue_44_high,
  141340. &_huff_book__44c6_s_long,&_huff_book__44c6_s_long,
  141341. &_resbook_44s_6,&_resbook_44s_6}
  141342. };
  141343. static vorbis_residue_template _res_44s_7[]={
  141344. {2,0, &_residue_44_high,
  141345. &_huff_book__44c7_s_short,&_huff_book__44c7_s_short,
  141346. &_resbook_44s_7,&_resbook_44s_7},
  141347. {2,0, &_residue_44_high,
  141348. &_huff_book__44c7_s_long,&_huff_book__44c7_s_long,
  141349. &_resbook_44s_7,&_resbook_44s_7}
  141350. };
  141351. static vorbis_residue_template _res_44s_8[]={
  141352. {2,0, &_residue_44_high,
  141353. &_huff_book__44c8_s_short,&_huff_book__44c8_s_short,
  141354. &_resbook_44s_8,&_resbook_44s_8},
  141355. {2,0, &_residue_44_high,
  141356. &_huff_book__44c8_s_long,&_huff_book__44c8_s_long,
  141357. &_resbook_44s_8,&_resbook_44s_8}
  141358. };
  141359. static vorbis_residue_template _res_44s_9[]={
  141360. {2,0, &_residue_44_high,
  141361. &_huff_book__44c9_s_short,&_huff_book__44c9_s_short,
  141362. &_resbook_44s_9,&_resbook_44s_9},
  141363. {2,0, &_residue_44_high,
  141364. &_huff_book__44c9_s_long,&_huff_book__44c9_s_long,
  141365. &_resbook_44s_9,&_resbook_44s_9}
  141366. };
  141367. static vorbis_mapping_template _mapres_template_44_stereo[]={
  141368. { _map_nominal, _res_44s_n1 }, /* -1 */
  141369. { _map_nominal, _res_44s_0 }, /* 0 */
  141370. { _map_nominal, _res_44s_1 }, /* 1 */
  141371. { _map_nominal, _res_44s_2 }, /* 2 */
  141372. { _map_nominal, _res_44s_3 }, /* 3 */
  141373. { _map_nominal, _res_44s_4 }, /* 4 */
  141374. { _map_nominal, _res_44s_5 }, /* 5 */
  141375. { _map_nominal, _res_44s_6 }, /* 6 */
  141376. { _map_nominal, _res_44s_7 }, /* 7 */
  141377. { _map_nominal, _res_44s_8 }, /* 8 */
  141378. { _map_nominal, _res_44s_9 }, /* 9 */
  141379. };
  141380. /*** End of inlined file: residue_44.h ***/
  141381. /*** Start of inlined file: psych_44.h ***/
  141382. /* preecho trigger settings *****************************************/
  141383. static vorbis_info_psy_global _psy_global_44[5]={
  141384. {8, /* lines per eighth octave */
  141385. {20.f,14.f,12.f,12.f,12.f,12.f,12.f},
  141386. {-60.f,-30.f,-40.f,-40.f,-40.f,-40.f,-40.f}, 2,-75.f,
  141387. -6.f,
  141388. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141389. },
  141390. {8, /* lines per eighth octave */
  141391. {14.f,10.f,10.f,10.f,10.f,10.f,10.f},
  141392. {-40.f,-30.f,-25.f,-25.f,-25.f,-25.f,-25.f}, 2,-80.f,
  141393. -6.f,
  141394. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141395. },
  141396. {8, /* lines per eighth octave */
  141397. {12.f,10.f,10.f,10.f,10.f,10.f,10.f},
  141398. {-20.f,-20.f,-15.f,-15.f,-15.f,-15.f,-15.f}, 0,-80.f,
  141399. -6.f,
  141400. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141401. },
  141402. {8, /* lines per eighth octave */
  141403. {10.f,8.f,8.f,8.f,8.f,8.f,8.f},
  141404. {-20.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-80.f,
  141405. -6.f,
  141406. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141407. },
  141408. {8, /* lines per eighth octave */
  141409. {10.f,6.f,6.f,6.f,6.f,6.f,6.f},
  141410. {-15.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-85.f,
  141411. -6.f,
  141412. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141413. },
  141414. };
  141415. /* noise compander lookups * low, mid, high quality ****************/
  141416. static compandblock _psy_compand_44[6]={
  141417. /* sub-mode Z short */
  141418. {{
  141419. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  141420. 8, 9,10,11,12,13,14, 15, /* 15dB */
  141421. 16,17,18,19,20,21,22, 23, /* 23dB */
  141422. 24,25,26,27,28,29,30, 31, /* 31dB */
  141423. 32,33,34,35,36,37,38, 39, /* 39dB */
  141424. }},
  141425. /* mode_Z nominal short */
  141426. {{
  141427. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  141428. 7, 7, 7, 7, 6, 6, 6, 7, /* 15dB */
  141429. 7, 8, 9,10,11,12,13, 14, /* 23dB */
  141430. 15,16,17,17,17,18,18, 19, /* 31dB */
  141431. 19,19,20,21,22,23,24, 25, /* 39dB */
  141432. }},
  141433. /* mode A short */
  141434. {{
  141435. 0, 1, 2, 3, 4, 5, 5, 5, /* 7dB */
  141436. 6, 6, 6, 5, 4, 4, 4, 4, /* 15dB */
  141437. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  141438. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  141439. 11,12,13,14,15,16,17, 18, /* 39dB */
  141440. }},
  141441. /* sub-mode Z long */
  141442. {{
  141443. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  141444. 8, 9,10,11,12,13,14, 15, /* 15dB */
  141445. 16,17,18,19,20,21,22, 23, /* 23dB */
  141446. 24,25,26,27,28,29,30, 31, /* 31dB */
  141447. 32,33,34,35,36,37,38, 39, /* 39dB */
  141448. }},
  141449. /* mode_Z nominal long */
  141450. {{
  141451. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  141452. 8, 9,10,11,12,12,13, 13, /* 15dB */
  141453. 13,14,14,14,15,15,15, 15, /* 23dB */
  141454. 16,16,17,17,17,18,18, 19, /* 31dB */
  141455. 19,19,20,21,22,23,24, 25, /* 39dB */
  141456. }},
  141457. /* mode A long */
  141458. {{
  141459. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  141460. 8, 8, 7, 6, 5, 4, 4, 4, /* 15dB */
  141461. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  141462. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  141463. 11,12,13,14,15,16,17, 18, /* 39dB */
  141464. }}
  141465. };
  141466. /* tonal masking curve level adjustments *************************/
  141467. static vp_adjblock _vp_tonemask_adj_longblock[12]={
  141468. /* 63 125 250 500 1 2 4 8 16 */
  141469. {{ -3, -8,-13,-15,-10,-10,-10,-10,-10,-10,-10, 0, 0, 0, 0, 0, 0}}, /* -1 */
  141470. /* {{-15,-15,-15,-15,-10, -8, -4, -2, 0, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  141471. {{ -4,-10,-14,-16,-15,-14,-13,-12,-12,-12,-11, -1, -1, -1, -1, -1, 0}}, /* 0 */
  141472. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  141473. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, -1, -1, 0}}, /* 1 */
  141474. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  141475. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -6, -3, -1, -1, -1, 0}}, /* 2 */
  141476. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  141477. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, -1, -1, 0}}, /* 3 */
  141478. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, *//* 4 */
  141479. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  141480. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  141481. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  141482. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  141483. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  141484. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  141485. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  141486. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  141487. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  141488. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  141489. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  141490. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  141491. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  141492. };
  141493. static vp_adjblock _vp_tonemask_adj_otherblock[12]={
  141494. /* 63 125 250 500 1 2 4 8 16 */
  141495. {{ -3, -8,-13,-15,-10,-10, -9, -9, -9, -9, -9, 1, 1, 1, 1, 1, 1}}, /* -1 */
  141496. /* {{-20,-20,-20,-20,-14,-12,-10, -8, -4, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  141497. {{ -4,-10,-14,-16,-14,-13,-12,-12,-11,-11,-10, 0, 0, 0, 0, 0, 0}}, /* 0 */
  141498. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  141499. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, 0, 0, 0}}, /* 1 */
  141500. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  141501. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -5, -2, -1, 0, 0, 0}}, /* 2 */
  141502. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  141503. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, 0, 0, 0}}, /* 3 */
  141504. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 4 */
  141505. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  141506. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  141507. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  141508. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  141509. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  141510. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  141511. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  141512. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  141513. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  141514. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  141515. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  141516. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  141517. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  141518. };
  141519. /* noise bias (transition block) */
  141520. static noise3 _psy_noisebias_trans[12]={
  141521. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  141522. /* -1 */
  141523. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  141524. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  141525. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  141526. /* 0
  141527. {{{-15,-15,-15,-15,-15,-12,-10, -8, 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, 4, 10},
  141529. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  141530. {{{-15,-15,-15,-15,-15,-12, -6, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  141531. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 3, 6},
  141532. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},
  141533. /* 1
  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, 2, 8},
  141536. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  141537. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  141538. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  141539. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  141540. /* 2
  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, -2, -2, -2, -2, 0, 2, 6},
  141543. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}}, */
  141544. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  141545. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  141546. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -7, -4}}},
  141547. /* 3
  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, -1, 1, 6},
  141550. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  141551. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  141552. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  141553. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  141554. /* 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, -1, 1, 5},
  141557. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  141558. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141559. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  141560. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  141561. /* 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, -2, -1, 2},
  141564. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}}, */
  141565. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141566. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  141567. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},
  141568. /* 6
  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, -4, -2, 1},
  141571. {-34,-34,-34,-34,-30,-26,-24,-18,-17,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  141572. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141573. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  141574. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},
  141575. /* 7
  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,-18,-14,-12,-10, -8, -8, -8, -6, -4, 0},
  141578. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},*/
  141579. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141580. {-32,-32,-32,-32,-28,-24,-24,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  141581. {-34,-34,-34,-34,-30,-26,-26,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  141582. /* 8
  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,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  141585. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  141586. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  141587. {-36,-36,-36,-36,-30,-30,-30,-24,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  141588. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-30,-30,-30,-30,-30,-30,-24,-20}}},
  141589. /* 9
  141590. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  141591. {-36,-36,-36,-36,-34,-32,-32,-28,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  141592. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  141593. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  141594. {-38,-38,-38,-38,-36,-34,-34,-30,-24,-20,-20,-20,-20,-18,-16,-12,-10},
  141595. {-40,-40,-40,-40,-40,-40,-40,-38,-35,-35,-35,-35,-35,-35,-35,-35,-30}}},
  141596. /* 10 */
  141597. {{{-30,-30,-30,-30,-30,-30,-30,-28,-20,-14,-14,-14,-14,-14,-14,-12,-10},
  141598. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-20},
  141599. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  141600. };
  141601. /* noise bias (long block) */
  141602. static noise3 _psy_noisebias_long[12]={
  141603. /*63 125 250 500 1k 2k 4k 8k 16k*/
  141604. /* -1 */
  141605. {{{-10,-10,-10,-10,-10, -4, 0, 0, 0, 6, 6, 6, 6, 10, 10, 12, 20},
  141606. {-20,-20,-20,-20,-20,-20,-10, -2, 0, 0, 0, 0, 0, 2, 4, 6, 15},
  141607. {-20,-20,-20,-20,-20,-20,-20,-10, -6, -6, -6, -6, -6, -4, -4, -4, -2}}},
  141608. /* 0 */
  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, 4, 10},
  141611. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  141612. {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  141613. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 3, 6},
  141614. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},
  141615. /* 1 */
  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, 2, 8},
  141618. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  141619. {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  141620. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  141621. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  141622. /* 2 */
  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, -2, -2, -2, -2, 0, 2, 6},
  141625. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  141626. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  141627. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  141628. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  141629. /* 3 */
  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, -1, 1, 6},
  141632. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  141633. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  141634. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  141635. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -5}}},
  141636. /* 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, -1, 1, 5},
  141639. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  141640. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  141641. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  141642. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -7}}},
  141643. /* 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, -2, -1, 2},
  141646. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},*/
  141647. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  141648. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  141649. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -8}}},
  141650. /* 6 */
  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, -4, -2, 1},
  141653. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  141654. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  141655. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  141656. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12,-10}}},
  141657. /* 7 */
  141658. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  141659. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-10, -8, -8, -8, -8, -6, -4, 0},
  141660. {-26,-26,-26,-26,-26,-26,-26,-22,-20,-19,-19,-19,-19,-18,-17,-16,-12}}},
  141661. /* 8 */
  141662. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 0, 0, 0, 0, 1, 2, 3, 7},
  141663. {-26,-26,-26,-26,-26,-26,-26,-20,-16,-12,-10,-10,-10,-10, -8, -6, -2},
  141664. {-28,-28,-28,-28,-28,-28,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  141665. /* 9 */
  141666. {{{-22,-22,-22,-22,-22,-22,-22,-18,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  141667. {-26,-26,-26,-26,-26,-26,-26,-22,-18,-16,-16,-16,-16,-14,-12,-10, -7},
  141668. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  141669. /* 10 */
  141670. {{{-24,-24,-24,-24,-24,-24,-24,-24,-24,-18,-14,-14,-14,-14,-14,-12,-10},
  141671. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-20},
  141672. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  141673. };
  141674. /* noise bias (impulse block) */
  141675. static noise3 _psy_noisebias_impulse[12]={
  141676. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  141677. /* -1 */
  141678. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  141679. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  141680. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  141681. /* 0 */
  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, 4, 10},
  141684. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},*/
  141685. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  141686. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 3, 6},
  141687. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  141688. /* 1 */
  141689. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  141690. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -4, -4, -2, -2, -2, -2, 2},
  141691. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8,-10,-10, -8, -8, -8, -6, -4}}},
  141692. /* 2 */
  141693. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  141694. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  141695. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  141696. /* 3 */
  141697. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  141698. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  141699. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  141700. /* 4 */
  141701. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  141702. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  141703. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  141704. /* 5 */
  141705. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  141706. {-32,-32,-32,-32,-28,-24,-22,-16,-10, -6, -8, -8, -6, -6, -6, -4, -2},
  141707. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-12,-12,-12,-12,-12,-10, -9, -5}}},
  141708. /* 6
  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,-24,-20,-12,-12,-14,-14,-10, -9, -8, -6, -4},
  141711. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-15,-15,-15,-15,-15,-13,-12, -8}}},*/
  141712. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  141713. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-16,-16,-16,-16,-16,-14,-14,-12},
  141714. {-36,-36,-36,-36,-36,-34,-28,-24,-20,-20,-20,-20,-20,-20,-20,-18,-16}}},
  141715. /* 7 */
  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,-24,-20,-14,-14,-16,-16,-14,-12,-10,-10,-10},
  141718. {-34,-34,-34,-34,-32,-32,-30,-24,-20,-19,-19,-19,-19,-19,-17,-16,-12}}},*/
  141719. {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  141720. {-34,-34,-34,-34,-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-24,-22},
  141721. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  141722. /* 8 */
  141723. /* {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  141724. {-34,-34,-34,-34,-30,-30,-30,-24,-20,-20,-20,-20,-20,-18,-16,-16,-14},
  141725. {-36,-36,-36,-36,-36,-34,-28,-24,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  141726. {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  141727. {-34,-34,-34,-34,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-24},
  141728. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  141729. /* 9 */
  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,-22,-20,-20,-18},
  141732. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  141733. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  141734. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26},
  141735. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  141736. /* 10 */
  141737. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-16,-16,-16,-16,-16,-14,-12},
  141738. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-26},
  141739. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  141740. };
  141741. /* noise bias (padding block) */
  141742. static noise3 _psy_noisebias_padding[12]={
  141743. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  141744. /* -1 */
  141745. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  141746. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  141747. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  141748. /* 0 */
  141749. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  141750. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, 2, 3, 6, 6, 8, 10},
  141751. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -4, -4, -4, -4, -2, 0, 2}}},
  141752. /* 1 */
  141753. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  141754. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  141755. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -6, -4, -2, 0}}},
  141756. /* 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, -4, 0, 0, 0, 2, 2, 4, 8},
  141759. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},*/
  141760. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  141761. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  141762. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  141763. /* 3 */
  141764. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  141765. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  141766. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  141767. /* 4 */
  141768. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  141769. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, -1, 0, 2, 6},
  141770. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  141771. /* 5 */
  141772. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  141773. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -3, -3, -3, -3, -2, 0, 4},
  141774. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-10,-10,-10,-10,-10, -8, -5, -3}}},
  141775. /* 6 */
  141776. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  141777. {-34,-34,-34,-34,-30,-30,-24,-20,-14, -8, -4, -4, -4, -4, -3, -1, 4},
  141778. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-13,-13,-13,-13,-13,-11, -8, -6}}},
  141779. /* 7 */
  141780. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  141781. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-10, -8, -6, -6, -6, -5, -3, 1},
  141782. {-34,-34,-34,-34,-32,-32,-28,-22,-18,-16,-16,-16,-16,-16,-14,-12,-10}}},
  141783. /* 8 */
  141784. {{{-22,-22,-22,-22,-22,-20,-14,-10, -4, 0, 0, 0, 0, 3, 5, 5, 11},
  141785. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-12,-10, -8, -8, -8, -7, -5, -2},
  141786. {-36,-36,-36,-36,-36,-34,-28,-22,-20,-20,-20,-20,-20,-20,-20,-16,-14}}},
  141787. /* 9 */
  141788. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -2, -2, -2, -2, 0, 2, 6},
  141789. {-36,-36,-36,-36,-34,-32,-32,-24,-16,-12,-12,-12,-12,-12,-10, -8, -5},
  141790. {-40,-40,-40,-40,-40,-40,-40,-32,-26,-24,-24,-24,-24,-24,-24,-20,-18}}},
  141791. /* 10 */
  141792. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-12,-12,-12,-12,-12,-10, -8},
  141793. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-25,-25,-25,-25,-25,-25,-15},
  141794. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  141795. };
  141796. static noiseguard _psy_noiseguards_44[4]={
  141797. {3,3,15},
  141798. {3,3,15},
  141799. {10,10,100},
  141800. {10,10,100},
  141801. };
  141802. static int _psy_tone_suppress[12]={
  141803. -20,-20,-20,-20,-20,-24,-30,-40,-40,-45,-45,-45,
  141804. };
  141805. static int _psy_tone_0dB[12]={
  141806. 90,90,95,95,95,95,105,105,105,105,105,105,
  141807. };
  141808. static int _psy_noise_suppress[12]={
  141809. -20,-20,-24,-24,-24,-24,-30,-40,-40,-45,-45,-45,
  141810. };
  141811. static vorbis_info_psy _psy_info_template={
  141812. /* blockflag */
  141813. -1,
  141814. /* ath_adjatt, ath_maxatt */
  141815. -140.,-140.,
  141816. /* tonemask att boost/decay,suppr,curves */
  141817. {0.f,0.f,0.f}, 0.,0., -40.f, {0.},
  141818. /*noisemaskp,supp, low/high window, low/hi guard, minimum */
  141819. 1, -0.f, .5f, .5f, 0,0,0,
  141820. /* noiseoffset*3, noisecompand, max_curve_dB */
  141821. {{-1},{-1},{-1}},{-1},105.f,
  141822. /* noise normalization - channel_p, point_p, start, partition, thresh. */
  141823. 0,0,-1,-1,0.,
  141824. };
  141825. /* ath ****************/
  141826. static int _psy_ath_floater[12]={
  141827. -100,-100,-100,-100,-100,-100,-105,-105,-105,-105,-110,-120,
  141828. };
  141829. static int _psy_ath_abs[12]={
  141830. -130,-130,-130,-130,-140,-140,-140,-140,-140,-140,-140,-150,
  141831. };
  141832. /* stereo setup. These don't map directly to quality level, there's
  141833. an additional indirection as several of the below may be used in a
  141834. single bitmanaged stream
  141835. ****************/
  141836. /* various stereo possibilities */
  141837. /* stereo mode by base quality level */
  141838. static adj_stereo _psy_stereo_modes_44[12]={
  141839. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -1 */
  141840. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  141841. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  141842. { 1, 2, 3, 4, 4, 4, 4, 4, 4, 5, 6, 7, 8, 8, 8},
  141843. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  141844. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 0 */
  141845. /*{{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  141846. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  141847. { 1, 2, 3, 4, 5, 5, 6, 6, 6, 6, 6, 7, 8, 8, 8},
  141848. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  141849. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 1, 0, 0, 0, 0, 0},
  141850. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  141851. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  141852. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  141853. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 */
  141854. {{ 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 0, 0, 0, 0, 0},
  141855. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  141856. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  141857. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  141858. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 2 */
  141859. /* {{ 3, 3, 3, 3, 3, 3, 2, 2, 2, 1, 0, 0, 0, 0, 0},
  141860. { 8, 8, 8, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3, 2, 1},
  141861. { 3, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  141862. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  141863. {{ 3, 3, 3, 3, 3, 3, 3, 2, 1, 1, 0, 0, 0, 0, 0},
  141864. { 8, 8, 6, 6, 5, 5, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  141865. { 3, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  141866. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  141867. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 3 */
  141868. {{ 2, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0},
  141869. { 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  141870. { 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 10, 10, 10, 10, 10},
  141871. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  141872. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 4 */
  141873. {{ 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141874. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 2, 1, 0},
  141875. { 6, 6, 6, 8, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10},
  141876. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  141877. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 5 */
  141878. /* {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141879. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  141880. { 6, 6, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  141881. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  141882. {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141883. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  141884. { 6, 7, 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12},
  141885. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  141886. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 6 */
  141887. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141888. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141889. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  141890. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  141891. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141892. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141893. { 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  141894. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  141895. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 7 */
  141896. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141897. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141898. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  141899. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  141900. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141901. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141902. { 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  141903. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  141904. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 8 */
  141905. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141906. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141907. { 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  141908. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  141909. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141910. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141911. { 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  141912. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  141913. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 9 */
  141914. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141915. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141916. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  141917. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  141918. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 10 */
  141919. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141920. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141921. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  141922. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  141923. };
  141924. /* tone master attenuation by base quality mode and bitrate tweak */
  141925. static att3 _psy_tone_masteratt_44[12]={
  141926. {{ 35, 21, 9}, 0, 0}, /* -1 */
  141927. {{ 30, 20, 8}, -2, 1.25}, /* 0 */
  141928. /* {{ 25, 14, 4}, 0, 0}, *//* 1 */
  141929. {{ 25, 12, 2}, 0, 0}, /* 1 */
  141930. /* {{ 20, 10, -2}, 0, 0}, *//* 2 */
  141931. {{ 20, 9, -3}, 0, 0}, /* 2 */
  141932. {{ 20, 9, -4}, 0, 0}, /* 3 */
  141933. {{ 20, 9, -4}, 0, 0}, /* 4 */
  141934. {{ 20, 6, -6}, 0, 0}, /* 5 */
  141935. {{ 20, 3, -10}, 0, 0}, /* 6 */
  141936. {{ 18, 1, -14}, 0, 0}, /* 7 */
  141937. {{ 18, 0, -16}, 0, 0}, /* 8 */
  141938. {{ 18, -2, -16}, 0, 0}, /* 9 */
  141939. {{ 12, -2, -20}, 0, 0}, /* 10 */
  141940. };
  141941. /* lowpass by mode **************/
  141942. static double _psy_lowpass_44[12]={
  141943. /* 15.1,15.8,16.5,17.9,20.5,48.,999.,999.,999.,999.,999. */
  141944. 13.9,15.1,15.8,16.5,17.2,18.9,20.1,48.,999.,999.,999.,999.
  141945. };
  141946. /* noise normalization **********/
  141947. static int _noise_start_short_44[11]={
  141948. /* 16,16,16,16,32,32,9999,9999,9999,9999 */
  141949. 32,16,16,16,32,9999,9999,9999,9999,9999,9999
  141950. };
  141951. static int _noise_start_long_44[11]={
  141952. /* 128,128,128,256,512,512,9999,9999,9999,9999 */
  141953. 256,128,128,256,512,9999,9999,9999,9999,9999,9999
  141954. };
  141955. static int _noise_part_short_44[11]={
  141956. 8,8,8,8,8,8,8,8,8,8,8
  141957. };
  141958. static int _noise_part_long_44[11]={
  141959. 32,32,32,32,32,32,32,32,32,32,32
  141960. };
  141961. static double _noise_thresh_44[11]={
  141962. /* .2,.2,.3,.4,.5,.5,9999.,9999.,9999.,9999., */
  141963. .2,.2,.2,.4,.6,9999.,9999.,9999.,9999.,9999.,9999.,
  141964. };
  141965. static double _noise_thresh_5only[2]={
  141966. .5,.5,
  141967. };
  141968. /*** End of inlined file: psych_44.h ***/
  141969. static double rate_mapping_44_stereo[12]={
  141970. 22500.,32000.,40000.,48000.,56000.,64000.,
  141971. 80000.,96000.,112000.,128000.,160000.,250001.
  141972. };
  141973. static double quality_mapping_44[12]={
  141974. -.1,.0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0
  141975. };
  141976. static int blocksize_short_44[11]={
  141977. 512,256,256,256,256,256,256,256,256,256,256
  141978. };
  141979. static int blocksize_long_44[11]={
  141980. 4096,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048
  141981. };
  141982. static double _psy_compand_short_mapping[12]={
  141983. 0.5, 1., 1., 1.3, 1.6, 2., 2., 2., 2., 2., 2., 2.
  141984. };
  141985. static double _psy_compand_long_mapping[12]={
  141986. 3.5, 4., 4., 4.3, 4.6, 5., 5., 5., 5., 5., 5., 5.
  141987. };
  141988. static double _global_mapping_44[12]={
  141989. /* 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.5, 4., 4. */
  141990. 0., 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.7, 4., 4.
  141991. };
  141992. static int _floor_short_mapping_44[11]={
  141993. 1,0,0,2,2,4,5,5,5,5,5
  141994. };
  141995. static int _floor_long_mapping_44[11]={
  141996. 8,7,7,7,7,7,7,7,7,7,7
  141997. };
  141998. ve_setup_data_template ve_setup_44_stereo={
  141999. 11,
  142000. rate_mapping_44_stereo,
  142001. quality_mapping_44,
  142002. 2,
  142003. 40000,
  142004. 50000,
  142005. blocksize_short_44,
  142006. blocksize_long_44,
  142007. _psy_tone_masteratt_44,
  142008. _psy_tone_0dB,
  142009. _psy_tone_suppress,
  142010. _vp_tonemask_adj_otherblock,
  142011. _vp_tonemask_adj_longblock,
  142012. _vp_tonemask_adj_otherblock,
  142013. _psy_noiseguards_44,
  142014. _psy_noisebias_impulse,
  142015. _psy_noisebias_padding,
  142016. _psy_noisebias_trans,
  142017. _psy_noisebias_long,
  142018. _psy_noise_suppress,
  142019. _psy_compand_44,
  142020. _psy_compand_short_mapping,
  142021. _psy_compand_long_mapping,
  142022. {_noise_start_short_44,_noise_start_long_44},
  142023. {_noise_part_short_44,_noise_part_long_44},
  142024. _noise_thresh_44,
  142025. _psy_ath_floater,
  142026. _psy_ath_abs,
  142027. _psy_lowpass_44,
  142028. _psy_global_44,
  142029. _global_mapping_44,
  142030. _psy_stereo_modes_44,
  142031. _floor_books,
  142032. _floor,
  142033. _floor_short_mapping_44,
  142034. _floor_long_mapping_44,
  142035. _mapres_template_44_stereo
  142036. };
  142037. /*** End of inlined file: setup_44.h ***/
  142038. /*** Start of inlined file: setup_44u.h ***/
  142039. /*** Start of inlined file: residue_44u.h ***/
  142040. /*** Start of inlined file: res_books_uncoupled.h ***/
  142041. static long _vq_quantlist__16u0__p1_0[] = {
  142042. 1,
  142043. 0,
  142044. 2,
  142045. };
  142046. static long _vq_lengthlist__16u0__p1_0[] = {
  142047. 1, 4, 4, 5, 7, 7, 5, 7, 8, 5, 8, 8, 8,10,10, 8,
  142048. 10,11, 5, 8, 8, 8,10,10, 8,10,10, 4, 9, 9, 9,12,
  142049. 11, 8,11,11, 8,12,11,10,12,14,10,13,13, 7,11,11,
  142050. 10,14,12,11,14,14, 4, 9, 9, 8,11,11, 9,11,12, 7,
  142051. 11,11,10,13,14,10,12,14, 8,11,12,10,14,14,10,13,
  142052. 12,
  142053. };
  142054. static float _vq_quantthresh__16u0__p1_0[] = {
  142055. -0.5, 0.5,
  142056. };
  142057. static long _vq_quantmap__16u0__p1_0[] = {
  142058. 1, 0, 2,
  142059. };
  142060. static encode_aux_threshmatch _vq_auxt__16u0__p1_0 = {
  142061. _vq_quantthresh__16u0__p1_0,
  142062. _vq_quantmap__16u0__p1_0,
  142063. 3,
  142064. 3
  142065. };
  142066. static static_codebook _16u0__p1_0 = {
  142067. 4, 81,
  142068. _vq_lengthlist__16u0__p1_0,
  142069. 1, -535822336, 1611661312, 2, 0,
  142070. _vq_quantlist__16u0__p1_0,
  142071. NULL,
  142072. &_vq_auxt__16u0__p1_0,
  142073. NULL,
  142074. 0
  142075. };
  142076. static long _vq_quantlist__16u0__p2_0[] = {
  142077. 1,
  142078. 0,
  142079. 2,
  142080. };
  142081. static long _vq_lengthlist__16u0__p2_0[] = {
  142082. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 9, 7,
  142083. 8, 9, 5, 7, 7, 7, 9, 8, 7, 9, 7, 4, 7, 7, 7, 9,
  142084. 9, 7, 8, 8, 6, 9, 8, 7, 8,11, 9,11,10, 6, 8, 9,
  142085. 8,11, 8, 9,10,11, 4, 7, 7, 7, 8, 8, 7, 9, 9, 6,
  142086. 9, 8, 9,11,10, 8, 8,11, 6, 8, 9, 9,10,11, 8,11,
  142087. 8,
  142088. };
  142089. static float _vq_quantthresh__16u0__p2_0[] = {
  142090. -0.5, 0.5,
  142091. };
  142092. static long _vq_quantmap__16u0__p2_0[] = {
  142093. 1, 0, 2,
  142094. };
  142095. static encode_aux_threshmatch _vq_auxt__16u0__p2_0 = {
  142096. _vq_quantthresh__16u0__p2_0,
  142097. _vq_quantmap__16u0__p2_0,
  142098. 3,
  142099. 3
  142100. };
  142101. static static_codebook _16u0__p2_0 = {
  142102. 4, 81,
  142103. _vq_lengthlist__16u0__p2_0,
  142104. 1, -535822336, 1611661312, 2, 0,
  142105. _vq_quantlist__16u0__p2_0,
  142106. NULL,
  142107. &_vq_auxt__16u0__p2_0,
  142108. NULL,
  142109. 0
  142110. };
  142111. static long _vq_quantlist__16u0__p3_0[] = {
  142112. 2,
  142113. 1,
  142114. 3,
  142115. 0,
  142116. 4,
  142117. };
  142118. static long _vq_lengthlist__16u0__p3_0[] = {
  142119. 1, 5, 5, 7, 7, 6, 7, 7, 8, 8, 6, 7, 8, 8, 8, 8,
  142120. 9, 9,11,11, 8, 9, 9,11,11, 6, 9, 8,10,10, 8,10,
  142121. 10,11,11, 8,10,10,11,11,10,11,10,13,12, 9,11,10,
  142122. 13,13, 6, 8, 9,10,10, 8,10,10,11,11, 8,10,10,11,
  142123. 11, 9,10,11,13,12,10,10,11,12,12, 8,11,11,14,13,
  142124. 10,12,11,15,13, 9,12,11,15,14,12,14,13,16,14,12,
  142125. 13,13,17,14, 8,11,11,13,14, 9,11,12,14,15,10,11,
  142126. 12,13,15,11,13,13,14,16,12,13,14,14,16, 5, 9, 9,
  142127. 11,11, 9,11,11,12,12, 8,11,11,12,12,11,12,12,15,
  142128. 14,10,12,12,15,15, 8,11,11,13,12,10,12,12,13,13,
  142129. 10,12,12,14,13,12,12,13,14,15,11,13,13,17,16, 7,
  142130. 11,11,13,13,10,12,12,14,13,10,12,12,13,14,12,13,
  142131. 12,15,14,11,13,13,15,14, 9,12,12,16,15,11,13,13,
  142132. 17,16,10,13,13,16,16,13,14,15,15,16,13,15,14,19,
  142133. 17, 9,12,12,14,16,11,13,13,15,16,10,13,13,17,16,
  142134. 13,14,13,17,15,12,15,15,16,17, 5, 9, 9,11,11, 8,
  142135. 11,11,13,12, 9,11,11,12,12,10,12,12,14,15,11,12,
  142136. 12,14,14, 7,11,10,13,12,10,12,12,14,13,10,11,12,
  142137. 13,13,11,13,13,15,16,12,12,13,15,15, 7,11,11,13,
  142138. 13,10,13,13,14,14,10,12,12,13,13,11,13,13,16,15,
  142139. 12,13,13,15,14, 9,12,12,15,15,10,13,13,17,16,11,
  142140. 12,13,15,15,12,15,14,18,18,13,14,14,16,17, 9,12,
  142141. 12,15,16,10,13,13,15,16,11,13,13,15,16,13,15,15,
  142142. 17,17,13,15,14,16,15, 7,11,11,15,16,10,13,12,16,
  142143. 17,10,12,13,15,17,15,16,16,18,17,13,15,15,17,18,
  142144. 8,12,12,16,16,11,13,14,17,18,11,13,13,18,16,15,
  142145. 17,16,17,19,14,15,15,17,16, 8,12,12,16,15,11,14,
  142146. 13,18,17,11,13,14,18,17,15,16,16,18,17,13,16,16,
  142147. 18,18,11,15,14,18,17,13,14,15,18, 0,12,15,15, 0,
  142148. 17,17,16,17,17,18,14,16,18,18, 0,11,14,14,17, 0,
  142149. 12,15,14,17,19,12,15,14,18, 0,15,18,16, 0,17,14,
  142150. 18,16,18, 0, 7,11,11,16,15,10,12,12,18,16,10,13,
  142151. 13,16,15,13,15,14,17,17,14,16,16,19,18, 8,12,12,
  142152. 16,16,11,13,13,18,16,11,13,14,17,16,14,15,15,19,
  142153. 18,15,16,16, 0,19, 8,12,12,16,17,11,13,13,17,17,
  142154. 11,14,13,17,17,13,15,15,17,19,15,17,17,19, 0,11,
  142155. 14,15,19,17,12,15,16,18,18,12,14,15,19,17,14,16,
  142156. 17, 0,18,16,16,19,17, 0,11,14,14,18,19,12,15,14,
  142157. 17,17,13,16,14,17,16,14,17,16,18,18,15,18,15, 0,
  142158. 18,
  142159. };
  142160. static float _vq_quantthresh__16u0__p3_0[] = {
  142161. -1.5, -0.5, 0.5, 1.5,
  142162. };
  142163. static long _vq_quantmap__16u0__p3_0[] = {
  142164. 3, 1, 0, 2, 4,
  142165. };
  142166. static encode_aux_threshmatch _vq_auxt__16u0__p3_0 = {
  142167. _vq_quantthresh__16u0__p3_0,
  142168. _vq_quantmap__16u0__p3_0,
  142169. 5,
  142170. 5
  142171. };
  142172. static static_codebook _16u0__p3_0 = {
  142173. 4, 625,
  142174. _vq_lengthlist__16u0__p3_0,
  142175. 1, -533725184, 1611661312, 3, 0,
  142176. _vq_quantlist__16u0__p3_0,
  142177. NULL,
  142178. &_vq_auxt__16u0__p3_0,
  142179. NULL,
  142180. 0
  142181. };
  142182. static long _vq_quantlist__16u0__p4_0[] = {
  142183. 2,
  142184. 1,
  142185. 3,
  142186. 0,
  142187. 4,
  142188. };
  142189. static long _vq_lengthlist__16u0__p4_0[] = {
  142190. 3, 5, 5, 8, 8, 6, 6, 6, 9, 9, 6, 6, 6, 9, 9, 9,
  142191. 10, 9,11,11, 9, 9, 9,11,11, 6, 7, 7,10,10, 7, 7,
  142192. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  142193. 11,12, 6, 7, 7,10,10, 7, 8, 7,10,10, 7, 8, 7,10,
  142194. 10,10,11,10,12,11,10,10,10,13,10, 9,10,10,12,12,
  142195. 10,11,10,14,12, 9,11,11,13,13,11,12,13,13,13,11,
  142196. 12,12,15,13, 9,10,10,12,13, 9,11,10,12,13,10,10,
  142197. 11,12,13,11,12,12,12,13,11,12,12,13,13, 5, 7, 7,
  142198. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  142199. 13,10,10,11,12,12, 6, 8, 8,11,10, 7, 8, 9,10,12,
  142200. 8, 9, 9,11,11,11,10,11,11,12,10,11,11,13,12, 7,
  142201. 8, 8,10,11, 8, 9, 8,11,10, 8, 9, 9,11,11,10,12,
  142202. 10,13,11,10,11,11,13,13,10,11,10,14,13,10,10,11,
  142203. 13,13,10,12,11,14,13,12,11,13,12,13,13,12,13,14,
  142204. 14,10,11,11,13,13,10,11,10,12,13,10,12,12,12,14,
  142205. 12,12,12,14,12,12,13,12,17,15, 5, 7, 7,10,10, 7,
  142206. 8, 8,10,10, 7, 8, 8,11,10,10,10,11,12,12,10,11,
  142207. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  142208. 10,11,11,11,11,12,12,10,10,11,12,13, 6, 8, 8,10,
  142209. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,12,12,13,13,
  142210. 11,11,10,13,11, 9,11,10,14,13,11,11,11,15,13,10,
  142211. 10,11,13,13,12,13,13,14,14,12,11,12,12,13,10,11,
  142212. 11,12,13,10,11,12,13,13,10,11,10,13,12,12,12,13,
  142213. 14, 0,12,13,11,13,11, 8,10,10,13,13,10,11,11,14,
  142214. 13,10,11,11,13,12,13,14,14,14,15,12,12,12,15,14,
  142215. 9,11,10,13,12,10,10,11,13,14,11,11,11,15,12,13,
  142216. 12,14,15,16,13,13,13,14,13, 9,11,11,12,12,10,12,
  142217. 11,13,13,10,11,11,13,14,13,13,13,15,15,13,13,14,
  142218. 17,15,11,12,12,14,14,10,11,12,13,15,12,13,13, 0,
  142219. 15,13,11,14,12,16,14,16,14, 0,15,11,12,12,14,16,
  142220. 11,13,12,16,15,12,13,13,14,15,12,14,12,15,13,15,
  142221. 14,14,16,16, 8,10,10,13,13,10,11,10,13,14,10,11,
  142222. 11,13,13,13,13,12,14,14,14,13,13,16,17, 9,10,10,
  142223. 12,14,10,12,11,14,13,10,11,12,13,14,12,12,12,15,
  142224. 15,13,13,13,14,14, 9,10,10,13,13,10,11,12,12,14,
  142225. 10,11,10,13,13,13,13,13,14,16,13,13,13,14,14,11,
  142226. 12,13,15,13,12,14,13,14,16,12,12,13,13,14,13,14,
  142227. 14,17,15,13,12,17,13,16,11,12,13,14,15,12,13,14,
  142228. 14,17,11,12,11,14,14,13,16,14,16, 0,14,15,11,15,
  142229. 11,
  142230. };
  142231. static float _vq_quantthresh__16u0__p4_0[] = {
  142232. -1.5, -0.5, 0.5, 1.5,
  142233. };
  142234. static long _vq_quantmap__16u0__p4_0[] = {
  142235. 3, 1, 0, 2, 4,
  142236. };
  142237. static encode_aux_threshmatch _vq_auxt__16u0__p4_0 = {
  142238. _vq_quantthresh__16u0__p4_0,
  142239. _vq_quantmap__16u0__p4_0,
  142240. 5,
  142241. 5
  142242. };
  142243. static static_codebook _16u0__p4_0 = {
  142244. 4, 625,
  142245. _vq_lengthlist__16u0__p4_0,
  142246. 1, -533725184, 1611661312, 3, 0,
  142247. _vq_quantlist__16u0__p4_0,
  142248. NULL,
  142249. &_vq_auxt__16u0__p4_0,
  142250. NULL,
  142251. 0
  142252. };
  142253. static long _vq_quantlist__16u0__p5_0[] = {
  142254. 4,
  142255. 3,
  142256. 5,
  142257. 2,
  142258. 6,
  142259. 1,
  142260. 7,
  142261. 0,
  142262. 8,
  142263. };
  142264. static long _vq_lengthlist__16u0__p5_0[] = {
  142265. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  142266. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  142267. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 7, 8, 8,
  142268. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  142269. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,10,11,11,12,
  142270. 12,
  142271. };
  142272. static float _vq_quantthresh__16u0__p5_0[] = {
  142273. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  142274. };
  142275. static long _vq_quantmap__16u0__p5_0[] = {
  142276. 7, 5, 3, 1, 0, 2, 4, 6,
  142277. 8,
  142278. };
  142279. static encode_aux_threshmatch _vq_auxt__16u0__p5_0 = {
  142280. _vq_quantthresh__16u0__p5_0,
  142281. _vq_quantmap__16u0__p5_0,
  142282. 9,
  142283. 9
  142284. };
  142285. static static_codebook _16u0__p5_0 = {
  142286. 2, 81,
  142287. _vq_lengthlist__16u0__p5_0,
  142288. 1, -531628032, 1611661312, 4, 0,
  142289. _vq_quantlist__16u0__p5_0,
  142290. NULL,
  142291. &_vq_auxt__16u0__p5_0,
  142292. NULL,
  142293. 0
  142294. };
  142295. static long _vq_quantlist__16u0__p6_0[] = {
  142296. 6,
  142297. 5,
  142298. 7,
  142299. 4,
  142300. 8,
  142301. 3,
  142302. 9,
  142303. 2,
  142304. 10,
  142305. 1,
  142306. 11,
  142307. 0,
  142308. 12,
  142309. };
  142310. static long _vq_lengthlist__16u0__p6_0[] = {
  142311. 1, 4, 4, 7, 7,10,10,12,12,13,13,18,17, 3, 6, 6,
  142312. 9, 9,11,11,13,13,14,14,18,17, 3, 6, 6, 9, 9,11,
  142313. 11,13,13,14,14,17,18, 7, 9, 9,11,11,13,13,14,14,
  142314. 15,15, 0, 0, 7, 9, 9,11,11,13,13,14,14,15,16,19,
  142315. 18,10,11,11,13,13,14,14,16,15,17,18, 0, 0,10,11,
  142316. 11,13,13,14,14,15,15,16,18, 0, 0,11,13,13,14,14,
  142317. 15,15,17,17, 0,19, 0, 0,11,13,13,14,14,14,15,16,
  142318. 18, 0,19, 0, 0,13,14,14,15,15,18,17,18,18, 0,19,
  142319. 0, 0,13,14,14,15,16,16,16,18,18,19, 0, 0, 0,16,
  142320. 17,17, 0,17,19,19, 0,19, 0, 0, 0, 0,16,19,16,17,
  142321. 18, 0,19, 0, 0, 0, 0, 0, 0,
  142322. };
  142323. static float _vq_quantthresh__16u0__p6_0[] = {
  142324. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  142325. 12.5, 17.5, 22.5, 27.5,
  142326. };
  142327. static long _vq_quantmap__16u0__p6_0[] = {
  142328. 11, 9, 7, 5, 3, 1, 0, 2,
  142329. 4, 6, 8, 10, 12,
  142330. };
  142331. static encode_aux_threshmatch _vq_auxt__16u0__p6_0 = {
  142332. _vq_quantthresh__16u0__p6_0,
  142333. _vq_quantmap__16u0__p6_0,
  142334. 13,
  142335. 13
  142336. };
  142337. static static_codebook _16u0__p6_0 = {
  142338. 2, 169,
  142339. _vq_lengthlist__16u0__p6_0,
  142340. 1, -526516224, 1616117760, 4, 0,
  142341. _vq_quantlist__16u0__p6_0,
  142342. NULL,
  142343. &_vq_auxt__16u0__p6_0,
  142344. NULL,
  142345. 0
  142346. };
  142347. static long _vq_quantlist__16u0__p6_1[] = {
  142348. 2,
  142349. 1,
  142350. 3,
  142351. 0,
  142352. 4,
  142353. };
  142354. static long _vq_lengthlist__16u0__p6_1[] = {
  142355. 1, 4, 5, 6, 6, 4, 6, 6, 6, 6, 4, 6, 6, 6, 6, 6,
  142356. 6, 6, 7, 7, 6, 6, 6, 7, 7,
  142357. };
  142358. static float _vq_quantthresh__16u0__p6_1[] = {
  142359. -1.5, -0.5, 0.5, 1.5,
  142360. };
  142361. static long _vq_quantmap__16u0__p6_1[] = {
  142362. 3, 1, 0, 2, 4,
  142363. };
  142364. static encode_aux_threshmatch _vq_auxt__16u0__p6_1 = {
  142365. _vq_quantthresh__16u0__p6_1,
  142366. _vq_quantmap__16u0__p6_1,
  142367. 5,
  142368. 5
  142369. };
  142370. static static_codebook _16u0__p6_1 = {
  142371. 2, 25,
  142372. _vq_lengthlist__16u0__p6_1,
  142373. 1, -533725184, 1611661312, 3, 0,
  142374. _vq_quantlist__16u0__p6_1,
  142375. NULL,
  142376. &_vq_auxt__16u0__p6_1,
  142377. NULL,
  142378. 0
  142379. };
  142380. static long _vq_quantlist__16u0__p7_0[] = {
  142381. 1,
  142382. 0,
  142383. 2,
  142384. };
  142385. static long _vq_lengthlist__16u0__p7_0[] = {
  142386. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  142387. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  142388. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  142389. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  142390. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  142391. 7,
  142392. };
  142393. static float _vq_quantthresh__16u0__p7_0[] = {
  142394. -157.5, 157.5,
  142395. };
  142396. static long _vq_quantmap__16u0__p7_0[] = {
  142397. 1, 0, 2,
  142398. };
  142399. static encode_aux_threshmatch _vq_auxt__16u0__p7_0 = {
  142400. _vq_quantthresh__16u0__p7_0,
  142401. _vq_quantmap__16u0__p7_0,
  142402. 3,
  142403. 3
  142404. };
  142405. static static_codebook _16u0__p7_0 = {
  142406. 4, 81,
  142407. _vq_lengthlist__16u0__p7_0,
  142408. 1, -518803456, 1628680192, 2, 0,
  142409. _vq_quantlist__16u0__p7_0,
  142410. NULL,
  142411. &_vq_auxt__16u0__p7_0,
  142412. NULL,
  142413. 0
  142414. };
  142415. static long _vq_quantlist__16u0__p7_1[] = {
  142416. 7,
  142417. 6,
  142418. 8,
  142419. 5,
  142420. 9,
  142421. 4,
  142422. 10,
  142423. 3,
  142424. 11,
  142425. 2,
  142426. 12,
  142427. 1,
  142428. 13,
  142429. 0,
  142430. 14,
  142431. };
  142432. static long _vq_lengthlist__16u0__p7_1[] = {
  142433. 1, 5, 5, 6, 5, 9,10,11,11,10,10,10,10,10,10, 5,
  142434. 8, 8, 8,10,10,10,10,10,10,10,10,10,10,10, 5, 8,
  142435. 9, 9, 9,10,10,10,10,10,10,10,10,10,10, 5,10, 8,
  142436. 10,10,10,10,10,10,10,10,10,10,10,10, 4, 8, 9,10,
  142437. 10,10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,
  142438. 10,10,10,10,10,10,10,10,10,10, 9,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,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142445. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142446. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142447. 10,
  142448. };
  142449. static float _vq_quantthresh__16u0__p7_1[] = {
  142450. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  142451. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  142452. };
  142453. static long _vq_quantmap__16u0__p7_1[] = {
  142454. 13, 11, 9, 7, 5, 3, 1, 0,
  142455. 2, 4, 6, 8, 10, 12, 14,
  142456. };
  142457. static encode_aux_threshmatch _vq_auxt__16u0__p7_1 = {
  142458. _vq_quantthresh__16u0__p7_1,
  142459. _vq_quantmap__16u0__p7_1,
  142460. 15,
  142461. 15
  142462. };
  142463. static static_codebook _16u0__p7_1 = {
  142464. 2, 225,
  142465. _vq_lengthlist__16u0__p7_1,
  142466. 1, -520986624, 1620377600, 4, 0,
  142467. _vq_quantlist__16u0__p7_1,
  142468. NULL,
  142469. &_vq_auxt__16u0__p7_1,
  142470. NULL,
  142471. 0
  142472. };
  142473. static long _vq_quantlist__16u0__p7_2[] = {
  142474. 10,
  142475. 9,
  142476. 11,
  142477. 8,
  142478. 12,
  142479. 7,
  142480. 13,
  142481. 6,
  142482. 14,
  142483. 5,
  142484. 15,
  142485. 4,
  142486. 16,
  142487. 3,
  142488. 17,
  142489. 2,
  142490. 18,
  142491. 1,
  142492. 19,
  142493. 0,
  142494. 20,
  142495. };
  142496. static long _vq_lengthlist__16u0__p7_2[] = {
  142497. 1, 6, 6, 7, 8, 7, 7,10, 9,10, 9,11,10, 9,11,10,
  142498. 9, 9, 9, 9,10, 6, 8, 7, 9, 9, 8, 8,10,10, 9,11,
  142499. 11,12,12,10, 9,11, 9,12,10, 9, 6, 9, 8, 9,12, 8,
  142500. 8,11, 9,11,11,12,11,12,12,10,11,11,10,10,11, 7,
  142501. 10, 9, 9, 9, 9, 9,10, 9,10, 9,10,10,12,10,10,10,
  142502. 11,12,10,10, 7, 9, 9, 9,10, 9, 9,10,10, 9, 9, 9,
  142503. 11,11,10,10,10,10, 9, 9,12, 7, 9,10, 9,11, 9,10,
  142504. 9,10,11,11,11,10,11,12, 9,12,11,10,10,10, 7, 9,
  142505. 9, 9, 9,10,12,10, 9,11,12,10,11,12,12,11, 9,10,
  142506. 11,10,11, 7, 9,10,10,11,10, 9,10,11,11,11,10,12,
  142507. 12,12,11,11,10,11,11,12, 8, 9,10,12,11,10,10,12,
  142508. 12,12,12,12,10,11,11, 9,11,10,12,11,11, 8, 9,10,
  142509. 10,11,12,11,11,10,10,10,12,12,12, 9,10,12,12,12,
  142510. 12,12, 8,10,11,10,10,12, 9,11,12,12,11,12,12,12,
  142511. 12,10,12,10,10,10,10, 8,12,11,11,11,10,10,11,12,
  142512. 12,12,12,11,12,12,12,11,11,11,12,10, 9,10,10,12,
  142513. 10,12,10,12,12,10,10,10,11,12,12,12,11,12,12,12,
  142514. 11,10,11,12,12,12,11,12,12,11,12,12,11,12,12,12,
  142515. 12,11,12,12,10,10,10,10,11,11,12,11,12,12,12,12,
  142516. 12,12,12,11,12,11,10,11,11,12,11,11, 9,10,10,10,
  142517. 12,10,10,11, 9,11,12,11,12,11,12,12,10,11,10,12,
  142518. 9, 9, 9,12,11,10,11,10,12,10,12,10,12,12,12,11,
  142519. 11,11,11,11,10, 9,10,10,11,10,11,11,12,11,10,11,
  142520. 12,12,12,11,11, 9,12,10,12, 9,10,12,10,10,11,10,
  142521. 11,11,12,11,10,11,10,11,11,11,11,12,11,11,10, 9,
  142522. 10,10,10, 9,11,11,10, 9,12,10,11,12,11,12,12,11,
  142523. 12,11,12,11,10,11,10,12,11,12,11,12,11,12,10,11,
  142524. 10,10,12,11,10,11,11,11,10,
  142525. };
  142526. static float _vq_quantthresh__16u0__p7_2[] = {
  142527. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  142528. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  142529. 6.5, 7.5, 8.5, 9.5,
  142530. };
  142531. static long _vq_quantmap__16u0__p7_2[] = {
  142532. 19, 17, 15, 13, 11, 9, 7, 5,
  142533. 3, 1, 0, 2, 4, 6, 8, 10,
  142534. 12, 14, 16, 18, 20,
  142535. };
  142536. static encode_aux_threshmatch _vq_auxt__16u0__p7_2 = {
  142537. _vq_quantthresh__16u0__p7_2,
  142538. _vq_quantmap__16u0__p7_2,
  142539. 21,
  142540. 21
  142541. };
  142542. static static_codebook _16u0__p7_2 = {
  142543. 2, 441,
  142544. _vq_lengthlist__16u0__p7_2,
  142545. 1, -529268736, 1611661312, 5, 0,
  142546. _vq_quantlist__16u0__p7_2,
  142547. NULL,
  142548. &_vq_auxt__16u0__p7_2,
  142549. NULL,
  142550. 0
  142551. };
  142552. static long _huff_lengthlist__16u0__single[] = {
  142553. 3, 5, 8, 7,14, 8, 9,19, 5, 2, 5, 5, 9, 6, 9,19,
  142554. 8, 4, 5, 7, 8, 9,13,19, 7, 4, 6, 5, 9, 6, 9,19,
  142555. 12, 8, 7, 9,10,11,13,19, 8, 5, 8, 6, 9, 6, 7,19,
  142556. 8, 8,10, 7, 7, 4, 5,19,12,17,19,15,18,13,11,18,
  142557. };
  142558. static static_codebook _huff_book__16u0__single = {
  142559. 2, 64,
  142560. _huff_lengthlist__16u0__single,
  142561. 0, 0, 0, 0, 0,
  142562. NULL,
  142563. NULL,
  142564. NULL,
  142565. NULL,
  142566. 0
  142567. };
  142568. static long _huff_lengthlist__16u1__long[] = {
  142569. 3, 6,10, 8,12, 8,14, 8,14,19, 5, 3, 5, 5, 7, 6,
  142570. 11, 7,16,19, 7, 5, 6, 7, 7, 9,11,12,19,19, 6, 4,
  142571. 7, 5, 7, 6,10, 7,18,18, 8, 6, 7, 7, 7, 7, 8, 9,
  142572. 18,18, 7, 5, 8, 5, 7, 5, 8, 6,18,18,12, 9,10, 9,
  142573. 9, 9, 8, 9,18,18, 8, 7,10, 6, 8, 5, 6, 4,11,18,
  142574. 11,15,16,12,11, 8, 8, 6, 9,18,14,18,18,18,16,16,
  142575. 16,13,16,18,
  142576. };
  142577. static static_codebook _huff_book__16u1__long = {
  142578. 2, 100,
  142579. _huff_lengthlist__16u1__long,
  142580. 0, 0, 0, 0, 0,
  142581. NULL,
  142582. NULL,
  142583. NULL,
  142584. NULL,
  142585. 0
  142586. };
  142587. static long _vq_quantlist__16u1__p1_0[] = {
  142588. 1,
  142589. 0,
  142590. 2,
  142591. };
  142592. static long _vq_lengthlist__16u1__p1_0[] = {
  142593. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 7, 7,10,10, 7,
  142594. 9,10, 5, 7, 8, 7,10, 9, 7,10,10, 5, 8, 8, 8,10,
  142595. 10, 8,10,10, 7,10,10,10,11,12,10,12,13, 7,10,10,
  142596. 9,13,11,10,12,13, 5, 8, 8, 8,10,10, 8,10,10, 7,
  142597. 10,10,10,12,12, 9,11,12, 7,10,11,10,12,12,10,13,
  142598. 11,
  142599. };
  142600. static float _vq_quantthresh__16u1__p1_0[] = {
  142601. -0.5, 0.5,
  142602. };
  142603. static long _vq_quantmap__16u1__p1_0[] = {
  142604. 1, 0, 2,
  142605. };
  142606. static encode_aux_threshmatch _vq_auxt__16u1__p1_0 = {
  142607. _vq_quantthresh__16u1__p1_0,
  142608. _vq_quantmap__16u1__p1_0,
  142609. 3,
  142610. 3
  142611. };
  142612. static static_codebook _16u1__p1_0 = {
  142613. 4, 81,
  142614. _vq_lengthlist__16u1__p1_0,
  142615. 1, -535822336, 1611661312, 2, 0,
  142616. _vq_quantlist__16u1__p1_0,
  142617. NULL,
  142618. &_vq_auxt__16u1__p1_0,
  142619. NULL,
  142620. 0
  142621. };
  142622. static long _vq_quantlist__16u1__p2_0[] = {
  142623. 1,
  142624. 0,
  142625. 2,
  142626. };
  142627. static long _vq_lengthlist__16u1__p2_0[] = {
  142628. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 7, 8, 6,
  142629. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 6, 8,
  142630. 8, 6, 8, 8, 6, 8, 8, 7, 7,10, 8, 9, 9, 6, 8, 8,
  142631. 7, 9, 8, 8, 9,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  142632. 8, 8, 8,10, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 7,10,
  142633. 8,
  142634. };
  142635. static float _vq_quantthresh__16u1__p2_0[] = {
  142636. -0.5, 0.5,
  142637. };
  142638. static long _vq_quantmap__16u1__p2_0[] = {
  142639. 1, 0, 2,
  142640. };
  142641. static encode_aux_threshmatch _vq_auxt__16u1__p2_0 = {
  142642. _vq_quantthresh__16u1__p2_0,
  142643. _vq_quantmap__16u1__p2_0,
  142644. 3,
  142645. 3
  142646. };
  142647. static static_codebook _16u1__p2_0 = {
  142648. 4, 81,
  142649. _vq_lengthlist__16u1__p2_0,
  142650. 1, -535822336, 1611661312, 2, 0,
  142651. _vq_quantlist__16u1__p2_0,
  142652. NULL,
  142653. &_vq_auxt__16u1__p2_0,
  142654. NULL,
  142655. 0
  142656. };
  142657. static long _vq_quantlist__16u1__p3_0[] = {
  142658. 2,
  142659. 1,
  142660. 3,
  142661. 0,
  142662. 4,
  142663. };
  142664. static long _vq_lengthlist__16u1__p3_0[] = {
  142665. 1, 5, 5, 8, 8, 6, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  142666. 10, 9,11,11, 9, 9,10,11,11, 6, 8, 8,10,10, 8, 9,
  142667. 10,11,11, 8, 9,10,11,11,10,11,11,12,13,10,11,11,
  142668. 13,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  142669. 11,10,11,11,13,13,10,11,11,13,12, 9,11,11,14,13,
  142670. 10,12,12,15,14,10,12,11,14,13,12,13,13,15,15,12,
  142671. 13,13,16,14, 9,11,11,13,14,10,11,12,14,14,10,12,
  142672. 12,14,15,12,13,13,14,15,12,13,14,15,16, 5, 8, 8,
  142673. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  142674. 14,11,12,12,14,14, 8,10,10,12,12, 9,11,12,12,13,
  142675. 10,12,12,13,13,12,12,13,14,15,11,13,13,15,15, 7,
  142676. 10,10,12,12, 9,12,11,13,12,10,11,12,13,13,12,13,
  142677. 12,15,14,11,12,13,15,15,10,12,12,15,14,11,13,13,
  142678. 16,15,11,13,13,16,15,14,13,14,15,16,13,15,15,17,
  142679. 17,10,12,12,14,15,11,12,12,15,15,11,13,13,15,16,
  142680. 13,15,13,16,15,13,15,15,16,17, 5, 8, 8,11,11, 8,
  142681. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  142682. 12,14,14, 7,10,10,12,12,10,12,12,14,13, 9,11,12,
  142683. 12,13,12,13,13,15,15,12,12,13,13,15, 7,10,10,12,
  142684. 13,10,11,12,13,13,10,12,11,13,13,11,13,13,15,15,
  142685. 12,13,12,15,14, 9,12,12,15,14,11,13,13,15,15,11,
  142686. 12,13,15,15,13,14,14,17,19,13,13,14,16,16,10,12,
  142687. 12,14,15,11,13,13,15,16,11,13,12,16,15,13,15,15,
  142688. 17,18,14,15,13,16,15, 8,11,11,15,14,10,12,12,16,
  142689. 15,10,12,12,16,16,14,15,15,18,17,13,14,15,16,18,
  142690. 9,12,12,15,15,11,12,14,16,17,11,13,13,16,15,15,
  142691. 15,15,17,18,14,15,16,17,17, 9,12,12,15,15,11,14,
  142692. 13,16,16,11,13,13,16,16,15,16,15,17,18,14,16,15,
  142693. 17,16,12,14,14,17,16,12,14,15,18,17,13,15,15,17,
  142694. 17,15,15,18,16,20,15,16,17,18,18,11,14,14,16,17,
  142695. 13,15,14,18,17,13,15,15,17,17,15,17,15,18,17,15,
  142696. 17,16,19,18, 8,11,11,14,15,10,12,12,15,15,10,12,
  142697. 12,16,16,13,14,14,17,16,14,15,15,17,17, 9,12,12,
  142698. 15,16,11,13,13,16,16,11,12,13,16,16,14,16,15,20,
  142699. 17,14,16,16,17,17, 9,12,12,15,16,11,13,13,16,17,
  142700. 11,13,13,17,16,14,15,15,17,18,15,15,15,18,18,11,
  142701. 14,14,17,16,13,15,15,17,17,13,14,14,18,17,15,16,
  142702. 16,18,19,15,15,17,17,19,11,14,14,16,17,13,15,14,
  142703. 17,19,13,15,14,18,17,15,17,16,18,18,15,17,15,18,
  142704. 16,
  142705. };
  142706. static float _vq_quantthresh__16u1__p3_0[] = {
  142707. -1.5, -0.5, 0.5, 1.5,
  142708. };
  142709. static long _vq_quantmap__16u1__p3_0[] = {
  142710. 3, 1, 0, 2, 4,
  142711. };
  142712. static encode_aux_threshmatch _vq_auxt__16u1__p3_0 = {
  142713. _vq_quantthresh__16u1__p3_0,
  142714. _vq_quantmap__16u1__p3_0,
  142715. 5,
  142716. 5
  142717. };
  142718. static static_codebook _16u1__p3_0 = {
  142719. 4, 625,
  142720. _vq_lengthlist__16u1__p3_0,
  142721. 1, -533725184, 1611661312, 3, 0,
  142722. _vq_quantlist__16u1__p3_0,
  142723. NULL,
  142724. &_vq_auxt__16u1__p3_0,
  142725. NULL,
  142726. 0
  142727. };
  142728. static long _vq_quantlist__16u1__p4_0[] = {
  142729. 2,
  142730. 1,
  142731. 3,
  142732. 0,
  142733. 4,
  142734. };
  142735. static long _vq_lengthlist__16u1__p4_0[] = {
  142736. 4, 5, 5, 8, 8, 6, 6, 7, 9, 9, 6, 6, 6, 9, 9, 9,
  142737. 10, 9,11,11, 9, 9,10,11,11, 6, 7, 7,10, 9, 7, 7,
  142738. 8, 9,10, 7, 7, 8,10,10,10,10,10,10,12, 9, 9,10,
  142739. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 7,10,
  142740. 10, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  142741. 10,10,10,12,12, 9,10,10,12,12,12,11,12,13,13,11,
  142742. 11,12,12,13, 9,10,10,11,12, 9,10,10,12,12,10,10,
  142743. 10,12,12,11,12,11,14,13,11,12,12,14,13, 5, 7, 7,
  142744. 10,10, 7, 8, 8,10,10, 7, 8, 7,10,10,10,10,10,12,
  142745. 12,10,10,10,12,12, 6, 8, 7,10,10, 7, 7, 9,10,11,
  142746. 8, 9, 9,11,10,10,10,11,11,13,10,10,11,12,13, 6,
  142747. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,10,11,10,11,
  142748. 10,13,11,10,11,10,12,12,10,11,10,12,11,10,10,10,
  142749. 12,13,10,11,11,13,12,11,11,13,11,14,12,12,13,14,
  142750. 14, 9,10,10,12,13,10,11,10,13,12,10,11,11,12,13,
  142751. 11,12,11,14,12,12,13,13,15,14, 5, 7, 7,10,10, 7,
  142752. 7, 8,10,10, 7, 8, 8,10,10,10,10,10,11,12,10,10,
  142753. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  142754. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 7, 8,10,
  142755. 10, 8, 8, 9,10,11, 7, 9, 7,11,10,10,11,11,13,12,
  142756. 11,11,10,13,11, 9,10,10,12,12,10,11,11,13,12,10,
  142757. 10,11,12,12,12,13,13,14,14,11,11,12,12,14,10,10,
  142758. 11,12,12,10,11,11,12,13,10,10,10,13,12,12,13,13,
  142759. 15,14,12,13,10,14,11, 8,10,10,12,12,10,11,10,13,
  142760. 13, 9,10,10,12,12,12,13,13,15,14,11,12,12,13,13,
  142761. 9,10,10,13,12,10,10,11,13,13,10,11,10,13,12,12,
  142762. 12,13,14,15,12,13,12,15,13, 9,10,10,12,13,10,11,
  142763. 10,13,12,10,10,11,12,13,12,14,12,15,13,12,12,13,
  142764. 14,15,11,12,11,14,13,11,11,12,14,15,12,13,12,15,
  142765. 14,13,11,15,11,16,13,14,14,16,15,11,12,12,14,14,
  142766. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,12,14,
  142767. 14,14,15,15, 8,10,10,12,12, 9,10,10,12,12,10,10,
  142768. 11,13,13,11,12,12,13,13,12,13,13,14,15, 9,10,10,
  142769. 13,12,10,11,11,13,12,10,10,11,13,13,12,13,12,15,
  142770. 14,12,12,13,13,16, 9, 9,10,12,13,10,10,11,12,13,
  142771. 10,11,10,13,13,12,12,13,13,15,13,13,12,15,13,11,
  142772. 12,12,14,14,12,13,12,15,14,11,11,12,13,14,14,14,
  142773. 14,16,15,13,12,15,12,16,11,11,12,13,14,12,13,13,
  142774. 14,15,10,12,11,14,13,14,15,14,16,16,13,14,11,15,
  142775. 11,
  142776. };
  142777. static float _vq_quantthresh__16u1__p4_0[] = {
  142778. -1.5, -0.5, 0.5, 1.5,
  142779. };
  142780. static long _vq_quantmap__16u1__p4_0[] = {
  142781. 3, 1, 0, 2, 4,
  142782. };
  142783. static encode_aux_threshmatch _vq_auxt__16u1__p4_0 = {
  142784. _vq_quantthresh__16u1__p4_0,
  142785. _vq_quantmap__16u1__p4_0,
  142786. 5,
  142787. 5
  142788. };
  142789. static static_codebook _16u1__p4_0 = {
  142790. 4, 625,
  142791. _vq_lengthlist__16u1__p4_0,
  142792. 1, -533725184, 1611661312, 3, 0,
  142793. _vq_quantlist__16u1__p4_0,
  142794. NULL,
  142795. &_vq_auxt__16u1__p4_0,
  142796. NULL,
  142797. 0
  142798. };
  142799. static long _vq_quantlist__16u1__p5_0[] = {
  142800. 4,
  142801. 3,
  142802. 5,
  142803. 2,
  142804. 6,
  142805. 1,
  142806. 7,
  142807. 0,
  142808. 8,
  142809. };
  142810. static long _vq_lengthlist__16u1__p5_0[] = {
  142811. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  142812. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  142813. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  142814. 10, 9,11,11,12,11, 7, 8, 8, 9, 9,11,11,12,12, 9,
  142815. 10,10,11,11,12,12,13,12, 9,10,10,11,11,12,12,12,
  142816. 13,
  142817. };
  142818. static float _vq_quantthresh__16u1__p5_0[] = {
  142819. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  142820. };
  142821. static long _vq_quantmap__16u1__p5_0[] = {
  142822. 7, 5, 3, 1, 0, 2, 4, 6,
  142823. 8,
  142824. };
  142825. static encode_aux_threshmatch _vq_auxt__16u1__p5_0 = {
  142826. _vq_quantthresh__16u1__p5_0,
  142827. _vq_quantmap__16u1__p5_0,
  142828. 9,
  142829. 9
  142830. };
  142831. static static_codebook _16u1__p5_0 = {
  142832. 2, 81,
  142833. _vq_lengthlist__16u1__p5_0,
  142834. 1, -531628032, 1611661312, 4, 0,
  142835. _vq_quantlist__16u1__p5_0,
  142836. NULL,
  142837. &_vq_auxt__16u1__p5_0,
  142838. NULL,
  142839. 0
  142840. };
  142841. static long _vq_quantlist__16u1__p6_0[] = {
  142842. 4,
  142843. 3,
  142844. 5,
  142845. 2,
  142846. 6,
  142847. 1,
  142848. 7,
  142849. 0,
  142850. 8,
  142851. };
  142852. static long _vq_lengthlist__16u1__p6_0[] = {
  142853. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 4, 6, 6, 8, 8,
  142854. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  142855. 8, 8,10, 9, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  142856. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  142857. 9, 9,10,10,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  142858. 11,
  142859. };
  142860. static float _vq_quantthresh__16u1__p6_0[] = {
  142861. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  142862. };
  142863. static long _vq_quantmap__16u1__p6_0[] = {
  142864. 7, 5, 3, 1, 0, 2, 4, 6,
  142865. 8,
  142866. };
  142867. static encode_aux_threshmatch _vq_auxt__16u1__p6_0 = {
  142868. _vq_quantthresh__16u1__p6_0,
  142869. _vq_quantmap__16u1__p6_0,
  142870. 9,
  142871. 9
  142872. };
  142873. static static_codebook _16u1__p6_0 = {
  142874. 2, 81,
  142875. _vq_lengthlist__16u1__p6_0,
  142876. 1, -531628032, 1611661312, 4, 0,
  142877. _vq_quantlist__16u1__p6_0,
  142878. NULL,
  142879. &_vq_auxt__16u1__p6_0,
  142880. NULL,
  142881. 0
  142882. };
  142883. static long _vq_quantlist__16u1__p7_0[] = {
  142884. 1,
  142885. 0,
  142886. 2,
  142887. };
  142888. static long _vq_lengthlist__16u1__p7_0[] = {
  142889. 1, 4, 4, 4, 8, 8, 4, 8, 8, 5,11, 9, 8,12,11, 8,
  142890. 12,11, 5,10,11, 8,11,12, 8,11,12, 4,11,11,11,14,
  142891. 13,10,13,13, 8,14,13,12,14,16,12,16,15, 8,14,14,
  142892. 13,16,14,12,15,16, 4,11,11,10,14,13,11,14,14, 8,
  142893. 15,14,12,15,15,12,14,16, 8,14,14,11,16,15,12,15,
  142894. 13,
  142895. };
  142896. static float _vq_quantthresh__16u1__p7_0[] = {
  142897. -5.5, 5.5,
  142898. };
  142899. static long _vq_quantmap__16u1__p7_0[] = {
  142900. 1, 0, 2,
  142901. };
  142902. static encode_aux_threshmatch _vq_auxt__16u1__p7_0 = {
  142903. _vq_quantthresh__16u1__p7_0,
  142904. _vq_quantmap__16u1__p7_0,
  142905. 3,
  142906. 3
  142907. };
  142908. static static_codebook _16u1__p7_0 = {
  142909. 4, 81,
  142910. _vq_lengthlist__16u1__p7_0,
  142911. 1, -529137664, 1618345984, 2, 0,
  142912. _vq_quantlist__16u1__p7_0,
  142913. NULL,
  142914. &_vq_auxt__16u1__p7_0,
  142915. NULL,
  142916. 0
  142917. };
  142918. static long _vq_quantlist__16u1__p7_1[] = {
  142919. 5,
  142920. 4,
  142921. 6,
  142922. 3,
  142923. 7,
  142924. 2,
  142925. 8,
  142926. 1,
  142927. 9,
  142928. 0,
  142929. 10,
  142930. };
  142931. static long _vq_lengthlist__16u1__p7_1[] = {
  142932. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 5, 7, 7,
  142933. 8, 8, 8, 8, 8, 8, 4, 5, 6, 7, 7, 8, 8, 8, 8, 8,
  142934. 8, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  142935. 8, 8, 8, 9, 9, 9, 9, 7, 8, 8, 8, 8, 9, 9, 9,10,
  142936. 9,10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10, 9, 8, 8, 8,
  142937. 9, 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,10,
  142938. 10,10,10, 8, 8, 8, 9, 9, 9,10,10,10,10,10, 8, 8,
  142939. 8, 9, 9,10,10,10,10,10,10,
  142940. };
  142941. static float _vq_quantthresh__16u1__p7_1[] = {
  142942. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  142943. 3.5, 4.5,
  142944. };
  142945. static long _vq_quantmap__16u1__p7_1[] = {
  142946. 9, 7, 5, 3, 1, 0, 2, 4,
  142947. 6, 8, 10,
  142948. };
  142949. static encode_aux_threshmatch _vq_auxt__16u1__p7_1 = {
  142950. _vq_quantthresh__16u1__p7_1,
  142951. _vq_quantmap__16u1__p7_1,
  142952. 11,
  142953. 11
  142954. };
  142955. static static_codebook _16u1__p7_1 = {
  142956. 2, 121,
  142957. _vq_lengthlist__16u1__p7_1,
  142958. 1, -531365888, 1611661312, 4, 0,
  142959. _vq_quantlist__16u1__p7_1,
  142960. NULL,
  142961. &_vq_auxt__16u1__p7_1,
  142962. NULL,
  142963. 0
  142964. };
  142965. static long _vq_quantlist__16u1__p8_0[] = {
  142966. 5,
  142967. 4,
  142968. 6,
  142969. 3,
  142970. 7,
  142971. 2,
  142972. 8,
  142973. 1,
  142974. 9,
  142975. 0,
  142976. 10,
  142977. };
  142978. static long _vq_lengthlist__16u1__p8_0[] = {
  142979. 1, 4, 4, 5, 5, 8, 8,10,10,12,12, 4, 7, 7, 8, 8,
  142980. 9, 9,12,11,14,13, 4, 7, 7, 7, 8, 9,10,11,11,13,
  142981. 12, 5, 8, 8, 9, 9,11,11,12,13,15,14, 5, 7, 8, 9,
  142982. 9,11,11,13,13,17,15, 8, 9,10,11,11,12,13,17,14,
  142983. 17,16, 8,10, 9,11,11,12,12,13,15,15,17,10,11,11,
  142984. 12,13,14,15,15,16,16,17, 9,11,11,12,12,14,15,17,
  142985. 15,15,16,11,14,12,14,15,16,15,16,16,16,15,11,13,
  142986. 13,14,14,15,15,16,16,15,16,
  142987. };
  142988. static float _vq_quantthresh__16u1__p8_0[] = {
  142989. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  142990. 38.5, 49.5,
  142991. };
  142992. static long _vq_quantmap__16u1__p8_0[] = {
  142993. 9, 7, 5, 3, 1, 0, 2, 4,
  142994. 6, 8, 10,
  142995. };
  142996. static encode_aux_threshmatch _vq_auxt__16u1__p8_0 = {
  142997. _vq_quantthresh__16u1__p8_0,
  142998. _vq_quantmap__16u1__p8_0,
  142999. 11,
  143000. 11
  143001. };
  143002. static static_codebook _16u1__p8_0 = {
  143003. 2, 121,
  143004. _vq_lengthlist__16u1__p8_0,
  143005. 1, -524582912, 1618345984, 4, 0,
  143006. _vq_quantlist__16u1__p8_0,
  143007. NULL,
  143008. &_vq_auxt__16u1__p8_0,
  143009. NULL,
  143010. 0
  143011. };
  143012. static long _vq_quantlist__16u1__p8_1[] = {
  143013. 5,
  143014. 4,
  143015. 6,
  143016. 3,
  143017. 7,
  143018. 2,
  143019. 8,
  143020. 1,
  143021. 9,
  143022. 0,
  143023. 10,
  143024. };
  143025. static long _vq_lengthlist__16u1__p8_1[] = {
  143026. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7,
  143027. 8, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  143028. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 6, 7, 7, 7,
  143029. 7, 8, 8, 8, 8, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  143030. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  143031. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  143032. 9, 9, 9, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  143033. 8, 9, 9, 9, 9, 9, 9, 9, 9,
  143034. };
  143035. static float _vq_quantthresh__16u1__p8_1[] = {
  143036. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143037. 3.5, 4.5,
  143038. };
  143039. static long _vq_quantmap__16u1__p8_1[] = {
  143040. 9, 7, 5, 3, 1, 0, 2, 4,
  143041. 6, 8, 10,
  143042. };
  143043. static encode_aux_threshmatch _vq_auxt__16u1__p8_1 = {
  143044. _vq_quantthresh__16u1__p8_1,
  143045. _vq_quantmap__16u1__p8_1,
  143046. 11,
  143047. 11
  143048. };
  143049. static static_codebook _16u1__p8_1 = {
  143050. 2, 121,
  143051. _vq_lengthlist__16u1__p8_1,
  143052. 1, -531365888, 1611661312, 4, 0,
  143053. _vq_quantlist__16u1__p8_1,
  143054. NULL,
  143055. &_vq_auxt__16u1__p8_1,
  143056. NULL,
  143057. 0
  143058. };
  143059. static long _vq_quantlist__16u1__p9_0[] = {
  143060. 7,
  143061. 6,
  143062. 8,
  143063. 5,
  143064. 9,
  143065. 4,
  143066. 10,
  143067. 3,
  143068. 11,
  143069. 2,
  143070. 12,
  143071. 1,
  143072. 13,
  143073. 0,
  143074. 14,
  143075. };
  143076. static long _vq_lengthlist__16u1__p9_0[] = {
  143077. 1, 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, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143087. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143088. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143089. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143090. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143091. 8,
  143092. };
  143093. static float _vq_quantthresh__16u1__p9_0[] = {
  143094. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  143095. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  143096. };
  143097. static long _vq_quantmap__16u1__p9_0[] = {
  143098. 13, 11, 9, 7, 5, 3, 1, 0,
  143099. 2, 4, 6, 8, 10, 12, 14,
  143100. };
  143101. static encode_aux_threshmatch _vq_auxt__16u1__p9_0 = {
  143102. _vq_quantthresh__16u1__p9_0,
  143103. _vq_quantmap__16u1__p9_0,
  143104. 15,
  143105. 15
  143106. };
  143107. static static_codebook _16u1__p9_0 = {
  143108. 2, 225,
  143109. _vq_lengthlist__16u1__p9_0,
  143110. 1, -514071552, 1627381760, 4, 0,
  143111. _vq_quantlist__16u1__p9_0,
  143112. NULL,
  143113. &_vq_auxt__16u1__p9_0,
  143114. NULL,
  143115. 0
  143116. };
  143117. static long _vq_quantlist__16u1__p9_1[] = {
  143118. 7,
  143119. 6,
  143120. 8,
  143121. 5,
  143122. 9,
  143123. 4,
  143124. 10,
  143125. 3,
  143126. 11,
  143127. 2,
  143128. 12,
  143129. 1,
  143130. 13,
  143131. 0,
  143132. 14,
  143133. };
  143134. static long _vq_lengthlist__16u1__p9_1[] = {
  143135. 1, 6, 5, 9, 9,10,10, 6, 7, 9, 9,10,10,10,10, 5,
  143136. 10, 8,10, 8,10,10, 8, 8,10, 9,10,10,10,10, 5, 8,
  143137. 9,10,10,10,10, 8,10,10,10,10,10,10,10, 9,10,10,
  143138. 10,10,10,10, 9, 9,10,10,10,10,10,10, 9, 9, 8, 9,
  143139. 10,10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  143140. 10,10,10,10,10,10,10,10,10,10,10, 8,10,10,10,10,
  143141. 10,10,10,10,10,10,10,10,10, 6, 8, 8,10,10,10, 8,
  143142. 10,10,10,10,10,10,10,10, 5, 8, 8,10,10,10, 9, 9,
  143143. 10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,10,
  143144. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143145. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  143146. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143147. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143148. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143149. 9,
  143150. };
  143151. static float _vq_quantthresh__16u1__p9_1[] = {
  143152. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  143153. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  143154. };
  143155. static long _vq_quantmap__16u1__p9_1[] = {
  143156. 13, 11, 9, 7, 5, 3, 1, 0,
  143157. 2, 4, 6, 8, 10, 12, 14,
  143158. };
  143159. static encode_aux_threshmatch _vq_auxt__16u1__p9_1 = {
  143160. _vq_quantthresh__16u1__p9_1,
  143161. _vq_quantmap__16u1__p9_1,
  143162. 15,
  143163. 15
  143164. };
  143165. static static_codebook _16u1__p9_1 = {
  143166. 2, 225,
  143167. _vq_lengthlist__16u1__p9_1,
  143168. 1, -522338304, 1620115456, 4, 0,
  143169. _vq_quantlist__16u1__p9_1,
  143170. NULL,
  143171. &_vq_auxt__16u1__p9_1,
  143172. NULL,
  143173. 0
  143174. };
  143175. static long _vq_quantlist__16u1__p9_2[] = {
  143176. 8,
  143177. 7,
  143178. 9,
  143179. 6,
  143180. 10,
  143181. 5,
  143182. 11,
  143183. 4,
  143184. 12,
  143185. 3,
  143186. 13,
  143187. 2,
  143188. 14,
  143189. 1,
  143190. 15,
  143191. 0,
  143192. 16,
  143193. };
  143194. static long _vq_lengthlist__16u1__p9_2[] = {
  143195. 1, 6, 6, 7, 8, 8,11,10, 9, 9,11, 9,10, 9,11,11,
  143196. 9, 6, 7, 6,11, 8,11, 9,10,10,11, 9,11,10,10,10,
  143197. 11, 9, 5, 7, 7, 8, 8,10,11, 8, 8,11, 9, 9,10,11,
  143198. 9,10,11, 8, 9, 6, 8, 8, 9, 9,10,10,11,11,11, 9,
  143199. 11,10, 9,11, 8, 8, 8, 9, 8, 9,10,11, 9, 9,11,11,
  143200. 10, 9, 9,11,10, 8,11, 8, 9, 8,11, 9,10, 9,10,11,
  143201. 11,10,10, 9,10,10, 8, 8, 9,10,10,10, 9,11, 9,10,
  143202. 11,11,11,11,10, 9,11, 9, 9,11,11,10, 8,11,11,11,
  143203. 9,10,10,11,10,11,11, 9,11,10, 9,11,10,10,10,10,
  143204. 9,11,10,11,10, 9, 9,10,11, 9, 8,10,11,11,10,10,
  143205. 11, 9,11,10,11,11,10,11, 9, 9, 8,10, 8, 9,11, 9,
  143206. 8,10,10, 9,11,10,11,10,11, 9,11, 8,10,11,11,11,
  143207. 11,10,10,11,11,11,11,10,11,11,10, 9, 8,10,10, 9,
  143208. 11,10,11,11,11, 9, 9, 9,11,11,11,10,10, 9, 9,10,
  143209. 9,11,11,11,11, 8,10,11,10,11,11,10,11,11, 9, 9,
  143210. 9,10, 9,11, 9,11,11,11,11,11,10,11,11,10,11,10,
  143211. 11,11, 9,11,10,11,10, 9,10, 9,10,10,11,11,11,11,
  143212. 9,10, 9,10,11,11,10,11,11,11,11,11,11,10,11,11,
  143213. 10,
  143214. };
  143215. static float _vq_quantthresh__16u1__p9_2[] = {
  143216. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  143217. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  143218. };
  143219. static long _vq_quantmap__16u1__p9_2[] = {
  143220. 15, 13, 11, 9, 7, 5, 3, 1,
  143221. 0, 2, 4, 6, 8, 10, 12, 14,
  143222. 16,
  143223. };
  143224. static encode_aux_threshmatch _vq_auxt__16u1__p9_2 = {
  143225. _vq_quantthresh__16u1__p9_2,
  143226. _vq_quantmap__16u1__p9_2,
  143227. 17,
  143228. 17
  143229. };
  143230. static static_codebook _16u1__p9_2 = {
  143231. 2, 289,
  143232. _vq_lengthlist__16u1__p9_2,
  143233. 1, -529530880, 1611661312, 5, 0,
  143234. _vq_quantlist__16u1__p9_2,
  143235. NULL,
  143236. &_vq_auxt__16u1__p9_2,
  143237. NULL,
  143238. 0
  143239. };
  143240. static long _huff_lengthlist__16u1__short[] = {
  143241. 5, 7,10, 9,11,10,15,11,13,16, 6, 4, 6, 6, 7, 7,
  143242. 10, 9,12,16,10, 6, 5, 6, 6, 7,10,11,16,16, 9, 6,
  143243. 7, 6, 7, 7,10, 8,14,16,11, 6, 5, 4, 5, 6, 8, 9,
  143244. 15,16, 9, 6, 6, 5, 6, 6, 9, 8,14,16,12, 7, 6, 6,
  143245. 5, 6, 6, 7,13,16, 8, 6, 7, 6, 5, 5, 4, 4,11,16,
  143246. 9, 8, 9, 9, 7, 7, 6, 5,13,16,14,14,16,15,16,15,
  143247. 16,16,16,16,
  143248. };
  143249. static static_codebook _huff_book__16u1__short = {
  143250. 2, 100,
  143251. _huff_lengthlist__16u1__short,
  143252. 0, 0, 0, 0, 0,
  143253. NULL,
  143254. NULL,
  143255. NULL,
  143256. NULL,
  143257. 0
  143258. };
  143259. static long _huff_lengthlist__16u2__long[] = {
  143260. 5, 7,10,10,10,11,11,13,18,19, 6, 5, 5, 6, 7, 8,
  143261. 9,12,19,19, 8, 5, 4, 4, 6, 7, 9,13,19,19, 8, 5,
  143262. 4, 4, 5, 6, 8,12,17,19, 7, 5, 5, 4, 4, 5, 7,12,
  143263. 18,18, 8, 7, 7, 6, 5, 5, 6,10,18,18, 9, 9, 9, 8,
  143264. 6, 5, 6, 9,18,18,11,13,13,13, 8, 7, 7, 9,16,18,
  143265. 13,17,18,16,11, 9, 9, 9,17,18,15,18,18,18,15,13,
  143266. 13,14,18,18,
  143267. };
  143268. static static_codebook _huff_book__16u2__long = {
  143269. 2, 100,
  143270. _huff_lengthlist__16u2__long,
  143271. 0, 0, 0, 0, 0,
  143272. NULL,
  143273. NULL,
  143274. NULL,
  143275. NULL,
  143276. 0
  143277. };
  143278. static long _huff_lengthlist__16u2__short[] = {
  143279. 8,11,12,12,14,15,16,16,16,16, 9, 7, 7, 8, 9,11,
  143280. 13,14,16,16,13, 7, 6, 6, 7, 9,12,13,15,16,15, 7,
  143281. 6, 5, 4, 6,10,11,14,16,12, 8, 7, 4, 2, 4, 7,10,
  143282. 14,16,11, 9, 7, 5, 3, 4, 6, 9,14,16,11,10, 9, 7,
  143283. 5, 5, 6, 9,16,16,10,10, 9, 8, 6, 6, 7,10,16,16,
  143284. 11,11,11,10,10,10,11,14,16,16,16,14,14,13,14,16,
  143285. 16,16,16,16,
  143286. };
  143287. static static_codebook _huff_book__16u2__short = {
  143288. 2, 100,
  143289. _huff_lengthlist__16u2__short,
  143290. 0, 0, 0, 0, 0,
  143291. NULL,
  143292. NULL,
  143293. NULL,
  143294. NULL,
  143295. 0
  143296. };
  143297. static long _vq_quantlist__16u2_p1_0[] = {
  143298. 1,
  143299. 0,
  143300. 2,
  143301. };
  143302. static long _vq_lengthlist__16u2_p1_0[] = {
  143303. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  143304. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 8, 9,
  143305. 9, 7, 9, 9, 7, 9, 9, 9,10,10, 9,10,10, 7, 9, 9,
  143306. 9,10,10, 9,10,11, 5, 7, 8, 8, 9, 9, 8, 9, 9, 7,
  143307. 9, 9, 9,10,10, 9, 9,10, 7, 9, 9, 9,10,10, 9,11,
  143308. 10,
  143309. };
  143310. static float _vq_quantthresh__16u2_p1_0[] = {
  143311. -0.5, 0.5,
  143312. };
  143313. static long _vq_quantmap__16u2_p1_0[] = {
  143314. 1, 0, 2,
  143315. };
  143316. static encode_aux_threshmatch _vq_auxt__16u2_p1_0 = {
  143317. _vq_quantthresh__16u2_p1_0,
  143318. _vq_quantmap__16u2_p1_0,
  143319. 3,
  143320. 3
  143321. };
  143322. static static_codebook _16u2_p1_0 = {
  143323. 4, 81,
  143324. _vq_lengthlist__16u2_p1_0,
  143325. 1, -535822336, 1611661312, 2, 0,
  143326. _vq_quantlist__16u2_p1_0,
  143327. NULL,
  143328. &_vq_auxt__16u2_p1_0,
  143329. NULL,
  143330. 0
  143331. };
  143332. static long _vq_quantlist__16u2_p2_0[] = {
  143333. 2,
  143334. 1,
  143335. 3,
  143336. 0,
  143337. 4,
  143338. };
  143339. static long _vq_lengthlist__16u2_p2_0[] = {
  143340. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  143341. 10, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  143342. 8,10,10, 7, 8, 8,10,10,10,10,10,12,12, 9,10,10,
  143343. 11,12, 5, 7, 7, 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,
  143344. 10, 9,10,10,12,11,10,10,10,12,12, 9,10,10,12,12,
  143345. 10,11,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  143346. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,12,10,10,
  143347. 10,12,12,11,12,12,14,13,12,13,12,14,14, 5, 7, 7,
  143348. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  143349. 12,10,10,11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  143350. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,12,13, 7,
  143351. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  143352. 10,13,12,10,11,11,13,13, 9,11,10,13,13,10,11,11,
  143353. 13,13,10,11,11,13,13,12,12,13,13,15,12,12,13,14,
  143354. 15, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  143355. 11,13,11,14,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  143356. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  143357. 11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  143358. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  143359. 11, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,12,
  143360. 11,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  143361. 10,11,12,13,12,13,13,15,14,11,11,13,12,14,10,10,
  143362. 11,13,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  143363. 14,14,12,13,12,14,13, 8,10, 9,12,12, 9,11,10,13,
  143364. 13, 9,10,10,12,13,12,13,13,14,14,12,12,13,14,14,
  143365. 9,11,10,13,13,10,11,11,13,13,10,11,11,13,13,12,
  143366. 13,13,15,15,13,13,13,14,15, 9,10,10,12,13,10,11,
  143367. 10,13,12,10,11,11,13,13,12,13,12,15,14,13,13,13,
  143368. 14,15,11,12,12,15,14,12,12,13,15,15,12,13,13,15,
  143369. 14,14,13,15,14,16,13,14,15,16,16,11,12,12,14,14,
  143370. 11,12,12,15,14,12,13,13,15,15,13,14,13,16,14,14,
  143371. 14,14,16,16, 8, 9, 9,12,12, 9,10,10,13,12, 9,10,
  143372. 10,13,13,12,12,12,14,14,12,12,13,15,15, 9,10,10,
  143373. 13,12,10,11,11,13,13,10,10,11,13,14,12,13,13,15,
  143374. 15,12,12,13,14,15, 9,10,10,13,13,10,11,11,13,13,
  143375. 10,11,11,13,13,12,13,13,14,14,13,14,13,15,14,11,
  143376. 12,12,14,14,12,13,13,15,14,11,12,12,14,15,14,14,
  143377. 14,16,15,13,12,14,14,16,11,12,13,14,15,12,13,13,
  143378. 14,16,12,13,12,15,14,13,15,14,16,16,14,15,13,16,
  143379. 13,
  143380. };
  143381. static float _vq_quantthresh__16u2_p2_0[] = {
  143382. -1.5, -0.5, 0.5, 1.5,
  143383. };
  143384. static long _vq_quantmap__16u2_p2_0[] = {
  143385. 3, 1, 0, 2, 4,
  143386. };
  143387. static encode_aux_threshmatch _vq_auxt__16u2_p2_0 = {
  143388. _vq_quantthresh__16u2_p2_0,
  143389. _vq_quantmap__16u2_p2_0,
  143390. 5,
  143391. 5
  143392. };
  143393. static static_codebook _16u2_p2_0 = {
  143394. 4, 625,
  143395. _vq_lengthlist__16u2_p2_0,
  143396. 1, -533725184, 1611661312, 3, 0,
  143397. _vq_quantlist__16u2_p2_0,
  143398. NULL,
  143399. &_vq_auxt__16u2_p2_0,
  143400. NULL,
  143401. 0
  143402. };
  143403. static long _vq_quantlist__16u2_p3_0[] = {
  143404. 4,
  143405. 3,
  143406. 5,
  143407. 2,
  143408. 6,
  143409. 1,
  143410. 7,
  143411. 0,
  143412. 8,
  143413. };
  143414. static long _vq_lengthlist__16u2_p3_0[] = {
  143415. 2, 4, 4, 6, 6, 7, 7, 9, 9, 4, 5, 5, 6, 6, 8, 7,
  143416. 9, 9, 4, 5, 5, 6, 6, 7, 8, 9, 9, 6, 6, 6, 7, 7,
  143417. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  143418. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  143419. 9, 9,10, 9,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  143420. 11,
  143421. };
  143422. static float _vq_quantthresh__16u2_p3_0[] = {
  143423. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143424. };
  143425. static long _vq_quantmap__16u2_p3_0[] = {
  143426. 7, 5, 3, 1, 0, 2, 4, 6,
  143427. 8,
  143428. };
  143429. static encode_aux_threshmatch _vq_auxt__16u2_p3_0 = {
  143430. _vq_quantthresh__16u2_p3_0,
  143431. _vq_quantmap__16u2_p3_0,
  143432. 9,
  143433. 9
  143434. };
  143435. static static_codebook _16u2_p3_0 = {
  143436. 2, 81,
  143437. _vq_lengthlist__16u2_p3_0,
  143438. 1, -531628032, 1611661312, 4, 0,
  143439. _vq_quantlist__16u2_p3_0,
  143440. NULL,
  143441. &_vq_auxt__16u2_p3_0,
  143442. NULL,
  143443. 0
  143444. };
  143445. static long _vq_quantlist__16u2_p4_0[] = {
  143446. 8,
  143447. 7,
  143448. 9,
  143449. 6,
  143450. 10,
  143451. 5,
  143452. 11,
  143453. 4,
  143454. 12,
  143455. 3,
  143456. 13,
  143457. 2,
  143458. 14,
  143459. 1,
  143460. 15,
  143461. 0,
  143462. 16,
  143463. };
  143464. static long _vq_lengthlist__16u2_p4_0[] = {
  143465. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,11,
  143466. 11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  143467. 12,11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  143468. 11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  143469. 11,11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,
  143470. 10,11,11,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  143471. 11,11,12,12,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  143472. 10,11,11,11,12,12,12, 9, 9, 9, 9, 9, 9,10,10,10,
  143473. 10,10,11,11,12,12,13,13, 8, 9, 9, 9, 9,10, 9,10,
  143474. 10,10,10,11,11,12,12,13,13, 9, 9, 9, 9, 9,10,10,
  143475. 10,10,11,11,11,12,12,12,13,13, 9, 9, 9, 9, 9,10,
  143476. 10,10,10,11,11,12,11,12,12,13,13,10,10,10,10,10,
  143477. 11,11,11,11,11,12,12,12,12,13,13,14,10,10,10,10,
  143478. 10,11,11,11,11,12,11,12,12,13,12,13,13,11,11,11,
  143479. 11,11,12,12,12,12,12,12,13,13,13,13,14,14,11,11,
  143480. 11,11,11,12,12,12,12,12,12,13,12,13,13,14,14,11,
  143481. 12,12,12,12,12,12,13,13,13,13,13,13,14,14,14,14,
  143482. 11,12,12,12,12,12,12,13,13,13,13,14,13,14,14,14,
  143483. 14,
  143484. };
  143485. static float _vq_quantthresh__16u2_p4_0[] = {
  143486. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  143487. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  143488. };
  143489. static long _vq_quantmap__16u2_p4_0[] = {
  143490. 15, 13, 11, 9, 7, 5, 3, 1,
  143491. 0, 2, 4, 6, 8, 10, 12, 14,
  143492. 16,
  143493. };
  143494. static encode_aux_threshmatch _vq_auxt__16u2_p4_0 = {
  143495. _vq_quantthresh__16u2_p4_0,
  143496. _vq_quantmap__16u2_p4_0,
  143497. 17,
  143498. 17
  143499. };
  143500. static static_codebook _16u2_p4_0 = {
  143501. 2, 289,
  143502. _vq_lengthlist__16u2_p4_0,
  143503. 1, -529530880, 1611661312, 5, 0,
  143504. _vq_quantlist__16u2_p4_0,
  143505. NULL,
  143506. &_vq_auxt__16u2_p4_0,
  143507. NULL,
  143508. 0
  143509. };
  143510. static long _vq_quantlist__16u2_p5_0[] = {
  143511. 1,
  143512. 0,
  143513. 2,
  143514. };
  143515. static long _vq_lengthlist__16u2_p5_0[] = {
  143516. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10, 9, 7,
  143517. 10, 9, 5, 8, 9, 7, 9,10, 7, 9,10, 4, 9, 9, 9,11,
  143518. 11, 8,11,11, 7,11,11,10,10,13,10,14,13, 7,11,11,
  143519. 10,13,11,10,13,14, 5, 9, 9, 8,11,11, 9,11,11, 7,
  143520. 11,11,10,14,13,10,12,14, 7,11,11,10,13,13,10,13,
  143521. 10,
  143522. };
  143523. static float _vq_quantthresh__16u2_p5_0[] = {
  143524. -5.5, 5.5,
  143525. };
  143526. static long _vq_quantmap__16u2_p5_0[] = {
  143527. 1, 0, 2,
  143528. };
  143529. static encode_aux_threshmatch _vq_auxt__16u2_p5_0 = {
  143530. _vq_quantthresh__16u2_p5_0,
  143531. _vq_quantmap__16u2_p5_0,
  143532. 3,
  143533. 3
  143534. };
  143535. static static_codebook _16u2_p5_0 = {
  143536. 4, 81,
  143537. _vq_lengthlist__16u2_p5_0,
  143538. 1, -529137664, 1618345984, 2, 0,
  143539. _vq_quantlist__16u2_p5_0,
  143540. NULL,
  143541. &_vq_auxt__16u2_p5_0,
  143542. NULL,
  143543. 0
  143544. };
  143545. static long _vq_quantlist__16u2_p5_1[] = {
  143546. 5,
  143547. 4,
  143548. 6,
  143549. 3,
  143550. 7,
  143551. 2,
  143552. 8,
  143553. 1,
  143554. 9,
  143555. 0,
  143556. 10,
  143557. };
  143558. static long _vq_lengthlist__16u2_p5_1[] = {
  143559. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 5, 5, 5, 7, 7,
  143560. 7, 7, 8, 8, 8, 8, 5, 5, 6, 7, 7, 7, 7, 8, 8, 8,
  143561. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  143562. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  143563. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  143564. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  143565. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  143566. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  143567. };
  143568. static float _vq_quantthresh__16u2_p5_1[] = {
  143569. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143570. 3.5, 4.5,
  143571. };
  143572. static long _vq_quantmap__16u2_p5_1[] = {
  143573. 9, 7, 5, 3, 1, 0, 2, 4,
  143574. 6, 8, 10,
  143575. };
  143576. static encode_aux_threshmatch _vq_auxt__16u2_p5_1 = {
  143577. _vq_quantthresh__16u2_p5_1,
  143578. _vq_quantmap__16u2_p5_1,
  143579. 11,
  143580. 11
  143581. };
  143582. static static_codebook _16u2_p5_1 = {
  143583. 2, 121,
  143584. _vq_lengthlist__16u2_p5_1,
  143585. 1, -531365888, 1611661312, 4, 0,
  143586. _vq_quantlist__16u2_p5_1,
  143587. NULL,
  143588. &_vq_auxt__16u2_p5_1,
  143589. NULL,
  143590. 0
  143591. };
  143592. static long _vq_quantlist__16u2_p6_0[] = {
  143593. 6,
  143594. 5,
  143595. 7,
  143596. 4,
  143597. 8,
  143598. 3,
  143599. 9,
  143600. 2,
  143601. 10,
  143602. 1,
  143603. 11,
  143604. 0,
  143605. 12,
  143606. };
  143607. static long _vq_lengthlist__16u2_p6_0[] = {
  143608. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6,
  143609. 8, 8, 9, 9, 9, 9,10,10,12,11, 4, 6, 6, 8, 8, 9,
  143610. 9, 9, 9,10,10,11,12, 7, 8, 8, 9, 9,10,10,10,10,
  143611. 12,12,13,12, 7, 8, 8, 9, 9,10,10,10,10,11,12,12,
  143612. 12, 8, 9, 9,10,10,11,11,11,11,12,12,13,13, 8, 9,
  143613. 9,10,10,11,11,11,11,12,13,13,13, 8, 9, 9,10,10,
  143614. 11,11,12,12,13,13,14,14, 8, 9, 9,10,10,11,11,12,
  143615. 12,13,13,14,14, 9,10,10,11,12,13,12,13,14,14,14,
  143616. 14,14, 9,10,10,11,12,12,13,13,13,14,14,14,14,10,
  143617. 11,11,12,12,13,13,14,14,15,15,15,15,10,11,11,12,
  143618. 12,13,13,14,14,14,14,15,15,
  143619. };
  143620. static float _vq_quantthresh__16u2_p6_0[] = {
  143621. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  143622. 12.5, 17.5, 22.5, 27.5,
  143623. };
  143624. static long _vq_quantmap__16u2_p6_0[] = {
  143625. 11, 9, 7, 5, 3, 1, 0, 2,
  143626. 4, 6, 8, 10, 12,
  143627. };
  143628. static encode_aux_threshmatch _vq_auxt__16u2_p6_0 = {
  143629. _vq_quantthresh__16u2_p6_0,
  143630. _vq_quantmap__16u2_p6_0,
  143631. 13,
  143632. 13
  143633. };
  143634. static static_codebook _16u2_p6_0 = {
  143635. 2, 169,
  143636. _vq_lengthlist__16u2_p6_0,
  143637. 1, -526516224, 1616117760, 4, 0,
  143638. _vq_quantlist__16u2_p6_0,
  143639. NULL,
  143640. &_vq_auxt__16u2_p6_0,
  143641. NULL,
  143642. 0
  143643. };
  143644. static long _vq_quantlist__16u2_p6_1[] = {
  143645. 2,
  143646. 1,
  143647. 3,
  143648. 0,
  143649. 4,
  143650. };
  143651. static long _vq_lengthlist__16u2_p6_1[] = {
  143652. 2, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  143653. 5, 5, 6, 6, 5, 5, 5, 6, 6,
  143654. };
  143655. static float _vq_quantthresh__16u2_p6_1[] = {
  143656. -1.5, -0.5, 0.5, 1.5,
  143657. };
  143658. static long _vq_quantmap__16u2_p6_1[] = {
  143659. 3, 1, 0, 2, 4,
  143660. };
  143661. static encode_aux_threshmatch _vq_auxt__16u2_p6_1 = {
  143662. _vq_quantthresh__16u2_p6_1,
  143663. _vq_quantmap__16u2_p6_1,
  143664. 5,
  143665. 5
  143666. };
  143667. static static_codebook _16u2_p6_1 = {
  143668. 2, 25,
  143669. _vq_lengthlist__16u2_p6_1,
  143670. 1, -533725184, 1611661312, 3, 0,
  143671. _vq_quantlist__16u2_p6_1,
  143672. NULL,
  143673. &_vq_auxt__16u2_p6_1,
  143674. NULL,
  143675. 0
  143676. };
  143677. static long _vq_quantlist__16u2_p7_0[] = {
  143678. 6,
  143679. 5,
  143680. 7,
  143681. 4,
  143682. 8,
  143683. 3,
  143684. 9,
  143685. 2,
  143686. 10,
  143687. 1,
  143688. 11,
  143689. 0,
  143690. 12,
  143691. };
  143692. static long _vq_lengthlist__16u2_p7_0[] = {
  143693. 1, 4, 4, 7, 7, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 6,
  143694. 9, 9, 9, 9, 9, 9,10,10,11,11, 4, 6, 6, 8, 9, 9,
  143695. 9, 9, 9,10,11,12,11, 7, 8, 9,10,10,10,10,11,10,
  143696. 11,12,12,13, 7, 9, 9,10,10,10,10,10,10,11,12,13,
  143697. 13, 7, 9, 8,10,10,11,11,11,12,12,13,13,14, 7, 9,
  143698. 9,10,10,11,11,11,12,13,13,13,13, 8, 9, 9,10,11,
  143699. 11,12,12,12,13,13,13,13, 8, 9, 9,10,11,11,11,12,
  143700. 12,13,13,14,14, 9,10,10,12,11,12,13,13,13,14,13,
  143701. 13,13, 9,10,10,11,11,12,12,13,14,13,13,14,13,10,
  143702. 11,11,12,13,14,14,14,15,14,14,14,14,10,11,11,12,
  143703. 12,13,13,13,14,14,14,15,14,
  143704. };
  143705. static float _vq_quantthresh__16u2_p7_0[] = {
  143706. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  143707. 27.5, 38.5, 49.5, 60.5,
  143708. };
  143709. static long _vq_quantmap__16u2_p7_0[] = {
  143710. 11, 9, 7, 5, 3, 1, 0, 2,
  143711. 4, 6, 8, 10, 12,
  143712. };
  143713. static encode_aux_threshmatch _vq_auxt__16u2_p7_0 = {
  143714. _vq_quantthresh__16u2_p7_0,
  143715. _vq_quantmap__16u2_p7_0,
  143716. 13,
  143717. 13
  143718. };
  143719. static static_codebook _16u2_p7_0 = {
  143720. 2, 169,
  143721. _vq_lengthlist__16u2_p7_0,
  143722. 1, -523206656, 1618345984, 4, 0,
  143723. _vq_quantlist__16u2_p7_0,
  143724. NULL,
  143725. &_vq_auxt__16u2_p7_0,
  143726. NULL,
  143727. 0
  143728. };
  143729. static long _vq_quantlist__16u2_p7_1[] = {
  143730. 5,
  143731. 4,
  143732. 6,
  143733. 3,
  143734. 7,
  143735. 2,
  143736. 8,
  143737. 1,
  143738. 9,
  143739. 0,
  143740. 10,
  143741. };
  143742. static long _vq_lengthlist__16u2_p7_1[] = {
  143743. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  143744. 7, 7, 7, 7, 8, 8, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8,
  143745. 8, 6, 6, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 7, 7, 7,
  143746. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  143747. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  143748. 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8,
  143749. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  143750. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143751. };
  143752. static float _vq_quantthresh__16u2_p7_1[] = {
  143753. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143754. 3.5, 4.5,
  143755. };
  143756. static long _vq_quantmap__16u2_p7_1[] = {
  143757. 9, 7, 5, 3, 1, 0, 2, 4,
  143758. 6, 8, 10,
  143759. };
  143760. static encode_aux_threshmatch _vq_auxt__16u2_p7_1 = {
  143761. _vq_quantthresh__16u2_p7_1,
  143762. _vq_quantmap__16u2_p7_1,
  143763. 11,
  143764. 11
  143765. };
  143766. static static_codebook _16u2_p7_1 = {
  143767. 2, 121,
  143768. _vq_lengthlist__16u2_p7_1,
  143769. 1, -531365888, 1611661312, 4, 0,
  143770. _vq_quantlist__16u2_p7_1,
  143771. NULL,
  143772. &_vq_auxt__16u2_p7_1,
  143773. NULL,
  143774. 0
  143775. };
  143776. static long _vq_quantlist__16u2_p8_0[] = {
  143777. 7,
  143778. 6,
  143779. 8,
  143780. 5,
  143781. 9,
  143782. 4,
  143783. 10,
  143784. 3,
  143785. 11,
  143786. 2,
  143787. 12,
  143788. 1,
  143789. 13,
  143790. 0,
  143791. 14,
  143792. };
  143793. static long _vq_lengthlist__16u2_p8_0[] = {
  143794. 1, 5, 5, 7, 7, 8, 8, 7, 7, 8, 8,10, 9,11,11, 4,
  143795. 6, 6, 8, 8,10, 9, 9, 8, 9, 9,10,10,12,14, 4, 6,
  143796. 7, 8, 9, 9,10, 9, 8, 9, 9,10,12,12,11, 7, 8, 8,
  143797. 10,10,10,10, 9, 9,10,10,11,13,13,12, 7, 8, 8, 9,
  143798. 11,11,10, 9, 9,11,10,12,11,11,14, 8, 9, 9,11,10,
  143799. 11,11,10,10,11,11,13,12,14,12, 8, 9, 9,11,12,11,
  143800. 11,10,10,12,11,12,12,12,14, 7, 8, 8, 9, 9,10,10,
  143801. 10,11,12,11,13,13,14,12, 7, 8, 9, 9, 9,10,10,11,
  143802. 11,11,12,12,14,14,14, 8,10, 9,10,11,11,11,11,14,
  143803. 12,12,13,14,14,13, 9, 9, 9,10,11,11,11,12,12,12,
  143804. 14,12,14,13,14,10,10,10,12,11,12,11,14,13,14,13,
  143805. 14,14,13,14, 9,10,10,11,12,11,13,12,13,13,14,14,
  143806. 14,13,14,10,13,13,12,12,11,12,14,13,14,13,14,12,
  143807. 14,13,10,11,11,12,11,12,12,14,14,14,13,14,14,14,
  143808. 14,
  143809. };
  143810. static float _vq_quantthresh__16u2_p8_0[] = {
  143811. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  143812. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  143813. };
  143814. static long _vq_quantmap__16u2_p8_0[] = {
  143815. 13, 11, 9, 7, 5, 3, 1, 0,
  143816. 2, 4, 6, 8, 10, 12, 14,
  143817. };
  143818. static encode_aux_threshmatch _vq_auxt__16u2_p8_0 = {
  143819. _vq_quantthresh__16u2_p8_0,
  143820. _vq_quantmap__16u2_p8_0,
  143821. 15,
  143822. 15
  143823. };
  143824. static static_codebook _16u2_p8_0 = {
  143825. 2, 225,
  143826. _vq_lengthlist__16u2_p8_0,
  143827. 1, -520986624, 1620377600, 4, 0,
  143828. _vq_quantlist__16u2_p8_0,
  143829. NULL,
  143830. &_vq_auxt__16u2_p8_0,
  143831. NULL,
  143832. 0
  143833. };
  143834. static long _vq_quantlist__16u2_p8_1[] = {
  143835. 10,
  143836. 9,
  143837. 11,
  143838. 8,
  143839. 12,
  143840. 7,
  143841. 13,
  143842. 6,
  143843. 14,
  143844. 5,
  143845. 15,
  143846. 4,
  143847. 16,
  143848. 3,
  143849. 17,
  143850. 2,
  143851. 18,
  143852. 1,
  143853. 19,
  143854. 0,
  143855. 20,
  143856. };
  143857. static long _vq_lengthlist__16u2_p8_1[] = {
  143858. 2, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,10, 9, 9,
  143859. 9,10,10,10,10, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,
  143860. 10, 9,10,10,10,10,10,10,11,10, 5, 6, 6, 7, 7, 8,
  143861. 8, 8, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 7,
  143862. 7, 7, 8, 8, 9, 8, 9, 9,10, 9,10,10,10,10,10,10,
  143863. 11,10,11,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,10, 9,10,
  143864. 10,10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,
  143865. 10, 9,10,10,10,10,10,10,10,11,10,10,11,10, 8, 8,
  143866. 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,
  143867. 11,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  143868. 11,10,11,10,11,10,11,10, 8, 9, 9, 9, 9, 9,10,10,
  143869. 10,10,10,10,10,10,10,10,11,11,10,10,10, 9,10, 9,
  143870. 9,10,10,10,11,10,10,10,10,10,10,10,10,11,11,11,
  143871. 11,11, 9, 9, 9,10, 9,10,10,10,10,10,10,11,10,11,
  143872. 10,11,11,11,11,10,10, 9,10, 9,10,10,10,10,11,10,
  143873. 10,10,10,10,11,10,11,10,11,10,10,11, 9,10,10,10,
  143874. 10,10,10,10,10,10,11,10,10,11,11,10,11,11,11,11,
  143875. 11, 9, 9,10,10,10,10,10,11,10,10,11,10,10,11,10,
  143876. 10,11,11,11,11,11, 9,10,10,10,10,10,10,10,11,10,
  143877. 11,10,11,10,11,11,11,11,11,10,11,10,10,10,10,10,
  143878. 10,10,10,10,11,11,11,11,11,11,11,11,11,10,11,11,
  143879. 10,10,10,10,10,11,10,10,10,11,10,11,11,11,11,10,
  143880. 12,11,11,11,10,10,10,10,10,10,11,10,10,10,11,11,
  143881. 12,11,11,11,11,11,11,11,11,11,10,10,10,11,10,11,
  143882. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  143883. 10,10,11,10,11,10,10,11,11,11,11,11,11,11,11,11,
  143884. 11,11,11,10,10,10,10,10,10,10,11,11,10,11,11,10,
  143885. 11,11,10,11,11,11,10,11,11,
  143886. };
  143887. static float _vq_quantthresh__16u2_p8_1[] = {
  143888. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  143889. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  143890. 6.5, 7.5, 8.5, 9.5,
  143891. };
  143892. static long _vq_quantmap__16u2_p8_1[] = {
  143893. 19, 17, 15, 13, 11, 9, 7, 5,
  143894. 3, 1, 0, 2, 4, 6, 8, 10,
  143895. 12, 14, 16, 18, 20,
  143896. };
  143897. static encode_aux_threshmatch _vq_auxt__16u2_p8_1 = {
  143898. _vq_quantthresh__16u2_p8_1,
  143899. _vq_quantmap__16u2_p8_1,
  143900. 21,
  143901. 21
  143902. };
  143903. static static_codebook _16u2_p8_1 = {
  143904. 2, 441,
  143905. _vq_lengthlist__16u2_p8_1,
  143906. 1, -529268736, 1611661312, 5, 0,
  143907. _vq_quantlist__16u2_p8_1,
  143908. NULL,
  143909. &_vq_auxt__16u2_p8_1,
  143910. NULL,
  143911. 0
  143912. };
  143913. static long _vq_quantlist__16u2_p9_0[] = {
  143914. 5586,
  143915. 4655,
  143916. 6517,
  143917. 3724,
  143918. 7448,
  143919. 2793,
  143920. 8379,
  143921. 1862,
  143922. 9310,
  143923. 931,
  143924. 10241,
  143925. 0,
  143926. 11172,
  143927. 5521,
  143928. 5651,
  143929. };
  143930. static long _vq_lengthlist__16u2_p9_0[] = {
  143931. 1,10,10,10,10,10,10,10,10,10,10,10,10, 5, 4,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,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143941. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143942. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143943. 10,10,10, 4,10,10,10,10,10,10,10,10,10,10,10,10,
  143944. 6, 6, 5,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 5,
  143945. 5,
  143946. };
  143947. static float _vq_quantthresh__16u2_p9_0[] = {
  143948. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -498, -32.5, 32.5,
  143949. 498, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5,
  143950. };
  143951. static long _vq_quantmap__16u2_p9_0[] = {
  143952. 11, 9, 7, 5, 3, 1, 13, 0,
  143953. 14, 2, 4, 6, 8, 10, 12,
  143954. };
  143955. static encode_aux_threshmatch _vq_auxt__16u2_p9_0 = {
  143956. _vq_quantthresh__16u2_p9_0,
  143957. _vq_quantmap__16u2_p9_0,
  143958. 15,
  143959. 15
  143960. };
  143961. static static_codebook _16u2_p9_0 = {
  143962. 2, 225,
  143963. _vq_lengthlist__16u2_p9_0,
  143964. 1, -510275072, 1611661312, 14, 0,
  143965. _vq_quantlist__16u2_p9_0,
  143966. NULL,
  143967. &_vq_auxt__16u2_p9_0,
  143968. NULL,
  143969. 0
  143970. };
  143971. static long _vq_quantlist__16u2_p9_1[] = {
  143972. 392,
  143973. 343,
  143974. 441,
  143975. 294,
  143976. 490,
  143977. 245,
  143978. 539,
  143979. 196,
  143980. 588,
  143981. 147,
  143982. 637,
  143983. 98,
  143984. 686,
  143985. 49,
  143986. 735,
  143987. 0,
  143988. 784,
  143989. 388,
  143990. 396,
  143991. };
  143992. static long _vq_lengthlist__16u2_p9_1[] = {
  143993. 1,12,10,12,10,12,10,12,11,12,12,12,12,12,12,12,
  143994. 12, 5, 5, 9,10,12,11,11,12,12,12,12,12,12,12,12,
  143995. 12,12,12,12,10, 9, 9,11, 9,11,11,12,11,12,12,12,
  143996. 12,12,12,12,12,12,12, 8, 8,10,11, 9,12,11,12,12,
  143997. 12,12,12,12,12,12,12,12,12,12, 9, 8,10,11,12,11,
  143998. 12,11,12,12,12,12,12,12,12,12,12,12,12, 8, 9,11,
  143999. 11,10,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144000. 9,10,11,12,11,12,11,12,12,12,12,12,12,12,12,12,
  144001. 12,12,12, 9, 9,11,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,12,12,12,12,12,12,12,12,12,12,12,12,
  144005. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144006. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144007. 12,12,12,12,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,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144011. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144012. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144013. 11,11,11, 5, 8, 9, 9, 8,11, 9,11,11,11,11,11,11,
  144014. 11,11,11,11, 5, 5, 4, 8, 8, 8, 8,10, 9,10,10,11,
  144015. 11,11,11,11,11,11,11, 5, 4,
  144016. };
  144017. static float _vq_quantthresh__16u2_p9_1[] = {
  144018. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -26.5,
  144019. -2, 2, 26.5, 73.5, 122.5, 171.5, 220.5, 269.5,
  144020. 318.5, 367.5,
  144021. };
  144022. static long _vq_quantmap__16u2_p9_1[] = {
  144023. 15, 13, 11, 9, 7, 5, 3, 1,
  144024. 17, 0, 18, 2, 4, 6, 8, 10,
  144025. 12, 14, 16,
  144026. };
  144027. static encode_aux_threshmatch _vq_auxt__16u2_p9_1 = {
  144028. _vq_quantthresh__16u2_p9_1,
  144029. _vq_quantmap__16u2_p9_1,
  144030. 19,
  144031. 19
  144032. };
  144033. static static_codebook _16u2_p9_1 = {
  144034. 2, 361,
  144035. _vq_lengthlist__16u2_p9_1,
  144036. 1, -518488064, 1611661312, 10, 0,
  144037. _vq_quantlist__16u2_p9_1,
  144038. NULL,
  144039. &_vq_auxt__16u2_p9_1,
  144040. NULL,
  144041. 0
  144042. };
  144043. static long _vq_quantlist__16u2_p9_2[] = {
  144044. 24,
  144045. 23,
  144046. 25,
  144047. 22,
  144048. 26,
  144049. 21,
  144050. 27,
  144051. 20,
  144052. 28,
  144053. 19,
  144054. 29,
  144055. 18,
  144056. 30,
  144057. 17,
  144058. 31,
  144059. 16,
  144060. 32,
  144061. 15,
  144062. 33,
  144063. 14,
  144064. 34,
  144065. 13,
  144066. 35,
  144067. 12,
  144068. 36,
  144069. 11,
  144070. 37,
  144071. 10,
  144072. 38,
  144073. 9,
  144074. 39,
  144075. 8,
  144076. 40,
  144077. 7,
  144078. 41,
  144079. 6,
  144080. 42,
  144081. 5,
  144082. 43,
  144083. 4,
  144084. 44,
  144085. 3,
  144086. 45,
  144087. 2,
  144088. 46,
  144089. 1,
  144090. 47,
  144091. 0,
  144092. 48,
  144093. };
  144094. static long _vq_lengthlist__16u2_p9_2[] = {
  144095. 1, 3, 3, 4, 7, 7, 7, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  144096. 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 9, 9, 8, 9, 9,
  144097. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,12,12,10,
  144098. 11,
  144099. };
  144100. static float _vq_quantthresh__16u2_p9_2[] = {
  144101. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  144102. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  144103. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144104. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144105. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  144106. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  144107. };
  144108. static long _vq_quantmap__16u2_p9_2[] = {
  144109. 47, 45, 43, 41, 39, 37, 35, 33,
  144110. 31, 29, 27, 25, 23, 21, 19, 17,
  144111. 15, 13, 11, 9, 7, 5, 3, 1,
  144112. 0, 2, 4, 6, 8, 10, 12, 14,
  144113. 16, 18, 20, 22, 24, 26, 28, 30,
  144114. 32, 34, 36, 38, 40, 42, 44, 46,
  144115. 48,
  144116. };
  144117. static encode_aux_threshmatch _vq_auxt__16u2_p9_2 = {
  144118. _vq_quantthresh__16u2_p9_2,
  144119. _vq_quantmap__16u2_p9_2,
  144120. 49,
  144121. 49
  144122. };
  144123. static static_codebook _16u2_p9_2 = {
  144124. 1, 49,
  144125. _vq_lengthlist__16u2_p9_2,
  144126. 1, -526909440, 1611661312, 6, 0,
  144127. _vq_quantlist__16u2_p9_2,
  144128. NULL,
  144129. &_vq_auxt__16u2_p9_2,
  144130. NULL,
  144131. 0
  144132. };
  144133. static long _vq_quantlist__8u0__p1_0[] = {
  144134. 1,
  144135. 0,
  144136. 2,
  144137. };
  144138. static long _vq_lengthlist__8u0__p1_0[] = {
  144139. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  144140. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 4, 9, 8, 8,11,
  144141. 11, 8,11,11, 7,11,11,10,11,13,10,13,13, 7,11,11,
  144142. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 8,11,11, 7,
  144143. 11,11, 9,13,13,10,12,13, 7,11,11,10,13,13,10,13,
  144144. 11,
  144145. };
  144146. static float _vq_quantthresh__8u0__p1_0[] = {
  144147. -0.5, 0.5,
  144148. };
  144149. static long _vq_quantmap__8u0__p1_0[] = {
  144150. 1, 0, 2,
  144151. };
  144152. static encode_aux_threshmatch _vq_auxt__8u0__p1_0 = {
  144153. _vq_quantthresh__8u0__p1_0,
  144154. _vq_quantmap__8u0__p1_0,
  144155. 3,
  144156. 3
  144157. };
  144158. static static_codebook _8u0__p1_0 = {
  144159. 4, 81,
  144160. _vq_lengthlist__8u0__p1_0,
  144161. 1, -535822336, 1611661312, 2, 0,
  144162. _vq_quantlist__8u0__p1_0,
  144163. NULL,
  144164. &_vq_auxt__8u0__p1_0,
  144165. NULL,
  144166. 0
  144167. };
  144168. static long _vq_quantlist__8u0__p2_0[] = {
  144169. 1,
  144170. 0,
  144171. 2,
  144172. };
  144173. static long _vq_lengthlist__8u0__p2_0[] = {
  144174. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 6, 7, 8, 6,
  144175. 7, 8, 5, 7, 7, 6, 8, 8, 7, 9, 7, 5, 7, 7, 7, 9,
  144176. 9, 7, 8, 8, 6, 9, 8, 7, 7,10, 8,10,10, 6, 8, 8,
  144177. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  144178. 8, 8, 8,10,10, 8, 8,10, 6, 8, 9, 8,10,10, 7,10,
  144179. 8,
  144180. };
  144181. static float _vq_quantthresh__8u0__p2_0[] = {
  144182. -0.5, 0.5,
  144183. };
  144184. static long _vq_quantmap__8u0__p2_0[] = {
  144185. 1, 0, 2,
  144186. };
  144187. static encode_aux_threshmatch _vq_auxt__8u0__p2_0 = {
  144188. _vq_quantthresh__8u0__p2_0,
  144189. _vq_quantmap__8u0__p2_0,
  144190. 3,
  144191. 3
  144192. };
  144193. static static_codebook _8u0__p2_0 = {
  144194. 4, 81,
  144195. _vq_lengthlist__8u0__p2_0,
  144196. 1, -535822336, 1611661312, 2, 0,
  144197. _vq_quantlist__8u0__p2_0,
  144198. NULL,
  144199. &_vq_auxt__8u0__p2_0,
  144200. NULL,
  144201. 0
  144202. };
  144203. static long _vq_quantlist__8u0__p3_0[] = {
  144204. 2,
  144205. 1,
  144206. 3,
  144207. 0,
  144208. 4,
  144209. };
  144210. static long _vq_lengthlist__8u0__p3_0[] = {
  144211. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  144212. 10, 9,11,11, 8, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  144213. 10,11,11, 8,10,10,11,11,10,11,11,12,12,10,11,11,
  144214. 12,13, 6, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  144215. 11, 9,10,11,12,12,10,11,11,12,12, 8,11,11,14,13,
  144216. 10,12,11,15,13,10,12,11,14,14,12,13,12,16,14,12,
  144217. 14,12,16,15, 8,11,11,13,14,10,11,12,13,15,10,11,
  144218. 12,13,15,11,12,13,14,15,12,12,14,14,16, 5, 8, 8,
  144219. 11,11, 9,11,11,12,12, 8,10,11,12,12,11,12,12,15,
  144220. 14,11,12,12,14,14, 7,11,10,13,12,10,11,12,13,14,
  144221. 10,12,12,14,13,12,13,13,14,15,12,13,13,15,15, 7,
  144222. 10,11,12,13,10,12,11,14,13,10,12,13,13,15,12,13,
  144223. 12,14,14,11,13,13,15,16, 9,12,12,15,14,11,13,13,
  144224. 15,16,11,13,13,16,16,13,14,15,15,15,12,14,15,17,
  144225. 16, 9,12,12,14,15,11,13,13,15,16,11,13,13,16,18,
  144226. 13,14,14,17,16,13,15,15,17,18, 5, 8, 9,11,11, 8,
  144227. 11,11,12,12, 8,10,11,12,12,11,12,12,14,14,11,12,
  144228. 12,14,15, 7,11,10,12,13,10,12,12,14,13,10,11,12,
  144229. 13,14,11,13,13,15,14,12,13,13,14,15, 7,10,11,13,
  144230. 13,10,12,12,13,14,10,12,12,13,13,11,13,13,16,16,
  144231. 12,13,13,15,14, 9,12,12,16,15,10,13,13,15,15,11,
  144232. 13,13,17,15,12,15,15,18,17,13,14,14,15,16, 9,12,
  144233. 12,15,15,11,13,13,15,16,11,13,13,15,15,12,15,15,
  144234. 16,16,13,15,14,17,15, 7,11,11,15,15,10,13,13,16,
  144235. 15,10,13,13,15,16,14,15,15,17,19,13,15,14,15,18,
  144236. 9,12,12,16,16,11,13,14,17,16,11,13,13,17,16,15,
  144237. 15,16,17,19,13,15,16, 0,18, 9,12,12,16,15,11,14,
  144238. 13,17,17,11,13,14,16,16,15,16,16,19,18,13,15,15,
  144239. 17,19,11,14,14,19,16,12,14,15, 0,18,12,16,15,18,
  144240. 17,15,15,18,16,19,14,15,17,19,19,11,14,14,18,19,
  144241. 13,15,14,19,19,12,16,15,18,17,15,17,15, 0,16,14,
  144242. 17,16,19, 0, 7,11,11,14,14,10,12,12,15,15,10,13,
  144243. 13,16,15,13,15,15,17, 0,14,15,15,16,19, 9,12,12,
  144244. 16,16,11,14,14,16,16,11,13,13,16,16,14,17,16,19,
  144245. 0,14,18,17,17,19, 9,12,12,15,16,11,13,13,15,17,
  144246. 12,14,13,19,16,13,15,15,17,19,15,17,16,17,19,11,
  144247. 14,14,19,16,12,15,15,19,17,13,14,15,17,19,14,16,
  144248. 17,19,19,16,15,16,17,19,11,15,14,16,16,12,15,15,
  144249. 19, 0,12,14,15,19,19,14,16,16, 0,18,15,19,14,18,
  144250. 16,
  144251. };
  144252. static float _vq_quantthresh__8u0__p3_0[] = {
  144253. -1.5, -0.5, 0.5, 1.5,
  144254. };
  144255. static long _vq_quantmap__8u0__p3_0[] = {
  144256. 3, 1, 0, 2, 4,
  144257. };
  144258. static encode_aux_threshmatch _vq_auxt__8u0__p3_0 = {
  144259. _vq_quantthresh__8u0__p3_0,
  144260. _vq_quantmap__8u0__p3_0,
  144261. 5,
  144262. 5
  144263. };
  144264. static static_codebook _8u0__p3_0 = {
  144265. 4, 625,
  144266. _vq_lengthlist__8u0__p3_0,
  144267. 1, -533725184, 1611661312, 3, 0,
  144268. _vq_quantlist__8u0__p3_0,
  144269. NULL,
  144270. &_vq_auxt__8u0__p3_0,
  144271. NULL,
  144272. 0
  144273. };
  144274. static long _vq_quantlist__8u0__p4_0[] = {
  144275. 2,
  144276. 1,
  144277. 3,
  144278. 0,
  144279. 4,
  144280. };
  144281. static long _vq_lengthlist__8u0__p4_0[] = {
  144282. 3, 5, 5, 8, 8, 5, 6, 7, 9, 9, 6, 7, 6, 9, 9, 9,
  144283. 9, 9,10,11, 9, 9, 9,11,10, 6, 7, 7,10,10, 7, 7,
  144284. 8,10,10, 7, 8, 8,10,10,10,10,10,10,11, 9,10,10,
  144285. 11,12, 6, 7, 7,10,10, 7, 8, 8,10,10, 7, 8, 7,10,
  144286. 10, 9,10,10,12,11,10,10,10,11,10, 9,10,10,12,11,
  144287. 10,10,10,13,11, 9,10,10,12,12,11,11,12,12,13,11,
  144288. 11,11,12,13, 9,10,10,12,12,10,10,11,12,12,10,10,
  144289. 11,12,12,11,11,11,13,13,11,12,12,13,13, 5, 7, 7,
  144290. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,11,12,
  144291. 12,10,11,10,12,12, 7, 8, 8,11,11, 7, 8, 9,10,11,
  144292. 8, 9, 9,11,11,11,10,11,10,12,10,11,11,12,13, 7,
  144293. 8, 8,10,11, 8, 9, 8,12,10, 8, 9, 9,11,12,10,11,
  144294. 10,13,11,10,11,11,13,12, 9,11,10,13,12,10,10,11,
  144295. 12,12,10,11,11,13,13,12,10,13,11,14,11,12,12,15,
  144296. 13, 9,11,11,13,13,10,11,11,13,12,10,11,11,12,14,
  144297. 12,13,11,14,12,12,12,12,14,14, 5, 7, 7,10,10, 7,
  144298. 8, 8,10,10, 7, 8, 8,11,10,10,11,11,12,12,10,11,
  144299. 10,12,12, 7, 8, 8,10,11, 8, 9, 9,12,11, 8, 8, 9,
  144300. 10,11,10,11,11,12,13,11,10,11,11,13, 6, 8, 8,10,
  144301. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,11,11,12,12,
  144302. 10,11,10,13,10, 9,11,10,13,12,10,12,11,13,13,10,
  144303. 10,11,12,13,11,12,13,15,14,11,11,13,12,13, 9,10,
  144304. 11,12,13,10,11,11,12,13,10,11,10,13,12,12,13,13,
  144305. 13,14,12,12,11,14,11, 8,10,10,12,13,10,11,11,13,
  144306. 13,10,11,10,13,13,12,13,14,15,14,12,12,12,14,13,
  144307. 9,10,10,13,12,10,10,12,13,13,10,11,11,15,12,12,
  144308. 12,13,15,14,12,13,13,15,13, 9,10,11,12,13,10,12,
  144309. 10,13,12,10,11,11,12,13,12,14,12,15,13,12,12,12,
  144310. 15,14,11,12,11,14,13,11,11,12,14,14,12,13,13,14,
  144311. 13,13,11,15,11,15,14,14,14,16,15,11,12,12,13,14,
  144312. 11,13,11,14,14,12,12,13,14,15,12,14,12,15,12,13,
  144313. 15,14,16,15, 8,10,10,12,12,10,10,10,12,13,10,11,
  144314. 11,13,13,12,12,12,13,14,13,13,13,15,15, 9,10,10,
  144315. 12,12,10,11,11,13,12,10,10,11,13,13,12,12,12,14,
  144316. 14,12,12,13,15,14, 9,10,10,13,12,10,10,12,12,13,
  144317. 10,11,10,13,13,12,13,13,14,14,12,13,12,14,13,11,
  144318. 12,12,14,13,12,13,12,14,14,10,12,12,14,14,14,14,
  144319. 14,16,14,13,12,14,12,15,10,12,12,14,15,12,13,13,
  144320. 14,16,11,12,11,15,14,13,14,14,14,15,13,14,11,14,
  144321. 12,
  144322. };
  144323. static float _vq_quantthresh__8u0__p4_0[] = {
  144324. -1.5, -0.5, 0.5, 1.5,
  144325. };
  144326. static long _vq_quantmap__8u0__p4_0[] = {
  144327. 3, 1, 0, 2, 4,
  144328. };
  144329. static encode_aux_threshmatch _vq_auxt__8u0__p4_0 = {
  144330. _vq_quantthresh__8u0__p4_0,
  144331. _vq_quantmap__8u0__p4_0,
  144332. 5,
  144333. 5
  144334. };
  144335. static static_codebook _8u0__p4_0 = {
  144336. 4, 625,
  144337. _vq_lengthlist__8u0__p4_0,
  144338. 1, -533725184, 1611661312, 3, 0,
  144339. _vq_quantlist__8u0__p4_0,
  144340. NULL,
  144341. &_vq_auxt__8u0__p4_0,
  144342. NULL,
  144343. 0
  144344. };
  144345. static long _vq_quantlist__8u0__p5_0[] = {
  144346. 4,
  144347. 3,
  144348. 5,
  144349. 2,
  144350. 6,
  144351. 1,
  144352. 7,
  144353. 0,
  144354. 8,
  144355. };
  144356. static long _vq_lengthlist__8u0__p5_0[] = {
  144357. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 7, 8, 8,
  144358. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 6, 8, 8, 9, 9,
  144359. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  144360. 9, 9,10,10,12,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  144361. 10,10,11,11,11,12,12,12, 9,10,10,11,11,12,12,12,
  144362. 12,
  144363. };
  144364. static float _vq_quantthresh__8u0__p5_0[] = {
  144365. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144366. };
  144367. static long _vq_quantmap__8u0__p5_0[] = {
  144368. 7, 5, 3, 1, 0, 2, 4, 6,
  144369. 8,
  144370. };
  144371. static encode_aux_threshmatch _vq_auxt__8u0__p5_0 = {
  144372. _vq_quantthresh__8u0__p5_0,
  144373. _vq_quantmap__8u0__p5_0,
  144374. 9,
  144375. 9
  144376. };
  144377. static static_codebook _8u0__p5_0 = {
  144378. 2, 81,
  144379. _vq_lengthlist__8u0__p5_0,
  144380. 1, -531628032, 1611661312, 4, 0,
  144381. _vq_quantlist__8u0__p5_0,
  144382. NULL,
  144383. &_vq_auxt__8u0__p5_0,
  144384. NULL,
  144385. 0
  144386. };
  144387. static long _vq_quantlist__8u0__p6_0[] = {
  144388. 6,
  144389. 5,
  144390. 7,
  144391. 4,
  144392. 8,
  144393. 3,
  144394. 9,
  144395. 2,
  144396. 10,
  144397. 1,
  144398. 11,
  144399. 0,
  144400. 12,
  144401. };
  144402. static long _vq_lengthlist__8u0__p6_0[] = {
  144403. 1, 4, 4, 7, 7, 9, 9,11,11,12,12,16,16, 3, 6, 6,
  144404. 9, 9,11,11,12,12,13,14,18,16, 3, 6, 7, 9, 9,11,
  144405. 11,13,12,14,14,17,16, 7, 9, 9,11,11,12,12,14,14,
  144406. 14,14,17,16, 7, 9, 9,11,11,13,12,13,13,14,14,17,
  144407. 0, 9,11,11,12,13,14,14,14,13,15,14,17,17, 9,11,
  144408. 11,12,12,14,14,13,14,14,15, 0, 0,11,12,12,15,14,
  144409. 15,14,15,14,15,16,17, 0,11,12,13,13,13,14,14,15,
  144410. 14,15,15, 0, 0,12,14,14,15,15,14,16,15,15,17,16,
  144411. 0,18,13,14,14,15,14,15,14,15,16,17,16, 0, 0,17,
  144412. 17,18, 0,16,18,16, 0, 0, 0,17, 0, 0,16, 0, 0,16,
  144413. 16, 0,15, 0,17, 0, 0, 0, 0,
  144414. };
  144415. static float _vq_quantthresh__8u0__p6_0[] = {
  144416. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  144417. 12.5, 17.5, 22.5, 27.5,
  144418. };
  144419. static long _vq_quantmap__8u0__p6_0[] = {
  144420. 11, 9, 7, 5, 3, 1, 0, 2,
  144421. 4, 6, 8, 10, 12,
  144422. };
  144423. static encode_aux_threshmatch _vq_auxt__8u0__p6_0 = {
  144424. _vq_quantthresh__8u0__p6_0,
  144425. _vq_quantmap__8u0__p6_0,
  144426. 13,
  144427. 13
  144428. };
  144429. static static_codebook _8u0__p6_0 = {
  144430. 2, 169,
  144431. _vq_lengthlist__8u0__p6_0,
  144432. 1, -526516224, 1616117760, 4, 0,
  144433. _vq_quantlist__8u0__p6_0,
  144434. NULL,
  144435. &_vq_auxt__8u0__p6_0,
  144436. NULL,
  144437. 0
  144438. };
  144439. static long _vq_quantlist__8u0__p6_1[] = {
  144440. 2,
  144441. 1,
  144442. 3,
  144443. 0,
  144444. 4,
  144445. };
  144446. static long _vq_lengthlist__8u0__p6_1[] = {
  144447. 1, 4, 4, 6, 6, 4, 6, 5, 7, 7, 4, 5, 6, 7, 7, 6,
  144448. 7, 7, 7, 7, 6, 7, 7, 7, 7,
  144449. };
  144450. static float _vq_quantthresh__8u0__p6_1[] = {
  144451. -1.5, -0.5, 0.5, 1.5,
  144452. };
  144453. static long _vq_quantmap__8u0__p6_1[] = {
  144454. 3, 1, 0, 2, 4,
  144455. };
  144456. static encode_aux_threshmatch _vq_auxt__8u0__p6_1 = {
  144457. _vq_quantthresh__8u0__p6_1,
  144458. _vq_quantmap__8u0__p6_1,
  144459. 5,
  144460. 5
  144461. };
  144462. static static_codebook _8u0__p6_1 = {
  144463. 2, 25,
  144464. _vq_lengthlist__8u0__p6_1,
  144465. 1, -533725184, 1611661312, 3, 0,
  144466. _vq_quantlist__8u0__p6_1,
  144467. NULL,
  144468. &_vq_auxt__8u0__p6_1,
  144469. NULL,
  144470. 0
  144471. };
  144472. static long _vq_quantlist__8u0__p7_0[] = {
  144473. 1,
  144474. 0,
  144475. 2,
  144476. };
  144477. static long _vq_lengthlist__8u0__p7_0[] = {
  144478. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144479. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144480. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  144481. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  144482. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  144483. 7,
  144484. };
  144485. static float _vq_quantthresh__8u0__p7_0[] = {
  144486. -157.5, 157.5,
  144487. };
  144488. static long _vq_quantmap__8u0__p7_0[] = {
  144489. 1, 0, 2,
  144490. };
  144491. static encode_aux_threshmatch _vq_auxt__8u0__p7_0 = {
  144492. _vq_quantthresh__8u0__p7_0,
  144493. _vq_quantmap__8u0__p7_0,
  144494. 3,
  144495. 3
  144496. };
  144497. static static_codebook _8u0__p7_0 = {
  144498. 4, 81,
  144499. _vq_lengthlist__8u0__p7_0,
  144500. 1, -518803456, 1628680192, 2, 0,
  144501. _vq_quantlist__8u0__p7_0,
  144502. NULL,
  144503. &_vq_auxt__8u0__p7_0,
  144504. NULL,
  144505. 0
  144506. };
  144507. static long _vq_quantlist__8u0__p7_1[] = {
  144508. 7,
  144509. 6,
  144510. 8,
  144511. 5,
  144512. 9,
  144513. 4,
  144514. 10,
  144515. 3,
  144516. 11,
  144517. 2,
  144518. 12,
  144519. 1,
  144520. 13,
  144521. 0,
  144522. 14,
  144523. };
  144524. static long _vq_lengthlist__8u0__p7_1[] = {
  144525. 1, 5, 5, 5, 5,10,10,11,11,11,11,11,11,11,11, 5,
  144526. 7, 6, 8, 8, 9,10,11,11,11,11,11,11,11,11, 6, 6,
  144527. 7, 9, 7,11,10,11,11,11,11,11,11,11,11, 5, 6, 6,
  144528. 11, 8,11,11,11,11,11,11,11,11,11,11, 5, 6, 6, 9,
  144529. 10,11,10,11,11,11,11,11,11,11,11, 7,10,10,11,11,
  144530. 11,11,11,11,11,11,11,11,11,11, 7,11, 8,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,11,11,11,11,11,
  144535. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144536. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144537. 11,11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,
  144538. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144539. 10,
  144540. };
  144541. static float _vq_quantthresh__8u0__p7_1[] = {
  144542. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  144543. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  144544. };
  144545. static long _vq_quantmap__8u0__p7_1[] = {
  144546. 13, 11, 9, 7, 5, 3, 1, 0,
  144547. 2, 4, 6, 8, 10, 12, 14,
  144548. };
  144549. static encode_aux_threshmatch _vq_auxt__8u0__p7_1 = {
  144550. _vq_quantthresh__8u0__p7_1,
  144551. _vq_quantmap__8u0__p7_1,
  144552. 15,
  144553. 15
  144554. };
  144555. static static_codebook _8u0__p7_1 = {
  144556. 2, 225,
  144557. _vq_lengthlist__8u0__p7_1,
  144558. 1, -520986624, 1620377600, 4, 0,
  144559. _vq_quantlist__8u0__p7_1,
  144560. NULL,
  144561. &_vq_auxt__8u0__p7_1,
  144562. NULL,
  144563. 0
  144564. };
  144565. static long _vq_quantlist__8u0__p7_2[] = {
  144566. 10,
  144567. 9,
  144568. 11,
  144569. 8,
  144570. 12,
  144571. 7,
  144572. 13,
  144573. 6,
  144574. 14,
  144575. 5,
  144576. 15,
  144577. 4,
  144578. 16,
  144579. 3,
  144580. 17,
  144581. 2,
  144582. 18,
  144583. 1,
  144584. 19,
  144585. 0,
  144586. 20,
  144587. };
  144588. static long _vq_lengthlist__8u0__p7_2[] = {
  144589. 1, 6, 5, 7, 7, 9, 9, 9, 9,10,12,12,10,11,11,10,
  144590. 11,11,11,10,11, 6, 8, 8, 9, 9,10,10, 9,10,11,11,
  144591. 10,11,11,11,11,10,11,11,11,11, 6, 7, 8, 9, 9, 9,
  144592. 10,11,10,11,12,11,10,11,11,11,11,11,11,12,10, 8,
  144593. 9, 9,10, 9,10,10, 9,10,10,10,10,10, 9,10,10,10,
  144594. 10, 9,10,10, 9, 9, 9, 9,10,10, 9, 9,10,10,11,10,
  144595. 9,12,10,11,10, 9,10,10,10, 8, 9, 9,10, 9,10, 9,
  144596. 9,10,10, 9,10, 9,11,10,10,10,10,10, 9,10, 8, 8,
  144597. 9, 9,10, 9,11, 9, 8, 9, 9,10,11,10,10,10,11,12,
  144598. 9, 9,11, 8, 9, 8,11,10,11,10,10, 9,11,10,10,10,
  144599. 10,10,10,10,11,11,11,11, 8, 9, 9, 9,10,10,10,11,
  144600. 11,12,11,12,11,10,10,10,12,11,11,11,10, 8,10, 9,
  144601. 11,10,10,11,12,10,11,12,11,11,12,11,12,12,10,11,
  144602. 11,10, 9, 9,10,11,12,10,10,10,11,10,11,11,10,12,
  144603. 12,10,11,10,11,12,10, 9,10,10,11,10,11,11,11,11,
  144604. 11,12,11,11,11, 9,11,10,11,10,11,10, 9, 9,10,11,
  144605. 11,11,10,10,11,12,12,11,12,11,11,11,12,12,12,12,
  144606. 11, 9,11,11,12,10,11,11,11,11,11,11,12,11,11,12,
  144607. 11,11,11,10,11,11, 9,11,10,11,11,11,10,10,10,11,
  144608. 11,11,12,10,11,10,11,11,11,11,12, 9,11,10,11,11,
  144609. 10,10,11,11, 9,11,11,12,10,10,10,10,10,11,11,10,
  144610. 9,10,11,11,12,11,10,10,12,11,11,12,11,12,11,11,
  144611. 10,10,11,11,10,12,11,10,11,10,11,10,10,10,11,11,
  144612. 10,10,11,11,11,11,10,10,10,12,11,11,11,11,10, 9,
  144613. 10,11,11,11,12,11,11,11,12,10,11,11,11, 9,10,11,
  144614. 11,11,11,11,11,10,10,11,11,12,11,10,11,12,11,10,
  144615. 10,11, 9,10,11,11,11,11,11,10,11,11,10,12,11,11,
  144616. 11,12,11,11,11,10,10,11,11,
  144617. };
  144618. static float _vq_quantthresh__8u0__p7_2[] = {
  144619. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  144620. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  144621. 6.5, 7.5, 8.5, 9.5,
  144622. };
  144623. static long _vq_quantmap__8u0__p7_2[] = {
  144624. 19, 17, 15, 13, 11, 9, 7, 5,
  144625. 3, 1, 0, 2, 4, 6, 8, 10,
  144626. 12, 14, 16, 18, 20,
  144627. };
  144628. static encode_aux_threshmatch _vq_auxt__8u0__p7_2 = {
  144629. _vq_quantthresh__8u0__p7_2,
  144630. _vq_quantmap__8u0__p7_2,
  144631. 21,
  144632. 21
  144633. };
  144634. static static_codebook _8u0__p7_2 = {
  144635. 2, 441,
  144636. _vq_lengthlist__8u0__p7_2,
  144637. 1, -529268736, 1611661312, 5, 0,
  144638. _vq_quantlist__8u0__p7_2,
  144639. NULL,
  144640. &_vq_auxt__8u0__p7_2,
  144641. NULL,
  144642. 0
  144643. };
  144644. static long _huff_lengthlist__8u0__single[] = {
  144645. 4, 7,11, 9,12, 8, 7,10, 6, 4, 5, 5, 7, 5, 6,16,
  144646. 9, 5, 5, 6, 7, 7, 9,16, 7, 4, 6, 5, 7, 5, 7,17,
  144647. 10, 7, 7, 8, 7, 7, 8,18, 7, 5, 6, 4, 5, 4, 5,15,
  144648. 7, 6, 7, 5, 6, 4, 5,15,12,13,18,12,17,11, 9,17,
  144649. };
  144650. static static_codebook _huff_book__8u0__single = {
  144651. 2, 64,
  144652. _huff_lengthlist__8u0__single,
  144653. 0, 0, 0, 0, 0,
  144654. NULL,
  144655. NULL,
  144656. NULL,
  144657. NULL,
  144658. 0
  144659. };
  144660. static long _vq_quantlist__8u1__p1_0[] = {
  144661. 1,
  144662. 0,
  144663. 2,
  144664. };
  144665. static long _vq_lengthlist__8u1__p1_0[] = {
  144666. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 7, 9,10, 7,
  144667. 9, 9, 5, 8, 8, 7,10, 9, 7, 9, 9, 5, 8, 8, 8,10,
  144668. 10, 8,10,10, 7,10,10, 9,10,12,10,12,12, 7,10,10,
  144669. 9,12,11,10,12,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  144670. 10,10,10,12,12, 9,11,12, 7,10,10,10,12,12, 9,12,
  144671. 10,
  144672. };
  144673. static float _vq_quantthresh__8u1__p1_0[] = {
  144674. -0.5, 0.5,
  144675. };
  144676. static long _vq_quantmap__8u1__p1_0[] = {
  144677. 1, 0, 2,
  144678. };
  144679. static encode_aux_threshmatch _vq_auxt__8u1__p1_0 = {
  144680. _vq_quantthresh__8u1__p1_0,
  144681. _vq_quantmap__8u1__p1_0,
  144682. 3,
  144683. 3
  144684. };
  144685. static static_codebook _8u1__p1_0 = {
  144686. 4, 81,
  144687. _vq_lengthlist__8u1__p1_0,
  144688. 1, -535822336, 1611661312, 2, 0,
  144689. _vq_quantlist__8u1__p1_0,
  144690. NULL,
  144691. &_vq_auxt__8u1__p1_0,
  144692. NULL,
  144693. 0
  144694. };
  144695. static long _vq_quantlist__8u1__p2_0[] = {
  144696. 1,
  144697. 0,
  144698. 2,
  144699. };
  144700. static long _vq_lengthlist__8u1__p2_0[] = {
  144701. 3, 4, 5, 5, 6, 6, 5, 6, 6, 5, 7, 6, 6, 7, 8, 6,
  144702. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 7, 8,
  144703. 8, 6, 7, 7, 6, 8, 7, 7, 7, 9, 8, 9, 9, 6, 7, 8,
  144704. 7, 9, 7, 8, 9, 9, 5, 6, 6, 6, 7, 7, 7, 8, 8, 6,
  144705. 8, 7, 8, 9, 9, 7, 7, 9, 6, 7, 8, 8, 9, 9, 7, 9,
  144706. 7,
  144707. };
  144708. static float _vq_quantthresh__8u1__p2_0[] = {
  144709. -0.5, 0.5,
  144710. };
  144711. static long _vq_quantmap__8u1__p2_0[] = {
  144712. 1, 0, 2,
  144713. };
  144714. static encode_aux_threshmatch _vq_auxt__8u1__p2_0 = {
  144715. _vq_quantthresh__8u1__p2_0,
  144716. _vq_quantmap__8u1__p2_0,
  144717. 3,
  144718. 3
  144719. };
  144720. static static_codebook _8u1__p2_0 = {
  144721. 4, 81,
  144722. _vq_lengthlist__8u1__p2_0,
  144723. 1, -535822336, 1611661312, 2, 0,
  144724. _vq_quantlist__8u1__p2_0,
  144725. NULL,
  144726. &_vq_auxt__8u1__p2_0,
  144727. NULL,
  144728. 0
  144729. };
  144730. static long _vq_quantlist__8u1__p3_0[] = {
  144731. 2,
  144732. 1,
  144733. 3,
  144734. 0,
  144735. 4,
  144736. };
  144737. static long _vq_lengthlist__8u1__p3_0[] = {
  144738. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  144739. 10, 9,11,11, 9, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  144740. 10,11,11, 8, 9,10,11,11,10,11,11,12,12,10,11,11,
  144741. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  144742. 11,10,11,11,12,12,10,11,11,12,12, 9,11,11,14,13,
  144743. 10,12,11,14,14,10,12,11,14,13,12,13,13,15,14,12,
  144744. 13,13,15,14, 8,11,11,13,14,10,11,12,13,15,10,11,
  144745. 12,14,14,12,13,13,14,15,12,13,13,14,15, 5, 8, 8,
  144746. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  144747. 13,11,12,12,13,14, 8,10,10,12,12, 9,11,12,13,14,
  144748. 10,12,12,13,13,12,12,13,14,14,11,13,13,15,15, 7,
  144749. 10,10,12,12, 9,12,11,14,12,10,11,12,13,14,12,13,
  144750. 12,14,14,12,13,13,15,16,10,12,12,15,14,11,12,13,
  144751. 15,15,11,13,13,15,16,14,14,15,15,16,13,14,15,17,
  144752. 15, 9,12,12,14,15,11,13,12,15,15,11,13,13,15,15,
  144753. 13,14,13,15,14,13,14,14,17, 0, 5, 8, 8,11,11, 8,
  144754. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  144755. 12,14,14, 7,10,10,12,12,10,12,12,13,13, 9,11,12,
  144756. 12,13,11,12,13,15,15,11,12,13,14,15, 8,10,10,12,
  144757. 12,10,12,11,13,13,10,12,11,13,13,11,13,13,15,14,
  144758. 12,13,12,15,13, 9,12,12,14,14,11,13,13,16,15,11,
  144759. 12,13,16,15,13,14,15,16,16,13,13,15,15,16,10,12,
  144760. 12,15,14,11,13,13,14,16,11,13,13,15,16,13,15,15,
  144761. 16,17,13,15,14,16,15, 8,11,11,14,15,10,12,12,15,
  144762. 15,10,12,12,15,16,14,15,15,16,17,13,14,14,16,16,
  144763. 9,12,12,15,15,11,13,14,15,17,11,13,13,15,16,14,
  144764. 15,16,19,17,13,15,15, 0,17, 9,12,12,15,15,11,14,
  144765. 13,16,15,11,13,13,15,16,15,15,15,18,17,13,15,15,
  144766. 17,17,11,15,14,18,16,12,14,15,17,17,12,15,15,18,
  144767. 18,15,15,16,15,19,14,16,16, 0, 0,11,14,14,16,17,
  144768. 12,15,14,18,17,12,15,15,18,18,15,17,15,18,16,14,
  144769. 16,16,18,18, 7,11,11,14,14,10,12,12,15,15,10,12,
  144770. 13,15,15,13,14,15,16,16,14,15,15,18,18, 9,12,12,
  144771. 15,15,11,13,13,16,15,11,12,13,16,16,14,15,15,17,
  144772. 16,15,16,16,17,17, 9,12,12,15,15,11,13,13,15,17,
  144773. 11,14,13,16,15,13,15,15,17,17,15,15,15,18,17,11,
  144774. 14,14,17,15,12,14,15,17,18,13,13,15,17,17,14,16,
  144775. 16,19,18,16,15,17,17, 0,11,14,14,17,17,12,15,15,
  144776. 18, 0,12,15,14,18,16,14,17,17,19, 0,16,18,15, 0,
  144777. 16,
  144778. };
  144779. static float _vq_quantthresh__8u1__p3_0[] = {
  144780. -1.5, -0.5, 0.5, 1.5,
  144781. };
  144782. static long _vq_quantmap__8u1__p3_0[] = {
  144783. 3, 1, 0, 2, 4,
  144784. };
  144785. static encode_aux_threshmatch _vq_auxt__8u1__p3_0 = {
  144786. _vq_quantthresh__8u1__p3_0,
  144787. _vq_quantmap__8u1__p3_0,
  144788. 5,
  144789. 5
  144790. };
  144791. static static_codebook _8u1__p3_0 = {
  144792. 4, 625,
  144793. _vq_lengthlist__8u1__p3_0,
  144794. 1, -533725184, 1611661312, 3, 0,
  144795. _vq_quantlist__8u1__p3_0,
  144796. NULL,
  144797. &_vq_auxt__8u1__p3_0,
  144798. NULL,
  144799. 0
  144800. };
  144801. static long _vq_quantlist__8u1__p4_0[] = {
  144802. 2,
  144803. 1,
  144804. 3,
  144805. 0,
  144806. 4,
  144807. };
  144808. static long _vq_lengthlist__8u1__p4_0[] = {
  144809. 4, 5, 5, 9, 9, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 9,
  144810. 9, 9,11,11, 9, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 7,
  144811. 8, 9,10, 7, 7, 8, 9,10, 9, 9,10,10,11, 9, 9,10,
  144812. 10,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 7,10,
  144813. 9, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  144814. 9,10,10,12,11, 9,10,10,12,12,11,11,12,12,13,11,
  144815. 11,12,12,13, 9, 9,10,12,11, 9,10,10,12,12,10,10,
  144816. 10,12,12,11,12,11,13,12,11,12,11,13,12, 6, 7, 7,
  144817. 9, 9, 7, 8, 8,10,10, 7, 8, 7,10, 9,10,10,10,12,
  144818. 12,10,10,10,12,11, 7, 8, 7,10,10, 7, 7, 9,10,11,
  144819. 8, 9, 9,11,10,10,10,11,10,12,10,10,11,12,12, 7,
  144820. 8, 8,10,10, 7, 9, 8,11,10, 8, 8, 9,11,11,10,11,
  144821. 10,12,11,10,11,11,12,12, 9,10,10,12,12, 9,10,10,
  144822. 12,12,10,11,11,13,12,11,10,12,10,14,12,12,12,13,
  144823. 14, 9,10,10,12,12, 9,11,10,12,12,10,11,11,12,12,
  144824. 11,12,11,14,12,12,12,12,14,14, 5, 7, 7, 9, 9, 7,
  144825. 7, 7, 9,10, 7, 8, 8,10,10,10,10,10,11,11,10,10,
  144826. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  144827. 10,11,10,10,10,11,12,10,10,11,11,13, 6, 7, 8,10,
  144828. 10, 8, 9, 9,10,10, 7, 9, 7,11,10,10,11,10,12,12,
  144829. 10,11,10,12,10, 9,10,10,12,12,10,11,11,13,12, 9,
  144830. 10,10,12,12,12,12,12,14,13,11,11,12,11,14, 9,10,
  144831. 10,11,12,10,11,11,12,13, 9,10,10,12,12,12,12,12,
  144832. 14,13,11,12,10,14,11, 9, 9,10,11,12, 9,10,10,12,
  144833. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,13,12,
  144834. 9,10, 9,12,12, 9,10,11,12,13,10,11,10,13,11,12,
  144835. 12,13,13,14,12,12,12,13,13, 9,10,10,12,12,10,11,
  144836. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,12,
  144837. 13,14,11,12,11,14,13,10,10,11,13,13,12,12,12,14,
  144838. 13,12,10,14,10,15,13,14,14,14,14,11,11,12,13,14,
  144839. 10,12,11,13,13,12,12,12,13,15,12,13,11,15,12,13,
  144840. 13,14,14,14, 9,10, 9,12,12, 9,10,10,12,12,10,10,
  144841. 10,12,12,11,11,12,12,13,12,12,12,14,14, 9,10,10,
  144842. 12,12,10,11,10,13,12,10,10,11,12,13,12,12,12,14,
  144843. 13,12,12,13,13,14, 9,10,10,12,13,10,10,11,11,12,
  144844. 9,11,10,13,12,12,12,12,13,14,12,13,12,14,13,11,
  144845. 12,11,13,13,12,13,12,14,13,10,11,12,13,13,13,13,
  144846. 13,14,15,12,11,14,12,14,11,11,12,12,13,12,12,12,
  144847. 13,14,10,12,10,14,13,13,13,13,14,15,12,14,11,15,
  144848. 10,
  144849. };
  144850. static float _vq_quantthresh__8u1__p4_0[] = {
  144851. -1.5, -0.5, 0.5, 1.5,
  144852. };
  144853. static long _vq_quantmap__8u1__p4_0[] = {
  144854. 3, 1, 0, 2, 4,
  144855. };
  144856. static encode_aux_threshmatch _vq_auxt__8u1__p4_0 = {
  144857. _vq_quantthresh__8u1__p4_0,
  144858. _vq_quantmap__8u1__p4_0,
  144859. 5,
  144860. 5
  144861. };
  144862. static static_codebook _8u1__p4_0 = {
  144863. 4, 625,
  144864. _vq_lengthlist__8u1__p4_0,
  144865. 1, -533725184, 1611661312, 3, 0,
  144866. _vq_quantlist__8u1__p4_0,
  144867. NULL,
  144868. &_vq_auxt__8u1__p4_0,
  144869. NULL,
  144870. 0
  144871. };
  144872. static long _vq_quantlist__8u1__p5_0[] = {
  144873. 4,
  144874. 3,
  144875. 5,
  144876. 2,
  144877. 6,
  144878. 1,
  144879. 7,
  144880. 0,
  144881. 8,
  144882. };
  144883. static long _vq_lengthlist__8u1__p5_0[] = {
  144884. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  144885. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  144886. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  144887. 9, 9,10,10,12,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  144888. 10,10,11,11,11,11,13,12, 9,10,10,11,11,12,12,12,
  144889. 13,
  144890. };
  144891. static float _vq_quantthresh__8u1__p5_0[] = {
  144892. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144893. };
  144894. static long _vq_quantmap__8u1__p5_0[] = {
  144895. 7, 5, 3, 1, 0, 2, 4, 6,
  144896. 8,
  144897. };
  144898. static encode_aux_threshmatch _vq_auxt__8u1__p5_0 = {
  144899. _vq_quantthresh__8u1__p5_0,
  144900. _vq_quantmap__8u1__p5_0,
  144901. 9,
  144902. 9
  144903. };
  144904. static static_codebook _8u1__p5_0 = {
  144905. 2, 81,
  144906. _vq_lengthlist__8u1__p5_0,
  144907. 1, -531628032, 1611661312, 4, 0,
  144908. _vq_quantlist__8u1__p5_0,
  144909. NULL,
  144910. &_vq_auxt__8u1__p5_0,
  144911. NULL,
  144912. 0
  144913. };
  144914. static long _vq_quantlist__8u1__p6_0[] = {
  144915. 4,
  144916. 3,
  144917. 5,
  144918. 2,
  144919. 6,
  144920. 1,
  144921. 7,
  144922. 0,
  144923. 8,
  144924. };
  144925. static long _vq_lengthlist__8u1__p6_0[] = {
  144926. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 5, 6, 6, 7, 7,
  144927. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  144928. 8, 8, 9, 9, 6, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  144929. 8, 8, 8, 9,10,10, 7, 7, 7, 8, 8, 9, 8,10,10, 9,
  144930. 9, 9, 9, 9,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  144931. 10,
  144932. };
  144933. static float _vq_quantthresh__8u1__p6_0[] = {
  144934. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144935. };
  144936. static long _vq_quantmap__8u1__p6_0[] = {
  144937. 7, 5, 3, 1, 0, 2, 4, 6,
  144938. 8,
  144939. };
  144940. static encode_aux_threshmatch _vq_auxt__8u1__p6_0 = {
  144941. _vq_quantthresh__8u1__p6_0,
  144942. _vq_quantmap__8u1__p6_0,
  144943. 9,
  144944. 9
  144945. };
  144946. static static_codebook _8u1__p6_0 = {
  144947. 2, 81,
  144948. _vq_lengthlist__8u1__p6_0,
  144949. 1, -531628032, 1611661312, 4, 0,
  144950. _vq_quantlist__8u1__p6_0,
  144951. NULL,
  144952. &_vq_auxt__8u1__p6_0,
  144953. NULL,
  144954. 0
  144955. };
  144956. static long _vq_quantlist__8u1__p7_0[] = {
  144957. 1,
  144958. 0,
  144959. 2,
  144960. };
  144961. static long _vq_lengthlist__8u1__p7_0[] = {
  144962. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,10,10, 8,
  144963. 10,10, 5, 9, 9, 7,10,10, 8,10,10, 4,10,10, 9,12,
  144964. 12, 9,11,11, 7,12,11,10,11,13,10,13,13, 7,12,12,
  144965. 10,13,12,10,13,13, 4,10,10, 9,12,12, 9,12,12, 7,
  144966. 12,12,10,13,13,10,12,13, 7,11,12,10,13,13,10,13,
  144967. 11,
  144968. };
  144969. static float _vq_quantthresh__8u1__p7_0[] = {
  144970. -5.5, 5.5,
  144971. };
  144972. static long _vq_quantmap__8u1__p7_0[] = {
  144973. 1, 0, 2,
  144974. };
  144975. static encode_aux_threshmatch _vq_auxt__8u1__p7_0 = {
  144976. _vq_quantthresh__8u1__p7_0,
  144977. _vq_quantmap__8u1__p7_0,
  144978. 3,
  144979. 3
  144980. };
  144981. static static_codebook _8u1__p7_0 = {
  144982. 4, 81,
  144983. _vq_lengthlist__8u1__p7_0,
  144984. 1, -529137664, 1618345984, 2, 0,
  144985. _vq_quantlist__8u1__p7_0,
  144986. NULL,
  144987. &_vq_auxt__8u1__p7_0,
  144988. NULL,
  144989. 0
  144990. };
  144991. static long _vq_quantlist__8u1__p7_1[] = {
  144992. 5,
  144993. 4,
  144994. 6,
  144995. 3,
  144996. 7,
  144997. 2,
  144998. 8,
  144999. 1,
  145000. 9,
  145001. 0,
  145002. 10,
  145003. };
  145004. static long _vq_lengthlist__8u1__p7_1[] = {
  145005. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  145006. 8, 8, 9, 9, 9, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 9,
  145007. 9, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  145008. 8, 8, 8, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  145009. 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  145010. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  145011. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  145012. 9, 9, 9, 9, 9,10,10,10,10,
  145013. };
  145014. static float _vq_quantthresh__8u1__p7_1[] = {
  145015. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145016. 3.5, 4.5,
  145017. };
  145018. static long _vq_quantmap__8u1__p7_1[] = {
  145019. 9, 7, 5, 3, 1, 0, 2, 4,
  145020. 6, 8, 10,
  145021. };
  145022. static encode_aux_threshmatch _vq_auxt__8u1__p7_1 = {
  145023. _vq_quantthresh__8u1__p7_1,
  145024. _vq_quantmap__8u1__p7_1,
  145025. 11,
  145026. 11
  145027. };
  145028. static static_codebook _8u1__p7_1 = {
  145029. 2, 121,
  145030. _vq_lengthlist__8u1__p7_1,
  145031. 1, -531365888, 1611661312, 4, 0,
  145032. _vq_quantlist__8u1__p7_1,
  145033. NULL,
  145034. &_vq_auxt__8u1__p7_1,
  145035. NULL,
  145036. 0
  145037. };
  145038. static long _vq_quantlist__8u1__p8_0[] = {
  145039. 5,
  145040. 4,
  145041. 6,
  145042. 3,
  145043. 7,
  145044. 2,
  145045. 8,
  145046. 1,
  145047. 9,
  145048. 0,
  145049. 10,
  145050. };
  145051. static long _vq_lengthlist__8u1__p8_0[] = {
  145052. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  145053. 9, 9,11,11,13,12, 4, 6, 6, 7, 7, 9, 9,11,11,12,
  145054. 12, 6, 7, 7, 9, 9,11,11,12,12,13,13, 6, 7, 7, 9,
  145055. 9,11,11,12,12,13,13, 8, 9, 9,11,11,12,12,13,13,
  145056. 14,14, 8, 9, 9,11,11,12,12,13,13,14,14, 9,11,11,
  145057. 12,12,13,13,14,14,15,15, 9,11,11,12,12,13,13,14,
  145058. 14,15,14,11,12,12,13,13,14,14,15,15,16,16,11,12,
  145059. 12,13,13,14,14,15,15,15,15,
  145060. };
  145061. static float _vq_quantthresh__8u1__p8_0[] = {
  145062. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  145063. 38.5, 49.5,
  145064. };
  145065. static long _vq_quantmap__8u1__p8_0[] = {
  145066. 9, 7, 5, 3, 1, 0, 2, 4,
  145067. 6, 8, 10,
  145068. };
  145069. static encode_aux_threshmatch _vq_auxt__8u1__p8_0 = {
  145070. _vq_quantthresh__8u1__p8_0,
  145071. _vq_quantmap__8u1__p8_0,
  145072. 11,
  145073. 11
  145074. };
  145075. static static_codebook _8u1__p8_0 = {
  145076. 2, 121,
  145077. _vq_lengthlist__8u1__p8_0,
  145078. 1, -524582912, 1618345984, 4, 0,
  145079. _vq_quantlist__8u1__p8_0,
  145080. NULL,
  145081. &_vq_auxt__8u1__p8_0,
  145082. NULL,
  145083. 0
  145084. };
  145085. static long _vq_quantlist__8u1__p8_1[] = {
  145086. 5,
  145087. 4,
  145088. 6,
  145089. 3,
  145090. 7,
  145091. 2,
  145092. 8,
  145093. 1,
  145094. 9,
  145095. 0,
  145096. 10,
  145097. };
  145098. static long _vq_lengthlist__8u1__p8_1[] = {
  145099. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 6, 6, 7, 7,
  145100. 7, 7, 8, 8, 8, 8, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  145101. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  145102. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  145103. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145104. 8, 8, 8, 8, 9, 8, 9, 9, 7, 8, 8, 8, 8, 8, 8, 9,
  145105. 8, 9, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8,
  145106. 8, 8, 8, 8, 8, 9, 9, 9, 9,
  145107. };
  145108. static float _vq_quantthresh__8u1__p8_1[] = {
  145109. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145110. 3.5, 4.5,
  145111. };
  145112. static long _vq_quantmap__8u1__p8_1[] = {
  145113. 9, 7, 5, 3, 1, 0, 2, 4,
  145114. 6, 8, 10,
  145115. };
  145116. static encode_aux_threshmatch _vq_auxt__8u1__p8_1 = {
  145117. _vq_quantthresh__8u1__p8_1,
  145118. _vq_quantmap__8u1__p8_1,
  145119. 11,
  145120. 11
  145121. };
  145122. static static_codebook _8u1__p8_1 = {
  145123. 2, 121,
  145124. _vq_lengthlist__8u1__p8_1,
  145125. 1, -531365888, 1611661312, 4, 0,
  145126. _vq_quantlist__8u1__p8_1,
  145127. NULL,
  145128. &_vq_auxt__8u1__p8_1,
  145129. NULL,
  145130. 0
  145131. };
  145132. static long _vq_quantlist__8u1__p9_0[] = {
  145133. 7,
  145134. 6,
  145135. 8,
  145136. 5,
  145137. 9,
  145138. 4,
  145139. 10,
  145140. 3,
  145141. 11,
  145142. 2,
  145143. 12,
  145144. 1,
  145145. 13,
  145146. 0,
  145147. 14,
  145148. };
  145149. static long _vq_lengthlist__8u1__p9_0[] = {
  145150. 1, 4, 4,11,11,11,11,11,11,11,11,11,11,11,11, 3,
  145151. 11, 8,11,11,11,11,11,11,11,11,11,11,11,11, 3, 9,
  145152. 9,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,11,11,11,11,11,11,
  145160. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145161. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145162. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  145163. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145164. 10,
  145165. };
  145166. static float _vq_quantthresh__8u1__p9_0[] = {
  145167. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  145168. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  145169. };
  145170. static long _vq_quantmap__8u1__p9_0[] = {
  145171. 13, 11, 9, 7, 5, 3, 1, 0,
  145172. 2, 4, 6, 8, 10, 12, 14,
  145173. };
  145174. static encode_aux_threshmatch _vq_auxt__8u1__p9_0 = {
  145175. _vq_quantthresh__8u1__p9_0,
  145176. _vq_quantmap__8u1__p9_0,
  145177. 15,
  145178. 15
  145179. };
  145180. static static_codebook _8u1__p9_0 = {
  145181. 2, 225,
  145182. _vq_lengthlist__8u1__p9_0,
  145183. 1, -514071552, 1627381760, 4, 0,
  145184. _vq_quantlist__8u1__p9_0,
  145185. NULL,
  145186. &_vq_auxt__8u1__p9_0,
  145187. NULL,
  145188. 0
  145189. };
  145190. static long _vq_quantlist__8u1__p9_1[] = {
  145191. 7,
  145192. 6,
  145193. 8,
  145194. 5,
  145195. 9,
  145196. 4,
  145197. 10,
  145198. 3,
  145199. 11,
  145200. 2,
  145201. 12,
  145202. 1,
  145203. 13,
  145204. 0,
  145205. 14,
  145206. };
  145207. static long _vq_lengthlist__8u1__p9_1[] = {
  145208. 1, 4, 4, 7, 7, 9, 9, 7, 7, 8, 8,10,10,11,11, 4,
  145209. 7, 7, 9, 9,10,10, 8, 8,10,10,10,11,10,11, 4, 7,
  145210. 7, 9, 9,10,10, 8, 8,10, 9,11,11,11,11, 7, 9, 9,
  145211. 12,12,11,12,10,10,11,10,12,11,11,11, 7, 9, 9,11,
  145212. 11,13,12, 9, 9,11,10,11,11,12,11, 9,10,10,12,12,
  145213. 14,14,10,10,11,12,12,11,11,11, 9,10,11,11,13,14,
  145214. 13,10,11,11,11,12,11,12,12, 7, 8, 8,10, 9,11,10,
  145215. 11,12,12,11,12,14,12,13, 7, 8, 8, 9,10,10,11,12,
  145216. 12,12,11,12,12,12,13, 9, 9, 9,11,11,13,12,12,12,
  145217. 12,11,12,12,13,12, 8,10,10,11,10,11,12,12,12,12,
  145218. 12,12,14,12,12, 9,11,11,11,12,12,12,12,13,13,12,
  145219. 12,13,13,12,10,11,11,12,11,12,12,12,11,12,13,12,
  145220. 12,12,13,11,11,12,12,12,13,12,12,11,12,13,13,12,
  145221. 12,13,12,11,12,12,13,13,12,13,12,13,13,13,13,14,
  145222. 13,
  145223. };
  145224. static float _vq_quantthresh__8u1__p9_1[] = {
  145225. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  145226. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  145227. };
  145228. static long _vq_quantmap__8u1__p9_1[] = {
  145229. 13, 11, 9, 7, 5, 3, 1, 0,
  145230. 2, 4, 6, 8, 10, 12, 14,
  145231. };
  145232. static encode_aux_threshmatch _vq_auxt__8u1__p9_1 = {
  145233. _vq_quantthresh__8u1__p9_1,
  145234. _vq_quantmap__8u1__p9_1,
  145235. 15,
  145236. 15
  145237. };
  145238. static static_codebook _8u1__p9_1 = {
  145239. 2, 225,
  145240. _vq_lengthlist__8u1__p9_1,
  145241. 1, -522338304, 1620115456, 4, 0,
  145242. _vq_quantlist__8u1__p9_1,
  145243. NULL,
  145244. &_vq_auxt__8u1__p9_1,
  145245. NULL,
  145246. 0
  145247. };
  145248. static long _vq_quantlist__8u1__p9_2[] = {
  145249. 8,
  145250. 7,
  145251. 9,
  145252. 6,
  145253. 10,
  145254. 5,
  145255. 11,
  145256. 4,
  145257. 12,
  145258. 3,
  145259. 13,
  145260. 2,
  145261. 14,
  145262. 1,
  145263. 15,
  145264. 0,
  145265. 16,
  145266. };
  145267. static long _vq_lengthlist__8u1__p9_2[] = {
  145268. 2, 5, 4, 6, 6, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145269. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  145270. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145271. 9, 9, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  145272. 9,10,10, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  145273. 9, 9, 9,10,10, 8, 8, 8, 9, 9, 9, 9,10,10,10, 9,
  145274. 10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  145275. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,
  145276. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  145277. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  145278. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  145279. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  145280. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  145281. 9,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  145282. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10,
  145283. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  145284. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145285. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145286. 10,
  145287. };
  145288. static float _vq_quantthresh__8u1__p9_2[] = {
  145289. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  145290. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  145291. };
  145292. static long _vq_quantmap__8u1__p9_2[] = {
  145293. 15, 13, 11, 9, 7, 5, 3, 1,
  145294. 0, 2, 4, 6, 8, 10, 12, 14,
  145295. 16,
  145296. };
  145297. static encode_aux_threshmatch _vq_auxt__8u1__p9_2 = {
  145298. _vq_quantthresh__8u1__p9_2,
  145299. _vq_quantmap__8u1__p9_2,
  145300. 17,
  145301. 17
  145302. };
  145303. static static_codebook _8u1__p9_2 = {
  145304. 2, 289,
  145305. _vq_lengthlist__8u1__p9_2,
  145306. 1, -529530880, 1611661312, 5, 0,
  145307. _vq_quantlist__8u1__p9_2,
  145308. NULL,
  145309. &_vq_auxt__8u1__p9_2,
  145310. NULL,
  145311. 0
  145312. };
  145313. static long _huff_lengthlist__8u1__single[] = {
  145314. 4, 7,13, 9,15, 9,16, 8,10,13, 7, 5, 8, 6, 9, 7,
  145315. 10, 7,10,11,11, 6, 7, 8, 8, 9, 9, 9,12,16, 8, 5,
  145316. 8, 6, 8, 6, 9, 7,10,12,11, 7, 7, 7, 6, 7, 7, 7,
  145317. 11,15, 7, 5, 8, 6, 7, 5, 7, 6, 9,13,13, 9, 9, 8,
  145318. 6, 6, 5, 5, 9,14, 8, 6, 8, 6, 6, 4, 5, 3, 5,13,
  145319. 9, 9,11, 8,10, 7, 8, 4, 5,12,11,16,17,15,17,12,
  145320. 13, 8, 8,15,
  145321. };
  145322. static static_codebook _huff_book__8u1__single = {
  145323. 2, 100,
  145324. _huff_lengthlist__8u1__single,
  145325. 0, 0, 0, 0, 0,
  145326. NULL,
  145327. NULL,
  145328. NULL,
  145329. NULL,
  145330. 0
  145331. };
  145332. static long _huff_lengthlist__44u0__long[] = {
  145333. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  145334. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  145335. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  145336. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  145337. };
  145338. static static_codebook _huff_book__44u0__long = {
  145339. 2, 64,
  145340. _huff_lengthlist__44u0__long,
  145341. 0, 0, 0, 0, 0,
  145342. NULL,
  145343. NULL,
  145344. NULL,
  145345. NULL,
  145346. 0
  145347. };
  145348. static long _vq_quantlist__44u0__p1_0[] = {
  145349. 1,
  145350. 0,
  145351. 2,
  145352. };
  145353. static long _vq_lengthlist__44u0__p1_0[] = {
  145354. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  145355. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  145356. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  145357. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  145358. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  145359. 13,
  145360. };
  145361. static float _vq_quantthresh__44u0__p1_0[] = {
  145362. -0.5, 0.5,
  145363. };
  145364. static long _vq_quantmap__44u0__p1_0[] = {
  145365. 1, 0, 2,
  145366. };
  145367. static encode_aux_threshmatch _vq_auxt__44u0__p1_0 = {
  145368. _vq_quantthresh__44u0__p1_0,
  145369. _vq_quantmap__44u0__p1_0,
  145370. 3,
  145371. 3
  145372. };
  145373. static static_codebook _44u0__p1_0 = {
  145374. 4, 81,
  145375. _vq_lengthlist__44u0__p1_0,
  145376. 1, -535822336, 1611661312, 2, 0,
  145377. _vq_quantlist__44u0__p1_0,
  145378. NULL,
  145379. &_vq_auxt__44u0__p1_0,
  145380. NULL,
  145381. 0
  145382. };
  145383. static long _vq_quantlist__44u0__p2_0[] = {
  145384. 1,
  145385. 0,
  145386. 2,
  145387. };
  145388. static long _vq_lengthlist__44u0__p2_0[] = {
  145389. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  145390. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  145391. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  145392. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  145393. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  145394. 9,
  145395. };
  145396. static float _vq_quantthresh__44u0__p2_0[] = {
  145397. -0.5, 0.5,
  145398. };
  145399. static long _vq_quantmap__44u0__p2_0[] = {
  145400. 1, 0, 2,
  145401. };
  145402. static encode_aux_threshmatch _vq_auxt__44u0__p2_0 = {
  145403. _vq_quantthresh__44u0__p2_0,
  145404. _vq_quantmap__44u0__p2_0,
  145405. 3,
  145406. 3
  145407. };
  145408. static static_codebook _44u0__p2_0 = {
  145409. 4, 81,
  145410. _vq_lengthlist__44u0__p2_0,
  145411. 1, -535822336, 1611661312, 2, 0,
  145412. _vq_quantlist__44u0__p2_0,
  145413. NULL,
  145414. &_vq_auxt__44u0__p2_0,
  145415. NULL,
  145416. 0
  145417. };
  145418. static long _vq_quantlist__44u0__p3_0[] = {
  145419. 2,
  145420. 1,
  145421. 3,
  145422. 0,
  145423. 4,
  145424. };
  145425. static long _vq_lengthlist__44u0__p3_0[] = {
  145426. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  145427. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  145428. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  145429. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  145430. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  145431. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  145432. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  145433. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  145434. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  145435. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  145436. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  145437. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  145438. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  145439. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  145440. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  145441. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  145442. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  145443. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  145444. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  145445. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  145446. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  145447. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  145448. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  145449. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  145450. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  145451. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  145452. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  145453. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  145454. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  145455. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  145456. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  145457. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  145458. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  145459. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  145460. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  145461. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  145462. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  145463. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  145464. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  145465. 19,
  145466. };
  145467. static float _vq_quantthresh__44u0__p3_0[] = {
  145468. -1.5, -0.5, 0.5, 1.5,
  145469. };
  145470. static long _vq_quantmap__44u0__p3_0[] = {
  145471. 3, 1, 0, 2, 4,
  145472. };
  145473. static encode_aux_threshmatch _vq_auxt__44u0__p3_0 = {
  145474. _vq_quantthresh__44u0__p3_0,
  145475. _vq_quantmap__44u0__p3_0,
  145476. 5,
  145477. 5
  145478. };
  145479. static static_codebook _44u0__p3_0 = {
  145480. 4, 625,
  145481. _vq_lengthlist__44u0__p3_0,
  145482. 1, -533725184, 1611661312, 3, 0,
  145483. _vq_quantlist__44u0__p3_0,
  145484. NULL,
  145485. &_vq_auxt__44u0__p3_0,
  145486. NULL,
  145487. 0
  145488. };
  145489. static long _vq_quantlist__44u0__p4_0[] = {
  145490. 2,
  145491. 1,
  145492. 3,
  145493. 0,
  145494. 4,
  145495. };
  145496. static long _vq_lengthlist__44u0__p4_0[] = {
  145497. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  145498. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  145499. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  145500. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  145501. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  145502. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  145503. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  145504. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  145505. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  145506. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  145507. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  145508. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  145509. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  145510. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  145511. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  145512. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  145513. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  145514. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  145515. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  145516. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  145517. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  145518. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  145519. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  145520. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  145521. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  145522. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  145523. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  145524. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  145525. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  145526. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  145527. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  145528. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  145529. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  145530. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  145531. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  145532. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  145533. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  145534. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  145535. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  145536. 12,
  145537. };
  145538. static float _vq_quantthresh__44u0__p4_0[] = {
  145539. -1.5, -0.5, 0.5, 1.5,
  145540. };
  145541. static long _vq_quantmap__44u0__p4_0[] = {
  145542. 3, 1, 0, 2, 4,
  145543. };
  145544. static encode_aux_threshmatch _vq_auxt__44u0__p4_0 = {
  145545. _vq_quantthresh__44u0__p4_0,
  145546. _vq_quantmap__44u0__p4_0,
  145547. 5,
  145548. 5
  145549. };
  145550. static static_codebook _44u0__p4_0 = {
  145551. 4, 625,
  145552. _vq_lengthlist__44u0__p4_0,
  145553. 1, -533725184, 1611661312, 3, 0,
  145554. _vq_quantlist__44u0__p4_0,
  145555. NULL,
  145556. &_vq_auxt__44u0__p4_0,
  145557. NULL,
  145558. 0
  145559. };
  145560. static long _vq_quantlist__44u0__p5_0[] = {
  145561. 4,
  145562. 3,
  145563. 5,
  145564. 2,
  145565. 6,
  145566. 1,
  145567. 7,
  145568. 0,
  145569. 8,
  145570. };
  145571. static long _vq_lengthlist__44u0__p5_0[] = {
  145572. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  145573. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  145574. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  145575. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  145576. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  145577. 12,
  145578. };
  145579. static float _vq_quantthresh__44u0__p5_0[] = {
  145580. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145581. };
  145582. static long _vq_quantmap__44u0__p5_0[] = {
  145583. 7, 5, 3, 1, 0, 2, 4, 6,
  145584. 8,
  145585. };
  145586. static encode_aux_threshmatch _vq_auxt__44u0__p5_0 = {
  145587. _vq_quantthresh__44u0__p5_0,
  145588. _vq_quantmap__44u0__p5_0,
  145589. 9,
  145590. 9
  145591. };
  145592. static static_codebook _44u0__p5_0 = {
  145593. 2, 81,
  145594. _vq_lengthlist__44u0__p5_0,
  145595. 1, -531628032, 1611661312, 4, 0,
  145596. _vq_quantlist__44u0__p5_0,
  145597. NULL,
  145598. &_vq_auxt__44u0__p5_0,
  145599. NULL,
  145600. 0
  145601. };
  145602. static long _vq_quantlist__44u0__p6_0[] = {
  145603. 6,
  145604. 5,
  145605. 7,
  145606. 4,
  145607. 8,
  145608. 3,
  145609. 9,
  145610. 2,
  145611. 10,
  145612. 1,
  145613. 11,
  145614. 0,
  145615. 12,
  145616. };
  145617. static long _vq_lengthlist__44u0__p6_0[] = {
  145618. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  145619. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  145620. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  145621. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  145622. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  145623. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  145624. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  145625. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  145626. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  145627. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  145628. 15,17,16,17,18,17,17,18, 0,
  145629. };
  145630. static float _vq_quantthresh__44u0__p6_0[] = {
  145631. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  145632. 12.5, 17.5, 22.5, 27.5,
  145633. };
  145634. static long _vq_quantmap__44u0__p6_0[] = {
  145635. 11, 9, 7, 5, 3, 1, 0, 2,
  145636. 4, 6, 8, 10, 12,
  145637. };
  145638. static encode_aux_threshmatch _vq_auxt__44u0__p6_0 = {
  145639. _vq_quantthresh__44u0__p6_0,
  145640. _vq_quantmap__44u0__p6_0,
  145641. 13,
  145642. 13
  145643. };
  145644. static static_codebook _44u0__p6_0 = {
  145645. 2, 169,
  145646. _vq_lengthlist__44u0__p6_0,
  145647. 1, -526516224, 1616117760, 4, 0,
  145648. _vq_quantlist__44u0__p6_0,
  145649. NULL,
  145650. &_vq_auxt__44u0__p6_0,
  145651. NULL,
  145652. 0
  145653. };
  145654. static long _vq_quantlist__44u0__p6_1[] = {
  145655. 2,
  145656. 1,
  145657. 3,
  145658. 0,
  145659. 4,
  145660. };
  145661. static long _vq_lengthlist__44u0__p6_1[] = {
  145662. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  145663. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  145664. };
  145665. static float _vq_quantthresh__44u0__p6_1[] = {
  145666. -1.5, -0.5, 0.5, 1.5,
  145667. };
  145668. static long _vq_quantmap__44u0__p6_1[] = {
  145669. 3, 1, 0, 2, 4,
  145670. };
  145671. static encode_aux_threshmatch _vq_auxt__44u0__p6_1 = {
  145672. _vq_quantthresh__44u0__p6_1,
  145673. _vq_quantmap__44u0__p6_1,
  145674. 5,
  145675. 5
  145676. };
  145677. static static_codebook _44u0__p6_1 = {
  145678. 2, 25,
  145679. _vq_lengthlist__44u0__p6_1,
  145680. 1, -533725184, 1611661312, 3, 0,
  145681. _vq_quantlist__44u0__p6_1,
  145682. NULL,
  145683. &_vq_auxt__44u0__p6_1,
  145684. NULL,
  145685. 0
  145686. };
  145687. static long _vq_quantlist__44u0__p7_0[] = {
  145688. 2,
  145689. 1,
  145690. 3,
  145691. 0,
  145692. 4,
  145693. };
  145694. static long _vq_lengthlist__44u0__p7_0[] = {
  145695. 1, 4, 4,11,11, 9,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, 9,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,11,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,10,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,11,11,11,11,11,11,11,11,11,11,
  145723. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145724. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145725. 11,11,11,11,11,11,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,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145732. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145733. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145734. 10,
  145735. };
  145736. static float _vq_quantthresh__44u0__p7_0[] = {
  145737. -253.5, -84.5, 84.5, 253.5,
  145738. };
  145739. static long _vq_quantmap__44u0__p7_0[] = {
  145740. 3, 1, 0, 2, 4,
  145741. };
  145742. static encode_aux_threshmatch _vq_auxt__44u0__p7_0 = {
  145743. _vq_quantthresh__44u0__p7_0,
  145744. _vq_quantmap__44u0__p7_0,
  145745. 5,
  145746. 5
  145747. };
  145748. static static_codebook _44u0__p7_0 = {
  145749. 4, 625,
  145750. _vq_lengthlist__44u0__p7_0,
  145751. 1, -518709248, 1626677248, 3, 0,
  145752. _vq_quantlist__44u0__p7_0,
  145753. NULL,
  145754. &_vq_auxt__44u0__p7_0,
  145755. NULL,
  145756. 0
  145757. };
  145758. static long _vq_quantlist__44u0__p7_1[] = {
  145759. 6,
  145760. 5,
  145761. 7,
  145762. 4,
  145763. 8,
  145764. 3,
  145765. 9,
  145766. 2,
  145767. 10,
  145768. 1,
  145769. 11,
  145770. 0,
  145771. 12,
  145772. };
  145773. static long _vq_lengthlist__44u0__p7_1[] = {
  145774. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  145775. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  145776. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  145777. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  145778. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  145779. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  145780. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  145781. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  145782. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  145783. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  145784. 15,15,15,15,15,15,15,15,15,
  145785. };
  145786. static float _vq_quantthresh__44u0__p7_1[] = {
  145787. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  145788. 32.5, 45.5, 58.5, 71.5,
  145789. };
  145790. static long _vq_quantmap__44u0__p7_1[] = {
  145791. 11, 9, 7, 5, 3, 1, 0, 2,
  145792. 4, 6, 8, 10, 12,
  145793. };
  145794. static encode_aux_threshmatch _vq_auxt__44u0__p7_1 = {
  145795. _vq_quantthresh__44u0__p7_1,
  145796. _vq_quantmap__44u0__p7_1,
  145797. 13,
  145798. 13
  145799. };
  145800. static static_codebook _44u0__p7_1 = {
  145801. 2, 169,
  145802. _vq_lengthlist__44u0__p7_1,
  145803. 1, -523010048, 1618608128, 4, 0,
  145804. _vq_quantlist__44u0__p7_1,
  145805. NULL,
  145806. &_vq_auxt__44u0__p7_1,
  145807. NULL,
  145808. 0
  145809. };
  145810. static long _vq_quantlist__44u0__p7_2[] = {
  145811. 6,
  145812. 5,
  145813. 7,
  145814. 4,
  145815. 8,
  145816. 3,
  145817. 9,
  145818. 2,
  145819. 10,
  145820. 1,
  145821. 11,
  145822. 0,
  145823. 12,
  145824. };
  145825. static long _vq_lengthlist__44u0__p7_2[] = {
  145826. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  145827. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  145828. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  145829. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  145830. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  145831. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  145832. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  145833. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  145834. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  145835. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  145836. 9, 9, 9,10, 9, 9,10,10, 9,
  145837. };
  145838. static float _vq_quantthresh__44u0__p7_2[] = {
  145839. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  145840. 2.5, 3.5, 4.5, 5.5,
  145841. };
  145842. static long _vq_quantmap__44u0__p7_2[] = {
  145843. 11, 9, 7, 5, 3, 1, 0, 2,
  145844. 4, 6, 8, 10, 12,
  145845. };
  145846. static encode_aux_threshmatch _vq_auxt__44u0__p7_2 = {
  145847. _vq_quantthresh__44u0__p7_2,
  145848. _vq_quantmap__44u0__p7_2,
  145849. 13,
  145850. 13
  145851. };
  145852. static static_codebook _44u0__p7_2 = {
  145853. 2, 169,
  145854. _vq_lengthlist__44u0__p7_2,
  145855. 1, -531103744, 1611661312, 4, 0,
  145856. _vq_quantlist__44u0__p7_2,
  145857. NULL,
  145858. &_vq_auxt__44u0__p7_2,
  145859. NULL,
  145860. 0
  145861. };
  145862. static long _huff_lengthlist__44u0__short[] = {
  145863. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  145864. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  145865. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  145866. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  145867. };
  145868. static static_codebook _huff_book__44u0__short = {
  145869. 2, 64,
  145870. _huff_lengthlist__44u0__short,
  145871. 0, 0, 0, 0, 0,
  145872. NULL,
  145873. NULL,
  145874. NULL,
  145875. NULL,
  145876. 0
  145877. };
  145878. static long _huff_lengthlist__44u1__long[] = {
  145879. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  145880. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  145881. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  145882. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  145883. };
  145884. static static_codebook _huff_book__44u1__long = {
  145885. 2, 64,
  145886. _huff_lengthlist__44u1__long,
  145887. 0, 0, 0, 0, 0,
  145888. NULL,
  145889. NULL,
  145890. NULL,
  145891. NULL,
  145892. 0
  145893. };
  145894. static long _vq_quantlist__44u1__p1_0[] = {
  145895. 1,
  145896. 0,
  145897. 2,
  145898. };
  145899. static long _vq_lengthlist__44u1__p1_0[] = {
  145900. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  145901. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  145902. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  145903. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  145904. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  145905. 13,
  145906. };
  145907. static float _vq_quantthresh__44u1__p1_0[] = {
  145908. -0.5, 0.5,
  145909. };
  145910. static long _vq_quantmap__44u1__p1_0[] = {
  145911. 1, 0, 2,
  145912. };
  145913. static encode_aux_threshmatch _vq_auxt__44u1__p1_0 = {
  145914. _vq_quantthresh__44u1__p1_0,
  145915. _vq_quantmap__44u1__p1_0,
  145916. 3,
  145917. 3
  145918. };
  145919. static static_codebook _44u1__p1_0 = {
  145920. 4, 81,
  145921. _vq_lengthlist__44u1__p1_0,
  145922. 1, -535822336, 1611661312, 2, 0,
  145923. _vq_quantlist__44u1__p1_0,
  145924. NULL,
  145925. &_vq_auxt__44u1__p1_0,
  145926. NULL,
  145927. 0
  145928. };
  145929. static long _vq_quantlist__44u1__p2_0[] = {
  145930. 1,
  145931. 0,
  145932. 2,
  145933. };
  145934. static long _vq_lengthlist__44u1__p2_0[] = {
  145935. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  145936. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  145937. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  145938. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  145939. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  145940. 9,
  145941. };
  145942. static float _vq_quantthresh__44u1__p2_0[] = {
  145943. -0.5, 0.5,
  145944. };
  145945. static long _vq_quantmap__44u1__p2_0[] = {
  145946. 1, 0, 2,
  145947. };
  145948. static encode_aux_threshmatch _vq_auxt__44u1__p2_0 = {
  145949. _vq_quantthresh__44u1__p2_0,
  145950. _vq_quantmap__44u1__p2_0,
  145951. 3,
  145952. 3
  145953. };
  145954. static static_codebook _44u1__p2_0 = {
  145955. 4, 81,
  145956. _vq_lengthlist__44u1__p2_0,
  145957. 1, -535822336, 1611661312, 2, 0,
  145958. _vq_quantlist__44u1__p2_0,
  145959. NULL,
  145960. &_vq_auxt__44u1__p2_0,
  145961. NULL,
  145962. 0
  145963. };
  145964. static long _vq_quantlist__44u1__p3_0[] = {
  145965. 2,
  145966. 1,
  145967. 3,
  145968. 0,
  145969. 4,
  145970. };
  145971. static long _vq_lengthlist__44u1__p3_0[] = {
  145972. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  145973. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  145974. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  145975. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  145976. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  145977. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  145978. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  145979. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  145980. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  145981. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  145982. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  145983. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  145984. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  145985. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  145986. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  145987. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  145988. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  145989. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  145990. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  145991. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  145992. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  145993. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  145994. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  145995. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  145996. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  145997. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  145998. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  145999. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  146000. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  146001. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  146002. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  146003. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  146004. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  146005. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  146006. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  146007. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  146008. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  146009. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  146010. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  146011. 19,
  146012. };
  146013. static float _vq_quantthresh__44u1__p3_0[] = {
  146014. -1.5, -0.5, 0.5, 1.5,
  146015. };
  146016. static long _vq_quantmap__44u1__p3_0[] = {
  146017. 3, 1, 0, 2, 4,
  146018. };
  146019. static encode_aux_threshmatch _vq_auxt__44u1__p3_0 = {
  146020. _vq_quantthresh__44u1__p3_0,
  146021. _vq_quantmap__44u1__p3_0,
  146022. 5,
  146023. 5
  146024. };
  146025. static static_codebook _44u1__p3_0 = {
  146026. 4, 625,
  146027. _vq_lengthlist__44u1__p3_0,
  146028. 1, -533725184, 1611661312, 3, 0,
  146029. _vq_quantlist__44u1__p3_0,
  146030. NULL,
  146031. &_vq_auxt__44u1__p3_0,
  146032. NULL,
  146033. 0
  146034. };
  146035. static long _vq_quantlist__44u1__p4_0[] = {
  146036. 2,
  146037. 1,
  146038. 3,
  146039. 0,
  146040. 4,
  146041. };
  146042. static long _vq_lengthlist__44u1__p4_0[] = {
  146043. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  146044. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  146045. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  146046. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  146047. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  146048. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  146049. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  146050. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  146051. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  146052. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  146053. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  146054. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146055. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  146056. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  146057. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  146058. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  146059. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  146060. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  146061. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  146062. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  146063. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  146064. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  146065. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  146066. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  146067. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  146068. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  146069. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  146070. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  146071. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  146072. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  146073. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  146074. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  146075. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  146076. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  146077. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  146078. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  146079. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  146080. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  146081. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  146082. 12,
  146083. };
  146084. static float _vq_quantthresh__44u1__p4_0[] = {
  146085. -1.5, -0.5, 0.5, 1.5,
  146086. };
  146087. static long _vq_quantmap__44u1__p4_0[] = {
  146088. 3, 1, 0, 2, 4,
  146089. };
  146090. static encode_aux_threshmatch _vq_auxt__44u1__p4_0 = {
  146091. _vq_quantthresh__44u1__p4_0,
  146092. _vq_quantmap__44u1__p4_0,
  146093. 5,
  146094. 5
  146095. };
  146096. static static_codebook _44u1__p4_0 = {
  146097. 4, 625,
  146098. _vq_lengthlist__44u1__p4_0,
  146099. 1, -533725184, 1611661312, 3, 0,
  146100. _vq_quantlist__44u1__p4_0,
  146101. NULL,
  146102. &_vq_auxt__44u1__p4_0,
  146103. NULL,
  146104. 0
  146105. };
  146106. static long _vq_quantlist__44u1__p5_0[] = {
  146107. 4,
  146108. 3,
  146109. 5,
  146110. 2,
  146111. 6,
  146112. 1,
  146113. 7,
  146114. 0,
  146115. 8,
  146116. };
  146117. static long _vq_lengthlist__44u1__p5_0[] = {
  146118. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  146119. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  146120. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  146121. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  146122. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  146123. 12,
  146124. };
  146125. static float _vq_quantthresh__44u1__p5_0[] = {
  146126. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146127. };
  146128. static long _vq_quantmap__44u1__p5_0[] = {
  146129. 7, 5, 3, 1, 0, 2, 4, 6,
  146130. 8,
  146131. };
  146132. static encode_aux_threshmatch _vq_auxt__44u1__p5_0 = {
  146133. _vq_quantthresh__44u1__p5_0,
  146134. _vq_quantmap__44u1__p5_0,
  146135. 9,
  146136. 9
  146137. };
  146138. static static_codebook _44u1__p5_0 = {
  146139. 2, 81,
  146140. _vq_lengthlist__44u1__p5_0,
  146141. 1, -531628032, 1611661312, 4, 0,
  146142. _vq_quantlist__44u1__p5_0,
  146143. NULL,
  146144. &_vq_auxt__44u1__p5_0,
  146145. NULL,
  146146. 0
  146147. };
  146148. static long _vq_quantlist__44u1__p6_0[] = {
  146149. 6,
  146150. 5,
  146151. 7,
  146152. 4,
  146153. 8,
  146154. 3,
  146155. 9,
  146156. 2,
  146157. 10,
  146158. 1,
  146159. 11,
  146160. 0,
  146161. 12,
  146162. };
  146163. static long _vq_lengthlist__44u1__p6_0[] = {
  146164. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  146165. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  146166. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  146167. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  146168. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  146169. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  146170. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  146171. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  146172. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  146173. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  146174. 15,17,16,17,18,17,17,18, 0,
  146175. };
  146176. static float _vq_quantthresh__44u1__p6_0[] = {
  146177. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  146178. 12.5, 17.5, 22.5, 27.5,
  146179. };
  146180. static long _vq_quantmap__44u1__p6_0[] = {
  146181. 11, 9, 7, 5, 3, 1, 0, 2,
  146182. 4, 6, 8, 10, 12,
  146183. };
  146184. static encode_aux_threshmatch _vq_auxt__44u1__p6_0 = {
  146185. _vq_quantthresh__44u1__p6_0,
  146186. _vq_quantmap__44u1__p6_0,
  146187. 13,
  146188. 13
  146189. };
  146190. static static_codebook _44u1__p6_0 = {
  146191. 2, 169,
  146192. _vq_lengthlist__44u1__p6_0,
  146193. 1, -526516224, 1616117760, 4, 0,
  146194. _vq_quantlist__44u1__p6_0,
  146195. NULL,
  146196. &_vq_auxt__44u1__p6_0,
  146197. NULL,
  146198. 0
  146199. };
  146200. static long _vq_quantlist__44u1__p6_1[] = {
  146201. 2,
  146202. 1,
  146203. 3,
  146204. 0,
  146205. 4,
  146206. };
  146207. static long _vq_lengthlist__44u1__p6_1[] = {
  146208. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  146209. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  146210. };
  146211. static float _vq_quantthresh__44u1__p6_1[] = {
  146212. -1.5, -0.5, 0.5, 1.5,
  146213. };
  146214. static long _vq_quantmap__44u1__p6_1[] = {
  146215. 3, 1, 0, 2, 4,
  146216. };
  146217. static encode_aux_threshmatch _vq_auxt__44u1__p6_1 = {
  146218. _vq_quantthresh__44u1__p6_1,
  146219. _vq_quantmap__44u1__p6_1,
  146220. 5,
  146221. 5
  146222. };
  146223. static static_codebook _44u1__p6_1 = {
  146224. 2, 25,
  146225. _vq_lengthlist__44u1__p6_1,
  146226. 1, -533725184, 1611661312, 3, 0,
  146227. _vq_quantlist__44u1__p6_1,
  146228. NULL,
  146229. &_vq_auxt__44u1__p6_1,
  146230. NULL,
  146231. 0
  146232. };
  146233. static long _vq_quantlist__44u1__p7_0[] = {
  146234. 3,
  146235. 2,
  146236. 4,
  146237. 1,
  146238. 5,
  146239. 0,
  146240. 6,
  146241. };
  146242. static long _vq_lengthlist__44u1__p7_0[] = {
  146243. 1, 3, 2, 9, 9, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146244. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146245. 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  146246. 8,
  146247. };
  146248. static float _vq_quantthresh__44u1__p7_0[] = {
  146249. -422.5, -253.5, -84.5, 84.5, 253.5, 422.5,
  146250. };
  146251. static long _vq_quantmap__44u1__p7_0[] = {
  146252. 5, 3, 1, 0, 2, 4, 6,
  146253. };
  146254. static encode_aux_threshmatch _vq_auxt__44u1__p7_0 = {
  146255. _vq_quantthresh__44u1__p7_0,
  146256. _vq_quantmap__44u1__p7_0,
  146257. 7,
  146258. 7
  146259. };
  146260. static static_codebook _44u1__p7_0 = {
  146261. 2, 49,
  146262. _vq_lengthlist__44u1__p7_0,
  146263. 1, -518017024, 1626677248, 3, 0,
  146264. _vq_quantlist__44u1__p7_0,
  146265. NULL,
  146266. &_vq_auxt__44u1__p7_0,
  146267. NULL,
  146268. 0
  146269. };
  146270. static long _vq_quantlist__44u1__p7_1[] = {
  146271. 6,
  146272. 5,
  146273. 7,
  146274. 4,
  146275. 8,
  146276. 3,
  146277. 9,
  146278. 2,
  146279. 10,
  146280. 1,
  146281. 11,
  146282. 0,
  146283. 12,
  146284. };
  146285. static long _vq_lengthlist__44u1__p7_1[] = {
  146286. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  146287. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  146288. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  146289. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  146290. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  146291. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  146292. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  146293. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  146294. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  146295. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  146296. 15,15,15,15,15,15,15,15,15,
  146297. };
  146298. static float _vq_quantthresh__44u1__p7_1[] = {
  146299. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  146300. 32.5, 45.5, 58.5, 71.5,
  146301. };
  146302. static long _vq_quantmap__44u1__p7_1[] = {
  146303. 11, 9, 7, 5, 3, 1, 0, 2,
  146304. 4, 6, 8, 10, 12,
  146305. };
  146306. static encode_aux_threshmatch _vq_auxt__44u1__p7_1 = {
  146307. _vq_quantthresh__44u1__p7_1,
  146308. _vq_quantmap__44u1__p7_1,
  146309. 13,
  146310. 13
  146311. };
  146312. static static_codebook _44u1__p7_1 = {
  146313. 2, 169,
  146314. _vq_lengthlist__44u1__p7_1,
  146315. 1, -523010048, 1618608128, 4, 0,
  146316. _vq_quantlist__44u1__p7_1,
  146317. NULL,
  146318. &_vq_auxt__44u1__p7_1,
  146319. NULL,
  146320. 0
  146321. };
  146322. static long _vq_quantlist__44u1__p7_2[] = {
  146323. 6,
  146324. 5,
  146325. 7,
  146326. 4,
  146327. 8,
  146328. 3,
  146329. 9,
  146330. 2,
  146331. 10,
  146332. 1,
  146333. 11,
  146334. 0,
  146335. 12,
  146336. };
  146337. static long _vq_lengthlist__44u1__p7_2[] = {
  146338. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  146339. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  146340. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  146341. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  146342. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  146343. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  146344. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  146345. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146346. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146347. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  146348. 9, 9, 9,10, 9, 9,10,10, 9,
  146349. };
  146350. static float _vq_quantthresh__44u1__p7_2[] = {
  146351. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  146352. 2.5, 3.5, 4.5, 5.5,
  146353. };
  146354. static long _vq_quantmap__44u1__p7_2[] = {
  146355. 11, 9, 7, 5, 3, 1, 0, 2,
  146356. 4, 6, 8, 10, 12,
  146357. };
  146358. static encode_aux_threshmatch _vq_auxt__44u1__p7_2 = {
  146359. _vq_quantthresh__44u1__p7_2,
  146360. _vq_quantmap__44u1__p7_2,
  146361. 13,
  146362. 13
  146363. };
  146364. static static_codebook _44u1__p7_2 = {
  146365. 2, 169,
  146366. _vq_lengthlist__44u1__p7_2,
  146367. 1, -531103744, 1611661312, 4, 0,
  146368. _vq_quantlist__44u1__p7_2,
  146369. NULL,
  146370. &_vq_auxt__44u1__p7_2,
  146371. NULL,
  146372. 0
  146373. };
  146374. static long _huff_lengthlist__44u1__short[] = {
  146375. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  146376. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  146377. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  146378. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  146379. };
  146380. static static_codebook _huff_book__44u1__short = {
  146381. 2, 64,
  146382. _huff_lengthlist__44u1__short,
  146383. 0, 0, 0, 0, 0,
  146384. NULL,
  146385. NULL,
  146386. NULL,
  146387. NULL,
  146388. 0
  146389. };
  146390. static long _huff_lengthlist__44u2__long[] = {
  146391. 5, 9,14,12,15,13,10,13, 7, 4, 5, 6, 8, 7, 8,12,
  146392. 13, 4, 3, 5, 5, 6, 9,15,12, 6, 5, 6, 6, 6, 7,14,
  146393. 14, 7, 4, 6, 4, 6, 8,15,12, 6, 6, 5, 5, 5, 6,14,
  146394. 9, 7, 8, 6, 7, 5, 4,10,10,13,14,14,15,10, 6, 8,
  146395. };
  146396. static static_codebook _huff_book__44u2__long = {
  146397. 2, 64,
  146398. _huff_lengthlist__44u2__long,
  146399. 0, 0, 0, 0, 0,
  146400. NULL,
  146401. NULL,
  146402. NULL,
  146403. NULL,
  146404. 0
  146405. };
  146406. static long _vq_quantlist__44u2__p1_0[] = {
  146407. 1,
  146408. 0,
  146409. 2,
  146410. };
  146411. static long _vq_lengthlist__44u2__p1_0[] = {
  146412. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  146413. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146414. 11, 8,11,11, 8,11,11,11,13,14,11,13,13, 7,11,11,
  146415. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 8,
  146416. 11,11,11,14,13,10,12,13, 8,11,11,11,13,13,11,13,
  146417. 13,
  146418. };
  146419. static float _vq_quantthresh__44u2__p1_0[] = {
  146420. -0.5, 0.5,
  146421. };
  146422. static long _vq_quantmap__44u2__p1_0[] = {
  146423. 1, 0, 2,
  146424. };
  146425. static encode_aux_threshmatch _vq_auxt__44u2__p1_0 = {
  146426. _vq_quantthresh__44u2__p1_0,
  146427. _vq_quantmap__44u2__p1_0,
  146428. 3,
  146429. 3
  146430. };
  146431. static static_codebook _44u2__p1_0 = {
  146432. 4, 81,
  146433. _vq_lengthlist__44u2__p1_0,
  146434. 1, -535822336, 1611661312, 2, 0,
  146435. _vq_quantlist__44u2__p1_0,
  146436. NULL,
  146437. &_vq_auxt__44u2__p1_0,
  146438. NULL,
  146439. 0
  146440. };
  146441. static long _vq_quantlist__44u2__p2_0[] = {
  146442. 1,
  146443. 0,
  146444. 2,
  146445. };
  146446. static long _vq_lengthlist__44u2__p2_0[] = {
  146447. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  146448. 8, 8, 5, 6, 6, 6, 8, 7, 7, 8, 8, 5, 6, 6, 7, 8,
  146449. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  146450. 7,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  146451. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  146452. 9,
  146453. };
  146454. static float _vq_quantthresh__44u2__p2_0[] = {
  146455. -0.5, 0.5,
  146456. };
  146457. static long _vq_quantmap__44u2__p2_0[] = {
  146458. 1, 0, 2,
  146459. };
  146460. static encode_aux_threshmatch _vq_auxt__44u2__p2_0 = {
  146461. _vq_quantthresh__44u2__p2_0,
  146462. _vq_quantmap__44u2__p2_0,
  146463. 3,
  146464. 3
  146465. };
  146466. static static_codebook _44u2__p2_0 = {
  146467. 4, 81,
  146468. _vq_lengthlist__44u2__p2_0,
  146469. 1, -535822336, 1611661312, 2, 0,
  146470. _vq_quantlist__44u2__p2_0,
  146471. NULL,
  146472. &_vq_auxt__44u2__p2_0,
  146473. NULL,
  146474. 0
  146475. };
  146476. static long _vq_quantlist__44u2__p3_0[] = {
  146477. 2,
  146478. 1,
  146479. 3,
  146480. 0,
  146481. 4,
  146482. };
  146483. static long _vq_lengthlist__44u2__p3_0[] = {
  146484. 2, 4, 4, 7, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  146485. 9, 9,12,11, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  146486. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  146487. 12,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  146488. 11, 9,11,10,13,13,10,11,11,13,13, 8,10,10,14,13,
  146489. 10,11,11,15,14, 9,11,11,15,14,13,14,13,16,14,12,
  146490. 13,13,15,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  146491. 11,14,15,12,13,13,15,15,12,13,14,15,16, 5, 7, 7,
  146492. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  146493. 13,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  146494. 9,11,11,13,13,12,13,12,14,14,11,12,13,15,15, 7,
  146495. 9, 9,12,12, 8,11,10,13,12, 9,11,11,13,13,11,13,
  146496. 12,15,13,11,13,13,15,16, 9,12,11,15,15,11,12,12,
  146497. 16,15,11,12,13,16,16,13,14,15,16,15,13,15,15,17,
  146498. 17, 9,11,11,14,15,10,12,12,15,15,11,13,12,15,16,
  146499. 13,15,14,16,16,13,15,15,17,19, 5, 7, 7,10,10, 7,
  146500. 9, 9,12,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  146501. 11,13,14, 7, 9, 9,12,12, 9,11,11,13,13, 9,10,11,
  146502. 12,13,11,13,12,16,15,11,12,12,14,15, 7, 9, 9,12,
  146503. 12, 9,11,11,13,13, 9,11,11,13,12,11,13,12,15,16,
  146504. 12,13,13,15,14, 9,11,11,15,14,11,13,12,16,15,10,
  146505. 11,12,15,15,13,14,14,18,17,13,14,14,15,17,10,11,
  146506. 11,14,15,11,13,12,15,17,11,13,12,15,16,13,15,14,
  146507. 18,17,14,15,15,16,18, 7,10,10,14,14,10,12,12,15,
  146508. 15,10,12,12,15,15,14,15,15,18,17,13,15,15,16,16,
  146509. 9,11,11,16,15,11,13,13,16,18,11,13,13,16,16,15,
  146510. 16,16, 0, 0,14,15,16,18,17, 9,11,11,15,15,10,13,
  146511. 12,17,16,11,12,13,16,17,14,15,16,19,19,14,15,15,
  146512. 0,20,12,14,14, 0, 0,13,14,16,19,18,13,15,16,20,
  146513. 17,16,18, 0, 0, 0,15,16,17,18,19,11,14,14, 0,19,
  146514. 12,15,14,17,17,13,15,15, 0, 0,16,17,15,20,19,15,
  146515. 17,16,19, 0, 8,10,10,14,15,10,12,11,15,15,10,11,
  146516. 12,16,15,13,14,14,19,17,14,15,15, 0, 0, 9,11,11,
  146517. 16,15,11,13,13,17,16,10,12,13,16,17,14,15,15,18,
  146518. 18,14,15,16,20,19, 9,12,12, 0,15,11,13,13,16,17,
  146519. 11,13,13,19,17,14,16,16,18,17,15,16,16,17,19,11,
  146520. 14,14,18,18,13,14,15, 0, 0,12,14,15,19,18,15,16,
  146521. 19, 0,19,15,16,19,19,17,12,14,14,16,19,13,15,15,
  146522. 0,17,13,15,14,18,18,15,16,15, 0,18,16,17,17, 0,
  146523. 0,
  146524. };
  146525. static float _vq_quantthresh__44u2__p3_0[] = {
  146526. -1.5, -0.5, 0.5, 1.5,
  146527. };
  146528. static long _vq_quantmap__44u2__p3_0[] = {
  146529. 3, 1, 0, 2, 4,
  146530. };
  146531. static encode_aux_threshmatch _vq_auxt__44u2__p3_0 = {
  146532. _vq_quantthresh__44u2__p3_0,
  146533. _vq_quantmap__44u2__p3_0,
  146534. 5,
  146535. 5
  146536. };
  146537. static static_codebook _44u2__p3_0 = {
  146538. 4, 625,
  146539. _vq_lengthlist__44u2__p3_0,
  146540. 1, -533725184, 1611661312, 3, 0,
  146541. _vq_quantlist__44u2__p3_0,
  146542. NULL,
  146543. &_vq_auxt__44u2__p3_0,
  146544. NULL,
  146545. 0
  146546. };
  146547. static long _vq_quantlist__44u2__p4_0[] = {
  146548. 2,
  146549. 1,
  146550. 3,
  146551. 0,
  146552. 4,
  146553. };
  146554. static long _vq_lengthlist__44u2__p4_0[] = {
  146555. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  146556. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  146557. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  146558. 11,12, 5, 7, 7, 9, 9, 6, 8, 7,10,10, 7, 8, 8,10,
  146559. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10,10,12,12,
  146560. 10,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  146561. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,13,10,10,
  146562. 10,12,13,11,12,12,14,13,12,12,12,14,13, 5, 7, 7,
  146563. 10, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  146564. 12,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  146565. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,13,13, 6,
  146566. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146567. 10,13,11,10,11,11,13,13, 9,10,10,13,13,10,11,11,
  146568. 13,13,10,11,11,14,13,12,11,13,12,15,12,13,13,15,
  146569. 15, 9,10,10,12,13,10,11,10,13,13,10,11,11,13,13,
  146570. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9,10, 7,
  146571. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  146572. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  146573. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  146574. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  146575. 10,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  146576. 10,11,13,13,12,13,13,15,15,12,11,13,12,14, 9,10,
  146577. 10,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  146578. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  146579. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  146580. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,12,13,
  146581. 13,14,14,16,12,13,13,15,14, 9,10,10,13,13,10,11,
  146582. 10,14,13,10,11,11,13,14,12,14,13,16,14,13,13,13,
  146583. 14,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  146584. 15,14,12,15,12,16,14,15,15,17,16,11,12,12,14,15,
  146585. 11,13,11,15,14,12,13,13,15,16,13,15,12,17,13,14,
  146586. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,13,13, 9,10,
  146587. 10,13,13,12,13,12,14,14,12,13,13,15,15, 9,10,10,
  146588. 13,13,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  146589. 14,12,12,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  146590. 10,11,11,14,13,13,13,13,15,15,13,14,13,16,14,11,
  146591. 12,12,14,14,12,13,13,16,15,11,12,13,14,15,14,15,
  146592. 15,16,16,14,13,15,13,17,11,12,12,14,15,12,13,13,
  146593. 15,16,11,13,12,15,15,14,15,14,16,16,14,15,12,17,
  146594. 13,
  146595. };
  146596. static float _vq_quantthresh__44u2__p4_0[] = {
  146597. -1.5, -0.5, 0.5, 1.5,
  146598. };
  146599. static long _vq_quantmap__44u2__p4_0[] = {
  146600. 3, 1, 0, 2, 4,
  146601. };
  146602. static encode_aux_threshmatch _vq_auxt__44u2__p4_0 = {
  146603. _vq_quantthresh__44u2__p4_0,
  146604. _vq_quantmap__44u2__p4_0,
  146605. 5,
  146606. 5
  146607. };
  146608. static static_codebook _44u2__p4_0 = {
  146609. 4, 625,
  146610. _vq_lengthlist__44u2__p4_0,
  146611. 1, -533725184, 1611661312, 3, 0,
  146612. _vq_quantlist__44u2__p4_0,
  146613. NULL,
  146614. &_vq_auxt__44u2__p4_0,
  146615. NULL,
  146616. 0
  146617. };
  146618. static long _vq_quantlist__44u2__p5_0[] = {
  146619. 4,
  146620. 3,
  146621. 5,
  146622. 2,
  146623. 6,
  146624. 1,
  146625. 7,
  146626. 0,
  146627. 8,
  146628. };
  146629. static long _vq_lengthlist__44u2__p5_0[] = {
  146630. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 8, 8, 8,
  146631. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  146632. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  146633. 9, 9,10,11,12,12, 8, 8, 8, 9, 9,10,10,12,12,10,
  146634. 10,10,11,11,12,12,13,13,10,10,10,11,11,12,12,13,
  146635. 13,
  146636. };
  146637. static float _vq_quantthresh__44u2__p5_0[] = {
  146638. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146639. };
  146640. static long _vq_quantmap__44u2__p5_0[] = {
  146641. 7, 5, 3, 1, 0, 2, 4, 6,
  146642. 8,
  146643. };
  146644. static encode_aux_threshmatch _vq_auxt__44u2__p5_0 = {
  146645. _vq_quantthresh__44u2__p5_0,
  146646. _vq_quantmap__44u2__p5_0,
  146647. 9,
  146648. 9
  146649. };
  146650. static static_codebook _44u2__p5_0 = {
  146651. 2, 81,
  146652. _vq_lengthlist__44u2__p5_0,
  146653. 1, -531628032, 1611661312, 4, 0,
  146654. _vq_quantlist__44u2__p5_0,
  146655. NULL,
  146656. &_vq_auxt__44u2__p5_0,
  146657. NULL,
  146658. 0
  146659. };
  146660. static long _vq_quantlist__44u2__p6_0[] = {
  146661. 6,
  146662. 5,
  146663. 7,
  146664. 4,
  146665. 8,
  146666. 3,
  146667. 9,
  146668. 2,
  146669. 10,
  146670. 1,
  146671. 11,
  146672. 0,
  146673. 12,
  146674. };
  146675. static long _vq_lengthlist__44u2__p6_0[] = {
  146676. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,14,13, 4, 6, 5,
  146677. 8, 8, 9, 9,11,10,12,11,15,14, 4, 5, 6, 8, 8, 9,
  146678. 9,11,11,11,11,14,14, 6, 8, 8,10, 9,11,11,11,11,
  146679. 12,12,15,15, 6, 8, 8, 9, 9,11,11,11,12,12,12,15,
  146680. 15, 8,10,10,11,11,11,11,12,12,13,13,15,16, 8,10,
  146681. 10,11,11,11,11,12,12,13,13,16,16,10,11,11,12,12,
  146682. 12,12,13,13,13,13,17,16,10,11,11,12,12,12,12,13,
  146683. 13,13,14,16,17,11,12,12,13,13,13,13,14,14,15,14,
  146684. 18,17,11,12,12,13,13,13,13,14,14,14,15,19,18,14,
  146685. 15,15,15,15,16,16,18,19,18,18, 0, 0,14,15,15,16,
  146686. 15,17,17,16,18,17,18, 0, 0,
  146687. };
  146688. static float _vq_quantthresh__44u2__p6_0[] = {
  146689. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  146690. 12.5, 17.5, 22.5, 27.5,
  146691. };
  146692. static long _vq_quantmap__44u2__p6_0[] = {
  146693. 11, 9, 7, 5, 3, 1, 0, 2,
  146694. 4, 6, 8, 10, 12,
  146695. };
  146696. static encode_aux_threshmatch _vq_auxt__44u2__p6_0 = {
  146697. _vq_quantthresh__44u2__p6_0,
  146698. _vq_quantmap__44u2__p6_0,
  146699. 13,
  146700. 13
  146701. };
  146702. static static_codebook _44u2__p6_0 = {
  146703. 2, 169,
  146704. _vq_lengthlist__44u2__p6_0,
  146705. 1, -526516224, 1616117760, 4, 0,
  146706. _vq_quantlist__44u2__p6_0,
  146707. NULL,
  146708. &_vq_auxt__44u2__p6_0,
  146709. NULL,
  146710. 0
  146711. };
  146712. static long _vq_quantlist__44u2__p6_1[] = {
  146713. 2,
  146714. 1,
  146715. 3,
  146716. 0,
  146717. 4,
  146718. };
  146719. static long _vq_lengthlist__44u2__p6_1[] = {
  146720. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  146721. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  146722. };
  146723. static float _vq_quantthresh__44u2__p6_1[] = {
  146724. -1.5, -0.5, 0.5, 1.5,
  146725. };
  146726. static long _vq_quantmap__44u2__p6_1[] = {
  146727. 3, 1, 0, 2, 4,
  146728. };
  146729. static encode_aux_threshmatch _vq_auxt__44u2__p6_1 = {
  146730. _vq_quantthresh__44u2__p6_1,
  146731. _vq_quantmap__44u2__p6_1,
  146732. 5,
  146733. 5
  146734. };
  146735. static static_codebook _44u2__p6_1 = {
  146736. 2, 25,
  146737. _vq_lengthlist__44u2__p6_1,
  146738. 1, -533725184, 1611661312, 3, 0,
  146739. _vq_quantlist__44u2__p6_1,
  146740. NULL,
  146741. &_vq_auxt__44u2__p6_1,
  146742. NULL,
  146743. 0
  146744. };
  146745. static long _vq_quantlist__44u2__p7_0[] = {
  146746. 4,
  146747. 3,
  146748. 5,
  146749. 2,
  146750. 6,
  146751. 1,
  146752. 7,
  146753. 0,
  146754. 8,
  146755. };
  146756. static long _vq_lengthlist__44u2__p7_0[] = {
  146757. 1, 3, 2,12,12,12,12,12,12, 4,12,12,12,12,12,12,
  146758. 12,12, 5,12,12,12,12,12,12,12,12,12,12,11,11,11,
  146759. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146760. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146761. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146762. 11,
  146763. };
  146764. static float _vq_quantthresh__44u2__p7_0[] = {
  146765. -591.5, -422.5, -253.5, -84.5, 84.5, 253.5, 422.5, 591.5,
  146766. };
  146767. static long _vq_quantmap__44u2__p7_0[] = {
  146768. 7, 5, 3, 1, 0, 2, 4, 6,
  146769. 8,
  146770. };
  146771. static encode_aux_threshmatch _vq_auxt__44u2__p7_0 = {
  146772. _vq_quantthresh__44u2__p7_0,
  146773. _vq_quantmap__44u2__p7_0,
  146774. 9,
  146775. 9
  146776. };
  146777. static static_codebook _44u2__p7_0 = {
  146778. 2, 81,
  146779. _vq_lengthlist__44u2__p7_0,
  146780. 1, -516612096, 1626677248, 4, 0,
  146781. _vq_quantlist__44u2__p7_0,
  146782. NULL,
  146783. &_vq_auxt__44u2__p7_0,
  146784. NULL,
  146785. 0
  146786. };
  146787. static long _vq_quantlist__44u2__p7_1[] = {
  146788. 6,
  146789. 5,
  146790. 7,
  146791. 4,
  146792. 8,
  146793. 3,
  146794. 9,
  146795. 2,
  146796. 10,
  146797. 1,
  146798. 11,
  146799. 0,
  146800. 12,
  146801. };
  146802. static long _vq_lengthlist__44u2__p7_1[] = {
  146803. 1, 4, 4, 7, 6, 7, 6, 8, 7, 9, 7, 9, 8, 4, 7, 6,
  146804. 8, 8, 9, 8,10, 9,10,10,11,11, 4, 7, 7, 8, 8, 8,
  146805. 8, 9,10,11,11,11,11, 6, 8, 8,10,10,10,10,11,11,
  146806. 12,12,12,12, 7, 8, 8,10,10,10,10,11,11,12,12,13,
  146807. 13, 7, 9, 9,11,10,12,12,13,13,14,13,14,14, 7, 9,
  146808. 9,10,11,11,12,13,13,13,13,16,14, 9,10,10,12,12,
  146809. 13,13,14,14,15,16,15,16, 9,10,10,12,12,12,13,14,
  146810. 14,14,15,16,15,10,12,12,13,13,15,13,16,16,15,17,
  146811. 17,17,10,11,11,12,14,14,14,15,15,17,17,15,17,11,
  146812. 12,12,14,14,14,15,15,15,17,16,17,17,10,12,12,13,
  146813. 14,14,14,17,15,17,17,17,17,
  146814. };
  146815. static float _vq_quantthresh__44u2__p7_1[] = {
  146816. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  146817. 32.5, 45.5, 58.5, 71.5,
  146818. };
  146819. static long _vq_quantmap__44u2__p7_1[] = {
  146820. 11, 9, 7, 5, 3, 1, 0, 2,
  146821. 4, 6, 8, 10, 12,
  146822. };
  146823. static encode_aux_threshmatch _vq_auxt__44u2__p7_1 = {
  146824. _vq_quantthresh__44u2__p7_1,
  146825. _vq_quantmap__44u2__p7_1,
  146826. 13,
  146827. 13
  146828. };
  146829. static static_codebook _44u2__p7_1 = {
  146830. 2, 169,
  146831. _vq_lengthlist__44u2__p7_1,
  146832. 1, -523010048, 1618608128, 4, 0,
  146833. _vq_quantlist__44u2__p7_1,
  146834. NULL,
  146835. &_vq_auxt__44u2__p7_1,
  146836. NULL,
  146837. 0
  146838. };
  146839. static long _vq_quantlist__44u2__p7_2[] = {
  146840. 6,
  146841. 5,
  146842. 7,
  146843. 4,
  146844. 8,
  146845. 3,
  146846. 9,
  146847. 2,
  146848. 10,
  146849. 1,
  146850. 11,
  146851. 0,
  146852. 12,
  146853. };
  146854. static long _vq_lengthlist__44u2__p7_2[] = {
  146855. 2, 5, 5, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 5, 6, 6,
  146856. 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 5, 6, 6, 7, 7, 8,
  146857. 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7, 8, 8, 8, 8, 8,
  146858. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  146859. 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 7, 8,
  146860. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 9,
  146861. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  146862. 9, 9, 9, 9, 9, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146863. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8,
  146864. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9,
  146865. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146866. };
  146867. static float _vq_quantthresh__44u2__p7_2[] = {
  146868. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  146869. 2.5, 3.5, 4.5, 5.5,
  146870. };
  146871. static long _vq_quantmap__44u2__p7_2[] = {
  146872. 11, 9, 7, 5, 3, 1, 0, 2,
  146873. 4, 6, 8, 10, 12,
  146874. };
  146875. static encode_aux_threshmatch _vq_auxt__44u2__p7_2 = {
  146876. _vq_quantthresh__44u2__p7_2,
  146877. _vq_quantmap__44u2__p7_2,
  146878. 13,
  146879. 13
  146880. };
  146881. static static_codebook _44u2__p7_2 = {
  146882. 2, 169,
  146883. _vq_lengthlist__44u2__p7_2,
  146884. 1, -531103744, 1611661312, 4, 0,
  146885. _vq_quantlist__44u2__p7_2,
  146886. NULL,
  146887. &_vq_auxt__44u2__p7_2,
  146888. NULL,
  146889. 0
  146890. };
  146891. static long _huff_lengthlist__44u2__short[] = {
  146892. 13,15,17,17,15,15,12,17,11, 9, 7,10,10, 9,12,17,
  146893. 10, 6, 3, 6, 5, 7,10,17,15,10, 6, 9, 8, 9,11,17,
  146894. 15, 8, 4, 7, 3, 5, 9,16,16,10, 5, 8, 4, 5, 8,16,
  146895. 13,11, 5, 8, 3, 3, 5,14,13,12, 7,10, 5, 5, 7,14,
  146896. };
  146897. static static_codebook _huff_book__44u2__short = {
  146898. 2, 64,
  146899. _huff_lengthlist__44u2__short,
  146900. 0, 0, 0, 0, 0,
  146901. NULL,
  146902. NULL,
  146903. NULL,
  146904. NULL,
  146905. 0
  146906. };
  146907. static long _huff_lengthlist__44u3__long[] = {
  146908. 6, 9,13,12,14,11,10,13, 8, 4, 5, 7, 8, 7, 8,12,
  146909. 11, 4, 3, 5, 5, 7, 9,14,11, 6, 5, 6, 6, 6, 7,13,
  146910. 13, 7, 5, 6, 4, 5, 7,14,11, 7, 6, 6, 5, 5, 6,13,
  146911. 9, 7, 8, 6, 7, 5, 3, 9, 9,12,13,12,14,10, 6, 7,
  146912. };
  146913. static static_codebook _huff_book__44u3__long = {
  146914. 2, 64,
  146915. _huff_lengthlist__44u3__long,
  146916. 0, 0, 0, 0, 0,
  146917. NULL,
  146918. NULL,
  146919. NULL,
  146920. NULL,
  146921. 0
  146922. };
  146923. static long _vq_quantlist__44u3__p1_0[] = {
  146924. 1,
  146925. 0,
  146926. 2,
  146927. };
  146928. static long _vq_lengthlist__44u3__p1_0[] = {
  146929. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  146930. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146931. 11, 8,11,11, 8,11,11,11,13,14,11,14,14, 8,11,11,
  146932. 10,14,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  146933. 11,11,11,14,14,10,12,14, 8,11,11,11,14,14,11,14,
  146934. 13,
  146935. };
  146936. static float _vq_quantthresh__44u3__p1_0[] = {
  146937. -0.5, 0.5,
  146938. };
  146939. static long _vq_quantmap__44u3__p1_0[] = {
  146940. 1, 0, 2,
  146941. };
  146942. static encode_aux_threshmatch _vq_auxt__44u3__p1_0 = {
  146943. _vq_quantthresh__44u3__p1_0,
  146944. _vq_quantmap__44u3__p1_0,
  146945. 3,
  146946. 3
  146947. };
  146948. static static_codebook _44u3__p1_0 = {
  146949. 4, 81,
  146950. _vq_lengthlist__44u3__p1_0,
  146951. 1, -535822336, 1611661312, 2, 0,
  146952. _vq_quantlist__44u3__p1_0,
  146953. NULL,
  146954. &_vq_auxt__44u3__p1_0,
  146955. NULL,
  146956. 0
  146957. };
  146958. static long _vq_quantlist__44u3__p2_0[] = {
  146959. 1,
  146960. 0,
  146961. 2,
  146962. };
  146963. static long _vq_lengthlist__44u3__p2_0[] = {
  146964. 2, 5, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  146965. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 7, 8,
  146966. 8, 6, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  146967. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  146968. 8, 8, 8,10,10, 8, 8,10, 7, 8, 8, 8,10,10, 8,10,
  146969. 9,
  146970. };
  146971. static float _vq_quantthresh__44u3__p2_0[] = {
  146972. -0.5, 0.5,
  146973. };
  146974. static long _vq_quantmap__44u3__p2_0[] = {
  146975. 1, 0, 2,
  146976. };
  146977. static encode_aux_threshmatch _vq_auxt__44u3__p2_0 = {
  146978. _vq_quantthresh__44u3__p2_0,
  146979. _vq_quantmap__44u3__p2_0,
  146980. 3,
  146981. 3
  146982. };
  146983. static static_codebook _44u3__p2_0 = {
  146984. 4, 81,
  146985. _vq_lengthlist__44u3__p2_0,
  146986. 1, -535822336, 1611661312, 2, 0,
  146987. _vq_quantlist__44u3__p2_0,
  146988. NULL,
  146989. &_vq_auxt__44u3__p2_0,
  146990. NULL,
  146991. 0
  146992. };
  146993. static long _vq_quantlist__44u3__p3_0[] = {
  146994. 2,
  146995. 1,
  146996. 3,
  146997. 0,
  146998. 4,
  146999. };
  147000. static long _vq_lengthlist__44u3__p3_0[] = {
  147001. 2, 4, 4, 7, 7, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  147002. 9, 9,12,12, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  147003. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  147004. 13,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  147005. 11, 9,11,10,13,13,10,11,11,14,13, 8,10,10,14,13,
  147006. 10,11,11,15,14, 9,11,11,14,14,13,14,13,16,16,12,
  147007. 13,13,15,15, 8,10,10,13,14, 9,11,11,14,14,10,11,
  147008. 11,14,15,12,13,13,15,15,13,14,14,15,16, 5, 7, 7,
  147009. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  147010. 14,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  147011. 9,11,11,13,13,12,12,13,15,15,11,12,13,15,16, 7,
  147012. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  147013. 12,15,13,11,13,13,15,16, 9,12,11,15,14,11,12,13,
  147014. 16,15,11,13,13,15,16,14,14,15,17,16,13,15,16, 0,
  147015. 17, 9,11,11,15,15,10,13,12,15,15,11,13,13,15,16,
  147016. 13,15,13,16,15,14,16,15, 0,19, 5, 7, 7,10,10, 7,
  147017. 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,14,10,11,
  147018. 12,14,14, 7, 9, 9,12,12, 9,11,11,14,13, 9,10,11,
  147019. 12,13,11,13,13,16,16,11,12,13,13,16, 7, 9, 9,12,
  147020. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,15,
  147021. 12,13,12,15,14, 9,11,11,15,14,11,13,12,16,16,10,
  147022. 12,12,15,15,13,15,15,17,19,13,14,15,16,17,10,12,
  147023. 12,15,15,11,13,13,16,16,11,13,13,15,16,13,15,15,
  147024. 0, 0,14,15,15,16,16, 8,10,10,14,14,10,12,12,15,
  147025. 15,10,12,11,15,16,14,15,15,19,20,13,14,14,18,16,
  147026. 9,11,11,15,15,11,13,13,17,16,11,13,13,16,16,15,
  147027. 17,17,20,20,14,15,16,17,20, 9,11,11,15,15,10,13,
  147028. 12,16,15,11,13,13,15,17,14,16,15,18, 0,14,16,15,
  147029. 18,20,12,14,14, 0, 0,14,14,16, 0, 0,13,16,15, 0,
  147030. 0,17,17,18, 0, 0,16,17,19,19, 0,12,14,14,18, 0,
  147031. 12,16,14, 0,17,13,15,15,18, 0,16,18,17, 0,17,16,
  147032. 18,17, 0, 0, 7,10,10,14,14,10,12,11,15,15,10,12,
  147033. 12,16,15,13,15,15,18, 0,14,15,15,17, 0, 9,11,11,
  147034. 15,15,11,13,13,16,16,11,12,13,16,16,14,15,16,17,
  147035. 17,14,16,16,16,18, 9,11,12,16,16,11,13,13,17,17,
  147036. 11,14,13,20,17,15,16,16,19, 0,15,16,17, 0,19,11,
  147037. 13,14,17,16,14,15,15,20,18,13,14,15,17,19,16,18,
  147038. 18, 0,20,16,16,19,17, 0,12,15,14,17, 0,14,15,15,
  147039. 18,19,13,16,15,19,20,15,18,18, 0,20,17, 0,16, 0,
  147040. 0,
  147041. };
  147042. static float _vq_quantthresh__44u3__p3_0[] = {
  147043. -1.5, -0.5, 0.5, 1.5,
  147044. };
  147045. static long _vq_quantmap__44u3__p3_0[] = {
  147046. 3, 1, 0, 2, 4,
  147047. };
  147048. static encode_aux_threshmatch _vq_auxt__44u3__p3_0 = {
  147049. _vq_quantthresh__44u3__p3_0,
  147050. _vq_quantmap__44u3__p3_0,
  147051. 5,
  147052. 5
  147053. };
  147054. static static_codebook _44u3__p3_0 = {
  147055. 4, 625,
  147056. _vq_lengthlist__44u3__p3_0,
  147057. 1, -533725184, 1611661312, 3, 0,
  147058. _vq_quantlist__44u3__p3_0,
  147059. NULL,
  147060. &_vq_auxt__44u3__p3_0,
  147061. NULL,
  147062. 0
  147063. };
  147064. static long _vq_quantlist__44u3__p4_0[] = {
  147065. 2,
  147066. 1,
  147067. 3,
  147068. 0,
  147069. 4,
  147070. };
  147071. static long _vq_lengthlist__44u3__p4_0[] = {
  147072. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  147073. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  147074. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  147075. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  147076. 10, 9,10, 9,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  147077. 9,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  147078. 12,12,13,14, 9, 9,10,12,12, 9,10,10,12,12, 9,10,
  147079. 10,12,13,11,12,11,14,13,12,12,12,14,13, 5, 7, 7,
  147080. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  147081. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  147082. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  147083. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147084. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  147085. 13,13,10,11,11,13,13,12,12,13,12,15,12,13,13,15,
  147086. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  147087. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  147088. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  147089. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  147090. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  147091. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  147092. 11,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  147093. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  147094. 11,12,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  147095. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  147096. 13, 9,10,10,13,13,12,13,13,15,14,12,12,12,14,13,
  147097. 9,10,10,13,12,10,11,11,13,13,10,11,11,14,12,13,
  147098. 13,14,14,16,12,13,13,15,15, 9,10,10,13,13,10,11,
  147099. 10,14,13,10,11,11,13,14,12,14,13,15,14,13,13,13,
  147100. 15,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  147101. 14,14,12,15,12,16,14,15,15,17,15,11,12,12,14,14,
  147102. 11,13,11,15,14,12,13,13,15,15,13,15,12,17,13,14,
  147103. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  147104. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  147105. 13,12,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  147106. 15,12,12,13,14,16, 9,10,10,13,13,10,11,11,13,14,
  147107. 10,11,11,14,13,12,13,13,14,15,13,14,13,16,14,11,
  147108. 12,12,14,14,12,13,13,15,14,11,12,13,14,15,14,15,
  147109. 15,16,16,13,13,15,13,16,11,12,12,14,15,12,13,13,
  147110. 14,15,11,13,12,15,14,14,15,15,16,16,14,15,12,16,
  147111. 13,
  147112. };
  147113. static float _vq_quantthresh__44u3__p4_0[] = {
  147114. -1.5, -0.5, 0.5, 1.5,
  147115. };
  147116. static long _vq_quantmap__44u3__p4_0[] = {
  147117. 3, 1, 0, 2, 4,
  147118. };
  147119. static encode_aux_threshmatch _vq_auxt__44u3__p4_0 = {
  147120. _vq_quantthresh__44u3__p4_0,
  147121. _vq_quantmap__44u3__p4_0,
  147122. 5,
  147123. 5
  147124. };
  147125. static static_codebook _44u3__p4_0 = {
  147126. 4, 625,
  147127. _vq_lengthlist__44u3__p4_0,
  147128. 1, -533725184, 1611661312, 3, 0,
  147129. _vq_quantlist__44u3__p4_0,
  147130. NULL,
  147131. &_vq_auxt__44u3__p4_0,
  147132. NULL,
  147133. 0
  147134. };
  147135. static long _vq_quantlist__44u3__p5_0[] = {
  147136. 4,
  147137. 3,
  147138. 5,
  147139. 2,
  147140. 6,
  147141. 1,
  147142. 7,
  147143. 0,
  147144. 8,
  147145. };
  147146. static long _vq_lengthlist__44u3__p5_0[] = {
  147147. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  147148. 10,10, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  147149. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,10, 7, 8, 8,
  147150. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  147151. 10,10,11,10,11,11,12,12, 9,10,10,10,10,11,11,12,
  147152. 12,
  147153. };
  147154. static float _vq_quantthresh__44u3__p5_0[] = {
  147155. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147156. };
  147157. static long _vq_quantmap__44u3__p5_0[] = {
  147158. 7, 5, 3, 1, 0, 2, 4, 6,
  147159. 8,
  147160. };
  147161. static encode_aux_threshmatch _vq_auxt__44u3__p5_0 = {
  147162. _vq_quantthresh__44u3__p5_0,
  147163. _vq_quantmap__44u3__p5_0,
  147164. 9,
  147165. 9
  147166. };
  147167. static static_codebook _44u3__p5_0 = {
  147168. 2, 81,
  147169. _vq_lengthlist__44u3__p5_0,
  147170. 1, -531628032, 1611661312, 4, 0,
  147171. _vq_quantlist__44u3__p5_0,
  147172. NULL,
  147173. &_vq_auxt__44u3__p5_0,
  147174. NULL,
  147175. 0
  147176. };
  147177. static long _vq_quantlist__44u3__p6_0[] = {
  147178. 6,
  147179. 5,
  147180. 7,
  147181. 4,
  147182. 8,
  147183. 3,
  147184. 9,
  147185. 2,
  147186. 10,
  147187. 1,
  147188. 11,
  147189. 0,
  147190. 12,
  147191. };
  147192. static long _vq_lengthlist__44u3__p6_0[] = {
  147193. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,13,14, 4, 6, 5,
  147194. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  147195. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  147196. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  147197. 15, 8, 9, 9,11,10,11,11,12,12,13,13,15,16, 8, 9,
  147198. 9,10,11,11,11,12,12,13,13,16,16,10,10,11,11,11,
  147199. 12,12,13,13,13,14,17,16, 9,10,11,12,11,12,12,13,
  147200. 13,13,13,16,18,11,12,11,12,12,13,13,13,14,15,14,
  147201. 17,17,11,11,12,12,12,13,13,13,14,14,15,18,17,14,
  147202. 15,15,15,15,16,16,17,17,19,18, 0,20,14,15,14,15,
  147203. 15,16,16,16,17,18,16,20,18,
  147204. };
  147205. static float _vq_quantthresh__44u3__p6_0[] = {
  147206. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147207. 12.5, 17.5, 22.5, 27.5,
  147208. };
  147209. static long _vq_quantmap__44u3__p6_0[] = {
  147210. 11, 9, 7, 5, 3, 1, 0, 2,
  147211. 4, 6, 8, 10, 12,
  147212. };
  147213. static encode_aux_threshmatch _vq_auxt__44u3__p6_0 = {
  147214. _vq_quantthresh__44u3__p6_0,
  147215. _vq_quantmap__44u3__p6_0,
  147216. 13,
  147217. 13
  147218. };
  147219. static static_codebook _44u3__p6_0 = {
  147220. 2, 169,
  147221. _vq_lengthlist__44u3__p6_0,
  147222. 1, -526516224, 1616117760, 4, 0,
  147223. _vq_quantlist__44u3__p6_0,
  147224. NULL,
  147225. &_vq_auxt__44u3__p6_0,
  147226. NULL,
  147227. 0
  147228. };
  147229. static long _vq_quantlist__44u3__p6_1[] = {
  147230. 2,
  147231. 1,
  147232. 3,
  147233. 0,
  147234. 4,
  147235. };
  147236. static long _vq_lengthlist__44u3__p6_1[] = {
  147237. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  147238. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  147239. };
  147240. static float _vq_quantthresh__44u3__p6_1[] = {
  147241. -1.5, -0.5, 0.5, 1.5,
  147242. };
  147243. static long _vq_quantmap__44u3__p6_1[] = {
  147244. 3, 1, 0, 2, 4,
  147245. };
  147246. static encode_aux_threshmatch _vq_auxt__44u3__p6_1 = {
  147247. _vq_quantthresh__44u3__p6_1,
  147248. _vq_quantmap__44u3__p6_1,
  147249. 5,
  147250. 5
  147251. };
  147252. static static_codebook _44u3__p6_1 = {
  147253. 2, 25,
  147254. _vq_lengthlist__44u3__p6_1,
  147255. 1, -533725184, 1611661312, 3, 0,
  147256. _vq_quantlist__44u3__p6_1,
  147257. NULL,
  147258. &_vq_auxt__44u3__p6_1,
  147259. NULL,
  147260. 0
  147261. };
  147262. static long _vq_quantlist__44u3__p7_0[] = {
  147263. 4,
  147264. 3,
  147265. 5,
  147266. 2,
  147267. 6,
  147268. 1,
  147269. 7,
  147270. 0,
  147271. 8,
  147272. };
  147273. static long _vq_lengthlist__44u3__p7_0[] = {
  147274. 1, 3, 3,10,10,10,10,10,10, 4,10,10,10,10,10,10,
  147275. 10,10, 4,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  147276. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147277. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147278. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147279. 9,
  147280. };
  147281. static float _vq_quantthresh__44u3__p7_0[] = {
  147282. -892.5, -637.5, -382.5, -127.5, 127.5, 382.5, 637.5, 892.5,
  147283. };
  147284. static long _vq_quantmap__44u3__p7_0[] = {
  147285. 7, 5, 3, 1, 0, 2, 4, 6,
  147286. 8,
  147287. };
  147288. static encode_aux_threshmatch _vq_auxt__44u3__p7_0 = {
  147289. _vq_quantthresh__44u3__p7_0,
  147290. _vq_quantmap__44u3__p7_0,
  147291. 9,
  147292. 9
  147293. };
  147294. static static_codebook _44u3__p7_0 = {
  147295. 2, 81,
  147296. _vq_lengthlist__44u3__p7_0,
  147297. 1, -515907584, 1627381760, 4, 0,
  147298. _vq_quantlist__44u3__p7_0,
  147299. NULL,
  147300. &_vq_auxt__44u3__p7_0,
  147301. NULL,
  147302. 0
  147303. };
  147304. static long _vq_quantlist__44u3__p7_1[] = {
  147305. 7,
  147306. 6,
  147307. 8,
  147308. 5,
  147309. 9,
  147310. 4,
  147311. 10,
  147312. 3,
  147313. 11,
  147314. 2,
  147315. 12,
  147316. 1,
  147317. 13,
  147318. 0,
  147319. 14,
  147320. };
  147321. static long _vq_lengthlist__44u3__p7_1[] = {
  147322. 1, 4, 4, 6, 6, 7, 6, 8, 7, 9, 8,10, 9,11,11, 4,
  147323. 7, 7, 8, 7, 9, 9,10,10,11,11,11,11,12,12, 4, 7,
  147324. 7, 7, 7, 9, 9,10,10,11,11,12,12,12,11, 6, 8, 8,
  147325. 9, 9,10,10,11,11,12,12,13,12,13,13, 6, 8, 8, 9,
  147326. 9,10,11,11,11,12,12,13,14,13,13, 8, 9, 9,11,11,
  147327. 12,12,12,13,14,13,14,14,14,15, 8, 9, 9,11,11,11,
  147328. 12,13,14,13,14,15,17,14,15, 9,10,10,12,12,13,13,
  147329. 13,14,15,15,15,16,16,16, 9,11,11,12,12,13,13,14,
  147330. 14,14,15,16,16,16,16,10,12,12,13,13,14,14,15,15,
  147331. 15,16,17,17,17,17,10,12,11,13,13,15,14,15,14,16,
  147332. 17,16,16,16,16,11,13,12,14,14,14,14,15,16,17,16,
  147333. 17,17,17,17,11,13,12,14,14,14,15,17,16,17,17,17,
  147334. 17,17,17,12,13,13,15,16,15,16,17,17,16,16,17,17,
  147335. 17,17,12,13,13,15,15,15,16,17,17,17,16,17,16,17,
  147336. 17,
  147337. };
  147338. static float _vq_quantthresh__44u3__p7_1[] = {
  147339. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  147340. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  147341. };
  147342. static long _vq_quantmap__44u3__p7_1[] = {
  147343. 13, 11, 9, 7, 5, 3, 1, 0,
  147344. 2, 4, 6, 8, 10, 12, 14,
  147345. };
  147346. static encode_aux_threshmatch _vq_auxt__44u3__p7_1 = {
  147347. _vq_quantthresh__44u3__p7_1,
  147348. _vq_quantmap__44u3__p7_1,
  147349. 15,
  147350. 15
  147351. };
  147352. static static_codebook _44u3__p7_1 = {
  147353. 2, 225,
  147354. _vq_lengthlist__44u3__p7_1,
  147355. 1, -522338304, 1620115456, 4, 0,
  147356. _vq_quantlist__44u3__p7_1,
  147357. NULL,
  147358. &_vq_auxt__44u3__p7_1,
  147359. NULL,
  147360. 0
  147361. };
  147362. static long _vq_quantlist__44u3__p7_2[] = {
  147363. 8,
  147364. 7,
  147365. 9,
  147366. 6,
  147367. 10,
  147368. 5,
  147369. 11,
  147370. 4,
  147371. 12,
  147372. 3,
  147373. 13,
  147374. 2,
  147375. 14,
  147376. 1,
  147377. 15,
  147378. 0,
  147379. 16,
  147380. };
  147381. static long _vq_lengthlist__44u3__p7_2[] = {
  147382. 2, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  147383. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147384. 10,10, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  147385. 9,10, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147386. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  147387. 9,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147388. 10,10,10,10,10,10, 7, 8, 8, 9, 8, 9, 9, 9, 9,10,
  147389. 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147390. 9,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9,10,
  147391. 9,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  147392. 9,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  147393. 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,
  147394. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10,
  147395. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  147396. 10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,10,
  147397. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,
  147398. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147399. 9,10,10,10,10,10,10,10,10,10,10,10,11,11,11,10,
  147400. 11,
  147401. };
  147402. static float _vq_quantthresh__44u3__p7_2[] = {
  147403. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  147404. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  147405. };
  147406. static long _vq_quantmap__44u3__p7_2[] = {
  147407. 15, 13, 11, 9, 7, 5, 3, 1,
  147408. 0, 2, 4, 6, 8, 10, 12, 14,
  147409. 16,
  147410. };
  147411. static encode_aux_threshmatch _vq_auxt__44u3__p7_2 = {
  147412. _vq_quantthresh__44u3__p7_2,
  147413. _vq_quantmap__44u3__p7_2,
  147414. 17,
  147415. 17
  147416. };
  147417. static static_codebook _44u3__p7_2 = {
  147418. 2, 289,
  147419. _vq_lengthlist__44u3__p7_2,
  147420. 1, -529530880, 1611661312, 5, 0,
  147421. _vq_quantlist__44u3__p7_2,
  147422. NULL,
  147423. &_vq_auxt__44u3__p7_2,
  147424. NULL,
  147425. 0
  147426. };
  147427. static long _huff_lengthlist__44u3__short[] = {
  147428. 14,14,14,15,13,15,12,16,10, 8, 7, 9, 9, 8,12,16,
  147429. 10, 5, 4, 6, 5, 6, 9,16,14, 8, 6, 8, 7, 8,10,16,
  147430. 14, 7, 4, 6, 3, 5, 8,16,15, 9, 5, 7, 4, 4, 7,16,
  147431. 13,10, 6, 7, 4, 3, 4,13,13,12, 7, 9, 5, 5, 6,12,
  147432. };
  147433. static static_codebook _huff_book__44u3__short = {
  147434. 2, 64,
  147435. _huff_lengthlist__44u3__short,
  147436. 0, 0, 0, 0, 0,
  147437. NULL,
  147438. NULL,
  147439. NULL,
  147440. NULL,
  147441. 0
  147442. };
  147443. static long _huff_lengthlist__44u4__long[] = {
  147444. 3, 8,12,12,13,12,11,13, 5, 4, 6, 7, 8, 8, 9,13,
  147445. 9, 5, 4, 5, 5, 7, 9,13, 9, 6, 5, 6, 6, 7, 8,12,
  147446. 12, 7, 5, 6, 4, 5, 8,13,11, 7, 6, 6, 5, 5, 6,12,
  147447. 10, 8, 8, 7, 7, 5, 3, 8,10,12,13,12,12, 9, 6, 7,
  147448. };
  147449. static static_codebook _huff_book__44u4__long = {
  147450. 2, 64,
  147451. _huff_lengthlist__44u4__long,
  147452. 0, 0, 0, 0, 0,
  147453. NULL,
  147454. NULL,
  147455. NULL,
  147456. NULL,
  147457. 0
  147458. };
  147459. static long _vq_quantlist__44u4__p1_0[] = {
  147460. 1,
  147461. 0,
  147462. 2,
  147463. };
  147464. static long _vq_lengthlist__44u4__p1_0[] = {
  147465. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  147466. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  147467. 11, 8,11,11, 8,11,11,11,13,14,11,15,14, 8,11,11,
  147468. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  147469. 11,11,11,15,14,10,12,14, 8,11,11,11,14,14,11,14,
  147470. 13,
  147471. };
  147472. static float _vq_quantthresh__44u4__p1_0[] = {
  147473. -0.5, 0.5,
  147474. };
  147475. static long _vq_quantmap__44u4__p1_0[] = {
  147476. 1, 0, 2,
  147477. };
  147478. static encode_aux_threshmatch _vq_auxt__44u4__p1_0 = {
  147479. _vq_quantthresh__44u4__p1_0,
  147480. _vq_quantmap__44u4__p1_0,
  147481. 3,
  147482. 3
  147483. };
  147484. static static_codebook _44u4__p1_0 = {
  147485. 4, 81,
  147486. _vq_lengthlist__44u4__p1_0,
  147487. 1, -535822336, 1611661312, 2, 0,
  147488. _vq_quantlist__44u4__p1_0,
  147489. NULL,
  147490. &_vq_auxt__44u4__p1_0,
  147491. NULL,
  147492. 0
  147493. };
  147494. static long _vq_quantlist__44u4__p2_0[] = {
  147495. 1,
  147496. 0,
  147497. 2,
  147498. };
  147499. static long _vq_lengthlist__44u4__p2_0[] = {
  147500. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  147501. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 6, 8,
  147502. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147503. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 6, 8, 8, 6,
  147504. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  147505. 9,
  147506. };
  147507. static float _vq_quantthresh__44u4__p2_0[] = {
  147508. -0.5, 0.5,
  147509. };
  147510. static long _vq_quantmap__44u4__p2_0[] = {
  147511. 1, 0, 2,
  147512. };
  147513. static encode_aux_threshmatch _vq_auxt__44u4__p2_0 = {
  147514. _vq_quantthresh__44u4__p2_0,
  147515. _vq_quantmap__44u4__p2_0,
  147516. 3,
  147517. 3
  147518. };
  147519. static static_codebook _44u4__p2_0 = {
  147520. 4, 81,
  147521. _vq_lengthlist__44u4__p2_0,
  147522. 1, -535822336, 1611661312, 2, 0,
  147523. _vq_quantlist__44u4__p2_0,
  147524. NULL,
  147525. &_vq_auxt__44u4__p2_0,
  147526. NULL,
  147527. 0
  147528. };
  147529. static long _vq_quantlist__44u4__p3_0[] = {
  147530. 2,
  147531. 1,
  147532. 3,
  147533. 0,
  147534. 4,
  147535. };
  147536. static long _vq_lengthlist__44u4__p3_0[] = {
  147537. 2, 4, 4, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  147538. 10, 9,12,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  147539. 9,11,11, 7, 9, 9,11,11,10,12,11,14,14, 9,10,11,
  147540. 13,14, 5, 7, 7,10,10, 7, 9, 9,11,11, 7, 9, 9,11,
  147541. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  147542. 10,12,12,15,14, 9,11,11,15,14,13,14,14,17,17,12,
  147543. 14,14,16,16, 8,10,10,14,14, 9,11,11,14,15,10,12,
  147544. 12,14,15,12,14,13,16,16,13,14,15,15,18, 4, 7, 7,
  147545. 10,10, 7, 9, 9,12,11, 7, 9, 9,11,12,10,12,11,15,
  147546. 14,10,11,12,14,15, 7, 9, 9,12,12, 9,11,12,13,13,
  147547. 9,11,12,13,13,12,13,13,15,16,11,13,13,15,16, 7,
  147548. 9, 9,12,12, 9,11,10,13,12, 9,11,12,13,14,11,13,
  147549. 12,16,14,12,13,13,15,16,10,12,12,16,15,11,13,13,
  147550. 17,16,11,13,13,17,16,14,15,15,17,17,14,16,16,18,
  147551. 20, 9,11,11,15,16,11,13,12,16,16,11,13,13,16,17,
  147552. 14,15,14,18,16,14,16,16,17,20, 5, 7, 7,10,10, 7,
  147553. 9, 9,12,11, 7, 9,10,11,12,10,12,11,15,15,10,12,
  147554. 12,14,14, 7, 9, 9,12,12, 9,12,11,14,13, 9,10,11,
  147555. 12,13,12,13,14,16,16,11,12,13,14,16, 7, 9, 9,12,
  147556. 12, 9,12,11,13,13, 9,12,11,13,13,11,13,13,16,16,
  147557. 12,13,13,16,15, 9,11,11,16,14,11,13,13,16,16,11,
  147558. 12,13,16,16,14,16,16,17,17,13,14,15,16,17,10,12,
  147559. 12,15,15,11,13,13,16,17,11,13,13,16,16,14,16,15,
  147560. 19,19,14,15,15,17,18, 8,10,10,14,14,10,12,12,15,
  147561. 15,10,12,12,16,16,14,16,15,20,19,13,15,15,17,16,
  147562. 9,12,12,16,16,11,13,13,16,18,11,14,13,16,17,16,
  147563. 17,16,20, 0,15,16,18,18,20, 9,11,11,15,15,11,14,
  147564. 12,17,16,11,13,13,17,17,15,17,15,20,20,14,16,16,
  147565. 17, 0,13,15,14,18,16,14,15,16, 0,18,14,16,16, 0,
  147566. 0,18,16, 0, 0,20,16,18,18, 0, 0,12,14,14,17,18,
  147567. 13,15,14,20,18,14,16,15,19,19,16,20,16, 0,18,16,
  147568. 19,17,19, 0, 8,10,10,14,14,10,12,12,16,15,10,12,
  147569. 12,16,16,13,15,15,18,17,14,16,16,19, 0, 9,11,11,
  147570. 16,15,11,14,13,18,17,11,12,13,17,18,14,17,16,18,
  147571. 18,15,16,17,18,18, 9,12,12,16,16,11,13,13,16,18,
  147572. 11,14,13,17,17,15,16,16,18,20,16,17,17,20,20,12,
  147573. 14,14,18,17,14,16,16, 0,19,13,14,15,18, 0,16, 0,
  147574. 0, 0, 0,16,16, 0,19,20,13,15,14, 0, 0,14,16,16,
  147575. 18,19,14,16,15, 0,20,16,20,18, 0,20,17,20,17, 0,
  147576. 0,
  147577. };
  147578. static float _vq_quantthresh__44u4__p3_0[] = {
  147579. -1.5, -0.5, 0.5, 1.5,
  147580. };
  147581. static long _vq_quantmap__44u4__p3_0[] = {
  147582. 3, 1, 0, 2, 4,
  147583. };
  147584. static encode_aux_threshmatch _vq_auxt__44u4__p3_0 = {
  147585. _vq_quantthresh__44u4__p3_0,
  147586. _vq_quantmap__44u4__p3_0,
  147587. 5,
  147588. 5
  147589. };
  147590. static static_codebook _44u4__p3_0 = {
  147591. 4, 625,
  147592. _vq_lengthlist__44u4__p3_0,
  147593. 1, -533725184, 1611661312, 3, 0,
  147594. _vq_quantlist__44u4__p3_0,
  147595. NULL,
  147596. &_vq_auxt__44u4__p3_0,
  147597. NULL,
  147598. 0
  147599. };
  147600. static long _vq_quantlist__44u4__p4_0[] = {
  147601. 2,
  147602. 1,
  147603. 3,
  147604. 0,
  147605. 4,
  147606. };
  147607. static long _vq_lengthlist__44u4__p4_0[] = {
  147608. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  147609. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  147610. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  147611. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  147612. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  147613. 9,10,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  147614. 12,12,13,14, 9, 9,10,12,12, 9,10,10,13,13, 9,10,
  147615. 10,12,13,11,12,12,14,13,11,12,12,14,14, 5, 7, 7,
  147616. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  147617. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  147618. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  147619. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147620. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  147621. 13,14,10,11,11,14,13,12,12,13,12,15,12,13,13,15,
  147622. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  147623. 12,13,11,15,13,13,13,13,15,15, 5, 7, 7, 9, 9, 7,
  147624. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  147625. 11,12,13, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  147626. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  147627. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  147628. 11,12,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  147629. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  147630. 11,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  147631. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  147632. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  147633. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,13,13,
  147634. 13,14,14,16,13,13,13,15,15, 9,10,10,13,13,10,11,
  147635. 10,14,13,10,11,11,13,14,12,14,13,16,14,12,13,13,
  147636. 14,15,11,12,12,15,14,11,12,13,14,15,12,13,13,16,
  147637. 15,14,12,15,12,16,14,15,15,16,16,11,12,12,14,14,
  147638. 11,13,12,15,14,12,13,13,15,16,13,15,13,17,13,14,
  147639. 15,15,16,17, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  147640. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  147641. 13,12,10,11,11,14,13,10,10,11,13,14,13,13,13,15,
  147642. 15,12,13,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  147643. 10,11,11,14,14,13,13,13,15,15,13,14,13,16,14,11,
  147644. 12,12,15,14,12,13,13,16,15,11,12,13,14,15,14,15,
  147645. 15,17,16,13,13,15,13,16,11,12,13,14,15,13,13,13,
  147646. 15,16,11,13,12,15,14,14,15,15,16,16,14,15,12,17,
  147647. 13,
  147648. };
  147649. static float _vq_quantthresh__44u4__p4_0[] = {
  147650. -1.5, -0.5, 0.5, 1.5,
  147651. };
  147652. static long _vq_quantmap__44u4__p4_0[] = {
  147653. 3, 1, 0, 2, 4,
  147654. };
  147655. static encode_aux_threshmatch _vq_auxt__44u4__p4_0 = {
  147656. _vq_quantthresh__44u4__p4_0,
  147657. _vq_quantmap__44u4__p4_0,
  147658. 5,
  147659. 5
  147660. };
  147661. static static_codebook _44u4__p4_0 = {
  147662. 4, 625,
  147663. _vq_lengthlist__44u4__p4_0,
  147664. 1, -533725184, 1611661312, 3, 0,
  147665. _vq_quantlist__44u4__p4_0,
  147666. NULL,
  147667. &_vq_auxt__44u4__p4_0,
  147668. NULL,
  147669. 0
  147670. };
  147671. static long _vq_quantlist__44u4__p5_0[] = {
  147672. 4,
  147673. 3,
  147674. 5,
  147675. 2,
  147676. 6,
  147677. 1,
  147678. 7,
  147679. 0,
  147680. 8,
  147681. };
  147682. static long _vq_lengthlist__44u4__p5_0[] = {
  147683. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  147684. 10, 9, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  147685. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,11, 7, 8, 8,
  147686. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  147687. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  147688. 12,
  147689. };
  147690. static float _vq_quantthresh__44u4__p5_0[] = {
  147691. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147692. };
  147693. static long _vq_quantmap__44u4__p5_0[] = {
  147694. 7, 5, 3, 1, 0, 2, 4, 6,
  147695. 8,
  147696. };
  147697. static encode_aux_threshmatch _vq_auxt__44u4__p5_0 = {
  147698. _vq_quantthresh__44u4__p5_0,
  147699. _vq_quantmap__44u4__p5_0,
  147700. 9,
  147701. 9
  147702. };
  147703. static static_codebook _44u4__p5_0 = {
  147704. 2, 81,
  147705. _vq_lengthlist__44u4__p5_0,
  147706. 1, -531628032, 1611661312, 4, 0,
  147707. _vq_quantlist__44u4__p5_0,
  147708. NULL,
  147709. &_vq_auxt__44u4__p5_0,
  147710. NULL,
  147711. 0
  147712. };
  147713. static long _vq_quantlist__44u4__p6_0[] = {
  147714. 6,
  147715. 5,
  147716. 7,
  147717. 4,
  147718. 8,
  147719. 3,
  147720. 9,
  147721. 2,
  147722. 10,
  147723. 1,
  147724. 11,
  147725. 0,
  147726. 12,
  147727. };
  147728. static long _vq_lengthlist__44u4__p6_0[] = {
  147729. 1, 4, 4, 6, 6, 8, 8, 9, 9,11,10,13,13, 4, 6, 5,
  147730. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  147731. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  147732. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  147733. 15, 8, 9, 9,11,10,11,11,12,12,13,13,16,16, 8, 9,
  147734. 9,10,10,11,11,12,12,13,13,16,16,10,10,10,12,11,
  147735. 12,12,13,13,14,14,16,16,10,10,10,11,12,12,12,13,
  147736. 13,13,14,16,17,11,12,11,12,12,13,13,14,14,15,14,
  147737. 18,17,11,11,12,12,12,13,13,14,14,14,15,19,18,14,
  147738. 15,14,15,15,17,16,17,17,17,17,21, 0,14,15,15,16,
  147739. 16,16,16,17,17,18,17,20,21,
  147740. };
  147741. static float _vq_quantthresh__44u4__p6_0[] = {
  147742. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147743. 12.5, 17.5, 22.5, 27.5,
  147744. };
  147745. static long _vq_quantmap__44u4__p6_0[] = {
  147746. 11, 9, 7, 5, 3, 1, 0, 2,
  147747. 4, 6, 8, 10, 12,
  147748. };
  147749. static encode_aux_threshmatch _vq_auxt__44u4__p6_0 = {
  147750. _vq_quantthresh__44u4__p6_0,
  147751. _vq_quantmap__44u4__p6_0,
  147752. 13,
  147753. 13
  147754. };
  147755. static static_codebook _44u4__p6_0 = {
  147756. 2, 169,
  147757. _vq_lengthlist__44u4__p6_0,
  147758. 1, -526516224, 1616117760, 4, 0,
  147759. _vq_quantlist__44u4__p6_0,
  147760. NULL,
  147761. &_vq_auxt__44u4__p6_0,
  147762. NULL,
  147763. 0
  147764. };
  147765. static long _vq_quantlist__44u4__p6_1[] = {
  147766. 2,
  147767. 1,
  147768. 3,
  147769. 0,
  147770. 4,
  147771. };
  147772. static long _vq_lengthlist__44u4__p6_1[] = {
  147773. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  147774. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  147775. };
  147776. static float _vq_quantthresh__44u4__p6_1[] = {
  147777. -1.5, -0.5, 0.5, 1.5,
  147778. };
  147779. static long _vq_quantmap__44u4__p6_1[] = {
  147780. 3, 1, 0, 2, 4,
  147781. };
  147782. static encode_aux_threshmatch _vq_auxt__44u4__p6_1 = {
  147783. _vq_quantthresh__44u4__p6_1,
  147784. _vq_quantmap__44u4__p6_1,
  147785. 5,
  147786. 5
  147787. };
  147788. static static_codebook _44u4__p6_1 = {
  147789. 2, 25,
  147790. _vq_lengthlist__44u4__p6_1,
  147791. 1, -533725184, 1611661312, 3, 0,
  147792. _vq_quantlist__44u4__p6_1,
  147793. NULL,
  147794. &_vq_auxt__44u4__p6_1,
  147795. NULL,
  147796. 0
  147797. };
  147798. static long _vq_quantlist__44u4__p7_0[] = {
  147799. 6,
  147800. 5,
  147801. 7,
  147802. 4,
  147803. 8,
  147804. 3,
  147805. 9,
  147806. 2,
  147807. 10,
  147808. 1,
  147809. 11,
  147810. 0,
  147811. 12,
  147812. };
  147813. static long _vq_lengthlist__44u4__p7_0[] = {
  147814. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 3,12,11,
  147815. 12,12,12,12,12,12,12,12,12,12, 4,11,10,12,12,12,
  147816. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  147817. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  147818. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  147819. 12,12,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,11,11,11,11,11,11,11,
  147822. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147823. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147824. 11,11,11,11,11,11,11,11,11,
  147825. };
  147826. static float _vq_quantthresh__44u4__p7_0[] = {
  147827. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  147828. 637.5, 892.5, 1147.5, 1402.5,
  147829. };
  147830. static long _vq_quantmap__44u4__p7_0[] = {
  147831. 11, 9, 7, 5, 3, 1, 0, 2,
  147832. 4, 6, 8, 10, 12,
  147833. };
  147834. static encode_aux_threshmatch _vq_auxt__44u4__p7_0 = {
  147835. _vq_quantthresh__44u4__p7_0,
  147836. _vq_quantmap__44u4__p7_0,
  147837. 13,
  147838. 13
  147839. };
  147840. static static_codebook _44u4__p7_0 = {
  147841. 2, 169,
  147842. _vq_lengthlist__44u4__p7_0,
  147843. 1, -514332672, 1627381760, 4, 0,
  147844. _vq_quantlist__44u4__p7_0,
  147845. NULL,
  147846. &_vq_auxt__44u4__p7_0,
  147847. NULL,
  147848. 0
  147849. };
  147850. static long _vq_quantlist__44u4__p7_1[] = {
  147851. 7,
  147852. 6,
  147853. 8,
  147854. 5,
  147855. 9,
  147856. 4,
  147857. 10,
  147858. 3,
  147859. 11,
  147860. 2,
  147861. 12,
  147862. 1,
  147863. 13,
  147864. 0,
  147865. 14,
  147866. };
  147867. static long _vq_lengthlist__44u4__p7_1[] = {
  147868. 1, 4, 4, 6, 6, 7, 7, 9, 8,10, 8,10, 9,11,11, 4,
  147869. 7, 6, 8, 7, 9, 9,10,10,11,10,11,10,12,10, 4, 6,
  147870. 7, 8, 8, 9, 9,10,10,11,11,11,11,12,12, 6, 8, 8,
  147871. 10, 9,11,10,12,11,12,12,12,12,13,13, 6, 8, 8,10,
  147872. 10,10,11,11,11,12,12,13,12,13,13, 8, 9, 9,11,11,
  147873. 12,11,12,12,13,13,13,13,13,13, 8, 9, 9,11,11,11,
  147874. 12,12,12,13,13,13,13,13,13, 9,10,10,12,11,13,13,
  147875. 13,13,14,13,13,14,14,14, 9,10,11,11,12,12,13,13,
  147876. 13,13,13,14,15,14,14,10,11,11,12,12,13,13,14,14,
  147877. 14,14,14,15,16,16,10,11,11,12,13,13,13,13,15,14,
  147878. 14,15,16,15,16,10,12,12,13,13,14,14,14,15,15,15,
  147879. 15,15,15,16,11,12,12,13,13,14,14,14,15,15,15,16,
  147880. 15,17,16,11,12,12,13,13,13,15,15,14,16,16,16,16,
  147881. 16,17,11,12,12,13,13,14,14,15,14,15,15,17,17,16,
  147882. 16,
  147883. };
  147884. static float _vq_quantthresh__44u4__p7_1[] = {
  147885. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  147886. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  147887. };
  147888. static long _vq_quantmap__44u4__p7_1[] = {
  147889. 13, 11, 9, 7, 5, 3, 1, 0,
  147890. 2, 4, 6, 8, 10, 12, 14,
  147891. };
  147892. static encode_aux_threshmatch _vq_auxt__44u4__p7_1 = {
  147893. _vq_quantthresh__44u4__p7_1,
  147894. _vq_quantmap__44u4__p7_1,
  147895. 15,
  147896. 15
  147897. };
  147898. static static_codebook _44u4__p7_1 = {
  147899. 2, 225,
  147900. _vq_lengthlist__44u4__p7_1,
  147901. 1, -522338304, 1620115456, 4, 0,
  147902. _vq_quantlist__44u4__p7_1,
  147903. NULL,
  147904. &_vq_auxt__44u4__p7_1,
  147905. NULL,
  147906. 0
  147907. };
  147908. static long _vq_quantlist__44u4__p7_2[] = {
  147909. 8,
  147910. 7,
  147911. 9,
  147912. 6,
  147913. 10,
  147914. 5,
  147915. 11,
  147916. 4,
  147917. 12,
  147918. 3,
  147919. 13,
  147920. 2,
  147921. 14,
  147922. 1,
  147923. 15,
  147924. 0,
  147925. 16,
  147926. };
  147927. static long _vq_lengthlist__44u4__p7_2[] = {
  147928. 2, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  147929. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147930. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  147931. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147932. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  147933. 9,10, 9,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147934. 10,10,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  147935. 9,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  147936. 10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  147937. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,
  147938. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  147939. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  147940. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  147941. 10,10,10,10,10,10,10,10,10,11,10,10,10, 9, 9, 9,
  147942. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  147943. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  147944. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147945. 9,10, 9,10,10,10,10,10,10,10,10,10,10,11,10,10,
  147946. 10,
  147947. };
  147948. static float _vq_quantthresh__44u4__p7_2[] = {
  147949. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  147950. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  147951. };
  147952. static long _vq_quantmap__44u4__p7_2[] = {
  147953. 15, 13, 11, 9, 7, 5, 3, 1,
  147954. 0, 2, 4, 6, 8, 10, 12, 14,
  147955. 16,
  147956. };
  147957. static encode_aux_threshmatch _vq_auxt__44u4__p7_2 = {
  147958. _vq_quantthresh__44u4__p7_2,
  147959. _vq_quantmap__44u4__p7_2,
  147960. 17,
  147961. 17
  147962. };
  147963. static static_codebook _44u4__p7_2 = {
  147964. 2, 289,
  147965. _vq_lengthlist__44u4__p7_2,
  147966. 1, -529530880, 1611661312, 5, 0,
  147967. _vq_quantlist__44u4__p7_2,
  147968. NULL,
  147969. &_vq_auxt__44u4__p7_2,
  147970. NULL,
  147971. 0
  147972. };
  147973. static long _huff_lengthlist__44u4__short[] = {
  147974. 14,17,15,17,16,14,13,16,10, 7, 7,10,13,10,15,16,
  147975. 9, 4, 4, 6, 5, 7, 9,16,12, 8, 7, 8, 8, 8,11,16,
  147976. 14, 7, 4, 6, 3, 5, 8,15,13, 8, 5, 7, 4, 5, 7,16,
  147977. 12, 9, 6, 8, 3, 3, 5,16,14,13, 7,10, 5, 5, 7,15,
  147978. };
  147979. static static_codebook _huff_book__44u4__short = {
  147980. 2, 64,
  147981. _huff_lengthlist__44u4__short,
  147982. 0, 0, 0, 0, 0,
  147983. NULL,
  147984. NULL,
  147985. NULL,
  147986. NULL,
  147987. 0
  147988. };
  147989. static long _huff_lengthlist__44u5__long[] = {
  147990. 3, 8,13,12,14,12,16,11,13,14, 5, 4, 5, 6, 7, 8,
  147991. 10, 9,12,15,10, 5, 5, 5, 6, 8, 9, 9,13,15,10, 5,
  147992. 5, 6, 6, 7, 8, 8,11,13,12, 7, 5, 6, 4, 6, 7, 7,
  147993. 11,14,11, 7, 7, 6, 6, 6, 7, 6,10,14,14, 9, 8, 8,
  147994. 6, 7, 7, 7,11,16,11, 8, 8, 7, 6, 6, 7, 4, 7,12,
  147995. 10,10,12,10,10, 9,10, 5, 6, 9,10,12,15,13,14,14,
  147996. 14, 8, 7, 8,
  147997. };
  147998. static static_codebook _huff_book__44u5__long = {
  147999. 2, 100,
  148000. _huff_lengthlist__44u5__long,
  148001. 0, 0, 0, 0, 0,
  148002. NULL,
  148003. NULL,
  148004. NULL,
  148005. NULL,
  148006. 0
  148007. };
  148008. static long _vq_quantlist__44u5__p1_0[] = {
  148009. 1,
  148010. 0,
  148011. 2,
  148012. };
  148013. static long _vq_lengthlist__44u5__p1_0[] = {
  148014. 1, 4, 4, 5, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  148015. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  148016. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  148017. 10,13,11,10,13,13, 4, 8, 8, 8,11,10, 8,10,10, 7,
  148018. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  148019. 12,
  148020. };
  148021. static float _vq_quantthresh__44u5__p1_0[] = {
  148022. -0.5, 0.5,
  148023. };
  148024. static long _vq_quantmap__44u5__p1_0[] = {
  148025. 1, 0, 2,
  148026. };
  148027. static encode_aux_threshmatch _vq_auxt__44u5__p1_0 = {
  148028. _vq_quantthresh__44u5__p1_0,
  148029. _vq_quantmap__44u5__p1_0,
  148030. 3,
  148031. 3
  148032. };
  148033. static static_codebook _44u5__p1_0 = {
  148034. 4, 81,
  148035. _vq_lengthlist__44u5__p1_0,
  148036. 1, -535822336, 1611661312, 2, 0,
  148037. _vq_quantlist__44u5__p1_0,
  148038. NULL,
  148039. &_vq_auxt__44u5__p1_0,
  148040. NULL,
  148041. 0
  148042. };
  148043. static long _vq_quantlist__44u5__p2_0[] = {
  148044. 1,
  148045. 0,
  148046. 2,
  148047. };
  148048. static long _vq_lengthlist__44u5__p2_0[] = {
  148049. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  148050. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  148051. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  148052. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  148053. 8, 7, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  148054. 9,
  148055. };
  148056. static float _vq_quantthresh__44u5__p2_0[] = {
  148057. -0.5, 0.5,
  148058. };
  148059. static long _vq_quantmap__44u5__p2_0[] = {
  148060. 1, 0, 2,
  148061. };
  148062. static encode_aux_threshmatch _vq_auxt__44u5__p2_0 = {
  148063. _vq_quantthresh__44u5__p2_0,
  148064. _vq_quantmap__44u5__p2_0,
  148065. 3,
  148066. 3
  148067. };
  148068. static static_codebook _44u5__p2_0 = {
  148069. 4, 81,
  148070. _vq_lengthlist__44u5__p2_0,
  148071. 1, -535822336, 1611661312, 2, 0,
  148072. _vq_quantlist__44u5__p2_0,
  148073. NULL,
  148074. &_vq_auxt__44u5__p2_0,
  148075. NULL,
  148076. 0
  148077. };
  148078. static long _vq_quantlist__44u5__p3_0[] = {
  148079. 2,
  148080. 1,
  148081. 3,
  148082. 0,
  148083. 4,
  148084. };
  148085. static long _vq_lengthlist__44u5__p3_0[] = {
  148086. 2, 4, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  148087. 10, 9,13,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  148088. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  148089. 13,14, 5, 7, 7, 9,10, 7, 9, 8,11,11, 7, 9, 9,11,
  148090. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,13,13,
  148091. 10,11,11,15,14, 9,11,11,14,14,13,14,14,17,16,12,
  148092. 13,13,15,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  148093. 11,14,15,12,14,13,16,16,13,15,14,15,17, 5, 7, 7,
  148094. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,
  148095. 14,10,11,12,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  148096. 9,11,11,13,13,12,13,13,15,16,11,12,13,15,16, 6,
  148097. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,14,11,13,
  148098. 12,16,14,11,13,13,16,17,10,12,11,15,15,11,13,13,
  148099. 16,16,11,13,13,17,16,14,15,15,17,17,14,16,16,17,
  148100. 18, 9,11,11,14,15,10,12,12,15,15,11,13,13,16,17,
  148101. 13,15,13,17,15,14,15,16,18, 0, 5, 7, 7,10,10, 7,
  148102. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  148103. 12,14,15, 6, 9, 9,12,11, 9,11,11,13,13, 8,10,11,
  148104. 12,13,11,13,13,16,15,11,12,13,14,15, 7, 9, 9,11,
  148105. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,16,
  148106. 11,13,13,15,14, 9,11,11,15,14,11,13,13,17,15,10,
  148107. 12,12,15,15,14,16,16,17,17,13,13,15,15,17,10,11,
  148108. 12,15,15,11,13,13,16,16,11,13,13,15,15,14,15,15,
  148109. 18,18,14,15,15,17,17, 8,10,10,13,13,10,12,11,15,
  148110. 15,10,11,12,15,15,14,15,15,18,18,13,14,14,18,18,
  148111. 9,11,11,15,16,11,13,13,17,17,11,13,13,16,16,15,
  148112. 15,16,17, 0,14,15,17, 0, 0, 9,11,11,15,15,10,13,
  148113. 12,18,16,11,13,13,15,16,14,16,15,20,20,14,15,16,
  148114. 17, 0,13,14,14,20,16,14,15,16,19,18,14,15,15,19,
  148115. 0,18,16, 0,20,20,16,18,18, 0, 0,12,14,14,18,18,
  148116. 13,15,14,18,16,14,15,16,18,20,16,19,16, 0,17,17,
  148117. 18,18,19, 0, 8,10,10,14,14,10,11,11,14,15,10,11,
  148118. 12,15,15,13,15,14,19,17,13,15,15,17, 0, 9,11,11,
  148119. 16,15,11,13,13,16,16,10,12,13,15,17,14,16,16,18,
  148120. 18,14,15,15,18, 0, 9,11,11,15,15,11,13,13,16,17,
  148121. 11,13,13,18,17,14,18,16,18,18,15,17,17,18, 0,12,
  148122. 14,14,18,18,14,15,15,20, 0,13,14,15,17, 0,16,18,
  148123. 17, 0, 0,16,16, 0,17,20,12,14,14,18,18,14,16,15,
  148124. 0,18,14,16,15,18, 0,16,19,17, 0, 0,17,18,16, 0,
  148125. 0,
  148126. };
  148127. static float _vq_quantthresh__44u5__p3_0[] = {
  148128. -1.5, -0.5, 0.5, 1.5,
  148129. };
  148130. static long _vq_quantmap__44u5__p3_0[] = {
  148131. 3, 1, 0, 2, 4,
  148132. };
  148133. static encode_aux_threshmatch _vq_auxt__44u5__p3_0 = {
  148134. _vq_quantthresh__44u5__p3_0,
  148135. _vq_quantmap__44u5__p3_0,
  148136. 5,
  148137. 5
  148138. };
  148139. static static_codebook _44u5__p3_0 = {
  148140. 4, 625,
  148141. _vq_lengthlist__44u5__p3_0,
  148142. 1, -533725184, 1611661312, 3, 0,
  148143. _vq_quantlist__44u5__p3_0,
  148144. NULL,
  148145. &_vq_auxt__44u5__p3_0,
  148146. NULL,
  148147. 0
  148148. };
  148149. static long _vq_quantlist__44u5__p4_0[] = {
  148150. 2,
  148151. 1,
  148152. 3,
  148153. 0,
  148154. 4,
  148155. };
  148156. static long _vq_lengthlist__44u5__p4_0[] = {
  148157. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  148158. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  148159. 8,10,10, 6, 7, 8, 9,10, 9,10,10,11,12, 9, 9,10,
  148160. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  148161. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,12,11,
  148162. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  148163. 11,12,13,14, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  148164. 10,12,12,11,12,11,14,13,11,12,12,13,13, 5, 7, 7,
  148165. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  148166. 12, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,10,11,
  148167. 8, 9, 9,11,11,10,10,11,11,13,10,11,11,12,13, 6,
  148168. 7, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  148169. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  148170. 12,13,10,11,11,13,13,12,11,13,12,15,12,13,13,14,
  148171. 15, 9,10,10,12,12, 9,11,10,13,12,10,11,11,13,13,
  148172. 11,13,11,14,12,12,13,13,14,15, 5, 7, 7, 9, 9, 7,
  148173. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  148174. 10,12,12, 6, 8, 7,10,10, 8, 9, 9,11,11, 7, 8, 9,
  148175. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  148176. 10, 8, 9, 9,11,11, 8, 9, 8,11,10,10,11,11,13,12,
  148177. 10,11,10,13,11, 9,10,10,12,12,10,11,11,13,12, 9,
  148178. 10,10,12,13,12,13,13,14,15,11,11,13,12,14, 9,10,
  148179. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,13,13,
  148180. 14,14,12,13,11,14,12, 8, 9, 9,12,12, 9,10,10,12,
  148181. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,14,13,
  148182. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  148183. 12,13,14,15,12,13,13,15,14, 9,10,10,12,12,10,11,
  148184. 10,13,12,10,11,11,12,13,12,13,12,15,13,12,13,13,
  148185. 14,15,11,12,12,14,13,11,12,12,14,15,12,13,13,15,
  148186. 14,13,12,14,12,16,13,14,14,15,15,11,11,12,14,14,
  148187. 11,12,11,14,13,12,13,13,14,15,13,14,12,16,12,14,
  148188. 14,15,16,16, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  148189. 10,12,13,11,12,12,13,13,12,12,13,14,14, 9,10,10,
  148190. 12,12,10,11,10,13,12,10,10,11,12,13,12,13,13,15,
  148191. 14,12,12,13,13,15, 9,10,10,12,13,10,11,11,12,13,
  148192. 10,11,11,13,13,12,13,13,14,15,12,13,12,15,14,11,
  148193. 12,11,14,13,12,13,13,15,14,11,11,12,13,14,14,15,
  148194. 14,16,15,13,12,14,13,16,11,12,12,13,14,12,13,13,
  148195. 14,15,11,12,11,14,14,14,14,14,15,16,13,15,12,16,
  148196. 12,
  148197. };
  148198. static float _vq_quantthresh__44u5__p4_0[] = {
  148199. -1.5, -0.5, 0.5, 1.5,
  148200. };
  148201. static long _vq_quantmap__44u5__p4_0[] = {
  148202. 3, 1, 0, 2, 4,
  148203. };
  148204. static encode_aux_threshmatch _vq_auxt__44u5__p4_0 = {
  148205. _vq_quantthresh__44u5__p4_0,
  148206. _vq_quantmap__44u5__p4_0,
  148207. 5,
  148208. 5
  148209. };
  148210. static static_codebook _44u5__p4_0 = {
  148211. 4, 625,
  148212. _vq_lengthlist__44u5__p4_0,
  148213. 1, -533725184, 1611661312, 3, 0,
  148214. _vq_quantlist__44u5__p4_0,
  148215. NULL,
  148216. &_vq_auxt__44u5__p4_0,
  148217. NULL,
  148218. 0
  148219. };
  148220. static long _vq_quantlist__44u5__p5_0[] = {
  148221. 4,
  148222. 3,
  148223. 5,
  148224. 2,
  148225. 6,
  148226. 1,
  148227. 7,
  148228. 0,
  148229. 8,
  148230. };
  148231. static long _vq_lengthlist__44u5__p5_0[] = {
  148232. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  148233. 11,10, 3, 5, 5, 7, 8, 8, 8,10,11, 6, 8, 7,10, 9,
  148234. 10,10,11,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  148235. 10,10,11,11,13,12, 8, 8, 9, 9,10,11,11,12,13,10,
  148236. 11,10,12,11,13,12,14,14,10,10,11,11,12,12,13,14,
  148237. 14,
  148238. };
  148239. static float _vq_quantthresh__44u5__p5_0[] = {
  148240. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148241. };
  148242. static long _vq_quantmap__44u5__p5_0[] = {
  148243. 7, 5, 3, 1, 0, 2, 4, 6,
  148244. 8,
  148245. };
  148246. static encode_aux_threshmatch _vq_auxt__44u5__p5_0 = {
  148247. _vq_quantthresh__44u5__p5_0,
  148248. _vq_quantmap__44u5__p5_0,
  148249. 9,
  148250. 9
  148251. };
  148252. static static_codebook _44u5__p5_0 = {
  148253. 2, 81,
  148254. _vq_lengthlist__44u5__p5_0,
  148255. 1, -531628032, 1611661312, 4, 0,
  148256. _vq_quantlist__44u5__p5_0,
  148257. NULL,
  148258. &_vq_auxt__44u5__p5_0,
  148259. NULL,
  148260. 0
  148261. };
  148262. static long _vq_quantlist__44u5__p6_0[] = {
  148263. 4,
  148264. 3,
  148265. 5,
  148266. 2,
  148267. 6,
  148268. 1,
  148269. 7,
  148270. 0,
  148271. 8,
  148272. };
  148273. static long _vq_lengthlist__44u5__p6_0[] = {
  148274. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  148275. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  148276. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  148277. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  148278. 9, 9,10,10,11,10,11,11, 9, 9, 9,10,10,11,10,11,
  148279. 11,
  148280. };
  148281. static float _vq_quantthresh__44u5__p6_0[] = {
  148282. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148283. };
  148284. static long _vq_quantmap__44u5__p6_0[] = {
  148285. 7, 5, 3, 1, 0, 2, 4, 6,
  148286. 8,
  148287. };
  148288. static encode_aux_threshmatch _vq_auxt__44u5__p6_0 = {
  148289. _vq_quantthresh__44u5__p6_0,
  148290. _vq_quantmap__44u5__p6_0,
  148291. 9,
  148292. 9
  148293. };
  148294. static static_codebook _44u5__p6_0 = {
  148295. 2, 81,
  148296. _vq_lengthlist__44u5__p6_0,
  148297. 1, -531628032, 1611661312, 4, 0,
  148298. _vq_quantlist__44u5__p6_0,
  148299. NULL,
  148300. &_vq_auxt__44u5__p6_0,
  148301. NULL,
  148302. 0
  148303. };
  148304. static long _vq_quantlist__44u5__p7_0[] = {
  148305. 1,
  148306. 0,
  148307. 2,
  148308. };
  148309. static long _vq_lengthlist__44u5__p7_0[] = {
  148310. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,11,10, 7,
  148311. 11,10, 5, 9, 9, 7,10,10, 8,10,11, 4, 9, 9, 9,12,
  148312. 12, 9,12,12, 8,12,12,11,12,12,10,12,13, 7,12,12,
  148313. 11,12,12,10,12,13, 4, 9, 9, 9,12,12, 9,12,12, 7,
  148314. 12,11,10,13,13,11,12,12, 7,12,12,10,13,13,11,12,
  148315. 12,
  148316. };
  148317. static float _vq_quantthresh__44u5__p7_0[] = {
  148318. -5.5, 5.5,
  148319. };
  148320. static long _vq_quantmap__44u5__p7_0[] = {
  148321. 1, 0, 2,
  148322. };
  148323. static encode_aux_threshmatch _vq_auxt__44u5__p7_0 = {
  148324. _vq_quantthresh__44u5__p7_0,
  148325. _vq_quantmap__44u5__p7_0,
  148326. 3,
  148327. 3
  148328. };
  148329. static static_codebook _44u5__p7_0 = {
  148330. 4, 81,
  148331. _vq_lengthlist__44u5__p7_0,
  148332. 1, -529137664, 1618345984, 2, 0,
  148333. _vq_quantlist__44u5__p7_0,
  148334. NULL,
  148335. &_vq_auxt__44u5__p7_0,
  148336. NULL,
  148337. 0
  148338. };
  148339. static long _vq_quantlist__44u5__p7_1[] = {
  148340. 5,
  148341. 4,
  148342. 6,
  148343. 3,
  148344. 7,
  148345. 2,
  148346. 8,
  148347. 1,
  148348. 9,
  148349. 0,
  148350. 10,
  148351. };
  148352. static long _vq_lengthlist__44u5__p7_1[] = {
  148353. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  148354. 8, 8, 9, 8, 8, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 8,
  148355. 9, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  148356. 8, 9, 9, 9, 9, 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  148357. 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  148358. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  148359. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  148360. 9, 9, 9, 9, 9,10,10,10,10,
  148361. };
  148362. static float _vq_quantthresh__44u5__p7_1[] = {
  148363. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  148364. 3.5, 4.5,
  148365. };
  148366. static long _vq_quantmap__44u5__p7_1[] = {
  148367. 9, 7, 5, 3, 1, 0, 2, 4,
  148368. 6, 8, 10,
  148369. };
  148370. static encode_aux_threshmatch _vq_auxt__44u5__p7_1 = {
  148371. _vq_quantthresh__44u5__p7_1,
  148372. _vq_quantmap__44u5__p7_1,
  148373. 11,
  148374. 11
  148375. };
  148376. static static_codebook _44u5__p7_1 = {
  148377. 2, 121,
  148378. _vq_lengthlist__44u5__p7_1,
  148379. 1, -531365888, 1611661312, 4, 0,
  148380. _vq_quantlist__44u5__p7_1,
  148381. NULL,
  148382. &_vq_auxt__44u5__p7_1,
  148383. NULL,
  148384. 0
  148385. };
  148386. static long _vq_quantlist__44u5__p8_0[] = {
  148387. 5,
  148388. 4,
  148389. 6,
  148390. 3,
  148391. 7,
  148392. 2,
  148393. 8,
  148394. 1,
  148395. 9,
  148396. 0,
  148397. 10,
  148398. };
  148399. static long _vq_lengthlist__44u5__p8_0[] = {
  148400. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  148401. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  148402. 11, 6, 8, 7, 9, 9,10,10,11,11,13,12, 6, 8, 8, 9,
  148403. 9,10,10,11,11,12,13, 8, 9, 9,10,10,12,12,13,12,
  148404. 14,13, 8, 9, 9,10,10,12,12,13,13,14,14, 9,11,11,
  148405. 12,12,13,13,14,14,15,14, 9,11,11,12,12,13,13,14,
  148406. 14,15,14,11,12,12,13,13,14,14,15,14,15,14,11,11,
  148407. 12,13,13,14,14,14,14,15,15,
  148408. };
  148409. static float _vq_quantthresh__44u5__p8_0[] = {
  148410. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  148411. 38.5, 49.5,
  148412. };
  148413. static long _vq_quantmap__44u5__p8_0[] = {
  148414. 9, 7, 5, 3, 1, 0, 2, 4,
  148415. 6, 8, 10,
  148416. };
  148417. static encode_aux_threshmatch _vq_auxt__44u5__p8_0 = {
  148418. _vq_quantthresh__44u5__p8_0,
  148419. _vq_quantmap__44u5__p8_0,
  148420. 11,
  148421. 11
  148422. };
  148423. static static_codebook _44u5__p8_0 = {
  148424. 2, 121,
  148425. _vq_lengthlist__44u5__p8_0,
  148426. 1, -524582912, 1618345984, 4, 0,
  148427. _vq_quantlist__44u5__p8_0,
  148428. NULL,
  148429. &_vq_auxt__44u5__p8_0,
  148430. NULL,
  148431. 0
  148432. };
  148433. static long _vq_quantlist__44u5__p8_1[] = {
  148434. 5,
  148435. 4,
  148436. 6,
  148437. 3,
  148438. 7,
  148439. 2,
  148440. 8,
  148441. 1,
  148442. 9,
  148443. 0,
  148444. 10,
  148445. };
  148446. static long _vq_lengthlist__44u5__p8_1[] = {
  148447. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 6,
  148448. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  148449. 8, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 6, 6, 7, 7,
  148450. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  148451. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8,
  148452. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  148453. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  148454. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  148455. };
  148456. static float _vq_quantthresh__44u5__p8_1[] = {
  148457. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  148458. 3.5, 4.5,
  148459. };
  148460. static long _vq_quantmap__44u5__p8_1[] = {
  148461. 9, 7, 5, 3, 1, 0, 2, 4,
  148462. 6, 8, 10,
  148463. };
  148464. static encode_aux_threshmatch _vq_auxt__44u5__p8_1 = {
  148465. _vq_quantthresh__44u5__p8_1,
  148466. _vq_quantmap__44u5__p8_1,
  148467. 11,
  148468. 11
  148469. };
  148470. static static_codebook _44u5__p8_1 = {
  148471. 2, 121,
  148472. _vq_lengthlist__44u5__p8_1,
  148473. 1, -531365888, 1611661312, 4, 0,
  148474. _vq_quantlist__44u5__p8_1,
  148475. NULL,
  148476. &_vq_auxt__44u5__p8_1,
  148477. NULL,
  148478. 0
  148479. };
  148480. static long _vq_quantlist__44u5__p9_0[] = {
  148481. 6,
  148482. 5,
  148483. 7,
  148484. 4,
  148485. 8,
  148486. 3,
  148487. 9,
  148488. 2,
  148489. 10,
  148490. 1,
  148491. 11,
  148492. 0,
  148493. 12,
  148494. };
  148495. static long _vq_lengthlist__44u5__p9_0[] = {
  148496. 1, 3, 2,12,10,13,13,13,13,13,13,13,13, 4, 9, 9,
  148497. 13,13,13,13,13,13,13,13,13,13, 5,10, 9,13,13,13,
  148498. 13,13,13,13,13,13,13,12,13,13,13,13,13,13,13,13,
  148499. 13,13,13,13,11,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,13,13,13,
  148502. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  148503. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  148504. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,12,
  148505. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148506. 12,12,12,12,12,12,12,12,12,
  148507. };
  148508. static float _vq_quantthresh__44u5__p9_0[] = {
  148509. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  148510. 637.5, 892.5, 1147.5, 1402.5,
  148511. };
  148512. static long _vq_quantmap__44u5__p9_0[] = {
  148513. 11, 9, 7, 5, 3, 1, 0, 2,
  148514. 4, 6, 8, 10, 12,
  148515. };
  148516. static encode_aux_threshmatch _vq_auxt__44u5__p9_0 = {
  148517. _vq_quantthresh__44u5__p9_0,
  148518. _vq_quantmap__44u5__p9_0,
  148519. 13,
  148520. 13
  148521. };
  148522. static static_codebook _44u5__p9_0 = {
  148523. 2, 169,
  148524. _vq_lengthlist__44u5__p9_0,
  148525. 1, -514332672, 1627381760, 4, 0,
  148526. _vq_quantlist__44u5__p9_0,
  148527. NULL,
  148528. &_vq_auxt__44u5__p9_0,
  148529. NULL,
  148530. 0
  148531. };
  148532. static long _vq_quantlist__44u5__p9_1[] = {
  148533. 7,
  148534. 6,
  148535. 8,
  148536. 5,
  148537. 9,
  148538. 4,
  148539. 10,
  148540. 3,
  148541. 11,
  148542. 2,
  148543. 12,
  148544. 1,
  148545. 13,
  148546. 0,
  148547. 14,
  148548. };
  148549. static long _vq_lengthlist__44u5__p9_1[] = {
  148550. 1, 4, 4, 7, 7, 8, 8, 8, 7, 8, 7, 9, 8, 9, 9, 4,
  148551. 7, 6, 9, 8,10,10, 9, 8, 9, 9, 9, 9, 9, 8, 5, 6,
  148552. 6, 8, 9,10,10, 9, 9, 9,10,10,10,10,11, 7, 8, 8,
  148553. 10,10,11,11,10,10,11,11,11,12,11,11, 7, 8, 8,10,
  148554. 10,11,11,10,10,11,11,12,11,11,11, 8, 9, 9,11,11,
  148555. 12,12,11,11,12,11,12,12,12,12, 8, 9,10,11,11,12,
  148556. 12,11,11,12,12,12,12,12,12, 8, 9, 9,10,10,12,11,
  148557. 12,12,12,12,12,12,12,13, 8, 9, 9,11,11,11,11,12,
  148558. 12,12,12,13,12,13,13, 9,10,10,11,11,12,12,12,13,
  148559. 12,13,13,13,14,13, 9,10,10,11,11,12,12,12,13,13,
  148560. 12,13,13,14,13, 9,11,10,12,11,13,12,12,13,13,13,
  148561. 13,13,13,14, 9,10,10,12,12,12,12,12,13,13,13,13,
  148562. 13,14,14,10,11,11,12,12,12,13,13,13,14,14,13,14,
  148563. 14,14,10,11,11,12,12,12,12,13,12,13,14,13,14,14,
  148564. 14,
  148565. };
  148566. static float _vq_quantthresh__44u5__p9_1[] = {
  148567. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  148568. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  148569. };
  148570. static long _vq_quantmap__44u5__p9_1[] = {
  148571. 13, 11, 9, 7, 5, 3, 1, 0,
  148572. 2, 4, 6, 8, 10, 12, 14,
  148573. };
  148574. static encode_aux_threshmatch _vq_auxt__44u5__p9_1 = {
  148575. _vq_quantthresh__44u5__p9_1,
  148576. _vq_quantmap__44u5__p9_1,
  148577. 15,
  148578. 15
  148579. };
  148580. static static_codebook _44u5__p9_1 = {
  148581. 2, 225,
  148582. _vq_lengthlist__44u5__p9_1,
  148583. 1, -522338304, 1620115456, 4, 0,
  148584. _vq_quantlist__44u5__p9_1,
  148585. NULL,
  148586. &_vq_auxt__44u5__p9_1,
  148587. NULL,
  148588. 0
  148589. };
  148590. static long _vq_quantlist__44u5__p9_2[] = {
  148591. 8,
  148592. 7,
  148593. 9,
  148594. 6,
  148595. 10,
  148596. 5,
  148597. 11,
  148598. 4,
  148599. 12,
  148600. 3,
  148601. 13,
  148602. 2,
  148603. 14,
  148604. 1,
  148605. 15,
  148606. 0,
  148607. 16,
  148608. };
  148609. static long _vq_lengthlist__44u5__p9_2[] = {
  148610. 2, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148611. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  148612. 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  148613. 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  148614. 9, 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  148615. 9, 9, 9, 9, 9, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  148616. 9,10, 9,10,10,10, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  148617. 9, 9,10, 9,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  148618. 9,10, 9,10,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  148619. 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,10, 9,
  148620. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,
  148621. 9,10, 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  148622. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  148623. 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  148624. 9,10,10, 9,10,10,10,10,10,10,10,10,10,10, 9, 9,
  148625. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  148626. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  148627. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,
  148628. 10,
  148629. };
  148630. static float _vq_quantthresh__44u5__p9_2[] = {
  148631. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148632. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148633. };
  148634. static long _vq_quantmap__44u5__p9_2[] = {
  148635. 15, 13, 11, 9, 7, 5, 3, 1,
  148636. 0, 2, 4, 6, 8, 10, 12, 14,
  148637. 16,
  148638. };
  148639. static encode_aux_threshmatch _vq_auxt__44u5__p9_2 = {
  148640. _vq_quantthresh__44u5__p9_2,
  148641. _vq_quantmap__44u5__p9_2,
  148642. 17,
  148643. 17
  148644. };
  148645. static static_codebook _44u5__p9_2 = {
  148646. 2, 289,
  148647. _vq_lengthlist__44u5__p9_2,
  148648. 1, -529530880, 1611661312, 5, 0,
  148649. _vq_quantlist__44u5__p9_2,
  148650. NULL,
  148651. &_vq_auxt__44u5__p9_2,
  148652. NULL,
  148653. 0
  148654. };
  148655. static long _huff_lengthlist__44u5__short[] = {
  148656. 4,10,17,13,17,13,17,17,17,17, 3, 6, 8, 9,11, 9,
  148657. 15,12,16,17, 6, 5, 5, 7, 7, 8,10,11,17,17, 7, 8,
  148658. 7, 9, 9,10,13,13,17,17, 8, 6, 5, 7, 4, 7, 5, 8,
  148659. 14,17, 9, 9, 8, 9, 7, 9, 8,10,16,17,12,10, 7, 8,
  148660. 4, 7, 4, 7,16,17,12,11, 9,10, 6, 9, 5, 7,14,17,
  148661. 14,13,10,15, 4, 8, 3, 5,14,17,17,14,11,15, 6,10,
  148662. 6, 8,15,17,
  148663. };
  148664. static static_codebook _huff_book__44u5__short = {
  148665. 2, 100,
  148666. _huff_lengthlist__44u5__short,
  148667. 0, 0, 0, 0, 0,
  148668. NULL,
  148669. NULL,
  148670. NULL,
  148671. NULL,
  148672. 0
  148673. };
  148674. static long _huff_lengthlist__44u6__long[] = {
  148675. 3, 9,14,13,14,13,16,12,13,14, 5, 4, 6, 6, 8, 9,
  148676. 11,10,12,15,10, 5, 5, 6, 6, 8,10,10,13,16,10, 6,
  148677. 6, 6, 6, 8, 9, 9,12,14,13, 7, 6, 6, 4, 6, 6, 7,
  148678. 11,14,10, 7, 7, 7, 6, 6, 6, 7,10,13,15,10, 9, 8,
  148679. 5, 6, 5, 6,10,14,10, 9, 8, 8, 6, 6, 5, 4, 6,11,
  148680. 11,11,12,11,10, 9, 9, 5, 5, 9,10,12,15,13,13,13,
  148681. 13, 8, 7, 7,
  148682. };
  148683. static static_codebook _huff_book__44u6__long = {
  148684. 2, 100,
  148685. _huff_lengthlist__44u6__long,
  148686. 0, 0, 0, 0, 0,
  148687. NULL,
  148688. NULL,
  148689. NULL,
  148690. NULL,
  148691. 0
  148692. };
  148693. static long _vq_quantlist__44u6__p1_0[] = {
  148694. 1,
  148695. 0,
  148696. 2,
  148697. };
  148698. static long _vq_lengthlist__44u6__p1_0[] = {
  148699. 1, 4, 4, 4, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  148700. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  148701. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  148702. 10,13,11,10,13,13, 5, 8, 8, 8,11,10, 8,10,10, 7,
  148703. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  148704. 12,
  148705. };
  148706. static float _vq_quantthresh__44u6__p1_0[] = {
  148707. -0.5, 0.5,
  148708. };
  148709. static long _vq_quantmap__44u6__p1_0[] = {
  148710. 1, 0, 2,
  148711. };
  148712. static encode_aux_threshmatch _vq_auxt__44u6__p1_0 = {
  148713. _vq_quantthresh__44u6__p1_0,
  148714. _vq_quantmap__44u6__p1_0,
  148715. 3,
  148716. 3
  148717. };
  148718. static static_codebook _44u6__p1_0 = {
  148719. 4, 81,
  148720. _vq_lengthlist__44u6__p1_0,
  148721. 1, -535822336, 1611661312, 2, 0,
  148722. _vq_quantlist__44u6__p1_0,
  148723. NULL,
  148724. &_vq_auxt__44u6__p1_0,
  148725. NULL,
  148726. 0
  148727. };
  148728. static long _vq_quantlist__44u6__p2_0[] = {
  148729. 1,
  148730. 0,
  148731. 2,
  148732. };
  148733. static long _vq_lengthlist__44u6__p2_0[] = {
  148734. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  148735. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  148736. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 7, 7,
  148737. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  148738. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  148739. 9,
  148740. };
  148741. static float _vq_quantthresh__44u6__p2_0[] = {
  148742. -0.5, 0.5,
  148743. };
  148744. static long _vq_quantmap__44u6__p2_0[] = {
  148745. 1, 0, 2,
  148746. };
  148747. static encode_aux_threshmatch _vq_auxt__44u6__p2_0 = {
  148748. _vq_quantthresh__44u6__p2_0,
  148749. _vq_quantmap__44u6__p2_0,
  148750. 3,
  148751. 3
  148752. };
  148753. static static_codebook _44u6__p2_0 = {
  148754. 4, 81,
  148755. _vq_lengthlist__44u6__p2_0,
  148756. 1, -535822336, 1611661312, 2, 0,
  148757. _vq_quantlist__44u6__p2_0,
  148758. NULL,
  148759. &_vq_auxt__44u6__p2_0,
  148760. NULL,
  148761. 0
  148762. };
  148763. static long _vq_quantlist__44u6__p3_0[] = {
  148764. 2,
  148765. 1,
  148766. 3,
  148767. 0,
  148768. 4,
  148769. };
  148770. static long _vq_lengthlist__44u6__p3_0[] = {
  148771. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  148772. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  148773. 9,11,11, 7, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  148774. 13,14, 5, 7, 7, 9,10, 6, 9, 8,11,11, 7, 9, 9,11,
  148775. 11, 9,11,10,14,13,10,11,11,14,13, 8,10,10,13,13,
  148776. 10,11,11,15,15, 9,11,11,14,14,13,14,14,17,16,12,
  148777. 13,14,16,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  148778. 12,14,15,12,14,13,16,15,13,14,14,15,17, 5, 7, 7,
  148779. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,
  148780. 14,10,11,11,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  148781. 9,11,11,13,13,11,13,13,14,15,11,12,13,15,16, 6,
  148782. 9, 9,11,12, 8,11,10,13,12, 9,11,11,13,14,11,13,
  148783. 12,16,14,11,13,13,15,16,10,12,11,14,15,11,13,13,
  148784. 15,17,11,13,13,17,16,15,15,16,17,16,14,15,16,18,
  148785. 0, 9,11,11,14,15,10,12,12,16,15,11,13,13,16,16,
  148786. 13,15,14,18,15,14,16,16, 0, 0, 5, 7, 7,10,10, 7,
  148787. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  148788. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  148789. 12,13,11,13,13,16,15,11,12,13,14,16, 7, 9, 9,11,
  148790. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,16,15,
  148791. 11,13,12,15,15, 9,11,11,15,14,11,13,13,17,16,10,
  148792. 12,13,15,16,14,16,16, 0,18,14,14,15,15,17,10,11,
  148793. 12,15,15,11,13,13,16,16,11,13,13,16,16,14,16,16,
  148794. 19,17,14,15,15,17,17, 8,10,10,14,14,10,12,11,15,
  148795. 15,10,11,12,16,15,14,15,15,18,20,13,14,16,17,18,
  148796. 9,11,11,15,16,11,13,13,17,17,11,13,13,17,16,15,
  148797. 16,16, 0, 0,15,16,16, 0, 0, 9,11,11,15,15,10,13,
  148798. 12,17,15,11,13,13,17,16,15,17,15,20,19,15,16,16,
  148799. 19, 0,13,15,14, 0,17,14,15,16, 0,20,15,16,16, 0,
  148800. 19,17,18, 0, 0, 0,16,17,18, 0, 0,12,14,14,19,18,
  148801. 13,15,14, 0,17,14,15,16,19,19,16,18,16, 0,19,19,
  148802. 20,17,20, 0, 8,10,10,13,14,10,11,11,15,15,10,12,
  148803. 12,15,16,14,15,14,19,16,14,15,15, 0,18, 9,11,11,
  148804. 16,15,11,13,13, 0,16,11,12,13,16,17,14,16,17, 0,
  148805. 19,15,16,16,18, 0, 9,11,11,15,16,11,13,13,16,16,
  148806. 11,14,13,18,17,15,16,16,18,20,15,17,19, 0, 0,12,
  148807. 14,14,17,17,14,16,15, 0, 0,13,14,15,19, 0,16,18,
  148808. 20, 0, 0,16,16,18,18, 0,12,14,14,17,20,14,16,16,
  148809. 19, 0,14,16,14, 0,20,16,20,17, 0, 0,17, 0,15, 0,
  148810. 19,
  148811. };
  148812. static float _vq_quantthresh__44u6__p3_0[] = {
  148813. -1.5, -0.5, 0.5, 1.5,
  148814. };
  148815. static long _vq_quantmap__44u6__p3_0[] = {
  148816. 3, 1, 0, 2, 4,
  148817. };
  148818. static encode_aux_threshmatch _vq_auxt__44u6__p3_0 = {
  148819. _vq_quantthresh__44u6__p3_0,
  148820. _vq_quantmap__44u6__p3_0,
  148821. 5,
  148822. 5
  148823. };
  148824. static static_codebook _44u6__p3_0 = {
  148825. 4, 625,
  148826. _vq_lengthlist__44u6__p3_0,
  148827. 1, -533725184, 1611661312, 3, 0,
  148828. _vq_quantlist__44u6__p3_0,
  148829. NULL,
  148830. &_vq_auxt__44u6__p3_0,
  148831. NULL,
  148832. 0
  148833. };
  148834. static long _vq_quantlist__44u6__p4_0[] = {
  148835. 2,
  148836. 1,
  148837. 3,
  148838. 0,
  148839. 4,
  148840. };
  148841. static long _vq_lengthlist__44u6__p4_0[] = {
  148842. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  148843. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  148844. 8,10,10, 7, 7, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  148845. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 8,10,
  148846. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  148847. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,13,11,
  148848. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  148849. 10,12,12,11,12,11,13,12,11,12,12,13,13, 5, 7, 7,
  148850. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  148851. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  148852. 8, 9, 9,11,11,10,10,11,12,13,10,10,11,12,12, 6,
  148853. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  148854. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  148855. 13,13,10,11,11,12,13,12,12,12,13,14,12,12,13,14,
  148856. 14, 9,10,10,12,12, 9,10,10,13,12,10,11,11,13,13,
  148857. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  148858. 8, 7,10,10, 7, 8, 8,10,10, 9,10,10,12,11, 9,10,
  148859. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  148860. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  148861. 10, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,10,13,12,
  148862. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,12, 9,
  148863. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  148864. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,12,12,
  148865. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  148866. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,14,
  148867. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  148868. 12,13,14,15,12,12,13,14,14, 9,10,10,12,12, 9,11,
  148869. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,13,
  148870. 14,15,11,12,12,14,13,11,12,12,14,14,12,13,13,14,
  148871. 14,13,13,14,14,16,13,14,14,15,15,11,12,11,13,13,
  148872. 11,12,11,14,13,12,12,13,14,15,12,14,12,15,12,13,
  148873. 14,15,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  148874. 10,12,12,11,12,12,14,13,11,12,12,13,13, 9,10,10,
  148875. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  148876. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  148877. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  148878. 11,11,13,13,12,13,12,14,14,11,11,12,13,14,14,14,
  148879. 14,16,15,12,12,14,12,15,11,12,12,13,14,12,13,13,
  148880. 14,15,11,12,12,14,14,13,14,14,16,16,13,14,13,16,
  148881. 13,
  148882. };
  148883. static float _vq_quantthresh__44u6__p4_0[] = {
  148884. -1.5, -0.5, 0.5, 1.5,
  148885. };
  148886. static long _vq_quantmap__44u6__p4_0[] = {
  148887. 3, 1, 0, 2, 4,
  148888. };
  148889. static encode_aux_threshmatch _vq_auxt__44u6__p4_0 = {
  148890. _vq_quantthresh__44u6__p4_0,
  148891. _vq_quantmap__44u6__p4_0,
  148892. 5,
  148893. 5
  148894. };
  148895. static static_codebook _44u6__p4_0 = {
  148896. 4, 625,
  148897. _vq_lengthlist__44u6__p4_0,
  148898. 1, -533725184, 1611661312, 3, 0,
  148899. _vq_quantlist__44u6__p4_0,
  148900. NULL,
  148901. &_vq_auxt__44u6__p4_0,
  148902. NULL,
  148903. 0
  148904. };
  148905. static long _vq_quantlist__44u6__p5_0[] = {
  148906. 4,
  148907. 3,
  148908. 5,
  148909. 2,
  148910. 6,
  148911. 1,
  148912. 7,
  148913. 0,
  148914. 8,
  148915. };
  148916. static long _vq_lengthlist__44u6__p5_0[] = {
  148917. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  148918. 11,11, 3, 5, 5, 7, 8, 8, 8,11,11, 6, 8, 7, 9, 9,
  148919. 10, 9,12,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  148920. 10, 9,12,11,13,13, 8, 8, 9, 9,10,11,12,13,13,10,
  148921. 11,11,12,12,13,13,14,14,10,10,11,11,12,13,13,14,
  148922. 14,
  148923. };
  148924. static float _vq_quantthresh__44u6__p5_0[] = {
  148925. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148926. };
  148927. static long _vq_quantmap__44u6__p5_0[] = {
  148928. 7, 5, 3, 1, 0, 2, 4, 6,
  148929. 8,
  148930. };
  148931. static encode_aux_threshmatch _vq_auxt__44u6__p5_0 = {
  148932. _vq_quantthresh__44u6__p5_0,
  148933. _vq_quantmap__44u6__p5_0,
  148934. 9,
  148935. 9
  148936. };
  148937. static static_codebook _44u6__p5_0 = {
  148938. 2, 81,
  148939. _vq_lengthlist__44u6__p5_0,
  148940. 1, -531628032, 1611661312, 4, 0,
  148941. _vq_quantlist__44u6__p5_0,
  148942. NULL,
  148943. &_vq_auxt__44u6__p5_0,
  148944. NULL,
  148945. 0
  148946. };
  148947. static long _vq_quantlist__44u6__p6_0[] = {
  148948. 4,
  148949. 3,
  148950. 5,
  148951. 2,
  148952. 6,
  148953. 1,
  148954. 7,
  148955. 0,
  148956. 8,
  148957. };
  148958. static long _vq_lengthlist__44u6__p6_0[] = {
  148959. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  148960. 9, 9, 4, 4, 5, 6, 6, 7, 8, 9, 9, 5, 6, 6, 7, 7,
  148961. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  148962. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,10,11, 9,
  148963. 9, 9,10,10,11,11,12,11, 9, 9, 9,10,10,11,11,11,
  148964. 12,
  148965. };
  148966. static float _vq_quantthresh__44u6__p6_0[] = {
  148967. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148968. };
  148969. static long _vq_quantmap__44u6__p6_0[] = {
  148970. 7, 5, 3, 1, 0, 2, 4, 6,
  148971. 8,
  148972. };
  148973. static encode_aux_threshmatch _vq_auxt__44u6__p6_0 = {
  148974. _vq_quantthresh__44u6__p6_0,
  148975. _vq_quantmap__44u6__p6_0,
  148976. 9,
  148977. 9
  148978. };
  148979. static static_codebook _44u6__p6_0 = {
  148980. 2, 81,
  148981. _vq_lengthlist__44u6__p6_0,
  148982. 1, -531628032, 1611661312, 4, 0,
  148983. _vq_quantlist__44u6__p6_0,
  148984. NULL,
  148985. &_vq_auxt__44u6__p6_0,
  148986. NULL,
  148987. 0
  148988. };
  148989. static long _vq_quantlist__44u6__p7_0[] = {
  148990. 1,
  148991. 0,
  148992. 2,
  148993. };
  148994. static long _vq_lengthlist__44u6__p7_0[] = {
  148995. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10,10, 8,
  148996. 10,10, 5, 8, 9, 7,10,10, 7,10, 9, 4, 8, 8, 9,11,
  148997. 11, 8,11,11, 7,11,11,10,10,13,10,13,13, 7,11,11,
  148998. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 9,11,11, 7,
  148999. 11,11,10,13,13,10,12,13, 7,11,11,10,13,13, 9,13,
  149000. 10,
  149001. };
  149002. static float _vq_quantthresh__44u6__p7_0[] = {
  149003. -5.5, 5.5,
  149004. };
  149005. static long _vq_quantmap__44u6__p7_0[] = {
  149006. 1, 0, 2,
  149007. };
  149008. static encode_aux_threshmatch _vq_auxt__44u6__p7_0 = {
  149009. _vq_quantthresh__44u6__p7_0,
  149010. _vq_quantmap__44u6__p7_0,
  149011. 3,
  149012. 3
  149013. };
  149014. static static_codebook _44u6__p7_0 = {
  149015. 4, 81,
  149016. _vq_lengthlist__44u6__p7_0,
  149017. 1, -529137664, 1618345984, 2, 0,
  149018. _vq_quantlist__44u6__p7_0,
  149019. NULL,
  149020. &_vq_auxt__44u6__p7_0,
  149021. NULL,
  149022. 0
  149023. };
  149024. static long _vq_quantlist__44u6__p7_1[] = {
  149025. 5,
  149026. 4,
  149027. 6,
  149028. 3,
  149029. 7,
  149030. 2,
  149031. 8,
  149032. 1,
  149033. 9,
  149034. 0,
  149035. 10,
  149036. };
  149037. static long _vq_lengthlist__44u6__p7_1[] = {
  149038. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 6,
  149039. 8, 8, 8, 8, 8, 8, 4, 5, 5, 6, 7, 8, 8, 8, 8, 8,
  149040. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  149041. 7, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 9, 9,
  149042. 9, 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  149043. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  149044. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  149045. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149046. };
  149047. static float _vq_quantthresh__44u6__p7_1[] = {
  149048. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149049. 3.5, 4.5,
  149050. };
  149051. static long _vq_quantmap__44u6__p7_1[] = {
  149052. 9, 7, 5, 3, 1, 0, 2, 4,
  149053. 6, 8, 10,
  149054. };
  149055. static encode_aux_threshmatch _vq_auxt__44u6__p7_1 = {
  149056. _vq_quantthresh__44u6__p7_1,
  149057. _vq_quantmap__44u6__p7_1,
  149058. 11,
  149059. 11
  149060. };
  149061. static static_codebook _44u6__p7_1 = {
  149062. 2, 121,
  149063. _vq_lengthlist__44u6__p7_1,
  149064. 1, -531365888, 1611661312, 4, 0,
  149065. _vq_quantlist__44u6__p7_1,
  149066. NULL,
  149067. &_vq_auxt__44u6__p7_1,
  149068. NULL,
  149069. 0
  149070. };
  149071. static long _vq_quantlist__44u6__p8_0[] = {
  149072. 5,
  149073. 4,
  149074. 6,
  149075. 3,
  149076. 7,
  149077. 2,
  149078. 8,
  149079. 1,
  149080. 9,
  149081. 0,
  149082. 10,
  149083. };
  149084. static long _vq_lengthlist__44u6__p8_0[] = {
  149085. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  149086. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  149087. 11, 6, 8, 8, 9, 9,10,10,11,11,12,12, 6, 8, 8, 9,
  149088. 9,10,10,11,11,12,12, 8, 9, 9,10,10,11,11,12,12,
  149089. 13,13, 8, 9, 9,10,10,11,11,12,12,13,13,10,10,10,
  149090. 11,11,13,13,13,13,15,14, 9,10,10,12,11,12,13,13,
  149091. 13,14,15,11,12,12,13,13,13,13,15,14,15,15,11,11,
  149092. 12,13,13,14,14,14,15,15,15,
  149093. };
  149094. static float _vq_quantthresh__44u6__p8_0[] = {
  149095. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  149096. 38.5, 49.5,
  149097. };
  149098. static long _vq_quantmap__44u6__p8_0[] = {
  149099. 9, 7, 5, 3, 1, 0, 2, 4,
  149100. 6, 8, 10,
  149101. };
  149102. static encode_aux_threshmatch _vq_auxt__44u6__p8_0 = {
  149103. _vq_quantthresh__44u6__p8_0,
  149104. _vq_quantmap__44u6__p8_0,
  149105. 11,
  149106. 11
  149107. };
  149108. static static_codebook _44u6__p8_0 = {
  149109. 2, 121,
  149110. _vq_lengthlist__44u6__p8_0,
  149111. 1, -524582912, 1618345984, 4, 0,
  149112. _vq_quantlist__44u6__p8_0,
  149113. NULL,
  149114. &_vq_auxt__44u6__p8_0,
  149115. NULL,
  149116. 0
  149117. };
  149118. static long _vq_quantlist__44u6__p8_1[] = {
  149119. 5,
  149120. 4,
  149121. 6,
  149122. 3,
  149123. 7,
  149124. 2,
  149125. 8,
  149126. 1,
  149127. 9,
  149128. 0,
  149129. 10,
  149130. };
  149131. static long _vq_lengthlist__44u6__p8_1[] = {
  149132. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 7,
  149133. 7, 7, 8, 7, 8, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7, 8,
  149134. 8, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 6, 7, 7,
  149135. 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  149136. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  149137. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  149138. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  149139. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149140. };
  149141. static float _vq_quantthresh__44u6__p8_1[] = {
  149142. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149143. 3.5, 4.5,
  149144. };
  149145. static long _vq_quantmap__44u6__p8_1[] = {
  149146. 9, 7, 5, 3, 1, 0, 2, 4,
  149147. 6, 8, 10,
  149148. };
  149149. static encode_aux_threshmatch _vq_auxt__44u6__p8_1 = {
  149150. _vq_quantthresh__44u6__p8_1,
  149151. _vq_quantmap__44u6__p8_1,
  149152. 11,
  149153. 11
  149154. };
  149155. static static_codebook _44u6__p8_1 = {
  149156. 2, 121,
  149157. _vq_lengthlist__44u6__p8_1,
  149158. 1, -531365888, 1611661312, 4, 0,
  149159. _vq_quantlist__44u6__p8_1,
  149160. NULL,
  149161. &_vq_auxt__44u6__p8_1,
  149162. NULL,
  149163. 0
  149164. };
  149165. static long _vq_quantlist__44u6__p9_0[] = {
  149166. 7,
  149167. 6,
  149168. 8,
  149169. 5,
  149170. 9,
  149171. 4,
  149172. 10,
  149173. 3,
  149174. 11,
  149175. 2,
  149176. 12,
  149177. 1,
  149178. 13,
  149179. 0,
  149180. 14,
  149181. };
  149182. static long _vq_lengthlist__44u6__p9_0[] = {
  149183. 1, 3, 2, 9, 8,15,15,15,15,15,15,15,15,15,15, 4,
  149184. 8, 9,13,14,14,14,14,14,14,14,14,14,14,14, 5, 8,
  149185. 9,14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,
  149186. 14,14,14,14,14,14,14,14,14,14,14,14,11,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,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149195. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149196. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149197. 14,
  149198. };
  149199. static float _vq_quantthresh__44u6__p9_0[] = {
  149200. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  149201. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  149202. };
  149203. static long _vq_quantmap__44u6__p9_0[] = {
  149204. 13, 11, 9, 7, 5, 3, 1, 0,
  149205. 2, 4, 6, 8, 10, 12, 14,
  149206. };
  149207. static encode_aux_threshmatch _vq_auxt__44u6__p9_0 = {
  149208. _vq_quantthresh__44u6__p9_0,
  149209. _vq_quantmap__44u6__p9_0,
  149210. 15,
  149211. 15
  149212. };
  149213. static static_codebook _44u6__p9_0 = {
  149214. 2, 225,
  149215. _vq_lengthlist__44u6__p9_0,
  149216. 1, -514071552, 1627381760, 4, 0,
  149217. _vq_quantlist__44u6__p9_0,
  149218. NULL,
  149219. &_vq_auxt__44u6__p9_0,
  149220. NULL,
  149221. 0
  149222. };
  149223. static long _vq_quantlist__44u6__p9_1[] = {
  149224. 7,
  149225. 6,
  149226. 8,
  149227. 5,
  149228. 9,
  149229. 4,
  149230. 10,
  149231. 3,
  149232. 11,
  149233. 2,
  149234. 12,
  149235. 1,
  149236. 13,
  149237. 0,
  149238. 14,
  149239. };
  149240. static long _vq_lengthlist__44u6__p9_1[] = {
  149241. 1, 4, 4, 7, 7, 8, 9, 8, 8, 9, 8, 9, 8, 9, 9, 4,
  149242. 7, 6, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 4, 7,
  149243. 6, 9, 9,10,10, 9, 9,10,10,10,10,11,11, 7, 9, 8,
  149244. 10,10,11,11,10,10,11,11,11,11,11,11, 7, 8, 9,10,
  149245. 10,11,11,10,10,11,11,11,11,11,12, 8,10,10,11,11,
  149246. 12,12,11,11,12,12,12,12,13,12, 8,10,10,11,11,12,
  149247. 11,11,11,11,12,12,12,12,13, 8, 9, 9,11,10,11,11,
  149248. 12,12,12,12,13,12,13,12, 8, 9, 9,11,11,11,11,12,
  149249. 12,12,12,12,13,13,13, 9,10,10,11,12,12,12,12,12,
  149250. 13,13,13,13,13,13, 9,10,10,11,11,12,12,12,12,13,
  149251. 13,13,13,14,13,10,10,10,12,11,12,12,13,13,13,13,
  149252. 13,13,13,13,10,10,11,11,11,12,12,13,13,13,13,13,
  149253. 13,13,13,10,11,11,12,12,13,12,12,13,13,13,13,13,
  149254. 13,14,10,11,11,12,12,13,12,13,13,13,14,13,13,14,
  149255. 13,
  149256. };
  149257. static float _vq_quantthresh__44u6__p9_1[] = {
  149258. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  149259. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  149260. };
  149261. static long _vq_quantmap__44u6__p9_1[] = {
  149262. 13, 11, 9, 7, 5, 3, 1, 0,
  149263. 2, 4, 6, 8, 10, 12, 14,
  149264. };
  149265. static encode_aux_threshmatch _vq_auxt__44u6__p9_1 = {
  149266. _vq_quantthresh__44u6__p9_1,
  149267. _vq_quantmap__44u6__p9_1,
  149268. 15,
  149269. 15
  149270. };
  149271. static static_codebook _44u6__p9_1 = {
  149272. 2, 225,
  149273. _vq_lengthlist__44u6__p9_1,
  149274. 1, -522338304, 1620115456, 4, 0,
  149275. _vq_quantlist__44u6__p9_1,
  149276. NULL,
  149277. &_vq_auxt__44u6__p9_1,
  149278. NULL,
  149279. 0
  149280. };
  149281. static long _vq_quantlist__44u6__p9_2[] = {
  149282. 8,
  149283. 7,
  149284. 9,
  149285. 6,
  149286. 10,
  149287. 5,
  149288. 11,
  149289. 4,
  149290. 12,
  149291. 3,
  149292. 13,
  149293. 2,
  149294. 14,
  149295. 1,
  149296. 15,
  149297. 0,
  149298. 16,
  149299. };
  149300. static long _vq_lengthlist__44u6__p9_2[] = {
  149301. 3, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 8, 8, 9, 9,
  149302. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  149303. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  149304. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149305. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149306. 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149307. 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149308. 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149309. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  149310. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9, 9, 9, 9,
  149311. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 8, 9, 9, 9, 9, 9,
  149312. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  149313. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9, 9, 9, 9, 9,
  149314. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,
  149315. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9, 9,
  149316. 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9,10, 9,
  149317. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9,10,10,
  149318. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10, 9, 9,
  149319. 10,
  149320. };
  149321. static float _vq_quantthresh__44u6__p9_2[] = {
  149322. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  149323. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  149324. };
  149325. static long _vq_quantmap__44u6__p9_2[] = {
  149326. 15, 13, 11, 9, 7, 5, 3, 1,
  149327. 0, 2, 4, 6, 8, 10, 12, 14,
  149328. 16,
  149329. };
  149330. static encode_aux_threshmatch _vq_auxt__44u6__p9_2 = {
  149331. _vq_quantthresh__44u6__p9_2,
  149332. _vq_quantmap__44u6__p9_2,
  149333. 17,
  149334. 17
  149335. };
  149336. static static_codebook _44u6__p9_2 = {
  149337. 2, 289,
  149338. _vq_lengthlist__44u6__p9_2,
  149339. 1, -529530880, 1611661312, 5, 0,
  149340. _vq_quantlist__44u6__p9_2,
  149341. NULL,
  149342. &_vq_auxt__44u6__p9_2,
  149343. NULL,
  149344. 0
  149345. };
  149346. static long _huff_lengthlist__44u6__short[] = {
  149347. 4,11,16,13,17,13,17,16,17,17, 4, 7, 9, 9,13,10,
  149348. 16,12,16,17, 7, 6, 5, 7, 8, 9,12,12,16,17, 6, 9,
  149349. 7, 9,10,10,15,15,17,17, 6, 7, 5, 7, 5, 7, 7,10,
  149350. 16,17, 7, 9, 8, 9, 8,10,11,11,15,17, 7, 7, 7, 8,
  149351. 5, 8, 8, 9,15,17, 8, 7, 9, 9, 7, 8, 7, 2, 7,15,
  149352. 14,13,13,15, 5,10, 4, 3, 6,17,17,15,13,17, 7,11,
  149353. 7, 6, 9,16,
  149354. };
  149355. static static_codebook _huff_book__44u6__short = {
  149356. 2, 100,
  149357. _huff_lengthlist__44u6__short,
  149358. 0, 0, 0, 0, 0,
  149359. NULL,
  149360. NULL,
  149361. NULL,
  149362. NULL,
  149363. 0
  149364. };
  149365. static long _huff_lengthlist__44u7__long[] = {
  149366. 3, 9,14,13,15,14,16,13,13,14, 5, 5, 7, 7, 8, 9,
  149367. 11,10,12,15,10, 6, 5, 6, 6, 9,10,10,13,16,10, 6,
  149368. 6, 6, 6, 8, 9, 9,12,15,14, 7, 6, 6, 5, 6, 6, 8,
  149369. 12,15,10, 8, 7, 7, 6, 7, 7, 7,11,13,14,10, 9, 8,
  149370. 5, 6, 4, 5, 9,12,10, 9, 9, 8, 6, 6, 5, 3, 6,11,
  149371. 12,11,12,12,10, 9, 8, 5, 5, 8,10,11,15,13,13,13,
  149372. 12, 8, 6, 7,
  149373. };
  149374. static static_codebook _huff_book__44u7__long = {
  149375. 2, 100,
  149376. _huff_lengthlist__44u7__long,
  149377. 0, 0, 0, 0, 0,
  149378. NULL,
  149379. NULL,
  149380. NULL,
  149381. NULL,
  149382. 0
  149383. };
  149384. static long _vq_quantlist__44u7__p1_0[] = {
  149385. 1,
  149386. 0,
  149387. 2,
  149388. };
  149389. static long _vq_lengthlist__44u7__p1_0[] = {
  149390. 1, 4, 4, 4, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  149391. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 5, 8, 8, 8,11,
  149392. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  149393. 10,13,12,10,13,13, 5, 8, 8, 8,11,10, 8,10,11, 7,
  149394. 10,10,10,13,13,10,12,13, 8,11,11,10,13,13,10,13,
  149395. 12,
  149396. };
  149397. static float _vq_quantthresh__44u7__p1_0[] = {
  149398. -0.5, 0.5,
  149399. };
  149400. static long _vq_quantmap__44u7__p1_0[] = {
  149401. 1, 0, 2,
  149402. };
  149403. static encode_aux_threshmatch _vq_auxt__44u7__p1_0 = {
  149404. _vq_quantthresh__44u7__p1_0,
  149405. _vq_quantmap__44u7__p1_0,
  149406. 3,
  149407. 3
  149408. };
  149409. static static_codebook _44u7__p1_0 = {
  149410. 4, 81,
  149411. _vq_lengthlist__44u7__p1_0,
  149412. 1, -535822336, 1611661312, 2, 0,
  149413. _vq_quantlist__44u7__p1_0,
  149414. NULL,
  149415. &_vq_auxt__44u7__p1_0,
  149416. NULL,
  149417. 0
  149418. };
  149419. static long _vq_quantlist__44u7__p2_0[] = {
  149420. 1,
  149421. 0,
  149422. 2,
  149423. };
  149424. static long _vq_lengthlist__44u7__p2_0[] = {
  149425. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  149426. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  149427. 7, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  149428. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  149429. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  149430. 9,
  149431. };
  149432. static float _vq_quantthresh__44u7__p2_0[] = {
  149433. -0.5, 0.5,
  149434. };
  149435. static long _vq_quantmap__44u7__p2_0[] = {
  149436. 1, 0, 2,
  149437. };
  149438. static encode_aux_threshmatch _vq_auxt__44u7__p2_0 = {
  149439. _vq_quantthresh__44u7__p2_0,
  149440. _vq_quantmap__44u7__p2_0,
  149441. 3,
  149442. 3
  149443. };
  149444. static static_codebook _44u7__p2_0 = {
  149445. 4, 81,
  149446. _vq_lengthlist__44u7__p2_0,
  149447. 1, -535822336, 1611661312, 2, 0,
  149448. _vq_quantlist__44u7__p2_0,
  149449. NULL,
  149450. &_vq_auxt__44u7__p2_0,
  149451. NULL,
  149452. 0
  149453. };
  149454. static long _vq_quantlist__44u7__p3_0[] = {
  149455. 2,
  149456. 1,
  149457. 3,
  149458. 0,
  149459. 4,
  149460. };
  149461. static long _vq_lengthlist__44u7__p3_0[] = {
  149462. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  149463. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  149464. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  149465. 13,14, 5, 7, 7, 9, 9, 7, 9, 8,11,11, 7, 9, 9,11,
  149466. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  149467. 10,11,12,15,14, 9,11,11,15,14,13,14,14,16,16,12,
  149468. 13,14,17,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  149469. 12,14,15,12,14,13,16,16,13,14,15,15,17, 5, 7, 7,
  149470. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,15,
  149471. 14,10,11,12,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  149472. 9,11,11,13,13,11,13,13,14,17,11,13,13,15,16, 6,
  149473. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  149474. 12,16,14,11,13,13,16,16,10,12,12,15,15,11,13,13,
  149475. 16,16,11,13,13,16,15,14,16,17,17,19,14,16,16,18,
  149476. 0, 9,11,11,14,15,10,13,12,16,15,11,13,13,16,16,
  149477. 14,15,14, 0,16,14,16,16,18, 0, 5, 7, 7,10,10, 7,
  149478. 9, 9,12,11, 7, 9, 9,11,12,10,11,11,15,14,10,11,
  149479. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  149480. 12,13,11,13,13,17,15,11,12,13,14,15, 7, 9, 9,11,
  149481. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,12,16,16,
  149482. 11,13,13,15,14, 9,11,11,14,15,11,13,13,16,15,10,
  149483. 12,13,16,16,15,16,16, 0, 0,14,13,15,16,18,10,11,
  149484. 11,15,15,11,13,14,16,18,11,13,13,16,15,15,16,16,
  149485. 19, 0,14,15,15,16,16, 8,10,10,13,13,10,12,11,16,
  149486. 15,10,11,11,16,15,13,15,16,18, 0,13,14,15,17,17,
  149487. 9,11,11,15,15,11,13,13,16,18,11,13,13,16,17,15,
  149488. 16,16, 0, 0,15,18,16, 0,17, 9,11,11,15,15,11,13,
  149489. 12,17,15,11,13,14,16,17,15,18,15, 0,17,15,16,16,
  149490. 18,19,13,15,14, 0,18,14,16,16,19,18,14,16,15,19,
  149491. 19,16,18,19, 0, 0,16,17, 0, 0, 0,12,14,14,17,17,
  149492. 13,16,14, 0,18,14,16,15,18, 0,16,18,16,19,17,18,
  149493. 19,17, 0, 0, 8,10,10,14,14, 9,12,11,15,15,10,11,
  149494. 12,15,17,13,15,15,18,16,14,16,15,18,17, 9,11,11,
  149495. 16,15,11,13,13, 0,16,11,12,13,16,15,15,16,16, 0,
  149496. 17,15,15,16,18,17, 9,12,11,15,17,11,13,13,16,16,
  149497. 11,14,13,16,16,15,15,16,18,19,16,18,16, 0, 0,12,
  149498. 14,14, 0,16,14,16,16, 0,18,13,14,15,16, 0,17,16,
  149499. 18, 0, 0,16,16,17,19, 0,13,14,14,17, 0,14,17,16,
  149500. 0,19,14,15,15,18,19,17,16,18, 0, 0,15,19,16, 0,
  149501. 0,
  149502. };
  149503. static float _vq_quantthresh__44u7__p3_0[] = {
  149504. -1.5, -0.5, 0.5, 1.5,
  149505. };
  149506. static long _vq_quantmap__44u7__p3_0[] = {
  149507. 3, 1, 0, 2, 4,
  149508. };
  149509. static encode_aux_threshmatch _vq_auxt__44u7__p3_0 = {
  149510. _vq_quantthresh__44u7__p3_0,
  149511. _vq_quantmap__44u7__p3_0,
  149512. 5,
  149513. 5
  149514. };
  149515. static static_codebook _44u7__p3_0 = {
  149516. 4, 625,
  149517. _vq_lengthlist__44u7__p3_0,
  149518. 1, -533725184, 1611661312, 3, 0,
  149519. _vq_quantlist__44u7__p3_0,
  149520. NULL,
  149521. &_vq_auxt__44u7__p3_0,
  149522. NULL,
  149523. 0
  149524. };
  149525. static long _vq_quantlist__44u7__p4_0[] = {
  149526. 2,
  149527. 1,
  149528. 3,
  149529. 0,
  149530. 4,
  149531. };
  149532. static long _vq_lengthlist__44u7__p4_0[] = {
  149533. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  149534. 9, 9,11,11, 8, 9, 9,10,11, 6, 7, 7, 9, 9, 7, 8,
  149535. 8,10,10, 6, 7, 8, 9,10, 9,10,10,12,12, 9, 9,10,
  149536. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  149537. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  149538. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  149539. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,11, 9,10,
  149540. 10,12,12,11,12,11,13,13,11,12,12,13,13, 6, 7, 7,
  149541. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  149542. 11, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  149543. 8, 9, 9,11,11,10,11,11,12,12,10,10,11,12,13, 6,
  149544. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  149545. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  149546. 13,13,10,11,11,13,12,12,12,13,13,14,12,12,13,14,
  149547. 14, 9,10,10,12,12, 9,10,10,12,12,10,11,11,13,13,
  149548. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  149549. 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,11, 9,10,
  149550. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  149551. 10,11,10,11,11,13,12,10,10,11,11,13, 7, 8, 8,10,
  149552. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,10,13,12,
  149553. 10,11,11,12,12, 9,10,10,12,12,10,11,11,13,12, 9,
  149554. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  149555. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,12,
  149556. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  149557. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,13,
  149558. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  149559. 13,13,14,14,12,12,13,14,14, 9,10,10,12,12, 9,11,
  149560. 10,13,12,10,10,11,12,13,11,13,12,14,13,12,12,13,
  149561. 14,14,11,12,12,13,13,11,12,13,14,14,12,13,13,14,
  149562. 14,13,13,14,14,16,13,14,14,16,16,11,11,11,13,13,
  149563. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,13,14,
  149564. 14,14,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149565. 10,12,12,11,12,12,14,13,11,12,12,13,14, 9,10,10,
  149566. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  149567. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,12,13,
  149568. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  149569. 12,12,13,13,12,13,12,14,14,11,11,12,13,14,13,15,
  149570. 14,16,15,13,12,14,13,16,11,12,12,13,13,12,13,13,
  149571. 14,14,12,12,12,14,14,13,14,14,15,15,13,14,13,16,
  149572. 14,
  149573. };
  149574. static float _vq_quantthresh__44u7__p4_0[] = {
  149575. -1.5, -0.5, 0.5, 1.5,
  149576. };
  149577. static long _vq_quantmap__44u7__p4_0[] = {
  149578. 3, 1, 0, 2, 4,
  149579. };
  149580. static encode_aux_threshmatch _vq_auxt__44u7__p4_0 = {
  149581. _vq_quantthresh__44u7__p4_0,
  149582. _vq_quantmap__44u7__p4_0,
  149583. 5,
  149584. 5
  149585. };
  149586. static static_codebook _44u7__p4_0 = {
  149587. 4, 625,
  149588. _vq_lengthlist__44u7__p4_0,
  149589. 1, -533725184, 1611661312, 3, 0,
  149590. _vq_quantlist__44u7__p4_0,
  149591. NULL,
  149592. &_vq_auxt__44u7__p4_0,
  149593. NULL,
  149594. 0
  149595. };
  149596. static long _vq_quantlist__44u7__p5_0[] = {
  149597. 4,
  149598. 3,
  149599. 5,
  149600. 2,
  149601. 6,
  149602. 1,
  149603. 7,
  149604. 0,
  149605. 8,
  149606. };
  149607. static long _vq_lengthlist__44u7__p5_0[] = {
  149608. 2, 3, 3, 6, 6, 7, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  149609. 11,11, 3, 5, 5, 7, 7, 8, 9,11,11, 6, 8, 7, 9, 9,
  149610. 10,10,12,12, 6, 7, 8, 9,10,10,10,12,12, 8, 8, 8,
  149611. 10,10,12,11,13,13, 8, 8, 9,10,10,11,11,13,13,10,
  149612. 11,11,12,12,13,13,14,14,10,11,11,12,12,13,13,14,
  149613. 14,
  149614. };
  149615. static float _vq_quantthresh__44u7__p5_0[] = {
  149616. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149617. };
  149618. static long _vq_quantmap__44u7__p5_0[] = {
  149619. 7, 5, 3, 1, 0, 2, 4, 6,
  149620. 8,
  149621. };
  149622. static encode_aux_threshmatch _vq_auxt__44u7__p5_0 = {
  149623. _vq_quantthresh__44u7__p5_0,
  149624. _vq_quantmap__44u7__p5_0,
  149625. 9,
  149626. 9
  149627. };
  149628. static static_codebook _44u7__p5_0 = {
  149629. 2, 81,
  149630. _vq_lengthlist__44u7__p5_0,
  149631. 1, -531628032, 1611661312, 4, 0,
  149632. _vq_quantlist__44u7__p5_0,
  149633. NULL,
  149634. &_vq_auxt__44u7__p5_0,
  149635. NULL,
  149636. 0
  149637. };
  149638. static long _vq_quantlist__44u7__p6_0[] = {
  149639. 4,
  149640. 3,
  149641. 5,
  149642. 2,
  149643. 6,
  149644. 1,
  149645. 7,
  149646. 0,
  149647. 8,
  149648. };
  149649. static long _vq_lengthlist__44u7__p6_0[] = {
  149650. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 8, 7,
  149651. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  149652. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  149653. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,11,11, 9,
  149654. 9, 9,10,10,11,10,12,11, 9, 9, 9,10,10,11,11,11,
  149655. 12,
  149656. };
  149657. static float _vq_quantthresh__44u7__p6_0[] = {
  149658. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149659. };
  149660. static long _vq_quantmap__44u7__p6_0[] = {
  149661. 7, 5, 3, 1, 0, 2, 4, 6,
  149662. 8,
  149663. };
  149664. static encode_aux_threshmatch _vq_auxt__44u7__p6_0 = {
  149665. _vq_quantthresh__44u7__p6_0,
  149666. _vq_quantmap__44u7__p6_0,
  149667. 9,
  149668. 9
  149669. };
  149670. static static_codebook _44u7__p6_0 = {
  149671. 2, 81,
  149672. _vq_lengthlist__44u7__p6_0,
  149673. 1, -531628032, 1611661312, 4, 0,
  149674. _vq_quantlist__44u7__p6_0,
  149675. NULL,
  149676. &_vq_auxt__44u7__p6_0,
  149677. NULL,
  149678. 0
  149679. };
  149680. static long _vq_quantlist__44u7__p7_0[] = {
  149681. 1,
  149682. 0,
  149683. 2,
  149684. };
  149685. static long _vq_lengthlist__44u7__p7_0[] = {
  149686. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 8, 9, 9, 7,
  149687. 10,10, 5, 8, 9, 7, 9,10, 8, 9, 9, 4, 9, 9, 9,11,
  149688. 10, 8,10,10, 7,11,10,10,10,12,10,12,12, 7,10,10,
  149689. 10,12,11,10,12,12, 5, 9, 9, 8,10,10, 9,11,11, 7,
  149690. 11,10,10,12,12,10,11,12, 7,10,11,10,12,12,10,12,
  149691. 10,
  149692. };
  149693. static float _vq_quantthresh__44u7__p7_0[] = {
  149694. -5.5, 5.5,
  149695. };
  149696. static long _vq_quantmap__44u7__p7_0[] = {
  149697. 1, 0, 2,
  149698. };
  149699. static encode_aux_threshmatch _vq_auxt__44u7__p7_0 = {
  149700. _vq_quantthresh__44u7__p7_0,
  149701. _vq_quantmap__44u7__p7_0,
  149702. 3,
  149703. 3
  149704. };
  149705. static static_codebook _44u7__p7_0 = {
  149706. 4, 81,
  149707. _vq_lengthlist__44u7__p7_0,
  149708. 1, -529137664, 1618345984, 2, 0,
  149709. _vq_quantlist__44u7__p7_0,
  149710. NULL,
  149711. &_vq_auxt__44u7__p7_0,
  149712. NULL,
  149713. 0
  149714. };
  149715. static long _vq_quantlist__44u7__p7_1[] = {
  149716. 5,
  149717. 4,
  149718. 6,
  149719. 3,
  149720. 7,
  149721. 2,
  149722. 8,
  149723. 1,
  149724. 9,
  149725. 0,
  149726. 10,
  149727. };
  149728. static long _vq_lengthlist__44u7__p7_1[] = {
  149729. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6,
  149730. 8, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6, 7, 8, 8, 8, 8,
  149731. 8, 6, 7, 6, 7, 7, 8, 8, 9, 9, 9, 9, 6, 6, 7, 7,
  149732. 7, 8, 8, 9, 9, 9, 9, 7, 8, 7, 8, 8, 9, 9, 9, 9,
  149733. 9, 9, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  149734. 9, 9, 9, 9,10, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  149735. 9, 9,10, 8, 8, 8, 9, 9, 9, 9,10, 9,10,10, 8, 8,
  149736. 8, 9, 9, 9, 9, 9,10,10,10,
  149737. };
  149738. static float _vq_quantthresh__44u7__p7_1[] = {
  149739. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149740. 3.5, 4.5,
  149741. };
  149742. static long _vq_quantmap__44u7__p7_1[] = {
  149743. 9, 7, 5, 3, 1, 0, 2, 4,
  149744. 6, 8, 10,
  149745. };
  149746. static encode_aux_threshmatch _vq_auxt__44u7__p7_1 = {
  149747. _vq_quantthresh__44u7__p7_1,
  149748. _vq_quantmap__44u7__p7_1,
  149749. 11,
  149750. 11
  149751. };
  149752. static static_codebook _44u7__p7_1 = {
  149753. 2, 121,
  149754. _vq_lengthlist__44u7__p7_1,
  149755. 1, -531365888, 1611661312, 4, 0,
  149756. _vq_quantlist__44u7__p7_1,
  149757. NULL,
  149758. &_vq_auxt__44u7__p7_1,
  149759. NULL,
  149760. 0
  149761. };
  149762. static long _vq_quantlist__44u7__p8_0[] = {
  149763. 5,
  149764. 4,
  149765. 6,
  149766. 3,
  149767. 7,
  149768. 2,
  149769. 8,
  149770. 1,
  149771. 9,
  149772. 0,
  149773. 10,
  149774. };
  149775. static long _vq_lengthlist__44u7__p8_0[] = {
  149776. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  149777. 9, 9,11,10,12,12, 5, 6, 5, 7, 7, 9, 9,10,11,12,
  149778. 12, 6, 7, 7, 8, 8,10,10,11,11,13,13, 6, 7, 7, 8,
  149779. 8,10,10,11,12,13,13, 8, 9, 9,10,10,11,11,12,12,
  149780. 14,14, 8, 9, 9,10,10,11,11,12,12,14,14,10,10,10,
  149781. 11,11,13,12,14,14,15,15,10,10,10,12,12,13,13,14,
  149782. 14,15,15,11,12,12,13,13,14,14,15,14,16,15,11,12,
  149783. 12,13,13,14,14,15,15,15,16,
  149784. };
  149785. static float _vq_quantthresh__44u7__p8_0[] = {
  149786. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  149787. 38.5, 49.5,
  149788. };
  149789. static long _vq_quantmap__44u7__p8_0[] = {
  149790. 9, 7, 5, 3, 1, 0, 2, 4,
  149791. 6, 8, 10,
  149792. };
  149793. static encode_aux_threshmatch _vq_auxt__44u7__p8_0 = {
  149794. _vq_quantthresh__44u7__p8_0,
  149795. _vq_quantmap__44u7__p8_0,
  149796. 11,
  149797. 11
  149798. };
  149799. static static_codebook _44u7__p8_0 = {
  149800. 2, 121,
  149801. _vq_lengthlist__44u7__p8_0,
  149802. 1, -524582912, 1618345984, 4, 0,
  149803. _vq_quantlist__44u7__p8_0,
  149804. NULL,
  149805. &_vq_auxt__44u7__p8_0,
  149806. NULL,
  149807. 0
  149808. };
  149809. static long _vq_quantlist__44u7__p8_1[] = {
  149810. 5,
  149811. 4,
  149812. 6,
  149813. 3,
  149814. 7,
  149815. 2,
  149816. 8,
  149817. 1,
  149818. 9,
  149819. 0,
  149820. 10,
  149821. };
  149822. static long _vq_lengthlist__44u7__p8_1[] = {
  149823. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  149824. 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  149825. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  149826. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  149827. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  149828. 7, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  149829. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  149830. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  149831. };
  149832. static float _vq_quantthresh__44u7__p8_1[] = {
  149833. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149834. 3.5, 4.5,
  149835. };
  149836. static long _vq_quantmap__44u7__p8_1[] = {
  149837. 9, 7, 5, 3, 1, 0, 2, 4,
  149838. 6, 8, 10,
  149839. };
  149840. static encode_aux_threshmatch _vq_auxt__44u7__p8_1 = {
  149841. _vq_quantthresh__44u7__p8_1,
  149842. _vq_quantmap__44u7__p8_1,
  149843. 11,
  149844. 11
  149845. };
  149846. static static_codebook _44u7__p8_1 = {
  149847. 2, 121,
  149848. _vq_lengthlist__44u7__p8_1,
  149849. 1, -531365888, 1611661312, 4, 0,
  149850. _vq_quantlist__44u7__p8_1,
  149851. NULL,
  149852. &_vq_auxt__44u7__p8_1,
  149853. NULL,
  149854. 0
  149855. };
  149856. static long _vq_quantlist__44u7__p9_0[] = {
  149857. 5,
  149858. 4,
  149859. 6,
  149860. 3,
  149861. 7,
  149862. 2,
  149863. 8,
  149864. 1,
  149865. 9,
  149866. 0,
  149867. 10,
  149868. };
  149869. static long _vq_lengthlist__44u7__p9_0[] = {
  149870. 1, 3, 3,10,10,10,10,10,10,10,10, 4,10,10,10,10,
  149871. 10,10,10,10,10,10, 4,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,10,10,10,
  149874. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  149875. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  149876. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  149877. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  149878. };
  149879. static float _vq_quantthresh__44u7__p9_0[] = {
  149880. -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5, 1592.5,
  149881. 2229.5, 2866.5,
  149882. };
  149883. static long _vq_quantmap__44u7__p9_0[] = {
  149884. 9, 7, 5, 3, 1, 0, 2, 4,
  149885. 6, 8, 10,
  149886. };
  149887. static encode_aux_threshmatch _vq_auxt__44u7__p9_0 = {
  149888. _vq_quantthresh__44u7__p9_0,
  149889. _vq_quantmap__44u7__p9_0,
  149890. 11,
  149891. 11
  149892. };
  149893. static static_codebook _44u7__p9_0 = {
  149894. 2, 121,
  149895. _vq_lengthlist__44u7__p9_0,
  149896. 1, -512171520, 1630791680, 4, 0,
  149897. _vq_quantlist__44u7__p9_0,
  149898. NULL,
  149899. &_vq_auxt__44u7__p9_0,
  149900. NULL,
  149901. 0
  149902. };
  149903. static long _vq_quantlist__44u7__p9_1[] = {
  149904. 6,
  149905. 5,
  149906. 7,
  149907. 4,
  149908. 8,
  149909. 3,
  149910. 9,
  149911. 2,
  149912. 10,
  149913. 1,
  149914. 11,
  149915. 0,
  149916. 12,
  149917. };
  149918. static long _vq_lengthlist__44u7__p9_1[] = {
  149919. 1, 4, 4, 6, 5, 8, 6, 9, 8,10, 9,11,10, 4, 6, 6,
  149920. 8, 8, 9, 9,11,10,11,11,11,11, 4, 6, 6, 8, 8,10,
  149921. 9,11,11,11,11,11,12, 6, 8, 8,10,10,11,11,12,12,
  149922. 13,12,13,13, 6, 8, 8,10,10,11,11,12,12,12,13,14,
  149923. 13, 8,10,10,11,11,12,13,14,14,14,14,15,15, 8,10,
  149924. 10,11,12,12,13,13,14,14,14,14,15, 9,11,11,13,13,
  149925. 14,14,15,14,16,15,17,15, 9,11,11,12,13,14,14,15,
  149926. 14,15,15,15,16,10,12,12,13,14,15,15,15,15,16,17,
  149927. 16,17,10,13,12,13,14,14,16,16,16,16,15,16,17,11,
  149928. 13,13,14,15,14,17,15,16,17,17,17,17,11,13,13,14,
  149929. 15,15,15,15,17,17,16,17,16,
  149930. };
  149931. static float _vq_quantthresh__44u7__p9_1[] = {
  149932. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  149933. 122.5, 171.5, 220.5, 269.5,
  149934. };
  149935. static long _vq_quantmap__44u7__p9_1[] = {
  149936. 11, 9, 7, 5, 3, 1, 0, 2,
  149937. 4, 6, 8, 10, 12,
  149938. };
  149939. static encode_aux_threshmatch _vq_auxt__44u7__p9_1 = {
  149940. _vq_quantthresh__44u7__p9_1,
  149941. _vq_quantmap__44u7__p9_1,
  149942. 13,
  149943. 13
  149944. };
  149945. static static_codebook _44u7__p9_1 = {
  149946. 2, 169,
  149947. _vq_lengthlist__44u7__p9_1,
  149948. 1, -518889472, 1622704128, 4, 0,
  149949. _vq_quantlist__44u7__p9_1,
  149950. NULL,
  149951. &_vq_auxt__44u7__p9_1,
  149952. NULL,
  149953. 0
  149954. };
  149955. static long _vq_quantlist__44u7__p9_2[] = {
  149956. 24,
  149957. 23,
  149958. 25,
  149959. 22,
  149960. 26,
  149961. 21,
  149962. 27,
  149963. 20,
  149964. 28,
  149965. 19,
  149966. 29,
  149967. 18,
  149968. 30,
  149969. 17,
  149970. 31,
  149971. 16,
  149972. 32,
  149973. 15,
  149974. 33,
  149975. 14,
  149976. 34,
  149977. 13,
  149978. 35,
  149979. 12,
  149980. 36,
  149981. 11,
  149982. 37,
  149983. 10,
  149984. 38,
  149985. 9,
  149986. 39,
  149987. 8,
  149988. 40,
  149989. 7,
  149990. 41,
  149991. 6,
  149992. 42,
  149993. 5,
  149994. 43,
  149995. 4,
  149996. 44,
  149997. 3,
  149998. 45,
  149999. 2,
  150000. 46,
  150001. 1,
  150002. 47,
  150003. 0,
  150004. 48,
  150005. };
  150006. static long _vq_lengthlist__44u7__p9_2[] = {
  150007. 2, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  150008. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  150009. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  150010. 8,
  150011. };
  150012. static float _vq_quantthresh__44u7__p9_2[] = {
  150013. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  150014. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  150015. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150016. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150017. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  150018. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  150019. };
  150020. static long _vq_quantmap__44u7__p9_2[] = {
  150021. 47, 45, 43, 41, 39, 37, 35, 33,
  150022. 31, 29, 27, 25, 23, 21, 19, 17,
  150023. 15, 13, 11, 9, 7, 5, 3, 1,
  150024. 0, 2, 4, 6, 8, 10, 12, 14,
  150025. 16, 18, 20, 22, 24, 26, 28, 30,
  150026. 32, 34, 36, 38, 40, 42, 44, 46,
  150027. 48,
  150028. };
  150029. static encode_aux_threshmatch _vq_auxt__44u7__p9_2 = {
  150030. _vq_quantthresh__44u7__p9_2,
  150031. _vq_quantmap__44u7__p9_2,
  150032. 49,
  150033. 49
  150034. };
  150035. static static_codebook _44u7__p9_2 = {
  150036. 1, 49,
  150037. _vq_lengthlist__44u7__p9_2,
  150038. 1, -526909440, 1611661312, 6, 0,
  150039. _vq_quantlist__44u7__p9_2,
  150040. NULL,
  150041. &_vq_auxt__44u7__p9_2,
  150042. NULL,
  150043. 0
  150044. };
  150045. static long _huff_lengthlist__44u7__short[] = {
  150046. 5,12,17,16,16,17,17,17,17,17, 4, 7,11,11,12, 9,
  150047. 17,10,17,17, 7, 7, 8, 9, 7, 9,11,10,15,17, 7, 9,
  150048. 10,11,10,12,14,12,16,17, 7, 8, 5, 7, 4, 7, 7, 8,
  150049. 16,16, 6,10, 9,10, 7,10,11,11,16,17, 6, 8, 8, 9,
  150050. 5, 7, 5, 8,16,17, 5, 5, 8, 7, 6, 7, 7, 6, 6,14,
  150051. 12,10,12,11, 7,11, 4, 4, 2, 7,17,15,15,15, 8,15,
  150052. 6, 8, 5, 9,
  150053. };
  150054. static static_codebook _huff_book__44u7__short = {
  150055. 2, 100,
  150056. _huff_lengthlist__44u7__short,
  150057. 0, 0, 0, 0, 0,
  150058. NULL,
  150059. NULL,
  150060. NULL,
  150061. NULL,
  150062. 0
  150063. };
  150064. static long _huff_lengthlist__44u8__long[] = {
  150065. 3, 9,13,14,14,15,14,14,15,15, 5, 4, 6, 8,10,12,
  150066. 12,14,15,15, 9, 5, 4, 5, 8,10,11,13,16,16,10, 7,
  150067. 4, 3, 5, 7, 9,11,13,13,10, 9, 7, 4, 4, 6, 8,10,
  150068. 12,14,13,11, 9, 6, 5, 5, 6, 8,12,14,13,11,10, 8,
  150069. 7, 6, 6, 7,10,14,13,11,12,10, 8, 7, 6, 6, 9,13,
  150070. 12,11,14,12,11, 9, 8, 7, 9,11,11,12,14,13,14,11,
  150071. 10, 8, 8, 9,
  150072. };
  150073. static static_codebook _huff_book__44u8__long = {
  150074. 2, 100,
  150075. _huff_lengthlist__44u8__long,
  150076. 0, 0, 0, 0, 0,
  150077. NULL,
  150078. NULL,
  150079. NULL,
  150080. NULL,
  150081. 0
  150082. };
  150083. static long _huff_lengthlist__44u8__short[] = {
  150084. 6,14,18,18,17,17,17,17,17,17, 4, 7, 9, 9,10,13,
  150085. 15,17,17,17, 6, 7, 5, 6, 8,11,16,17,16,17, 5, 7,
  150086. 5, 4, 6,10,14,17,17,17, 6, 6, 6, 5, 7,10,13,16,
  150087. 17,17, 7, 6, 7, 7, 7, 8, 7,10,15,16,12, 9, 9, 6,
  150088. 6, 5, 3, 5,11,15,14,14,13, 5, 5, 7, 3, 4, 8,15,
  150089. 17,17,13, 7, 7,10, 6, 6,10,15,17,17,16,10,11,14,
  150090. 10,10,15,17,
  150091. };
  150092. static static_codebook _huff_book__44u8__short = {
  150093. 2, 100,
  150094. _huff_lengthlist__44u8__short,
  150095. 0, 0, 0, 0, 0,
  150096. NULL,
  150097. NULL,
  150098. NULL,
  150099. NULL,
  150100. 0
  150101. };
  150102. static long _vq_quantlist__44u8_p1_0[] = {
  150103. 1,
  150104. 0,
  150105. 2,
  150106. };
  150107. static long _vq_lengthlist__44u8_p1_0[] = {
  150108. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 8, 9, 9, 7,
  150109. 9, 9, 5, 7, 7, 7, 9, 9, 8, 9, 9, 5, 7, 7, 7, 9,
  150110. 9, 7, 9, 9, 7, 9, 9, 9,10,11, 9,11,10, 7, 9, 9,
  150111. 9,11,10, 9,10,11, 5, 7, 7, 7, 9, 9, 7, 9, 9, 7,
  150112. 9, 9, 9,11,10, 9,10,10, 8, 9, 9, 9,11,11, 9,11,
  150113. 10,
  150114. };
  150115. static float _vq_quantthresh__44u8_p1_0[] = {
  150116. -0.5, 0.5,
  150117. };
  150118. static long _vq_quantmap__44u8_p1_0[] = {
  150119. 1, 0, 2,
  150120. };
  150121. static encode_aux_threshmatch _vq_auxt__44u8_p1_0 = {
  150122. _vq_quantthresh__44u8_p1_0,
  150123. _vq_quantmap__44u8_p1_0,
  150124. 3,
  150125. 3
  150126. };
  150127. static static_codebook _44u8_p1_0 = {
  150128. 4, 81,
  150129. _vq_lengthlist__44u8_p1_0,
  150130. 1, -535822336, 1611661312, 2, 0,
  150131. _vq_quantlist__44u8_p1_0,
  150132. NULL,
  150133. &_vq_auxt__44u8_p1_0,
  150134. NULL,
  150135. 0
  150136. };
  150137. static long _vq_quantlist__44u8_p2_0[] = {
  150138. 2,
  150139. 1,
  150140. 3,
  150141. 0,
  150142. 4,
  150143. };
  150144. static long _vq_lengthlist__44u8_p2_0[] = {
  150145. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  150146. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  150147. 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,10,
  150148. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  150149. 10, 9,10, 9,12,11, 9,10,10,12,12, 8, 9, 9,12,11,
  150150. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,14,11,
  150151. 11,12,13,14, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150152. 10,12,12,11,12,11,13,13,11,12,12,14,14, 5, 7, 7,
  150153. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  150154. 12, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  150155. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,12,13, 6,
  150156. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  150157. 10,13,12,10,11,11,13,13, 9,10,10,12,12,10,11,11,
  150158. 13,13,10,11,11,13,13,12,12,13,13,14,12,13,13,14,
  150159. 14, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  150160. 11,13,12,14,13,12,13,13,14,14, 5, 7, 7, 9, 9, 7,
  150161. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  150162. 10,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  150163. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  150164. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  150165. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  150166. 10,11,12,13,12,13,13,14,14,12,12,13,13,14, 9,10,
  150167. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,13,
  150168. 15,14,12,13,13,14,13, 8, 9, 9,11,11, 9,10,10,12,
  150169. 12, 9,10,10,12,12,12,12,12,14,13,11,12,12,14,14,
  150170. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  150171. 13,13,14,15,12,13,13,14,15, 9,10,10,12,12,10,11,
  150172. 10,13,12,10,11,11,13,13,12,13,12,15,14,12,13,13,
  150173. 14,15,11,12,12,14,14,12,13,13,14,14,12,13,13,15,
  150174. 14,14,14,14,14,16,14,14,15,16,16,11,12,12,14,14,
  150175. 11,12,12,14,14,12,13,13,14,15,13,14,13,16,14,14,
  150176. 14,14,16,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150177. 10,12,12,11,12,12,14,13,11,12,12,14,14, 9,10,10,
  150178. 12,12,10,11,11,13,13,10,10,11,12,13,12,13,13,15,
  150179. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  150180. 10,11,11,13,13,12,13,13,14,14,12,13,13,15,14,11,
  150181. 12,12,14,13,12,13,13,15,14,11,12,12,13,14,14,15,
  150182. 14,16,15,13,13,14,13,16,11,12,12,14,14,12,13,13,
  150183. 14,15,12,13,12,15,14,14,14,14,16,15,14,15,13,16,
  150184. 14,
  150185. };
  150186. static float _vq_quantthresh__44u8_p2_0[] = {
  150187. -1.5, -0.5, 0.5, 1.5,
  150188. };
  150189. static long _vq_quantmap__44u8_p2_0[] = {
  150190. 3, 1, 0, 2, 4,
  150191. };
  150192. static encode_aux_threshmatch _vq_auxt__44u8_p2_0 = {
  150193. _vq_quantthresh__44u8_p2_0,
  150194. _vq_quantmap__44u8_p2_0,
  150195. 5,
  150196. 5
  150197. };
  150198. static static_codebook _44u8_p2_0 = {
  150199. 4, 625,
  150200. _vq_lengthlist__44u8_p2_0,
  150201. 1, -533725184, 1611661312, 3, 0,
  150202. _vq_quantlist__44u8_p2_0,
  150203. NULL,
  150204. &_vq_auxt__44u8_p2_0,
  150205. NULL,
  150206. 0
  150207. };
  150208. static long _vq_quantlist__44u8_p3_0[] = {
  150209. 4,
  150210. 3,
  150211. 5,
  150212. 2,
  150213. 6,
  150214. 1,
  150215. 7,
  150216. 0,
  150217. 8,
  150218. };
  150219. static long _vq_lengthlist__44u8_p3_0[] = {
  150220. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  150221. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  150222. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  150223. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  150224. 9, 9,10,10,11,10,12,11, 9, 9, 9, 9,10,11,11,11,
  150225. 12,
  150226. };
  150227. static float _vq_quantthresh__44u8_p3_0[] = {
  150228. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150229. };
  150230. static long _vq_quantmap__44u8_p3_0[] = {
  150231. 7, 5, 3, 1, 0, 2, 4, 6,
  150232. 8,
  150233. };
  150234. static encode_aux_threshmatch _vq_auxt__44u8_p3_0 = {
  150235. _vq_quantthresh__44u8_p3_0,
  150236. _vq_quantmap__44u8_p3_0,
  150237. 9,
  150238. 9
  150239. };
  150240. static static_codebook _44u8_p3_0 = {
  150241. 2, 81,
  150242. _vq_lengthlist__44u8_p3_0,
  150243. 1, -531628032, 1611661312, 4, 0,
  150244. _vq_quantlist__44u8_p3_0,
  150245. NULL,
  150246. &_vq_auxt__44u8_p3_0,
  150247. NULL,
  150248. 0
  150249. };
  150250. static long _vq_quantlist__44u8_p4_0[] = {
  150251. 8,
  150252. 7,
  150253. 9,
  150254. 6,
  150255. 10,
  150256. 5,
  150257. 11,
  150258. 4,
  150259. 12,
  150260. 3,
  150261. 13,
  150262. 2,
  150263. 14,
  150264. 1,
  150265. 15,
  150266. 0,
  150267. 16,
  150268. };
  150269. static long _vq_lengthlist__44u8_p4_0[] = {
  150270. 4, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,11,11,11,
  150271. 11, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  150272. 12,12, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  150273. 11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  150274. 11,11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,
  150275. 10,11,11,12,12, 7, 7, 7, 8, 8, 9, 8,10, 9,10, 9,
  150276. 11,10,12,11,13,12, 7, 7, 7, 8, 8, 8, 9, 9,10, 9,
  150277. 10,10,11,11,12,12,13, 8, 8, 8, 9, 9, 9, 9,10,10,
  150278. 11,10,11,11,12,12,13,13, 8, 8, 8, 9, 9, 9,10,10,
  150279. 10,10,11,11,11,12,12,12,13, 8, 9, 9, 9, 9,10, 9,
  150280. 11,10,11,11,12,11,13,12,13,13, 8, 9, 9, 9, 9, 9,
  150281. 10,10,11,11,11,11,12,12,13,13,13,10,10,10,10,10,
  150282. 11,10,11,11,12,11,13,12,13,13,14,13,10,10,10,10,
  150283. 10,10,11,11,11,11,12,12,13,13,13,13,14,11,11,11,
  150284. 11,11,12,11,12,12,13,12,13,13,14,13,14,14,11,11,
  150285. 11,11,11,11,12,12,12,12,13,13,13,13,14,14,14,11,
  150286. 12,12,12,12,13,12,13,12,13,13,14,13,14,14,14,14,
  150287. 11,12,12,12,12,12,12,13,13,13,13,13,14,14,14,14,
  150288. 14,
  150289. };
  150290. static float _vq_quantthresh__44u8_p4_0[] = {
  150291. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150292. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150293. };
  150294. static long _vq_quantmap__44u8_p4_0[] = {
  150295. 15, 13, 11, 9, 7, 5, 3, 1,
  150296. 0, 2, 4, 6, 8, 10, 12, 14,
  150297. 16,
  150298. };
  150299. static encode_aux_threshmatch _vq_auxt__44u8_p4_0 = {
  150300. _vq_quantthresh__44u8_p4_0,
  150301. _vq_quantmap__44u8_p4_0,
  150302. 17,
  150303. 17
  150304. };
  150305. static static_codebook _44u8_p4_0 = {
  150306. 2, 289,
  150307. _vq_lengthlist__44u8_p4_0,
  150308. 1, -529530880, 1611661312, 5, 0,
  150309. _vq_quantlist__44u8_p4_0,
  150310. NULL,
  150311. &_vq_auxt__44u8_p4_0,
  150312. NULL,
  150313. 0
  150314. };
  150315. static long _vq_quantlist__44u8_p5_0[] = {
  150316. 1,
  150317. 0,
  150318. 2,
  150319. };
  150320. static long _vq_lengthlist__44u8_p5_0[] = {
  150321. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  150322. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  150323. 10, 8,10,10, 7,10,10, 9,10,12, 9,12,11, 7,10,10,
  150324. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  150325. 10,10, 9,11,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  150326. 10,
  150327. };
  150328. static float _vq_quantthresh__44u8_p5_0[] = {
  150329. -5.5, 5.5,
  150330. };
  150331. static long _vq_quantmap__44u8_p5_0[] = {
  150332. 1, 0, 2,
  150333. };
  150334. static encode_aux_threshmatch _vq_auxt__44u8_p5_0 = {
  150335. _vq_quantthresh__44u8_p5_0,
  150336. _vq_quantmap__44u8_p5_0,
  150337. 3,
  150338. 3
  150339. };
  150340. static static_codebook _44u8_p5_0 = {
  150341. 4, 81,
  150342. _vq_lengthlist__44u8_p5_0,
  150343. 1, -529137664, 1618345984, 2, 0,
  150344. _vq_quantlist__44u8_p5_0,
  150345. NULL,
  150346. &_vq_auxt__44u8_p5_0,
  150347. NULL,
  150348. 0
  150349. };
  150350. static long _vq_quantlist__44u8_p5_1[] = {
  150351. 5,
  150352. 4,
  150353. 6,
  150354. 3,
  150355. 7,
  150356. 2,
  150357. 8,
  150358. 1,
  150359. 9,
  150360. 0,
  150361. 10,
  150362. };
  150363. static long _vq_lengthlist__44u8_p5_1[] = {
  150364. 4, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 5, 5, 6, 6,
  150365. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8,
  150366. 8, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 6, 6, 6, 7,
  150367. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  150368. 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 7, 8, 7,
  150369. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  150370. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 8, 8,
  150371. 8, 8, 8, 8, 8, 8, 8, 9, 9,
  150372. };
  150373. static float _vq_quantthresh__44u8_p5_1[] = {
  150374. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150375. 3.5, 4.5,
  150376. };
  150377. static long _vq_quantmap__44u8_p5_1[] = {
  150378. 9, 7, 5, 3, 1, 0, 2, 4,
  150379. 6, 8, 10,
  150380. };
  150381. static encode_aux_threshmatch _vq_auxt__44u8_p5_1 = {
  150382. _vq_quantthresh__44u8_p5_1,
  150383. _vq_quantmap__44u8_p5_1,
  150384. 11,
  150385. 11
  150386. };
  150387. static static_codebook _44u8_p5_1 = {
  150388. 2, 121,
  150389. _vq_lengthlist__44u8_p5_1,
  150390. 1, -531365888, 1611661312, 4, 0,
  150391. _vq_quantlist__44u8_p5_1,
  150392. NULL,
  150393. &_vq_auxt__44u8_p5_1,
  150394. NULL,
  150395. 0
  150396. };
  150397. static long _vq_quantlist__44u8_p6_0[] = {
  150398. 6,
  150399. 5,
  150400. 7,
  150401. 4,
  150402. 8,
  150403. 3,
  150404. 9,
  150405. 2,
  150406. 10,
  150407. 1,
  150408. 11,
  150409. 0,
  150410. 12,
  150411. };
  150412. static long _vq_lengthlist__44u8_p6_0[] = {
  150413. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  150414. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7, 8,
  150415. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 7, 8, 8, 8, 8, 9,
  150416. 9,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 8,10, 9,11,
  150417. 10, 7, 8, 8, 8, 8, 8, 9, 9, 9,10,10,11,11, 7, 8,
  150418. 8, 8, 8, 9, 8, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  150419. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  150420. 9,10,10,11,11, 9, 9, 9, 9,10,10,10,10,10,10,11,
  150421. 11,12, 9, 9, 9,10, 9,10,10,10,10,11,10,12,11,10,
  150422. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  150423. 11,11,11,11,11,12,11,12,12,
  150424. };
  150425. static float _vq_quantthresh__44u8_p6_0[] = {
  150426. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  150427. 12.5, 17.5, 22.5, 27.5,
  150428. };
  150429. static long _vq_quantmap__44u8_p6_0[] = {
  150430. 11, 9, 7, 5, 3, 1, 0, 2,
  150431. 4, 6, 8, 10, 12,
  150432. };
  150433. static encode_aux_threshmatch _vq_auxt__44u8_p6_0 = {
  150434. _vq_quantthresh__44u8_p6_0,
  150435. _vq_quantmap__44u8_p6_0,
  150436. 13,
  150437. 13
  150438. };
  150439. static static_codebook _44u8_p6_0 = {
  150440. 2, 169,
  150441. _vq_lengthlist__44u8_p6_0,
  150442. 1, -526516224, 1616117760, 4, 0,
  150443. _vq_quantlist__44u8_p6_0,
  150444. NULL,
  150445. &_vq_auxt__44u8_p6_0,
  150446. NULL,
  150447. 0
  150448. };
  150449. static long _vq_quantlist__44u8_p6_1[] = {
  150450. 2,
  150451. 1,
  150452. 3,
  150453. 0,
  150454. 4,
  150455. };
  150456. static long _vq_lengthlist__44u8_p6_1[] = {
  150457. 3, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  150458. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  150459. };
  150460. static float _vq_quantthresh__44u8_p6_1[] = {
  150461. -1.5, -0.5, 0.5, 1.5,
  150462. };
  150463. static long _vq_quantmap__44u8_p6_1[] = {
  150464. 3, 1, 0, 2, 4,
  150465. };
  150466. static encode_aux_threshmatch _vq_auxt__44u8_p6_1 = {
  150467. _vq_quantthresh__44u8_p6_1,
  150468. _vq_quantmap__44u8_p6_1,
  150469. 5,
  150470. 5
  150471. };
  150472. static static_codebook _44u8_p6_1 = {
  150473. 2, 25,
  150474. _vq_lengthlist__44u8_p6_1,
  150475. 1, -533725184, 1611661312, 3, 0,
  150476. _vq_quantlist__44u8_p6_1,
  150477. NULL,
  150478. &_vq_auxt__44u8_p6_1,
  150479. NULL,
  150480. 0
  150481. };
  150482. static long _vq_quantlist__44u8_p7_0[] = {
  150483. 6,
  150484. 5,
  150485. 7,
  150486. 4,
  150487. 8,
  150488. 3,
  150489. 9,
  150490. 2,
  150491. 10,
  150492. 1,
  150493. 11,
  150494. 0,
  150495. 12,
  150496. };
  150497. static long _vq_lengthlist__44u8_p7_0[] = {
  150498. 1, 4, 5, 6, 6, 7, 7, 8, 8,10,10,11,11, 5, 6, 6,
  150499. 7, 7, 8, 8, 9, 9,11,10,12,11, 5, 6, 6, 7, 7, 8,
  150500. 8, 9, 9,10,11,11,12, 6, 7, 7, 8, 8, 9, 9,10,10,
  150501. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,12,13,
  150502. 12, 7, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  150503. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  150504. 11,11,12,12,13,13,14,14, 9, 9, 9,10,10,11,11,12,
  150505. 12,13,13,14,14,10,11,11,12,11,13,12,13,13,14,14,
  150506. 15,15,10,11,11,11,12,12,13,13,14,14,14,15,15,11,
  150507. 12,12,13,13,14,13,15,14,15,15,16,15,11,11,12,13,
  150508. 13,13,14,14,14,15,15,15,16,
  150509. };
  150510. static float _vq_quantthresh__44u8_p7_0[] = {
  150511. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  150512. 27.5, 38.5, 49.5, 60.5,
  150513. };
  150514. static long _vq_quantmap__44u8_p7_0[] = {
  150515. 11, 9, 7, 5, 3, 1, 0, 2,
  150516. 4, 6, 8, 10, 12,
  150517. };
  150518. static encode_aux_threshmatch _vq_auxt__44u8_p7_0 = {
  150519. _vq_quantthresh__44u8_p7_0,
  150520. _vq_quantmap__44u8_p7_0,
  150521. 13,
  150522. 13
  150523. };
  150524. static static_codebook _44u8_p7_0 = {
  150525. 2, 169,
  150526. _vq_lengthlist__44u8_p7_0,
  150527. 1, -523206656, 1618345984, 4, 0,
  150528. _vq_quantlist__44u8_p7_0,
  150529. NULL,
  150530. &_vq_auxt__44u8_p7_0,
  150531. NULL,
  150532. 0
  150533. };
  150534. static long _vq_quantlist__44u8_p7_1[] = {
  150535. 5,
  150536. 4,
  150537. 6,
  150538. 3,
  150539. 7,
  150540. 2,
  150541. 8,
  150542. 1,
  150543. 9,
  150544. 0,
  150545. 10,
  150546. };
  150547. static long _vq_lengthlist__44u8_p7_1[] = {
  150548. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  150549. 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  150550. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  150551. 7, 7, 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8,
  150552. 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 7, 7, 7,
  150553. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  150554. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  150555. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  150556. };
  150557. static float _vq_quantthresh__44u8_p7_1[] = {
  150558. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150559. 3.5, 4.5,
  150560. };
  150561. static long _vq_quantmap__44u8_p7_1[] = {
  150562. 9, 7, 5, 3, 1, 0, 2, 4,
  150563. 6, 8, 10,
  150564. };
  150565. static encode_aux_threshmatch _vq_auxt__44u8_p7_1 = {
  150566. _vq_quantthresh__44u8_p7_1,
  150567. _vq_quantmap__44u8_p7_1,
  150568. 11,
  150569. 11
  150570. };
  150571. static static_codebook _44u8_p7_1 = {
  150572. 2, 121,
  150573. _vq_lengthlist__44u8_p7_1,
  150574. 1, -531365888, 1611661312, 4, 0,
  150575. _vq_quantlist__44u8_p7_1,
  150576. NULL,
  150577. &_vq_auxt__44u8_p7_1,
  150578. NULL,
  150579. 0
  150580. };
  150581. static long _vq_quantlist__44u8_p8_0[] = {
  150582. 7,
  150583. 6,
  150584. 8,
  150585. 5,
  150586. 9,
  150587. 4,
  150588. 10,
  150589. 3,
  150590. 11,
  150591. 2,
  150592. 12,
  150593. 1,
  150594. 13,
  150595. 0,
  150596. 14,
  150597. };
  150598. static long _vq_lengthlist__44u8_p8_0[] = {
  150599. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8,10, 9,11,10, 4,
  150600. 6, 6, 8, 8,10, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  150601. 6, 8, 8,10,10, 9, 9,10,10,11,11,11,12, 7, 8, 8,
  150602. 10,10,11,11,11,10,12,11,12,12,13,11, 7, 8, 8,10,
  150603. 10,11,11,10,10,11,11,12,12,13,13, 8,10,10,11,11,
  150604. 12,11,12,11,13,12,13,12,14,13, 8,10, 9,11,11,12,
  150605. 12,12,12,12,12,13,13,14,13, 8, 9, 9,11,10,12,11,
  150606. 13,12,13,13,14,13,14,13, 8, 9, 9,10,11,12,12,12,
  150607. 12,13,13,14,15,14,14, 9,10,10,12,11,13,12,13,13,
  150608. 14,13,14,14,14,14, 9,10,10,12,12,12,12,13,13,14,
  150609. 14,14,15,14,14,10,11,11,13,12,13,12,14,14,14,14,
  150610. 14,14,15,15,10,11,11,12,12,13,13,14,14,14,15,15,
  150611. 14,16,15,11,12,12,13,12,14,14,14,13,15,14,15,15,
  150612. 15,17,11,12,12,13,13,14,14,14,15,15,14,15,15,14,
  150613. 17,
  150614. };
  150615. static float _vq_quantthresh__44u8_p8_0[] = {
  150616. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  150617. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  150618. };
  150619. static long _vq_quantmap__44u8_p8_0[] = {
  150620. 13, 11, 9, 7, 5, 3, 1, 0,
  150621. 2, 4, 6, 8, 10, 12, 14,
  150622. };
  150623. static encode_aux_threshmatch _vq_auxt__44u8_p8_0 = {
  150624. _vq_quantthresh__44u8_p8_0,
  150625. _vq_quantmap__44u8_p8_0,
  150626. 15,
  150627. 15
  150628. };
  150629. static static_codebook _44u8_p8_0 = {
  150630. 2, 225,
  150631. _vq_lengthlist__44u8_p8_0,
  150632. 1, -520986624, 1620377600, 4, 0,
  150633. _vq_quantlist__44u8_p8_0,
  150634. NULL,
  150635. &_vq_auxt__44u8_p8_0,
  150636. NULL,
  150637. 0
  150638. };
  150639. static long _vq_quantlist__44u8_p8_1[] = {
  150640. 10,
  150641. 9,
  150642. 11,
  150643. 8,
  150644. 12,
  150645. 7,
  150646. 13,
  150647. 6,
  150648. 14,
  150649. 5,
  150650. 15,
  150651. 4,
  150652. 16,
  150653. 3,
  150654. 17,
  150655. 2,
  150656. 18,
  150657. 1,
  150658. 19,
  150659. 0,
  150660. 20,
  150661. };
  150662. static long _vq_lengthlist__44u8_p8_1[] = {
  150663. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  150664. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  150665. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 5, 6, 6, 7, 7, 8,
  150666. 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  150667. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150668. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  150669. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  150670. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10, 8, 8,
  150671. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  150672. 10, 9,10, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,
  150673. 10,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9,
  150674. 9, 9, 9, 9, 9, 9,10,10,10,10, 9,10,10, 9, 9, 9,
  150675. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  150676. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  150677. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,
  150678. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  150679. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  150680. 10, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  150681. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  150682. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  150683. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150684. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  150685. 10,10,10,10,10, 9, 9, 9,10, 9,10,10,10,10,10,10,
  150686. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  150687. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  150688. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  150689. 10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,10,
  150690. 10,10,10,10,10,10,10,10,10,
  150691. };
  150692. static float _vq_quantthresh__44u8_p8_1[] = {
  150693. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  150694. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  150695. 6.5, 7.5, 8.5, 9.5,
  150696. };
  150697. static long _vq_quantmap__44u8_p8_1[] = {
  150698. 19, 17, 15, 13, 11, 9, 7, 5,
  150699. 3, 1, 0, 2, 4, 6, 8, 10,
  150700. 12, 14, 16, 18, 20,
  150701. };
  150702. static encode_aux_threshmatch _vq_auxt__44u8_p8_1 = {
  150703. _vq_quantthresh__44u8_p8_1,
  150704. _vq_quantmap__44u8_p8_1,
  150705. 21,
  150706. 21
  150707. };
  150708. static static_codebook _44u8_p8_1 = {
  150709. 2, 441,
  150710. _vq_lengthlist__44u8_p8_1,
  150711. 1, -529268736, 1611661312, 5, 0,
  150712. _vq_quantlist__44u8_p8_1,
  150713. NULL,
  150714. &_vq_auxt__44u8_p8_1,
  150715. NULL,
  150716. 0
  150717. };
  150718. static long _vq_quantlist__44u8_p9_0[] = {
  150719. 4,
  150720. 3,
  150721. 5,
  150722. 2,
  150723. 6,
  150724. 1,
  150725. 7,
  150726. 0,
  150727. 8,
  150728. };
  150729. static long _vq_lengthlist__44u8_p9_0[] = {
  150730. 1, 3, 3, 9, 9, 9, 9, 9, 9, 4, 9, 9, 9, 9, 9, 9,
  150731. 9, 9, 5, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150732. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150733. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150734. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  150735. 8,
  150736. };
  150737. static float _vq_quantthresh__44u8_p9_0[] = {
  150738. -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5, 2327.5, 3258.5,
  150739. };
  150740. static long _vq_quantmap__44u8_p9_0[] = {
  150741. 7, 5, 3, 1, 0, 2, 4, 6,
  150742. 8,
  150743. };
  150744. static encode_aux_threshmatch _vq_auxt__44u8_p9_0 = {
  150745. _vq_quantthresh__44u8_p9_0,
  150746. _vq_quantmap__44u8_p9_0,
  150747. 9,
  150748. 9
  150749. };
  150750. static static_codebook _44u8_p9_0 = {
  150751. 2, 81,
  150752. _vq_lengthlist__44u8_p9_0,
  150753. 1, -511895552, 1631393792, 4, 0,
  150754. _vq_quantlist__44u8_p9_0,
  150755. NULL,
  150756. &_vq_auxt__44u8_p9_0,
  150757. NULL,
  150758. 0
  150759. };
  150760. static long _vq_quantlist__44u8_p9_1[] = {
  150761. 9,
  150762. 8,
  150763. 10,
  150764. 7,
  150765. 11,
  150766. 6,
  150767. 12,
  150768. 5,
  150769. 13,
  150770. 4,
  150771. 14,
  150772. 3,
  150773. 15,
  150774. 2,
  150775. 16,
  150776. 1,
  150777. 17,
  150778. 0,
  150779. 18,
  150780. };
  150781. static long _vq_lengthlist__44u8_p9_1[] = {
  150782. 1, 4, 4, 7, 7, 8, 7, 8, 6, 9, 7,10, 8,11,10,11,
  150783. 11,11,11, 4, 7, 6, 9, 9,10, 9, 9, 9,10,10,11,10,
  150784. 11,10,11,11,13,11, 4, 7, 7, 9, 9, 9, 9, 9, 9,10,
  150785. 10,11,10,11,11,11,12,11,12, 7, 9, 8,11,11,11,11,
  150786. 10,10,11,11,12,12,12,12,12,12,14,13, 7, 8, 9,10,
  150787. 11,11,11,10,10,11,11,11,11,12,12,14,12,13,14, 8,
  150788. 9, 9,11,11,11,11,11,11,12,12,14,12,15,14,14,14,
  150789. 15,14, 8, 9, 9,11,11,11,11,12,11,12,12,13,13,13,
  150790. 13,13,13,14,14, 8, 9, 9,11,10,12,11,12,12,13,13,
  150791. 13,13,15,14,14,14,16,16, 8, 9, 9,10,11,11,12,12,
  150792. 12,13,13,13,14,14,14,15,16,15,15, 9,10,10,11,12,
  150793. 12,13,13,13,14,14,16,14,14,16,16,16,16,15, 9,10,
  150794. 10,11,11,12,13,13,14,15,14,16,14,15,16,16,16,16,
  150795. 15,10,11,11,12,13,13,14,15,15,15,15,15,16,15,16,
  150796. 15,16,15,15,10,11,11,13,13,14,13,13,15,14,15,15,
  150797. 16,15,15,15,16,15,16,10,12,12,14,14,14,14,14,16,
  150798. 16,15,15,15,16,16,16,16,16,16,11,12,12,14,14,14,
  150799. 14,15,15,16,15,16,15,16,15,16,16,16,16,12,12,13,
  150800. 14,14,15,16,16,16,16,16,16,15,16,16,16,16,16,16,
  150801. 12,13,13,14,14,14,14,15,16,15,16,16,16,16,16,16,
  150802. 16,16,16,12,13,14,14,14,16,15,16,15,16,16,16,16,
  150803. 16,16,16,16,16,16,12,14,13,14,15,15,15,16,15,16,
  150804. 16,15,16,16,16,16,16,16,16,
  150805. };
  150806. static float _vq_quantthresh__44u8_p9_1[] = {
  150807. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  150808. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  150809. 367.5, 416.5,
  150810. };
  150811. static long _vq_quantmap__44u8_p9_1[] = {
  150812. 17, 15, 13, 11, 9, 7, 5, 3,
  150813. 1, 0, 2, 4, 6, 8, 10, 12,
  150814. 14, 16, 18,
  150815. };
  150816. static encode_aux_threshmatch _vq_auxt__44u8_p9_1 = {
  150817. _vq_quantthresh__44u8_p9_1,
  150818. _vq_quantmap__44u8_p9_1,
  150819. 19,
  150820. 19
  150821. };
  150822. static static_codebook _44u8_p9_1 = {
  150823. 2, 361,
  150824. _vq_lengthlist__44u8_p9_1,
  150825. 1, -518287360, 1622704128, 5, 0,
  150826. _vq_quantlist__44u8_p9_1,
  150827. NULL,
  150828. &_vq_auxt__44u8_p9_1,
  150829. NULL,
  150830. 0
  150831. };
  150832. static long _vq_quantlist__44u8_p9_2[] = {
  150833. 24,
  150834. 23,
  150835. 25,
  150836. 22,
  150837. 26,
  150838. 21,
  150839. 27,
  150840. 20,
  150841. 28,
  150842. 19,
  150843. 29,
  150844. 18,
  150845. 30,
  150846. 17,
  150847. 31,
  150848. 16,
  150849. 32,
  150850. 15,
  150851. 33,
  150852. 14,
  150853. 34,
  150854. 13,
  150855. 35,
  150856. 12,
  150857. 36,
  150858. 11,
  150859. 37,
  150860. 10,
  150861. 38,
  150862. 9,
  150863. 39,
  150864. 8,
  150865. 40,
  150866. 7,
  150867. 41,
  150868. 6,
  150869. 42,
  150870. 5,
  150871. 43,
  150872. 4,
  150873. 44,
  150874. 3,
  150875. 45,
  150876. 2,
  150877. 46,
  150878. 1,
  150879. 47,
  150880. 0,
  150881. 48,
  150882. };
  150883. static long _vq_lengthlist__44u8_p9_2[] = {
  150884. 2, 3, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  150885. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  150886. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  150887. 7,
  150888. };
  150889. static float _vq_quantthresh__44u8_p9_2[] = {
  150890. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  150891. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  150892. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150893. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150894. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  150895. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  150896. };
  150897. static long _vq_quantmap__44u8_p9_2[] = {
  150898. 47, 45, 43, 41, 39, 37, 35, 33,
  150899. 31, 29, 27, 25, 23, 21, 19, 17,
  150900. 15, 13, 11, 9, 7, 5, 3, 1,
  150901. 0, 2, 4, 6, 8, 10, 12, 14,
  150902. 16, 18, 20, 22, 24, 26, 28, 30,
  150903. 32, 34, 36, 38, 40, 42, 44, 46,
  150904. 48,
  150905. };
  150906. static encode_aux_threshmatch _vq_auxt__44u8_p9_2 = {
  150907. _vq_quantthresh__44u8_p9_2,
  150908. _vq_quantmap__44u8_p9_2,
  150909. 49,
  150910. 49
  150911. };
  150912. static static_codebook _44u8_p9_2 = {
  150913. 1, 49,
  150914. _vq_lengthlist__44u8_p9_2,
  150915. 1, -526909440, 1611661312, 6, 0,
  150916. _vq_quantlist__44u8_p9_2,
  150917. NULL,
  150918. &_vq_auxt__44u8_p9_2,
  150919. NULL,
  150920. 0
  150921. };
  150922. static long _huff_lengthlist__44u9__long[] = {
  150923. 3, 9,13,13,14,15,14,14,15,15, 5, 5, 9,10,12,12,
  150924. 13,14,16,15,10, 6, 6, 6, 8,11,12,13,16,15,11, 7,
  150925. 5, 3, 5, 8,10,12,15,15,10,10, 7, 4, 3, 5, 8,10,
  150926. 12,12,12,12, 9, 7, 5, 4, 6, 8,10,13,13,12,11, 9,
  150927. 7, 5, 5, 6, 9,12,14,12,12,10, 8, 6, 6, 6, 7,11,
  150928. 13,12,14,13,10, 8, 7, 7, 7,10,11,11,12,13,12,11,
  150929. 10, 8, 8, 9,
  150930. };
  150931. static static_codebook _huff_book__44u9__long = {
  150932. 2, 100,
  150933. _huff_lengthlist__44u9__long,
  150934. 0, 0, 0, 0, 0,
  150935. NULL,
  150936. NULL,
  150937. NULL,
  150938. NULL,
  150939. 0
  150940. };
  150941. static long _huff_lengthlist__44u9__short[] = {
  150942. 9,16,18,18,17,17,17,17,17,17, 5, 8,11,12,11,12,
  150943. 17,17,16,16, 6, 6, 8, 8, 9,10,14,15,16,16, 6, 7,
  150944. 7, 4, 6, 9,13,16,16,16, 6, 6, 7, 4, 5, 8,11,15,
  150945. 17,16, 7, 6, 7, 6, 6, 8, 9,10,14,16,11, 8, 8, 7,
  150946. 6, 6, 3, 4,10,15,14,12,12,10, 5, 6, 3, 3, 8,13,
  150947. 15,17,15,11, 6, 8, 6, 6, 9,14,17,15,15,12, 8,10,
  150948. 9, 9,12,15,
  150949. };
  150950. static static_codebook _huff_book__44u9__short = {
  150951. 2, 100,
  150952. _huff_lengthlist__44u9__short,
  150953. 0, 0, 0, 0, 0,
  150954. NULL,
  150955. NULL,
  150956. NULL,
  150957. NULL,
  150958. 0
  150959. };
  150960. static long _vq_quantlist__44u9_p1_0[] = {
  150961. 1,
  150962. 0,
  150963. 2,
  150964. };
  150965. static long _vq_lengthlist__44u9_p1_0[] = {
  150966. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  150967. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 7, 9,
  150968. 9, 7, 9, 9, 8, 9, 9, 9,10,11, 9,11,11, 7, 9, 9,
  150969. 9,11,10, 9,11,11, 5, 7, 7, 7, 9, 9, 8, 9,10, 7,
  150970. 9, 9, 9,11,11, 9,10,11, 7, 9,10, 9,11,11, 9,11,
  150971. 10,
  150972. };
  150973. static float _vq_quantthresh__44u9_p1_0[] = {
  150974. -0.5, 0.5,
  150975. };
  150976. static long _vq_quantmap__44u9_p1_0[] = {
  150977. 1, 0, 2,
  150978. };
  150979. static encode_aux_threshmatch _vq_auxt__44u9_p1_0 = {
  150980. _vq_quantthresh__44u9_p1_0,
  150981. _vq_quantmap__44u9_p1_0,
  150982. 3,
  150983. 3
  150984. };
  150985. static static_codebook _44u9_p1_0 = {
  150986. 4, 81,
  150987. _vq_lengthlist__44u9_p1_0,
  150988. 1, -535822336, 1611661312, 2, 0,
  150989. _vq_quantlist__44u9_p1_0,
  150990. NULL,
  150991. &_vq_auxt__44u9_p1_0,
  150992. NULL,
  150993. 0
  150994. };
  150995. static long _vq_quantlist__44u9_p2_0[] = {
  150996. 2,
  150997. 1,
  150998. 3,
  150999. 0,
  151000. 4,
  151001. };
  151002. static long _vq_lengthlist__44u9_p2_0[] = {
  151003. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  151004. 9, 9,11,10, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  151005. 8,10,10, 7, 8, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  151006. 11,11, 6, 7, 7, 9, 9, 7, 8, 8,10, 9, 7, 8, 8,10,
  151007. 10, 9,10, 9,11,11, 9,10,10,11,11, 8, 9, 9,11,11,
  151008. 9,10,10,12,11, 9,10,10,11,12,11,11,11,13,13,11,
  151009. 11,11,12,13, 8, 9, 9,11,11, 9,10,10,11,11, 9,10,
  151010. 10,12,11,11,12,11,13,12,11,11,12,13,13, 6, 7, 7,
  151011. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  151012. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  151013. 8, 9, 9,10,10,10,11,11,12,12,10,10,11,12,12, 7,
  151014. 8, 8,10,10, 8, 9, 8,10,10, 8, 9, 9,10,10,10,11,
  151015. 10,12,11,10,10,11,12,12, 9,10,10,11,12,10,11,11,
  151016. 12,12,10,11,10,12,12,12,12,12,13,13,11,12,12,13,
  151017. 13, 9,10,10,11,11, 9,10,10,12,12,10,11,11,12,13,
  151018. 11,12,11,13,12,12,12,12,13,14, 6, 7, 7, 9, 9, 7,
  151019. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,11,11, 9,10,
  151020. 10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,10, 8, 8, 9,
  151021. 10,10,10,11,10,12,12,10,10,11,11,12, 7, 8, 8,10,
  151022. 10, 8, 9, 9,10,10, 8, 9, 9,10,10,10,11,10,12,12,
  151023. 10,11,10,12,12, 9,10,10,12,11,10,11,11,12,12, 9,
  151024. 10,10,12,12,12,12,12,13,13,11,11,12,12,14, 9,10,
  151025. 10,11,12,10,11,11,12,12,10,11,11,12,12,11,12,12,
  151026. 14,14,12,12,12,13,13, 8, 9, 9,11,11, 9,10,10,12,
  151027. 11, 9,10,10,12,12,11,12,11,13,13,11,11,12,13,13,
  151028. 9,10,10,12,12,10,11,11,12,12,10,11,11,12,12,12,
  151029. 12,12,14,14,12,12,12,13,13, 9,10,10,12,11,10,11,
  151030. 10,12,12,10,11,11,12,12,11,12,12,14,13,12,12,12,
  151031. 13,14,11,12,11,13,13,11,12,12,13,13,12,12,12,14,
  151032. 14,13,13,13,13,15,13,13,14,15,15,11,11,11,13,13,
  151033. 11,12,11,13,13,11,12,12,13,13,12,13,12,15,13,13,
  151034. 13,14,14,15, 8, 9, 9,11,11, 9,10,10,11,12, 9,10,
  151035. 10,11,12,11,12,11,13,13,11,12,12,13,13, 9,10,10,
  151036. 11,12,10,11,10,12,12,10,10,11,12,13,12,12,12,14,
  151037. 13,11,12,12,13,14, 9,10,10,12,12,10,11,11,12,12,
  151038. 10,11,11,12,12,12,12,12,14,13,12,12,12,14,13,11,
  151039. 11,11,13,13,11,12,12,14,13,11,11,12,13,13,13,13,
  151040. 13,15,14,12,12,13,13,15,11,12,12,13,13,12,12,12,
  151041. 13,14,11,12,12,13,13,13,13,14,14,15,13,13,13,14,
  151042. 14,
  151043. };
  151044. static float _vq_quantthresh__44u9_p2_0[] = {
  151045. -1.5, -0.5, 0.5, 1.5,
  151046. };
  151047. static long _vq_quantmap__44u9_p2_0[] = {
  151048. 3, 1, 0, 2, 4,
  151049. };
  151050. static encode_aux_threshmatch _vq_auxt__44u9_p2_0 = {
  151051. _vq_quantthresh__44u9_p2_0,
  151052. _vq_quantmap__44u9_p2_0,
  151053. 5,
  151054. 5
  151055. };
  151056. static static_codebook _44u9_p2_0 = {
  151057. 4, 625,
  151058. _vq_lengthlist__44u9_p2_0,
  151059. 1, -533725184, 1611661312, 3, 0,
  151060. _vq_quantlist__44u9_p2_0,
  151061. NULL,
  151062. &_vq_auxt__44u9_p2_0,
  151063. NULL,
  151064. 0
  151065. };
  151066. static long _vq_quantlist__44u9_p3_0[] = {
  151067. 4,
  151068. 3,
  151069. 5,
  151070. 2,
  151071. 6,
  151072. 1,
  151073. 7,
  151074. 0,
  151075. 8,
  151076. };
  151077. static long _vq_lengthlist__44u9_p3_0[] = {
  151078. 3, 4, 4, 5, 5, 7, 7, 8, 8, 4, 5, 5, 6, 6, 7, 7,
  151079. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  151080. 8, 8, 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  151081. 8, 8, 9, 9,10,10, 7, 7, 7, 8, 8, 9, 9,10,10, 8,
  151082. 9, 9,10, 9,10,10,11,11, 8, 9, 9, 9,10,10,10,11,
  151083. 11,
  151084. };
  151085. static float _vq_quantthresh__44u9_p3_0[] = {
  151086. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  151087. };
  151088. static long _vq_quantmap__44u9_p3_0[] = {
  151089. 7, 5, 3, 1, 0, 2, 4, 6,
  151090. 8,
  151091. };
  151092. static encode_aux_threshmatch _vq_auxt__44u9_p3_0 = {
  151093. _vq_quantthresh__44u9_p3_0,
  151094. _vq_quantmap__44u9_p3_0,
  151095. 9,
  151096. 9
  151097. };
  151098. static static_codebook _44u9_p3_0 = {
  151099. 2, 81,
  151100. _vq_lengthlist__44u9_p3_0,
  151101. 1, -531628032, 1611661312, 4, 0,
  151102. _vq_quantlist__44u9_p3_0,
  151103. NULL,
  151104. &_vq_auxt__44u9_p3_0,
  151105. NULL,
  151106. 0
  151107. };
  151108. static long _vq_quantlist__44u9_p4_0[] = {
  151109. 8,
  151110. 7,
  151111. 9,
  151112. 6,
  151113. 10,
  151114. 5,
  151115. 11,
  151116. 4,
  151117. 12,
  151118. 3,
  151119. 13,
  151120. 2,
  151121. 14,
  151122. 1,
  151123. 15,
  151124. 0,
  151125. 16,
  151126. };
  151127. static long _vq_lengthlist__44u9_p4_0[] = {
  151128. 4, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  151129. 11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  151130. 11,11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  151131. 10,11,11, 6, 6, 6, 7, 6, 7, 7, 8, 8, 9, 9,10,10,
  151132. 11,11,12,11, 6, 6, 6, 6, 7, 7, 7, 8, 8, 9, 9,10,
  151133. 10,11,11,11,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,
  151134. 10,10,11,11,12,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  151135. 9,10,10,11,11,12,12, 8, 8, 8, 8, 8, 9, 8,10, 9,
  151136. 10,10,11,10,12,11,13,12, 8, 8, 8, 8, 8, 9, 9, 9,
  151137. 10,10,10,10,11,11,12,12,12, 8, 8, 8, 9, 9, 9, 9,
  151138. 10,10,11,10,12,11,12,12,13,12, 8, 8, 8, 9, 9, 9,
  151139. 9,10,10,10,11,11,11,12,12,12,13, 9, 9, 9,10,10,
  151140. 10,10,11,10,11,11,12,11,13,12,13,13, 9, 9,10,10,
  151141. 10,10,10,10,11,11,11,11,12,12,13,13,13,10,11,10,
  151142. 11,11,11,11,12,11,12,12,13,12,13,13,14,13,10,10,
  151143. 10,11,11,11,11,11,12,12,12,12,13,13,13,13,14,11,
  151144. 11,11,12,11,12,12,12,12,13,13,13,13,14,13,14,14,
  151145. 11,11,11,11,12,12,12,12,12,12,13,13,13,13,14,14,
  151146. 14,
  151147. };
  151148. static float _vq_quantthresh__44u9_p4_0[] = {
  151149. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151150. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151151. };
  151152. static long _vq_quantmap__44u9_p4_0[] = {
  151153. 15, 13, 11, 9, 7, 5, 3, 1,
  151154. 0, 2, 4, 6, 8, 10, 12, 14,
  151155. 16,
  151156. };
  151157. static encode_aux_threshmatch _vq_auxt__44u9_p4_0 = {
  151158. _vq_quantthresh__44u9_p4_0,
  151159. _vq_quantmap__44u9_p4_0,
  151160. 17,
  151161. 17
  151162. };
  151163. static static_codebook _44u9_p4_0 = {
  151164. 2, 289,
  151165. _vq_lengthlist__44u9_p4_0,
  151166. 1, -529530880, 1611661312, 5, 0,
  151167. _vq_quantlist__44u9_p4_0,
  151168. NULL,
  151169. &_vq_auxt__44u9_p4_0,
  151170. NULL,
  151171. 0
  151172. };
  151173. static long _vq_quantlist__44u9_p5_0[] = {
  151174. 1,
  151175. 0,
  151176. 2,
  151177. };
  151178. static long _vq_lengthlist__44u9_p5_0[] = {
  151179. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  151180. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  151181. 10, 8,10,10, 7,10,10, 9,10,12, 9,11,11, 7,10,10,
  151182. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  151183. 10,10, 9,12,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  151184. 10,
  151185. };
  151186. static float _vq_quantthresh__44u9_p5_0[] = {
  151187. -5.5, 5.5,
  151188. };
  151189. static long _vq_quantmap__44u9_p5_0[] = {
  151190. 1, 0, 2,
  151191. };
  151192. static encode_aux_threshmatch _vq_auxt__44u9_p5_0 = {
  151193. _vq_quantthresh__44u9_p5_0,
  151194. _vq_quantmap__44u9_p5_0,
  151195. 3,
  151196. 3
  151197. };
  151198. static static_codebook _44u9_p5_0 = {
  151199. 4, 81,
  151200. _vq_lengthlist__44u9_p5_0,
  151201. 1, -529137664, 1618345984, 2, 0,
  151202. _vq_quantlist__44u9_p5_0,
  151203. NULL,
  151204. &_vq_auxt__44u9_p5_0,
  151205. NULL,
  151206. 0
  151207. };
  151208. static long _vq_quantlist__44u9_p5_1[] = {
  151209. 5,
  151210. 4,
  151211. 6,
  151212. 3,
  151213. 7,
  151214. 2,
  151215. 8,
  151216. 1,
  151217. 9,
  151218. 0,
  151219. 10,
  151220. };
  151221. static long _vq_lengthlist__44u9_p5_1[] = {
  151222. 5, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 6,
  151223. 7, 7, 7, 7, 8, 7, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  151224. 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 6, 6, 6, 7,
  151225. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  151226. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  151227. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  151228. 8, 8, 8, 7, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  151229. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  151230. };
  151231. static float _vq_quantthresh__44u9_p5_1[] = {
  151232. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151233. 3.5, 4.5,
  151234. };
  151235. static long _vq_quantmap__44u9_p5_1[] = {
  151236. 9, 7, 5, 3, 1, 0, 2, 4,
  151237. 6, 8, 10,
  151238. };
  151239. static encode_aux_threshmatch _vq_auxt__44u9_p5_1 = {
  151240. _vq_quantthresh__44u9_p5_1,
  151241. _vq_quantmap__44u9_p5_1,
  151242. 11,
  151243. 11
  151244. };
  151245. static static_codebook _44u9_p5_1 = {
  151246. 2, 121,
  151247. _vq_lengthlist__44u9_p5_1,
  151248. 1, -531365888, 1611661312, 4, 0,
  151249. _vq_quantlist__44u9_p5_1,
  151250. NULL,
  151251. &_vq_auxt__44u9_p5_1,
  151252. NULL,
  151253. 0
  151254. };
  151255. static long _vq_quantlist__44u9_p6_0[] = {
  151256. 6,
  151257. 5,
  151258. 7,
  151259. 4,
  151260. 8,
  151261. 3,
  151262. 9,
  151263. 2,
  151264. 10,
  151265. 1,
  151266. 11,
  151267. 0,
  151268. 12,
  151269. };
  151270. static long _vq_lengthlist__44u9_p6_0[] = {
  151271. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  151272. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 5, 6, 7, 7, 8,
  151273. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  151274. 10,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  151275. 10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 7, 8,
  151276. 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  151277. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  151278. 9,10,10,11,11, 9, 9, 9,10,10,10,10,10,11,11,11,
  151279. 11,12, 9, 9, 9,10,10,10,10,10,10,11,10,12,11,10,
  151280. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  151281. 10,11,11,11,11,12,11,12,12,
  151282. };
  151283. static float _vq_quantthresh__44u9_p6_0[] = {
  151284. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  151285. 12.5, 17.5, 22.5, 27.5,
  151286. };
  151287. static long _vq_quantmap__44u9_p6_0[] = {
  151288. 11, 9, 7, 5, 3, 1, 0, 2,
  151289. 4, 6, 8, 10, 12,
  151290. };
  151291. static encode_aux_threshmatch _vq_auxt__44u9_p6_0 = {
  151292. _vq_quantthresh__44u9_p6_0,
  151293. _vq_quantmap__44u9_p6_0,
  151294. 13,
  151295. 13
  151296. };
  151297. static static_codebook _44u9_p6_0 = {
  151298. 2, 169,
  151299. _vq_lengthlist__44u9_p6_0,
  151300. 1, -526516224, 1616117760, 4, 0,
  151301. _vq_quantlist__44u9_p6_0,
  151302. NULL,
  151303. &_vq_auxt__44u9_p6_0,
  151304. NULL,
  151305. 0
  151306. };
  151307. static long _vq_quantlist__44u9_p6_1[] = {
  151308. 2,
  151309. 1,
  151310. 3,
  151311. 0,
  151312. 4,
  151313. };
  151314. static long _vq_lengthlist__44u9_p6_1[] = {
  151315. 4, 4, 4, 5, 5, 4, 5, 4, 5, 5, 4, 4, 5, 5, 5, 5,
  151316. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  151317. };
  151318. static float _vq_quantthresh__44u9_p6_1[] = {
  151319. -1.5, -0.5, 0.5, 1.5,
  151320. };
  151321. static long _vq_quantmap__44u9_p6_1[] = {
  151322. 3, 1, 0, 2, 4,
  151323. };
  151324. static encode_aux_threshmatch _vq_auxt__44u9_p6_1 = {
  151325. _vq_quantthresh__44u9_p6_1,
  151326. _vq_quantmap__44u9_p6_1,
  151327. 5,
  151328. 5
  151329. };
  151330. static static_codebook _44u9_p6_1 = {
  151331. 2, 25,
  151332. _vq_lengthlist__44u9_p6_1,
  151333. 1, -533725184, 1611661312, 3, 0,
  151334. _vq_quantlist__44u9_p6_1,
  151335. NULL,
  151336. &_vq_auxt__44u9_p6_1,
  151337. NULL,
  151338. 0
  151339. };
  151340. static long _vq_quantlist__44u9_p7_0[] = {
  151341. 6,
  151342. 5,
  151343. 7,
  151344. 4,
  151345. 8,
  151346. 3,
  151347. 9,
  151348. 2,
  151349. 10,
  151350. 1,
  151351. 11,
  151352. 0,
  151353. 12,
  151354. };
  151355. static long _vq_lengthlist__44u9_p7_0[] = {
  151356. 1, 4, 5, 6, 6, 7, 7, 8, 9,10,10,11,11, 5, 6, 6,
  151357. 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 6, 6, 7, 7, 8,
  151358. 8, 9, 9,10,10,11,11, 6, 7, 7, 8, 8, 9, 9,10,10,
  151359. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,12,
  151360. 12, 8, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  151361. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  151362. 11,11,12,12,13,13,13,13, 9, 9, 9,10,10,11,11,12,
  151363. 12,13,13,14,14,10,10,10,11,11,12,12,13,13,14,13,
  151364. 15,14,10,10,10,11,11,12,12,13,13,14,14,14,14,11,
  151365. 11,12,12,12,13,13,14,14,14,14,15,15,11,11,12,12,
  151366. 12,13,13,14,14,14,15,15,15,
  151367. };
  151368. static float _vq_quantthresh__44u9_p7_0[] = {
  151369. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  151370. 27.5, 38.5, 49.5, 60.5,
  151371. };
  151372. static long _vq_quantmap__44u9_p7_0[] = {
  151373. 11, 9, 7, 5, 3, 1, 0, 2,
  151374. 4, 6, 8, 10, 12,
  151375. };
  151376. static encode_aux_threshmatch _vq_auxt__44u9_p7_0 = {
  151377. _vq_quantthresh__44u9_p7_0,
  151378. _vq_quantmap__44u9_p7_0,
  151379. 13,
  151380. 13
  151381. };
  151382. static static_codebook _44u9_p7_0 = {
  151383. 2, 169,
  151384. _vq_lengthlist__44u9_p7_0,
  151385. 1, -523206656, 1618345984, 4, 0,
  151386. _vq_quantlist__44u9_p7_0,
  151387. NULL,
  151388. &_vq_auxt__44u9_p7_0,
  151389. NULL,
  151390. 0
  151391. };
  151392. static long _vq_quantlist__44u9_p7_1[] = {
  151393. 5,
  151394. 4,
  151395. 6,
  151396. 3,
  151397. 7,
  151398. 2,
  151399. 8,
  151400. 1,
  151401. 9,
  151402. 0,
  151403. 10,
  151404. };
  151405. static long _vq_lengthlist__44u9_p7_1[] = {
  151406. 5, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7,
  151407. 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  151408. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 7, 7, 7,
  151409. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151410. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151411. 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151412. 7, 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 8, 7, 7,
  151413. 7, 7, 7, 7, 7, 8, 8, 8, 8,
  151414. };
  151415. static float _vq_quantthresh__44u9_p7_1[] = {
  151416. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151417. 3.5, 4.5,
  151418. };
  151419. static long _vq_quantmap__44u9_p7_1[] = {
  151420. 9, 7, 5, 3, 1, 0, 2, 4,
  151421. 6, 8, 10,
  151422. };
  151423. static encode_aux_threshmatch _vq_auxt__44u9_p7_1 = {
  151424. _vq_quantthresh__44u9_p7_1,
  151425. _vq_quantmap__44u9_p7_1,
  151426. 11,
  151427. 11
  151428. };
  151429. static static_codebook _44u9_p7_1 = {
  151430. 2, 121,
  151431. _vq_lengthlist__44u9_p7_1,
  151432. 1, -531365888, 1611661312, 4, 0,
  151433. _vq_quantlist__44u9_p7_1,
  151434. NULL,
  151435. &_vq_auxt__44u9_p7_1,
  151436. NULL,
  151437. 0
  151438. };
  151439. static long _vq_quantlist__44u9_p8_0[] = {
  151440. 7,
  151441. 6,
  151442. 8,
  151443. 5,
  151444. 9,
  151445. 4,
  151446. 10,
  151447. 3,
  151448. 11,
  151449. 2,
  151450. 12,
  151451. 1,
  151452. 13,
  151453. 0,
  151454. 14,
  151455. };
  151456. static long _vq_lengthlist__44u9_p8_0[] = {
  151457. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,11,10, 4,
  151458. 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  151459. 6, 8, 8, 9,10, 9, 9,10,10,11,11,12,12, 7, 8, 8,
  151460. 10,10,11,11,10,10,11,11,12,12,13,12, 7, 8, 8,10,
  151461. 10,11,11,10,10,11,11,12,12,12,13, 8,10, 9,11,11,
  151462. 12,12,11,11,12,12,13,13,14,13, 8, 9, 9,11,11,12,
  151463. 12,11,12,12,12,13,13,14,13, 8, 9, 9,10,10,12,11,
  151464. 13,12,13,13,14,13,15,14, 8, 9, 9,10,10,11,12,12,
  151465. 12,13,13,13,14,14,14, 9,10,10,12,11,13,12,13,13,
  151466. 14,13,14,14,14,15, 9,10,10,11,12,12,12,13,13,14,
  151467. 14,14,15,15,15,10,11,11,12,12,13,13,14,14,14,14,
  151468. 15,14,16,15,10,11,11,12,12,13,13,13,14,14,14,14,
  151469. 14,15,16,11,12,12,13,13,14,13,14,14,15,14,15,16,
  151470. 16,16,11,12,12,13,13,14,13,14,14,15,15,15,16,15,
  151471. 15,
  151472. };
  151473. static float _vq_quantthresh__44u9_p8_0[] = {
  151474. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  151475. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  151476. };
  151477. static long _vq_quantmap__44u9_p8_0[] = {
  151478. 13, 11, 9, 7, 5, 3, 1, 0,
  151479. 2, 4, 6, 8, 10, 12, 14,
  151480. };
  151481. static encode_aux_threshmatch _vq_auxt__44u9_p8_0 = {
  151482. _vq_quantthresh__44u9_p8_0,
  151483. _vq_quantmap__44u9_p8_0,
  151484. 15,
  151485. 15
  151486. };
  151487. static static_codebook _44u9_p8_0 = {
  151488. 2, 225,
  151489. _vq_lengthlist__44u9_p8_0,
  151490. 1, -520986624, 1620377600, 4, 0,
  151491. _vq_quantlist__44u9_p8_0,
  151492. NULL,
  151493. &_vq_auxt__44u9_p8_0,
  151494. NULL,
  151495. 0
  151496. };
  151497. static long _vq_quantlist__44u9_p8_1[] = {
  151498. 10,
  151499. 9,
  151500. 11,
  151501. 8,
  151502. 12,
  151503. 7,
  151504. 13,
  151505. 6,
  151506. 14,
  151507. 5,
  151508. 15,
  151509. 4,
  151510. 16,
  151511. 3,
  151512. 17,
  151513. 2,
  151514. 18,
  151515. 1,
  151516. 19,
  151517. 0,
  151518. 20,
  151519. };
  151520. static long _vq_lengthlist__44u9_p8_1[] = {
  151521. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  151522. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  151523. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8,
  151524. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  151525. 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  151526. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  151527. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  151528. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10, 8, 8,
  151529. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151530. 9,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151531. 10, 9,10, 9,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  151532. 9, 9, 9, 9, 9,10,10, 9,10,10,10,10,10, 9, 9, 9,
  151533. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151534. 10,10, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  151535. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151536. 9, 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  151537. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  151538. 10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151539. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  151540. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  151541. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151542. 9, 9, 9, 9,10, 9, 9,10,10,10,10,10,10,10,10,10,
  151543. 10,10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,
  151544. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,10,
  151545. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  151546. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  151547. 10,10,10,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  151548. 10,10,10,10,10,10,10,10,10,
  151549. };
  151550. static float _vq_quantthresh__44u9_p8_1[] = {
  151551. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  151552. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  151553. 6.5, 7.5, 8.5, 9.5,
  151554. };
  151555. static long _vq_quantmap__44u9_p8_1[] = {
  151556. 19, 17, 15, 13, 11, 9, 7, 5,
  151557. 3, 1, 0, 2, 4, 6, 8, 10,
  151558. 12, 14, 16, 18, 20,
  151559. };
  151560. static encode_aux_threshmatch _vq_auxt__44u9_p8_1 = {
  151561. _vq_quantthresh__44u9_p8_1,
  151562. _vq_quantmap__44u9_p8_1,
  151563. 21,
  151564. 21
  151565. };
  151566. static static_codebook _44u9_p8_1 = {
  151567. 2, 441,
  151568. _vq_lengthlist__44u9_p8_1,
  151569. 1, -529268736, 1611661312, 5, 0,
  151570. _vq_quantlist__44u9_p8_1,
  151571. NULL,
  151572. &_vq_auxt__44u9_p8_1,
  151573. NULL,
  151574. 0
  151575. };
  151576. static long _vq_quantlist__44u9_p9_0[] = {
  151577. 7,
  151578. 6,
  151579. 8,
  151580. 5,
  151581. 9,
  151582. 4,
  151583. 10,
  151584. 3,
  151585. 11,
  151586. 2,
  151587. 12,
  151588. 1,
  151589. 13,
  151590. 0,
  151591. 14,
  151592. };
  151593. static long _vq_lengthlist__44u9_p9_0[] = {
  151594. 1, 3, 3,11,11,11,11,11,11,11,11,11,11,11,11, 4,
  151595. 10,11,11,11,11,11,11,11,11,11,11,11,11,11, 4,10,
  151596. 10,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. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151604. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151605. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151606. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151607. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151608. 10,
  151609. };
  151610. static float _vq_quantthresh__44u9_p9_0[] = {
  151611. -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5,
  151612. 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  151613. };
  151614. static long _vq_quantmap__44u9_p9_0[] = {
  151615. 13, 11, 9, 7, 5, 3, 1, 0,
  151616. 2, 4, 6, 8, 10, 12, 14,
  151617. };
  151618. static encode_aux_threshmatch _vq_auxt__44u9_p9_0 = {
  151619. _vq_quantthresh__44u9_p9_0,
  151620. _vq_quantmap__44u9_p9_0,
  151621. 15,
  151622. 15
  151623. };
  151624. static static_codebook _44u9_p9_0 = {
  151625. 2, 225,
  151626. _vq_lengthlist__44u9_p9_0,
  151627. 1, -510036736, 1631393792, 4, 0,
  151628. _vq_quantlist__44u9_p9_0,
  151629. NULL,
  151630. &_vq_auxt__44u9_p9_0,
  151631. NULL,
  151632. 0
  151633. };
  151634. static long _vq_quantlist__44u9_p9_1[] = {
  151635. 9,
  151636. 8,
  151637. 10,
  151638. 7,
  151639. 11,
  151640. 6,
  151641. 12,
  151642. 5,
  151643. 13,
  151644. 4,
  151645. 14,
  151646. 3,
  151647. 15,
  151648. 2,
  151649. 16,
  151650. 1,
  151651. 17,
  151652. 0,
  151653. 18,
  151654. };
  151655. static long _vq_lengthlist__44u9_p9_1[] = {
  151656. 1, 4, 4, 7, 7, 8, 7, 8, 7, 9, 8,10, 9,10,10,11,
  151657. 11,12,12, 4, 7, 6, 9, 9,10, 9, 9, 8,10,10,11,10,
  151658. 12,10,13,12,13,12, 4, 6, 6, 9, 9, 9, 9, 9, 9,10,
  151659. 10,11,11,11,12,12,12,12,12, 7, 9, 8,11,10,10,10,
  151660. 11,10,11,11,12,12,13,12,13,13,13,13, 7, 8, 9,10,
  151661. 10,11,11,10,10,11,11,11,12,13,13,13,13,14,14, 8,
  151662. 9, 9,11,11,12,11,12,12,13,12,12,13,13,14,15,14,
  151663. 14,14, 8, 9, 9,10,11,11,11,12,12,13,12,13,13,14,
  151664. 14,14,15,14,16, 8, 9, 9,11,10,12,12,12,12,15,13,
  151665. 13,13,17,14,15,15,15,14, 8, 9, 9,10,11,11,12,13,
  151666. 12,13,13,13,14,15,14,14,14,16,15, 9,11,10,12,12,
  151667. 13,13,13,13,14,14,16,15,14,14,14,15,15,17, 9,10,
  151668. 10,11,11,13,13,13,14,14,13,15,14,15,14,15,16,15,
  151669. 16,10,11,11,12,12,13,14,15,14,15,14,14,15,17,16,
  151670. 15,15,17,17,10,12,11,13,12,14,14,13,14,15,15,15,
  151671. 15,16,17,17,15,17,16,11,12,12,14,13,15,14,15,16,
  151672. 17,15,17,15,17,15,15,16,17,15,11,11,12,14,14,14,
  151673. 14,14,15,15,16,15,17,17,17,16,17,16,15,12,12,13,
  151674. 14,14,14,15,14,15,15,16,16,17,16,17,15,17,17,16,
  151675. 12,14,12,14,14,15,15,15,14,14,16,16,16,15,16,16,
  151676. 15,17,15,12,13,13,14,15,14,15,17,15,17,16,17,17,
  151677. 17,16,17,16,17,17,12,13,13,14,16,15,15,15,16,15,
  151678. 17,17,15,17,15,17,16,16,17,
  151679. };
  151680. static float _vq_quantthresh__44u9_p9_1[] = {
  151681. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  151682. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  151683. 367.5, 416.5,
  151684. };
  151685. static long _vq_quantmap__44u9_p9_1[] = {
  151686. 17, 15, 13, 11, 9, 7, 5, 3,
  151687. 1, 0, 2, 4, 6, 8, 10, 12,
  151688. 14, 16, 18,
  151689. };
  151690. static encode_aux_threshmatch _vq_auxt__44u9_p9_1 = {
  151691. _vq_quantthresh__44u9_p9_1,
  151692. _vq_quantmap__44u9_p9_1,
  151693. 19,
  151694. 19
  151695. };
  151696. static static_codebook _44u9_p9_1 = {
  151697. 2, 361,
  151698. _vq_lengthlist__44u9_p9_1,
  151699. 1, -518287360, 1622704128, 5, 0,
  151700. _vq_quantlist__44u9_p9_1,
  151701. NULL,
  151702. &_vq_auxt__44u9_p9_1,
  151703. NULL,
  151704. 0
  151705. };
  151706. static long _vq_quantlist__44u9_p9_2[] = {
  151707. 24,
  151708. 23,
  151709. 25,
  151710. 22,
  151711. 26,
  151712. 21,
  151713. 27,
  151714. 20,
  151715. 28,
  151716. 19,
  151717. 29,
  151718. 18,
  151719. 30,
  151720. 17,
  151721. 31,
  151722. 16,
  151723. 32,
  151724. 15,
  151725. 33,
  151726. 14,
  151727. 34,
  151728. 13,
  151729. 35,
  151730. 12,
  151731. 36,
  151732. 11,
  151733. 37,
  151734. 10,
  151735. 38,
  151736. 9,
  151737. 39,
  151738. 8,
  151739. 40,
  151740. 7,
  151741. 41,
  151742. 6,
  151743. 42,
  151744. 5,
  151745. 43,
  151746. 4,
  151747. 44,
  151748. 3,
  151749. 45,
  151750. 2,
  151751. 46,
  151752. 1,
  151753. 47,
  151754. 0,
  151755. 48,
  151756. };
  151757. static long _vq_lengthlist__44u9_p9_2[] = {
  151758. 2, 4, 4, 5, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  151759. 6, 6, 6, 7, 6, 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151760. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151761. 7,
  151762. };
  151763. static float _vq_quantthresh__44u9_p9_2[] = {
  151764. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  151765. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  151766. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151767. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151768. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  151769. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  151770. };
  151771. static long _vq_quantmap__44u9_p9_2[] = {
  151772. 47, 45, 43, 41, 39, 37, 35, 33,
  151773. 31, 29, 27, 25, 23, 21, 19, 17,
  151774. 15, 13, 11, 9, 7, 5, 3, 1,
  151775. 0, 2, 4, 6, 8, 10, 12, 14,
  151776. 16, 18, 20, 22, 24, 26, 28, 30,
  151777. 32, 34, 36, 38, 40, 42, 44, 46,
  151778. 48,
  151779. };
  151780. static encode_aux_threshmatch _vq_auxt__44u9_p9_2 = {
  151781. _vq_quantthresh__44u9_p9_2,
  151782. _vq_quantmap__44u9_p9_2,
  151783. 49,
  151784. 49
  151785. };
  151786. static static_codebook _44u9_p9_2 = {
  151787. 1, 49,
  151788. _vq_lengthlist__44u9_p9_2,
  151789. 1, -526909440, 1611661312, 6, 0,
  151790. _vq_quantlist__44u9_p9_2,
  151791. NULL,
  151792. &_vq_auxt__44u9_p9_2,
  151793. NULL,
  151794. 0
  151795. };
  151796. static long _huff_lengthlist__44un1__long[] = {
  151797. 5, 6,12, 9,14, 9, 9,19, 6, 1, 5, 5, 8, 7, 9,19,
  151798. 12, 4, 4, 7, 7, 9,11,18, 9, 5, 6, 6, 8, 7, 8,17,
  151799. 14, 8, 7, 8, 8,10,12,18, 9, 6, 8, 6, 8, 6, 8,18,
  151800. 9, 8,11, 8,11, 7, 5,15,16,18,18,18,17,15,11,18,
  151801. };
  151802. static static_codebook _huff_book__44un1__long = {
  151803. 2, 64,
  151804. _huff_lengthlist__44un1__long,
  151805. 0, 0, 0, 0, 0,
  151806. NULL,
  151807. NULL,
  151808. NULL,
  151809. NULL,
  151810. 0
  151811. };
  151812. static long _vq_quantlist__44un1__p1_0[] = {
  151813. 1,
  151814. 0,
  151815. 2,
  151816. };
  151817. static long _vq_lengthlist__44un1__p1_0[] = {
  151818. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  151819. 10,11, 5, 8, 8, 8,11,10, 8,11,10, 4, 9, 9, 8,11,
  151820. 11, 8,11,11, 8,12,11,10,12,14,11,13,13, 7,11,11,
  151821. 10,13,11,11,13,14, 4, 8, 9, 8,11,11, 8,11,12, 7,
  151822. 11,11,11,14,13,10,11,13, 8,11,12,11,13,13,10,14,
  151823. 12,
  151824. };
  151825. static float _vq_quantthresh__44un1__p1_0[] = {
  151826. -0.5, 0.5,
  151827. };
  151828. static long _vq_quantmap__44un1__p1_0[] = {
  151829. 1, 0, 2,
  151830. };
  151831. static encode_aux_threshmatch _vq_auxt__44un1__p1_0 = {
  151832. _vq_quantthresh__44un1__p1_0,
  151833. _vq_quantmap__44un1__p1_0,
  151834. 3,
  151835. 3
  151836. };
  151837. static static_codebook _44un1__p1_0 = {
  151838. 4, 81,
  151839. _vq_lengthlist__44un1__p1_0,
  151840. 1, -535822336, 1611661312, 2, 0,
  151841. _vq_quantlist__44un1__p1_0,
  151842. NULL,
  151843. &_vq_auxt__44un1__p1_0,
  151844. NULL,
  151845. 0
  151846. };
  151847. static long _vq_quantlist__44un1__p2_0[] = {
  151848. 1,
  151849. 0,
  151850. 2,
  151851. };
  151852. static long _vq_lengthlist__44un1__p2_0[] = {
  151853. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  151854. 7, 9, 5, 7, 7, 6, 8, 7, 7, 9, 8, 4, 7, 7, 7, 9,
  151855. 8, 7, 8, 8, 7, 9, 8, 8, 8,10, 9,10,10, 6, 8, 8,
  151856. 7,10, 8, 9,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  151857. 8, 8, 9,10,10, 7, 8,10, 6, 8, 9, 9,10,10, 8,10,
  151858. 8,
  151859. };
  151860. static float _vq_quantthresh__44un1__p2_0[] = {
  151861. -0.5, 0.5,
  151862. };
  151863. static long _vq_quantmap__44un1__p2_0[] = {
  151864. 1, 0, 2,
  151865. };
  151866. static encode_aux_threshmatch _vq_auxt__44un1__p2_0 = {
  151867. _vq_quantthresh__44un1__p2_0,
  151868. _vq_quantmap__44un1__p2_0,
  151869. 3,
  151870. 3
  151871. };
  151872. static static_codebook _44un1__p2_0 = {
  151873. 4, 81,
  151874. _vq_lengthlist__44un1__p2_0,
  151875. 1, -535822336, 1611661312, 2, 0,
  151876. _vq_quantlist__44un1__p2_0,
  151877. NULL,
  151878. &_vq_auxt__44un1__p2_0,
  151879. NULL,
  151880. 0
  151881. };
  151882. static long _vq_quantlist__44un1__p3_0[] = {
  151883. 2,
  151884. 1,
  151885. 3,
  151886. 0,
  151887. 4,
  151888. };
  151889. static long _vq_lengthlist__44un1__p3_0[] = {
  151890. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  151891. 10, 9,12,12, 9, 9,10,11,12, 6, 8, 8,10,10, 8,10,
  151892. 10,11,11, 8, 9,10,11,11,10,11,11,13,13,10,11,11,
  151893. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10,10,11,
  151894. 11,10,11,11,13,12,10,11,11,13,12, 9,11,11,15,13,
  151895. 10,12,11,15,13,10,11,11,15,14,12,14,13,16,15,12,
  151896. 13,13,17,16, 9,11,11,13,15,10,11,12,14,15,10,11,
  151897. 12,14,15,12,13,13,15,16,12,13,13,16,16, 5, 8, 8,
  151898. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  151899. 14,11,12,12,14,14, 8,11,10,13,12,10,11,12,12,13,
  151900. 10,12,12,13,13,12,12,13,13,15,11,12,13,15,14, 7,
  151901. 10,10,12,12, 9,12,11,13,12,10,12,12,13,14,12,13,
  151902. 12,15,13,11,13,12,14,15,10,12,12,16,14,11,12,12,
  151903. 16,15,11,13,12,17,16,13,13,15,15,17,13,15,15,20,
  151904. 17,10,12,12,14,16,11,12,12,15,15,11,13,13,15,18,
  151905. 13,14,13,15,15,13,15,14,16,16, 5, 8, 8,11,11, 8,
  151906. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  151907. 12,14,15, 7,10,10,13,12,10,12,12,14,13, 9,10,12,
  151908. 12,13,11,13,13,15,15,11,12,13,13,15, 8,10,10,12,
  151909. 13,10,12,12,13,13,10,12,11,13,13,11,13,12,15,15,
  151910. 12,13,12,15,13,10,12,12,16,14,11,12,12,16,15,10,
  151911. 12,12,16,14,14,15,14,18,16,13,13,14,15,16,10,12,
  151912. 12,14,16,11,13,13,16,16,11,13,12,14,16,13,15,15,
  151913. 18,18,13,15,13,16,14, 8,11,11,16,16,10,13,13,17,
  151914. 16,10,12,12,16,15,14,16,15,20,17,13,14,14,17,17,
  151915. 9,12,12,16,16,11,13,14,16,17,11,13,13,16,16,15,
  151916. 15,19,18, 0,14,15,15,18,18, 9,12,12,17,16,11,13,
  151917. 12,17,16,11,12,13,15,17,15,16,15, 0,19,14,15,14,
  151918. 19,18,12,14,14, 0,16,13,14,14,19,18,13,15,16,17,
  151919. 16,15,15,17,18, 0,14,16,16,19, 0,12,14,14,16,18,
  151920. 13,15,13,17,18,13,15,14,17,18,15,18,14,18,18,16,
  151921. 17,16, 0,17, 8,11,11,15,15,10,12,12,16,16,10,13,
  151922. 13,16,16,13,15,14,17,17,14,15,17,17,18, 9,12,12,
  151923. 16,15,11,13,13,16,16,11,12,13,17,17,14,14,15,17,
  151924. 17,14,15,16, 0,18, 9,12,12,16,17,11,13,13,16,17,
  151925. 11,14,13,18,17,14,16,14,17,17,15,17,17,18,18,12,
  151926. 14,14, 0,16,13,15,15,19, 0,12,13,15, 0, 0,14,17,
  151927. 16,19, 0,16,15,18,18, 0,12,14,14,17, 0,13,14,14,
  151928. 17, 0,13,15,14, 0,18,15,16,16, 0,18,15,18,15, 0,
  151929. 17,
  151930. };
  151931. static float _vq_quantthresh__44un1__p3_0[] = {
  151932. -1.5, -0.5, 0.5, 1.5,
  151933. };
  151934. static long _vq_quantmap__44un1__p3_0[] = {
  151935. 3, 1, 0, 2, 4,
  151936. };
  151937. static encode_aux_threshmatch _vq_auxt__44un1__p3_0 = {
  151938. _vq_quantthresh__44un1__p3_0,
  151939. _vq_quantmap__44un1__p3_0,
  151940. 5,
  151941. 5
  151942. };
  151943. static static_codebook _44un1__p3_0 = {
  151944. 4, 625,
  151945. _vq_lengthlist__44un1__p3_0,
  151946. 1, -533725184, 1611661312, 3, 0,
  151947. _vq_quantlist__44un1__p3_0,
  151948. NULL,
  151949. &_vq_auxt__44un1__p3_0,
  151950. NULL,
  151951. 0
  151952. };
  151953. static long _vq_quantlist__44un1__p4_0[] = {
  151954. 2,
  151955. 1,
  151956. 3,
  151957. 0,
  151958. 4,
  151959. };
  151960. static long _vq_lengthlist__44un1__p4_0[] = {
  151961. 3, 5, 5, 9, 9, 5, 6, 6,10, 9, 5, 6, 6, 9,10,10,
  151962. 10,10,12,11, 9,10,10,12,12, 5, 7, 7,10,10, 7, 7,
  151963. 8,10,11, 7, 7, 8,10,11,10,10,11,11,13,10,10,11,
  151964. 11,13, 6, 7, 7,10,10, 7, 8, 7,11,10, 7, 8, 7,10,
  151965. 10,10,11, 9,13,11,10,11,10,13,11,10,10,10,14,13,
  151966. 10,11,11,14,13,10,10,11,13,14,12,12,13,15,15,12,
  151967. 12,13,13,14,10,10,10,12,13,10,11,10,13,13,10,11,
  151968. 11,13,13,12,13,12,14,13,12,13,13,14,13, 5, 7, 7,
  151969. 10,10, 7, 8, 8,11,10, 7, 8, 8,10,10,11,11,11,13,
  151970. 13,10,11,11,12,12, 7, 8, 8,11,11, 7, 8, 9,10,12,
  151971. 8, 9, 9,11,11,11,10,12,11,14,11,11,12,13,13, 6,
  151972. 8, 8,10,11, 7, 9, 7,12,10, 8, 9,10,11,12,10,12,
  151973. 10,14,11,11,12,11,13,13,10,11,11,14,14,10,10,11,
  151974. 13,14,11,12,12,15,13,12,11,14,12,16,12,13,14,15,
  151975. 16,10,10,11,13,14,10,11,10,14,12,11,12,12,13,14,
  151976. 12,13,11,15,12,14,14,14,15,15, 5, 7, 7,10,10, 7,
  151977. 8, 8,10,10, 7, 8, 8,10,11,10,11,10,12,12,10,11,
  151978. 11,12,13, 6, 8, 8,11,11, 8, 9, 9,12,11, 7, 7, 9,
  151979. 10,12,11,11,11,12,13,11,10,12,11,15, 7, 8, 8,11,
  151980. 11, 8, 9, 9,11,11, 7, 9, 8,12,10,11,12,11,13,12,
  151981. 11,12,10,15,11,10,11,10,14,12,11,12,11,14,13,10,
  151982. 10,11,13,14,13,13,13,17,15,12,11,14,12,15,10,10,
  151983. 11,13,14,11,12,12,14,14,10,11,10,14,13,13,14,13,
  151984. 16,17,12,14,11,16,12, 9,10,10,14,13,10,11,10,14,
  151985. 14,10,11,11,13,13,13,14,14,16,15,12,13,13,14,14,
  151986. 9,11,10,14,13,10,10,12,13,14,11,12,11,14,13,13,
  151987. 14,14,14,15,13,14,14,15,15, 9,10,11,13,14,10,11,
  151988. 10,15,13,11,11,12,12,15,13,14,12,15,14,13,13,14,
  151989. 14,15,12,13,12,16,14,11,11,12,15,14,13,15,13,16,
  151990. 14,13,12,15,12,17,15,16,15,16,16,12,12,13,13,15,
  151991. 11,13,11,15,14,13,13,14,15,17,13,14,12, 0,13,14,
  151992. 15,14,15, 0, 9,10,10,13,13,10,11,11,13,13,10,11,
  151993. 11,13,13,12,13,12,14,14,13,14,14,15,17, 9,10,10,
  151994. 13,13,11,12,11,15,12,10,10,11,13,16,13,14,13,15,
  151995. 14,13,13,14,15,16,10,10,11,13,14,11,11,12,13,14,
  151996. 10,12,11,14,14,13,13,13,14,15,13,15,13,16,15,12,
  151997. 13,12,15,13,12,15,13,15,15,11,11,13,14,15,15,15,
  151998. 15,15,17,13,12,14,13,17,12,12,14,14,15,13,13,14,
  151999. 14,16,11,13,11,16,15,14,16,16,17, 0,14,13,11,16,
  152000. 12,
  152001. };
  152002. static float _vq_quantthresh__44un1__p4_0[] = {
  152003. -1.5, -0.5, 0.5, 1.5,
  152004. };
  152005. static long _vq_quantmap__44un1__p4_0[] = {
  152006. 3, 1, 0, 2, 4,
  152007. };
  152008. static encode_aux_threshmatch _vq_auxt__44un1__p4_0 = {
  152009. _vq_quantthresh__44un1__p4_0,
  152010. _vq_quantmap__44un1__p4_0,
  152011. 5,
  152012. 5
  152013. };
  152014. static static_codebook _44un1__p4_0 = {
  152015. 4, 625,
  152016. _vq_lengthlist__44un1__p4_0,
  152017. 1, -533725184, 1611661312, 3, 0,
  152018. _vq_quantlist__44un1__p4_0,
  152019. NULL,
  152020. &_vq_auxt__44un1__p4_0,
  152021. NULL,
  152022. 0
  152023. };
  152024. static long _vq_quantlist__44un1__p5_0[] = {
  152025. 4,
  152026. 3,
  152027. 5,
  152028. 2,
  152029. 6,
  152030. 1,
  152031. 7,
  152032. 0,
  152033. 8,
  152034. };
  152035. static long _vq_lengthlist__44un1__p5_0[] = {
  152036. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  152037. 10, 9, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 7, 9, 9,
  152038. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 8, 8, 8,
  152039. 9, 9,10,10,11,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  152040. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  152041. 12,
  152042. };
  152043. static float _vq_quantthresh__44un1__p5_0[] = {
  152044. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  152045. };
  152046. static long _vq_quantmap__44un1__p5_0[] = {
  152047. 7, 5, 3, 1, 0, 2, 4, 6,
  152048. 8,
  152049. };
  152050. static encode_aux_threshmatch _vq_auxt__44un1__p5_0 = {
  152051. _vq_quantthresh__44un1__p5_0,
  152052. _vq_quantmap__44un1__p5_0,
  152053. 9,
  152054. 9
  152055. };
  152056. static static_codebook _44un1__p5_0 = {
  152057. 2, 81,
  152058. _vq_lengthlist__44un1__p5_0,
  152059. 1, -531628032, 1611661312, 4, 0,
  152060. _vq_quantlist__44un1__p5_0,
  152061. NULL,
  152062. &_vq_auxt__44un1__p5_0,
  152063. NULL,
  152064. 0
  152065. };
  152066. static long _vq_quantlist__44un1__p6_0[] = {
  152067. 6,
  152068. 5,
  152069. 7,
  152070. 4,
  152071. 8,
  152072. 3,
  152073. 9,
  152074. 2,
  152075. 10,
  152076. 1,
  152077. 11,
  152078. 0,
  152079. 12,
  152080. };
  152081. static long _vq_lengthlist__44un1__p6_0[] = {
  152082. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,15,15, 4, 5, 5,
  152083. 8, 8, 9, 9,11,11,12,12,16,16, 4, 5, 6, 8, 8, 9,
  152084. 9,11,11,12,12,14,14, 7, 8, 8, 9, 9,10,10,11,12,
  152085. 13,13,16,17, 7, 8, 8, 9, 9,10,10,12,12,12,13,15,
  152086. 15, 9,10,10,10,10,11,11,12,12,13,13,15,16, 9, 9,
  152087. 9,10,10,11,11,13,12,13,13,17,17,10,11,11,11,12,
  152088. 12,12,13,13,14,15, 0,18,10,11,11,12,12,12,13,14,
  152089. 13,14,14,17,16,11,12,12,13,13,14,14,14,14,15,16,
  152090. 17,16,11,12,12,13,13,14,14,14,14,15,15,17,17,14,
  152091. 15,15,16,16,16,17,17,16, 0,17, 0,18,14,15,15,16,
  152092. 16, 0,15,18,18, 0,16, 0, 0,
  152093. };
  152094. static float _vq_quantthresh__44un1__p6_0[] = {
  152095. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  152096. 12.5, 17.5, 22.5, 27.5,
  152097. };
  152098. static long _vq_quantmap__44un1__p6_0[] = {
  152099. 11, 9, 7, 5, 3, 1, 0, 2,
  152100. 4, 6, 8, 10, 12,
  152101. };
  152102. static encode_aux_threshmatch _vq_auxt__44un1__p6_0 = {
  152103. _vq_quantthresh__44un1__p6_0,
  152104. _vq_quantmap__44un1__p6_0,
  152105. 13,
  152106. 13
  152107. };
  152108. static static_codebook _44un1__p6_0 = {
  152109. 2, 169,
  152110. _vq_lengthlist__44un1__p6_0,
  152111. 1, -526516224, 1616117760, 4, 0,
  152112. _vq_quantlist__44un1__p6_0,
  152113. NULL,
  152114. &_vq_auxt__44un1__p6_0,
  152115. NULL,
  152116. 0
  152117. };
  152118. static long _vq_quantlist__44un1__p6_1[] = {
  152119. 2,
  152120. 1,
  152121. 3,
  152122. 0,
  152123. 4,
  152124. };
  152125. static long _vq_lengthlist__44un1__p6_1[] = {
  152126. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 6, 5, 5,
  152127. 6, 5, 6, 6, 5, 6, 6, 6, 6,
  152128. };
  152129. static float _vq_quantthresh__44un1__p6_1[] = {
  152130. -1.5, -0.5, 0.5, 1.5,
  152131. };
  152132. static long _vq_quantmap__44un1__p6_1[] = {
  152133. 3, 1, 0, 2, 4,
  152134. };
  152135. static encode_aux_threshmatch _vq_auxt__44un1__p6_1 = {
  152136. _vq_quantthresh__44un1__p6_1,
  152137. _vq_quantmap__44un1__p6_1,
  152138. 5,
  152139. 5
  152140. };
  152141. static static_codebook _44un1__p6_1 = {
  152142. 2, 25,
  152143. _vq_lengthlist__44un1__p6_1,
  152144. 1, -533725184, 1611661312, 3, 0,
  152145. _vq_quantlist__44un1__p6_1,
  152146. NULL,
  152147. &_vq_auxt__44un1__p6_1,
  152148. NULL,
  152149. 0
  152150. };
  152151. static long _vq_quantlist__44un1__p7_0[] = {
  152152. 2,
  152153. 1,
  152154. 3,
  152155. 0,
  152156. 4,
  152157. };
  152158. static long _vq_lengthlist__44un1__p7_0[] = {
  152159. 1, 5, 3,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  152160. 11,11,11,11,11,11,11,11,11,10,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,10,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,11,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, 8,11,11,
  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,10,
  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,11,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,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152174. 11,11,11,11,11,11,11,11,11,11, 7,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,10,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. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152193. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152194. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152195. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152196. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152197. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152198. 10,
  152199. };
  152200. static float _vq_quantthresh__44un1__p7_0[] = {
  152201. -253.5, -84.5, 84.5, 253.5,
  152202. };
  152203. static long _vq_quantmap__44un1__p7_0[] = {
  152204. 3, 1, 0, 2, 4,
  152205. };
  152206. static encode_aux_threshmatch _vq_auxt__44un1__p7_0 = {
  152207. _vq_quantthresh__44un1__p7_0,
  152208. _vq_quantmap__44un1__p7_0,
  152209. 5,
  152210. 5
  152211. };
  152212. static static_codebook _44un1__p7_0 = {
  152213. 4, 625,
  152214. _vq_lengthlist__44un1__p7_0,
  152215. 1, -518709248, 1626677248, 3, 0,
  152216. _vq_quantlist__44un1__p7_0,
  152217. NULL,
  152218. &_vq_auxt__44un1__p7_0,
  152219. NULL,
  152220. 0
  152221. };
  152222. static long _vq_quantlist__44un1__p7_1[] = {
  152223. 6,
  152224. 5,
  152225. 7,
  152226. 4,
  152227. 8,
  152228. 3,
  152229. 9,
  152230. 2,
  152231. 10,
  152232. 1,
  152233. 11,
  152234. 0,
  152235. 12,
  152236. };
  152237. static long _vq_lengthlist__44un1__p7_1[] = {
  152238. 1, 4, 4, 6, 6, 6, 6, 9, 8, 9, 8, 8, 8, 5, 7, 7,
  152239. 7, 7, 8, 8, 8,10, 8,10, 8, 9, 5, 7, 7, 8, 7, 7,
  152240. 8,10,10,11,10,12,11, 7, 8, 8, 9, 9, 9,10,11,11,
  152241. 11,11,11,11, 7, 8, 8, 8, 9, 9, 9,10,10,10,11,11,
  152242. 12, 7, 8, 8, 9, 9,10,11,11,12,11,12,11,11, 7, 8,
  152243. 8, 9, 9,10,10,11,11,11,12,12,11, 8,10,10,10,10,
  152244. 11,11,14,11,12,12,12,13, 9,10,10,10,10,12,11,14,
  152245. 11,14,11,12,13,10,11,11,11,11,13,11,14,14,13,13,
  152246. 13,14,11,11,11,12,11,12,12,12,13,14,14,13,14,12,
  152247. 11,12,12,12,12,13,13,13,14,13,14,14,11,12,12,14,
  152248. 12,13,13,12,13,13,14,14,14,
  152249. };
  152250. static float _vq_quantthresh__44un1__p7_1[] = {
  152251. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  152252. 32.5, 45.5, 58.5, 71.5,
  152253. };
  152254. static long _vq_quantmap__44un1__p7_1[] = {
  152255. 11, 9, 7, 5, 3, 1, 0, 2,
  152256. 4, 6, 8, 10, 12,
  152257. };
  152258. static encode_aux_threshmatch _vq_auxt__44un1__p7_1 = {
  152259. _vq_quantthresh__44un1__p7_1,
  152260. _vq_quantmap__44un1__p7_1,
  152261. 13,
  152262. 13
  152263. };
  152264. static static_codebook _44un1__p7_1 = {
  152265. 2, 169,
  152266. _vq_lengthlist__44un1__p7_1,
  152267. 1, -523010048, 1618608128, 4, 0,
  152268. _vq_quantlist__44un1__p7_1,
  152269. NULL,
  152270. &_vq_auxt__44un1__p7_1,
  152271. NULL,
  152272. 0
  152273. };
  152274. static long _vq_quantlist__44un1__p7_2[] = {
  152275. 6,
  152276. 5,
  152277. 7,
  152278. 4,
  152279. 8,
  152280. 3,
  152281. 9,
  152282. 2,
  152283. 10,
  152284. 1,
  152285. 11,
  152286. 0,
  152287. 12,
  152288. };
  152289. static long _vq_lengthlist__44un1__p7_2[] = {
  152290. 3, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9, 9, 8, 4, 5, 5,
  152291. 6, 6, 8, 8, 9, 8, 9, 9, 9, 9, 4, 5, 5, 7, 6, 8,
  152292. 8, 8, 8, 9, 8, 9, 8, 6, 7, 7, 7, 8, 8, 8, 9, 9,
  152293. 9, 9, 9, 9, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  152294. 9, 7, 8, 8, 8, 8, 9, 8, 9, 9,10, 9, 9,10, 7, 8,
  152295. 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 8, 9, 9, 9, 9,
  152296. 9, 9, 9, 9,10,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9,
  152297. 9, 9, 9,10,10, 9, 9, 9,10, 9, 9,10, 9, 9,10,10,
  152298. 10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10, 9,
  152299. 9, 9,10, 9, 9,10,10, 9,10,10,10,10, 9, 9, 9,10,
  152300. 9, 9, 9,10,10,10,10,10,10,
  152301. };
  152302. static float _vq_quantthresh__44un1__p7_2[] = {
  152303. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  152304. 2.5, 3.5, 4.5, 5.5,
  152305. };
  152306. static long _vq_quantmap__44un1__p7_2[] = {
  152307. 11, 9, 7, 5, 3, 1, 0, 2,
  152308. 4, 6, 8, 10, 12,
  152309. };
  152310. static encode_aux_threshmatch _vq_auxt__44un1__p7_2 = {
  152311. _vq_quantthresh__44un1__p7_2,
  152312. _vq_quantmap__44un1__p7_2,
  152313. 13,
  152314. 13
  152315. };
  152316. static static_codebook _44un1__p7_2 = {
  152317. 2, 169,
  152318. _vq_lengthlist__44un1__p7_2,
  152319. 1, -531103744, 1611661312, 4, 0,
  152320. _vq_quantlist__44un1__p7_2,
  152321. NULL,
  152322. &_vq_auxt__44un1__p7_2,
  152323. NULL,
  152324. 0
  152325. };
  152326. static long _huff_lengthlist__44un1__short[] = {
  152327. 12,12,14,12,14,14,14,14,12, 6, 6, 8, 9, 9,11,14,
  152328. 12, 4, 2, 6, 6, 7,11,14,13, 6, 5, 7, 8, 9,11,14,
  152329. 13, 8, 5, 8, 6, 8,12,14,12, 7, 7, 8, 8, 8,10,14,
  152330. 12, 6, 3, 4, 4, 4, 7,14,11, 7, 4, 6, 6, 6, 8,14,
  152331. };
  152332. static static_codebook _huff_book__44un1__short = {
  152333. 2, 64,
  152334. _huff_lengthlist__44un1__short,
  152335. 0, 0, 0, 0, 0,
  152336. NULL,
  152337. NULL,
  152338. NULL,
  152339. NULL,
  152340. 0
  152341. };
  152342. /*** End of inlined file: res_books_uncoupled.h ***/
  152343. /***** residue backends *********************************************/
  152344. static vorbis_info_residue0 _residue_44_low_un={
  152345. 0,-1, -1, 8,-1,
  152346. {0},
  152347. {-1},
  152348. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 28.5},
  152349. { -1, 25, -1, 45, -1, -1, -1}
  152350. };
  152351. static vorbis_info_residue0 _residue_44_mid_un={
  152352. 0,-1, -1, 10,-1,
  152353. /* 0 1 2 3 4 5 6 7 8 9 */
  152354. {0},
  152355. {-1},
  152356. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 4.5, 16.5, 60.5},
  152357. { -1, 30, -1, 50, -1, 80, -1, -1, -1}
  152358. };
  152359. static vorbis_info_residue0 _residue_44_hi_un={
  152360. 0,-1, -1, 10,-1,
  152361. /* 0 1 2 3 4 5 6 7 8 9 */
  152362. {0},
  152363. {-1},
  152364. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  152365. { -1, -1, -1, -1, -1, -1, -1, -1, -1}
  152366. };
  152367. /* mapping conventions:
  152368. only one submap (this would change for efficient 5.1 support for example)*/
  152369. /* Four psychoacoustic profiles are used, one for each blocktype */
  152370. static vorbis_info_mapping0 _map_nominal_u[2]={
  152371. {1, {0,0}, {0}, {0}, 0,{0},{0}},
  152372. {1, {0,0}, {1}, {1}, 0,{0},{0}}
  152373. };
  152374. static static_bookblock _resbook_44u_n1={
  152375. {
  152376. {0},
  152377. {0,0,&_44un1__p1_0},
  152378. {0,0,&_44un1__p2_0},
  152379. {0,0,&_44un1__p3_0},
  152380. {0,0,&_44un1__p4_0},
  152381. {0,0,&_44un1__p5_0},
  152382. {&_44un1__p6_0,&_44un1__p6_1},
  152383. {&_44un1__p7_0,&_44un1__p7_1,&_44un1__p7_2}
  152384. }
  152385. };
  152386. static static_bookblock _resbook_44u_0={
  152387. {
  152388. {0},
  152389. {0,0,&_44u0__p1_0},
  152390. {0,0,&_44u0__p2_0},
  152391. {0,0,&_44u0__p3_0},
  152392. {0,0,&_44u0__p4_0},
  152393. {0,0,&_44u0__p5_0},
  152394. {&_44u0__p6_0,&_44u0__p6_1},
  152395. {&_44u0__p7_0,&_44u0__p7_1,&_44u0__p7_2}
  152396. }
  152397. };
  152398. static static_bookblock _resbook_44u_1={
  152399. {
  152400. {0},
  152401. {0,0,&_44u1__p1_0},
  152402. {0,0,&_44u1__p2_0},
  152403. {0,0,&_44u1__p3_0},
  152404. {0,0,&_44u1__p4_0},
  152405. {0,0,&_44u1__p5_0},
  152406. {&_44u1__p6_0,&_44u1__p6_1},
  152407. {&_44u1__p7_0,&_44u1__p7_1,&_44u1__p7_2}
  152408. }
  152409. };
  152410. static static_bookblock _resbook_44u_2={
  152411. {
  152412. {0},
  152413. {0,0,&_44u2__p1_0},
  152414. {0,0,&_44u2__p2_0},
  152415. {0,0,&_44u2__p3_0},
  152416. {0,0,&_44u2__p4_0},
  152417. {0,0,&_44u2__p5_0},
  152418. {&_44u2__p6_0,&_44u2__p6_1},
  152419. {&_44u2__p7_0,&_44u2__p7_1,&_44u2__p7_2}
  152420. }
  152421. };
  152422. static static_bookblock _resbook_44u_3={
  152423. {
  152424. {0},
  152425. {0,0,&_44u3__p1_0},
  152426. {0,0,&_44u3__p2_0},
  152427. {0,0,&_44u3__p3_0},
  152428. {0,0,&_44u3__p4_0},
  152429. {0,0,&_44u3__p5_0},
  152430. {&_44u3__p6_0,&_44u3__p6_1},
  152431. {&_44u3__p7_0,&_44u3__p7_1,&_44u3__p7_2}
  152432. }
  152433. };
  152434. static static_bookblock _resbook_44u_4={
  152435. {
  152436. {0},
  152437. {0,0,&_44u4__p1_0},
  152438. {0,0,&_44u4__p2_0},
  152439. {0,0,&_44u4__p3_0},
  152440. {0,0,&_44u4__p4_0},
  152441. {0,0,&_44u4__p5_0},
  152442. {&_44u4__p6_0,&_44u4__p6_1},
  152443. {&_44u4__p7_0,&_44u4__p7_1,&_44u4__p7_2}
  152444. }
  152445. };
  152446. static static_bookblock _resbook_44u_5={
  152447. {
  152448. {0},
  152449. {0,0,&_44u5__p1_0},
  152450. {0,0,&_44u5__p2_0},
  152451. {0,0,&_44u5__p3_0},
  152452. {0,0,&_44u5__p4_0},
  152453. {0,0,&_44u5__p5_0},
  152454. {0,0,&_44u5__p6_0},
  152455. {&_44u5__p7_0,&_44u5__p7_1},
  152456. {&_44u5__p8_0,&_44u5__p8_1},
  152457. {&_44u5__p9_0,&_44u5__p9_1,&_44u5__p9_2}
  152458. }
  152459. };
  152460. static static_bookblock _resbook_44u_6={
  152461. {
  152462. {0},
  152463. {0,0,&_44u6__p1_0},
  152464. {0,0,&_44u6__p2_0},
  152465. {0,0,&_44u6__p3_0},
  152466. {0,0,&_44u6__p4_0},
  152467. {0,0,&_44u6__p5_0},
  152468. {0,0,&_44u6__p6_0},
  152469. {&_44u6__p7_0,&_44u6__p7_1},
  152470. {&_44u6__p8_0,&_44u6__p8_1},
  152471. {&_44u6__p9_0,&_44u6__p9_1,&_44u6__p9_2}
  152472. }
  152473. };
  152474. static static_bookblock _resbook_44u_7={
  152475. {
  152476. {0},
  152477. {0,0,&_44u7__p1_0},
  152478. {0,0,&_44u7__p2_0},
  152479. {0,0,&_44u7__p3_0},
  152480. {0,0,&_44u7__p4_0},
  152481. {0,0,&_44u7__p5_0},
  152482. {0,0,&_44u7__p6_0},
  152483. {&_44u7__p7_0,&_44u7__p7_1},
  152484. {&_44u7__p8_0,&_44u7__p8_1},
  152485. {&_44u7__p9_0,&_44u7__p9_1,&_44u7__p9_2}
  152486. }
  152487. };
  152488. static static_bookblock _resbook_44u_8={
  152489. {
  152490. {0},
  152491. {0,0,&_44u8_p1_0},
  152492. {0,0,&_44u8_p2_0},
  152493. {0,0,&_44u8_p3_0},
  152494. {0,0,&_44u8_p4_0},
  152495. {&_44u8_p5_0,&_44u8_p5_1},
  152496. {&_44u8_p6_0,&_44u8_p6_1},
  152497. {&_44u8_p7_0,&_44u8_p7_1},
  152498. {&_44u8_p8_0,&_44u8_p8_1},
  152499. {&_44u8_p9_0,&_44u8_p9_1,&_44u8_p9_2}
  152500. }
  152501. };
  152502. static static_bookblock _resbook_44u_9={
  152503. {
  152504. {0},
  152505. {0,0,&_44u9_p1_0},
  152506. {0,0,&_44u9_p2_0},
  152507. {0,0,&_44u9_p3_0},
  152508. {0,0,&_44u9_p4_0},
  152509. {&_44u9_p5_0,&_44u9_p5_1},
  152510. {&_44u9_p6_0,&_44u9_p6_1},
  152511. {&_44u9_p7_0,&_44u9_p7_1},
  152512. {&_44u9_p8_0,&_44u9_p8_1},
  152513. {&_44u9_p9_0,&_44u9_p9_1,&_44u9_p9_2}
  152514. }
  152515. };
  152516. static vorbis_residue_template _res_44u_n1[]={
  152517. {1,0, &_residue_44_low_un,
  152518. &_huff_book__44un1__short,&_huff_book__44un1__short,
  152519. &_resbook_44u_n1,&_resbook_44u_n1},
  152520. {1,0, &_residue_44_low_un,
  152521. &_huff_book__44un1__long,&_huff_book__44un1__long,
  152522. &_resbook_44u_n1,&_resbook_44u_n1}
  152523. };
  152524. static vorbis_residue_template _res_44u_0[]={
  152525. {1,0, &_residue_44_low_un,
  152526. &_huff_book__44u0__short,&_huff_book__44u0__short,
  152527. &_resbook_44u_0,&_resbook_44u_0},
  152528. {1,0, &_residue_44_low_un,
  152529. &_huff_book__44u0__long,&_huff_book__44u0__long,
  152530. &_resbook_44u_0,&_resbook_44u_0}
  152531. };
  152532. static vorbis_residue_template _res_44u_1[]={
  152533. {1,0, &_residue_44_low_un,
  152534. &_huff_book__44u1__short,&_huff_book__44u1__short,
  152535. &_resbook_44u_1,&_resbook_44u_1},
  152536. {1,0, &_residue_44_low_un,
  152537. &_huff_book__44u1__long,&_huff_book__44u1__long,
  152538. &_resbook_44u_1,&_resbook_44u_1}
  152539. };
  152540. static vorbis_residue_template _res_44u_2[]={
  152541. {1,0, &_residue_44_low_un,
  152542. &_huff_book__44u2__short,&_huff_book__44u2__short,
  152543. &_resbook_44u_2,&_resbook_44u_2},
  152544. {1,0, &_residue_44_low_un,
  152545. &_huff_book__44u2__long,&_huff_book__44u2__long,
  152546. &_resbook_44u_2,&_resbook_44u_2}
  152547. };
  152548. static vorbis_residue_template _res_44u_3[]={
  152549. {1,0, &_residue_44_low_un,
  152550. &_huff_book__44u3__short,&_huff_book__44u3__short,
  152551. &_resbook_44u_3,&_resbook_44u_3},
  152552. {1,0, &_residue_44_low_un,
  152553. &_huff_book__44u3__long,&_huff_book__44u3__long,
  152554. &_resbook_44u_3,&_resbook_44u_3}
  152555. };
  152556. static vorbis_residue_template _res_44u_4[]={
  152557. {1,0, &_residue_44_low_un,
  152558. &_huff_book__44u4__short,&_huff_book__44u4__short,
  152559. &_resbook_44u_4,&_resbook_44u_4},
  152560. {1,0, &_residue_44_low_un,
  152561. &_huff_book__44u4__long,&_huff_book__44u4__long,
  152562. &_resbook_44u_4,&_resbook_44u_4}
  152563. };
  152564. static vorbis_residue_template _res_44u_5[]={
  152565. {1,0, &_residue_44_mid_un,
  152566. &_huff_book__44u5__short,&_huff_book__44u5__short,
  152567. &_resbook_44u_5,&_resbook_44u_5},
  152568. {1,0, &_residue_44_mid_un,
  152569. &_huff_book__44u5__long,&_huff_book__44u5__long,
  152570. &_resbook_44u_5,&_resbook_44u_5}
  152571. };
  152572. static vorbis_residue_template _res_44u_6[]={
  152573. {1,0, &_residue_44_mid_un,
  152574. &_huff_book__44u6__short,&_huff_book__44u6__short,
  152575. &_resbook_44u_6,&_resbook_44u_6},
  152576. {1,0, &_residue_44_mid_un,
  152577. &_huff_book__44u6__long,&_huff_book__44u6__long,
  152578. &_resbook_44u_6,&_resbook_44u_6}
  152579. };
  152580. static vorbis_residue_template _res_44u_7[]={
  152581. {1,0, &_residue_44_mid_un,
  152582. &_huff_book__44u7__short,&_huff_book__44u7__short,
  152583. &_resbook_44u_7,&_resbook_44u_7},
  152584. {1,0, &_residue_44_mid_un,
  152585. &_huff_book__44u7__long,&_huff_book__44u7__long,
  152586. &_resbook_44u_7,&_resbook_44u_7}
  152587. };
  152588. static vorbis_residue_template _res_44u_8[]={
  152589. {1,0, &_residue_44_hi_un,
  152590. &_huff_book__44u8__short,&_huff_book__44u8__short,
  152591. &_resbook_44u_8,&_resbook_44u_8},
  152592. {1,0, &_residue_44_hi_un,
  152593. &_huff_book__44u8__long,&_huff_book__44u8__long,
  152594. &_resbook_44u_8,&_resbook_44u_8}
  152595. };
  152596. static vorbis_residue_template _res_44u_9[]={
  152597. {1,0, &_residue_44_hi_un,
  152598. &_huff_book__44u9__short,&_huff_book__44u9__short,
  152599. &_resbook_44u_9,&_resbook_44u_9},
  152600. {1,0, &_residue_44_hi_un,
  152601. &_huff_book__44u9__long,&_huff_book__44u9__long,
  152602. &_resbook_44u_9,&_resbook_44u_9}
  152603. };
  152604. static vorbis_mapping_template _mapres_template_44_uncoupled[]={
  152605. { _map_nominal_u, _res_44u_n1 }, /* -1 */
  152606. { _map_nominal_u, _res_44u_0 }, /* 0 */
  152607. { _map_nominal_u, _res_44u_1 }, /* 1 */
  152608. { _map_nominal_u, _res_44u_2 }, /* 2 */
  152609. { _map_nominal_u, _res_44u_3 }, /* 3 */
  152610. { _map_nominal_u, _res_44u_4 }, /* 4 */
  152611. { _map_nominal_u, _res_44u_5 }, /* 5 */
  152612. { _map_nominal_u, _res_44u_6 }, /* 6 */
  152613. { _map_nominal_u, _res_44u_7 }, /* 7 */
  152614. { _map_nominal_u, _res_44u_8 }, /* 8 */
  152615. { _map_nominal_u, _res_44u_9 }, /* 9 */
  152616. };
  152617. /*** End of inlined file: residue_44u.h ***/
  152618. static double rate_mapping_44_un[12]={
  152619. 32000.,48000.,60000.,70000.,80000.,86000.,
  152620. 96000.,110000.,120000.,140000.,160000.,240001.
  152621. };
  152622. ve_setup_data_template ve_setup_44_uncoupled={
  152623. 11,
  152624. rate_mapping_44_un,
  152625. quality_mapping_44,
  152626. -1,
  152627. 40000,
  152628. 50000,
  152629. blocksize_short_44,
  152630. blocksize_long_44,
  152631. _psy_tone_masteratt_44,
  152632. _psy_tone_0dB,
  152633. _psy_tone_suppress,
  152634. _vp_tonemask_adj_otherblock,
  152635. _vp_tonemask_adj_longblock,
  152636. _vp_tonemask_adj_otherblock,
  152637. _psy_noiseguards_44,
  152638. _psy_noisebias_impulse,
  152639. _psy_noisebias_padding,
  152640. _psy_noisebias_trans,
  152641. _psy_noisebias_long,
  152642. _psy_noise_suppress,
  152643. _psy_compand_44,
  152644. _psy_compand_short_mapping,
  152645. _psy_compand_long_mapping,
  152646. {_noise_start_short_44,_noise_start_long_44},
  152647. {_noise_part_short_44,_noise_part_long_44},
  152648. _noise_thresh_44,
  152649. _psy_ath_floater,
  152650. _psy_ath_abs,
  152651. _psy_lowpass_44,
  152652. _psy_global_44,
  152653. _global_mapping_44,
  152654. NULL,
  152655. _floor_books,
  152656. _floor,
  152657. _floor_short_mapping_44,
  152658. _floor_long_mapping_44,
  152659. _mapres_template_44_uncoupled
  152660. };
  152661. /*** End of inlined file: setup_44u.h ***/
  152662. /*** Start of inlined file: setup_32.h ***/
  152663. static double rate_mapping_32[12]={
  152664. 18000.,28000.,35000.,45000.,56000.,60000.,
  152665. 75000.,90000.,100000.,115000.,150000.,190000.,
  152666. };
  152667. static double rate_mapping_32_un[12]={
  152668. 30000.,42000.,52000.,64000.,72000.,78000.,
  152669. 86000.,92000.,110000.,120000.,140000.,190000.,
  152670. };
  152671. static double _psy_lowpass_32[12]={
  152672. 12.3,13.,13.,14.,15.,99.,99.,99.,99.,99.,99.,99.
  152673. };
  152674. ve_setup_data_template ve_setup_32_stereo={
  152675. 11,
  152676. rate_mapping_32,
  152677. quality_mapping_44,
  152678. 2,
  152679. 26000,
  152680. 40000,
  152681. blocksize_short_44,
  152682. blocksize_long_44,
  152683. _psy_tone_masteratt_44,
  152684. _psy_tone_0dB,
  152685. _psy_tone_suppress,
  152686. _vp_tonemask_adj_otherblock,
  152687. _vp_tonemask_adj_longblock,
  152688. _vp_tonemask_adj_otherblock,
  152689. _psy_noiseguards_44,
  152690. _psy_noisebias_impulse,
  152691. _psy_noisebias_padding,
  152692. _psy_noisebias_trans,
  152693. _psy_noisebias_long,
  152694. _psy_noise_suppress,
  152695. _psy_compand_44,
  152696. _psy_compand_short_mapping,
  152697. _psy_compand_long_mapping,
  152698. {_noise_start_short_44,_noise_start_long_44},
  152699. {_noise_part_short_44,_noise_part_long_44},
  152700. _noise_thresh_44,
  152701. _psy_ath_floater,
  152702. _psy_ath_abs,
  152703. _psy_lowpass_32,
  152704. _psy_global_44,
  152705. _global_mapping_44,
  152706. _psy_stereo_modes_44,
  152707. _floor_books,
  152708. _floor,
  152709. _floor_short_mapping_44,
  152710. _floor_long_mapping_44,
  152711. _mapres_template_44_stereo
  152712. };
  152713. ve_setup_data_template ve_setup_32_uncoupled={
  152714. 11,
  152715. rate_mapping_32_un,
  152716. quality_mapping_44,
  152717. -1,
  152718. 26000,
  152719. 40000,
  152720. blocksize_short_44,
  152721. blocksize_long_44,
  152722. _psy_tone_masteratt_44,
  152723. _psy_tone_0dB,
  152724. _psy_tone_suppress,
  152725. _vp_tonemask_adj_otherblock,
  152726. _vp_tonemask_adj_longblock,
  152727. _vp_tonemask_adj_otherblock,
  152728. _psy_noiseguards_44,
  152729. _psy_noisebias_impulse,
  152730. _psy_noisebias_padding,
  152731. _psy_noisebias_trans,
  152732. _psy_noisebias_long,
  152733. _psy_noise_suppress,
  152734. _psy_compand_44,
  152735. _psy_compand_short_mapping,
  152736. _psy_compand_long_mapping,
  152737. {_noise_start_short_44,_noise_start_long_44},
  152738. {_noise_part_short_44,_noise_part_long_44},
  152739. _noise_thresh_44,
  152740. _psy_ath_floater,
  152741. _psy_ath_abs,
  152742. _psy_lowpass_32,
  152743. _psy_global_44,
  152744. _global_mapping_44,
  152745. NULL,
  152746. _floor_books,
  152747. _floor,
  152748. _floor_short_mapping_44,
  152749. _floor_long_mapping_44,
  152750. _mapres_template_44_uncoupled
  152751. };
  152752. /*** End of inlined file: setup_32.h ***/
  152753. /*** Start of inlined file: setup_8.h ***/
  152754. /*** Start of inlined file: psych_8.h ***/
  152755. static att3 _psy_tone_masteratt_8[3]={
  152756. {{ 32, 25, 12}, 0, 0}, /* 0 */
  152757. {{ 30, 25, 12}, 0, 0}, /* 0 */
  152758. {{ 20, 0, -14}, 0, 0}, /* 0 */
  152759. };
  152760. static vp_adjblock _vp_tonemask_adj_8[3]={
  152761. /* adjust for mode zero */
  152762. /* 63 125 250 500 1 2 4 8 16 */
  152763. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  152764. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  152765. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 1 */
  152766. };
  152767. static noise3 _psy_noisebias_8[3]={
  152768. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  152769. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  152770. {-10,-10,-10,-10, -5, -5, -5, 0, 0, 4, 4, 4, 4, 4, 99, 99, 99},
  152771. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  152772. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  152773. {-10,-10,-10,-10,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  152774. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  152775. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  152776. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  152777. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  152778. };
  152779. /* stereo mode by base quality level */
  152780. static adj_stereo _psy_stereo_modes_8[3]={
  152781. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  152782. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  152783. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  152784. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  152785. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  152786. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  152787. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  152788. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  152789. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  152790. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  152791. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  152792. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  152793. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  152794. };
  152795. static noiseguard _psy_noiseguards_8[2]={
  152796. {10,10,-1},
  152797. {10,10,-1},
  152798. };
  152799. static compandblock _psy_compand_8[2]={
  152800. {{
  152801. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  152802. 8, 8, 9, 9,10,10,11, 11, /* 15dB */
  152803. 12,12,13,13,14,14,15, 15, /* 23dB */
  152804. 16,16,17,17,17,18,18, 19, /* 31dB */
  152805. 19,19,20,21,22,23,24, 25, /* 39dB */
  152806. }},
  152807. {{
  152808. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  152809. 7, 7, 6, 6, 5, 5, 4, 4, /* 15dB */
  152810. 3, 3, 3, 4, 5, 6, 7, 8, /* 23dB */
  152811. 9,10,11,12,13,14,15, 16, /* 31dB */
  152812. 17,18,19,20,21,22,23, 24, /* 39dB */
  152813. }},
  152814. };
  152815. static double _psy_lowpass_8[3]={3.,4.,4.};
  152816. static int _noise_start_8[2]={
  152817. 64,64,
  152818. };
  152819. static int _noise_part_8[2]={
  152820. 8,8,
  152821. };
  152822. static int _psy_ath_floater_8[3]={
  152823. -100,-100,-105,
  152824. };
  152825. static int _psy_ath_abs_8[3]={
  152826. -130,-130,-140,
  152827. };
  152828. /*** End of inlined file: psych_8.h ***/
  152829. /*** Start of inlined file: residue_8.h ***/
  152830. /***** residue backends *********************************************/
  152831. static static_bookblock _resbook_8s_0={
  152832. {
  152833. {0},{0,0,&_8c0_s_p1_0},{0,0,&_8c0_s_p2_0},{0,0,&_8c0_s_p3_0},
  152834. {0,0,&_8c0_s_p4_0},{0,0,&_8c0_s_p5_0},{0,0,&_8c0_s_p6_0},
  152835. {&_8c0_s_p7_0,&_8c0_s_p7_1},{&_8c0_s_p8_0,&_8c0_s_p8_1},
  152836. {&_8c0_s_p9_0,&_8c0_s_p9_1,&_8c0_s_p9_2}
  152837. }
  152838. };
  152839. static static_bookblock _resbook_8s_1={
  152840. {
  152841. {0},{0,0,&_8c1_s_p1_0},{0,0,&_8c1_s_p2_0},{0,0,&_8c1_s_p3_0},
  152842. {0,0,&_8c1_s_p4_0},{0,0,&_8c1_s_p5_0},{0,0,&_8c1_s_p6_0},
  152843. {&_8c1_s_p7_0,&_8c1_s_p7_1},{&_8c1_s_p8_0,&_8c1_s_p8_1},
  152844. {&_8c1_s_p9_0,&_8c1_s_p9_1,&_8c1_s_p9_2}
  152845. }
  152846. };
  152847. static vorbis_residue_template _res_8s_0[]={
  152848. {2,0, &_residue_44_mid,
  152849. &_huff_book__8c0_s_single,&_huff_book__8c0_s_single,
  152850. &_resbook_8s_0,&_resbook_8s_0},
  152851. };
  152852. static vorbis_residue_template _res_8s_1[]={
  152853. {2,0, &_residue_44_mid,
  152854. &_huff_book__8c1_s_single,&_huff_book__8c1_s_single,
  152855. &_resbook_8s_1,&_resbook_8s_1},
  152856. };
  152857. static vorbis_mapping_template _mapres_template_8_stereo[2]={
  152858. { _map_nominal, _res_8s_0 }, /* 0 */
  152859. { _map_nominal, _res_8s_1 }, /* 1 */
  152860. };
  152861. static static_bookblock _resbook_8u_0={
  152862. {
  152863. {0},
  152864. {0,0,&_8u0__p1_0},
  152865. {0,0,&_8u0__p2_0},
  152866. {0,0,&_8u0__p3_0},
  152867. {0,0,&_8u0__p4_0},
  152868. {0,0,&_8u0__p5_0},
  152869. {&_8u0__p6_0,&_8u0__p6_1},
  152870. {&_8u0__p7_0,&_8u0__p7_1,&_8u0__p7_2}
  152871. }
  152872. };
  152873. static static_bookblock _resbook_8u_1={
  152874. {
  152875. {0},
  152876. {0,0,&_8u1__p1_0},
  152877. {0,0,&_8u1__p2_0},
  152878. {0,0,&_8u1__p3_0},
  152879. {0,0,&_8u1__p4_0},
  152880. {0,0,&_8u1__p5_0},
  152881. {0,0,&_8u1__p6_0},
  152882. {&_8u1__p7_0,&_8u1__p7_1},
  152883. {&_8u1__p8_0,&_8u1__p8_1},
  152884. {&_8u1__p9_0,&_8u1__p9_1,&_8u1__p9_2}
  152885. }
  152886. };
  152887. static vorbis_residue_template _res_8u_0[]={
  152888. {1,0, &_residue_44_low_un,
  152889. &_huff_book__8u0__single,&_huff_book__8u0__single,
  152890. &_resbook_8u_0,&_resbook_8u_0},
  152891. };
  152892. static vorbis_residue_template _res_8u_1[]={
  152893. {1,0, &_residue_44_mid_un,
  152894. &_huff_book__8u1__single,&_huff_book__8u1__single,
  152895. &_resbook_8u_1,&_resbook_8u_1},
  152896. };
  152897. static vorbis_mapping_template _mapres_template_8_uncoupled[2]={
  152898. { _map_nominal_u, _res_8u_0 }, /* 0 */
  152899. { _map_nominal_u, _res_8u_1 }, /* 1 */
  152900. };
  152901. /*** End of inlined file: residue_8.h ***/
  152902. static int blocksize_8[2]={
  152903. 512,512
  152904. };
  152905. static int _floor_mapping_8[2]={
  152906. 6,6,
  152907. };
  152908. static double rate_mapping_8[3]={
  152909. 6000.,9000.,32000.,
  152910. };
  152911. static double rate_mapping_8_uncoupled[3]={
  152912. 8000.,14000.,42000.,
  152913. };
  152914. static double quality_mapping_8[3]={
  152915. -.1,.0,1.
  152916. };
  152917. static double _psy_compand_8_mapping[3]={ 0., 1., 1.};
  152918. static double _global_mapping_8[3]={ 1., 2., 3. };
  152919. ve_setup_data_template ve_setup_8_stereo={
  152920. 2,
  152921. rate_mapping_8,
  152922. quality_mapping_8,
  152923. 2,
  152924. 8000,
  152925. 9000,
  152926. blocksize_8,
  152927. blocksize_8,
  152928. _psy_tone_masteratt_8,
  152929. _psy_tone_0dB,
  152930. _psy_tone_suppress,
  152931. _vp_tonemask_adj_8,
  152932. NULL,
  152933. _vp_tonemask_adj_8,
  152934. _psy_noiseguards_8,
  152935. _psy_noisebias_8,
  152936. _psy_noisebias_8,
  152937. NULL,
  152938. NULL,
  152939. _psy_noise_suppress,
  152940. _psy_compand_8,
  152941. _psy_compand_8_mapping,
  152942. NULL,
  152943. {_noise_start_8,_noise_start_8},
  152944. {_noise_part_8,_noise_part_8},
  152945. _noise_thresh_5only,
  152946. _psy_ath_floater_8,
  152947. _psy_ath_abs_8,
  152948. _psy_lowpass_8,
  152949. _psy_global_44,
  152950. _global_mapping_8,
  152951. _psy_stereo_modes_8,
  152952. _floor_books,
  152953. _floor,
  152954. _floor_mapping_8,
  152955. NULL,
  152956. _mapres_template_8_stereo
  152957. };
  152958. ve_setup_data_template ve_setup_8_uncoupled={
  152959. 2,
  152960. rate_mapping_8_uncoupled,
  152961. quality_mapping_8,
  152962. -1,
  152963. 8000,
  152964. 9000,
  152965. blocksize_8,
  152966. blocksize_8,
  152967. _psy_tone_masteratt_8,
  152968. _psy_tone_0dB,
  152969. _psy_tone_suppress,
  152970. _vp_tonemask_adj_8,
  152971. NULL,
  152972. _vp_tonemask_adj_8,
  152973. _psy_noiseguards_8,
  152974. _psy_noisebias_8,
  152975. _psy_noisebias_8,
  152976. NULL,
  152977. NULL,
  152978. _psy_noise_suppress,
  152979. _psy_compand_8,
  152980. _psy_compand_8_mapping,
  152981. NULL,
  152982. {_noise_start_8,_noise_start_8},
  152983. {_noise_part_8,_noise_part_8},
  152984. _noise_thresh_5only,
  152985. _psy_ath_floater_8,
  152986. _psy_ath_abs_8,
  152987. _psy_lowpass_8,
  152988. _psy_global_44,
  152989. _global_mapping_8,
  152990. _psy_stereo_modes_8,
  152991. _floor_books,
  152992. _floor,
  152993. _floor_mapping_8,
  152994. NULL,
  152995. _mapres_template_8_uncoupled
  152996. };
  152997. /*** End of inlined file: setup_8.h ***/
  152998. /*** Start of inlined file: setup_11.h ***/
  152999. /*** Start of inlined file: psych_11.h ***/
  153000. static double _psy_lowpass_11[3]={4.5,5.5,30.,};
  153001. static att3 _psy_tone_masteratt_11[3]={
  153002. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153003. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153004. {{ 20, 0, -14}, 0, 0}, /* 0 */
  153005. };
  153006. static vp_adjblock _vp_tonemask_adj_11[3]={
  153007. /* adjust for mode zero */
  153008. /* 63 125 250 500 1 2 4 8 16 */
  153009. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 2, 0,99,99,99}}, /* 0 */
  153010. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 5, 0, 0,99,99,99}}, /* 1 */
  153011. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 2 */
  153012. };
  153013. static noise3 _psy_noisebias_11[3]={
  153014. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  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, 0, 0, 4, 4, 5, 5, 10, 99, 99, 99},
  153017. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153018. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  153019. {-15,-15,-15,-15,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  153020. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153021. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  153022. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  153023. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  153024. };
  153025. static double _noise_thresh_11[3]={ .3,.5,.5 };
  153026. /*** End of inlined file: psych_11.h ***/
  153027. static int blocksize_11[2]={
  153028. 512,512
  153029. };
  153030. static int _floor_mapping_11[2]={
  153031. 6,6,
  153032. };
  153033. static double rate_mapping_11[3]={
  153034. 8000.,13000.,44000.,
  153035. };
  153036. static double rate_mapping_11_uncoupled[3]={
  153037. 12000.,20000.,50000.,
  153038. };
  153039. static double quality_mapping_11[3]={
  153040. -.1,.0,1.
  153041. };
  153042. ve_setup_data_template ve_setup_11_stereo={
  153043. 2,
  153044. rate_mapping_11,
  153045. quality_mapping_11,
  153046. 2,
  153047. 9000,
  153048. 15000,
  153049. blocksize_11,
  153050. blocksize_11,
  153051. _psy_tone_masteratt_11,
  153052. _psy_tone_0dB,
  153053. _psy_tone_suppress,
  153054. _vp_tonemask_adj_11,
  153055. NULL,
  153056. _vp_tonemask_adj_11,
  153057. _psy_noiseguards_8,
  153058. _psy_noisebias_11,
  153059. _psy_noisebias_11,
  153060. NULL,
  153061. NULL,
  153062. _psy_noise_suppress,
  153063. _psy_compand_8,
  153064. _psy_compand_8_mapping,
  153065. NULL,
  153066. {_noise_start_8,_noise_start_8},
  153067. {_noise_part_8,_noise_part_8},
  153068. _noise_thresh_11,
  153069. _psy_ath_floater_8,
  153070. _psy_ath_abs_8,
  153071. _psy_lowpass_11,
  153072. _psy_global_44,
  153073. _global_mapping_8,
  153074. _psy_stereo_modes_8,
  153075. _floor_books,
  153076. _floor,
  153077. _floor_mapping_11,
  153078. NULL,
  153079. _mapres_template_8_stereo
  153080. };
  153081. ve_setup_data_template ve_setup_11_uncoupled={
  153082. 2,
  153083. rate_mapping_11_uncoupled,
  153084. quality_mapping_11,
  153085. -1,
  153086. 9000,
  153087. 15000,
  153088. blocksize_11,
  153089. blocksize_11,
  153090. _psy_tone_masteratt_11,
  153091. _psy_tone_0dB,
  153092. _psy_tone_suppress,
  153093. _vp_tonemask_adj_11,
  153094. NULL,
  153095. _vp_tonemask_adj_11,
  153096. _psy_noiseguards_8,
  153097. _psy_noisebias_11,
  153098. _psy_noisebias_11,
  153099. NULL,
  153100. NULL,
  153101. _psy_noise_suppress,
  153102. _psy_compand_8,
  153103. _psy_compand_8_mapping,
  153104. NULL,
  153105. {_noise_start_8,_noise_start_8},
  153106. {_noise_part_8,_noise_part_8},
  153107. _noise_thresh_11,
  153108. _psy_ath_floater_8,
  153109. _psy_ath_abs_8,
  153110. _psy_lowpass_11,
  153111. _psy_global_44,
  153112. _global_mapping_8,
  153113. _psy_stereo_modes_8,
  153114. _floor_books,
  153115. _floor,
  153116. _floor_mapping_11,
  153117. NULL,
  153118. _mapres_template_8_uncoupled
  153119. };
  153120. /*** End of inlined file: setup_11.h ***/
  153121. /*** Start of inlined file: setup_16.h ***/
  153122. /*** Start of inlined file: psych_16.h ***/
  153123. /* stereo mode by base quality level */
  153124. static adj_stereo _psy_stereo_modes_16[4]={
  153125. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  153126. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153127. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153128. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4},
  153129. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153130. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153131. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153132. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 4, 4, 4, 4, 4},
  153133. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153134. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153135. { 5, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153136. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153137. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153138. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  153139. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  153140. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8},
  153141. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153142. };
  153143. static double _psy_lowpass_16[4]={6.5,8,30.,99.};
  153144. static att3 _psy_tone_masteratt_16[4]={
  153145. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153146. {{ 25, 22, 12}, 0, 0}, /* 0 */
  153147. {{ 20, 12, 0}, 0, 0}, /* 0 */
  153148. {{ 15, 0, -14}, 0, 0}, /* 0 */
  153149. };
  153150. static vp_adjblock _vp_tonemask_adj_16[4]={
  153151. /* adjust for mode zero */
  153152. /* 63 125 250 500 1 2 4 8 16 */
  153153. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 0 */
  153154. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 1 */
  153155. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  153156. {{-30,-30,-30,-30,-30,-26,-20,-10, -5, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  153157. };
  153158. static noise3 _psy_noisebias_16_short[4]={
  153159. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153160. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  153161. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  153162. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153163. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  153164. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 4, 5, 6, 8, 8, 15},
  153165. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  153166. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  153167. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10, -8, 0, 0, 0, 0, 2, 5},
  153168. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153169. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  153170. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  153171. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153172. };
  153173. static noise3 _psy_noisebias_16_impulse[4]={
  153174. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153175. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  153176. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  153177. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153178. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 4, 4, 4, 5, 5, 6, 8, 15},
  153179. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 0, 0, 0, 0, 4, 10},
  153180. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  153181. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 4, 10},
  153182. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10,-10,-10,-10,-10,-10, -7, -5},
  153183. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153184. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  153185. {-30,-30,-30,-30,-26,-22,-20,-18,-18,-18,-20,-20,-20,-20,-20,-20,-16},
  153186. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153187. };
  153188. static noise3 _psy_noisebias_16[4]={
  153189. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153190. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 8, 8, 10, 10, 10, 14, 20},
  153191. {-10,-10,-10,-10,-10, -5, -2, -2, 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. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  153194. {-15,-15,-15,-15,-15,-10, -5, -5, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  153195. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153196. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  153197. {-20,-20,-20,-20,-16,-12,-20,-10, -5, -5, 0, 0, 0, 0, 0, 2, 5},
  153198. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153199. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  153200. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  153201. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153202. };
  153203. static double _noise_thresh_16[4]={ .3,.5,.5,.5 };
  153204. static int _noise_start_16[3]={ 256,256,9999 };
  153205. static int _noise_part_16[4]={ 8,8,8,8 };
  153206. static int _psy_ath_floater_16[4]={
  153207. -100,-100,-100,-105,
  153208. };
  153209. static int _psy_ath_abs_16[4]={
  153210. -130,-130,-130,-140,
  153211. };
  153212. /*** End of inlined file: psych_16.h ***/
  153213. /*** Start of inlined file: residue_16.h ***/
  153214. /***** residue backends *********************************************/
  153215. static static_bookblock _resbook_16s_0={
  153216. {
  153217. {0},
  153218. {0,0,&_16c0_s_p1_0},
  153219. {0,0,&_16c0_s_p2_0},
  153220. {0,0,&_16c0_s_p3_0},
  153221. {0,0,&_16c0_s_p4_0},
  153222. {0,0,&_16c0_s_p5_0},
  153223. {0,0,&_16c0_s_p6_0},
  153224. {&_16c0_s_p7_0,&_16c0_s_p7_1},
  153225. {&_16c0_s_p8_0,&_16c0_s_p8_1},
  153226. {&_16c0_s_p9_0,&_16c0_s_p9_1,&_16c0_s_p9_2}
  153227. }
  153228. };
  153229. static static_bookblock _resbook_16s_1={
  153230. {
  153231. {0},
  153232. {0,0,&_16c1_s_p1_0},
  153233. {0,0,&_16c1_s_p2_0},
  153234. {0,0,&_16c1_s_p3_0},
  153235. {0,0,&_16c1_s_p4_0},
  153236. {0,0,&_16c1_s_p5_0},
  153237. {0,0,&_16c1_s_p6_0},
  153238. {&_16c1_s_p7_0,&_16c1_s_p7_1},
  153239. {&_16c1_s_p8_0,&_16c1_s_p8_1},
  153240. {&_16c1_s_p9_0,&_16c1_s_p9_1,&_16c1_s_p9_2}
  153241. }
  153242. };
  153243. static static_bookblock _resbook_16s_2={
  153244. {
  153245. {0},
  153246. {0,0,&_16c2_s_p1_0},
  153247. {0,0,&_16c2_s_p2_0},
  153248. {0,0,&_16c2_s_p3_0},
  153249. {0,0,&_16c2_s_p4_0},
  153250. {&_16c2_s_p5_0,&_16c2_s_p5_1},
  153251. {&_16c2_s_p6_0,&_16c2_s_p6_1},
  153252. {&_16c2_s_p7_0,&_16c2_s_p7_1},
  153253. {&_16c2_s_p8_0,&_16c2_s_p8_1},
  153254. {&_16c2_s_p9_0,&_16c2_s_p9_1,&_16c2_s_p9_2}
  153255. }
  153256. };
  153257. static vorbis_residue_template _res_16s_0[]={
  153258. {2,0, &_residue_44_mid,
  153259. &_huff_book__16c0_s_single,&_huff_book__16c0_s_single,
  153260. &_resbook_16s_0,&_resbook_16s_0},
  153261. };
  153262. static vorbis_residue_template _res_16s_1[]={
  153263. {2,0, &_residue_44_mid,
  153264. &_huff_book__16c1_s_short,&_huff_book__16c1_s_short,
  153265. &_resbook_16s_1,&_resbook_16s_1},
  153266. {2,0, &_residue_44_mid,
  153267. &_huff_book__16c1_s_long,&_huff_book__16c1_s_long,
  153268. &_resbook_16s_1,&_resbook_16s_1}
  153269. };
  153270. static vorbis_residue_template _res_16s_2[]={
  153271. {2,0, &_residue_44_high,
  153272. &_huff_book__16c2_s_short,&_huff_book__16c2_s_short,
  153273. &_resbook_16s_2,&_resbook_16s_2},
  153274. {2,0, &_residue_44_high,
  153275. &_huff_book__16c2_s_long,&_huff_book__16c2_s_long,
  153276. &_resbook_16s_2,&_resbook_16s_2}
  153277. };
  153278. static vorbis_mapping_template _mapres_template_16_stereo[3]={
  153279. { _map_nominal, _res_16s_0 }, /* 0 */
  153280. { _map_nominal, _res_16s_1 }, /* 1 */
  153281. { _map_nominal, _res_16s_2 }, /* 2 */
  153282. };
  153283. static static_bookblock _resbook_16u_0={
  153284. {
  153285. {0},
  153286. {0,0,&_16u0__p1_0},
  153287. {0,0,&_16u0__p2_0},
  153288. {0,0,&_16u0__p3_0},
  153289. {0,0,&_16u0__p4_0},
  153290. {0,0,&_16u0__p5_0},
  153291. {&_16u0__p6_0,&_16u0__p6_1},
  153292. {&_16u0__p7_0,&_16u0__p7_1,&_16u0__p7_2}
  153293. }
  153294. };
  153295. static static_bookblock _resbook_16u_1={
  153296. {
  153297. {0},
  153298. {0,0,&_16u1__p1_0},
  153299. {0,0,&_16u1__p2_0},
  153300. {0,0,&_16u1__p3_0},
  153301. {0,0,&_16u1__p4_0},
  153302. {0,0,&_16u1__p5_0},
  153303. {0,0,&_16u1__p6_0},
  153304. {&_16u1__p7_0,&_16u1__p7_1},
  153305. {&_16u1__p8_0,&_16u1__p8_1},
  153306. {&_16u1__p9_0,&_16u1__p9_1,&_16u1__p9_2}
  153307. }
  153308. };
  153309. static static_bookblock _resbook_16u_2={
  153310. {
  153311. {0},
  153312. {0,0,&_16u2_p1_0},
  153313. {0,0,&_16u2_p2_0},
  153314. {0,0,&_16u2_p3_0},
  153315. {0,0,&_16u2_p4_0},
  153316. {&_16u2_p5_0,&_16u2_p5_1},
  153317. {&_16u2_p6_0,&_16u2_p6_1},
  153318. {&_16u2_p7_0,&_16u2_p7_1},
  153319. {&_16u2_p8_0,&_16u2_p8_1},
  153320. {&_16u2_p9_0,&_16u2_p9_1,&_16u2_p9_2}
  153321. }
  153322. };
  153323. static vorbis_residue_template _res_16u_0[]={
  153324. {1,0, &_residue_44_low_un,
  153325. &_huff_book__16u0__single,&_huff_book__16u0__single,
  153326. &_resbook_16u_0,&_resbook_16u_0},
  153327. };
  153328. static vorbis_residue_template _res_16u_1[]={
  153329. {1,0, &_residue_44_mid_un,
  153330. &_huff_book__16u1__short,&_huff_book__16u1__short,
  153331. &_resbook_16u_1,&_resbook_16u_1},
  153332. {1,0, &_residue_44_mid_un,
  153333. &_huff_book__16u1__long,&_huff_book__16u1__long,
  153334. &_resbook_16u_1,&_resbook_16u_1}
  153335. };
  153336. static vorbis_residue_template _res_16u_2[]={
  153337. {1,0, &_residue_44_hi_un,
  153338. &_huff_book__16u2__short,&_huff_book__16u2__short,
  153339. &_resbook_16u_2,&_resbook_16u_2},
  153340. {1,0, &_residue_44_hi_un,
  153341. &_huff_book__16u2__long,&_huff_book__16u2__long,
  153342. &_resbook_16u_2,&_resbook_16u_2}
  153343. };
  153344. static vorbis_mapping_template _mapres_template_16_uncoupled[3]={
  153345. { _map_nominal_u, _res_16u_0 }, /* 0 */
  153346. { _map_nominal_u, _res_16u_1 }, /* 1 */
  153347. { _map_nominal_u, _res_16u_2 }, /* 2 */
  153348. };
  153349. /*** End of inlined file: residue_16.h ***/
  153350. static int blocksize_16_short[3]={
  153351. 1024,512,512
  153352. };
  153353. static int blocksize_16_long[3]={
  153354. 1024,1024,1024
  153355. };
  153356. static int _floor_mapping_16_short[3]={
  153357. 9,3,3
  153358. };
  153359. static int _floor_mapping_16[3]={
  153360. 9,9,9
  153361. };
  153362. static double rate_mapping_16[4]={
  153363. 12000.,20000.,44000.,86000.
  153364. };
  153365. static double rate_mapping_16_uncoupled[4]={
  153366. 16000.,28000.,64000.,100000.
  153367. };
  153368. static double _global_mapping_16[4]={ 1., 2., 3., 4. };
  153369. static double quality_mapping_16[4]={ -.1,.05,.5,1. };
  153370. static double _psy_compand_16_mapping[4]={ 0., .8, 1., 1.};
  153371. ve_setup_data_template ve_setup_16_stereo={
  153372. 3,
  153373. rate_mapping_16,
  153374. quality_mapping_16,
  153375. 2,
  153376. 15000,
  153377. 19000,
  153378. blocksize_16_short,
  153379. blocksize_16_long,
  153380. _psy_tone_masteratt_16,
  153381. _psy_tone_0dB,
  153382. _psy_tone_suppress,
  153383. _vp_tonemask_adj_16,
  153384. _vp_tonemask_adj_16,
  153385. _vp_tonemask_adj_16,
  153386. _psy_noiseguards_8,
  153387. _psy_noisebias_16_impulse,
  153388. _psy_noisebias_16_short,
  153389. _psy_noisebias_16_short,
  153390. _psy_noisebias_16,
  153391. _psy_noise_suppress,
  153392. _psy_compand_8,
  153393. _psy_compand_16_mapping,
  153394. _psy_compand_16_mapping,
  153395. {_noise_start_16,_noise_start_16},
  153396. { _noise_part_16, _noise_part_16},
  153397. _noise_thresh_16,
  153398. _psy_ath_floater_16,
  153399. _psy_ath_abs_16,
  153400. _psy_lowpass_16,
  153401. _psy_global_44,
  153402. _global_mapping_16,
  153403. _psy_stereo_modes_16,
  153404. _floor_books,
  153405. _floor,
  153406. _floor_mapping_16_short,
  153407. _floor_mapping_16,
  153408. _mapres_template_16_stereo
  153409. };
  153410. ve_setup_data_template ve_setup_16_uncoupled={
  153411. 3,
  153412. rate_mapping_16_uncoupled,
  153413. quality_mapping_16,
  153414. -1,
  153415. 15000,
  153416. 19000,
  153417. blocksize_16_short,
  153418. blocksize_16_long,
  153419. _psy_tone_masteratt_16,
  153420. _psy_tone_0dB,
  153421. _psy_tone_suppress,
  153422. _vp_tonemask_adj_16,
  153423. _vp_tonemask_adj_16,
  153424. _vp_tonemask_adj_16,
  153425. _psy_noiseguards_8,
  153426. _psy_noisebias_16_impulse,
  153427. _psy_noisebias_16_short,
  153428. _psy_noisebias_16_short,
  153429. _psy_noisebias_16,
  153430. _psy_noise_suppress,
  153431. _psy_compand_8,
  153432. _psy_compand_16_mapping,
  153433. _psy_compand_16_mapping,
  153434. {_noise_start_16,_noise_start_16},
  153435. { _noise_part_16, _noise_part_16},
  153436. _noise_thresh_16,
  153437. _psy_ath_floater_16,
  153438. _psy_ath_abs_16,
  153439. _psy_lowpass_16,
  153440. _psy_global_44,
  153441. _global_mapping_16,
  153442. _psy_stereo_modes_16,
  153443. _floor_books,
  153444. _floor,
  153445. _floor_mapping_16_short,
  153446. _floor_mapping_16,
  153447. _mapres_template_16_uncoupled
  153448. };
  153449. /*** End of inlined file: setup_16.h ***/
  153450. /*** Start of inlined file: setup_22.h ***/
  153451. static double rate_mapping_22[4]={
  153452. 15000.,20000.,44000.,86000.
  153453. };
  153454. static double rate_mapping_22_uncoupled[4]={
  153455. 16000.,28000.,50000.,90000.
  153456. };
  153457. static double _psy_lowpass_22[4]={9.5,11.,30.,99.};
  153458. ve_setup_data_template ve_setup_22_stereo={
  153459. 3,
  153460. rate_mapping_22,
  153461. quality_mapping_16,
  153462. 2,
  153463. 19000,
  153464. 26000,
  153465. blocksize_16_short,
  153466. blocksize_16_long,
  153467. _psy_tone_masteratt_16,
  153468. _psy_tone_0dB,
  153469. _psy_tone_suppress,
  153470. _vp_tonemask_adj_16,
  153471. _vp_tonemask_adj_16,
  153472. _vp_tonemask_adj_16,
  153473. _psy_noiseguards_8,
  153474. _psy_noisebias_16_impulse,
  153475. _psy_noisebias_16_short,
  153476. _psy_noisebias_16_short,
  153477. _psy_noisebias_16,
  153478. _psy_noise_suppress,
  153479. _psy_compand_8,
  153480. _psy_compand_8_mapping,
  153481. _psy_compand_8_mapping,
  153482. {_noise_start_16,_noise_start_16},
  153483. { _noise_part_16, _noise_part_16},
  153484. _noise_thresh_16,
  153485. _psy_ath_floater_16,
  153486. _psy_ath_abs_16,
  153487. _psy_lowpass_22,
  153488. _psy_global_44,
  153489. _global_mapping_16,
  153490. _psy_stereo_modes_16,
  153491. _floor_books,
  153492. _floor,
  153493. _floor_mapping_16_short,
  153494. _floor_mapping_16,
  153495. _mapres_template_16_stereo
  153496. };
  153497. ve_setup_data_template ve_setup_22_uncoupled={
  153498. 3,
  153499. rate_mapping_22_uncoupled,
  153500. quality_mapping_16,
  153501. -1,
  153502. 19000,
  153503. 26000,
  153504. blocksize_16_short,
  153505. blocksize_16_long,
  153506. _psy_tone_masteratt_16,
  153507. _psy_tone_0dB,
  153508. _psy_tone_suppress,
  153509. _vp_tonemask_adj_16,
  153510. _vp_tonemask_adj_16,
  153511. _vp_tonemask_adj_16,
  153512. _psy_noiseguards_8,
  153513. _psy_noisebias_16_impulse,
  153514. _psy_noisebias_16_short,
  153515. _psy_noisebias_16_short,
  153516. _psy_noisebias_16,
  153517. _psy_noise_suppress,
  153518. _psy_compand_8,
  153519. _psy_compand_8_mapping,
  153520. _psy_compand_8_mapping,
  153521. {_noise_start_16,_noise_start_16},
  153522. { _noise_part_16, _noise_part_16},
  153523. _noise_thresh_16,
  153524. _psy_ath_floater_16,
  153525. _psy_ath_abs_16,
  153526. _psy_lowpass_22,
  153527. _psy_global_44,
  153528. _global_mapping_16,
  153529. _psy_stereo_modes_16,
  153530. _floor_books,
  153531. _floor,
  153532. _floor_mapping_16_short,
  153533. _floor_mapping_16,
  153534. _mapres_template_16_uncoupled
  153535. };
  153536. /*** End of inlined file: setup_22.h ***/
  153537. /*** Start of inlined file: setup_X.h ***/
  153538. static double rate_mapping_X[12]={
  153539. -1.,-1.,-1.,-1.,-1.,-1.,
  153540. -1.,-1.,-1.,-1.,-1.,-1.
  153541. };
  153542. ve_setup_data_template ve_setup_X_stereo={
  153543. 11,
  153544. rate_mapping_X,
  153545. quality_mapping_44,
  153546. 2,
  153547. 50000,
  153548. 200000,
  153549. blocksize_short_44,
  153550. blocksize_long_44,
  153551. _psy_tone_masteratt_44,
  153552. _psy_tone_0dB,
  153553. _psy_tone_suppress,
  153554. _vp_tonemask_adj_otherblock,
  153555. _vp_tonemask_adj_longblock,
  153556. _vp_tonemask_adj_otherblock,
  153557. _psy_noiseguards_44,
  153558. _psy_noisebias_impulse,
  153559. _psy_noisebias_padding,
  153560. _psy_noisebias_trans,
  153561. _psy_noisebias_long,
  153562. _psy_noise_suppress,
  153563. _psy_compand_44,
  153564. _psy_compand_short_mapping,
  153565. _psy_compand_long_mapping,
  153566. {_noise_start_short_44,_noise_start_long_44},
  153567. {_noise_part_short_44,_noise_part_long_44},
  153568. _noise_thresh_44,
  153569. _psy_ath_floater,
  153570. _psy_ath_abs,
  153571. _psy_lowpass_44,
  153572. _psy_global_44,
  153573. _global_mapping_44,
  153574. _psy_stereo_modes_44,
  153575. _floor_books,
  153576. _floor,
  153577. _floor_short_mapping_44,
  153578. _floor_long_mapping_44,
  153579. _mapres_template_44_stereo
  153580. };
  153581. ve_setup_data_template ve_setup_X_uncoupled={
  153582. 11,
  153583. rate_mapping_X,
  153584. quality_mapping_44,
  153585. -1,
  153586. 50000,
  153587. 200000,
  153588. blocksize_short_44,
  153589. blocksize_long_44,
  153590. _psy_tone_masteratt_44,
  153591. _psy_tone_0dB,
  153592. _psy_tone_suppress,
  153593. _vp_tonemask_adj_otherblock,
  153594. _vp_tonemask_adj_longblock,
  153595. _vp_tonemask_adj_otherblock,
  153596. _psy_noiseguards_44,
  153597. _psy_noisebias_impulse,
  153598. _psy_noisebias_padding,
  153599. _psy_noisebias_trans,
  153600. _psy_noisebias_long,
  153601. _psy_noise_suppress,
  153602. _psy_compand_44,
  153603. _psy_compand_short_mapping,
  153604. _psy_compand_long_mapping,
  153605. {_noise_start_short_44,_noise_start_long_44},
  153606. {_noise_part_short_44,_noise_part_long_44},
  153607. _noise_thresh_44,
  153608. _psy_ath_floater,
  153609. _psy_ath_abs,
  153610. _psy_lowpass_44,
  153611. _psy_global_44,
  153612. _global_mapping_44,
  153613. NULL,
  153614. _floor_books,
  153615. _floor,
  153616. _floor_short_mapping_44,
  153617. _floor_long_mapping_44,
  153618. _mapres_template_44_uncoupled
  153619. };
  153620. ve_setup_data_template ve_setup_XX_stereo={
  153621. 2,
  153622. rate_mapping_X,
  153623. quality_mapping_8,
  153624. 2,
  153625. 0,
  153626. 8000,
  153627. blocksize_8,
  153628. blocksize_8,
  153629. _psy_tone_masteratt_8,
  153630. _psy_tone_0dB,
  153631. _psy_tone_suppress,
  153632. _vp_tonemask_adj_8,
  153633. NULL,
  153634. _vp_tonemask_adj_8,
  153635. _psy_noiseguards_8,
  153636. _psy_noisebias_8,
  153637. _psy_noisebias_8,
  153638. NULL,
  153639. NULL,
  153640. _psy_noise_suppress,
  153641. _psy_compand_8,
  153642. _psy_compand_8_mapping,
  153643. NULL,
  153644. {_noise_start_8,_noise_start_8},
  153645. {_noise_part_8,_noise_part_8},
  153646. _noise_thresh_5only,
  153647. _psy_ath_floater_8,
  153648. _psy_ath_abs_8,
  153649. _psy_lowpass_8,
  153650. _psy_global_44,
  153651. _global_mapping_8,
  153652. _psy_stereo_modes_8,
  153653. _floor_books,
  153654. _floor,
  153655. _floor_mapping_8,
  153656. NULL,
  153657. _mapres_template_8_stereo
  153658. };
  153659. ve_setup_data_template ve_setup_XX_uncoupled={
  153660. 2,
  153661. rate_mapping_X,
  153662. quality_mapping_8,
  153663. -1,
  153664. 0,
  153665. 8000,
  153666. blocksize_8,
  153667. blocksize_8,
  153668. _psy_tone_masteratt_8,
  153669. _psy_tone_0dB,
  153670. _psy_tone_suppress,
  153671. _vp_tonemask_adj_8,
  153672. NULL,
  153673. _vp_tonemask_adj_8,
  153674. _psy_noiseguards_8,
  153675. _psy_noisebias_8,
  153676. _psy_noisebias_8,
  153677. NULL,
  153678. NULL,
  153679. _psy_noise_suppress,
  153680. _psy_compand_8,
  153681. _psy_compand_8_mapping,
  153682. NULL,
  153683. {_noise_start_8,_noise_start_8},
  153684. {_noise_part_8,_noise_part_8},
  153685. _noise_thresh_5only,
  153686. _psy_ath_floater_8,
  153687. _psy_ath_abs_8,
  153688. _psy_lowpass_8,
  153689. _psy_global_44,
  153690. _global_mapping_8,
  153691. _psy_stereo_modes_8,
  153692. _floor_books,
  153693. _floor,
  153694. _floor_mapping_8,
  153695. NULL,
  153696. _mapres_template_8_uncoupled
  153697. };
  153698. /*** End of inlined file: setup_X.h ***/
  153699. static ve_setup_data_template *setup_list[]={
  153700. &ve_setup_44_stereo,
  153701. &ve_setup_44_uncoupled,
  153702. &ve_setup_32_stereo,
  153703. &ve_setup_32_uncoupled,
  153704. &ve_setup_22_stereo,
  153705. &ve_setup_22_uncoupled,
  153706. &ve_setup_16_stereo,
  153707. &ve_setup_16_uncoupled,
  153708. &ve_setup_11_stereo,
  153709. &ve_setup_11_uncoupled,
  153710. &ve_setup_8_stereo,
  153711. &ve_setup_8_uncoupled,
  153712. &ve_setup_X_stereo,
  153713. &ve_setup_X_uncoupled,
  153714. &ve_setup_XX_stereo,
  153715. &ve_setup_XX_uncoupled,
  153716. 0
  153717. };
  153718. static int vorbis_encode_toplevel_setup(vorbis_info *vi,int ch,long rate){
  153719. if(vi && vi->codec_setup){
  153720. vi->version=0;
  153721. vi->channels=ch;
  153722. vi->rate=rate;
  153723. return(0);
  153724. }
  153725. return(OV_EINVAL);
  153726. }
  153727. static void vorbis_encode_floor_setup(vorbis_info *vi,double s,int block,
  153728. static_codebook ***books,
  153729. vorbis_info_floor1 *in,
  153730. int *x){
  153731. int i,k,is=s;
  153732. vorbis_info_floor1 *f=(vorbis_info_floor1*) _ogg_calloc(1,sizeof(*f));
  153733. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  153734. memcpy(f,in+x[is],sizeof(*f));
  153735. /* fill in the lowpass field, even if it's temporary */
  153736. f->n=ci->blocksizes[block]>>1;
  153737. /* books */
  153738. {
  153739. int partitions=f->partitions;
  153740. int maxclass=-1;
  153741. int maxbook=-1;
  153742. for(i=0;i<partitions;i++)
  153743. if(f->partitionclass[i]>maxclass)maxclass=f->partitionclass[i];
  153744. for(i=0;i<=maxclass;i++){
  153745. if(f->class_book[i]>maxbook)maxbook=f->class_book[i];
  153746. f->class_book[i]+=ci->books;
  153747. for(k=0;k<(1<<f->class_subs[i]);k++){
  153748. if(f->class_subbook[i][k]>maxbook)maxbook=f->class_subbook[i][k];
  153749. if(f->class_subbook[i][k]>=0)f->class_subbook[i][k]+=ci->books;
  153750. }
  153751. }
  153752. for(i=0;i<=maxbook;i++)
  153753. ci->book_param[ci->books++]=books[x[is]][i];
  153754. }
  153755. /* for now, we're only using floor 1 */
  153756. ci->floor_type[ci->floors]=1;
  153757. ci->floor_param[ci->floors]=f;
  153758. ci->floors++;
  153759. return;
  153760. }
  153761. static void vorbis_encode_global_psych_setup(vorbis_info *vi,double s,
  153762. vorbis_info_psy_global *in,
  153763. double *x){
  153764. int i,is=s;
  153765. double ds=s-is;
  153766. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  153767. vorbis_info_psy_global *g=&ci->psy_g_param;
  153768. memcpy(g,in+(int)x[is],sizeof(*g));
  153769. ds=x[is]*(1.-ds)+x[is+1]*ds;
  153770. is=(int)ds;
  153771. ds-=is;
  153772. if(ds==0 && is>0){
  153773. is--;
  153774. ds=1.;
  153775. }
  153776. /* interpolate the trigger threshholds */
  153777. for(i=0;i<4;i++){
  153778. g->preecho_thresh[i]=in[is].preecho_thresh[i]*(1.-ds)+in[is+1].preecho_thresh[i]*ds;
  153779. g->postecho_thresh[i]=in[is].postecho_thresh[i]*(1.-ds)+in[is+1].postecho_thresh[i]*ds;
  153780. }
  153781. g->ampmax_att_per_sec=ci->hi.amplitude_track_dBpersec;
  153782. return;
  153783. }
  153784. static void vorbis_encode_global_stereo(vorbis_info *vi,
  153785. highlevel_encode_setup *hi,
  153786. adj_stereo *p){
  153787. float s=hi->stereo_point_setting;
  153788. int i,is=s;
  153789. double ds=s-is;
  153790. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  153791. vorbis_info_psy_global *g=&ci->psy_g_param;
  153792. if(p){
  153793. memcpy(g->coupling_prepointamp,p[is].pre,sizeof(*p[is].pre)*PACKETBLOBS);
  153794. memcpy(g->coupling_postpointamp,p[is].post,sizeof(*p[is].post)*PACKETBLOBS);
  153795. if(hi->managed){
  153796. /* interpolate the kHz threshholds */
  153797. for(i=0;i<PACKETBLOBS;i++){
  153798. float kHz=p[is].kHz[i]*(1.-ds)+p[is+1].kHz[i]*ds;
  153799. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  153800. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  153801. g->coupling_pkHz[i]=kHz;
  153802. kHz=p[is].lowpasskHz[i]*(1.-ds)+p[is+1].lowpasskHz[i]*ds;
  153803. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  153804. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  153805. }
  153806. }else{
  153807. float kHz=p[is].kHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].kHz[PACKETBLOBS/2]*ds;
  153808. for(i=0;i<PACKETBLOBS;i++){
  153809. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  153810. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  153811. g->coupling_pkHz[i]=kHz;
  153812. }
  153813. kHz=p[is].lowpasskHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].lowpasskHz[PACKETBLOBS/2]*ds;
  153814. for(i=0;i<PACKETBLOBS;i++){
  153815. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  153816. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  153817. }
  153818. }
  153819. }else{
  153820. for(i=0;i<PACKETBLOBS;i++){
  153821. g->sliding_lowpass[0][i]=ci->blocksizes[0];
  153822. g->sliding_lowpass[1][i]=ci->blocksizes[1];
  153823. }
  153824. }
  153825. return;
  153826. }
  153827. static void vorbis_encode_psyset_setup(vorbis_info *vi,double s,
  153828. int *nn_start,
  153829. int *nn_partition,
  153830. double *nn_thresh,
  153831. int block){
  153832. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  153833. vorbis_info_psy *p=ci->psy_param[block];
  153834. highlevel_encode_setup *hi=&ci->hi;
  153835. int is=s;
  153836. if(block>=ci->psys)
  153837. ci->psys=block+1;
  153838. if(!p){
  153839. p=(vorbis_info_psy*)_ogg_calloc(1,sizeof(*p));
  153840. ci->psy_param[block]=p;
  153841. }
  153842. memcpy(p,&_psy_info_template,sizeof(*p));
  153843. p->blockflag=block>>1;
  153844. if(hi->noise_normalize_p){
  153845. p->normal_channel_p=1;
  153846. p->normal_point_p=1;
  153847. p->normal_start=nn_start[is];
  153848. p->normal_partition=nn_partition[is];
  153849. p->normal_thresh=nn_thresh[is];
  153850. }
  153851. return;
  153852. }
  153853. static void vorbis_encode_tonemask_setup(vorbis_info *vi,double s,int block,
  153854. att3 *att,
  153855. int *max,
  153856. vp_adjblock *in){
  153857. int i,is=s;
  153858. double ds=s-is;
  153859. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  153860. vorbis_info_psy *p=ci->psy_param[block];
  153861. /* 0 and 2 are only used by bitmanagement, but there's no harm to always
  153862. filling the values in here */
  153863. p->tone_masteratt[0]=att[is].att[0]*(1.-ds)+att[is+1].att[0]*ds;
  153864. p->tone_masteratt[1]=att[is].att[1]*(1.-ds)+att[is+1].att[1]*ds;
  153865. p->tone_masteratt[2]=att[is].att[2]*(1.-ds)+att[is+1].att[2]*ds;
  153866. p->tone_centerboost=att[is].boost*(1.-ds)+att[is+1].boost*ds;
  153867. p->tone_decay=att[is].decay*(1.-ds)+att[is+1].decay*ds;
  153868. p->max_curve_dB=max[is]*(1.-ds)+max[is+1]*ds;
  153869. for(i=0;i<P_BANDS;i++)
  153870. p->toneatt[i]=in[is].block[i]*(1.-ds)+in[is+1].block[i]*ds;
  153871. return;
  153872. }
  153873. static void vorbis_encode_compand_setup(vorbis_info *vi,double s,int block,
  153874. compandblock *in, double *x){
  153875. int i,is=s;
  153876. double ds=s-is;
  153877. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  153878. vorbis_info_psy *p=ci->psy_param[block];
  153879. ds=x[is]*(1.-ds)+x[is+1]*ds;
  153880. is=(int)ds;
  153881. ds-=is;
  153882. if(ds==0 && is>0){
  153883. is--;
  153884. ds=1.;
  153885. }
  153886. /* interpolate the compander settings */
  153887. for(i=0;i<NOISE_COMPAND_LEVELS;i++)
  153888. p->noisecompand[i]=in[is].data[i]*(1.-ds)+in[is+1].data[i]*ds;
  153889. return;
  153890. }
  153891. static void vorbis_encode_peak_setup(vorbis_info *vi,double s,int block,
  153892. int *suppress){
  153893. int is=s;
  153894. double ds=s-is;
  153895. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  153896. vorbis_info_psy *p=ci->psy_param[block];
  153897. p->tone_abs_limit=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  153898. return;
  153899. }
  153900. static void vorbis_encode_noisebias_setup(vorbis_info *vi,double s,int block,
  153901. int *suppress,
  153902. noise3 *in,
  153903. noiseguard *guard,
  153904. double userbias){
  153905. int i,is=s,j;
  153906. double ds=s-is;
  153907. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  153908. vorbis_info_psy *p=ci->psy_param[block];
  153909. p->noisemaxsupp=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  153910. p->noisewindowlomin=guard[block].lo;
  153911. p->noisewindowhimin=guard[block].hi;
  153912. p->noisewindowfixed=guard[block].fixed;
  153913. for(j=0;j<P_NOISECURVES;j++)
  153914. for(i=0;i<P_BANDS;i++)
  153915. p->noiseoff[j][i]=in[is].data[j][i]*(1.-ds)+in[is+1].data[j][i]*ds;
  153916. /* impulse blocks may take a user specified bias to boost the
  153917. nominal/high noise encoding depth */
  153918. for(j=0;j<P_NOISECURVES;j++){
  153919. float min=p->noiseoff[j][0]+6; /* the lowest it can go */
  153920. for(i=0;i<P_BANDS;i++){
  153921. p->noiseoff[j][i]+=userbias;
  153922. if(p->noiseoff[j][i]<min)p->noiseoff[j][i]=min;
  153923. }
  153924. }
  153925. return;
  153926. }
  153927. static void vorbis_encode_ath_setup(vorbis_info *vi,int block){
  153928. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  153929. vorbis_info_psy *p=ci->psy_param[block];
  153930. p->ath_adjatt=ci->hi.ath_floating_dB;
  153931. p->ath_maxatt=ci->hi.ath_absolute_dB;
  153932. return;
  153933. }
  153934. static int book_dup_or_new(codec_setup_info *ci,static_codebook *book){
  153935. int i;
  153936. for(i=0;i<ci->books;i++)
  153937. if(ci->book_param[i]==book)return(i);
  153938. return(ci->books++);
  153939. }
  153940. static void vorbis_encode_blocksize_setup(vorbis_info *vi,double s,
  153941. int *shortb,int *longb){
  153942. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  153943. int is=s;
  153944. int blockshort=shortb[is];
  153945. int blocklong=longb[is];
  153946. ci->blocksizes[0]=blockshort;
  153947. ci->blocksizes[1]=blocklong;
  153948. }
  153949. static void vorbis_encode_residue_setup(vorbis_info *vi,
  153950. int number, int block,
  153951. vorbis_residue_template *res){
  153952. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  153953. int i,n;
  153954. vorbis_info_residue0 *r=(vorbis_info_residue0*)(ci->residue_param[number]=
  153955. (vorbis_info_residue0*)_ogg_malloc(sizeof(*r)));
  153956. memcpy(r,res->res,sizeof(*r));
  153957. if(ci->residues<=number)ci->residues=number+1;
  153958. switch(ci->blocksizes[block]){
  153959. case 64:case 128:case 256:
  153960. r->grouping=16;
  153961. break;
  153962. default:
  153963. r->grouping=32;
  153964. break;
  153965. }
  153966. ci->residue_type[number]=res->res_type;
  153967. /* to be adjusted by lowpass/pointlimit later */
  153968. n=r->end=ci->blocksizes[block]>>1;
  153969. if(res->res_type==2)
  153970. n=r->end*=vi->channels;
  153971. /* fill in all the books */
  153972. {
  153973. int booklist=0,k;
  153974. if(ci->hi.managed){
  153975. for(i=0;i<r->partitions;i++)
  153976. for(k=0;k<3;k++)
  153977. if(res->books_base_managed->books[i][k])
  153978. r->secondstages[i]|=(1<<k);
  153979. r->groupbook=book_dup_or_new(ci,res->book_aux_managed);
  153980. ci->book_param[r->groupbook]=res->book_aux_managed;
  153981. for(i=0;i<r->partitions;i++){
  153982. for(k=0;k<3;k++){
  153983. if(res->books_base_managed->books[i][k]){
  153984. int bookid=book_dup_or_new(ci,res->books_base_managed->books[i][k]);
  153985. r->booklist[booklist++]=bookid;
  153986. ci->book_param[bookid]=res->books_base_managed->books[i][k];
  153987. }
  153988. }
  153989. }
  153990. }else{
  153991. for(i=0;i<r->partitions;i++)
  153992. for(k=0;k<3;k++)
  153993. if(res->books_base->books[i][k])
  153994. r->secondstages[i]|=(1<<k);
  153995. r->groupbook=book_dup_or_new(ci,res->book_aux);
  153996. ci->book_param[r->groupbook]=res->book_aux;
  153997. for(i=0;i<r->partitions;i++){
  153998. for(k=0;k<3;k++){
  153999. if(res->books_base->books[i][k]){
  154000. int bookid=book_dup_or_new(ci,res->books_base->books[i][k]);
  154001. r->booklist[booklist++]=bookid;
  154002. ci->book_param[bookid]=res->books_base->books[i][k];
  154003. }
  154004. }
  154005. }
  154006. }
  154007. }
  154008. /* lowpass setup/pointlimit */
  154009. {
  154010. double freq=ci->hi.lowpass_kHz*1000.;
  154011. vorbis_info_floor1 *f=(vorbis_info_floor1*)ci->floor_param[block]; /* by convention */
  154012. double nyq=vi->rate/2.;
  154013. long blocksize=ci->blocksizes[block]>>1;
  154014. /* lowpass needs to be set in the floor and the residue. */
  154015. if(freq>nyq)freq=nyq;
  154016. /* in the floor, the granularity can be very fine; it doesn't alter
  154017. the encoding structure, only the samples used to fit the floor
  154018. approximation */
  154019. f->n=freq/nyq*blocksize;
  154020. /* this res may by limited by the maximum pointlimit of the mode,
  154021. not the lowpass. the floor is always lowpass limited. */
  154022. if(res->limit_type){
  154023. if(ci->hi.managed)
  154024. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS-1]*1000.;
  154025. else
  154026. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS/2]*1000.;
  154027. if(freq>nyq)freq=nyq;
  154028. }
  154029. /* in the residue, we're constrained, physically, by partition
  154030. boundaries. We still lowpass 'wherever', but we have to round up
  154031. here to next boundary, or the vorbis spec will round it *down* to
  154032. previous boundary in encode/decode */
  154033. if(ci->residue_type[block]==2)
  154034. r->end=(int)((freq/nyq*blocksize*2)/r->grouping+.9)* /* round up only if we're well past */
  154035. r->grouping;
  154036. else
  154037. r->end=(int)((freq/nyq*blocksize)/r->grouping+.9)* /* round up only if we're well past */
  154038. r->grouping;
  154039. }
  154040. }
  154041. /* we assume two maps in this encoder */
  154042. static void vorbis_encode_map_n_res_setup(vorbis_info *vi,double s,
  154043. vorbis_mapping_template *maps){
  154044. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154045. int i,j,is=s,modes=2;
  154046. vorbis_info_mapping0 *map=maps[is].map;
  154047. vorbis_info_mode *mode=_mode_template;
  154048. vorbis_residue_template *res=maps[is].res;
  154049. if(ci->blocksizes[0]==ci->blocksizes[1])modes=1;
  154050. for(i=0;i<modes;i++){
  154051. ci->map_param[i]=_ogg_calloc(1,sizeof(*map));
  154052. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*mode));
  154053. memcpy(ci->mode_param[i],mode+i,sizeof(*_mode_template));
  154054. if(i>=ci->modes)ci->modes=i+1;
  154055. ci->map_type[i]=0;
  154056. memcpy(ci->map_param[i],map+i,sizeof(*map));
  154057. if(i>=ci->maps)ci->maps=i+1;
  154058. for(j=0;j<map[i].submaps;j++)
  154059. vorbis_encode_residue_setup(vi,map[i].residuesubmap[j],i
  154060. ,res+map[i].residuesubmap[j]);
  154061. }
  154062. }
  154063. static double setting_to_approx_bitrate(vorbis_info *vi){
  154064. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154065. highlevel_encode_setup *hi=&ci->hi;
  154066. ve_setup_data_template *setup=(ve_setup_data_template *)hi->setup;
  154067. int is=hi->base_setting;
  154068. double ds=hi->base_setting-is;
  154069. int ch=vi->channels;
  154070. double *r=setup->rate_mapping;
  154071. if(r==NULL)
  154072. return(-1);
  154073. return((r[is]*(1.-ds)+r[is+1]*ds)*ch);
  154074. }
  154075. static void get_setup_template(vorbis_info *vi,
  154076. long ch,long srate,
  154077. double req,int q_or_bitrate){
  154078. int i=0,j;
  154079. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154080. highlevel_encode_setup *hi=&ci->hi;
  154081. if(q_or_bitrate)req/=ch;
  154082. while(setup_list[i]){
  154083. if(setup_list[i]->coupling_restriction==-1 ||
  154084. setup_list[i]->coupling_restriction==ch){
  154085. if(srate>=setup_list[i]->samplerate_min_restriction &&
  154086. srate<=setup_list[i]->samplerate_max_restriction){
  154087. int mappings=setup_list[i]->mappings;
  154088. double *map=(q_or_bitrate?
  154089. setup_list[i]->rate_mapping:
  154090. setup_list[i]->quality_mapping);
  154091. /* the template matches. Does the requested quality mode
  154092. fall within this template's modes? */
  154093. if(req<map[0]){++i;continue;}
  154094. if(req>map[setup_list[i]->mappings]){++i;continue;}
  154095. for(j=0;j<mappings;j++)
  154096. if(req>=map[j] && req<map[j+1])break;
  154097. /* an all-points match */
  154098. hi->setup=setup_list[i];
  154099. if(j==mappings)
  154100. hi->base_setting=j-.001;
  154101. else{
  154102. float low=map[j];
  154103. float high=map[j+1];
  154104. float del=(req-low)/(high-low);
  154105. hi->base_setting=j+del;
  154106. }
  154107. return;
  154108. }
  154109. }
  154110. i++;
  154111. }
  154112. hi->setup=NULL;
  154113. }
  154114. /* encoders will need to use vorbis_info_init beforehand and call
  154115. vorbis_info clear when all done */
  154116. /* two interfaces; this, more detailed one, and later a convenience
  154117. layer on top */
  154118. /* the final setup call */
  154119. int vorbis_encode_setup_init(vorbis_info *vi){
  154120. int i0=0,singleblock=0;
  154121. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154122. ve_setup_data_template *setup=NULL;
  154123. highlevel_encode_setup *hi=&ci->hi;
  154124. if(ci==NULL)return(OV_EINVAL);
  154125. if(!hi->impulse_block_p)i0=1;
  154126. /* too low/high an ATH floater is nonsensical, but doesn't break anything */
  154127. if(hi->ath_floating_dB>-80)hi->ath_floating_dB=-80;
  154128. if(hi->ath_floating_dB<-200)hi->ath_floating_dB=-200;
  154129. /* again, bound this to avoid the app shooting itself int he foot
  154130. too badly */
  154131. if(hi->amplitude_track_dBpersec>0.)hi->amplitude_track_dBpersec=0.;
  154132. if(hi->amplitude_track_dBpersec<-99999.)hi->amplitude_track_dBpersec=-99999.;
  154133. /* get the appropriate setup template; matches the fetch in previous
  154134. stages */
  154135. setup=(ve_setup_data_template *)hi->setup;
  154136. if(setup==NULL)return(OV_EINVAL);
  154137. hi->set_in_stone=1;
  154138. /* choose block sizes from configured sizes as well as paying
  154139. attention to long_block_p and short_block_p. If the configured
  154140. short and long blocks are the same length, we set long_block_p
  154141. and unset short_block_p */
  154142. vorbis_encode_blocksize_setup(vi,hi->base_setting,
  154143. setup->blocksize_short,
  154144. setup->blocksize_long);
  154145. if(ci->blocksizes[0]==ci->blocksizes[1])singleblock=1;
  154146. /* floor setup; choose proper floor params. Allocated on the floor
  154147. stack in order; if we alloc only long floor, it's 0 */
  154148. vorbis_encode_floor_setup(vi,hi->short_setting,0,
  154149. setup->floor_books,
  154150. setup->floor_params,
  154151. setup->floor_short_mapping);
  154152. if(!singleblock)
  154153. vorbis_encode_floor_setup(vi,hi->long_setting,1,
  154154. setup->floor_books,
  154155. setup->floor_params,
  154156. setup->floor_long_mapping);
  154157. /* setup of [mostly] short block detection and stereo*/
  154158. vorbis_encode_global_psych_setup(vi,hi->trigger_setting,
  154159. setup->global_params,
  154160. setup->global_mapping);
  154161. vorbis_encode_global_stereo(vi,hi,setup->stereo_modes);
  154162. /* basic psych setup and noise normalization */
  154163. vorbis_encode_psyset_setup(vi,hi->short_setting,
  154164. setup->psy_noise_normal_start[0],
  154165. setup->psy_noise_normal_partition[0],
  154166. setup->psy_noise_normal_thresh,
  154167. 0);
  154168. vorbis_encode_psyset_setup(vi,hi->short_setting,
  154169. setup->psy_noise_normal_start[0],
  154170. setup->psy_noise_normal_partition[0],
  154171. setup->psy_noise_normal_thresh,
  154172. 1);
  154173. if(!singleblock){
  154174. vorbis_encode_psyset_setup(vi,hi->long_setting,
  154175. setup->psy_noise_normal_start[1],
  154176. setup->psy_noise_normal_partition[1],
  154177. setup->psy_noise_normal_thresh,
  154178. 2);
  154179. vorbis_encode_psyset_setup(vi,hi->long_setting,
  154180. setup->psy_noise_normal_start[1],
  154181. setup->psy_noise_normal_partition[1],
  154182. setup->psy_noise_normal_thresh,
  154183. 3);
  154184. }
  154185. /* tone masking setup */
  154186. vorbis_encode_tonemask_setup(vi,hi->block[i0].tone_mask_setting,0,
  154187. setup->psy_tone_masteratt,
  154188. setup->psy_tone_0dB,
  154189. setup->psy_tone_adj_impulse);
  154190. vorbis_encode_tonemask_setup(vi,hi->block[1].tone_mask_setting,1,
  154191. setup->psy_tone_masteratt,
  154192. setup->psy_tone_0dB,
  154193. setup->psy_tone_adj_other);
  154194. if(!singleblock){
  154195. vorbis_encode_tonemask_setup(vi,hi->block[2].tone_mask_setting,2,
  154196. setup->psy_tone_masteratt,
  154197. setup->psy_tone_0dB,
  154198. setup->psy_tone_adj_other);
  154199. vorbis_encode_tonemask_setup(vi,hi->block[3].tone_mask_setting,3,
  154200. setup->psy_tone_masteratt,
  154201. setup->psy_tone_0dB,
  154202. setup->psy_tone_adj_long);
  154203. }
  154204. /* noise companding setup */
  154205. vorbis_encode_compand_setup(vi,hi->block[i0].noise_compand_setting,0,
  154206. setup->psy_noise_compand,
  154207. setup->psy_noise_compand_short_mapping);
  154208. vorbis_encode_compand_setup(vi,hi->block[1].noise_compand_setting,1,
  154209. setup->psy_noise_compand,
  154210. setup->psy_noise_compand_short_mapping);
  154211. if(!singleblock){
  154212. vorbis_encode_compand_setup(vi,hi->block[2].noise_compand_setting,2,
  154213. setup->psy_noise_compand,
  154214. setup->psy_noise_compand_long_mapping);
  154215. vorbis_encode_compand_setup(vi,hi->block[3].noise_compand_setting,3,
  154216. setup->psy_noise_compand,
  154217. setup->psy_noise_compand_long_mapping);
  154218. }
  154219. /* peak guarding setup */
  154220. vorbis_encode_peak_setup(vi,hi->block[i0].tone_peaklimit_setting,0,
  154221. setup->psy_tone_dBsuppress);
  154222. vorbis_encode_peak_setup(vi,hi->block[1].tone_peaklimit_setting,1,
  154223. setup->psy_tone_dBsuppress);
  154224. if(!singleblock){
  154225. vorbis_encode_peak_setup(vi,hi->block[2].tone_peaklimit_setting,2,
  154226. setup->psy_tone_dBsuppress);
  154227. vorbis_encode_peak_setup(vi,hi->block[3].tone_peaklimit_setting,3,
  154228. setup->psy_tone_dBsuppress);
  154229. }
  154230. /* noise bias setup */
  154231. vorbis_encode_noisebias_setup(vi,hi->block[i0].noise_bias_setting,0,
  154232. setup->psy_noise_dBsuppress,
  154233. setup->psy_noise_bias_impulse,
  154234. setup->psy_noiseguards,
  154235. (i0==0?hi->impulse_noisetune:0.));
  154236. vorbis_encode_noisebias_setup(vi,hi->block[1].noise_bias_setting,1,
  154237. setup->psy_noise_dBsuppress,
  154238. setup->psy_noise_bias_padding,
  154239. setup->psy_noiseguards,0.);
  154240. if(!singleblock){
  154241. vorbis_encode_noisebias_setup(vi,hi->block[2].noise_bias_setting,2,
  154242. setup->psy_noise_dBsuppress,
  154243. setup->psy_noise_bias_trans,
  154244. setup->psy_noiseguards,0.);
  154245. vorbis_encode_noisebias_setup(vi,hi->block[3].noise_bias_setting,3,
  154246. setup->psy_noise_dBsuppress,
  154247. setup->psy_noise_bias_long,
  154248. setup->psy_noiseguards,0.);
  154249. }
  154250. vorbis_encode_ath_setup(vi,0);
  154251. vorbis_encode_ath_setup(vi,1);
  154252. if(!singleblock){
  154253. vorbis_encode_ath_setup(vi,2);
  154254. vorbis_encode_ath_setup(vi,3);
  154255. }
  154256. vorbis_encode_map_n_res_setup(vi,hi->base_setting,setup->maps);
  154257. /* set bitrate readonlies and management */
  154258. if(hi->bitrate_av>0)
  154259. vi->bitrate_nominal=hi->bitrate_av;
  154260. else{
  154261. vi->bitrate_nominal=setting_to_approx_bitrate(vi);
  154262. }
  154263. vi->bitrate_lower=hi->bitrate_min;
  154264. vi->bitrate_upper=hi->bitrate_max;
  154265. if(hi->bitrate_av)
  154266. vi->bitrate_window=(double)hi->bitrate_reservoir/hi->bitrate_av;
  154267. else
  154268. vi->bitrate_window=0.;
  154269. if(hi->managed){
  154270. ci->bi.avg_rate=hi->bitrate_av;
  154271. ci->bi.min_rate=hi->bitrate_min;
  154272. ci->bi.max_rate=hi->bitrate_max;
  154273. ci->bi.reservoir_bits=hi->bitrate_reservoir;
  154274. ci->bi.reservoir_bias=
  154275. hi->bitrate_reservoir_bias;
  154276. ci->bi.slew_damp=hi->bitrate_av_damp;
  154277. }
  154278. return(0);
  154279. }
  154280. static int vorbis_encode_setup_setting(vorbis_info *vi,
  154281. long channels,
  154282. long rate){
  154283. int ret=0,i,is;
  154284. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154285. highlevel_encode_setup *hi=&ci->hi;
  154286. ve_setup_data_template *setup=(ve_setup_data_template*) hi->setup;
  154287. double ds;
  154288. ret=vorbis_encode_toplevel_setup(vi,channels,rate);
  154289. if(ret)return(ret);
  154290. is=hi->base_setting;
  154291. ds=hi->base_setting-is;
  154292. hi->short_setting=hi->base_setting;
  154293. hi->long_setting=hi->base_setting;
  154294. hi->managed=0;
  154295. hi->impulse_block_p=1;
  154296. hi->noise_normalize_p=1;
  154297. hi->stereo_point_setting=hi->base_setting;
  154298. hi->lowpass_kHz=
  154299. setup->psy_lowpass[is]*(1.-ds)+setup->psy_lowpass[is+1]*ds;
  154300. hi->ath_floating_dB=setup->psy_ath_float[is]*(1.-ds)+
  154301. setup->psy_ath_float[is+1]*ds;
  154302. hi->ath_absolute_dB=setup->psy_ath_abs[is]*(1.-ds)+
  154303. setup->psy_ath_abs[is+1]*ds;
  154304. hi->amplitude_track_dBpersec=-6.;
  154305. hi->trigger_setting=hi->base_setting;
  154306. for(i=0;i<4;i++){
  154307. hi->block[i].tone_mask_setting=hi->base_setting;
  154308. hi->block[i].tone_peaklimit_setting=hi->base_setting;
  154309. hi->block[i].noise_bias_setting=hi->base_setting;
  154310. hi->block[i].noise_compand_setting=hi->base_setting;
  154311. }
  154312. return(ret);
  154313. }
  154314. int vorbis_encode_setup_vbr(vorbis_info *vi,
  154315. long channels,
  154316. long rate,
  154317. float quality){
  154318. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154319. highlevel_encode_setup *hi=&ci->hi;
  154320. quality+=.0000001;
  154321. if(quality>=1.)quality=.9999;
  154322. get_setup_template(vi,channels,rate,quality,0);
  154323. if(!hi->setup)return OV_EIMPL;
  154324. return vorbis_encode_setup_setting(vi,channels,rate);
  154325. }
  154326. int vorbis_encode_init_vbr(vorbis_info *vi,
  154327. long channels,
  154328. long rate,
  154329. float base_quality /* 0. to 1. */
  154330. ){
  154331. int ret=0;
  154332. ret=vorbis_encode_setup_vbr(vi,channels,rate,base_quality);
  154333. if(ret){
  154334. vorbis_info_clear(vi);
  154335. return ret;
  154336. }
  154337. ret=vorbis_encode_setup_init(vi);
  154338. if(ret)
  154339. vorbis_info_clear(vi);
  154340. return(ret);
  154341. }
  154342. int vorbis_encode_setup_managed(vorbis_info *vi,
  154343. long channels,
  154344. long rate,
  154345. long max_bitrate,
  154346. long nominal_bitrate,
  154347. long min_bitrate){
  154348. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154349. highlevel_encode_setup *hi=&ci->hi;
  154350. double tnominal=nominal_bitrate;
  154351. int ret=0;
  154352. if(nominal_bitrate<=0.){
  154353. if(max_bitrate>0.){
  154354. if(min_bitrate>0.)
  154355. nominal_bitrate=(max_bitrate+min_bitrate)*.5;
  154356. else
  154357. nominal_bitrate=max_bitrate*.875;
  154358. }else{
  154359. if(min_bitrate>0.){
  154360. nominal_bitrate=min_bitrate;
  154361. }else{
  154362. return(OV_EINVAL);
  154363. }
  154364. }
  154365. }
  154366. get_setup_template(vi,channels,rate,nominal_bitrate,1);
  154367. if(!hi->setup)return OV_EIMPL;
  154368. ret=vorbis_encode_setup_setting(vi,channels,rate);
  154369. if(ret){
  154370. vorbis_info_clear(vi);
  154371. return ret;
  154372. }
  154373. /* initialize management with sane defaults */
  154374. hi->managed=1;
  154375. hi->bitrate_min=min_bitrate;
  154376. hi->bitrate_max=max_bitrate;
  154377. hi->bitrate_av=tnominal;
  154378. hi->bitrate_av_damp=1.5f; /* full range in no less than 1.5 second */
  154379. hi->bitrate_reservoir=nominal_bitrate*2;
  154380. hi->bitrate_reservoir_bias=.1; /* bias toward hoarding bits */
  154381. return(ret);
  154382. }
  154383. int vorbis_encode_init(vorbis_info *vi,
  154384. long channels,
  154385. long rate,
  154386. long max_bitrate,
  154387. long nominal_bitrate,
  154388. long min_bitrate){
  154389. int ret=vorbis_encode_setup_managed(vi,channels,rate,
  154390. max_bitrate,
  154391. nominal_bitrate,
  154392. min_bitrate);
  154393. if(ret){
  154394. vorbis_info_clear(vi);
  154395. return(ret);
  154396. }
  154397. ret=vorbis_encode_setup_init(vi);
  154398. if(ret)
  154399. vorbis_info_clear(vi);
  154400. return(ret);
  154401. }
  154402. int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg){
  154403. if(vi){
  154404. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154405. highlevel_encode_setup *hi=&ci->hi;
  154406. int setp=(number&0xf); /* a read request has a low nibble of 0 */
  154407. if(setp && hi->set_in_stone)return(OV_EINVAL);
  154408. switch(number){
  154409. /* now deprecated *****************/
  154410. case OV_ECTL_RATEMANAGE_GET:
  154411. {
  154412. struct ovectl_ratemanage_arg *ai=
  154413. (struct ovectl_ratemanage_arg *)arg;
  154414. ai->management_active=hi->managed;
  154415. ai->bitrate_hard_window=ai->bitrate_av_window=
  154416. (double)hi->bitrate_reservoir/vi->rate;
  154417. ai->bitrate_av_window_center=1.;
  154418. ai->bitrate_hard_min=hi->bitrate_min;
  154419. ai->bitrate_hard_max=hi->bitrate_max;
  154420. ai->bitrate_av_lo=hi->bitrate_av;
  154421. ai->bitrate_av_hi=hi->bitrate_av;
  154422. }
  154423. return(0);
  154424. /* now deprecated *****************/
  154425. case OV_ECTL_RATEMANAGE_SET:
  154426. {
  154427. struct ovectl_ratemanage_arg *ai=
  154428. (struct ovectl_ratemanage_arg *)arg;
  154429. if(ai==NULL){
  154430. hi->managed=0;
  154431. }else{
  154432. hi->managed=ai->management_active;
  154433. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_AVG,arg);
  154434. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_HARD,arg);
  154435. }
  154436. }
  154437. return 0;
  154438. /* now deprecated *****************/
  154439. case OV_ECTL_RATEMANAGE_AVG:
  154440. {
  154441. struct ovectl_ratemanage_arg *ai=
  154442. (struct ovectl_ratemanage_arg *)arg;
  154443. if(ai==NULL){
  154444. hi->bitrate_av=0;
  154445. }else{
  154446. hi->bitrate_av=(ai->bitrate_av_lo+ai->bitrate_av_hi)*.5;
  154447. }
  154448. }
  154449. return(0);
  154450. /* now deprecated *****************/
  154451. case OV_ECTL_RATEMANAGE_HARD:
  154452. {
  154453. struct ovectl_ratemanage_arg *ai=
  154454. (struct ovectl_ratemanage_arg *)arg;
  154455. if(ai==NULL){
  154456. hi->bitrate_min=0;
  154457. hi->bitrate_max=0;
  154458. }else{
  154459. hi->bitrate_min=ai->bitrate_hard_min;
  154460. hi->bitrate_max=ai->bitrate_hard_max;
  154461. hi->bitrate_reservoir=ai->bitrate_hard_window*
  154462. (hi->bitrate_max+hi->bitrate_min)*.5;
  154463. }
  154464. if(hi->bitrate_reservoir<128.)
  154465. hi->bitrate_reservoir=128.;
  154466. }
  154467. return(0);
  154468. /* replacement ratemanage interface */
  154469. case OV_ECTL_RATEMANAGE2_GET:
  154470. {
  154471. struct ovectl_ratemanage2_arg *ai=
  154472. (struct ovectl_ratemanage2_arg *)arg;
  154473. if(ai==NULL)return OV_EINVAL;
  154474. ai->management_active=hi->managed;
  154475. ai->bitrate_limit_min_kbps=hi->bitrate_min/1000;
  154476. ai->bitrate_limit_max_kbps=hi->bitrate_max/1000;
  154477. ai->bitrate_average_kbps=hi->bitrate_av/1000;
  154478. ai->bitrate_average_damping=hi->bitrate_av_damp;
  154479. ai->bitrate_limit_reservoir_bits=hi->bitrate_reservoir;
  154480. ai->bitrate_limit_reservoir_bias=hi->bitrate_reservoir_bias;
  154481. }
  154482. return (0);
  154483. case OV_ECTL_RATEMANAGE2_SET:
  154484. {
  154485. struct ovectl_ratemanage2_arg *ai=
  154486. (struct ovectl_ratemanage2_arg *)arg;
  154487. if(ai==NULL){
  154488. hi->managed=0;
  154489. }else{
  154490. /* sanity check; only catch invariant violations */
  154491. if(ai->bitrate_limit_min_kbps>0 &&
  154492. ai->bitrate_average_kbps>0 &&
  154493. ai->bitrate_limit_min_kbps>ai->bitrate_average_kbps)
  154494. return OV_EINVAL;
  154495. if(ai->bitrate_limit_max_kbps>0 &&
  154496. ai->bitrate_average_kbps>0 &&
  154497. ai->bitrate_limit_max_kbps<ai->bitrate_average_kbps)
  154498. return OV_EINVAL;
  154499. if(ai->bitrate_limit_min_kbps>0 &&
  154500. ai->bitrate_limit_max_kbps>0 &&
  154501. ai->bitrate_limit_min_kbps>ai->bitrate_limit_max_kbps)
  154502. return OV_EINVAL;
  154503. if(ai->bitrate_average_damping <= 0.)
  154504. return OV_EINVAL;
  154505. if(ai->bitrate_limit_reservoir_bits < 0)
  154506. return OV_EINVAL;
  154507. if(ai->bitrate_limit_reservoir_bias < 0.)
  154508. return OV_EINVAL;
  154509. if(ai->bitrate_limit_reservoir_bias > 1.)
  154510. return OV_EINVAL;
  154511. hi->managed=ai->management_active;
  154512. hi->bitrate_min=ai->bitrate_limit_min_kbps * 1000;
  154513. hi->bitrate_max=ai->bitrate_limit_max_kbps * 1000;
  154514. hi->bitrate_av=ai->bitrate_average_kbps * 1000;
  154515. hi->bitrate_av_damp=ai->bitrate_average_damping;
  154516. hi->bitrate_reservoir=ai->bitrate_limit_reservoir_bits;
  154517. hi->bitrate_reservoir_bias=ai->bitrate_limit_reservoir_bias;
  154518. }
  154519. }
  154520. return 0;
  154521. case OV_ECTL_LOWPASS_GET:
  154522. {
  154523. double *farg=(double *)arg;
  154524. *farg=hi->lowpass_kHz;
  154525. }
  154526. return(0);
  154527. case OV_ECTL_LOWPASS_SET:
  154528. {
  154529. double *farg=(double *)arg;
  154530. hi->lowpass_kHz=*farg;
  154531. if(hi->lowpass_kHz<2.)hi->lowpass_kHz=2.;
  154532. if(hi->lowpass_kHz>99.)hi->lowpass_kHz=99.;
  154533. }
  154534. return(0);
  154535. case OV_ECTL_IBLOCK_GET:
  154536. {
  154537. double *farg=(double *)arg;
  154538. *farg=hi->impulse_noisetune;
  154539. }
  154540. return(0);
  154541. case OV_ECTL_IBLOCK_SET:
  154542. {
  154543. double *farg=(double *)arg;
  154544. hi->impulse_noisetune=*farg;
  154545. if(hi->impulse_noisetune>0.)hi->impulse_noisetune=0.;
  154546. if(hi->impulse_noisetune<-15.)hi->impulse_noisetune=-15.;
  154547. }
  154548. return(0);
  154549. }
  154550. return(OV_EIMPL);
  154551. }
  154552. return(OV_EINVAL);
  154553. }
  154554. #endif
  154555. /*** End of inlined file: vorbisenc.c ***/
  154556. /*** Start of inlined file: vorbisfile.c ***/
  154557. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  154558. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  154559. // tasks..
  154560. #if JUCE_MSVC
  154561. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  154562. #endif
  154563. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  154564. #if JUCE_USE_OGGVORBIS
  154565. #include <stdlib.h>
  154566. #include <stdio.h>
  154567. #include <errno.h>
  154568. #include <string.h>
  154569. #include <math.h>
  154570. /* A 'chained bitstream' is a Vorbis bitstream that contains more than
  154571. one logical bitstream arranged end to end (the only form of Ogg
  154572. multiplexing allowed in a Vorbis bitstream; grouping [parallel
  154573. multiplexing] is not allowed in Vorbis) */
  154574. /* A Vorbis file can be played beginning to end (streamed) without
  154575. worrying ahead of time about chaining (see decoder_example.c). If
  154576. we have the whole file, however, and want random access
  154577. (seeking/scrubbing) or desire to know the total length/time of a
  154578. file, we need to account for the possibility of chaining. */
  154579. /* We can handle things a number of ways; we can determine the entire
  154580. bitstream structure right off the bat, or find pieces on demand.
  154581. This example determines and caches structure for the entire
  154582. bitstream, but builds a virtual decoder on the fly when moving
  154583. between links in the chain. */
  154584. /* There are also different ways to implement seeking. Enough
  154585. information exists in an Ogg bitstream to seek to
  154586. sample-granularity positions in the output. Or, one can seek by
  154587. picking some portion of the stream roughly in the desired area if
  154588. we only want coarse navigation through the stream. */
  154589. /*************************************************************************
  154590. * Many, many internal helpers. The intention is not to be confusing;
  154591. * rampant duplication and monolithic function implementation would be
  154592. * harder to understand anyway. The high level functions are last. Begin
  154593. * grokking near the end of the file */
  154594. /* read a little more data from the file/pipe into the ogg_sync framer
  154595. */
  154596. #define CHUNKSIZE 8500 /* a shade over 8k; anyone using pages well
  154597. over 8k gets what they deserve */
  154598. static long _get_data(OggVorbis_File *vf){
  154599. errno=0;
  154600. if(vf->datasource){
  154601. char *buffer=ogg_sync_buffer(&vf->oy,CHUNKSIZE);
  154602. long bytes=(vf->callbacks.read_func)(buffer,1,CHUNKSIZE,vf->datasource);
  154603. if(bytes>0)ogg_sync_wrote(&vf->oy,bytes);
  154604. if(bytes==0 && errno)return(-1);
  154605. return(bytes);
  154606. }else
  154607. return(0);
  154608. }
  154609. /* save a tiny smidge of verbosity to make the code more readable */
  154610. static void _seek_helper(OggVorbis_File *vf,ogg_int64_t offset){
  154611. if(vf->datasource){
  154612. (vf->callbacks.seek_func)(vf->datasource, offset, SEEK_SET);
  154613. vf->offset=offset;
  154614. ogg_sync_reset(&vf->oy);
  154615. }else{
  154616. /* shouldn't happen unless someone writes a broken callback */
  154617. return;
  154618. }
  154619. }
  154620. /* The read/seek functions track absolute position within the stream */
  154621. /* from the head of the stream, get the next page. boundary specifies
  154622. if the function is allowed to fetch more data from the stream (and
  154623. how much) or only use internally buffered data.
  154624. boundary: -1) unbounded search
  154625. 0) read no additional data; use cached only
  154626. n) search for a new page beginning for n bytes
  154627. return: <0) did not find a page (OV_FALSE, OV_EOF, OV_EREAD)
  154628. n) found a page at absolute offset n */
  154629. static ogg_int64_t _get_next_page(OggVorbis_File *vf,ogg_page *og,
  154630. ogg_int64_t boundary){
  154631. if(boundary>0)boundary+=vf->offset;
  154632. while(1){
  154633. long more;
  154634. if(boundary>0 && vf->offset>=boundary)return(OV_FALSE);
  154635. more=ogg_sync_pageseek(&vf->oy,og);
  154636. if(more<0){
  154637. /* skipped n bytes */
  154638. vf->offset-=more;
  154639. }else{
  154640. if(more==0){
  154641. /* send more paramedics */
  154642. if(!boundary)return(OV_FALSE);
  154643. {
  154644. long ret=_get_data(vf);
  154645. if(ret==0)return(OV_EOF);
  154646. if(ret<0)return(OV_EREAD);
  154647. }
  154648. }else{
  154649. /* got a page. Return the offset at the page beginning,
  154650. advance the internal offset past the page end */
  154651. ogg_int64_t ret=vf->offset;
  154652. vf->offset+=more;
  154653. return(ret);
  154654. }
  154655. }
  154656. }
  154657. }
  154658. /* find the latest page beginning before the current stream cursor
  154659. position. Much dirtier than the above as Ogg doesn't have any
  154660. backward search linkage. no 'readp' as it will certainly have to
  154661. read. */
  154662. /* returns offset or OV_EREAD, OV_FAULT */
  154663. static ogg_int64_t _get_prev_page(OggVorbis_File *vf,ogg_page *og){
  154664. ogg_int64_t begin=vf->offset;
  154665. ogg_int64_t end=begin;
  154666. ogg_int64_t ret;
  154667. ogg_int64_t offset=-1;
  154668. while(offset==-1){
  154669. begin-=CHUNKSIZE;
  154670. if(begin<0)
  154671. begin=0;
  154672. _seek_helper(vf,begin);
  154673. while(vf->offset<end){
  154674. ret=_get_next_page(vf,og,end-vf->offset);
  154675. if(ret==OV_EREAD)return(OV_EREAD);
  154676. if(ret<0){
  154677. break;
  154678. }else{
  154679. offset=ret;
  154680. }
  154681. }
  154682. }
  154683. /* we have the offset. Actually snork and hold the page now */
  154684. _seek_helper(vf,offset);
  154685. ret=_get_next_page(vf,og,CHUNKSIZE);
  154686. if(ret<0)
  154687. /* this shouldn't be possible */
  154688. return(OV_EFAULT);
  154689. return(offset);
  154690. }
  154691. /* finds each bitstream link one at a time using a bisection search
  154692. (has to begin by knowing the offset of the lb's initial page).
  154693. Recurses for each link so it can alloc the link storage after
  154694. finding them all, then unroll and fill the cache at the same time */
  154695. static int _bisect_forward_serialno(OggVorbis_File *vf,
  154696. ogg_int64_t begin,
  154697. ogg_int64_t searched,
  154698. ogg_int64_t end,
  154699. long currentno,
  154700. long m){
  154701. ogg_int64_t endsearched=end;
  154702. ogg_int64_t next=end;
  154703. ogg_page og;
  154704. ogg_int64_t ret;
  154705. /* the below guards against garbage seperating the last and
  154706. first pages of two links. */
  154707. while(searched<endsearched){
  154708. ogg_int64_t bisect;
  154709. if(endsearched-searched<CHUNKSIZE){
  154710. bisect=searched;
  154711. }else{
  154712. bisect=(searched+endsearched)/2;
  154713. }
  154714. _seek_helper(vf,bisect);
  154715. ret=_get_next_page(vf,&og,-1);
  154716. if(ret==OV_EREAD)return(OV_EREAD);
  154717. if(ret<0 || ogg_page_serialno(&og)!=currentno){
  154718. endsearched=bisect;
  154719. if(ret>=0)next=ret;
  154720. }else{
  154721. searched=ret+og.header_len+og.body_len;
  154722. }
  154723. }
  154724. _seek_helper(vf,next);
  154725. ret=_get_next_page(vf,&og,-1);
  154726. if(ret==OV_EREAD)return(OV_EREAD);
  154727. if(searched>=end || ret<0){
  154728. vf->links=m+1;
  154729. vf->offsets=(ogg_int64_t*)_ogg_malloc((vf->links+1)*sizeof(*vf->offsets));
  154730. vf->serialnos=(long*)_ogg_malloc(vf->links*sizeof(*vf->serialnos));
  154731. vf->offsets[m+1]=searched;
  154732. }else{
  154733. ret=_bisect_forward_serialno(vf,next,vf->offset,
  154734. end,ogg_page_serialno(&og),m+1);
  154735. if(ret==OV_EREAD)return(OV_EREAD);
  154736. }
  154737. vf->offsets[m]=begin;
  154738. vf->serialnos[m]=currentno;
  154739. return(0);
  154740. }
  154741. /* uses the local ogg_stream storage in vf; this is important for
  154742. non-streaming input sources */
  154743. static int _fetch_headers(OggVorbis_File *vf,vorbis_info *vi,vorbis_comment *vc,
  154744. long *serialno,ogg_page *og_ptr){
  154745. ogg_page og;
  154746. ogg_packet op;
  154747. int i,ret;
  154748. if(!og_ptr){
  154749. ogg_int64_t llret=_get_next_page(vf,&og,CHUNKSIZE);
  154750. if(llret==OV_EREAD)return(OV_EREAD);
  154751. if(llret<0)return OV_ENOTVORBIS;
  154752. og_ptr=&og;
  154753. }
  154754. ogg_stream_reset_serialno(&vf->os,ogg_page_serialno(og_ptr));
  154755. if(serialno)*serialno=vf->os.serialno;
  154756. vf->ready_state=STREAMSET;
  154757. /* extract the initial header from the first page and verify that the
  154758. Ogg bitstream is in fact Vorbis data */
  154759. vorbis_info_init(vi);
  154760. vorbis_comment_init(vc);
  154761. i=0;
  154762. while(i<3){
  154763. ogg_stream_pagein(&vf->os,og_ptr);
  154764. while(i<3){
  154765. int result=ogg_stream_packetout(&vf->os,&op);
  154766. if(result==0)break;
  154767. if(result==-1){
  154768. ret=OV_EBADHEADER;
  154769. goto bail_header;
  154770. }
  154771. if((ret=vorbis_synthesis_headerin(vi,vc,&op))){
  154772. goto bail_header;
  154773. }
  154774. i++;
  154775. }
  154776. if(i<3)
  154777. if(_get_next_page(vf,og_ptr,CHUNKSIZE)<0){
  154778. ret=OV_EBADHEADER;
  154779. goto bail_header;
  154780. }
  154781. }
  154782. return 0;
  154783. bail_header:
  154784. vorbis_info_clear(vi);
  154785. vorbis_comment_clear(vc);
  154786. vf->ready_state=OPENED;
  154787. return ret;
  154788. }
  154789. /* last step of the OggVorbis_File initialization; get all the
  154790. vorbis_info structs and PCM positions. Only called by the seekable
  154791. initialization (local stream storage is hacked slightly; pay
  154792. attention to how that's done) */
  154793. /* this is void and does not propogate errors up because we want to be
  154794. able to open and use damaged bitstreams as well as we can. Just
  154795. watch out for missing information for links in the OggVorbis_File
  154796. struct */
  154797. static void _prefetch_all_headers(OggVorbis_File *vf, ogg_int64_t dataoffset){
  154798. ogg_page og;
  154799. int i;
  154800. ogg_int64_t ret;
  154801. vf->vi=(vorbis_info*) _ogg_realloc(vf->vi,vf->links*sizeof(*vf->vi));
  154802. vf->vc=(vorbis_comment*) _ogg_realloc(vf->vc,vf->links*sizeof(*vf->vc));
  154803. vf->dataoffsets=(ogg_int64_t*) _ogg_malloc(vf->links*sizeof(*vf->dataoffsets));
  154804. vf->pcmlengths=(ogg_int64_t*) _ogg_malloc(vf->links*2*sizeof(*vf->pcmlengths));
  154805. for(i=0;i<vf->links;i++){
  154806. if(i==0){
  154807. /* we already grabbed the initial header earlier. Just set the offset */
  154808. vf->dataoffsets[i]=dataoffset;
  154809. _seek_helper(vf,dataoffset);
  154810. }else{
  154811. /* seek to the location of the initial header */
  154812. _seek_helper(vf,vf->offsets[i]);
  154813. if(_fetch_headers(vf,vf->vi+i,vf->vc+i,NULL,NULL)<0){
  154814. vf->dataoffsets[i]=-1;
  154815. }else{
  154816. vf->dataoffsets[i]=vf->offset;
  154817. }
  154818. }
  154819. /* fetch beginning PCM offset */
  154820. if(vf->dataoffsets[i]!=-1){
  154821. ogg_int64_t accumulated=0;
  154822. long lastblock=-1;
  154823. int result;
  154824. ogg_stream_reset_serialno(&vf->os,vf->serialnos[i]);
  154825. while(1){
  154826. ogg_packet op;
  154827. ret=_get_next_page(vf,&og,-1);
  154828. if(ret<0)
  154829. /* this should not be possible unless the file is
  154830. truncated/mangled */
  154831. break;
  154832. if(ogg_page_serialno(&og)!=vf->serialnos[i])
  154833. break;
  154834. /* count blocksizes of all frames in the page */
  154835. ogg_stream_pagein(&vf->os,&og);
  154836. while((result=ogg_stream_packetout(&vf->os,&op))){
  154837. if(result>0){ /* ignore holes */
  154838. long thisblock=vorbis_packet_blocksize(vf->vi+i,&op);
  154839. if(lastblock!=-1)
  154840. accumulated+=(lastblock+thisblock)>>2;
  154841. lastblock=thisblock;
  154842. }
  154843. }
  154844. if(ogg_page_granulepos(&og)!=-1){
  154845. /* pcm offset of last packet on the first audio page */
  154846. accumulated= ogg_page_granulepos(&og)-accumulated;
  154847. break;
  154848. }
  154849. }
  154850. /* less than zero? This is a stream with samples trimmed off
  154851. the beginning, a normal occurrence; set the offset to zero */
  154852. if(accumulated<0)accumulated=0;
  154853. vf->pcmlengths[i*2]=accumulated;
  154854. }
  154855. /* get the PCM length of this link. To do this,
  154856. get the last page of the stream */
  154857. {
  154858. ogg_int64_t end=vf->offsets[i+1];
  154859. _seek_helper(vf,end);
  154860. while(1){
  154861. ret=_get_prev_page(vf,&og);
  154862. if(ret<0){
  154863. /* this should not be possible */
  154864. vorbis_info_clear(vf->vi+i);
  154865. vorbis_comment_clear(vf->vc+i);
  154866. break;
  154867. }
  154868. if(ogg_page_granulepos(&og)!=-1){
  154869. vf->pcmlengths[i*2+1]=ogg_page_granulepos(&og)-vf->pcmlengths[i*2];
  154870. break;
  154871. }
  154872. vf->offset=ret;
  154873. }
  154874. }
  154875. }
  154876. }
  154877. static int _make_decode_ready(OggVorbis_File *vf){
  154878. if(vf->ready_state>STREAMSET)return 0;
  154879. if(vf->ready_state<STREAMSET)return OV_EFAULT;
  154880. if(vf->seekable){
  154881. if(vorbis_synthesis_init(&vf->vd,vf->vi+vf->current_link))
  154882. return OV_EBADLINK;
  154883. }else{
  154884. if(vorbis_synthesis_init(&vf->vd,vf->vi))
  154885. return OV_EBADLINK;
  154886. }
  154887. vorbis_block_init(&vf->vd,&vf->vb);
  154888. vf->ready_state=INITSET;
  154889. vf->bittrack=0.f;
  154890. vf->samptrack=0.f;
  154891. return 0;
  154892. }
  154893. static int _open_seekable2(OggVorbis_File *vf){
  154894. long serialno=vf->current_serialno;
  154895. ogg_int64_t dataoffset=vf->offset, end;
  154896. ogg_page og;
  154897. /* we're partially open and have a first link header state in
  154898. storage in vf */
  154899. /* we can seek, so set out learning all about this file */
  154900. (vf->callbacks.seek_func)(vf->datasource,0,SEEK_END);
  154901. vf->offset=vf->end=(vf->callbacks.tell_func)(vf->datasource);
  154902. /* We get the offset for the last page of the physical bitstream.
  154903. Most OggVorbis files will contain a single logical bitstream */
  154904. end=_get_prev_page(vf,&og);
  154905. if(end<0)return(end);
  154906. /* more than one logical bitstream? */
  154907. if(ogg_page_serialno(&og)!=serialno){
  154908. /* Chained bitstream. Bisect-search each logical bitstream
  154909. section. Do so based on serial number only */
  154910. if(_bisect_forward_serialno(vf,0,0,end+1,serialno,0)<0)return(OV_EREAD);
  154911. }else{
  154912. /* Only one logical bitstream */
  154913. if(_bisect_forward_serialno(vf,0,end,end+1,serialno,0))return(OV_EREAD);
  154914. }
  154915. /* the initial header memory is referenced by vf after; don't free it */
  154916. _prefetch_all_headers(vf,dataoffset);
  154917. return(ov_raw_seek(vf,0));
  154918. }
  154919. /* clear out the current logical bitstream decoder */
  154920. static void _decode_clear(OggVorbis_File *vf){
  154921. vorbis_dsp_clear(&vf->vd);
  154922. vorbis_block_clear(&vf->vb);
  154923. vf->ready_state=OPENED;
  154924. }
  154925. /* fetch and process a packet. Handles the case where we're at a
  154926. bitstream boundary and dumps the decoding machine. If the decoding
  154927. machine is unloaded, it loads it. It also keeps pcm_offset up to
  154928. date (seek and read both use this. seek uses a special hack with
  154929. readp).
  154930. return: <0) error, OV_HOLE (lost packet) or OV_EOF
  154931. 0) need more data (only if readp==0)
  154932. 1) got a packet
  154933. */
  154934. static int _fetch_and_process_packet(OggVorbis_File *vf,
  154935. ogg_packet *op_in,
  154936. int readp,
  154937. int spanp){
  154938. ogg_page og;
  154939. /* handle one packet. Try to fetch it from current stream state */
  154940. /* extract packets from page */
  154941. while(1){
  154942. /* process a packet if we can. If the machine isn't loaded,
  154943. neither is a page */
  154944. if(vf->ready_state==INITSET){
  154945. while(1) {
  154946. ogg_packet op;
  154947. ogg_packet *op_ptr=(op_in?op_in:&op);
  154948. int result=ogg_stream_packetout(&vf->os,op_ptr);
  154949. ogg_int64_t granulepos;
  154950. op_in=NULL;
  154951. if(result==-1)return(OV_HOLE); /* hole in the data. */
  154952. if(result>0){
  154953. /* got a packet. process it */
  154954. granulepos=op_ptr->granulepos;
  154955. if(!vorbis_synthesis(&vf->vb,op_ptr)){ /* lazy check for lazy
  154956. header handling. The
  154957. header packets aren't
  154958. audio, so if/when we
  154959. submit them,
  154960. vorbis_synthesis will
  154961. reject them */
  154962. /* suck in the synthesis data and track bitrate */
  154963. {
  154964. int oldsamples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  154965. /* for proper use of libvorbis within libvorbisfile,
  154966. oldsamples will always be zero. */
  154967. if(oldsamples)return(OV_EFAULT);
  154968. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  154969. vf->samptrack+=vorbis_synthesis_pcmout(&vf->vd,NULL)-oldsamples;
  154970. vf->bittrack+=op_ptr->bytes*8;
  154971. }
  154972. /* update the pcm offset. */
  154973. if(granulepos!=-1 && !op_ptr->e_o_s){
  154974. int link=(vf->seekable?vf->current_link:0);
  154975. int i,samples;
  154976. /* this packet has a pcm_offset on it (the last packet
  154977. completed on a page carries the offset) After processing
  154978. (above), we know the pcm position of the *last* sample
  154979. ready to be returned. Find the offset of the *first*
  154980. As an aside, this trick is inaccurate if we begin
  154981. reading anew right at the last page; the end-of-stream
  154982. granulepos declares the last frame in the stream, and the
  154983. last packet of the last page may be a partial frame.
  154984. So, we need a previous granulepos from an in-sequence page
  154985. to have a reference point. Thus the !op_ptr->e_o_s clause
  154986. above */
  154987. if(vf->seekable && link>0)
  154988. granulepos-=vf->pcmlengths[link*2];
  154989. if(granulepos<0)granulepos=0; /* actually, this
  154990. shouldn't be possible
  154991. here unless the stream
  154992. is very broken */
  154993. samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  154994. granulepos-=samples;
  154995. for(i=0;i<link;i++)
  154996. granulepos+=vf->pcmlengths[i*2+1];
  154997. vf->pcm_offset=granulepos;
  154998. }
  154999. return(1);
  155000. }
  155001. }
  155002. else
  155003. break;
  155004. }
  155005. }
  155006. if(vf->ready_state>=OPENED){
  155007. ogg_int64_t ret;
  155008. if(!readp)return(0);
  155009. if((ret=_get_next_page(vf,&og,-1))<0){
  155010. return(OV_EOF); /* eof.
  155011. leave unitialized */
  155012. }
  155013. /* bitrate tracking; add the header's bytes here, the body bytes
  155014. are done by packet above */
  155015. vf->bittrack+=og.header_len*8;
  155016. /* has our decoding just traversed a bitstream boundary? */
  155017. if(vf->ready_state==INITSET){
  155018. if(vf->current_serialno!=ogg_page_serialno(&og)){
  155019. if(!spanp)
  155020. return(OV_EOF);
  155021. _decode_clear(vf);
  155022. if(!vf->seekable){
  155023. vorbis_info_clear(vf->vi);
  155024. vorbis_comment_clear(vf->vc);
  155025. }
  155026. }
  155027. }
  155028. }
  155029. /* Do we need to load a new machine before submitting the page? */
  155030. /* This is different in the seekable and non-seekable cases.
  155031. In the seekable case, we already have all the header
  155032. information loaded and cached; we just initialize the machine
  155033. with it and continue on our merry way.
  155034. In the non-seekable (streaming) case, we'll only be at a
  155035. boundary if we just left the previous logical bitstream and
  155036. we're now nominally at the header of the next bitstream
  155037. */
  155038. if(vf->ready_state!=INITSET){
  155039. int link;
  155040. if(vf->ready_state<STREAMSET){
  155041. if(vf->seekable){
  155042. vf->current_serialno=ogg_page_serialno(&og);
  155043. /* match the serialno to bitstream section. We use this rather than
  155044. offset positions to avoid problems near logical bitstream
  155045. boundaries */
  155046. for(link=0;link<vf->links;link++)
  155047. if(vf->serialnos[link]==vf->current_serialno)break;
  155048. if(link==vf->links)return(OV_EBADLINK); /* sign of a bogus
  155049. stream. error out,
  155050. leave machine
  155051. uninitialized */
  155052. vf->current_link=link;
  155053. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  155054. vf->ready_state=STREAMSET;
  155055. }else{
  155056. /* we're streaming */
  155057. /* fetch the three header packets, build the info struct */
  155058. int ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,&og);
  155059. if(ret)return(ret);
  155060. vf->current_link++;
  155061. link=0;
  155062. }
  155063. }
  155064. {
  155065. int ret=_make_decode_ready(vf);
  155066. if(ret<0)return ret;
  155067. }
  155068. }
  155069. ogg_stream_pagein(&vf->os,&og);
  155070. }
  155071. }
  155072. /* if, eg, 64 bit stdio is configured by default, this will build with
  155073. fseek64 */
  155074. static int _fseek64_wrap(FILE *f,ogg_int64_t off,int whence){
  155075. if(f==NULL)return(-1);
  155076. return fseek(f,off,whence);
  155077. }
  155078. static int _ov_open1(void *f,OggVorbis_File *vf,char *initial,
  155079. long ibytes, ov_callbacks callbacks){
  155080. int offsettest=(f?callbacks.seek_func(f,0,SEEK_CUR):-1);
  155081. int ret;
  155082. memset(vf,0,sizeof(*vf));
  155083. vf->datasource=f;
  155084. vf->callbacks = callbacks;
  155085. /* init the framing state */
  155086. ogg_sync_init(&vf->oy);
  155087. /* perhaps some data was previously read into a buffer for testing
  155088. against other stream types. Allow initialization from this
  155089. previously read data (as we may be reading from a non-seekable
  155090. stream) */
  155091. if(initial){
  155092. char *buffer=ogg_sync_buffer(&vf->oy,ibytes);
  155093. memcpy(buffer,initial,ibytes);
  155094. ogg_sync_wrote(&vf->oy,ibytes);
  155095. }
  155096. /* can we seek? Stevens suggests the seek test was portable */
  155097. if(offsettest!=-1)vf->seekable=1;
  155098. /* No seeking yet; Set up a 'single' (current) logical bitstream
  155099. entry for partial open */
  155100. vf->links=1;
  155101. vf->vi=(vorbis_info*) _ogg_calloc(vf->links,sizeof(*vf->vi));
  155102. vf->vc=(vorbis_comment*) _ogg_calloc(vf->links,sizeof(*vf->vc));
  155103. ogg_stream_init(&vf->os,-1); /* fill in the serialno later */
  155104. /* Try to fetch the headers, maintaining all the storage */
  155105. if((ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,NULL))<0){
  155106. vf->datasource=NULL;
  155107. ov_clear(vf);
  155108. }else
  155109. vf->ready_state=PARTOPEN;
  155110. return(ret);
  155111. }
  155112. static int _ov_open2(OggVorbis_File *vf){
  155113. if(vf->ready_state != PARTOPEN) return OV_EINVAL;
  155114. vf->ready_state=OPENED;
  155115. if(vf->seekable){
  155116. int ret=_open_seekable2(vf);
  155117. if(ret){
  155118. vf->datasource=NULL;
  155119. ov_clear(vf);
  155120. }
  155121. return(ret);
  155122. }else
  155123. vf->ready_state=STREAMSET;
  155124. return 0;
  155125. }
  155126. /* clear out the OggVorbis_File struct */
  155127. int ov_clear(OggVorbis_File *vf){
  155128. if(vf){
  155129. vorbis_block_clear(&vf->vb);
  155130. vorbis_dsp_clear(&vf->vd);
  155131. ogg_stream_clear(&vf->os);
  155132. if(vf->vi && vf->links){
  155133. int i;
  155134. for(i=0;i<vf->links;i++){
  155135. vorbis_info_clear(vf->vi+i);
  155136. vorbis_comment_clear(vf->vc+i);
  155137. }
  155138. _ogg_free(vf->vi);
  155139. _ogg_free(vf->vc);
  155140. }
  155141. if(vf->dataoffsets)_ogg_free(vf->dataoffsets);
  155142. if(vf->pcmlengths)_ogg_free(vf->pcmlengths);
  155143. if(vf->serialnos)_ogg_free(vf->serialnos);
  155144. if(vf->offsets)_ogg_free(vf->offsets);
  155145. ogg_sync_clear(&vf->oy);
  155146. if(vf->datasource)(vf->callbacks.close_func)(vf->datasource);
  155147. memset(vf,0,sizeof(*vf));
  155148. }
  155149. #ifdef DEBUG_LEAKS
  155150. _VDBG_dump();
  155151. #endif
  155152. return(0);
  155153. }
  155154. /* inspects the OggVorbis file and finds/documents all the logical
  155155. bitstreams contained in it. Tries to be tolerant of logical
  155156. bitstream sections that are truncated/woogie.
  155157. return: -1) error
  155158. 0) OK
  155159. */
  155160. int ov_open_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  155161. ov_callbacks callbacks){
  155162. int ret=_ov_open1(f,vf,initial,ibytes,callbacks);
  155163. if(ret)return ret;
  155164. return _ov_open2(vf);
  155165. }
  155166. int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  155167. ov_callbacks callbacks = {
  155168. (size_t (*)(void *, size_t, size_t, void *)) fread,
  155169. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  155170. (int (*)(void *)) fclose,
  155171. (long (*)(void *)) ftell
  155172. };
  155173. return ov_open_callbacks((void *)f, vf, initial, ibytes, callbacks);
  155174. }
  155175. /* cheap hack for game usage where downsampling is desirable; there's
  155176. no need for SRC as we can just do it cheaply in libvorbis. */
  155177. int ov_halfrate(OggVorbis_File *vf,int flag){
  155178. int i;
  155179. if(vf->vi==NULL)return OV_EINVAL;
  155180. if(!vf->seekable)return OV_EINVAL;
  155181. if(vf->ready_state>=STREAMSET)
  155182. _decode_clear(vf); /* clear out stream state; later on libvorbis
  155183. will be able to swap this on the fly, but
  155184. for now dumping the decode machine is needed
  155185. to reinit the MDCT lookups. 1.1 libvorbis
  155186. is planned to be able to switch on the fly */
  155187. for(i=0;i<vf->links;i++){
  155188. if(vorbis_synthesis_halfrate(vf->vi+i,flag)){
  155189. ov_halfrate(vf,0);
  155190. return OV_EINVAL;
  155191. }
  155192. }
  155193. return 0;
  155194. }
  155195. int ov_halfrate_p(OggVorbis_File *vf){
  155196. if(vf->vi==NULL)return OV_EINVAL;
  155197. return vorbis_synthesis_halfrate_p(vf->vi);
  155198. }
  155199. /* Only partially open the vorbis file; test for Vorbisness, and load
  155200. the headers for the first chain. Do not seek (although test for
  155201. seekability). Use ov_test_open to finish opening the file, else
  155202. ov_clear to close/free it. Same return codes as open. */
  155203. int ov_test_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  155204. ov_callbacks callbacks)
  155205. {
  155206. return _ov_open1(f,vf,initial,ibytes,callbacks);
  155207. }
  155208. int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  155209. ov_callbacks callbacks = {
  155210. (size_t (*)(void *, size_t, size_t, void *)) fread,
  155211. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  155212. (int (*)(void *)) fclose,
  155213. (long (*)(void *)) ftell
  155214. };
  155215. return ov_test_callbacks((void *)f, vf, initial, ibytes, callbacks);
  155216. }
  155217. int ov_test_open(OggVorbis_File *vf){
  155218. if(vf->ready_state!=PARTOPEN)return(OV_EINVAL);
  155219. return _ov_open2(vf);
  155220. }
  155221. /* How many logical bitstreams in this physical bitstream? */
  155222. long ov_streams(OggVorbis_File *vf){
  155223. return vf->links;
  155224. }
  155225. /* Is the FILE * associated with vf seekable? */
  155226. long ov_seekable(OggVorbis_File *vf){
  155227. return vf->seekable;
  155228. }
  155229. /* returns the bitrate for a given logical bitstream or the entire
  155230. physical bitstream. If the file is open for random access, it will
  155231. find the *actual* average bitrate. If the file is streaming, it
  155232. returns the nominal bitrate (if set) else the average of the
  155233. upper/lower bounds (if set) else -1 (unset).
  155234. If you want the actual bitrate field settings, get them from the
  155235. vorbis_info structs */
  155236. long ov_bitrate(OggVorbis_File *vf,int i){
  155237. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155238. if(i>=vf->links)return(OV_EINVAL);
  155239. if(!vf->seekable && i!=0)return(ov_bitrate(vf,0));
  155240. if(i<0){
  155241. ogg_int64_t bits=0;
  155242. int i;
  155243. float br;
  155244. for(i=0;i<vf->links;i++)
  155245. bits+=(vf->offsets[i+1]-vf->dataoffsets[i])*8;
  155246. /* This once read: return(rint(bits/ov_time_total(vf,-1)));
  155247. * gcc 3.x on x86 miscompiled this at optimisation level 2 and above,
  155248. * so this is slightly transformed to make it work.
  155249. */
  155250. br = bits/ov_time_total(vf,-1);
  155251. return(rint(br));
  155252. }else{
  155253. if(vf->seekable){
  155254. /* return the actual bitrate */
  155255. return(rint((vf->offsets[i+1]-vf->dataoffsets[i])*8/ov_time_total(vf,i)));
  155256. }else{
  155257. /* return nominal if set */
  155258. if(vf->vi[i].bitrate_nominal>0){
  155259. return vf->vi[i].bitrate_nominal;
  155260. }else{
  155261. if(vf->vi[i].bitrate_upper>0){
  155262. if(vf->vi[i].bitrate_lower>0){
  155263. return (vf->vi[i].bitrate_upper+vf->vi[i].bitrate_lower)/2;
  155264. }else{
  155265. return vf->vi[i].bitrate_upper;
  155266. }
  155267. }
  155268. return(OV_FALSE);
  155269. }
  155270. }
  155271. }
  155272. }
  155273. /* returns the actual bitrate since last call. returns -1 if no
  155274. additional data to offer since last call (or at beginning of stream),
  155275. EINVAL if stream is only partially open
  155276. */
  155277. long ov_bitrate_instant(OggVorbis_File *vf){
  155278. int link=(vf->seekable?vf->current_link:0);
  155279. long ret;
  155280. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155281. if(vf->samptrack==0)return(OV_FALSE);
  155282. ret=vf->bittrack/vf->samptrack*vf->vi[link].rate+.5;
  155283. vf->bittrack=0.f;
  155284. vf->samptrack=0.f;
  155285. return(ret);
  155286. }
  155287. /* Guess */
  155288. long ov_serialnumber(OggVorbis_File *vf,int i){
  155289. if(i>=vf->links)return(ov_serialnumber(vf,vf->links-1));
  155290. if(!vf->seekable && i>=0)return(ov_serialnumber(vf,-1));
  155291. if(i<0){
  155292. return(vf->current_serialno);
  155293. }else{
  155294. return(vf->serialnos[i]);
  155295. }
  155296. }
  155297. /* returns: total raw (compressed) length of content if i==-1
  155298. raw (compressed) length of that logical bitstream for i==0 to n
  155299. OV_EINVAL if the stream is not seekable (we can't know the length)
  155300. or if stream is only partially open
  155301. */
  155302. ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i){
  155303. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155304. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  155305. if(i<0){
  155306. ogg_int64_t acc=0;
  155307. int i;
  155308. for(i=0;i<vf->links;i++)
  155309. acc+=ov_raw_total(vf,i);
  155310. return(acc);
  155311. }else{
  155312. return(vf->offsets[i+1]-vf->offsets[i]);
  155313. }
  155314. }
  155315. /* returns: total PCM length (samples) of content if i==-1 PCM length
  155316. (samples) of that logical bitstream for i==0 to n
  155317. OV_EINVAL if the stream is not seekable (we can't know the
  155318. length) or only partially open
  155319. */
  155320. ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i){
  155321. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155322. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  155323. if(i<0){
  155324. ogg_int64_t acc=0;
  155325. int i;
  155326. for(i=0;i<vf->links;i++)
  155327. acc+=ov_pcm_total(vf,i);
  155328. return(acc);
  155329. }else{
  155330. return(vf->pcmlengths[i*2+1]);
  155331. }
  155332. }
  155333. /* returns: total seconds of content if i==-1
  155334. seconds in that logical bitstream for i==0 to n
  155335. OV_EINVAL if the stream is not seekable (we can't know the
  155336. length) or only partially open
  155337. */
  155338. double ov_time_total(OggVorbis_File *vf,int i){
  155339. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155340. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  155341. if(i<0){
  155342. double acc=0;
  155343. int i;
  155344. for(i=0;i<vf->links;i++)
  155345. acc+=ov_time_total(vf,i);
  155346. return(acc);
  155347. }else{
  155348. return((double)(vf->pcmlengths[i*2+1])/vf->vi[i].rate);
  155349. }
  155350. }
  155351. /* seek to an offset relative to the *compressed* data. This also
  155352. scans packets to update the PCM cursor. It will cross a logical
  155353. bitstream boundary, but only if it can't get any packets out of the
  155354. tail of the bitstream we seek to (so no surprises).
  155355. returns zero on success, nonzero on failure */
  155356. int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos){
  155357. ogg_stream_state work_os;
  155358. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155359. if(!vf->seekable)
  155360. return(OV_ENOSEEK); /* don't dump machine if we can't seek */
  155361. if(pos<0 || pos>vf->end)return(OV_EINVAL);
  155362. /* don't yet clear out decoding machine (if it's initialized), in
  155363. the case we're in the same link. Restart the decode lapping, and
  155364. let _fetch_and_process_packet deal with a potential bitstream
  155365. boundary */
  155366. vf->pcm_offset=-1;
  155367. ogg_stream_reset_serialno(&vf->os,
  155368. vf->current_serialno); /* must set serialno */
  155369. vorbis_synthesis_restart(&vf->vd);
  155370. _seek_helper(vf,pos);
  155371. /* we need to make sure the pcm_offset is set, but we don't want to
  155372. advance the raw cursor past good packets just to get to the first
  155373. with a granulepos. That's not equivalent behavior to beginning
  155374. decoding as immediately after the seek position as possible.
  155375. So, a hack. We use two stream states; a local scratch state and
  155376. the shared vf->os stream state. We use the local state to
  155377. scan, and the shared state as a buffer for later decode.
  155378. Unfortuantely, on the last page we still advance to last packet
  155379. because the granulepos on the last page is not necessarily on a
  155380. packet boundary, and we need to make sure the granpos is
  155381. correct.
  155382. */
  155383. {
  155384. ogg_page og;
  155385. ogg_packet op;
  155386. int lastblock=0;
  155387. int accblock=0;
  155388. int thisblock;
  155389. int eosflag;
  155390. ogg_stream_init(&work_os,vf->current_serialno); /* get the memory ready */
  155391. ogg_stream_reset(&work_os); /* eliminate the spurious OV_HOLE
  155392. return from not necessarily
  155393. starting from the beginning */
  155394. while(1){
  155395. if(vf->ready_state>=STREAMSET){
  155396. /* snarf/scan a packet if we can */
  155397. int result=ogg_stream_packetout(&work_os,&op);
  155398. if(result>0){
  155399. if(vf->vi[vf->current_link].codec_setup){
  155400. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  155401. if(thisblock<0){
  155402. ogg_stream_packetout(&vf->os,NULL);
  155403. thisblock=0;
  155404. }else{
  155405. if(eosflag)
  155406. ogg_stream_packetout(&vf->os,NULL);
  155407. else
  155408. if(lastblock)accblock+=(lastblock+thisblock)>>2;
  155409. }
  155410. if(op.granulepos!=-1){
  155411. int i,link=vf->current_link;
  155412. ogg_int64_t granulepos=op.granulepos-vf->pcmlengths[link*2];
  155413. if(granulepos<0)granulepos=0;
  155414. for(i=0;i<link;i++)
  155415. granulepos+=vf->pcmlengths[i*2+1];
  155416. vf->pcm_offset=granulepos-accblock;
  155417. break;
  155418. }
  155419. lastblock=thisblock;
  155420. continue;
  155421. }else
  155422. ogg_stream_packetout(&vf->os,NULL);
  155423. }
  155424. }
  155425. if(!lastblock){
  155426. if(_get_next_page(vf,&og,-1)<0){
  155427. vf->pcm_offset=ov_pcm_total(vf,-1);
  155428. break;
  155429. }
  155430. }else{
  155431. /* huh? Bogus stream with packets but no granulepos */
  155432. vf->pcm_offset=-1;
  155433. break;
  155434. }
  155435. /* has our decoding just traversed a bitstream boundary? */
  155436. if(vf->ready_state>=STREAMSET)
  155437. if(vf->current_serialno!=ogg_page_serialno(&og)){
  155438. _decode_clear(vf); /* clear out stream state */
  155439. ogg_stream_clear(&work_os);
  155440. }
  155441. if(vf->ready_state<STREAMSET){
  155442. int link;
  155443. vf->current_serialno=ogg_page_serialno(&og);
  155444. for(link=0;link<vf->links;link++)
  155445. if(vf->serialnos[link]==vf->current_serialno)break;
  155446. if(link==vf->links)goto seek_error; /* sign of a bogus stream.
  155447. error out, leave
  155448. machine uninitialized */
  155449. vf->current_link=link;
  155450. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  155451. ogg_stream_reset_serialno(&work_os,vf->current_serialno);
  155452. vf->ready_state=STREAMSET;
  155453. }
  155454. ogg_stream_pagein(&vf->os,&og);
  155455. ogg_stream_pagein(&work_os,&og);
  155456. eosflag=ogg_page_eos(&og);
  155457. }
  155458. }
  155459. ogg_stream_clear(&work_os);
  155460. vf->bittrack=0.f;
  155461. vf->samptrack=0.f;
  155462. return(0);
  155463. seek_error:
  155464. /* dump the machine so we're in a known state */
  155465. vf->pcm_offset=-1;
  155466. ogg_stream_clear(&work_os);
  155467. _decode_clear(vf);
  155468. return OV_EBADLINK;
  155469. }
  155470. /* Page granularity seek (faster than sample granularity because we
  155471. don't do the last bit of decode to find a specific sample).
  155472. Seek to the last [granule marked] page preceeding the specified pos
  155473. location, such that decoding past the returned point will quickly
  155474. arrive at the requested position. */
  155475. int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos){
  155476. int link=-1;
  155477. ogg_int64_t result=0;
  155478. ogg_int64_t total=ov_pcm_total(vf,-1);
  155479. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155480. if(!vf->seekable)return(OV_ENOSEEK);
  155481. if(pos<0 || pos>total)return(OV_EINVAL);
  155482. /* which bitstream section does this pcm offset occur in? */
  155483. for(link=vf->links-1;link>=0;link--){
  155484. total-=vf->pcmlengths[link*2+1];
  155485. if(pos>=total)break;
  155486. }
  155487. /* search within the logical bitstream for the page with the highest
  155488. pcm_pos preceeding (or equal to) pos. There is a danger here;
  155489. missing pages or incorrect frame number information in the
  155490. bitstream could make our task impossible. Account for that (it
  155491. would be an error condition) */
  155492. /* new search algorithm by HB (Nicholas Vinen) */
  155493. {
  155494. ogg_int64_t end=vf->offsets[link+1];
  155495. ogg_int64_t begin=vf->offsets[link];
  155496. ogg_int64_t begintime = vf->pcmlengths[link*2];
  155497. ogg_int64_t endtime = vf->pcmlengths[link*2+1]+begintime;
  155498. ogg_int64_t target=pos-total+begintime;
  155499. ogg_int64_t best=begin;
  155500. ogg_page og;
  155501. while(begin<end){
  155502. ogg_int64_t bisect;
  155503. if(end-begin<CHUNKSIZE){
  155504. bisect=begin;
  155505. }else{
  155506. /* take a (pretty decent) guess. */
  155507. bisect=begin +
  155508. (target-begintime)*(end-begin)/(endtime-begintime) - CHUNKSIZE;
  155509. if(bisect<=begin)
  155510. bisect=begin+1;
  155511. }
  155512. _seek_helper(vf,bisect);
  155513. while(begin<end){
  155514. result=_get_next_page(vf,&og,end-vf->offset);
  155515. if(result==OV_EREAD) goto seek_error;
  155516. if(result<0){
  155517. if(bisect<=begin+1)
  155518. end=begin; /* found it */
  155519. else{
  155520. if(bisect==0) goto seek_error;
  155521. bisect-=CHUNKSIZE;
  155522. if(bisect<=begin)bisect=begin+1;
  155523. _seek_helper(vf,bisect);
  155524. }
  155525. }else{
  155526. ogg_int64_t granulepos=ogg_page_granulepos(&og);
  155527. if(granulepos==-1)continue;
  155528. if(granulepos<target){
  155529. best=result; /* raw offset of packet with granulepos */
  155530. begin=vf->offset; /* raw offset of next page */
  155531. begintime=granulepos;
  155532. if(target-begintime>44100)break;
  155533. bisect=begin; /* *not* begin + 1 */
  155534. }else{
  155535. if(bisect<=begin+1)
  155536. end=begin; /* found it */
  155537. else{
  155538. if(end==vf->offset){ /* we're pretty close - we'd be stuck in */
  155539. end=result;
  155540. bisect-=CHUNKSIZE; /* an endless loop otherwise. */
  155541. if(bisect<=begin)bisect=begin+1;
  155542. _seek_helper(vf,bisect);
  155543. }else{
  155544. end=result;
  155545. endtime=granulepos;
  155546. break;
  155547. }
  155548. }
  155549. }
  155550. }
  155551. }
  155552. }
  155553. /* found our page. seek to it, update pcm offset. Easier case than
  155554. raw_seek, don't keep packets preceeding granulepos. */
  155555. {
  155556. ogg_page og;
  155557. ogg_packet op;
  155558. /* seek */
  155559. _seek_helper(vf,best);
  155560. vf->pcm_offset=-1;
  155561. if(_get_next_page(vf,&og,-1)<0)return(OV_EOF); /* shouldn't happen */
  155562. if(link!=vf->current_link){
  155563. /* Different link; dump entire decode machine */
  155564. _decode_clear(vf);
  155565. vf->current_link=link;
  155566. vf->current_serialno=ogg_page_serialno(&og);
  155567. vf->ready_state=STREAMSET;
  155568. }else{
  155569. vorbis_synthesis_restart(&vf->vd);
  155570. }
  155571. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  155572. ogg_stream_pagein(&vf->os,&og);
  155573. /* pull out all but last packet; the one with granulepos */
  155574. while(1){
  155575. result=ogg_stream_packetpeek(&vf->os,&op);
  155576. if(result==0){
  155577. /* !!! the packet finishing this page originated on a
  155578. preceeding page. Keep fetching previous pages until we
  155579. get one with a granulepos or without the 'continued' flag
  155580. set. Then just use raw_seek for simplicity. */
  155581. _seek_helper(vf,best);
  155582. while(1){
  155583. result=_get_prev_page(vf,&og);
  155584. if(result<0) goto seek_error;
  155585. if(ogg_page_granulepos(&og)>-1 ||
  155586. !ogg_page_continued(&og)){
  155587. return ov_raw_seek(vf,result);
  155588. }
  155589. vf->offset=result;
  155590. }
  155591. }
  155592. if(result<0){
  155593. result = OV_EBADPACKET;
  155594. goto seek_error;
  155595. }
  155596. if(op.granulepos!=-1){
  155597. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  155598. if(vf->pcm_offset<0)vf->pcm_offset=0;
  155599. vf->pcm_offset+=total;
  155600. break;
  155601. }else
  155602. result=ogg_stream_packetout(&vf->os,NULL);
  155603. }
  155604. }
  155605. }
  155606. /* verify result */
  155607. if(vf->pcm_offset>pos || pos>ov_pcm_total(vf,-1)){
  155608. result=OV_EFAULT;
  155609. goto seek_error;
  155610. }
  155611. vf->bittrack=0.f;
  155612. vf->samptrack=0.f;
  155613. return(0);
  155614. seek_error:
  155615. /* dump machine so we're in a known state */
  155616. vf->pcm_offset=-1;
  155617. _decode_clear(vf);
  155618. return (int)result;
  155619. }
  155620. /* seek to a sample offset relative to the decompressed pcm stream
  155621. returns zero on success, nonzero on failure */
  155622. int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos){
  155623. int thisblock,lastblock=0;
  155624. int ret=ov_pcm_seek_page(vf,pos);
  155625. if(ret<0)return(ret);
  155626. if((ret=_make_decode_ready(vf)))return ret;
  155627. /* discard leading packets we don't need for the lapping of the
  155628. position we want; don't decode them */
  155629. while(1){
  155630. ogg_packet op;
  155631. ogg_page og;
  155632. int ret=ogg_stream_packetpeek(&vf->os,&op);
  155633. if(ret>0){
  155634. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  155635. if(thisblock<0){
  155636. ogg_stream_packetout(&vf->os,NULL);
  155637. continue; /* non audio packet */
  155638. }
  155639. if(lastblock)vf->pcm_offset+=(lastblock+thisblock)>>2;
  155640. if(vf->pcm_offset+((thisblock+
  155641. vorbis_info_blocksize(vf->vi,1))>>2)>=pos)break;
  155642. /* remove the packet from packet queue and track its granulepos */
  155643. ogg_stream_packetout(&vf->os,NULL);
  155644. vorbis_synthesis_trackonly(&vf->vb,&op); /* set up a vb with
  155645. only tracking, no
  155646. pcm_decode */
  155647. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  155648. /* end of logical stream case is hard, especially with exact
  155649. length positioning. */
  155650. if(op.granulepos>-1){
  155651. int i;
  155652. /* always believe the stream markers */
  155653. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  155654. if(vf->pcm_offset<0)vf->pcm_offset=0;
  155655. for(i=0;i<vf->current_link;i++)
  155656. vf->pcm_offset+=vf->pcmlengths[i*2+1];
  155657. }
  155658. lastblock=thisblock;
  155659. }else{
  155660. if(ret<0 && ret!=OV_HOLE)break;
  155661. /* suck in a new page */
  155662. if(_get_next_page(vf,&og,-1)<0)break;
  155663. if(vf->current_serialno!=ogg_page_serialno(&og))_decode_clear(vf);
  155664. if(vf->ready_state<STREAMSET){
  155665. int link;
  155666. vf->current_serialno=ogg_page_serialno(&og);
  155667. for(link=0;link<vf->links;link++)
  155668. if(vf->serialnos[link]==vf->current_serialno)break;
  155669. if(link==vf->links)return(OV_EBADLINK);
  155670. vf->current_link=link;
  155671. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  155672. vf->ready_state=STREAMSET;
  155673. ret=_make_decode_ready(vf);
  155674. if(ret)return ret;
  155675. lastblock=0;
  155676. }
  155677. ogg_stream_pagein(&vf->os,&og);
  155678. }
  155679. }
  155680. vf->bittrack=0.f;
  155681. vf->samptrack=0.f;
  155682. /* discard samples until we reach the desired position. Crossing a
  155683. logical bitstream boundary with abandon is OK. */
  155684. while(vf->pcm_offset<pos){
  155685. ogg_int64_t target=pos-vf->pcm_offset;
  155686. long samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  155687. if(samples>target)samples=target;
  155688. vorbis_synthesis_read(&vf->vd,samples);
  155689. vf->pcm_offset+=samples;
  155690. if(samples<target)
  155691. if(_fetch_and_process_packet(vf,NULL,1,1)<=0)
  155692. vf->pcm_offset=ov_pcm_total(vf,-1); /* eof */
  155693. }
  155694. return 0;
  155695. }
  155696. /* seek to a playback time relative to the decompressed pcm stream
  155697. returns zero on success, nonzero on failure */
  155698. int ov_time_seek(OggVorbis_File *vf,double seconds){
  155699. /* translate time to PCM position and call ov_pcm_seek */
  155700. int link=-1;
  155701. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  155702. double time_total=ov_time_total(vf,-1);
  155703. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155704. if(!vf->seekable)return(OV_ENOSEEK);
  155705. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  155706. /* which bitstream section does this time offset occur in? */
  155707. for(link=vf->links-1;link>=0;link--){
  155708. pcm_total-=vf->pcmlengths[link*2+1];
  155709. time_total-=ov_time_total(vf,link);
  155710. if(seconds>=time_total)break;
  155711. }
  155712. /* enough information to convert time offset to pcm offset */
  155713. {
  155714. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  155715. return(ov_pcm_seek(vf,target));
  155716. }
  155717. }
  155718. /* page-granularity version of ov_time_seek
  155719. returns zero on success, nonzero on failure */
  155720. int ov_time_seek_page(OggVorbis_File *vf,double seconds){
  155721. /* translate time to PCM position and call ov_pcm_seek */
  155722. int link=-1;
  155723. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  155724. double time_total=ov_time_total(vf,-1);
  155725. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155726. if(!vf->seekable)return(OV_ENOSEEK);
  155727. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  155728. /* which bitstream section does this time offset occur in? */
  155729. for(link=vf->links-1;link>=0;link--){
  155730. pcm_total-=vf->pcmlengths[link*2+1];
  155731. time_total-=ov_time_total(vf,link);
  155732. if(seconds>=time_total)break;
  155733. }
  155734. /* enough information to convert time offset to pcm offset */
  155735. {
  155736. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  155737. return(ov_pcm_seek_page(vf,target));
  155738. }
  155739. }
  155740. /* tell the current stream offset cursor. Note that seek followed by
  155741. tell will likely not give the set offset due to caching */
  155742. ogg_int64_t ov_raw_tell(OggVorbis_File *vf){
  155743. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155744. return(vf->offset);
  155745. }
  155746. /* return PCM offset (sample) of next PCM sample to be read */
  155747. ogg_int64_t ov_pcm_tell(OggVorbis_File *vf){
  155748. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155749. return(vf->pcm_offset);
  155750. }
  155751. /* return time offset (seconds) of next PCM sample to be read */
  155752. double ov_time_tell(OggVorbis_File *vf){
  155753. int link=0;
  155754. ogg_int64_t pcm_total=0;
  155755. double time_total=0.f;
  155756. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155757. if(vf->seekable){
  155758. pcm_total=ov_pcm_total(vf,-1);
  155759. time_total=ov_time_total(vf,-1);
  155760. /* which bitstream section does this time offset occur in? */
  155761. for(link=vf->links-1;link>=0;link--){
  155762. pcm_total-=vf->pcmlengths[link*2+1];
  155763. time_total-=ov_time_total(vf,link);
  155764. if(vf->pcm_offset>=pcm_total)break;
  155765. }
  155766. }
  155767. return((double)time_total+(double)(vf->pcm_offset-pcm_total)/vf->vi[link].rate);
  155768. }
  155769. /* link: -1) return the vorbis_info struct for the bitstream section
  155770. currently being decoded
  155771. 0-n) to request information for a specific bitstream section
  155772. In the case of a non-seekable bitstream, any call returns the
  155773. current bitstream. NULL in the case that the machine is not
  155774. initialized */
  155775. vorbis_info *ov_info(OggVorbis_File *vf,int link){
  155776. if(vf->seekable){
  155777. if(link<0)
  155778. if(vf->ready_state>=STREAMSET)
  155779. return vf->vi+vf->current_link;
  155780. else
  155781. return vf->vi;
  155782. else
  155783. if(link>=vf->links)
  155784. return NULL;
  155785. else
  155786. return vf->vi+link;
  155787. }else{
  155788. return vf->vi;
  155789. }
  155790. }
  155791. /* grr, strong typing, grr, no templates/inheritence, grr */
  155792. vorbis_comment *ov_comment(OggVorbis_File *vf,int link){
  155793. if(vf->seekable){
  155794. if(link<0)
  155795. if(vf->ready_state>=STREAMSET)
  155796. return vf->vc+vf->current_link;
  155797. else
  155798. return vf->vc;
  155799. else
  155800. if(link>=vf->links)
  155801. return NULL;
  155802. else
  155803. return vf->vc+link;
  155804. }else{
  155805. return vf->vc;
  155806. }
  155807. }
  155808. static int host_is_big_endian() {
  155809. ogg_int32_t pattern = 0xfeedface; /* deadbeef */
  155810. unsigned char *bytewise = (unsigned char *)&pattern;
  155811. if (bytewise[0] == 0xfe) return 1;
  155812. return 0;
  155813. }
  155814. /* up to this point, everything could more or less hide the multiple
  155815. logical bitstream nature of chaining from the toplevel application
  155816. if the toplevel application didn't particularly care. However, at
  155817. the point that we actually read audio back, the multiple-section
  155818. nature must surface: Multiple bitstream sections do not necessarily
  155819. have to have the same number of channels or sampling rate.
  155820. ov_read returns the sequential logical bitstream number currently
  155821. being decoded along with the PCM data in order that the toplevel
  155822. application can take action on channel/sample rate changes. This
  155823. number will be incremented even for streamed (non-seekable) streams
  155824. (for seekable streams, it represents the actual logical bitstream
  155825. index within the physical bitstream. Note that the accessor
  155826. functions above are aware of this dichotomy).
  155827. input values: buffer) a buffer to hold packed PCM data for return
  155828. length) the byte length requested to be placed into buffer
  155829. bigendianp) should the data be packed LSB first (0) or
  155830. MSB first (1)
  155831. word) word size for output. currently 1 (byte) or
  155832. 2 (16 bit short)
  155833. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  155834. 0) EOF
  155835. n) number of bytes of PCM actually returned. The
  155836. below works on a packet-by-packet basis, so the
  155837. return length is not related to the 'length' passed
  155838. in, just guaranteed to fit.
  155839. *section) set to the logical bitstream number */
  155840. long ov_read(OggVorbis_File *vf,char *buffer,int length,
  155841. int bigendianp,int word,int sgned,int *bitstream){
  155842. int i,j;
  155843. int host_endian = host_is_big_endian();
  155844. float **pcm;
  155845. long samples;
  155846. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155847. while(1){
  155848. if(vf->ready_state==INITSET){
  155849. samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  155850. if(samples)break;
  155851. }
  155852. /* suck in another packet */
  155853. {
  155854. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  155855. if(ret==OV_EOF)
  155856. return(0);
  155857. if(ret<=0)
  155858. return(ret);
  155859. }
  155860. }
  155861. if(samples>0){
  155862. /* yay! proceed to pack data into the byte buffer */
  155863. long channels=ov_info(vf,-1)->channels;
  155864. long bytespersample=word * channels;
  155865. vorbis_fpu_control fpu;
  155866. (void) fpu; // (to avoid a warning about it being unused)
  155867. if(samples>length/bytespersample)samples=length/bytespersample;
  155868. if(samples <= 0)
  155869. return OV_EINVAL;
  155870. /* a tight loop to pack each size */
  155871. {
  155872. int val;
  155873. if(word==1){
  155874. int off=(sgned?0:128);
  155875. vorbis_fpu_setround(&fpu);
  155876. for(j=0;j<samples;j++)
  155877. for(i=0;i<channels;i++){
  155878. val=vorbis_ftoi(pcm[i][j]*128.f);
  155879. if(val>127)val=127;
  155880. else if(val<-128)val=-128;
  155881. *buffer++=val+off;
  155882. }
  155883. vorbis_fpu_restore(fpu);
  155884. }else{
  155885. int off=(sgned?0:32768);
  155886. if(host_endian==bigendianp){
  155887. if(sgned){
  155888. vorbis_fpu_setround(&fpu);
  155889. for(i=0;i<channels;i++) { /* It's faster in this order */
  155890. float *src=pcm[i];
  155891. short *dest=((short *)buffer)+i;
  155892. for(j=0;j<samples;j++) {
  155893. val=vorbis_ftoi(src[j]*32768.f);
  155894. if(val>32767)val=32767;
  155895. else if(val<-32768)val=-32768;
  155896. *dest=val;
  155897. dest+=channels;
  155898. }
  155899. }
  155900. vorbis_fpu_restore(fpu);
  155901. }else{
  155902. vorbis_fpu_setround(&fpu);
  155903. for(i=0;i<channels;i++) {
  155904. float *src=pcm[i];
  155905. short *dest=((short *)buffer)+i;
  155906. for(j=0;j<samples;j++) {
  155907. val=vorbis_ftoi(src[j]*32768.f);
  155908. if(val>32767)val=32767;
  155909. else if(val<-32768)val=-32768;
  155910. *dest=val+off;
  155911. dest+=channels;
  155912. }
  155913. }
  155914. vorbis_fpu_restore(fpu);
  155915. }
  155916. }else if(bigendianp){
  155917. vorbis_fpu_setround(&fpu);
  155918. for(j=0;j<samples;j++)
  155919. for(i=0;i<channels;i++){
  155920. val=vorbis_ftoi(pcm[i][j]*32768.f);
  155921. if(val>32767)val=32767;
  155922. else if(val<-32768)val=-32768;
  155923. val+=off;
  155924. *buffer++=(val>>8);
  155925. *buffer++=(val&0xff);
  155926. }
  155927. vorbis_fpu_restore(fpu);
  155928. }else{
  155929. int val;
  155930. vorbis_fpu_setround(&fpu);
  155931. for(j=0;j<samples;j++)
  155932. for(i=0;i<channels;i++){
  155933. val=vorbis_ftoi(pcm[i][j]*32768.f);
  155934. if(val>32767)val=32767;
  155935. else if(val<-32768)val=-32768;
  155936. val+=off;
  155937. *buffer++=(val&0xff);
  155938. *buffer++=(val>>8);
  155939. }
  155940. vorbis_fpu_restore(fpu);
  155941. }
  155942. }
  155943. }
  155944. vorbis_synthesis_read(&vf->vd,samples);
  155945. vf->pcm_offset+=samples;
  155946. if(bitstream)*bitstream=vf->current_link;
  155947. return(samples*bytespersample);
  155948. }else{
  155949. return(samples);
  155950. }
  155951. }
  155952. /* input values: pcm_channels) a float vector per channel of output
  155953. length) the sample length being read by the app
  155954. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  155955. 0) EOF
  155956. n) number of samples of PCM actually returned. The
  155957. below works on a packet-by-packet basis, so the
  155958. return length is not related to the 'length' passed
  155959. in, just guaranteed to fit.
  155960. *section) set to the logical bitstream number */
  155961. long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int length,
  155962. int *bitstream){
  155963. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155964. while(1){
  155965. if(vf->ready_state==INITSET){
  155966. float **pcm;
  155967. long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  155968. if(samples){
  155969. if(pcm_channels)*pcm_channels=pcm;
  155970. if(samples>length)samples=length;
  155971. vorbis_synthesis_read(&vf->vd,samples);
  155972. vf->pcm_offset+=samples;
  155973. if(bitstream)*bitstream=vf->current_link;
  155974. return samples;
  155975. }
  155976. }
  155977. /* suck in another packet */
  155978. {
  155979. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  155980. if(ret==OV_EOF)return(0);
  155981. if(ret<=0)return(ret);
  155982. }
  155983. }
  155984. }
  155985. extern float *vorbis_window(vorbis_dsp_state *v,int W);
  155986. extern void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,
  155987. ogg_int64_t off);
  155988. static void _ov_splice(float **pcm,float **lappcm,
  155989. int n1, int n2,
  155990. int ch1, int ch2,
  155991. float *w1, float *w2){
  155992. int i,j;
  155993. float *w=w1;
  155994. int n=n1;
  155995. if(n1>n2){
  155996. n=n2;
  155997. w=w2;
  155998. }
  155999. /* splice */
  156000. for(j=0;j<ch1 && j<ch2;j++){
  156001. float *s=lappcm[j];
  156002. float *d=pcm[j];
  156003. for(i=0;i<n;i++){
  156004. float wd=w[i]*w[i];
  156005. float ws=1.-wd;
  156006. d[i]=d[i]*wd + s[i]*ws;
  156007. }
  156008. }
  156009. /* window from zero */
  156010. for(;j<ch2;j++){
  156011. float *d=pcm[j];
  156012. for(i=0;i<n;i++){
  156013. float wd=w[i]*w[i];
  156014. d[i]=d[i]*wd;
  156015. }
  156016. }
  156017. }
  156018. /* make sure vf is INITSET */
  156019. static int _ov_initset(OggVorbis_File *vf){
  156020. while(1){
  156021. if(vf->ready_state==INITSET)break;
  156022. /* suck in another packet */
  156023. {
  156024. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  156025. if(ret<0 && ret!=OV_HOLE)return(ret);
  156026. }
  156027. }
  156028. return 0;
  156029. }
  156030. /* make sure vf is INITSET and that we have a primed buffer; if
  156031. we're crosslapping at a stream section boundary, this also makes
  156032. sure we're sanity checking against the right stream information */
  156033. static int _ov_initprime(OggVorbis_File *vf){
  156034. vorbis_dsp_state *vd=&vf->vd;
  156035. while(1){
  156036. if(vf->ready_state==INITSET)
  156037. if(vorbis_synthesis_pcmout(vd,NULL))break;
  156038. /* suck in another packet */
  156039. {
  156040. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  156041. if(ret<0 && ret!=OV_HOLE)return(ret);
  156042. }
  156043. }
  156044. return 0;
  156045. }
  156046. /* grab enough data for lapping from vf; this may be in the form of
  156047. unreturned, already-decoded pcm, remaining PCM we will need to
  156048. decode, or synthetic postextrapolation from last packets. */
  156049. static void _ov_getlap(OggVorbis_File *vf,vorbis_info *vi,vorbis_dsp_state *vd,
  156050. float **lappcm,int lapsize){
  156051. int lapcount=0,i;
  156052. float **pcm;
  156053. /* try first to decode the lapping data */
  156054. while(lapcount<lapsize){
  156055. int samples=vorbis_synthesis_pcmout(vd,&pcm);
  156056. if(samples){
  156057. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  156058. for(i=0;i<vi->channels;i++)
  156059. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  156060. lapcount+=samples;
  156061. vorbis_synthesis_read(vd,samples);
  156062. }else{
  156063. /* suck in another packet */
  156064. int ret=_fetch_and_process_packet(vf,NULL,1,0); /* do *not* span */
  156065. if(ret==OV_EOF)break;
  156066. }
  156067. }
  156068. if(lapcount<lapsize){
  156069. /* failed to get lapping data from normal decode; pry it from the
  156070. postextrapolation buffering, or the second half of the MDCT
  156071. from the last packet */
  156072. int samples=vorbis_synthesis_lapout(&vf->vd,&pcm);
  156073. if(samples==0){
  156074. for(i=0;i<vi->channels;i++)
  156075. memset(lappcm[i]+lapcount,0,sizeof(**pcm)*lapsize-lapcount);
  156076. lapcount=lapsize;
  156077. }else{
  156078. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  156079. for(i=0;i<vi->channels;i++)
  156080. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  156081. lapcount+=samples;
  156082. }
  156083. }
  156084. }
  156085. /* this sets up crosslapping of a sample by using trailing data from
  156086. sample 1 and lapping it into the windowing buffer of sample 2 */
  156087. int ov_crosslap(OggVorbis_File *vf1, OggVorbis_File *vf2){
  156088. vorbis_info *vi1,*vi2;
  156089. float **lappcm;
  156090. float **pcm;
  156091. float *w1,*w2;
  156092. int n1,n2,i,ret,hs1,hs2;
  156093. if(vf1==vf2)return(0); /* degenerate case */
  156094. if(vf1->ready_state<OPENED)return(OV_EINVAL);
  156095. if(vf2->ready_state<OPENED)return(OV_EINVAL);
  156096. /* the relevant overlap buffers must be pre-checked and pre-primed
  156097. before looking at settings in the event that priming would cross
  156098. a bitstream boundary. So, do it now */
  156099. ret=_ov_initset(vf1);
  156100. if(ret)return(ret);
  156101. ret=_ov_initprime(vf2);
  156102. if(ret)return(ret);
  156103. vi1=ov_info(vf1,-1);
  156104. vi2=ov_info(vf2,-1);
  156105. hs1=ov_halfrate_p(vf1);
  156106. hs2=ov_halfrate_p(vf2);
  156107. lappcm=(float**) alloca(sizeof(*lappcm)*vi1->channels);
  156108. n1=vorbis_info_blocksize(vi1,0)>>(1+hs1);
  156109. n2=vorbis_info_blocksize(vi2,0)>>(1+hs2);
  156110. w1=vorbis_window(&vf1->vd,0);
  156111. w2=vorbis_window(&vf2->vd,0);
  156112. for(i=0;i<vi1->channels;i++)
  156113. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  156114. _ov_getlap(vf1,vi1,&vf1->vd,lappcm,n1);
  156115. /* have a lapping buffer from vf1; now to splice it into the lapping
  156116. buffer of vf2 */
  156117. /* consolidate and expose the buffer. */
  156118. vorbis_synthesis_lapout(&vf2->vd,&pcm);
  156119. _analysis_output_always("pcmL",0,pcm[0],n1*2,0,0,0);
  156120. _analysis_output_always("pcmR",0,pcm[1],n1*2,0,0,0);
  156121. /* splice */
  156122. _ov_splice(pcm,lappcm,n1,n2,vi1->channels,vi2->channels,w1,w2);
  156123. /* done */
  156124. return(0);
  156125. }
  156126. static int _ov_64_seek_lap(OggVorbis_File *vf,ogg_int64_t pos,
  156127. int (*localseek)(OggVorbis_File *,ogg_int64_t)){
  156128. vorbis_info *vi;
  156129. float **lappcm;
  156130. float **pcm;
  156131. float *w1,*w2;
  156132. int n1,n2,ch1,ch2,hs;
  156133. int i,ret;
  156134. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156135. ret=_ov_initset(vf);
  156136. if(ret)return(ret);
  156137. vi=ov_info(vf,-1);
  156138. hs=ov_halfrate_p(vf);
  156139. ch1=vi->channels;
  156140. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  156141. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  156142. persistent; even if the decode state
  156143. from this link gets dumped, this
  156144. window array continues to exist */
  156145. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  156146. for(i=0;i<ch1;i++)
  156147. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  156148. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  156149. /* have lapping data; seek and prime the buffer */
  156150. ret=localseek(vf,pos);
  156151. if(ret)return ret;
  156152. ret=_ov_initprime(vf);
  156153. if(ret)return(ret);
  156154. /* Guard against cross-link changes; they're perfectly legal */
  156155. vi=ov_info(vf,-1);
  156156. ch2=vi->channels;
  156157. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  156158. w2=vorbis_window(&vf->vd,0);
  156159. /* consolidate and expose the buffer. */
  156160. vorbis_synthesis_lapout(&vf->vd,&pcm);
  156161. /* splice */
  156162. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  156163. /* done */
  156164. return(0);
  156165. }
  156166. int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  156167. return _ov_64_seek_lap(vf,pos,ov_raw_seek);
  156168. }
  156169. int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  156170. return _ov_64_seek_lap(vf,pos,ov_pcm_seek);
  156171. }
  156172. int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos){
  156173. return _ov_64_seek_lap(vf,pos,ov_pcm_seek_page);
  156174. }
  156175. static int _ov_d_seek_lap(OggVorbis_File *vf,double pos,
  156176. int (*localseek)(OggVorbis_File *,double)){
  156177. vorbis_info *vi;
  156178. float **lappcm;
  156179. float **pcm;
  156180. float *w1,*w2;
  156181. int n1,n2,ch1,ch2,hs;
  156182. int i,ret;
  156183. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156184. ret=_ov_initset(vf);
  156185. if(ret)return(ret);
  156186. vi=ov_info(vf,-1);
  156187. hs=ov_halfrate_p(vf);
  156188. ch1=vi->channels;
  156189. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  156190. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  156191. persistent; even if the decode state
  156192. from this link gets dumped, this
  156193. window array continues to exist */
  156194. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  156195. for(i=0;i<ch1;i++)
  156196. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  156197. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  156198. /* have lapping data; seek and prime the buffer */
  156199. ret=localseek(vf,pos);
  156200. if(ret)return ret;
  156201. ret=_ov_initprime(vf);
  156202. if(ret)return(ret);
  156203. /* Guard against cross-link changes; they're perfectly legal */
  156204. vi=ov_info(vf,-1);
  156205. ch2=vi->channels;
  156206. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  156207. w2=vorbis_window(&vf->vd,0);
  156208. /* consolidate and expose the buffer. */
  156209. vorbis_synthesis_lapout(&vf->vd,&pcm);
  156210. /* splice */
  156211. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  156212. /* done */
  156213. return(0);
  156214. }
  156215. int ov_time_seek_lap(OggVorbis_File *vf,double pos){
  156216. return _ov_d_seek_lap(vf,pos,ov_time_seek);
  156217. }
  156218. int ov_time_seek_page_lap(OggVorbis_File *vf,double pos){
  156219. return _ov_d_seek_lap(vf,pos,ov_time_seek_page);
  156220. }
  156221. #endif
  156222. /*** End of inlined file: vorbisfile.c ***/
  156223. /*** Start of inlined file: window.c ***/
  156224. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  156225. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  156226. // tasks..
  156227. #if JUCE_MSVC
  156228. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  156229. #endif
  156230. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  156231. #if JUCE_USE_OGGVORBIS
  156232. #include <stdlib.h>
  156233. #include <math.h>
  156234. static float vwin64[32] = {
  156235. 0.0009460463F, 0.0085006468F, 0.0235352254F, 0.0458950567F,
  156236. 0.0753351908F, 0.1115073077F, 0.1539457973F, 0.2020557475F,
  156237. 0.2551056759F, 0.3122276645F, 0.3724270287F, 0.4346027792F,
  156238. 0.4975789974F, 0.5601459521F, 0.6211085051F, 0.6793382689F,
  156239. 0.7338252629F, 0.7837245849F, 0.8283939355F, 0.8674186656F,
  156240. 0.9006222429F, 0.9280614787F, 0.9500073081F, 0.9669131782F,
  156241. 0.9793740220F, 0.9880792941F, 0.9937636139F, 0.9971582668F,
  156242. 0.9989462667F, 0.9997230082F, 0.9999638688F, 0.9999995525F,
  156243. };
  156244. static float vwin128[64] = {
  156245. 0.0002365472F, 0.0021280687F, 0.0059065254F, 0.0115626550F,
  156246. 0.0190823442F, 0.0284463735F, 0.0396300935F, 0.0526030430F,
  156247. 0.0673285281F, 0.0837631763F, 0.1018564887F, 0.1215504095F,
  156248. 0.1427789367F, 0.1654677960F, 0.1895342001F, 0.2148867160F,
  156249. 0.2414252576F, 0.2690412240F, 0.2976177952F, 0.3270303960F,
  156250. 0.3571473350F, 0.3878306189F, 0.4189369387F, 0.4503188188F,
  156251. 0.4818259135F, 0.5133064334F, 0.5446086751F, 0.5755826278F,
  156252. 0.6060816248F, 0.6359640047F, 0.6650947483F, 0.6933470543F,
  156253. 0.7206038179F, 0.7467589810F, 0.7717187213F, 0.7954024542F,
  156254. 0.8177436264F, 0.8386902831F, 0.8582053981F, 0.8762669622F,
  156255. 0.8928678298F, 0.9080153310F, 0.9217306608F, 0.9340480615F,
  156256. 0.9450138200F, 0.9546851041F, 0.9631286621F, 0.9704194171F,
  156257. 0.9766389810F, 0.9818741197F, 0.9862151938F, 0.9897546035F,
  156258. 0.9925852598F, 0.9947991032F, 0.9964856900F, 0.9977308602F,
  156259. 0.9986155015F, 0.9992144193F, 0.9995953200F, 0.9998179155F,
  156260. 0.9999331503F, 0.9999825563F, 0.9999977357F, 0.9999999720F,
  156261. };
  156262. static float vwin256[128] = {
  156263. 0.0000591390F, 0.0005321979F, 0.0014780301F, 0.0028960636F,
  156264. 0.0047854363F, 0.0071449926F, 0.0099732775F, 0.0132685298F,
  156265. 0.0170286741F, 0.0212513119F, 0.0259337111F, 0.0310727950F,
  156266. 0.0366651302F, 0.0427069140F, 0.0491939614F, 0.0561216907F,
  156267. 0.0634851102F, 0.0712788035F, 0.0794969160F, 0.0881331402F,
  156268. 0.0971807028F, 0.1066323515F, 0.1164803426F, 0.1267164297F,
  156269. 0.1373318534F, 0.1483173323F, 0.1596630553F, 0.1713586755F,
  156270. 0.1833933062F, 0.1957555184F, 0.2084333404F, 0.2214142599F,
  156271. 0.2346852280F, 0.2482326664F, 0.2620424757F, 0.2761000481F,
  156272. 0.2903902813F, 0.3048975959F, 0.3196059553F, 0.3344988887F,
  156273. 0.3495595160F, 0.3647705766F, 0.3801144597F, 0.3955732382F,
  156274. 0.4111287047F, 0.4267624093F, 0.4424557009F, 0.4581897696F,
  156275. 0.4739456913F, 0.4897044744F, 0.5054471075F, 0.5211546088F,
  156276. 0.5368080763F, 0.5523887395F, 0.5678780103F, 0.5832575361F,
  156277. 0.5985092508F, 0.6136154277F, 0.6285587300F, 0.6433222619F,
  156278. 0.6578896175F, 0.6722449294F, 0.6863729144F, 0.7002589187F,
  156279. 0.7138889597F, 0.7272497662F, 0.7403288154F, 0.7531143679F,
  156280. 0.7655954985F, 0.7777621249F, 0.7896050322F, 0.8011158947F,
  156281. 0.8122872932F, 0.8231127294F, 0.8335866365F, 0.8437043850F,
  156282. 0.8534622861F, 0.8628575905F, 0.8718884835F, 0.8805540765F,
  156283. 0.8888543947F, 0.8967903616F, 0.9043637797F, 0.9115773078F,
  156284. 0.9184344360F, 0.9249394562F, 0.9310974312F, 0.9369141608F,
  156285. 0.9423961446F, 0.9475505439F, 0.9523851406F, 0.9569082947F,
  156286. 0.9611289005F, 0.9650563408F, 0.9687004405F, 0.9720714191F,
  156287. 0.9751798427F, 0.9780365753F, 0.9806527301F, 0.9830396204F,
  156288. 0.9852087111F, 0.9871715701F, 0.9889398207F, 0.9905250941F,
  156289. 0.9919389832F, 0.9931929973F, 0.9942985174F, 0.9952667537F,
  156290. 0.9961087037F, 0.9968351119F, 0.9974564312F, 0.9979827858F,
  156291. 0.9984239359F, 0.9987892441F, 0.9990876435F, 0.9993276081F,
  156292. 0.9995171241F, 0.9996636648F, 0.9997741654F, 0.9998550016F,
  156293. 0.9999119692F, 0.9999502656F, 0.9999744742F, 0.9999885497F,
  156294. 0.9999958064F, 0.9999989077F, 0.9999998584F, 0.9999999983F,
  156295. };
  156296. static float vwin512[256] = {
  156297. 0.0000147849F, 0.0001330607F, 0.0003695946F, 0.0007243509F,
  156298. 0.0011972759F, 0.0017882983F, 0.0024973285F, 0.0033242588F,
  156299. 0.0042689632F, 0.0053312973F, 0.0065110982F, 0.0078081841F,
  156300. 0.0092223540F, 0.0107533880F, 0.0124010466F, 0.0141650703F,
  156301. 0.0160451800F, 0.0180410758F, 0.0201524373F, 0.0223789233F,
  156302. 0.0247201710F, 0.0271757958F, 0.0297453914F, 0.0324285286F,
  156303. 0.0352247556F, 0.0381335972F, 0.0411545545F, 0.0442871045F,
  156304. 0.0475306997F, 0.0508847676F, 0.0543487103F, 0.0579219038F,
  156305. 0.0616036982F, 0.0653934164F, 0.0692903546F, 0.0732937809F,
  156306. 0.0774029356F, 0.0816170305F, 0.0859352485F, 0.0903567428F,
  156307. 0.0948806375F, 0.0995060259F, 0.1042319712F, 0.1090575056F,
  156308. 0.1139816300F, 0.1190033137F, 0.1241214941F, 0.1293350764F,
  156309. 0.1346429333F, 0.1400439046F, 0.1455367974F, 0.1511203852F,
  156310. 0.1567934083F, 0.1625545735F, 0.1684025537F, 0.1743359881F,
  156311. 0.1803534820F, 0.1864536069F, 0.1926349000F, 0.1988958650F,
  156312. 0.2052349715F, 0.2116506555F, 0.2181413191F, 0.2247053313F,
  156313. 0.2313410275F, 0.2380467105F, 0.2448206500F, 0.2516610835F,
  156314. 0.2585662164F, 0.2655342226F, 0.2725632448F, 0.2796513950F,
  156315. 0.2867967551F, 0.2939973773F, 0.3012512852F, 0.3085564739F,
  156316. 0.3159109111F, 0.3233125375F, 0.3307592680F, 0.3382489922F,
  156317. 0.3457795756F, 0.3533488602F, 0.3609546657F, 0.3685947904F,
  156318. 0.3762670121F, 0.3839690896F, 0.3916987634F, 0.3994537572F,
  156319. 0.4072317788F, 0.4150305215F, 0.4228476653F, 0.4306808783F,
  156320. 0.4385278181F, 0.4463861329F, 0.4542534630F, 0.4621274424F,
  156321. 0.4700057001F, 0.4778858615F, 0.4857655502F, 0.4936423891F,
  156322. 0.5015140023F, 0.5093780165F, 0.5172320626F, 0.5250737772F,
  156323. 0.5329008043F, 0.5407107971F, 0.5485014192F, 0.5562703465F,
  156324. 0.5640152688F, 0.5717338914F, 0.5794239366F, 0.5870831457F,
  156325. 0.5947092801F, 0.6023001235F, 0.6098534829F, 0.6173671907F,
  156326. 0.6248391059F, 0.6322671161F, 0.6396491384F, 0.6469831217F,
  156327. 0.6542670475F, 0.6614989319F, 0.6686768267F, 0.6757988210F,
  156328. 0.6828630426F, 0.6898676592F, 0.6968108799F, 0.7036909564F,
  156329. 0.7105061843F, 0.7172549043F, 0.7239355032F, 0.7305464154F,
  156330. 0.7370861235F, 0.7435531598F, 0.7499461068F, 0.7562635986F,
  156331. 0.7625043214F, 0.7686670148F, 0.7747504721F, 0.7807535410F,
  156332. 0.7866751247F, 0.7925141825F, 0.7982697296F, 0.8039408387F,
  156333. 0.8095266395F, 0.8150263196F, 0.8204391248F, 0.8257643590F,
  156334. 0.8310013848F, 0.8361496236F, 0.8412085555F, 0.8461777194F,
  156335. 0.8510567129F, 0.8558451924F, 0.8605428730F, 0.8651495278F,
  156336. 0.8696649882F, 0.8740891432F, 0.8784219392F, 0.8826633797F,
  156337. 0.8868135244F, 0.8908724888F, 0.8948404441F, 0.8987176157F,
  156338. 0.9025042831F, 0.9062007791F, 0.9098074886F, 0.9133248482F,
  156339. 0.9167533451F, 0.9200935163F, 0.9233459472F, 0.9265112712F,
  156340. 0.9295901680F, 0.9325833632F, 0.9354916263F, 0.9383157705F,
  156341. 0.9410566504F, 0.9437151618F, 0.9462922398F, 0.9487888576F,
  156342. 0.9512060252F, 0.9535447882F, 0.9558062262F, 0.9579914516F,
  156343. 0.9601016078F, 0.9621378683F, 0.9641014348F, 0.9659935361F,
  156344. 0.9678154261F, 0.9695683830F, 0.9712537071F, 0.9728727198F,
  156345. 0.9744267618F, 0.9759171916F, 0.9773453842F, 0.9787127293F,
  156346. 0.9800206298F, 0.9812705006F, 0.9824637665F, 0.9836018613F,
  156347. 0.9846862258F, 0.9857183066F, 0.9866995544F, 0.9876314227F,
  156348. 0.9885153662F, 0.9893528393F, 0.9901452948F, 0.9908941823F,
  156349. 0.9916009470F, 0.9922670279F, 0.9928938570F, 0.9934828574F,
  156350. 0.9940354423F, 0.9945530133F, 0.9950369595F, 0.9954886562F,
  156351. 0.9959094633F, 0.9963007242F, 0.9966637649F, 0.9969998925F,
  156352. 0.9973103939F, 0.9975965351F, 0.9978595598F, 0.9981006885F,
  156353. 0.9983211172F, 0.9985220166F, 0.9987045311F, 0.9988697776F,
  156354. 0.9990188449F, 0.9991527924F, 0.9992726499F, 0.9993794157F,
  156355. 0.9994740570F, 0.9995575079F, 0.9996306699F, 0.9996944099F,
  156356. 0.9997495605F, 0.9997969190F, 0.9998372465F, 0.9998712678F,
  156357. 0.9998996704F, 0.9999231041F, 0.9999421807F, 0.9999574732F,
  156358. 0.9999695157F, 0.9999788026F, 0.9999857885F, 0.9999908879F,
  156359. 0.9999944746F, 0.9999968817F, 0.9999984010F, 0.9999992833F,
  156360. 0.9999997377F, 0.9999999317F, 0.9999999911F, 0.9999999999F,
  156361. };
  156362. static float vwin1024[512] = {
  156363. 0.0000036962F, 0.0000332659F, 0.0000924041F, 0.0001811086F,
  156364. 0.0002993761F, 0.0004472021F, 0.0006245811F, 0.0008315063F,
  156365. 0.0010679699F, 0.0013339631F, 0.0016294757F, 0.0019544965F,
  156366. 0.0023090133F, 0.0026930125F, 0.0031064797F, 0.0035493989F,
  156367. 0.0040217533F, 0.0045235250F, 0.0050546946F, 0.0056152418F,
  156368. 0.0062051451F, 0.0068243817F, 0.0074729278F, 0.0081507582F,
  156369. 0.0088578466F, 0.0095941655F, 0.0103596863F, 0.0111543789F,
  156370. 0.0119782122F, 0.0128311538F, 0.0137131701F, 0.0146242260F,
  156371. 0.0155642855F, 0.0165333111F, 0.0175312640F, 0.0185581042F,
  156372. 0.0196137903F, 0.0206982797F, 0.0218115284F, 0.0229534910F,
  156373. 0.0241241208F, 0.0253233698F, 0.0265511886F, 0.0278075263F,
  156374. 0.0290923308F, 0.0304055484F, 0.0317471241F, 0.0331170013F,
  156375. 0.0345151222F, 0.0359414274F, 0.0373958560F, 0.0388783456F,
  156376. 0.0403888325F, 0.0419272511F, 0.0434935347F, 0.0450876148F,
  156377. 0.0467094213F, 0.0483588828F, 0.0500359261F, 0.0517404765F,
  156378. 0.0534724575F, 0.0552317913F, 0.0570183983F, 0.0588321971F,
  156379. 0.0606731048F, 0.0625410369F, 0.0644359070F, 0.0663576272F,
  156380. 0.0683061077F, 0.0702812571F, 0.0722829821F, 0.0743111878F,
  156381. 0.0763657775F, 0.0784466526F, 0.0805537129F, 0.0826868561F,
  156382. 0.0848459782F, 0.0870309736F, 0.0892417345F, 0.0914781514F,
  156383. 0.0937401128F, 0.0960275056F, 0.0983402145F, 0.1006781223F,
  156384. 0.1030411101F, 0.1054290568F, 0.1078418397F, 0.1102793336F,
  156385. 0.1127414119F, 0.1152279457F, 0.1177388042F, 0.1202738544F,
  156386. 0.1228329618F, 0.1254159892F, 0.1280227980F, 0.1306532471F,
  156387. 0.1333071937F, 0.1359844927F, 0.1386849970F, 0.1414085575F,
  156388. 0.1441550230F, 0.1469242403F, 0.1497160539F, 0.1525303063F,
  156389. 0.1553668381F, 0.1582254875F, 0.1611060909F, 0.1640084822F,
  156390. 0.1669324936F, 0.1698779549F, 0.1728446939F, 0.1758325362F,
  156391. 0.1788413055F, 0.1818708232F, 0.1849209084F, 0.1879913785F,
  156392. 0.1910820485F, 0.1941927312F, 0.1973232376F, 0.2004733764F,
  156393. 0.2036429541F, 0.2068317752F, 0.2100396421F, 0.2132663552F,
  156394. 0.2165117125F, 0.2197755102F, 0.2230575422F, 0.2263576007F,
  156395. 0.2296754753F, 0.2330109540F, 0.2363638225F, 0.2397338646F,
  156396. 0.2431208619F, 0.2465245941F, 0.2499448389F, 0.2533813719F,
  156397. 0.2568339669F, 0.2603023956F, 0.2637864277F, 0.2672858312F,
  156398. 0.2708003718F, 0.2743298135F, 0.2778739186F, 0.2814324472F,
  156399. 0.2850051576F, 0.2885918065F, 0.2921921485F, 0.2958059366F,
  156400. 0.2994329219F, 0.3030728538F, 0.3067254799F, 0.3103905462F,
  156401. 0.3140677969F, 0.3177569747F, 0.3214578205F, 0.3251700736F,
  156402. 0.3288934718F, 0.3326277513F, 0.3363726468F, 0.3401278914F,
  156403. 0.3438932168F, 0.3476683533F, 0.3514530297F, 0.3552469734F,
  156404. 0.3590499106F, 0.3628615659F, 0.3666816630F, 0.3705099239F,
  156405. 0.3743460698F, 0.3781898204F, 0.3820408945F, 0.3858990095F,
  156406. 0.3897638820F, 0.3936352274F, 0.3975127601F, 0.4013961936F,
  156407. 0.4052852405F, 0.4091796123F, 0.4130790198F, 0.4169831732F,
  156408. 0.4208917815F, 0.4248045534F, 0.4287211965F, 0.4326414181F,
  156409. 0.4365649248F, 0.4404914225F, 0.4444206167F, 0.4483522125F,
  156410. 0.4522859146F, 0.4562214270F, 0.4601584538F, 0.4640966984F,
  156411. 0.4680358644F, 0.4719756548F, 0.4759157726F, 0.4798559209F,
  156412. 0.4837958024F, 0.4877351199F, 0.4916735765F, 0.4956108751F,
  156413. 0.4995467188F, 0.5034808109F, 0.5074128550F, 0.5113425550F,
  156414. 0.5152696149F, 0.5191937395F, 0.5231146336F, 0.5270320028F,
  156415. 0.5309455530F, 0.5348549910F, 0.5387600239F, 0.5426603597F,
  156416. 0.5465557070F, 0.5504457754F, 0.5543302752F, 0.5582089175F,
  156417. 0.5620814145F, 0.5659474793F, 0.5698068262F, 0.5736591704F,
  156418. 0.5775042283F, 0.5813417176F, 0.5851713571F, 0.5889928670F,
  156419. 0.5928059689F, 0.5966103856F, 0.6004058415F, 0.6041920626F,
  156420. 0.6079687761F, 0.6117357113F, 0.6154925986F, 0.6192391705F,
  156421. 0.6229751612F, 0.6267003064F, 0.6304143441F, 0.6341170137F,
  156422. 0.6378080569F, 0.6414872173F, 0.6451542405F, 0.6488088741F,
  156423. 0.6524508681F, 0.6560799742F, 0.6596959469F, 0.6632985424F,
  156424. 0.6668875197F, 0.6704626398F, 0.6740236662F, 0.6775703649F,
  156425. 0.6811025043F, 0.6846198554F, 0.6881221916F, 0.6916092892F,
  156426. 0.6950809269F, 0.6985368861F, 0.7019769510F, 0.7054009085F,
  156427. 0.7088085484F, 0.7121996632F, 0.7155740484F, 0.7189315023F,
  156428. 0.7222718263F, 0.7255948245F, 0.7289003043F, 0.7321880760F,
  156429. 0.7354579530F, 0.7387097518F, 0.7419432921F, 0.7451583966F,
  156430. 0.7483548915F, 0.7515326059F, 0.7546913723F, 0.7578310265F,
  156431. 0.7609514077F, 0.7640523581F, 0.7671337237F, 0.7701953535F,
  156432. 0.7732371001F, 0.7762588195F, 0.7792603711F, 0.7822416178F,
  156433. 0.7852024259F, 0.7881426654F, 0.7910622097F, 0.7939609356F,
  156434. 0.7968387237F, 0.7996954579F, 0.8025310261F, 0.8053453193F,
  156435. 0.8081382324F, 0.8109096638F, 0.8136595156F, 0.8163876936F,
  156436. 0.8190941071F, 0.8217786690F, 0.8244412960F, 0.8270819086F,
  156437. 0.8297004305F, 0.8322967896F, 0.8348709171F, 0.8374227481F,
  156438. 0.8399522213F, 0.8424592789F, 0.8449438672F, 0.8474059356F,
  156439. 0.8498454378F, 0.8522623306F, 0.8546565748F, 0.8570281348F,
  156440. 0.8593769787F, 0.8617030779F, 0.8640064080F, 0.8662869477F,
  156441. 0.8685446796F, 0.8707795899F, 0.8729916682F, 0.8751809079F,
  156442. 0.8773473059F, 0.8794908626F, 0.8816115819F, 0.8837094713F,
  156443. 0.8857845418F, 0.8878368079F, 0.8898662874F, 0.8918730019F,
  156444. 0.8938569760F, 0.8958182380F, 0.8977568194F, 0.8996727552F,
  156445. 0.9015660837F, 0.9034368465F, 0.9052850885F, 0.9071108577F,
  156446. 0.9089142057F, 0.9106951869F, 0.9124538591F, 0.9141902832F,
  156447. 0.9159045233F, 0.9175966464F, 0.9192667228F, 0.9209148257F,
  156448. 0.9225410313F, 0.9241454187F, 0.9257280701F, 0.9272890704F,
  156449. 0.9288285075F, 0.9303464720F, 0.9318430576F, 0.9333183603F,
  156450. 0.9347724792F, 0.9362055158F, 0.9376175745F, 0.9390087622F,
  156451. 0.9403791881F, 0.9417289644F, 0.9430582055F, 0.9443670283F,
  156452. 0.9456555521F, 0.9469238986F, 0.9481721917F, 0.9494005577F,
  156453. 0.9506091252F, 0.9517980248F, 0.9529673894F, 0.9541173540F,
  156454. 0.9552480557F, 0.9563596334F, 0.9574522282F, 0.9585259830F,
  156455. 0.9595810428F, 0.9606175542F, 0.9616356656F, 0.9626355274F,
  156456. 0.9636172915F, 0.9645811114F, 0.9655271425F, 0.9664555414F,
  156457. 0.9673664664F, 0.9682600774F, 0.9691365355F, 0.9699960034F,
  156458. 0.9708386448F, 0.9716646250F, 0.9724741103F, 0.9732672685F,
  156459. 0.9740442683F, 0.9748052795F, 0.9755504729F, 0.9762800205F,
  156460. 0.9769940950F, 0.9776928703F, 0.9783765210F, 0.9790452223F,
  156461. 0.9796991504F, 0.9803384823F, 0.9809633954F, 0.9815740679F,
  156462. 0.9821706784F, 0.9827534063F, 0.9833224312F, 0.9838779332F,
  156463. 0.9844200928F, 0.9849490910F, 0.9854651087F, 0.9859683274F,
  156464. 0.9864589286F, 0.9869370940F, 0.9874030054F, 0.9878568447F,
  156465. 0.9882987937F, 0.9887290343F, 0.9891477481F, 0.9895551169F,
  156466. 0.9899513220F, 0.9903365446F, 0.9907109658F, 0.9910747662F,
  156467. 0.9914281260F, 0.9917712252F, 0.9921042433F, 0.9924273593F,
  156468. 0.9927407516F, 0.9930445982F, 0.9933390763F, 0.9936243626F,
  156469. 0.9939006331F, 0.9941680631F, 0.9944268269F, 0.9946770982F,
  156470. 0.9949190498F, 0.9951528537F, 0.9953786808F, 0.9955967011F,
  156471. 0.9958070836F, 0.9960099963F, 0.9962056061F, 0.9963940787F,
  156472. 0.9965755786F, 0.9967502693F, 0.9969183129F, 0.9970798704F,
  156473. 0.9972351013F, 0.9973841640F, 0.9975272151F, 0.9976644103F,
  156474. 0.9977959036F, 0.9979218476F, 0.9980423932F, 0.9981576901F,
  156475. 0.9982678862F, 0.9983731278F, 0.9984735596F, 0.9985693247F,
  156476. 0.9986605645F, 0.9987474186F, 0.9988300248F, 0.9989085193F,
  156477. 0.9989830364F, 0.9990537085F, 0.9991206662F, 0.9991840382F,
  156478. 0.9992439513F, 0.9993005303F, 0.9993538982F, 0.9994041757F,
  156479. 0.9994514817F, 0.9994959330F, 0.9995376444F, 0.9995767286F,
  156480. 0.9996132960F, 0.9996474550F, 0.9996793121F, 0.9997089710F,
  156481. 0.9997365339F, 0.9997621003F, 0.9997857677F, 0.9998076311F,
  156482. 0.9998277836F, 0.9998463156F, 0.9998633155F, 0.9998788692F,
  156483. 0.9998930603F, 0.9999059701F, 0.9999176774F, 0.9999282586F,
  156484. 0.9999377880F, 0.9999463370F, 0.9999539749F, 0.9999607685F,
  156485. 0.9999667820F, 0.9999720773F, 0.9999767136F, 0.9999807479F,
  156486. 0.9999842344F, 0.9999872249F, 0.9999897688F, 0.9999919127F,
  156487. 0.9999937009F, 0.9999951749F, 0.9999963738F, 0.9999973342F,
  156488. 0.9999980900F, 0.9999986724F, 0.9999991103F, 0.9999994297F,
  156489. 0.9999996543F, 0.9999998049F, 0.9999999000F, 0.9999999552F,
  156490. 0.9999999836F, 0.9999999957F, 0.9999999994F, 1.0000000000F,
  156491. };
  156492. static float vwin2048[1024] = {
  156493. 0.0000009241F, 0.0000083165F, 0.0000231014F, 0.0000452785F,
  156494. 0.0000748476F, 0.0001118085F, 0.0001561608F, 0.0002079041F,
  156495. 0.0002670379F, 0.0003335617F, 0.0004074748F, 0.0004887765F,
  156496. 0.0005774661F, 0.0006735427F, 0.0007770054F, 0.0008878533F,
  156497. 0.0010060853F, 0.0011317002F, 0.0012646969F, 0.0014050742F,
  156498. 0.0015528307F, 0.0017079650F, 0.0018704756F, 0.0020403610F,
  156499. 0.0022176196F, 0.0024022497F, 0.0025942495F, 0.0027936173F,
  156500. 0.0030003511F, 0.0032144490F, 0.0034359088F, 0.0036647286F,
  156501. 0.0039009061F, 0.0041444391F, 0.0043953253F, 0.0046535621F,
  156502. 0.0049191472F, 0.0051920781F, 0.0054723520F, 0.0057599664F,
  156503. 0.0060549184F, 0.0063572052F, 0.0066668239F, 0.0069837715F,
  156504. 0.0073080449F, 0.0076396410F, 0.0079785566F, 0.0083247884F,
  156505. 0.0086783330F, 0.0090391871F, 0.0094073470F, 0.0097828092F,
  156506. 0.0101655700F, 0.0105556258F, 0.0109529726F, 0.0113576065F,
  156507. 0.0117695237F, 0.0121887200F, 0.0126151913F, 0.0130489335F,
  156508. 0.0134899422F, 0.0139382130F, 0.0143937415F, 0.0148565233F,
  156509. 0.0153265536F, 0.0158038279F, 0.0162883413F, 0.0167800889F,
  156510. 0.0172790660F, 0.0177852675F, 0.0182986882F, 0.0188193231F,
  156511. 0.0193471668F, 0.0198822141F, 0.0204244594F, 0.0209738974F,
  156512. 0.0215305225F, 0.0220943289F, 0.0226653109F, 0.0232434627F,
  156513. 0.0238287784F, 0.0244212519F, 0.0250208772F, 0.0256276481F,
  156514. 0.0262415582F, 0.0268626014F, 0.0274907711F, 0.0281260608F,
  156515. 0.0287684638F, 0.0294179736F, 0.0300745833F, 0.0307382859F,
  156516. 0.0314090747F, 0.0320869424F, 0.0327718819F, 0.0334638860F,
  156517. 0.0341629474F, 0.0348690586F, 0.0355822122F, 0.0363024004F,
  156518. 0.0370296157F, 0.0377638502F, 0.0385050960F, 0.0392533451F,
  156519. 0.0400085896F, 0.0407708211F, 0.0415400315F, 0.0423162123F,
  156520. 0.0430993552F, 0.0438894515F, 0.0446864926F, 0.0454904698F,
  156521. 0.0463013742F, 0.0471191969F, 0.0479439288F, 0.0487755607F,
  156522. 0.0496140836F, 0.0504594879F, 0.0513117642F, 0.0521709031F,
  156523. 0.0530368949F, 0.0539097297F, 0.0547893979F, 0.0556758894F,
  156524. 0.0565691941F, 0.0574693019F, 0.0583762026F, 0.0592898858F,
  156525. 0.0602103410F, 0.0611375576F, 0.0620715250F, 0.0630122324F,
  156526. 0.0639596688F, 0.0649138234F, 0.0658746848F, 0.0668422421F,
  156527. 0.0678164838F, 0.0687973985F, 0.0697849746F, 0.0707792005F,
  156528. 0.0717800645F, 0.0727875547F, 0.0738016591F, 0.0748223656F,
  156529. 0.0758496620F, 0.0768835359F, 0.0779239751F, 0.0789709668F,
  156530. 0.0800244985F, 0.0810845574F, 0.0821511306F, 0.0832242052F,
  156531. 0.0843037679F, 0.0853898056F, 0.0864823050F, 0.0875812525F,
  156532. 0.0886866347F, 0.0897984378F, 0.0909166480F, 0.0920412513F,
  156533. 0.0931722338F, 0.0943095813F, 0.0954532795F, 0.0966033140F,
  156534. 0.0977596702F, 0.0989223336F, 0.1000912894F, 0.1012665227F,
  156535. 0.1024480185F, 0.1036357616F, 0.1048297369F, 0.1060299290F,
  156536. 0.1072363224F, 0.1084489014F, 0.1096676504F, 0.1108925534F,
  156537. 0.1121235946F, 0.1133607577F, 0.1146040267F, 0.1158533850F,
  156538. 0.1171088163F, 0.1183703040F, 0.1196378312F, 0.1209113812F,
  156539. 0.1221909370F, 0.1234764815F, 0.1247679974F, 0.1260654674F,
  156540. 0.1273688740F, 0.1286781995F, 0.1299934263F, 0.1313145365F,
  156541. 0.1326415121F, 0.1339743349F, 0.1353129866F, 0.1366574490F,
  156542. 0.1380077035F, 0.1393637315F, 0.1407255141F, 0.1420930325F,
  156543. 0.1434662677F, 0.1448452004F, 0.1462298115F, 0.1476200814F,
  156544. 0.1490159906F, 0.1504175195F, 0.1518246482F, 0.1532373569F,
  156545. 0.1546556253F, 0.1560794333F, 0.1575087606F, 0.1589435866F,
  156546. 0.1603838909F, 0.1618296526F, 0.1632808509F, 0.1647374648F,
  156547. 0.1661994731F, 0.1676668546F, 0.1691395880F, 0.1706176516F,
  156548. 0.1721010238F, 0.1735896829F, 0.1750836068F, 0.1765827736F,
  156549. 0.1780871610F, 0.1795967468F, 0.1811115084F, 0.1826314234F,
  156550. 0.1841564689F, 0.1856866221F, 0.1872218600F, 0.1887621595F,
  156551. 0.1903074974F, 0.1918578503F, 0.1934131947F, 0.1949735068F,
  156552. 0.1965387630F, 0.1981089393F, 0.1996840117F, 0.2012639560F,
  156553. 0.2028487479F, 0.2044383630F, 0.2060327766F, 0.2076319642F,
  156554. 0.2092359007F, 0.2108445614F, 0.2124579211F, 0.2140759545F,
  156555. 0.2156986364F, 0.2173259411F, 0.2189578432F, 0.2205943168F,
  156556. 0.2222353361F, 0.2238808751F, 0.2255309076F, 0.2271854073F,
  156557. 0.2288443480F, 0.2305077030F, 0.2321754457F, 0.2338475493F,
  156558. 0.2355239869F, 0.2372047315F, 0.2388897560F, 0.2405790329F,
  156559. 0.2422725350F, 0.2439702347F, 0.2456721043F, 0.2473781159F,
  156560. 0.2490882418F, 0.2508024539F, 0.2525207240F, 0.2542430237F,
  156561. 0.2559693248F, 0.2576995986F, 0.2594338166F, 0.2611719498F,
  156562. 0.2629139695F, 0.2646598466F, 0.2664095520F, 0.2681630564F,
  156563. 0.2699203304F, 0.2716813445F, 0.2734460691F, 0.2752144744F,
  156564. 0.2769865307F, 0.2787622079F, 0.2805414760F, 0.2823243047F,
  156565. 0.2841106637F, 0.2859005227F, 0.2876938509F, 0.2894906179F,
  156566. 0.2912907928F, 0.2930943447F, 0.2949012426F, 0.2967114554F,
  156567. 0.2985249520F, 0.3003417009F, 0.3021616708F, 0.3039848301F,
  156568. 0.3058111471F, 0.3076405901F, 0.3094731273F, 0.3113087266F,
  156569. 0.3131473560F, 0.3149889833F, 0.3168335762F, 0.3186811024F,
  156570. 0.3205315294F, 0.3223848245F, 0.3242409552F, 0.3260998886F,
  156571. 0.3279615918F, 0.3298260319F, 0.3316931758F, 0.3335629903F,
  156572. 0.3354354423F, 0.3373104982F, 0.3391881247F, 0.3410682882F,
  156573. 0.3429509551F, 0.3448360917F, 0.3467236642F, 0.3486136387F,
  156574. 0.3505059811F, 0.3524006575F, 0.3542976336F, 0.3561968753F,
  156575. 0.3580983482F, 0.3600020179F, 0.3619078499F, 0.3638158096F,
  156576. 0.3657258625F, 0.3676379737F, 0.3695521086F, 0.3714682321F,
  156577. 0.3733863094F, 0.3753063055F, 0.3772281852F, 0.3791519134F,
  156578. 0.3810774548F, 0.3830047742F, 0.3849338362F, 0.3868646053F,
  156579. 0.3887970459F, 0.3907311227F, 0.3926667998F, 0.3946040417F,
  156580. 0.3965428125F, 0.3984830765F, 0.4004247978F, 0.4023679403F,
  156581. 0.4043124683F, 0.4062583455F, 0.4082055359F, 0.4101540034F,
  156582. 0.4121037117F, 0.4140546246F, 0.4160067058F, 0.4179599190F,
  156583. 0.4199142277F, 0.4218695956F, 0.4238259861F, 0.4257833627F,
  156584. 0.4277416888F, 0.4297009279F, 0.4316610433F, 0.4336219983F,
  156585. 0.4355837562F, 0.4375462803F, 0.4395095337F, 0.4414734797F,
  156586. 0.4434380815F, 0.4454033021F, 0.4473691046F, 0.4493354521F,
  156587. 0.4513023078F, 0.4532696345F, 0.4552373954F, 0.4572055533F,
  156588. 0.4591740713F, 0.4611429123F, 0.4631120393F, 0.4650814151F,
  156589. 0.4670510028F, 0.4690207650F, 0.4709906649F, 0.4729606651F,
  156590. 0.4749307287F, 0.4769008185F, 0.4788708972F, 0.4808409279F,
  156591. 0.4828108732F, 0.4847806962F, 0.4867503597F, 0.4887198264F,
  156592. 0.4906890593F, 0.4926580213F, 0.4946266753F, 0.4965949840F,
  156593. 0.4985629105F, 0.5005304176F, 0.5024974683F, 0.5044640255F,
  156594. 0.5064300522F, 0.5083955114F, 0.5103603659F, 0.5123245790F,
  156595. 0.5142881136F, 0.5162509328F, 0.5182129997F, 0.5201742774F,
  156596. 0.5221347290F, 0.5240943178F, 0.5260530070F, 0.5280107598F,
  156597. 0.5299675395F, 0.5319233095F, 0.5338780330F, 0.5358316736F,
  156598. 0.5377841946F, 0.5397355596F, 0.5416857320F, 0.5436346755F,
  156599. 0.5455823538F, 0.5475287304F, 0.5494737691F, 0.5514174337F,
  156600. 0.5533596881F, 0.5553004962F, 0.5572398218F, 0.5591776291F,
  156601. 0.5611138821F, 0.5630485449F, 0.5649815818F, 0.5669129570F,
  156602. 0.5688426349F, 0.5707705799F, 0.5726967564F, 0.5746211290F,
  156603. 0.5765436624F, 0.5784643212F, 0.5803830702F, 0.5822998743F,
  156604. 0.5842146984F, 0.5861275076F, 0.5880382669F, 0.5899469416F,
  156605. 0.5918534968F, 0.5937578981F, 0.5956601107F, 0.5975601004F,
  156606. 0.5994578326F, 0.6013532732F, 0.6032463880F, 0.6051371429F,
  156607. 0.6070255039F, 0.6089114372F, 0.6107949090F, 0.6126758856F,
  156608. 0.6145543334F, 0.6164302191F, 0.6183035092F, 0.6201741706F,
  156609. 0.6220421700F, 0.6239074745F, 0.6257700513F, 0.6276298674F,
  156610. 0.6294868903F, 0.6313410873F, 0.6331924262F, 0.6350408745F,
  156611. 0.6368864001F, 0.6387289710F, 0.6405685552F, 0.6424051209F,
  156612. 0.6442386364F, 0.6460690702F, 0.6478963910F, 0.6497205673F,
  156613. 0.6515415682F, 0.6533593625F, 0.6551739194F, 0.6569852082F,
  156614. 0.6587931984F, 0.6605978593F, 0.6623991609F, 0.6641970728F,
  156615. 0.6659915652F, 0.6677826081F, 0.6695701718F, 0.6713542268F,
  156616. 0.6731347437F, 0.6749116932F, 0.6766850461F, 0.6784547736F,
  156617. 0.6802208469F, 0.6819832374F, 0.6837419164F, 0.6854968559F,
  156618. 0.6872480275F, 0.6889954034F, 0.6907389556F, 0.6924786566F,
  156619. 0.6942144788F, 0.6959463950F, 0.6976743780F, 0.6993984008F,
  156620. 0.7011184365F, 0.7028344587F, 0.7045464407F, 0.7062543564F,
  156621. 0.7079581796F, 0.7096578844F, 0.7113534450F, 0.7130448359F,
  156622. 0.7147320316F, 0.7164150070F, 0.7180937371F, 0.7197681970F,
  156623. 0.7214383620F, 0.7231042077F, 0.7247657098F, 0.7264228443F,
  156624. 0.7280755871F, 0.7297239147F, 0.7313678035F, 0.7330072301F,
  156625. 0.7346421715F, 0.7362726046F, 0.7378985069F, 0.7395198556F,
  156626. 0.7411366285F, 0.7427488034F, 0.7443563584F, 0.7459592717F,
  156627. 0.7475575218F, 0.7491510873F, 0.7507399471F, 0.7523240803F,
  156628. 0.7539034661F, 0.7554780839F, 0.7570479136F, 0.7586129349F,
  156629. 0.7601731279F, 0.7617284730F, 0.7632789506F, 0.7648245416F,
  156630. 0.7663652267F, 0.7679009872F, 0.7694318044F, 0.7709576599F,
  156631. 0.7724785354F, 0.7739944130F, 0.7755052749F, 0.7770111035F,
  156632. 0.7785118815F, 0.7800075916F, 0.7814982170F, 0.7829837410F,
  156633. 0.7844641472F, 0.7859394191F, 0.7874095408F, 0.7888744965F,
  156634. 0.7903342706F, 0.7917888476F, 0.7932382124F, 0.7946823501F,
  156635. 0.7961212460F, 0.7975548855F, 0.7989832544F, 0.8004063386F,
  156636. 0.8018241244F, 0.8032365981F, 0.8046437463F, 0.8060455560F,
  156637. 0.8074420141F, 0.8088331080F, 0.8102188253F, 0.8115991536F,
  156638. 0.8129740810F, 0.8143435957F, 0.8157076861F, 0.8170663409F,
  156639. 0.8184195489F, 0.8197672994F, 0.8211095817F, 0.8224463853F,
  156640. 0.8237777001F, 0.8251035161F, 0.8264238235F, 0.8277386129F,
  156641. 0.8290478750F, 0.8303516008F, 0.8316497814F, 0.8329424083F,
  156642. 0.8342294731F, 0.8355109677F, 0.8367868841F, 0.8380572148F,
  156643. 0.8393219523F, 0.8405810893F, 0.8418346190F, 0.8430825345F,
  156644. 0.8443248294F, 0.8455614974F, 0.8467925323F, 0.8480179285F,
  156645. 0.8492376802F, 0.8504517822F, 0.8516602292F, 0.8528630164F,
  156646. 0.8540601391F, 0.8552515928F, 0.8564373733F, 0.8576174766F,
  156647. 0.8587918990F, 0.8599606368F, 0.8611236868F, 0.8622810460F,
  156648. 0.8634327113F, 0.8645786802F, 0.8657189504F, 0.8668535195F,
  156649. 0.8679823857F, 0.8691055472F, 0.8702230025F, 0.8713347503F,
  156650. 0.8724407896F, 0.8735411194F, 0.8746357394F, 0.8757246489F,
  156651. 0.8768078479F, 0.8778853364F, 0.8789571146F, 0.8800231832F,
  156652. 0.8810835427F, 0.8821381942F, 0.8831871387F, 0.8842303777F,
  156653. 0.8852679127F, 0.8862997456F, 0.8873258784F, 0.8883463132F,
  156654. 0.8893610527F, 0.8903700994F, 0.8913734562F, 0.8923711263F,
  156655. 0.8933631129F, 0.8943494196F, 0.8953300500F, 0.8963050083F,
  156656. 0.8972742985F, 0.8982379249F, 0.8991958922F, 0.9001482052F,
  156657. 0.9010948688F, 0.9020358883F, 0.9029712690F, 0.9039010165F,
  156658. 0.9048251367F, 0.9057436357F, 0.9066565195F, 0.9075637946F,
  156659. 0.9084654678F, 0.9093615456F, 0.9102520353F, 0.9111369440F,
  156660. 0.9120162792F, 0.9128900484F, 0.9137582595F, 0.9146209204F,
  156661. 0.9154780394F, 0.9163296248F, 0.9171756853F, 0.9180162296F,
  156662. 0.9188512667F, 0.9196808057F, 0.9205048559F, 0.9213234270F,
  156663. 0.9221365285F, 0.9229441704F, 0.9237463629F, 0.9245431160F,
  156664. 0.9253344404F, 0.9261203465F, 0.9269008453F, 0.9276759477F,
  156665. 0.9284456648F, 0.9292100080F, 0.9299689889F, 0.9307226190F,
  156666. 0.9314709103F, 0.9322138747F, 0.9329515245F, 0.9336838721F,
  156667. 0.9344109300F, 0.9351327108F, 0.9358492275F, 0.9365604931F,
  156668. 0.9372665208F, 0.9379673239F, 0.9386629160F, 0.9393533107F,
  156669. 0.9400385220F, 0.9407185637F, 0.9413934501F, 0.9420631954F,
  156670. 0.9427278141F, 0.9433873208F, 0.9440417304F, 0.9446910576F,
  156671. 0.9453353176F, 0.9459745255F, 0.9466086968F, 0.9472378469F,
  156672. 0.9478619915F, 0.9484811463F, 0.9490953274F, 0.9497045506F,
  156673. 0.9503088323F, 0.9509081888F, 0.9515026365F, 0.9520921921F,
  156674. 0.9526768723F, 0.9532566940F, 0.9538316742F, 0.9544018300F,
  156675. 0.9549671786F, 0.9555277375F, 0.9560835241F, 0.9566345562F,
  156676. 0.9571808513F, 0.9577224275F, 0.9582593027F, 0.9587914949F,
  156677. 0.9593190225F, 0.9598419038F, 0.9603601571F, 0.9608738012F,
  156678. 0.9613828546F, 0.9618873361F, 0.9623872646F, 0.9628826591F,
  156679. 0.9633735388F, 0.9638599227F, 0.9643418303F, 0.9648192808F,
  156680. 0.9652922939F, 0.9657608890F, 0.9662250860F, 0.9666849046F,
  156681. 0.9671403646F, 0.9675914861F, 0.9680382891F, 0.9684807937F,
  156682. 0.9689190202F, 0.9693529890F, 0.9697827203F, 0.9702082347F,
  156683. 0.9706295529F, 0.9710466953F, 0.9714596828F, 0.9718685362F,
  156684. 0.9722732762F, 0.9726739240F, 0.9730705005F, 0.9734630267F,
  156685. 0.9738515239F, 0.9742360134F, 0.9746165163F, 0.9749930540F,
  156686. 0.9753656481F, 0.9757343198F, 0.9760990909F, 0.9764599829F,
  156687. 0.9768170175F, 0.9771702164F, 0.9775196013F, 0.9778651941F,
  156688. 0.9782070167F, 0.9785450909F, 0.9788794388F, 0.9792100824F,
  156689. 0.9795370437F, 0.9798603449F, 0.9801800080F, 0.9804960554F,
  156690. 0.9808085092F, 0.9811173916F, 0.9814227251F, 0.9817245318F,
  156691. 0.9820228343F, 0.9823176549F, 0.9826090160F, 0.9828969402F,
  156692. 0.9831814498F, 0.9834625674F, 0.9837403156F, 0.9840147169F,
  156693. 0.9842857939F, 0.9845535692F, 0.9848180654F, 0.9850793052F,
  156694. 0.9853373113F, 0.9855921062F, 0.9858437127F, 0.9860921535F,
  156695. 0.9863374512F, 0.9865796287F, 0.9868187085F, 0.9870547136F,
  156696. 0.9872876664F, 0.9875175899F, 0.9877445067F, 0.9879684396F,
  156697. 0.9881894112F, 0.9884074444F, 0.9886225619F, 0.9888347863F,
  156698. 0.9890441404F, 0.9892506468F, 0.9894543284F, 0.9896552077F,
  156699. 0.9898533074F, 0.9900486502F, 0.9902412587F, 0.9904311555F,
  156700. 0.9906183633F, 0.9908029045F, 0.9909848019F, 0.9911640779F,
  156701. 0.9913407550F, 0.9915148557F, 0.9916864025F, 0.9918554179F,
  156702. 0.9920219241F, 0.9921859437F, 0.9923474989F, 0.9925066120F,
  156703. 0.9926633054F, 0.9928176012F, 0.9929695218F, 0.9931190891F,
  156704. 0.9932663254F, 0.9934112527F, 0.9935538932F, 0.9936942686F,
  156705. 0.9938324012F, 0.9939683126F, 0.9941020248F, 0.9942335597F,
  156706. 0.9943629388F, 0.9944901841F, 0.9946153170F, 0.9947383593F,
  156707. 0.9948593325F, 0.9949782579F, 0.9950951572F, 0.9952100516F,
  156708. 0.9953229625F, 0.9954339111F, 0.9955429186F, 0.9956500062F,
  156709. 0.9957551948F, 0.9958585056F, 0.9959599593F, 0.9960595769F,
  156710. 0.9961573792F, 0.9962533869F, 0.9963476206F, 0.9964401009F,
  156711. 0.9965308483F, 0.9966198833F, 0.9967072261F, 0.9967928971F,
  156712. 0.9968769164F, 0.9969593041F, 0.9970400804F, 0.9971192651F,
  156713. 0.9971968781F, 0.9972729391F, 0.9973474680F, 0.9974204842F,
  156714. 0.9974920074F, 0.9975620569F, 0.9976306521F, 0.9976978122F,
  156715. 0.9977635565F, 0.9978279039F, 0.9978908736F, 0.9979524842F,
  156716. 0.9980127547F, 0.9980717037F, 0.9981293499F, 0.9981857116F,
  156717. 0.9982408073F, 0.9982946554F, 0.9983472739F, 0.9983986810F,
  156718. 0.9984488947F, 0.9984979328F, 0.9985458132F, 0.9985925534F,
  156719. 0.9986381711F, 0.9986826838F, 0.9987261086F, 0.9987684630F,
  156720. 0.9988097640F, 0.9988500286F, 0.9988892738F, 0.9989275163F,
  156721. 0.9989647727F, 0.9990010597F, 0.9990363938F, 0.9990707911F,
  156722. 0.9991042679F, 0.9991368404F, 0.9991685244F, 0.9991993358F,
  156723. 0.9992292905F, 0.9992584038F, 0.9992866914F, 0.9993141686F,
  156724. 0.9993408506F, 0.9993667526F, 0.9993918895F, 0.9994162761F,
  156725. 0.9994399273F, 0.9994628576F, 0.9994850815F, 0.9995066133F,
  156726. 0.9995274672F, 0.9995476574F, 0.9995671978F, 0.9995861021F,
  156727. 0.9996043841F, 0.9996220573F, 0.9996391352F, 0.9996556310F,
  156728. 0.9996715579F, 0.9996869288F, 0.9997017568F, 0.9997160543F,
  156729. 0.9997298342F, 0.9997431088F, 0.9997558905F, 0.9997681914F,
  156730. 0.9997800236F, 0.9997913990F, 0.9998023292F, 0.9998128261F,
  156731. 0.9998229009F, 0.9998325650F, 0.9998418296F, 0.9998507058F,
  156732. 0.9998592044F, 0.9998673362F, 0.9998751117F, 0.9998825415F,
  156733. 0.9998896358F, 0.9998964047F, 0.9999028584F, 0.9999090066F,
  156734. 0.9999148590F, 0.9999204253F, 0.9999257148F, 0.9999307368F,
  156735. 0.9999355003F, 0.9999400144F, 0.9999442878F, 0.9999483293F,
  156736. 0.9999521472F, 0.9999557499F, 0.9999591457F, 0.9999623426F,
  156737. 0.9999653483F, 0.9999681708F, 0.9999708175F, 0.9999732959F,
  156738. 0.9999756132F, 0.9999777765F, 0.9999797928F, 0.9999816688F,
  156739. 0.9999834113F, 0.9999850266F, 0.9999865211F, 0.9999879009F,
  156740. 0.9999891721F, 0.9999903405F, 0.9999914118F, 0.9999923914F,
  156741. 0.9999932849F, 0.9999940972F, 0.9999948336F, 0.9999954989F,
  156742. 0.9999960978F, 0.9999966349F, 0.9999971146F, 0.9999975411F,
  156743. 0.9999979185F, 0.9999982507F, 0.9999985414F, 0.9999987944F,
  156744. 0.9999990129F, 0.9999992003F, 0.9999993596F, 0.9999994939F,
  156745. 0.9999996059F, 0.9999996981F, 0.9999997732F, 0.9999998333F,
  156746. 0.9999998805F, 0.9999999170F, 0.9999999444F, 0.9999999643F,
  156747. 0.9999999784F, 0.9999999878F, 0.9999999937F, 0.9999999972F,
  156748. 0.9999999990F, 0.9999999997F, 1.0000000000F, 1.0000000000F,
  156749. };
  156750. static float vwin4096[2048] = {
  156751. 0.0000002310F, 0.0000020791F, 0.0000057754F, 0.0000113197F,
  156752. 0.0000187121F, 0.0000279526F, 0.0000390412F, 0.0000519777F,
  156753. 0.0000667623F, 0.0000833949F, 0.0001018753F, 0.0001222036F,
  156754. 0.0001443798F, 0.0001684037F, 0.0001942754F, 0.0002219947F,
  156755. 0.0002515616F, 0.0002829761F, 0.0003162380F, 0.0003513472F,
  156756. 0.0003883038F, 0.0004271076F, 0.0004677584F, 0.0005102563F,
  156757. 0.0005546011F, 0.0006007928F, 0.0006488311F, 0.0006987160F,
  156758. 0.0007504474F, 0.0008040251F, 0.0008594490F, 0.0009167191F,
  156759. 0.0009758351F, 0.0010367969F, 0.0010996044F, 0.0011642574F,
  156760. 0.0012307558F, 0.0012990994F, 0.0013692880F, 0.0014413216F,
  156761. 0.0015151998F, 0.0015909226F, 0.0016684898F, 0.0017479011F,
  156762. 0.0018291565F, 0.0019122556F, 0.0019971983F, 0.0020839845F,
  156763. 0.0021726138F, 0.0022630861F, 0.0023554012F, 0.0024495588F,
  156764. 0.0025455588F, 0.0026434008F, 0.0027430847F, 0.0028446103F,
  156765. 0.0029479772F, 0.0030531853F, 0.0031602342F, 0.0032691238F,
  156766. 0.0033798538F, 0.0034924239F, 0.0036068338F, 0.0037230833F,
  156767. 0.0038411721F, 0.0039610999F, 0.0040828664F, 0.0042064714F,
  156768. 0.0043319145F, 0.0044591954F, 0.0045883139F, 0.0047192696F,
  156769. 0.0048520622F, 0.0049866914F, 0.0051231569F, 0.0052614583F,
  156770. 0.0054015953F, 0.0055435676F, 0.0056873748F, 0.0058330166F,
  156771. 0.0059804926F, 0.0061298026F, 0.0062809460F, 0.0064339226F,
  156772. 0.0065887320F, 0.0067453738F, 0.0069038476F, 0.0070641531F,
  156773. 0.0072262899F, 0.0073902575F, 0.0075560556F, 0.0077236838F,
  156774. 0.0078931417F, 0.0080644288F, 0.0082375447F, 0.0084124891F,
  156775. 0.0085892615F, 0.0087678614F, 0.0089482885F, 0.0091305422F,
  156776. 0.0093146223F, 0.0095005281F, 0.0096882592F, 0.0098778153F,
  156777. 0.0100691958F, 0.0102624002F, 0.0104574281F, 0.0106542791F,
  156778. 0.0108529525F, 0.0110534480F, 0.0112557651F, 0.0114599032F,
  156779. 0.0116658618F, 0.0118736405F, 0.0120832387F, 0.0122946560F,
  156780. 0.0125078917F, 0.0127229454F, 0.0129398166F, 0.0131585046F,
  156781. 0.0133790090F, 0.0136013292F, 0.0138254647F, 0.0140514149F,
  156782. 0.0142791792F, 0.0145087572F, 0.0147401481F, 0.0149733515F,
  156783. 0.0152083667F, 0.0154451932F, 0.0156838304F, 0.0159242777F,
  156784. 0.0161665345F, 0.0164106001F, 0.0166564741F, 0.0169041557F,
  156785. 0.0171536443F, 0.0174049393F, 0.0176580401F, 0.0179129461F,
  156786. 0.0181696565F, 0.0184281708F, 0.0186884883F, 0.0189506084F,
  156787. 0.0192145303F, 0.0194802535F, 0.0197477772F, 0.0200171008F,
  156788. 0.0202882236F, 0.0205611449F, 0.0208358639F, 0.0211123801F,
  156789. 0.0213906927F, 0.0216708011F, 0.0219527043F, 0.0222364019F,
  156790. 0.0225218930F, 0.0228091769F, 0.0230982529F, 0.0233891203F,
  156791. 0.0236817782F, 0.0239762259F, 0.0242724628F, 0.0245704880F,
  156792. 0.0248703007F, 0.0251719002F, 0.0254752858F, 0.0257804565F,
  156793. 0.0260874117F, 0.0263961506F, 0.0267066722F, 0.0270189760F,
  156794. 0.0273330609F, 0.0276489263F, 0.0279665712F, 0.0282859949F,
  156795. 0.0286071966F, 0.0289301753F, 0.0292549303F, 0.0295814607F,
  156796. 0.0299097656F, 0.0302398442F, 0.0305716957F, 0.0309053191F,
  156797. 0.0312407135F, 0.0315778782F, 0.0319168122F, 0.0322575145F,
  156798. 0.0325999844F, 0.0329442209F, 0.0332902231F, 0.0336379900F,
  156799. 0.0339875208F, 0.0343388146F, 0.0346918703F, 0.0350466871F,
  156800. 0.0354032640F, 0.0357616000F, 0.0361216943F, 0.0364835458F,
  156801. 0.0368471535F, 0.0372125166F, 0.0375796339F, 0.0379485046F,
  156802. 0.0383191276F, 0.0386915020F, 0.0390656267F, 0.0394415008F,
  156803. 0.0398191231F, 0.0401984927F, 0.0405796086F, 0.0409624698F,
  156804. 0.0413470751F, 0.0417334235F, 0.0421215141F, 0.0425113457F,
  156805. 0.0429029172F, 0.0432962277F, 0.0436912760F, 0.0440880610F,
  156806. 0.0444865817F, 0.0448868370F, 0.0452888257F, 0.0456925468F,
  156807. 0.0460979992F, 0.0465051816F, 0.0469140931F, 0.0473247325F,
  156808. 0.0477370986F, 0.0481511902F, 0.0485670064F, 0.0489845458F,
  156809. 0.0494038074F, 0.0498247899F, 0.0502474922F, 0.0506719131F,
  156810. 0.0510980514F, 0.0515259060F, 0.0519554756F, 0.0523867590F,
  156811. 0.0528197550F, 0.0532544624F, 0.0536908800F, 0.0541290066F,
  156812. 0.0545688408F, 0.0550103815F, 0.0554536274F, 0.0558985772F,
  156813. 0.0563452297F, 0.0567935837F, 0.0572436377F, 0.0576953907F,
  156814. 0.0581488412F, 0.0586039880F, 0.0590608297F, 0.0595193651F,
  156815. 0.0599795929F, 0.0604415117F, 0.0609051202F, 0.0613704170F,
  156816. 0.0618374009F, 0.0623060704F, 0.0627764243F, 0.0632484611F,
  156817. 0.0637221795F, 0.0641975781F, 0.0646746555F, 0.0651534104F,
  156818. 0.0656338413F, 0.0661159469F, 0.0665997257F, 0.0670851763F,
  156819. 0.0675722973F, 0.0680610873F, 0.0685515448F, 0.0690436684F,
  156820. 0.0695374567F, 0.0700329081F, 0.0705300213F, 0.0710287947F,
  156821. 0.0715292269F, 0.0720313163F, 0.0725350616F, 0.0730404612F,
  156822. 0.0735475136F, 0.0740562172F, 0.0745665707F, 0.0750785723F,
  156823. 0.0755922207F, 0.0761075143F, 0.0766244515F, 0.0771430307F,
  156824. 0.0776632505F, 0.0781851092F, 0.0787086052F, 0.0792337371F,
  156825. 0.0797605032F, 0.0802889018F, 0.0808189315F, 0.0813505905F,
  156826. 0.0818838773F, 0.0824187903F, 0.0829553277F, 0.0834934881F,
  156827. 0.0840332697F, 0.0845746708F, 0.0851176899F, 0.0856623252F,
  156828. 0.0862085751F, 0.0867564379F, 0.0873059119F, 0.0878569954F,
  156829. 0.0884096867F, 0.0889639840F, 0.0895198858F, 0.0900773902F,
  156830. 0.0906364955F, 0.0911972000F, 0.0917595019F, 0.0923233995F,
  156831. 0.0928888909F, 0.0934559745F, 0.0940246485F, 0.0945949110F,
  156832. 0.0951667604F, 0.0957401946F, 0.0963152121F, 0.0968918109F,
  156833. 0.0974699893F, 0.0980497454F, 0.0986310773F, 0.0992139832F,
  156834. 0.0997984614F, 0.1003845098F, 0.1009721267F, 0.1015613101F,
  156835. 0.1021520582F, 0.1027443692F, 0.1033382410F, 0.1039336718F,
  156836. 0.1045306597F, 0.1051292027F, 0.1057292990F, 0.1063309466F,
  156837. 0.1069341435F, 0.1075388878F, 0.1081451776F, 0.1087530108F,
  156838. 0.1093623856F, 0.1099732998F, 0.1105857516F, 0.1111997389F,
  156839. 0.1118152597F, 0.1124323121F, 0.1130508939F, 0.1136710032F,
  156840. 0.1142926379F, 0.1149157960F, 0.1155404755F, 0.1161666742F,
  156841. 0.1167943901F, 0.1174236211F, 0.1180543652F, 0.1186866202F,
  156842. 0.1193203841F, 0.1199556548F, 0.1205924300F, 0.1212307078F,
  156843. 0.1218704860F, 0.1225117624F, 0.1231545349F, 0.1237988013F,
  156844. 0.1244445596F, 0.1250918074F, 0.1257405427F, 0.1263907632F,
  156845. 0.1270424667F, 0.1276956512F, 0.1283503142F, 0.1290064537F,
  156846. 0.1296640674F, 0.1303231530F, 0.1309837084F, 0.1316457312F,
  156847. 0.1323092193F, 0.1329741703F, 0.1336405820F, 0.1343084520F,
  156848. 0.1349777782F, 0.1356485582F, 0.1363207897F, 0.1369944704F,
  156849. 0.1376695979F, 0.1383461700F, 0.1390241842F, 0.1397036384F,
  156850. 0.1403845300F, 0.1410668567F, 0.1417506162F, 0.1424358061F,
  156851. 0.1431224240F, 0.1438104674F, 0.1444999341F, 0.1451908216F,
  156852. 0.1458831274F, 0.1465768492F, 0.1472719844F, 0.1479685308F,
  156853. 0.1486664857F, 0.1493658468F, 0.1500666115F, 0.1507687775F,
  156854. 0.1514723422F, 0.1521773031F, 0.1528836577F, 0.1535914035F,
  156855. 0.1543005380F, 0.1550110587F, 0.1557229631F, 0.1564362485F,
  156856. 0.1571509124F, 0.1578669524F, 0.1585843657F, 0.1593031499F,
  156857. 0.1600233024F, 0.1607448205F, 0.1614677017F, 0.1621919433F,
  156858. 0.1629175428F, 0.1636444975F, 0.1643728047F, 0.1651024619F,
  156859. 0.1658334665F, 0.1665658156F, 0.1672995067F, 0.1680345371F,
  156860. 0.1687709041F, 0.1695086050F, 0.1702476372F, 0.1709879978F,
  156861. 0.1717296843F, 0.1724726938F, 0.1732170237F, 0.1739626711F,
  156862. 0.1747096335F, 0.1754579079F, 0.1762074916F, 0.1769583819F,
  156863. 0.1777105760F, 0.1784640710F, 0.1792188642F, 0.1799749529F,
  156864. 0.1807323340F, 0.1814910049F, 0.1822509628F, 0.1830122046F,
  156865. 0.1837747277F, 0.1845385292F, 0.1853036062F, 0.1860699558F,
  156866. 0.1868375751F, 0.1876064613F, 0.1883766114F, 0.1891480226F,
  156867. 0.1899206919F, 0.1906946164F, 0.1914697932F, 0.1922462194F,
  156868. 0.1930238919F, 0.1938028079F, 0.1945829643F, 0.1953643583F,
  156869. 0.1961469868F, 0.1969308468F, 0.1977159353F, 0.1985022494F,
  156870. 0.1992897859F, 0.2000785420F, 0.2008685145F, 0.2016597005F,
  156871. 0.2024520968F, 0.2032457005F, 0.2040405084F, 0.2048365175F,
  156872. 0.2056337247F, 0.2064321269F, 0.2072317211F, 0.2080325041F,
  156873. 0.2088344727F, 0.2096376240F, 0.2104419547F, 0.2112474618F,
  156874. 0.2120541420F, 0.2128619923F, 0.2136710094F, 0.2144811902F,
  156875. 0.2152925315F, 0.2161050301F, 0.2169186829F, 0.2177334866F,
  156876. 0.2185494381F, 0.2193665340F, 0.2201847712F, 0.2210041465F,
  156877. 0.2218246565F, 0.2226462981F, 0.2234690680F, 0.2242929629F,
  156878. 0.2251179796F, 0.2259441147F, 0.2267713650F, 0.2275997272F,
  156879. 0.2284291979F, 0.2292597739F, 0.2300914518F, 0.2309242283F,
  156880. 0.2317581001F, 0.2325930638F, 0.2334291160F, 0.2342662534F,
  156881. 0.2351044727F, 0.2359437703F, 0.2367841431F, 0.2376255875F,
  156882. 0.2384681001F, 0.2393116776F, 0.2401563165F, 0.2410020134F,
  156883. 0.2418487649F, 0.2426965675F, 0.2435454178F, 0.2443953122F,
  156884. 0.2452462474F, 0.2460982199F, 0.2469512262F, 0.2478052628F,
  156885. 0.2486603262F, 0.2495164129F, 0.2503735194F, 0.2512316421F,
  156886. 0.2520907776F, 0.2529509222F, 0.2538120726F, 0.2546742250F,
  156887. 0.2555373760F, 0.2564015219F, 0.2572666593F, 0.2581327845F,
  156888. 0.2589998939F, 0.2598679840F, 0.2607370510F, 0.2616070916F,
  156889. 0.2624781019F, 0.2633500783F, 0.2642230173F, 0.2650969152F,
  156890. 0.2659717684F, 0.2668475731F, 0.2677243257F, 0.2686020226F,
  156891. 0.2694806601F, 0.2703602344F, 0.2712407419F, 0.2721221789F,
  156892. 0.2730045417F, 0.2738878265F, 0.2747720297F, 0.2756571474F,
  156893. 0.2765431760F, 0.2774301117F, 0.2783179508F, 0.2792066895F,
  156894. 0.2800963240F, 0.2809868505F, 0.2818782654F, 0.2827705647F,
  156895. 0.2836637447F, 0.2845578016F, 0.2854527315F, 0.2863485307F,
  156896. 0.2872451953F, 0.2881427215F, 0.2890411055F, 0.2899403433F,
  156897. 0.2908404312F, 0.2917413654F, 0.2926431418F, 0.2935457567F,
  156898. 0.2944492061F, 0.2953534863F, 0.2962585932F, 0.2971645230F,
  156899. 0.2980712717F, 0.2989788356F, 0.2998872105F, 0.3007963927F,
  156900. 0.3017063781F, 0.3026171629F, 0.3035287430F, 0.3044411145F,
  156901. 0.3053542736F, 0.3062682161F, 0.3071829381F, 0.3080984356F,
  156902. 0.3090147047F, 0.3099317413F, 0.3108495414F, 0.3117681011F,
  156903. 0.3126874163F, 0.3136074830F, 0.3145282972F, 0.3154498548F,
  156904. 0.3163721517F, 0.3172951841F, 0.3182189477F, 0.3191434385F,
  156905. 0.3200686525F, 0.3209945856F, 0.3219212336F, 0.3228485927F,
  156906. 0.3237766585F, 0.3247054271F, 0.3256348943F, 0.3265650560F,
  156907. 0.3274959081F, 0.3284274465F, 0.3293596671F, 0.3302925657F,
  156908. 0.3312261382F, 0.3321603804F, 0.3330952882F, 0.3340308574F,
  156909. 0.3349670838F, 0.3359039634F, 0.3368414919F, 0.3377796651F,
  156910. 0.3387184789F, 0.3396579290F, 0.3405980113F, 0.3415387216F,
  156911. 0.3424800556F, 0.3434220091F, 0.3443645779F, 0.3453077578F,
  156912. 0.3462515446F, 0.3471959340F, 0.3481409217F, 0.3490865036F,
  156913. 0.3500326754F, 0.3509794328F, 0.3519267715F, 0.3528746873F,
  156914. 0.3538231759F, 0.3547722330F, 0.3557218544F, 0.3566720357F,
  156915. 0.3576227727F, 0.3585740610F, 0.3595258964F, 0.3604782745F,
  156916. 0.3614311910F, 0.3623846417F, 0.3633386221F, 0.3642931280F,
  156917. 0.3652481549F, 0.3662036987F, 0.3671597548F, 0.3681163191F,
  156918. 0.3690733870F, 0.3700309544F, 0.3709890167F, 0.3719475696F,
  156919. 0.3729066089F, 0.3738661299F, 0.3748261285F, 0.3757866002F,
  156920. 0.3767475406F, 0.3777089453F, 0.3786708100F, 0.3796331302F,
  156921. 0.3805959014F, 0.3815591194F, 0.3825227796F, 0.3834868777F,
  156922. 0.3844514093F, 0.3854163698F, 0.3863817549F, 0.3873475601F,
  156923. 0.3883137810F, 0.3892804131F, 0.3902474521F, 0.3912148933F,
  156924. 0.3921827325F, 0.3931509650F, 0.3941195865F, 0.3950885925F,
  156925. 0.3960579785F, 0.3970277400F, 0.3979978725F, 0.3989683716F,
  156926. 0.3999392328F, 0.4009104516F, 0.4018820234F, 0.4028539438F,
  156927. 0.4038262084F, 0.4047988125F, 0.4057717516F, 0.4067450214F,
  156928. 0.4077186172F, 0.4086925345F, 0.4096667688F, 0.4106413155F,
  156929. 0.4116161703F, 0.4125913284F, 0.4135667854F, 0.4145425368F,
  156930. 0.4155185780F, 0.4164949044F, 0.4174715116F, 0.4184483949F,
  156931. 0.4194255498F, 0.4204029718F, 0.4213806563F, 0.4223585987F,
  156932. 0.4233367946F, 0.4243152392F, 0.4252939281F, 0.4262728566F,
  156933. 0.4272520202F, 0.4282314144F, 0.4292110345F, 0.4301908760F,
  156934. 0.4311709343F, 0.4321512047F, 0.4331316828F, 0.4341123639F,
  156935. 0.4350932435F, 0.4360743168F, 0.4370555794F, 0.4380370267F,
  156936. 0.4390186540F, 0.4400004567F, 0.4409824303F, 0.4419645701F,
  156937. 0.4429468716F, 0.4439293300F, 0.4449119409F, 0.4458946996F,
  156938. 0.4468776014F, 0.4478606418F, 0.4488438162F, 0.4498271199F,
  156939. 0.4508105483F, 0.4517940967F, 0.4527777607F, 0.4537615355F,
  156940. 0.4547454165F, 0.4557293991F, 0.4567134786F, 0.4576976505F,
  156941. 0.4586819101F, 0.4596662527F, 0.4606506738F, 0.4616351687F,
  156942. 0.4626197328F, 0.4636043614F, 0.4645890499F, 0.4655737936F,
  156943. 0.4665585880F, 0.4675434284F, 0.4685283101F, 0.4695132286F,
  156944. 0.4704981791F, 0.4714831570F, 0.4724681577F, 0.4734531766F,
  156945. 0.4744382089F, 0.4754232501F, 0.4764082956F, 0.4773933406F,
  156946. 0.4783783806F, 0.4793634108F, 0.4803484267F, 0.4813334237F,
  156947. 0.4823183969F, 0.4833033419F, 0.4842882540F, 0.4852731285F,
  156948. 0.4862579608F, 0.4872427462F, 0.4882274802F, 0.4892121580F,
  156949. 0.4901967751F, 0.4911813267F, 0.4921658083F, 0.4931502151F,
  156950. 0.4941345427F, 0.4951187863F, 0.4961029412F, 0.4970870029F,
  156951. 0.4980709667F, 0.4990548280F, 0.5000385822F, 0.5010222245F,
  156952. 0.5020057505F, 0.5029891553F, 0.5039724345F, 0.5049555834F,
  156953. 0.5059385973F, 0.5069214716F, 0.5079042018F, 0.5088867831F,
  156954. 0.5098692110F, 0.5108514808F, 0.5118335879F, 0.5128155277F,
  156955. 0.5137972956F, 0.5147788869F, 0.5157602971F, 0.5167415215F,
  156956. 0.5177225555F, 0.5187033945F, 0.5196840339F, 0.5206644692F,
  156957. 0.5216446956F, 0.5226247086F, 0.5236045035F, 0.5245840759F,
  156958. 0.5255634211F, 0.5265425344F, 0.5275214114F, 0.5285000474F,
  156959. 0.5294784378F, 0.5304565781F, 0.5314344637F, 0.5324120899F,
  156960. 0.5333894522F, 0.5343665461F, 0.5353433670F, 0.5363199102F,
  156961. 0.5372961713F, 0.5382721457F, 0.5392478287F, 0.5402232159F,
  156962. 0.5411983027F, 0.5421730845F, 0.5431475569F, 0.5441217151F,
  156963. 0.5450955548F, 0.5460690714F, 0.5470422602F, 0.5480151169F,
  156964. 0.5489876368F, 0.5499598155F, 0.5509316484F, 0.5519031310F,
  156965. 0.5528742587F, 0.5538450271F, 0.5548154317F, 0.5557854680F,
  156966. 0.5567551314F, 0.5577244174F, 0.5586933216F, 0.5596618395F,
  156967. 0.5606299665F, 0.5615976983F, 0.5625650302F, 0.5635319580F,
  156968. 0.5644984770F, 0.5654645828F, 0.5664302709F, 0.5673955370F,
  156969. 0.5683603765F, 0.5693247850F, 0.5702887580F, 0.5712522912F,
  156970. 0.5722153800F, 0.5731780200F, 0.5741402069F, 0.5751019362F,
  156971. 0.5760632034F, 0.5770240042F, 0.5779843341F, 0.5789441889F,
  156972. 0.5799035639F, 0.5808624549F, 0.5818208575F, 0.5827787673F,
  156973. 0.5837361800F, 0.5846930910F, 0.5856494961F, 0.5866053910F,
  156974. 0.5875607712F, 0.5885156324F, 0.5894699703F, 0.5904237804F,
  156975. 0.5913770586F, 0.5923298004F, 0.5932820016F, 0.5942336578F,
  156976. 0.5951847646F, 0.5961353179F, 0.5970853132F, 0.5980347464F,
  156977. 0.5989836131F, 0.5999319090F, 0.6008796298F, 0.6018267713F,
  156978. 0.6027733292F, 0.6037192993F, 0.6046646773F, 0.6056094589F,
  156979. 0.6065536400F, 0.6074972162F, 0.6084401833F, 0.6093825372F,
  156980. 0.6103242736F, 0.6112653884F, 0.6122058772F, 0.6131457359F,
  156981. 0.6140849604F, 0.6150235464F, 0.6159614897F, 0.6168987862F,
  156982. 0.6178354318F, 0.6187714223F, 0.6197067535F, 0.6206414213F,
  156983. 0.6215754215F, 0.6225087501F, 0.6234414028F, 0.6243733757F,
  156984. 0.6253046646F, 0.6262352654F, 0.6271651739F, 0.6280943862F,
  156985. 0.6290228982F, 0.6299507057F, 0.6308778048F, 0.6318041913F,
  156986. 0.6327298612F, 0.6336548105F, 0.6345790352F, 0.6355025312F,
  156987. 0.6364252945F, 0.6373473211F, 0.6382686070F, 0.6391891483F,
  156988. 0.6401089409F, 0.6410279808F, 0.6419462642F, 0.6428637869F,
  156989. 0.6437805452F, 0.6446965350F, 0.6456117524F, 0.6465261935F,
  156990. 0.6474398544F, 0.6483527311F, 0.6492648197F, 0.6501761165F,
  156991. 0.6510866174F, 0.6519963186F, 0.6529052162F, 0.6538133064F,
  156992. 0.6547205854F, 0.6556270492F, 0.6565326941F, 0.6574375162F,
  156993. 0.6583415117F, 0.6592446769F, 0.6601470079F, 0.6610485009F,
  156994. 0.6619491521F, 0.6628489578F, 0.6637479143F, 0.6646460177F,
  156995. 0.6655432643F, 0.6664396505F, 0.6673351724F, 0.6682298264F,
  156996. 0.6691236087F, 0.6700165157F, 0.6709085436F, 0.6717996889F,
  156997. 0.6726899478F, 0.6735793167F, 0.6744677918F, 0.6753553697F,
  156998. 0.6762420466F, 0.6771278190F, 0.6780126832F, 0.6788966357F,
  156999. 0.6797796728F, 0.6806617909F, 0.6815429866F, 0.6824232562F,
  157000. 0.6833025961F, 0.6841810030F, 0.6850584731F, 0.6859350031F,
  157001. 0.6868105894F, 0.6876852284F, 0.6885589168F, 0.6894316510F,
  157002. 0.6903034275F, 0.6911742430F, 0.6920440939F, 0.6929129769F,
  157003. 0.6937808884F, 0.6946478251F, 0.6955137837F, 0.6963787606F,
  157004. 0.6972427525F, 0.6981057560F, 0.6989677678F, 0.6998287845F,
  157005. 0.7006888028F, 0.7015478194F, 0.7024058309F, 0.7032628340F,
  157006. 0.7041188254F, 0.7049738019F, 0.7058277601F, 0.7066806969F,
  157007. 0.7075326089F, 0.7083834929F, 0.7092333457F, 0.7100821640F,
  157008. 0.7109299447F, 0.7117766846F, 0.7126223804F, 0.7134670291F,
  157009. 0.7143106273F, 0.7151531721F, 0.7159946602F, 0.7168350885F,
  157010. 0.7176744539F, 0.7185127534F, 0.7193499837F, 0.7201861418F,
  157011. 0.7210212247F, 0.7218552293F, 0.7226881526F, 0.7235199914F,
  157012. 0.7243507428F, 0.7251804039F, 0.7260089715F, 0.7268364426F,
  157013. 0.7276628144F, 0.7284880839F, 0.7293122481F, 0.7301353040F,
  157014. 0.7309572487F, 0.7317780794F, 0.7325977930F, 0.7334163868F,
  157015. 0.7342338579F, 0.7350502033F, 0.7358654202F, 0.7366795059F,
  157016. 0.7374924573F, 0.7383042718F, 0.7391149465F, 0.7399244787F,
  157017. 0.7407328655F, 0.7415401041F, 0.7423461920F, 0.7431511261F,
  157018. 0.7439549040F, 0.7447575227F, 0.7455589797F, 0.7463592723F,
  157019. 0.7471583976F, 0.7479563532F, 0.7487531363F, 0.7495487443F,
  157020. 0.7503431745F, 0.7511364244F, 0.7519284913F, 0.7527193726F,
  157021. 0.7535090658F, 0.7542975683F, 0.7550848776F, 0.7558709910F,
  157022. 0.7566559062F, 0.7574396205F, 0.7582221314F, 0.7590034366F,
  157023. 0.7597835334F, 0.7605624194F, 0.7613400923F, 0.7621165495F,
  157024. 0.7628917886F, 0.7636658072F, 0.7644386030F, 0.7652101735F,
  157025. 0.7659805164F, 0.7667496292F, 0.7675175098F, 0.7682841556F,
  157026. 0.7690495645F, 0.7698137341F, 0.7705766622F, 0.7713383463F,
  157027. 0.7720987844F, 0.7728579741F, 0.7736159132F, 0.7743725994F,
  157028. 0.7751280306F, 0.7758822046F, 0.7766351192F, 0.7773867722F,
  157029. 0.7781371614F, 0.7788862848F, 0.7796341401F, 0.7803807253F,
  157030. 0.7811260383F, 0.7818700769F, 0.7826128392F, 0.7833543230F,
  157031. 0.7840945263F, 0.7848334471F, 0.7855710833F, 0.7863074330F,
  157032. 0.7870424941F, 0.7877762647F, 0.7885087428F, 0.7892399264F,
  157033. 0.7899698137F, 0.7906984026F, 0.7914256914F, 0.7921516780F,
  157034. 0.7928763607F, 0.7935997375F, 0.7943218065F, 0.7950425661F,
  157035. 0.7957620142F, 0.7964801492F, 0.7971969692F, 0.7979124724F,
  157036. 0.7986266570F, 0.7993395214F, 0.8000510638F, 0.8007612823F,
  157037. 0.8014701754F, 0.8021777413F, 0.8028839784F, 0.8035888849F,
  157038. 0.8042924592F, 0.8049946997F, 0.8056956048F, 0.8063951727F,
  157039. 0.8070934020F, 0.8077902910F, 0.8084858381F, 0.8091800419F,
  157040. 0.8098729007F, 0.8105644130F, 0.8112545774F, 0.8119433922F,
  157041. 0.8126308561F, 0.8133169676F, 0.8140017251F, 0.8146851272F,
  157042. 0.8153671726F, 0.8160478598F, 0.8167271874F, 0.8174051539F,
  157043. 0.8180817582F, 0.8187569986F, 0.8194308741F, 0.8201033831F,
  157044. 0.8207745244F, 0.8214442966F, 0.8221126986F, 0.8227797290F,
  157045. 0.8234453865F, 0.8241096700F, 0.8247725781F, 0.8254341097F,
  157046. 0.8260942636F, 0.8267530385F, 0.8274104334F, 0.8280664470F,
  157047. 0.8287210782F, 0.8293743259F, 0.8300261889F, 0.8306766662F,
  157048. 0.8313257566F, 0.8319734591F, 0.8326197727F, 0.8332646963F,
  157049. 0.8339082288F, 0.8345503692F, 0.8351911167F, 0.8358304700F,
  157050. 0.8364684284F, 0.8371049907F, 0.8377401562F, 0.8383739238F,
  157051. 0.8390062927F, 0.8396372618F, 0.8402668305F, 0.8408949977F,
  157052. 0.8415217626F, 0.8421471245F, 0.8427710823F, 0.8433936354F,
  157053. 0.8440147830F, 0.8446345242F, 0.8452528582F, 0.8458697844F,
  157054. 0.8464853020F, 0.8470994102F, 0.8477121084F, 0.8483233958F,
  157055. 0.8489332718F, 0.8495417356F, 0.8501487866F, 0.8507544243F,
  157056. 0.8513586479F, 0.8519614568F, 0.8525628505F, 0.8531628283F,
  157057. 0.8537613897F, 0.8543585341F, 0.8549542611F, 0.8555485699F,
  157058. 0.8561414603F, 0.8567329315F, 0.8573229832F, 0.8579116149F,
  157059. 0.8584988262F, 0.8590846165F, 0.8596689855F, 0.8602519327F,
  157060. 0.8608334577F, 0.8614135603F, 0.8619922399F, 0.8625694962F,
  157061. 0.8631453289F, 0.8637197377F, 0.8642927222F, 0.8648642821F,
  157062. 0.8654344172F, 0.8660031272F, 0.8665704118F, 0.8671362708F,
  157063. 0.8677007039F, 0.8682637109F, 0.8688252917F, 0.8693854460F,
  157064. 0.8699441737F, 0.8705014745F, 0.8710573485F, 0.8716117953F,
  157065. 0.8721648150F, 0.8727164073F, 0.8732665723F, 0.8738153098F,
  157066. 0.8743626197F, 0.8749085021F, 0.8754529569F, 0.8759959840F,
  157067. 0.8765375835F, 0.8770777553F, 0.8776164996F, 0.8781538162F,
  157068. 0.8786897054F, 0.8792241670F, 0.8797572013F, 0.8802888082F,
  157069. 0.8808189880F, 0.8813477407F, 0.8818750664F, 0.8824009653F,
  157070. 0.8829254375F, 0.8834484833F, 0.8839701028F, 0.8844902961F,
  157071. 0.8850090636F, 0.8855264054F, 0.8860423218F, 0.8865568131F,
  157072. 0.8870698794F, 0.8875815212F, 0.8880917386F, 0.8886005319F,
  157073. 0.8891079016F, 0.8896138479F, 0.8901183712F, 0.8906214719F,
  157074. 0.8911231503F, 0.8916234067F, 0.8921222417F, 0.8926196556F,
  157075. 0.8931156489F, 0.8936102219F, 0.8941033752F, 0.8945951092F,
  157076. 0.8950854244F, 0.8955743212F, 0.8960618003F, 0.8965478621F,
  157077. 0.8970325071F, 0.8975157359F, 0.8979975490F, 0.8984779471F,
  157078. 0.8989569307F, 0.8994345004F, 0.8999106568F, 0.9003854005F,
  157079. 0.9008587323F, 0.9013306526F, 0.9018011623F, 0.9022702619F,
  157080. 0.9027379521F, 0.9032042337F, 0.9036691074F, 0.9041325739F,
  157081. 0.9045946339F, 0.9050552882F, 0.9055145376F, 0.9059723828F,
  157082. 0.9064288246F, 0.9068838638F, 0.9073375013F, 0.9077897379F,
  157083. 0.9082405743F, 0.9086900115F, 0.9091380503F, 0.9095846917F,
  157084. 0.9100299364F, 0.9104737854F, 0.9109162397F, 0.9113573001F,
  157085. 0.9117969675F, 0.9122352430F, 0.9126721275F, 0.9131076219F,
  157086. 0.9135417273F, 0.9139744447F, 0.9144057750F, 0.9148357194F,
  157087. 0.9152642787F, 0.9156914542F, 0.9161172468F, 0.9165416576F,
  157088. 0.9169646877F, 0.9173863382F, 0.9178066102F, 0.9182255048F,
  157089. 0.9186430232F, 0.9190591665F, 0.9194739359F, 0.9198873324F,
  157090. 0.9202993574F, 0.9207100120F, 0.9211192973F, 0.9215272147F,
  157091. 0.9219337653F, 0.9223389504F, 0.9227427713F, 0.9231452290F,
  157092. 0.9235463251F, 0.9239460607F, 0.9243444371F, 0.9247414557F,
  157093. 0.9251371177F, 0.9255314245F, 0.9259243774F, 0.9263159778F,
  157094. 0.9267062270F, 0.9270951264F, 0.9274826774F, 0.9278688814F,
  157095. 0.9282537398F, 0.9286372540F, 0.9290194254F, 0.9294002555F,
  157096. 0.9297797458F, 0.9301578976F, 0.9305347125F, 0.9309101919F,
  157097. 0.9312843373F, 0.9316571503F, 0.9320286323F, 0.9323987849F,
  157098. 0.9327676097F, 0.9331351080F, 0.9335012816F, 0.9338661320F,
  157099. 0.9342296607F, 0.9345918694F, 0.9349527596F, 0.9353123330F,
  157100. 0.9356705911F, 0.9360275357F, 0.9363831683F, 0.9367374905F,
  157101. 0.9370905042F, 0.9374422108F, 0.9377926122F, 0.9381417099F,
  157102. 0.9384895057F, 0.9388360014F, 0.9391811985F, 0.9395250989F,
  157103. 0.9398677043F, 0.9402090165F, 0.9405490371F, 0.9408877680F,
  157104. 0.9412252110F, 0.9415613678F, 0.9418962402F, 0.9422298301F,
  157105. 0.9425621392F, 0.9428931695F, 0.9432229226F, 0.9435514005F,
  157106. 0.9438786050F, 0.9442045381F, 0.9445292014F, 0.9448525971F,
  157107. 0.9451747268F, 0.9454955926F, 0.9458151963F, 0.9461335399F,
  157108. 0.9464506253F, 0.9467664545F, 0.9470810293F, 0.9473943517F,
  157109. 0.9477064238F, 0.9480172474F, 0.9483268246F, 0.9486351573F,
  157110. 0.9489422475F, 0.9492480973F, 0.9495527087F, 0.9498560837F,
  157111. 0.9501582243F, 0.9504591325F, 0.9507588105F, 0.9510572603F,
  157112. 0.9513544839F, 0.9516504834F, 0.9519452609F, 0.9522388186F,
  157113. 0.9525311584F, 0.9528222826F, 0.9531121932F, 0.9534008923F,
  157114. 0.9536883821F, 0.9539746647F, 0.9542597424F, 0.9545436171F,
  157115. 0.9548262912F, 0.9551077667F, 0.9553880459F, 0.9556671309F,
  157116. 0.9559450239F, 0.9562217272F, 0.9564972429F, 0.9567715733F,
  157117. 0.9570447206F, 0.9573166871F, 0.9575874749F, 0.9578570863F,
  157118. 0.9581255236F, 0.9583927890F, 0.9586588849F, 0.9589238134F,
  157119. 0.9591875769F, 0.9594501777F, 0.9597116180F, 0.9599719003F,
  157120. 0.9602310267F, 0.9604889995F, 0.9607458213F, 0.9610014942F,
  157121. 0.9612560206F, 0.9615094028F, 0.9617616433F, 0.9620127443F,
  157122. 0.9622627083F, 0.9625115376F, 0.9627592345F, 0.9630058016F,
  157123. 0.9632512411F, 0.9634955555F, 0.9637387471F, 0.9639808185F,
  157124. 0.9642217720F, 0.9644616100F, 0.9647003349F, 0.9649379493F,
  157125. 0.9651744556F, 0.9654098561F, 0.9656441534F, 0.9658773499F,
  157126. 0.9661094480F, 0.9663404504F, 0.9665703593F, 0.9667991774F,
  157127. 0.9670269071F, 0.9672535509F, 0.9674791114F, 0.9677035909F,
  157128. 0.9679269921F, 0.9681493174F, 0.9683705694F, 0.9685907506F,
  157129. 0.9688098636F, 0.9690279108F, 0.9692448948F, 0.9694608182F,
  157130. 0.9696756836F, 0.9698894934F, 0.9701022503F, 0.9703139569F,
  157131. 0.9705246156F, 0.9707342291F, 0.9709428000F, 0.9711503309F,
  157132. 0.9713568243F, 0.9715622829F, 0.9717667093F, 0.9719701060F,
  157133. 0.9721724757F, 0.9723738210F, 0.9725741446F, 0.9727734490F,
  157134. 0.9729717369F, 0.9731690109F, 0.9733652737F, 0.9735605279F,
  157135. 0.9737547762F, 0.9739480212F, 0.9741402656F, 0.9743315120F,
  157136. 0.9745217631F, 0.9747110216F, 0.9748992901F, 0.9750865714F,
  157137. 0.9752728681F, 0.9754581829F, 0.9756425184F, 0.9758258775F,
  157138. 0.9760082627F, 0.9761896768F, 0.9763701224F, 0.9765496024F,
  157139. 0.9767281193F, 0.9769056760F, 0.9770822751F, 0.9772579193F,
  157140. 0.9774326114F, 0.9776063542F, 0.9777791502F, 0.9779510023F,
  157141. 0.9781219133F, 0.9782918858F, 0.9784609226F, 0.9786290264F,
  157142. 0.9787962000F, 0.9789624461F, 0.9791277676F, 0.9792921671F,
  157143. 0.9794556474F, 0.9796182113F, 0.9797798615F, 0.9799406009F,
  157144. 0.9801004321F, 0.9802593580F, 0.9804173813F, 0.9805745049F,
  157145. 0.9807307314F, 0.9808860637F, 0.9810405046F, 0.9811940568F,
  157146. 0.9813467232F, 0.9814985065F, 0.9816494095F, 0.9817994351F,
  157147. 0.9819485860F, 0.9820968650F, 0.9822442750F, 0.9823908186F,
  157148. 0.9825364988F, 0.9826813184F, 0.9828252801F, 0.9829683868F,
  157149. 0.9831106413F, 0.9832520463F, 0.9833926048F, 0.9835323195F,
  157150. 0.9836711932F, 0.9838092288F, 0.9839464291F, 0.9840827969F,
  157151. 0.9842183351F, 0.9843530464F, 0.9844869337F, 0.9846199998F,
  157152. 0.9847522475F, 0.9848836798F, 0.9850142993F, 0.9851441090F,
  157153. 0.9852731117F, 0.9854013101F, 0.9855287073F, 0.9856553058F,
  157154. 0.9857811087F, 0.9859061188F, 0.9860303388F, 0.9861537717F,
  157155. 0.9862764202F, 0.9863982872F, 0.9865193756F, 0.9866396882F,
  157156. 0.9867592277F, 0.9868779972F, 0.9869959993F, 0.9871132370F,
  157157. 0.9872297131F, 0.9873454304F, 0.9874603918F, 0.9875746001F,
  157158. 0.9876880581F, 0.9878007688F, 0.9879127348F, 0.9880239592F,
  157159. 0.9881344447F, 0.9882441941F, 0.9883532104F, 0.9884614962F,
  157160. 0.9885690546F, 0.9886758883F, 0.9887820001F, 0.9888873930F,
  157161. 0.9889920697F, 0.9890960331F, 0.9891992859F, 0.9893018312F,
  157162. 0.9894036716F, 0.9895048100F, 0.9896052493F, 0.9897049923F,
  157163. 0.9898040418F, 0.9899024006F, 0.9900000717F, 0.9900970577F,
  157164. 0.9901933616F, 0.9902889862F, 0.9903839343F, 0.9904782087F,
  157165. 0.9905718122F, 0.9906647477F, 0.9907570180F, 0.9908486259F,
  157166. 0.9909395742F, 0.9910298658F, 0.9911195034F, 0.9912084899F,
  157167. 0.9912968281F, 0.9913845208F, 0.9914715708F, 0.9915579810F,
  157168. 0.9916437540F, 0.9917288928F, 0.9918134001F, 0.9918972788F,
  157169. 0.9919805316F, 0.9920631613F, 0.9921451707F, 0.9922265626F,
  157170. 0.9923073399F, 0.9923875052F, 0.9924670615F, 0.9925460114F,
  157171. 0.9926243577F, 0.9927021033F, 0.9927792508F, 0.9928558032F,
  157172. 0.9929317631F, 0.9930071333F, 0.9930819167F, 0.9931561158F,
  157173. 0.9932297337F, 0.9933027728F, 0.9933752362F, 0.9934471264F,
  157174. 0.9935184462F, 0.9935891985F, 0.9936593859F, 0.9937290112F,
  157175. 0.9937980771F, 0.9938665864F, 0.9939345418F, 0.9940019460F,
  157176. 0.9940688018F, 0.9941351118F, 0.9942008789F, 0.9942661057F,
  157177. 0.9943307950F, 0.9943949494F, 0.9944585717F, 0.9945216645F,
  157178. 0.9945842307F, 0.9946462728F, 0.9947077936F, 0.9947687957F,
  157179. 0.9948292820F, 0.9948892550F, 0.9949487174F, 0.9950076719F,
  157180. 0.9950661212F, 0.9951240679F, 0.9951815148F, 0.9952384645F,
  157181. 0.9952949196F, 0.9953508828F, 0.9954063568F, 0.9954613442F,
  157182. 0.9955158476F, 0.9955698697F, 0.9956234132F, 0.9956764806F,
  157183. 0.9957290746F, 0.9957811978F, 0.9958328528F, 0.9958840423F,
  157184. 0.9959347688F, 0.9959850351F, 0.9960348435F, 0.9960841969F,
  157185. 0.9961330977F, 0.9961815486F, 0.9962295521F, 0.9962771108F,
  157186. 0.9963242274F, 0.9963709043F, 0.9964171441F, 0.9964629494F,
  157187. 0.9965083228F, 0.9965532668F, 0.9965977840F, 0.9966418768F,
  157188. 0.9966855479F, 0.9967287998F, 0.9967716350F, 0.9968140559F,
  157189. 0.9968560653F, 0.9968976655F, 0.9969388591F, 0.9969796485F,
  157190. 0.9970200363F, 0.9970600250F, 0.9970996170F, 0.9971388149F,
  157191. 0.9971776211F, 0.9972160380F, 0.9972540683F, 0.9972917142F,
  157192. 0.9973289783F, 0.9973658631F, 0.9974023709F, 0.9974385042F,
  157193. 0.9974742655F, 0.9975096571F, 0.9975446816F, 0.9975793413F,
  157194. 0.9976136386F, 0.9976475759F, 0.9976811557F, 0.9977143803F,
  157195. 0.9977472521F, 0.9977797736F, 0.9978119470F, 0.9978437748F,
  157196. 0.9978752593F, 0.9979064029F, 0.9979372079F, 0.9979676768F,
  157197. 0.9979978117F, 0.9980276151F, 0.9980570893F, 0.9980862367F,
  157198. 0.9981150595F, 0.9981435600F, 0.9981717406F, 0.9981996035F,
  157199. 0.9982271511F, 0.9982543856F, 0.9982813093F, 0.9983079246F,
  157200. 0.9983342336F, 0.9983602386F, 0.9983859418F, 0.9984113456F,
  157201. 0.9984364522F, 0.9984612638F, 0.9984857825F, 0.9985100108F,
  157202. 0.9985339507F, 0.9985576044F, 0.9985809743F, 0.9986040624F,
  157203. 0.9986268710F, 0.9986494022F, 0.9986716583F, 0.9986936413F,
  157204. 0.9987153535F, 0.9987367969F, 0.9987579738F, 0.9987788864F,
  157205. 0.9987995366F, 0.9988199267F, 0.9988400587F, 0.9988599348F,
  157206. 0.9988795572F, 0.9988989278F, 0.9989180487F, 0.9989369222F,
  157207. 0.9989555501F, 0.9989739347F, 0.9989920780F, 0.9990099820F,
  157208. 0.9990276487F, 0.9990450803F, 0.9990622787F, 0.9990792460F,
  157209. 0.9990959841F, 0.9991124952F, 0.9991287812F, 0.9991448440F,
  157210. 0.9991606858F, 0.9991763084F, 0.9991917139F, 0.9992069042F,
  157211. 0.9992218813F, 0.9992366471F, 0.9992512035F, 0.9992655525F,
  157212. 0.9992796961F, 0.9992936361F, 0.9993073744F, 0.9993209131F,
  157213. 0.9993342538F, 0.9993473987F, 0.9993603494F, 0.9993731080F,
  157214. 0.9993856762F, 0.9993980559F, 0.9994102490F, 0.9994222573F,
  157215. 0.9994340827F, 0.9994457269F, 0.9994571918F, 0.9994684793F,
  157216. 0.9994795910F, 0.9994905288F, 0.9995012945F, 0.9995118898F,
  157217. 0.9995223165F, 0.9995325765F, 0.9995426713F, 0.9995526029F,
  157218. 0.9995623728F, 0.9995719829F, 0.9995814349F, 0.9995907304F,
  157219. 0.9995998712F, 0.9996088590F, 0.9996176954F, 0.9996263821F,
  157220. 0.9996349208F, 0.9996433132F, 0.9996515609F, 0.9996596656F,
  157221. 0.9996676288F, 0.9996754522F, 0.9996831375F, 0.9996906862F,
  157222. 0.9996981000F, 0.9997053804F, 0.9997125290F, 0.9997195474F,
  157223. 0.9997264371F, 0.9997331998F, 0.9997398369F, 0.9997463500F,
  157224. 0.9997527406F, 0.9997590103F, 0.9997651606F, 0.9997711930F,
  157225. 0.9997771089F, 0.9997829098F, 0.9997885973F, 0.9997941728F,
  157226. 0.9997996378F, 0.9998049936F, 0.9998102419F, 0.9998153839F,
  157227. 0.9998204211F, 0.9998253550F, 0.9998301868F, 0.9998349182F,
  157228. 0.9998395503F, 0.9998440847F, 0.9998485226F, 0.9998528654F,
  157229. 0.9998571146F, 0.9998612713F, 0.9998653370F, 0.9998693130F,
  157230. 0.9998732007F, 0.9998770012F, 0.9998807159F, 0.9998843461F,
  157231. 0.9998878931F, 0.9998913581F, 0.9998947424F, 0.9998980473F,
  157232. 0.9999012740F, 0.9999044237F, 0.9999074976F, 0.9999104971F,
  157233. 0.9999134231F, 0.9999162771F, 0.9999190601F, 0.9999217733F,
  157234. 0.9999244179F, 0.9999269950F, 0.9999295058F, 0.9999319515F,
  157235. 0.9999343332F, 0.9999366519F, 0.9999389088F, 0.9999411050F,
  157236. 0.9999432416F, 0.9999453196F, 0.9999473402F, 0.9999493044F,
  157237. 0.9999512132F, 0.9999530677F, 0.9999548690F, 0.9999566180F,
  157238. 0.9999583157F, 0.9999599633F, 0.9999615616F, 0.9999631116F,
  157239. 0.9999646144F, 0.9999660709F, 0.9999674820F, 0.9999688487F,
  157240. 0.9999701719F, 0.9999714526F, 0.9999726917F, 0.9999738900F,
  157241. 0.9999750486F, 0.9999761682F, 0.9999772497F, 0.9999782941F,
  157242. 0.9999793021F, 0.9999802747F, 0.9999812126F, 0.9999821167F,
  157243. 0.9999829878F, 0.9999838268F, 0.9999846343F, 0.9999854113F,
  157244. 0.9999861584F, 0.9999868765F, 0.9999875664F, 0.9999882287F,
  157245. 0.9999888642F, 0.9999894736F, 0.9999900577F, 0.9999906172F,
  157246. 0.9999911528F, 0.9999916651F, 0.9999921548F, 0.9999926227F,
  157247. 0.9999930693F, 0.9999934954F, 0.9999939015F, 0.9999942883F,
  157248. 0.9999946564F, 0.9999950064F, 0.9999953390F, 0.9999956547F,
  157249. 0.9999959541F, 0.9999962377F, 0.9999965062F, 0.9999967601F,
  157250. 0.9999969998F, 0.9999972260F, 0.9999974392F, 0.9999976399F,
  157251. 0.9999978285F, 0.9999980056F, 0.9999981716F, 0.9999983271F,
  157252. 0.9999984724F, 0.9999986081F, 0.9999987345F, 0.9999988521F,
  157253. 0.9999989613F, 0.9999990625F, 0.9999991562F, 0.9999992426F,
  157254. 0.9999993223F, 0.9999993954F, 0.9999994625F, 0.9999995239F,
  157255. 0.9999995798F, 0.9999996307F, 0.9999996768F, 0.9999997184F,
  157256. 0.9999997559F, 0.9999997895F, 0.9999998195F, 0.9999998462F,
  157257. 0.9999998698F, 0.9999998906F, 0.9999999088F, 0.9999999246F,
  157258. 0.9999999383F, 0.9999999500F, 0.9999999600F, 0.9999999684F,
  157259. 0.9999999754F, 0.9999999811F, 0.9999999858F, 0.9999999896F,
  157260. 0.9999999925F, 0.9999999948F, 0.9999999965F, 0.9999999978F,
  157261. 0.9999999986F, 0.9999999992F, 0.9999999996F, 0.9999999998F,
  157262. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  157263. };
  157264. static float vwin8192[4096] = {
  157265. 0.0000000578F, 0.0000005198F, 0.0000014438F, 0.0000028299F,
  157266. 0.0000046780F, 0.0000069882F, 0.0000097604F, 0.0000129945F,
  157267. 0.0000166908F, 0.0000208490F, 0.0000254692F, 0.0000305515F,
  157268. 0.0000360958F, 0.0000421021F, 0.0000485704F, 0.0000555006F,
  157269. 0.0000628929F, 0.0000707472F, 0.0000790635F, 0.0000878417F,
  157270. 0.0000970820F, 0.0001067842F, 0.0001169483F, 0.0001275744F,
  157271. 0.0001386625F, 0.0001502126F, 0.0001622245F, 0.0001746984F,
  157272. 0.0001876343F, 0.0002010320F, 0.0002148917F, 0.0002292132F,
  157273. 0.0002439967F, 0.0002592421F, 0.0002749493F, 0.0002911184F,
  157274. 0.0003077493F, 0.0003248421F, 0.0003423967F, 0.0003604132F,
  157275. 0.0003788915F, 0.0003978316F, 0.0004172335F, 0.0004370971F,
  157276. 0.0004574226F, 0.0004782098F, 0.0004994587F, 0.0005211694F,
  157277. 0.0005433418F, 0.0005659759F, 0.0005890717F, 0.0006126292F,
  157278. 0.0006366484F, 0.0006611292F, 0.0006860716F, 0.0007114757F,
  157279. 0.0007373414F, 0.0007636687F, 0.0007904576F, 0.0008177080F,
  157280. 0.0008454200F, 0.0008735935F, 0.0009022285F, 0.0009313250F,
  157281. 0.0009608830F, 0.0009909025F, 0.0010213834F, 0.0010523257F,
  157282. 0.0010837295F, 0.0011155946F, 0.0011479211F, 0.0011807090F,
  157283. 0.0012139582F, 0.0012476687F, 0.0012818405F, 0.0013164736F,
  157284. 0.0013515679F, 0.0013871235F, 0.0014231402F, 0.0014596182F,
  157285. 0.0014965573F, 0.0015339576F, 0.0015718190F, 0.0016101415F,
  157286. 0.0016489251F, 0.0016881698F, 0.0017278754F, 0.0017680421F,
  157287. 0.0018086698F, 0.0018497584F, 0.0018913080F, 0.0019333185F,
  157288. 0.0019757898F, 0.0020187221F, 0.0020621151F, 0.0021059690F,
  157289. 0.0021502837F, 0.0021950591F, 0.0022402953F, 0.0022859921F,
  157290. 0.0023321497F, 0.0023787679F, 0.0024258467F, 0.0024733861F,
  157291. 0.0025213861F, 0.0025698466F, 0.0026187676F, 0.0026681491F,
  157292. 0.0027179911F, 0.0027682935F, 0.0028190562F, 0.0028702794F,
  157293. 0.0029219628F, 0.0029741066F, 0.0030267107F, 0.0030797749F,
  157294. 0.0031332994F, 0.0031872841F, 0.0032417289F, 0.0032966338F,
  157295. 0.0033519988F, 0.0034078238F, 0.0034641089F, 0.0035208539F,
  157296. 0.0035780589F, 0.0036357237F, 0.0036938485F, 0.0037524331F,
  157297. 0.0038114775F, 0.0038709817F, 0.0039309456F, 0.0039913692F,
  157298. 0.0040522524F, 0.0041135953F, 0.0041753978F, 0.0042376599F,
  157299. 0.0043003814F, 0.0043635624F, 0.0044272029F, 0.0044913028F,
  157300. 0.0045558620F, 0.0046208806F, 0.0046863585F, 0.0047522955F,
  157301. 0.0048186919F, 0.0048855473F, 0.0049528619F, 0.0050206356F,
  157302. 0.0050888684F, 0.0051575601F, 0.0052267108F, 0.0052963204F,
  157303. 0.0053663890F, 0.0054369163F, 0.0055079025F, 0.0055793474F,
  157304. 0.0056512510F, 0.0057236133F, 0.0057964342F, 0.0058697137F,
  157305. 0.0059434517F, 0.0060176482F, 0.0060923032F, 0.0061674166F,
  157306. 0.0062429883F, 0.0063190183F, 0.0063955066F, 0.0064724532F,
  157307. 0.0065498579F, 0.0066277207F, 0.0067060416F, 0.0067848205F,
  157308. 0.0068640575F, 0.0069437523F, 0.0070239051F, 0.0071045157F,
  157309. 0.0071855840F, 0.0072671102F, 0.0073490940F, 0.0074315355F,
  157310. 0.0075144345F, 0.0075977911F, 0.0076816052F, 0.0077658768F,
  157311. 0.0078506057F, 0.0079357920F, 0.0080214355F, 0.0081075363F,
  157312. 0.0081940943F, 0.0082811094F, 0.0083685816F, 0.0084565108F,
  157313. 0.0085448970F, 0.0086337401F, 0.0087230401F, 0.0088127969F,
  157314. 0.0089030104F, 0.0089936807F, 0.0090848076F, 0.0091763911F,
  157315. 0.0092684311F, 0.0093609276F, 0.0094538805F, 0.0095472898F,
  157316. 0.0096411554F, 0.0097354772F, 0.0098302552F, 0.0099254894F,
  157317. 0.0100211796F, 0.0101173259F, 0.0102139281F, 0.0103109863F,
  157318. 0.0104085002F, 0.0105064700F, 0.0106048955F, 0.0107037766F,
  157319. 0.0108031133F, 0.0109029056F, 0.0110031534F, 0.0111038565F,
  157320. 0.0112050151F, 0.0113066289F, 0.0114086980F, 0.0115112222F,
  157321. 0.0116142015F, 0.0117176359F, 0.0118215252F, 0.0119258695F,
  157322. 0.0120306686F, 0.0121359225F, 0.0122416312F, 0.0123477944F,
  157323. 0.0124544123F, 0.0125614847F, 0.0126690116F, 0.0127769928F,
  157324. 0.0128854284F, 0.0129943182F, 0.0131036623F, 0.0132134604F,
  157325. 0.0133237126F, 0.0134344188F, 0.0135455790F, 0.0136571929F,
  157326. 0.0137692607F, 0.0138817821F, 0.0139947572F, 0.0141081859F,
  157327. 0.0142220681F, 0.0143364037F, 0.0144511927F, 0.0145664350F,
  157328. 0.0146821304F, 0.0147982791F, 0.0149148808F, 0.0150319355F,
  157329. 0.0151494431F, 0.0152674036F, 0.0153858168F, 0.0155046828F,
  157330. 0.0156240014F, 0.0157437726F, 0.0158639962F, 0.0159846723F,
  157331. 0.0161058007F, 0.0162273814F, 0.0163494142F, 0.0164718991F,
  157332. 0.0165948361F, 0.0167182250F, 0.0168420658F, 0.0169663584F,
  157333. 0.0170911027F, 0.0172162987F, 0.0173419462F, 0.0174680452F,
  157334. 0.0175945956F, 0.0177215974F, 0.0178490504F, 0.0179769545F,
  157335. 0.0181053098F, 0.0182341160F, 0.0183633732F, 0.0184930812F,
  157336. 0.0186232399F, 0.0187538494F, 0.0188849094F, 0.0190164200F,
  157337. 0.0191483809F, 0.0192807923F, 0.0194136539F, 0.0195469656F,
  157338. 0.0196807275F, 0.0198149394F, 0.0199496012F, 0.0200847128F,
  157339. 0.0202202742F, 0.0203562853F, 0.0204927460F, 0.0206296561F,
  157340. 0.0207670157F, 0.0209048245F, 0.0210430826F, 0.0211817899F,
  157341. 0.0213209462F, 0.0214605515F, 0.0216006057F, 0.0217411086F,
  157342. 0.0218820603F, 0.0220234605F, 0.0221653093F, 0.0223076066F,
  157343. 0.0224503521F, 0.0225935459F, 0.0227371879F, 0.0228812779F,
  157344. 0.0230258160F, 0.0231708018F, 0.0233162355F, 0.0234621169F,
  157345. 0.0236084459F, 0.0237552224F, 0.0239024462F, 0.0240501175F,
  157346. 0.0241982359F, 0.0243468015F, 0.0244958141F, 0.0246452736F,
  157347. 0.0247951800F, 0.0249455331F, 0.0250963329F, 0.0252475792F,
  157348. 0.0253992720F, 0.0255514111F, 0.0257039965F, 0.0258570281F,
  157349. 0.0260105057F, 0.0261644293F, 0.0263187987F, 0.0264736139F,
  157350. 0.0266288747F, 0.0267845811F, 0.0269407330F, 0.0270973302F,
  157351. 0.0272543727F, 0.0274118604F, 0.0275697930F, 0.0277281707F,
  157352. 0.0278869932F, 0.0280462604F, 0.0282059723F, 0.0283661287F,
  157353. 0.0285267295F, 0.0286877747F, 0.0288492641F, 0.0290111976F,
  157354. 0.0291735751F, 0.0293363965F, 0.0294996617F, 0.0296633706F,
  157355. 0.0298275231F, 0.0299921190F, 0.0301571583F, 0.0303226409F,
  157356. 0.0304885667F, 0.0306549354F, 0.0308217472F, 0.0309890017F,
  157357. 0.0311566989F, 0.0313248388F, 0.0314934211F, 0.0316624459F,
  157358. 0.0318319128F, 0.0320018220F, 0.0321721732F, 0.0323429663F,
  157359. 0.0325142013F, 0.0326858779F, 0.0328579962F, 0.0330305559F,
  157360. 0.0332035570F, 0.0333769994F, 0.0335508829F, 0.0337252074F,
  157361. 0.0338999728F, 0.0340751790F, 0.0342508259F, 0.0344269134F,
  157362. 0.0346034412F, 0.0347804094F, 0.0349578178F, 0.0351356663F,
  157363. 0.0353139548F, 0.0354926831F, 0.0356718511F, 0.0358514588F,
  157364. 0.0360315059F, 0.0362119924F, 0.0363929182F, 0.0365742831F,
  157365. 0.0367560870F, 0.0369383297F, 0.0371210113F, 0.0373041315F,
  157366. 0.0374876902F, 0.0376716873F, 0.0378561226F, 0.0380409961F,
  157367. 0.0382263077F, 0.0384120571F, 0.0385982443F, 0.0387848691F,
  157368. 0.0389719315F, 0.0391594313F, 0.0393473683F, 0.0395357425F,
  157369. 0.0397245537F, 0.0399138017F, 0.0401034866F, 0.0402936080F,
  157370. 0.0404841660F, 0.0406751603F, 0.0408665909F, 0.0410584576F,
  157371. 0.0412507603F, 0.0414434988F, 0.0416366731F, 0.0418302829F,
  157372. 0.0420243282F, 0.0422188088F, 0.0424137246F, 0.0426090755F,
  157373. 0.0428048613F, 0.0430010819F, 0.0431977371F, 0.0433948269F,
  157374. 0.0435923511F, 0.0437903095F, 0.0439887020F, 0.0441875285F,
  157375. 0.0443867889F, 0.0445864830F, 0.0447866106F, 0.0449871717F,
  157376. 0.0451881661F, 0.0453895936F, 0.0455914542F, 0.0457937477F,
  157377. 0.0459964738F, 0.0461996326F, 0.0464032239F, 0.0466072475F,
  157378. 0.0468117032F, 0.0470165910F, 0.0472219107F, 0.0474276622F,
  157379. 0.0476338452F, 0.0478404597F, 0.0480475056F, 0.0482549827F,
  157380. 0.0484628907F, 0.0486712297F, 0.0488799994F, 0.0490891998F,
  157381. 0.0492988306F, 0.0495088917F, 0.0497193830F, 0.0499303043F,
  157382. 0.0501416554F, 0.0503534363F, 0.0505656468F, 0.0507782867F,
  157383. 0.0509913559F, 0.0512048542F, 0.0514187815F, 0.0516331376F,
  157384. 0.0518479225F, 0.0520631358F, 0.0522787775F, 0.0524948475F,
  157385. 0.0527113455F, 0.0529282715F, 0.0531456252F, 0.0533634066F,
  157386. 0.0535816154F, 0.0538002515F, 0.0540193148F, 0.0542388051F,
  157387. 0.0544587222F, 0.0546790660F, 0.0548998364F, 0.0551210331F,
  157388. 0.0553426561F, 0.0555647051F, 0.0557871801F, 0.0560100807F,
  157389. 0.0562334070F, 0.0564571587F, 0.0566813357F, 0.0569059378F,
  157390. 0.0571309649F, 0.0573564168F, 0.0575822933F, 0.0578085942F,
  157391. 0.0580353195F, 0.0582624689F, 0.0584900423F, 0.0587180396F,
  157392. 0.0589464605F, 0.0591753049F, 0.0594045726F, 0.0596342635F,
  157393. 0.0598643774F, 0.0600949141F, 0.0603258735F, 0.0605572555F,
  157394. 0.0607890597F, 0.0610212862F, 0.0612539346F, 0.0614870049F,
  157395. 0.0617204968F, 0.0619544103F, 0.0621887451F, 0.0624235010F,
  157396. 0.0626586780F, 0.0628942758F, 0.0631302942F, 0.0633667331F,
  157397. 0.0636035923F, 0.0638408717F, 0.0640785710F, 0.0643166901F,
  157398. 0.0645552288F, 0.0647941870F, 0.0650335645F, 0.0652733610F,
  157399. 0.0655135765F, 0.0657542108F, 0.0659952636F, 0.0662367348F,
  157400. 0.0664786242F, 0.0667209316F, 0.0669636570F, 0.0672068000F,
  157401. 0.0674503605F, 0.0676943384F, 0.0679387334F, 0.0681835454F,
  157402. 0.0684287742F, 0.0686744196F, 0.0689204814F, 0.0691669595F,
  157403. 0.0694138536F, 0.0696611637F, 0.0699088894F, 0.0701570307F,
  157404. 0.0704055873F, 0.0706545590F, 0.0709039458F, 0.0711537473F,
  157405. 0.0714039634F, 0.0716545939F, 0.0719056387F, 0.0721570975F,
  157406. 0.0724089702F, 0.0726612565F, 0.0729139563F, 0.0731670694F,
  157407. 0.0734205956F, 0.0736745347F, 0.0739288866F, 0.0741836510F,
  157408. 0.0744388277F, 0.0746944166F, 0.0749504175F, 0.0752068301F,
  157409. 0.0754636543F, 0.0757208899F, 0.0759785367F, 0.0762365946F,
  157410. 0.0764950632F, 0.0767539424F, 0.0770132320F, 0.0772729319F,
  157411. 0.0775330418F, 0.0777935616F, 0.0780544909F, 0.0783158298F,
  157412. 0.0785775778F, 0.0788397349F, 0.0791023009F, 0.0793652755F,
  157413. 0.0796286585F, 0.0798924498F, 0.0801566492F, 0.0804212564F,
  157414. 0.0806862712F, 0.0809516935F, 0.0812175231F, 0.0814837597F,
  157415. 0.0817504031F, 0.0820174532F, 0.0822849097F, 0.0825527724F,
  157416. 0.0828210412F, 0.0830897158F, 0.0833587960F, 0.0836282816F,
  157417. 0.0838981724F, 0.0841684682F, 0.0844391688F, 0.0847102740F,
  157418. 0.0849817835F, 0.0852536973F, 0.0855260150F, 0.0857987364F,
  157419. 0.0860718614F, 0.0863453897F, 0.0866193211F, 0.0868936554F,
  157420. 0.0871683924F, 0.0874435319F, 0.0877190737F, 0.0879950175F,
  157421. 0.0882713632F, 0.0885481105F, 0.0888252592F, 0.0891028091F,
  157422. 0.0893807600F, 0.0896591117F, 0.0899378639F, 0.0902170165F,
  157423. 0.0904965692F, 0.0907765218F, 0.0910568740F, 0.0913376258F,
  157424. 0.0916187767F, 0.0919003268F, 0.0921822756F, 0.0924646230F,
  157425. 0.0927473687F, 0.0930305126F, 0.0933140545F, 0.0935979940F,
  157426. 0.0938823310F, 0.0941670653F, 0.0944521966F, 0.0947377247F,
  157427. 0.0950236494F, 0.0953099704F, 0.0955966876F, 0.0958838007F,
  157428. 0.0961713094F, 0.0964592136F, 0.0967475131F, 0.0970362075F,
  157429. 0.0973252967F, 0.0976147805F, 0.0979046585F, 0.0981949307F,
  157430. 0.0984855967F, 0.0987766563F, 0.0990681093F, 0.0993599555F,
  157431. 0.0996521945F, 0.0999448263F, 0.1002378506F, 0.1005312671F,
  157432. 0.1008250755F, 0.1011192757F, 0.1014138675F, 0.1017088505F,
  157433. 0.1020042246F, 0.1022999895F, 0.1025961450F, 0.1028926909F,
  157434. 0.1031896268F, 0.1034869526F, 0.1037846680F, 0.1040827729F,
  157435. 0.1043812668F, 0.1046801497F, 0.1049794213F, 0.1052790813F,
  157436. 0.1055791294F, 0.1058795656F, 0.1061803894F, 0.1064816006F,
  157437. 0.1067831991F, 0.1070851846F, 0.1073875568F, 0.1076903155F,
  157438. 0.1079934604F, 0.1082969913F, 0.1086009079F, 0.1089052101F,
  157439. 0.1092098975F, 0.1095149699F, 0.1098204270F, 0.1101262687F,
  157440. 0.1104324946F, 0.1107391045F, 0.1110460982F, 0.1113534754F,
  157441. 0.1116612359F, 0.1119693793F, 0.1122779055F, 0.1125868142F,
  157442. 0.1128961052F, 0.1132057781F, 0.1135158328F, 0.1138262690F,
  157443. 0.1141370863F, 0.1144482847F, 0.1147598638F, 0.1150718233F,
  157444. 0.1153841631F, 0.1156968828F, 0.1160099822F, 0.1163234610F,
  157445. 0.1166373190F, 0.1169515559F, 0.1172661714F, 0.1175811654F,
  157446. 0.1178965374F, 0.1182122874F, 0.1185284149F, 0.1188449198F,
  157447. 0.1191618018F, 0.1194790606F, 0.1197966960F, 0.1201147076F,
  157448. 0.1204330953F, 0.1207518587F, 0.1210709976F, 0.1213905118F,
  157449. 0.1217104009F, 0.1220306647F, 0.1223513029F, 0.1226723153F,
  157450. 0.1229937016F, 0.1233154615F, 0.1236375948F, 0.1239601011F,
  157451. 0.1242829803F, 0.1246062319F, 0.1249298559F, 0.1252538518F,
  157452. 0.1255782195F, 0.1259029586F, 0.1262280689F, 0.1265535501F,
  157453. 0.1268794019F, 0.1272056241F, 0.1275322163F, 0.1278591784F,
  157454. 0.1281865099F, 0.1285142108F, 0.1288422805F, 0.1291707190F,
  157455. 0.1294995259F, 0.1298287009F, 0.1301582437F, 0.1304881542F,
  157456. 0.1308184319F, 0.1311490766F, 0.1314800881F, 0.1318114660F,
  157457. 0.1321432100F, 0.1324753200F, 0.1328077955F, 0.1331406364F,
  157458. 0.1334738422F, 0.1338074129F, 0.1341413479F, 0.1344756472F,
  157459. 0.1348103103F, 0.1351453370F, 0.1354807270F, 0.1358164801F,
  157460. 0.1361525959F, 0.1364890741F, 0.1368259145F, 0.1371631167F,
  157461. 0.1375006805F, 0.1378386056F, 0.1381768917F, 0.1385155384F,
  157462. 0.1388545456F, 0.1391939129F, 0.1395336400F, 0.1398737266F,
  157463. 0.1402141724F, 0.1405549772F, 0.1408961406F, 0.1412376623F,
  157464. 0.1415795421F, 0.1419217797F, 0.1422643746F, 0.1426073268F,
  157465. 0.1429506358F, 0.1432943013F, 0.1436383231F, 0.1439827008F,
  157466. 0.1443274342F, 0.1446725229F, 0.1450179667F, 0.1453637652F,
  157467. 0.1457099181F, 0.1460564252F, 0.1464032861F, 0.1467505006F,
  157468. 0.1470980682F, 0.1474459888F, 0.1477942620F, 0.1481428875F,
  157469. 0.1484918651F, 0.1488411942F, 0.1491908748F, 0.1495409065F,
  157470. 0.1498912889F, 0.1502420218F, 0.1505931048F, 0.1509445376F,
  157471. 0.1512963200F, 0.1516484516F, 0.1520009321F, 0.1523537612F,
  157472. 0.1527069385F, 0.1530604638F, 0.1534143368F, 0.1537685571F,
  157473. 0.1541231244F, 0.1544780384F, 0.1548332987F, 0.1551889052F,
  157474. 0.1555448574F, 0.1559011550F, 0.1562577978F, 0.1566147853F,
  157475. 0.1569721173F, 0.1573297935F, 0.1576878135F, 0.1580461771F,
  157476. 0.1584048838F, 0.1587639334F, 0.1591233255F, 0.1594830599F,
  157477. 0.1598431361F, 0.1602035540F, 0.1605643131F, 0.1609254131F,
  157478. 0.1612868537F, 0.1616486346F, 0.1620107555F, 0.1623732160F,
  157479. 0.1627360158F, 0.1630991545F, 0.1634626319F, 0.1638264476F,
  157480. 0.1641906013F, 0.1645550926F, 0.1649199212F, 0.1652850869F,
  157481. 0.1656505892F, 0.1660164278F, 0.1663826024F, 0.1667491127F,
  157482. 0.1671159583F, 0.1674831388F, 0.1678506541F, 0.1682185036F,
  157483. 0.1685866872F, 0.1689552044F, 0.1693240549F, 0.1696932384F,
  157484. 0.1700627545F, 0.1704326029F, 0.1708027833F, 0.1711732952F,
  157485. 0.1715441385F, 0.1719153127F, 0.1722868175F, 0.1726586526F,
  157486. 0.1730308176F, 0.1734033121F, 0.1737761359F, 0.1741492886F,
  157487. 0.1745227698F, 0.1748965792F, 0.1752707164F, 0.1756451812F,
  157488. 0.1760199731F, 0.1763950918F, 0.1767705370F, 0.1771463083F,
  157489. 0.1775224054F, 0.1778988279F, 0.1782755754F, 0.1786526477F,
  157490. 0.1790300444F, 0.1794077651F, 0.1797858094F, 0.1801641771F,
  157491. 0.1805428677F, 0.1809218810F, 0.1813012165F, 0.1816808739F,
  157492. 0.1820608528F, 0.1824411530F, 0.1828217739F, 0.1832027154F,
  157493. 0.1835839770F, 0.1839655584F, 0.1843474592F, 0.1847296790F,
  157494. 0.1851122175F, 0.1854950744F, 0.1858782492F, 0.1862617417F,
  157495. 0.1866455514F, 0.1870296780F, 0.1874141211F, 0.1877988804F,
  157496. 0.1881839555F, 0.1885693461F, 0.1889550517F, 0.1893410721F,
  157497. 0.1897274068F, 0.1901140555F, 0.1905010178F, 0.1908882933F,
  157498. 0.1912758818F, 0.1916637828F, 0.1920519959F, 0.1924405208F,
  157499. 0.1928293571F, 0.1932185044F, 0.1936079625F, 0.1939977308F,
  157500. 0.1943878091F, 0.1947781969F, 0.1951688939F, 0.1955598998F,
  157501. 0.1959512141F, 0.1963428364F, 0.1967347665F, 0.1971270038F,
  157502. 0.1975195482F, 0.1979123990F, 0.1983055561F, 0.1986990190F,
  157503. 0.1990927873F, 0.1994868607F, 0.1998812388F, 0.2002759212F,
  157504. 0.2006709075F, 0.2010661974F, 0.2014617904F, 0.2018576862F,
  157505. 0.2022538844F, 0.2026503847F, 0.2030471865F, 0.2034442897F,
  157506. 0.2038416937F, 0.2042393982F, 0.2046374028F, 0.2050357071F,
  157507. 0.2054343107F, 0.2058332133F, 0.2062324145F, 0.2066319138F,
  157508. 0.2070317110F, 0.2074318055F, 0.2078321970F, 0.2082328852F,
  157509. 0.2086338696F, 0.2090351498F, 0.2094367255F, 0.2098385962F,
  157510. 0.2102407617F, 0.2106432213F, 0.2110459749F, 0.2114490220F,
  157511. 0.2118523621F, 0.2122559950F, 0.2126599202F, 0.2130641373F,
  157512. 0.2134686459F, 0.2138734456F, 0.2142785361F, 0.2146839168F,
  157513. 0.2150895875F, 0.2154955478F, 0.2159017972F, 0.2163083353F,
  157514. 0.2167151617F, 0.2171222761F, 0.2175296780F, 0.2179373670F,
  157515. 0.2183453428F, 0.2187536049F, 0.2191621529F, 0.2195709864F,
  157516. 0.2199801051F, 0.2203895085F, 0.2207991961F, 0.2212091677F,
  157517. 0.2216194228F, 0.2220299610F, 0.2224407818F, 0.2228518850F,
  157518. 0.2232632699F, 0.2236749364F, 0.2240868839F, 0.2244991121F,
  157519. 0.2249116204F, 0.2253244086F, 0.2257374763F, 0.2261508229F,
  157520. 0.2265644481F, 0.2269783514F, 0.2273925326F, 0.2278069911F,
  157521. 0.2282217265F, 0.2286367384F, 0.2290520265F, 0.2294675902F,
  157522. 0.2298834292F, 0.2302995431F, 0.2307159314F, 0.2311325937F,
  157523. 0.2315495297F, 0.2319667388F, 0.2323842207F, 0.2328019749F,
  157524. 0.2332200011F, 0.2336382988F, 0.2340568675F, 0.2344757070F,
  157525. 0.2348948166F, 0.2353141961F, 0.2357338450F, 0.2361537629F,
  157526. 0.2365739493F, 0.2369944038F, 0.2374151261F, 0.2378361156F,
  157527. 0.2382573720F, 0.2386788948F, 0.2391006836F, 0.2395227380F,
  157528. 0.2399450575F, 0.2403676417F, 0.2407904902F, 0.2412136026F,
  157529. 0.2416369783F, 0.2420606171F, 0.2424845185F, 0.2429086820F,
  157530. 0.2433331072F, 0.2437577936F, 0.2441827409F, 0.2446079486F,
  157531. 0.2450334163F, 0.2454591435F, 0.2458851298F, 0.2463113747F,
  157532. 0.2467378779F, 0.2471646389F, 0.2475916573F, 0.2480189325F,
  157533. 0.2484464643F, 0.2488742521F, 0.2493022955F, 0.2497305940F,
  157534. 0.2501591473F, 0.2505879549F, 0.2510170163F, 0.2514463311F,
  157535. 0.2518758989F, 0.2523057193F, 0.2527357916F, 0.2531661157F,
  157536. 0.2535966909F, 0.2540275169F, 0.2544585931F, 0.2548899193F,
  157537. 0.2553214948F, 0.2557533193F, 0.2561853924F, 0.2566177135F,
  157538. 0.2570502822F, 0.2574830981F, 0.2579161608F, 0.2583494697F,
  157539. 0.2587830245F, 0.2592168246F, 0.2596508697F, 0.2600851593F,
  157540. 0.2605196929F, 0.2609544701F, 0.2613894904F, 0.2618247534F,
  157541. 0.2622602586F, 0.2626960055F, 0.2631319938F, 0.2635682230F,
  157542. 0.2640046925F, 0.2644414021F, 0.2648783511F, 0.2653155391F,
  157543. 0.2657529657F, 0.2661906305F, 0.2666285329F, 0.2670666725F,
  157544. 0.2675050489F, 0.2679436616F, 0.2683825101F, 0.2688215940F,
  157545. 0.2692609127F, 0.2697004660F, 0.2701402532F, 0.2705802739F,
  157546. 0.2710205278F, 0.2714610142F, 0.2719017327F, 0.2723426830F,
  157547. 0.2727838644F, 0.2732252766F, 0.2736669191F, 0.2741087914F,
  157548. 0.2745508930F, 0.2749932235F, 0.2754357824F, 0.2758785693F,
  157549. 0.2763215837F, 0.2767648251F, 0.2772082930F, 0.2776519870F,
  157550. 0.2780959066F, 0.2785400513F, 0.2789844207F, 0.2794290143F,
  157551. 0.2798738316F, 0.2803188722F, 0.2807641355F, 0.2812096211F,
  157552. 0.2816553286F, 0.2821012574F, 0.2825474071F, 0.2829937773F,
  157553. 0.2834403673F, 0.2838871768F, 0.2843342053F, 0.2847814523F,
  157554. 0.2852289174F, 0.2856765999F, 0.2861244996F, 0.2865726159F,
  157555. 0.2870209482F, 0.2874694962F, 0.2879182594F, 0.2883672372F,
  157556. 0.2888164293F, 0.2892658350F, 0.2897154540F, 0.2901652858F,
  157557. 0.2906153298F, 0.2910655856F, 0.2915160527F, 0.2919667306F,
  157558. 0.2924176189F, 0.2928687171F, 0.2933200246F, 0.2937715409F,
  157559. 0.2942232657F, 0.2946751984F, 0.2951273386F, 0.2955796856F,
  157560. 0.2960322391F, 0.2964849986F, 0.2969379636F, 0.2973911335F,
  157561. 0.2978445080F, 0.2982980864F, 0.2987518684F, 0.2992058534F,
  157562. 0.2996600409F, 0.3001144305F, 0.3005690217F, 0.3010238139F,
  157563. 0.3014788067F, 0.3019339995F, 0.3023893920F, 0.3028449835F,
  157564. 0.3033007736F, 0.3037567618F, 0.3042129477F, 0.3046693306F,
  157565. 0.3051259102F, 0.3055826859F, 0.3060396572F, 0.3064968236F,
  157566. 0.3069541847F, 0.3074117399F, 0.3078694887F, 0.3083274307F,
  157567. 0.3087855653F, 0.3092438920F, 0.3097024104F, 0.3101611199F,
  157568. 0.3106200200F, 0.3110791103F, 0.3115383902F, 0.3119978592F,
  157569. 0.3124575169F, 0.3129173627F, 0.3133773961F, 0.3138376166F,
  157570. 0.3142980238F, 0.3147586170F, 0.3152193959F, 0.3156803598F,
  157571. 0.3161415084F, 0.3166028410F, 0.3170643573F, 0.3175260566F,
  157572. 0.3179879384F, 0.3184500023F, 0.3189122478F, 0.3193746743F,
  157573. 0.3198372814F, 0.3203000685F, 0.3207630351F, 0.3212261807F,
  157574. 0.3216895048F, 0.3221530069F, 0.3226166865F, 0.3230805430F,
  157575. 0.3235445760F, 0.3240087849F, 0.3244731693F, 0.3249377285F,
  157576. 0.3254024622F, 0.3258673698F, 0.3263324507F, 0.3267977045F,
  157577. 0.3272631306F, 0.3277287286F, 0.3281944978F, 0.3286604379F,
  157578. 0.3291265482F, 0.3295928284F, 0.3300592777F, 0.3305258958F,
  157579. 0.3309926821F, 0.3314596361F, 0.3319267573F, 0.3323940451F,
  157580. 0.3328614990F, 0.3333291186F, 0.3337969033F, 0.3342648525F,
  157581. 0.3347329658F, 0.3352012427F, 0.3356696825F, 0.3361382849F,
  157582. 0.3366070492F, 0.3370759749F, 0.3375450616F, 0.3380143087F,
  157583. 0.3384837156F, 0.3389532819F, 0.3394230071F, 0.3398928905F,
  157584. 0.3403629317F, 0.3408331302F, 0.3413034854F, 0.3417739967F,
  157585. 0.3422446638F, 0.3427154860F, 0.3431864628F, 0.3436575938F,
  157586. 0.3441288782F, 0.3446003158F, 0.3450719058F, 0.3455436478F,
  157587. 0.3460155412F, 0.3464875856F, 0.3469597804F, 0.3474321250F,
  157588. 0.3479046189F, 0.3483772617F, 0.3488500527F, 0.3493229914F,
  157589. 0.3497960774F, 0.3502693100F, 0.3507426887F, 0.3512162131F,
  157590. 0.3516898825F, 0.3521636965F, 0.3526376545F, 0.3531117559F,
  157591. 0.3535860003F, 0.3540603870F, 0.3545349157F, 0.3550095856F,
  157592. 0.3554843964F, 0.3559593474F, 0.3564344381F, 0.3569096680F,
  157593. 0.3573850366F, 0.3578605432F, 0.3583361875F, 0.3588119687F,
  157594. 0.3592878865F, 0.3597639402F, 0.3602401293F, 0.3607164533F,
  157595. 0.3611929117F, 0.3616695038F, 0.3621462292F, 0.3626230873F,
  157596. 0.3631000776F, 0.3635771995F, 0.3640544525F, 0.3645318360F,
  157597. 0.3650093496F, 0.3654869926F, 0.3659647645F, 0.3664426648F,
  157598. 0.3669206930F, 0.3673988484F, 0.3678771306F, 0.3683555390F,
  157599. 0.3688340731F, 0.3693127322F, 0.3697915160F, 0.3702704237F,
  157600. 0.3707494549F, 0.3712286091F, 0.3717078857F, 0.3721872840F,
  157601. 0.3726668037F, 0.3731464441F, 0.3736262047F, 0.3741060850F,
  157602. 0.3745860843F, 0.3750662023F, 0.3755464382F, 0.3760267915F,
  157603. 0.3765072618F, 0.3769878484F, 0.3774685509F, 0.3779493686F,
  157604. 0.3784303010F, 0.3789113475F, 0.3793925076F, 0.3798737809F,
  157605. 0.3803551666F, 0.3808366642F, 0.3813182733F, 0.3817999932F,
  157606. 0.3822818234F, 0.3827637633F, 0.3832458124F, 0.3837279702F,
  157607. 0.3842102360F, 0.3846926093F, 0.3851750897F, 0.3856576764F,
  157608. 0.3861403690F, 0.3866231670F, 0.3871060696F, 0.3875890765F,
  157609. 0.3880721870F, 0.3885554007F, 0.3890387168F, 0.3895221349F,
  157610. 0.3900056544F, 0.3904892748F, 0.3909729955F, 0.3914568160F,
  157611. 0.3919407356F, 0.3924247539F, 0.3929088702F, 0.3933930841F,
  157612. 0.3938773949F, 0.3943618021F, 0.3948463052F, 0.3953309035F,
  157613. 0.3958155966F, 0.3963003838F, 0.3967852646F, 0.3972702385F,
  157614. 0.3977553048F, 0.3982404631F, 0.3987257127F, 0.3992110531F,
  157615. 0.3996964838F, 0.4001820041F, 0.4006676136F, 0.4011533116F,
  157616. 0.4016390976F, 0.4021249710F, 0.4026109313F, 0.4030969779F,
  157617. 0.4035831102F, 0.4040693277F, 0.4045556299F, 0.4050420160F,
  157618. 0.4055284857F, 0.4060150383F, 0.4065016732F, 0.4069883899F,
  157619. 0.4074751879F, 0.4079620665F, 0.4084490252F, 0.4089360635F,
  157620. 0.4094231807F, 0.4099103763F, 0.4103976498F, 0.4108850005F,
  157621. 0.4113724280F, 0.4118599315F, 0.4123475107F, 0.4128351648F,
  157622. 0.4133228934F, 0.4138106959F, 0.4142985716F, 0.4147865201F,
  157623. 0.4152745408F, 0.4157626330F, 0.4162507963F, 0.4167390301F,
  157624. 0.4172273337F, 0.4177157067F, 0.4182041484F, 0.4186926583F,
  157625. 0.4191812359F, 0.4196698805F, 0.4201585915F, 0.4206473685F,
  157626. 0.4211362108F, 0.4216251179F, 0.4221140892F, 0.4226031241F,
  157627. 0.4230922221F, 0.4235813826F, 0.4240706050F, 0.4245598887F,
  157628. 0.4250492332F, 0.4255386379F, 0.4260281022F, 0.4265176256F,
  157629. 0.4270072075F, 0.4274968473F, 0.4279865445F, 0.4284762984F,
  157630. 0.4289661086F, 0.4294559743F, 0.4299458951F, 0.4304358704F,
  157631. 0.4309258996F, 0.4314159822F, 0.4319061175F, 0.4323963050F,
  157632. 0.4328865441F, 0.4333768342F, 0.4338671749F, 0.4343575654F,
  157633. 0.4348480052F, 0.4353384938F, 0.4358290306F, 0.4363196149F,
  157634. 0.4368102463F, 0.4373009241F, 0.4377916478F, 0.4382824168F,
  157635. 0.4387732305F, 0.4392640884F, 0.4397549899F, 0.4402459343F,
  157636. 0.4407369212F, 0.4412279499F, 0.4417190198F, 0.4422101305F,
  157637. 0.4427012813F, 0.4431924717F, 0.4436837010F, 0.4441749686F,
  157638. 0.4446662742F, 0.4451576169F, 0.4456489963F, 0.4461404118F,
  157639. 0.4466318628F, 0.4471233487F, 0.4476148690F, 0.4481064230F,
  157640. 0.4485980103F, 0.4490896302F, 0.4495812821F, 0.4500729654F,
  157641. 0.4505646797F, 0.4510564243F, 0.4515481986F, 0.4520400021F,
  157642. 0.4525318341F, 0.4530236942F, 0.4535155816F, 0.4540074959F,
  157643. 0.4544994365F, 0.4549914028F, 0.4554833941F, 0.4559754100F,
  157644. 0.4564674499F, 0.4569595131F, 0.4574515991F, 0.4579437074F,
  157645. 0.4584358372F, 0.4589279881F, 0.4594201595F, 0.4599123508F,
  157646. 0.4604045615F, 0.4608967908F, 0.4613890383F, 0.4618813034F,
  157647. 0.4623735855F, 0.4628658841F, 0.4633581984F, 0.4638505281F,
  157648. 0.4643428724F, 0.4648352308F, 0.4653276028F, 0.4658199877F,
  157649. 0.4663123849F, 0.4668047940F, 0.4672972143F, 0.4677896451F,
  157650. 0.4682820861F, 0.4687745365F, 0.4692669958F, 0.4697594634F,
  157651. 0.4702519387F, 0.4707444211F, 0.4712369102F, 0.4717294052F,
  157652. 0.4722219056F, 0.4727144109F, 0.4732069204F, 0.4736994336F,
  157653. 0.4741919498F, 0.4746844686F, 0.4751769893F, 0.4756695113F,
  157654. 0.4761620341F, 0.4766545571F, 0.4771470797F, 0.4776396013F,
  157655. 0.4781321213F, 0.4786246392F, 0.4791171544F, 0.4796096663F,
  157656. 0.4801021744F, 0.4805946779F, 0.4810871765F, 0.4815796694F,
  157657. 0.4820721561F, 0.4825646360F, 0.4830571086F, 0.4835495732F,
  157658. 0.4840420293F, 0.4845344763F, 0.4850269136F, 0.4855193407F,
  157659. 0.4860117569F, 0.4865041617F, 0.4869965545F, 0.4874889347F,
  157660. 0.4879813018F, 0.4884736551F, 0.4889659941F, 0.4894583182F,
  157661. 0.4899506268F, 0.4904429193F, 0.4909351952F, 0.4914274538F,
  157662. 0.4919196947F, 0.4924119172F, 0.4929041207F, 0.4933963046F,
  157663. 0.4938884685F, 0.4943806116F, 0.4948727335F, 0.4953648335F,
  157664. 0.4958569110F, 0.4963489656F, 0.4968409965F, 0.4973330032F,
  157665. 0.4978249852F, 0.4983169419F, 0.4988088726F, 0.4993007768F,
  157666. 0.4997926539F, 0.5002845034F, 0.5007763247F, 0.5012681171F,
  157667. 0.5017598801F, 0.5022516132F, 0.5027433157F, 0.5032349871F,
  157668. 0.5037266268F, 0.5042182341F, 0.5047098086F, 0.5052013497F,
  157669. 0.5056928567F, 0.5061843292F, 0.5066757664F, 0.5071671679F,
  157670. 0.5076585330F, 0.5081498613F, 0.5086411520F, 0.5091324047F,
  157671. 0.5096236187F, 0.5101147934F, 0.5106059284F, 0.5110970230F,
  157672. 0.5115880766F, 0.5120790887F, 0.5125700587F, 0.5130609860F,
  157673. 0.5135518700F, 0.5140427102F, 0.5145335059F, 0.5150242566F,
  157674. 0.5155149618F, 0.5160056208F, 0.5164962331F, 0.5169867980F,
  157675. 0.5174773151F, 0.5179677837F, 0.5184582033F, 0.5189485733F,
  157676. 0.5194388931F, 0.5199291621F, 0.5204193798F, 0.5209095455F,
  157677. 0.5213996588F, 0.5218897190F, 0.5223797256F, 0.5228696779F,
  157678. 0.5233595755F, 0.5238494177F, 0.5243392039F, 0.5248289337F,
  157679. 0.5253186063F, 0.5258082213F, 0.5262977781F, 0.5267872760F,
  157680. 0.5272767146F, 0.5277660932F, 0.5282554112F, 0.5287446682F,
  157681. 0.5292338635F, 0.5297229965F, 0.5302120667F, 0.5307010736F,
  157682. 0.5311900164F, 0.5316788947F, 0.5321677079F, 0.5326564554F,
  157683. 0.5331451366F, 0.5336337511F, 0.5341222981F, 0.5346107771F,
  157684. 0.5350991876F, 0.5355875290F, 0.5360758007F, 0.5365640021F,
  157685. 0.5370521327F, 0.5375401920F, 0.5380281792F, 0.5385160939F,
  157686. 0.5390039355F, 0.5394917034F, 0.5399793971F, 0.5404670159F,
  157687. 0.5409545594F, 0.5414420269F, 0.5419294179F, 0.5424167318F,
  157688. 0.5429039680F, 0.5433911261F, 0.5438782053F, 0.5443652051F,
  157689. 0.5448521250F, 0.5453389644F, 0.5458257228F, 0.5463123995F,
  157690. 0.5467989940F, 0.5472855057F, 0.5477719341F, 0.5482582786F,
  157691. 0.5487445387F, 0.5492307137F, 0.5497168031F, 0.5502028063F,
  157692. 0.5506887228F, 0.5511745520F, 0.5516602934F, 0.5521459463F,
  157693. 0.5526315103F, 0.5531169847F, 0.5536023690F, 0.5540876626F,
  157694. 0.5545728649F, 0.5550579755F, 0.5555429937F, 0.5560279189F,
  157695. 0.5565127507F, 0.5569974884F, 0.5574821315F, 0.5579666794F,
  157696. 0.5584511316F, 0.5589354875F, 0.5594197465F, 0.5599039080F,
  157697. 0.5603879716F, 0.5608719367F, 0.5613558026F, 0.5618395689F,
  157698. 0.5623232350F, 0.5628068002F, 0.5632902642F, 0.5637736262F,
  157699. 0.5642568858F, 0.5647400423F, 0.5652230953F, 0.5657060442F,
  157700. 0.5661888883F, 0.5666716272F, 0.5671542603F, 0.5676367870F,
  157701. 0.5681192069F, 0.5686015192F, 0.5690837235F, 0.5695658192F,
  157702. 0.5700478058F, 0.5705296827F, 0.5710114494F, 0.5714931052F,
  157703. 0.5719746497F, 0.5724560822F, 0.5729374023F, 0.5734186094F,
  157704. 0.5738997029F, 0.5743806823F, 0.5748615470F, 0.5753422965F,
  157705. 0.5758229301F, 0.5763034475F, 0.5767838480F, 0.5772641310F,
  157706. 0.5777442960F, 0.5782243426F, 0.5787042700F, 0.5791840778F,
  157707. 0.5796637654F, 0.5801433322F, 0.5806227778F, 0.5811021016F,
  157708. 0.5815813029F, 0.5820603814F, 0.5825393363F, 0.5830181673F,
  157709. 0.5834968737F, 0.5839754549F, 0.5844539105F, 0.5849322399F,
  157710. 0.5854104425F, 0.5858885179F, 0.5863664653F, 0.5868442844F,
  157711. 0.5873219746F, 0.5877995353F, 0.5882769660F, 0.5887542661F,
  157712. 0.5892314351F, 0.5897084724F, 0.5901853776F, 0.5906621500F,
  157713. 0.5911387892F, 0.5916152945F, 0.5920916655F, 0.5925679016F,
  157714. 0.5930440022F, 0.5935199669F, 0.5939957950F, 0.5944714861F,
  157715. 0.5949470396F, 0.5954224550F, 0.5958977317F, 0.5963728692F,
  157716. 0.5968478669F, 0.5973227244F, 0.5977974411F, 0.5982720163F,
  157717. 0.5987464497F, 0.5992207407F, 0.5996948887F, 0.6001688932F,
  157718. 0.6006427537F, 0.6011164696F, 0.6015900405F, 0.6020634657F,
  157719. 0.6025367447F, 0.6030098770F, 0.6034828621F, 0.6039556995F,
  157720. 0.6044283885F, 0.6049009288F, 0.6053733196F, 0.6058455606F,
  157721. 0.6063176512F, 0.6067895909F, 0.6072613790F, 0.6077330152F,
  157722. 0.6082044989F, 0.6086758295F, 0.6091470065F, 0.6096180294F,
  157723. 0.6100888977F, 0.6105596108F, 0.6110301682F, 0.6115005694F,
  157724. 0.6119708139F, 0.6124409011F, 0.6129108305F, 0.6133806017F,
  157725. 0.6138502139F, 0.6143196669F, 0.6147889599F, 0.6152580926F,
  157726. 0.6157270643F, 0.6161958746F, 0.6166645230F, 0.6171330088F,
  157727. 0.6176013317F, 0.6180694910F, 0.6185374863F, 0.6190053171F,
  157728. 0.6194729827F, 0.6199404828F, 0.6204078167F, 0.6208749841F,
  157729. 0.6213419842F, 0.6218088168F, 0.6222754811F, 0.6227419768F,
  157730. 0.6232083032F, 0.6236744600F, 0.6241404465F, 0.6246062622F,
  157731. 0.6250719067F, 0.6255373795F, 0.6260026799F, 0.6264678076F,
  157732. 0.6269327619F, 0.6273975425F, 0.6278621487F, 0.6283265800F,
  157733. 0.6287908361F, 0.6292549163F, 0.6297188201F, 0.6301825471F,
  157734. 0.6306460966F, 0.6311094683F, 0.6315726617F, 0.6320356761F,
  157735. 0.6324985111F, 0.6329611662F, 0.6334236410F, 0.6338859348F,
  157736. 0.6343480472F, 0.6348099777F, 0.6352717257F, 0.6357332909F,
  157737. 0.6361946726F, 0.6366558704F, 0.6371168837F, 0.6375777122F,
  157738. 0.6380383552F, 0.6384988123F, 0.6389590830F, 0.6394191668F,
  157739. 0.6398790631F, 0.6403387716F, 0.6407982916F, 0.6412576228F,
  157740. 0.6417167645F, 0.6421757163F, 0.6426344778F, 0.6430930483F,
  157741. 0.6435514275F, 0.6440096149F, 0.6444676098F, 0.6449254119F,
  157742. 0.6453830207F, 0.6458404356F, 0.6462976562F, 0.6467546820F,
  157743. 0.6472115125F, 0.6476681472F, 0.6481245856F, 0.6485808273F,
  157744. 0.6490368717F, 0.6494927183F, 0.6499483667F, 0.6504038164F,
  157745. 0.6508590670F, 0.6513141178F, 0.6517689684F, 0.6522236185F,
  157746. 0.6526780673F, 0.6531323146F, 0.6535863598F, 0.6540402024F,
  157747. 0.6544938419F, 0.6549472779F, 0.6554005099F, 0.6558535373F,
  157748. 0.6563063598F, 0.6567589769F, 0.6572113880F, 0.6576635927F,
  157749. 0.6581155906F, 0.6585673810F, 0.6590189637F, 0.6594703380F,
  157750. 0.6599215035F, 0.6603724598F, 0.6608232064F, 0.6612737427F,
  157751. 0.6617240684F, 0.6621741829F, 0.6626240859F, 0.6630737767F,
  157752. 0.6635232550F, 0.6639725202F, 0.6644215720F, 0.6648704098F,
  157753. 0.6653190332F, 0.6657674417F, 0.6662156348F, 0.6666636121F,
  157754. 0.6671113731F, 0.6675589174F, 0.6680062445F, 0.6684533538F,
  157755. 0.6689002450F, 0.6693469177F, 0.6697933712F, 0.6702396052F,
  157756. 0.6706856193F, 0.6711314129F, 0.6715769855F, 0.6720223369F,
  157757. 0.6724674664F, 0.6729123736F, 0.6733570581F, 0.6738015194F,
  157758. 0.6742457570F, 0.6746897706F, 0.6751335596F, 0.6755771236F,
  157759. 0.6760204621F, 0.6764635747F, 0.6769064609F, 0.6773491204F,
  157760. 0.6777915525F, 0.6782337570F, 0.6786757332F, 0.6791174809F,
  157761. 0.6795589995F, 0.6800002886F, 0.6804413477F, 0.6808821765F,
  157762. 0.6813227743F, 0.6817631409F, 0.6822032758F, 0.6826431785F,
  157763. 0.6830828485F, 0.6835222855F, 0.6839614890F, 0.6844004585F,
  157764. 0.6848391936F, 0.6852776939F, 0.6857159589F, 0.6861539883F,
  157765. 0.6865917815F, 0.6870293381F, 0.6874666576F, 0.6879037398F,
  157766. 0.6883405840F, 0.6887771899F, 0.6892135571F, 0.6896496850F,
  157767. 0.6900855733F, 0.6905212216F, 0.6909566294F, 0.6913917963F,
  157768. 0.6918267218F, 0.6922614055F, 0.6926958471F, 0.6931300459F,
  157769. 0.6935640018F, 0.6939977141F, 0.6944311825F, 0.6948644066F,
  157770. 0.6952973859F, 0.6957301200F, 0.6961626085F, 0.6965948510F,
  157771. 0.6970268470F, 0.6974585961F, 0.6978900980F, 0.6983213521F,
  157772. 0.6987523580F, 0.6991831154F, 0.6996136238F, 0.7000438828F,
  157773. 0.7004738921F, 0.7009036510F, 0.7013331594F, 0.7017624166F,
  157774. 0.7021914224F, 0.7026201763F, 0.7030486779F, 0.7034769268F,
  157775. 0.7039049226F, 0.7043326648F, 0.7047601531F, 0.7051873870F,
  157776. 0.7056143662F, 0.7060410902F, 0.7064675586F, 0.7068937711F,
  157777. 0.7073197271F, 0.7077454264F, 0.7081708684F, 0.7085960529F,
  157778. 0.7090209793F, 0.7094456474F, 0.7098700566F, 0.7102942066F,
  157779. 0.7107180970F, 0.7111417274F, 0.7115650974F, 0.7119882066F,
  157780. 0.7124110545F, 0.7128336409F, 0.7132559653F, 0.7136780272F,
  157781. 0.7140998264F, 0.7145213624F, 0.7149426348F, 0.7153636433F,
  157782. 0.7157843874F, 0.7162048668F, 0.7166250810F, 0.7170450296F,
  157783. 0.7174647124F, 0.7178841289F, 0.7183032786F, 0.7187221613F,
  157784. 0.7191407765F, 0.7195591239F, 0.7199772030F, 0.7203950135F,
  157785. 0.7208125550F, 0.7212298271F, 0.7216468294F, 0.7220635616F,
  157786. 0.7224800233F, 0.7228962140F, 0.7233121335F, 0.7237277813F,
  157787. 0.7241431571F, 0.7245582604F, 0.7249730910F, 0.7253876484F,
  157788. 0.7258019322F, 0.7262159422F, 0.7266296778F, 0.7270431388F,
  157789. 0.7274563247F, 0.7278692353F, 0.7282818700F, 0.7286942287F,
  157790. 0.7291063108F, 0.7295181160F, 0.7299296440F, 0.7303408944F,
  157791. 0.7307518669F, 0.7311625609F, 0.7315729763F, 0.7319831126F,
  157792. 0.7323929695F, 0.7328025466F, 0.7332118435F, 0.7336208600F,
  157793. 0.7340295955F, 0.7344380499F, 0.7348462226F, 0.7352541134F,
  157794. 0.7356617220F, 0.7360690478F, 0.7364760907F, 0.7368828502F,
  157795. 0.7372893259F, 0.7376955176F, 0.7381014249F, 0.7385070475F,
  157796. 0.7389123849F, 0.7393174368F, 0.7397222029F, 0.7401266829F,
  157797. 0.7405308763F, 0.7409347829F, 0.7413384023F, 0.7417417341F,
  157798. 0.7421447780F, 0.7425475338F, 0.7429500009F, 0.7433521791F,
  157799. 0.7437540681F, 0.7441556674F, 0.7445569769F, 0.7449579960F,
  157800. 0.7453587245F, 0.7457591621F, 0.7461593084F, 0.7465591631F,
  157801. 0.7469587259F, 0.7473579963F, 0.7477569741F, 0.7481556590F,
  157802. 0.7485540506F, 0.7489521486F, 0.7493499526F, 0.7497474623F,
  157803. 0.7501446775F, 0.7505415977F, 0.7509382227F, 0.7513345521F,
  157804. 0.7517305856F, 0.7521263229F, 0.7525217636F, 0.7529169074F,
  157805. 0.7533117541F, 0.7537063032F, 0.7541005545F, 0.7544945076F,
  157806. 0.7548881623F, 0.7552815182F, 0.7556745749F, 0.7560673323F,
  157807. 0.7564597899F, 0.7568519474F, 0.7572438046F, 0.7576353611F,
  157808. 0.7580266166F, 0.7584175708F, 0.7588082235F, 0.7591985741F,
  157809. 0.7595886226F, 0.7599783685F, 0.7603678116F, 0.7607569515F,
  157810. 0.7611457879F, 0.7615343206F, 0.7619225493F, 0.7623104735F,
  157811. 0.7626980931F, 0.7630854078F, 0.7634724171F, 0.7638591209F,
  157812. 0.7642455188F, 0.7646316106F, 0.7650173959F, 0.7654028744F,
  157813. 0.7657880459F, 0.7661729100F, 0.7665574664F, 0.7669417150F,
  157814. 0.7673256553F, 0.7677092871F, 0.7680926100F, 0.7684756239F,
  157815. 0.7688583284F, 0.7692407232F, 0.7696228080F, 0.7700045826F,
  157816. 0.7703860467F, 0.7707671999F, 0.7711480420F, 0.7715285728F,
  157817. 0.7719087918F, 0.7722886989F, 0.7726682938F, 0.7730475762F,
  157818. 0.7734265458F, 0.7738052023F, 0.7741835454F, 0.7745615750F,
  157819. 0.7749392906F, 0.7753166921F, 0.7756937791F, 0.7760705514F,
  157820. 0.7764470087F, 0.7768231508F, 0.7771989773F, 0.7775744880F,
  157821. 0.7779496827F, 0.7783245610F, 0.7786991227F, 0.7790733676F,
  157822. 0.7794472953F, 0.7798209056F, 0.7801941982F, 0.7805671729F,
  157823. 0.7809398294F, 0.7813121675F, 0.7816841869F, 0.7820558873F,
  157824. 0.7824272684F, 0.7827983301F, 0.7831690720F, 0.7835394940F,
  157825. 0.7839095957F, 0.7842793768F, 0.7846488373F, 0.7850179767F,
  157826. 0.7853867948F, 0.7857552914F, 0.7861234663F, 0.7864913191F,
  157827. 0.7868588497F, 0.7872260578F, 0.7875929431F, 0.7879595055F,
  157828. 0.7883257445F, 0.7886916601F, 0.7890572520F, 0.7894225198F,
  157829. 0.7897874635F, 0.7901520827F, 0.7905163772F, 0.7908803468F,
  157830. 0.7912439912F, 0.7916073102F, 0.7919703035F, 0.7923329710F,
  157831. 0.7926953124F, 0.7930573274F, 0.7934190158F, 0.7937803774F,
  157832. 0.7941414120F, 0.7945021193F, 0.7948624991F, 0.7952225511F,
  157833. 0.7955822752F, 0.7959416711F, 0.7963007387F, 0.7966594775F,
  157834. 0.7970178875F, 0.7973759685F, 0.7977337201F, 0.7980911422F,
  157835. 0.7984482346F, 0.7988049970F, 0.7991614292F, 0.7995175310F,
  157836. 0.7998733022F, 0.8002287426F, 0.8005838519F, 0.8009386299F,
  157837. 0.8012930765F, 0.8016471914F, 0.8020009744F, 0.8023544253F,
  157838. 0.8027075438F, 0.8030603298F, 0.8034127831F, 0.8037649035F,
  157839. 0.8041166906F, 0.8044681445F, 0.8048192647F, 0.8051700512F,
  157840. 0.8055205038F, 0.8058706222F, 0.8062204062F, 0.8065698556F,
  157841. 0.8069189702F, 0.8072677499F, 0.8076161944F, 0.8079643036F,
  157842. 0.8083120772F, 0.8086595151F, 0.8090066170F, 0.8093533827F,
  157843. 0.8096998122F, 0.8100459051F, 0.8103916613F, 0.8107370806F,
  157844. 0.8110821628F, 0.8114269077F, 0.8117713151F, 0.8121153849F,
  157845. 0.8124591169F, 0.8128025108F, 0.8131455666F, 0.8134882839F,
  157846. 0.8138306627F, 0.8141727027F, 0.8145144038F, 0.8148557658F,
  157847. 0.8151967886F, 0.8155374718F, 0.8158778154F, 0.8162178192F,
  157848. 0.8165574830F, 0.8168968067F, 0.8172357900F, 0.8175744328F,
  157849. 0.8179127349F, 0.8182506962F, 0.8185883164F, 0.8189255955F,
  157850. 0.8192625332F, 0.8195991295F, 0.8199353840F, 0.8202712967F,
  157851. 0.8206068673F, 0.8209420958F, 0.8212769820F, 0.8216115256F,
  157852. 0.8219457266F, 0.8222795848F, 0.8226131000F, 0.8229462721F,
  157853. 0.8232791009F, 0.8236115863F, 0.8239437280F, 0.8242755260F,
  157854. 0.8246069801F, 0.8249380901F, 0.8252688559F, 0.8255992774F,
  157855. 0.8259293544F, 0.8262590867F, 0.8265884741F, 0.8269175167F,
  157856. 0.8272462141F, 0.8275745663F, 0.8279025732F, 0.8282302344F,
  157857. 0.8285575501F, 0.8288845199F, 0.8292111437F, 0.8295374215F,
  157858. 0.8298633530F, 0.8301889382F, 0.8305141768F, 0.8308390688F,
  157859. 0.8311636141F, 0.8314878124F, 0.8318116637F, 0.8321351678F,
  157860. 0.8324583246F, 0.8327811340F, 0.8331035957F, 0.8334257098F,
  157861. 0.8337474761F, 0.8340688944F, 0.8343899647F, 0.8347106867F,
  157862. 0.8350310605F, 0.8353510857F, 0.8356707624F, 0.8359900904F,
  157863. 0.8363090696F, 0.8366276999F, 0.8369459811F, 0.8372639131F,
  157864. 0.8375814958F, 0.8378987292F, 0.8382156130F, 0.8385321472F,
  157865. 0.8388483316F, 0.8391641662F, 0.8394796508F, 0.8397947853F,
  157866. 0.8401095697F, 0.8404240037F, 0.8407380873F, 0.8410518204F,
  157867. 0.8413652029F, 0.8416782347F, 0.8419909156F, 0.8423032456F,
  157868. 0.8426152245F, 0.8429268523F, 0.8432381289F, 0.8435490541F,
  157869. 0.8438596279F, 0.8441698502F, 0.8444797208F, 0.8447892396F,
  157870. 0.8450984067F, 0.8454072218F, 0.8457156849F, 0.8460237959F,
  157871. 0.8463315547F, 0.8466389612F, 0.8469460154F, 0.8472527170F,
  157872. 0.8475590661F, 0.8478650625F, 0.8481707063F, 0.8484759971F,
  157873. 0.8487809351F, 0.8490855201F, 0.8493897521F, 0.8496936308F,
  157874. 0.8499971564F, 0.8503003286F, 0.8506031474F, 0.8509056128F,
  157875. 0.8512077246F, 0.8515094828F, 0.8518108872F, 0.8521119379F,
  157876. 0.8524126348F, 0.8527129777F, 0.8530129666F, 0.8533126015F,
  157877. 0.8536118822F, 0.8539108087F, 0.8542093809F, 0.8545075988F,
  157878. 0.8548054623F, 0.8551029712F, 0.8554001257F, 0.8556969255F,
  157879. 0.8559933707F, 0.8562894611F, 0.8565851968F, 0.8568805775F,
  157880. 0.8571756034F, 0.8574702743F, 0.8577645902F, 0.8580585509F,
  157881. 0.8583521566F, 0.8586454070F, 0.8589383021F, 0.8592308420F,
  157882. 0.8595230265F, 0.8598148556F, 0.8601063292F, 0.8603974473F,
  157883. 0.8606882098F, 0.8609786167F, 0.8612686680F, 0.8615583636F,
  157884. 0.8618477034F, 0.8621366874F, 0.8624253156F, 0.8627135878F,
  157885. 0.8630015042F, 0.8632890646F, 0.8635762690F, 0.8638631173F,
  157886. 0.8641496096F, 0.8644357457F, 0.8647215257F, 0.8650069495F,
  157887. 0.8652920171F, 0.8655767283F, 0.8658610833F, 0.8661450820F,
  157888. 0.8664287243F, 0.8667120102F, 0.8669949397F, 0.8672775127F,
  157889. 0.8675597293F, 0.8678415894F, 0.8681230929F, 0.8684042398F,
  157890. 0.8686850302F, 0.8689654640F, 0.8692455412F, 0.8695252617F,
  157891. 0.8698046255F, 0.8700836327F, 0.8703622831F, 0.8706405768F,
  157892. 0.8709185138F, 0.8711960940F, 0.8714733174F, 0.8717501840F,
  157893. 0.8720266939F, 0.8723028469F, 0.8725786430F, 0.8728540824F,
  157894. 0.8731291648F, 0.8734038905F, 0.8736782592F, 0.8739522711F,
  157895. 0.8742259261F, 0.8744992242F, 0.8747721653F, 0.8750447496F,
  157896. 0.8753169770F, 0.8755888475F, 0.8758603611F, 0.8761315177F,
  157897. 0.8764023175F, 0.8766727603F, 0.8769428462F, 0.8772125752F,
  157898. 0.8774819474F, 0.8777509626F, 0.8780196209F, 0.8782879224F,
  157899. 0.8785558669F, 0.8788234546F, 0.8790906854F, 0.8793575594F,
  157900. 0.8796240765F, 0.8798902368F, 0.8801560403F, 0.8804214870F,
  157901. 0.8806865768F, 0.8809513099F, 0.8812156863F, 0.8814797059F,
  157902. 0.8817433687F, 0.8820066749F, 0.8822696243F, 0.8825322171F,
  157903. 0.8827944532F, 0.8830563327F, 0.8833178556F, 0.8835790219F,
  157904. 0.8838398316F, 0.8841002848F, 0.8843603815F, 0.8846201217F,
  157905. 0.8848795054F, 0.8851385327F, 0.8853972036F, 0.8856555182F,
  157906. 0.8859134764F, 0.8861710783F, 0.8864283239F, 0.8866852133F,
  157907. 0.8869417464F, 0.8871979234F, 0.8874537443F, 0.8877092090F,
  157908. 0.8879643177F, 0.8882190704F, 0.8884734671F, 0.8887275078F,
  157909. 0.8889811927F, 0.8892345216F, 0.8894874948F, 0.8897401122F,
  157910. 0.8899923738F, 0.8902442798F, 0.8904958301F, 0.8907470248F,
  157911. 0.8909978640F, 0.8912483477F, 0.8914984759F, 0.8917482487F,
  157912. 0.8919976662F, 0.8922467284F, 0.8924954353F, 0.8927437871F,
  157913. 0.8929917837F, 0.8932394252F, 0.8934867118F, 0.8937336433F,
  157914. 0.8939802199F, 0.8942264417F, 0.8944723087F, 0.8947178210F,
  157915. 0.8949629785F, 0.8952077815F, 0.8954522299F, 0.8956963239F,
  157916. 0.8959400634F, 0.8961834486F, 0.8964264795F, 0.8966691561F,
  157917. 0.8969114786F, 0.8971534470F, 0.8973950614F, 0.8976363219F,
  157918. 0.8978772284F, 0.8981177812F, 0.8983579802F, 0.8985978256F,
  157919. 0.8988373174F, 0.8990764556F, 0.8993152405F, 0.8995536720F,
  157920. 0.8997917502F, 0.9000294751F, 0.9002668470F, 0.9005038658F,
  157921. 0.9007405317F, 0.9009768446F, 0.9012128048F, 0.9014484123F,
  157922. 0.9016836671F, 0.9019185693F, 0.9021531191F, 0.9023873165F,
  157923. 0.9026211616F, 0.9028546546F, 0.9030877954F, 0.9033205841F,
  157924. 0.9035530210F, 0.9037851059F, 0.9040168392F, 0.9042482207F,
  157925. 0.9044792507F, 0.9047099293F, 0.9049402564F, 0.9051702323F,
  157926. 0.9053998569F, 0.9056291305F, 0.9058580531F, 0.9060866248F,
  157927. 0.9063148457F, 0.9065427159F, 0.9067702355F, 0.9069974046F,
  157928. 0.9072242233F, 0.9074506917F, 0.9076768100F, 0.9079025782F,
  157929. 0.9081279964F, 0.9083530647F, 0.9085777833F, 0.9088021523F,
  157930. 0.9090261717F, 0.9092498417F, 0.9094731623F, 0.9096961338F,
  157931. 0.9099187561F, 0.9101410295F, 0.9103629540F, 0.9105845297F,
  157932. 0.9108057568F, 0.9110266354F, 0.9112471656F, 0.9114673475F,
  157933. 0.9116871812F, 0.9119066668F, 0.9121258046F, 0.9123445945F,
  157934. 0.9125630367F, 0.9127811314F, 0.9129988786F, 0.9132162785F,
  157935. 0.9134333312F, 0.9136500368F, 0.9138663954F, 0.9140824073F,
  157936. 0.9142980724F, 0.9145133910F, 0.9147283632F, 0.9149429890F,
  157937. 0.9151572687F, 0.9153712023F, 0.9155847900F, 0.9157980319F,
  157938. 0.9160109282F, 0.9162234790F, 0.9164356844F, 0.9166475445F,
  157939. 0.9168590595F, 0.9170702296F, 0.9172810548F, 0.9174915354F,
  157940. 0.9177016714F, 0.9179114629F, 0.9181209102F, 0.9183300134F,
  157941. 0.9185387726F, 0.9187471879F, 0.9189552595F, 0.9191629876F,
  157942. 0.9193703723F, 0.9195774136F, 0.9197841119F, 0.9199904672F,
  157943. 0.9201964797F, 0.9204021495F, 0.9206074767F, 0.9208124616F,
  157944. 0.9210171043F, 0.9212214049F, 0.9214253636F, 0.9216289805F,
  157945. 0.9218322558F, 0.9220351896F, 0.9222377821F, 0.9224400335F,
  157946. 0.9226419439F, 0.9228435134F, 0.9230447423F, 0.9232456307F,
  157947. 0.9234461787F, 0.9236463865F, 0.9238462543F, 0.9240457822F,
  157948. 0.9242449704F, 0.9244438190F, 0.9246423282F, 0.9248404983F,
  157949. 0.9250383293F, 0.9252358214F, 0.9254329747F, 0.9256297896F,
  157950. 0.9258262660F, 0.9260224042F, 0.9262182044F, 0.9264136667F,
  157951. 0.9266087913F, 0.9268035783F, 0.9269980280F, 0.9271921405F,
  157952. 0.9273859160F, 0.9275793546F, 0.9277724566F, 0.9279652221F,
  157953. 0.9281576513F, 0.9283497443F, 0.9285415014F, 0.9287329227F,
  157954. 0.9289240084F, 0.9291147586F, 0.9293051737F, 0.9294952536F,
  157955. 0.9296849987F, 0.9298744091F, 0.9300634850F, 0.9302522266F,
  157956. 0.9304406340F, 0.9306287074F, 0.9308164471F, 0.9310038532F,
  157957. 0.9311909259F, 0.9313776654F, 0.9315640719F, 0.9317501455F,
  157958. 0.9319358865F, 0.9321212951F, 0.9323063713F, 0.9324911155F,
  157959. 0.9326755279F, 0.9328596085F, 0.9330433577F, 0.9332267756F,
  157960. 0.9334098623F, 0.9335926182F, 0.9337750434F, 0.9339571380F,
  157961. 0.9341389023F, 0.9343203366F, 0.9345014409F, 0.9346822155F,
  157962. 0.9348626606F, 0.9350427763F, 0.9352225630F, 0.9354020207F,
  157963. 0.9355811498F, 0.9357599503F, 0.9359384226F, 0.9361165667F,
  157964. 0.9362943830F, 0.9364718716F, 0.9366490327F, 0.9368258666F,
  157965. 0.9370023733F, 0.9371785533F, 0.9373544066F, 0.9375299335F,
  157966. 0.9377051341F, 0.9378800087F, 0.9380545576F, 0.9382287809F,
  157967. 0.9384026787F, 0.9385762515F, 0.9387494993F, 0.9389224223F,
  157968. 0.9390950209F, 0.9392672951F, 0.9394392453F, 0.9396108716F,
  157969. 0.9397821743F, 0.9399531536F, 0.9401238096F, 0.9402941427F,
  157970. 0.9404641530F, 0.9406338407F, 0.9408032061F, 0.9409722495F,
  157971. 0.9411409709F, 0.9413093707F, 0.9414774491F, 0.9416452062F,
  157972. 0.9418126424F, 0.9419797579F, 0.9421465528F, 0.9423130274F,
  157973. 0.9424791819F, 0.9426450166F, 0.9428105317F, 0.9429757274F,
  157974. 0.9431406039F, 0.9433051616F, 0.9434694005F, 0.9436333209F,
  157975. 0.9437969232F, 0.9439602074F, 0.9441231739F, 0.9442858229F,
  157976. 0.9444481545F, 0.9446101691F, 0.9447718669F, 0.9449332481F,
  157977. 0.9450943129F, 0.9452550617F, 0.9454154945F, 0.9455756118F,
  157978. 0.9457354136F, 0.9458949003F, 0.9460540721F, 0.9462129292F,
  157979. 0.9463714719F, 0.9465297003F, 0.9466876149F, 0.9468452157F,
  157980. 0.9470025031F, 0.9471594772F, 0.9473161384F, 0.9474724869F,
  157981. 0.9476285229F, 0.9477842466F, 0.9479396584F, 0.9480947585F,
  157982. 0.9482495470F, 0.9484040243F, 0.9485581906F, 0.9487120462F,
  157983. 0.9488655913F, 0.9490188262F, 0.9491717511F, 0.9493243662F,
  157984. 0.9494766718F, 0.9496286683F, 0.9497803557F, 0.9499317345F,
  157985. 0.9500828047F, 0.9502335668F, 0.9503840209F, 0.9505341673F,
  157986. 0.9506840062F, 0.9508335380F, 0.9509827629F, 0.9511316810F,
  157987. 0.9512802928F, 0.9514285984F, 0.9515765982F, 0.9517242923F,
  157988. 0.9518716810F, 0.9520187646F, 0.9521655434F, 0.9523120176F,
  157989. 0.9524581875F, 0.9526040534F, 0.9527496154F, 0.9528948739F,
  157990. 0.9530398292F, 0.9531844814F, 0.9533288310F, 0.9534728780F,
  157991. 0.9536166229F, 0.9537600659F, 0.9539032071F, 0.9540460470F,
  157992. 0.9541885858F, 0.9543308237F, 0.9544727611F, 0.9546143981F,
  157993. 0.9547557351F, 0.9548967723F, 0.9550375100F, 0.9551779485F,
  157994. 0.9553180881F, 0.9554579290F, 0.9555974714F, 0.9557367158F,
  157995. 0.9558756623F, 0.9560143112F, 0.9561526628F, 0.9562907174F,
  157996. 0.9564284752F, 0.9565659366F, 0.9567031017F, 0.9568399710F,
  157997. 0.9569765446F, 0.9571128229F, 0.9572488061F, 0.9573844944F,
  157998. 0.9575198883F, 0.9576549879F, 0.9577897936F, 0.9579243056F,
  157999. 0.9580585242F, 0.9581924497F, 0.9583260824F, 0.9584594226F,
  158000. 0.9585924705F, 0.9587252264F, 0.9588576906F, 0.9589898634F,
  158001. 0.9591217452F, 0.9592533360F, 0.9593846364F, 0.9595156465F,
  158002. 0.9596463666F, 0.9597767971F, 0.9599069382F, 0.9600367901F,
  158003. 0.9601663533F, 0.9602956279F, 0.9604246143F, 0.9605533128F,
  158004. 0.9606817236F, 0.9608098471F, 0.9609376835F, 0.9610652332F,
  158005. 0.9611924963F, 0.9613194733F, 0.9614461644F, 0.9615725699F,
  158006. 0.9616986901F, 0.9618245253F, 0.9619500757F, 0.9620753418F,
  158007. 0.9622003238F, 0.9623250219F, 0.9624494365F, 0.9625735679F,
  158008. 0.9626974163F, 0.9628209821F, 0.9629442656F, 0.9630672671F,
  158009. 0.9631899868F, 0.9633124251F, 0.9634345822F, 0.9635564585F,
  158010. 0.9636780543F, 0.9637993699F, 0.9639204056F, 0.9640411616F,
  158011. 0.9641616383F, 0.9642818359F, 0.9644017549F, 0.9645213955F,
  158012. 0.9646407579F, 0.9647598426F, 0.9648786497F, 0.9649971797F,
  158013. 0.9651154328F, 0.9652334092F, 0.9653511095F, 0.9654685337F,
  158014. 0.9655856823F, 0.9657025556F, 0.9658191538F, 0.9659354773F,
  158015. 0.9660515263F, 0.9661673013F, 0.9662828024F, 0.9663980300F,
  158016. 0.9665129845F, 0.9666276660F, 0.9667420750F, 0.9668562118F,
  158017. 0.9669700766F, 0.9670836698F, 0.9671969917F, 0.9673100425F,
  158018. 0.9674228227F, 0.9675353325F, 0.9676475722F, 0.9677595422F,
  158019. 0.9678712428F, 0.9679826742F, 0.9680938368F, 0.9682047309F,
  158020. 0.9683153569F, 0.9684257150F, 0.9685358056F, 0.9686456289F,
  158021. 0.9687551853F, 0.9688644752F, 0.9689734987F, 0.9690822564F,
  158022. 0.9691907483F, 0.9692989750F, 0.9694069367F, 0.9695146337F,
  158023. 0.9696220663F, 0.9697292349F, 0.9698361398F, 0.9699427813F,
  158024. 0.9700491597F, 0.9701552754F, 0.9702611286F, 0.9703667197F,
  158025. 0.9704720490F, 0.9705771169F, 0.9706819236F, 0.9707864695F,
  158026. 0.9708907549F, 0.9709947802F, 0.9710985456F, 0.9712020514F,
  158027. 0.9713052981F, 0.9714082859F, 0.9715110151F, 0.9716134862F,
  158028. 0.9717156993F, 0.9718176549F, 0.9719193532F, 0.9720207946F,
  158029. 0.9721219794F, 0.9722229080F, 0.9723235806F, 0.9724239976F,
  158030. 0.9725241593F, 0.9726240661F, 0.9727237183F, 0.9728231161F,
  158031. 0.9729222601F, 0.9730211503F, 0.9731197873F, 0.9732181713F,
  158032. 0.9733163027F, 0.9734141817F, 0.9735118088F, 0.9736091842F,
  158033. 0.9737063083F, 0.9738031814F, 0.9738998039F, 0.9739961760F,
  158034. 0.9740922981F, 0.9741881706F, 0.9742837938F, 0.9743791680F,
  158035. 0.9744742935F, 0.9745691707F, 0.9746637999F, 0.9747581814F,
  158036. 0.9748523157F, 0.9749462029F, 0.9750398435F, 0.9751332378F,
  158037. 0.9752263861F, 0.9753192887F, 0.9754119461F, 0.9755043585F,
  158038. 0.9755965262F, 0.9756884496F, 0.9757801291F, 0.9758715650F,
  158039. 0.9759627575F, 0.9760537071F, 0.9761444141F, 0.9762348789F,
  158040. 0.9763251016F, 0.9764150828F, 0.9765048228F, 0.9765943218F,
  158041. 0.9766835802F, 0.9767725984F, 0.9768613767F, 0.9769499154F,
  158042. 0.9770382149F, 0.9771262755F, 0.9772140976F, 0.9773016815F,
  158043. 0.9773890275F, 0.9774761360F, 0.9775630073F, 0.9776496418F,
  158044. 0.9777360398F, 0.9778222016F, 0.9779081277F, 0.9779938182F,
  158045. 0.9780792736F, 0.9781644943F, 0.9782494805F, 0.9783342326F,
  158046. 0.9784187509F, 0.9785030359F, 0.9785870877F, 0.9786709069F,
  158047. 0.9787544936F, 0.9788378484F, 0.9789209714F, 0.9790038631F,
  158048. 0.9790865238F, 0.9791689538F, 0.9792511535F, 0.9793331232F,
  158049. 0.9794148633F, 0.9794963742F, 0.9795776561F, 0.9796587094F,
  158050. 0.9797395345F, 0.9798201316F, 0.9799005013F, 0.9799806437F,
  158051. 0.9800605593F, 0.9801402483F, 0.9802197112F, 0.9802989483F,
  158052. 0.9803779600F, 0.9804567465F, 0.9805353082F, 0.9806136455F,
  158053. 0.9806917587F, 0.9807696482F, 0.9808473143F, 0.9809247574F,
  158054. 0.9810019778F, 0.9810789759F, 0.9811557519F, 0.9812323064F,
  158055. 0.9813086395F, 0.9813847517F, 0.9814606433F, 0.9815363147F,
  158056. 0.9816117662F, 0.9816869981F, 0.9817620108F, 0.9818368047F,
  158057. 0.9819113801F, 0.9819857374F, 0.9820598769F, 0.9821337989F,
  158058. 0.9822075038F, 0.9822809920F, 0.9823542638F, 0.9824273195F,
  158059. 0.9825001596F, 0.9825727843F, 0.9826451940F, 0.9827173891F,
  158060. 0.9827893700F, 0.9828611368F, 0.9829326901F, 0.9830040302F,
  158061. 0.9830751574F, 0.9831460720F, 0.9832167745F, 0.9832872652F,
  158062. 0.9833575444F, 0.9834276124F, 0.9834974697F, 0.9835671166F,
  158063. 0.9836365535F, 0.9837057806F, 0.9837747983F, 0.9838436071F,
  158064. 0.9839122072F, 0.9839805990F, 0.9840487829F, 0.9841167591F,
  158065. 0.9841845282F, 0.9842520903F, 0.9843194459F, 0.9843865953F,
  158066. 0.9844535389F, 0.9845202771F, 0.9845868101F, 0.9846531383F,
  158067. 0.9847192622F, 0.9847851820F, 0.9848508980F, 0.9849164108F,
  158068. 0.9849817205F, 0.9850468276F, 0.9851117324F, 0.9851764352F,
  158069. 0.9852409365F, 0.9853052366F, 0.9853693358F, 0.9854332344F,
  158070. 0.9854969330F, 0.9855604317F, 0.9856237309F, 0.9856868310F,
  158071. 0.9857497325F, 0.9858124355F, 0.9858749404F, 0.9859372477F,
  158072. 0.9859993577F, 0.9860612707F, 0.9861229871F, 0.9861845072F,
  158073. 0.9862458315F, 0.9863069601F, 0.9863678936F, 0.9864286322F,
  158074. 0.9864891764F, 0.9865495264F, 0.9866096826F, 0.9866696454F,
  158075. 0.9867294152F, 0.9867889922F, 0.9868483769F, 0.9869075695F,
  158076. 0.9869665706F, 0.9870253803F, 0.9870839991F, 0.9871424273F,
  158077. 0.9872006653F, 0.9872587135F, 0.9873165721F, 0.9873742415F,
  158078. 0.9874317222F, 0.9874890144F, 0.9875461185F, 0.9876030348F,
  158079. 0.9876597638F, 0.9877163057F, 0.9877726610F, 0.9878288300F,
  158080. 0.9878848130F, 0.9879406104F, 0.9879962225F, 0.9880516497F,
  158081. 0.9881068924F, 0.9881619509F, 0.9882168256F, 0.9882715168F,
  158082. 0.9883260249F, 0.9883803502F, 0.9884344931F, 0.9884884539F,
  158083. 0.9885422331F, 0.9885958309F, 0.9886492477F, 0.9887024838F,
  158084. 0.9887555397F, 0.9888084157F, 0.9888611120F, 0.9889136292F,
  158085. 0.9889659675F, 0.9890181273F, 0.9890701089F, 0.9891219128F,
  158086. 0.9891735392F, 0.9892249885F, 0.9892762610F, 0.9893273572F,
  158087. 0.9893782774F, 0.9894290219F, 0.9894795911F, 0.9895299853F,
  158088. 0.9895802049F, 0.9896302502F, 0.9896801217F, 0.9897298196F,
  158089. 0.9897793443F, 0.9898286961F, 0.9898778755F, 0.9899268828F,
  158090. 0.9899757183F, 0.9900243823F, 0.9900728753F, 0.9901211976F,
  158091. 0.9901693495F, 0.9902173314F, 0.9902651436F, 0.9903127865F,
  158092. 0.9903602605F, 0.9904075659F, 0.9904547031F, 0.9905016723F,
  158093. 0.9905484740F, 0.9905951086F, 0.9906415763F, 0.9906878775F,
  158094. 0.9907340126F, 0.9907799819F, 0.9908257858F, 0.9908714247F,
  158095. 0.9909168988F, 0.9909622086F, 0.9910073543F, 0.9910523364F,
  158096. 0.9910971552F, 0.9911418110F, 0.9911863042F, 0.9912306351F,
  158097. 0.9912748042F, 0.9913188117F, 0.9913626580F, 0.9914063435F,
  158098. 0.9914498684F, 0.9914932333F, 0.9915364383F, 0.9915794839F,
  158099. 0.9916223703F, 0.9916650981F, 0.9917076674F, 0.9917500787F,
  158100. 0.9917923323F, 0.9918344286F, 0.9918763679F, 0.9919181505F,
  158101. 0.9919597769F, 0.9920012473F, 0.9920425621F, 0.9920837217F,
  158102. 0.9921247263F, 0.9921655765F, 0.9922062724F, 0.9922468145F,
  158103. 0.9922872030F, 0.9923274385F, 0.9923675211F, 0.9924074513F,
  158104. 0.9924472294F, 0.9924868557F, 0.9925263306F, 0.9925656544F,
  158105. 0.9926048275F, 0.9926438503F, 0.9926827230F, 0.9927214461F,
  158106. 0.9927600199F, 0.9927984446F, 0.9928367208F, 0.9928748486F,
  158107. 0.9929128285F, 0.9929506608F, 0.9929883459F, 0.9930258841F,
  158108. 0.9930632757F, 0.9931005211F, 0.9931376207F, 0.9931745747F,
  158109. 0.9932113836F, 0.9932480476F, 0.9932845671F, 0.9933209425F,
  158110. 0.9933571742F, 0.9933932623F, 0.9934292074F, 0.9934650097F,
  158111. 0.9935006696F, 0.9935361874F, 0.9935715635F, 0.9936067982F,
  158112. 0.9936418919F, 0.9936768448F, 0.9937116574F, 0.9937463300F,
  158113. 0.9937808629F, 0.9938152565F, 0.9938495111F, 0.9938836271F,
  158114. 0.9939176047F, 0.9939514444F, 0.9939851465F, 0.9940187112F,
  158115. 0.9940521391F, 0.9940854303F, 0.9941185853F, 0.9941516044F,
  158116. 0.9941844879F, 0.9942172361F, 0.9942498495F, 0.9942823283F,
  158117. 0.9943146729F, 0.9943468836F, 0.9943789608F, 0.9944109047F,
  158118. 0.9944427158F, 0.9944743944F, 0.9945059408F, 0.9945373553F,
  158119. 0.9945686384F, 0.9945997902F, 0.9946308112F, 0.9946617017F,
  158120. 0.9946924621F, 0.9947230926F, 0.9947535937F, 0.9947839656F,
  158121. 0.9948142086F, 0.9948443232F, 0.9948743097F, 0.9949041683F,
  158122. 0.9949338995F, 0.9949635035F, 0.9949929807F, 0.9950223315F,
  158123. 0.9950515561F, 0.9950806549F, 0.9951096282F, 0.9951384764F,
  158124. 0.9951671998F, 0.9951957987F, 0.9952242735F, 0.9952526245F,
  158125. 0.9952808520F, 0.9953089564F, 0.9953369380F, 0.9953647971F,
  158126. 0.9953925340F, 0.9954201491F, 0.9954476428F, 0.9954750153F,
  158127. 0.9955022670F, 0.9955293981F, 0.9955564092F, 0.9955833003F,
  158128. 0.9956100720F, 0.9956367245F, 0.9956632582F, 0.9956896733F,
  158129. 0.9957159703F, 0.9957421494F, 0.9957682110F, 0.9957941553F,
  158130. 0.9958199828F, 0.9958456937F, 0.9958712884F, 0.9958967672F,
  158131. 0.9959221305F, 0.9959473784F, 0.9959725115F, 0.9959975300F,
  158132. 0.9960224342F, 0.9960472244F, 0.9960719011F, 0.9960964644F,
  158133. 0.9961209148F, 0.9961452525F, 0.9961694779F, 0.9961935913F,
  158134. 0.9962175930F, 0.9962414834F, 0.9962652627F, 0.9962889313F,
  158135. 0.9963124895F, 0.9963359377F, 0.9963592761F, 0.9963825051F,
  158136. 0.9964056250F, 0.9964286361F, 0.9964515387F, 0.9964743332F,
  158137. 0.9964970198F, 0.9965195990F, 0.9965420709F, 0.9965644360F,
  158138. 0.9965866946F, 0.9966088469F, 0.9966308932F, 0.9966528340F,
  158139. 0.9966746695F, 0.9966964001F, 0.9967180260F, 0.9967395475F,
  158140. 0.9967609651F, 0.9967822789F, 0.9968034894F, 0.9968245968F,
  158141. 0.9968456014F, 0.9968665036F, 0.9968873037F, 0.9969080019F,
  158142. 0.9969285987F, 0.9969490942F, 0.9969694889F, 0.9969897830F,
  158143. 0.9970099769F, 0.9970300708F, 0.9970500651F, 0.9970699601F,
  158144. 0.9970897561F, 0.9971094533F, 0.9971290522F, 0.9971485531F,
  158145. 0.9971679561F, 0.9971872617F, 0.9972064702F, 0.9972255818F,
  158146. 0.9972445968F, 0.9972635157F, 0.9972823386F, 0.9973010659F,
  158147. 0.9973196980F, 0.9973382350F, 0.9973566773F, 0.9973750253F,
  158148. 0.9973932791F, 0.9974114392F, 0.9974295059F, 0.9974474793F,
  158149. 0.9974653599F, 0.9974831480F, 0.9975008438F, 0.9975184476F,
  158150. 0.9975359598F, 0.9975533806F, 0.9975707104F, 0.9975879495F,
  158151. 0.9976050981F, 0.9976221566F, 0.9976391252F, 0.9976560043F,
  158152. 0.9976727941F, 0.9976894950F, 0.9977061073F, 0.9977226312F,
  158153. 0.9977390671F, 0.9977554152F, 0.9977716759F, 0.9977878495F,
  158154. 0.9978039361F, 0.9978199363F, 0.9978358501F, 0.9978516780F,
  158155. 0.9978674202F, 0.9978830771F, 0.9978986488F, 0.9979141358F,
  158156. 0.9979295383F, 0.9979448566F, 0.9979600909F, 0.9979752417F,
  158157. 0.9979903091F, 0.9980052936F, 0.9980201952F, 0.9980350145F,
  158158. 0.9980497515F, 0.9980644067F, 0.9980789804F, 0.9980934727F,
  158159. 0.9981078841F, 0.9981222147F, 0.9981364649F, 0.9981506350F,
  158160. 0.9981647253F, 0.9981787360F, 0.9981926674F, 0.9982065199F,
  158161. 0.9982202936F, 0.9982339890F, 0.9982476062F, 0.9982611456F,
  158162. 0.9982746074F, 0.9982879920F, 0.9983012996F, 0.9983145304F,
  158163. 0.9983276849F, 0.9983407632F, 0.9983537657F, 0.9983666926F,
  158164. 0.9983795442F, 0.9983923208F, 0.9984050226F, 0.9984176501F,
  158165. 0.9984302033F, 0.9984426827F, 0.9984550884F, 0.9984674208F,
  158166. 0.9984796802F, 0.9984918667F, 0.9985039808F, 0.9985160227F,
  158167. 0.9985279926F, 0.9985398909F, 0.9985517177F, 0.9985634734F,
  158168. 0.9985751583F, 0.9985867727F, 0.9985983167F, 0.9986097907F,
  158169. 0.9986211949F, 0.9986325297F, 0.9986437953F, 0.9986549919F,
  158170. 0.9986661199F, 0.9986771795F, 0.9986881710F, 0.9986990946F,
  158171. 0.9987099507F, 0.9987207394F, 0.9987314611F, 0.9987421161F,
  158172. 0.9987527045F, 0.9987632267F, 0.9987736829F, 0.9987840734F,
  158173. 0.9987943985F, 0.9988046584F, 0.9988148534F, 0.9988249838F,
  158174. 0.9988350498F, 0.9988450516F, 0.9988549897F, 0.9988648641F,
  158175. 0.9988746753F, 0.9988844233F, 0.9988941086F, 0.9989037313F,
  158176. 0.9989132918F, 0.9989227902F, 0.9989322269F, 0.9989416021F,
  158177. 0.9989509160F, 0.9989601690F, 0.9989693613F, 0.9989784931F,
  158178. 0.9989875647F, 0.9989965763F, 0.9990055283F, 0.9990144208F,
  158179. 0.9990232541F, 0.9990320286F, 0.9990407443F, 0.9990494016F,
  158180. 0.9990580008F, 0.9990665421F, 0.9990750257F, 0.9990834519F,
  158181. 0.9990918209F, 0.9991001331F, 0.9991083886F, 0.9991165877F,
  158182. 0.9991247307F, 0.9991328177F, 0.9991408491F, 0.9991488251F,
  158183. 0.9991567460F, 0.9991646119F, 0.9991724232F, 0.9991801801F,
  158184. 0.9991878828F, 0.9991955316F, 0.9992031267F, 0.9992106684F,
  158185. 0.9992181569F, 0.9992255925F, 0.9992329753F, 0.9992403057F,
  158186. 0.9992475839F, 0.9992548101F, 0.9992619846F, 0.9992691076F,
  158187. 0.9992761793F, 0.9992832001F, 0.9992901701F, 0.9992970895F,
  158188. 0.9993039587F, 0.9993107777F, 0.9993175470F, 0.9993242667F,
  158189. 0.9993309371F, 0.9993375583F, 0.9993441307F, 0.9993506545F,
  158190. 0.9993571298F, 0.9993635570F, 0.9993699362F, 0.9993762678F,
  158191. 0.9993825519F, 0.9993887887F, 0.9993949785F, 0.9994011216F,
  158192. 0.9994072181F, 0.9994132683F, 0.9994192725F, 0.9994252307F,
  158193. 0.9994311434F, 0.9994370107F, 0.9994428327F, 0.9994486099F,
  158194. 0.9994543423F, 0.9994600303F, 0.9994656739F, 0.9994712736F,
  158195. 0.9994768294F, 0.9994823417F, 0.9994878105F, 0.9994932363F,
  158196. 0.9994986191F, 0.9995039592F, 0.9995092568F, 0.9995145122F,
  158197. 0.9995197256F, 0.9995248971F, 0.9995300270F, 0.9995351156F,
  158198. 0.9995401630F, 0.9995451695F, 0.9995501352F, 0.9995550604F,
  158199. 0.9995599454F, 0.9995647903F, 0.9995695953F, 0.9995743607F,
  158200. 0.9995790866F, 0.9995837734F, 0.9995884211F, 0.9995930300F,
  158201. 0.9995976004F, 0.9996021324F, 0.9996066263F, 0.9996110822F,
  158202. 0.9996155004F, 0.9996198810F, 0.9996242244F, 0.9996285306F,
  158203. 0.9996327999F, 0.9996370326F, 0.9996412287F, 0.9996453886F,
  158204. 0.9996495125F, 0.9996536004F, 0.9996576527F, 0.9996616696F,
  158205. 0.9996656512F, 0.9996695977F, 0.9996735094F, 0.9996773865F,
  158206. 0.9996812291F, 0.9996850374F, 0.9996888118F, 0.9996925523F,
  158207. 0.9996962591F, 0.9996999325F, 0.9997035727F, 0.9997071798F,
  158208. 0.9997107541F, 0.9997142957F, 0.9997178049F, 0.9997212818F,
  158209. 0.9997247266F, 0.9997281396F, 0.9997315209F, 0.9997348708F,
  158210. 0.9997381893F, 0.9997414767F, 0.9997447333F, 0.9997479591F,
  158211. 0.9997511544F, 0.9997543194F, 0.9997574542F, 0.9997605591F,
  158212. 0.9997636342F, 0.9997666797F, 0.9997696958F, 0.9997726828F,
  158213. 0.9997756407F, 0.9997785698F, 0.9997814703F, 0.9997843423F,
  158214. 0.9997871860F, 0.9997900016F, 0.9997927894F, 0.9997955494F,
  158215. 0.9997982818F, 0.9998009869F, 0.9998036648F, 0.9998063157F,
  158216. 0.9998089398F, 0.9998115373F, 0.9998141082F, 0.9998166529F,
  158217. 0.9998191715F, 0.9998216642F, 0.9998241311F, 0.9998265724F,
  158218. 0.9998289884F, 0.9998313790F, 0.9998337447F, 0.9998360854F,
  158219. 0.9998384015F, 0.9998406930F, 0.9998429602F, 0.9998452031F,
  158220. 0.9998474221F, 0.9998496171F, 0.9998517885F, 0.9998539364F,
  158221. 0.9998560610F, 0.9998581624F, 0.9998602407F, 0.9998622962F,
  158222. 0.9998643291F, 0.9998663394F, 0.9998683274F, 0.9998702932F,
  158223. 0.9998722370F, 0.9998741589F, 0.9998760591F, 0.9998779378F,
  158224. 0.9998797952F, 0.9998816313F, 0.9998834464F, 0.9998852406F,
  158225. 0.9998870141F, 0.9998887670F, 0.9998904995F, 0.9998922117F,
  158226. 0.9998939039F, 0.9998955761F, 0.9998972285F, 0.9998988613F,
  158227. 0.9999004746F, 0.9999020686F, 0.9999036434F, 0.9999051992F,
  158228. 0.9999067362F, 0.9999082544F, 0.9999097541F, 0.9999112354F,
  158229. 0.9999126984F, 0.9999141433F, 0.9999155703F, 0.9999169794F,
  158230. 0.9999183709F, 0.9999197449F, 0.9999211014F, 0.9999224408F,
  158231. 0.9999237631F, 0.9999250684F, 0.9999263570F, 0.9999276289F,
  158232. 0.9999288843F, 0.9999301233F, 0.9999313461F, 0.9999325529F,
  158233. 0.9999337437F, 0.9999349187F, 0.9999360780F, 0.9999372218F,
  158234. 0.9999383503F, 0.9999394635F, 0.9999405616F, 0.9999416447F,
  158235. 0.9999427129F, 0.9999437665F, 0.9999448055F, 0.9999458301F,
  158236. 0.9999468404F, 0.9999478365F, 0.9999488185F, 0.9999497867F,
  158237. 0.9999507411F, 0.9999516819F, 0.9999526091F, 0.9999535230F,
  158238. 0.9999544236F, 0.9999553111F, 0.9999561856F, 0.9999570472F,
  158239. 0.9999578960F, 0.9999587323F, 0.9999595560F, 0.9999603674F,
  158240. 0.9999611666F, 0.9999619536F, 0.9999627286F, 0.9999634917F,
  158241. 0.9999642431F, 0.9999649828F, 0.9999657110F, 0.9999664278F,
  158242. 0.9999671334F, 0.9999678278F, 0.9999685111F, 0.9999691835F,
  158243. 0.9999698451F, 0.9999704960F, 0.9999711364F, 0.9999717662F,
  158244. 0.9999723858F, 0.9999729950F, 0.9999735942F, 0.9999741834F,
  158245. 0.9999747626F, 0.9999753321F, 0.9999758919F, 0.9999764421F,
  158246. 0.9999769828F, 0.9999775143F, 0.9999780364F, 0.9999785495F,
  158247. 0.9999790535F, 0.9999795485F, 0.9999800348F, 0.9999805124F,
  158248. 0.9999809813F, 0.9999814417F, 0.9999818938F, 0.9999823375F,
  158249. 0.9999827731F, 0.9999832005F, 0.9999836200F, 0.9999840316F,
  158250. 0.9999844353F, 0.9999848314F, 0.9999852199F, 0.9999856008F,
  158251. 0.9999859744F, 0.9999863407F, 0.9999866997F, 0.9999870516F,
  158252. 0.9999873965F, 0.9999877345F, 0.9999880656F, 0.9999883900F,
  158253. 0.9999887078F, 0.9999890190F, 0.9999893237F, 0.9999896220F,
  158254. 0.9999899140F, 0.9999901999F, 0.9999904796F, 0.9999907533F,
  158255. 0.9999910211F, 0.9999912830F, 0.9999915391F, 0.9999917896F,
  158256. 0.9999920345F, 0.9999922738F, 0.9999925077F, 0.9999927363F,
  158257. 0.9999929596F, 0.9999931777F, 0.9999933907F, 0.9999935987F,
  158258. 0.9999938018F, 0.9999940000F, 0.9999941934F, 0.9999943820F,
  158259. 0.9999945661F, 0.9999947456F, 0.9999949206F, 0.9999950912F,
  158260. 0.9999952575F, 0.9999954195F, 0.9999955773F, 0.9999957311F,
  158261. 0.9999958807F, 0.9999960265F, 0.9999961683F, 0.9999963063F,
  158262. 0.9999964405F, 0.9999965710F, 0.9999966979F, 0.9999968213F,
  158263. 0.9999969412F, 0.9999970576F, 0.9999971707F, 0.9999972805F,
  158264. 0.9999973871F, 0.9999974905F, 0.9999975909F, 0.9999976881F,
  158265. 0.9999977824F, 0.9999978738F, 0.9999979624F, 0.9999980481F,
  158266. 0.9999981311F, 0.9999982115F, 0.9999982892F, 0.9999983644F,
  158267. 0.9999984370F, 0.9999985072F, 0.9999985750F, 0.9999986405F,
  158268. 0.9999987037F, 0.9999987647F, 0.9999988235F, 0.9999988802F,
  158269. 0.9999989348F, 0.9999989873F, 0.9999990379F, 0.9999990866F,
  158270. 0.9999991334F, 0.9999991784F, 0.9999992217F, 0.9999992632F,
  158271. 0.9999993030F, 0.9999993411F, 0.9999993777F, 0.9999994128F,
  158272. 0.9999994463F, 0.9999994784F, 0.9999995091F, 0.9999995384F,
  158273. 0.9999995663F, 0.9999995930F, 0.9999996184F, 0.9999996426F,
  158274. 0.9999996657F, 0.9999996876F, 0.9999997084F, 0.9999997282F,
  158275. 0.9999997469F, 0.9999997647F, 0.9999997815F, 0.9999997973F,
  158276. 0.9999998123F, 0.9999998265F, 0.9999998398F, 0.9999998524F,
  158277. 0.9999998642F, 0.9999998753F, 0.9999998857F, 0.9999998954F,
  158278. 0.9999999045F, 0.9999999130F, 0.9999999209F, 0.9999999282F,
  158279. 0.9999999351F, 0.9999999414F, 0.9999999472F, 0.9999999526F,
  158280. 0.9999999576F, 0.9999999622F, 0.9999999664F, 0.9999999702F,
  158281. 0.9999999737F, 0.9999999769F, 0.9999999798F, 0.9999999824F,
  158282. 0.9999999847F, 0.9999999868F, 0.9999999887F, 0.9999999904F,
  158283. 0.9999999919F, 0.9999999932F, 0.9999999943F, 0.9999999953F,
  158284. 0.9999999961F, 0.9999999969F, 0.9999999975F, 0.9999999980F,
  158285. 0.9999999985F, 0.9999999988F, 0.9999999991F, 0.9999999993F,
  158286. 0.9999999995F, 0.9999999997F, 0.9999999998F, 0.9999999999F,
  158287. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  158288. 1.0000000000F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  158289. };
  158290. static float *vwin[8] = {
  158291. vwin64,
  158292. vwin128,
  158293. vwin256,
  158294. vwin512,
  158295. vwin1024,
  158296. vwin2048,
  158297. vwin4096,
  158298. vwin8192,
  158299. };
  158300. float *_vorbis_window_get(int n){
  158301. return vwin[n];
  158302. }
  158303. void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  158304. int lW,int W,int nW){
  158305. lW=(W?lW:0);
  158306. nW=(W?nW:0);
  158307. {
  158308. float *windowLW=vwin[winno[lW]];
  158309. float *windowNW=vwin[winno[nW]];
  158310. long n=blocksizes[W];
  158311. long ln=blocksizes[lW];
  158312. long rn=blocksizes[nW];
  158313. long leftbegin=n/4-ln/4;
  158314. long leftend=leftbegin+ln/2;
  158315. long rightbegin=n/2+n/4-rn/4;
  158316. long rightend=rightbegin+rn/2;
  158317. int i,p;
  158318. for(i=0;i<leftbegin;i++)
  158319. d[i]=0.f;
  158320. for(p=0;i<leftend;i++,p++)
  158321. d[i]*=windowLW[p];
  158322. for(i=rightbegin,p=rn/2-1;i<rightend;i++,p--)
  158323. d[i]*=windowNW[p];
  158324. for(;i<n;i++)
  158325. d[i]=0.f;
  158326. }
  158327. }
  158328. #endif
  158329. /*** End of inlined file: window.c ***/
  158330. #else
  158331. #include <vorbis/vorbisenc.h>
  158332. #include <vorbis/codec.h>
  158333. #include <vorbis/vorbisfile.h>
  158334. #endif
  158335. }
  158336. #undef max
  158337. #undef min
  158338. BEGIN_JUCE_NAMESPACE
  158339. static const char* const oggFormatName = "Ogg-Vorbis file";
  158340. static const char* const oggExtensions[] = { ".ogg", 0 };
  158341. class OggReader : public AudioFormatReader
  158342. {
  158343. OggVorbisNamespace::OggVorbis_File ovFile;
  158344. OggVorbisNamespace::ov_callbacks callbacks;
  158345. AudioSampleBuffer reservoir;
  158346. int reservoirStart, samplesInReservoir;
  158347. public:
  158348. OggReader (InputStream* const inp)
  158349. : AudioFormatReader (inp, TRANS (oggFormatName)),
  158350. reservoir (2, 4096),
  158351. reservoirStart (0),
  158352. samplesInReservoir (0)
  158353. {
  158354. using namespace OggVorbisNamespace;
  158355. sampleRate = 0;
  158356. usesFloatingPointData = true;
  158357. callbacks.read_func = &oggReadCallback;
  158358. callbacks.seek_func = &oggSeekCallback;
  158359. callbacks.close_func = &oggCloseCallback;
  158360. callbacks.tell_func = &oggTellCallback;
  158361. const int err = ov_open_callbacks (input, &ovFile, 0, 0, callbacks);
  158362. if (err == 0)
  158363. {
  158364. vorbis_info* info = ov_info (&ovFile, -1);
  158365. lengthInSamples = (uint32) ov_pcm_total (&ovFile, -1);
  158366. numChannels = info->channels;
  158367. bitsPerSample = 16;
  158368. sampleRate = info->rate;
  158369. reservoir.setSize (numChannels,
  158370. (int) jmin (lengthInSamples, (int64) reservoir.getNumSamples()));
  158371. }
  158372. }
  158373. ~OggReader()
  158374. {
  158375. OggVorbisNamespace::ov_clear (&ovFile);
  158376. }
  158377. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  158378. int64 startSampleInFile, int numSamples)
  158379. {
  158380. while (numSamples > 0)
  158381. {
  158382. const int numAvailable = reservoirStart + samplesInReservoir - startSampleInFile;
  158383. if (startSampleInFile >= reservoirStart && numAvailable > 0)
  158384. {
  158385. // got a few samples overlapping, so use them before seeking..
  158386. const int numToUse = jmin (numSamples, numAvailable);
  158387. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  158388. if (destSamples[i] != 0)
  158389. memcpy (destSamples[i] + startOffsetInDestBuffer,
  158390. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  158391. sizeof (float) * numToUse);
  158392. startSampleInFile += numToUse;
  158393. numSamples -= numToUse;
  158394. startOffsetInDestBuffer += numToUse;
  158395. if (numSamples == 0)
  158396. break;
  158397. }
  158398. if (startSampleInFile < reservoirStart
  158399. || startSampleInFile + numSamples > reservoirStart + samplesInReservoir)
  158400. {
  158401. // buffer miss, so refill the reservoir
  158402. int bitStream = 0;
  158403. reservoirStart = jmax (0, (int) startSampleInFile);
  158404. samplesInReservoir = reservoir.getNumSamples();
  158405. if (reservoirStart != (int) OggVorbisNamespace::ov_pcm_tell (&ovFile))
  158406. OggVorbisNamespace::ov_pcm_seek (&ovFile, reservoirStart);
  158407. int offset = 0;
  158408. int numToRead = samplesInReservoir;
  158409. while (numToRead > 0)
  158410. {
  158411. float** dataIn = 0;
  158412. const int samps = OggVorbisNamespace::ov_read_float (&ovFile, &dataIn, numToRead, &bitStream);
  158413. if (samps <= 0)
  158414. break;
  158415. jassert (samps <= numToRead);
  158416. for (int i = jmin ((int) numChannels, reservoir.getNumChannels()); --i >= 0;)
  158417. {
  158418. memcpy (reservoir.getSampleData (i, offset),
  158419. dataIn[i],
  158420. sizeof (float) * samps);
  158421. }
  158422. numToRead -= samps;
  158423. offset += samps;
  158424. }
  158425. if (numToRead > 0)
  158426. reservoir.clear (offset, numToRead);
  158427. }
  158428. }
  158429. if (numSamples > 0)
  158430. {
  158431. for (int i = numDestChannels; --i >= 0;)
  158432. if (destSamples[i] != 0)
  158433. zeromem (destSamples[i] + startOffsetInDestBuffer,
  158434. sizeof (int) * numSamples);
  158435. }
  158436. return true;
  158437. }
  158438. static size_t oggReadCallback (void* ptr, size_t size, size_t nmemb, void* datasource)
  158439. {
  158440. return (size_t) (static_cast <InputStream*> (datasource)->read (ptr, (int) (size * nmemb)) / size);
  158441. }
  158442. static int oggSeekCallback (void* datasource, OggVorbisNamespace::ogg_int64_t offset, int whence)
  158443. {
  158444. InputStream* const in = static_cast <InputStream*> (datasource);
  158445. if (whence == SEEK_CUR)
  158446. offset += in->getPosition();
  158447. else if (whence == SEEK_END)
  158448. offset += in->getTotalLength();
  158449. in->setPosition (offset);
  158450. return 0;
  158451. }
  158452. static int oggCloseCallback (void*)
  158453. {
  158454. return 0;
  158455. }
  158456. static long oggTellCallback (void* datasource)
  158457. {
  158458. return (long) static_cast <InputStream*> (datasource)->getPosition();
  158459. }
  158460. juce_UseDebuggingNewOperator
  158461. };
  158462. class OggWriter : public AudioFormatWriter
  158463. {
  158464. OggVorbisNamespace::ogg_stream_state os;
  158465. OggVorbisNamespace::ogg_page og;
  158466. OggVorbisNamespace::ogg_packet op;
  158467. OggVorbisNamespace::vorbis_info vi;
  158468. OggVorbisNamespace::vorbis_comment vc;
  158469. OggVorbisNamespace::vorbis_dsp_state vd;
  158470. OggVorbisNamespace::vorbis_block vb;
  158471. public:
  158472. bool ok;
  158473. OggWriter (OutputStream* const out,
  158474. const double sampleRate,
  158475. const int numChannels,
  158476. const int bitsPerSample,
  158477. const int qualityIndex)
  158478. : AudioFormatWriter (out, TRANS (oggFormatName),
  158479. sampleRate,
  158480. numChannels,
  158481. bitsPerSample)
  158482. {
  158483. using namespace OggVorbisNamespace;
  158484. ok = false;
  158485. vorbis_info_init (&vi);
  158486. if (vorbis_encode_init_vbr (&vi,
  158487. numChannels,
  158488. (int) sampleRate,
  158489. jlimit (0.0f, 1.0f, qualityIndex * 0.5f)) == 0)
  158490. {
  158491. vorbis_comment_init (&vc);
  158492. if (JUCEApplication::getInstance() != 0)
  158493. vorbis_comment_add_tag (&vc, "ENCODER", const_cast <char*> (JUCEApplication::getInstance()->getApplicationName().toUTF8()));
  158494. vorbis_analysis_init (&vd, &vi);
  158495. vorbis_block_init (&vd, &vb);
  158496. ogg_stream_init (&os, Random::getSystemRandom().nextInt());
  158497. ogg_packet header;
  158498. ogg_packet header_comm;
  158499. ogg_packet header_code;
  158500. vorbis_analysis_headerout (&vd, &vc, &header, &header_comm, &header_code);
  158501. ogg_stream_packetin (&os, &header);
  158502. ogg_stream_packetin (&os, &header_comm);
  158503. ogg_stream_packetin (&os, &header_code);
  158504. for (;;)
  158505. {
  158506. if (ogg_stream_flush (&os, &og) == 0)
  158507. break;
  158508. output->write (og.header, og.header_len);
  158509. output->write (og.body, og.body_len);
  158510. }
  158511. ok = true;
  158512. }
  158513. }
  158514. ~OggWriter()
  158515. {
  158516. using namespace OggVorbisNamespace;
  158517. if (ok)
  158518. {
  158519. // write a zero-length packet to show ogg that we're finished..
  158520. write (0, 0);
  158521. ogg_stream_clear (&os);
  158522. vorbis_block_clear (&vb);
  158523. vorbis_dsp_clear (&vd);
  158524. vorbis_comment_clear (&vc);
  158525. vorbis_info_clear (&vi);
  158526. output->flush();
  158527. }
  158528. else
  158529. {
  158530. vorbis_info_clear (&vi);
  158531. output = 0; // to stop the base class deleting this, as it needs to be returned
  158532. // to the caller of createWriter()
  158533. }
  158534. }
  158535. bool write (const int** samplesToWrite, int numSamples)
  158536. {
  158537. using namespace OggVorbisNamespace;
  158538. if (! ok)
  158539. return false;
  158540. if (numSamples > 0)
  158541. {
  158542. const double gain = 1.0 / 0x80000000u;
  158543. float** const vorbisBuffer = vorbis_analysis_buffer (&vd, numSamples);
  158544. for (int i = numChannels; --i >= 0;)
  158545. {
  158546. float* const dst = vorbisBuffer[i];
  158547. const int* const src = samplesToWrite [i];
  158548. if (src != 0 && dst != 0)
  158549. {
  158550. for (int j = 0; j < numSamples; ++j)
  158551. dst[j] = (float) (src[j] * gain);
  158552. }
  158553. }
  158554. }
  158555. vorbis_analysis_wrote (&vd, numSamples);
  158556. while (vorbis_analysis_blockout (&vd, &vb) == 1)
  158557. {
  158558. vorbis_analysis (&vb, 0);
  158559. vorbis_bitrate_addblock (&vb);
  158560. while (vorbis_bitrate_flushpacket (&vd, &op))
  158561. {
  158562. ogg_stream_packetin (&os, &op);
  158563. for (;;)
  158564. {
  158565. if (ogg_stream_pageout (&os, &og) == 0)
  158566. break;
  158567. output->write (og.header, og.header_len);
  158568. output->write (og.body, og.body_len);
  158569. if (ogg_page_eos (&og))
  158570. break;
  158571. }
  158572. }
  158573. }
  158574. return true;
  158575. }
  158576. juce_UseDebuggingNewOperator
  158577. };
  158578. OggVorbisAudioFormat::OggVorbisAudioFormat()
  158579. : AudioFormat (TRANS (oggFormatName), StringArray (oggExtensions))
  158580. {
  158581. }
  158582. OggVorbisAudioFormat::~OggVorbisAudioFormat()
  158583. {
  158584. }
  158585. const Array <int> OggVorbisAudioFormat::getPossibleSampleRates()
  158586. {
  158587. const int rates[] = { 22050, 32000, 44100, 48000, 0 };
  158588. return Array <int> (rates);
  158589. }
  158590. const Array <int> OggVorbisAudioFormat::getPossibleBitDepths()
  158591. {
  158592. Array <int> depths;
  158593. depths.add (32);
  158594. return depths;
  158595. }
  158596. bool OggVorbisAudioFormat::canDoStereo()
  158597. {
  158598. return true;
  158599. }
  158600. bool OggVorbisAudioFormat::canDoMono()
  158601. {
  158602. return true;
  158603. }
  158604. AudioFormatReader* OggVorbisAudioFormat::createReaderFor (InputStream* in,
  158605. const bool deleteStreamIfOpeningFails)
  158606. {
  158607. ScopedPointer <OggReader> r (new OggReader (in));
  158608. if (r->sampleRate != 0)
  158609. return r.release();
  158610. if (! deleteStreamIfOpeningFails)
  158611. r->input = 0;
  158612. return 0;
  158613. }
  158614. AudioFormatWriter* OggVorbisAudioFormat::createWriterFor (OutputStream* out,
  158615. double sampleRate,
  158616. unsigned int numChannels,
  158617. int bitsPerSample,
  158618. const StringPairArray& /*metadataValues*/,
  158619. int qualityOptionIndex)
  158620. {
  158621. ScopedPointer <OggWriter> w (new OggWriter (out,
  158622. sampleRate,
  158623. numChannels,
  158624. bitsPerSample,
  158625. qualityOptionIndex));
  158626. return w->ok ? w.release() : 0;
  158627. }
  158628. bool OggVorbisAudioFormat::isCompressed()
  158629. {
  158630. return true;
  158631. }
  158632. const StringArray OggVorbisAudioFormat::getQualityOptions()
  158633. {
  158634. StringArray s;
  158635. s.add ("Low Quality");
  158636. s.add ("Medium Quality");
  158637. s.add ("High Quality");
  158638. return s;
  158639. }
  158640. int OggVorbisAudioFormat::estimateOggFileQuality (const File& source)
  158641. {
  158642. FileInputStream* const in = source.createInputStream();
  158643. if (in != 0)
  158644. {
  158645. ScopedPointer <AudioFormatReader> r (createReaderFor (in, true));
  158646. if (r != 0)
  158647. {
  158648. const int64 numSamps = r->lengthInSamples;
  158649. r = 0;
  158650. const int64 fileNumSamps = source.getSize() / 4;
  158651. const double ratio = numSamps / (double) fileNumSamps;
  158652. if (ratio > 12.0)
  158653. return 0;
  158654. else if (ratio > 6.0)
  158655. return 1;
  158656. else
  158657. return 2;
  158658. }
  158659. }
  158660. return 1;
  158661. }
  158662. END_JUCE_NAMESPACE
  158663. #endif
  158664. /*** End of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  158665. #endif
  158666. #if JUCE_BUILD_CORE && ! JUCE_ONLY_BUILD_CORE_LIBRARY // do these in the core section to help balance the sizes
  158667. /*** Start of inlined file: juce_JPEGLoader.cpp ***/
  158668. #if JUCE_MSVC
  158669. #pragma warning (push)
  158670. #endif
  158671. namespace jpeglibNamespace
  158672. {
  158673. #if JUCE_INCLUDE_JPEGLIB_CODE
  158674. #if JUCE_MINGW
  158675. typedef unsigned char boolean;
  158676. #endif
  158677. extern "C"
  158678. {
  158679. #define JPEG_INTERNALS
  158680. #undef FAR
  158681. /*** Start of inlined file: jpeglib.h ***/
  158682. #ifndef JPEGLIB_H
  158683. #define JPEGLIB_H
  158684. /*
  158685. * First we include the configuration files that record how this
  158686. * installation of the JPEG library is set up. jconfig.h can be
  158687. * generated automatically for many systems. jmorecfg.h contains
  158688. * manual configuration options that most people need not worry about.
  158689. */
  158690. #ifndef JCONFIG_INCLUDED /* in case jinclude.h already did */
  158691. /*** Start of inlined file: jconfig.h ***/
  158692. /* see jconfig.doc for explanations */
  158693. // disable all the warnings under MSVC
  158694. #ifdef _MSC_VER
  158695. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  158696. #endif
  158697. #ifdef __BORLANDC__
  158698. #pragma warn -8057
  158699. #pragma warn -8019
  158700. #pragma warn -8004
  158701. #pragma warn -8008
  158702. #endif
  158703. #define HAVE_PROTOTYPES
  158704. #define HAVE_UNSIGNED_CHAR
  158705. #define HAVE_UNSIGNED_SHORT
  158706. /* #define void char */
  158707. /* #define const */
  158708. #undef CHAR_IS_UNSIGNED
  158709. #define HAVE_STDDEF_H
  158710. #define HAVE_STDLIB_H
  158711. #undef NEED_BSD_STRINGS
  158712. #undef NEED_SYS_TYPES_H
  158713. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  158714. #undef NEED_SHORT_EXTERNAL_NAMES
  158715. #undef INCOMPLETE_TYPES_BROKEN
  158716. /* Define "boolean" as unsigned char, not int, per Windows custom */
  158717. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  158718. typedef unsigned char boolean;
  158719. #endif
  158720. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  158721. #ifdef JPEG_INTERNALS
  158722. #undef RIGHT_SHIFT_IS_UNSIGNED
  158723. #endif /* JPEG_INTERNALS */
  158724. #ifdef JPEG_CJPEG_DJPEG
  158725. #define BMP_SUPPORTED /* BMP image file format */
  158726. #define GIF_SUPPORTED /* GIF image file format */
  158727. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  158728. #undef RLE_SUPPORTED /* Utah RLE image file format */
  158729. #define TARGA_SUPPORTED /* Targa image file format */
  158730. #define TWO_FILE_COMMANDLINE /* optional */
  158731. #define USE_SETMODE /* Microsoft has setmode() */
  158732. #undef NEED_SIGNAL_CATCHER
  158733. #undef DONT_USE_B_MODE
  158734. #undef PROGRESS_REPORT /* optional */
  158735. #endif /* JPEG_CJPEG_DJPEG */
  158736. /*** End of inlined file: jconfig.h ***/
  158737. /* widely used configuration options */
  158738. #endif
  158739. /*** Start of inlined file: jmorecfg.h ***/
  158740. /*
  158741. * Define BITS_IN_JSAMPLE as either
  158742. * 8 for 8-bit sample values (the usual setting)
  158743. * 12 for 12-bit sample values
  158744. * Only 8 and 12 are legal data precisions for lossy JPEG according to the
  158745. * JPEG standard, and the IJG code does not support anything else!
  158746. * We do not support run-time selection of data precision, sorry.
  158747. */
  158748. #define BITS_IN_JSAMPLE 8 /* use 8 or 12 */
  158749. /*
  158750. * Maximum number of components (color channels) allowed in JPEG image.
  158751. * To meet the letter of the JPEG spec, set this to 255. However, darn
  158752. * few applications need more than 4 channels (maybe 5 for CMYK + alpha
  158753. * mask). We recommend 10 as a reasonable compromise; use 4 if you are
  158754. * really short on memory. (Each allowed component costs a hundred or so
  158755. * bytes of storage, whether actually used in an image or not.)
  158756. */
  158757. #define MAX_COMPONENTS 10 /* maximum number of image components */
  158758. /*
  158759. * Basic data types.
  158760. * You may need to change these if you have a machine with unusual data
  158761. * type sizes; for example, "char" not 8 bits, "short" not 16 bits,
  158762. * or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits,
  158763. * but it had better be at least 16.
  158764. */
  158765. /* Representation of a single sample (pixel element value).
  158766. * We frequently allocate large arrays of these, so it's important to keep
  158767. * them small. But if you have memory to burn and access to char or short
  158768. * arrays is very slow on your hardware, you might want to change these.
  158769. */
  158770. #if BITS_IN_JSAMPLE == 8
  158771. /* JSAMPLE should be the smallest type that will hold the values 0..255.
  158772. * You can use a signed char by having GETJSAMPLE mask it with 0xFF.
  158773. */
  158774. #ifdef HAVE_UNSIGNED_CHAR
  158775. typedef unsigned char JSAMPLE;
  158776. #define GETJSAMPLE(value) ((int) (value))
  158777. #else /* not HAVE_UNSIGNED_CHAR */
  158778. typedef char JSAMPLE;
  158779. #ifdef CHAR_IS_UNSIGNED
  158780. #define GETJSAMPLE(value) ((int) (value))
  158781. #else
  158782. #define GETJSAMPLE(value) ((int) (value) & 0xFF)
  158783. #endif /* CHAR_IS_UNSIGNED */
  158784. #endif /* HAVE_UNSIGNED_CHAR */
  158785. #define MAXJSAMPLE 255
  158786. #define CENTERJSAMPLE 128
  158787. #endif /* BITS_IN_JSAMPLE == 8 */
  158788. #if BITS_IN_JSAMPLE == 12
  158789. /* JSAMPLE should be the smallest type that will hold the values 0..4095.
  158790. * On nearly all machines "short" will do nicely.
  158791. */
  158792. typedef short JSAMPLE;
  158793. #define GETJSAMPLE(value) ((int) (value))
  158794. #define MAXJSAMPLE 4095
  158795. #define CENTERJSAMPLE 2048
  158796. #endif /* BITS_IN_JSAMPLE == 12 */
  158797. /* Representation of a DCT frequency coefficient.
  158798. * This should be a signed value of at least 16 bits; "short" is usually OK.
  158799. * Again, we allocate large arrays of these, but you can change to int
  158800. * if you have memory to burn and "short" is really slow.
  158801. */
  158802. typedef short JCOEF;
  158803. /* Compressed datastreams are represented as arrays of JOCTET.
  158804. * These must be EXACTLY 8 bits wide, at least once they are written to
  158805. * external storage. Note that when using the stdio data source/destination
  158806. * managers, this is also the data type passed to fread/fwrite.
  158807. */
  158808. #ifdef HAVE_UNSIGNED_CHAR
  158809. typedef unsigned char JOCTET;
  158810. #define GETJOCTET(value) (value)
  158811. #else /* not HAVE_UNSIGNED_CHAR */
  158812. typedef char JOCTET;
  158813. #ifdef CHAR_IS_UNSIGNED
  158814. #define GETJOCTET(value) (value)
  158815. #else
  158816. #define GETJOCTET(value) ((value) & 0xFF)
  158817. #endif /* CHAR_IS_UNSIGNED */
  158818. #endif /* HAVE_UNSIGNED_CHAR */
  158819. /* These typedefs are used for various table entries and so forth.
  158820. * They must be at least as wide as specified; but making them too big
  158821. * won't cost a huge amount of memory, so we don't provide special
  158822. * extraction code like we did for JSAMPLE. (In other words, these
  158823. * typedefs live at a different point on the speed/space tradeoff curve.)
  158824. */
  158825. /* UINT8 must hold at least the values 0..255. */
  158826. #ifdef HAVE_UNSIGNED_CHAR
  158827. typedef unsigned char UINT8;
  158828. #else /* not HAVE_UNSIGNED_CHAR */
  158829. #ifdef CHAR_IS_UNSIGNED
  158830. typedef char UINT8;
  158831. #else /* not CHAR_IS_UNSIGNED */
  158832. typedef short UINT8;
  158833. #endif /* CHAR_IS_UNSIGNED */
  158834. #endif /* HAVE_UNSIGNED_CHAR */
  158835. /* UINT16 must hold at least the values 0..65535. */
  158836. #ifdef HAVE_UNSIGNED_SHORT
  158837. typedef unsigned short UINT16;
  158838. #else /* not HAVE_UNSIGNED_SHORT */
  158839. typedef unsigned int UINT16;
  158840. #endif /* HAVE_UNSIGNED_SHORT */
  158841. /* INT16 must hold at least the values -32768..32767. */
  158842. #ifndef XMD_H /* X11/xmd.h correctly defines INT16 */
  158843. typedef short INT16;
  158844. #endif
  158845. /* INT32 must hold at least signed 32-bit values. */
  158846. #ifndef XMD_H /* X11/xmd.h correctly defines INT32 */
  158847. typedef long INT32;
  158848. #endif
  158849. /* Datatype used for image dimensions. The JPEG standard only supports
  158850. * images up to 64K*64K due to 16-bit fields in SOF markers. Therefore
  158851. * "unsigned int" is sufficient on all machines. However, if you need to
  158852. * handle larger images and you don't mind deviating from the spec, you
  158853. * can change this datatype.
  158854. */
  158855. typedef unsigned int JDIMENSION;
  158856. #define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */
  158857. /* These macros are used in all function definitions and extern declarations.
  158858. * You could modify them if you need to change function linkage conventions;
  158859. * in particular, you'll need to do that to make the library a Windows DLL.
  158860. * Another application is to make all functions global for use with debuggers
  158861. * or code profilers that require it.
  158862. */
  158863. /* a function called through method pointers: */
  158864. #define METHODDEF(type) static type
  158865. /* a function used only in its module: */
  158866. #define LOCAL(type) static type
  158867. /* a function referenced thru EXTERNs: */
  158868. #define GLOBAL(type) type
  158869. /* a reference to a GLOBAL function: */
  158870. #define EXTERN(type) extern type
  158871. /* This macro is used to declare a "method", that is, a function pointer.
  158872. * We want to supply prototype parameters if the compiler can cope.
  158873. * Note that the arglist parameter must be parenthesized!
  158874. * Again, you can customize this if you need special linkage keywords.
  158875. */
  158876. #ifdef HAVE_PROTOTYPES
  158877. #define JMETHOD(type,methodname,arglist) type (*methodname) arglist
  158878. #else
  158879. #define JMETHOD(type,methodname,arglist) type (*methodname) ()
  158880. #endif
  158881. /* Here is the pseudo-keyword for declaring pointers that must be "far"
  158882. * on 80x86 machines. Most of the specialized coding for 80x86 is handled
  158883. * by just saying "FAR *" where such a pointer is needed. In a few places
  158884. * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol.
  158885. */
  158886. #ifdef NEED_FAR_POINTERS
  158887. #define FAR far
  158888. #else
  158889. #define FAR
  158890. #endif
  158891. /*
  158892. * On a few systems, type boolean and/or its values FALSE, TRUE may appear
  158893. * in standard header files. Or you may have conflicts with application-
  158894. * specific header files that you want to include together with these files.
  158895. * Defining HAVE_BOOLEAN before including jpeglib.h should make it work.
  158896. */
  158897. #ifndef HAVE_BOOLEAN
  158898. typedef int boolean;
  158899. #endif
  158900. #ifndef FALSE /* in case these macros already exist */
  158901. #define FALSE 0 /* values of boolean */
  158902. #endif
  158903. #ifndef TRUE
  158904. #define TRUE 1
  158905. #endif
  158906. /*
  158907. * The remaining options affect code selection within the JPEG library,
  158908. * but they don't need to be visible to most applications using the library.
  158909. * To minimize application namespace pollution, the symbols won't be
  158910. * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined.
  158911. */
  158912. #ifdef JPEG_INTERNALS
  158913. #define JPEG_INTERNAL_OPTIONS
  158914. #endif
  158915. #ifdef JPEG_INTERNAL_OPTIONS
  158916. /*
  158917. * These defines indicate whether to include various optional functions.
  158918. * Undefining some of these symbols will produce a smaller but less capable
  158919. * library. Note that you can leave certain source files out of the
  158920. * compilation/linking process if you've #undef'd the corresponding symbols.
  158921. * (You may HAVE to do that if your compiler doesn't like null source files.)
  158922. */
  158923. /* Arithmetic coding is unsupported for legal reasons. Complaints to IBM. */
  158924. /* Capability options common to encoder and decoder: */
  158925. #define DCT_ISLOW_SUPPORTED /* slow but accurate integer algorithm */
  158926. #define DCT_IFAST_SUPPORTED /* faster, less accurate integer method */
  158927. #define DCT_FLOAT_SUPPORTED /* floating-point: accurate, fast on fast HW */
  158928. /* Encoder capability options: */
  158929. #undef C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  158930. #define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  158931. #define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  158932. #define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */
  158933. /* Note: if you selected 12-bit data precision, it is dangerous to turn off
  158934. * ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8-bit
  158935. * precision, so jchuff.c normally uses entropy optimization to compute
  158936. * usable tables for higher precision. If you don't want to do optimization,
  158937. * you'll have to supply different default Huffman tables.
  158938. * The exact same statements apply for progressive JPEG: the default tables
  158939. * don't work for progressive mode. (This may get fixed, however.)
  158940. */
  158941. #define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */
  158942. /* Decoder capability options: */
  158943. #undef D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  158944. #define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  158945. #define D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  158946. #define SAVE_MARKERS_SUPPORTED /* jpeg_save_markers() needed? */
  158947. #define BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */
  158948. #define IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */
  158949. #undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */
  158950. #define UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */
  158951. #define QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */
  158952. #define QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */
  158953. /* more capability options later, no doubt */
  158954. /*
  158955. * Ordering of RGB data in scanlines passed to or from the application.
  158956. * If your application wants to deal with data in the order B,G,R, just
  158957. * change these macros. You can also deal with formats such as R,G,B,X
  158958. * (one extra byte per pixel) by changing RGB_PIXELSIZE. Note that changing
  158959. * the offsets will also change the order in which colormap data is organized.
  158960. * RESTRICTIONS:
  158961. * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats.
  158962. * 2. These macros only affect RGB<=>YCbCr color conversion, so they are not
  158963. * useful if you are using JPEG color spaces other than YCbCr or grayscale.
  158964. * 3. The color quantizer modules will not behave desirably if RGB_PIXELSIZE
  158965. * is not 3 (they don't understand about dummy color components!). So you
  158966. * can't use color quantization if you change that value.
  158967. */
  158968. #define RGB_RED 0 /* Offset of Red in an RGB scanline element */
  158969. #define RGB_GREEN 1 /* Offset of Green */
  158970. #define RGB_BLUE 2 /* Offset of Blue */
  158971. #define RGB_PIXELSIZE 3 /* JSAMPLEs per RGB scanline element */
  158972. /* Definitions for speed-related optimizations. */
  158973. /* If your compiler supports inline functions, define INLINE
  158974. * as the inline keyword; otherwise define it as empty.
  158975. */
  158976. #ifndef INLINE
  158977. #ifdef __GNUC__ /* for instance, GNU C knows about inline */
  158978. #define INLINE __inline__
  158979. #endif
  158980. #ifndef INLINE
  158981. #define INLINE /* default is to define it as empty */
  158982. #endif
  158983. #endif
  158984. /* On some machines (notably 68000 series) "int" is 32 bits, but multiplying
  158985. * two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIER
  158986. * as short on such a machine. MULTIPLIER must be at least 16 bits wide.
  158987. */
  158988. #ifndef MULTIPLIER
  158989. #define MULTIPLIER int /* type for fastest integer multiply */
  158990. #endif
  158991. /* FAST_FLOAT should be either float or double, whichever is done faster
  158992. * by your compiler. (Note that this type is only used in the floating point
  158993. * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.)
  158994. * Typically, float is faster in ANSI C compilers, while double is faster in
  158995. * pre-ANSI compilers (because they insist on converting to double anyway).
  158996. * The code below therefore chooses float if we have ANSI-style prototypes.
  158997. */
  158998. #ifndef FAST_FLOAT
  158999. #ifdef HAVE_PROTOTYPES
  159000. #define FAST_FLOAT float
  159001. #else
  159002. #define FAST_FLOAT double
  159003. #endif
  159004. #endif
  159005. #endif /* JPEG_INTERNAL_OPTIONS */
  159006. /*** End of inlined file: jmorecfg.h ***/
  159007. /* seldom changed options */
  159008. /* Version ID for the JPEG library.
  159009. * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60".
  159010. */
  159011. #define JPEG_LIB_VERSION 62 /* Version 6b */
  159012. /* Various constants determining the sizes of things.
  159013. * All of these are specified by the JPEG standard, so don't change them
  159014. * if you want to be compatible.
  159015. */
  159016. #define DCTSIZE 8 /* The basic DCT block is 8x8 samples */
  159017. #define DCTSIZE2 64 /* DCTSIZE squared; # of elements in a block */
  159018. #define NUM_QUANT_TBLS 4 /* Quantization tables are numbered 0..3 */
  159019. #define NUM_HUFF_TBLS 4 /* Huffman tables are numbered 0..3 */
  159020. #define NUM_ARITH_TBLS 16 /* Arith-coding tables are numbered 0..15 */
  159021. #define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */
  159022. #define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */
  159023. /* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard;
  159024. * the PostScript DCT filter can emit files with many more than 10 blocks/MCU.
  159025. * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU
  159026. * to handle it. We even let you do this from the jconfig.h file. However,
  159027. * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe
  159028. * sometimes emits noncompliant files doesn't mean you should too.
  159029. */
  159030. #define C_MAX_BLOCKS_IN_MCU 10 /* compressor's limit on blocks per MCU */
  159031. #ifndef D_MAX_BLOCKS_IN_MCU
  159032. #define D_MAX_BLOCKS_IN_MCU 10 /* decompressor's limit on blocks per MCU */
  159033. #endif
  159034. /* Data structures for images (arrays of samples and of DCT coefficients).
  159035. * On 80x86 machines, the image arrays are too big for near pointers,
  159036. * but the pointer arrays can fit in near memory.
  159037. */
  159038. typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */
  159039. typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */
  159040. typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */
  159041. typedef JCOEF JBLOCK[DCTSIZE2]; /* one block of coefficients */
  159042. typedef JBLOCK FAR *JBLOCKROW; /* pointer to one row of coefficient blocks */
  159043. typedef JBLOCKROW *JBLOCKARRAY; /* a 2-D array of coefficient blocks */
  159044. typedef JBLOCKARRAY *JBLOCKIMAGE; /* a 3-D array of coefficient blocks */
  159045. typedef JCOEF FAR *JCOEFPTR; /* useful in a couple of places */
  159046. /* Types for JPEG compression parameters and working tables. */
  159047. /* DCT coefficient quantization tables. */
  159048. typedef struct {
  159049. /* This array gives the coefficient quantizers in natural array order
  159050. * (not the zigzag order in which they are stored in a JPEG DQT marker).
  159051. * CAUTION: IJG versions prior to v6a kept this array in zigzag order.
  159052. */
  159053. UINT16 quantval[DCTSIZE2]; /* quantization step for each coefficient */
  159054. /* This field is used only during compression. It's initialized FALSE when
  159055. * the table is created, and set TRUE when it's been output to the file.
  159056. * You could suppress output of a table by setting this to TRUE.
  159057. * (See jpeg_suppress_tables for an example.)
  159058. */
  159059. boolean sent_table; /* TRUE when table has been output */
  159060. } JQUANT_TBL;
  159061. /* Huffman coding tables. */
  159062. typedef struct {
  159063. /* These two fields directly represent the contents of a JPEG DHT marker */
  159064. UINT8 bits[17]; /* bits[k] = # of symbols with codes of */
  159065. /* length k bits; bits[0] is unused */
  159066. UINT8 huffval[256]; /* The symbols, in order of incr code length */
  159067. /* This field is used only during compression. It's initialized FALSE when
  159068. * the table is created, and set TRUE when it's been output to the file.
  159069. * You could suppress output of a table by setting this to TRUE.
  159070. * (See jpeg_suppress_tables for an example.)
  159071. */
  159072. boolean sent_table; /* TRUE when table has been output */
  159073. } JHUFF_TBL;
  159074. /* Basic info about one component (color channel). */
  159075. typedef struct {
  159076. /* These values are fixed over the whole image. */
  159077. /* For compression, they must be supplied by parameter setup; */
  159078. /* for decompression, they are read from the SOF marker. */
  159079. int component_id; /* identifier for this component (0..255) */
  159080. int component_index; /* its index in SOF or cinfo->comp_info[] */
  159081. int h_samp_factor; /* horizontal sampling factor (1..4) */
  159082. int v_samp_factor; /* vertical sampling factor (1..4) */
  159083. int quant_tbl_no; /* quantization table selector (0..3) */
  159084. /* These values may vary between scans. */
  159085. /* For compression, they must be supplied by parameter setup; */
  159086. /* for decompression, they are read from the SOS marker. */
  159087. /* The decompressor output side may not use these variables. */
  159088. int dc_tbl_no; /* DC entropy table selector (0..3) */
  159089. int ac_tbl_no; /* AC entropy table selector (0..3) */
  159090. /* Remaining fields should be treated as private by applications. */
  159091. /* These values are computed during compression or decompression startup: */
  159092. /* Component's size in DCT blocks.
  159093. * Any dummy blocks added to complete an MCU are not counted; therefore
  159094. * these values do not depend on whether a scan is interleaved or not.
  159095. */
  159096. JDIMENSION width_in_blocks;
  159097. JDIMENSION height_in_blocks;
  159098. /* Size of a DCT block in samples. Always DCTSIZE for compression.
  159099. * For decompression this is the size of the output from one DCT block,
  159100. * reflecting any scaling we choose to apply during the IDCT step.
  159101. * Values of 1,2,4,8 are likely to be supported. Note that different
  159102. * components may receive different IDCT scalings.
  159103. */
  159104. int DCT_scaled_size;
  159105. /* The downsampled dimensions are the component's actual, unpadded number
  159106. * of samples at the main buffer (preprocessing/compression interface), thus
  159107. * downsampled_width = ceil(image_width * Hi/Hmax)
  159108. * and similarly for height. For decompression, IDCT scaling is included, so
  159109. * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
  159110. */
  159111. JDIMENSION downsampled_width; /* actual width in samples */
  159112. JDIMENSION downsampled_height; /* actual height in samples */
  159113. /* This flag is used only for decompression. In cases where some of the
  159114. * components will be ignored (eg grayscale output from YCbCr image),
  159115. * we can skip most computations for the unused components.
  159116. */
  159117. boolean component_needed; /* do we need the value of this component? */
  159118. /* These values are computed before starting a scan of the component. */
  159119. /* The decompressor output side may not use these variables. */
  159120. int MCU_width; /* number of blocks per MCU, horizontally */
  159121. int MCU_height; /* number of blocks per MCU, vertically */
  159122. int MCU_blocks; /* MCU_width * MCU_height */
  159123. int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */
  159124. int last_col_width; /* # of non-dummy blocks across in last MCU */
  159125. int last_row_height; /* # of non-dummy blocks down in last MCU */
  159126. /* Saved quantization table for component; NULL if none yet saved.
  159127. * See jdinput.c comments about the need for this information.
  159128. * This field is currently used only for decompression.
  159129. */
  159130. JQUANT_TBL * quant_table;
  159131. /* Private per-component storage for DCT or IDCT subsystem. */
  159132. void * dct_table;
  159133. } jpeg_component_info;
  159134. /* The script for encoding a multiple-scan file is an array of these: */
  159135. typedef struct {
  159136. int comps_in_scan; /* number of components encoded in this scan */
  159137. int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */
  159138. int Ss, Se; /* progressive JPEG spectral selection parms */
  159139. int Ah, Al; /* progressive JPEG successive approx. parms */
  159140. } jpeg_scan_info;
  159141. /* The decompressor can save APPn and COM markers in a list of these: */
  159142. typedef struct jpeg_marker_struct FAR * jpeg_saved_marker_ptr;
  159143. struct jpeg_marker_struct {
  159144. jpeg_saved_marker_ptr next; /* next in list, or NULL */
  159145. UINT8 marker; /* marker code: JPEG_COM, or JPEG_APP0+n */
  159146. unsigned int original_length; /* # bytes of data in the file */
  159147. unsigned int data_length; /* # bytes of data saved at data[] */
  159148. JOCTET FAR * data; /* the data contained in the marker */
  159149. /* the marker length word is not counted in data_length or original_length */
  159150. };
  159151. /* Known color spaces. */
  159152. typedef enum {
  159153. JCS_UNKNOWN, /* error/unspecified */
  159154. JCS_GRAYSCALE, /* monochrome */
  159155. JCS_RGB, /* red/green/blue */
  159156. JCS_YCbCr, /* Y/Cb/Cr (also known as YUV) */
  159157. JCS_CMYK, /* C/M/Y/K */
  159158. JCS_YCCK /* Y/Cb/Cr/K */
  159159. } J_COLOR_SPACE;
  159160. /* DCT/IDCT algorithm options. */
  159161. typedef enum {
  159162. JDCT_ISLOW, /* slow but accurate integer algorithm */
  159163. JDCT_IFAST, /* faster, less accurate integer method */
  159164. JDCT_FLOAT /* floating-point: accurate, fast on fast HW */
  159165. } J_DCT_METHOD;
  159166. #ifndef JDCT_DEFAULT /* may be overridden in jconfig.h */
  159167. #define JDCT_DEFAULT JDCT_ISLOW
  159168. #endif
  159169. #ifndef JDCT_FASTEST /* may be overridden in jconfig.h */
  159170. #define JDCT_FASTEST JDCT_IFAST
  159171. #endif
  159172. /* Dithering options for decompression. */
  159173. typedef enum {
  159174. JDITHER_NONE, /* no dithering */
  159175. JDITHER_ORDERED, /* simple ordered dither */
  159176. JDITHER_FS /* Floyd-Steinberg error diffusion dither */
  159177. } J_DITHER_MODE;
  159178. /* Common fields between JPEG compression and decompression master structs. */
  159179. #define jpeg_common_fields \
  159180. struct jpeg_error_mgr * err; /* Error handler module */\
  159181. struct jpeg_memory_mgr * mem; /* Memory manager module */\
  159182. struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\
  159183. void * client_data; /* Available for use by application */\
  159184. boolean is_decompressor; /* So common code can tell which is which */\
  159185. int global_state /* For checking call sequence validity */
  159186. /* Routines that are to be used by both halves of the library are declared
  159187. * to receive a pointer to this structure. There are no actual instances of
  159188. * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct.
  159189. */
  159190. struct jpeg_common_struct {
  159191. jpeg_common_fields; /* Fields common to both master struct types */
  159192. /* Additional fields follow in an actual jpeg_compress_struct or
  159193. * jpeg_decompress_struct. All three structs must agree on these
  159194. * initial fields! (This would be a lot cleaner in C++.)
  159195. */
  159196. };
  159197. typedef struct jpeg_common_struct * j_common_ptr;
  159198. typedef struct jpeg_compress_struct * j_compress_ptr;
  159199. typedef struct jpeg_decompress_struct * j_decompress_ptr;
  159200. /* Master record for a compression instance */
  159201. struct jpeg_compress_struct {
  159202. jpeg_common_fields; /* Fields shared with jpeg_decompress_struct */
  159203. /* Destination for compressed data */
  159204. struct jpeg_destination_mgr * dest;
  159205. /* Description of source image --- these fields must be filled in by
  159206. * outer application before starting compression. in_color_space must
  159207. * be correct before you can even call jpeg_set_defaults().
  159208. */
  159209. JDIMENSION image_width; /* input image width */
  159210. JDIMENSION image_height; /* input image height */
  159211. int input_components; /* # of color components in input image */
  159212. J_COLOR_SPACE in_color_space; /* colorspace of input image */
  159213. double input_gamma; /* image gamma of input image */
  159214. /* Compression parameters --- these fields must be set before calling
  159215. * jpeg_start_compress(). We recommend calling jpeg_set_defaults() to
  159216. * initialize everything to reasonable defaults, then changing anything
  159217. * the application specifically wants to change. That way you won't get
  159218. * burnt when new parameters are added. Also note that there are several
  159219. * helper routines to simplify changing parameters.
  159220. */
  159221. int data_precision; /* bits of precision in image data */
  159222. int num_components; /* # of color components in JPEG image */
  159223. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  159224. jpeg_component_info * comp_info;
  159225. /* comp_info[i] describes component that appears i'th in SOF */
  159226. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  159227. /* ptrs to coefficient quantization tables, or NULL if not defined */
  159228. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  159229. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  159230. /* ptrs to Huffman coding tables, or NULL if not defined */
  159231. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  159232. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  159233. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  159234. int num_scans; /* # of entries in scan_info array */
  159235. const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */
  159236. /* The default value of scan_info is NULL, which causes a single-scan
  159237. * sequential JPEG file to be emitted. To create a multi-scan file,
  159238. * set num_scans and scan_info to point to an array of scan definitions.
  159239. */
  159240. boolean raw_data_in; /* TRUE=caller supplies downsampled data */
  159241. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  159242. boolean optimize_coding; /* TRUE=optimize entropy encoding parms */
  159243. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  159244. int smoothing_factor; /* 1..100, or 0 for no input smoothing */
  159245. J_DCT_METHOD dct_method; /* DCT algorithm selector */
  159246. /* The restart interval can be specified in absolute MCUs by setting
  159247. * restart_interval, or in MCU rows by setting restart_in_rows
  159248. * (in which case the correct restart_interval will be figured
  159249. * for each scan).
  159250. */
  159251. unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */
  159252. int restart_in_rows; /* if > 0, MCU rows per restart interval */
  159253. /* Parameters controlling emission of special markers. */
  159254. boolean write_JFIF_header; /* should a JFIF marker be written? */
  159255. UINT8 JFIF_major_version; /* What to write for the JFIF version number */
  159256. UINT8 JFIF_minor_version;
  159257. /* These three values are not used by the JPEG code, merely copied */
  159258. /* into the JFIF APP0 marker. density_unit can be 0 for unknown, */
  159259. /* 1 for dots/inch, or 2 for dots/cm. Note that the pixel aspect */
  159260. /* ratio is defined by X_density/Y_density even when density_unit=0. */
  159261. UINT8 density_unit; /* JFIF code for pixel size units */
  159262. UINT16 X_density; /* Horizontal pixel density */
  159263. UINT16 Y_density; /* Vertical pixel density */
  159264. boolean write_Adobe_marker; /* should an Adobe marker be written? */
  159265. /* State variable: index of next scanline to be written to
  159266. * jpeg_write_scanlines(). Application may use this to control its
  159267. * processing loop, e.g., "while (next_scanline < image_height)".
  159268. */
  159269. JDIMENSION next_scanline; /* 0 .. image_height-1 */
  159270. /* Remaining fields are known throughout compressor, but generally
  159271. * should not be touched by a surrounding application.
  159272. */
  159273. /*
  159274. * These fields are computed during compression startup
  159275. */
  159276. boolean progressive_mode; /* TRUE if scan script uses progressive mode */
  159277. int max_h_samp_factor; /* largest h_samp_factor */
  159278. int max_v_samp_factor; /* largest v_samp_factor */
  159279. JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to coef ctlr */
  159280. /* The coefficient controller receives data in units of MCU rows as defined
  159281. * for fully interleaved scans (whether the JPEG file is interleaved or not).
  159282. * There are v_samp_factor * DCTSIZE sample rows of each component in an
  159283. * "iMCU" (interleaved MCU) row.
  159284. */
  159285. /*
  159286. * These fields are valid during any one scan.
  159287. * They describe the components and MCUs actually appearing in the scan.
  159288. */
  159289. int comps_in_scan; /* # of JPEG components in this scan */
  159290. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  159291. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  159292. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  159293. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  159294. int blocks_in_MCU; /* # of DCT blocks per MCU */
  159295. int MCU_membership[C_MAX_BLOCKS_IN_MCU];
  159296. /* MCU_membership[i] is index in cur_comp_info of component owning */
  159297. /* i'th block in an MCU */
  159298. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  159299. /*
  159300. * Links to compression subobjects (methods and private variables of modules)
  159301. */
  159302. struct jpeg_comp_master * master;
  159303. struct jpeg_c_main_controller * main;
  159304. struct jpeg_c_prep_controller * prep;
  159305. struct jpeg_c_coef_controller * coef;
  159306. struct jpeg_marker_writer * marker;
  159307. struct jpeg_color_converter * cconvert;
  159308. struct jpeg_downsampler * downsample;
  159309. struct jpeg_forward_dct * fdct;
  159310. struct jpeg_entropy_encoder * entropy;
  159311. jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */
  159312. int script_space_size;
  159313. };
  159314. /* Master record for a decompression instance */
  159315. struct jpeg_decompress_struct {
  159316. jpeg_common_fields; /* Fields shared with jpeg_compress_struct */
  159317. /* Source of compressed data */
  159318. struct jpeg_source_mgr * src;
  159319. /* Basic description of image --- filled in by jpeg_read_header(). */
  159320. /* Application may inspect these values to decide how to process image. */
  159321. JDIMENSION image_width; /* nominal image width (from SOF marker) */
  159322. JDIMENSION image_height; /* nominal image height */
  159323. int num_components; /* # of color components in JPEG image */
  159324. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  159325. /* Decompression processing parameters --- these fields must be set before
  159326. * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes
  159327. * them to default values.
  159328. */
  159329. J_COLOR_SPACE out_color_space; /* colorspace for output */
  159330. unsigned int scale_num, scale_denom; /* fraction by which to scale image */
  159331. double output_gamma; /* image gamma wanted in output */
  159332. boolean buffered_image; /* TRUE=multiple output passes */
  159333. boolean raw_data_out; /* TRUE=downsampled data wanted */
  159334. J_DCT_METHOD dct_method; /* IDCT algorithm selector */
  159335. boolean do_fancy_upsampling; /* TRUE=apply fancy upsampling */
  159336. boolean do_block_smoothing; /* TRUE=apply interblock smoothing */
  159337. boolean quantize_colors; /* TRUE=colormapped output wanted */
  159338. /* the following are ignored if not quantize_colors: */
  159339. J_DITHER_MODE dither_mode; /* type of color dithering to use */
  159340. boolean two_pass_quantize; /* TRUE=use two-pass color quantization */
  159341. int desired_number_of_colors; /* max # colors to use in created colormap */
  159342. /* these are significant only in buffered-image mode: */
  159343. boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */
  159344. boolean enable_external_quant;/* enable future use of external colormap */
  159345. boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */
  159346. /* Description of actual output image that will be returned to application.
  159347. * These fields are computed by jpeg_start_decompress().
  159348. * You can also use jpeg_calc_output_dimensions() to determine these values
  159349. * in advance of calling jpeg_start_decompress().
  159350. */
  159351. JDIMENSION output_width; /* scaled image width */
  159352. JDIMENSION output_height; /* scaled image height */
  159353. int out_color_components; /* # of color components in out_color_space */
  159354. int output_components; /* # of color components returned */
  159355. /* output_components is 1 (a colormap index) when quantizing colors;
  159356. * otherwise it equals out_color_components.
  159357. */
  159358. int rec_outbuf_height; /* min recommended height of scanline buffer */
  159359. /* If the buffer passed to jpeg_read_scanlines() is less than this many rows
  159360. * high, space and time will be wasted due to unnecessary data copying.
  159361. * Usually rec_outbuf_height will be 1 or 2, at most 4.
  159362. */
  159363. /* When quantizing colors, the output colormap is described by these fields.
  159364. * The application can supply a colormap by setting colormap non-NULL before
  159365. * calling jpeg_start_decompress; otherwise a colormap is created during
  159366. * jpeg_start_decompress or jpeg_start_output.
  159367. * The map has out_color_components rows and actual_number_of_colors columns.
  159368. */
  159369. int actual_number_of_colors; /* number of entries in use */
  159370. JSAMPARRAY colormap; /* The color map as a 2-D pixel array */
  159371. /* State variables: these variables indicate the progress of decompression.
  159372. * The application may examine these but must not modify them.
  159373. */
  159374. /* Row index of next scanline to be read from jpeg_read_scanlines().
  159375. * Application may use this to control its processing loop, e.g.,
  159376. * "while (output_scanline < output_height)".
  159377. */
  159378. JDIMENSION output_scanline; /* 0 .. output_height-1 */
  159379. /* Current input scan number and number of iMCU rows completed in scan.
  159380. * These indicate the progress of the decompressor input side.
  159381. */
  159382. int input_scan_number; /* Number of SOS markers seen so far */
  159383. JDIMENSION input_iMCU_row; /* Number of iMCU rows completed */
  159384. /* The "output scan number" is the notional scan being displayed by the
  159385. * output side. The decompressor will not allow output scan/row number
  159386. * to get ahead of input scan/row, but it can fall arbitrarily far behind.
  159387. */
  159388. int output_scan_number; /* Nominal scan number being displayed */
  159389. JDIMENSION output_iMCU_row; /* Number of iMCU rows read */
  159390. /* Current progression status. coef_bits[c][i] indicates the precision
  159391. * with which component c's DCT coefficient i (in zigzag order) is known.
  159392. * It is -1 when no data has yet been received, otherwise it is the point
  159393. * transform (shift) value for the most recent scan of the coefficient
  159394. * (thus, 0 at completion of the progression).
  159395. * This pointer is NULL when reading a non-progressive file.
  159396. */
  159397. int (*coef_bits)[DCTSIZE2]; /* -1 or current Al value for each coef */
  159398. /* Internal JPEG parameters --- the application usually need not look at
  159399. * these fields. Note that the decompressor output side may not use
  159400. * any parameters that can change between scans.
  159401. */
  159402. /* Quantization and Huffman tables are carried forward across input
  159403. * datastreams when processing abbreviated JPEG datastreams.
  159404. */
  159405. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  159406. /* ptrs to coefficient quantization tables, or NULL if not defined */
  159407. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  159408. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  159409. /* ptrs to Huffman coding tables, or NULL if not defined */
  159410. /* These parameters are never carried across datastreams, since they
  159411. * are given in SOF/SOS markers or defined to be reset by SOI.
  159412. */
  159413. int data_precision; /* bits of precision in image data */
  159414. jpeg_component_info * comp_info;
  159415. /* comp_info[i] describes component that appears i'th in SOF */
  159416. boolean progressive_mode; /* TRUE if SOFn specifies progressive mode */
  159417. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  159418. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  159419. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  159420. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  159421. unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */
  159422. /* These fields record data obtained from optional markers recognized by
  159423. * the JPEG library.
  159424. */
  159425. boolean saw_JFIF_marker; /* TRUE iff a JFIF APP0 marker was found */
  159426. /* Data copied from JFIF marker; only valid if saw_JFIF_marker is TRUE: */
  159427. UINT8 JFIF_major_version; /* JFIF version number */
  159428. UINT8 JFIF_minor_version;
  159429. UINT8 density_unit; /* JFIF code for pixel size units */
  159430. UINT16 X_density; /* Horizontal pixel density */
  159431. UINT16 Y_density; /* Vertical pixel density */
  159432. boolean saw_Adobe_marker; /* TRUE iff an Adobe APP14 marker was found */
  159433. UINT8 Adobe_transform; /* Color transform code from Adobe marker */
  159434. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  159435. /* Aside from the specific data retained from APPn markers known to the
  159436. * library, the uninterpreted contents of any or all APPn and COM markers
  159437. * can be saved in a list for examination by the application.
  159438. */
  159439. jpeg_saved_marker_ptr marker_list; /* Head of list of saved markers */
  159440. /* Remaining fields are known throughout decompressor, but generally
  159441. * should not be touched by a surrounding application.
  159442. */
  159443. /*
  159444. * These fields are computed during decompression startup
  159445. */
  159446. int max_h_samp_factor; /* largest h_samp_factor */
  159447. int max_v_samp_factor; /* largest v_samp_factor */
  159448. int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */
  159449. JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */
  159450. /* The coefficient controller's input and output progress is measured in
  159451. * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows
  159452. * in fully interleaved JPEG scans, but are used whether the scan is
  159453. * interleaved or not. We define an iMCU row as v_samp_factor DCT block
  159454. * rows of each component. Therefore, the IDCT output contains
  159455. * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row.
  159456. */
  159457. JSAMPLE * sample_range_limit; /* table for fast range-limiting */
  159458. /*
  159459. * These fields are valid during any one scan.
  159460. * They describe the components and MCUs actually appearing in the scan.
  159461. * Note that the decompressor output side must not use these fields.
  159462. */
  159463. int comps_in_scan; /* # of JPEG components in this scan */
  159464. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  159465. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  159466. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  159467. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  159468. int blocks_in_MCU; /* # of DCT blocks per MCU */
  159469. int MCU_membership[D_MAX_BLOCKS_IN_MCU];
  159470. /* MCU_membership[i] is index in cur_comp_info of component owning */
  159471. /* i'th block in an MCU */
  159472. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  159473. /* This field is shared between entropy decoder and marker parser.
  159474. * It is either zero or the code of a JPEG marker that has been
  159475. * read from the data source, but has not yet been processed.
  159476. */
  159477. int unread_marker;
  159478. /*
  159479. * Links to decompression subobjects (methods, private variables of modules)
  159480. */
  159481. struct jpeg_decomp_master * master;
  159482. struct jpeg_d_main_controller * main;
  159483. struct jpeg_d_coef_controller * coef;
  159484. struct jpeg_d_post_controller * post;
  159485. struct jpeg_input_controller * inputctl;
  159486. struct jpeg_marker_reader * marker;
  159487. struct jpeg_entropy_decoder * entropy;
  159488. struct jpeg_inverse_dct * idct;
  159489. struct jpeg_upsampler * upsample;
  159490. struct jpeg_color_deconverter * cconvert;
  159491. struct jpeg_color_quantizer * cquantize;
  159492. };
  159493. /* "Object" declarations for JPEG modules that may be supplied or called
  159494. * directly by the surrounding application.
  159495. * As with all objects in the JPEG library, these structs only define the
  159496. * publicly visible methods and state variables of a module. Additional
  159497. * private fields may exist after the public ones.
  159498. */
  159499. /* Error handler object */
  159500. struct jpeg_error_mgr {
  159501. /* Error exit handler: does not return to caller */
  159502. JMETHOD(void, error_exit, (j_common_ptr cinfo));
  159503. /* Conditionally emit a trace or warning message */
  159504. JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level));
  159505. /* Routine that actually outputs a trace or error message */
  159506. JMETHOD(void, output_message, (j_common_ptr cinfo));
  159507. /* Format a message string for the most recent JPEG error or message */
  159508. JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer));
  159509. #define JMSG_LENGTH_MAX 200 /* recommended size of format_message buffer */
  159510. /* Reset error state variables at start of a new image */
  159511. JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo));
  159512. /* The message ID code and any parameters are saved here.
  159513. * A message can have one string parameter or up to 8 int parameters.
  159514. */
  159515. int msg_code;
  159516. #define JMSG_STR_PARM_MAX 80
  159517. union {
  159518. int i[8];
  159519. char s[JMSG_STR_PARM_MAX];
  159520. } msg_parm;
  159521. /* Standard state variables for error facility */
  159522. int trace_level; /* max msg_level that will be displayed */
  159523. /* For recoverable corrupt-data errors, we emit a warning message,
  159524. * but keep going unless emit_message chooses to abort. emit_message
  159525. * should count warnings in num_warnings. The surrounding application
  159526. * can check for bad data by seeing if num_warnings is nonzero at the
  159527. * end of processing.
  159528. */
  159529. long num_warnings; /* number of corrupt-data warnings */
  159530. /* These fields point to the table(s) of error message strings.
  159531. * An application can change the table pointer to switch to a different
  159532. * message list (typically, to change the language in which errors are
  159533. * reported). Some applications may wish to add additional error codes
  159534. * that will be handled by the JPEG library error mechanism; the second
  159535. * table pointer is used for this purpose.
  159536. *
  159537. * First table includes all errors generated by JPEG library itself.
  159538. * Error code 0 is reserved for a "no such error string" message.
  159539. */
  159540. const char * const * jpeg_message_table; /* Library errors */
  159541. int last_jpeg_message; /* Table contains strings 0..last_jpeg_message */
  159542. /* Second table can be added by application (see cjpeg/djpeg for example).
  159543. * It contains strings numbered first_addon_message..last_addon_message.
  159544. */
  159545. const char * const * addon_message_table; /* Non-library errors */
  159546. int first_addon_message; /* code for first string in addon table */
  159547. int last_addon_message; /* code for last string in addon table */
  159548. };
  159549. /* Progress monitor object */
  159550. struct jpeg_progress_mgr {
  159551. JMETHOD(void, progress_monitor, (j_common_ptr cinfo));
  159552. long pass_counter; /* work units completed in this pass */
  159553. long pass_limit; /* total number of work units in this pass */
  159554. int completed_passes; /* passes completed so far */
  159555. int total_passes; /* total number of passes expected */
  159556. };
  159557. /* Data destination object for compression */
  159558. struct jpeg_destination_mgr {
  159559. JOCTET * next_output_byte; /* => next byte to write in buffer */
  159560. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  159561. JMETHOD(void, init_destination, (j_compress_ptr cinfo));
  159562. JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo));
  159563. JMETHOD(void, term_destination, (j_compress_ptr cinfo));
  159564. };
  159565. /* Data source object for decompression */
  159566. struct jpeg_source_mgr {
  159567. const JOCTET * next_input_byte; /* => next byte to read from buffer */
  159568. size_t bytes_in_buffer; /* # of bytes remaining in buffer */
  159569. JMETHOD(void, init_source, (j_decompress_ptr cinfo));
  159570. JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo));
  159571. JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes));
  159572. JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired));
  159573. JMETHOD(void, term_source, (j_decompress_ptr cinfo));
  159574. };
  159575. /* Memory manager object.
  159576. * Allocates "small" objects (a few K total), "large" objects (tens of K),
  159577. * and "really big" objects (virtual arrays with backing store if needed).
  159578. * The memory manager does not allow individual objects to be freed; rather,
  159579. * each created object is assigned to a pool, and whole pools can be freed
  159580. * at once. This is faster and more convenient than remembering exactly what
  159581. * to free, especially where malloc()/free() are not too speedy.
  159582. * NB: alloc routines never return NULL. They exit to error_exit if not
  159583. * successful.
  159584. */
  159585. #define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */
  159586. #define JPOOL_IMAGE 1 /* lasts until done with image/datastream */
  159587. #define JPOOL_NUMPOOLS 2
  159588. typedef struct jvirt_sarray_control * jvirt_sarray_ptr;
  159589. typedef struct jvirt_barray_control * jvirt_barray_ptr;
  159590. struct jpeg_memory_mgr {
  159591. /* Method pointers */
  159592. JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id,
  159593. size_t sizeofobject));
  159594. JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id,
  159595. size_t sizeofobject));
  159596. JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id,
  159597. JDIMENSION samplesperrow,
  159598. JDIMENSION numrows));
  159599. JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id,
  159600. JDIMENSION blocksperrow,
  159601. JDIMENSION numrows));
  159602. JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo,
  159603. int pool_id,
  159604. boolean pre_zero,
  159605. JDIMENSION samplesperrow,
  159606. JDIMENSION numrows,
  159607. JDIMENSION maxaccess));
  159608. JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo,
  159609. int pool_id,
  159610. boolean pre_zero,
  159611. JDIMENSION blocksperrow,
  159612. JDIMENSION numrows,
  159613. JDIMENSION maxaccess));
  159614. JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo));
  159615. JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo,
  159616. jvirt_sarray_ptr ptr,
  159617. JDIMENSION start_row,
  159618. JDIMENSION num_rows,
  159619. boolean writable));
  159620. JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo,
  159621. jvirt_barray_ptr ptr,
  159622. JDIMENSION start_row,
  159623. JDIMENSION num_rows,
  159624. boolean writable));
  159625. JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id));
  159626. JMETHOD(void, self_destruct, (j_common_ptr cinfo));
  159627. /* Limit on memory allocation for this JPEG object. (Note that this is
  159628. * merely advisory, not a guaranteed maximum; it only affects the space
  159629. * used for virtual-array buffers.) May be changed by outer application
  159630. * after creating the JPEG object.
  159631. */
  159632. long max_memory_to_use;
  159633. /* Maximum allocation request accepted by alloc_large. */
  159634. long max_alloc_chunk;
  159635. };
  159636. /* Routine signature for application-supplied marker processing methods.
  159637. * Need not pass marker code since it is stored in cinfo->unread_marker.
  159638. */
  159639. typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo));
  159640. /* Declarations for routines called by application.
  159641. * The JPP macro hides prototype parameters from compilers that can't cope.
  159642. * Note JPP requires double parentheses.
  159643. */
  159644. #ifdef HAVE_PROTOTYPES
  159645. #define JPP(arglist) arglist
  159646. #else
  159647. #define JPP(arglist) ()
  159648. #endif
  159649. /* Short forms of external names for systems with brain-damaged linkers.
  159650. * We shorten external names to be unique in the first six letters, which
  159651. * is good enough for all known systems.
  159652. * (If your compiler itself needs names to be unique in less than 15
  159653. * characters, you are out of luck. Get a better compiler.)
  159654. */
  159655. #ifdef NEED_SHORT_EXTERNAL_NAMES
  159656. #define jpeg_std_error jStdError
  159657. #define jpeg_CreateCompress jCreaCompress
  159658. #define jpeg_CreateDecompress jCreaDecompress
  159659. #define jpeg_destroy_compress jDestCompress
  159660. #define jpeg_destroy_decompress jDestDecompress
  159661. #define jpeg_stdio_dest jStdDest
  159662. #define jpeg_stdio_src jStdSrc
  159663. #define jpeg_set_defaults jSetDefaults
  159664. #define jpeg_set_colorspace jSetColorspace
  159665. #define jpeg_default_colorspace jDefColorspace
  159666. #define jpeg_set_quality jSetQuality
  159667. #define jpeg_set_linear_quality jSetLQuality
  159668. #define jpeg_add_quant_table jAddQuantTable
  159669. #define jpeg_quality_scaling jQualityScaling
  159670. #define jpeg_simple_progression jSimProgress
  159671. #define jpeg_suppress_tables jSuppressTables
  159672. #define jpeg_alloc_quant_table jAlcQTable
  159673. #define jpeg_alloc_huff_table jAlcHTable
  159674. #define jpeg_start_compress jStrtCompress
  159675. #define jpeg_write_scanlines jWrtScanlines
  159676. #define jpeg_finish_compress jFinCompress
  159677. #define jpeg_write_raw_data jWrtRawData
  159678. #define jpeg_write_marker jWrtMarker
  159679. #define jpeg_write_m_header jWrtMHeader
  159680. #define jpeg_write_m_byte jWrtMByte
  159681. #define jpeg_write_tables jWrtTables
  159682. #define jpeg_read_header jReadHeader
  159683. #define jpeg_start_decompress jStrtDecompress
  159684. #define jpeg_read_scanlines jReadScanlines
  159685. #define jpeg_finish_decompress jFinDecompress
  159686. #define jpeg_read_raw_data jReadRawData
  159687. #define jpeg_has_multiple_scans jHasMultScn
  159688. #define jpeg_start_output jStrtOutput
  159689. #define jpeg_finish_output jFinOutput
  159690. #define jpeg_input_complete jInComplete
  159691. #define jpeg_new_colormap jNewCMap
  159692. #define jpeg_consume_input jConsumeInput
  159693. #define jpeg_calc_output_dimensions jCalcDimensions
  159694. #define jpeg_save_markers jSaveMarkers
  159695. #define jpeg_set_marker_processor jSetMarker
  159696. #define jpeg_read_coefficients jReadCoefs
  159697. #define jpeg_write_coefficients jWrtCoefs
  159698. #define jpeg_copy_critical_parameters jCopyCrit
  159699. #define jpeg_abort_compress jAbrtCompress
  159700. #define jpeg_abort_decompress jAbrtDecompress
  159701. #define jpeg_abort jAbort
  159702. #define jpeg_destroy jDestroy
  159703. #define jpeg_resync_to_restart jResyncRestart
  159704. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  159705. /* Default error-management setup */
  159706. EXTERN(struct jpeg_error_mgr *) jpeg_std_error
  159707. JPP((struct jpeg_error_mgr * err));
  159708. /* Initialization of JPEG compression objects.
  159709. * jpeg_create_compress() and jpeg_create_decompress() are the exported
  159710. * names that applications should call. These expand to calls on
  159711. * jpeg_CreateCompress and jpeg_CreateDecompress with additional information
  159712. * passed for version mismatch checking.
  159713. * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx.
  159714. */
  159715. #define jpeg_create_compress(cinfo) \
  159716. jpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, \
  159717. (size_t) sizeof(struct jpeg_compress_struct))
  159718. #define jpeg_create_decompress(cinfo) \
  159719. jpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, \
  159720. (size_t) sizeof(struct jpeg_decompress_struct))
  159721. EXTERN(void) jpeg_CreateCompress JPP((j_compress_ptr cinfo,
  159722. int version, size_t structsize));
  159723. EXTERN(void) jpeg_CreateDecompress JPP((j_decompress_ptr cinfo,
  159724. int version, size_t structsize));
  159725. /* Destruction of JPEG compression objects */
  159726. EXTERN(void) jpeg_destroy_compress JPP((j_compress_ptr cinfo));
  159727. EXTERN(void) jpeg_destroy_decompress JPP((j_decompress_ptr cinfo));
  159728. /* Standard data source and destination managers: stdio streams. */
  159729. /* Caller is responsible for opening the file before and closing after. */
  159730. EXTERN(void) jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile));
  159731. EXTERN(void) jpeg_stdio_src JPP((j_decompress_ptr cinfo, FILE * infile));
  159732. /* Default parameter setup for compression */
  159733. EXTERN(void) jpeg_set_defaults JPP((j_compress_ptr cinfo));
  159734. /* Compression parameter setup aids */
  159735. EXTERN(void) jpeg_set_colorspace JPP((j_compress_ptr cinfo,
  159736. J_COLOR_SPACE colorspace));
  159737. EXTERN(void) jpeg_default_colorspace JPP((j_compress_ptr cinfo));
  159738. EXTERN(void) jpeg_set_quality JPP((j_compress_ptr cinfo, int quality,
  159739. boolean force_baseline));
  159740. EXTERN(void) jpeg_set_linear_quality JPP((j_compress_ptr cinfo,
  159741. int scale_factor,
  159742. boolean force_baseline));
  159743. EXTERN(void) jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl,
  159744. const unsigned int *basic_table,
  159745. int scale_factor,
  159746. boolean force_baseline));
  159747. EXTERN(int) jpeg_quality_scaling JPP((int quality));
  159748. EXTERN(void) jpeg_simple_progression JPP((j_compress_ptr cinfo));
  159749. EXTERN(void) jpeg_suppress_tables JPP((j_compress_ptr cinfo,
  159750. boolean suppress));
  159751. EXTERN(JQUANT_TBL *) jpeg_alloc_quant_table JPP((j_common_ptr cinfo));
  159752. EXTERN(JHUFF_TBL *) jpeg_alloc_huff_table JPP((j_common_ptr cinfo));
  159753. /* Main entry points for compression */
  159754. EXTERN(void) jpeg_start_compress JPP((j_compress_ptr cinfo,
  159755. boolean write_all_tables));
  159756. EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo,
  159757. JSAMPARRAY scanlines,
  159758. JDIMENSION num_lines));
  159759. EXTERN(void) jpeg_finish_compress JPP((j_compress_ptr cinfo));
  159760. /* Replaces jpeg_write_scanlines when writing raw downsampled data. */
  159761. EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo,
  159762. JSAMPIMAGE data,
  159763. JDIMENSION num_lines));
  159764. /* Write a special marker. See libjpeg.doc concerning safe usage. */
  159765. EXTERN(void) jpeg_write_marker
  159766. JPP((j_compress_ptr cinfo, int marker,
  159767. const JOCTET * dataptr, unsigned int datalen));
  159768. /* Same, but piecemeal. */
  159769. EXTERN(void) jpeg_write_m_header
  159770. JPP((j_compress_ptr cinfo, int marker, unsigned int datalen));
  159771. EXTERN(void) jpeg_write_m_byte
  159772. JPP((j_compress_ptr cinfo, int val));
  159773. /* Alternate compression function: just write an abbreviated table file */
  159774. EXTERN(void) jpeg_write_tables JPP((j_compress_ptr cinfo));
  159775. /* Decompression startup: read start of JPEG datastream to see what's there */
  159776. EXTERN(int) jpeg_read_header JPP((j_decompress_ptr cinfo,
  159777. boolean require_image));
  159778. /* Return value is one of: */
  159779. #define JPEG_SUSPENDED 0 /* Suspended due to lack of input data */
  159780. #define JPEG_HEADER_OK 1 /* Found valid image datastream */
  159781. #define JPEG_HEADER_TABLES_ONLY 2 /* Found valid table-specs-only datastream */
  159782. /* If you pass require_image = TRUE (normal case), you need not check for
  159783. * a TABLES_ONLY return code; an abbreviated file will cause an error exit.
  159784. * JPEG_SUSPENDED is only possible if you use a data source module that can
  159785. * give a suspension return (the stdio source module doesn't).
  159786. */
  159787. /* Main entry points for decompression */
  159788. EXTERN(boolean) jpeg_start_decompress JPP((j_decompress_ptr cinfo));
  159789. EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo,
  159790. JSAMPARRAY scanlines,
  159791. JDIMENSION max_lines));
  159792. EXTERN(boolean) jpeg_finish_decompress JPP((j_decompress_ptr cinfo));
  159793. /* Replaces jpeg_read_scanlines when reading raw downsampled data. */
  159794. EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo,
  159795. JSAMPIMAGE data,
  159796. JDIMENSION max_lines));
  159797. /* Additional entry points for buffered-image mode. */
  159798. EXTERN(boolean) jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo));
  159799. EXTERN(boolean) jpeg_start_output JPP((j_decompress_ptr cinfo,
  159800. int scan_number));
  159801. EXTERN(boolean) jpeg_finish_output JPP((j_decompress_ptr cinfo));
  159802. EXTERN(boolean) jpeg_input_complete JPP((j_decompress_ptr cinfo));
  159803. EXTERN(void) jpeg_new_colormap JPP((j_decompress_ptr cinfo));
  159804. EXTERN(int) jpeg_consume_input JPP((j_decompress_ptr cinfo));
  159805. /* Return value is one of: */
  159806. /* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */
  159807. #define JPEG_REACHED_SOS 1 /* Reached start of new scan */
  159808. #define JPEG_REACHED_EOI 2 /* Reached end of image */
  159809. #define JPEG_ROW_COMPLETED 3 /* Completed one iMCU row */
  159810. #define JPEG_SCAN_COMPLETED 4 /* Completed last iMCU row of a scan */
  159811. /* Precalculate output dimensions for current decompression parameters. */
  159812. EXTERN(void) jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo));
  159813. /* Control saving of COM and APPn markers into marker_list. */
  159814. EXTERN(void) jpeg_save_markers
  159815. JPP((j_decompress_ptr cinfo, int marker_code,
  159816. unsigned int length_limit));
  159817. /* Install a special processing method for COM or APPn markers. */
  159818. EXTERN(void) jpeg_set_marker_processor
  159819. JPP((j_decompress_ptr cinfo, int marker_code,
  159820. jpeg_marker_parser_method routine));
  159821. /* Read or write raw DCT coefficients --- useful for lossless transcoding. */
  159822. EXTERN(jvirt_barray_ptr *) jpeg_read_coefficients JPP((j_decompress_ptr cinfo));
  159823. EXTERN(void) jpeg_write_coefficients JPP((j_compress_ptr cinfo,
  159824. jvirt_barray_ptr * coef_arrays));
  159825. EXTERN(void) jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo,
  159826. j_compress_ptr dstinfo));
  159827. /* If you choose to abort compression or decompression before completing
  159828. * jpeg_finish_(de)compress, then you need to clean up to release memory,
  159829. * temporary files, etc. You can just call jpeg_destroy_(de)compress
  159830. * if you're done with the JPEG object, but if you want to clean it up and
  159831. * reuse it, call this:
  159832. */
  159833. EXTERN(void) jpeg_abort_compress JPP((j_compress_ptr cinfo));
  159834. EXTERN(void) jpeg_abort_decompress JPP((j_decompress_ptr cinfo));
  159835. /* Generic versions of jpeg_abort and jpeg_destroy that work on either
  159836. * flavor of JPEG object. These may be more convenient in some places.
  159837. */
  159838. EXTERN(void) jpeg_abort JPP((j_common_ptr cinfo));
  159839. EXTERN(void) jpeg_destroy JPP((j_common_ptr cinfo));
  159840. /* Default restart-marker-resync procedure for use by data source modules */
  159841. EXTERN(boolean) jpeg_resync_to_restart JPP((j_decompress_ptr cinfo,
  159842. int desired));
  159843. /* These marker codes are exported since applications and data source modules
  159844. * are likely to want to use them.
  159845. */
  159846. #define JPEG_RST0 0xD0 /* RST0 marker code */
  159847. #define JPEG_EOI 0xD9 /* EOI marker code */
  159848. #define JPEG_APP0 0xE0 /* APP0 marker code */
  159849. #define JPEG_COM 0xFE /* COM marker code */
  159850. /* If we have a brain-damaged compiler that emits warnings (or worse, errors)
  159851. * for structure definitions that are never filled in, keep it quiet by
  159852. * supplying dummy definitions for the various substructures.
  159853. */
  159854. #ifdef INCOMPLETE_TYPES_BROKEN
  159855. #ifndef JPEG_INTERNALS /* will be defined in jpegint.h */
  159856. struct jvirt_sarray_control { long dummy; };
  159857. struct jvirt_barray_control { long dummy; };
  159858. struct jpeg_comp_master { long dummy; };
  159859. struct jpeg_c_main_controller { long dummy; };
  159860. struct jpeg_c_prep_controller { long dummy; };
  159861. struct jpeg_c_coef_controller { long dummy; };
  159862. struct jpeg_marker_writer { long dummy; };
  159863. struct jpeg_color_converter { long dummy; };
  159864. struct jpeg_downsampler { long dummy; };
  159865. struct jpeg_forward_dct { long dummy; };
  159866. struct jpeg_entropy_encoder { long dummy; };
  159867. struct jpeg_decomp_master { long dummy; };
  159868. struct jpeg_d_main_controller { long dummy; };
  159869. struct jpeg_d_coef_controller { long dummy; };
  159870. struct jpeg_d_post_controller { long dummy; };
  159871. struct jpeg_input_controller { long dummy; };
  159872. struct jpeg_marker_reader { long dummy; };
  159873. struct jpeg_entropy_decoder { long dummy; };
  159874. struct jpeg_inverse_dct { long dummy; };
  159875. struct jpeg_upsampler { long dummy; };
  159876. struct jpeg_color_deconverter { long dummy; };
  159877. struct jpeg_color_quantizer { long dummy; };
  159878. #endif /* JPEG_INTERNALS */
  159879. #endif /* INCOMPLETE_TYPES_BROKEN */
  159880. /*
  159881. * The JPEG library modules define JPEG_INTERNALS before including this file.
  159882. * The internal structure declarations are read only when that is true.
  159883. * Applications using the library should not include jpegint.h, but may wish
  159884. * to include jerror.h.
  159885. */
  159886. #ifdef JPEG_INTERNALS
  159887. /*** Start of inlined file: jpegint.h ***/
  159888. /* Declarations for both compression & decompression */
  159889. typedef enum { /* Operating modes for buffer controllers */
  159890. JBUF_PASS_THRU, /* Plain stripwise operation */
  159891. /* Remaining modes require a full-image buffer to have been created */
  159892. JBUF_SAVE_SOURCE, /* Run source subobject only, save output */
  159893. JBUF_CRANK_DEST, /* Run dest subobject only, using saved data */
  159894. JBUF_SAVE_AND_PASS /* Run both subobjects, save output */
  159895. } J_BUF_MODE;
  159896. /* Values of global_state field (jdapi.c has some dependencies on ordering!) */
  159897. #define CSTATE_START 100 /* after create_compress */
  159898. #define CSTATE_SCANNING 101 /* start_compress done, write_scanlines OK */
  159899. #define CSTATE_RAW_OK 102 /* start_compress done, write_raw_data OK */
  159900. #define CSTATE_WRCOEFS 103 /* jpeg_write_coefficients done */
  159901. #define DSTATE_START 200 /* after create_decompress */
  159902. #define DSTATE_INHEADER 201 /* reading header markers, no SOS yet */
  159903. #define DSTATE_READY 202 /* found SOS, ready for start_decompress */
  159904. #define DSTATE_PRELOAD 203 /* reading multiscan file in start_decompress*/
  159905. #define DSTATE_PRESCAN 204 /* performing dummy pass for 2-pass quant */
  159906. #define DSTATE_SCANNING 205 /* start_decompress done, read_scanlines OK */
  159907. #define DSTATE_RAW_OK 206 /* start_decompress done, read_raw_data OK */
  159908. #define DSTATE_BUFIMAGE 207 /* expecting jpeg_start_output */
  159909. #define DSTATE_BUFPOST 208 /* looking for SOS/EOI in jpeg_finish_output */
  159910. #define DSTATE_RDCOEFS 209 /* reading file in jpeg_read_coefficients */
  159911. #define DSTATE_STOPPING 210 /* looking for EOI in jpeg_finish_decompress */
  159912. /* Declarations for compression modules */
  159913. /* Master control module */
  159914. struct jpeg_comp_master {
  159915. JMETHOD(void, prepare_for_pass, (j_compress_ptr cinfo));
  159916. JMETHOD(void, pass_startup, (j_compress_ptr cinfo));
  159917. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  159918. /* State variables made visible to other modules */
  159919. boolean call_pass_startup; /* True if pass_startup must be called */
  159920. boolean is_last_pass; /* True during last pass */
  159921. };
  159922. /* Main buffer control (downsampled-data buffer) */
  159923. struct jpeg_c_main_controller {
  159924. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  159925. JMETHOD(void, process_data, (j_compress_ptr cinfo,
  159926. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  159927. JDIMENSION in_rows_avail));
  159928. };
  159929. /* Compression preprocessing (downsampling input buffer control) */
  159930. struct jpeg_c_prep_controller {
  159931. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  159932. JMETHOD(void, pre_process_data, (j_compress_ptr cinfo,
  159933. JSAMPARRAY input_buf,
  159934. JDIMENSION *in_row_ctr,
  159935. JDIMENSION in_rows_avail,
  159936. JSAMPIMAGE output_buf,
  159937. JDIMENSION *out_row_group_ctr,
  159938. JDIMENSION out_row_groups_avail));
  159939. };
  159940. /* Coefficient buffer control */
  159941. struct jpeg_c_coef_controller {
  159942. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  159943. JMETHOD(boolean, compress_data, (j_compress_ptr cinfo,
  159944. JSAMPIMAGE input_buf));
  159945. };
  159946. /* Colorspace conversion */
  159947. struct jpeg_color_converter {
  159948. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  159949. JMETHOD(void, color_convert, (j_compress_ptr cinfo,
  159950. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  159951. JDIMENSION output_row, int num_rows));
  159952. };
  159953. /* Downsampling */
  159954. struct jpeg_downsampler {
  159955. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  159956. JMETHOD(void, downsample, (j_compress_ptr cinfo,
  159957. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  159958. JSAMPIMAGE output_buf,
  159959. JDIMENSION out_row_group_index));
  159960. boolean need_context_rows; /* TRUE if need rows above & below */
  159961. };
  159962. /* Forward DCT (also controls coefficient quantization) */
  159963. struct jpeg_forward_dct {
  159964. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  159965. /* perhaps this should be an array??? */
  159966. JMETHOD(void, forward_DCT, (j_compress_ptr cinfo,
  159967. jpeg_component_info * compptr,
  159968. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  159969. JDIMENSION start_row, JDIMENSION start_col,
  159970. JDIMENSION num_blocks));
  159971. };
  159972. /* Entropy encoding */
  159973. struct jpeg_entropy_encoder {
  159974. JMETHOD(void, start_pass, (j_compress_ptr cinfo, boolean gather_statistics));
  159975. JMETHOD(boolean, encode_mcu, (j_compress_ptr cinfo, JBLOCKROW *MCU_data));
  159976. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  159977. };
  159978. /* Marker writing */
  159979. struct jpeg_marker_writer {
  159980. JMETHOD(void, write_file_header, (j_compress_ptr cinfo));
  159981. JMETHOD(void, write_frame_header, (j_compress_ptr cinfo));
  159982. JMETHOD(void, write_scan_header, (j_compress_ptr cinfo));
  159983. JMETHOD(void, write_file_trailer, (j_compress_ptr cinfo));
  159984. JMETHOD(void, write_tables_only, (j_compress_ptr cinfo));
  159985. /* These routines are exported to allow insertion of extra markers */
  159986. /* Probably only COM and APPn markers should be written this way */
  159987. JMETHOD(void, write_marker_header, (j_compress_ptr cinfo, int marker,
  159988. unsigned int datalen));
  159989. JMETHOD(void, write_marker_byte, (j_compress_ptr cinfo, int val));
  159990. };
  159991. /* Declarations for decompression modules */
  159992. /* Master control module */
  159993. struct jpeg_decomp_master {
  159994. JMETHOD(void, prepare_for_output_pass, (j_decompress_ptr cinfo));
  159995. JMETHOD(void, finish_output_pass, (j_decompress_ptr cinfo));
  159996. /* State variables made visible to other modules */
  159997. boolean is_dummy_pass; /* True during 1st pass for 2-pass quant */
  159998. };
  159999. /* Input control module */
  160000. struct jpeg_input_controller {
  160001. JMETHOD(int, consume_input, (j_decompress_ptr cinfo));
  160002. JMETHOD(void, reset_input_controller, (j_decompress_ptr cinfo));
  160003. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  160004. JMETHOD(void, finish_input_pass, (j_decompress_ptr cinfo));
  160005. /* State variables made visible to other modules */
  160006. boolean has_multiple_scans; /* True if file has multiple scans */
  160007. boolean eoi_reached; /* True when EOI has been consumed */
  160008. };
  160009. /* Main buffer control (downsampled-data buffer) */
  160010. struct jpeg_d_main_controller {
  160011. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  160012. JMETHOD(void, process_data, (j_decompress_ptr cinfo,
  160013. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  160014. JDIMENSION out_rows_avail));
  160015. };
  160016. /* Coefficient buffer control */
  160017. struct jpeg_d_coef_controller {
  160018. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  160019. JMETHOD(int, consume_data, (j_decompress_ptr cinfo));
  160020. JMETHOD(void, start_output_pass, (j_decompress_ptr cinfo));
  160021. JMETHOD(int, decompress_data, (j_decompress_ptr cinfo,
  160022. JSAMPIMAGE output_buf));
  160023. /* Pointer to array of coefficient virtual arrays, or NULL if none */
  160024. jvirt_barray_ptr *coef_arrays;
  160025. };
  160026. /* Decompression postprocessing (color quantization buffer control) */
  160027. struct jpeg_d_post_controller {
  160028. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  160029. JMETHOD(void, post_process_data, (j_decompress_ptr cinfo,
  160030. JSAMPIMAGE input_buf,
  160031. JDIMENSION *in_row_group_ctr,
  160032. JDIMENSION in_row_groups_avail,
  160033. JSAMPARRAY output_buf,
  160034. JDIMENSION *out_row_ctr,
  160035. JDIMENSION out_rows_avail));
  160036. };
  160037. /* Marker reading & parsing */
  160038. struct jpeg_marker_reader {
  160039. JMETHOD(void, reset_marker_reader, (j_decompress_ptr cinfo));
  160040. /* Read markers until SOS or EOI.
  160041. * Returns same codes as are defined for jpeg_consume_input:
  160042. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  160043. */
  160044. JMETHOD(int, read_markers, (j_decompress_ptr cinfo));
  160045. /* Read a restart marker --- exported for use by entropy decoder only */
  160046. jpeg_marker_parser_method read_restart_marker;
  160047. /* State of marker reader --- nominally internal, but applications
  160048. * supplying COM or APPn handlers might like to know the state.
  160049. */
  160050. boolean saw_SOI; /* found SOI? */
  160051. boolean saw_SOF; /* found SOF? */
  160052. int next_restart_num; /* next restart number expected (0-7) */
  160053. unsigned int discarded_bytes; /* # of bytes skipped looking for a marker */
  160054. };
  160055. /* Entropy decoding */
  160056. struct jpeg_entropy_decoder {
  160057. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160058. JMETHOD(boolean, decode_mcu, (j_decompress_ptr cinfo,
  160059. JBLOCKROW *MCU_data));
  160060. /* This is here to share code between baseline and progressive decoders; */
  160061. /* other modules probably should not use it */
  160062. boolean insufficient_data; /* set TRUE after emitting warning */
  160063. };
  160064. /* Inverse DCT (also performs dequantization) */
  160065. typedef JMETHOD(void, inverse_DCT_method_ptr,
  160066. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  160067. JCOEFPTR coef_block,
  160068. JSAMPARRAY output_buf, JDIMENSION output_col));
  160069. struct jpeg_inverse_dct {
  160070. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160071. /* It is useful to allow each component to have a separate IDCT method. */
  160072. inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS];
  160073. };
  160074. /* Upsampling (note that upsampler must also call color converter) */
  160075. struct jpeg_upsampler {
  160076. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160077. JMETHOD(void, upsample, (j_decompress_ptr cinfo,
  160078. JSAMPIMAGE input_buf,
  160079. JDIMENSION *in_row_group_ctr,
  160080. JDIMENSION in_row_groups_avail,
  160081. JSAMPARRAY output_buf,
  160082. JDIMENSION *out_row_ctr,
  160083. JDIMENSION out_rows_avail));
  160084. boolean need_context_rows; /* TRUE if need rows above & below */
  160085. };
  160086. /* Colorspace conversion */
  160087. struct jpeg_color_deconverter {
  160088. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160089. JMETHOD(void, color_convert, (j_decompress_ptr cinfo,
  160090. JSAMPIMAGE input_buf, JDIMENSION input_row,
  160091. JSAMPARRAY output_buf, int num_rows));
  160092. };
  160093. /* Color quantization or color precision reduction */
  160094. struct jpeg_color_quantizer {
  160095. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, boolean is_pre_scan));
  160096. JMETHOD(void, color_quantize, (j_decompress_ptr cinfo,
  160097. JSAMPARRAY input_buf, JSAMPARRAY output_buf,
  160098. int num_rows));
  160099. JMETHOD(void, finish_pass, (j_decompress_ptr cinfo));
  160100. JMETHOD(void, new_color_map, (j_decompress_ptr cinfo));
  160101. };
  160102. /* Miscellaneous useful macros */
  160103. #undef MAX
  160104. #define MAX(a,b) ((a) > (b) ? (a) : (b))
  160105. #undef MIN
  160106. #define MIN(a,b) ((a) < (b) ? (a) : (b))
  160107. /* We assume that right shift corresponds to signed division by 2 with
  160108. * rounding towards minus infinity. This is correct for typical "arithmetic
  160109. * shift" instructions that shift in copies of the sign bit. But some
  160110. * C compilers implement >> with an unsigned shift. For these machines you
  160111. * must define RIGHT_SHIFT_IS_UNSIGNED.
  160112. * RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity.
  160113. * It is only applied with constant shift counts. SHIFT_TEMPS must be
  160114. * included in the variables of any routine using RIGHT_SHIFT.
  160115. */
  160116. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  160117. #define SHIFT_TEMPS INT32 shift_temp;
  160118. #define RIGHT_SHIFT(x,shft) \
  160119. ((shift_temp = (x)) < 0 ? \
  160120. (shift_temp >> (shft)) | ((~((INT32) 0)) << (32-(shft))) : \
  160121. (shift_temp >> (shft)))
  160122. #else
  160123. #define SHIFT_TEMPS
  160124. #define RIGHT_SHIFT(x,shft) ((x) >> (shft))
  160125. #endif
  160126. /* Short forms of external names for systems with brain-damaged linkers. */
  160127. #ifdef NEED_SHORT_EXTERNAL_NAMES
  160128. #define jinit_compress_master jICompress
  160129. #define jinit_c_master_control jICMaster
  160130. #define jinit_c_main_controller jICMainC
  160131. #define jinit_c_prep_controller jICPrepC
  160132. #define jinit_c_coef_controller jICCoefC
  160133. #define jinit_color_converter jICColor
  160134. #define jinit_downsampler jIDownsampler
  160135. #define jinit_forward_dct jIFDCT
  160136. #define jinit_huff_encoder jIHEncoder
  160137. #define jinit_phuff_encoder jIPHEncoder
  160138. #define jinit_marker_writer jIMWriter
  160139. #define jinit_master_decompress jIDMaster
  160140. #define jinit_d_main_controller jIDMainC
  160141. #define jinit_d_coef_controller jIDCoefC
  160142. #define jinit_d_post_controller jIDPostC
  160143. #define jinit_input_controller jIInCtlr
  160144. #define jinit_marker_reader jIMReader
  160145. #define jinit_huff_decoder jIHDecoder
  160146. #define jinit_phuff_decoder jIPHDecoder
  160147. #define jinit_inverse_dct jIIDCT
  160148. #define jinit_upsampler jIUpsampler
  160149. #define jinit_color_deconverter jIDColor
  160150. #define jinit_1pass_quantizer jI1Quant
  160151. #define jinit_2pass_quantizer jI2Quant
  160152. #define jinit_merged_upsampler jIMUpsampler
  160153. #define jinit_memory_mgr jIMemMgr
  160154. #define jdiv_round_up jDivRound
  160155. #define jround_up jRound
  160156. #define jcopy_sample_rows jCopySamples
  160157. #define jcopy_block_row jCopyBlocks
  160158. #define jzero_far jZeroFar
  160159. #define jpeg_zigzag_order jZIGTable
  160160. #define jpeg_natural_order jZAGTable
  160161. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  160162. /* Compression module initialization routines */
  160163. EXTERN(void) jinit_compress_master JPP((j_compress_ptr cinfo));
  160164. EXTERN(void) jinit_c_master_control JPP((j_compress_ptr cinfo,
  160165. boolean transcode_only));
  160166. EXTERN(void) jinit_c_main_controller JPP((j_compress_ptr cinfo,
  160167. boolean need_full_buffer));
  160168. EXTERN(void) jinit_c_prep_controller JPP((j_compress_ptr cinfo,
  160169. boolean need_full_buffer));
  160170. EXTERN(void) jinit_c_coef_controller JPP((j_compress_ptr cinfo,
  160171. boolean need_full_buffer));
  160172. EXTERN(void) jinit_color_converter JPP((j_compress_ptr cinfo));
  160173. EXTERN(void) jinit_downsampler JPP((j_compress_ptr cinfo));
  160174. EXTERN(void) jinit_forward_dct JPP((j_compress_ptr cinfo));
  160175. EXTERN(void) jinit_huff_encoder JPP((j_compress_ptr cinfo));
  160176. EXTERN(void) jinit_phuff_encoder JPP((j_compress_ptr cinfo));
  160177. EXTERN(void) jinit_marker_writer JPP((j_compress_ptr cinfo));
  160178. /* Decompression module initialization routines */
  160179. EXTERN(void) jinit_master_decompress JPP((j_decompress_ptr cinfo));
  160180. EXTERN(void) jinit_d_main_controller JPP((j_decompress_ptr cinfo,
  160181. boolean need_full_buffer));
  160182. EXTERN(void) jinit_d_coef_controller JPP((j_decompress_ptr cinfo,
  160183. boolean need_full_buffer));
  160184. EXTERN(void) jinit_d_post_controller JPP((j_decompress_ptr cinfo,
  160185. boolean need_full_buffer));
  160186. EXTERN(void) jinit_input_controller JPP((j_decompress_ptr cinfo));
  160187. EXTERN(void) jinit_marker_reader JPP((j_decompress_ptr cinfo));
  160188. EXTERN(void) jinit_huff_decoder JPP((j_decompress_ptr cinfo));
  160189. EXTERN(void) jinit_phuff_decoder JPP((j_decompress_ptr cinfo));
  160190. EXTERN(void) jinit_inverse_dct JPP((j_decompress_ptr cinfo));
  160191. EXTERN(void) jinit_upsampler JPP((j_decompress_ptr cinfo));
  160192. EXTERN(void) jinit_color_deconverter JPP((j_decompress_ptr cinfo));
  160193. EXTERN(void) jinit_1pass_quantizer JPP((j_decompress_ptr cinfo));
  160194. EXTERN(void) jinit_2pass_quantizer JPP((j_decompress_ptr cinfo));
  160195. EXTERN(void) jinit_merged_upsampler JPP((j_decompress_ptr cinfo));
  160196. /* Memory manager initialization */
  160197. EXTERN(void) jinit_memory_mgr JPP((j_common_ptr cinfo));
  160198. /* Utility routines in jutils.c */
  160199. EXTERN(long) jdiv_round_up JPP((long a, long b));
  160200. EXTERN(long) jround_up JPP((long a, long b));
  160201. EXTERN(void) jcopy_sample_rows JPP((JSAMPARRAY input_array, int source_row,
  160202. JSAMPARRAY output_array, int dest_row,
  160203. int num_rows, JDIMENSION num_cols));
  160204. EXTERN(void) jcopy_block_row JPP((JBLOCKROW input_row, JBLOCKROW output_row,
  160205. JDIMENSION num_blocks));
  160206. EXTERN(void) jzero_far JPP((void FAR * target, size_t bytestozero));
  160207. /* Constant tables in jutils.c */
  160208. #if 0 /* This table is not actually needed in v6a */
  160209. extern const int jpeg_zigzag_order[]; /* natural coef order to zigzag order */
  160210. #endif
  160211. extern const int jpeg_natural_order[]; /* zigzag coef order to natural order */
  160212. /* Suppress undefined-structure complaints if necessary. */
  160213. #ifdef INCOMPLETE_TYPES_BROKEN
  160214. #ifndef AM_MEMORY_MANAGER /* only jmemmgr.c defines these */
  160215. struct jvirt_sarray_control { long dummy; };
  160216. struct jvirt_barray_control { long dummy; };
  160217. #endif
  160218. #endif /* INCOMPLETE_TYPES_BROKEN */
  160219. /*** End of inlined file: jpegint.h ***/
  160220. /* fetch private declarations */
  160221. /*** Start of inlined file: jerror.h ***/
  160222. /*
  160223. * To define the enum list of message codes, include this file without
  160224. * defining macro JMESSAGE. To create a message string table, include it
  160225. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  160226. */
  160227. #ifndef JMESSAGE
  160228. #ifndef JERROR_H
  160229. /* First time through, define the enum list */
  160230. #define JMAKE_ENUM_LIST
  160231. #else
  160232. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  160233. #define JMESSAGE(code,string)
  160234. #endif /* JERROR_H */
  160235. #endif /* JMESSAGE */
  160236. #ifdef JMAKE_ENUM_LIST
  160237. typedef enum {
  160238. #define JMESSAGE(code,string) code ,
  160239. #endif /* JMAKE_ENUM_LIST */
  160240. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  160241. /* For maintenance convenience, list is alphabetical by message code name */
  160242. JMESSAGE(JERR_ARITH_NOTIMPL,
  160243. "Sorry, there are legal restrictions on arithmetic coding")
  160244. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  160245. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  160246. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  160247. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  160248. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  160249. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  160250. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  160251. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  160252. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  160253. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  160254. JMESSAGE(JERR_BAD_LIB_VERSION,
  160255. "Wrong JPEG library version: library is %d, caller expects %d")
  160256. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  160257. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  160258. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  160259. JMESSAGE(JERR_BAD_PROGRESSION,
  160260. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  160261. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  160262. "Invalid progressive parameters at scan script entry %d")
  160263. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  160264. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  160265. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  160266. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  160267. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  160268. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  160269. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  160270. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  160271. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  160272. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  160273. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  160274. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  160275. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  160276. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  160277. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  160278. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  160279. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  160280. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  160281. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  160282. JMESSAGE(JERR_FILE_READ, "Input file read error")
  160283. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  160284. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  160285. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  160286. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  160287. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  160288. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  160289. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  160290. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  160291. "Cannot transcode due to multiple use of quantization table %d")
  160292. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  160293. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  160294. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  160295. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  160296. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  160297. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  160298. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  160299. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  160300. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  160301. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  160302. JMESSAGE(JERR_QUANT_COMPONENTS,
  160303. "Cannot quantize more than %d color components")
  160304. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  160305. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  160306. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  160307. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  160308. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  160309. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  160310. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  160311. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  160312. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  160313. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  160314. JMESSAGE(JERR_TFILE_WRITE,
  160315. "Write failed on temporary file --- out of disk space?")
  160316. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  160317. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  160318. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  160319. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  160320. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  160321. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  160322. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  160323. JMESSAGE(JMSG_VERSION, JVERSION)
  160324. JMESSAGE(JTRC_16BIT_TABLES,
  160325. "Caution: quantization tables are too coarse for baseline JPEG")
  160326. JMESSAGE(JTRC_ADOBE,
  160327. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  160328. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  160329. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  160330. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  160331. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  160332. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  160333. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  160334. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  160335. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  160336. JMESSAGE(JTRC_EOI, "End Of Image")
  160337. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  160338. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  160339. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  160340. "Warning: thumbnail image size does not match data length %u")
  160341. JMESSAGE(JTRC_JFIF_EXTENSION,
  160342. "JFIF extension marker: type 0x%02x, length %u")
  160343. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  160344. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  160345. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  160346. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  160347. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  160348. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  160349. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  160350. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  160351. JMESSAGE(JTRC_RST, "RST%d")
  160352. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  160353. "Smoothing not supported with nonstandard sampling ratios")
  160354. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  160355. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  160356. JMESSAGE(JTRC_SOI, "Start of Image")
  160357. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  160358. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  160359. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  160360. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  160361. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  160362. JMESSAGE(JTRC_THUMB_JPEG,
  160363. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  160364. JMESSAGE(JTRC_THUMB_PALETTE,
  160365. "JFIF extension marker: palette thumbnail image, length %u")
  160366. JMESSAGE(JTRC_THUMB_RGB,
  160367. "JFIF extension marker: RGB thumbnail image, length %u")
  160368. JMESSAGE(JTRC_UNKNOWN_IDS,
  160369. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  160370. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  160371. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  160372. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  160373. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  160374. "Inconsistent progression sequence for component %d coefficient %d")
  160375. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  160376. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  160377. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  160378. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  160379. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  160380. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  160381. JMESSAGE(JWRN_MUST_RESYNC,
  160382. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  160383. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  160384. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  160385. #ifdef JMAKE_ENUM_LIST
  160386. JMSG_LASTMSGCODE
  160387. } J_MESSAGE_CODE;
  160388. #undef JMAKE_ENUM_LIST
  160389. #endif /* JMAKE_ENUM_LIST */
  160390. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  160391. #undef JMESSAGE
  160392. #ifndef JERROR_H
  160393. #define JERROR_H
  160394. /* Macros to simplify using the error and trace message stuff */
  160395. /* The first parameter is either type of cinfo pointer */
  160396. /* Fatal errors (print message and exit) */
  160397. #define ERREXIT(cinfo,code) \
  160398. ((cinfo)->err->msg_code = (code), \
  160399. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160400. #define ERREXIT1(cinfo,code,p1) \
  160401. ((cinfo)->err->msg_code = (code), \
  160402. (cinfo)->err->msg_parm.i[0] = (p1), \
  160403. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160404. #define ERREXIT2(cinfo,code,p1,p2) \
  160405. ((cinfo)->err->msg_code = (code), \
  160406. (cinfo)->err->msg_parm.i[0] = (p1), \
  160407. (cinfo)->err->msg_parm.i[1] = (p2), \
  160408. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160409. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  160410. ((cinfo)->err->msg_code = (code), \
  160411. (cinfo)->err->msg_parm.i[0] = (p1), \
  160412. (cinfo)->err->msg_parm.i[1] = (p2), \
  160413. (cinfo)->err->msg_parm.i[2] = (p3), \
  160414. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160415. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  160416. ((cinfo)->err->msg_code = (code), \
  160417. (cinfo)->err->msg_parm.i[0] = (p1), \
  160418. (cinfo)->err->msg_parm.i[1] = (p2), \
  160419. (cinfo)->err->msg_parm.i[2] = (p3), \
  160420. (cinfo)->err->msg_parm.i[3] = (p4), \
  160421. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160422. #define ERREXITS(cinfo,code,str) \
  160423. ((cinfo)->err->msg_code = (code), \
  160424. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  160425. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160426. #define MAKESTMT(stuff) do { stuff } while (0)
  160427. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  160428. #define WARNMS(cinfo,code) \
  160429. ((cinfo)->err->msg_code = (code), \
  160430. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  160431. #define WARNMS1(cinfo,code,p1) \
  160432. ((cinfo)->err->msg_code = (code), \
  160433. (cinfo)->err->msg_parm.i[0] = (p1), \
  160434. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  160435. #define WARNMS2(cinfo,code,p1,p2) \
  160436. ((cinfo)->err->msg_code = (code), \
  160437. (cinfo)->err->msg_parm.i[0] = (p1), \
  160438. (cinfo)->err->msg_parm.i[1] = (p2), \
  160439. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  160440. /* Informational/debugging messages */
  160441. #define TRACEMS(cinfo,lvl,code) \
  160442. ((cinfo)->err->msg_code = (code), \
  160443. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  160444. #define TRACEMS1(cinfo,lvl,code,p1) \
  160445. ((cinfo)->err->msg_code = (code), \
  160446. (cinfo)->err->msg_parm.i[0] = (p1), \
  160447. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  160448. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  160449. ((cinfo)->err->msg_code = (code), \
  160450. (cinfo)->err->msg_parm.i[0] = (p1), \
  160451. (cinfo)->err->msg_parm.i[1] = (p2), \
  160452. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  160453. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  160454. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  160455. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  160456. (cinfo)->err->msg_code = (code); \
  160457. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  160458. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  160459. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  160460. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  160461. (cinfo)->err->msg_code = (code); \
  160462. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  160463. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  160464. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  160465. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  160466. _mp[4] = (p5); \
  160467. (cinfo)->err->msg_code = (code); \
  160468. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  160469. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  160470. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  160471. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  160472. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  160473. (cinfo)->err->msg_code = (code); \
  160474. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  160475. #define TRACEMSS(cinfo,lvl,code,str) \
  160476. ((cinfo)->err->msg_code = (code), \
  160477. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  160478. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  160479. #endif /* JERROR_H */
  160480. /*** End of inlined file: jerror.h ***/
  160481. /* fetch error codes too */
  160482. #endif
  160483. #endif /* JPEGLIB_H */
  160484. /*** End of inlined file: jpeglib.h ***/
  160485. /*** Start of inlined file: jcapimin.c ***/
  160486. #define JPEG_INTERNALS
  160487. /*** Start of inlined file: jinclude.h ***/
  160488. /* Include auto-config file to find out which system include files we need. */
  160489. #ifndef __jinclude_h__
  160490. #define __jinclude_h__
  160491. /*** Start of inlined file: jconfig.h ***/
  160492. /* see jconfig.doc for explanations */
  160493. // disable all the warnings under MSVC
  160494. #ifdef _MSC_VER
  160495. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  160496. #endif
  160497. #ifdef __BORLANDC__
  160498. #pragma warn -8057
  160499. #pragma warn -8019
  160500. #pragma warn -8004
  160501. #pragma warn -8008
  160502. #endif
  160503. #define HAVE_PROTOTYPES
  160504. #define HAVE_UNSIGNED_CHAR
  160505. #define HAVE_UNSIGNED_SHORT
  160506. /* #define void char */
  160507. /* #define const */
  160508. #undef CHAR_IS_UNSIGNED
  160509. #define HAVE_STDDEF_H
  160510. #define HAVE_STDLIB_H
  160511. #undef NEED_BSD_STRINGS
  160512. #undef NEED_SYS_TYPES_H
  160513. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  160514. #undef NEED_SHORT_EXTERNAL_NAMES
  160515. #undef INCOMPLETE_TYPES_BROKEN
  160516. /* Define "boolean" as unsigned char, not int, per Windows custom */
  160517. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  160518. typedef unsigned char boolean;
  160519. #endif
  160520. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  160521. #ifdef JPEG_INTERNALS
  160522. #undef RIGHT_SHIFT_IS_UNSIGNED
  160523. #endif /* JPEG_INTERNALS */
  160524. #ifdef JPEG_CJPEG_DJPEG
  160525. #define BMP_SUPPORTED /* BMP image file format */
  160526. #define GIF_SUPPORTED /* GIF image file format */
  160527. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  160528. #undef RLE_SUPPORTED /* Utah RLE image file format */
  160529. #define TARGA_SUPPORTED /* Targa image file format */
  160530. #define TWO_FILE_COMMANDLINE /* optional */
  160531. #define USE_SETMODE /* Microsoft has setmode() */
  160532. #undef NEED_SIGNAL_CATCHER
  160533. #undef DONT_USE_B_MODE
  160534. #undef PROGRESS_REPORT /* optional */
  160535. #endif /* JPEG_CJPEG_DJPEG */
  160536. /*** End of inlined file: jconfig.h ***/
  160537. /* auto configuration options */
  160538. #define JCONFIG_INCLUDED /* so that jpeglib.h doesn't do it again */
  160539. /*
  160540. * We need the NULL macro and size_t typedef.
  160541. * On an ANSI-conforming system it is sufficient to include <stddef.h>.
  160542. * Otherwise, we get them from <stdlib.h> or <stdio.h>; we may have to
  160543. * pull in <sys/types.h> as well.
  160544. * Note that the core JPEG library does not require <stdio.h>;
  160545. * only the default error handler and data source/destination modules do.
  160546. * But we must pull it in because of the references to FILE in jpeglib.h.
  160547. * You can remove those references if you want to compile without <stdio.h>.
  160548. */
  160549. #ifdef HAVE_STDDEF_H
  160550. #include <stddef.h>
  160551. #endif
  160552. #ifdef HAVE_STDLIB_H
  160553. #include <stdlib.h>
  160554. #endif
  160555. #ifdef NEED_SYS_TYPES_H
  160556. #include <sys/types.h>
  160557. #endif
  160558. #include <stdio.h>
  160559. /*
  160560. * We need memory copying and zeroing functions, plus strncpy().
  160561. * ANSI and System V implementations declare these in <string.h>.
  160562. * BSD doesn't have the mem() functions, but it does have bcopy()/bzero().
  160563. * Some systems may declare memset and memcpy in <memory.h>.
  160564. *
  160565. * NOTE: we assume the size parameters to these functions are of type size_t.
  160566. * Change the casts in these macros if not!
  160567. */
  160568. #ifdef NEED_BSD_STRINGS
  160569. #include <strings.h>
  160570. #define MEMZERO(target,size) bzero((void *)(target), (size_t)(size))
  160571. #define MEMCOPY(dest,src,size) bcopy((const void *)(src), (void *)(dest), (size_t)(size))
  160572. #else /* not BSD, assume ANSI/SysV string lib */
  160573. #include <string.h>
  160574. #define MEMZERO(target,size) memset((void *)(target), 0, (size_t)(size))
  160575. #define MEMCOPY(dest,src,size) memcpy((void *)(dest), (const void *)(src), (size_t)(size))
  160576. #endif
  160577. /*
  160578. * In ANSI C, and indeed any rational implementation, size_t is also the
  160579. * type returned by sizeof(). However, it seems there are some irrational
  160580. * implementations out there, in which sizeof() returns an int even though
  160581. * size_t is defined as long or unsigned long. To ensure consistent results
  160582. * we always use this SIZEOF() macro in place of using sizeof() directly.
  160583. */
  160584. #define SIZEOF(object) ((size_t) sizeof(object))
  160585. /*
  160586. * The modules that use fread() and fwrite() always invoke them through
  160587. * these macros. On some systems you may need to twiddle the argument casts.
  160588. * CAUTION: argument order is different from underlying functions!
  160589. */
  160590. #define JFREAD(file,buf,sizeofbuf) \
  160591. ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  160592. #define JFWRITE(file,buf,sizeofbuf) \
  160593. ((size_t) fwrite((const void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  160594. typedef enum { /* JPEG marker codes */
  160595. M_SOF0 = 0xc0,
  160596. M_SOF1 = 0xc1,
  160597. M_SOF2 = 0xc2,
  160598. M_SOF3 = 0xc3,
  160599. M_SOF5 = 0xc5,
  160600. M_SOF6 = 0xc6,
  160601. M_SOF7 = 0xc7,
  160602. M_JPG = 0xc8,
  160603. M_SOF9 = 0xc9,
  160604. M_SOF10 = 0xca,
  160605. M_SOF11 = 0xcb,
  160606. M_SOF13 = 0xcd,
  160607. M_SOF14 = 0xce,
  160608. M_SOF15 = 0xcf,
  160609. M_DHT = 0xc4,
  160610. M_DAC = 0xcc,
  160611. M_RST0 = 0xd0,
  160612. M_RST1 = 0xd1,
  160613. M_RST2 = 0xd2,
  160614. M_RST3 = 0xd3,
  160615. M_RST4 = 0xd4,
  160616. M_RST5 = 0xd5,
  160617. M_RST6 = 0xd6,
  160618. M_RST7 = 0xd7,
  160619. M_SOI = 0xd8,
  160620. M_EOI = 0xd9,
  160621. M_SOS = 0xda,
  160622. M_DQT = 0xdb,
  160623. M_DNL = 0xdc,
  160624. M_DRI = 0xdd,
  160625. M_DHP = 0xde,
  160626. M_EXP = 0xdf,
  160627. M_APP0 = 0xe0,
  160628. M_APP1 = 0xe1,
  160629. M_APP2 = 0xe2,
  160630. M_APP3 = 0xe3,
  160631. M_APP4 = 0xe4,
  160632. M_APP5 = 0xe5,
  160633. M_APP6 = 0xe6,
  160634. M_APP7 = 0xe7,
  160635. M_APP8 = 0xe8,
  160636. M_APP9 = 0xe9,
  160637. M_APP10 = 0xea,
  160638. M_APP11 = 0xeb,
  160639. M_APP12 = 0xec,
  160640. M_APP13 = 0xed,
  160641. M_APP14 = 0xee,
  160642. M_APP15 = 0xef,
  160643. M_JPG0 = 0xf0,
  160644. M_JPG13 = 0xfd,
  160645. M_COM = 0xfe,
  160646. M_TEM = 0x01,
  160647. M_ERROR = 0x100
  160648. } JPEG_MARKER;
  160649. /*
  160650. * Figure F.12: extend sign bit.
  160651. * On some machines, a shift and add will be faster than a table lookup.
  160652. */
  160653. #ifdef AVOID_TABLES
  160654. #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
  160655. #else
  160656. #define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
  160657. static const int extend_test[16] = /* entry n is 2**(n-1) */
  160658. { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
  160659. 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
  160660. static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
  160661. { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
  160662. ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
  160663. ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
  160664. ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
  160665. #endif /* AVOID_TABLES */
  160666. #endif
  160667. /*** End of inlined file: jinclude.h ***/
  160668. /*
  160669. * Initialization of a JPEG compression object.
  160670. * The error manager must already be set up (in case memory manager fails).
  160671. */
  160672. GLOBAL(void)
  160673. jpeg_CreateCompress (j_compress_ptr cinfo, int version, size_t structsize)
  160674. {
  160675. int i;
  160676. /* Guard against version mismatches between library and caller. */
  160677. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  160678. if (version != JPEG_LIB_VERSION)
  160679. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  160680. if (structsize != SIZEOF(struct jpeg_compress_struct))
  160681. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  160682. (int) SIZEOF(struct jpeg_compress_struct), (int) structsize);
  160683. /* For debugging purposes, we zero the whole master structure.
  160684. * But the application has already set the err pointer, and may have set
  160685. * client_data, so we have to save and restore those fields.
  160686. * Note: if application hasn't set client_data, tools like Purify may
  160687. * complain here.
  160688. */
  160689. {
  160690. struct jpeg_error_mgr * err = cinfo->err;
  160691. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  160692. MEMZERO(cinfo, SIZEOF(struct jpeg_compress_struct));
  160693. cinfo->err = err;
  160694. cinfo->client_data = client_data;
  160695. }
  160696. cinfo->is_decompressor = FALSE;
  160697. /* Initialize a memory manager instance for this object */
  160698. jinit_memory_mgr((j_common_ptr) cinfo);
  160699. /* Zero out pointers to permanent structures. */
  160700. cinfo->progress = NULL;
  160701. cinfo->dest = NULL;
  160702. cinfo->comp_info = NULL;
  160703. for (i = 0; i < NUM_QUANT_TBLS; i++)
  160704. cinfo->quant_tbl_ptrs[i] = NULL;
  160705. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  160706. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  160707. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  160708. }
  160709. cinfo->script_space = NULL;
  160710. cinfo->input_gamma = 1.0; /* in case application forgets */
  160711. /* OK, I'm ready */
  160712. cinfo->global_state = CSTATE_START;
  160713. }
  160714. /*
  160715. * Destruction of a JPEG compression object
  160716. */
  160717. GLOBAL(void)
  160718. jpeg_destroy_compress (j_compress_ptr cinfo)
  160719. {
  160720. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  160721. }
  160722. /*
  160723. * Abort processing of a JPEG compression operation,
  160724. * but don't destroy the object itself.
  160725. */
  160726. GLOBAL(void)
  160727. jpeg_abort_compress (j_compress_ptr cinfo)
  160728. {
  160729. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  160730. }
  160731. /*
  160732. * Forcibly suppress or un-suppress all quantization and Huffman tables.
  160733. * Marks all currently defined tables as already written (if suppress)
  160734. * or not written (if !suppress). This will control whether they get emitted
  160735. * by a subsequent jpeg_start_compress call.
  160736. *
  160737. * This routine is exported for use by applications that want to produce
  160738. * abbreviated JPEG datastreams. It logically belongs in jcparam.c, but
  160739. * since it is called by jpeg_start_compress, we put it here --- otherwise
  160740. * jcparam.o would be linked whether the application used it or not.
  160741. */
  160742. GLOBAL(void)
  160743. jpeg_suppress_tables (j_compress_ptr cinfo, boolean suppress)
  160744. {
  160745. int i;
  160746. JQUANT_TBL * qtbl;
  160747. JHUFF_TBL * htbl;
  160748. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  160749. if ((qtbl = cinfo->quant_tbl_ptrs[i]) != NULL)
  160750. qtbl->sent_table = suppress;
  160751. }
  160752. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  160753. if ((htbl = cinfo->dc_huff_tbl_ptrs[i]) != NULL)
  160754. htbl->sent_table = suppress;
  160755. if ((htbl = cinfo->ac_huff_tbl_ptrs[i]) != NULL)
  160756. htbl->sent_table = suppress;
  160757. }
  160758. }
  160759. /*
  160760. * Finish JPEG compression.
  160761. *
  160762. * If a multipass operating mode was selected, this may do a great deal of
  160763. * work including most of the actual output.
  160764. */
  160765. GLOBAL(void)
  160766. jpeg_finish_compress (j_compress_ptr cinfo)
  160767. {
  160768. JDIMENSION iMCU_row;
  160769. if (cinfo->global_state == CSTATE_SCANNING ||
  160770. cinfo->global_state == CSTATE_RAW_OK) {
  160771. /* Terminate first pass */
  160772. if (cinfo->next_scanline < cinfo->image_height)
  160773. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  160774. (*cinfo->master->finish_pass) (cinfo);
  160775. } else if (cinfo->global_state != CSTATE_WRCOEFS)
  160776. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  160777. /* Perform any remaining passes */
  160778. while (! cinfo->master->is_last_pass) {
  160779. (*cinfo->master->prepare_for_pass) (cinfo);
  160780. for (iMCU_row = 0; iMCU_row < cinfo->total_iMCU_rows; iMCU_row++) {
  160781. if (cinfo->progress != NULL) {
  160782. cinfo->progress->pass_counter = (long) iMCU_row;
  160783. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows;
  160784. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  160785. }
  160786. /* We bypass the main controller and invoke coef controller directly;
  160787. * all work is being done from the coefficient buffer.
  160788. */
  160789. if (! (*cinfo->coef->compress_data) (cinfo, (JSAMPIMAGE) NULL))
  160790. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  160791. }
  160792. (*cinfo->master->finish_pass) (cinfo);
  160793. }
  160794. /* Write EOI, do final cleanup */
  160795. (*cinfo->marker->write_file_trailer) (cinfo);
  160796. (*cinfo->dest->term_destination) (cinfo);
  160797. /* We can use jpeg_abort to release memory and reset global_state */
  160798. jpeg_abort((j_common_ptr) cinfo);
  160799. }
  160800. /*
  160801. * Write a special marker.
  160802. * This is only recommended for writing COM or APPn markers.
  160803. * Must be called after jpeg_start_compress() and before
  160804. * first call to jpeg_write_scanlines() or jpeg_write_raw_data().
  160805. */
  160806. GLOBAL(void)
  160807. jpeg_write_marker (j_compress_ptr cinfo, int marker,
  160808. const JOCTET *dataptr, unsigned int datalen)
  160809. {
  160810. JMETHOD(void, write_marker_byte, (j_compress_ptr info, int val));
  160811. if (cinfo->next_scanline != 0 ||
  160812. (cinfo->global_state != CSTATE_SCANNING &&
  160813. cinfo->global_state != CSTATE_RAW_OK &&
  160814. cinfo->global_state != CSTATE_WRCOEFS))
  160815. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  160816. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  160817. write_marker_byte = cinfo->marker->write_marker_byte; /* copy for speed */
  160818. while (datalen--) {
  160819. (*write_marker_byte) (cinfo, *dataptr);
  160820. dataptr++;
  160821. }
  160822. }
  160823. /* Same, but piecemeal. */
  160824. GLOBAL(void)
  160825. jpeg_write_m_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  160826. {
  160827. if (cinfo->next_scanline != 0 ||
  160828. (cinfo->global_state != CSTATE_SCANNING &&
  160829. cinfo->global_state != CSTATE_RAW_OK &&
  160830. cinfo->global_state != CSTATE_WRCOEFS))
  160831. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  160832. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  160833. }
  160834. GLOBAL(void)
  160835. jpeg_write_m_byte (j_compress_ptr cinfo, int val)
  160836. {
  160837. (*cinfo->marker->write_marker_byte) (cinfo, val);
  160838. }
  160839. /*
  160840. * Alternate compression function: just write an abbreviated table file.
  160841. * Before calling this, all parameters and a data destination must be set up.
  160842. *
  160843. * To produce a pair of files containing abbreviated tables and abbreviated
  160844. * image data, one would proceed as follows:
  160845. *
  160846. * initialize JPEG object
  160847. * set JPEG parameters
  160848. * set destination to table file
  160849. * jpeg_write_tables(cinfo);
  160850. * set destination to image file
  160851. * jpeg_start_compress(cinfo, FALSE);
  160852. * write data...
  160853. * jpeg_finish_compress(cinfo);
  160854. *
  160855. * jpeg_write_tables has the side effect of marking all tables written
  160856. * (same as jpeg_suppress_tables(..., TRUE)). Thus a subsequent start_compress
  160857. * will not re-emit the tables unless it is passed write_all_tables=TRUE.
  160858. */
  160859. GLOBAL(void)
  160860. jpeg_write_tables (j_compress_ptr cinfo)
  160861. {
  160862. if (cinfo->global_state != CSTATE_START)
  160863. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  160864. /* (Re)initialize error mgr and destination modules */
  160865. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  160866. (*cinfo->dest->init_destination) (cinfo);
  160867. /* Initialize the marker writer ... bit of a crock to do it here. */
  160868. jinit_marker_writer(cinfo);
  160869. /* Write them tables! */
  160870. (*cinfo->marker->write_tables_only) (cinfo);
  160871. /* And clean up. */
  160872. (*cinfo->dest->term_destination) (cinfo);
  160873. /*
  160874. * In library releases up through v6a, we called jpeg_abort() here to free
  160875. * any working memory allocated by the destination manager and marker
  160876. * writer. Some applications had a problem with that: they allocated space
  160877. * of their own from the library memory manager, and didn't want it to go
  160878. * away during write_tables. So now we do nothing. This will cause a
  160879. * memory leak if an app calls write_tables repeatedly without doing a full
  160880. * compression cycle or otherwise resetting the JPEG object. However, that
  160881. * seems less bad than unexpectedly freeing memory in the normal case.
  160882. * An app that prefers the old behavior can call jpeg_abort for itself after
  160883. * each call to jpeg_write_tables().
  160884. */
  160885. }
  160886. /*** End of inlined file: jcapimin.c ***/
  160887. /*** Start of inlined file: jcapistd.c ***/
  160888. #define JPEG_INTERNALS
  160889. /*
  160890. * Compression initialization.
  160891. * Before calling this, all parameters and a data destination must be set up.
  160892. *
  160893. * We require a write_all_tables parameter as a failsafe check when writing
  160894. * multiple datastreams from the same compression object. Since prior runs
  160895. * will have left all the tables marked sent_table=TRUE, a subsequent run
  160896. * would emit an abbreviated stream (no tables) by default. This may be what
  160897. * is wanted, but for safety's sake it should not be the default behavior:
  160898. * programmers should have to make a deliberate choice to emit abbreviated
  160899. * images. Therefore the documentation and examples should encourage people
  160900. * to pass write_all_tables=TRUE; then it will take active thought to do the
  160901. * wrong thing.
  160902. */
  160903. GLOBAL(void)
  160904. jpeg_start_compress (j_compress_ptr cinfo, boolean write_all_tables)
  160905. {
  160906. if (cinfo->global_state != CSTATE_START)
  160907. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  160908. if (write_all_tables)
  160909. jpeg_suppress_tables(cinfo, FALSE); /* mark all tables to be written */
  160910. /* (Re)initialize error mgr and destination modules */
  160911. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  160912. (*cinfo->dest->init_destination) (cinfo);
  160913. /* Perform master selection of active modules */
  160914. jinit_compress_master(cinfo);
  160915. /* Set up for the first pass */
  160916. (*cinfo->master->prepare_for_pass) (cinfo);
  160917. /* Ready for application to drive first pass through jpeg_write_scanlines
  160918. * or jpeg_write_raw_data.
  160919. */
  160920. cinfo->next_scanline = 0;
  160921. cinfo->global_state = (cinfo->raw_data_in ? CSTATE_RAW_OK : CSTATE_SCANNING);
  160922. }
  160923. /*
  160924. * Write some scanlines of data to the JPEG compressor.
  160925. *
  160926. * The return value will be the number of lines actually written.
  160927. * This should be less than the supplied num_lines only in case that
  160928. * the data destination module has requested suspension of the compressor,
  160929. * or if more than image_height scanlines are passed in.
  160930. *
  160931. * Note: we warn about excess calls to jpeg_write_scanlines() since
  160932. * this likely signals an application programmer error. However,
  160933. * excess scanlines passed in the last valid call are *silently* ignored,
  160934. * so that the application need not adjust num_lines for end-of-image
  160935. * when using a multiple-scanline buffer.
  160936. */
  160937. GLOBAL(JDIMENSION)
  160938. jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines,
  160939. JDIMENSION num_lines)
  160940. {
  160941. JDIMENSION row_ctr, rows_left;
  160942. if (cinfo->global_state != CSTATE_SCANNING)
  160943. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  160944. if (cinfo->next_scanline >= cinfo->image_height)
  160945. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  160946. /* Call progress monitor hook if present */
  160947. if (cinfo->progress != NULL) {
  160948. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  160949. cinfo->progress->pass_limit = (long) cinfo->image_height;
  160950. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  160951. }
  160952. /* Give master control module another chance if this is first call to
  160953. * jpeg_write_scanlines. This lets output of the frame/scan headers be
  160954. * delayed so that application can write COM, etc, markers between
  160955. * jpeg_start_compress and jpeg_write_scanlines.
  160956. */
  160957. if (cinfo->master->call_pass_startup)
  160958. (*cinfo->master->pass_startup) (cinfo);
  160959. /* Ignore any extra scanlines at bottom of image. */
  160960. rows_left = cinfo->image_height - cinfo->next_scanline;
  160961. if (num_lines > rows_left)
  160962. num_lines = rows_left;
  160963. row_ctr = 0;
  160964. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, num_lines);
  160965. cinfo->next_scanline += row_ctr;
  160966. return row_ctr;
  160967. }
  160968. /*
  160969. * Alternate entry point to write raw data.
  160970. * Processes exactly one iMCU row per call, unless suspended.
  160971. */
  160972. GLOBAL(JDIMENSION)
  160973. jpeg_write_raw_data (j_compress_ptr cinfo, JSAMPIMAGE data,
  160974. JDIMENSION num_lines)
  160975. {
  160976. JDIMENSION lines_per_iMCU_row;
  160977. if (cinfo->global_state != CSTATE_RAW_OK)
  160978. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  160979. if (cinfo->next_scanline >= cinfo->image_height) {
  160980. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  160981. return 0;
  160982. }
  160983. /* Call progress monitor hook if present */
  160984. if (cinfo->progress != NULL) {
  160985. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  160986. cinfo->progress->pass_limit = (long) cinfo->image_height;
  160987. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  160988. }
  160989. /* Give master control module another chance if this is first call to
  160990. * jpeg_write_raw_data. This lets output of the frame/scan headers be
  160991. * delayed so that application can write COM, etc, markers between
  160992. * jpeg_start_compress and jpeg_write_raw_data.
  160993. */
  160994. if (cinfo->master->call_pass_startup)
  160995. (*cinfo->master->pass_startup) (cinfo);
  160996. /* Verify that at least one iMCU row has been passed. */
  160997. lines_per_iMCU_row = cinfo->max_v_samp_factor * DCTSIZE;
  160998. if (num_lines < lines_per_iMCU_row)
  160999. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  161000. /* Directly compress the row. */
  161001. if (! (*cinfo->coef->compress_data) (cinfo, data)) {
  161002. /* If compressor did not consume the whole row, suspend processing. */
  161003. return 0;
  161004. }
  161005. /* OK, we processed one iMCU row. */
  161006. cinfo->next_scanline += lines_per_iMCU_row;
  161007. return lines_per_iMCU_row;
  161008. }
  161009. /*** End of inlined file: jcapistd.c ***/
  161010. /*** Start of inlined file: jccoefct.c ***/
  161011. #define JPEG_INTERNALS
  161012. /* We use a full-image coefficient buffer when doing Huffman optimization,
  161013. * and also for writing multiple-scan JPEG files. In all cases, the DCT
  161014. * step is run during the first pass, and subsequent passes need only read
  161015. * the buffered coefficients.
  161016. */
  161017. #ifdef ENTROPY_OPT_SUPPORTED
  161018. #define FULL_COEF_BUFFER_SUPPORTED
  161019. #else
  161020. #ifdef C_MULTISCAN_FILES_SUPPORTED
  161021. #define FULL_COEF_BUFFER_SUPPORTED
  161022. #endif
  161023. #endif
  161024. /* Private buffer controller object */
  161025. typedef struct {
  161026. struct jpeg_c_coef_controller pub; /* public fields */
  161027. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  161028. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  161029. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  161030. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  161031. /* For single-pass compression, it's sufficient to buffer just one MCU
  161032. * (although this may prove a bit slow in practice). We allocate a
  161033. * workspace of C_MAX_BLOCKS_IN_MCU coefficient blocks, and reuse it for each
  161034. * MCU constructed and sent. (On 80x86, the workspace is FAR even though
  161035. * it's not really very big; this is to keep the module interfaces unchanged
  161036. * when a large coefficient buffer is necessary.)
  161037. * In multi-pass modes, this array points to the current MCU's blocks
  161038. * within the virtual arrays.
  161039. */
  161040. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  161041. /* In multi-pass modes, we need a virtual block array for each component. */
  161042. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  161043. } my_coef_controller;
  161044. typedef my_coef_controller * my_coef_ptr;
  161045. /* Forward declarations */
  161046. METHODDEF(boolean) compress_data
  161047. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161048. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161049. METHODDEF(boolean) compress_first_pass
  161050. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161051. METHODDEF(boolean) compress_output
  161052. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161053. #endif
  161054. LOCAL(void)
  161055. start_iMCU_row (j_compress_ptr cinfo)
  161056. /* Reset within-iMCU-row counters for a new row */
  161057. {
  161058. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161059. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  161060. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  161061. * But at the bottom of the image, process only what's left.
  161062. */
  161063. if (cinfo->comps_in_scan > 1) {
  161064. coef->MCU_rows_per_iMCU_row = 1;
  161065. } else {
  161066. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  161067. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  161068. else
  161069. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  161070. }
  161071. coef->mcu_ctr = 0;
  161072. coef->MCU_vert_offset = 0;
  161073. }
  161074. /*
  161075. * Initialize for a processing pass.
  161076. */
  161077. METHODDEF(void)
  161078. start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  161079. {
  161080. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161081. coef->iMCU_row_num = 0;
  161082. start_iMCU_row(cinfo);
  161083. switch (pass_mode) {
  161084. case JBUF_PASS_THRU:
  161085. if (coef->whole_image[0] != NULL)
  161086. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161087. coef->pub.compress_data = compress_data;
  161088. break;
  161089. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161090. case JBUF_SAVE_AND_PASS:
  161091. if (coef->whole_image[0] == NULL)
  161092. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161093. coef->pub.compress_data = compress_first_pass;
  161094. break;
  161095. case JBUF_CRANK_DEST:
  161096. if (coef->whole_image[0] == NULL)
  161097. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161098. coef->pub.compress_data = compress_output;
  161099. break;
  161100. #endif
  161101. default:
  161102. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161103. break;
  161104. }
  161105. }
  161106. /*
  161107. * Process some data in the single-pass case.
  161108. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  161109. * per call, ie, v_samp_factor block rows for each component in the image.
  161110. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  161111. *
  161112. * NB: input_buf contains a plane for each component in image,
  161113. * which we index according to the component's SOF position.
  161114. */
  161115. METHODDEF(boolean)
  161116. compress_data (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  161117. {
  161118. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161119. JDIMENSION MCU_col_num; /* index of current MCU within row */
  161120. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  161121. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  161122. int blkn, bi, ci, yindex, yoffset, blockcnt;
  161123. JDIMENSION ypos, xpos;
  161124. jpeg_component_info *compptr;
  161125. /* Loop to write as much as one whole iMCU row */
  161126. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  161127. yoffset++) {
  161128. for (MCU_col_num = coef->mcu_ctr; MCU_col_num <= last_MCU_col;
  161129. MCU_col_num++) {
  161130. /* Determine where data comes from in input_buf and do the DCT thing.
  161131. * Each call on forward_DCT processes a horizontal row of DCT blocks
  161132. * as wide as an MCU; we rely on having allocated the MCU_buffer[] blocks
  161133. * sequentially. Dummy blocks at the right or bottom edge are filled in
  161134. * specially. The data in them does not matter for image reconstruction,
  161135. * so we fill them with values that will encode to the smallest amount of
  161136. * data, viz: all zeroes in the AC entries, DC entries equal to previous
  161137. * block's DC value. (Thanks to Thomas Kinsman for this idea.)
  161138. */
  161139. blkn = 0;
  161140. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161141. compptr = cinfo->cur_comp_info[ci];
  161142. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  161143. : compptr->last_col_width;
  161144. xpos = MCU_col_num * compptr->MCU_sample_width;
  161145. ypos = yoffset * DCTSIZE; /* ypos == (yoffset+yindex) * DCTSIZE */
  161146. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  161147. if (coef->iMCU_row_num < last_iMCU_row ||
  161148. yoffset+yindex < compptr->last_row_height) {
  161149. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  161150. input_buf[compptr->component_index],
  161151. coef->MCU_buffer[blkn],
  161152. ypos, xpos, (JDIMENSION) blockcnt);
  161153. if (blockcnt < compptr->MCU_width) {
  161154. /* Create some dummy blocks at the right edge of the image. */
  161155. jzero_far((void FAR *) coef->MCU_buffer[blkn + blockcnt],
  161156. (compptr->MCU_width - blockcnt) * SIZEOF(JBLOCK));
  161157. for (bi = blockcnt; bi < compptr->MCU_width; bi++) {
  161158. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn+bi-1][0][0];
  161159. }
  161160. }
  161161. } else {
  161162. /* Create a row of dummy blocks at the bottom of the image. */
  161163. jzero_far((void FAR *) coef->MCU_buffer[blkn],
  161164. compptr->MCU_width * SIZEOF(JBLOCK));
  161165. for (bi = 0; bi < compptr->MCU_width; bi++) {
  161166. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn-1][0][0];
  161167. }
  161168. }
  161169. blkn += compptr->MCU_width;
  161170. ypos += DCTSIZE;
  161171. }
  161172. }
  161173. /* Try to write the MCU. In event of a suspension failure, we will
  161174. * re-DCT the MCU on restart (a bit inefficient, could be fixed...)
  161175. */
  161176. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  161177. /* Suspension forced; update state counters and exit */
  161178. coef->MCU_vert_offset = yoffset;
  161179. coef->mcu_ctr = MCU_col_num;
  161180. return FALSE;
  161181. }
  161182. }
  161183. /* Completed an MCU row, but perhaps not an iMCU row */
  161184. coef->mcu_ctr = 0;
  161185. }
  161186. /* Completed the iMCU row, advance counters for next one */
  161187. coef->iMCU_row_num++;
  161188. start_iMCU_row(cinfo);
  161189. return TRUE;
  161190. }
  161191. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161192. /*
  161193. * Process some data in the first pass of a multi-pass case.
  161194. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  161195. * per call, ie, v_samp_factor block rows for each component in the image.
  161196. * This amount of data is read from the source buffer, DCT'd and quantized,
  161197. * and saved into the virtual arrays. We also generate suitable dummy blocks
  161198. * as needed at the right and lower edges. (The dummy blocks are constructed
  161199. * in the virtual arrays, which have been padded appropriately.) This makes
  161200. * it possible for subsequent passes not to worry about real vs. dummy blocks.
  161201. *
  161202. * We must also emit the data to the entropy encoder. This is conveniently
  161203. * done by calling compress_output() after we've loaded the current strip
  161204. * of the virtual arrays.
  161205. *
  161206. * NB: input_buf contains a plane for each component in image. All
  161207. * components are DCT'd and loaded into the virtual arrays in this pass.
  161208. * However, it may be that only a subset of the components are emitted to
  161209. * the entropy encoder during this first pass; be careful about looking
  161210. * at the scan-dependent variables (MCU dimensions, etc).
  161211. */
  161212. METHODDEF(boolean)
  161213. compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  161214. {
  161215. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161216. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  161217. JDIMENSION blocks_across, MCUs_across, MCUindex;
  161218. int bi, ci, h_samp_factor, block_row, block_rows, ndummy;
  161219. JCOEF lastDC;
  161220. jpeg_component_info *compptr;
  161221. JBLOCKARRAY buffer;
  161222. JBLOCKROW thisblockrow, lastblockrow;
  161223. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161224. ci++, compptr++) {
  161225. /* Align the virtual buffer for this component. */
  161226. buffer = (*cinfo->mem->access_virt_barray)
  161227. ((j_common_ptr) cinfo, coef->whole_image[ci],
  161228. coef->iMCU_row_num * compptr->v_samp_factor,
  161229. (JDIMENSION) compptr->v_samp_factor, TRUE);
  161230. /* Count non-dummy DCT block rows in this iMCU row. */
  161231. if (coef->iMCU_row_num < last_iMCU_row)
  161232. block_rows = compptr->v_samp_factor;
  161233. else {
  161234. /* NB: can't use last_row_height here, since may not be set! */
  161235. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  161236. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  161237. }
  161238. blocks_across = compptr->width_in_blocks;
  161239. h_samp_factor = compptr->h_samp_factor;
  161240. /* Count number of dummy blocks to be added at the right margin. */
  161241. ndummy = (int) (blocks_across % h_samp_factor);
  161242. if (ndummy > 0)
  161243. ndummy = h_samp_factor - ndummy;
  161244. /* Perform DCT for all non-dummy blocks in this iMCU row. Each call
  161245. * on forward_DCT processes a complete horizontal row of DCT blocks.
  161246. */
  161247. for (block_row = 0; block_row < block_rows; block_row++) {
  161248. thisblockrow = buffer[block_row];
  161249. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  161250. input_buf[ci], thisblockrow,
  161251. (JDIMENSION) (block_row * DCTSIZE),
  161252. (JDIMENSION) 0, blocks_across);
  161253. if (ndummy > 0) {
  161254. /* Create dummy blocks at the right edge of the image. */
  161255. thisblockrow += blocks_across; /* => first dummy block */
  161256. jzero_far((void FAR *) thisblockrow, ndummy * SIZEOF(JBLOCK));
  161257. lastDC = thisblockrow[-1][0];
  161258. for (bi = 0; bi < ndummy; bi++) {
  161259. thisblockrow[bi][0] = lastDC;
  161260. }
  161261. }
  161262. }
  161263. /* If at end of image, create dummy block rows as needed.
  161264. * The tricky part here is that within each MCU, we want the DC values
  161265. * of the dummy blocks to match the last real block's DC value.
  161266. * This squeezes a few more bytes out of the resulting file...
  161267. */
  161268. if (coef->iMCU_row_num == last_iMCU_row) {
  161269. blocks_across += ndummy; /* include lower right corner */
  161270. MCUs_across = blocks_across / h_samp_factor;
  161271. for (block_row = block_rows; block_row < compptr->v_samp_factor;
  161272. block_row++) {
  161273. thisblockrow = buffer[block_row];
  161274. lastblockrow = buffer[block_row-1];
  161275. jzero_far((void FAR *) thisblockrow,
  161276. (size_t) (blocks_across * SIZEOF(JBLOCK)));
  161277. for (MCUindex = 0; MCUindex < MCUs_across; MCUindex++) {
  161278. lastDC = lastblockrow[h_samp_factor-1][0];
  161279. for (bi = 0; bi < h_samp_factor; bi++) {
  161280. thisblockrow[bi][0] = lastDC;
  161281. }
  161282. thisblockrow += h_samp_factor; /* advance to next MCU in row */
  161283. lastblockrow += h_samp_factor;
  161284. }
  161285. }
  161286. }
  161287. }
  161288. /* NB: compress_output will increment iMCU_row_num if successful.
  161289. * A suspension return will result in redoing all the work above next time.
  161290. */
  161291. /* Emit data to the entropy encoder, sharing code with subsequent passes */
  161292. return compress_output(cinfo, input_buf);
  161293. }
  161294. /*
  161295. * Process some data in subsequent passes of a multi-pass case.
  161296. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  161297. * per call, ie, v_samp_factor block rows for each component in the scan.
  161298. * The data is obtained from the virtual arrays and fed to the entropy coder.
  161299. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  161300. *
  161301. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  161302. */
  161303. METHODDEF(boolean)
  161304. compress_output (j_compress_ptr cinfo, JSAMPIMAGE)
  161305. {
  161306. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161307. JDIMENSION MCU_col_num; /* index of current MCU within row */
  161308. int blkn, ci, xindex, yindex, yoffset;
  161309. JDIMENSION start_col;
  161310. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  161311. JBLOCKROW buffer_ptr;
  161312. jpeg_component_info *compptr;
  161313. /* Align the virtual buffers for the components used in this scan.
  161314. * NB: during first pass, this is safe only because the buffers will
  161315. * already be aligned properly, so jmemmgr.c won't need to do any I/O.
  161316. */
  161317. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161318. compptr = cinfo->cur_comp_info[ci];
  161319. buffer[ci] = (*cinfo->mem->access_virt_barray)
  161320. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  161321. coef->iMCU_row_num * compptr->v_samp_factor,
  161322. (JDIMENSION) compptr->v_samp_factor, FALSE);
  161323. }
  161324. /* Loop to process one whole iMCU row */
  161325. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  161326. yoffset++) {
  161327. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  161328. MCU_col_num++) {
  161329. /* Construct list of pointers to DCT blocks belonging to this MCU */
  161330. blkn = 0; /* index of current DCT block within MCU */
  161331. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161332. compptr = cinfo->cur_comp_info[ci];
  161333. start_col = MCU_col_num * compptr->MCU_width;
  161334. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  161335. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  161336. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  161337. coef->MCU_buffer[blkn++] = buffer_ptr++;
  161338. }
  161339. }
  161340. }
  161341. /* Try to write the MCU. */
  161342. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  161343. /* Suspension forced; update state counters and exit */
  161344. coef->MCU_vert_offset = yoffset;
  161345. coef->mcu_ctr = MCU_col_num;
  161346. return FALSE;
  161347. }
  161348. }
  161349. /* Completed an MCU row, but perhaps not an iMCU row */
  161350. coef->mcu_ctr = 0;
  161351. }
  161352. /* Completed the iMCU row, advance counters for next one */
  161353. coef->iMCU_row_num++;
  161354. start_iMCU_row(cinfo);
  161355. return TRUE;
  161356. }
  161357. #endif /* FULL_COEF_BUFFER_SUPPORTED */
  161358. /*
  161359. * Initialize coefficient buffer controller.
  161360. */
  161361. GLOBAL(void)
  161362. jinit_c_coef_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  161363. {
  161364. my_coef_ptr coef;
  161365. coef = (my_coef_ptr)
  161366. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161367. SIZEOF(my_coef_controller));
  161368. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  161369. coef->pub.start_pass = start_pass_coef;
  161370. /* Create the coefficient buffer. */
  161371. if (need_full_buffer) {
  161372. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161373. /* Allocate a full-image virtual array for each component, */
  161374. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  161375. int ci;
  161376. jpeg_component_info *compptr;
  161377. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161378. ci++, compptr++) {
  161379. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  161380. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  161381. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  161382. (long) compptr->h_samp_factor),
  161383. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  161384. (long) compptr->v_samp_factor),
  161385. (JDIMENSION) compptr->v_samp_factor);
  161386. }
  161387. #else
  161388. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161389. #endif
  161390. } else {
  161391. /* We only need a single-MCU buffer. */
  161392. JBLOCKROW buffer;
  161393. int i;
  161394. buffer = (JBLOCKROW)
  161395. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161396. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  161397. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  161398. coef->MCU_buffer[i] = buffer + i;
  161399. }
  161400. coef->whole_image[0] = NULL; /* flag for no virtual arrays */
  161401. }
  161402. }
  161403. /*** End of inlined file: jccoefct.c ***/
  161404. /*** Start of inlined file: jccolor.c ***/
  161405. #define JPEG_INTERNALS
  161406. /* Private subobject */
  161407. typedef struct {
  161408. struct jpeg_color_converter pub; /* public fields */
  161409. /* Private state for RGB->YCC conversion */
  161410. INT32 * rgb_ycc_tab; /* => table for RGB to YCbCr conversion */
  161411. } my_color_converter;
  161412. typedef my_color_converter * my_cconvert_ptr;
  161413. /**************** RGB -> YCbCr conversion: most common case **************/
  161414. /*
  161415. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  161416. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  161417. * The conversion equations to be implemented are therefore
  161418. * Y = 0.29900 * R + 0.58700 * G + 0.11400 * B
  161419. * Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + CENTERJSAMPLE
  161420. * Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + CENTERJSAMPLE
  161421. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  161422. * Note: older versions of the IJG code used a zero offset of MAXJSAMPLE/2,
  161423. * rather than CENTERJSAMPLE, for Cb and Cr. This gave equal positive and
  161424. * negative swings for Cb/Cr, but meant that grayscale values (Cb=Cr=0)
  161425. * were not represented exactly. Now we sacrifice exact representation of
  161426. * maximum red and maximum blue in order to get exact grayscales.
  161427. *
  161428. * To avoid floating-point arithmetic, we represent the fractional constants
  161429. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  161430. * the products by 2^16, with appropriate rounding, to get the correct answer.
  161431. *
  161432. * For even more speed, we avoid doing any multiplications in the inner loop
  161433. * by precalculating the constants times R,G,B for all possible values.
  161434. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  161435. * for 12-bit samples it is still acceptable. It's not very reasonable for
  161436. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  161437. * colorspace anyway.
  161438. * The CENTERJSAMPLE offsets and the rounding fudge-factor of 0.5 are included
  161439. * in the tables to save adding them separately in the inner loop.
  161440. */
  161441. #define SCALEBITS 16 /* speediest right-shift on some machines */
  161442. #define CBCR_OFFSET ((INT32) CENTERJSAMPLE << SCALEBITS)
  161443. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  161444. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  161445. /* We allocate one big table and divide it up into eight parts, instead of
  161446. * doing eight alloc_small requests. This lets us use a single table base
  161447. * address, which can be held in a register in the inner loops on many
  161448. * machines (more than can hold all eight addresses, anyway).
  161449. */
  161450. #define R_Y_OFF 0 /* offset to R => Y section */
  161451. #define G_Y_OFF (1*(MAXJSAMPLE+1)) /* offset to G => Y section */
  161452. #define B_Y_OFF (2*(MAXJSAMPLE+1)) /* etc. */
  161453. #define R_CB_OFF (3*(MAXJSAMPLE+1))
  161454. #define G_CB_OFF (4*(MAXJSAMPLE+1))
  161455. #define B_CB_OFF (5*(MAXJSAMPLE+1))
  161456. #define R_CR_OFF B_CB_OFF /* B=>Cb, R=>Cr are the same */
  161457. #define G_CR_OFF (6*(MAXJSAMPLE+1))
  161458. #define B_CR_OFF (7*(MAXJSAMPLE+1))
  161459. #define TABLE_SIZE (8*(MAXJSAMPLE+1))
  161460. /*
  161461. * Initialize for RGB->YCC colorspace conversion.
  161462. */
  161463. METHODDEF(void)
  161464. rgb_ycc_start (j_compress_ptr cinfo)
  161465. {
  161466. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  161467. INT32 * rgb_ycc_tab;
  161468. INT32 i;
  161469. /* Allocate and fill in the conversion tables. */
  161470. cconvert->rgb_ycc_tab = rgb_ycc_tab = (INT32 *)
  161471. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161472. (TABLE_SIZE * SIZEOF(INT32)));
  161473. for (i = 0; i <= MAXJSAMPLE; i++) {
  161474. rgb_ycc_tab[i+R_Y_OFF] = FIX(0.29900) * i;
  161475. rgb_ycc_tab[i+G_Y_OFF] = FIX(0.58700) * i;
  161476. rgb_ycc_tab[i+B_Y_OFF] = FIX(0.11400) * i + ONE_HALF;
  161477. rgb_ycc_tab[i+R_CB_OFF] = (-FIX(0.16874)) * i;
  161478. rgb_ycc_tab[i+G_CB_OFF] = (-FIX(0.33126)) * i;
  161479. /* We use a rounding fudge-factor of 0.5-epsilon for Cb and Cr.
  161480. * This ensures that the maximum output will round to MAXJSAMPLE
  161481. * not MAXJSAMPLE+1, and thus that we don't have to range-limit.
  161482. */
  161483. rgb_ycc_tab[i+B_CB_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  161484. /* B=>Cb and R=>Cr tables are the same
  161485. rgb_ycc_tab[i+R_CR_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  161486. */
  161487. rgb_ycc_tab[i+G_CR_OFF] = (-FIX(0.41869)) * i;
  161488. rgb_ycc_tab[i+B_CR_OFF] = (-FIX(0.08131)) * i;
  161489. }
  161490. }
  161491. /*
  161492. * Convert some rows of samples to the JPEG colorspace.
  161493. *
  161494. * Note that we change from the application's interleaved-pixel format
  161495. * to our internal noninterleaved, one-plane-per-component format.
  161496. * The input buffer is therefore three times as wide as the output buffer.
  161497. *
  161498. * A starting row offset is provided only for the output buffer. The caller
  161499. * can easily adjust the passed input_buf value to accommodate any row
  161500. * offset required on that side.
  161501. */
  161502. METHODDEF(void)
  161503. rgb_ycc_convert (j_compress_ptr cinfo,
  161504. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  161505. JDIMENSION output_row, int num_rows)
  161506. {
  161507. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  161508. register int r, g, b;
  161509. register INT32 * ctab = cconvert->rgb_ycc_tab;
  161510. register JSAMPROW inptr;
  161511. register JSAMPROW outptr0, outptr1, outptr2;
  161512. register JDIMENSION col;
  161513. JDIMENSION num_cols = cinfo->image_width;
  161514. while (--num_rows >= 0) {
  161515. inptr = *input_buf++;
  161516. outptr0 = output_buf[0][output_row];
  161517. outptr1 = output_buf[1][output_row];
  161518. outptr2 = output_buf[2][output_row];
  161519. output_row++;
  161520. for (col = 0; col < num_cols; col++) {
  161521. r = GETJSAMPLE(inptr[RGB_RED]);
  161522. g = GETJSAMPLE(inptr[RGB_GREEN]);
  161523. b = GETJSAMPLE(inptr[RGB_BLUE]);
  161524. inptr += RGB_PIXELSIZE;
  161525. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  161526. * must be too; we do not need an explicit range-limiting operation.
  161527. * Hence the value being shifted is never negative, and we don't
  161528. * need the general RIGHT_SHIFT macro.
  161529. */
  161530. /* Y */
  161531. outptr0[col] = (JSAMPLE)
  161532. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  161533. >> SCALEBITS);
  161534. /* Cb */
  161535. outptr1[col] = (JSAMPLE)
  161536. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  161537. >> SCALEBITS);
  161538. /* Cr */
  161539. outptr2[col] = (JSAMPLE)
  161540. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  161541. >> SCALEBITS);
  161542. }
  161543. }
  161544. }
  161545. /**************** Cases other than RGB -> YCbCr **************/
  161546. /*
  161547. * Convert some rows of samples to the JPEG colorspace.
  161548. * This version handles RGB->grayscale conversion, which is the same
  161549. * as the RGB->Y portion of RGB->YCbCr.
  161550. * We assume rgb_ycc_start has been called (we only use the Y tables).
  161551. */
  161552. METHODDEF(void)
  161553. rgb_gray_convert (j_compress_ptr cinfo,
  161554. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  161555. JDIMENSION output_row, int num_rows)
  161556. {
  161557. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  161558. register int r, g, b;
  161559. register INT32 * ctab = cconvert->rgb_ycc_tab;
  161560. register JSAMPROW inptr;
  161561. register JSAMPROW outptr;
  161562. register JDIMENSION col;
  161563. JDIMENSION num_cols = cinfo->image_width;
  161564. while (--num_rows >= 0) {
  161565. inptr = *input_buf++;
  161566. outptr = output_buf[0][output_row];
  161567. output_row++;
  161568. for (col = 0; col < num_cols; col++) {
  161569. r = GETJSAMPLE(inptr[RGB_RED]);
  161570. g = GETJSAMPLE(inptr[RGB_GREEN]);
  161571. b = GETJSAMPLE(inptr[RGB_BLUE]);
  161572. inptr += RGB_PIXELSIZE;
  161573. /* Y */
  161574. outptr[col] = (JSAMPLE)
  161575. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  161576. >> SCALEBITS);
  161577. }
  161578. }
  161579. }
  161580. /*
  161581. * Convert some rows of samples to the JPEG colorspace.
  161582. * This version handles Adobe-style CMYK->YCCK conversion,
  161583. * where we convert R=1-C, G=1-M, and B=1-Y to YCbCr using the same
  161584. * conversion as above, while passing K (black) unchanged.
  161585. * We assume rgb_ycc_start has been called.
  161586. */
  161587. METHODDEF(void)
  161588. cmyk_ycck_convert (j_compress_ptr cinfo,
  161589. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  161590. JDIMENSION output_row, int num_rows)
  161591. {
  161592. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  161593. register int r, g, b;
  161594. register INT32 * ctab = cconvert->rgb_ycc_tab;
  161595. register JSAMPROW inptr;
  161596. register JSAMPROW outptr0, outptr1, outptr2, outptr3;
  161597. register JDIMENSION col;
  161598. JDIMENSION num_cols = cinfo->image_width;
  161599. while (--num_rows >= 0) {
  161600. inptr = *input_buf++;
  161601. outptr0 = output_buf[0][output_row];
  161602. outptr1 = output_buf[1][output_row];
  161603. outptr2 = output_buf[2][output_row];
  161604. outptr3 = output_buf[3][output_row];
  161605. output_row++;
  161606. for (col = 0; col < num_cols; col++) {
  161607. r = MAXJSAMPLE - GETJSAMPLE(inptr[0]);
  161608. g = MAXJSAMPLE - GETJSAMPLE(inptr[1]);
  161609. b = MAXJSAMPLE - GETJSAMPLE(inptr[2]);
  161610. /* K passes through as-is */
  161611. outptr3[col] = inptr[3]; /* don't need GETJSAMPLE here */
  161612. inptr += 4;
  161613. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  161614. * must be too; we do not need an explicit range-limiting operation.
  161615. * Hence the value being shifted is never negative, and we don't
  161616. * need the general RIGHT_SHIFT macro.
  161617. */
  161618. /* Y */
  161619. outptr0[col] = (JSAMPLE)
  161620. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  161621. >> SCALEBITS);
  161622. /* Cb */
  161623. outptr1[col] = (JSAMPLE)
  161624. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  161625. >> SCALEBITS);
  161626. /* Cr */
  161627. outptr2[col] = (JSAMPLE)
  161628. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  161629. >> SCALEBITS);
  161630. }
  161631. }
  161632. }
  161633. /*
  161634. * Convert some rows of samples to the JPEG colorspace.
  161635. * This version handles grayscale output with no conversion.
  161636. * The source can be either plain grayscale or YCbCr (since Y == gray).
  161637. */
  161638. METHODDEF(void)
  161639. grayscale_convert (j_compress_ptr cinfo,
  161640. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  161641. JDIMENSION output_row, int num_rows)
  161642. {
  161643. register JSAMPROW inptr;
  161644. register JSAMPROW outptr;
  161645. register JDIMENSION col;
  161646. JDIMENSION num_cols = cinfo->image_width;
  161647. int instride = cinfo->input_components;
  161648. while (--num_rows >= 0) {
  161649. inptr = *input_buf++;
  161650. outptr = output_buf[0][output_row];
  161651. output_row++;
  161652. for (col = 0; col < num_cols; col++) {
  161653. outptr[col] = inptr[0]; /* don't need GETJSAMPLE() here */
  161654. inptr += instride;
  161655. }
  161656. }
  161657. }
  161658. /*
  161659. * Convert some rows of samples to the JPEG colorspace.
  161660. * This version handles multi-component colorspaces without conversion.
  161661. * We assume input_components == num_components.
  161662. */
  161663. METHODDEF(void)
  161664. null_convert (j_compress_ptr cinfo,
  161665. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  161666. JDIMENSION output_row, int num_rows)
  161667. {
  161668. register JSAMPROW inptr;
  161669. register JSAMPROW outptr;
  161670. register JDIMENSION col;
  161671. register int ci;
  161672. int nc = cinfo->num_components;
  161673. JDIMENSION num_cols = cinfo->image_width;
  161674. while (--num_rows >= 0) {
  161675. /* It seems fastest to make a separate pass for each component. */
  161676. for (ci = 0; ci < nc; ci++) {
  161677. inptr = *input_buf;
  161678. outptr = output_buf[ci][output_row];
  161679. for (col = 0; col < num_cols; col++) {
  161680. outptr[col] = inptr[ci]; /* don't need GETJSAMPLE() here */
  161681. inptr += nc;
  161682. }
  161683. }
  161684. input_buf++;
  161685. output_row++;
  161686. }
  161687. }
  161688. /*
  161689. * Empty method for start_pass.
  161690. */
  161691. METHODDEF(void)
  161692. null_method (j_compress_ptr)
  161693. {
  161694. /* no work needed */
  161695. }
  161696. /*
  161697. * Module initialization routine for input colorspace conversion.
  161698. */
  161699. GLOBAL(void)
  161700. jinit_color_converter (j_compress_ptr cinfo)
  161701. {
  161702. my_cconvert_ptr cconvert;
  161703. cconvert = (my_cconvert_ptr)
  161704. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161705. SIZEOF(my_color_converter));
  161706. cinfo->cconvert = (struct jpeg_color_converter *) cconvert;
  161707. /* set start_pass to null method until we find out differently */
  161708. cconvert->pub.start_pass = null_method;
  161709. /* Make sure input_components agrees with in_color_space */
  161710. switch (cinfo->in_color_space) {
  161711. case JCS_GRAYSCALE:
  161712. if (cinfo->input_components != 1)
  161713. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  161714. break;
  161715. case JCS_RGB:
  161716. #if RGB_PIXELSIZE != 3
  161717. if (cinfo->input_components != RGB_PIXELSIZE)
  161718. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  161719. break;
  161720. #endif /* else share code with YCbCr */
  161721. case JCS_YCbCr:
  161722. if (cinfo->input_components != 3)
  161723. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  161724. break;
  161725. case JCS_CMYK:
  161726. case JCS_YCCK:
  161727. if (cinfo->input_components != 4)
  161728. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  161729. break;
  161730. default: /* JCS_UNKNOWN can be anything */
  161731. if (cinfo->input_components < 1)
  161732. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  161733. break;
  161734. }
  161735. /* Check num_components, set conversion method based on requested space */
  161736. switch (cinfo->jpeg_color_space) {
  161737. case JCS_GRAYSCALE:
  161738. if (cinfo->num_components != 1)
  161739. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  161740. if (cinfo->in_color_space == JCS_GRAYSCALE)
  161741. cconvert->pub.color_convert = grayscale_convert;
  161742. else if (cinfo->in_color_space == JCS_RGB) {
  161743. cconvert->pub.start_pass = rgb_ycc_start;
  161744. cconvert->pub.color_convert = rgb_gray_convert;
  161745. } else if (cinfo->in_color_space == JCS_YCbCr)
  161746. cconvert->pub.color_convert = grayscale_convert;
  161747. else
  161748. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  161749. break;
  161750. case JCS_RGB:
  161751. if (cinfo->num_components != 3)
  161752. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  161753. if (cinfo->in_color_space == JCS_RGB && RGB_PIXELSIZE == 3)
  161754. cconvert->pub.color_convert = null_convert;
  161755. else
  161756. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  161757. break;
  161758. case JCS_YCbCr:
  161759. if (cinfo->num_components != 3)
  161760. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  161761. if (cinfo->in_color_space == JCS_RGB) {
  161762. cconvert->pub.start_pass = rgb_ycc_start;
  161763. cconvert->pub.color_convert = rgb_ycc_convert;
  161764. } else if (cinfo->in_color_space == JCS_YCbCr)
  161765. cconvert->pub.color_convert = null_convert;
  161766. else
  161767. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  161768. break;
  161769. case JCS_CMYK:
  161770. if (cinfo->num_components != 4)
  161771. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  161772. if (cinfo->in_color_space == JCS_CMYK)
  161773. cconvert->pub.color_convert = null_convert;
  161774. else
  161775. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  161776. break;
  161777. case JCS_YCCK:
  161778. if (cinfo->num_components != 4)
  161779. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  161780. if (cinfo->in_color_space == JCS_CMYK) {
  161781. cconvert->pub.start_pass = rgb_ycc_start;
  161782. cconvert->pub.color_convert = cmyk_ycck_convert;
  161783. } else if (cinfo->in_color_space == JCS_YCCK)
  161784. cconvert->pub.color_convert = null_convert;
  161785. else
  161786. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  161787. break;
  161788. default: /* allow null conversion of JCS_UNKNOWN */
  161789. if (cinfo->jpeg_color_space != cinfo->in_color_space ||
  161790. cinfo->num_components != cinfo->input_components)
  161791. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  161792. cconvert->pub.color_convert = null_convert;
  161793. break;
  161794. }
  161795. }
  161796. /*** End of inlined file: jccolor.c ***/
  161797. #undef FIX
  161798. /*** Start of inlined file: jcdctmgr.c ***/
  161799. #define JPEG_INTERNALS
  161800. /*** Start of inlined file: jdct.h ***/
  161801. /*
  161802. * A forward DCT routine is given a pointer to a work area of type DCTELEM[];
  161803. * the DCT is to be performed in-place in that buffer. Type DCTELEM is int
  161804. * for 8-bit samples, INT32 for 12-bit samples. (NOTE: Floating-point DCT
  161805. * implementations use an array of type FAST_FLOAT, instead.)
  161806. * The DCT inputs are expected to be signed (range +-CENTERJSAMPLE).
  161807. * The DCT outputs are returned scaled up by a factor of 8; they therefore
  161808. * have a range of +-8K for 8-bit data, +-128K for 12-bit data. This
  161809. * convention improves accuracy in integer implementations and saves some
  161810. * work in floating-point ones.
  161811. * Quantization of the output coefficients is done by jcdctmgr.c.
  161812. */
  161813. #ifndef __jdct_h__
  161814. #define __jdct_h__
  161815. #if BITS_IN_JSAMPLE == 8
  161816. typedef int DCTELEM; /* 16 or 32 bits is fine */
  161817. #else
  161818. typedef INT32 DCTELEM; /* must have 32 bits */
  161819. #endif
  161820. typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data));
  161821. typedef JMETHOD(void, float_DCT_method_ptr, (FAST_FLOAT * data));
  161822. /*
  161823. * An inverse DCT routine is given a pointer to the input JBLOCK and a pointer
  161824. * to an output sample array. The routine must dequantize the input data as
  161825. * well as perform the IDCT; for dequantization, it uses the multiplier table
  161826. * pointed to by compptr->dct_table. The output data is to be placed into the
  161827. * sample array starting at a specified column. (Any row offset needed will
  161828. * be applied to the array pointer before it is passed to the IDCT code.)
  161829. * Note that the number of samples emitted by the IDCT routine is
  161830. * DCT_scaled_size * DCT_scaled_size.
  161831. */
  161832. /* typedef inverse_DCT_method_ptr is declared in jpegint.h */
  161833. /*
  161834. * Each IDCT routine has its own ideas about the best dct_table element type.
  161835. */
  161836. typedef MULTIPLIER ISLOW_MULT_TYPE; /* short or int, whichever is faster */
  161837. #if BITS_IN_JSAMPLE == 8
  161838. typedef MULTIPLIER IFAST_MULT_TYPE; /* 16 bits is OK, use short if faster */
  161839. #define IFAST_SCALE_BITS 2 /* fractional bits in scale factors */
  161840. #else
  161841. typedef INT32 IFAST_MULT_TYPE; /* need 32 bits for scaled quantizers */
  161842. #define IFAST_SCALE_BITS 13 /* fractional bits in scale factors */
  161843. #endif
  161844. typedef FAST_FLOAT FLOAT_MULT_TYPE; /* preferred floating type */
  161845. /*
  161846. * Each IDCT routine is responsible for range-limiting its results and
  161847. * converting them to unsigned form (0..MAXJSAMPLE). The raw outputs could
  161848. * be quite far out of range if the input data is corrupt, so a bulletproof
  161849. * range-limiting step is required. We use a mask-and-table-lookup method
  161850. * to do the combined operations quickly. See the comments with
  161851. * prepare_range_limit_table (in jdmaster.c) for more info.
  161852. */
  161853. #define IDCT_range_limit(cinfo) ((cinfo)->sample_range_limit + CENTERJSAMPLE)
  161854. #define RANGE_MASK (MAXJSAMPLE * 4 + 3) /* 2 bits wider than legal samples */
  161855. /* Short forms of external names for systems with brain-damaged linkers. */
  161856. #ifdef NEED_SHORT_EXTERNAL_NAMES
  161857. #define jpeg_fdct_islow jFDislow
  161858. #define jpeg_fdct_ifast jFDifast
  161859. #define jpeg_fdct_float jFDfloat
  161860. #define jpeg_idct_islow jRDislow
  161861. #define jpeg_idct_ifast jRDifast
  161862. #define jpeg_idct_float jRDfloat
  161863. #define jpeg_idct_4x4 jRD4x4
  161864. #define jpeg_idct_2x2 jRD2x2
  161865. #define jpeg_idct_1x1 jRD1x1
  161866. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  161867. /* Extern declarations for the forward and inverse DCT routines. */
  161868. EXTERN(void) jpeg_fdct_islow JPP((DCTELEM * data));
  161869. EXTERN(void) jpeg_fdct_ifast JPP((DCTELEM * data));
  161870. EXTERN(void) jpeg_fdct_float JPP((FAST_FLOAT * data));
  161871. EXTERN(void) jpeg_idct_islow
  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_ifast
  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_float
  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_4x4
  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_2x2
  161884. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  161885. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  161886. EXTERN(void) jpeg_idct_1x1
  161887. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  161888. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  161889. /*
  161890. * Macros for handling fixed-point arithmetic; these are used by many
  161891. * but not all of the DCT/IDCT modules.
  161892. *
  161893. * All values are expected to be of type INT32.
  161894. * Fractional constants are scaled left by CONST_BITS bits.
  161895. * CONST_BITS is defined within each module using these macros,
  161896. * and may differ from one module to the next.
  161897. */
  161898. #define ONE ((INT32) 1)
  161899. #define CONST_SCALE (ONE << CONST_BITS)
  161900. /* Convert a positive real constant to an integer scaled by CONST_SCALE.
  161901. * Caution: some C compilers fail to reduce "FIX(constant)" at compile time,
  161902. * thus causing a lot of useless floating-point operations at run time.
  161903. */
  161904. #define FIX(x) ((INT32) ((x) * CONST_SCALE + 0.5))
  161905. /* Descale and correctly round an INT32 value that's scaled by N bits.
  161906. * We assume RIGHT_SHIFT rounds towards minus infinity, so adding
  161907. * the fudge factor is correct for either sign of X.
  161908. */
  161909. #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
  161910. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  161911. * This macro is used only when the two inputs will actually be no more than
  161912. * 16 bits wide, so that a 16x16->32 bit multiply can be used instead of a
  161913. * full 32x32 multiply. This provides a useful speedup on many machines.
  161914. * Unfortunately there is no way to specify a 16x16->32 multiply portably
  161915. * in C, but some C compilers will do the right thing if you provide the
  161916. * correct combination of casts.
  161917. */
  161918. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  161919. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT16) (const)))
  161920. #endif
  161921. #ifdef SHORTxLCONST_32 /* known to work with Microsoft C 6.0 */
  161922. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT32) (const)))
  161923. #endif
  161924. #ifndef MULTIPLY16C16 /* default definition */
  161925. #define MULTIPLY16C16(var,const) ((var) * (const))
  161926. #endif
  161927. /* Same except both inputs are variables. */
  161928. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  161929. #define MULTIPLY16V16(var1,var2) (((INT16) (var1)) * ((INT16) (var2)))
  161930. #endif
  161931. #ifndef MULTIPLY16V16 /* default definition */
  161932. #define MULTIPLY16V16(var1,var2) ((var1) * (var2))
  161933. #endif
  161934. #endif
  161935. /*** End of inlined file: jdct.h ***/
  161936. /* Private declarations for DCT subsystem */
  161937. /* Private subobject for this module */
  161938. typedef struct {
  161939. struct jpeg_forward_dct pub; /* public fields */
  161940. /* Pointer to the DCT routine actually in use */
  161941. forward_DCT_method_ptr do_dct;
  161942. /* The actual post-DCT divisors --- not identical to the quant table
  161943. * entries, because of scaling (especially for an unnormalized DCT).
  161944. * Each table is given in normal array order.
  161945. */
  161946. DCTELEM * divisors[NUM_QUANT_TBLS];
  161947. #ifdef DCT_FLOAT_SUPPORTED
  161948. /* Same as above for the floating-point case. */
  161949. float_DCT_method_ptr do_float_dct;
  161950. FAST_FLOAT * float_divisors[NUM_QUANT_TBLS];
  161951. #endif
  161952. } my_fdct_controller;
  161953. typedef my_fdct_controller * my_fdct_ptr;
  161954. /*
  161955. * Initialize for a processing pass.
  161956. * Verify that all referenced Q-tables are present, and set up
  161957. * the divisor table for each one.
  161958. * In the current implementation, DCT of all components is done during
  161959. * the first pass, even if only some components will be output in the
  161960. * first scan. Hence all components should be examined here.
  161961. */
  161962. METHODDEF(void)
  161963. start_pass_fdctmgr (j_compress_ptr cinfo)
  161964. {
  161965. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  161966. int ci, qtblno, i;
  161967. jpeg_component_info *compptr;
  161968. JQUANT_TBL * qtbl;
  161969. DCTELEM * dtbl;
  161970. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161971. ci++, compptr++) {
  161972. qtblno = compptr->quant_tbl_no;
  161973. /* Make sure specified quantization table is present */
  161974. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  161975. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  161976. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  161977. qtbl = cinfo->quant_tbl_ptrs[qtblno];
  161978. /* Compute divisors for this quant table */
  161979. /* We may do this more than once for same table, but it's not a big deal */
  161980. switch (cinfo->dct_method) {
  161981. #ifdef DCT_ISLOW_SUPPORTED
  161982. case JDCT_ISLOW:
  161983. /* For LL&M IDCT method, divisors are equal to raw quantization
  161984. * coefficients multiplied by 8 (to counteract scaling).
  161985. */
  161986. if (fdct->divisors[qtblno] == NULL) {
  161987. fdct->divisors[qtblno] = (DCTELEM *)
  161988. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161989. DCTSIZE2 * SIZEOF(DCTELEM));
  161990. }
  161991. dtbl = fdct->divisors[qtblno];
  161992. for (i = 0; i < DCTSIZE2; i++) {
  161993. dtbl[i] = ((DCTELEM) qtbl->quantval[i]) << 3;
  161994. }
  161995. break;
  161996. #endif
  161997. #ifdef DCT_IFAST_SUPPORTED
  161998. case JDCT_IFAST:
  161999. {
  162000. /* For AA&N IDCT method, divisors are equal to quantization
  162001. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  162002. * scalefactor[0] = 1
  162003. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  162004. * We apply a further scale factor of 8.
  162005. */
  162006. #define CONST_BITS 14
  162007. static const INT16 aanscales[DCTSIZE2] = {
  162008. /* precomputed values scaled up by 14 bits */
  162009. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  162010. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  162011. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  162012. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  162013. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  162014. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  162015. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  162016. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  162017. };
  162018. SHIFT_TEMPS
  162019. if (fdct->divisors[qtblno] == NULL) {
  162020. fdct->divisors[qtblno] = (DCTELEM *)
  162021. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162022. DCTSIZE2 * SIZEOF(DCTELEM));
  162023. }
  162024. dtbl = fdct->divisors[qtblno];
  162025. for (i = 0; i < DCTSIZE2; i++) {
  162026. dtbl[i] = (DCTELEM)
  162027. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  162028. (INT32) aanscales[i]),
  162029. CONST_BITS-3);
  162030. }
  162031. }
  162032. break;
  162033. #endif
  162034. #ifdef DCT_FLOAT_SUPPORTED
  162035. case JDCT_FLOAT:
  162036. {
  162037. /* For float AA&N IDCT method, divisors are equal to quantization
  162038. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  162039. * scalefactor[0] = 1
  162040. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  162041. * We apply a further scale factor of 8.
  162042. * What's actually stored is 1/divisor so that the inner loop can
  162043. * use a multiplication rather than a division.
  162044. */
  162045. FAST_FLOAT * fdtbl;
  162046. int row, col;
  162047. static const double aanscalefactor[DCTSIZE] = {
  162048. 1.0, 1.387039845, 1.306562965, 1.175875602,
  162049. 1.0, 0.785694958, 0.541196100, 0.275899379
  162050. };
  162051. if (fdct->float_divisors[qtblno] == NULL) {
  162052. fdct->float_divisors[qtblno] = (FAST_FLOAT *)
  162053. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162054. DCTSIZE2 * SIZEOF(FAST_FLOAT));
  162055. }
  162056. fdtbl = fdct->float_divisors[qtblno];
  162057. i = 0;
  162058. for (row = 0; row < DCTSIZE; row++) {
  162059. for (col = 0; col < DCTSIZE; col++) {
  162060. fdtbl[i] = (FAST_FLOAT)
  162061. (1.0 / (((double) qtbl->quantval[i] *
  162062. aanscalefactor[row] * aanscalefactor[col] * 8.0)));
  162063. i++;
  162064. }
  162065. }
  162066. }
  162067. break;
  162068. #endif
  162069. default:
  162070. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162071. break;
  162072. }
  162073. }
  162074. }
  162075. /*
  162076. * Perform forward DCT on one or more blocks of a component.
  162077. *
  162078. * The input samples are taken from the sample_data[] array starting at
  162079. * position start_row/start_col, and moving to the right for any additional
  162080. * blocks. The quantized coefficients are returned in coef_blocks[].
  162081. */
  162082. METHODDEF(void)
  162083. forward_DCT (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162084. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  162085. JDIMENSION start_row, JDIMENSION start_col,
  162086. JDIMENSION num_blocks)
  162087. /* This version is used for integer DCT implementations. */
  162088. {
  162089. /* This routine is heavily used, so it's worth coding it tightly. */
  162090. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  162091. forward_DCT_method_ptr do_dct = fdct->do_dct;
  162092. DCTELEM * divisors = fdct->divisors[compptr->quant_tbl_no];
  162093. DCTELEM workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  162094. JDIMENSION bi;
  162095. sample_data += start_row; /* fold in the vertical offset once */
  162096. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  162097. /* Load data into workspace, applying unsigned->signed conversion */
  162098. { register DCTELEM *workspaceptr;
  162099. register JSAMPROW elemptr;
  162100. register int elemr;
  162101. workspaceptr = workspace;
  162102. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  162103. elemptr = sample_data[elemr] + start_col;
  162104. #if DCTSIZE == 8 /* unroll the inner loop */
  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. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162111. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162112. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162113. #else
  162114. { register int elemc;
  162115. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  162116. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162117. }
  162118. }
  162119. #endif
  162120. }
  162121. }
  162122. /* Perform the DCT */
  162123. (*do_dct) (workspace);
  162124. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  162125. { register DCTELEM temp, qval;
  162126. register int i;
  162127. register JCOEFPTR output_ptr = coef_blocks[bi];
  162128. for (i = 0; i < DCTSIZE2; i++) {
  162129. qval = divisors[i];
  162130. temp = workspace[i];
  162131. /* Divide the coefficient value by qval, ensuring proper rounding.
  162132. * Since C does not specify the direction of rounding for negative
  162133. * quotients, we have to force the dividend positive for portability.
  162134. *
  162135. * In most files, at least half of the output values will be zero
  162136. * (at default quantization settings, more like three-quarters...)
  162137. * so we should ensure that this case is fast. On many machines,
  162138. * a comparison is enough cheaper than a divide to make a special test
  162139. * a win. Since both inputs will be nonnegative, we need only test
  162140. * for a < b to discover whether a/b is 0.
  162141. * If your machine's division is fast enough, define FAST_DIVIDE.
  162142. */
  162143. #ifdef FAST_DIVIDE
  162144. #define DIVIDE_BY(a,b) a /= b
  162145. #else
  162146. #define DIVIDE_BY(a,b) if (a >= b) a /= b; else a = 0
  162147. #endif
  162148. if (temp < 0) {
  162149. temp = -temp;
  162150. temp += qval>>1; /* for rounding */
  162151. DIVIDE_BY(temp, qval);
  162152. temp = -temp;
  162153. } else {
  162154. temp += qval>>1; /* for rounding */
  162155. DIVIDE_BY(temp, qval);
  162156. }
  162157. output_ptr[i] = (JCOEF) temp;
  162158. }
  162159. }
  162160. }
  162161. }
  162162. #ifdef DCT_FLOAT_SUPPORTED
  162163. METHODDEF(void)
  162164. forward_DCT_float (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162165. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  162166. JDIMENSION start_row, JDIMENSION start_col,
  162167. JDIMENSION num_blocks)
  162168. /* This version is used for floating-point DCT implementations. */
  162169. {
  162170. /* This routine is heavily used, so it's worth coding it tightly. */
  162171. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  162172. float_DCT_method_ptr do_dct = fdct->do_float_dct;
  162173. FAST_FLOAT * divisors = fdct->float_divisors[compptr->quant_tbl_no];
  162174. FAST_FLOAT workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  162175. JDIMENSION bi;
  162176. sample_data += start_row; /* fold in the vertical offset once */
  162177. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  162178. /* Load data into workspace, applying unsigned->signed conversion */
  162179. { register FAST_FLOAT *workspaceptr;
  162180. register JSAMPROW elemptr;
  162181. register int elemr;
  162182. workspaceptr = workspace;
  162183. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  162184. elemptr = sample_data[elemr] + start_col;
  162185. #if DCTSIZE == 8 /* unroll the inner loop */
  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. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162192. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162193. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162194. #else
  162195. { register int elemc;
  162196. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  162197. *workspaceptr++ = (FAST_FLOAT)
  162198. (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162199. }
  162200. }
  162201. #endif
  162202. }
  162203. }
  162204. /* Perform the DCT */
  162205. (*do_dct) (workspace);
  162206. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  162207. { register FAST_FLOAT temp;
  162208. register int i;
  162209. register JCOEFPTR output_ptr = coef_blocks[bi];
  162210. for (i = 0; i < DCTSIZE2; i++) {
  162211. /* Apply the quantization and scaling factor */
  162212. temp = workspace[i] * divisors[i];
  162213. /* Round to nearest integer.
  162214. * Since C does not specify the direction of rounding for negative
  162215. * quotients, we have to force the dividend positive for portability.
  162216. * The maximum coefficient size is +-16K (for 12-bit data), so this
  162217. * code should work for either 16-bit or 32-bit ints.
  162218. */
  162219. output_ptr[i] = (JCOEF) ((int) (temp + (FAST_FLOAT) 16384.5) - 16384);
  162220. }
  162221. }
  162222. }
  162223. }
  162224. #endif /* DCT_FLOAT_SUPPORTED */
  162225. /*
  162226. * Initialize FDCT manager.
  162227. */
  162228. GLOBAL(void)
  162229. jinit_forward_dct (j_compress_ptr cinfo)
  162230. {
  162231. my_fdct_ptr fdct;
  162232. int i;
  162233. fdct = (my_fdct_ptr)
  162234. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162235. SIZEOF(my_fdct_controller));
  162236. cinfo->fdct = (struct jpeg_forward_dct *) fdct;
  162237. fdct->pub.start_pass = start_pass_fdctmgr;
  162238. switch (cinfo->dct_method) {
  162239. #ifdef DCT_ISLOW_SUPPORTED
  162240. case JDCT_ISLOW:
  162241. fdct->pub.forward_DCT = forward_DCT;
  162242. fdct->do_dct = jpeg_fdct_islow;
  162243. break;
  162244. #endif
  162245. #ifdef DCT_IFAST_SUPPORTED
  162246. case JDCT_IFAST:
  162247. fdct->pub.forward_DCT = forward_DCT;
  162248. fdct->do_dct = jpeg_fdct_ifast;
  162249. break;
  162250. #endif
  162251. #ifdef DCT_FLOAT_SUPPORTED
  162252. case JDCT_FLOAT:
  162253. fdct->pub.forward_DCT = forward_DCT_float;
  162254. fdct->do_float_dct = jpeg_fdct_float;
  162255. break;
  162256. #endif
  162257. default:
  162258. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162259. break;
  162260. }
  162261. /* Mark divisor tables unallocated */
  162262. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  162263. fdct->divisors[i] = NULL;
  162264. #ifdef DCT_FLOAT_SUPPORTED
  162265. fdct->float_divisors[i] = NULL;
  162266. #endif
  162267. }
  162268. }
  162269. /*** End of inlined file: jcdctmgr.c ***/
  162270. #undef CONST_BITS
  162271. /*** Start of inlined file: jchuff.c ***/
  162272. #define JPEG_INTERNALS
  162273. /*** Start of inlined file: jchuff.h ***/
  162274. /* The legal range of a DCT coefficient is
  162275. * -1024 .. +1023 for 8-bit data;
  162276. * -16384 .. +16383 for 12-bit data.
  162277. * Hence the magnitude should always fit in 10 or 14 bits respectively.
  162278. */
  162279. #ifndef _jchuff_h_
  162280. #define _jchuff_h_
  162281. #if BITS_IN_JSAMPLE == 8
  162282. #define MAX_COEF_BITS 10
  162283. #else
  162284. #define MAX_COEF_BITS 14
  162285. #endif
  162286. /* Derived data constructed for each Huffman table */
  162287. typedef struct {
  162288. unsigned int ehufco[256]; /* code for each symbol */
  162289. char ehufsi[256]; /* length of code for each symbol */
  162290. /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */
  162291. } c_derived_tbl;
  162292. /* Short forms of external names for systems with brain-damaged linkers. */
  162293. #ifdef NEED_SHORT_EXTERNAL_NAMES
  162294. #define jpeg_make_c_derived_tbl jMkCDerived
  162295. #define jpeg_gen_optimal_table jGenOptTbl
  162296. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  162297. /* Expand a Huffman table definition into the derived format */
  162298. EXTERN(void) jpeg_make_c_derived_tbl
  162299. JPP((j_compress_ptr cinfo, boolean isDC, int tblno,
  162300. c_derived_tbl ** pdtbl));
  162301. /* Generate an optimal table definition given the specified counts */
  162302. EXTERN(void) jpeg_gen_optimal_table
  162303. JPP((j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[]));
  162304. #endif
  162305. /*** End of inlined file: jchuff.h ***/
  162306. /* Declarations shared with jcphuff.c */
  162307. /* Expanded entropy encoder object for Huffman encoding.
  162308. *
  162309. * The savable_state subrecord contains fields that change within an MCU,
  162310. * but must not be updated permanently until we complete the MCU.
  162311. */
  162312. typedef struct {
  162313. INT32 put_buffer; /* current bit-accumulation buffer */
  162314. int put_bits; /* # of bits now in it */
  162315. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  162316. } savable_state;
  162317. /* This macro is to work around compilers with missing or broken
  162318. * structure assignment. You'll need to fix this code if you have
  162319. * such a compiler and you change MAX_COMPS_IN_SCAN.
  162320. */
  162321. #ifndef NO_STRUCT_ASSIGN
  162322. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  162323. #else
  162324. #if MAX_COMPS_IN_SCAN == 4
  162325. #define ASSIGN_STATE(dest,src) \
  162326. ((dest).put_buffer = (src).put_buffer, \
  162327. (dest).put_bits = (src).put_bits, \
  162328. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  162329. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  162330. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  162331. (dest).last_dc_val[3] = (src).last_dc_val[3])
  162332. #endif
  162333. #endif
  162334. typedef struct {
  162335. struct jpeg_entropy_encoder pub; /* public fields */
  162336. savable_state saved; /* Bit buffer & DC state at start of MCU */
  162337. /* These fields are NOT loaded into local working state. */
  162338. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  162339. int next_restart_num; /* next restart number to write (0-7) */
  162340. /* Pointers to derived tables (these workspaces have image lifespan) */
  162341. c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  162342. c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  162343. #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
  162344. long * dc_count_ptrs[NUM_HUFF_TBLS];
  162345. long * ac_count_ptrs[NUM_HUFF_TBLS];
  162346. #endif
  162347. } huff_entropy_encoder;
  162348. typedef huff_entropy_encoder * huff_entropy_ptr;
  162349. /* Working state while writing an MCU.
  162350. * This struct contains all the fields that are needed by subroutines.
  162351. */
  162352. typedef struct {
  162353. JOCTET * next_output_byte; /* => next byte to write in buffer */
  162354. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  162355. savable_state cur; /* Current bit buffer & DC state */
  162356. j_compress_ptr cinfo; /* dump_buffer needs access to this */
  162357. } working_state;
  162358. /* Forward declarations */
  162359. METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
  162360. JBLOCKROW *MCU_data));
  162361. METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
  162362. #ifdef ENTROPY_OPT_SUPPORTED
  162363. METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
  162364. JBLOCKROW *MCU_data));
  162365. METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
  162366. #endif
  162367. /*
  162368. * Initialize for a Huffman-compressed scan.
  162369. * If gather_statistics is TRUE, we do not output anything during the scan,
  162370. * just count the Huffman symbols used and generate Huffman code tables.
  162371. */
  162372. METHODDEF(void)
  162373. start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
  162374. {
  162375. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  162376. int ci, dctbl, actbl;
  162377. jpeg_component_info * compptr;
  162378. if (gather_statistics) {
  162379. #ifdef ENTROPY_OPT_SUPPORTED
  162380. entropy->pub.encode_mcu = encode_mcu_gather;
  162381. entropy->pub.finish_pass = finish_pass_gather;
  162382. #else
  162383. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162384. #endif
  162385. } else {
  162386. entropy->pub.encode_mcu = encode_mcu_huff;
  162387. entropy->pub.finish_pass = finish_pass_huff;
  162388. }
  162389. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162390. compptr = cinfo->cur_comp_info[ci];
  162391. dctbl = compptr->dc_tbl_no;
  162392. actbl = compptr->ac_tbl_no;
  162393. if (gather_statistics) {
  162394. #ifdef ENTROPY_OPT_SUPPORTED
  162395. /* Check for invalid table indexes */
  162396. /* (make_c_derived_tbl does this in the other path) */
  162397. if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
  162398. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
  162399. if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
  162400. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
  162401. /* Allocate and zero the statistics tables */
  162402. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  162403. if (entropy->dc_count_ptrs[dctbl] == NULL)
  162404. entropy->dc_count_ptrs[dctbl] = (long *)
  162405. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162406. 257 * SIZEOF(long));
  162407. MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
  162408. if (entropy->ac_count_ptrs[actbl] == NULL)
  162409. entropy->ac_count_ptrs[actbl] = (long *)
  162410. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162411. 257 * SIZEOF(long));
  162412. MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
  162413. #endif
  162414. } else {
  162415. /* Compute derived values for Huffman tables */
  162416. /* We may do this more than once for a table, but it's not expensive */
  162417. jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
  162418. & entropy->dc_derived_tbls[dctbl]);
  162419. jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
  162420. & entropy->ac_derived_tbls[actbl]);
  162421. }
  162422. /* Initialize DC predictions to 0 */
  162423. entropy->saved.last_dc_val[ci] = 0;
  162424. }
  162425. /* Initialize bit buffer to empty */
  162426. entropy->saved.put_buffer = 0;
  162427. entropy->saved.put_bits = 0;
  162428. /* Initialize restart stuff */
  162429. entropy->restarts_to_go = cinfo->restart_interval;
  162430. entropy->next_restart_num = 0;
  162431. }
  162432. /*
  162433. * Compute the derived values for a Huffman table.
  162434. * This routine also performs some validation checks on the table.
  162435. *
  162436. * Note this is also used by jcphuff.c.
  162437. */
  162438. GLOBAL(void)
  162439. jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
  162440. c_derived_tbl ** pdtbl)
  162441. {
  162442. JHUFF_TBL *htbl;
  162443. c_derived_tbl *dtbl;
  162444. int p, i, l, lastp, si, maxsymbol;
  162445. char huffsize[257];
  162446. unsigned int huffcode[257];
  162447. unsigned int code;
  162448. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  162449. * paralleling the order of the symbols themselves in htbl->huffval[].
  162450. */
  162451. /* Find the input Huffman table */
  162452. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  162453. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  162454. htbl =
  162455. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  162456. if (htbl == NULL)
  162457. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  162458. /* Allocate a workspace if we haven't already done so. */
  162459. if (*pdtbl == NULL)
  162460. *pdtbl = (c_derived_tbl *)
  162461. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162462. SIZEOF(c_derived_tbl));
  162463. dtbl = *pdtbl;
  162464. /* Figure C.1: make table of Huffman code length for each symbol */
  162465. p = 0;
  162466. for (l = 1; l <= 16; l++) {
  162467. i = (int) htbl->bits[l];
  162468. if (i < 0 || p + i > 256) /* protect against table overrun */
  162469. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  162470. while (i--)
  162471. huffsize[p++] = (char) l;
  162472. }
  162473. huffsize[p] = 0;
  162474. lastp = p;
  162475. /* Figure C.2: generate the codes themselves */
  162476. /* We also validate that the counts represent a legal Huffman code tree. */
  162477. code = 0;
  162478. si = huffsize[0];
  162479. p = 0;
  162480. while (huffsize[p]) {
  162481. while (((int) huffsize[p]) == si) {
  162482. huffcode[p++] = code;
  162483. code++;
  162484. }
  162485. /* code is now 1 more than the last code used for codelength si; but
  162486. * it must still fit in si bits, since no code is allowed to be all ones.
  162487. */
  162488. if (((INT32) code) >= (((INT32) 1) << si))
  162489. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  162490. code <<= 1;
  162491. si++;
  162492. }
  162493. /* Figure C.3: generate encoding tables */
  162494. /* These are code and size indexed by symbol value */
  162495. /* Set all codeless symbols to have code length 0;
  162496. * this lets us detect duplicate VAL entries here, and later
  162497. * allows emit_bits to detect any attempt to emit such symbols.
  162498. */
  162499. MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
  162500. /* This is also a convenient place to check for out-of-range
  162501. * and duplicated VAL entries. We allow 0..255 for AC symbols
  162502. * but only 0..15 for DC. (We could constrain them further
  162503. * based on data depth and mode, but this seems enough.)
  162504. */
  162505. maxsymbol = isDC ? 15 : 255;
  162506. for (p = 0; p < lastp; p++) {
  162507. i = htbl->huffval[p];
  162508. if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
  162509. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  162510. dtbl->ehufco[i] = huffcode[p];
  162511. dtbl->ehufsi[i] = huffsize[p];
  162512. }
  162513. }
  162514. /* Outputting bytes to the file */
  162515. /* Emit a byte, taking 'action' if must suspend. */
  162516. #define emit_byte(state,val,action) \
  162517. { *(state)->next_output_byte++ = (JOCTET) (val); \
  162518. if (--(state)->free_in_buffer == 0) \
  162519. if (! dump_buffer(state)) \
  162520. { action; } }
  162521. LOCAL(boolean)
  162522. dump_buffer (working_state * state)
  162523. /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
  162524. {
  162525. struct jpeg_destination_mgr * dest = state->cinfo->dest;
  162526. if (! (*dest->empty_output_buffer) (state->cinfo))
  162527. return FALSE;
  162528. /* After a successful buffer dump, must reset buffer pointers */
  162529. state->next_output_byte = dest->next_output_byte;
  162530. state->free_in_buffer = dest->free_in_buffer;
  162531. return TRUE;
  162532. }
  162533. /* Outputting bits to the file */
  162534. /* Only the right 24 bits of put_buffer are used; the valid bits are
  162535. * left-justified in this part. At most 16 bits can be passed to emit_bits
  162536. * in one call, and we never retain more than 7 bits in put_buffer
  162537. * between calls, so 24 bits are sufficient.
  162538. */
  162539. INLINE
  162540. LOCAL(boolean)
  162541. emit_bits (working_state * state, unsigned int code, int size)
  162542. /* Emit some bits; return TRUE if successful, FALSE if must suspend */
  162543. {
  162544. /* This routine is heavily used, so it's worth coding tightly. */
  162545. register INT32 put_buffer = (INT32) code;
  162546. register int put_bits = state->cur.put_bits;
  162547. /* if size is 0, caller used an invalid Huffman table entry */
  162548. if (size == 0)
  162549. ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
  162550. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  162551. put_bits += size; /* new number of bits in buffer */
  162552. put_buffer <<= 24 - put_bits; /* align incoming bits */
  162553. put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
  162554. while (put_bits >= 8) {
  162555. int c = (int) ((put_buffer >> 16) & 0xFF);
  162556. emit_byte(state, c, return FALSE);
  162557. if (c == 0xFF) { /* need to stuff a zero byte? */
  162558. emit_byte(state, 0, return FALSE);
  162559. }
  162560. put_buffer <<= 8;
  162561. put_bits -= 8;
  162562. }
  162563. state->cur.put_buffer = put_buffer; /* update state variables */
  162564. state->cur.put_bits = put_bits;
  162565. return TRUE;
  162566. }
  162567. LOCAL(boolean)
  162568. flush_bits (working_state * state)
  162569. {
  162570. if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
  162571. return FALSE;
  162572. state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
  162573. state->cur.put_bits = 0;
  162574. return TRUE;
  162575. }
  162576. /* Encode a single block's worth of coefficients */
  162577. LOCAL(boolean)
  162578. encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
  162579. c_derived_tbl *dctbl, c_derived_tbl *actbl)
  162580. {
  162581. register int temp, temp2;
  162582. register int nbits;
  162583. register int k, r, i;
  162584. /* Encode the DC coefficient difference per section F.1.2.1 */
  162585. temp = temp2 = block[0] - last_dc_val;
  162586. if (temp < 0) {
  162587. temp = -temp; /* temp is abs value of input */
  162588. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  162589. /* This code assumes we are on a two's complement machine */
  162590. temp2--;
  162591. }
  162592. /* Find the number of bits needed for the magnitude of the coefficient */
  162593. nbits = 0;
  162594. while (temp) {
  162595. nbits++;
  162596. temp >>= 1;
  162597. }
  162598. /* Check for out-of-range coefficient values.
  162599. * Since we're encoding a difference, the range limit is twice as much.
  162600. */
  162601. if (nbits > MAX_COEF_BITS+1)
  162602. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  162603. /* Emit the Huffman-coded symbol for the number of bits */
  162604. if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
  162605. return FALSE;
  162606. /* Emit that number of bits of the value, if positive, */
  162607. /* or the complement of its magnitude, if negative. */
  162608. if (nbits) /* emit_bits rejects calls with size 0 */
  162609. if (! emit_bits(state, (unsigned int) temp2, nbits))
  162610. return FALSE;
  162611. /* Encode the AC coefficients per section F.1.2.2 */
  162612. r = 0; /* r = run length of zeros */
  162613. for (k = 1; k < DCTSIZE2; k++) {
  162614. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  162615. r++;
  162616. } else {
  162617. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  162618. while (r > 15) {
  162619. if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
  162620. return FALSE;
  162621. r -= 16;
  162622. }
  162623. temp2 = temp;
  162624. if (temp < 0) {
  162625. temp = -temp; /* temp is abs value of input */
  162626. /* This code assumes we are on a two's complement machine */
  162627. temp2--;
  162628. }
  162629. /* Find the number of bits needed for the magnitude of the coefficient */
  162630. nbits = 1; /* there must be at least one 1 bit */
  162631. while ((temp >>= 1))
  162632. nbits++;
  162633. /* Check for out-of-range coefficient values */
  162634. if (nbits > MAX_COEF_BITS)
  162635. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  162636. /* Emit Huffman symbol for run length / number of bits */
  162637. i = (r << 4) + nbits;
  162638. if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
  162639. return FALSE;
  162640. /* Emit that number of bits of the value, if positive, */
  162641. /* or the complement of its magnitude, if negative. */
  162642. if (! emit_bits(state, (unsigned int) temp2, nbits))
  162643. return FALSE;
  162644. r = 0;
  162645. }
  162646. }
  162647. /* If the last coef(s) were zero, emit an end-of-block code */
  162648. if (r > 0)
  162649. if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
  162650. return FALSE;
  162651. return TRUE;
  162652. }
  162653. /*
  162654. * Emit a restart marker & resynchronize predictions.
  162655. */
  162656. LOCAL(boolean)
  162657. emit_restart (working_state * state, int restart_num)
  162658. {
  162659. int ci;
  162660. if (! flush_bits(state))
  162661. return FALSE;
  162662. emit_byte(state, 0xFF, return FALSE);
  162663. emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
  162664. /* Re-initialize DC predictions to 0 */
  162665. for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
  162666. state->cur.last_dc_val[ci] = 0;
  162667. /* The restart counter is not updated until we successfully write the MCU. */
  162668. return TRUE;
  162669. }
  162670. /*
  162671. * Encode and output one MCU's worth of Huffman-compressed coefficients.
  162672. */
  162673. METHODDEF(boolean)
  162674. encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  162675. {
  162676. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  162677. working_state state;
  162678. int blkn, ci;
  162679. jpeg_component_info * compptr;
  162680. /* Load up working state */
  162681. state.next_output_byte = cinfo->dest->next_output_byte;
  162682. state.free_in_buffer = cinfo->dest->free_in_buffer;
  162683. ASSIGN_STATE(state.cur, entropy->saved);
  162684. state.cinfo = cinfo;
  162685. /* Emit restart marker if needed */
  162686. if (cinfo->restart_interval) {
  162687. if (entropy->restarts_to_go == 0)
  162688. if (! emit_restart(&state, entropy->next_restart_num))
  162689. return FALSE;
  162690. }
  162691. /* Encode the MCU data blocks */
  162692. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  162693. ci = cinfo->MCU_membership[blkn];
  162694. compptr = cinfo->cur_comp_info[ci];
  162695. if (! encode_one_block(&state,
  162696. MCU_data[blkn][0], state.cur.last_dc_val[ci],
  162697. entropy->dc_derived_tbls[compptr->dc_tbl_no],
  162698. entropy->ac_derived_tbls[compptr->ac_tbl_no]))
  162699. return FALSE;
  162700. /* Update last_dc_val */
  162701. state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
  162702. }
  162703. /* Completed MCU, so update state */
  162704. cinfo->dest->next_output_byte = state.next_output_byte;
  162705. cinfo->dest->free_in_buffer = state.free_in_buffer;
  162706. ASSIGN_STATE(entropy->saved, state.cur);
  162707. /* Update restart-interval state too */
  162708. if (cinfo->restart_interval) {
  162709. if (entropy->restarts_to_go == 0) {
  162710. entropy->restarts_to_go = cinfo->restart_interval;
  162711. entropy->next_restart_num++;
  162712. entropy->next_restart_num &= 7;
  162713. }
  162714. entropy->restarts_to_go--;
  162715. }
  162716. return TRUE;
  162717. }
  162718. /*
  162719. * Finish up at the end of a Huffman-compressed scan.
  162720. */
  162721. METHODDEF(void)
  162722. finish_pass_huff (j_compress_ptr cinfo)
  162723. {
  162724. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  162725. working_state state;
  162726. /* Load up working state ... flush_bits needs it */
  162727. state.next_output_byte = cinfo->dest->next_output_byte;
  162728. state.free_in_buffer = cinfo->dest->free_in_buffer;
  162729. ASSIGN_STATE(state.cur, entropy->saved);
  162730. state.cinfo = cinfo;
  162731. /* Flush out the last data */
  162732. if (! flush_bits(&state))
  162733. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  162734. /* Update state */
  162735. cinfo->dest->next_output_byte = state.next_output_byte;
  162736. cinfo->dest->free_in_buffer = state.free_in_buffer;
  162737. ASSIGN_STATE(entropy->saved, state.cur);
  162738. }
  162739. /*
  162740. * Huffman coding optimization.
  162741. *
  162742. * We first scan the supplied data and count the number of uses of each symbol
  162743. * that is to be Huffman-coded. (This process MUST agree with the code above.)
  162744. * Then we build a Huffman coding tree for the observed counts.
  162745. * Symbols which are not needed at all for the particular image are not
  162746. * assigned any code, which saves space in the DHT marker as well as in
  162747. * the compressed data.
  162748. */
  162749. #ifdef ENTROPY_OPT_SUPPORTED
  162750. /* Process a single block's worth of coefficients */
  162751. LOCAL(void)
  162752. htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
  162753. long dc_counts[], long ac_counts[])
  162754. {
  162755. register int temp;
  162756. register int nbits;
  162757. register int k, r;
  162758. /* Encode the DC coefficient difference per section F.1.2.1 */
  162759. temp = block[0] - last_dc_val;
  162760. if (temp < 0)
  162761. temp = -temp;
  162762. /* Find the number of bits needed for the magnitude of the coefficient */
  162763. nbits = 0;
  162764. while (temp) {
  162765. nbits++;
  162766. temp >>= 1;
  162767. }
  162768. /* Check for out-of-range coefficient values.
  162769. * Since we're encoding a difference, the range limit is twice as much.
  162770. */
  162771. if (nbits > MAX_COEF_BITS+1)
  162772. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  162773. /* Count the Huffman symbol for the number of bits */
  162774. dc_counts[nbits]++;
  162775. /* Encode the AC coefficients per section F.1.2.2 */
  162776. r = 0; /* r = run length of zeros */
  162777. for (k = 1; k < DCTSIZE2; k++) {
  162778. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  162779. r++;
  162780. } else {
  162781. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  162782. while (r > 15) {
  162783. ac_counts[0xF0]++;
  162784. r -= 16;
  162785. }
  162786. /* Find the number of bits needed for the magnitude of the coefficient */
  162787. if (temp < 0)
  162788. temp = -temp;
  162789. /* Find the number of bits needed for the magnitude of the coefficient */
  162790. nbits = 1; /* there must be at least one 1 bit */
  162791. while ((temp >>= 1))
  162792. nbits++;
  162793. /* Check for out-of-range coefficient values */
  162794. if (nbits > MAX_COEF_BITS)
  162795. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  162796. /* Count Huffman symbol for run length / number of bits */
  162797. ac_counts[(r << 4) + nbits]++;
  162798. r = 0;
  162799. }
  162800. }
  162801. /* If the last coef(s) were zero, emit an end-of-block code */
  162802. if (r > 0)
  162803. ac_counts[0]++;
  162804. }
  162805. /*
  162806. * Trial-encode one MCU's worth of Huffman-compressed coefficients.
  162807. * No data is actually output, so no suspension return is possible.
  162808. */
  162809. METHODDEF(boolean)
  162810. encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  162811. {
  162812. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  162813. int blkn, ci;
  162814. jpeg_component_info * compptr;
  162815. /* Take care of restart intervals if needed */
  162816. if (cinfo->restart_interval) {
  162817. if (entropy->restarts_to_go == 0) {
  162818. /* Re-initialize DC predictions to 0 */
  162819. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  162820. entropy->saved.last_dc_val[ci] = 0;
  162821. /* Update restart state */
  162822. entropy->restarts_to_go = cinfo->restart_interval;
  162823. }
  162824. entropy->restarts_to_go--;
  162825. }
  162826. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  162827. ci = cinfo->MCU_membership[blkn];
  162828. compptr = cinfo->cur_comp_info[ci];
  162829. htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
  162830. entropy->dc_count_ptrs[compptr->dc_tbl_no],
  162831. entropy->ac_count_ptrs[compptr->ac_tbl_no]);
  162832. entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
  162833. }
  162834. return TRUE;
  162835. }
  162836. /*
  162837. * Generate the best Huffman code table for the given counts, fill htbl.
  162838. * Note this is also used by jcphuff.c.
  162839. *
  162840. * The JPEG standard requires that no symbol be assigned a codeword of all
  162841. * one bits (so that padding bits added at the end of a compressed segment
  162842. * can't look like a valid code). Because of the canonical ordering of
  162843. * codewords, this just means that there must be an unused slot in the
  162844. * longest codeword length category. Section K.2 of the JPEG spec suggests
  162845. * reserving such a slot by pretending that symbol 256 is a valid symbol
  162846. * with count 1. In theory that's not optimal; giving it count zero but
  162847. * including it in the symbol set anyway should give a better Huffman code.
  162848. * But the theoretically better code actually seems to come out worse in
  162849. * practice, because it produces more all-ones bytes (which incur stuffed
  162850. * zero bytes in the final file). In any case the difference is tiny.
  162851. *
  162852. * The JPEG standard requires Huffman codes to be no more than 16 bits long.
  162853. * If some symbols have a very small but nonzero probability, the Huffman tree
  162854. * must be adjusted to meet the code length restriction. We currently use
  162855. * the adjustment method suggested in JPEG section K.2. This method is *not*
  162856. * optimal; it may not choose the best possible limited-length code. But
  162857. * typically only very-low-frequency symbols will be given less-than-optimal
  162858. * lengths, so the code is almost optimal. Experimental comparisons against
  162859. * an optimal limited-length-code algorithm indicate that the difference is
  162860. * microscopic --- usually less than a hundredth of a percent of total size.
  162861. * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
  162862. */
  162863. GLOBAL(void)
  162864. jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
  162865. {
  162866. #define MAX_CLEN 32 /* assumed maximum initial code length */
  162867. UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
  162868. int codesize[257]; /* codesize[k] = code length of symbol k */
  162869. int others[257]; /* next symbol in current branch of tree */
  162870. int c1, c2;
  162871. int p, i, j;
  162872. long v;
  162873. /* This algorithm is explained in section K.2 of the JPEG standard */
  162874. MEMZERO(bits, SIZEOF(bits));
  162875. MEMZERO(codesize, SIZEOF(codesize));
  162876. for (i = 0; i < 257; i++)
  162877. others[i] = -1; /* init links to empty */
  162878. freq[256] = 1; /* make sure 256 has a nonzero count */
  162879. /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
  162880. * that no real symbol is given code-value of all ones, because 256
  162881. * will be placed last in the largest codeword category.
  162882. */
  162883. /* Huffman's basic algorithm to assign optimal code lengths to symbols */
  162884. for (;;) {
  162885. /* Find the smallest nonzero frequency, set c1 = its symbol */
  162886. /* In case of ties, take the larger symbol number */
  162887. c1 = -1;
  162888. v = 1000000000L;
  162889. for (i = 0; i <= 256; i++) {
  162890. if (freq[i] && freq[i] <= v) {
  162891. v = freq[i];
  162892. c1 = i;
  162893. }
  162894. }
  162895. /* Find the next smallest nonzero frequency, set c2 = its symbol */
  162896. /* In case of ties, take the larger symbol number */
  162897. c2 = -1;
  162898. v = 1000000000L;
  162899. for (i = 0; i <= 256; i++) {
  162900. if (freq[i] && freq[i] <= v && i != c1) {
  162901. v = freq[i];
  162902. c2 = i;
  162903. }
  162904. }
  162905. /* Done if we've merged everything into one frequency */
  162906. if (c2 < 0)
  162907. break;
  162908. /* Else merge the two counts/trees */
  162909. freq[c1] += freq[c2];
  162910. freq[c2] = 0;
  162911. /* Increment the codesize of everything in c1's tree branch */
  162912. codesize[c1]++;
  162913. while (others[c1] >= 0) {
  162914. c1 = others[c1];
  162915. codesize[c1]++;
  162916. }
  162917. others[c1] = c2; /* chain c2 onto c1's tree branch */
  162918. /* Increment the codesize of everything in c2's tree branch */
  162919. codesize[c2]++;
  162920. while (others[c2] >= 0) {
  162921. c2 = others[c2];
  162922. codesize[c2]++;
  162923. }
  162924. }
  162925. /* Now count the number of symbols of each code length */
  162926. for (i = 0; i <= 256; i++) {
  162927. if (codesize[i]) {
  162928. /* The JPEG standard seems to think that this can't happen, */
  162929. /* but I'm paranoid... */
  162930. if (codesize[i] > MAX_CLEN)
  162931. ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
  162932. bits[codesize[i]]++;
  162933. }
  162934. }
  162935. /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
  162936. * Huffman procedure assigned any such lengths, we must adjust the coding.
  162937. * Here is what the JPEG spec says about how this next bit works:
  162938. * Since symbols are paired for the longest Huffman code, the symbols are
  162939. * removed from this length category two at a time. The prefix for the pair
  162940. * (which is one bit shorter) is allocated to one of the pair; then,
  162941. * skipping the BITS entry for that prefix length, a code word from the next
  162942. * shortest nonzero BITS entry is converted into a prefix for two code words
  162943. * one bit longer.
  162944. */
  162945. for (i = MAX_CLEN; i > 16; i--) {
  162946. while (bits[i] > 0) {
  162947. j = i - 2; /* find length of new prefix to be used */
  162948. while (bits[j] == 0)
  162949. j--;
  162950. bits[i] -= 2; /* remove two symbols */
  162951. bits[i-1]++; /* one goes in this length */
  162952. bits[j+1] += 2; /* two new symbols in this length */
  162953. bits[j]--; /* symbol of this length is now a prefix */
  162954. }
  162955. }
  162956. /* Remove the count for the pseudo-symbol 256 from the largest codelength */
  162957. while (bits[i] == 0) /* find largest codelength still in use */
  162958. i--;
  162959. bits[i]--;
  162960. /* Return final symbol counts (only for lengths 0..16) */
  162961. MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
  162962. /* Return a list of the symbols sorted by code length */
  162963. /* It's not real clear to me why we don't need to consider the codelength
  162964. * changes made above, but the JPEG spec seems to think this works.
  162965. */
  162966. p = 0;
  162967. for (i = 1; i <= MAX_CLEN; i++) {
  162968. for (j = 0; j <= 255; j++) {
  162969. if (codesize[j] == i) {
  162970. htbl->huffval[p] = (UINT8) j;
  162971. p++;
  162972. }
  162973. }
  162974. }
  162975. /* Set sent_table FALSE so updated table will be written to JPEG file. */
  162976. htbl->sent_table = FALSE;
  162977. }
  162978. /*
  162979. * Finish up a statistics-gathering pass and create the new Huffman tables.
  162980. */
  162981. METHODDEF(void)
  162982. finish_pass_gather (j_compress_ptr cinfo)
  162983. {
  162984. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  162985. int ci, dctbl, actbl;
  162986. jpeg_component_info * compptr;
  162987. JHUFF_TBL **htblptr;
  162988. boolean did_dc[NUM_HUFF_TBLS];
  162989. boolean did_ac[NUM_HUFF_TBLS];
  162990. /* It's important not to apply jpeg_gen_optimal_table more than once
  162991. * per table, because it clobbers the input frequency counts!
  162992. */
  162993. MEMZERO(did_dc, SIZEOF(did_dc));
  162994. MEMZERO(did_ac, SIZEOF(did_ac));
  162995. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162996. compptr = cinfo->cur_comp_info[ci];
  162997. dctbl = compptr->dc_tbl_no;
  162998. actbl = compptr->ac_tbl_no;
  162999. if (! did_dc[dctbl]) {
  163000. htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
  163001. if (*htblptr == NULL)
  163002. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  163003. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
  163004. did_dc[dctbl] = TRUE;
  163005. }
  163006. if (! did_ac[actbl]) {
  163007. htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
  163008. if (*htblptr == NULL)
  163009. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  163010. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
  163011. did_ac[actbl] = TRUE;
  163012. }
  163013. }
  163014. }
  163015. #endif /* ENTROPY_OPT_SUPPORTED */
  163016. /*
  163017. * Module initialization routine for Huffman entropy encoding.
  163018. */
  163019. GLOBAL(void)
  163020. jinit_huff_encoder (j_compress_ptr cinfo)
  163021. {
  163022. huff_entropy_ptr entropy;
  163023. int i;
  163024. entropy = (huff_entropy_ptr)
  163025. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163026. SIZEOF(huff_entropy_encoder));
  163027. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  163028. entropy->pub.start_pass = start_pass_huff;
  163029. /* Mark tables unallocated */
  163030. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  163031. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  163032. #ifdef ENTROPY_OPT_SUPPORTED
  163033. entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
  163034. #endif
  163035. }
  163036. }
  163037. /*** End of inlined file: jchuff.c ***/
  163038. #undef emit_byte
  163039. /*** Start of inlined file: jcinit.c ***/
  163040. #define JPEG_INTERNALS
  163041. /*
  163042. * Master selection of compression modules.
  163043. * This is done once at the start of processing an image. We determine
  163044. * which modules will be used and give them appropriate initialization calls.
  163045. */
  163046. GLOBAL(void)
  163047. jinit_compress_master (j_compress_ptr cinfo)
  163048. {
  163049. /* Initialize master control (includes parameter checking/processing) */
  163050. jinit_c_master_control(cinfo, FALSE /* full compression */);
  163051. /* Preprocessing */
  163052. if (! cinfo->raw_data_in) {
  163053. jinit_color_converter(cinfo);
  163054. jinit_downsampler(cinfo);
  163055. jinit_c_prep_controller(cinfo, FALSE /* never need full buffer here */);
  163056. }
  163057. /* Forward DCT */
  163058. jinit_forward_dct(cinfo);
  163059. /* Entropy encoding: either Huffman or arithmetic coding. */
  163060. if (cinfo->arith_code) {
  163061. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  163062. } else {
  163063. if (cinfo->progressive_mode) {
  163064. #ifdef C_PROGRESSIVE_SUPPORTED
  163065. jinit_phuff_encoder(cinfo);
  163066. #else
  163067. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163068. #endif
  163069. } else
  163070. jinit_huff_encoder(cinfo);
  163071. }
  163072. /* Need a full-image coefficient buffer in any multi-pass mode. */
  163073. jinit_c_coef_controller(cinfo,
  163074. (boolean) (cinfo->num_scans > 1 || cinfo->optimize_coding));
  163075. jinit_c_main_controller(cinfo, FALSE /* never need full buffer here */);
  163076. jinit_marker_writer(cinfo);
  163077. /* We can now tell the memory manager to allocate virtual arrays. */
  163078. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  163079. /* Write the datastream header (SOI) immediately.
  163080. * Frame and scan headers are postponed till later.
  163081. * This lets application insert special markers after the SOI.
  163082. */
  163083. (*cinfo->marker->write_file_header) (cinfo);
  163084. }
  163085. /*** End of inlined file: jcinit.c ***/
  163086. /*** Start of inlined file: jcmainct.c ***/
  163087. #define JPEG_INTERNALS
  163088. /* Note: currently, there is no operating mode in which a full-image buffer
  163089. * is needed at this step. If there were, that mode could not be used with
  163090. * "raw data" input, since this module is bypassed in that case. However,
  163091. * we've left the code here for possible use in special applications.
  163092. */
  163093. #undef FULL_MAIN_BUFFER_SUPPORTED
  163094. /* Private buffer controller object */
  163095. typedef struct {
  163096. struct jpeg_c_main_controller pub; /* public fields */
  163097. JDIMENSION cur_iMCU_row; /* number of current iMCU row */
  163098. JDIMENSION rowgroup_ctr; /* counts row groups received in iMCU row */
  163099. boolean suspended; /* remember if we suspended output */
  163100. J_BUF_MODE pass_mode; /* current operating mode */
  163101. /* If using just a strip buffer, this points to the entire set of buffers
  163102. * (we allocate one for each component). In the full-image case, this
  163103. * points to the currently accessible strips of the virtual arrays.
  163104. */
  163105. JSAMPARRAY buffer[MAX_COMPONENTS];
  163106. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163107. /* If using full-image storage, this array holds pointers to virtual-array
  163108. * control blocks for each component. Unused if not full-image storage.
  163109. */
  163110. jvirt_sarray_ptr whole_image[MAX_COMPONENTS];
  163111. #endif
  163112. } my_main_controller;
  163113. typedef my_main_controller * my_main_ptr;
  163114. /* Forward declarations */
  163115. METHODDEF(void) process_data_simple_main
  163116. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  163117. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  163118. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163119. METHODDEF(void) process_data_buffer_main
  163120. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  163121. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  163122. #endif
  163123. /*
  163124. * Initialize for a processing pass.
  163125. */
  163126. METHODDEF(void)
  163127. start_pass_main (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  163128. {
  163129. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  163130. /* Do nothing in raw-data mode. */
  163131. if (cinfo->raw_data_in)
  163132. return;
  163133. main_->cur_iMCU_row = 0; /* initialize counters */
  163134. main_->rowgroup_ctr = 0;
  163135. main_->suspended = FALSE;
  163136. main_->pass_mode = pass_mode; /* save mode for use by process_data */
  163137. switch (pass_mode) {
  163138. case JBUF_PASS_THRU:
  163139. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163140. if (main_->whole_image[0] != NULL)
  163141. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163142. #endif
  163143. main_->pub.process_data = process_data_simple_main;
  163144. break;
  163145. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163146. case JBUF_SAVE_SOURCE:
  163147. case JBUF_CRANK_DEST:
  163148. case JBUF_SAVE_AND_PASS:
  163149. if (main_->whole_image[0] == NULL)
  163150. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163151. main_->pub.process_data = process_data_buffer_main;
  163152. break;
  163153. #endif
  163154. default:
  163155. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163156. break;
  163157. }
  163158. }
  163159. /*
  163160. * Process some data.
  163161. * This routine handles the simple pass-through mode,
  163162. * where we have only a strip buffer.
  163163. */
  163164. METHODDEF(void)
  163165. process_data_simple_main (j_compress_ptr cinfo,
  163166. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  163167. JDIMENSION in_rows_avail)
  163168. {
  163169. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  163170. while (main_->cur_iMCU_row < cinfo->total_iMCU_rows) {
  163171. /* Read input data if we haven't filled the main buffer yet */
  163172. if (main_->rowgroup_ctr < DCTSIZE)
  163173. (*cinfo->prep->pre_process_data) (cinfo,
  163174. input_buf, in_row_ctr, in_rows_avail,
  163175. main_->buffer, &main_->rowgroup_ctr,
  163176. (JDIMENSION) DCTSIZE);
  163177. /* If we don't have a full iMCU row buffered, return to application for
  163178. * more data. Note that preprocessor will always pad to fill the iMCU row
  163179. * at the bottom of the image.
  163180. */
  163181. if (main_->rowgroup_ctr != DCTSIZE)
  163182. return;
  163183. /* Send the completed row to the compressor */
  163184. if (! (*cinfo->coef->compress_data) (cinfo, main_->buffer)) {
  163185. /* If compressor did not consume the whole row, then we must need to
  163186. * suspend processing and return to the application. In this situation
  163187. * we pretend we didn't yet consume the last input row; otherwise, if
  163188. * it happened to be the last row of the image, the application would
  163189. * think we were done.
  163190. */
  163191. if (! main_->suspended) {
  163192. (*in_row_ctr)--;
  163193. main_->suspended = TRUE;
  163194. }
  163195. return;
  163196. }
  163197. /* We did finish the row. Undo our little suspension hack if a previous
  163198. * call suspended; then mark the main buffer empty.
  163199. */
  163200. if (main_->suspended) {
  163201. (*in_row_ctr)++;
  163202. main_->suspended = FALSE;
  163203. }
  163204. main_->rowgroup_ctr = 0;
  163205. main_->cur_iMCU_row++;
  163206. }
  163207. }
  163208. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163209. /*
  163210. * Process some data.
  163211. * This routine handles all of the modes that use a full-size buffer.
  163212. */
  163213. METHODDEF(void)
  163214. process_data_buffer_main (j_compress_ptr cinfo,
  163215. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  163216. JDIMENSION in_rows_avail)
  163217. {
  163218. my_main_ptr main = (my_main_ptr) cinfo->main;
  163219. int ci;
  163220. jpeg_component_info *compptr;
  163221. boolean writing = (main->pass_mode != JBUF_CRANK_DEST);
  163222. while (main->cur_iMCU_row < cinfo->total_iMCU_rows) {
  163223. /* Realign the virtual buffers if at the start of an iMCU row. */
  163224. if (main->rowgroup_ctr == 0) {
  163225. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163226. ci++, compptr++) {
  163227. main->buffer[ci] = (*cinfo->mem->access_virt_sarray)
  163228. ((j_common_ptr) cinfo, main->whole_image[ci],
  163229. main->cur_iMCU_row * (compptr->v_samp_factor * DCTSIZE),
  163230. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE), writing);
  163231. }
  163232. /* In a read pass, pretend we just read some source data. */
  163233. if (! writing) {
  163234. *in_row_ctr += cinfo->max_v_samp_factor * DCTSIZE;
  163235. main->rowgroup_ctr = DCTSIZE;
  163236. }
  163237. }
  163238. /* If a write pass, read input data until the current iMCU row is full. */
  163239. /* Note: preprocessor will pad if necessary to fill the last iMCU row. */
  163240. if (writing) {
  163241. (*cinfo->prep->pre_process_data) (cinfo,
  163242. input_buf, in_row_ctr, in_rows_avail,
  163243. main->buffer, &main->rowgroup_ctr,
  163244. (JDIMENSION) DCTSIZE);
  163245. /* Return to application if we need more data to fill the iMCU row. */
  163246. if (main->rowgroup_ctr < DCTSIZE)
  163247. return;
  163248. }
  163249. /* Emit data, unless this is a sink-only pass. */
  163250. if (main->pass_mode != JBUF_SAVE_SOURCE) {
  163251. if (! (*cinfo->coef->compress_data) (cinfo, main->buffer)) {
  163252. /* If compressor did not consume the whole row, then we must need to
  163253. * suspend processing and return to the application. In this situation
  163254. * we pretend we didn't yet consume the last input row; otherwise, if
  163255. * it happened to be the last row of the image, the application would
  163256. * think we were done.
  163257. */
  163258. if (! main->suspended) {
  163259. (*in_row_ctr)--;
  163260. main->suspended = TRUE;
  163261. }
  163262. return;
  163263. }
  163264. /* We did finish the row. Undo our little suspension hack if a previous
  163265. * call suspended; then mark the main buffer empty.
  163266. */
  163267. if (main->suspended) {
  163268. (*in_row_ctr)++;
  163269. main->suspended = FALSE;
  163270. }
  163271. }
  163272. /* If get here, we are done with this iMCU row. Mark buffer empty. */
  163273. main->rowgroup_ctr = 0;
  163274. main->cur_iMCU_row++;
  163275. }
  163276. }
  163277. #endif /* FULL_MAIN_BUFFER_SUPPORTED */
  163278. /*
  163279. * Initialize main buffer controller.
  163280. */
  163281. GLOBAL(void)
  163282. jinit_c_main_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  163283. {
  163284. my_main_ptr main_;
  163285. int ci;
  163286. jpeg_component_info *compptr;
  163287. main_ = (my_main_ptr)
  163288. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163289. SIZEOF(my_main_controller));
  163290. cinfo->main = (struct jpeg_c_main_controller *) main_;
  163291. main_->pub.start_pass = start_pass_main;
  163292. /* We don't need to create a buffer in raw-data mode. */
  163293. if (cinfo->raw_data_in)
  163294. return;
  163295. /* Create the buffer. It holds downsampled data, so each component
  163296. * may be of a different size.
  163297. */
  163298. if (need_full_buffer) {
  163299. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163300. /* Allocate a full-image virtual array for each component */
  163301. /* Note we pad the bottom to a multiple of the iMCU height */
  163302. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163303. ci++, compptr++) {
  163304. main->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
  163305. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  163306. compptr->width_in_blocks * DCTSIZE,
  163307. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  163308. (long) compptr->v_samp_factor) * DCTSIZE,
  163309. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  163310. }
  163311. #else
  163312. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163313. #endif
  163314. } else {
  163315. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163316. main_->whole_image[0] = NULL; /* flag for no virtual arrays */
  163317. #endif
  163318. /* Allocate a strip buffer for each component */
  163319. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163320. ci++, compptr++) {
  163321. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  163322. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163323. compptr->width_in_blocks * DCTSIZE,
  163324. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  163325. }
  163326. }
  163327. }
  163328. /*** End of inlined file: jcmainct.c ***/
  163329. /*** Start of inlined file: jcmarker.c ***/
  163330. #define JPEG_INTERNALS
  163331. /* Private state */
  163332. typedef struct {
  163333. struct jpeg_marker_writer pub; /* public fields */
  163334. unsigned int last_restart_interval; /* last DRI value emitted; 0 after SOI */
  163335. } my_marker_writer;
  163336. typedef my_marker_writer * my_marker_ptr;
  163337. /*
  163338. * Basic output routines.
  163339. *
  163340. * Note that we do not support suspension while writing a marker.
  163341. * Therefore, an application using suspension must ensure that there is
  163342. * enough buffer space for the initial markers (typ. 600-700 bytes) before
  163343. * calling jpeg_start_compress, and enough space to write the trailing EOI
  163344. * (a few bytes) before calling jpeg_finish_compress. Multipass compression
  163345. * modes are not supported at all with suspension, so those two are the only
  163346. * points where markers will be written.
  163347. */
  163348. LOCAL(void)
  163349. emit_byte (j_compress_ptr cinfo, int val)
  163350. /* Emit a byte */
  163351. {
  163352. struct jpeg_destination_mgr * dest = cinfo->dest;
  163353. *(dest->next_output_byte)++ = (JOCTET) val;
  163354. if (--dest->free_in_buffer == 0) {
  163355. if (! (*dest->empty_output_buffer) (cinfo))
  163356. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  163357. }
  163358. }
  163359. LOCAL(void)
  163360. emit_marker (j_compress_ptr cinfo, JPEG_MARKER mark)
  163361. /* Emit a marker code */
  163362. {
  163363. emit_byte(cinfo, 0xFF);
  163364. emit_byte(cinfo, (int) mark);
  163365. }
  163366. LOCAL(void)
  163367. emit_2bytes (j_compress_ptr cinfo, int value)
  163368. /* Emit a 2-byte integer; these are always MSB first in JPEG files */
  163369. {
  163370. emit_byte(cinfo, (value >> 8) & 0xFF);
  163371. emit_byte(cinfo, value & 0xFF);
  163372. }
  163373. /*
  163374. * Routines to write specific marker types.
  163375. */
  163376. LOCAL(int)
  163377. emit_dqt (j_compress_ptr cinfo, int index)
  163378. /* Emit a DQT marker */
  163379. /* Returns the precision used (0 = 8bits, 1 = 16bits) for baseline checking */
  163380. {
  163381. JQUANT_TBL * qtbl = cinfo->quant_tbl_ptrs[index];
  163382. int prec;
  163383. int i;
  163384. if (qtbl == NULL)
  163385. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, index);
  163386. prec = 0;
  163387. for (i = 0; i < DCTSIZE2; i++) {
  163388. if (qtbl->quantval[i] > 255)
  163389. prec = 1;
  163390. }
  163391. if (! qtbl->sent_table) {
  163392. emit_marker(cinfo, M_DQT);
  163393. emit_2bytes(cinfo, prec ? DCTSIZE2*2 + 1 + 2 : DCTSIZE2 + 1 + 2);
  163394. emit_byte(cinfo, index + (prec<<4));
  163395. for (i = 0; i < DCTSIZE2; i++) {
  163396. /* The table entries must be emitted in zigzag order. */
  163397. unsigned int qval = qtbl->quantval[jpeg_natural_order[i]];
  163398. if (prec)
  163399. emit_byte(cinfo, (int) (qval >> 8));
  163400. emit_byte(cinfo, (int) (qval & 0xFF));
  163401. }
  163402. qtbl->sent_table = TRUE;
  163403. }
  163404. return prec;
  163405. }
  163406. LOCAL(void)
  163407. emit_dht (j_compress_ptr cinfo, int index, boolean is_ac)
  163408. /* Emit a DHT marker */
  163409. {
  163410. JHUFF_TBL * htbl;
  163411. int length, i;
  163412. if (is_ac) {
  163413. htbl = cinfo->ac_huff_tbl_ptrs[index];
  163414. index += 0x10; /* output index has AC bit set */
  163415. } else {
  163416. htbl = cinfo->dc_huff_tbl_ptrs[index];
  163417. }
  163418. if (htbl == NULL)
  163419. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, index);
  163420. if (! htbl->sent_table) {
  163421. emit_marker(cinfo, M_DHT);
  163422. length = 0;
  163423. for (i = 1; i <= 16; i++)
  163424. length += htbl->bits[i];
  163425. emit_2bytes(cinfo, length + 2 + 1 + 16);
  163426. emit_byte(cinfo, index);
  163427. for (i = 1; i <= 16; i++)
  163428. emit_byte(cinfo, htbl->bits[i]);
  163429. for (i = 0; i < length; i++)
  163430. emit_byte(cinfo, htbl->huffval[i]);
  163431. htbl->sent_table = TRUE;
  163432. }
  163433. }
  163434. LOCAL(void)
  163435. emit_dac (j_compress_ptr)
  163436. /* Emit a DAC marker */
  163437. /* Since the useful info is so small, we want to emit all the tables in */
  163438. /* one DAC marker. Therefore this routine does its own scan of the table. */
  163439. {
  163440. #ifdef C_ARITH_CODING_SUPPORTED
  163441. char dc_in_use[NUM_ARITH_TBLS];
  163442. char ac_in_use[NUM_ARITH_TBLS];
  163443. int length, i;
  163444. jpeg_component_info *compptr;
  163445. for (i = 0; i < NUM_ARITH_TBLS; i++)
  163446. dc_in_use[i] = ac_in_use[i] = 0;
  163447. for (i = 0; i < cinfo->comps_in_scan; i++) {
  163448. compptr = cinfo->cur_comp_info[i];
  163449. dc_in_use[compptr->dc_tbl_no] = 1;
  163450. ac_in_use[compptr->ac_tbl_no] = 1;
  163451. }
  163452. length = 0;
  163453. for (i = 0; i < NUM_ARITH_TBLS; i++)
  163454. length += dc_in_use[i] + ac_in_use[i];
  163455. emit_marker(cinfo, M_DAC);
  163456. emit_2bytes(cinfo, length*2 + 2);
  163457. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  163458. if (dc_in_use[i]) {
  163459. emit_byte(cinfo, i);
  163460. emit_byte(cinfo, cinfo->arith_dc_L[i] + (cinfo->arith_dc_U[i]<<4));
  163461. }
  163462. if (ac_in_use[i]) {
  163463. emit_byte(cinfo, i + 0x10);
  163464. emit_byte(cinfo, cinfo->arith_ac_K[i]);
  163465. }
  163466. }
  163467. #endif /* C_ARITH_CODING_SUPPORTED */
  163468. }
  163469. LOCAL(void)
  163470. emit_dri (j_compress_ptr cinfo)
  163471. /* Emit a DRI marker */
  163472. {
  163473. emit_marker(cinfo, M_DRI);
  163474. emit_2bytes(cinfo, 4); /* fixed length */
  163475. emit_2bytes(cinfo, (int) cinfo->restart_interval);
  163476. }
  163477. LOCAL(void)
  163478. emit_sof (j_compress_ptr cinfo, JPEG_MARKER code)
  163479. /* Emit a SOF marker */
  163480. {
  163481. int ci;
  163482. jpeg_component_info *compptr;
  163483. emit_marker(cinfo, code);
  163484. emit_2bytes(cinfo, 3 * cinfo->num_components + 2 + 5 + 1); /* length */
  163485. /* Make sure image isn't bigger than SOF field can handle */
  163486. if ((long) cinfo->image_height > 65535L ||
  163487. (long) cinfo->image_width > 65535L)
  163488. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) 65535);
  163489. emit_byte(cinfo, cinfo->data_precision);
  163490. emit_2bytes(cinfo, (int) cinfo->image_height);
  163491. emit_2bytes(cinfo, (int) cinfo->image_width);
  163492. emit_byte(cinfo, cinfo->num_components);
  163493. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163494. ci++, compptr++) {
  163495. emit_byte(cinfo, compptr->component_id);
  163496. emit_byte(cinfo, (compptr->h_samp_factor << 4) + compptr->v_samp_factor);
  163497. emit_byte(cinfo, compptr->quant_tbl_no);
  163498. }
  163499. }
  163500. LOCAL(void)
  163501. emit_sos (j_compress_ptr cinfo)
  163502. /* Emit a SOS marker */
  163503. {
  163504. int i, td, ta;
  163505. jpeg_component_info *compptr;
  163506. emit_marker(cinfo, M_SOS);
  163507. emit_2bytes(cinfo, 2 * cinfo->comps_in_scan + 2 + 1 + 3); /* length */
  163508. emit_byte(cinfo, cinfo->comps_in_scan);
  163509. for (i = 0; i < cinfo->comps_in_scan; i++) {
  163510. compptr = cinfo->cur_comp_info[i];
  163511. emit_byte(cinfo, compptr->component_id);
  163512. td = compptr->dc_tbl_no;
  163513. ta = compptr->ac_tbl_no;
  163514. if (cinfo->progressive_mode) {
  163515. /* Progressive mode: only DC or only AC tables are used in one scan;
  163516. * furthermore, Huffman coding of DC refinement uses no table at all.
  163517. * We emit 0 for unused field(s); this is recommended by the P&M text
  163518. * but does not seem to be specified in the standard.
  163519. */
  163520. if (cinfo->Ss == 0) {
  163521. ta = 0; /* DC scan */
  163522. if (cinfo->Ah != 0 && !cinfo->arith_code)
  163523. td = 0; /* no DC table either */
  163524. } else {
  163525. td = 0; /* AC scan */
  163526. }
  163527. }
  163528. emit_byte(cinfo, (td << 4) + ta);
  163529. }
  163530. emit_byte(cinfo, cinfo->Ss);
  163531. emit_byte(cinfo, cinfo->Se);
  163532. emit_byte(cinfo, (cinfo->Ah << 4) + cinfo->Al);
  163533. }
  163534. LOCAL(void)
  163535. emit_jfif_app0 (j_compress_ptr cinfo)
  163536. /* Emit a JFIF-compliant APP0 marker */
  163537. {
  163538. /*
  163539. * Length of APP0 block (2 bytes)
  163540. * Block ID (4 bytes - ASCII "JFIF")
  163541. * Zero byte (1 byte to terminate the ID string)
  163542. * Version Major, Minor (2 bytes - major first)
  163543. * Units (1 byte - 0x00 = none, 0x01 = inch, 0x02 = cm)
  163544. * Xdpu (2 bytes - dots per unit horizontal)
  163545. * Ydpu (2 bytes - dots per unit vertical)
  163546. * Thumbnail X size (1 byte)
  163547. * Thumbnail Y size (1 byte)
  163548. */
  163549. emit_marker(cinfo, M_APP0);
  163550. emit_2bytes(cinfo, 2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1); /* length */
  163551. emit_byte(cinfo, 0x4A); /* Identifier: ASCII "JFIF" */
  163552. emit_byte(cinfo, 0x46);
  163553. emit_byte(cinfo, 0x49);
  163554. emit_byte(cinfo, 0x46);
  163555. emit_byte(cinfo, 0);
  163556. emit_byte(cinfo, cinfo->JFIF_major_version); /* Version fields */
  163557. emit_byte(cinfo, cinfo->JFIF_minor_version);
  163558. emit_byte(cinfo, cinfo->density_unit); /* Pixel size information */
  163559. emit_2bytes(cinfo, (int) cinfo->X_density);
  163560. emit_2bytes(cinfo, (int) cinfo->Y_density);
  163561. emit_byte(cinfo, 0); /* No thumbnail image */
  163562. emit_byte(cinfo, 0);
  163563. }
  163564. LOCAL(void)
  163565. emit_adobe_app14 (j_compress_ptr cinfo)
  163566. /* Emit an Adobe APP14 marker */
  163567. {
  163568. /*
  163569. * Length of APP14 block (2 bytes)
  163570. * Block ID (5 bytes - ASCII "Adobe")
  163571. * Version Number (2 bytes - currently 100)
  163572. * Flags0 (2 bytes - currently 0)
  163573. * Flags1 (2 bytes - currently 0)
  163574. * Color transform (1 byte)
  163575. *
  163576. * Although Adobe TN 5116 mentions Version = 101, all the Adobe files
  163577. * now in circulation seem to use Version = 100, so that's what we write.
  163578. *
  163579. * We write the color transform byte as 1 if the JPEG color space is
  163580. * YCbCr, 2 if it's YCCK, 0 otherwise. Adobe's definition has to do with
  163581. * whether the encoder performed a transformation, which is pretty useless.
  163582. */
  163583. emit_marker(cinfo, M_APP14);
  163584. emit_2bytes(cinfo, 2 + 5 + 2 + 2 + 2 + 1); /* length */
  163585. emit_byte(cinfo, 0x41); /* Identifier: ASCII "Adobe" */
  163586. emit_byte(cinfo, 0x64);
  163587. emit_byte(cinfo, 0x6F);
  163588. emit_byte(cinfo, 0x62);
  163589. emit_byte(cinfo, 0x65);
  163590. emit_2bytes(cinfo, 100); /* Version */
  163591. emit_2bytes(cinfo, 0); /* Flags0 */
  163592. emit_2bytes(cinfo, 0); /* Flags1 */
  163593. switch (cinfo->jpeg_color_space) {
  163594. case JCS_YCbCr:
  163595. emit_byte(cinfo, 1); /* Color transform = 1 */
  163596. break;
  163597. case JCS_YCCK:
  163598. emit_byte(cinfo, 2); /* Color transform = 2 */
  163599. break;
  163600. default:
  163601. emit_byte(cinfo, 0); /* Color transform = 0 */
  163602. break;
  163603. }
  163604. }
  163605. /*
  163606. * These routines allow writing an arbitrary marker with parameters.
  163607. * The only intended use is to emit COM or APPn markers after calling
  163608. * write_file_header and before calling write_frame_header.
  163609. * Other uses are not guaranteed to produce desirable results.
  163610. * Counting the parameter bytes properly is the caller's responsibility.
  163611. */
  163612. METHODDEF(void)
  163613. write_marker_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  163614. /* Emit an arbitrary marker header */
  163615. {
  163616. if (datalen > (unsigned int) 65533) /* safety check */
  163617. ERREXIT(cinfo, JERR_BAD_LENGTH);
  163618. emit_marker(cinfo, (JPEG_MARKER) marker);
  163619. emit_2bytes(cinfo, (int) (datalen + 2)); /* total length */
  163620. }
  163621. METHODDEF(void)
  163622. write_marker_byte (j_compress_ptr cinfo, int val)
  163623. /* Emit one byte of marker parameters following write_marker_header */
  163624. {
  163625. emit_byte(cinfo, val);
  163626. }
  163627. /*
  163628. * Write datastream header.
  163629. * This consists of an SOI and optional APPn markers.
  163630. * We recommend use of the JFIF marker, but not the Adobe marker,
  163631. * when using YCbCr or grayscale data. The JFIF marker should NOT
  163632. * be used for any other JPEG colorspace. The Adobe marker is helpful
  163633. * to distinguish RGB, CMYK, and YCCK colorspaces.
  163634. * Note that an application can write additional header markers after
  163635. * jpeg_start_compress returns.
  163636. */
  163637. METHODDEF(void)
  163638. write_file_header (j_compress_ptr cinfo)
  163639. {
  163640. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  163641. emit_marker(cinfo, M_SOI); /* first the SOI */
  163642. /* SOI is defined to reset restart interval to 0 */
  163643. marker->last_restart_interval = 0;
  163644. if (cinfo->write_JFIF_header) /* next an optional JFIF APP0 */
  163645. emit_jfif_app0(cinfo);
  163646. if (cinfo->write_Adobe_marker) /* next an optional Adobe APP14 */
  163647. emit_adobe_app14(cinfo);
  163648. }
  163649. /*
  163650. * Write frame header.
  163651. * This consists of DQT and SOFn markers.
  163652. * Note that we do not emit the SOF until we have emitted the DQT(s).
  163653. * This avoids compatibility problems with incorrect implementations that
  163654. * try to error-check the quant table numbers as soon as they see the SOF.
  163655. */
  163656. METHODDEF(void)
  163657. write_frame_header (j_compress_ptr cinfo)
  163658. {
  163659. int ci, prec;
  163660. boolean is_baseline;
  163661. jpeg_component_info *compptr;
  163662. /* Emit DQT for each quantization table.
  163663. * Note that emit_dqt() suppresses any duplicate tables.
  163664. */
  163665. prec = 0;
  163666. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163667. ci++, compptr++) {
  163668. prec += emit_dqt(cinfo, compptr->quant_tbl_no);
  163669. }
  163670. /* now prec is nonzero iff there are any 16-bit quant tables. */
  163671. /* Check for a non-baseline specification.
  163672. * Note we assume that Huffman table numbers won't be changed later.
  163673. */
  163674. if (cinfo->arith_code || cinfo->progressive_mode ||
  163675. cinfo->data_precision != 8) {
  163676. is_baseline = FALSE;
  163677. } else {
  163678. is_baseline = TRUE;
  163679. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163680. ci++, compptr++) {
  163681. if (compptr->dc_tbl_no > 1 || compptr->ac_tbl_no > 1)
  163682. is_baseline = FALSE;
  163683. }
  163684. if (prec && is_baseline) {
  163685. is_baseline = FALSE;
  163686. /* If it's baseline except for quantizer size, warn the user */
  163687. TRACEMS(cinfo, 0, JTRC_16BIT_TABLES);
  163688. }
  163689. }
  163690. /* Emit the proper SOF marker */
  163691. if (cinfo->arith_code) {
  163692. emit_sof(cinfo, M_SOF9); /* SOF code for arithmetic coding */
  163693. } else {
  163694. if (cinfo->progressive_mode)
  163695. emit_sof(cinfo, M_SOF2); /* SOF code for progressive Huffman */
  163696. else if (is_baseline)
  163697. emit_sof(cinfo, M_SOF0); /* SOF code for baseline implementation */
  163698. else
  163699. emit_sof(cinfo, M_SOF1); /* SOF code for non-baseline Huffman file */
  163700. }
  163701. }
  163702. /*
  163703. * Write scan header.
  163704. * This consists of DHT or DAC markers, optional DRI, and SOS.
  163705. * Compressed data will be written following the SOS.
  163706. */
  163707. METHODDEF(void)
  163708. write_scan_header (j_compress_ptr cinfo)
  163709. {
  163710. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  163711. int i;
  163712. jpeg_component_info *compptr;
  163713. if (cinfo->arith_code) {
  163714. /* Emit arith conditioning info. We may have some duplication
  163715. * if the file has multiple scans, but it's so small it's hardly
  163716. * worth worrying about.
  163717. */
  163718. emit_dac(cinfo);
  163719. } else {
  163720. /* Emit Huffman tables.
  163721. * Note that emit_dht() suppresses any duplicate tables.
  163722. */
  163723. for (i = 0; i < cinfo->comps_in_scan; i++) {
  163724. compptr = cinfo->cur_comp_info[i];
  163725. if (cinfo->progressive_mode) {
  163726. /* Progressive mode: only DC or only AC tables are used in one scan */
  163727. if (cinfo->Ss == 0) {
  163728. if (cinfo->Ah == 0) /* DC needs no table for refinement scan */
  163729. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  163730. } else {
  163731. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  163732. }
  163733. } else {
  163734. /* Sequential mode: need both DC and AC tables */
  163735. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  163736. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  163737. }
  163738. }
  163739. }
  163740. /* Emit DRI if required --- note that DRI value could change for each scan.
  163741. * We avoid wasting space with unnecessary DRIs, however.
  163742. */
  163743. if (cinfo->restart_interval != marker->last_restart_interval) {
  163744. emit_dri(cinfo);
  163745. marker->last_restart_interval = cinfo->restart_interval;
  163746. }
  163747. emit_sos(cinfo);
  163748. }
  163749. /*
  163750. * Write datastream trailer.
  163751. */
  163752. METHODDEF(void)
  163753. write_file_trailer (j_compress_ptr cinfo)
  163754. {
  163755. emit_marker(cinfo, M_EOI);
  163756. }
  163757. /*
  163758. * Write an abbreviated table-specification datastream.
  163759. * This consists of SOI, DQT and DHT tables, and EOI.
  163760. * Any table that is defined and not marked sent_table = TRUE will be
  163761. * emitted. Note that all tables will be marked sent_table = TRUE at exit.
  163762. */
  163763. METHODDEF(void)
  163764. write_tables_only (j_compress_ptr cinfo)
  163765. {
  163766. int i;
  163767. emit_marker(cinfo, M_SOI);
  163768. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  163769. if (cinfo->quant_tbl_ptrs[i] != NULL)
  163770. (void) emit_dqt(cinfo, i);
  163771. }
  163772. if (! cinfo->arith_code) {
  163773. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  163774. if (cinfo->dc_huff_tbl_ptrs[i] != NULL)
  163775. emit_dht(cinfo, i, FALSE);
  163776. if (cinfo->ac_huff_tbl_ptrs[i] != NULL)
  163777. emit_dht(cinfo, i, TRUE);
  163778. }
  163779. }
  163780. emit_marker(cinfo, M_EOI);
  163781. }
  163782. /*
  163783. * Initialize the marker writer module.
  163784. */
  163785. GLOBAL(void)
  163786. jinit_marker_writer (j_compress_ptr cinfo)
  163787. {
  163788. my_marker_ptr marker;
  163789. /* Create the subobject */
  163790. marker = (my_marker_ptr)
  163791. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163792. SIZEOF(my_marker_writer));
  163793. cinfo->marker = (struct jpeg_marker_writer *) marker;
  163794. /* Initialize method pointers */
  163795. marker->pub.write_file_header = write_file_header;
  163796. marker->pub.write_frame_header = write_frame_header;
  163797. marker->pub.write_scan_header = write_scan_header;
  163798. marker->pub.write_file_trailer = write_file_trailer;
  163799. marker->pub.write_tables_only = write_tables_only;
  163800. marker->pub.write_marker_header = write_marker_header;
  163801. marker->pub.write_marker_byte = write_marker_byte;
  163802. /* Initialize private state */
  163803. marker->last_restart_interval = 0;
  163804. }
  163805. /*** End of inlined file: jcmarker.c ***/
  163806. /*** Start of inlined file: jcmaster.c ***/
  163807. #define JPEG_INTERNALS
  163808. /* Private state */
  163809. typedef enum {
  163810. main_pass, /* input data, also do first output step */
  163811. huff_opt_pass, /* Huffman code optimization pass */
  163812. output_pass /* data output pass */
  163813. } c_pass_type;
  163814. typedef struct {
  163815. struct jpeg_comp_master pub; /* public fields */
  163816. c_pass_type pass_type; /* the type of the current pass */
  163817. int pass_number; /* # of passes completed */
  163818. int total_passes; /* total # of passes needed */
  163819. int scan_number; /* current index in scan_info[] */
  163820. } my_comp_master;
  163821. typedef my_comp_master * my_master_ptr;
  163822. /*
  163823. * Support routines that do various essential calculations.
  163824. */
  163825. LOCAL(void)
  163826. initial_setup (j_compress_ptr cinfo)
  163827. /* Do computations that are needed before master selection phase */
  163828. {
  163829. int ci;
  163830. jpeg_component_info *compptr;
  163831. long samplesperrow;
  163832. JDIMENSION jd_samplesperrow;
  163833. /* Sanity check on image dimensions */
  163834. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  163835. || cinfo->num_components <= 0 || cinfo->input_components <= 0)
  163836. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  163837. /* Make sure image isn't bigger than I can handle */
  163838. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  163839. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  163840. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  163841. /* Width of an input scanline must be representable as JDIMENSION. */
  163842. samplesperrow = (long) cinfo->image_width * (long) cinfo->input_components;
  163843. jd_samplesperrow = (JDIMENSION) samplesperrow;
  163844. if ((long) jd_samplesperrow != samplesperrow)
  163845. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  163846. /* For now, precision must match compiled-in value... */
  163847. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  163848. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  163849. /* Check that number of components won't exceed internal array sizes */
  163850. if (cinfo->num_components > MAX_COMPONENTS)
  163851. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  163852. MAX_COMPONENTS);
  163853. /* Compute maximum sampling factors; check factor validity */
  163854. cinfo->max_h_samp_factor = 1;
  163855. cinfo->max_v_samp_factor = 1;
  163856. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163857. ci++, compptr++) {
  163858. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  163859. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  163860. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  163861. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  163862. compptr->h_samp_factor);
  163863. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  163864. compptr->v_samp_factor);
  163865. }
  163866. /* Compute dimensions of components */
  163867. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163868. ci++, compptr++) {
  163869. /* Fill in the correct component_index value; don't rely on application */
  163870. compptr->component_index = ci;
  163871. /* For compression, we never do DCT scaling. */
  163872. compptr->DCT_scaled_size = DCTSIZE;
  163873. /* Size in DCT blocks */
  163874. compptr->width_in_blocks = (JDIMENSION)
  163875. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  163876. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  163877. compptr->height_in_blocks = (JDIMENSION)
  163878. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  163879. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  163880. /* Size in samples */
  163881. compptr->downsampled_width = (JDIMENSION)
  163882. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  163883. (long) cinfo->max_h_samp_factor);
  163884. compptr->downsampled_height = (JDIMENSION)
  163885. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  163886. (long) cinfo->max_v_samp_factor);
  163887. /* Mark component needed (this flag isn't actually used for compression) */
  163888. compptr->component_needed = TRUE;
  163889. }
  163890. /* Compute number of fully interleaved MCU rows (number of times that
  163891. * main controller will call coefficient controller).
  163892. */
  163893. cinfo->total_iMCU_rows = (JDIMENSION)
  163894. jdiv_round_up((long) cinfo->image_height,
  163895. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  163896. }
  163897. #ifdef C_MULTISCAN_FILES_SUPPORTED
  163898. LOCAL(void)
  163899. validate_script (j_compress_ptr cinfo)
  163900. /* Verify that the scan script in cinfo->scan_info[] is valid; also
  163901. * determine whether it uses progressive JPEG, and set cinfo->progressive_mode.
  163902. */
  163903. {
  163904. const jpeg_scan_info * scanptr;
  163905. int scanno, ncomps, ci, coefi, thisi;
  163906. int Ss, Se, Ah, Al;
  163907. boolean component_sent[MAX_COMPONENTS];
  163908. #ifdef C_PROGRESSIVE_SUPPORTED
  163909. int * last_bitpos_ptr;
  163910. int last_bitpos[MAX_COMPONENTS][DCTSIZE2];
  163911. /* -1 until that coefficient has been seen; then last Al for it */
  163912. #endif
  163913. if (cinfo->num_scans <= 0)
  163914. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, 0);
  163915. /* For sequential JPEG, all scans must have Ss=0, Se=DCTSIZE2-1;
  163916. * for progressive JPEG, no scan can have this.
  163917. */
  163918. scanptr = cinfo->scan_info;
  163919. if (scanptr->Ss != 0 || scanptr->Se != DCTSIZE2-1) {
  163920. #ifdef C_PROGRESSIVE_SUPPORTED
  163921. cinfo->progressive_mode = TRUE;
  163922. last_bitpos_ptr = & last_bitpos[0][0];
  163923. for (ci = 0; ci < cinfo->num_components; ci++)
  163924. for (coefi = 0; coefi < DCTSIZE2; coefi++)
  163925. *last_bitpos_ptr++ = -1;
  163926. #else
  163927. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163928. #endif
  163929. } else {
  163930. cinfo->progressive_mode = FALSE;
  163931. for (ci = 0; ci < cinfo->num_components; ci++)
  163932. component_sent[ci] = FALSE;
  163933. }
  163934. for (scanno = 1; scanno <= cinfo->num_scans; scanptr++, scanno++) {
  163935. /* Validate component indexes */
  163936. ncomps = scanptr->comps_in_scan;
  163937. if (ncomps <= 0 || ncomps > MAX_COMPS_IN_SCAN)
  163938. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, ncomps, MAX_COMPS_IN_SCAN);
  163939. for (ci = 0; ci < ncomps; ci++) {
  163940. thisi = scanptr->component_index[ci];
  163941. if (thisi < 0 || thisi >= cinfo->num_components)
  163942. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  163943. /* Components must appear in SOF order within each scan */
  163944. if (ci > 0 && thisi <= scanptr->component_index[ci-1])
  163945. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  163946. }
  163947. /* Validate progression parameters */
  163948. Ss = scanptr->Ss;
  163949. Se = scanptr->Se;
  163950. Ah = scanptr->Ah;
  163951. Al = scanptr->Al;
  163952. if (cinfo->progressive_mode) {
  163953. #ifdef C_PROGRESSIVE_SUPPORTED
  163954. /* The JPEG spec simply gives the ranges 0..13 for Ah and Al, but that
  163955. * seems wrong: the upper bound ought to depend on data precision.
  163956. * Perhaps they really meant 0..N+1 for N-bit precision.
  163957. * Here we allow 0..10 for 8-bit data; Al larger than 10 results in
  163958. * out-of-range reconstructed DC values during the first DC scan,
  163959. * which might cause problems for some decoders.
  163960. */
  163961. #if BITS_IN_JSAMPLE == 8
  163962. #define MAX_AH_AL 10
  163963. #else
  163964. #define MAX_AH_AL 13
  163965. #endif
  163966. if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 ||
  163967. Ah < 0 || Ah > MAX_AH_AL || Al < 0 || Al > MAX_AH_AL)
  163968. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  163969. if (Ss == 0) {
  163970. if (Se != 0) /* DC and AC together not OK */
  163971. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  163972. } else {
  163973. if (ncomps != 1) /* AC scans must be for only one component */
  163974. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  163975. }
  163976. for (ci = 0; ci < ncomps; ci++) {
  163977. last_bitpos_ptr = & last_bitpos[scanptr->component_index[ci]][0];
  163978. if (Ss != 0 && last_bitpos_ptr[0] < 0) /* AC without prior DC scan */
  163979. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  163980. for (coefi = Ss; coefi <= Se; coefi++) {
  163981. if (last_bitpos_ptr[coefi] < 0) {
  163982. /* first scan of this coefficient */
  163983. if (Ah != 0)
  163984. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  163985. } else {
  163986. /* not first scan */
  163987. if (Ah != last_bitpos_ptr[coefi] || Al != Ah-1)
  163988. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  163989. }
  163990. last_bitpos_ptr[coefi] = Al;
  163991. }
  163992. }
  163993. #endif
  163994. } else {
  163995. /* For sequential JPEG, all progression parameters must be these: */
  163996. if (Ss != 0 || Se != DCTSIZE2-1 || Ah != 0 || Al != 0)
  163997. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  163998. /* Make sure components are not sent twice */
  163999. for (ci = 0; ci < ncomps; ci++) {
  164000. thisi = scanptr->component_index[ci];
  164001. if (component_sent[thisi])
  164002. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164003. component_sent[thisi] = TRUE;
  164004. }
  164005. }
  164006. }
  164007. /* Now verify that everything got sent. */
  164008. if (cinfo->progressive_mode) {
  164009. #ifdef C_PROGRESSIVE_SUPPORTED
  164010. /* For progressive mode, we only check that at least some DC data
  164011. * got sent for each component; the spec does not require that all bits
  164012. * of all coefficients be transmitted. Would it be wiser to enforce
  164013. * transmission of all coefficient bits??
  164014. */
  164015. for (ci = 0; ci < cinfo->num_components; ci++) {
  164016. if (last_bitpos[ci][0] < 0)
  164017. ERREXIT(cinfo, JERR_MISSING_DATA);
  164018. }
  164019. #endif
  164020. } else {
  164021. for (ci = 0; ci < cinfo->num_components; ci++) {
  164022. if (! component_sent[ci])
  164023. ERREXIT(cinfo, JERR_MISSING_DATA);
  164024. }
  164025. }
  164026. }
  164027. #endif /* C_MULTISCAN_FILES_SUPPORTED */
  164028. LOCAL(void)
  164029. select_scan_parameters (j_compress_ptr cinfo)
  164030. /* Set up the scan parameters for the current scan */
  164031. {
  164032. int ci;
  164033. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164034. if (cinfo->scan_info != NULL) {
  164035. /* Prepare for current scan --- the script is already validated */
  164036. my_master_ptr master = (my_master_ptr) cinfo->master;
  164037. const jpeg_scan_info * scanptr = cinfo->scan_info + master->scan_number;
  164038. cinfo->comps_in_scan = scanptr->comps_in_scan;
  164039. for (ci = 0; ci < scanptr->comps_in_scan; ci++) {
  164040. cinfo->cur_comp_info[ci] =
  164041. &cinfo->comp_info[scanptr->component_index[ci]];
  164042. }
  164043. cinfo->Ss = scanptr->Ss;
  164044. cinfo->Se = scanptr->Se;
  164045. cinfo->Ah = scanptr->Ah;
  164046. cinfo->Al = scanptr->Al;
  164047. }
  164048. else
  164049. #endif
  164050. {
  164051. /* Prepare for single sequential-JPEG scan containing all components */
  164052. if (cinfo->num_components > MAX_COMPS_IN_SCAN)
  164053. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  164054. MAX_COMPS_IN_SCAN);
  164055. cinfo->comps_in_scan = cinfo->num_components;
  164056. for (ci = 0; ci < cinfo->num_components; ci++) {
  164057. cinfo->cur_comp_info[ci] = &cinfo->comp_info[ci];
  164058. }
  164059. cinfo->Ss = 0;
  164060. cinfo->Se = DCTSIZE2-1;
  164061. cinfo->Ah = 0;
  164062. cinfo->Al = 0;
  164063. }
  164064. }
  164065. LOCAL(void)
  164066. per_scan_setup (j_compress_ptr cinfo)
  164067. /* Do computations that are needed before processing a JPEG scan */
  164068. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] are already set */
  164069. {
  164070. int ci, mcublks, tmp;
  164071. jpeg_component_info *compptr;
  164072. if (cinfo->comps_in_scan == 1) {
  164073. /* Noninterleaved (single-component) scan */
  164074. compptr = cinfo->cur_comp_info[0];
  164075. /* Overall image size in MCUs */
  164076. cinfo->MCUs_per_row = compptr->width_in_blocks;
  164077. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  164078. /* For noninterleaved scan, always one block per MCU */
  164079. compptr->MCU_width = 1;
  164080. compptr->MCU_height = 1;
  164081. compptr->MCU_blocks = 1;
  164082. compptr->MCU_sample_width = DCTSIZE;
  164083. compptr->last_col_width = 1;
  164084. /* For noninterleaved scans, it is convenient to define last_row_height
  164085. * as the number of block rows present in the last iMCU row.
  164086. */
  164087. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  164088. if (tmp == 0) tmp = compptr->v_samp_factor;
  164089. compptr->last_row_height = tmp;
  164090. /* Prepare array describing MCU composition */
  164091. cinfo->blocks_in_MCU = 1;
  164092. cinfo->MCU_membership[0] = 0;
  164093. } else {
  164094. /* Interleaved (multi-component) scan */
  164095. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  164096. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  164097. MAX_COMPS_IN_SCAN);
  164098. /* Overall image size in MCUs */
  164099. cinfo->MCUs_per_row = (JDIMENSION)
  164100. jdiv_round_up((long) cinfo->image_width,
  164101. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  164102. cinfo->MCU_rows_in_scan = (JDIMENSION)
  164103. jdiv_round_up((long) cinfo->image_height,
  164104. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  164105. cinfo->blocks_in_MCU = 0;
  164106. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  164107. compptr = cinfo->cur_comp_info[ci];
  164108. /* Sampling factors give # of blocks of component in each MCU */
  164109. compptr->MCU_width = compptr->h_samp_factor;
  164110. compptr->MCU_height = compptr->v_samp_factor;
  164111. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  164112. compptr->MCU_sample_width = compptr->MCU_width * DCTSIZE;
  164113. /* Figure number of non-dummy blocks in last MCU column & row */
  164114. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  164115. if (tmp == 0) tmp = compptr->MCU_width;
  164116. compptr->last_col_width = tmp;
  164117. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  164118. if (tmp == 0) tmp = compptr->MCU_height;
  164119. compptr->last_row_height = tmp;
  164120. /* Prepare array describing MCU composition */
  164121. mcublks = compptr->MCU_blocks;
  164122. if (cinfo->blocks_in_MCU + mcublks > C_MAX_BLOCKS_IN_MCU)
  164123. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  164124. while (mcublks-- > 0) {
  164125. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  164126. }
  164127. }
  164128. }
  164129. /* Convert restart specified in rows to actual MCU count. */
  164130. /* Note that count must fit in 16 bits, so we provide limiting. */
  164131. if (cinfo->restart_in_rows > 0) {
  164132. long nominal = (long) cinfo->restart_in_rows * (long) cinfo->MCUs_per_row;
  164133. cinfo->restart_interval = (unsigned int) MIN(nominal, 65535L);
  164134. }
  164135. }
  164136. /*
  164137. * Per-pass setup.
  164138. * This is called at the beginning of each pass. We determine which modules
  164139. * will be active during this pass and give them appropriate start_pass calls.
  164140. * We also set is_last_pass to indicate whether any more passes will be
  164141. * required.
  164142. */
  164143. METHODDEF(void)
  164144. prepare_for_pass (j_compress_ptr cinfo)
  164145. {
  164146. my_master_ptr master = (my_master_ptr) cinfo->master;
  164147. switch (master->pass_type) {
  164148. case main_pass:
  164149. /* Initial pass: will collect input data, and do either Huffman
  164150. * optimization or data output for the first scan.
  164151. */
  164152. select_scan_parameters(cinfo);
  164153. per_scan_setup(cinfo);
  164154. if (! cinfo->raw_data_in) {
  164155. (*cinfo->cconvert->start_pass) (cinfo);
  164156. (*cinfo->downsample->start_pass) (cinfo);
  164157. (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU);
  164158. }
  164159. (*cinfo->fdct->start_pass) (cinfo);
  164160. (*cinfo->entropy->start_pass) (cinfo, cinfo->optimize_coding);
  164161. (*cinfo->coef->start_pass) (cinfo,
  164162. (master->total_passes > 1 ?
  164163. JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  164164. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  164165. if (cinfo->optimize_coding) {
  164166. /* No immediate data output; postpone writing frame/scan headers */
  164167. master->pub.call_pass_startup = FALSE;
  164168. } else {
  164169. /* Will write frame/scan headers at first jpeg_write_scanlines call */
  164170. master->pub.call_pass_startup = TRUE;
  164171. }
  164172. break;
  164173. #ifdef ENTROPY_OPT_SUPPORTED
  164174. case huff_opt_pass:
  164175. /* Do Huffman optimization for a scan after the first one. */
  164176. select_scan_parameters(cinfo);
  164177. per_scan_setup(cinfo);
  164178. if (cinfo->Ss != 0 || cinfo->Ah == 0 || cinfo->arith_code) {
  164179. (*cinfo->entropy->start_pass) (cinfo, TRUE);
  164180. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  164181. master->pub.call_pass_startup = FALSE;
  164182. break;
  164183. }
  164184. /* Special case: Huffman DC refinement scans need no Huffman table
  164185. * and therefore we can skip the optimization pass for them.
  164186. */
  164187. master->pass_type = output_pass;
  164188. master->pass_number++;
  164189. /*FALLTHROUGH*/
  164190. #endif
  164191. case output_pass:
  164192. /* Do a data-output pass. */
  164193. /* We need not repeat per-scan setup if prior optimization pass did it. */
  164194. if (! cinfo->optimize_coding) {
  164195. select_scan_parameters(cinfo);
  164196. per_scan_setup(cinfo);
  164197. }
  164198. (*cinfo->entropy->start_pass) (cinfo, FALSE);
  164199. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  164200. /* We emit frame/scan headers now */
  164201. if (master->scan_number == 0)
  164202. (*cinfo->marker->write_frame_header) (cinfo);
  164203. (*cinfo->marker->write_scan_header) (cinfo);
  164204. master->pub.call_pass_startup = FALSE;
  164205. break;
  164206. default:
  164207. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164208. }
  164209. master->pub.is_last_pass = (master->pass_number == master->total_passes-1);
  164210. /* Set up progress monitor's pass info if present */
  164211. if (cinfo->progress != NULL) {
  164212. cinfo->progress->completed_passes = master->pass_number;
  164213. cinfo->progress->total_passes = master->total_passes;
  164214. }
  164215. }
  164216. /*
  164217. * Special start-of-pass hook.
  164218. * This is called by jpeg_write_scanlines if call_pass_startup is TRUE.
  164219. * In single-pass processing, we need this hook because we don't want to
  164220. * write frame/scan headers during jpeg_start_compress; we want to let the
  164221. * application write COM markers etc. between jpeg_start_compress and the
  164222. * jpeg_write_scanlines loop.
  164223. * In multi-pass processing, this routine is not used.
  164224. */
  164225. METHODDEF(void)
  164226. pass_startup (j_compress_ptr cinfo)
  164227. {
  164228. cinfo->master->call_pass_startup = FALSE; /* reset flag so call only once */
  164229. (*cinfo->marker->write_frame_header) (cinfo);
  164230. (*cinfo->marker->write_scan_header) (cinfo);
  164231. }
  164232. /*
  164233. * Finish up at end of pass.
  164234. */
  164235. METHODDEF(void)
  164236. finish_pass_master (j_compress_ptr cinfo)
  164237. {
  164238. my_master_ptr master = (my_master_ptr) cinfo->master;
  164239. /* The entropy coder always needs an end-of-pass call,
  164240. * either to analyze statistics or to flush its output buffer.
  164241. */
  164242. (*cinfo->entropy->finish_pass) (cinfo);
  164243. /* Update state for next pass */
  164244. switch (master->pass_type) {
  164245. case main_pass:
  164246. /* next pass is either output of scan 0 (after optimization)
  164247. * or output of scan 1 (if no optimization).
  164248. */
  164249. master->pass_type = output_pass;
  164250. if (! cinfo->optimize_coding)
  164251. master->scan_number++;
  164252. break;
  164253. case huff_opt_pass:
  164254. /* next pass is always output of current scan */
  164255. master->pass_type = output_pass;
  164256. break;
  164257. case output_pass:
  164258. /* next pass is either optimization or output of next scan */
  164259. if (cinfo->optimize_coding)
  164260. master->pass_type = huff_opt_pass;
  164261. master->scan_number++;
  164262. break;
  164263. }
  164264. master->pass_number++;
  164265. }
  164266. /*
  164267. * Initialize master compression control.
  164268. */
  164269. GLOBAL(void)
  164270. jinit_c_master_control (j_compress_ptr cinfo, boolean transcode_only)
  164271. {
  164272. my_master_ptr master;
  164273. master = (my_master_ptr)
  164274. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164275. SIZEOF(my_comp_master));
  164276. cinfo->master = (struct jpeg_comp_master *) master;
  164277. master->pub.prepare_for_pass = prepare_for_pass;
  164278. master->pub.pass_startup = pass_startup;
  164279. master->pub.finish_pass = finish_pass_master;
  164280. master->pub.is_last_pass = FALSE;
  164281. /* Validate parameters, determine derived values */
  164282. initial_setup(cinfo);
  164283. if (cinfo->scan_info != NULL) {
  164284. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164285. validate_script(cinfo);
  164286. #else
  164287. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164288. #endif
  164289. } else {
  164290. cinfo->progressive_mode = FALSE;
  164291. cinfo->num_scans = 1;
  164292. }
  164293. if (cinfo->progressive_mode) /* TEMPORARY HACK ??? */
  164294. cinfo->optimize_coding = TRUE; /* assume default tables no good for progressive mode */
  164295. /* Initialize my private state */
  164296. if (transcode_only) {
  164297. /* no main pass in transcoding */
  164298. if (cinfo->optimize_coding)
  164299. master->pass_type = huff_opt_pass;
  164300. else
  164301. master->pass_type = output_pass;
  164302. } else {
  164303. /* for normal compression, first pass is always this type: */
  164304. master->pass_type = main_pass;
  164305. }
  164306. master->scan_number = 0;
  164307. master->pass_number = 0;
  164308. if (cinfo->optimize_coding)
  164309. master->total_passes = cinfo->num_scans * 2;
  164310. else
  164311. master->total_passes = cinfo->num_scans;
  164312. }
  164313. /*** End of inlined file: jcmaster.c ***/
  164314. /*** Start of inlined file: jcomapi.c ***/
  164315. #define JPEG_INTERNALS
  164316. /*
  164317. * Abort processing of a JPEG compression or decompression operation,
  164318. * but don't destroy the object itself.
  164319. *
  164320. * For this, we merely clean up all the nonpermanent memory pools.
  164321. * Note that temp files (virtual arrays) are not allowed to belong to
  164322. * the permanent pool, so we will be able to close all temp files here.
  164323. * Closing a data source or destination, if necessary, is the application's
  164324. * responsibility.
  164325. */
  164326. GLOBAL(void)
  164327. jpeg_abort (j_common_ptr cinfo)
  164328. {
  164329. int pool;
  164330. /* Do nothing if called on a not-initialized or destroyed JPEG object. */
  164331. if (cinfo->mem == NULL)
  164332. return;
  164333. /* Releasing pools in reverse order might help avoid fragmentation
  164334. * with some (brain-damaged) malloc libraries.
  164335. */
  164336. for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) {
  164337. (*cinfo->mem->free_pool) (cinfo, pool);
  164338. }
  164339. /* Reset overall state for possible reuse of object */
  164340. if (cinfo->is_decompressor) {
  164341. cinfo->global_state = DSTATE_START;
  164342. /* Try to keep application from accessing now-deleted marker list.
  164343. * A bit kludgy to do it here, but this is the most central place.
  164344. */
  164345. ((j_decompress_ptr) cinfo)->marker_list = NULL;
  164346. } else {
  164347. cinfo->global_state = CSTATE_START;
  164348. }
  164349. }
  164350. /*
  164351. * Destruction of a JPEG object.
  164352. *
  164353. * Everything gets deallocated except the master jpeg_compress_struct itself
  164354. * and the error manager struct. Both of these are supplied by the application
  164355. * and must be freed, if necessary, by the application. (Often they are on
  164356. * the stack and so don't need to be freed anyway.)
  164357. * Closing a data source or destination, if necessary, is the application's
  164358. * responsibility.
  164359. */
  164360. GLOBAL(void)
  164361. jpeg_destroy (j_common_ptr cinfo)
  164362. {
  164363. /* We need only tell the memory manager to release everything. */
  164364. /* NB: mem pointer is NULL if memory mgr failed to initialize. */
  164365. if (cinfo->mem != NULL)
  164366. (*cinfo->mem->self_destruct) (cinfo);
  164367. cinfo->mem = NULL; /* be safe if jpeg_destroy is called twice */
  164368. cinfo->global_state = 0; /* mark it destroyed */
  164369. }
  164370. /*
  164371. * Convenience routines for allocating quantization and Huffman tables.
  164372. * (Would jutils.c be a more reasonable place to put these?)
  164373. */
  164374. GLOBAL(JQUANT_TBL *)
  164375. jpeg_alloc_quant_table (j_common_ptr cinfo)
  164376. {
  164377. JQUANT_TBL *tbl;
  164378. tbl = (JQUANT_TBL *)
  164379. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JQUANT_TBL));
  164380. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  164381. return tbl;
  164382. }
  164383. GLOBAL(JHUFF_TBL *)
  164384. jpeg_alloc_huff_table (j_common_ptr cinfo)
  164385. {
  164386. JHUFF_TBL *tbl;
  164387. tbl = (JHUFF_TBL *)
  164388. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JHUFF_TBL));
  164389. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  164390. return tbl;
  164391. }
  164392. /*** End of inlined file: jcomapi.c ***/
  164393. /*** Start of inlined file: jcparam.c ***/
  164394. #define JPEG_INTERNALS
  164395. /*
  164396. * Quantization table setup routines
  164397. */
  164398. GLOBAL(void)
  164399. jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl,
  164400. const unsigned int *basic_table,
  164401. int scale_factor, boolean force_baseline)
  164402. /* Define a quantization table equal to the basic_table times
  164403. * a scale factor (given as a percentage).
  164404. * If force_baseline is TRUE, the computed quantization table entries
  164405. * are limited to 1..255 for JPEG baseline compatibility.
  164406. */
  164407. {
  164408. JQUANT_TBL ** qtblptr;
  164409. int i;
  164410. long temp;
  164411. /* Safety check to ensure start_compress not called yet. */
  164412. if (cinfo->global_state != CSTATE_START)
  164413. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164414. if (which_tbl < 0 || which_tbl >= NUM_QUANT_TBLS)
  164415. ERREXIT1(cinfo, JERR_DQT_INDEX, which_tbl);
  164416. qtblptr = & cinfo->quant_tbl_ptrs[which_tbl];
  164417. if (*qtblptr == NULL)
  164418. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  164419. for (i = 0; i < DCTSIZE2; i++) {
  164420. temp = ((long) basic_table[i] * scale_factor + 50L) / 100L;
  164421. /* limit the values to the valid range */
  164422. if (temp <= 0L) temp = 1L;
  164423. if (temp > 32767L) temp = 32767L; /* max quantizer needed for 12 bits */
  164424. if (force_baseline && temp > 255L)
  164425. temp = 255L; /* limit to baseline range if requested */
  164426. (*qtblptr)->quantval[i] = (UINT16) temp;
  164427. }
  164428. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  164429. (*qtblptr)->sent_table = FALSE;
  164430. }
  164431. GLOBAL(void)
  164432. jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor,
  164433. boolean force_baseline)
  164434. /* Set or change the 'quality' (quantization) setting, using default tables
  164435. * and a straight percentage-scaling quality scale. In most cases it's better
  164436. * to use jpeg_set_quality (below); this entry point is provided for
  164437. * applications that insist on a linear percentage scaling.
  164438. */
  164439. {
  164440. /* These are the sample quantization tables given in JPEG spec section K.1.
  164441. * The spec says that the values given produce "good" quality, and
  164442. * when divided by 2, "very good" quality.
  164443. */
  164444. static const unsigned int std_luminance_quant_tbl[DCTSIZE2] = {
  164445. 16, 11, 10, 16, 24, 40, 51, 61,
  164446. 12, 12, 14, 19, 26, 58, 60, 55,
  164447. 14, 13, 16, 24, 40, 57, 69, 56,
  164448. 14, 17, 22, 29, 51, 87, 80, 62,
  164449. 18, 22, 37, 56, 68, 109, 103, 77,
  164450. 24, 35, 55, 64, 81, 104, 113, 92,
  164451. 49, 64, 78, 87, 103, 121, 120, 101,
  164452. 72, 92, 95, 98, 112, 100, 103, 99
  164453. };
  164454. static const unsigned int std_chrominance_quant_tbl[DCTSIZE2] = {
  164455. 17, 18, 24, 47, 99, 99, 99, 99,
  164456. 18, 21, 26, 66, 99, 99, 99, 99,
  164457. 24, 26, 56, 99, 99, 99, 99, 99,
  164458. 47, 66, 99, 99, 99, 99, 99, 99,
  164459. 99, 99, 99, 99, 99, 99, 99, 99,
  164460. 99, 99, 99, 99, 99, 99, 99, 99,
  164461. 99, 99, 99, 99, 99, 99, 99, 99,
  164462. 99, 99, 99, 99, 99, 99, 99, 99
  164463. };
  164464. /* Set up two quantization tables using the specified scaling */
  164465. jpeg_add_quant_table(cinfo, 0, std_luminance_quant_tbl,
  164466. scale_factor, force_baseline);
  164467. jpeg_add_quant_table(cinfo, 1, std_chrominance_quant_tbl,
  164468. scale_factor, force_baseline);
  164469. }
  164470. GLOBAL(int)
  164471. jpeg_quality_scaling (int quality)
  164472. /* Convert a user-specified quality rating to a percentage scaling factor
  164473. * for an underlying quantization table, using our recommended scaling curve.
  164474. * The input 'quality' factor should be 0 (terrible) to 100 (very good).
  164475. */
  164476. {
  164477. /* Safety limit on quality factor. Convert 0 to 1 to avoid zero divide. */
  164478. if (quality <= 0) quality = 1;
  164479. if (quality > 100) quality = 100;
  164480. /* The basic table is used as-is (scaling 100) for a quality of 50.
  164481. * Qualities 50..100 are converted to scaling percentage 200 - 2*Q;
  164482. * note that at Q=100 the scaling is 0, which will cause jpeg_add_quant_table
  164483. * to make all the table entries 1 (hence, minimum quantization loss).
  164484. * Qualities 1..50 are converted to scaling percentage 5000/Q.
  164485. */
  164486. if (quality < 50)
  164487. quality = 5000 / quality;
  164488. else
  164489. quality = 200 - quality*2;
  164490. return quality;
  164491. }
  164492. GLOBAL(void)
  164493. jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline)
  164494. /* Set or change the 'quality' (quantization) setting, using default tables.
  164495. * This is the standard quality-adjusting entry point for typical user
  164496. * interfaces; only those who want detailed control over quantization tables
  164497. * would use the preceding three routines directly.
  164498. */
  164499. {
  164500. /* Convert user 0-100 rating to percentage scaling */
  164501. quality = jpeg_quality_scaling(quality);
  164502. /* Set up standard quality tables */
  164503. jpeg_set_linear_quality(cinfo, quality, force_baseline);
  164504. }
  164505. /*
  164506. * Huffman table setup routines
  164507. */
  164508. LOCAL(void)
  164509. add_huff_table (j_compress_ptr cinfo,
  164510. JHUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val)
  164511. /* Define a Huffman table */
  164512. {
  164513. int nsymbols, len;
  164514. if (*htblptr == NULL)
  164515. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  164516. /* Copy the number-of-symbols-of-each-code-length counts */
  164517. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  164518. /* Validate the counts. We do this here mainly so we can copy the right
  164519. * number of symbols from the val[] array, without risking marching off
  164520. * the end of memory. jchuff.c will do a more thorough test later.
  164521. */
  164522. nsymbols = 0;
  164523. for (len = 1; len <= 16; len++)
  164524. nsymbols += bits[len];
  164525. if (nsymbols < 1 || nsymbols > 256)
  164526. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  164527. MEMCOPY((*htblptr)->huffval, val, nsymbols * SIZEOF(UINT8));
  164528. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  164529. (*htblptr)->sent_table = FALSE;
  164530. }
  164531. LOCAL(void)
  164532. std_huff_tables (j_compress_ptr cinfo)
  164533. /* Set up the standard Huffman tables (cf. JPEG standard section K.3) */
  164534. /* IMPORTANT: these are only valid for 8-bit data precision! */
  164535. {
  164536. static const UINT8 bits_dc_luminance[17] =
  164537. { /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 };
  164538. static const UINT8 val_dc_luminance[] =
  164539. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  164540. static const UINT8 bits_dc_chrominance[17] =
  164541. { /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
  164542. static const UINT8 val_dc_chrominance[] =
  164543. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  164544. static const UINT8 bits_ac_luminance[17] =
  164545. { /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d };
  164546. static const UINT8 val_ac_luminance[] =
  164547. { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
  164548. 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
  164549. 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
  164550. 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
  164551. 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
  164552. 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
  164553. 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
  164554. 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
  164555. 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
  164556. 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
  164557. 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
  164558. 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
  164559. 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
  164560. 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
  164561. 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
  164562. 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
  164563. 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
  164564. 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
  164565. 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
  164566. 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  164567. 0xf9, 0xfa };
  164568. static const UINT8 bits_ac_chrominance[17] =
  164569. { /* 0-base */ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 };
  164570. static const UINT8 val_ac_chrominance[] =
  164571. { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
  164572. 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
  164573. 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
  164574. 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
  164575. 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
  164576. 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
  164577. 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
  164578. 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
  164579. 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
  164580. 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
  164581. 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
  164582. 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
  164583. 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
  164584. 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
  164585. 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
  164586. 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
  164587. 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
  164588. 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
  164589. 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
  164590. 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  164591. 0xf9, 0xfa };
  164592. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[0],
  164593. bits_dc_luminance, val_dc_luminance);
  164594. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[0],
  164595. bits_ac_luminance, val_ac_luminance);
  164596. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[1],
  164597. bits_dc_chrominance, val_dc_chrominance);
  164598. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[1],
  164599. bits_ac_chrominance, val_ac_chrominance);
  164600. }
  164601. /*
  164602. * Default parameter setup for compression.
  164603. *
  164604. * Applications that don't choose to use this routine must do their
  164605. * own setup of all these parameters. Alternately, you can call this
  164606. * to establish defaults and then alter parameters selectively. This
  164607. * is the recommended approach since, if we add any new parameters,
  164608. * your code will still work (they'll be set to reasonable defaults).
  164609. */
  164610. GLOBAL(void)
  164611. jpeg_set_defaults (j_compress_ptr cinfo)
  164612. {
  164613. int i;
  164614. /* Safety check to ensure start_compress not called yet. */
  164615. if (cinfo->global_state != CSTATE_START)
  164616. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164617. /* Allocate comp_info array large enough for maximum component count.
  164618. * Array is made permanent in case application wants to compress
  164619. * multiple images at same param settings.
  164620. */
  164621. if (cinfo->comp_info == NULL)
  164622. cinfo->comp_info = (jpeg_component_info *)
  164623. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  164624. MAX_COMPONENTS * SIZEOF(jpeg_component_info));
  164625. /* Initialize everything not dependent on the color space */
  164626. cinfo->data_precision = BITS_IN_JSAMPLE;
  164627. /* Set up two quantization tables using default quality of 75 */
  164628. jpeg_set_quality(cinfo, 75, TRUE);
  164629. /* Set up two Huffman tables */
  164630. std_huff_tables(cinfo);
  164631. /* Initialize default arithmetic coding conditioning */
  164632. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  164633. cinfo->arith_dc_L[i] = 0;
  164634. cinfo->arith_dc_U[i] = 1;
  164635. cinfo->arith_ac_K[i] = 5;
  164636. }
  164637. /* Default is no multiple-scan output */
  164638. cinfo->scan_info = NULL;
  164639. cinfo->num_scans = 0;
  164640. /* Expect normal source image, not raw downsampled data */
  164641. cinfo->raw_data_in = FALSE;
  164642. /* Use Huffman coding, not arithmetic coding, by default */
  164643. cinfo->arith_code = FALSE;
  164644. /* By default, don't do extra passes to optimize entropy coding */
  164645. cinfo->optimize_coding = FALSE;
  164646. /* The standard Huffman tables are only valid for 8-bit data precision.
  164647. * If the precision is higher, force optimization on so that usable
  164648. * tables will be computed. This test can be removed if default tables
  164649. * are supplied that are valid for the desired precision.
  164650. */
  164651. if (cinfo->data_precision > 8)
  164652. cinfo->optimize_coding = TRUE;
  164653. /* By default, use the simpler non-cosited sampling alignment */
  164654. cinfo->CCIR601_sampling = FALSE;
  164655. /* No input smoothing */
  164656. cinfo->smoothing_factor = 0;
  164657. /* DCT algorithm preference */
  164658. cinfo->dct_method = JDCT_DEFAULT;
  164659. /* No restart markers */
  164660. cinfo->restart_interval = 0;
  164661. cinfo->restart_in_rows = 0;
  164662. /* Fill in default JFIF marker parameters. Note that whether the marker
  164663. * will actually be written is determined by jpeg_set_colorspace.
  164664. *
  164665. * By default, the library emits JFIF version code 1.01.
  164666. * An application that wants to emit JFIF 1.02 extension markers should set
  164667. * JFIF_minor_version to 2. We could probably get away with just defaulting
  164668. * to 1.02, but there may still be some decoders in use that will complain
  164669. * about that; saying 1.01 should minimize compatibility problems.
  164670. */
  164671. cinfo->JFIF_major_version = 1; /* Default JFIF version = 1.01 */
  164672. cinfo->JFIF_minor_version = 1;
  164673. cinfo->density_unit = 0; /* Pixel size is unknown by default */
  164674. cinfo->X_density = 1; /* Pixel aspect ratio is square by default */
  164675. cinfo->Y_density = 1;
  164676. /* Choose JPEG colorspace based on input space, set defaults accordingly */
  164677. jpeg_default_colorspace(cinfo);
  164678. }
  164679. /*
  164680. * Select an appropriate JPEG colorspace for in_color_space.
  164681. */
  164682. GLOBAL(void)
  164683. jpeg_default_colorspace (j_compress_ptr cinfo)
  164684. {
  164685. switch (cinfo->in_color_space) {
  164686. case JCS_GRAYSCALE:
  164687. jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
  164688. break;
  164689. case JCS_RGB:
  164690. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  164691. break;
  164692. case JCS_YCbCr:
  164693. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  164694. break;
  164695. case JCS_CMYK:
  164696. jpeg_set_colorspace(cinfo, JCS_CMYK); /* By default, no translation */
  164697. break;
  164698. case JCS_YCCK:
  164699. jpeg_set_colorspace(cinfo, JCS_YCCK);
  164700. break;
  164701. case JCS_UNKNOWN:
  164702. jpeg_set_colorspace(cinfo, JCS_UNKNOWN);
  164703. break;
  164704. default:
  164705. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  164706. }
  164707. }
  164708. /*
  164709. * Set the JPEG colorspace, and choose colorspace-dependent default values.
  164710. */
  164711. GLOBAL(void)
  164712. jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace)
  164713. {
  164714. jpeg_component_info * compptr;
  164715. int ci;
  164716. #define SET_COMP(index,id,hsamp,vsamp,quant,dctbl,actbl) \
  164717. (compptr = &cinfo->comp_info[index], \
  164718. compptr->component_id = (id), \
  164719. compptr->h_samp_factor = (hsamp), \
  164720. compptr->v_samp_factor = (vsamp), \
  164721. compptr->quant_tbl_no = (quant), \
  164722. compptr->dc_tbl_no = (dctbl), \
  164723. compptr->ac_tbl_no = (actbl) )
  164724. /* Safety check to ensure start_compress not called yet. */
  164725. if (cinfo->global_state != CSTATE_START)
  164726. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164727. /* For all colorspaces, we use Q and Huff tables 0 for luminance components,
  164728. * tables 1 for chrominance components.
  164729. */
  164730. cinfo->jpeg_color_space = colorspace;
  164731. cinfo->write_JFIF_header = FALSE; /* No marker for non-JFIF colorspaces */
  164732. cinfo->write_Adobe_marker = FALSE; /* write no Adobe marker by default */
  164733. switch (colorspace) {
  164734. case JCS_GRAYSCALE:
  164735. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  164736. cinfo->num_components = 1;
  164737. /* JFIF specifies component ID 1 */
  164738. SET_COMP(0, 1, 1,1, 0, 0,0);
  164739. break;
  164740. case JCS_RGB:
  164741. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag RGB */
  164742. cinfo->num_components = 3;
  164743. SET_COMP(0, 0x52 /* 'R' */, 1,1, 0, 0,0);
  164744. SET_COMP(1, 0x47 /* 'G' */, 1,1, 0, 0,0);
  164745. SET_COMP(2, 0x42 /* 'B' */, 1,1, 0, 0,0);
  164746. break;
  164747. case JCS_YCbCr:
  164748. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  164749. cinfo->num_components = 3;
  164750. /* JFIF specifies component IDs 1,2,3 */
  164751. /* We default to 2x2 subsamples of chrominance */
  164752. SET_COMP(0, 1, 2,2, 0, 0,0);
  164753. SET_COMP(1, 2, 1,1, 1, 1,1);
  164754. SET_COMP(2, 3, 1,1, 1, 1,1);
  164755. break;
  164756. case JCS_CMYK:
  164757. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag CMYK */
  164758. cinfo->num_components = 4;
  164759. SET_COMP(0, 0x43 /* 'C' */, 1,1, 0, 0,0);
  164760. SET_COMP(1, 0x4D /* 'M' */, 1,1, 0, 0,0);
  164761. SET_COMP(2, 0x59 /* 'Y' */, 1,1, 0, 0,0);
  164762. SET_COMP(3, 0x4B /* 'K' */, 1,1, 0, 0,0);
  164763. break;
  164764. case JCS_YCCK:
  164765. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag YCCK */
  164766. cinfo->num_components = 4;
  164767. SET_COMP(0, 1, 2,2, 0, 0,0);
  164768. SET_COMP(1, 2, 1,1, 1, 1,1);
  164769. SET_COMP(2, 3, 1,1, 1, 1,1);
  164770. SET_COMP(3, 4, 2,2, 0, 0,0);
  164771. break;
  164772. case JCS_UNKNOWN:
  164773. cinfo->num_components = cinfo->input_components;
  164774. if (cinfo->num_components < 1 || cinfo->num_components > MAX_COMPONENTS)
  164775. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  164776. MAX_COMPONENTS);
  164777. for (ci = 0; ci < cinfo->num_components; ci++) {
  164778. SET_COMP(ci, ci, 1,1, 0, 0,0);
  164779. }
  164780. break;
  164781. default:
  164782. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  164783. }
  164784. }
  164785. #ifdef C_PROGRESSIVE_SUPPORTED
  164786. LOCAL(jpeg_scan_info *)
  164787. fill_a_scan (jpeg_scan_info * scanptr, int ci,
  164788. int Ss, int Se, int Ah, int Al)
  164789. /* Support routine: generate one scan for specified component */
  164790. {
  164791. scanptr->comps_in_scan = 1;
  164792. scanptr->component_index[0] = ci;
  164793. scanptr->Ss = Ss;
  164794. scanptr->Se = Se;
  164795. scanptr->Ah = Ah;
  164796. scanptr->Al = Al;
  164797. scanptr++;
  164798. return scanptr;
  164799. }
  164800. LOCAL(jpeg_scan_info *)
  164801. fill_scans (jpeg_scan_info * scanptr, int ncomps,
  164802. int Ss, int Se, int Ah, int Al)
  164803. /* Support routine: generate one scan for each component */
  164804. {
  164805. int ci;
  164806. for (ci = 0; ci < ncomps; ci++) {
  164807. scanptr->comps_in_scan = 1;
  164808. scanptr->component_index[0] = ci;
  164809. scanptr->Ss = Ss;
  164810. scanptr->Se = Se;
  164811. scanptr->Ah = Ah;
  164812. scanptr->Al = Al;
  164813. scanptr++;
  164814. }
  164815. return scanptr;
  164816. }
  164817. LOCAL(jpeg_scan_info *)
  164818. fill_dc_scans (jpeg_scan_info * scanptr, int ncomps, int Ah, int Al)
  164819. /* Support routine: generate interleaved DC scan if possible, else N scans */
  164820. {
  164821. int ci;
  164822. if (ncomps <= MAX_COMPS_IN_SCAN) {
  164823. /* Single interleaved DC scan */
  164824. scanptr->comps_in_scan = ncomps;
  164825. for (ci = 0; ci < ncomps; ci++)
  164826. scanptr->component_index[ci] = ci;
  164827. scanptr->Ss = scanptr->Se = 0;
  164828. scanptr->Ah = Ah;
  164829. scanptr->Al = Al;
  164830. scanptr++;
  164831. } else {
  164832. /* Noninterleaved DC scan for each component */
  164833. scanptr = fill_scans(scanptr, ncomps, 0, 0, Ah, Al);
  164834. }
  164835. return scanptr;
  164836. }
  164837. /*
  164838. * Create a recommended progressive-JPEG script.
  164839. * cinfo->num_components and cinfo->jpeg_color_space must be correct.
  164840. */
  164841. GLOBAL(void)
  164842. jpeg_simple_progression (j_compress_ptr cinfo)
  164843. {
  164844. int ncomps = cinfo->num_components;
  164845. int nscans;
  164846. jpeg_scan_info * scanptr;
  164847. /* Safety check to ensure start_compress not called yet. */
  164848. if (cinfo->global_state != CSTATE_START)
  164849. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164850. /* Figure space needed for script. Calculation must match code below! */
  164851. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  164852. /* Custom script for YCbCr color images. */
  164853. nscans = 10;
  164854. } else {
  164855. /* All-purpose script for other color spaces. */
  164856. if (ncomps > MAX_COMPS_IN_SCAN)
  164857. nscans = 6 * ncomps; /* 2 DC + 4 AC scans per component */
  164858. else
  164859. nscans = 2 + 4 * ncomps; /* 2 DC scans; 4 AC scans per component */
  164860. }
  164861. /* Allocate space for script.
  164862. * We need to put it in the permanent pool in case the application performs
  164863. * multiple compressions without changing the settings. To avoid a memory
  164864. * leak if jpeg_simple_progression is called repeatedly for the same JPEG
  164865. * object, we try to re-use previously allocated space, and we allocate
  164866. * enough space to handle YCbCr even if initially asked for grayscale.
  164867. */
  164868. if (cinfo->script_space == NULL || cinfo->script_space_size < nscans) {
  164869. cinfo->script_space_size = MAX(nscans, 10);
  164870. cinfo->script_space = (jpeg_scan_info *)
  164871. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  164872. cinfo->script_space_size * SIZEOF(jpeg_scan_info));
  164873. }
  164874. scanptr = cinfo->script_space;
  164875. cinfo->scan_info = scanptr;
  164876. cinfo->num_scans = nscans;
  164877. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  164878. /* Custom script for YCbCr color images. */
  164879. /* Initial DC scan */
  164880. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  164881. /* Initial AC scan: get some luma data out in a hurry */
  164882. scanptr = fill_a_scan(scanptr, 0, 1, 5, 0, 2);
  164883. /* Chroma data is too small to be worth expending many scans on */
  164884. scanptr = fill_a_scan(scanptr, 2, 1, 63, 0, 1);
  164885. scanptr = fill_a_scan(scanptr, 1, 1, 63, 0, 1);
  164886. /* Complete spectral selection for luma AC */
  164887. scanptr = fill_a_scan(scanptr, 0, 6, 63, 0, 2);
  164888. /* Refine next bit of luma AC */
  164889. scanptr = fill_a_scan(scanptr, 0, 1, 63, 2, 1);
  164890. /* Finish DC successive approximation */
  164891. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  164892. /* Finish AC successive approximation */
  164893. scanptr = fill_a_scan(scanptr, 2, 1, 63, 1, 0);
  164894. scanptr = fill_a_scan(scanptr, 1, 1, 63, 1, 0);
  164895. /* Luma bottom bit comes last since it's usually largest scan */
  164896. scanptr = fill_a_scan(scanptr, 0, 1, 63, 1, 0);
  164897. } else {
  164898. /* All-purpose script for other color spaces. */
  164899. /* Successive approximation first pass */
  164900. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  164901. scanptr = fill_scans(scanptr, ncomps, 1, 5, 0, 2);
  164902. scanptr = fill_scans(scanptr, ncomps, 6, 63, 0, 2);
  164903. /* Successive approximation second pass */
  164904. scanptr = fill_scans(scanptr, ncomps, 1, 63, 2, 1);
  164905. /* Successive approximation final pass */
  164906. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  164907. scanptr = fill_scans(scanptr, ncomps, 1, 63, 1, 0);
  164908. }
  164909. }
  164910. #endif /* C_PROGRESSIVE_SUPPORTED */
  164911. /*** End of inlined file: jcparam.c ***/
  164912. /*** Start of inlined file: jcphuff.c ***/
  164913. #define JPEG_INTERNALS
  164914. #ifdef C_PROGRESSIVE_SUPPORTED
  164915. /* Expanded entropy encoder object for progressive Huffman encoding. */
  164916. typedef struct {
  164917. struct jpeg_entropy_encoder pub; /* public fields */
  164918. /* Mode flag: TRUE for optimization, FALSE for actual data output */
  164919. boolean gather_statistics;
  164920. /* Bit-level coding status.
  164921. * next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
  164922. */
  164923. JOCTET * next_output_byte; /* => next byte to write in buffer */
  164924. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  164925. INT32 put_buffer; /* current bit-accumulation buffer */
  164926. int put_bits; /* # of bits now in it */
  164927. j_compress_ptr cinfo; /* link to cinfo (needed for dump_buffer) */
  164928. /* Coding status for DC components */
  164929. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  164930. /* Coding status for AC components */
  164931. int ac_tbl_no; /* the table number of the single component */
  164932. unsigned int EOBRUN; /* run length of EOBs */
  164933. unsigned int BE; /* # of buffered correction bits before MCU */
  164934. char * bit_buffer; /* buffer for correction bits (1 per char) */
  164935. /* packing correction bits tightly would save some space but cost time... */
  164936. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  164937. int next_restart_num; /* next restart number to write (0-7) */
  164938. /* Pointers to derived tables (these workspaces have image lifespan).
  164939. * Since any one scan codes only DC or only AC, we only need one set
  164940. * of tables, not one for DC and one for AC.
  164941. */
  164942. c_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  164943. /* Statistics tables for optimization; again, one set is enough */
  164944. long * count_ptrs[NUM_HUFF_TBLS];
  164945. } phuff_entropy_encoder;
  164946. typedef phuff_entropy_encoder * phuff_entropy_ptr;
  164947. /* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
  164948. * buffer can hold. Larger sizes may slightly improve compression, but
  164949. * 1000 is already well into the realm of overkill.
  164950. * The minimum safe size is 64 bits.
  164951. */
  164952. #define MAX_CORR_BITS 1000 /* Max # of correction bits I can buffer */
  164953. /* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
  164954. * We assume that int right shift is unsigned if INT32 right shift is,
  164955. * which should be safe.
  164956. */
  164957. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  164958. #define ISHIFT_TEMPS int ishift_temp;
  164959. #define IRIGHT_SHIFT(x,shft) \
  164960. ((ishift_temp = (x)) < 0 ? \
  164961. (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
  164962. (ishift_temp >> (shft)))
  164963. #else
  164964. #define ISHIFT_TEMPS
  164965. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  164966. #endif
  164967. /* Forward declarations */
  164968. METHODDEF(boolean) encode_mcu_DC_first JPP((j_compress_ptr cinfo,
  164969. JBLOCKROW *MCU_data));
  164970. METHODDEF(boolean) encode_mcu_AC_first JPP((j_compress_ptr cinfo,
  164971. JBLOCKROW *MCU_data));
  164972. METHODDEF(boolean) encode_mcu_DC_refine JPP((j_compress_ptr cinfo,
  164973. JBLOCKROW *MCU_data));
  164974. METHODDEF(boolean) encode_mcu_AC_refine JPP((j_compress_ptr cinfo,
  164975. JBLOCKROW *MCU_data));
  164976. METHODDEF(void) finish_pass_phuff JPP((j_compress_ptr cinfo));
  164977. METHODDEF(void) finish_pass_gather_phuff JPP((j_compress_ptr cinfo));
  164978. /*
  164979. * Initialize for a Huffman-compressed scan using progressive JPEG.
  164980. */
  164981. METHODDEF(void)
  164982. start_pass_phuff (j_compress_ptr cinfo, boolean gather_statistics)
  164983. {
  164984. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  164985. boolean is_DC_band;
  164986. int ci, tbl;
  164987. jpeg_component_info * compptr;
  164988. entropy->cinfo = cinfo;
  164989. entropy->gather_statistics = gather_statistics;
  164990. is_DC_band = (cinfo->Ss == 0);
  164991. /* We assume jcmaster.c already validated the scan parameters. */
  164992. /* Select execution routines */
  164993. if (cinfo->Ah == 0) {
  164994. if (is_DC_band)
  164995. entropy->pub.encode_mcu = encode_mcu_DC_first;
  164996. else
  164997. entropy->pub.encode_mcu = encode_mcu_AC_first;
  164998. } else {
  164999. if (is_DC_band)
  165000. entropy->pub.encode_mcu = encode_mcu_DC_refine;
  165001. else {
  165002. entropy->pub.encode_mcu = encode_mcu_AC_refine;
  165003. /* AC refinement needs a correction bit buffer */
  165004. if (entropy->bit_buffer == NULL)
  165005. entropy->bit_buffer = (char *)
  165006. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165007. MAX_CORR_BITS * SIZEOF(char));
  165008. }
  165009. }
  165010. if (gather_statistics)
  165011. entropy->pub.finish_pass = finish_pass_gather_phuff;
  165012. else
  165013. entropy->pub.finish_pass = finish_pass_phuff;
  165014. /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1
  165015. * for AC coefficients.
  165016. */
  165017. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165018. compptr = cinfo->cur_comp_info[ci];
  165019. /* Initialize DC predictions to 0 */
  165020. entropy->last_dc_val[ci] = 0;
  165021. /* Get table index */
  165022. if (is_DC_band) {
  165023. if (cinfo->Ah != 0) /* DC refinement needs no table */
  165024. continue;
  165025. tbl = compptr->dc_tbl_no;
  165026. } else {
  165027. entropy->ac_tbl_no = tbl = compptr->ac_tbl_no;
  165028. }
  165029. if (gather_statistics) {
  165030. /* Check for invalid table index */
  165031. /* (make_c_derived_tbl does this in the other path) */
  165032. if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
  165033. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
  165034. /* Allocate and zero the statistics tables */
  165035. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  165036. if (entropy->count_ptrs[tbl] == NULL)
  165037. entropy->count_ptrs[tbl] = (long *)
  165038. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165039. 257 * SIZEOF(long));
  165040. MEMZERO(entropy->count_ptrs[tbl], 257 * SIZEOF(long));
  165041. } else {
  165042. /* Compute derived values for Huffman table */
  165043. /* We may do this more than once for a table, but it's not expensive */
  165044. jpeg_make_c_derived_tbl(cinfo, is_DC_band, tbl,
  165045. & entropy->derived_tbls[tbl]);
  165046. }
  165047. }
  165048. /* Initialize AC stuff */
  165049. entropy->EOBRUN = 0;
  165050. entropy->BE = 0;
  165051. /* Initialize bit buffer to empty */
  165052. entropy->put_buffer = 0;
  165053. entropy->put_bits = 0;
  165054. /* Initialize restart stuff */
  165055. entropy->restarts_to_go = cinfo->restart_interval;
  165056. entropy->next_restart_num = 0;
  165057. }
  165058. /* Outputting bytes to the file.
  165059. * NB: these must be called only when actually outputting,
  165060. * that is, entropy->gather_statistics == FALSE.
  165061. */
  165062. /* Emit a byte */
  165063. #define emit_byte(entropy,val) \
  165064. { *(entropy)->next_output_byte++ = (JOCTET) (val); \
  165065. if (--(entropy)->free_in_buffer == 0) \
  165066. dump_buffer_p(entropy); }
  165067. LOCAL(void)
  165068. dump_buffer_p (phuff_entropy_ptr entropy)
  165069. /* Empty the output buffer; we do not support suspension in this module. */
  165070. {
  165071. struct jpeg_destination_mgr * dest = entropy->cinfo->dest;
  165072. if (! (*dest->empty_output_buffer) (entropy->cinfo))
  165073. ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
  165074. /* After a successful buffer dump, must reset buffer pointers */
  165075. entropy->next_output_byte = dest->next_output_byte;
  165076. entropy->free_in_buffer = dest->free_in_buffer;
  165077. }
  165078. /* Outputting bits to the file */
  165079. /* Only the right 24 bits of put_buffer are used; the valid bits are
  165080. * left-justified in this part. At most 16 bits can be passed to emit_bits
  165081. * in one call, and we never retain more than 7 bits in put_buffer
  165082. * between calls, so 24 bits are sufficient.
  165083. */
  165084. INLINE
  165085. LOCAL(void)
  165086. emit_bits_p (phuff_entropy_ptr entropy, unsigned int code, int size)
  165087. /* Emit some bits, unless we are in gather mode */
  165088. {
  165089. /* This routine is heavily used, so it's worth coding tightly. */
  165090. register INT32 put_buffer = (INT32) code;
  165091. register int put_bits = entropy->put_bits;
  165092. /* if size is 0, caller used an invalid Huffman table entry */
  165093. if (size == 0)
  165094. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  165095. if (entropy->gather_statistics)
  165096. return; /* do nothing if we're only getting stats */
  165097. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  165098. put_bits += size; /* new number of bits in buffer */
  165099. put_buffer <<= 24 - put_bits; /* align incoming bits */
  165100. put_buffer |= entropy->put_buffer; /* and merge with old buffer contents */
  165101. while (put_bits >= 8) {
  165102. int c = (int) ((put_buffer >> 16) & 0xFF);
  165103. emit_byte(entropy, c);
  165104. if (c == 0xFF) { /* need to stuff a zero byte? */
  165105. emit_byte(entropy, 0);
  165106. }
  165107. put_buffer <<= 8;
  165108. put_bits -= 8;
  165109. }
  165110. entropy->put_buffer = put_buffer; /* update variables */
  165111. entropy->put_bits = put_bits;
  165112. }
  165113. LOCAL(void)
  165114. flush_bits_p (phuff_entropy_ptr entropy)
  165115. {
  165116. emit_bits_p(entropy, 0x7F, 7); /* fill any partial byte with ones */
  165117. entropy->put_buffer = 0; /* and reset bit-buffer to empty */
  165118. entropy->put_bits = 0;
  165119. }
  165120. /*
  165121. * Emit (or just count) a Huffman symbol.
  165122. */
  165123. INLINE
  165124. LOCAL(void)
  165125. emit_symbol (phuff_entropy_ptr entropy, int tbl_no, int symbol)
  165126. {
  165127. if (entropy->gather_statistics)
  165128. entropy->count_ptrs[tbl_no][symbol]++;
  165129. else {
  165130. c_derived_tbl * tbl = entropy->derived_tbls[tbl_no];
  165131. emit_bits_p(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
  165132. }
  165133. }
  165134. /*
  165135. * Emit bits from a correction bit buffer.
  165136. */
  165137. LOCAL(void)
  165138. emit_buffered_bits (phuff_entropy_ptr entropy, char * bufstart,
  165139. unsigned int nbits)
  165140. {
  165141. if (entropy->gather_statistics)
  165142. return; /* no real work */
  165143. while (nbits > 0) {
  165144. emit_bits_p(entropy, (unsigned int) (*bufstart), 1);
  165145. bufstart++;
  165146. nbits--;
  165147. }
  165148. }
  165149. /*
  165150. * Emit any pending EOBRUN symbol.
  165151. */
  165152. LOCAL(void)
  165153. emit_eobrun (phuff_entropy_ptr entropy)
  165154. {
  165155. register int temp, nbits;
  165156. if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */
  165157. temp = entropy->EOBRUN;
  165158. nbits = 0;
  165159. while ((temp >>= 1))
  165160. nbits++;
  165161. /* safety check: shouldn't happen given limited correction-bit buffer */
  165162. if (nbits > 14)
  165163. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  165164. emit_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
  165165. if (nbits)
  165166. emit_bits_p(entropy, entropy->EOBRUN, nbits);
  165167. entropy->EOBRUN = 0;
  165168. /* Emit any buffered correction bits */
  165169. emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
  165170. entropy->BE = 0;
  165171. }
  165172. }
  165173. /*
  165174. * Emit a restart marker & resynchronize predictions.
  165175. */
  165176. LOCAL(void)
  165177. emit_restart_p (phuff_entropy_ptr entropy, int restart_num)
  165178. {
  165179. int ci;
  165180. emit_eobrun(entropy);
  165181. if (! entropy->gather_statistics) {
  165182. flush_bits_p(entropy);
  165183. emit_byte(entropy, 0xFF);
  165184. emit_byte(entropy, JPEG_RST0 + restart_num);
  165185. }
  165186. if (entropy->cinfo->Ss == 0) {
  165187. /* Re-initialize DC predictions to 0 */
  165188. for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
  165189. entropy->last_dc_val[ci] = 0;
  165190. } else {
  165191. /* Re-initialize all AC-related fields to 0 */
  165192. entropy->EOBRUN = 0;
  165193. entropy->BE = 0;
  165194. }
  165195. }
  165196. /*
  165197. * MCU encoding for DC initial scan (either spectral selection,
  165198. * or first pass of successive approximation).
  165199. */
  165200. METHODDEF(boolean)
  165201. encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  165202. {
  165203. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165204. register int temp, temp2;
  165205. register int nbits;
  165206. int blkn, ci;
  165207. int Al = cinfo->Al;
  165208. JBLOCKROW block;
  165209. jpeg_component_info * compptr;
  165210. ISHIFT_TEMPS
  165211. entropy->next_output_byte = cinfo->dest->next_output_byte;
  165212. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  165213. /* Emit restart marker if needed */
  165214. if (cinfo->restart_interval)
  165215. if (entropy->restarts_to_go == 0)
  165216. emit_restart_p(entropy, entropy->next_restart_num);
  165217. /* Encode the MCU data blocks */
  165218. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  165219. block = MCU_data[blkn];
  165220. ci = cinfo->MCU_membership[blkn];
  165221. compptr = cinfo->cur_comp_info[ci];
  165222. /* Compute the DC value after the required point transform by Al.
  165223. * This is simply an arithmetic right shift.
  165224. */
  165225. temp2 = IRIGHT_SHIFT((int) ((*block)[0]), Al);
  165226. /* DC differences are figured on the point-transformed values. */
  165227. temp = temp2 - entropy->last_dc_val[ci];
  165228. entropy->last_dc_val[ci] = temp2;
  165229. /* Encode the DC coefficient difference per section G.1.2.1 */
  165230. temp2 = temp;
  165231. if (temp < 0) {
  165232. temp = -temp; /* temp is abs value of input */
  165233. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  165234. /* This code assumes we are on a two's complement machine */
  165235. temp2--;
  165236. }
  165237. /* Find the number of bits needed for the magnitude of the coefficient */
  165238. nbits = 0;
  165239. while (temp) {
  165240. nbits++;
  165241. temp >>= 1;
  165242. }
  165243. /* Check for out-of-range coefficient values.
  165244. * Since we're encoding a difference, the range limit is twice as much.
  165245. */
  165246. if (nbits > MAX_COEF_BITS+1)
  165247. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  165248. /* Count/emit the Huffman-coded symbol for the number of bits */
  165249. emit_symbol(entropy, compptr->dc_tbl_no, nbits);
  165250. /* Emit that number of bits of the value, if positive, */
  165251. /* or the complement of its magnitude, if negative. */
  165252. if (nbits) /* emit_bits rejects calls with size 0 */
  165253. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  165254. }
  165255. cinfo->dest->next_output_byte = entropy->next_output_byte;
  165256. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  165257. /* Update restart-interval state too */
  165258. if (cinfo->restart_interval) {
  165259. if (entropy->restarts_to_go == 0) {
  165260. entropy->restarts_to_go = cinfo->restart_interval;
  165261. entropy->next_restart_num++;
  165262. entropy->next_restart_num &= 7;
  165263. }
  165264. entropy->restarts_to_go--;
  165265. }
  165266. return TRUE;
  165267. }
  165268. /*
  165269. * MCU encoding for AC initial scan (either spectral selection,
  165270. * or first pass of successive approximation).
  165271. */
  165272. METHODDEF(boolean)
  165273. encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  165274. {
  165275. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165276. register int temp, temp2;
  165277. register int nbits;
  165278. register int r, k;
  165279. int Se = cinfo->Se;
  165280. int Al = cinfo->Al;
  165281. JBLOCKROW block;
  165282. entropy->next_output_byte = cinfo->dest->next_output_byte;
  165283. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  165284. /* Emit restart marker if needed */
  165285. if (cinfo->restart_interval)
  165286. if (entropy->restarts_to_go == 0)
  165287. emit_restart_p(entropy, entropy->next_restart_num);
  165288. /* Encode the MCU data block */
  165289. block = MCU_data[0];
  165290. /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
  165291. r = 0; /* r = run length of zeros */
  165292. for (k = cinfo->Ss; k <= Se; k++) {
  165293. if ((temp = (*block)[jpeg_natural_order[k]]) == 0) {
  165294. r++;
  165295. continue;
  165296. }
  165297. /* We must apply the point transform by Al. For AC coefficients this
  165298. * is an integer division with rounding towards 0. To do this portably
  165299. * in C, we shift after obtaining the absolute value; so the code is
  165300. * interwoven with finding the abs value (temp) and output bits (temp2).
  165301. */
  165302. if (temp < 0) {
  165303. temp = -temp; /* temp is abs value of input */
  165304. temp >>= Al; /* apply the point transform */
  165305. /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
  165306. temp2 = ~temp;
  165307. } else {
  165308. temp >>= Al; /* apply the point transform */
  165309. temp2 = temp;
  165310. }
  165311. /* Watch out for case that nonzero coef is zero after point transform */
  165312. if (temp == 0) {
  165313. r++;
  165314. continue;
  165315. }
  165316. /* Emit any pending EOBRUN */
  165317. if (entropy->EOBRUN > 0)
  165318. emit_eobrun(entropy);
  165319. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  165320. while (r > 15) {
  165321. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  165322. r -= 16;
  165323. }
  165324. /* Find the number of bits needed for the magnitude of the coefficient */
  165325. nbits = 1; /* there must be at least one 1 bit */
  165326. while ((temp >>= 1))
  165327. nbits++;
  165328. /* Check for out-of-range coefficient values */
  165329. if (nbits > MAX_COEF_BITS)
  165330. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  165331. /* Count/emit Huffman symbol for run length / number of bits */
  165332. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
  165333. /* Emit that number of bits of the value, if positive, */
  165334. /* or the complement of its magnitude, if negative. */
  165335. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  165336. r = 0; /* reset zero run length */
  165337. }
  165338. if (r > 0) { /* If there are trailing zeroes, */
  165339. entropy->EOBRUN++; /* count an EOB */
  165340. if (entropy->EOBRUN == 0x7FFF)
  165341. emit_eobrun(entropy); /* force it out to avoid overflow */
  165342. }
  165343. cinfo->dest->next_output_byte = entropy->next_output_byte;
  165344. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  165345. /* Update restart-interval state too */
  165346. if (cinfo->restart_interval) {
  165347. if (entropy->restarts_to_go == 0) {
  165348. entropy->restarts_to_go = cinfo->restart_interval;
  165349. entropy->next_restart_num++;
  165350. entropy->next_restart_num &= 7;
  165351. }
  165352. entropy->restarts_to_go--;
  165353. }
  165354. return TRUE;
  165355. }
  165356. /*
  165357. * MCU encoding for DC successive approximation refinement scan.
  165358. * Note: we assume such scans can be multi-component, although the spec
  165359. * is not very clear on the point.
  165360. */
  165361. METHODDEF(boolean)
  165362. encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  165363. {
  165364. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165365. register int temp;
  165366. int blkn;
  165367. int Al = cinfo->Al;
  165368. JBLOCKROW block;
  165369. entropy->next_output_byte = cinfo->dest->next_output_byte;
  165370. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  165371. /* Emit restart marker if needed */
  165372. if (cinfo->restart_interval)
  165373. if (entropy->restarts_to_go == 0)
  165374. emit_restart_p(entropy, entropy->next_restart_num);
  165375. /* Encode the MCU data blocks */
  165376. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  165377. block = MCU_data[blkn];
  165378. /* We simply emit the Al'th bit of the DC coefficient value. */
  165379. temp = (*block)[0];
  165380. emit_bits_p(entropy, (unsigned int) (temp >> Al), 1);
  165381. }
  165382. cinfo->dest->next_output_byte = entropy->next_output_byte;
  165383. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  165384. /* Update restart-interval state too */
  165385. if (cinfo->restart_interval) {
  165386. if (entropy->restarts_to_go == 0) {
  165387. entropy->restarts_to_go = cinfo->restart_interval;
  165388. entropy->next_restart_num++;
  165389. entropy->next_restart_num &= 7;
  165390. }
  165391. entropy->restarts_to_go--;
  165392. }
  165393. return TRUE;
  165394. }
  165395. /*
  165396. * MCU encoding for AC successive approximation refinement scan.
  165397. */
  165398. METHODDEF(boolean)
  165399. encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  165400. {
  165401. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165402. register int temp;
  165403. register int r, k;
  165404. int EOB;
  165405. char *BR_buffer;
  165406. unsigned int BR;
  165407. int Se = cinfo->Se;
  165408. int Al = cinfo->Al;
  165409. JBLOCKROW block;
  165410. int absvalues[DCTSIZE2];
  165411. entropy->next_output_byte = cinfo->dest->next_output_byte;
  165412. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  165413. /* Emit restart marker if needed */
  165414. if (cinfo->restart_interval)
  165415. if (entropy->restarts_to_go == 0)
  165416. emit_restart_p(entropy, entropy->next_restart_num);
  165417. /* Encode the MCU data block */
  165418. block = MCU_data[0];
  165419. /* It is convenient to make a pre-pass to determine the transformed
  165420. * coefficients' absolute values and the EOB position.
  165421. */
  165422. EOB = 0;
  165423. for (k = cinfo->Ss; k <= Se; k++) {
  165424. temp = (*block)[jpeg_natural_order[k]];
  165425. /* We must apply the point transform by Al. For AC coefficients this
  165426. * is an integer division with rounding towards 0. To do this portably
  165427. * in C, we shift after obtaining the absolute value.
  165428. */
  165429. if (temp < 0)
  165430. temp = -temp; /* temp is abs value of input */
  165431. temp >>= Al; /* apply the point transform */
  165432. absvalues[k] = temp; /* save abs value for main pass */
  165433. if (temp == 1)
  165434. EOB = k; /* EOB = index of last newly-nonzero coef */
  165435. }
  165436. /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
  165437. r = 0; /* r = run length of zeros */
  165438. BR = 0; /* BR = count of buffered bits added now */
  165439. BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
  165440. for (k = cinfo->Ss; k <= Se; k++) {
  165441. if ((temp = absvalues[k]) == 0) {
  165442. r++;
  165443. continue;
  165444. }
  165445. /* Emit any required ZRLs, but not if they can be folded into EOB */
  165446. while (r > 15 && k <= EOB) {
  165447. /* emit any pending EOBRUN and the BE correction bits */
  165448. emit_eobrun(entropy);
  165449. /* Emit ZRL */
  165450. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  165451. r -= 16;
  165452. /* Emit buffered correction bits that must be associated with ZRL */
  165453. emit_buffered_bits(entropy, BR_buffer, BR);
  165454. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  165455. BR = 0;
  165456. }
  165457. /* If the coef was previously nonzero, it only needs a correction bit.
  165458. * NOTE: a straight translation of the spec's figure G.7 would suggest
  165459. * that we also need to test r > 15. But if r > 15, we can only get here
  165460. * if k > EOB, which implies that this coefficient is not 1.
  165461. */
  165462. if (temp > 1) {
  165463. /* The correction bit is the next bit of the absolute value. */
  165464. BR_buffer[BR++] = (char) (temp & 1);
  165465. continue;
  165466. }
  165467. /* Emit any pending EOBRUN and the BE correction bits */
  165468. emit_eobrun(entropy);
  165469. /* Count/emit Huffman symbol for run length / number of bits */
  165470. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
  165471. /* Emit output bit for newly-nonzero coef */
  165472. temp = ((*block)[jpeg_natural_order[k]] < 0) ? 0 : 1;
  165473. emit_bits_p(entropy, (unsigned int) temp, 1);
  165474. /* Emit buffered correction bits that must be associated with this code */
  165475. emit_buffered_bits(entropy, BR_buffer, BR);
  165476. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  165477. BR = 0;
  165478. r = 0; /* reset zero run length */
  165479. }
  165480. if (r > 0 || BR > 0) { /* If there are trailing zeroes, */
  165481. entropy->EOBRUN++; /* count an EOB */
  165482. entropy->BE += BR; /* concat my correction bits to older ones */
  165483. /* We force out the EOB if we risk either:
  165484. * 1. overflow of the EOB counter;
  165485. * 2. overflow of the correction bit buffer during the next MCU.
  165486. */
  165487. if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
  165488. emit_eobrun(entropy);
  165489. }
  165490. cinfo->dest->next_output_byte = entropy->next_output_byte;
  165491. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  165492. /* Update restart-interval state too */
  165493. if (cinfo->restart_interval) {
  165494. if (entropy->restarts_to_go == 0) {
  165495. entropy->restarts_to_go = cinfo->restart_interval;
  165496. entropy->next_restart_num++;
  165497. entropy->next_restart_num &= 7;
  165498. }
  165499. entropy->restarts_to_go--;
  165500. }
  165501. return TRUE;
  165502. }
  165503. /*
  165504. * Finish up at the end of a Huffman-compressed progressive scan.
  165505. */
  165506. METHODDEF(void)
  165507. finish_pass_phuff (j_compress_ptr cinfo)
  165508. {
  165509. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165510. entropy->next_output_byte = cinfo->dest->next_output_byte;
  165511. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  165512. /* Flush out any buffered data */
  165513. emit_eobrun(entropy);
  165514. flush_bits_p(entropy);
  165515. cinfo->dest->next_output_byte = entropy->next_output_byte;
  165516. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  165517. }
  165518. /*
  165519. * Finish up a statistics-gathering pass and create the new Huffman tables.
  165520. */
  165521. METHODDEF(void)
  165522. finish_pass_gather_phuff (j_compress_ptr cinfo)
  165523. {
  165524. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165525. boolean is_DC_band;
  165526. int ci, tbl;
  165527. jpeg_component_info * compptr;
  165528. JHUFF_TBL **htblptr;
  165529. boolean did[NUM_HUFF_TBLS];
  165530. /* Flush out buffered data (all we care about is counting the EOB symbol) */
  165531. emit_eobrun(entropy);
  165532. is_DC_band = (cinfo->Ss == 0);
  165533. /* It's important not to apply jpeg_gen_optimal_table more than once
  165534. * per table, because it clobbers the input frequency counts!
  165535. */
  165536. MEMZERO(did, SIZEOF(did));
  165537. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165538. compptr = cinfo->cur_comp_info[ci];
  165539. if (is_DC_band) {
  165540. if (cinfo->Ah != 0) /* DC refinement needs no table */
  165541. continue;
  165542. tbl = compptr->dc_tbl_no;
  165543. } else {
  165544. tbl = compptr->ac_tbl_no;
  165545. }
  165546. if (! did[tbl]) {
  165547. if (is_DC_band)
  165548. htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
  165549. else
  165550. htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
  165551. if (*htblptr == NULL)
  165552. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  165553. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[tbl]);
  165554. did[tbl] = TRUE;
  165555. }
  165556. }
  165557. }
  165558. /*
  165559. * Module initialization routine for progressive Huffman entropy encoding.
  165560. */
  165561. GLOBAL(void)
  165562. jinit_phuff_encoder (j_compress_ptr cinfo)
  165563. {
  165564. phuff_entropy_ptr entropy;
  165565. int i;
  165566. entropy = (phuff_entropy_ptr)
  165567. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165568. SIZEOF(phuff_entropy_encoder));
  165569. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  165570. entropy->pub.start_pass = start_pass_phuff;
  165571. /* Mark tables unallocated */
  165572. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  165573. entropy->derived_tbls[i] = NULL;
  165574. entropy->count_ptrs[i] = NULL;
  165575. }
  165576. entropy->bit_buffer = NULL; /* needed only in AC refinement scan */
  165577. }
  165578. #endif /* C_PROGRESSIVE_SUPPORTED */
  165579. /*** End of inlined file: jcphuff.c ***/
  165580. /*** Start of inlined file: jcprepct.c ***/
  165581. #define JPEG_INTERNALS
  165582. /* At present, jcsample.c can request context rows only for smoothing.
  165583. * In the future, we might also need context rows for CCIR601 sampling
  165584. * or other more-complex downsampling procedures. The code to support
  165585. * context rows should be compiled only if needed.
  165586. */
  165587. #ifdef INPUT_SMOOTHING_SUPPORTED
  165588. #define CONTEXT_ROWS_SUPPORTED
  165589. #endif
  165590. /*
  165591. * For the simple (no-context-row) case, we just need to buffer one
  165592. * row group's worth of pixels for the downsampling step. At the bottom of
  165593. * the image, we pad to a full row group by replicating the last pixel row.
  165594. * The downsampler's last output row is then replicated if needed to pad
  165595. * out to a full iMCU row.
  165596. *
  165597. * When providing context rows, we must buffer three row groups' worth of
  165598. * pixels. Three row groups are physically allocated, but the row pointer
  165599. * arrays are made five row groups high, with the extra pointers above and
  165600. * below "wrapping around" to point to the last and first real row groups.
  165601. * This allows the downsampler to access the proper context rows.
  165602. * At the top and bottom of the image, we create dummy context rows by
  165603. * copying the first or last real pixel row. This copying could be avoided
  165604. * by pointer hacking as is done in jdmainct.c, but it doesn't seem worth the
  165605. * trouble on the compression side.
  165606. */
  165607. /* Private buffer controller object */
  165608. typedef struct {
  165609. struct jpeg_c_prep_controller pub; /* public fields */
  165610. /* Downsampling input buffer. This buffer holds color-converted data
  165611. * until we have enough to do a downsample step.
  165612. */
  165613. JSAMPARRAY color_buf[MAX_COMPONENTS];
  165614. JDIMENSION rows_to_go; /* counts rows remaining in source image */
  165615. int next_buf_row; /* index of next row to store in color_buf */
  165616. #ifdef CONTEXT_ROWS_SUPPORTED /* only needed for context case */
  165617. int this_row_group; /* starting row index of group to process */
  165618. int next_buf_stop; /* downsample when we reach this index */
  165619. #endif
  165620. } my_prep_controller;
  165621. typedef my_prep_controller * my_prep_ptr;
  165622. /*
  165623. * Initialize for a processing pass.
  165624. */
  165625. METHODDEF(void)
  165626. start_pass_prep (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  165627. {
  165628. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  165629. if (pass_mode != JBUF_PASS_THRU)
  165630. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  165631. /* Initialize total-height counter for detecting bottom of image */
  165632. prep->rows_to_go = cinfo->image_height;
  165633. /* Mark the conversion buffer empty */
  165634. prep->next_buf_row = 0;
  165635. #ifdef CONTEXT_ROWS_SUPPORTED
  165636. /* Preset additional state variables for context mode.
  165637. * These aren't used in non-context mode, so we needn't test which mode.
  165638. */
  165639. prep->this_row_group = 0;
  165640. /* Set next_buf_stop to stop after two row groups have been read in. */
  165641. prep->next_buf_stop = 2 * cinfo->max_v_samp_factor;
  165642. #endif
  165643. }
  165644. /*
  165645. * Expand an image vertically from height input_rows to height output_rows,
  165646. * by duplicating the bottom row.
  165647. */
  165648. LOCAL(void)
  165649. expand_bottom_edge (JSAMPARRAY image_data, JDIMENSION num_cols,
  165650. int input_rows, int output_rows)
  165651. {
  165652. register int row;
  165653. for (row = input_rows; row < output_rows; row++) {
  165654. jcopy_sample_rows(image_data, input_rows-1, image_data, row,
  165655. 1, num_cols);
  165656. }
  165657. }
  165658. /*
  165659. * Process some data in the simple no-context case.
  165660. *
  165661. * Preprocessor output data is counted in "row groups". A row group
  165662. * is defined to be v_samp_factor sample rows of each component.
  165663. * Downsampling will produce this much data from each max_v_samp_factor
  165664. * input rows.
  165665. */
  165666. METHODDEF(void)
  165667. pre_process_data (j_compress_ptr cinfo,
  165668. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  165669. JDIMENSION in_rows_avail,
  165670. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  165671. JDIMENSION out_row_groups_avail)
  165672. {
  165673. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  165674. int numrows, ci;
  165675. JDIMENSION inrows;
  165676. jpeg_component_info * compptr;
  165677. while (*in_row_ctr < in_rows_avail &&
  165678. *out_row_group_ctr < out_row_groups_avail) {
  165679. /* Do color conversion to fill the conversion buffer. */
  165680. inrows = in_rows_avail - *in_row_ctr;
  165681. numrows = cinfo->max_v_samp_factor - prep->next_buf_row;
  165682. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  165683. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  165684. prep->color_buf,
  165685. (JDIMENSION) prep->next_buf_row,
  165686. numrows);
  165687. *in_row_ctr += numrows;
  165688. prep->next_buf_row += numrows;
  165689. prep->rows_to_go -= numrows;
  165690. /* If at bottom of image, pad to fill the conversion buffer. */
  165691. if (prep->rows_to_go == 0 &&
  165692. prep->next_buf_row < cinfo->max_v_samp_factor) {
  165693. for (ci = 0; ci < cinfo->num_components; ci++) {
  165694. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  165695. prep->next_buf_row, cinfo->max_v_samp_factor);
  165696. }
  165697. prep->next_buf_row = cinfo->max_v_samp_factor;
  165698. }
  165699. /* If we've filled the conversion buffer, empty it. */
  165700. if (prep->next_buf_row == cinfo->max_v_samp_factor) {
  165701. (*cinfo->downsample->downsample) (cinfo,
  165702. prep->color_buf, (JDIMENSION) 0,
  165703. output_buf, *out_row_group_ctr);
  165704. prep->next_buf_row = 0;
  165705. (*out_row_group_ctr)++;
  165706. }
  165707. /* If at bottom of image, pad the output to a full iMCU height.
  165708. * Note we assume the caller is providing a one-iMCU-height output buffer!
  165709. */
  165710. if (prep->rows_to_go == 0 &&
  165711. *out_row_group_ctr < out_row_groups_avail) {
  165712. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165713. ci++, compptr++) {
  165714. expand_bottom_edge(output_buf[ci],
  165715. compptr->width_in_blocks * DCTSIZE,
  165716. (int) (*out_row_group_ctr * compptr->v_samp_factor),
  165717. (int) (out_row_groups_avail * compptr->v_samp_factor));
  165718. }
  165719. *out_row_group_ctr = out_row_groups_avail;
  165720. break; /* can exit outer loop without test */
  165721. }
  165722. }
  165723. }
  165724. #ifdef CONTEXT_ROWS_SUPPORTED
  165725. /*
  165726. * Process some data in the context case.
  165727. */
  165728. METHODDEF(void)
  165729. pre_process_context (j_compress_ptr cinfo,
  165730. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  165731. JDIMENSION in_rows_avail,
  165732. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  165733. JDIMENSION out_row_groups_avail)
  165734. {
  165735. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  165736. int numrows, ci;
  165737. int buf_height = cinfo->max_v_samp_factor * 3;
  165738. JDIMENSION inrows;
  165739. while (*out_row_group_ctr < out_row_groups_avail) {
  165740. if (*in_row_ctr < in_rows_avail) {
  165741. /* Do color conversion to fill the conversion buffer. */
  165742. inrows = in_rows_avail - *in_row_ctr;
  165743. numrows = prep->next_buf_stop - prep->next_buf_row;
  165744. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  165745. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  165746. prep->color_buf,
  165747. (JDIMENSION) prep->next_buf_row,
  165748. numrows);
  165749. /* Pad at top of image, if first time through */
  165750. if (prep->rows_to_go == cinfo->image_height) {
  165751. for (ci = 0; ci < cinfo->num_components; ci++) {
  165752. int row;
  165753. for (row = 1; row <= cinfo->max_v_samp_factor; row++) {
  165754. jcopy_sample_rows(prep->color_buf[ci], 0,
  165755. prep->color_buf[ci], -row,
  165756. 1, cinfo->image_width);
  165757. }
  165758. }
  165759. }
  165760. *in_row_ctr += numrows;
  165761. prep->next_buf_row += numrows;
  165762. prep->rows_to_go -= numrows;
  165763. } else {
  165764. /* Return for more data, unless we are at the bottom of the image. */
  165765. if (prep->rows_to_go != 0)
  165766. break;
  165767. /* When at bottom of image, pad to fill the conversion buffer. */
  165768. if (prep->next_buf_row < prep->next_buf_stop) {
  165769. for (ci = 0; ci < cinfo->num_components; ci++) {
  165770. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  165771. prep->next_buf_row, prep->next_buf_stop);
  165772. }
  165773. prep->next_buf_row = prep->next_buf_stop;
  165774. }
  165775. }
  165776. /* If we've gotten enough data, downsample a row group. */
  165777. if (prep->next_buf_row == prep->next_buf_stop) {
  165778. (*cinfo->downsample->downsample) (cinfo,
  165779. prep->color_buf,
  165780. (JDIMENSION) prep->this_row_group,
  165781. output_buf, *out_row_group_ctr);
  165782. (*out_row_group_ctr)++;
  165783. /* Advance pointers with wraparound as necessary. */
  165784. prep->this_row_group += cinfo->max_v_samp_factor;
  165785. if (prep->this_row_group >= buf_height)
  165786. prep->this_row_group = 0;
  165787. if (prep->next_buf_row >= buf_height)
  165788. prep->next_buf_row = 0;
  165789. prep->next_buf_stop = prep->next_buf_row + cinfo->max_v_samp_factor;
  165790. }
  165791. }
  165792. }
  165793. /*
  165794. * Create the wrapped-around downsampling input buffer needed for context mode.
  165795. */
  165796. LOCAL(void)
  165797. create_context_buffer (j_compress_ptr cinfo)
  165798. {
  165799. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  165800. int rgroup_height = cinfo->max_v_samp_factor;
  165801. int ci, i;
  165802. jpeg_component_info * compptr;
  165803. JSAMPARRAY true_buffer, fake_buffer;
  165804. /* Grab enough space for fake row pointers for all the components;
  165805. * we need five row groups' worth of pointers for each component.
  165806. */
  165807. fake_buffer = (JSAMPARRAY)
  165808. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165809. (cinfo->num_components * 5 * rgroup_height) *
  165810. SIZEOF(JSAMPROW));
  165811. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165812. ci++, compptr++) {
  165813. /* Allocate the actual buffer space (3 row groups) for this component.
  165814. * We make the buffer wide enough to allow the downsampler to edge-expand
  165815. * horizontally within the buffer, if it so chooses.
  165816. */
  165817. true_buffer = (*cinfo->mem->alloc_sarray)
  165818. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165819. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  165820. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  165821. (JDIMENSION) (3 * rgroup_height));
  165822. /* Copy true buffer row pointers into the middle of the fake row array */
  165823. MEMCOPY(fake_buffer + rgroup_height, true_buffer,
  165824. 3 * rgroup_height * SIZEOF(JSAMPROW));
  165825. /* Fill in the above and below wraparound pointers */
  165826. for (i = 0; i < rgroup_height; i++) {
  165827. fake_buffer[i] = true_buffer[2 * rgroup_height + i];
  165828. fake_buffer[4 * rgroup_height + i] = true_buffer[i];
  165829. }
  165830. prep->color_buf[ci] = fake_buffer + rgroup_height;
  165831. fake_buffer += 5 * rgroup_height; /* point to space for next component */
  165832. }
  165833. }
  165834. #endif /* CONTEXT_ROWS_SUPPORTED */
  165835. /*
  165836. * Initialize preprocessing controller.
  165837. */
  165838. GLOBAL(void)
  165839. jinit_c_prep_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  165840. {
  165841. my_prep_ptr prep;
  165842. int ci;
  165843. jpeg_component_info * compptr;
  165844. if (need_full_buffer) /* safety check */
  165845. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  165846. prep = (my_prep_ptr)
  165847. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165848. SIZEOF(my_prep_controller));
  165849. cinfo->prep = (struct jpeg_c_prep_controller *) prep;
  165850. prep->pub.start_pass = start_pass_prep;
  165851. /* Allocate the color conversion buffer.
  165852. * We make the buffer wide enough to allow the downsampler to edge-expand
  165853. * horizontally within the buffer, if it so chooses.
  165854. */
  165855. if (cinfo->downsample->need_context_rows) {
  165856. /* Set up to provide context rows */
  165857. #ifdef CONTEXT_ROWS_SUPPORTED
  165858. prep->pub.pre_process_data = pre_process_context;
  165859. create_context_buffer(cinfo);
  165860. #else
  165861. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165862. #endif
  165863. } else {
  165864. /* No context, just make it tall enough for one row group */
  165865. prep->pub.pre_process_data = pre_process_data;
  165866. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165867. ci++, compptr++) {
  165868. prep->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  165869. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165870. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  165871. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  165872. (JDIMENSION) cinfo->max_v_samp_factor);
  165873. }
  165874. }
  165875. }
  165876. /*** End of inlined file: jcprepct.c ***/
  165877. /*** Start of inlined file: jcsample.c ***/
  165878. #define JPEG_INTERNALS
  165879. /* Pointer to routine to downsample a single component */
  165880. typedef JMETHOD(void, downsample1_ptr,
  165881. (j_compress_ptr cinfo, jpeg_component_info * compptr,
  165882. JSAMPARRAY input_data, JSAMPARRAY output_data));
  165883. /* Private subobject */
  165884. typedef struct {
  165885. struct jpeg_downsampler pub; /* public fields */
  165886. /* Downsampling method pointers, one per component */
  165887. downsample1_ptr methods[MAX_COMPONENTS];
  165888. } my_downsampler;
  165889. typedef my_downsampler * my_downsample_ptr;
  165890. /*
  165891. * Initialize for a downsampling pass.
  165892. */
  165893. METHODDEF(void)
  165894. start_pass_downsample (j_compress_ptr)
  165895. {
  165896. /* no work for now */
  165897. }
  165898. /*
  165899. * Expand a component horizontally from width input_cols to width output_cols,
  165900. * by duplicating the rightmost samples.
  165901. */
  165902. LOCAL(void)
  165903. expand_right_edge (JSAMPARRAY image_data, int num_rows,
  165904. JDIMENSION input_cols, JDIMENSION output_cols)
  165905. {
  165906. register JSAMPROW ptr;
  165907. register JSAMPLE pixval;
  165908. register int count;
  165909. int row;
  165910. int numcols = (int) (output_cols - input_cols);
  165911. if (numcols > 0) {
  165912. for (row = 0; row < num_rows; row++) {
  165913. ptr = image_data[row] + input_cols;
  165914. pixval = ptr[-1]; /* don't need GETJSAMPLE() here */
  165915. for (count = numcols; count > 0; count--)
  165916. *ptr++ = pixval;
  165917. }
  165918. }
  165919. }
  165920. /*
  165921. * Do downsampling for a whole row group (all components).
  165922. *
  165923. * In this version we simply downsample each component independently.
  165924. */
  165925. METHODDEF(void)
  165926. sep_downsample (j_compress_ptr cinfo,
  165927. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  165928. JSAMPIMAGE output_buf, JDIMENSION out_row_group_index)
  165929. {
  165930. my_downsample_ptr downsample = (my_downsample_ptr) cinfo->downsample;
  165931. int ci;
  165932. jpeg_component_info * compptr;
  165933. JSAMPARRAY in_ptr, out_ptr;
  165934. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165935. ci++, compptr++) {
  165936. in_ptr = input_buf[ci] + in_row_index;
  165937. out_ptr = output_buf[ci] + (out_row_group_index * compptr->v_samp_factor);
  165938. (*downsample->methods[ci]) (cinfo, compptr, in_ptr, out_ptr);
  165939. }
  165940. }
  165941. /*
  165942. * Downsample pixel values of a single component.
  165943. * One row group is processed per call.
  165944. * This version handles arbitrary integral sampling ratios, without smoothing.
  165945. * Note that this version is not actually used for customary sampling ratios.
  165946. */
  165947. METHODDEF(void)
  165948. int_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  165949. JSAMPARRAY input_data, JSAMPARRAY output_data)
  165950. {
  165951. int inrow, outrow, h_expand, v_expand, numpix, numpix2, h, v;
  165952. JDIMENSION outcol, outcol_h; /* outcol_h == outcol*h_expand */
  165953. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  165954. JSAMPROW inptr, outptr;
  165955. INT32 outvalue;
  165956. h_expand = cinfo->max_h_samp_factor / compptr->h_samp_factor;
  165957. v_expand = cinfo->max_v_samp_factor / compptr->v_samp_factor;
  165958. numpix = h_expand * v_expand;
  165959. numpix2 = numpix/2;
  165960. /* Expand input data enough to let all the output samples be generated
  165961. * by the standard loop. Special-casing padded output would be more
  165962. * efficient.
  165963. */
  165964. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  165965. cinfo->image_width, output_cols * h_expand);
  165966. inrow = 0;
  165967. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  165968. outptr = output_data[outrow];
  165969. for (outcol = 0, outcol_h = 0; outcol < output_cols;
  165970. outcol++, outcol_h += h_expand) {
  165971. outvalue = 0;
  165972. for (v = 0; v < v_expand; v++) {
  165973. inptr = input_data[inrow+v] + outcol_h;
  165974. for (h = 0; h < h_expand; h++) {
  165975. outvalue += (INT32) GETJSAMPLE(*inptr++);
  165976. }
  165977. }
  165978. *outptr++ = (JSAMPLE) ((outvalue + numpix2) / numpix);
  165979. }
  165980. inrow += v_expand;
  165981. }
  165982. }
  165983. /*
  165984. * Downsample pixel values of a single component.
  165985. * This version handles the special case of a full-size component,
  165986. * without smoothing.
  165987. */
  165988. METHODDEF(void)
  165989. fullsize_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  165990. JSAMPARRAY input_data, JSAMPARRAY output_data)
  165991. {
  165992. /* Copy the data */
  165993. jcopy_sample_rows(input_data, 0, output_data, 0,
  165994. cinfo->max_v_samp_factor, cinfo->image_width);
  165995. /* Edge-expand */
  165996. expand_right_edge(output_data, cinfo->max_v_samp_factor,
  165997. cinfo->image_width, compptr->width_in_blocks * DCTSIZE);
  165998. }
  165999. /*
  166000. * Downsample pixel values of a single component.
  166001. * This version handles the common case of 2:1 horizontal and 1:1 vertical,
  166002. * without smoothing.
  166003. *
  166004. * A note about the "bias" calculations: when rounding fractional values to
  166005. * integer, we do not want to always round 0.5 up to the next integer.
  166006. * If we did that, we'd introduce a noticeable bias towards larger values.
  166007. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  166008. * alternate pixel locations (a simple ordered dither pattern).
  166009. */
  166010. METHODDEF(void)
  166011. h2v1_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166012. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166013. {
  166014. int outrow;
  166015. JDIMENSION outcol;
  166016. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166017. register JSAMPROW inptr, outptr;
  166018. register int bias;
  166019. /* Expand input data enough to let all the output samples be generated
  166020. * by the standard loop. Special-casing padded output would be more
  166021. * efficient.
  166022. */
  166023. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166024. cinfo->image_width, output_cols * 2);
  166025. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166026. outptr = output_data[outrow];
  166027. inptr = input_data[outrow];
  166028. bias = 0; /* bias = 0,1,0,1,... for successive samples */
  166029. for (outcol = 0; outcol < output_cols; outcol++) {
  166030. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr) + GETJSAMPLE(inptr[1])
  166031. + bias) >> 1);
  166032. bias ^= 1; /* 0=>1, 1=>0 */
  166033. inptr += 2;
  166034. }
  166035. }
  166036. }
  166037. /*
  166038. * Downsample pixel values of a single component.
  166039. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  166040. * without smoothing.
  166041. */
  166042. METHODDEF(void)
  166043. h2v2_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166044. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166045. {
  166046. int inrow, outrow;
  166047. JDIMENSION outcol;
  166048. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166049. register JSAMPROW inptr0, inptr1, outptr;
  166050. register int bias;
  166051. /* Expand input data enough to let all the output samples be generated
  166052. * by the standard loop. Special-casing padded output would be more
  166053. * efficient.
  166054. */
  166055. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166056. cinfo->image_width, output_cols * 2);
  166057. inrow = 0;
  166058. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166059. outptr = output_data[outrow];
  166060. inptr0 = input_data[inrow];
  166061. inptr1 = input_data[inrow+1];
  166062. bias = 1; /* bias = 1,2,1,2,... for successive samples */
  166063. for (outcol = 0; outcol < output_cols; outcol++) {
  166064. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166065. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1])
  166066. + bias) >> 2);
  166067. bias ^= 3; /* 1=>2, 2=>1 */
  166068. inptr0 += 2; inptr1 += 2;
  166069. }
  166070. inrow += 2;
  166071. }
  166072. }
  166073. #ifdef INPUT_SMOOTHING_SUPPORTED
  166074. /*
  166075. * Downsample pixel values of a single component.
  166076. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  166077. * with smoothing. One row of context is required.
  166078. */
  166079. METHODDEF(void)
  166080. h2v2_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166081. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166082. {
  166083. int inrow, outrow;
  166084. JDIMENSION colctr;
  166085. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166086. register JSAMPROW inptr0, inptr1, above_ptr, below_ptr, outptr;
  166087. INT32 membersum, neighsum, memberscale, neighscale;
  166088. /* Expand input data enough to let all the output samples be generated
  166089. * by the standard loop. Special-casing padded output would be more
  166090. * efficient.
  166091. */
  166092. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  166093. cinfo->image_width, output_cols * 2);
  166094. /* We don't bother to form the individual "smoothed" input pixel values;
  166095. * we can directly compute the output which is the average of the four
  166096. * smoothed values. Each of the four member pixels contributes a fraction
  166097. * (1-8*SF) to its own smoothed image and a fraction SF to each of the three
  166098. * other smoothed pixels, therefore a total fraction (1-5*SF)/4 to the final
  166099. * output. The four corner-adjacent neighbor pixels contribute a fraction
  166100. * SF to just one smoothed pixel, or SF/4 to the final output; while the
  166101. * eight edge-adjacent neighbors contribute SF to each of two smoothed
  166102. * pixels, or SF/2 overall. In order to use integer arithmetic, these
  166103. * factors are scaled by 2^16 = 65536.
  166104. * Also recall that SF = smoothing_factor / 1024.
  166105. */
  166106. memberscale = 16384 - cinfo->smoothing_factor * 80; /* scaled (1-5*SF)/4 */
  166107. neighscale = cinfo->smoothing_factor * 16; /* scaled SF/4 */
  166108. inrow = 0;
  166109. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166110. outptr = output_data[outrow];
  166111. inptr0 = input_data[inrow];
  166112. inptr1 = input_data[inrow+1];
  166113. above_ptr = input_data[inrow-1];
  166114. below_ptr = input_data[inrow+2];
  166115. /* Special case for first column: pretend column -1 is same as column 0 */
  166116. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166117. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  166118. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  166119. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  166120. GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[2]) +
  166121. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[2]);
  166122. neighsum += neighsum;
  166123. neighsum += GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[2]) +
  166124. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[2]);
  166125. membersum = membersum * memberscale + neighsum * neighscale;
  166126. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166127. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  166128. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  166129. /* sum of pixels directly mapped to this output element */
  166130. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166131. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  166132. /* sum of edge-neighbor pixels */
  166133. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  166134. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  166135. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[2]) +
  166136. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[2]);
  166137. /* The edge-neighbors count twice as much as corner-neighbors */
  166138. neighsum += neighsum;
  166139. /* Add in the corner-neighbors */
  166140. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[2]) +
  166141. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[2]);
  166142. /* form final output scaled up by 2^16 */
  166143. membersum = membersum * memberscale + neighsum * neighscale;
  166144. /* round, descale and output it */
  166145. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166146. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  166147. }
  166148. /* Special case for last column */
  166149. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166150. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  166151. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  166152. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  166153. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[1]) +
  166154. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[1]);
  166155. neighsum += neighsum;
  166156. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[1]) +
  166157. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[1]);
  166158. membersum = membersum * memberscale + neighsum * neighscale;
  166159. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  166160. inrow += 2;
  166161. }
  166162. }
  166163. /*
  166164. * Downsample pixel values of a single component.
  166165. * This version handles the special case of a full-size component,
  166166. * with smoothing. One row of context is required.
  166167. */
  166168. METHODDEF(void)
  166169. fullsize_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info *compptr,
  166170. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166171. {
  166172. int outrow;
  166173. JDIMENSION colctr;
  166174. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166175. register JSAMPROW inptr, above_ptr, below_ptr, outptr;
  166176. INT32 membersum, neighsum, memberscale, neighscale;
  166177. int colsum, lastcolsum, nextcolsum;
  166178. /* Expand input data enough to let all the output samples be generated
  166179. * by the standard loop. Special-casing padded output would be more
  166180. * efficient.
  166181. */
  166182. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  166183. cinfo->image_width, output_cols);
  166184. /* Each of the eight neighbor pixels contributes a fraction SF to the
  166185. * smoothed pixel, while the main pixel contributes (1-8*SF). In order
  166186. * to use integer arithmetic, these factors are multiplied by 2^16 = 65536.
  166187. * Also recall that SF = smoothing_factor / 1024.
  166188. */
  166189. memberscale = 65536L - cinfo->smoothing_factor * 512L; /* scaled 1-8*SF */
  166190. neighscale = cinfo->smoothing_factor * 64; /* scaled SF */
  166191. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166192. outptr = output_data[outrow];
  166193. inptr = input_data[outrow];
  166194. above_ptr = input_data[outrow-1];
  166195. below_ptr = input_data[outrow+1];
  166196. /* Special case for first column */
  166197. colsum = GETJSAMPLE(*above_ptr++) + GETJSAMPLE(*below_ptr++) +
  166198. GETJSAMPLE(*inptr);
  166199. membersum = GETJSAMPLE(*inptr++);
  166200. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  166201. GETJSAMPLE(*inptr);
  166202. neighsum = colsum + (colsum - membersum) + nextcolsum;
  166203. membersum = membersum * memberscale + neighsum * neighscale;
  166204. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166205. lastcolsum = colsum; colsum = nextcolsum;
  166206. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  166207. membersum = GETJSAMPLE(*inptr++);
  166208. above_ptr++; below_ptr++;
  166209. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  166210. GETJSAMPLE(*inptr);
  166211. neighsum = lastcolsum + (colsum - membersum) + nextcolsum;
  166212. membersum = membersum * memberscale + neighsum * neighscale;
  166213. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166214. lastcolsum = colsum; colsum = nextcolsum;
  166215. }
  166216. /* Special case for last column */
  166217. membersum = GETJSAMPLE(*inptr);
  166218. neighsum = lastcolsum + (colsum - membersum) + colsum;
  166219. membersum = membersum * memberscale + neighsum * neighscale;
  166220. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  166221. }
  166222. }
  166223. #endif /* INPUT_SMOOTHING_SUPPORTED */
  166224. /*
  166225. * Module initialization routine for downsampling.
  166226. * Note that we must select a routine for each component.
  166227. */
  166228. GLOBAL(void)
  166229. jinit_downsampler (j_compress_ptr cinfo)
  166230. {
  166231. my_downsample_ptr downsample;
  166232. int ci;
  166233. jpeg_component_info * compptr;
  166234. boolean smoothok = TRUE;
  166235. downsample = (my_downsample_ptr)
  166236. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166237. SIZEOF(my_downsampler));
  166238. cinfo->downsample = (struct jpeg_downsampler *) downsample;
  166239. downsample->pub.start_pass = start_pass_downsample;
  166240. downsample->pub.downsample = sep_downsample;
  166241. downsample->pub.need_context_rows = FALSE;
  166242. if (cinfo->CCIR601_sampling)
  166243. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  166244. /* Verify we can handle the sampling factors, and set up method pointers */
  166245. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166246. ci++, compptr++) {
  166247. if (compptr->h_samp_factor == cinfo->max_h_samp_factor &&
  166248. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  166249. #ifdef INPUT_SMOOTHING_SUPPORTED
  166250. if (cinfo->smoothing_factor) {
  166251. downsample->methods[ci] = fullsize_smooth_downsample;
  166252. downsample->pub.need_context_rows = TRUE;
  166253. } else
  166254. #endif
  166255. downsample->methods[ci] = fullsize_downsample;
  166256. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  166257. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  166258. smoothok = FALSE;
  166259. downsample->methods[ci] = h2v1_downsample;
  166260. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  166261. compptr->v_samp_factor * 2 == cinfo->max_v_samp_factor) {
  166262. #ifdef INPUT_SMOOTHING_SUPPORTED
  166263. if (cinfo->smoothing_factor) {
  166264. downsample->methods[ci] = h2v2_smooth_downsample;
  166265. downsample->pub.need_context_rows = TRUE;
  166266. } else
  166267. #endif
  166268. downsample->methods[ci] = h2v2_downsample;
  166269. } else if ((cinfo->max_h_samp_factor % compptr->h_samp_factor) == 0 &&
  166270. (cinfo->max_v_samp_factor % compptr->v_samp_factor) == 0) {
  166271. smoothok = FALSE;
  166272. downsample->methods[ci] = int_downsample;
  166273. } else
  166274. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  166275. }
  166276. #ifdef INPUT_SMOOTHING_SUPPORTED
  166277. if (cinfo->smoothing_factor && !smoothok)
  166278. TRACEMS(cinfo, 0, JTRC_SMOOTH_NOTIMPL);
  166279. #endif
  166280. }
  166281. /*** End of inlined file: jcsample.c ***/
  166282. /*** Start of inlined file: jctrans.c ***/
  166283. #define JPEG_INTERNALS
  166284. /* Forward declarations */
  166285. LOCAL(void) transencode_master_selection
  166286. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  166287. LOCAL(void) transencode_coef_controller
  166288. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  166289. /*
  166290. * Compression initialization for writing raw-coefficient data.
  166291. * Before calling this, all parameters and a data destination must be set up.
  166292. * Call jpeg_finish_compress() to actually write the data.
  166293. *
  166294. * The number of passed virtual arrays must match cinfo->num_components.
  166295. * Note that the virtual arrays need not be filled or even realized at
  166296. * the time write_coefficients is called; indeed, if the virtual arrays
  166297. * were requested from this compression object's memory manager, they
  166298. * typically will be realized during this routine and filled afterwards.
  166299. */
  166300. GLOBAL(void)
  166301. jpeg_write_coefficients (j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays)
  166302. {
  166303. if (cinfo->global_state != CSTATE_START)
  166304. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166305. /* Mark all tables to be written */
  166306. jpeg_suppress_tables(cinfo, FALSE);
  166307. /* (Re)initialize error mgr and destination modules */
  166308. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  166309. (*cinfo->dest->init_destination) (cinfo);
  166310. /* Perform master selection of active modules */
  166311. transencode_master_selection(cinfo, coef_arrays);
  166312. /* Wait for jpeg_finish_compress() call */
  166313. cinfo->next_scanline = 0; /* so jpeg_write_marker works */
  166314. cinfo->global_state = CSTATE_WRCOEFS;
  166315. }
  166316. /*
  166317. * Initialize the compression object with default parameters,
  166318. * then copy from the source object all parameters needed for lossless
  166319. * transcoding. Parameters that can be varied without loss (such as
  166320. * scan script and Huffman optimization) are left in their default states.
  166321. */
  166322. GLOBAL(void)
  166323. jpeg_copy_critical_parameters (j_decompress_ptr srcinfo,
  166324. j_compress_ptr dstinfo)
  166325. {
  166326. JQUANT_TBL ** qtblptr;
  166327. jpeg_component_info *incomp, *outcomp;
  166328. JQUANT_TBL *c_quant, *slot_quant;
  166329. int tblno, ci, coefi;
  166330. /* Safety check to ensure start_compress not called yet. */
  166331. if (dstinfo->global_state != CSTATE_START)
  166332. ERREXIT1(dstinfo, JERR_BAD_STATE, dstinfo->global_state);
  166333. /* Copy fundamental image dimensions */
  166334. dstinfo->image_width = srcinfo->image_width;
  166335. dstinfo->image_height = srcinfo->image_height;
  166336. dstinfo->input_components = srcinfo->num_components;
  166337. dstinfo->in_color_space = srcinfo->jpeg_color_space;
  166338. /* Initialize all parameters to default values */
  166339. jpeg_set_defaults(dstinfo);
  166340. /* jpeg_set_defaults may choose wrong colorspace, eg YCbCr if input is RGB.
  166341. * Fix it to get the right header markers for the image colorspace.
  166342. */
  166343. jpeg_set_colorspace(dstinfo, srcinfo->jpeg_color_space);
  166344. dstinfo->data_precision = srcinfo->data_precision;
  166345. dstinfo->CCIR601_sampling = srcinfo->CCIR601_sampling;
  166346. /* Copy the source's quantization tables. */
  166347. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  166348. if (srcinfo->quant_tbl_ptrs[tblno] != NULL) {
  166349. qtblptr = & dstinfo->quant_tbl_ptrs[tblno];
  166350. if (*qtblptr == NULL)
  166351. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) dstinfo);
  166352. MEMCOPY((*qtblptr)->quantval,
  166353. srcinfo->quant_tbl_ptrs[tblno]->quantval,
  166354. SIZEOF((*qtblptr)->quantval));
  166355. (*qtblptr)->sent_table = FALSE;
  166356. }
  166357. }
  166358. /* Copy the source's per-component info.
  166359. * Note we assume jpeg_set_defaults has allocated the dest comp_info array.
  166360. */
  166361. dstinfo->num_components = srcinfo->num_components;
  166362. if (dstinfo->num_components < 1 || dstinfo->num_components > MAX_COMPONENTS)
  166363. ERREXIT2(dstinfo, JERR_COMPONENT_COUNT, dstinfo->num_components,
  166364. MAX_COMPONENTS);
  166365. for (ci = 0, incomp = srcinfo->comp_info, outcomp = dstinfo->comp_info;
  166366. ci < dstinfo->num_components; ci++, incomp++, outcomp++) {
  166367. outcomp->component_id = incomp->component_id;
  166368. outcomp->h_samp_factor = incomp->h_samp_factor;
  166369. outcomp->v_samp_factor = incomp->v_samp_factor;
  166370. outcomp->quant_tbl_no = incomp->quant_tbl_no;
  166371. /* Make sure saved quantization table for component matches the qtable
  166372. * slot. If not, the input file re-used this qtable slot.
  166373. * IJG encoder currently cannot duplicate this.
  166374. */
  166375. tblno = outcomp->quant_tbl_no;
  166376. if (tblno < 0 || tblno >= NUM_QUANT_TBLS ||
  166377. srcinfo->quant_tbl_ptrs[tblno] == NULL)
  166378. ERREXIT1(dstinfo, JERR_NO_QUANT_TABLE, tblno);
  166379. slot_quant = srcinfo->quant_tbl_ptrs[tblno];
  166380. c_quant = incomp->quant_table;
  166381. if (c_quant != NULL) {
  166382. for (coefi = 0; coefi < DCTSIZE2; coefi++) {
  166383. if (c_quant->quantval[coefi] != slot_quant->quantval[coefi])
  166384. ERREXIT1(dstinfo, JERR_MISMATCHED_QUANT_TABLE, tblno);
  166385. }
  166386. }
  166387. /* Note: we do not copy the source's Huffman table assignments;
  166388. * instead we rely on jpeg_set_colorspace to have made a suitable choice.
  166389. */
  166390. }
  166391. /* Also copy JFIF version and resolution information, if available.
  166392. * Strictly speaking this isn't "critical" info, but it's nearly
  166393. * always appropriate to copy it if available. In particular,
  166394. * if the application chooses to copy JFIF 1.02 extension markers from
  166395. * the source file, we need to copy the version to make sure we don't
  166396. * emit a file that has 1.02 extensions but a claimed version of 1.01.
  166397. * We will *not*, however, copy version info from mislabeled "2.01" files.
  166398. */
  166399. if (srcinfo->saw_JFIF_marker) {
  166400. if (srcinfo->JFIF_major_version == 1) {
  166401. dstinfo->JFIF_major_version = srcinfo->JFIF_major_version;
  166402. dstinfo->JFIF_minor_version = srcinfo->JFIF_minor_version;
  166403. }
  166404. dstinfo->density_unit = srcinfo->density_unit;
  166405. dstinfo->X_density = srcinfo->X_density;
  166406. dstinfo->Y_density = srcinfo->Y_density;
  166407. }
  166408. }
  166409. /*
  166410. * Master selection of compression modules for transcoding.
  166411. * This substitutes for jcinit.c's initialization of the full compressor.
  166412. */
  166413. LOCAL(void)
  166414. transencode_master_selection (j_compress_ptr cinfo,
  166415. jvirt_barray_ptr * coef_arrays)
  166416. {
  166417. /* Although we don't actually use input_components for transcoding,
  166418. * jcmaster.c's initial_setup will complain if input_components is 0.
  166419. */
  166420. cinfo->input_components = 1;
  166421. /* Initialize master control (includes parameter checking/processing) */
  166422. jinit_c_master_control(cinfo, TRUE /* transcode only */);
  166423. /* Entropy encoding: either Huffman or arithmetic coding. */
  166424. if (cinfo->arith_code) {
  166425. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  166426. } else {
  166427. if (cinfo->progressive_mode) {
  166428. #ifdef C_PROGRESSIVE_SUPPORTED
  166429. jinit_phuff_encoder(cinfo);
  166430. #else
  166431. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166432. #endif
  166433. } else
  166434. jinit_huff_encoder(cinfo);
  166435. }
  166436. /* We need a special coefficient buffer controller. */
  166437. transencode_coef_controller(cinfo, coef_arrays);
  166438. jinit_marker_writer(cinfo);
  166439. /* We can now tell the memory manager to allocate virtual arrays. */
  166440. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  166441. /* Write the datastream header (SOI, JFIF) immediately.
  166442. * Frame and scan headers are postponed till later.
  166443. * This lets application insert special markers after the SOI.
  166444. */
  166445. (*cinfo->marker->write_file_header) (cinfo);
  166446. }
  166447. /*
  166448. * The rest of this file is a special implementation of the coefficient
  166449. * buffer controller. This is similar to jccoefct.c, but it handles only
  166450. * output from presupplied virtual arrays. Furthermore, we generate any
  166451. * dummy padding blocks on-the-fly rather than expecting them to be present
  166452. * in the arrays.
  166453. */
  166454. /* Private buffer controller object */
  166455. typedef struct {
  166456. struct jpeg_c_coef_controller pub; /* public fields */
  166457. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  166458. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  166459. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  166460. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  166461. /* Virtual block array for each component. */
  166462. jvirt_barray_ptr * whole_image;
  166463. /* Workspace for constructing dummy blocks at right/bottom edges. */
  166464. JBLOCKROW dummy_buffer[C_MAX_BLOCKS_IN_MCU];
  166465. } my_coef_controller2;
  166466. typedef my_coef_controller2 * my_coef_ptr2;
  166467. LOCAL(void)
  166468. start_iMCU_row2 (j_compress_ptr cinfo)
  166469. /* Reset within-iMCU-row counters for a new row */
  166470. {
  166471. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  166472. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  166473. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  166474. * But at the bottom of the image, process only what's left.
  166475. */
  166476. if (cinfo->comps_in_scan > 1) {
  166477. coef->MCU_rows_per_iMCU_row = 1;
  166478. } else {
  166479. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  166480. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  166481. else
  166482. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  166483. }
  166484. coef->mcu_ctr = 0;
  166485. coef->MCU_vert_offset = 0;
  166486. }
  166487. /*
  166488. * Initialize for a processing pass.
  166489. */
  166490. METHODDEF(void)
  166491. start_pass_coef2 (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  166492. {
  166493. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  166494. if (pass_mode != JBUF_CRANK_DEST)
  166495. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166496. coef->iMCU_row_num = 0;
  166497. start_iMCU_row2(cinfo);
  166498. }
  166499. /*
  166500. * Process some data.
  166501. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  166502. * per call, ie, v_samp_factor block rows for each component in the scan.
  166503. * The data is obtained from the virtual arrays and fed to the entropy coder.
  166504. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  166505. *
  166506. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  166507. */
  166508. METHODDEF(boolean)
  166509. compress_output2 (j_compress_ptr cinfo, JSAMPIMAGE)
  166510. {
  166511. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  166512. JDIMENSION MCU_col_num; /* index of current MCU within row */
  166513. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  166514. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  166515. int blkn, ci, xindex, yindex, yoffset, blockcnt;
  166516. JDIMENSION start_col;
  166517. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  166518. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  166519. JBLOCKROW buffer_ptr;
  166520. jpeg_component_info *compptr;
  166521. /* Align the virtual buffers for the components used in this scan. */
  166522. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166523. compptr = cinfo->cur_comp_info[ci];
  166524. buffer[ci] = (*cinfo->mem->access_virt_barray)
  166525. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  166526. coef->iMCU_row_num * compptr->v_samp_factor,
  166527. (JDIMENSION) compptr->v_samp_factor, FALSE);
  166528. }
  166529. /* Loop to process one whole iMCU row */
  166530. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  166531. yoffset++) {
  166532. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  166533. MCU_col_num++) {
  166534. /* Construct list of pointers to DCT blocks belonging to this MCU */
  166535. blkn = 0; /* index of current DCT block within MCU */
  166536. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166537. compptr = cinfo->cur_comp_info[ci];
  166538. start_col = MCU_col_num * compptr->MCU_width;
  166539. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  166540. : compptr->last_col_width;
  166541. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  166542. if (coef->iMCU_row_num < last_iMCU_row ||
  166543. yindex+yoffset < compptr->last_row_height) {
  166544. /* Fill in pointers to real blocks in this row */
  166545. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  166546. for (xindex = 0; xindex < blockcnt; xindex++)
  166547. MCU_buffer[blkn++] = buffer_ptr++;
  166548. } else {
  166549. /* At bottom of image, need a whole row of dummy blocks */
  166550. xindex = 0;
  166551. }
  166552. /* Fill in any dummy blocks needed in this row.
  166553. * Dummy blocks are filled in the same way as in jccoefct.c:
  166554. * all zeroes in the AC entries, DC entries equal to previous
  166555. * block's DC value. The init routine has already zeroed the
  166556. * AC entries, so we need only set the DC entries correctly.
  166557. */
  166558. for (; xindex < compptr->MCU_width; xindex++) {
  166559. MCU_buffer[blkn] = coef->dummy_buffer[blkn];
  166560. MCU_buffer[blkn][0][0] = MCU_buffer[blkn-1][0][0];
  166561. blkn++;
  166562. }
  166563. }
  166564. }
  166565. /* Try to write the MCU. */
  166566. if (! (*cinfo->entropy->encode_mcu) (cinfo, MCU_buffer)) {
  166567. /* Suspension forced; update state counters and exit */
  166568. coef->MCU_vert_offset = yoffset;
  166569. coef->mcu_ctr = MCU_col_num;
  166570. return FALSE;
  166571. }
  166572. }
  166573. /* Completed an MCU row, but perhaps not an iMCU row */
  166574. coef->mcu_ctr = 0;
  166575. }
  166576. /* Completed the iMCU row, advance counters for next one */
  166577. coef->iMCU_row_num++;
  166578. start_iMCU_row2(cinfo);
  166579. return TRUE;
  166580. }
  166581. /*
  166582. * Initialize coefficient buffer controller.
  166583. *
  166584. * Each passed coefficient array must be the right size for that
  166585. * coefficient: width_in_blocks wide and height_in_blocks high,
  166586. * with unitheight at least v_samp_factor.
  166587. */
  166588. LOCAL(void)
  166589. transencode_coef_controller (j_compress_ptr cinfo,
  166590. jvirt_barray_ptr * coef_arrays)
  166591. {
  166592. my_coef_ptr2 coef;
  166593. JBLOCKROW buffer;
  166594. int i;
  166595. coef = (my_coef_ptr2)
  166596. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166597. SIZEOF(my_coef_controller2));
  166598. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  166599. coef->pub.start_pass = start_pass_coef2;
  166600. coef->pub.compress_data = compress_output2;
  166601. /* Save pointer to virtual arrays */
  166602. coef->whole_image = coef_arrays;
  166603. /* Allocate and pre-zero space for dummy DCT blocks. */
  166604. buffer = (JBLOCKROW)
  166605. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166606. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  166607. jzero_far((void FAR *) buffer, C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  166608. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  166609. coef->dummy_buffer[i] = buffer + i;
  166610. }
  166611. }
  166612. /*** End of inlined file: jctrans.c ***/
  166613. /*** Start of inlined file: jdapistd.c ***/
  166614. #define JPEG_INTERNALS
  166615. /* Forward declarations */
  166616. LOCAL(boolean) output_pass_setup JPP((j_decompress_ptr cinfo));
  166617. /*
  166618. * Decompression initialization.
  166619. * jpeg_read_header must be completed before calling this.
  166620. *
  166621. * If a multipass operating mode was selected, this will do all but the
  166622. * last pass, and thus may take a great deal of time.
  166623. *
  166624. * Returns FALSE if suspended. The return value need be inspected only if
  166625. * a suspending data source is used.
  166626. */
  166627. GLOBAL(boolean)
  166628. jpeg_start_decompress (j_decompress_ptr cinfo)
  166629. {
  166630. if (cinfo->global_state == DSTATE_READY) {
  166631. /* First call: initialize master control, select active modules */
  166632. jinit_master_decompress(cinfo);
  166633. if (cinfo->buffered_image) {
  166634. /* No more work here; expecting jpeg_start_output next */
  166635. cinfo->global_state = DSTATE_BUFIMAGE;
  166636. return TRUE;
  166637. }
  166638. cinfo->global_state = DSTATE_PRELOAD;
  166639. }
  166640. if (cinfo->global_state == DSTATE_PRELOAD) {
  166641. /* If file has multiple scans, absorb them all into the coef buffer */
  166642. if (cinfo->inputctl->has_multiple_scans) {
  166643. #ifdef D_MULTISCAN_FILES_SUPPORTED
  166644. for (;;) {
  166645. int retcode;
  166646. /* Call progress monitor hook if present */
  166647. if (cinfo->progress != NULL)
  166648. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  166649. /* Absorb some more input */
  166650. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  166651. if (retcode == JPEG_SUSPENDED)
  166652. return FALSE;
  166653. if (retcode == JPEG_REACHED_EOI)
  166654. break;
  166655. /* Advance progress counter if appropriate */
  166656. if (cinfo->progress != NULL &&
  166657. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  166658. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  166659. /* jdmaster underestimated number of scans; ratchet up one scan */
  166660. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  166661. }
  166662. }
  166663. }
  166664. #else
  166665. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166666. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  166667. }
  166668. cinfo->output_scan_number = cinfo->input_scan_number;
  166669. } else if (cinfo->global_state != DSTATE_PRESCAN)
  166670. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166671. /* Perform any dummy output passes, and set up for the final pass */
  166672. return output_pass_setup(cinfo);
  166673. }
  166674. /*
  166675. * Set up for an output pass, and perform any dummy pass(es) needed.
  166676. * Common subroutine for jpeg_start_decompress and jpeg_start_output.
  166677. * Entry: global_state = DSTATE_PRESCAN only if previously suspended.
  166678. * Exit: If done, returns TRUE and sets global_state for proper output mode.
  166679. * If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN.
  166680. */
  166681. LOCAL(boolean)
  166682. output_pass_setup (j_decompress_ptr cinfo)
  166683. {
  166684. if (cinfo->global_state != DSTATE_PRESCAN) {
  166685. /* First call: do pass setup */
  166686. (*cinfo->master->prepare_for_output_pass) (cinfo);
  166687. cinfo->output_scanline = 0;
  166688. cinfo->global_state = DSTATE_PRESCAN;
  166689. }
  166690. /* Loop over any required dummy passes */
  166691. while (cinfo->master->is_dummy_pass) {
  166692. #ifdef QUANT_2PASS_SUPPORTED
  166693. /* Crank through the dummy pass */
  166694. while (cinfo->output_scanline < cinfo->output_height) {
  166695. JDIMENSION last_scanline;
  166696. /* Call progress monitor hook if present */
  166697. if (cinfo->progress != NULL) {
  166698. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  166699. cinfo->progress->pass_limit = (long) cinfo->output_height;
  166700. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  166701. }
  166702. /* Process some data */
  166703. last_scanline = cinfo->output_scanline;
  166704. (*cinfo->main->process_data) (cinfo, (JSAMPARRAY) NULL,
  166705. &cinfo->output_scanline, (JDIMENSION) 0);
  166706. if (cinfo->output_scanline == last_scanline)
  166707. return FALSE; /* No progress made, must suspend */
  166708. }
  166709. /* Finish up dummy pass, and set up for another one */
  166710. (*cinfo->master->finish_output_pass) (cinfo);
  166711. (*cinfo->master->prepare_for_output_pass) (cinfo);
  166712. cinfo->output_scanline = 0;
  166713. #else
  166714. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166715. #endif /* QUANT_2PASS_SUPPORTED */
  166716. }
  166717. /* Ready for application to drive output pass through
  166718. * jpeg_read_scanlines or jpeg_read_raw_data.
  166719. */
  166720. cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING;
  166721. return TRUE;
  166722. }
  166723. /*
  166724. * Read some scanlines of data from the JPEG decompressor.
  166725. *
  166726. * The return value will be the number of lines actually read.
  166727. * This may be less than the number requested in several cases,
  166728. * including bottom of image, data source suspension, and operating
  166729. * modes that emit multiple scanlines at a time.
  166730. *
  166731. * Note: we warn about excess calls to jpeg_read_scanlines() since
  166732. * this likely signals an application programmer error. However,
  166733. * an oversize buffer (max_lines > scanlines remaining) is not an error.
  166734. */
  166735. GLOBAL(JDIMENSION)
  166736. jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines,
  166737. JDIMENSION max_lines)
  166738. {
  166739. JDIMENSION row_ctr;
  166740. if (cinfo->global_state != DSTATE_SCANNING)
  166741. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166742. if (cinfo->output_scanline >= cinfo->output_height) {
  166743. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  166744. return 0;
  166745. }
  166746. /* Call progress monitor hook if present */
  166747. if (cinfo->progress != NULL) {
  166748. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  166749. cinfo->progress->pass_limit = (long) cinfo->output_height;
  166750. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  166751. }
  166752. /* Process some data */
  166753. row_ctr = 0;
  166754. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, max_lines);
  166755. cinfo->output_scanline += row_ctr;
  166756. return row_ctr;
  166757. }
  166758. /*
  166759. * Alternate entry point to read raw data.
  166760. * Processes exactly one iMCU row per call, unless suspended.
  166761. */
  166762. GLOBAL(JDIMENSION)
  166763. jpeg_read_raw_data (j_decompress_ptr cinfo, JSAMPIMAGE data,
  166764. JDIMENSION max_lines)
  166765. {
  166766. JDIMENSION lines_per_iMCU_row;
  166767. if (cinfo->global_state != DSTATE_RAW_OK)
  166768. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166769. if (cinfo->output_scanline >= cinfo->output_height) {
  166770. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  166771. return 0;
  166772. }
  166773. /* Call progress monitor hook if present */
  166774. if (cinfo->progress != NULL) {
  166775. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  166776. cinfo->progress->pass_limit = (long) cinfo->output_height;
  166777. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  166778. }
  166779. /* Verify that at least one iMCU row can be returned. */
  166780. lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size;
  166781. if (max_lines < lines_per_iMCU_row)
  166782. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  166783. /* Decompress directly into user's buffer. */
  166784. if (! (*cinfo->coef->decompress_data) (cinfo, data))
  166785. return 0; /* suspension forced, can do nothing more */
  166786. /* OK, we processed one iMCU row. */
  166787. cinfo->output_scanline += lines_per_iMCU_row;
  166788. return lines_per_iMCU_row;
  166789. }
  166790. /* Additional entry points for buffered-image mode. */
  166791. #ifdef D_MULTISCAN_FILES_SUPPORTED
  166792. /*
  166793. * Initialize for an output pass in buffered-image mode.
  166794. */
  166795. GLOBAL(boolean)
  166796. jpeg_start_output (j_decompress_ptr cinfo, int scan_number)
  166797. {
  166798. if (cinfo->global_state != DSTATE_BUFIMAGE &&
  166799. cinfo->global_state != DSTATE_PRESCAN)
  166800. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166801. /* Limit scan number to valid range */
  166802. if (scan_number <= 0)
  166803. scan_number = 1;
  166804. if (cinfo->inputctl->eoi_reached &&
  166805. scan_number > cinfo->input_scan_number)
  166806. scan_number = cinfo->input_scan_number;
  166807. cinfo->output_scan_number = scan_number;
  166808. /* Perform any dummy output passes, and set up for the real pass */
  166809. return output_pass_setup(cinfo);
  166810. }
  166811. /*
  166812. * Finish up after an output pass in buffered-image mode.
  166813. *
  166814. * Returns FALSE if suspended. The return value need be inspected only if
  166815. * a suspending data source is used.
  166816. */
  166817. GLOBAL(boolean)
  166818. jpeg_finish_output (j_decompress_ptr cinfo)
  166819. {
  166820. if ((cinfo->global_state == DSTATE_SCANNING ||
  166821. cinfo->global_state == DSTATE_RAW_OK) && cinfo->buffered_image) {
  166822. /* Terminate this pass. */
  166823. /* We do not require the whole pass to have been completed. */
  166824. (*cinfo->master->finish_output_pass) (cinfo);
  166825. cinfo->global_state = DSTATE_BUFPOST;
  166826. } else if (cinfo->global_state != DSTATE_BUFPOST) {
  166827. /* BUFPOST = repeat call after a suspension, anything else is error */
  166828. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166829. }
  166830. /* Read markers looking for SOS or EOI */
  166831. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  166832. ! cinfo->inputctl->eoi_reached) {
  166833. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  166834. return FALSE; /* Suspend, come back later */
  166835. }
  166836. cinfo->global_state = DSTATE_BUFIMAGE;
  166837. return TRUE;
  166838. }
  166839. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  166840. /*** End of inlined file: jdapistd.c ***/
  166841. /*** Start of inlined file: jdapimin.c ***/
  166842. #define JPEG_INTERNALS
  166843. /*
  166844. * Initialization of a JPEG decompression object.
  166845. * The error manager must already be set up (in case memory manager fails).
  166846. */
  166847. GLOBAL(void)
  166848. jpeg_CreateDecompress (j_decompress_ptr cinfo, int version, size_t structsize)
  166849. {
  166850. int i;
  166851. /* Guard against version mismatches between library and caller. */
  166852. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  166853. if (version != JPEG_LIB_VERSION)
  166854. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  166855. if (structsize != SIZEOF(struct jpeg_decompress_struct))
  166856. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  166857. (int) SIZEOF(struct jpeg_decompress_struct), (int) structsize);
  166858. /* For debugging purposes, we zero the whole master structure.
  166859. * But the application has already set the err pointer, and may have set
  166860. * client_data, so we have to save and restore those fields.
  166861. * Note: if application hasn't set client_data, tools like Purify may
  166862. * complain here.
  166863. */
  166864. {
  166865. struct jpeg_error_mgr * err = cinfo->err;
  166866. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  166867. MEMZERO(cinfo, SIZEOF(struct jpeg_decompress_struct));
  166868. cinfo->err = err;
  166869. cinfo->client_data = client_data;
  166870. }
  166871. cinfo->is_decompressor = TRUE;
  166872. /* Initialize a memory manager instance for this object */
  166873. jinit_memory_mgr((j_common_ptr) cinfo);
  166874. /* Zero out pointers to permanent structures. */
  166875. cinfo->progress = NULL;
  166876. cinfo->src = NULL;
  166877. for (i = 0; i < NUM_QUANT_TBLS; i++)
  166878. cinfo->quant_tbl_ptrs[i] = NULL;
  166879. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  166880. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  166881. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  166882. }
  166883. /* Initialize marker processor so application can override methods
  166884. * for COM, APPn markers before calling jpeg_read_header.
  166885. */
  166886. cinfo->marker_list = NULL;
  166887. jinit_marker_reader(cinfo);
  166888. /* And initialize the overall input controller. */
  166889. jinit_input_controller(cinfo);
  166890. /* OK, I'm ready */
  166891. cinfo->global_state = DSTATE_START;
  166892. }
  166893. /*
  166894. * Destruction of a JPEG decompression object
  166895. */
  166896. GLOBAL(void)
  166897. jpeg_destroy_decompress (j_decompress_ptr cinfo)
  166898. {
  166899. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  166900. }
  166901. /*
  166902. * Abort processing of a JPEG decompression operation,
  166903. * but don't destroy the object itself.
  166904. */
  166905. GLOBAL(void)
  166906. jpeg_abort_decompress (j_decompress_ptr cinfo)
  166907. {
  166908. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  166909. }
  166910. /*
  166911. * Set default decompression parameters.
  166912. */
  166913. LOCAL(void)
  166914. default_decompress_parms (j_decompress_ptr cinfo)
  166915. {
  166916. /* Guess the input colorspace, and set output colorspace accordingly. */
  166917. /* (Wish JPEG committee had provided a real way to specify this...) */
  166918. /* Note application may override our guesses. */
  166919. switch (cinfo->num_components) {
  166920. case 1:
  166921. cinfo->jpeg_color_space = JCS_GRAYSCALE;
  166922. cinfo->out_color_space = JCS_GRAYSCALE;
  166923. break;
  166924. case 3:
  166925. if (cinfo->saw_JFIF_marker) {
  166926. cinfo->jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */
  166927. } else if (cinfo->saw_Adobe_marker) {
  166928. switch (cinfo->Adobe_transform) {
  166929. case 0:
  166930. cinfo->jpeg_color_space = JCS_RGB;
  166931. break;
  166932. case 1:
  166933. cinfo->jpeg_color_space = JCS_YCbCr;
  166934. break;
  166935. default:
  166936. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  166937. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  166938. break;
  166939. }
  166940. } else {
  166941. /* Saw no special markers, try to guess from the component IDs */
  166942. int cid0 = cinfo->comp_info[0].component_id;
  166943. int cid1 = cinfo->comp_info[1].component_id;
  166944. int cid2 = cinfo->comp_info[2].component_id;
  166945. if (cid0 == 1 && cid1 == 2 && cid2 == 3)
  166946. cinfo->jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */
  166947. else if (cid0 == 82 && cid1 == 71 && cid2 == 66)
  166948. cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */
  166949. else {
  166950. TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2);
  166951. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  166952. }
  166953. }
  166954. /* Always guess RGB is proper output colorspace. */
  166955. cinfo->out_color_space = JCS_RGB;
  166956. break;
  166957. case 4:
  166958. if (cinfo->saw_Adobe_marker) {
  166959. switch (cinfo->Adobe_transform) {
  166960. case 0:
  166961. cinfo->jpeg_color_space = JCS_CMYK;
  166962. break;
  166963. case 2:
  166964. cinfo->jpeg_color_space = JCS_YCCK;
  166965. break;
  166966. default:
  166967. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  166968. cinfo->jpeg_color_space = JCS_YCCK; /* assume it's YCCK */
  166969. break;
  166970. }
  166971. } else {
  166972. /* No special markers, assume straight CMYK. */
  166973. cinfo->jpeg_color_space = JCS_CMYK;
  166974. }
  166975. cinfo->out_color_space = JCS_CMYK;
  166976. break;
  166977. default:
  166978. cinfo->jpeg_color_space = JCS_UNKNOWN;
  166979. cinfo->out_color_space = JCS_UNKNOWN;
  166980. break;
  166981. }
  166982. /* Set defaults for other decompression parameters. */
  166983. cinfo->scale_num = 1; /* 1:1 scaling */
  166984. cinfo->scale_denom = 1;
  166985. cinfo->output_gamma = 1.0;
  166986. cinfo->buffered_image = FALSE;
  166987. cinfo->raw_data_out = FALSE;
  166988. cinfo->dct_method = JDCT_DEFAULT;
  166989. cinfo->do_fancy_upsampling = TRUE;
  166990. cinfo->do_block_smoothing = TRUE;
  166991. cinfo->quantize_colors = FALSE;
  166992. /* We set these in case application only sets quantize_colors. */
  166993. cinfo->dither_mode = JDITHER_FS;
  166994. #ifdef QUANT_2PASS_SUPPORTED
  166995. cinfo->two_pass_quantize = TRUE;
  166996. #else
  166997. cinfo->two_pass_quantize = FALSE;
  166998. #endif
  166999. cinfo->desired_number_of_colors = 256;
  167000. cinfo->colormap = NULL;
  167001. /* Initialize for no mode change in buffered-image mode. */
  167002. cinfo->enable_1pass_quant = FALSE;
  167003. cinfo->enable_external_quant = FALSE;
  167004. cinfo->enable_2pass_quant = FALSE;
  167005. }
  167006. /*
  167007. * Decompression startup: read start of JPEG datastream to see what's there.
  167008. * Need only initialize JPEG object and supply a data source before calling.
  167009. *
  167010. * This routine will read as far as the first SOS marker (ie, actual start of
  167011. * compressed data), and will save all tables and parameters in the JPEG
  167012. * object. It will also initialize the decompression parameters to default
  167013. * values, and finally return JPEG_HEADER_OK. On return, the application may
  167014. * adjust the decompression parameters and then call jpeg_start_decompress.
  167015. * (Or, if the application only wanted to determine the image parameters,
  167016. * the data need not be decompressed. In that case, call jpeg_abort or
  167017. * jpeg_destroy to release any temporary space.)
  167018. * If an abbreviated (tables only) datastream is presented, the routine will
  167019. * return JPEG_HEADER_TABLES_ONLY upon reaching EOI. The application may then
  167020. * re-use the JPEG object to read the abbreviated image datastream(s).
  167021. * It is unnecessary (but OK) to call jpeg_abort in this case.
  167022. * The JPEG_SUSPENDED return code only occurs if the data source module
  167023. * requests suspension of the decompressor. In this case the application
  167024. * should load more source data and then re-call jpeg_read_header to resume
  167025. * processing.
  167026. * If a non-suspending data source is used and require_image is TRUE, then the
  167027. * return code need not be inspected since only JPEG_HEADER_OK is possible.
  167028. *
  167029. * This routine is now just a front end to jpeg_consume_input, with some
  167030. * extra error checking.
  167031. */
  167032. GLOBAL(int)
  167033. jpeg_read_header (j_decompress_ptr cinfo, boolean require_image)
  167034. {
  167035. int retcode;
  167036. if (cinfo->global_state != DSTATE_START &&
  167037. cinfo->global_state != DSTATE_INHEADER)
  167038. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167039. retcode = jpeg_consume_input(cinfo);
  167040. switch (retcode) {
  167041. case JPEG_REACHED_SOS:
  167042. retcode = JPEG_HEADER_OK;
  167043. break;
  167044. case JPEG_REACHED_EOI:
  167045. if (require_image) /* Complain if application wanted an image */
  167046. ERREXIT(cinfo, JERR_NO_IMAGE);
  167047. /* Reset to start state; it would be safer to require the application to
  167048. * call jpeg_abort, but we can't change it now for compatibility reasons.
  167049. * A side effect is to free any temporary memory (there shouldn't be any).
  167050. */
  167051. jpeg_abort((j_common_ptr) cinfo); /* sets state = DSTATE_START */
  167052. retcode = JPEG_HEADER_TABLES_ONLY;
  167053. break;
  167054. case JPEG_SUSPENDED:
  167055. /* no work */
  167056. break;
  167057. }
  167058. return retcode;
  167059. }
  167060. /*
  167061. * Consume data in advance of what the decompressor requires.
  167062. * This can be called at any time once the decompressor object has
  167063. * been created and a data source has been set up.
  167064. *
  167065. * This routine is essentially a state machine that handles a couple
  167066. * of critical state-transition actions, namely initial setup and
  167067. * transition from header scanning to ready-for-start_decompress.
  167068. * All the actual input is done via the input controller's consume_input
  167069. * method.
  167070. */
  167071. GLOBAL(int)
  167072. jpeg_consume_input (j_decompress_ptr cinfo)
  167073. {
  167074. int retcode = JPEG_SUSPENDED;
  167075. /* NB: every possible DSTATE value should be listed in this switch */
  167076. switch (cinfo->global_state) {
  167077. case DSTATE_START:
  167078. /* Start-of-datastream actions: reset appropriate modules */
  167079. (*cinfo->inputctl->reset_input_controller) (cinfo);
  167080. /* Initialize application's data source module */
  167081. (*cinfo->src->init_source) (cinfo);
  167082. cinfo->global_state = DSTATE_INHEADER;
  167083. /*FALLTHROUGH*/
  167084. case DSTATE_INHEADER:
  167085. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167086. if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */
  167087. /* Set up default parameters based on header data */
  167088. default_decompress_parms(cinfo);
  167089. /* Set global state: ready for start_decompress */
  167090. cinfo->global_state = DSTATE_READY;
  167091. }
  167092. break;
  167093. case DSTATE_READY:
  167094. /* Can't advance past first SOS until start_decompress is called */
  167095. retcode = JPEG_REACHED_SOS;
  167096. break;
  167097. case DSTATE_PRELOAD:
  167098. case DSTATE_PRESCAN:
  167099. case DSTATE_SCANNING:
  167100. case DSTATE_RAW_OK:
  167101. case DSTATE_BUFIMAGE:
  167102. case DSTATE_BUFPOST:
  167103. case DSTATE_STOPPING:
  167104. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167105. break;
  167106. default:
  167107. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167108. }
  167109. return retcode;
  167110. }
  167111. /*
  167112. * Have we finished reading the input file?
  167113. */
  167114. GLOBAL(boolean)
  167115. jpeg_input_complete (j_decompress_ptr cinfo)
  167116. {
  167117. /* Check for valid jpeg object */
  167118. if (cinfo->global_state < DSTATE_START ||
  167119. cinfo->global_state > DSTATE_STOPPING)
  167120. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167121. return cinfo->inputctl->eoi_reached;
  167122. }
  167123. /*
  167124. * Is there more than one scan?
  167125. */
  167126. GLOBAL(boolean)
  167127. jpeg_has_multiple_scans (j_decompress_ptr cinfo)
  167128. {
  167129. /* Only valid after jpeg_read_header completes */
  167130. if (cinfo->global_state < DSTATE_READY ||
  167131. cinfo->global_state > DSTATE_STOPPING)
  167132. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167133. return cinfo->inputctl->has_multiple_scans;
  167134. }
  167135. /*
  167136. * Finish JPEG decompression.
  167137. *
  167138. * This will normally just verify the file trailer and release temp storage.
  167139. *
  167140. * Returns FALSE if suspended. The return value need be inspected only if
  167141. * a suspending data source is used.
  167142. */
  167143. GLOBAL(boolean)
  167144. jpeg_finish_decompress (j_decompress_ptr cinfo)
  167145. {
  167146. if ((cinfo->global_state == DSTATE_SCANNING ||
  167147. cinfo->global_state == DSTATE_RAW_OK) && ! cinfo->buffered_image) {
  167148. /* Terminate final pass of non-buffered mode */
  167149. if (cinfo->output_scanline < cinfo->output_height)
  167150. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  167151. (*cinfo->master->finish_output_pass) (cinfo);
  167152. cinfo->global_state = DSTATE_STOPPING;
  167153. } else if (cinfo->global_state == DSTATE_BUFIMAGE) {
  167154. /* Finishing after a buffered-image operation */
  167155. cinfo->global_state = DSTATE_STOPPING;
  167156. } else if (cinfo->global_state != DSTATE_STOPPING) {
  167157. /* STOPPING = repeat call after a suspension, anything else is error */
  167158. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167159. }
  167160. /* Read until EOI */
  167161. while (! cinfo->inputctl->eoi_reached) {
  167162. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  167163. return FALSE; /* Suspend, come back later */
  167164. }
  167165. /* Do final cleanup */
  167166. (*cinfo->src->term_source) (cinfo);
  167167. /* We can use jpeg_abort to release memory and reset global_state */
  167168. jpeg_abort((j_common_ptr) cinfo);
  167169. return TRUE;
  167170. }
  167171. /*** End of inlined file: jdapimin.c ***/
  167172. /*** Start of inlined file: jdatasrc.c ***/
  167173. /* this is not a core library module, so it doesn't define JPEG_INTERNALS */
  167174. /*** Start of inlined file: jerror.h ***/
  167175. /*
  167176. * To define the enum list of message codes, include this file without
  167177. * defining macro JMESSAGE. To create a message string table, include it
  167178. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  167179. */
  167180. #ifndef JMESSAGE
  167181. #ifndef JERROR_H
  167182. /* First time through, define the enum list */
  167183. #define JMAKE_ENUM_LIST
  167184. #else
  167185. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  167186. #define JMESSAGE(code,string)
  167187. #endif /* JERROR_H */
  167188. #endif /* JMESSAGE */
  167189. #ifdef JMAKE_ENUM_LIST
  167190. typedef enum {
  167191. #define JMESSAGE(code,string) code ,
  167192. #endif /* JMAKE_ENUM_LIST */
  167193. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  167194. /* For maintenance convenience, list is alphabetical by message code name */
  167195. JMESSAGE(JERR_ARITH_NOTIMPL,
  167196. "Sorry, there are legal restrictions on arithmetic coding")
  167197. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  167198. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  167199. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  167200. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  167201. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  167202. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  167203. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  167204. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  167205. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  167206. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  167207. JMESSAGE(JERR_BAD_LIB_VERSION,
  167208. "Wrong JPEG library version: library is %d, caller expects %d")
  167209. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  167210. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  167211. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  167212. JMESSAGE(JERR_BAD_PROGRESSION,
  167213. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  167214. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  167215. "Invalid progressive parameters at scan script entry %d")
  167216. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  167217. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  167218. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  167219. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  167220. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  167221. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  167222. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  167223. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  167224. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  167225. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  167226. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  167227. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  167228. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  167229. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  167230. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  167231. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  167232. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  167233. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  167234. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  167235. JMESSAGE(JERR_FILE_READ, "Input file read error")
  167236. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  167237. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  167238. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  167239. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  167240. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  167241. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  167242. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  167243. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  167244. "Cannot transcode due to multiple use of quantization table %d")
  167245. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  167246. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  167247. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  167248. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  167249. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  167250. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  167251. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  167252. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  167253. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  167254. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  167255. JMESSAGE(JERR_QUANT_COMPONENTS,
  167256. "Cannot quantize more than %d color components")
  167257. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  167258. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  167259. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  167260. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  167261. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  167262. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  167263. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  167264. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  167265. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  167266. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  167267. JMESSAGE(JERR_TFILE_WRITE,
  167268. "Write failed on temporary file --- out of disk space?")
  167269. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  167270. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  167271. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  167272. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  167273. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  167274. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  167275. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  167276. JMESSAGE(JMSG_VERSION, JVERSION)
  167277. JMESSAGE(JTRC_16BIT_TABLES,
  167278. "Caution: quantization tables are too coarse for baseline JPEG")
  167279. JMESSAGE(JTRC_ADOBE,
  167280. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  167281. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  167282. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  167283. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  167284. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  167285. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  167286. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  167287. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  167288. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  167289. JMESSAGE(JTRC_EOI, "End Of Image")
  167290. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  167291. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  167292. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  167293. "Warning: thumbnail image size does not match data length %u")
  167294. JMESSAGE(JTRC_JFIF_EXTENSION,
  167295. "JFIF extension marker: type 0x%02x, length %u")
  167296. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  167297. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  167298. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  167299. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  167300. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  167301. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  167302. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  167303. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  167304. JMESSAGE(JTRC_RST, "RST%d")
  167305. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  167306. "Smoothing not supported with nonstandard sampling ratios")
  167307. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  167308. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  167309. JMESSAGE(JTRC_SOI, "Start of Image")
  167310. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  167311. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  167312. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  167313. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  167314. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  167315. JMESSAGE(JTRC_THUMB_JPEG,
  167316. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  167317. JMESSAGE(JTRC_THUMB_PALETTE,
  167318. "JFIF extension marker: palette thumbnail image, length %u")
  167319. JMESSAGE(JTRC_THUMB_RGB,
  167320. "JFIF extension marker: RGB thumbnail image, length %u")
  167321. JMESSAGE(JTRC_UNKNOWN_IDS,
  167322. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  167323. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  167324. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  167325. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  167326. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  167327. "Inconsistent progression sequence for component %d coefficient %d")
  167328. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  167329. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  167330. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  167331. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  167332. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  167333. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  167334. JMESSAGE(JWRN_MUST_RESYNC,
  167335. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  167336. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  167337. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  167338. #ifdef JMAKE_ENUM_LIST
  167339. JMSG_LASTMSGCODE
  167340. } J_MESSAGE_CODE;
  167341. #undef JMAKE_ENUM_LIST
  167342. #endif /* JMAKE_ENUM_LIST */
  167343. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  167344. #undef JMESSAGE
  167345. #ifndef JERROR_H
  167346. #define JERROR_H
  167347. /* Macros to simplify using the error and trace message stuff */
  167348. /* The first parameter is either type of cinfo pointer */
  167349. /* Fatal errors (print message and exit) */
  167350. #define ERREXIT(cinfo,code) \
  167351. ((cinfo)->err->msg_code = (code), \
  167352. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167353. #define ERREXIT1(cinfo,code,p1) \
  167354. ((cinfo)->err->msg_code = (code), \
  167355. (cinfo)->err->msg_parm.i[0] = (p1), \
  167356. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167357. #define ERREXIT2(cinfo,code,p1,p2) \
  167358. ((cinfo)->err->msg_code = (code), \
  167359. (cinfo)->err->msg_parm.i[0] = (p1), \
  167360. (cinfo)->err->msg_parm.i[1] = (p2), \
  167361. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167362. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  167363. ((cinfo)->err->msg_code = (code), \
  167364. (cinfo)->err->msg_parm.i[0] = (p1), \
  167365. (cinfo)->err->msg_parm.i[1] = (p2), \
  167366. (cinfo)->err->msg_parm.i[2] = (p3), \
  167367. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167368. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  167369. ((cinfo)->err->msg_code = (code), \
  167370. (cinfo)->err->msg_parm.i[0] = (p1), \
  167371. (cinfo)->err->msg_parm.i[1] = (p2), \
  167372. (cinfo)->err->msg_parm.i[2] = (p3), \
  167373. (cinfo)->err->msg_parm.i[3] = (p4), \
  167374. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167375. #define ERREXITS(cinfo,code,str) \
  167376. ((cinfo)->err->msg_code = (code), \
  167377. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  167378. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167379. #define MAKESTMT(stuff) do { stuff } while (0)
  167380. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  167381. #define WARNMS(cinfo,code) \
  167382. ((cinfo)->err->msg_code = (code), \
  167383. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  167384. #define WARNMS1(cinfo,code,p1) \
  167385. ((cinfo)->err->msg_code = (code), \
  167386. (cinfo)->err->msg_parm.i[0] = (p1), \
  167387. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  167388. #define WARNMS2(cinfo,code,p1,p2) \
  167389. ((cinfo)->err->msg_code = (code), \
  167390. (cinfo)->err->msg_parm.i[0] = (p1), \
  167391. (cinfo)->err->msg_parm.i[1] = (p2), \
  167392. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  167393. /* Informational/debugging messages */
  167394. #define TRACEMS(cinfo,lvl,code) \
  167395. ((cinfo)->err->msg_code = (code), \
  167396. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  167397. #define TRACEMS1(cinfo,lvl,code,p1) \
  167398. ((cinfo)->err->msg_code = (code), \
  167399. (cinfo)->err->msg_parm.i[0] = (p1), \
  167400. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  167401. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  167402. ((cinfo)->err->msg_code = (code), \
  167403. (cinfo)->err->msg_parm.i[0] = (p1), \
  167404. (cinfo)->err->msg_parm.i[1] = (p2), \
  167405. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  167406. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  167407. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  167408. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  167409. (cinfo)->err->msg_code = (code); \
  167410. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  167411. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  167412. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  167413. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  167414. (cinfo)->err->msg_code = (code); \
  167415. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  167416. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  167417. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  167418. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  167419. _mp[4] = (p5); \
  167420. (cinfo)->err->msg_code = (code); \
  167421. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  167422. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  167423. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  167424. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  167425. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  167426. (cinfo)->err->msg_code = (code); \
  167427. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  167428. #define TRACEMSS(cinfo,lvl,code,str) \
  167429. ((cinfo)->err->msg_code = (code), \
  167430. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  167431. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  167432. #endif /* JERROR_H */
  167433. /*** End of inlined file: jerror.h ***/
  167434. /* Expanded data source object for stdio input */
  167435. typedef struct {
  167436. struct jpeg_source_mgr pub; /* public fields */
  167437. FILE * infile; /* source stream */
  167438. JOCTET * buffer; /* start of buffer */
  167439. boolean start_of_file; /* have we gotten any data yet? */
  167440. } my_source_mgr;
  167441. typedef my_source_mgr * my_src_ptr;
  167442. #define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */
  167443. /*
  167444. * Initialize source --- called by jpeg_read_header
  167445. * before any data is actually read.
  167446. */
  167447. METHODDEF(void)
  167448. init_source (j_decompress_ptr cinfo)
  167449. {
  167450. my_src_ptr src = (my_src_ptr) cinfo->src;
  167451. /* We reset the empty-input-file flag for each image,
  167452. * but we don't clear the input buffer.
  167453. * This is correct behavior for reading a series of images from one source.
  167454. */
  167455. src->start_of_file = TRUE;
  167456. }
  167457. /*
  167458. * Fill the input buffer --- called whenever buffer is emptied.
  167459. *
  167460. * In typical applications, this should read fresh data into the buffer
  167461. * (ignoring the current state of next_input_byte & bytes_in_buffer),
  167462. * reset the pointer & count to the start of the buffer, and return TRUE
  167463. * indicating that the buffer has been reloaded. It is not necessary to
  167464. * fill the buffer entirely, only to obtain at least one more byte.
  167465. *
  167466. * There is no such thing as an EOF return. If the end of the file has been
  167467. * reached, the routine has a choice of ERREXIT() or inserting fake data into
  167468. * the buffer. In most cases, generating a warning message and inserting a
  167469. * fake EOI marker is the best course of action --- this will allow the
  167470. * decompressor to output however much of the image is there. However,
  167471. * the resulting error message is misleading if the real problem is an empty
  167472. * input file, so we handle that case specially.
  167473. *
  167474. * In applications that need to be able to suspend compression due to input
  167475. * not being available yet, a FALSE return indicates that no more data can be
  167476. * obtained right now, but more may be forthcoming later. In this situation,
  167477. * the decompressor will return to its caller (with an indication of the
  167478. * number of scanlines it has read, if any). The application should resume
  167479. * decompression after it has loaded more data into the input buffer. Note
  167480. * that there are substantial restrictions on the use of suspension --- see
  167481. * the documentation.
  167482. *
  167483. * When suspending, the decompressor will back up to a convenient restart point
  167484. * (typically the start of the current MCU). next_input_byte & bytes_in_buffer
  167485. * indicate where the restart point will be if the current call returns FALSE.
  167486. * Data beyond this point must be rescanned after resumption, so move it to
  167487. * the front of the buffer rather than discarding it.
  167488. */
  167489. METHODDEF(boolean)
  167490. fill_input_buffer (j_decompress_ptr cinfo)
  167491. {
  167492. my_src_ptr src = (my_src_ptr) cinfo->src;
  167493. size_t nbytes;
  167494. nbytes = JFREAD(src->infile, src->buffer, INPUT_BUF_SIZE);
  167495. if (nbytes <= 0) {
  167496. if (src->start_of_file) /* Treat empty input file as fatal error */
  167497. ERREXIT(cinfo, JERR_INPUT_EMPTY);
  167498. WARNMS(cinfo, JWRN_JPEG_EOF);
  167499. /* Insert a fake EOI marker */
  167500. src->buffer[0] = (JOCTET) 0xFF;
  167501. src->buffer[1] = (JOCTET) JPEG_EOI;
  167502. nbytes = 2;
  167503. }
  167504. src->pub.next_input_byte = src->buffer;
  167505. src->pub.bytes_in_buffer = nbytes;
  167506. src->start_of_file = FALSE;
  167507. return TRUE;
  167508. }
  167509. /*
  167510. * Skip data --- used to skip over a potentially large amount of
  167511. * uninteresting data (such as an APPn marker).
  167512. *
  167513. * Writers of suspendable-input applications must note that skip_input_data
  167514. * is not granted the right to give a suspension return. If the skip extends
  167515. * beyond the data currently in the buffer, the buffer can be marked empty so
  167516. * that the next read will cause a fill_input_buffer call that can suspend.
  167517. * Arranging for additional bytes to be discarded before reloading the input
  167518. * buffer is the application writer's problem.
  167519. */
  167520. METHODDEF(void)
  167521. skip_input_data (j_decompress_ptr cinfo, long num_bytes)
  167522. {
  167523. my_src_ptr src = (my_src_ptr) cinfo->src;
  167524. /* Just a dumb implementation for now. Could use fseek() except
  167525. * it doesn't work on pipes. Not clear that being smart is worth
  167526. * any trouble anyway --- large skips are infrequent.
  167527. */
  167528. if (num_bytes > 0) {
  167529. while (num_bytes > (long) src->pub.bytes_in_buffer) {
  167530. num_bytes -= (long) src->pub.bytes_in_buffer;
  167531. (void) fill_input_buffer(cinfo);
  167532. /* note we assume that fill_input_buffer will never return FALSE,
  167533. * so suspension need not be handled.
  167534. */
  167535. }
  167536. src->pub.next_input_byte += (size_t) num_bytes;
  167537. src->pub.bytes_in_buffer -= (size_t) num_bytes;
  167538. }
  167539. }
  167540. /*
  167541. * An additional method that can be provided by data source modules is the
  167542. * resync_to_restart method for error recovery in the presence of RST markers.
  167543. * For the moment, this source module just uses the default resync method
  167544. * provided by the JPEG library. That method assumes that no backtracking
  167545. * is possible.
  167546. */
  167547. /*
  167548. * Terminate source --- called by jpeg_finish_decompress
  167549. * after all data has been read. Often a no-op.
  167550. *
  167551. * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
  167552. * application must deal with any cleanup that should happen even
  167553. * for error exit.
  167554. */
  167555. METHODDEF(void)
  167556. term_source (j_decompress_ptr)
  167557. {
  167558. /* no work necessary here */
  167559. }
  167560. /*
  167561. * Prepare for input from a stdio stream.
  167562. * The caller must have already opened the stream, and is responsible
  167563. * for closing it after finishing decompression.
  167564. */
  167565. GLOBAL(void)
  167566. jpeg_stdio_src (j_decompress_ptr cinfo, FILE * infile)
  167567. {
  167568. my_src_ptr src;
  167569. /* The source object and input buffer are made permanent so that a series
  167570. * of JPEG images can be read from the same file by calling jpeg_stdio_src
  167571. * only before the first one. (If we discarded the buffer at the end of
  167572. * one image, we'd likely lose the start of the next one.)
  167573. * This makes it unsafe to use this manager and a different source
  167574. * manager serially with the same JPEG object. Caveat programmer.
  167575. */
  167576. if (cinfo->src == NULL) { /* first time for this JPEG object? */
  167577. cinfo->src = (struct jpeg_source_mgr *)
  167578. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  167579. SIZEOF(my_source_mgr));
  167580. src = (my_src_ptr) cinfo->src;
  167581. src->buffer = (JOCTET *)
  167582. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  167583. INPUT_BUF_SIZE * SIZEOF(JOCTET));
  167584. }
  167585. src = (my_src_ptr) cinfo->src;
  167586. src->pub.init_source = init_source;
  167587. src->pub.fill_input_buffer = fill_input_buffer;
  167588. src->pub.skip_input_data = skip_input_data;
  167589. src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
  167590. src->pub.term_source = term_source;
  167591. src->infile = infile;
  167592. src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
  167593. src->pub.next_input_byte = NULL; /* until buffer loaded */
  167594. }
  167595. /*** End of inlined file: jdatasrc.c ***/
  167596. /*** Start of inlined file: jdcoefct.c ***/
  167597. #define JPEG_INTERNALS
  167598. /* Block smoothing is only applicable for progressive JPEG, so: */
  167599. #ifndef D_PROGRESSIVE_SUPPORTED
  167600. #undef BLOCK_SMOOTHING_SUPPORTED
  167601. #endif
  167602. /* Private buffer controller object */
  167603. typedef struct {
  167604. struct jpeg_d_coef_controller pub; /* public fields */
  167605. /* These variables keep track of the current location of the input side. */
  167606. /* cinfo->input_iMCU_row is also used for this. */
  167607. JDIMENSION MCU_ctr; /* counts MCUs processed in current row */
  167608. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  167609. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  167610. /* The output side's location is represented by cinfo->output_iMCU_row. */
  167611. /* In single-pass modes, it's sufficient to buffer just one MCU.
  167612. * We allocate a workspace of D_MAX_BLOCKS_IN_MCU coefficient blocks,
  167613. * and let the entropy decoder write into that workspace each time.
  167614. * (On 80x86, the workspace is FAR even though it's not really very big;
  167615. * this is to keep the module interfaces unchanged when a large coefficient
  167616. * buffer is necessary.)
  167617. * In multi-pass modes, this array points to the current MCU's blocks
  167618. * within the virtual arrays; it is used only by the input side.
  167619. */
  167620. JBLOCKROW MCU_buffer[D_MAX_BLOCKS_IN_MCU];
  167621. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167622. /* In multi-pass modes, we need a virtual block array for each component. */
  167623. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  167624. #endif
  167625. #ifdef BLOCK_SMOOTHING_SUPPORTED
  167626. /* When doing block smoothing, we latch coefficient Al values here */
  167627. int * coef_bits_latch;
  167628. #define SAVED_COEFS 6 /* we save coef_bits[0..5] */
  167629. #endif
  167630. } my_coef_controller3;
  167631. typedef my_coef_controller3 * my_coef_ptr3;
  167632. /* Forward declarations */
  167633. METHODDEF(int) decompress_onepass
  167634. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  167635. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167636. METHODDEF(int) decompress_data
  167637. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  167638. #endif
  167639. #ifdef BLOCK_SMOOTHING_SUPPORTED
  167640. LOCAL(boolean) smoothing_ok JPP((j_decompress_ptr cinfo));
  167641. METHODDEF(int) decompress_smooth_data
  167642. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  167643. #endif
  167644. LOCAL(void)
  167645. start_iMCU_row3 (j_decompress_ptr cinfo)
  167646. /* Reset within-iMCU-row counters for a new row (input side) */
  167647. {
  167648. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  167649. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  167650. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  167651. * But at the bottom of the image, process only what's left.
  167652. */
  167653. if (cinfo->comps_in_scan > 1) {
  167654. coef->MCU_rows_per_iMCU_row = 1;
  167655. } else {
  167656. if (cinfo->input_iMCU_row < (cinfo->total_iMCU_rows-1))
  167657. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  167658. else
  167659. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  167660. }
  167661. coef->MCU_ctr = 0;
  167662. coef->MCU_vert_offset = 0;
  167663. }
  167664. /*
  167665. * Initialize for an input processing pass.
  167666. */
  167667. METHODDEF(void)
  167668. start_input_pass (j_decompress_ptr cinfo)
  167669. {
  167670. cinfo->input_iMCU_row = 0;
  167671. start_iMCU_row3(cinfo);
  167672. }
  167673. /*
  167674. * Initialize for an output processing pass.
  167675. */
  167676. METHODDEF(void)
  167677. start_output_pass (j_decompress_ptr cinfo)
  167678. {
  167679. #ifdef BLOCK_SMOOTHING_SUPPORTED
  167680. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  167681. /* If multipass, check to see whether to use block smoothing on this pass */
  167682. if (coef->pub.coef_arrays != NULL) {
  167683. if (cinfo->do_block_smoothing && smoothing_ok(cinfo))
  167684. coef->pub.decompress_data = decompress_smooth_data;
  167685. else
  167686. coef->pub.decompress_data = decompress_data;
  167687. }
  167688. #endif
  167689. cinfo->output_iMCU_row = 0;
  167690. }
  167691. /*
  167692. * Decompress and return some data in the single-pass case.
  167693. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  167694. * Input and output must run in lockstep since we have only a one-MCU buffer.
  167695. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  167696. *
  167697. * NB: output_buf contains a plane for each component in image,
  167698. * which we index according to the component's SOF position.
  167699. */
  167700. METHODDEF(int)
  167701. decompress_onepass (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  167702. {
  167703. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  167704. JDIMENSION MCU_col_num; /* index of current MCU within row */
  167705. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  167706. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  167707. int blkn, ci, xindex, yindex, yoffset, useful_width;
  167708. JSAMPARRAY output_ptr;
  167709. JDIMENSION start_col, output_col;
  167710. jpeg_component_info *compptr;
  167711. inverse_DCT_method_ptr inverse_DCT;
  167712. /* Loop to process as much as one whole iMCU row */
  167713. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  167714. yoffset++) {
  167715. for (MCU_col_num = coef->MCU_ctr; MCU_col_num <= last_MCU_col;
  167716. MCU_col_num++) {
  167717. /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */
  167718. jzero_far((void FAR *) coef->MCU_buffer[0],
  167719. (size_t) (cinfo->blocks_in_MCU * SIZEOF(JBLOCK)));
  167720. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  167721. /* Suspension forced; update state counters and exit */
  167722. coef->MCU_vert_offset = yoffset;
  167723. coef->MCU_ctr = MCU_col_num;
  167724. return JPEG_SUSPENDED;
  167725. }
  167726. /* Determine where data should go in output_buf and do the IDCT thing.
  167727. * We skip dummy blocks at the right and bottom edges (but blkn gets
  167728. * incremented past them!). Note the inner loop relies on having
  167729. * allocated the MCU_buffer[] blocks sequentially.
  167730. */
  167731. blkn = 0; /* index of current DCT block within MCU */
  167732. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167733. compptr = cinfo->cur_comp_info[ci];
  167734. /* Don't bother to IDCT an uninteresting component. */
  167735. if (! compptr->component_needed) {
  167736. blkn += compptr->MCU_blocks;
  167737. continue;
  167738. }
  167739. inverse_DCT = cinfo->idct->inverse_DCT[compptr->component_index];
  167740. useful_width = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  167741. : compptr->last_col_width;
  167742. output_ptr = output_buf[compptr->component_index] +
  167743. yoffset * compptr->DCT_scaled_size;
  167744. start_col = MCU_col_num * compptr->MCU_sample_width;
  167745. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  167746. if (cinfo->input_iMCU_row < last_iMCU_row ||
  167747. yoffset+yindex < compptr->last_row_height) {
  167748. output_col = start_col;
  167749. for (xindex = 0; xindex < useful_width; xindex++) {
  167750. (*inverse_DCT) (cinfo, compptr,
  167751. (JCOEFPTR) coef->MCU_buffer[blkn+xindex],
  167752. output_ptr, output_col);
  167753. output_col += compptr->DCT_scaled_size;
  167754. }
  167755. }
  167756. blkn += compptr->MCU_width;
  167757. output_ptr += compptr->DCT_scaled_size;
  167758. }
  167759. }
  167760. }
  167761. /* Completed an MCU row, but perhaps not an iMCU row */
  167762. coef->MCU_ctr = 0;
  167763. }
  167764. /* Completed the iMCU row, advance counters for next one */
  167765. cinfo->output_iMCU_row++;
  167766. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  167767. start_iMCU_row3(cinfo);
  167768. return JPEG_ROW_COMPLETED;
  167769. }
  167770. /* Completed the scan */
  167771. (*cinfo->inputctl->finish_input_pass) (cinfo);
  167772. return JPEG_SCAN_COMPLETED;
  167773. }
  167774. /*
  167775. * Dummy consume-input routine for single-pass operation.
  167776. */
  167777. METHODDEF(int)
  167778. dummy_consume_data (j_decompress_ptr)
  167779. {
  167780. return JPEG_SUSPENDED; /* Always indicate nothing was done */
  167781. }
  167782. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167783. /*
  167784. * Consume input data and store it in the full-image coefficient buffer.
  167785. * We read as much as one fully interleaved MCU row ("iMCU" row) per call,
  167786. * ie, v_samp_factor block rows for each component in the scan.
  167787. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  167788. */
  167789. METHODDEF(int)
  167790. consume_data (j_decompress_ptr cinfo)
  167791. {
  167792. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  167793. JDIMENSION MCU_col_num; /* index of current MCU within row */
  167794. int blkn, ci, xindex, yindex, yoffset;
  167795. JDIMENSION start_col;
  167796. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  167797. JBLOCKROW buffer_ptr;
  167798. jpeg_component_info *compptr;
  167799. /* Align the virtual buffers for the components used in this scan. */
  167800. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167801. compptr = cinfo->cur_comp_info[ci];
  167802. buffer[ci] = (*cinfo->mem->access_virt_barray)
  167803. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  167804. cinfo->input_iMCU_row * compptr->v_samp_factor,
  167805. (JDIMENSION) compptr->v_samp_factor, TRUE);
  167806. /* Note: entropy decoder expects buffer to be zeroed,
  167807. * but this is handled automatically by the memory manager
  167808. * because we requested a pre-zeroed array.
  167809. */
  167810. }
  167811. /* Loop to process one whole iMCU row */
  167812. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  167813. yoffset++) {
  167814. for (MCU_col_num = coef->MCU_ctr; MCU_col_num < cinfo->MCUs_per_row;
  167815. MCU_col_num++) {
  167816. /* Construct list of pointers to DCT blocks belonging to this MCU */
  167817. blkn = 0; /* index of current DCT block within MCU */
  167818. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167819. compptr = cinfo->cur_comp_info[ci];
  167820. start_col = MCU_col_num * compptr->MCU_width;
  167821. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  167822. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  167823. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  167824. coef->MCU_buffer[blkn++] = buffer_ptr++;
  167825. }
  167826. }
  167827. }
  167828. /* Try to fetch the MCU. */
  167829. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  167830. /* Suspension forced; update state counters and exit */
  167831. coef->MCU_vert_offset = yoffset;
  167832. coef->MCU_ctr = MCU_col_num;
  167833. return JPEG_SUSPENDED;
  167834. }
  167835. }
  167836. /* Completed an MCU row, but perhaps not an iMCU row */
  167837. coef->MCU_ctr = 0;
  167838. }
  167839. /* Completed the iMCU row, advance counters for next one */
  167840. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  167841. start_iMCU_row3(cinfo);
  167842. return JPEG_ROW_COMPLETED;
  167843. }
  167844. /* Completed the scan */
  167845. (*cinfo->inputctl->finish_input_pass) (cinfo);
  167846. return JPEG_SCAN_COMPLETED;
  167847. }
  167848. /*
  167849. * Decompress and return some data in the multi-pass case.
  167850. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  167851. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  167852. *
  167853. * NB: output_buf contains a plane for each component in image.
  167854. */
  167855. METHODDEF(int)
  167856. decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  167857. {
  167858. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  167859. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  167860. JDIMENSION block_num;
  167861. int ci, block_row, block_rows;
  167862. JBLOCKARRAY buffer;
  167863. JBLOCKROW buffer_ptr;
  167864. JSAMPARRAY output_ptr;
  167865. JDIMENSION output_col;
  167866. jpeg_component_info *compptr;
  167867. inverse_DCT_method_ptr inverse_DCT;
  167868. /* Force some input to be done if we are getting ahead of the input. */
  167869. while (cinfo->input_scan_number < cinfo->output_scan_number ||
  167870. (cinfo->input_scan_number == cinfo->output_scan_number &&
  167871. cinfo->input_iMCU_row <= cinfo->output_iMCU_row)) {
  167872. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  167873. return JPEG_SUSPENDED;
  167874. }
  167875. /* OK, output from the virtual arrays. */
  167876. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167877. ci++, compptr++) {
  167878. /* Don't bother to IDCT an uninteresting component. */
  167879. if (! compptr->component_needed)
  167880. continue;
  167881. /* Align the virtual buffer for this component. */
  167882. buffer = (*cinfo->mem->access_virt_barray)
  167883. ((j_common_ptr) cinfo, coef->whole_image[ci],
  167884. cinfo->output_iMCU_row * compptr->v_samp_factor,
  167885. (JDIMENSION) compptr->v_samp_factor, FALSE);
  167886. /* Count non-dummy DCT block rows in this iMCU row. */
  167887. if (cinfo->output_iMCU_row < last_iMCU_row)
  167888. block_rows = compptr->v_samp_factor;
  167889. else {
  167890. /* NB: can't use last_row_height here; it is input-side-dependent! */
  167891. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  167892. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  167893. }
  167894. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  167895. output_ptr = output_buf[ci];
  167896. /* Loop over all DCT blocks to be processed. */
  167897. for (block_row = 0; block_row < block_rows; block_row++) {
  167898. buffer_ptr = buffer[block_row];
  167899. output_col = 0;
  167900. for (block_num = 0; block_num < compptr->width_in_blocks; block_num++) {
  167901. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) buffer_ptr,
  167902. output_ptr, output_col);
  167903. buffer_ptr++;
  167904. output_col += compptr->DCT_scaled_size;
  167905. }
  167906. output_ptr += compptr->DCT_scaled_size;
  167907. }
  167908. }
  167909. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  167910. return JPEG_ROW_COMPLETED;
  167911. return JPEG_SCAN_COMPLETED;
  167912. }
  167913. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167914. #ifdef BLOCK_SMOOTHING_SUPPORTED
  167915. /*
  167916. * This code applies interblock smoothing as described by section K.8
  167917. * of the JPEG standard: the first 5 AC coefficients are estimated from
  167918. * the DC values of a DCT block and its 8 neighboring blocks.
  167919. * We apply smoothing only for progressive JPEG decoding, and only if
  167920. * the coefficients it can estimate are not yet known to full precision.
  167921. */
  167922. /* Natural-order array positions of the first 5 zigzag-order coefficients */
  167923. #define Q01_POS 1
  167924. #define Q10_POS 8
  167925. #define Q20_POS 16
  167926. #define Q11_POS 9
  167927. #define Q02_POS 2
  167928. /*
  167929. * Determine whether block smoothing is applicable and safe.
  167930. * We also latch the current states of the coef_bits[] entries for the
  167931. * AC coefficients; otherwise, if the input side of the decompressor
  167932. * advances into a new scan, we might think the coefficients are known
  167933. * more accurately than they really are.
  167934. */
  167935. LOCAL(boolean)
  167936. smoothing_ok (j_decompress_ptr cinfo)
  167937. {
  167938. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  167939. boolean smoothing_useful = FALSE;
  167940. int ci, coefi;
  167941. jpeg_component_info *compptr;
  167942. JQUANT_TBL * qtable;
  167943. int * coef_bits;
  167944. int * coef_bits_latch;
  167945. if (! cinfo->progressive_mode || cinfo->coef_bits == NULL)
  167946. return FALSE;
  167947. /* Allocate latch area if not already done */
  167948. if (coef->coef_bits_latch == NULL)
  167949. coef->coef_bits_latch = (int *)
  167950. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167951. cinfo->num_components *
  167952. (SAVED_COEFS * SIZEOF(int)));
  167953. coef_bits_latch = coef->coef_bits_latch;
  167954. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167955. ci++, compptr++) {
  167956. /* All components' quantization values must already be latched. */
  167957. if ((qtable = compptr->quant_table) == NULL)
  167958. return FALSE;
  167959. /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */
  167960. if (qtable->quantval[0] == 0 ||
  167961. qtable->quantval[Q01_POS] == 0 ||
  167962. qtable->quantval[Q10_POS] == 0 ||
  167963. qtable->quantval[Q20_POS] == 0 ||
  167964. qtable->quantval[Q11_POS] == 0 ||
  167965. qtable->quantval[Q02_POS] == 0)
  167966. return FALSE;
  167967. /* DC values must be at least partly known for all components. */
  167968. coef_bits = cinfo->coef_bits[ci];
  167969. if (coef_bits[0] < 0)
  167970. return FALSE;
  167971. /* Block smoothing is helpful if some AC coefficients remain inaccurate. */
  167972. for (coefi = 1; coefi <= 5; coefi++) {
  167973. coef_bits_latch[coefi] = coef_bits[coefi];
  167974. if (coef_bits[coefi] != 0)
  167975. smoothing_useful = TRUE;
  167976. }
  167977. coef_bits_latch += SAVED_COEFS;
  167978. }
  167979. return smoothing_useful;
  167980. }
  167981. /*
  167982. * Variant of decompress_data for use when doing block smoothing.
  167983. */
  167984. METHODDEF(int)
  167985. decompress_smooth_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  167986. {
  167987. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  167988. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  167989. JDIMENSION block_num, last_block_column;
  167990. int ci, block_row, block_rows, access_rows;
  167991. JBLOCKARRAY buffer;
  167992. JBLOCKROW buffer_ptr, prev_block_row, next_block_row;
  167993. JSAMPARRAY output_ptr;
  167994. JDIMENSION output_col;
  167995. jpeg_component_info *compptr;
  167996. inverse_DCT_method_ptr inverse_DCT;
  167997. boolean first_row, last_row;
  167998. JBLOCK workspace;
  167999. int *coef_bits;
  168000. JQUANT_TBL *quanttbl;
  168001. INT32 Q00,Q01,Q02,Q10,Q11,Q20, num;
  168002. int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9;
  168003. int Al, pred;
  168004. /* Force some input to be done if we are getting ahead of the input. */
  168005. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  168006. ! cinfo->inputctl->eoi_reached) {
  168007. if (cinfo->input_scan_number == cinfo->output_scan_number) {
  168008. /* If input is working on current scan, we ordinarily want it to
  168009. * have completed the current row. But if input scan is DC,
  168010. * we want it to keep one row ahead so that next block row's DC
  168011. * values are up to date.
  168012. */
  168013. JDIMENSION delta = (cinfo->Ss == 0) ? 1 : 0;
  168014. if (cinfo->input_iMCU_row > cinfo->output_iMCU_row+delta)
  168015. break;
  168016. }
  168017. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  168018. return JPEG_SUSPENDED;
  168019. }
  168020. /* OK, output from the virtual arrays. */
  168021. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168022. ci++, compptr++) {
  168023. /* Don't bother to IDCT an uninteresting component. */
  168024. if (! compptr->component_needed)
  168025. continue;
  168026. /* Count non-dummy DCT block rows in this iMCU row. */
  168027. if (cinfo->output_iMCU_row < last_iMCU_row) {
  168028. block_rows = compptr->v_samp_factor;
  168029. access_rows = block_rows * 2; /* this and next iMCU row */
  168030. last_row = FALSE;
  168031. } else {
  168032. /* NB: can't use last_row_height here; it is input-side-dependent! */
  168033. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  168034. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  168035. access_rows = block_rows; /* this iMCU row only */
  168036. last_row = TRUE;
  168037. }
  168038. /* Align the virtual buffer for this component. */
  168039. if (cinfo->output_iMCU_row > 0) {
  168040. access_rows += compptr->v_samp_factor; /* prior iMCU row too */
  168041. buffer = (*cinfo->mem->access_virt_barray)
  168042. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168043. (cinfo->output_iMCU_row - 1) * compptr->v_samp_factor,
  168044. (JDIMENSION) access_rows, FALSE);
  168045. buffer += compptr->v_samp_factor; /* point to current iMCU row */
  168046. first_row = FALSE;
  168047. } else {
  168048. buffer = (*cinfo->mem->access_virt_barray)
  168049. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168050. (JDIMENSION) 0, (JDIMENSION) access_rows, FALSE);
  168051. first_row = TRUE;
  168052. }
  168053. /* Fetch component-dependent info */
  168054. coef_bits = coef->coef_bits_latch + (ci * SAVED_COEFS);
  168055. quanttbl = compptr->quant_table;
  168056. Q00 = quanttbl->quantval[0];
  168057. Q01 = quanttbl->quantval[Q01_POS];
  168058. Q10 = quanttbl->quantval[Q10_POS];
  168059. Q20 = quanttbl->quantval[Q20_POS];
  168060. Q11 = quanttbl->quantval[Q11_POS];
  168061. Q02 = quanttbl->quantval[Q02_POS];
  168062. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  168063. output_ptr = output_buf[ci];
  168064. /* Loop over all DCT blocks to be processed. */
  168065. for (block_row = 0; block_row < block_rows; block_row++) {
  168066. buffer_ptr = buffer[block_row];
  168067. if (first_row && block_row == 0)
  168068. prev_block_row = buffer_ptr;
  168069. else
  168070. prev_block_row = buffer[block_row-1];
  168071. if (last_row && block_row == block_rows-1)
  168072. next_block_row = buffer_ptr;
  168073. else
  168074. next_block_row = buffer[block_row+1];
  168075. /* We fetch the surrounding DC values using a sliding-register approach.
  168076. * Initialize all nine here so as to do the right thing on narrow pics.
  168077. */
  168078. DC1 = DC2 = DC3 = (int) prev_block_row[0][0];
  168079. DC4 = DC5 = DC6 = (int) buffer_ptr[0][0];
  168080. DC7 = DC8 = DC9 = (int) next_block_row[0][0];
  168081. output_col = 0;
  168082. last_block_column = compptr->width_in_blocks - 1;
  168083. for (block_num = 0; block_num <= last_block_column; block_num++) {
  168084. /* Fetch current DCT block into workspace so we can modify it. */
  168085. jcopy_block_row(buffer_ptr, (JBLOCKROW) workspace, (JDIMENSION) 1);
  168086. /* Update DC values */
  168087. if (block_num < last_block_column) {
  168088. DC3 = (int) prev_block_row[1][0];
  168089. DC6 = (int) buffer_ptr[1][0];
  168090. DC9 = (int) next_block_row[1][0];
  168091. }
  168092. /* Compute coefficient estimates per K.8.
  168093. * An estimate is applied only if coefficient is still zero,
  168094. * and is not known to be fully accurate.
  168095. */
  168096. /* AC01 */
  168097. if ((Al=coef_bits[1]) != 0 && workspace[1] == 0) {
  168098. num = 36 * Q00 * (DC4 - DC6);
  168099. if (num >= 0) {
  168100. pred = (int) (((Q01<<7) + num) / (Q01<<8));
  168101. if (Al > 0 && pred >= (1<<Al))
  168102. pred = (1<<Al)-1;
  168103. } else {
  168104. pred = (int) (((Q01<<7) - num) / (Q01<<8));
  168105. if (Al > 0 && pred >= (1<<Al))
  168106. pred = (1<<Al)-1;
  168107. pred = -pred;
  168108. }
  168109. workspace[1] = (JCOEF) pred;
  168110. }
  168111. /* AC10 */
  168112. if ((Al=coef_bits[2]) != 0 && workspace[8] == 0) {
  168113. num = 36 * Q00 * (DC2 - DC8);
  168114. if (num >= 0) {
  168115. pred = (int) (((Q10<<7) + num) / (Q10<<8));
  168116. if (Al > 0 && pred >= (1<<Al))
  168117. pred = (1<<Al)-1;
  168118. } else {
  168119. pred = (int) (((Q10<<7) - num) / (Q10<<8));
  168120. if (Al > 0 && pred >= (1<<Al))
  168121. pred = (1<<Al)-1;
  168122. pred = -pred;
  168123. }
  168124. workspace[8] = (JCOEF) pred;
  168125. }
  168126. /* AC20 */
  168127. if ((Al=coef_bits[3]) != 0 && workspace[16] == 0) {
  168128. num = 9 * Q00 * (DC2 + DC8 - 2*DC5);
  168129. if (num >= 0) {
  168130. pred = (int) (((Q20<<7) + num) / (Q20<<8));
  168131. if (Al > 0 && pred >= (1<<Al))
  168132. pred = (1<<Al)-1;
  168133. } else {
  168134. pred = (int) (((Q20<<7) - num) / (Q20<<8));
  168135. if (Al > 0 && pred >= (1<<Al))
  168136. pred = (1<<Al)-1;
  168137. pred = -pred;
  168138. }
  168139. workspace[16] = (JCOEF) pred;
  168140. }
  168141. /* AC11 */
  168142. if ((Al=coef_bits[4]) != 0 && workspace[9] == 0) {
  168143. num = 5 * Q00 * (DC1 - DC3 - DC7 + DC9);
  168144. if (num >= 0) {
  168145. pred = (int) (((Q11<<7) + num) / (Q11<<8));
  168146. if (Al > 0 && pred >= (1<<Al))
  168147. pred = (1<<Al)-1;
  168148. } else {
  168149. pred = (int) (((Q11<<7) - num) / (Q11<<8));
  168150. if (Al > 0 && pred >= (1<<Al))
  168151. pred = (1<<Al)-1;
  168152. pred = -pred;
  168153. }
  168154. workspace[9] = (JCOEF) pred;
  168155. }
  168156. /* AC02 */
  168157. if ((Al=coef_bits[5]) != 0 && workspace[2] == 0) {
  168158. num = 9 * Q00 * (DC4 + DC6 - 2*DC5);
  168159. if (num >= 0) {
  168160. pred = (int) (((Q02<<7) + num) / (Q02<<8));
  168161. if (Al > 0 && pred >= (1<<Al))
  168162. pred = (1<<Al)-1;
  168163. } else {
  168164. pred = (int) (((Q02<<7) - num) / (Q02<<8));
  168165. if (Al > 0 && pred >= (1<<Al))
  168166. pred = (1<<Al)-1;
  168167. pred = -pred;
  168168. }
  168169. workspace[2] = (JCOEF) pred;
  168170. }
  168171. /* OK, do the IDCT */
  168172. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) workspace,
  168173. output_ptr, output_col);
  168174. /* Advance for next column */
  168175. DC1 = DC2; DC2 = DC3;
  168176. DC4 = DC5; DC5 = DC6;
  168177. DC7 = DC8; DC8 = DC9;
  168178. buffer_ptr++, prev_block_row++, next_block_row++;
  168179. output_col += compptr->DCT_scaled_size;
  168180. }
  168181. output_ptr += compptr->DCT_scaled_size;
  168182. }
  168183. }
  168184. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  168185. return JPEG_ROW_COMPLETED;
  168186. return JPEG_SCAN_COMPLETED;
  168187. }
  168188. #endif /* BLOCK_SMOOTHING_SUPPORTED */
  168189. /*
  168190. * Initialize coefficient buffer controller.
  168191. */
  168192. GLOBAL(void)
  168193. jinit_d_coef_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  168194. {
  168195. my_coef_ptr3 coef;
  168196. coef = (my_coef_ptr3)
  168197. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168198. SIZEOF(my_coef_controller3));
  168199. cinfo->coef = (struct jpeg_d_coef_controller *) coef;
  168200. coef->pub.start_input_pass = start_input_pass;
  168201. coef->pub.start_output_pass = start_output_pass;
  168202. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168203. coef->coef_bits_latch = NULL;
  168204. #endif
  168205. /* Create the coefficient buffer. */
  168206. if (need_full_buffer) {
  168207. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168208. /* Allocate a full-image virtual array for each component, */
  168209. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  168210. /* Note we ask for a pre-zeroed array. */
  168211. int ci, access_rows;
  168212. jpeg_component_info *compptr;
  168213. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168214. ci++, compptr++) {
  168215. access_rows = compptr->v_samp_factor;
  168216. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168217. /* If block smoothing could be used, need a bigger window */
  168218. if (cinfo->progressive_mode)
  168219. access_rows *= 3;
  168220. #endif
  168221. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  168222. ((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE,
  168223. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  168224. (long) compptr->h_samp_factor),
  168225. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  168226. (long) compptr->v_samp_factor),
  168227. (JDIMENSION) access_rows);
  168228. }
  168229. coef->pub.consume_data = consume_data;
  168230. coef->pub.decompress_data = decompress_data;
  168231. coef->pub.coef_arrays = coef->whole_image; /* link to virtual arrays */
  168232. #else
  168233. ERREXIT(cinfo, JERR_NOT_COMPILED);
  168234. #endif
  168235. } else {
  168236. /* We only need a single-MCU buffer. */
  168237. JBLOCKROW buffer;
  168238. int i;
  168239. buffer = (JBLOCKROW)
  168240. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168241. D_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  168242. for (i = 0; i < D_MAX_BLOCKS_IN_MCU; i++) {
  168243. coef->MCU_buffer[i] = buffer + i;
  168244. }
  168245. coef->pub.consume_data = dummy_consume_data;
  168246. coef->pub.decompress_data = decompress_onepass;
  168247. coef->pub.coef_arrays = NULL; /* flag for no virtual arrays */
  168248. }
  168249. }
  168250. /*** End of inlined file: jdcoefct.c ***/
  168251. #undef FIX
  168252. /*** Start of inlined file: jdcolor.c ***/
  168253. #define JPEG_INTERNALS
  168254. /* Private subobject */
  168255. typedef struct {
  168256. struct jpeg_color_deconverter pub; /* public fields */
  168257. /* Private state for YCC->RGB conversion */
  168258. int * Cr_r_tab; /* => table for Cr to R conversion */
  168259. int * Cb_b_tab; /* => table for Cb to B conversion */
  168260. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  168261. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  168262. } my_color_deconverter2;
  168263. typedef my_color_deconverter2 * my_cconvert_ptr2;
  168264. /**************** YCbCr -> RGB conversion: most common case **************/
  168265. /*
  168266. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  168267. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  168268. * The conversion equations to be implemented are therefore
  168269. * R = Y + 1.40200 * Cr
  168270. * G = Y - 0.34414 * Cb - 0.71414 * Cr
  168271. * B = Y + 1.77200 * Cb
  168272. * where Cb and Cr represent the incoming values less CENTERJSAMPLE.
  168273. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  168274. *
  168275. * To avoid floating-point arithmetic, we represent the fractional constants
  168276. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  168277. * the products by 2^16, with appropriate rounding, to get the correct answer.
  168278. * Notice that Y, being an integral input, does not contribute any fraction
  168279. * so it need not participate in the rounding.
  168280. *
  168281. * For even more speed, we avoid doing any multiplications in the inner loop
  168282. * by precalculating the constants times Cb and Cr for all possible values.
  168283. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  168284. * for 12-bit samples it is still acceptable. It's not very reasonable for
  168285. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  168286. * colorspace anyway.
  168287. * The Cr=>R and Cb=>B values can be rounded to integers in advance; the
  168288. * values for the G calculation are left scaled up, since we must add them
  168289. * together before rounding.
  168290. */
  168291. #define SCALEBITS 16 /* speediest right-shift on some machines */
  168292. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  168293. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  168294. /*
  168295. * Initialize tables for YCC->RGB colorspace conversion.
  168296. */
  168297. LOCAL(void)
  168298. build_ycc_rgb_table (j_decompress_ptr cinfo)
  168299. {
  168300. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  168301. int i;
  168302. INT32 x;
  168303. SHIFT_TEMPS
  168304. cconvert->Cr_r_tab = (int *)
  168305. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168306. (MAXJSAMPLE+1) * SIZEOF(int));
  168307. cconvert->Cb_b_tab = (int *)
  168308. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168309. (MAXJSAMPLE+1) * SIZEOF(int));
  168310. cconvert->Cr_g_tab = (INT32 *)
  168311. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168312. (MAXJSAMPLE+1) * SIZEOF(INT32));
  168313. cconvert->Cb_g_tab = (INT32 *)
  168314. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168315. (MAXJSAMPLE+1) * SIZEOF(INT32));
  168316. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  168317. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  168318. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  168319. /* Cr=>R value is nearest int to 1.40200 * x */
  168320. cconvert->Cr_r_tab[i] = (int)
  168321. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  168322. /* Cb=>B value is nearest int to 1.77200 * x */
  168323. cconvert->Cb_b_tab[i] = (int)
  168324. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  168325. /* Cr=>G value is scaled-up -0.71414 * x */
  168326. cconvert->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  168327. /* Cb=>G value is scaled-up -0.34414 * x */
  168328. /* We also add in ONE_HALF so that need not do it in inner loop */
  168329. cconvert->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  168330. }
  168331. }
  168332. /*
  168333. * Convert some rows of samples to the output colorspace.
  168334. *
  168335. * Note that we change from noninterleaved, one-plane-per-component format
  168336. * to interleaved-pixel format. The output buffer is therefore three times
  168337. * as wide as the input buffer.
  168338. * A starting row offset is provided only for the input buffer. The caller
  168339. * can easily adjust the passed output_buf value to accommodate any row
  168340. * offset required on that side.
  168341. */
  168342. METHODDEF(void)
  168343. ycc_rgb_convert (j_decompress_ptr cinfo,
  168344. JSAMPIMAGE input_buf, JDIMENSION input_row,
  168345. JSAMPARRAY output_buf, int num_rows)
  168346. {
  168347. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  168348. register int y, cb, cr;
  168349. register JSAMPROW outptr;
  168350. register JSAMPROW inptr0, inptr1, inptr2;
  168351. register JDIMENSION col;
  168352. JDIMENSION num_cols = cinfo->output_width;
  168353. /* copy these pointers into registers if possible */
  168354. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  168355. register int * Crrtab = cconvert->Cr_r_tab;
  168356. register int * Cbbtab = cconvert->Cb_b_tab;
  168357. register INT32 * Crgtab = cconvert->Cr_g_tab;
  168358. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  168359. SHIFT_TEMPS
  168360. while (--num_rows >= 0) {
  168361. inptr0 = input_buf[0][input_row];
  168362. inptr1 = input_buf[1][input_row];
  168363. inptr2 = input_buf[2][input_row];
  168364. input_row++;
  168365. outptr = *output_buf++;
  168366. for (col = 0; col < num_cols; col++) {
  168367. y = GETJSAMPLE(inptr0[col]);
  168368. cb = GETJSAMPLE(inptr1[col]);
  168369. cr = GETJSAMPLE(inptr2[col]);
  168370. /* Range-limiting is essential due to noise introduced by DCT losses. */
  168371. outptr[RGB_RED] = range_limit[y + Crrtab[cr]];
  168372. outptr[RGB_GREEN] = range_limit[y +
  168373. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  168374. SCALEBITS))];
  168375. outptr[RGB_BLUE] = range_limit[y + Cbbtab[cb]];
  168376. outptr += RGB_PIXELSIZE;
  168377. }
  168378. }
  168379. }
  168380. /**************** Cases other than YCbCr -> RGB **************/
  168381. /*
  168382. * Color conversion for no colorspace change: just copy the data,
  168383. * converting from separate-planes to interleaved representation.
  168384. */
  168385. METHODDEF(void)
  168386. null_convert2 (j_decompress_ptr cinfo,
  168387. JSAMPIMAGE input_buf, JDIMENSION input_row,
  168388. JSAMPARRAY output_buf, int num_rows)
  168389. {
  168390. register JSAMPROW inptr, outptr;
  168391. register JDIMENSION count;
  168392. register int num_components = cinfo->num_components;
  168393. JDIMENSION num_cols = cinfo->output_width;
  168394. int ci;
  168395. while (--num_rows >= 0) {
  168396. for (ci = 0; ci < num_components; ci++) {
  168397. inptr = input_buf[ci][input_row];
  168398. outptr = output_buf[0] + ci;
  168399. for (count = num_cols; count > 0; count--) {
  168400. *outptr = *inptr++; /* needn't bother with GETJSAMPLE() here */
  168401. outptr += num_components;
  168402. }
  168403. }
  168404. input_row++;
  168405. output_buf++;
  168406. }
  168407. }
  168408. /*
  168409. * Color conversion for grayscale: just copy the data.
  168410. * This also works for YCbCr -> grayscale conversion, in which
  168411. * we just copy the Y (luminance) component and ignore chrominance.
  168412. */
  168413. METHODDEF(void)
  168414. grayscale_convert2 (j_decompress_ptr cinfo,
  168415. JSAMPIMAGE input_buf, JDIMENSION input_row,
  168416. JSAMPARRAY output_buf, int num_rows)
  168417. {
  168418. jcopy_sample_rows(input_buf[0], (int) input_row, output_buf, 0,
  168419. num_rows, cinfo->output_width);
  168420. }
  168421. /*
  168422. * Convert grayscale to RGB: just duplicate the graylevel three times.
  168423. * This is provided to support applications that don't want to cope
  168424. * with grayscale as a separate case.
  168425. */
  168426. METHODDEF(void)
  168427. gray_rgb_convert (j_decompress_ptr cinfo,
  168428. JSAMPIMAGE input_buf, JDIMENSION input_row,
  168429. JSAMPARRAY output_buf, int num_rows)
  168430. {
  168431. register JSAMPROW inptr, outptr;
  168432. register JDIMENSION col;
  168433. JDIMENSION num_cols = cinfo->output_width;
  168434. while (--num_rows >= 0) {
  168435. inptr = input_buf[0][input_row++];
  168436. outptr = *output_buf++;
  168437. for (col = 0; col < num_cols; col++) {
  168438. /* We can dispense with GETJSAMPLE() here */
  168439. outptr[RGB_RED] = outptr[RGB_GREEN] = outptr[RGB_BLUE] = inptr[col];
  168440. outptr += RGB_PIXELSIZE;
  168441. }
  168442. }
  168443. }
  168444. /*
  168445. * Adobe-style YCCK->CMYK conversion.
  168446. * We convert YCbCr to R=1-C, G=1-M, and B=1-Y using the same
  168447. * conversion as above, while passing K (black) unchanged.
  168448. * We assume build_ycc_rgb_table has been called.
  168449. */
  168450. METHODDEF(void)
  168451. ycck_cmyk_convert (j_decompress_ptr cinfo,
  168452. JSAMPIMAGE input_buf, JDIMENSION input_row,
  168453. JSAMPARRAY output_buf, int num_rows)
  168454. {
  168455. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  168456. register int y, cb, cr;
  168457. register JSAMPROW outptr;
  168458. register JSAMPROW inptr0, inptr1, inptr2, inptr3;
  168459. register JDIMENSION col;
  168460. JDIMENSION num_cols = cinfo->output_width;
  168461. /* copy these pointers into registers if possible */
  168462. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  168463. register int * Crrtab = cconvert->Cr_r_tab;
  168464. register int * Cbbtab = cconvert->Cb_b_tab;
  168465. register INT32 * Crgtab = cconvert->Cr_g_tab;
  168466. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  168467. SHIFT_TEMPS
  168468. while (--num_rows >= 0) {
  168469. inptr0 = input_buf[0][input_row];
  168470. inptr1 = input_buf[1][input_row];
  168471. inptr2 = input_buf[2][input_row];
  168472. inptr3 = input_buf[3][input_row];
  168473. input_row++;
  168474. outptr = *output_buf++;
  168475. for (col = 0; col < num_cols; col++) {
  168476. y = GETJSAMPLE(inptr0[col]);
  168477. cb = GETJSAMPLE(inptr1[col]);
  168478. cr = GETJSAMPLE(inptr2[col]);
  168479. /* Range-limiting is essential due to noise introduced by DCT losses. */
  168480. outptr[0] = range_limit[MAXJSAMPLE - (y + Crrtab[cr])]; /* red */
  168481. outptr[1] = range_limit[MAXJSAMPLE - (y + /* green */
  168482. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  168483. SCALEBITS)))];
  168484. outptr[2] = range_limit[MAXJSAMPLE - (y + Cbbtab[cb])]; /* blue */
  168485. /* K passes through unchanged */
  168486. outptr[3] = inptr3[col]; /* don't need GETJSAMPLE here */
  168487. outptr += 4;
  168488. }
  168489. }
  168490. }
  168491. /*
  168492. * Empty method for start_pass.
  168493. */
  168494. METHODDEF(void)
  168495. start_pass_dcolor (j_decompress_ptr)
  168496. {
  168497. /* no work needed */
  168498. }
  168499. /*
  168500. * Module initialization routine for output colorspace conversion.
  168501. */
  168502. GLOBAL(void)
  168503. jinit_color_deconverter (j_decompress_ptr cinfo)
  168504. {
  168505. my_cconvert_ptr2 cconvert;
  168506. int ci;
  168507. cconvert = (my_cconvert_ptr2)
  168508. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168509. SIZEOF(my_color_deconverter2));
  168510. cinfo->cconvert = (struct jpeg_color_deconverter *) cconvert;
  168511. cconvert->pub.start_pass = start_pass_dcolor;
  168512. /* Make sure num_components agrees with jpeg_color_space */
  168513. switch (cinfo->jpeg_color_space) {
  168514. case JCS_GRAYSCALE:
  168515. if (cinfo->num_components != 1)
  168516. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  168517. break;
  168518. case JCS_RGB:
  168519. case JCS_YCbCr:
  168520. if (cinfo->num_components != 3)
  168521. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  168522. break;
  168523. case JCS_CMYK:
  168524. case JCS_YCCK:
  168525. if (cinfo->num_components != 4)
  168526. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  168527. break;
  168528. default: /* JCS_UNKNOWN can be anything */
  168529. if (cinfo->num_components < 1)
  168530. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  168531. break;
  168532. }
  168533. /* Set out_color_components and conversion method based on requested space.
  168534. * Also clear the component_needed flags for any unused components,
  168535. * so that earlier pipeline stages can avoid useless computation.
  168536. */
  168537. switch (cinfo->out_color_space) {
  168538. case JCS_GRAYSCALE:
  168539. cinfo->out_color_components = 1;
  168540. if (cinfo->jpeg_color_space == JCS_GRAYSCALE ||
  168541. cinfo->jpeg_color_space == JCS_YCbCr) {
  168542. cconvert->pub.color_convert = grayscale_convert2;
  168543. /* For color->grayscale conversion, only the Y (0) component is needed */
  168544. for (ci = 1; ci < cinfo->num_components; ci++)
  168545. cinfo->comp_info[ci].component_needed = FALSE;
  168546. } else
  168547. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  168548. break;
  168549. case JCS_RGB:
  168550. cinfo->out_color_components = RGB_PIXELSIZE;
  168551. if (cinfo->jpeg_color_space == JCS_YCbCr) {
  168552. cconvert->pub.color_convert = ycc_rgb_convert;
  168553. build_ycc_rgb_table(cinfo);
  168554. } else if (cinfo->jpeg_color_space == JCS_GRAYSCALE) {
  168555. cconvert->pub.color_convert = gray_rgb_convert;
  168556. } else if (cinfo->jpeg_color_space == JCS_RGB && RGB_PIXELSIZE == 3) {
  168557. cconvert->pub.color_convert = null_convert2;
  168558. } else
  168559. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  168560. break;
  168561. case JCS_CMYK:
  168562. cinfo->out_color_components = 4;
  168563. if (cinfo->jpeg_color_space == JCS_YCCK) {
  168564. cconvert->pub.color_convert = ycck_cmyk_convert;
  168565. build_ycc_rgb_table(cinfo);
  168566. } else if (cinfo->jpeg_color_space == JCS_CMYK) {
  168567. cconvert->pub.color_convert = null_convert2;
  168568. } else
  168569. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  168570. break;
  168571. default:
  168572. /* Permit null conversion to same output space */
  168573. if (cinfo->out_color_space == cinfo->jpeg_color_space) {
  168574. cinfo->out_color_components = cinfo->num_components;
  168575. cconvert->pub.color_convert = null_convert2;
  168576. } else /* unsupported non-null conversion */
  168577. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  168578. break;
  168579. }
  168580. if (cinfo->quantize_colors)
  168581. cinfo->output_components = 1; /* single colormapped output component */
  168582. else
  168583. cinfo->output_components = cinfo->out_color_components;
  168584. }
  168585. /*** End of inlined file: jdcolor.c ***/
  168586. #undef FIX
  168587. /*** Start of inlined file: jddctmgr.c ***/
  168588. #define JPEG_INTERNALS
  168589. /*
  168590. * The decompressor input side (jdinput.c) saves away the appropriate
  168591. * quantization table for each component at the start of the first scan
  168592. * involving that component. (This is necessary in order to correctly
  168593. * decode files that reuse Q-table slots.)
  168594. * When we are ready to make an output pass, the saved Q-table is converted
  168595. * to a multiplier table that will actually be used by the IDCT routine.
  168596. * The multiplier table contents are IDCT-method-dependent. To support
  168597. * application changes in IDCT method between scans, we can remake the
  168598. * multiplier tables if necessary.
  168599. * In buffered-image mode, the first output pass may occur before any data
  168600. * has been seen for some components, and thus before their Q-tables have
  168601. * been saved away. To handle this case, multiplier tables are preset
  168602. * to zeroes; the result of the IDCT will be a neutral gray level.
  168603. */
  168604. /* Private subobject for this module */
  168605. typedef struct {
  168606. struct jpeg_inverse_dct pub; /* public fields */
  168607. /* This array contains the IDCT method code that each multiplier table
  168608. * is currently set up for, or -1 if it's not yet set up.
  168609. * The actual multiplier tables are pointed to by dct_table in the
  168610. * per-component comp_info structures.
  168611. */
  168612. int cur_method[MAX_COMPONENTS];
  168613. } my_idct_controller;
  168614. typedef my_idct_controller * my_idct_ptr;
  168615. /* Allocated multiplier tables: big enough for any supported variant */
  168616. typedef union {
  168617. ISLOW_MULT_TYPE islow_array[DCTSIZE2];
  168618. #ifdef DCT_IFAST_SUPPORTED
  168619. IFAST_MULT_TYPE ifast_array[DCTSIZE2];
  168620. #endif
  168621. #ifdef DCT_FLOAT_SUPPORTED
  168622. FLOAT_MULT_TYPE float_array[DCTSIZE2];
  168623. #endif
  168624. } multiplier_table;
  168625. /* The current scaled-IDCT routines require ISLOW-style multiplier tables,
  168626. * so be sure to compile that code if either ISLOW or SCALING is requested.
  168627. */
  168628. #ifdef DCT_ISLOW_SUPPORTED
  168629. #define PROVIDE_ISLOW_TABLES
  168630. #else
  168631. #ifdef IDCT_SCALING_SUPPORTED
  168632. #define PROVIDE_ISLOW_TABLES
  168633. #endif
  168634. #endif
  168635. /*
  168636. * Prepare for an output pass.
  168637. * Here we select the proper IDCT routine for each component and build
  168638. * a matching multiplier table.
  168639. */
  168640. METHODDEF(void)
  168641. start_pass (j_decompress_ptr cinfo)
  168642. {
  168643. my_idct_ptr idct = (my_idct_ptr) cinfo->idct;
  168644. int ci, i;
  168645. jpeg_component_info *compptr;
  168646. int method = 0;
  168647. inverse_DCT_method_ptr method_ptr = NULL;
  168648. JQUANT_TBL * qtbl;
  168649. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168650. ci++, compptr++) {
  168651. /* Select the proper IDCT routine for this component's scaling */
  168652. switch (compptr->DCT_scaled_size) {
  168653. #ifdef IDCT_SCALING_SUPPORTED
  168654. case 1:
  168655. method_ptr = jpeg_idct_1x1;
  168656. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  168657. break;
  168658. case 2:
  168659. method_ptr = jpeg_idct_2x2;
  168660. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  168661. break;
  168662. case 4:
  168663. method_ptr = jpeg_idct_4x4;
  168664. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  168665. break;
  168666. #endif
  168667. case DCTSIZE:
  168668. switch (cinfo->dct_method) {
  168669. #ifdef DCT_ISLOW_SUPPORTED
  168670. case JDCT_ISLOW:
  168671. method_ptr = jpeg_idct_islow;
  168672. method = JDCT_ISLOW;
  168673. break;
  168674. #endif
  168675. #ifdef DCT_IFAST_SUPPORTED
  168676. case JDCT_IFAST:
  168677. method_ptr = jpeg_idct_ifast;
  168678. method = JDCT_IFAST;
  168679. break;
  168680. #endif
  168681. #ifdef DCT_FLOAT_SUPPORTED
  168682. case JDCT_FLOAT:
  168683. method_ptr = jpeg_idct_float;
  168684. method = JDCT_FLOAT;
  168685. break;
  168686. #endif
  168687. default:
  168688. ERREXIT(cinfo, JERR_NOT_COMPILED);
  168689. break;
  168690. }
  168691. break;
  168692. default:
  168693. ERREXIT1(cinfo, JERR_BAD_DCTSIZE, compptr->DCT_scaled_size);
  168694. break;
  168695. }
  168696. idct->pub.inverse_DCT[ci] = method_ptr;
  168697. /* Create multiplier table from quant table.
  168698. * However, we can skip this if the component is uninteresting
  168699. * or if we already built the table. Also, if no quant table
  168700. * has yet been saved for the component, we leave the
  168701. * multiplier table all-zero; we'll be reading zeroes from the
  168702. * coefficient controller's buffer anyway.
  168703. */
  168704. if (! compptr->component_needed || idct->cur_method[ci] == method)
  168705. continue;
  168706. qtbl = compptr->quant_table;
  168707. if (qtbl == NULL) /* happens if no data yet for component */
  168708. continue;
  168709. idct->cur_method[ci] = method;
  168710. switch (method) {
  168711. #ifdef PROVIDE_ISLOW_TABLES
  168712. case JDCT_ISLOW:
  168713. {
  168714. /* For LL&M IDCT method, multipliers are equal to raw quantization
  168715. * coefficients, but are stored as ints to ensure access efficiency.
  168716. */
  168717. ISLOW_MULT_TYPE * ismtbl = (ISLOW_MULT_TYPE *) compptr->dct_table;
  168718. for (i = 0; i < DCTSIZE2; i++) {
  168719. ismtbl[i] = (ISLOW_MULT_TYPE) qtbl->quantval[i];
  168720. }
  168721. }
  168722. break;
  168723. #endif
  168724. #ifdef DCT_IFAST_SUPPORTED
  168725. case JDCT_IFAST:
  168726. {
  168727. /* For AA&N IDCT method, multipliers are equal to quantization
  168728. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  168729. * scalefactor[0] = 1
  168730. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  168731. * For integer operation, the multiplier table is to be scaled by
  168732. * IFAST_SCALE_BITS.
  168733. */
  168734. IFAST_MULT_TYPE * ifmtbl = (IFAST_MULT_TYPE *) compptr->dct_table;
  168735. #define CONST_BITS 14
  168736. static const INT16 aanscales[DCTSIZE2] = {
  168737. /* precomputed values scaled up by 14 bits */
  168738. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  168739. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  168740. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  168741. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  168742. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  168743. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  168744. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  168745. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  168746. };
  168747. SHIFT_TEMPS
  168748. for (i = 0; i < DCTSIZE2; i++) {
  168749. ifmtbl[i] = (IFAST_MULT_TYPE)
  168750. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  168751. (INT32) aanscales[i]),
  168752. CONST_BITS-IFAST_SCALE_BITS);
  168753. }
  168754. }
  168755. break;
  168756. #endif
  168757. #ifdef DCT_FLOAT_SUPPORTED
  168758. case JDCT_FLOAT:
  168759. {
  168760. /* For float AA&N IDCT method, multipliers are equal to quantization
  168761. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  168762. * scalefactor[0] = 1
  168763. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  168764. */
  168765. FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr->dct_table;
  168766. int row, col;
  168767. static const double aanscalefactor[DCTSIZE] = {
  168768. 1.0, 1.387039845, 1.306562965, 1.175875602,
  168769. 1.0, 0.785694958, 0.541196100, 0.275899379
  168770. };
  168771. i = 0;
  168772. for (row = 0; row < DCTSIZE; row++) {
  168773. for (col = 0; col < DCTSIZE; col++) {
  168774. fmtbl[i] = (FLOAT_MULT_TYPE)
  168775. ((double) qtbl->quantval[i] *
  168776. aanscalefactor[row] * aanscalefactor[col]);
  168777. i++;
  168778. }
  168779. }
  168780. }
  168781. break;
  168782. #endif
  168783. default:
  168784. ERREXIT(cinfo, JERR_NOT_COMPILED);
  168785. break;
  168786. }
  168787. }
  168788. }
  168789. /*
  168790. * Initialize IDCT manager.
  168791. */
  168792. GLOBAL(void)
  168793. jinit_inverse_dct (j_decompress_ptr cinfo)
  168794. {
  168795. my_idct_ptr idct;
  168796. int ci;
  168797. jpeg_component_info *compptr;
  168798. idct = (my_idct_ptr)
  168799. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168800. SIZEOF(my_idct_controller));
  168801. cinfo->idct = (struct jpeg_inverse_dct *) idct;
  168802. idct->pub.start_pass = start_pass;
  168803. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168804. ci++, compptr++) {
  168805. /* Allocate and pre-zero a multiplier table for each component */
  168806. compptr->dct_table =
  168807. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168808. SIZEOF(multiplier_table));
  168809. MEMZERO(compptr->dct_table, SIZEOF(multiplier_table));
  168810. /* Mark multiplier table not yet set up for any method */
  168811. idct->cur_method[ci] = -1;
  168812. }
  168813. }
  168814. /*** End of inlined file: jddctmgr.c ***/
  168815. #undef CONST_BITS
  168816. #undef ASSIGN_STATE
  168817. /*** Start of inlined file: jdhuff.c ***/
  168818. #define JPEG_INTERNALS
  168819. /*** Start of inlined file: jdhuff.h ***/
  168820. /* Short forms of external names for systems with brain-damaged linkers. */
  168821. #ifndef __jdhuff_h__
  168822. #define __jdhuff_h__
  168823. #ifdef NEED_SHORT_EXTERNAL_NAMES
  168824. #define jpeg_make_d_derived_tbl jMkDDerived
  168825. #define jpeg_fill_bit_buffer jFilBitBuf
  168826. #define jpeg_huff_decode jHufDecode
  168827. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  168828. /* Derived data constructed for each Huffman table */
  168829. #define HUFF_LOOKAHEAD 8 /* # of bits of lookahead */
  168830. typedef struct {
  168831. /* Basic tables: (element [0] of each array is unused) */
  168832. INT32 maxcode[18]; /* largest code of length k (-1 if none) */
  168833. /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */
  168834. INT32 valoffset[17]; /* huffval[] offset for codes of length k */
  168835. /* valoffset[k] = huffval[] index of 1st symbol of code length k, less
  168836. * the smallest code of length k; so given a code of length k, the
  168837. * corresponding symbol is huffval[code + valoffset[k]]
  168838. */
  168839. /* Link to public Huffman table (needed only in jpeg_huff_decode) */
  168840. JHUFF_TBL *pub;
  168841. /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
  168842. * the input data stream. If the next Huffman code is no more
  168843. * than HUFF_LOOKAHEAD bits long, we can obtain its length and
  168844. * the corresponding symbol directly from these tables.
  168845. */
  168846. int look_nbits[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */
  168847. UINT8 look_sym[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */
  168848. } d_derived_tbl;
  168849. /* Expand a Huffman table definition into the derived format */
  168850. EXTERN(void) jpeg_make_d_derived_tbl
  168851. JPP((j_decompress_ptr cinfo, boolean isDC, int tblno,
  168852. d_derived_tbl ** pdtbl));
  168853. /*
  168854. * Fetching the next N bits from the input stream is a time-critical operation
  168855. * for the Huffman decoders. We implement it with a combination of inline
  168856. * macros and out-of-line subroutines. Note that N (the number of bits
  168857. * demanded at one time) never exceeds 15 for JPEG use.
  168858. *
  168859. * We read source bytes into get_buffer and dole out bits as needed.
  168860. * If get_buffer already contains enough bits, they are fetched in-line
  168861. * by the macros CHECK_BIT_BUFFER and GET_BITS. When there aren't enough
  168862. * bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer
  168863. * as full as possible (not just to the number of bits needed; this
  168864. * prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).
  168865. * Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.
  168866. * On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains
  168867. * at least the requested number of bits --- dummy zeroes are inserted if
  168868. * necessary.
  168869. */
  168870. typedef INT32 bit_buf_type; /* type of bit-extraction buffer */
  168871. #define BIT_BUF_SIZE 32 /* size of buffer in bits */
  168872. /* If long is > 32 bits on your machine, and shifting/masking longs is
  168873. * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE
  168874. * appropriately should be a win. Unfortunately we can't define the size
  168875. * with something like #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)
  168876. * because not all machines measure sizeof in 8-bit bytes.
  168877. */
  168878. typedef struct { /* Bitreading state saved across MCUs */
  168879. bit_buf_type get_buffer; /* current bit-extraction buffer */
  168880. int bits_left; /* # of unused bits in it */
  168881. } bitread_perm_state;
  168882. typedef struct { /* Bitreading working state within an MCU */
  168883. /* Current data source location */
  168884. /* We need a copy, rather than munging the original, in case of suspension */
  168885. const JOCTET * next_input_byte; /* => next byte to read from source */
  168886. size_t bytes_in_buffer; /* # of bytes remaining in source buffer */
  168887. /* Bit input buffer --- note these values are kept in register variables,
  168888. * not in this struct, inside the inner loops.
  168889. */
  168890. bit_buf_type get_buffer; /* current bit-extraction buffer */
  168891. int bits_left; /* # of unused bits in it */
  168892. /* Pointer needed by jpeg_fill_bit_buffer. */
  168893. j_decompress_ptr cinfo; /* back link to decompress master record */
  168894. } bitread_working_state;
  168895. /* Macros to declare and load/save bitread local variables. */
  168896. #define BITREAD_STATE_VARS \
  168897. register bit_buf_type get_buffer; \
  168898. register int bits_left; \
  168899. bitread_working_state br_state
  168900. #define BITREAD_LOAD_STATE(cinfop,permstate) \
  168901. br_state.cinfo = cinfop; \
  168902. br_state.next_input_byte = cinfop->src->next_input_byte; \
  168903. br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \
  168904. get_buffer = permstate.get_buffer; \
  168905. bits_left = permstate.bits_left;
  168906. #define BITREAD_SAVE_STATE(cinfop,permstate) \
  168907. cinfop->src->next_input_byte = br_state.next_input_byte; \
  168908. cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \
  168909. permstate.get_buffer = get_buffer; \
  168910. permstate.bits_left = bits_left
  168911. /*
  168912. * These macros provide the in-line portion of bit fetching.
  168913. * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer
  168914. * before using GET_BITS, PEEK_BITS, or DROP_BITS.
  168915. * The variables get_buffer and bits_left are assumed to be locals,
  168916. * but the state struct might not be (jpeg_huff_decode needs this).
  168917. * CHECK_BIT_BUFFER(state,n,action);
  168918. * Ensure there are N bits in get_buffer; if suspend, take action.
  168919. * val = GET_BITS(n);
  168920. * Fetch next N bits.
  168921. * val = PEEK_BITS(n);
  168922. * Fetch next N bits without removing them from the buffer.
  168923. * DROP_BITS(n);
  168924. * Discard next N bits.
  168925. * The value N should be a simple variable, not an expression, because it
  168926. * is evaluated multiple times.
  168927. */
  168928. #define CHECK_BIT_BUFFER(state,nbits,action) \
  168929. { if (bits_left < (nbits)) { \
  168930. if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits)) \
  168931. { action; } \
  168932. get_buffer = (state).get_buffer; bits_left = (state).bits_left; } }
  168933. #define GET_BITS(nbits) \
  168934. (((int) (get_buffer >> (bits_left -= (nbits)))) & ((1<<(nbits))-1))
  168935. #define PEEK_BITS(nbits) \
  168936. (((int) (get_buffer >> (bits_left - (nbits)))) & ((1<<(nbits))-1))
  168937. #define DROP_BITS(nbits) \
  168938. (bits_left -= (nbits))
  168939. /* Load up the bit buffer to a depth of at least nbits */
  168940. EXTERN(boolean) jpeg_fill_bit_buffer
  168941. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  168942. register int bits_left, int nbits));
  168943. /*
  168944. * Code for extracting next Huffman-coded symbol from input bit stream.
  168945. * Again, this is time-critical and we make the main paths be macros.
  168946. *
  168947. * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits
  168948. * without looping. Usually, more than 95% of the Huffman codes will be 8
  168949. * or fewer bits long. The few overlength codes are handled with a loop,
  168950. * which need not be inline code.
  168951. *
  168952. * Notes about the HUFF_DECODE macro:
  168953. * 1. Near the end of the data segment, we may fail to get enough bits
  168954. * for a lookahead. In that case, we do it the hard way.
  168955. * 2. If the lookahead table contains no entry, the next code must be
  168956. * more than HUFF_LOOKAHEAD bits long.
  168957. * 3. jpeg_huff_decode returns -1 if forced to suspend.
  168958. */
  168959. #define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \
  168960. { register int nb, look; \
  168961. if (bits_left < HUFF_LOOKAHEAD) { \
  168962. if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \
  168963. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  168964. if (bits_left < HUFF_LOOKAHEAD) { \
  168965. nb = 1; goto slowlabel; \
  168966. } \
  168967. } \
  168968. look = PEEK_BITS(HUFF_LOOKAHEAD); \
  168969. if ((nb = htbl->look_nbits[look]) != 0) { \
  168970. DROP_BITS(nb); \
  168971. result = htbl->look_sym[look]; \
  168972. } else { \
  168973. nb = HUFF_LOOKAHEAD+1; \
  168974. slowlabel: \
  168975. if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \
  168976. { failaction; } \
  168977. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  168978. } \
  168979. }
  168980. /* Out-of-line case for Huffman code fetching */
  168981. EXTERN(int) jpeg_huff_decode
  168982. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  168983. register int bits_left, d_derived_tbl * htbl, int min_bits));
  168984. #endif
  168985. /*** End of inlined file: jdhuff.h ***/
  168986. /* Declarations shared with jdphuff.c */
  168987. /*
  168988. * Expanded entropy decoder object for Huffman decoding.
  168989. *
  168990. * The savable_state subrecord contains fields that change within an MCU,
  168991. * but must not be updated permanently until we complete the MCU.
  168992. */
  168993. typedef struct {
  168994. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  168995. } savable_state2;
  168996. /* This macro is to work around compilers with missing or broken
  168997. * structure assignment. You'll need to fix this code if you have
  168998. * such a compiler and you change MAX_COMPS_IN_SCAN.
  168999. */
  169000. #ifndef NO_STRUCT_ASSIGN
  169001. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  169002. #else
  169003. #if MAX_COMPS_IN_SCAN == 4
  169004. #define ASSIGN_STATE(dest,src) \
  169005. ((dest).last_dc_val[0] = (src).last_dc_val[0], \
  169006. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  169007. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  169008. (dest).last_dc_val[3] = (src).last_dc_val[3])
  169009. #endif
  169010. #endif
  169011. typedef struct {
  169012. struct jpeg_entropy_decoder pub; /* public fields */
  169013. /* These fields are loaded into local variables at start of each MCU.
  169014. * In case of suspension, we exit WITHOUT updating them.
  169015. */
  169016. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  169017. savable_state2 saved; /* Other state at start of MCU */
  169018. /* These fields are NOT loaded into local working state. */
  169019. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  169020. /* Pointers to derived tables (these workspaces have image lifespan) */
  169021. d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  169022. d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  169023. /* Precalculated info set up by start_pass for use in decode_mcu: */
  169024. /* Pointers to derived tables to be used for each block within an MCU */
  169025. d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  169026. d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  169027. /* Whether we care about the DC and AC coefficient values for each block */
  169028. boolean dc_needed[D_MAX_BLOCKS_IN_MCU];
  169029. boolean ac_needed[D_MAX_BLOCKS_IN_MCU];
  169030. } huff_entropy_decoder2;
  169031. typedef huff_entropy_decoder2 * huff_entropy_ptr2;
  169032. /*
  169033. * Initialize for a Huffman-compressed scan.
  169034. */
  169035. METHODDEF(void)
  169036. start_pass_huff_decoder (j_decompress_ptr cinfo)
  169037. {
  169038. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  169039. int ci, blkn, dctbl, actbl;
  169040. jpeg_component_info * compptr;
  169041. /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
  169042. * This ought to be an error condition, but we make it a warning because
  169043. * there are some baseline files out there with all zeroes in these bytes.
  169044. */
  169045. if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
  169046. cinfo->Ah != 0 || cinfo->Al != 0)
  169047. WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
  169048. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  169049. compptr = cinfo->cur_comp_info[ci];
  169050. dctbl = compptr->dc_tbl_no;
  169051. actbl = compptr->ac_tbl_no;
  169052. /* Compute derived values for Huffman tables */
  169053. /* We may do this more than once for a table, but it's not expensive */
  169054. jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
  169055. & entropy->dc_derived_tbls[dctbl]);
  169056. jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
  169057. & entropy->ac_derived_tbls[actbl]);
  169058. /* Initialize DC predictions to 0 */
  169059. entropy->saved.last_dc_val[ci] = 0;
  169060. }
  169061. /* Precalculate decoding info for each block in an MCU of this scan */
  169062. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  169063. ci = cinfo->MCU_membership[blkn];
  169064. compptr = cinfo->cur_comp_info[ci];
  169065. /* Precalculate which table to use for each block */
  169066. entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
  169067. entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
  169068. /* Decide whether we really care about the coefficient values */
  169069. if (compptr->component_needed) {
  169070. entropy->dc_needed[blkn] = TRUE;
  169071. /* we don't need the ACs if producing a 1/8th-size image */
  169072. entropy->ac_needed[blkn] = (compptr->DCT_scaled_size > 1);
  169073. } else {
  169074. entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;
  169075. }
  169076. }
  169077. /* Initialize bitread state variables */
  169078. entropy->bitstate.bits_left = 0;
  169079. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  169080. entropy->pub.insufficient_data = FALSE;
  169081. /* Initialize restart counter */
  169082. entropy->restarts_to_go = cinfo->restart_interval;
  169083. }
  169084. /*
  169085. * Compute the derived values for a Huffman table.
  169086. * This routine also performs some validation checks on the table.
  169087. *
  169088. * Note this is also used by jdphuff.c.
  169089. */
  169090. GLOBAL(void)
  169091. jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,
  169092. d_derived_tbl ** pdtbl)
  169093. {
  169094. JHUFF_TBL *htbl;
  169095. d_derived_tbl *dtbl;
  169096. int p, i, l, si, numsymbols;
  169097. int lookbits, ctr;
  169098. char huffsize[257];
  169099. unsigned int huffcode[257];
  169100. unsigned int code;
  169101. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  169102. * paralleling the order of the symbols themselves in htbl->huffval[].
  169103. */
  169104. /* Find the input Huffman table */
  169105. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  169106. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  169107. htbl =
  169108. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  169109. if (htbl == NULL)
  169110. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  169111. /* Allocate a workspace if we haven't already done so. */
  169112. if (*pdtbl == NULL)
  169113. *pdtbl = (d_derived_tbl *)
  169114. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169115. SIZEOF(d_derived_tbl));
  169116. dtbl = *pdtbl;
  169117. dtbl->pub = htbl; /* fill in back link */
  169118. /* Figure C.1: make table of Huffman code length for each symbol */
  169119. p = 0;
  169120. for (l = 1; l <= 16; l++) {
  169121. i = (int) htbl->bits[l];
  169122. if (i < 0 || p + i > 256) /* protect against table overrun */
  169123. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  169124. while (i--)
  169125. huffsize[p++] = (char) l;
  169126. }
  169127. huffsize[p] = 0;
  169128. numsymbols = p;
  169129. /* Figure C.2: generate the codes themselves */
  169130. /* We also validate that the counts represent a legal Huffman code tree. */
  169131. code = 0;
  169132. si = huffsize[0];
  169133. p = 0;
  169134. while (huffsize[p]) {
  169135. while (((int) huffsize[p]) == si) {
  169136. huffcode[p++] = code;
  169137. code++;
  169138. }
  169139. /* code is now 1 more than the last code used for codelength si; but
  169140. * it must still fit in si bits, since no code is allowed to be all ones.
  169141. */
  169142. if (((INT32) code) >= (((INT32) 1) << si))
  169143. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  169144. code <<= 1;
  169145. si++;
  169146. }
  169147. /* Figure F.15: generate decoding tables for bit-sequential decoding */
  169148. p = 0;
  169149. for (l = 1; l <= 16; l++) {
  169150. if (htbl->bits[l]) {
  169151. /* valoffset[l] = huffval[] index of 1st symbol of code length l,
  169152. * minus the minimum code of length l
  169153. */
  169154. dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];
  169155. p += htbl->bits[l];
  169156. dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
  169157. } else {
  169158. dtbl->maxcode[l] = -1; /* -1 if no codes of this length */
  169159. }
  169160. }
  169161. dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
  169162. /* Compute lookahead tables to speed up decoding.
  169163. * First we set all the table entries to 0, indicating "too long";
  169164. * then we iterate through the Huffman codes that are short enough and
  169165. * fill in all the entries that correspond to bit sequences starting
  169166. * with that code.
  169167. */
  169168. MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
  169169. p = 0;
  169170. for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
  169171. for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
  169172. /* l = current code's length, p = its index in huffcode[] & huffval[]. */
  169173. /* Generate left-justified code followed by all possible bit sequences */
  169174. lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
  169175. for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
  169176. dtbl->look_nbits[lookbits] = l;
  169177. dtbl->look_sym[lookbits] = htbl->huffval[p];
  169178. lookbits++;
  169179. }
  169180. }
  169181. }
  169182. /* Validate symbols as being reasonable.
  169183. * For AC tables, we make no check, but accept all byte values 0..255.
  169184. * For DC tables, we require the symbols to be in range 0..15.
  169185. * (Tighter bounds could be applied depending on the data depth and mode,
  169186. * but this is sufficient to ensure safe decoding.)
  169187. */
  169188. if (isDC) {
  169189. for (i = 0; i < numsymbols; i++) {
  169190. int sym = htbl->huffval[i];
  169191. if (sym < 0 || sym > 15)
  169192. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  169193. }
  169194. }
  169195. }
  169196. /*
  169197. * Out-of-line code for bit fetching (shared with jdphuff.c).
  169198. * See jdhuff.h for info about usage.
  169199. * Note: current values of get_buffer and bits_left are passed as parameters,
  169200. * but are returned in the corresponding fields of the state struct.
  169201. *
  169202. * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
  169203. * of get_buffer to be used. (On machines with wider words, an even larger
  169204. * buffer could be used.) However, on some machines 32-bit shifts are
  169205. * quite slow and take time proportional to the number of places shifted.
  169206. * (This is true with most PC compilers, for instance.) In this case it may
  169207. * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the
  169208. * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
  169209. */
  169210. #ifdef SLOW_SHIFT_32
  169211. #define MIN_GET_BITS 15 /* minimum allowable value */
  169212. #else
  169213. #define MIN_GET_BITS (BIT_BUF_SIZE-7)
  169214. #endif
  169215. GLOBAL(boolean)
  169216. jpeg_fill_bit_buffer (bitread_working_state * state,
  169217. register bit_buf_type get_buffer, register int bits_left,
  169218. int nbits)
  169219. /* Load up the bit buffer to a depth of at least nbits */
  169220. {
  169221. /* Copy heavily used state fields into locals (hopefully registers) */
  169222. register const JOCTET * next_input_byte = state->next_input_byte;
  169223. register size_t bytes_in_buffer = state->bytes_in_buffer;
  169224. j_decompress_ptr cinfo = state->cinfo;
  169225. /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
  169226. /* (It is assumed that no request will be for more than that many bits.) */
  169227. /* We fail to do so only if we hit a marker or are forced to suspend. */
  169228. if (cinfo->unread_marker == 0) { /* cannot advance past a marker */
  169229. while (bits_left < MIN_GET_BITS) {
  169230. register int c;
  169231. /* Attempt to read a byte */
  169232. if (bytes_in_buffer == 0) {
  169233. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  169234. return FALSE;
  169235. next_input_byte = cinfo->src->next_input_byte;
  169236. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  169237. }
  169238. bytes_in_buffer--;
  169239. c = GETJOCTET(*next_input_byte++);
  169240. /* If it's 0xFF, check and discard stuffed zero byte */
  169241. if (c == 0xFF) {
  169242. /* Loop here to discard any padding FF's on terminating marker,
  169243. * so that we can save a valid unread_marker value. NOTE: we will
  169244. * accept multiple FF's followed by a 0 as meaning a single FF data
  169245. * byte. This data pattern is not valid according to the standard.
  169246. */
  169247. do {
  169248. if (bytes_in_buffer == 0) {
  169249. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  169250. return FALSE;
  169251. next_input_byte = cinfo->src->next_input_byte;
  169252. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  169253. }
  169254. bytes_in_buffer--;
  169255. c = GETJOCTET(*next_input_byte++);
  169256. } while (c == 0xFF);
  169257. if (c == 0) {
  169258. /* Found FF/00, which represents an FF data byte */
  169259. c = 0xFF;
  169260. } else {
  169261. /* Oops, it's actually a marker indicating end of compressed data.
  169262. * Save the marker code for later use.
  169263. * Fine point: it might appear that we should save the marker into
  169264. * bitread working state, not straight into permanent state. But
  169265. * once we have hit a marker, we cannot need to suspend within the
  169266. * current MCU, because we will read no more bytes from the data
  169267. * source. So it is OK to update permanent state right away.
  169268. */
  169269. cinfo->unread_marker = c;
  169270. /* See if we need to insert some fake zero bits. */
  169271. goto no_more_bytes;
  169272. }
  169273. }
  169274. /* OK, load c into get_buffer */
  169275. get_buffer = (get_buffer << 8) | c;
  169276. bits_left += 8;
  169277. } /* end while */
  169278. } else {
  169279. no_more_bytes:
  169280. /* We get here if we've read the marker that terminates the compressed
  169281. * data segment. There should be enough bits in the buffer register
  169282. * to satisfy the request; if so, no problem.
  169283. */
  169284. if (nbits > bits_left) {
  169285. /* Uh-oh. Report corrupted data to user and stuff zeroes into
  169286. * the data stream, so that we can produce some kind of image.
  169287. * We use a nonvolatile flag to ensure that only one warning message
  169288. * appears per data segment.
  169289. */
  169290. if (! cinfo->entropy->insufficient_data) {
  169291. WARNMS(cinfo, JWRN_HIT_MARKER);
  169292. cinfo->entropy->insufficient_data = TRUE;
  169293. }
  169294. /* Fill the buffer with zero bits */
  169295. get_buffer <<= MIN_GET_BITS - bits_left;
  169296. bits_left = MIN_GET_BITS;
  169297. }
  169298. }
  169299. /* Unload the local registers */
  169300. state->next_input_byte = next_input_byte;
  169301. state->bytes_in_buffer = bytes_in_buffer;
  169302. state->get_buffer = get_buffer;
  169303. state->bits_left = bits_left;
  169304. return TRUE;
  169305. }
  169306. /*
  169307. * Out-of-line code for Huffman code decoding.
  169308. * See jdhuff.h for info about usage.
  169309. */
  169310. GLOBAL(int)
  169311. jpeg_huff_decode (bitread_working_state * state,
  169312. register bit_buf_type get_buffer, register int bits_left,
  169313. d_derived_tbl * htbl, int min_bits)
  169314. {
  169315. register int l = min_bits;
  169316. register INT32 code;
  169317. /* HUFF_DECODE has determined that the code is at least min_bits */
  169318. /* bits long, so fetch that many bits in one swoop. */
  169319. CHECK_BIT_BUFFER(*state, l, return -1);
  169320. code = GET_BITS(l);
  169321. /* Collect the rest of the Huffman code one bit at a time. */
  169322. /* This is per Figure F.16 in the JPEG spec. */
  169323. while (code > htbl->maxcode[l]) {
  169324. code <<= 1;
  169325. CHECK_BIT_BUFFER(*state, 1, return -1);
  169326. code |= GET_BITS(1);
  169327. l++;
  169328. }
  169329. /* Unload the local registers */
  169330. state->get_buffer = get_buffer;
  169331. state->bits_left = bits_left;
  169332. /* With garbage input we may reach the sentinel value l = 17. */
  169333. if (l > 16) {
  169334. WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
  169335. return 0; /* fake a zero as the safest result */
  169336. }
  169337. return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
  169338. }
  169339. /*
  169340. * Check for a restart marker & resynchronize decoder.
  169341. * Returns FALSE if must suspend.
  169342. */
  169343. LOCAL(boolean)
  169344. process_restart (j_decompress_ptr cinfo)
  169345. {
  169346. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  169347. int ci;
  169348. /* Throw away any unused bits remaining in bit buffer; */
  169349. /* include any full bytes in next_marker's count of discarded bytes */
  169350. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  169351. entropy->bitstate.bits_left = 0;
  169352. /* Advance past the RSTn marker */
  169353. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  169354. return FALSE;
  169355. /* Re-initialize DC predictions to 0 */
  169356. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  169357. entropy->saved.last_dc_val[ci] = 0;
  169358. /* Reset restart counter */
  169359. entropy->restarts_to_go = cinfo->restart_interval;
  169360. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  169361. * against a marker. In that case we will end up treating the next data
  169362. * segment as empty, and we can avoid producing bogus output pixels by
  169363. * leaving the flag set.
  169364. */
  169365. if (cinfo->unread_marker == 0)
  169366. entropy->pub.insufficient_data = FALSE;
  169367. return TRUE;
  169368. }
  169369. /*
  169370. * Decode and return one MCU's worth of Huffman-compressed coefficients.
  169371. * The coefficients are reordered from zigzag order into natural array order,
  169372. * but are not dequantized.
  169373. *
  169374. * The i'th block of the MCU is stored into the block pointed to by
  169375. * MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
  169376. * (Wholesale zeroing is usually a little faster than retail...)
  169377. *
  169378. * Returns FALSE if data source requested suspension. In that case no
  169379. * changes have been made to permanent state. (Exception: some output
  169380. * coefficients may already have been assigned. This is harmless for
  169381. * this module, since we'll just re-assign them on the next call.)
  169382. */
  169383. METHODDEF(boolean)
  169384. decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  169385. {
  169386. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  169387. int blkn;
  169388. BITREAD_STATE_VARS;
  169389. savable_state2 state;
  169390. /* Process restart marker if needed; may have to suspend */
  169391. if (cinfo->restart_interval) {
  169392. if (entropy->restarts_to_go == 0)
  169393. if (! process_restart(cinfo))
  169394. return FALSE;
  169395. }
  169396. /* If we've run out of data, just leave the MCU set to zeroes.
  169397. * This way, we return uniform gray for the remainder of the segment.
  169398. */
  169399. if (! entropy->pub.insufficient_data) {
  169400. /* Load up working state */
  169401. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  169402. ASSIGN_STATE(state, entropy->saved);
  169403. /* Outer loop handles each block in the MCU */
  169404. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  169405. JBLOCKROW block = MCU_data[blkn];
  169406. d_derived_tbl * dctbl = entropy->dc_cur_tbls[blkn];
  169407. d_derived_tbl * actbl = entropy->ac_cur_tbls[blkn];
  169408. register int s, k, r;
  169409. /* Decode a single block's worth of coefficients */
  169410. /* Section F.2.2.1: decode the DC coefficient difference */
  169411. HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
  169412. if (s) {
  169413. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  169414. r = GET_BITS(s);
  169415. s = HUFF_EXTEND(r, s);
  169416. }
  169417. if (entropy->dc_needed[blkn]) {
  169418. /* Convert DC difference to actual value, update last_dc_val */
  169419. int ci = cinfo->MCU_membership[blkn];
  169420. s += state.last_dc_val[ci];
  169421. state.last_dc_val[ci] = s;
  169422. /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
  169423. (*block)[0] = (JCOEF) s;
  169424. }
  169425. if (entropy->ac_needed[blkn]) {
  169426. /* Section F.2.2.2: decode the AC coefficients */
  169427. /* Since zeroes are skipped, output area must be cleared beforehand */
  169428. for (k = 1; k < DCTSIZE2; k++) {
  169429. HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
  169430. r = s >> 4;
  169431. s &= 15;
  169432. if (s) {
  169433. k += r;
  169434. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  169435. r = GET_BITS(s);
  169436. s = HUFF_EXTEND(r, s);
  169437. /* Output coefficient in natural (dezigzagged) order.
  169438. * Note: the extra entries in jpeg_natural_order[] will save us
  169439. * if k >= DCTSIZE2, which could happen if the data is corrupted.
  169440. */
  169441. (*block)[jpeg_natural_order[k]] = (JCOEF) s;
  169442. } else {
  169443. if (r != 15)
  169444. break;
  169445. k += 15;
  169446. }
  169447. }
  169448. } else {
  169449. /* Section F.2.2.2: decode the AC coefficients */
  169450. /* In this path we just discard the values */
  169451. for (k = 1; k < DCTSIZE2; k++) {
  169452. HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
  169453. r = s >> 4;
  169454. s &= 15;
  169455. if (s) {
  169456. k += r;
  169457. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  169458. DROP_BITS(s);
  169459. } else {
  169460. if (r != 15)
  169461. break;
  169462. k += 15;
  169463. }
  169464. }
  169465. }
  169466. }
  169467. /* Completed MCU, so update state */
  169468. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  169469. ASSIGN_STATE(entropy->saved, state);
  169470. }
  169471. /* Account for restart interval (no-op if not using restarts) */
  169472. entropy->restarts_to_go--;
  169473. return TRUE;
  169474. }
  169475. /*
  169476. * Module initialization routine for Huffman entropy decoding.
  169477. */
  169478. GLOBAL(void)
  169479. jinit_huff_decoder (j_decompress_ptr cinfo)
  169480. {
  169481. huff_entropy_ptr2 entropy;
  169482. int i;
  169483. entropy = (huff_entropy_ptr2)
  169484. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169485. SIZEOF(huff_entropy_decoder2));
  169486. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  169487. entropy->pub.start_pass = start_pass_huff_decoder;
  169488. entropy->pub.decode_mcu = decode_mcu;
  169489. /* Mark tables unallocated */
  169490. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  169491. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  169492. }
  169493. }
  169494. /*** End of inlined file: jdhuff.c ***/
  169495. /*** Start of inlined file: jdinput.c ***/
  169496. #define JPEG_INTERNALS
  169497. /* Private state */
  169498. typedef struct {
  169499. struct jpeg_input_controller pub; /* public fields */
  169500. boolean inheaders; /* TRUE until first SOS is reached */
  169501. } my_input_controller;
  169502. typedef my_input_controller * my_inputctl_ptr;
  169503. /* Forward declarations */
  169504. METHODDEF(int) consume_markers JPP((j_decompress_ptr cinfo));
  169505. /*
  169506. * Routines to calculate various quantities related to the size of the image.
  169507. */
  169508. LOCAL(void)
  169509. initial_setup2 (j_decompress_ptr cinfo)
  169510. /* Called once, when first SOS marker is reached */
  169511. {
  169512. int ci;
  169513. jpeg_component_info *compptr;
  169514. /* Make sure image isn't bigger than I can handle */
  169515. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  169516. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  169517. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  169518. /* For now, precision must match compiled-in value... */
  169519. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  169520. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  169521. /* Check that number of components won't exceed internal array sizes */
  169522. if (cinfo->num_components > MAX_COMPONENTS)
  169523. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  169524. MAX_COMPONENTS);
  169525. /* Compute maximum sampling factors; check factor validity */
  169526. cinfo->max_h_samp_factor = 1;
  169527. cinfo->max_v_samp_factor = 1;
  169528. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169529. ci++, compptr++) {
  169530. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  169531. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  169532. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  169533. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  169534. compptr->h_samp_factor);
  169535. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  169536. compptr->v_samp_factor);
  169537. }
  169538. /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE.
  169539. * In the full decompressor, this will be overridden by jdmaster.c;
  169540. * but in the transcoder, jdmaster.c is not used, so we must do it here.
  169541. */
  169542. cinfo->min_DCT_scaled_size = DCTSIZE;
  169543. /* Compute dimensions of components */
  169544. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169545. ci++, compptr++) {
  169546. compptr->DCT_scaled_size = DCTSIZE;
  169547. /* Size in DCT blocks */
  169548. compptr->width_in_blocks = (JDIMENSION)
  169549. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  169550. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  169551. compptr->height_in_blocks = (JDIMENSION)
  169552. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  169553. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  169554. /* downsampled_width and downsampled_height will also be overridden by
  169555. * jdmaster.c if we are doing full decompression. The transcoder library
  169556. * doesn't use these values, but the calling application might.
  169557. */
  169558. /* Size in samples */
  169559. compptr->downsampled_width = (JDIMENSION)
  169560. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  169561. (long) cinfo->max_h_samp_factor);
  169562. compptr->downsampled_height = (JDIMENSION)
  169563. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  169564. (long) cinfo->max_v_samp_factor);
  169565. /* Mark component needed, until color conversion says otherwise */
  169566. compptr->component_needed = TRUE;
  169567. /* Mark no quantization table yet saved for component */
  169568. compptr->quant_table = NULL;
  169569. }
  169570. /* Compute number of fully interleaved MCU rows. */
  169571. cinfo->total_iMCU_rows = (JDIMENSION)
  169572. jdiv_round_up((long) cinfo->image_height,
  169573. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  169574. /* Decide whether file contains multiple scans */
  169575. if (cinfo->comps_in_scan < cinfo->num_components || cinfo->progressive_mode)
  169576. cinfo->inputctl->has_multiple_scans = TRUE;
  169577. else
  169578. cinfo->inputctl->has_multiple_scans = FALSE;
  169579. }
  169580. LOCAL(void)
  169581. per_scan_setup2 (j_decompress_ptr cinfo)
  169582. /* Do computations that are needed before processing a JPEG scan */
  169583. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] were set from SOS marker */
  169584. {
  169585. int ci, mcublks, tmp;
  169586. jpeg_component_info *compptr;
  169587. if (cinfo->comps_in_scan == 1) {
  169588. /* Noninterleaved (single-component) scan */
  169589. compptr = cinfo->cur_comp_info[0];
  169590. /* Overall image size in MCUs */
  169591. cinfo->MCUs_per_row = compptr->width_in_blocks;
  169592. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  169593. /* For noninterleaved scan, always one block per MCU */
  169594. compptr->MCU_width = 1;
  169595. compptr->MCU_height = 1;
  169596. compptr->MCU_blocks = 1;
  169597. compptr->MCU_sample_width = compptr->DCT_scaled_size;
  169598. compptr->last_col_width = 1;
  169599. /* For noninterleaved scans, it is convenient to define last_row_height
  169600. * as the number of block rows present in the last iMCU row.
  169601. */
  169602. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  169603. if (tmp == 0) tmp = compptr->v_samp_factor;
  169604. compptr->last_row_height = tmp;
  169605. /* Prepare array describing MCU composition */
  169606. cinfo->blocks_in_MCU = 1;
  169607. cinfo->MCU_membership[0] = 0;
  169608. } else {
  169609. /* Interleaved (multi-component) scan */
  169610. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  169611. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  169612. MAX_COMPS_IN_SCAN);
  169613. /* Overall image size in MCUs */
  169614. cinfo->MCUs_per_row = (JDIMENSION)
  169615. jdiv_round_up((long) cinfo->image_width,
  169616. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  169617. cinfo->MCU_rows_in_scan = (JDIMENSION)
  169618. jdiv_round_up((long) cinfo->image_height,
  169619. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  169620. cinfo->blocks_in_MCU = 0;
  169621. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  169622. compptr = cinfo->cur_comp_info[ci];
  169623. /* Sampling factors give # of blocks of component in each MCU */
  169624. compptr->MCU_width = compptr->h_samp_factor;
  169625. compptr->MCU_height = compptr->v_samp_factor;
  169626. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  169627. compptr->MCU_sample_width = compptr->MCU_width * compptr->DCT_scaled_size;
  169628. /* Figure number of non-dummy blocks in last MCU column & row */
  169629. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  169630. if (tmp == 0) tmp = compptr->MCU_width;
  169631. compptr->last_col_width = tmp;
  169632. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  169633. if (tmp == 0) tmp = compptr->MCU_height;
  169634. compptr->last_row_height = tmp;
  169635. /* Prepare array describing MCU composition */
  169636. mcublks = compptr->MCU_blocks;
  169637. if (cinfo->blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU)
  169638. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  169639. while (mcublks-- > 0) {
  169640. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  169641. }
  169642. }
  169643. }
  169644. }
  169645. /*
  169646. * Save away a copy of the Q-table referenced by each component present
  169647. * in the current scan, unless already saved during a prior scan.
  169648. *
  169649. * In a multiple-scan JPEG file, the encoder could assign different components
  169650. * the same Q-table slot number, but change table definitions between scans
  169651. * so that each component uses a different Q-table. (The IJG encoder is not
  169652. * currently capable of doing this, but other encoders might.) Since we want
  169653. * to be able to dequantize all the components at the end of the file, this
  169654. * means that we have to save away the table actually used for each component.
  169655. * We do this by copying the table at the start of the first scan containing
  169656. * the component.
  169657. * The JPEG spec prohibits the encoder from changing the contents of a Q-table
  169658. * slot between scans of a component using that slot. If the encoder does so
  169659. * anyway, this decoder will simply use the Q-table values that were current
  169660. * at the start of the first scan for the component.
  169661. *
  169662. * The decompressor output side looks only at the saved quant tables,
  169663. * not at the current Q-table slots.
  169664. */
  169665. LOCAL(void)
  169666. latch_quant_tables (j_decompress_ptr cinfo)
  169667. {
  169668. int ci, qtblno;
  169669. jpeg_component_info *compptr;
  169670. JQUANT_TBL * qtbl;
  169671. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  169672. compptr = cinfo->cur_comp_info[ci];
  169673. /* No work if we already saved Q-table for this component */
  169674. if (compptr->quant_table != NULL)
  169675. continue;
  169676. /* Make sure specified quantization table is present */
  169677. qtblno = compptr->quant_tbl_no;
  169678. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  169679. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  169680. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  169681. /* OK, save away the quantization table */
  169682. qtbl = (JQUANT_TBL *)
  169683. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169684. SIZEOF(JQUANT_TBL));
  169685. MEMCOPY(qtbl, cinfo->quant_tbl_ptrs[qtblno], SIZEOF(JQUANT_TBL));
  169686. compptr->quant_table = qtbl;
  169687. }
  169688. }
  169689. /*
  169690. * Initialize the input modules to read a scan of compressed data.
  169691. * The first call to this is done by jdmaster.c after initializing
  169692. * the entire decompressor (during jpeg_start_decompress).
  169693. * Subsequent calls come from consume_markers, below.
  169694. */
  169695. METHODDEF(void)
  169696. start_input_pass2 (j_decompress_ptr cinfo)
  169697. {
  169698. per_scan_setup2(cinfo);
  169699. latch_quant_tables(cinfo);
  169700. (*cinfo->entropy->start_pass) (cinfo);
  169701. (*cinfo->coef->start_input_pass) (cinfo);
  169702. cinfo->inputctl->consume_input = cinfo->coef->consume_data;
  169703. }
  169704. /*
  169705. * Finish up after inputting a compressed-data scan.
  169706. * This is called by the coefficient controller after it's read all
  169707. * the expected data of the scan.
  169708. */
  169709. METHODDEF(void)
  169710. finish_input_pass (j_decompress_ptr cinfo)
  169711. {
  169712. cinfo->inputctl->consume_input = consume_markers;
  169713. }
  169714. /*
  169715. * Read JPEG markers before, between, or after compressed-data scans.
  169716. * Change state as necessary when a new scan is reached.
  169717. * Return value is JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  169718. *
  169719. * The consume_input method pointer points either here or to the
  169720. * coefficient controller's consume_data routine, depending on whether
  169721. * we are reading a compressed data segment or inter-segment markers.
  169722. */
  169723. METHODDEF(int)
  169724. consume_markers (j_decompress_ptr cinfo)
  169725. {
  169726. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  169727. int val;
  169728. if (inputctl->pub.eoi_reached) /* After hitting EOI, read no further */
  169729. return JPEG_REACHED_EOI;
  169730. val = (*cinfo->marker->read_markers) (cinfo);
  169731. switch (val) {
  169732. case JPEG_REACHED_SOS: /* Found SOS */
  169733. if (inputctl->inheaders) { /* 1st SOS */
  169734. initial_setup2(cinfo);
  169735. inputctl->inheaders = FALSE;
  169736. /* Note: start_input_pass must be called by jdmaster.c
  169737. * before any more input can be consumed. jdapimin.c is
  169738. * responsible for enforcing this sequencing.
  169739. */
  169740. } else { /* 2nd or later SOS marker */
  169741. if (! inputctl->pub.has_multiple_scans)
  169742. ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */
  169743. start_input_pass2(cinfo);
  169744. }
  169745. break;
  169746. case JPEG_REACHED_EOI: /* Found EOI */
  169747. inputctl->pub.eoi_reached = TRUE;
  169748. if (inputctl->inheaders) { /* Tables-only datastream, apparently */
  169749. if (cinfo->marker->saw_SOF)
  169750. ERREXIT(cinfo, JERR_SOF_NO_SOS);
  169751. } else {
  169752. /* Prevent infinite loop in coef ctlr's decompress_data routine
  169753. * if user set output_scan_number larger than number of scans.
  169754. */
  169755. if (cinfo->output_scan_number > cinfo->input_scan_number)
  169756. cinfo->output_scan_number = cinfo->input_scan_number;
  169757. }
  169758. break;
  169759. case JPEG_SUSPENDED:
  169760. break;
  169761. }
  169762. return val;
  169763. }
  169764. /*
  169765. * Reset state to begin a fresh datastream.
  169766. */
  169767. METHODDEF(void)
  169768. reset_input_controller (j_decompress_ptr cinfo)
  169769. {
  169770. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  169771. inputctl->pub.consume_input = consume_markers;
  169772. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  169773. inputctl->pub.eoi_reached = FALSE;
  169774. inputctl->inheaders = TRUE;
  169775. /* Reset other modules */
  169776. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  169777. (*cinfo->marker->reset_marker_reader) (cinfo);
  169778. /* Reset progression state -- would be cleaner if entropy decoder did this */
  169779. cinfo->coef_bits = NULL;
  169780. }
  169781. /*
  169782. * Initialize the input controller module.
  169783. * This is called only once, when the decompression object is created.
  169784. */
  169785. GLOBAL(void)
  169786. jinit_input_controller (j_decompress_ptr cinfo)
  169787. {
  169788. my_inputctl_ptr inputctl;
  169789. /* Create subobject in permanent pool */
  169790. inputctl = (my_inputctl_ptr)
  169791. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  169792. SIZEOF(my_input_controller));
  169793. cinfo->inputctl = (struct jpeg_input_controller *) inputctl;
  169794. /* Initialize method pointers */
  169795. inputctl->pub.consume_input = consume_markers;
  169796. inputctl->pub.reset_input_controller = reset_input_controller;
  169797. inputctl->pub.start_input_pass = start_input_pass2;
  169798. inputctl->pub.finish_input_pass = finish_input_pass;
  169799. /* Initialize state: can't use reset_input_controller since we don't
  169800. * want to try to reset other modules yet.
  169801. */
  169802. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  169803. inputctl->pub.eoi_reached = FALSE;
  169804. inputctl->inheaders = TRUE;
  169805. }
  169806. /*** End of inlined file: jdinput.c ***/
  169807. /*** Start of inlined file: jdmainct.c ***/
  169808. #define JPEG_INTERNALS
  169809. /*
  169810. * In the current system design, the main buffer need never be a full-image
  169811. * buffer; any full-height buffers will be found inside the coefficient or
  169812. * postprocessing controllers. Nonetheless, the main controller is not
  169813. * trivial. Its responsibility is to provide context rows for upsampling/
  169814. * rescaling, and doing this in an efficient fashion is a bit tricky.
  169815. *
  169816. * Postprocessor input data is counted in "row groups". A row group
  169817. * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size)
  169818. * sample rows of each component. (We require DCT_scaled_size values to be
  169819. * chosen such that these numbers are integers. In practice DCT_scaled_size
  169820. * values will likely be powers of two, so we actually have the stronger
  169821. * condition that DCT_scaled_size / min_DCT_scaled_size is an integer.)
  169822. * Upsampling will typically produce max_v_samp_factor pixel rows from each
  169823. * row group (times any additional scale factor that the upsampler is
  169824. * applying).
  169825. *
  169826. * The coefficient controller will deliver data to us one iMCU row at a time;
  169827. * each iMCU row contains v_samp_factor * DCT_scaled_size sample rows, or
  169828. * exactly min_DCT_scaled_size row groups. (This amount of data corresponds
  169829. * to one row of MCUs when the image is fully interleaved.) Note that the
  169830. * number of sample rows varies across components, but the number of row
  169831. * groups does not. Some garbage sample rows may be included in the last iMCU
  169832. * row at the bottom of the image.
  169833. *
  169834. * Depending on the vertical scaling algorithm used, the upsampler may need
  169835. * access to the sample row(s) above and below its current input row group.
  169836. * The upsampler is required to set need_context_rows TRUE at global selection
  169837. * time if so. When need_context_rows is FALSE, this controller can simply
  169838. * obtain one iMCU row at a time from the coefficient controller and dole it
  169839. * out as row groups to the postprocessor.
  169840. *
  169841. * When need_context_rows is TRUE, this controller guarantees that the buffer
  169842. * passed to postprocessing contains at least one row group's worth of samples
  169843. * above and below the row group(s) being processed. Note that the context
  169844. * rows "above" the first passed row group appear at negative row offsets in
  169845. * the passed buffer. At the top and bottom of the image, the required
  169846. * context rows are manufactured by duplicating the first or last real sample
  169847. * row; this avoids having special cases in the upsampling inner loops.
  169848. *
  169849. * The amount of context is fixed at one row group just because that's a
  169850. * convenient number for this controller to work with. The existing
  169851. * upsamplers really only need one sample row of context. An upsampler
  169852. * supporting arbitrary output rescaling might wish for more than one row
  169853. * group of context when shrinking the image; tough, we don't handle that.
  169854. * (This is justified by the assumption that downsizing will be handled mostly
  169855. * by adjusting the DCT_scaled_size values, so that the actual scale factor at
  169856. * the upsample step needn't be much less than one.)
  169857. *
  169858. * To provide the desired context, we have to retain the last two row groups
  169859. * of one iMCU row while reading in the next iMCU row. (The last row group
  169860. * can't be processed until we have another row group for its below-context,
  169861. * and so we have to save the next-to-last group too for its above-context.)
  169862. * We could do this most simply by copying data around in our buffer, but
  169863. * that'd be very slow. We can avoid copying any data by creating a rather
  169864. * strange pointer structure. Here's how it works. We allocate a workspace
  169865. * consisting of M+2 row groups (where M = min_DCT_scaled_size is the number
  169866. * of row groups per iMCU row). We create two sets of redundant pointers to
  169867. * the workspace. Labeling the physical row groups 0 to M+1, the synthesized
  169868. * pointer lists look like this:
  169869. * M+1 M-1
  169870. * master pointer --> 0 master pointer --> 0
  169871. * 1 1
  169872. * ... ...
  169873. * M-3 M-3
  169874. * M-2 M
  169875. * M-1 M+1
  169876. * M M-2
  169877. * M+1 M-1
  169878. * 0 0
  169879. * We read alternate iMCU rows using each master pointer; thus the last two
  169880. * row groups of the previous iMCU row remain un-overwritten in the workspace.
  169881. * The pointer lists are set up so that the required context rows appear to
  169882. * be adjacent to the proper places when we pass the pointer lists to the
  169883. * upsampler.
  169884. *
  169885. * The above pictures describe the normal state of the pointer lists.
  169886. * At top and bottom of the image, we diddle the pointer lists to duplicate
  169887. * the first or last sample row as necessary (this is cheaper than copying
  169888. * sample rows around).
  169889. *
  169890. * This scheme breaks down if M < 2, ie, min_DCT_scaled_size is 1. In that
  169891. * situation each iMCU row provides only one row group so the buffering logic
  169892. * must be different (eg, we must read two iMCU rows before we can emit the
  169893. * first row group). For now, we simply do not support providing context
  169894. * rows when min_DCT_scaled_size is 1. That combination seems unlikely to
  169895. * be worth providing --- if someone wants a 1/8th-size preview, they probably
  169896. * want it quick and dirty, so a context-free upsampler is sufficient.
  169897. */
  169898. /* Private buffer controller object */
  169899. typedef struct {
  169900. struct jpeg_d_main_controller pub; /* public fields */
  169901. /* Pointer to allocated workspace (M or M+2 row groups). */
  169902. JSAMPARRAY buffer[MAX_COMPONENTS];
  169903. boolean buffer_full; /* Have we gotten an iMCU row from decoder? */
  169904. JDIMENSION rowgroup_ctr; /* counts row groups output to postprocessor */
  169905. /* Remaining fields are only used in the context case. */
  169906. /* These are the master pointers to the funny-order pointer lists. */
  169907. JSAMPIMAGE xbuffer[2]; /* pointers to weird pointer lists */
  169908. int whichptr; /* indicates which pointer set is now in use */
  169909. int context_state; /* process_data state machine status */
  169910. JDIMENSION rowgroups_avail; /* row groups available to postprocessor */
  169911. JDIMENSION iMCU_row_ctr; /* counts iMCU rows to detect image top/bot */
  169912. } my_main_controller4;
  169913. typedef my_main_controller4 * my_main_ptr4;
  169914. /* context_state values: */
  169915. #define CTX_PREPARE_FOR_IMCU 0 /* need to prepare for MCU row */
  169916. #define CTX_PROCESS_IMCU 1 /* feeding iMCU to postprocessor */
  169917. #define CTX_POSTPONED_ROW 2 /* feeding postponed row group */
  169918. /* Forward declarations */
  169919. METHODDEF(void) process_data_simple_main2
  169920. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  169921. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  169922. METHODDEF(void) process_data_context_main
  169923. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  169924. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  169925. #ifdef QUANT_2PASS_SUPPORTED
  169926. METHODDEF(void) process_data_crank_post
  169927. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  169928. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  169929. #endif
  169930. LOCAL(void)
  169931. alloc_funny_pointers (j_decompress_ptr cinfo)
  169932. /* Allocate space for the funny pointer lists.
  169933. * This is done only once, not once per pass.
  169934. */
  169935. {
  169936. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  169937. int ci, rgroup;
  169938. int M = cinfo->min_DCT_scaled_size;
  169939. jpeg_component_info *compptr;
  169940. JSAMPARRAY xbuf;
  169941. /* Get top-level space for component array pointers.
  169942. * We alloc both arrays with one call to save a few cycles.
  169943. */
  169944. main_->xbuffer[0] = (JSAMPIMAGE)
  169945. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169946. cinfo->num_components * 2 * SIZEOF(JSAMPARRAY));
  169947. main_->xbuffer[1] = main_->xbuffer[0] + cinfo->num_components;
  169948. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169949. ci++, compptr++) {
  169950. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  169951. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  169952. /* Get space for pointer lists --- M+4 row groups in each list.
  169953. * We alloc both pointer lists with one call to save a few cycles.
  169954. */
  169955. xbuf = (JSAMPARRAY)
  169956. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169957. 2 * (rgroup * (M + 4)) * SIZEOF(JSAMPROW));
  169958. xbuf += rgroup; /* want one row group at negative offsets */
  169959. main_->xbuffer[0][ci] = xbuf;
  169960. xbuf += rgroup * (M + 4);
  169961. main_->xbuffer[1][ci] = xbuf;
  169962. }
  169963. }
  169964. LOCAL(void)
  169965. make_funny_pointers (j_decompress_ptr cinfo)
  169966. /* Create the funny pointer lists discussed in the comments above.
  169967. * The actual workspace is already allocated (in main->buffer),
  169968. * and the space for the pointer lists is allocated too.
  169969. * This routine just fills in the curiously ordered lists.
  169970. * This will be repeated at the beginning of each pass.
  169971. */
  169972. {
  169973. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  169974. int ci, i, rgroup;
  169975. int M = cinfo->min_DCT_scaled_size;
  169976. jpeg_component_info *compptr;
  169977. JSAMPARRAY buf, xbuf0, xbuf1;
  169978. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169979. ci++, compptr++) {
  169980. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  169981. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  169982. xbuf0 = main_->xbuffer[0][ci];
  169983. xbuf1 = main_->xbuffer[1][ci];
  169984. /* First copy the workspace pointers as-is */
  169985. buf = main_->buffer[ci];
  169986. for (i = 0; i < rgroup * (M + 2); i++) {
  169987. xbuf0[i] = xbuf1[i] = buf[i];
  169988. }
  169989. /* In the second list, put the last four row groups in swapped order */
  169990. for (i = 0; i < rgroup * 2; i++) {
  169991. xbuf1[rgroup*(M-2) + i] = buf[rgroup*M + i];
  169992. xbuf1[rgroup*M + i] = buf[rgroup*(M-2) + i];
  169993. }
  169994. /* The wraparound pointers at top and bottom will be filled later
  169995. * (see set_wraparound_pointers, below). Initially we want the "above"
  169996. * pointers to duplicate the first actual data line. This only needs
  169997. * to happen in xbuffer[0].
  169998. */
  169999. for (i = 0; i < rgroup; i++) {
  170000. xbuf0[i - rgroup] = xbuf0[0];
  170001. }
  170002. }
  170003. }
  170004. LOCAL(void)
  170005. set_wraparound_pointers (j_decompress_ptr cinfo)
  170006. /* Set up the "wraparound" pointers at top and bottom of the pointer lists.
  170007. * This changes the pointer list state from top-of-image to the normal state.
  170008. */
  170009. {
  170010. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170011. int ci, i, rgroup;
  170012. int M = cinfo->min_DCT_scaled_size;
  170013. jpeg_component_info *compptr;
  170014. JSAMPARRAY xbuf0, xbuf1;
  170015. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170016. ci++, compptr++) {
  170017. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170018. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170019. xbuf0 = main_->xbuffer[0][ci];
  170020. xbuf1 = main_->xbuffer[1][ci];
  170021. for (i = 0; i < rgroup; i++) {
  170022. xbuf0[i - rgroup] = xbuf0[rgroup*(M+1) + i];
  170023. xbuf1[i - rgroup] = xbuf1[rgroup*(M+1) + i];
  170024. xbuf0[rgroup*(M+2) + i] = xbuf0[i];
  170025. xbuf1[rgroup*(M+2) + i] = xbuf1[i];
  170026. }
  170027. }
  170028. }
  170029. LOCAL(void)
  170030. set_bottom_pointers (j_decompress_ptr cinfo)
  170031. /* Change the pointer lists to duplicate the last sample row at the bottom
  170032. * of the image. whichptr indicates which xbuffer holds the final iMCU row.
  170033. * Also sets rowgroups_avail to indicate number of nondummy row groups in row.
  170034. */
  170035. {
  170036. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170037. int ci, i, rgroup, iMCUheight, rows_left;
  170038. jpeg_component_info *compptr;
  170039. JSAMPARRAY xbuf;
  170040. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170041. ci++, compptr++) {
  170042. /* Count sample rows in one iMCU row and in one row group */
  170043. iMCUheight = compptr->v_samp_factor * compptr->DCT_scaled_size;
  170044. rgroup = iMCUheight / cinfo->min_DCT_scaled_size;
  170045. /* Count nondummy sample rows remaining for this component */
  170046. rows_left = (int) (compptr->downsampled_height % (JDIMENSION) iMCUheight);
  170047. if (rows_left == 0) rows_left = iMCUheight;
  170048. /* Count nondummy row groups. Should get same answer for each component,
  170049. * so we need only do it once.
  170050. */
  170051. if (ci == 0) {
  170052. main_->rowgroups_avail = (JDIMENSION) ((rows_left-1) / rgroup + 1);
  170053. }
  170054. /* Duplicate the last real sample row rgroup*2 times; this pads out the
  170055. * last partial rowgroup and ensures at least one full rowgroup of context.
  170056. */
  170057. xbuf = main_->xbuffer[main_->whichptr][ci];
  170058. for (i = 0; i < rgroup * 2; i++) {
  170059. xbuf[rows_left + i] = xbuf[rows_left-1];
  170060. }
  170061. }
  170062. }
  170063. /*
  170064. * Initialize for a processing pass.
  170065. */
  170066. METHODDEF(void)
  170067. start_pass_main2 (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  170068. {
  170069. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170070. switch (pass_mode) {
  170071. case JBUF_PASS_THRU:
  170072. if (cinfo->upsample->need_context_rows) {
  170073. main_->pub.process_data = process_data_context_main;
  170074. make_funny_pointers(cinfo); /* Create the xbuffer[] lists */
  170075. main_->whichptr = 0; /* Read first iMCU row into xbuffer[0] */
  170076. main_->context_state = CTX_PREPARE_FOR_IMCU;
  170077. main_->iMCU_row_ctr = 0;
  170078. } else {
  170079. /* Simple case with no context needed */
  170080. main_->pub.process_data = process_data_simple_main2;
  170081. }
  170082. main_->buffer_full = FALSE; /* Mark buffer empty */
  170083. main_->rowgroup_ctr = 0;
  170084. break;
  170085. #ifdef QUANT_2PASS_SUPPORTED
  170086. case JBUF_CRANK_DEST:
  170087. /* For last pass of 2-pass quantization, just crank the postprocessor */
  170088. main_->pub.process_data = process_data_crank_post;
  170089. break;
  170090. #endif
  170091. default:
  170092. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  170093. break;
  170094. }
  170095. }
  170096. /*
  170097. * Process some data.
  170098. * This handles the simple case where no context is required.
  170099. */
  170100. METHODDEF(void)
  170101. process_data_simple_main2 (j_decompress_ptr cinfo,
  170102. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170103. JDIMENSION out_rows_avail)
  170104. {
  170105. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170106. JDIMENSION rowgroups_avail;
  170107. /* Read input data if we haven't filled the main buffer yet */
  170108. if (! main_->buffer_full) {
  170109. if (! (*cinfo->coef->decompress_data) (cinfo, main_->buffer))
  170110. return; /* suspension forced, can do nothing more */
  170111. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  170112. }
  170113. /* There are always min_DCT_scaled_size row groups in an iMCU row. */
  170114. rowgroups_avail = (JDIMENSION) cinfo->min_DCT_scaled_size;
  170115. /* Note: at the bottom of the image, we may pass extra garbage row groups
  170116. * to the postprocessor. The postprocessor has to check for bottom
  170117. * of image anyway (at row resolution), so no point in us doing it too.
  170118. */
  170119. /* Feed the postprocessor */
  170120. (*cinfo->post->post_process_data) (cinfo, main_->buffer,
  170121. &main_->rowgroup_ctr, rowgroups_avail,
  170122. output_buf, out_row_ctr, out_rows_avail);
  170123. /* Has postprocessor consumed all the data yet? If so, mark buffer empty */
  170124. if (main_->rowgroup_ctr >= rowgroups_avail) {
  170125. main_->buffer_full = FALSE;
  170126. main_->rowgroup_ctr = 0;
  170127. }
  170128. }
  170129. /*
  170130. * Process some data.
  170131. * This handles the case where context rows must be provided.
  170132. */
  170133. METHODDEF(void)
  170134. process_data_context_main (j_decompress_ptr cinfo,
  170135. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170136. JDIMENSION out_rows_avail)
  170137. {
  170138. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170139. /* Read input data if we haven't filled the main buffer yet */
  170140. if (! main_->buffer_full) {
  170141. if (! (*cinfo->coef->decompress_data) (cinfo,
  170142. main_->xbuffer[main_->whichptr]))
  170143. return; /* suspension forced, can do nothing more */
  170144. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  170145. main_->iMCU_row_ctr++; /* count rows received */
  170146. }
  170147. /* Postprocessor typically will not swallow all the input data it is handed
  170148. * in one call (due to filling the output buffer first). Must be prepared
  170149. * to exit and restart. This switch lets us keep track of how far we got.
  170150. * Note that each case falls through to the next on successful completion.
  170151. */
  170152. switch (main_->context_state) {
  170153. case CTX_POSTPONED_ROW:
  170154. /* Call postprocessor using previously set pointers for postponed row */
  170155. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  170156. &main_->rowgroup_ctr, main_->rowgroups_avail,
  170157. output_buf, out_row_ctr, out_rows_avail);
  170158. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  170159. return; /* Need to suspend */
  170160. main_->context_state = CTX_PREPARE_FOR_IMCU;
  170161. if (*out_row_ctr >= out_rows_avail)
  170162. return; /* Postprocessor exactly filled output buf */
  170163. /*FALLTHROUGH*/
  170164. case CTX_PREPARE_FOR_IMCU:
  170165. /* Prepare to process first M-1 row groups of this iMCU row */
  170166. main_->rowgroup_ctr = 0;
  170167. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size - 1);
  170168. /* Check for bottom of image: if so, tweak pointers to "duplicate"
  170169. * the last sample row, and adjust rowgroups_avail to ignore padding rows.
  170170. */
  170171. if (main_->iMCU_row_ctr == cinfo->total_iMCU_rows)
  170172. set_bottom_pointers(cinfo);
  170173. main_->context_state = CTX_PROCESS_IMCU;
  170174. /*FALLTHROUGH*/
  170175. case CTX_PROCESS_IMCU:
  170176. /* Call postprocessor using previously set pointers */
  170177. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  170178. &main_->rowgroup_ctr, main_->rowgroups_avail,
  170179. output_buf, out_row_ctr, out_rows_avail);
  170180. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  170181. return; /* Need to suspend */
  170182. /* After the first iMCU, change wraparound pointers to normal state */
  170183. if (main_->iMCU_row_ctr == 1)
  170184. set_wraparound_pointers(cinfo);
  170185. /* Prepare to load new iMCU row using other xbuffer list */
  170186. main_->whichptr ^= 1; /* 0=>1 or 1=>0 */
  170187. main_->buffer_full = FALSE;
  170188. /* Still need to process last row group of this iMCU row, */
  170189. /* which is saved at index M+1 of the other xbuffer */
  170190. main_->rowgroup_ctr = (JDIMENSION) (cinfo->min_DCT_scaled_size + 1);
  170191. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size + 2);
  170192. main_->context_state = CTX_POSTPONED_ROW;
  170193. }
  170194. }
  170195. /*
  170196. * Process some data.
  170197. * Final pass of two-pass quantization: just call the postprocessor.
  170198. * Source data will be the postprocessor controller's internal buffer.
  170199. */
  170200. #ifdef QUANT_2PASS_SUPPORTED
  170201. METHODDEF(void)
  170202. process_data_crank_post (j_decompress_ptr cinfo,
  170203. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170204. JDIMENSION out_rows_avail)
  170205. {
  170206. (*cinfo->post->post_process_data) (cinfo, (JSAMPIMAGE) NULL,
  170207. (JDIMENSION *) NULL, (JDIMENSION) 0,
  170208. output_buf, out_row_ctr, out_rows_avail);
  170209. }
  170210. #endif /* QUANT_2PASS_SUPPORTED */
  170211. /*
  170212. * Initialize main buffer controller.
  170213. */
  170214. GLOBAL(void)
  170215. jinit_d_main_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  170216. {
  170217. my_main_ptr4 main_;
  170218. int ci, rgroup, ngroups;
  170219. jpeg_component_info *compptr;
  170220. main_ = (my_main_ptr4)
  170221. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170222. SIZEOF(my_main_controller4));
  170223. cinfo->main = (struct jpeg_d_main_controller *) main_;
  170224. main_->pub.start_pass = start_pass_main2;
  170225. if (need_full_buffer) /* shouldn't happen */
  170226. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  170227. /* Allocate the workspace.
  170228. * ngroups is the number of row groups we need.
  170229. */
  170230. if (cinfo->upsample->need_context_rows) {
  170231. if (cinfo->min_DCT_scaled_size < 2) /* unsupported, see comments above */
  170232. ERREXIT(cinfo, JERR_NOTIMPL);
  170233. alloc_funny_pointers(cinfo); /* Alloc space for xbuffer[] lists */
  170234. ngroups = cinfo->min_DCT_scaled_size + 2;
  170235. } else {
  170236. ngroups = cinfo->min_DCT_scaled_size;
  170237. }
  170238. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170239. ci++, compptr++) {
  170240. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170241. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170242. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  170243. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170244. compptr->width_in_blocks * compptr->DCT_scaled_size,
  170245. (JDIMENSION) (rgroup * ngroups));
  170246. }
  170247. }
  170248. /*** End of inlined file: jdmainct.c ***/
  170249. /*** Start of inlined file: jdmarker.c ***/
  170250. #define JPEG_INTERNALS
  170251. /* Private state */
  170252. typedef struct {
  170253. struct jpeg_marker_reader pub; /* public fields */
  170254. /* Application-overridable marker processing methods */
  170255. jpeg_marker_parser_method process_COM;
  170256. jpeg_marker_parser_method process_APPn[16];
  170257. /* Limit on marker data length to save for each marker type */
  170258. unsigned int length_limit_COM;
  170259. unsigned int length_limit_APPn[16];
  170260. /* Status of COM/APPn marker saving */
  170261. jpeg_saved_marker_ptr cur_marker; /* NULL if not processing a marker */
  170262. unsigned int bytes_read; /* data bytes read so far in marker */
  170263. /* Note: cur_marker is not linked into marker_list until it's all read. */
  170264. } my_marker_reader;
  170265. typedef my_marker_reader * my_marker_ptr2;
  170266. /*
  170267. * Macros for fetching data from the data source module.
  170268. *
  170269. * At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect
  170270. * the current restart point; we update them only when we have reached a
  170271. * suitable place to restart if a suspension occurs.
  170272. */
  170273. /* Declare and initialize local copies of input pointer/count */
  170274. #define INPUT_VARS(cinfo) \
  170275. struct jpeg_source_mgr * datasrc = (cinfo)->src; \
  170276. const JOCTET * next_input_byte = datasrc->next_input_byte; \
  170277. size_t bytes_in_buffer = datasrc->bytes_in_buffer
  170278. /* Unload the local copies --- do this only at a restart boundary */
  170279. #define INPUT_SYNC(cinfo) \
  170280. ( datasrc->next_input_byte = next_input_byte, \
  170281. datasrc->bytes_in_buffer = bytes_in_buffer )
  170282. /* Reload the local copies --- used only in MAKE_BYTE_AVAIL */
  170283. #define INPUT_RELOAD(cinfo) \
  170284. ( next_input_byte = datasrc->next_input_byte, \
  170285. bytes_in_buffer = datasrc->bytes_in_buffer )
  170286. /* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
  170287. * Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
  170288. * but we must reload the local copies after a successful fill.
  170289. */
  170290. #define MAKE_BYTE_AVAIL(cinfo,action) \
  170291. if (bytes_in_buffer == 0) { \
  170292. if (! (*datasrc->fill_input_buffer) (cinfo)) \
  170293. { action; } \
  170294. INPUT_RELOAD(cinfo); \
  170295. }
  170296. /* Read a byte into variable V.
  170297. * If must suspend, take the specified action (typically "return FALSE").
  170298. */
  170299. #define INPUT_BYTE(cinfo,V,action) \
  170300. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  170301. bytes_in_buffer--; \
  170302. V = GETJOCTET(*next_input_byte++); )
  170303. /* As above, but read two bytes interpreted as an unsigned 16-bit integer.
  170304. * V should be declared unsigned int or perhaps INT32.
  170305. */
  170306. #define INPUT_2BYTES(cinfo,V,action) \
  170307. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  170308. bytes_in_buffer--; \
  170309. V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \
  170310. MAKE_BYTE_AVAIL(cinfo,action); \
  170311. bytes_in_buffer--; \
  170312. V += GETJOCTET(*next_input_byte++); )
  170313. /*
  170314. * Routines to process JPEG markers.
  170315. *
  170316. * Entry condition: JPEG marker itself has been read and its code saved
  170317. * in cinfo->unread_marker; input restart point is just after the marker.
  170318. *
  170319. * Exit: if return TRUE, have read and processed any parameters, and have
  170320. * updated the restart point to point after the parameters.
  170321. * If return FALSE, was forced to suspend before reaching end of
  170322. * marker parameters; restart point has not been moved. Same routine
  170323. * will be called again after application supplies more input data.
  170324. *
  170325. * This approach to suspension assumes that all of a marker's parameters
  170326. * can fit into a single input bufferload. This should hold for "normal"
  170327. * markers. Some COM/APPn markers might have large parameter segments
  170328. * that might not fit. If we are simply dropping such a marker, we use
  170329. * skip_input_data to get past it, and thereby put the problem on the
  170330. * source manager's shoulders. If we are saving the marker's contents
  170331. * into memory, we use a slightly different convention: when forced to
  170332. * suspend, the marker processor updates the restart point to the end of
  170333. * what it's consumed (ie, the end of the buffer) before returning FALSE.
  170334. * On resumption, cinfo->unread_marker still contains the marker code,
  170335. * but the data source will point to the next chunk of marker data.
  170336. * The marker processor must retain internal state to deal with this.
  170337. *
  170338. * Note that we don't bother to avoid duplicate trace messages if a
  170339. * suspension occurs within marker parameters. Other side effects
  170340. * require more care.
  170341. */
  170342. LOCAL(boolean)
  170343. get_soi (j_decompress_ptr cinfo)
  170344. /* Process an SOI marker */
  170345. {
  170346. int i;
  170347. TRACEMS(cinfo, 1, JTRC_SOI);
  170348. if (cinfo->marker->saw_SOI)
  170349. ERREXIT(cinfo, JERR_SOI_DUPLICATE);
  170350. /* Reset all parameters that are defined to be reset by SOI */
  170351. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  170352. cinfo->arith_dc_L[i] = 0;
  170353. cinfo->arith_dc_U[i] = 1;
  170354. cinfo->arith_ac_K[i] = 5;
  170355. }
  170356. cinfo->restart_interval = 0;
  170357. /* Set initial assumptions for colorspace etc */
  170358. cinfo->jpeg_color_space = JCS_UNKNOWN;
  170359. cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */
  170360. cinfo->saw_JFIF_marker = FALSE;
  170361. cinfo->JFIF_major_version = 1; /* set default JFIF APP0 values */
  170362. cinfo->JFIF_minor_version = 1;
  170363. cinfo->density_unit = 0;
  170364. cinfo->X_density = 1;
  170365. cinfo->Y_density = 1;
  170366. cinfo->saw_Adobe_marker = FALSE;
  170367. cinfo->Adobe_transform = 0;
  170368. cinfo->marker->saw_SOI = TRUE;
  170369. return TRUE;
  170370. }
  170371. LOCAL(boolean)
  170372. get_sof (j_decompress_ptr cinfo, boolean is_prog, boolean is_arith)
  170373. /* Process a SOFn marker */
  170374. {
  170375. INT32 length;
  170376. int c, ci;
  170377. jpeg_component_info * compptr;
  170378. INPUT_VARS(cinfo);
  170379. cinfo->progressive_mode = is_prog;
  170380. cinfo->arith_code = is_arith;
  170381. INPUT_2BYTES(cinfo, length, return FALSE);
  170382. INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE);
  170383. INPUT_2BYTES(cinfo, cinfo->image_height, return FALSE);
  170384. INPUT_2BYTES(cinfo, cinfo->image_width, return FALSE);
  170385. INPUT_BYTE(cinfo, cinfo->num_components, return FALSE);
  170386. length -= 8;
  170387. TRACEMS4(cinfo, 1, JTRC_SOF, cinfo->unread_marker,
  170388. (int) cinfo->image_width, (int) cinfo->image_height,
  170389. cinfo->num_components);
  170390. if (cinfo->marker->saw_SOF)
  170391. ERREXIT(cinfo, JERR_SOF_DUPLICATE);
  170392. /* We don't support files in which the image height is initially specified */
  170393. /* as 0 and is later redefined by DNL. As long as we have to check that, */
  170394. /* might as well have a general sanity check. */
  170395. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  170396. || cinfo->num_components <= 0)
  170397. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  170398. if (length != (cinfo->num_components * 3))
  170399. ERREXIT(cinfo, JERR_BAD_LENGTH);
  170400. if (cinfo->comp_info == NULL) /* do only once, even if suspend */
  170401. cinfo->comp_info = (jpeg_component_info *) (*cinfo->mem->alloc_small)
  170402. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170403. cinfo->num_components * SIZEOF(jpeg_component_info));
  170404. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170405. ci++, compptr++) {
  170406. compptr->component_index = ci;
  170407. INPUT_BYTE(cinfo, compptr->component_id, return FALSE);
  170408. INPUT_BYTE(cinfo, c, return FALSE);
  170409. compptr->h_samp_factor = (c >> 4) & 15;
  170410. compptr->v_samp_factor = (c ) & 15;
  170411. INPUT_BYTE(cinfo, compptr->quant_tbl_no, return FALSE);
  170412. TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT,
  170413. compptr->component_id, compptr->h_samp_factor,
  170414. compptr->v_samp_factor, compptr->quant_tbl_no);
  170415. }
  170416. cinfo->marker->saw_SOF = TRUE;
  170417. INPUT_SYNC(cinfo);
  170418. return TRUE;
  170419. }
  170420. LOCAL(boolean)
  170421. get_sos (j_decompress_ptr cinfo)
  170422. /* Process a SOS marker */
  170423. {
  170424. INT32 length;
  170425. int i, ci, n, c, cc;
  170426. jpeg_component_info * compptr;
  170427. INPUT_VARS(cinfo);
  170428. if (! cinfo->marker->saw_SOF)
  170429. ERREXIT(cinfo, JERR_SOS_NO_SOF);
  170430. INPUT_2BYTES(cinfo, length, return FALSE);
  170431. INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */
  170432. TRACEMS1(cinfo, 1, JTRC_SOS, n);
  170433. if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
  170434. ERREXIT(cinfo, JERR_BAD_LENGTH);
  170435. cinfo->comps_in_scan = n;
  170436. /* Collect the component-spec parameters */
  170437. for (i = 0; i < n; i++) {
  170438. INPUT_BYTE(cinfo, cc, return FALSE);
  170439. INPUT_BYTE(cinfo, c, return FALSE);
  170440. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170441. ci++, compptr++) {
  170442. if (cc == compptr->component_id)
  170443. goto id_found;
  170444. }
  170445. ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
  170446. id_found:
  170447. cinfo->cur_comp_info[i] = compptr;
  170448. compptr->dc_tbl_no = (c >> 4) & 15;
  170449. compptr->ac_tbl_no = (c ) & 15;
  170450. TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc,
  170451. compptr->dc_tbl_no, compptr->ac_tbl_no);
  170452. }
  170453. /* Collect the additional scan parameters Ss, Se, Ah/Al. */
  170454. INPUT_BYTE(cinfo, c, return FALSE);
  170455. cinfo->Ss = c;
  170456. INPUT_BYTE(cinfo, c, return FALSE);
  170457. cinfo->Se = c;
  170458. INPUT_BYTE(cinfo, c, return FALSE);
  170459. cinfo->Ah = (c >> 4) & 15;
  170460. cinfo->Al = (c ) & 15;
  170461. TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se,
  170462. cinfo->Ah, cinfo->Al);
  170463. /* Prepare to scan data & restart markers */
  170464. cinfo->marker->next_restart_num = 0;
  170465. /* Count another SOS marker */
  170466. cinfo->input_scan_number++;
  170467. INPUT_SYNC(cinfo);
  170468. return TRUE;
  170469. }
  170470. #ifdef D_ARITH_CODING_SUPPORTED
  170471. LOCAL(boolean)
  170472. get_dac (j_decompress_ptr cinfo)
  170473. /* Process a DAC marker */
  170474. {
  170475. INT32 length;
  170476. int index, val;
  170477. INPUT_VARS(cinfo);
  170478. INPUT_2BYTES(cinfo, length, return FALSE);
  170479. length -= 2;
  170480. while (length > 0) {
  170481. INPUT_BYTE(cinfo, index, return FALSE);
  170482. INPUT_BYTE(cinfo, val, return FALSE);
  170483. length -= 2;
  170484. TRACEMS2(cinfo, 1, JTRC_DAC, index, val);
  170485. if (index < 0 || index >= (2*NUM_ARITH_TBLS))
  170486. ERREXIT1(cinfo, JERR_DAC_INDEX, index);
  170487. if (index >= NUM_ARITH_TBLS) { /* define AC table */
  170488. cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = (UINT8) val;
  170489. } else { /* define DC table */
  170490. cinfo->arith_dc_L[index] = (UINT8) (val & 0x0F);
  170491. cinfo->arith_dc_U[index] = (UINT8) (val >> 4);
  170492. if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index])
  170493. ERREXIT1(cinfo, JERR_DAC_VALUE, val);
  170494. }
  170495. }
  170496. if (length != 0)
  170497. ERREXIT(cinfo, JERR_BAD_LENGTH);
  170498. INPUT_SYNC(cinfo);
  170499. return TRUE;
  170500. }
  170501. #else /* ! D_ARITH_CODING_SUPPORTED */
  170502. #define get_dac(cinfo) skip_variable(cinfo)
  170503. #endif /* D_ARITH_CODING_SUPPORTED */
  170504. LOCAL(boolean)
  170505. get_dht (j_decompress_ptr cinfo)
  170506. /* Process a DHT marker */
  170507. {
  170508. INT32 length;
  170509. UINT8 bits[17];
  170510. UINT8 huffval[256];
  170511. int i, index, count;
  170512. JHUFF_TBL **htblptr;
  170513. INPUT_VARS(cinfo);
  170514. INPUT_2BYTES(cinfo, length, return FALSE);
  170515. length -= 2;
  170516. while (length > 16) {
  170517. INPUT_BYTE(cinfo, index, return FALSE);
  170518. TRACEMS1(cinfo, 1, JTRC_DHT, index);
  170519. bits[0] = 0;
  170520. count = 0;
  170521. for (i = 1; i <= 16; i++) {
  170522. INPUT_BYTE(cinfo, bits[i], return FALSE);
  170523. count += bits[i];
  170524. }
  170525. length -= 1 + 16;
  170526. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  170527. bits[1], bits[2], bits[3], bits[4],
  170528. bits[5], bits[6], bits[7], bits[8]);
  170529. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  170530. bits[9], bits[10], bits[11], bits[12],
  170531. bits[13], bits[14], bits[15], bits[16]);
  170532. /* Here we just do minimal validation of the counts to avoid walking
  170533. * off the end of our table space. jdhuff.c will check more carefully.
  170534. */
  170535. if (count > 256 || ((INT32) count) > length)
  170536. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  170537. for (i = 0; i < count; i++)
  170538. INPUT_BYTE(cinfo, huffval[i], return FALSE);
  170539. length -= count;
  170540. if (index & 0x10) { /* AC table definition */
  170541. index -= 0x10;
  170542. htblptr = &cinfo->ac_huff_tbl_ptrs[index];
  170543. } else { /* DC table definition */
  170544. htblptr = &cinfo->dc_huff_tbl_ptrs[index];
  170545. }
  170546. if (index < 0 || index >= NUM_HUFF_TBLS)
  170547. ERREXIT1(cinfo, JERR_DHT_INDEX, index);
  170548. if (*htblptr == NULL)
  170549. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  170550. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  170551. MEMCOPY((*htblptr)->huffval, huffval, SIZEOF((*htblptr)->huffval));
  170552. }
  170553. if (length != 0)
  170554. ERREXIT(cinfo, JERR_BAD_LENGTH);
  170555. INPUT_SYNC(cinfo);
  170556. return TRUE;
  170557. }
  170558. LOCAL(boolean)
  170559. get_dqt (j_decompress_ptr cinfo)
  170560. /* Process a DQT marker */
  170561. {
  170562. INT32 length;
  170563. int n, i, prec;
  170564. unsigned int tmp;
  170565. JQUANT_TBL *quant_ptr;
  170566. INPUT_VARS(cinfo);
  170567. INPUT_2BYTES(cinfo, length, return FALSE);
  170568. length -= 2;
  170569. while (length > 0) {
  170570. INPUT_BYTE(cinfo, n, return FALSE);
  170571. prec = n >> 4;
  170572. n &= 0x0F;
  170573. TRACEMS2(cinfo, 1, JTRC_DQT, n, prec);
  170574. if (n >= NUM_QUANT_TBLS)
  170575. ERREXIT1(cinfo, JERR_DQT_INDEX, n);
  170576. if (cinfo->quant_tbl_ptrs[n] == NULL)
  170577. cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  170578. quant_ptr = cinfo->quant_tbl_ptrs[n];
  170579. for (i = 0; i < DCTSIZE2; i++) {
  170580. if (prec)
  170581. INPUT_2BYTES(cinfo, tmp, return FALSE);
  170582. else
  170583. INPUT_BYTE(cinfo, tmp, return FALSE);
  170584. /* We convert the zigzag-order table to natural array order. */
  170585. quant_ptr->quantval[jpeg_natural_order[i]] = (UINT16) tmp;
  170586. }
  170587. if (cinfo->err->trace_level >= 2) {
  170588. for (i = 0; i < DCTSIZE2; i += 8) {
  170589. TRACEMS8(cinfo, 2, JTRC_QUANTVALS,
  170590. quant_ptr->quantval[i], quant_ptr->quantval[i+1],
  170591. quant_ptr->quantval[i+2], quant_ptr->quantval[i+3],
  170592. quant_ptr->quantval[i+4], quant_ptr->quantval[i+5],
  170593. quant_ptr->quantval[i+6], quant_ptr->quantval[i+7]);
  170594. }
  170595. }
  170596. length -= DCTSIZE2+1;
  170597. if (prec) length -= DCTSIZE2;
  170598. }
  170599. if (length != 0)
  170600. ERREXIT(cinfo, JERR_BAD_LENGTH);
  170601. INPUT_SYNC(cinfo);
  170602. return TRUE;
  170603. }
  170604. LOCAL(boolean)
  170605. get_dri (j_decompress_ptr cinfo)
  170606. /* Process a DRI marker */
  170607. {
  170608. INT32 length;
  170609. unsigned int tmp;
  170610. INPUT_VARS(cinfo);
  170611. INPUT_2BYTES(cinfo, length, return FALSE);
  170612. if (length != 4)
  170613. ERREXIT(cinfo, JERR_BAD_LENGTH);
  170614. INPUT_2BYTES(cinfo, tmp, return FALSE);
  170615. TRACEMS1(cinfo, 1, JTRC_DRI, tmp);
  170616. cinfo->restart_interval = tmp;
  170617. INPUT_SYNC(cinfo);
  170618. return TRUE;
  170619. }
  170620. /*
  170621. * Routines for processing APPn and COM markers.
  170622. * These are either saved in memory or discarded, per application request.
  170623. * APP0 and APP14 are specially checked to see if they are
  170624. * JFIF and Adobe markers, respectively.
  170625. */
  170626. #define APP0_DATA_LEN 14 /* Length of interesting data in APP0 */
  170627. #define APP14_DATA_LEN 12 /* Length of interesting data in APP14 */
  170628. #define APPN_DATA_LEN 14 /* Must be the largest of the above!! */
  170629. LOCAL(void)
  170630. examine_app0 (j_decompress_ptr cinfo, JOCTET FAR * data,
  170631. unsigned int datalen, INT32 remaining)
  170632. /* Examine first few bytes from an APP0.
  170633. * Take appropriate action if it is a JFIF marker.
  170634. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  170635. */
  170636. {
  170637. INT32 totallen = (INT32) datalen + remaining;
  170638. if (datalen >= APP0_DATA_LEN &&
  170639. GETJOCTET(data[0]) == 0x4A &&
  170640. GETJOCTET(data[1]) == 0x46 &&
  170641. GETJOCTET(data[2]) == 0x49 &&
  170642. GETJOCTET(data[3]) == 0x46 &&
  170643. GETJOCTET(data[4]) == 0) {
  170644. /* Found JFIF APP0 marker: save info */
  170645. cinfo->saw_JFIF_marker = TRUE;
  170646. cinfo->JFIF_major_version = GETJOCTET(data[5]);
  170647. cinfo->JFIF_minor_version = GETJOCTET(data[6]);
  170648. cinfo->density_unit = GETJOCTET(data[7]);
  170649. cinfo->X_density = (GETJOCTET(data[8]) << 8) + GETJOCTET(data[9]);
  170650. cinfo->Y_density = (GETJOCTET(data[10]) << 8) + GETJOCTET(data[11]);
  170651. /* Check version.
  170652. * Major version must be 1, anything else signals an incompatible change.
  170653. * (We used to treat this as an error, but now it's a nonfatal warning,
  170654. * because some bozo at Hijaak couldn't read the spec.)
  170655. * Minor version should be 0..2, but process anyway if newer.
  170656. */
  170657. if (cinfo->JFIF_major_version != 1)
  170658. WARNMS2(cinfo, JWRN_JFIF_MAJOR,
  170659. cinfo->JFIF_major_version, cinfo->JFIF_minor_version);
  170660. /* Generate trace messages */
  170661. TRACEMS5(cinfo, 1, JTRC_JFIF,
  170662. cinfo->JFIF_major_version, cinfo->JFIF_minor_version,
  170663. cinfo->X_density, cinfo->Y_density, cinfo->density_unit);
  170664. /* Validate thumbnail dimensions and issue appropriate messages */
  170665. if (GETJOCTET(data[12]) | GETJOCTET(data[13]))
  170666. TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL,
  170667. GETJOCTET(data[12]), GETJOCTET(data[13]));
  170668. totallen -= APP0_DATA_LEN;
  170669. if (totallen !=
  170670. ((INT32)GETJOCTET(data[12]) * (INT32)GETJOCTET(data[13]) * (INT32) 3))
  170671. TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) totallen);
  170672. } else if (datalen >= 6 &&
  170673. GETJOCTET(data[0]) == 0x4A &&
  170674. GETJOCTET(data[1]) == 0x46 &&
  170675. GETJOCTET(data[2]) == 0x58 &&
  170676. GETJOCTET(data[3]) == 0x58 &&
  170677. GETJOCTET(data[4]) == 0) {
  170678. /* Found JFIF "JFXX" extension APP0 marker */
  170679. /* The library doesn't actually do anything with these,
  170680. * but we try to produce a helpful trace message.
  170681. */
  170682. switch (GETJOCTET(data[5])) {
  170683. case 0x10:
  170684. TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, (int) totallen);
  170685. break;
  170686. case 0x11:
  170687. TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, (int) totallen);
  170688. break;
  170689. case 0x13:
  170690. TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, (int) totallen);
  170691. break;
  170692. default:
  170693. TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION,
  170694. GETJOCTET(data[5]), (int) totallen);
  170695. break;
  170696. }
  170697. } else {
  170698. /* Start of APP0 does not match "JFIF" or "JFXX", or too short */
  170699. TRACEMS1(cinfo, 1, JTRC_APP0, (int) totallen);
  170700. }
  170701. }
  170702. LOCAL(void)
  170703. examine_app14 (j_decompress_ptr cinfo, JOCTET FAR * data,
  170704. unsigned int datalen, INT32 remaining)
  170705. /* Examine first few bytes from an APP14.
  170706. * Take appropriate action if it is an Adobe marker.
  170707. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  170708. */
  170709. {
  170710. unsigned int version, flags0, flags1, transform;
  170711. if (datalen >= APP14_DATA_LEN &&
  170712. GETJOCTET(data[0]) == 0x41 &&
  170713. GETJOCTET(data[1]) == 0x64 &&
  170714. GETJOCTET(data[2]) == 0x6F &&
  170715. GETJOCTET(data[3]) == 0x62 &&
  170716. GETJOCTET(data[4]) == 0x65) {
  170717. /* Found Adobe APP14 marker */
  170718. version = (GETJOCTET(data[5]) << 8) + GETJOCTET(data[6]);
  170719. flags0 = (GETJOCTET(data[7]) << 8) + GETJOCTET(data[8]);
  170720. flags1 = (GETJOCTET(data[9]) << 8) + GETJOCTET(data[10]);
  170721. transform = GETJOCTET(data[11]);
  170722. TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform);
  170723. cinfo->saw_Adobe_marker = TRUE;
  170724. cinfo->Adobe_transform = (UINT8) transform;
  170725. } else {
  170726. /* Start of APP14 does not match "Adobe", or too short */
  170727. TRACEMS1(cinfo, 1, JTRC_APP14, (int) (datalen + remaining));
  170728. }
  170729. }
  170730. METHODDEF(boolean)
  170731. get_interesting_appn (j_decompress_ptr cinfo)
  170732. /* Process an APP0 or APP14 marker without saving it */
  170733. {
  170734. INT32 length;
  170735. JOCTET b[APPN_DATA_LEN];
  170736. unsigned int i, numtoread;
  170737. INPUT_VARS(cinfo);
  170738. INPUT_2BYTES(cinfo, length, return FALSE);
  170739. length -= 2;
  170740. /* get the interesting part of the marker data */
  170741. if (length >= APPN_DATA_LEN)
  170742. numtoread = APPN_DATA_LEN;
  170743. else if (length > 0)
  170744. numtoread = (unsigned int) length;
  170745. else
  170746. numtoread = 0;
  170747. for (i = 0; i < numtoread; i++)
  170748. INPUT_BYTE(cinfo, b[i], return FALSE);
  170749. length -= numtoread;
  170750. /* process it */
  170751. switch (cinfo->unread_marker) {
  170752. case M_APP0:
  170753. examine_app0(cinfo, (JOCTET FAR *) b, numtoread, length);
  170754. break;
  170755. case M_APP14:
  170756. examine_app14(cinfo, (JOCTET FAR *) b, numtoread, length);
  170757. break;
  170758. default:
  170759. /* can't get here unless jpeg_save_markers chooses wrong processor */
  170760. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  170761. break;
  170762. }
  170763. /* skip any remaining data -- could be lots */
  170764. INPUT_SYNC(cinfo);
  170765. if (length > 0)
  170766. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  170767. return TRUE;
  170768. }
  170769. #ifdef SAVE_MARKERS_SUPPORTED
  170770. METHODDEF(boolean)
  170771. save_marker (j_decompress_ptr cinfo)
  170772. /* Save an APPn or COM marker into the marker list */
  170773. {
  170774. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  170775. jpeg_saved_marker_ptr cur_marker = marker->cur_marker;
  170776. unsigned int bytes_read, data_length;
  170777. JOCTET FAR * data;
  170778. INT32 length = 0;
  170779. INPUT_VARS(cinfo);
  170780. if (cur_marker == NULL) {
  170781. /* begin reading a marker */
  170782. INPUT_2BYTES(cinfo, length, return FALSE);
  170783. length -= 2;
  170784. if (length >= 0) { /* watch out for bogus length word */
  170785. /* figure out how much we want to save */
  170786. unsigned int limit;
  170787. if (cinfo->unread_marker == (int) M_COM)
  170788. limit = marker->length_limit_COM;
  170789. else
  170790. limit = marker->length_limit_APPn[cinfo->unread_marker - (int) M_APP0];
  170791. if ((unsigned int) length < limit)
  170792. limit = (unsigned int) length;
  170793. /* allocate and initialize the marker item */
  170794. cur_marker = (jpeg_saved_marker_ptr)
  170795. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170796. SIZEOF(struct jpeg_marker_struct) + limit);
  170797. cur_marker->next = NULL;
  170798. cur_marker->marker = (UINT8) cinfo->unread_marker;
  170799. cur_marker->original_length = (unsigned int) length;
  170800. cur_marker->data_length = limit;
  170801. /* data area is just beyond the jpeg_marker_struct */
  170802. data = cur_marker->data = (JOCTET FAR *) (cur_marker + 1);
  170803. marker->cur_marker = cur_marker;
  170804. marker->bytes_read = 0;
  170805. bytes_read = 0;
  170806. data_length = limit;
  170807. } else {
  170808. /* deal with bogus length word */
  170809. bytes_read = data_length = 0;
  170810. data = NULL;
  170811. }
  170812. } else {
  170813. /* resume reading a marker */
  170814. bytes_read = marker->bytes_read;
  170815. data_length = cur_marker->data_length;
  170816. data = cur_marker->data + bytes_read;
  170817. }
  170818. while (bytes_read < data_length) {
  170819. INPUT_SYNC(cinfo); /* move the restart point to here */
  170820. marker->bytes_read = bytes_read;
  170821. /* If there's not at least one byte in buffer, suspend */
  170822. MAKE_BYTE_AVAIL(cinfo, return FALSE);
  170823. /* Copy bytes with reasonable rapidity */
  170824. while (bytes_read < data_length && bytes_in_buffer > 0) {
  170825. *data++ = *next_input_byte++;
  170826. bytes_in_buffer--;
  170827. bytes_read++;
  170828. }
  170829. }
  170830. /* Done reading what we want to read */
  170831. if (cur_marker != NULL) { /* will be NULL if bogus length word */
  170832. /* Add new marker to end of list */
  170833. if (cinfo->marker_list == NULL) {
  170834. cinfo->marker_list = cur_marker;
  170835. } else {
  170836. jpeg_saved_marker_ptr prev = cinfo->marker_list;
  170837. while (prev->next != NULL)
  170838. prev = prev->next;
  170839. prev->next = cur_marker;
  170840. }
  170841. /* Reset pointer & calc remaining data length */
  170842. data = cur_marker->data;
  170843. length = cur_marker->original_length - data_length;
  170844. }
  170845. /* Reset to initial state for next marker */
  170846. marker->cur_marker = NULL;
  170847. /* Process the marker if interesting; else just make a generic trace msg */
  170848. switch (cinfo->unread_marker) {
  170849. case M_APP0:
  170850. examine_app0(cinfo, data, data_length, length);
  170851. break;
  170852. case M_APP14:
  170853. examine_app14(cinfo, data, data_length, length);
  170854. break;
  170855. default:
  170856. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker,
  170857. (int) (data_length + length));
  170858. break;
  170859. }
  170860. /* skip any remaining data -- could be lots */
  170861. INPUT_SYNC(cinfo); /* do before skip_input_data */
  170862. if (length > 0)
  170863. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  170864. return TRUE;
  170865. }
  170866. #endif /* SAVE_MARKERS_SUPPORTED */
  170867. METHODDEF(boolean)
  170868. skip_variable (j_decompress_ptr cinfo)
  170869. /* Skip over an unknown or uninteresting variable-length marker */
  170870. {
  170871. INT32 length;
  170872. INPUT_VARS(cinfo);
  170873. INPUT_2BYTES(cinfo, length, return FALSE);
  170874. length -= 2;
  170875. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) length);
  170876. INPUT_SYNC(cinfo); /* do before skip_input_data */
  170877. if (length > 0)
  170878. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  170879. return TRUE;
  170880. }
  170881. /*
  170882. * Find the next JPEG marker, save it in cinfo->unread_marker.
  170883. * Returns FALSE if had to suspend before reaching a marker;
  170884. * in that case cinfo->unread_marker is unchanged.
  170885. *
  170886. * Note that the result might not be a valid marker code,
  170887. * but it will never be 0 or FF.
  170888. */
  170889. LOCAL(boolean)
  170890. next_marker (j_decompress_ptr cinfo)
  170891. {
  170892. int c;
  170893. INPUT_VARS(cinfo);
  170894. for (;;) {
  170895. INPUT_BYTE(cinfo, c, return FALSE);
  170896. /* Skip any non-FF bytes.
  170897. * This may look a bit inefficient, but it will not occur in a valid file.
  170898. * We sync after each discarded byte so that a suspending data source
  170899. * can discard the byte from its buffer.
  170900. */
  170901. while (c != 0xFF) {
  170902. cinfo->marker->discarded_bytes++;
  170903. INPUT_SYNC(cinfo);
  170904. INPUT_BYTE(cinfo, c, return FALSE);
  170905. }
  170906. /* This loop swallows any duplicate FF bytes. Extra FFs are legal as
  170907. * pad bytes, so don't count them in discarded_bytes. We assume there
  170908. * will not be so many consecutive FF bytes as to overflow a suspending
  170909. * data source's input buffer.
  170910. */
  170911. do {
  170912. INPUT_BYTE(cinfo, c, return FALSE);
  170913. } while (c == 0xFF);
  170914. if (c != 0)
  170915. break; /* found a valid marker, exit loop */
  170916. /* Reach here if we found a stuffed-zero data sequence (FF/00).
  170917. * Discard it and loop back to try again.
  170918. */
  170919. cinfo->marker->discarded_bytes += 2;
  170920. INPUT_SYNC(cinfo);
  170921. }
  170922. if (cinfo->marker->discarded_bytes != 0) {
  170923. WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c);
  170924. cinfo->marker->discarded_bytes = 0;
  170925. }
  170926. cinfo->unread_marker = c;
  170927. INPUT_SYNC(cinfo);
  170928. return TRUE;
  170929. }
  170930. LOCAL(boolean)
  170931. first_marker (j_decompress_ptr cinfo)
  170932. /* Like next_marker, but used to obtain the initial SOI marker. */
  170933. /* For this marker, we do not allow preceding garbage or fill; otherwise,
  170934. * we might well scan an entire input file before realizing it ain't JPEG.
  170935. * If an application wants to process non-JFIF files, it must seek to the
  170936. * SOI before calling the JPEG library.
  170937. */
  170938. {
  170939. int c, c2;
  170940. INPUT_VARS(cinfo);
  170941. INPUT_BYTE(cinfo, c, return FALSE);
  170942. INPUT_BYTE(cinfo, c2, return FALSE);
  170943. if (c != 0xFF || c2 != (int) M_SOI)
  170944. ERREXIT2(cinfo, JERR_NO_SOI, c, c2);
  170945. cinfo->unread_marker = c2;
  170946. INPUT_SYNC(cinfo);
  170947. return TRUE;
  170948. }
  170949. /*
  170950. * Read markers until SOS or EOI.
  170951. *
  170952. * Returns same codes as are defined for jpeg_consume_input:
  170953. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  170954. */
  170955. METHODDEF(int)
  170956. read_markers (j_decompress_ptr cinfo)
  170957. {
  170958. /* Outer loop repeats once for each marker. */
  170959. for (;;) {
  170960. /* Collect the marker proper, unless we already did. */
  170961. /* NB: first_marker() enforces the requirement that SOI appear first. */
  170962. if (cinfo->unread_marker == 0) {
  170963. if (! cinfo->marker->saw_SOI) {
  170964. if (! first_marker(cinfo))
  170965. return JPEG_SUSPENDED;
  170966. } else {
  170967. if (! next_marker(cinfo))
  170968. return JPEG_SUSPENDED;
  170969. }
  170970. }
  170971. /* At this point cinfo->unread_marker contains the marker code and the
  170972. * input point is just past the marker proper, but before any parameters.
  170973. * A suspension will cause us to return with this state still true.
  170974. */
  170975. switch (cinfo->unread_marker) {
  170976. case M_SOI:
  170977. if (! get_soi(cinfo))
  170978. return JPEG_SUSPENDED;
  170979. break;
  170980. case M_SOF0: /* Baseline */
  170981. case M_SOF1: /* Extended sequential, Huffman */
  170982. if (! get_sof(cinfo, FALSE, FALSE))
  170983. return JPEG_SUSPENDED;
  170984. break;
  170985. case M_SOF2: /* Progressive, Huffman */
  170986. if (! get_sof(cinfo, TRUE, FALSE))
  170987. return JPEG_SUSPENDED;
  170988. break;
  170989. case M_SOF9: /* Extended sequential, arithmetic */
  170990. if (! get_sof(cinfo, FALSE, TRUE))
  170991. return JPEG_SUSPENDED;
  170992. break;
  170993. case M_SOF10: /* Progressive, arithmetic */
  170994. if (! get_sof(cinfo, TRUE, TRUE))
  170995. return JPEG_SUSPENDED;
  170996. break;
  170997. /* Currently unsupported SOFn types */
  170998. case M_SOF3: /* Lossless, Huffman */
  170999. case M_SOF5: /* Differential sequential, Huffman */
  171000. case M_SOF6: /* Differential progressive, Huffman */
  171001. case M_SOF7: /* Differential lossless, Huffman */
  171002. case M_JPG: /* Reserved for JPEG extensions */
  171003. case M_SOF11: /* Lossless, arithmetic */
  171004. case M_SOF13: /* Differential sequential, arithmetic */
  171005. case M_SOF14: /* Differential progressive, arithmetic */
  171006. case M_SOF15: /* Differential lossless, arithmetic */
  171007. ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker);
  171008. break;
  171009. case M_SOS:
  171010. if (! get_sos(cinfo))
  171011. return JPEG_SUSPENDED;
  171012. cinfo->unread_marker = 0; /* processed the marker */
  171013. return JPEG_REACHED_SOS;
  171014. case M_EOI:
  171015. TRACEMS(cinfo, 1, JTRC_EOI);
  171016. cinfo->unread_marker = 0; /* processed the marker */
  171017. return JPEG_REACHED_EOI;
  171018. case M_DAC:
  171019. if (! get_dac(cinfo))
  171020. return JPEG_SUSPENDED;
  171021. break;
  171022. case M_DHT:
  171023. if (! get_dht(cinfo))
  171024. return JPEG_SUSPENDED;
  171025. break;
  171026. case M_DQT:
  171027. if (! get_dqt(cinfo))
  171028. return JPEG_SUSPENDED;
  171029. break;
  171030. case M_DRI:
  171031. if (! get_dri(cinfo))
  171032. return JPEG_SUSPENDED;
  171033. break;
  171034. case M_APP0:
  171035. case M_APP1:
  171036. case M_APP2:
  171037. case M_APP3:
  171038. case M_APP4:
  171039. case M_APP5:
  171040. case M_APP6:
  171041. case M_APP7:
  171042. case M_APP8:
  171043. case M_APP9:
  171044. case M_APP10:
  171045. case M_APP11:
  171046. case M_APP12:
  171047. case M_APP13:
  171048. case M_APP14:
  171049. case M_APP15:
  171050. if (! (*((my_marker_ptr2) cinfo->marker)->process_APPn[
  171051. cinfo->unread_marker - (int) M_APP0]) (cinfo))
  171052. return JPEG_SUSPENDED;
  171053. break;
  171054. case M_COM:
  171055. if (! (*((my_marker_ptr2) cinfo->marker)->process_COM) (cinfo))
  171056. return JPEG_SUSPENDED;
  171057. break;
  171058. case M_RST0: /* these are all parameterless */
  171059. case M_RST1:
  171060. case M_RST2:
  171061. case M_RST3:
  171062. case M_RST4:
  171063. case M_RST5:
  171064. case M_RST6:
  171065. case M_RST7:
  171066. case M_TEM:
  171067. TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker);
  171068. break;
  171069. case M_DNL: /* Ignore DNL ... perhaps the wrong thing */
  171070. if (! skip_variable(cinfo))
  171071. return JPEG_SUSPENDED;
  171072. break;
  171073. default: /* must be DHP, EXP, JPGn, or RESn */
  171074. /* For now, we treat the reserved markers as fatal errors since they are
  171075. * likely to be used to signal incompatible JPEG Part 3 extensions.
  171076. * Once the JPEG 3 version-number marker is well defined, this code
  171077. * ought to change!
  171078. */
  171079. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  171080. break;
  171081. }
  171082. /* Successfully processed marker, so reset state variable */
  171083. cinfo->unread_marker = 0;
  171084. } /* end loop */
  171085. }
  171086. /*
  171087. * Read a restart marker, which is expected to appear next in the datastream;
  171088. * if the marker is not there, take appropriate recovery action.
  171089. * Returns FALSE if suspension is required.
  171090. *
  171091. * This is called by the entropy decoder after it has read an appropriate
  171092. * number of MCUs. cinfo->unread_marker may be nonzero if the entropy decoder
  171093. * has already read a marker from the data source. Under normal conditions
  171094. * cinfo->unread_marker will be reset to 0 before returning; if not reset,
  171095. * it holds a marker which the decoder will be unable to read past.
  171096. */
  171097. METHODDEF(boolean)
  171098. read_restart_marker (j_decompress_ptr cinfo)
  171099. {
  171100. /* Obtain a marker unless we already did. */
  171101. /* Note that next_marker will complain if it skips any data. */
  171102. if (cinfo->unread_marker == 0) {
  171103. if (! next_marker(cinfo))
  171104. return FALSE;
  171105. }
  171106. if (cinfo->unread_marker ==
  171107. ((int) M_RST0 + cinfo->marker->next_restart_num)) {
  171108. /* Normal case --- swallow the marker and let entropy decoder continue */
  171109. TRACEMS1(cinfo, 3, JTRC_RST, cinfo->marker->next_restart_num);
  171110. cinfo->unread_marker = 0;
  171111. } else {
  171112. /* Uh-oh, the restart markers have been messed up. */
  171113. /* Let the data source manager determine how to resync. */
  171114. if (! (*cinfo->src->resync_to_restart) (cinfo,
  171115. cinfo->marker->next_restart_num))
  171116. return FALSE;
  171117. }
  171118. /* Update next-restart state */
  171119. cinfo->marker->next_restart_num = (cinfo->marker->next_restart_num + 1) & 7;
  171120. return TRUE;
  171121. }
  171122. /*
  171123. * This is the default resync_to_restart method for data source managers
  171124. * to use if they don't have any better approach. Some data source managers
  171125. * may be able to back up, or may have additional knowledge about the data
  171126. * which permits a more intelligent recovery strategy; such managers would
  171127. * presumably supply their own resync method.
  171128. *
  171129. * read_restart_marker calls resync_to_restart if it finds a marker other than
  171130. * the restart marker it was expecting. (This code is *not* used unless
  171131. * a nonzero restart interval has been declared.) cinfo->unread_marker is
  171132. * the marker code actually found (might be anything, except 0 or FF).
  171133. * The desired restart marker number (0..7) is passed as a parameter.
  171134. * This routine is supposed to apply whatever error recovery strategy seems
  171135. * appropriate in order to position the input stream to the next data segment.
  171136. * Note that cinfo->unread_marker is treated as a marker appearing before
  171137. * the current data-source input point; usually it should be reset to zero
  171138. * before returning.
  171139. * Returns FALSE if suspension is required.
  171140. *
  171141. * This implementation is substantially constrained by wanting to treat the
  171142. * input as a data stream; this means we can't back up. Therefore, we have
  171143. * only the following actions to work with:
  171144. * 1. Simply discard the marker and let the entropy decoder resume at next
  171145. * byte of file.
  171146. * 2. Read forward until we find another marker, discarding intervening
  171147. * data. (In theory we could look ahead within the current bufferload,
  171148. * without having to discard data if we don't find the desired marker.
  171149. * This idea is not implemented here, in part because it makes behavior
  171150. * dependent on buffer size and chance buffer-boundary positions.)
  171151. * 3. Leave the marker unread (by failing to zero cinfo->unread_marker).
  171152. * This will cause the entropy decoder to process an empty data segment,
  171153. * inserting dummy zeroes, and then we will reprocess the marker.
  171154. *
  171155. * #2 is appropriate if we think the desired marker lies ahead, while #3 is
  171156. * appropriate if the found marker is a future restart marker (indicating
  171157. * that we have missed the desired restart marker, probably because it got
  171158. * corrupted).
  171159. * We apply #2 or #3 if the found marker is a restart marker no more than
  171160. * two counts behind or ahead of the expected one. We also apply #2 if the
  171161. * found marker is not a legal JPEG marker code (it's certainly bogus data).
  171162. * If the found marker is a restart marker more than 2 counts away, we do #1
  171163. * (too much risk that the marker is erroneous; with luck we will be able to
  171164. * resync at some future point).
  171165. * For any valid non-restart JPEG marker, we apply #3. This keeps us from
  171166. * overrunning the end of a scan. An implementation limited to single-scan
  171167. * files might find it better to apply #2 for markers other than EOI, since
  171168. * any other marker would have to be bogus data in that case.
  171169. */
  171170. GLOBAL(boolean)
  171171. jpeg_resync_to_restart (j_decompress_ptr cinfo, int desired)
  171172. {
  171173. int marker = cinfo->unread_marker;
  171174. int action = 1;
  171175. /* Always put up a warning. */
  171176. WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired);
  171177. /* Outer loop handles repeated decision after scanning forward. */
  171178. for (;;) {
  171179. if (marker < (int) M_SOF0)
  171180. action = 2; /* invalid marker */
  171181. else if (marker < (int) M_RST0 || marker > (int) M_RST7)
  171182. action = 3; /* valid non-restart marker */
  171183. else {
  171184. if (marker == ((int) M_RST0 + ((desired+1) & 7)) ||
  171185. marker == ((int) M_RST0 + ((desired+2) & 7)))
  171186. action = 3; /* one of the next two expected restarts */
  171187. else if (marker == ((int) M_RST0 + ((desired-1) & 7)) ||
  171188. marker == ((int) M_RST0 + ((desired-2) & 7)))
  171189. action = 2; /* a prior restart, so advance */
  171190. else
  171191. action = 1; /* desired restart or too far away */
  171192. }
  171193. TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action);
  171194. switch (action) {
  171195. case 1:
  171196. /* Discard marker and let entropy decoder resume processing. */
  171197. cinfo->unread_marker = 0;
  171198. return TRUE;
  171199. case 2:
  171200. /* Scan to the next marker, and repeat the decision loop. */
  171201. if (! next_marker(cinfo))
  171202. return FALSE;
  171203. marker = cinfo->unread_marker;
  171204. break;
  171205. case 3:
  171206. /* Return without advancing past this marker. */
  171207. /* Entropy decoder will be forced to process an empty segment. */
  171208. return TRUE;
  171209. }
  171210. } /* end loop */
  171211. }
  171212. /*
  171213. * Reset marker processing state to begin a fresh datastream.
  171214. */
  171215. METHODDEF(void)
  171216. reset_marker_reader (j_decompress_ptr cinfo)
  171217. {
  171218. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171219. cinfo->comp_info = NULL; /* until allocated by get_sof */
  171220. cinfo->input_scan_number = 0; /* no SOS seen yet */
  171221. cinfo->unread_marker = 0; /* no pending marker */
  171222. marker->pub.saw_SOI = FALSE; /* set internal state too */
  171223. marker->pub.saw_SOF = FALSE;
  171224. marker->pub.discarded_bytes = 0;
  171225. marker->cur_marker = NULL;
  171226. }
  171227. /*
  171228. * Initialize the marker reader module.
  171229. * This is called only once, when the decompression object is created.
  171230. */
  171231. GLOBAL(void)
  171232. jinit_marker_reader (j_decompress_ptr cinfo)
  171233. {
  171234. my_marker_ptr2 marker;
  171235. int i;
  171236. /* Create subobject in permanent pool */
  171237. marker = (my_marker_ptr2)
  171238. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  171239. SIZEOF(my_marker_reader));
  171240. cinfo->marker = (struct jpeg_marker_reader *) marker;
  171241. /* Initialize public method pointers */
  171242. marker->pub.reset_marker_reader = reset_marker_reader;
  171243. marker->pub.read_markers = read_markers;
  171244. marker->pub.read_restart_marker = read_restart_marker;
  171245. /* Initialize COM/APPn processing.
  171246. * By default, we examine and then discard APP0 and APP14,
  171247. * but simply discard COM and all other APPn.
  171248. */
  171249. marker->process_COM = skip_variable;
  171250. marker->length_limit_COM = 0;
  171251. for (i = 0; i < 16; i++) {
  171252. marker->process_APPn[i] = skip_variable;
  171253. marker->length_limit_APPn[i] = 0;
  171254. }
  171255. marker->process_APPn[0] = get_interesting_appn;
  171256. marker->process_APPn[14] = get_interesting_appn;
  171257. /* Reset marker processing state */
  171258. reset_marker_reader(cinfo);
  171259. }
  171260. /*
  171261. * Control saving of COM and APPn markers into marker_list.
  171262. */
  171263. #ifdef SAVE_MARKERS_SUPPORTED
  171264. GLOBAL(void)
  171265. jpeg_save_markers (j_decompress_ptr cinfo, int marker_code,
  171266. unsigned int length_limit)
  171267. {
  171268. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171269. long maxlength;
  171270. jpeg_marker_parser_method processor;
  171271. /* Length limit mustn't be larger than what we can allocate
  171272. * (should only be a concern in a 16-bit environment).
  171273. */
  171274. maxlength = cinfo->mem->max_alloc_chunk - SIZEOF(struct jpeg_marker_struct);
  171275. if (((long) length_limit) > maxlength)
  171276. length_limit = (unsigned int) maxlength;
  171277. /* Choose processor routine to use.
  171278. * APP0/APP14 have special requirements.
  171279. */
  171280. if (length_limit) {
  171281. processor = save_marker;
  171282. /* If saving APP0/APP14, save at least enough for our internal use. */
  171283. if (marker_code == (int) M_APP0 && length_limit < APP0_DATA_LEN)
  171284. length_limit = APP0_DATA_LEN;
  171285. else if (marker_code == (int) M_APP14 && length_limit < APP14_DATA_LEN)
  171286. length_limit = APP14_DATA_LEN;
  171287. } else {
  171288. processor = skip_variable;
  171289. /* If discarding APP0/APP14, use our regular on-the-fly processor. */
  171290. if (marker_code == (int) M_APP0 || marker_code == (int) M_APP14)
  171291. processor = get_interesting_appn;
  171292. }
  171293. if (marker_code == (int) M_COM) {
  171294. marker->process_COM = processor;
  171295. marker->length_limit_COM = length_limit;
  171296. } else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15) {
  171297. marker->process_APPn[marker_code - (int) M_APP0] = processor;
  171298. marker->length_limit_APPn[marker_code - (int) M_APP0] = length_limit;
  171299. } else
  171300. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  171301. }
  171302. #endif /* SAVE_MARKERS_SUPPORTED */
  171303. /*
  171304. * Install a special processing method for COM or APPn markers.
  171305. */
  171306. GLOBAL(void)
  171307. jpeg_set_marker_processor (j_decompress_ptr cinfo, int marker_code,
  171308. jpeg_marker_parser_method routine)
  171309. {
  171310. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171311. if (marker_code == (int) M_COM)
  171312. marker->process_COM = routine;
  171313. else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15)
  171314. marker->process_APPn[marker_code - (int) M_APP0] = routine;
  171315. else
  171316. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  171317. }
  171318. /*** End of inlined file: jdmarker.c ***/
  171319. /*** Start of inlined file: jdmaster.c ***/
  171320. #define JPEG_INTERNALS
  171321. /* Private state */
  171322. typedef struct {
  171323. struct jpeg_decomp_master pub; /* public fields */
  171324. int pass_number; /* # of passes completed */
  171325. boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */
  171326. /* Saved references to initialized quantizer modules,
  171327. * in case we need to switch modes.
  171328. */
  171329. struct jpeg_color_quantizer * quantizer_1pass;
  171330. struct jpeg_color_quantizer * quantizer_2pass;
  171331. } my_decomp_master;
  171332. typedef my_decomp_master * my_master_ptr6;
  171333. /*
  171334. * Determine whether merged upsample/color conversion should be used.
  171335. * CRUCIAL: this must match the actual capabilities of jdmerge.c!
  171336. */
  171337. LOCAL(boolean)
  171338. use_merged_upsample (j_decompress_ptr cinfo)
  171339. {
  171340. #ifdef UPSAMPLE_MERGING_SUPPORTED
  171341. /* Merging is the equivalent of plain box-filter upsampling */
  171342. if (cinfo->do_fancy_upsampling || cinfo->CCIR601_sampling)
  171343. return FALSE;
  171344. /* jdmerge.c only supports YCC=>RGB color conversion */
  171345. if (cinfo->jpeg_color_space != JCS_YCbCr || cinfo->num_components != 3 ||
  171346. cinfo->out_color_space != JCS_RGB ||
  171347. cinfo->out_color_components != RGB_PIXELSIZE)
  171348. return FALSE;
  171349. /* and it only handles 2h1v or 2h2v sampling ratios */
  171350. if (cinfo->comp_info[0].h_samp_factor != 2 ||
  171351. cinfo->comp_info[1].h_samp_factor != 1 ||
  171352. cinfo->comp_info[2].h_samp_factor != 1 ||
  171353. cinfo->comp_info[0].v_samp_factor > 2 ||
  171354. cinfo->comp_info[1].v_samp_factor != 1 ||
  171355. cinfo->comp_info[2].v_samp_factor != 1)
  171356. return FALSE;
  171357. /* furthermore, it doesn't work if we've scaled the IDCTs differently */
  171358. if (cinfo->comp_info[0].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  171359. cinfo->comp_info[1].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  171360. cinfo->comp_info[2].DCT_scaled_size != cinfo->min_DCT_scaled_size)
  171361. return FALSE;
  171362. /* ??? also need to test for upsample-time rescaling, when & if supported */
  171363. return TRUE; /* by golly, it'll work... */
  171364. #else
  171365. return FALSE;
  171366. #endif
  171367. }
  171368. /*
  171369. * Compute output image dimensions and related values.
  171370. * NOTE: this is exported for possible use by application.
  171371. * Hence it mustn't do anything that can't be done twice.
  171372. * Also note that it may be called before the master module is initialized!
  171373. */
  171374. GLOBAL(void)
  171375. jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
  171376. /* Do computations that are needed before master selection phase */
  171377. {
  171378. #ifdef IDCT_SCALING_SUPPORTED
  171379. int ci;
  171380. jpeg_component_info *compptr;
  171381. #endif
  171382. /* Prevent application from calling me at wrong times */
  171383. if (cinfo->global_state != DSTATE_READY)
  171384. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  171385. #ifdef IDCT_SCALING_SUPPORTED
  171386. /* Compute actual output image dimensions and DCT scaling choices. */
  171387. if (cinfo->scale_num * 8 <= cinfo->scale_denom) {
  171388. /* Provide 1/8 scaling */
  171389. cinfo->output_width = (JDIMENSION)
  171390. jdiv_round_up((long) cinfo->image_width, 8L);
  171391. cinfo->output_height = (JDIMENSION)
  171392. jdiv_round_up((long) cinfo->image_height, 8L);
  171393. cinfo->min_DCT_scaled_size = 1;
  171394. } else if (cinfo->scale_num * 4 <= cinfo->scale_denom) {
  171395. /* Provide 1/4 scaling */
  171396. cinfo->output_width = (JDIMENSION)
  171397. jdiv_round_up((long) cinfo->image_width, 4L);
  171398. cinfo->output_height = (JDIMENSION)
  171399. jdiv_round_up((long) cinfo->image_height, 4L);
  171400. cinfo->min_DCT_scaled_size = 2;
  171401. } else if (cinfo->scale_num * 2 <= cinfo->scale_denom) {
  171402. /* Provide 1/2 scaling */
  171403. cinfo->output_width = (JDIMENSION)
  171404. jdiv_round_up((long) cinfo->image_width, 2L);
  171405. cinfo->output_height = (JDIMENSION)
  171406. jdiv_round_up((long) cinfo->image_height, 2L);
  171407. cinfo->min_DCT_scaled_size = 4;
  171408. } else {
  171409. /* Provide 1/1 scaling */
  171410. cinfo->output_width = cinfo->image_width;
  171411. cinfo->output_height = cinfo->image_height;
  171412. cinfo->min_DCT_scaled_size = DCTSIZE;
  171413. }
  171414. /* In selecting the actual DCT scaling for each component, we try to
  171415. * scale up the chroma components via IDCT scaling rather than upsampling.
  171416. * This saves time if the upsampler gets to use 1:1 scaling.
  171417. * Note this code assumes that the supported DCT scalings are powers of 2.
  171418. */
  171419. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171420. ci++, compptr++) {
  171421. int ssize = cinfo->min_DCT_scaled_size;
  171422. while (ssize < DCTSIZE &&
  171423. (compptr->h_samp_factor * ssize * 2 <=
  171424. cinfo->max_h_samp_factor * cinfo->min_DCT_scaled_size) &&
  171425. (compptr->v_samp_factor * ssize * 2 <=
  171426. cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size)) {
  171427. ssize = ssize * 2;
  171428. }
  171429. compptr->DCT_scaled_size = ssize;
  171430. }
  171431. /* Recompute downsampled dimensions of components;
  171432. * application needs to know these if using raw downsampled data.
  171433. */
  171434. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171435. ci++, compptr++) {
  171436. /* Size in samples, after IDCT scaling */
  171437. compptr->downsampled_width = (JDIMENSION)
  171438. jdiv_round_up((long) cinfo->image_width *
  171439. (long) (compptr->h_samp_factor * compptr->DCT_scaled_size),
  171440. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  171441. compptr->downsampled_height = (JDIMENSION)
  171442. jdiv_round_up((long) cinfo->image_height *
  171443. (long) (compptr->v_samp_factor * compptr->DCT_scaled_size),
  171444. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  171445. }
  171446. #else /* !IDCT_SCALING_SUPPORTED */
  171447. /* Hardwire it to "no scaling" */
  171448. cinfo->output_width = cinfo->image_width;
  171449. cinfo->output_height = cinfo->image_height;
  171450. /* jdinput.c has already initialized DCT_scaled_size to DCTSIZE,
  171451. * and has computed unscaled downsampled_width and downsampled_height.
  171452. */
  171453. #endif /* IDCT_SCALING_SUPPORTED */
  171454. /* Report number of components in selected colorspace. */
  171455. /* Probably this should be in the color conversion module... */
  171456. switch (cinfo->out_color_space) {
  171457. case JCS_GRAYSCALE:
  171458. cinfo->out_color_components = 1;
  171459. break;
  171460. case JCS_RGB:
  171461. #if RGB_PIXELSIZE != 3
  171462. cinfo->out_color_components = RGB_PIXELSIZE;
  171463. break;
  171464. #endif /* else share code with YCbCr */
  171465. case JCS_YCbCr:
  171466. cinfo->out_color_components = 3;
  171467. break;
  171468. case JCS_CMYK:
  171469. case JCS_YCCK:
  171470. cinfo->out_color_components = 4;
  171471. break;
  171472. default: /* else must be same colorspace as in file */
  171473. cinfo->out_color_components = cinfo->num_components;
  171474. break;
  171475. }
  171476. cinfo->output_components = (cinfo->quantize_colors ? 1 :
  171477. cinfo->out_color_components);
  171478. /* See if upsampler will want to emit more than one row at a time */
  171479. if (use_merged_upsample(cinfo))
  171480. cinfo->rec_outbuf_height = cinfo->max_v_samp_factor;
  171481. else
  171482. cinfo->rec_outbuf_height = 1;
  171483. }
  171484. /*
  171485. * Several decompression processes need to range-limit values to the range
  171486. * 0..MAXJSAMPLE; the input value may fall somewhat outside this range
  171487. * due to noise introduced by quantization, roundoff error, etc. These
  171488. * processes are inner loops and need to be as fast as possible. On most
  171489. * machines, particularly CPUs with pipelines or instruction prefetch,
  171490. * a (subscript-check-less) C table lookup
  171491. * x = sample_range_limit[x];
  171492. * is faster than explicit tests
  171493. * if (x < 0) x = 0;
  171494. * else if (x > MAXJSAMPLE) x = MAXJSAMPLE;
  171495. * These processes all use a common table prepared by the routine below.
  171496. *
  171497. * For most steps we can mathematically guarantee that the initial value
  171498. * of x is within MAXJSAMPLE+1 of the legal range, so a table running from
  171499. * -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient. But for the initial
  171500. * limiting step (just after the IDCT), a wildly out-of-range value is
  171501. * possible if the input data is corrupt. To avoid any chance of indexing
  171502. * off the end of memory and getting a bad-pointer trap, we perform the
  171503. * post-IDCT limiting thus:
  171504. * x = range_limit[x & MASK];
  171505. * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit
  171506. * samples. Under normal circumstances this is more than enough range and
  171507. * a correct output will be generated; with bogus input data the mask will
  171508. * cause wraparound, and we will safely generate a bogus-but-in-range output.
  171509. * For the post-IDCT step, we want to convert the data from signed to unsigned
  171510. * representation by adding CENTERJSAMPLE at the same time that we limit it.
  171511. * So the post-IDCT limiting table ends up looking like this:
  171512. * CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE,
  171513. * MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  171514. * 0 (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  171515. * 0,1,...,CENTERJSAMPLE-1
  171516. * Negative inputs select values from the upper half of the table after
  171517. * masking.
  171518. *
  171519. * We can save some space by overlapping the start of the post-IDCT table
  171520. * with the simpler range limiting table. The post-IDCT table begins at
  171521. * sample_range_limit + CENTERJSAMPLE.
  171522. *
  171523. * Note that the table is allocated in near data space on PCs; it's small
  171524. * enough and used often enough to justify this.
  171525. */
  171526. LOCAL(void)
  171527. prepare_range_limit_table (j_decompress_ptr cinfo)
  171528. /* Allocate and fill in the sample_range_limit table */
  171529. {
  171530. JSAMPLE * table;
  171531. int i;
  171532. table = (JSAMPLE *)
  171533. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171534. (5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  171535. table += (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
  171536. cinfo->sample_range_limit = table;
  171537. /* First segment of "simple" table: limit[x] = 0 for x < 0 */
  171538. MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
  171539. /* Main part of "simple" table: limit[x] = x */
  171540. for (i = 0; i <= MAXJSAMPLE; i++)
  171541. table[i] = (JSAMPLE) i;
  171542. table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
  171543. /* End of simple table, rest of first half of post-IDCT table */
  171544. for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
  171545. table[i] = MAXJSAMPLE;
  171546. /* Second half of post-IDCT table */
  171547. MEMZERO(table + (2 * (MAXJSAMPLE+1)),
  171548. (2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  171549. MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
  171550. cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF(JSAMPLE));
  171551. }
  171552. /*
  171553. * Master selection of decompression modules.
  171554. * This is done once at jpeg_start_decompress time. We determine
  171555. * which modules will be used and give them appropriate initialization calls.
  171556. * We also initialize the decompressor input side to begin consuming data.
  171557. *
  171558. * Since jpeg_read_header has finished, we know what is in the SOF
  171559. * and (first) SOS markers. We also have all the application parameter
  171560. * settings.
  171561. */
  171562. LOCAL(void)
  171563. master_selection (j_decompress_ptr cinfo)
  171564. {
  171565. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  171566. boolean use_c_buffer;
  171567. long samplesperrow;
  171568. JDIMENSION jd_samplesperrow;
  171569. /* Initialize dimensions and other stuff */
  171570. jpeg_calc_output_dimensions(cinfo);
  171571. prepare_range_limit_table(cinfo);
  171572. /* Width of an output scanline must be representable as JDIMENSION. */
  171573. samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components;
  171574. jd_samplesperrow = (JDIMENSION) samplesperrow;
  171575. if ((long) jd_samplesperrow != samplesperrow)
  171576. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  171577. /* Initialize my private state */
  171578. master->pass_number = 0;
  171579. master->using_merged_upsample = use_merged_upsample(cinfo);
  171580. /* Color quantizer selection */
  171581. master->quantizer_1pass = NULL;
  171582. master->quantizer_2pass = NULL;
  171583. /* No mode changes if not using buffered-image mode. */
  171584. if (! cinfo->quantize_colors || ! cinfo->buffered_image) {
  171585. cinfo->enable_1pass_quant = FALSE;
  171586. cinfo->enable_external_quant = FALSE;
  171587. cinfo->enable_2pass_quant = FALSE;
  171588. }
  171589. if (cinfo->quantize_colors) {
  171590. if (cinfo->raw_data_out)
  171591. ERREXIT(cinfo, JERR_NOTIMPL);
  171592. /* 2-pass quantizer only works in 3-component color space. */
  171593. if (cinfo->out_color_components != 3) {
  171594. cinfo->enable_1pass_quant = TRUE;
  171595. cinfo->enable_external_quant = FALSE;
  171596. cinfo->enable_2pass_quant = FALSE;
  171597. cinfo->colormap = NULL;
  171598. } else if (cinfo->colormap != NULL) {
  171599. cinfo->enable_external_quant = TRUE;
  171600. } else if (cinfo->two_pass_quantize) {
  171601. cinfo->enable_2pass_quant = TRUE;
  171602. } else {
  171603. cinfo->enable_1pass_quant = TRUE;
  171604. }
  171605. if (cinfo->enable_1pass_quant) {
  171606. #ifdef QUANT_1PASS_SUPPORTED
  171607. jinit_1pass_quantizer(cinfo);
  171608. master->quantizer_1pass = cinfo->cquantize;
  171609. #else
  171610. ERREXIT(cinfo, JERR_NOT_COMPILED);
  171611. #endif
  171612. }
  171613. /* We use the 2-pass code to map to external colormaps. */
  171614. if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) {
  171615. #ifdef QUANT_2PASS_SUPPORTED
  171616. jinit_2pass_quantizer(cinfo);
  171617. master->quantizer_2pass = cinfo->cquantize;
  171618. #else
  171619. ERREXIT(cinfo, JERR_NOT_COMPILED);
  171620. #endif
  171621. }
  171622. /* If both quantizers are initialized, the 2-pass one is left active;
  171623. * this is necessary for starting with quantization to an external map.
  171624. */
  171625. }
  171626. /* Post-processing: in particular, color conversion first */
  171627. if (! cinfo->raw_data_out) {
  171628. if (master->using_merged_upsample) {
  171629. #ifdef UPSAMPLE_MERGING_SUPPORTED
  171630. jinit_merged_upsampler(cinfo); /* does color conversion too */
  171631. #else
  171632. ERREXIT(cinfo, JERR_NOT_COMPILED);
  171633. #endif
  171634. } else {
  171635. jinit_color_deconverter(cinfo);
  171636. jinit_upsampler(cinfo);
  171637. }
  171638. jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant);
  171639. }
  171640. /* Inverse DCT */
  171641. jinit_inverse_dct(cinfo);
  171642. /* Entropy decoding: either Huffman or arithmetic coding. */
  171643. if (cinfo->arith_code) {
  171644. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  171645. } else {
  171646. if (cinfo->progressive_mode) {
  171647. #ifdef D_PROGRESSIVE_SUPPORTED
  171648. jinit_phuff_decoder(cinfo);
  171649. #else
  171650. ERREXIT(cinfo, JERR_NOT_COMPILED);
  171651. #endif
  171652. } else
  171653. jinit_huff_decoder(cinfo);
  171654. }
  171655. /* Initialize principal buffer controllers. */
  171656. use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
  171657. jinit_d_coef_controller(cinfo, use_c_buffer);
  171658. if (! cinfo->raw_data_out)
  171659. jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */);
  171660. /* We can now tell the memory manager to allocate virtual arrays. */
  171661. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  171662. /* Initialize input side of decompressor to consume first scan. */
  171663. (*cinfo->inputctl->start_input_pass) (cinfo);
  171664. #ifdef D_MULTISCAN_FILES_SUPPORTED
  171665. /* If jpeg_start_decompress will read the whole file, initialize
  171666. * progress monitoring appropriately. The input step is counted
  171667. * as one pass.
  171668. */
  171669. if (cinfo->progress != NULL && ! cinfo->buffered_image &&
  171670. cinfo->inputctl->has_multiple_scans) {
  171671. int nscans;
  171672. /* Estimate number of scans to set pass_limit. */
  171673. if (cinfo->progressive_mode) {
  171674. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  171675. nscans = 2 + 3 * cinfo->num_components;
  171676. } else {
  171677. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  171678. nscans = cinfo->num_components;
  171679. }
  171680. cinfo->progress->pass_counter = 0L;
  171681. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  171682. cinfo->progress->completed_passes = 0;
  171683. cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2);
  171684. /* Count the input pass as done */
  171685. master->pass_number++;
  171686. }
  171687. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  171688. }
  171689. /*
  171690. * Per-pass setup.
  171691. * This is called at the beginning of each output pass. We determine which
  171692. * modules will be active during this pass and give them appropriate
  171693. * start_pass calls. We also set is_dummy_pass to indicate whether this
  171694. * is a "real" output pass or a dummy pass for color quantization.
  171695. * (In the latter case, jdapistd.c will crank the pass to completion.)
  171696. */
  171697. METHODDEF(void)
  171698. prepare_for_output_pass (j_decompress_ptr cinfo)
  171699. {
  171700. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  171701. if (master->pub.is_dummy_pass) {
  171702. #ifdef QUANT_2PASS_SUPPORTED
  171703. /* Final pass of 2-pass quantization */
  171704. master->pub.is_dummy_pass = FALSE;
  171705. (*cinfo->cquantize->start_pass) (cinfo, FALSE);
  171706. (*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST);
  171707. (*cinfo->main->start_pass) (cinfo, JBUF_CRANK_DEST);
  171708. #else
  171709. ERREXIT(cinfo, JERR_NOT_COMPILED);
  171710. #endif /* QUANT_2PASS_SUPPORTED */
  171711. } else {
  171712. if (cinfo->quantize_colors && cinfo->colormap == NULL) {
  171713. /* Select new quantization method */
  171714. if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) {
  171715. cinfo->cquantize = master->quantizer_2pass;
  171716. master->pub.is_dummy_pass = TRUE;
  171717. } else if (cinfo->enable_1pass_quant) {
  171718. cinfo->cquantize = master->quantizer_1pass;
  171719. } else {
  171720. ERREXIT(cinfo, JERR_MODE_CHANGE);
  171721. }
  171722. }
  171723. (*cinfo->idct->start_pass) (cinfo);
  171724. (*cinfo->coef->start_output_pass) (cinfo);
  171725. if (! cinfo->raw_data_out) {
  171726. if (! master->using_merged_upsample)
  171727. (*cinfo->cconvert->start_pass) (cinfo);
  171728. (*cinfo->upsample->start_pass) (cinfo);
  171729. if (cinfo->quantize_colors)
  171730. (*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass);
  171731. (*cinfo->post->start_pass) (cinfo,
  171732. (master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  171733. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  171734. }
  171735. }
  171736. /* Set up progress monitor's pass info if present */
  171737. if (cinfo->progress != NULL) {
  171738. cinfo->progress->completed_passes = master->pass_number;
  171739. cinfo->progress->total_passes = master->pass_number +
  171740. (master->pub.is_dummy_pass ? 2 : 1);
  171741. /* In buffered-image mode, we assume one more output pass if EOI not
  171742. * yet reached, but no more passes if EOI has been reached.
  171743. */
  171744. if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) {
  171745. cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1);
  171746. }
  171747. }
  171748. }
  171749. /*
  171750. * Finish up at end of an output pass.
  171751. */
  171752. METHODDEF(void)
  171753. finish_output_pass (j_decompress_ptr cinfo)
  171754. {
  171755. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  171756. if (cinfo->quantize_colors)
  171757. (*cinfo->cquantize->finish_pass) (cinfo);
  171758. master->pass_number++;
  171759. }
  171760. #ifdef D_MULTISCAN_FILES_SUPPORTED
  171761. /*
  171762. * Switch to a new external colormap between output passes.
  171763. */
  171764. GLOBAL(void)
  171765. jpeg_new_colormap (j_decompress_ptr cinfo)
  171766. {
  171767. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  171768. /* Prevent application from calling me at wrong times */
  171769. if (cinfo->global_state != DSTATE_BUFIMAGE)
  171770. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  171771. if (cinfo->quantize_colors && cinfo->enable_external_quant &&
  171772. cinfo->colormap != NULL) {
  171773. /* Select 2-pass quantizer for external colormap use */
  171774. cinfo->cquantize = master->quantizer_2pass;
  171775. /* Notify quantizer of colormap change */
  171776. (*cinfo->cquantize->new_color_map) (cinfo);
  171777. master->pub.is_dummy_pass = FALSE; /* just in case */
  171778. } else
  171779. ERREXIT(cinfo, JERR_MODE_CHANGE);
  171780. }
  171781. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  171782. /*
  171783. * Initialize master decompression control and select active modules.
  171784. * This is performed at the start of jpeg_start_decompress.
  171785. */
  171786. GLOBAL(void)
  171787. jinit_master_decompress (j_decompress_ptr cinfo)
  171788. {
  171789. my_master_ptr6 master;
  171790. master = (my_master_ptr6)
  171791. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171792. SIZEOF(my_decomp_master));
  171793. cinfo->master = (struct jpeg_decomp_master *) master;
  171794. master->pub.prepare_for_output_pass = prepare_for_output_pass;
  171795. master->pub.finish_output_pass = finish_output_pass;
  171796. master->pub.is_dummy_pass = FALSE;
  171797. master_selection(cinfo);
  171798. }
  171799. /*** End of inlined file: jdmaster.c ***/
  171800. #undef FIX
  171801. /*** Start of inlined file: jdmerge.c ***/
  171802. #define JPEG_INTERNALS
  171803. #ifdef UPSAMPLE_MERGING_SUPPORTED
  171804. /* Private subobject */
  171805. typedef struct {
  171806. struct jpeg_upsampler pub; /* public fields */
  171807. /* Pointer to routine to do actual upsampling/conversion of one row group */
  171808. JMETHOD(void, upmethod, (j_decompress_ptr cinfo,
  171809. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  171810. JSAMPARRAY output_buf));
  171811. /* Private state for YCC->RGB conversion */
  171812. int * Cr_r_tab; /* => table for Cr to R conversion */
  171813. int * Cb_b_tab; /* => table for Cb to B conversion */
  171814. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  171815. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  171816. /* For 2:1 vertical sampling, we produce two output rows at a time.
  171817. * We need a "spare" row buffer to hold the second output row if the
  171818. * application provides just a one-row buffer; we also use the spare
  171819. * to discard the dummy last row if the image height is odd.
  171820. */
  171821. JSAMPROW spare_row;
  171822. boolean spare_full; /* T if spare buffer is occupied */
  171823. JDIMENSION out_row_width; /* samples per output row */
  171824. JDIMENSION rows_to_go; /* counts rows remaining in image */
  171825. } my_upsampler;
  171826. typedef my_upsampler * my_upsample_ptr;
  171827. #define SCALEBITS 16 /* speediest right-shift on some machines */
  171828. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  171829. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  171830. /*
  171831. * Initialize tables for YCC->RGB colorspace conversion.
  171832. * This is taken directly from jdcolor.c; see that file for more info.
  171833. */
  171834. LOCAL(void)
  171835. build_ycc_rgb_table2 (j_decompress_ptr cinfo)
  171836. {
  171837. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  171838. int i;
  171839. INT32 x;
  171840. SHIFT_TEMPS
  171841. upsample->Cr_r_tab = (int *)
  171842. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171843. (MAXJSAMPLE+1) * SIZEOF(int));
  171844. upsample->Cb_b_tab = (int *)
  171845. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171846. (MAXJSAMPLE+1) * SIZEOF(int));
  171847. upsample->Cr_g_tab = (INT32 *)
  171848. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171849. (MAXJSAMPLE+1) * SIZEOF(INT32));
  171850. upsample->Cb_g_tab = (INT32 *)
  171851. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171852. (MAXJSAMPLE+1) * SIZEOF(INT32));
  171853. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  171854. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  171855. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  171856. /* Cr=>R value is nearest int to 1.40200 * x */
  171857. upsample->Cr_r_tab[i] = (int)
  171858. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  171859. /* Cb=>B value is nearest int to 1.77200 * x */
  171860. upsample->Cb_b_tab[i] = (int)
  171861. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  171862. /* Cr=>G value is scaled-up -0.71414 * x */
  171863. upsample->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  171864. /* Cb=>G value is scaled-up -0.34414 * x */
  171865. /* We also add in ONE_HALF so that need not do it in inner loop */
  171866. upsample->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  171867. }
  171868. }
  171869. /*
  171870. * Initialize for an upsampling pass.
  171871. */
  171872. METHODDEF(void)
  171873. start_pass_merged_upsample (j_decompress_ptr cinfo)
  171874. {
  171875. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  171876. /* Mark the spare buffer empty */
  171877. upsample->spare_full = FALSE;
  171878. /* Initialize total-height counter for detecting bottom of image */
  171879. upsample->rows_to_go = cinfo->output_height;
  171880. }
  171881. /*
  171882. * Control routine to do upsampling (and color conversion).
  171883. *
  171884. * The control routine just handles the row buffering considerations.
  171885. */
  171886. METHODDEF(void)
  171887. merged_2v_upsample (j_decompress_ptr cinfo,
  171888. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  171889. JDIMENSION,
  171890. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  171891. JDIMENSION out_rows_avail)
  171892. /* 2:1 vertical sampling case: may need a spare row. */
  171893. {
  171894. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  171895. JSAMPROW work_ptrs[2];
  171896. JDIMENSION num_rows; /* number of rows returned to caller */
  171897. if (upsample->spare_full) {
  171898. /* If we have a spare row saved from a previous cycle, just return it. */
  171899. jcopy_sample_rows(& upsample->spare_row, 0, output_buf + *out_row_ctr, 0,
  171900. 1, upsample->out_row_width);
  171901. num_rows = 1;
  171902. upsample->spare_full = FALSE;
  171903. } else {
  171904. /* Figure number of rows to return to caller. */
  171905. num_rows = 2;
  171906. /* Not more than the distance to the end of the image. */
  171907. if (num_rows > upsample->rows_to_go)
  171908. num_rows = upsample->rows_to_go;
  171909. /* And not more than what the client can accept: */
  171910. out_rows_avail -= *out_row_ctr;
  171911. if (num_rows > out_rows_avail)
  171912. num_rows = out_rows_avail;
  171913. /* Create output pointer array for upsampler. */
  171914. work_ptrs[0] = output_buf[*out_row_ctr];
  171915. if (num_rows > 1) {
  171916. work_ptrs[1] = output_buf[*out_row_ctr + 1];
  171917. } else {
  171918. work_ptrs[1] = upsample->spare_row;
  171919. upsample->spare_full = TRUE;
  171920. }
  171921. /* Now do the upsampling. */
  171922. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr, work_ptrs);
  171923. }
  171924. /* Adjust counts */
  171925. *out_row_ctr += num_rows;
  171926. upsample->rows_to_go -= num_rows;
  171927. /* When the buffer is emptied, declare this input row group consumed */
  171928. if (! upsample->spare_full)
  171929. (*in_row_group_ctr)++;
  171930. }
  171931. METHODDEF(void)
  171932. merged_1v_upsample (j_decompress_ptr cinfo,
  171933. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  171934. JDIMENSION,
  171935. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  171936. JDIMENSION)
  171937. /* 1:1 vertical sampling case: much easier, never need a spare row. */
  171938. {
  171939. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  171940. /* Just do the upsampling. */
  171941. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr,
  171942. output_buf + *out_row_ctr);
  171943. /* Adjust counts */
  171944. (*out_row_ctr)++;
  171945. (*in_row_group_ctr)++;
  171946. }
  171947. /*
  171948. * These are the routines invoked by the control routines to do
  171949. * the actual upsampling/conversion. One row group is processed per call.
  171950. *
  171951. * Note: since we may be writing directly into application-supplied buffers,
  171952. * we have to be honest about the output width; we can't assume the buffer
  171953. * has been rounded up to an even width.
  171954. */
  171955. /*
  171956. * Upsample and color convert for the case of 2:1 horizontal and 1:1 vertical.
  171957. */
  171958. METHODDEF(void)
  171959. h2v1_merged_upsample (j_decompress_ptr cinfo,
  171960. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  171961. JSAMPARRAY output_buf)
  171962. {
  171963. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  171964. register int y, cred, cgreen, cblue;
  171965. int cb, cr;
  171966. register JSAMPROW outptr;
  171967. JSAMPROW inptr0, inptr1, inptr2;
  171968. JDIMENSION col;
  171969. /* copy these pointers into registers if possible */
  171970. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  171971. int * Crrtab = upsample->Cr_r_tab;
  171972. int * Cbbtab = upsample->Cb_b_tab;
  171973. INT32 * Crgtab = upsample->Cr_g_tab;
  171974. INT32 * Cbgtab = upsample->Cb_g_tab;
  171975. SHIFT_TEMPS
  171976. inptr0 = input_buf[0][in_row_group_ctr];
  171977. inptr1 = input_buf[1][in_row_group_ctr];
  171978. inptr2 = input_buf[2][in_row_group_ctr];
  171979. outptr = output_buf[0];
  171980. /* Loop for each pair of output pixels */
  171981. for (col = cinfo->output_width >> 1; col > 0; col--) {
  171982. /* Do the chroma part of the calculation */
  171983. cb = GETJSAMPLE(*inptr1++);
  171984. cr = GETJSAMPLE(*inptr2++);
  171985. cred = Crrtab[cr];
  171986. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  171987. cblue = Cbbtab[cb];
  171988. /* Fetch 2 Y values and emit 2 pixels */
  171989. y = GETJSAMPLE(*inptr0++);
  171990. outptr[RGB_RED] = range_limit[y + cred];
  171991. outptr[RGB_GREEN] = range_limit[y + cgreen];
  171992. outptr[RGB_BLUE] = range_limit[y + cblue];
  171993. outptr += RGB_PIXELSIZE;
  171994. y = GETJSAMPLE(*inptr0++);
  171995. outptr[RGB_RED] = range_limit[y + cred];
  171996. outptr[RGB_GREEN] = range_limit[y + cgreen];
  171997. outptr[RGB_BLUE] = range_limit[y + cblue];
  171998. outptr += RGB_PIXELSIZE;
  171999. }
  172000. /* If image width is odd, do the last output column separately */
  172001. if (cinfo->output_width & 1) {
  172002. cb = GETJSAMPLE(*inptr1);
  172003. cr = GETJSAMPLE(*inptr2);
  172004. cred = Crrtab[cr];
  172005. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172006. cblue = Cbbtab[cb];
  172007. y = GETJSAMPLE(*inptr0);
  172008. outptr[RGB_RED] = range_limit[y + cred];
  172009. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172010. outptr[RGB_BLUE] = range_limit[y + cblue];
  172011. }
  172012. }
  172013. /*
  172014. * Upsample and color convert for the case of 2:1 horizontal and 2:1 vertical.
  172015. */
  172016. METHODDEF(void)
  172017. h2v2_merged_upsample (j_decompress_ptr cinfo,
  172018. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172019. JSAMPARRAY output_buf)
  172020. {
  172021. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172022. register int y, cred, cgreen, cblue;
  172023. int cb, cr;
  172024. register JSAMPROW outptr0, outptr1;
  172025. JSAMPROW inptr00, inptr01, inptr1, inptr2;
  172026. JDIMENSION col;
  172027. /* copy these pointers into registers if possible */
  172028. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  172029. int * Crrtab = upsample->Cr_r_tab;
  172030. int * Cbbtab = upsample->Cb_b_tab;
  172031. INT32 * Crgtab = upsample->Cr_g_tab;
  172032. INT32 * Cbgtab = upsample->Cb_g_tab;
  172033. SHIFT_TEMPS
  172034. inptr00 = input_buf[0][in_row_group_ctr*2];
  172035. inptr01 = input_buf[0][in_row_group_ctr*2 + 1];
  172036. inptr1 = input_buf[1][in_row_group_ctr];
  172037. inptr2 = input_buf[2][in_row_group_ctr];
  172038. outptr0 = output_buf[0];
  172039. outptr1 = output_buf[1];
  172040. /* Loop for each group of output pixels */
  172041. for (col = cinfo->output_width >> 1; col > 0; col--) {
  172042. /* Do the chroma part of the calculation */
  172043. cb = GETJSAMPLE(*inptr1++);
  172044. cr = GETJSAMPLE(*inptr2++);
  172045. cred = Crrtab[cr];
  172046. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172047. cblue = Cbbtab[cb];
  172048. /* Fetch 4 Y values and emit 4 pixels */
  172049. y = GETJSAMPLE(*inptr00++);
  172050. outptr0[RGB_RED] = range_limit[y + cred];
  172051. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172052. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172053. outptr0 += RGB_PIXELSIZE;
  172054. y = GETJSAMPLE(*inptr00++);
  172055. outptr0[RGB_RED] = range_limit[y + cred];
  172056. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172057. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172058. outptr0 += RGB_PIXELSIZE;
  172059. y = GETJSAMPLE(*inptr01++);
  172060. outptr1[RGB_RED] = range_limit[y + cred];
  172061. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172062. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172063. outptr1 += RGB_PIXELSIZE;
  172064. y = GETJSAMPLE(*inptr01++);
  172065. outptr1[RGB_RED] = range_limit[y + cred];
  172066. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172067. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172068. outptr1 += RGB_PIXELSIZE;
  172069. }
  172070. /* If image width is odd, do the last output column separately */
  172071. if (cinfo->output_width & 1) {
  172072. cb = GETJSAMPLE(*inptr1);
  172073. cr = GETJSAMPLE(*inptr2);
  172074. cred = Crrtab[cr];
  172075. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172076. cblue = Cbbtab[cb];
  172077. y = GETJSAMPLE(*inptr00);
  172078. outptr0[RGB_RED] = range_limit[y + cred];
  172079. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172080. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172081. y = GETJSAMPLE(*inptr01);
  172082. outptr1[RGB_RED] = range_limit[y + cred];
  172083. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172084. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172085. }
  172086. }
  172087. /*
  172088. * Module initialization routine for merged upsampling/color conversion.
  172089. *
  172090. * NB: this is called under the conditions determined by use_merged_upsample()
  172091. * in jdmaster.c. That routine MUST correspond to the actual capabilities
  172092. * of this module; no safety checks are made here.
  172093. */
  172094. GLOBAL(void)
  172095. jinit_merged_upsampler (j_decompress_ptr cinfo)
  172096. {
  172097. my_upsample_ptr upsample;
  172098. upsample = (my_upsample_ptr)
  172099. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172100. SIZEOF(my_upsampler));
  172101. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  172102. upsample->pub.start_pass = start_pass_merged_upsample;
  172103. upsample->pub.need_context_rows = FALSE;
  172104. upsample->out_row_width = cinfo->output_width * cinfo->out_color_components;
  172105. if (cinfo->max_v_samp_factor == 2) {
  172106. upsample->pub.upsample = merged_2v_upsample;
  172107. upsample->upmethod = h2v2_merged_upsample;
  172108. /* Allocate a spare row buffer */
  172109. upsample->spare_row = (JSAMPROW)
  172110. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172111. (size_t) (upsample->out_row_width * SIZEOF(JSAMPLE)));
  172112. } else {
  172113. upsample->pub.upsample = merged_1v_upsample;
  172114. upsample->upmethod = h2v1_merged_upsample;
  172115. /* No spare row needed */
  172116. upsample->spare_row = NULL;
  172117. }
  172118. build_ycc_rgb_table2(cinfo);
  172119. }
  172120. #endif /* UPSAMPLE_MERGING_SUPPORTED */
  172121. /*** End of inlined file: jdmerge.c ***/
  172122. #undef ASSIGN_STATE
  172123. /*** Start of inlined file: jdphuff.c ***/
  172124. #define JPEG_INTERNALS
  172125. #ifdef D_PROGRESSIVE_SUPPORTED
  172126. /*
  172127. * Expanded entropy decoder object for progressive Huffman decoding.
  172128. *
  172129. * The savable_state subrecord contains fields that change within an MCU,
  172130. * but must not be updated permanently until we complete the MCU.
  172131. */
  172132. typedef struct {
  172133. unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
  172134. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  172135. } savable_state3;
  172136. /* This macro is to work around compilers with missing or broken
  172137. * structure assignment. You'll need to fix this code if you have
  172138. * such a compiler and you change MAX_COMPS_IN_SCAN.
  172139. */
  172140. #ifndef NO_STRUCT_ASSIGN
  172141. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  172142. #else
  172143. #if MAX_COMPS_IN_SCAN == 4
  172144. #define ASSIGN_STATE(dest,src) \
  172145. ((dest).EOBRUN = (src).EOBRUN, \
  172146. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  172147. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  172148. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  172149. (dest).last_dc_val[3] = (src).last_dc_val[3])
  172150. #endif
  172151. #endif
  172152. typedef struct {
  172153. struct jpeg_entropy_decoder pub; /* public fields */
  172154. /* These fields are loaded into local variables at start of each MCU.
  172155. * In case of suspension, we exit WITHOUT updating them.
  172156. */
  172157. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  172158. savable_state3 saved; /* Other state at start of MCU */
  172159. /* These fields are NOT loaded into local working state. */
  172160. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  172161. /* Pointers to derived tables (these workspaces have image lifespan) */
  172162. d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  172163. d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
  172164. } phuff_entropy_decoder;
  172165. typedef phuff_entropy_decoder * phuff_entropy_ptr2;
  172166. /* Forward declarations */
  172167. METHODDEF(boolean) decode_mcu_DC_first JPP((j_decompress_ptr cinfo,
  172168. JBLOCKROW *MCU_data));
  172169. METHODDEF(boolean) decode_mcu_AC_first JPP((j_decompress_ptr cinfo,
  172170. JBLOCKROW *MCU_data));
  172171. METHODDEF(boolean) decode_mcu_DC_refine JPP((j_decompress_ptr cinfo,
  172172. JBLOCKROW *MCU_data));
  172173. METHODDEF(boolean) decode_mcu_AC_refine JPP((j_decompress_ptr cinfo,
  172174. JBLOCKROW *MCU_data));
  172175. /*
  172176. * Initialize for a Huffman-compressed scan.
  172177. */
  172178. METHODDEF(void)
  172179. start_pass_phuff_decoder (j_decompress_ptr cinfo)
  172180. {
  172181. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172182. boolean is_DC_band, bad;
  172183. int ci, coefi, tbl;
  172184. int *coef_bit_ptr;
  172185. jpeg_component_info * compptr;
  172186. is_DC_band = (cinfo->Ss == 0);
  172187. /* Validate scan parameters */
  172188. bad = FALSE;
  172189. if (is_DC_band) {
  172190. if (cinfo->Se != 0)
  172191. bad = TRUE;
  172192. } else {
  172193. /* need not check Ss/Se < 0 since they came from unsigned bytes */
  172194. if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
  172195. bad = TRUE;
  172196. /* AC scans may have only one component */
  172197. if (cinfo->comps_in_scan != 1)
  172198. bad = TRUE;
  172199. }
  172200. if (cinfo->Ah != 0) {
  172201. /* Successive approximation refinement scan: must have Al = Ah-1. */
  172202. if (cinfo->Al != cinfo->Ah-1)
  172203. bad = TRUE;
  172204. }
  172205. if (cinfo->Al > 13) /* need not check for < 0 */
  172206. bad = TRUE;
  172207. /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
  172208. * but the spec doesn't say so, and we try to be liberal about what we
  172209. * accept. Note: large Al values could result in out-of-range DC
  172210. * coefficients during early scans, leading to bizarre displays due to
  172211. * overflows in the IDCT math. But we won't crash.
  172212. */
  172213. if (bad)
  172214. ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
  172215. cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
  172216. /* Update progression status, and verify that scan order is legal.
  172217. * Note that inter-scan inconsistencies are treated as warnings
  172218. * not fatal errors ... not clear if this is right way to behave.
  172219. */
  172220. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  172221. int cindex = cinfo->cur_comp_info[ci]->component_index;
  172222. coef_bit_ptr = & cinfo->coef_bits[cindex][0];
  172223. if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
  172224. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
  172225. for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
  172226. int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
  172227. if (cinfo->Ah != expected)
  172228. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
  172229. coef_bit_ptr[coefi] = cinfo->Al;
  172230. }
  172231. }
  172232. /* Select MCU decoding routine */
  172233. if (cinfo->Ah == 0) {
  172234. if (is_DC_band)
  172235. entropy->pub.decode_mcu = decode_mcu_DC_first;
  172236. else
  172237. entropy->pub.decode_mcu = decode_mcu_AC_first;
  172238. } else {
  172239. if (is_DC_band)
  172240. entropy->pub.decode_mcu = decode_mcu_DC_refine;
  172241. else
  172242. entropy->pub.decode_mcu = decode_mcu_AC_refine;
  172243. }
  172244. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  172245. compptr = cinfo->cur_comp_info[ci];
  172246. /* Make sure requested tables are present, and compute derived tables.
  172247. * We may build same derived table more than once, but it's not expensive.
  172248. */
  172249. if (is_DC_band) {
  172250. if (cinfo->Ah == 0) { /* DC refinement needs no table */
  172251. tbl = compptr->dc_tbl_no;
  172252. jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
  172253. & entropy->derived_tbls[tbl]);
  172254. }
  172255. } else {
  172256. tbl = compptr->ac_tbl_no;
  172257. jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
  172258. & entropy->derived_tbls[tbl]);
  172259. /* remember the single active table */
  172260. entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
  172261. }
  172262. /* Initialize DC predictions to 0 */
  172263. entropy->saved.last_dc_val[ci] = 0;
  172264. }
  172265. /* Initialize bitread state variables */
  172266. entropy->bitstate.bits_left = 0;
  172267. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  172268. entropy->pub.insufficient_data = FALSE;
  172269. /* Initialize private state variables */
  172270. entropy->saved.EOBRUN = 0;
  172271. /* Initialize restart counter */
  172272. entropy->restarts_to_go = cinfo->restart_interval;
  172273. }
  172274. /*
  172275. * Check for a restart marker & resynchronize decoder.
  172276. * Returns FALSE if must suspend.
  172277. */
  172278. LOCAL(boolean)
  172279. process_restartp (j_decompress_ptr cinfo)
  172280. {
  172281. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172282. int ci;
  172283. /* Throw away any unused bits remaining in bit buffer; */
  172284. /* include any full bytes in next_marker's count of discarded bytes */
  172285. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  172286. entropy->bitstate.bits_left = 0;
  172287. /* Advance past the RSTn marker */
  172288. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  172289. return FALSE;
  172290. /* Re-initialize DC predictions to 0 */
  172291. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  172292. entropy->saved.last_dc_val[ci] = 0;
  172293. /* Re-init EOB run count, too */
  172294. entropy->saved.EOBRUN = 0;
  172295. /* Reset restart counter */
  172296. entropy->restarts_to_go = cinfo->restart_interval;
  172297. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  172298. * against a marker. In that case we will end up treating the next data
  172299. * segment as empty, and we can avoid producing bogus output pixels by
  172300. * leaving the flag set.
  172301. */
  172302. if (cinfo->unread_marker == 0)
  172303. entropy->pub.insufficient_data = FALSE;
  172304. return TRUE;
  172305. }
  172306. /*
  172307. * Huffman MCU decoding.
  172308. * Each of these routines decodes and returns one MCU's worth of
  172309. * Huffman-compressed coefficients.
  172310. * The coefficients are reordered from zigzag order into natural array order,
  172311. * but are not dequantized.
  172312. *
  172313. * The i'th block of the MCU is stored into the block pointed to by
  172314. * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
  172315. *
  172316. * We return FALSE if data source requested suspension. In that case no
  172317. * changes have been made to permanent state. (Exception: some output
  172318. * coefficients may already have been assigned. This is harmless for
  172319. * spectral selection, since we'll just re-assign them on the next call.
  172320. * Successive approximation AC refinement has to be more careful, however.)
  172321. */
  172322. /*
  172323. * MCU decoding for DC initial scan (either spectral selection,
  172324. * or first pass of successive approximation).
  172325. */
  172326. METHODDEF(boolean)
  172327. decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  172328. {
  172329. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172330. int Al = cinfo->Al;
  172331. register int s, r;
  172332. int blkn, ci;
  172333. JBLOCKROW block;
  172334. BITREAD_STATE_VARS;
  172335. savable_state3 state;
  172336. d_derived_tbl * tbl;
  172337. jpeg_component_info * compptr;
  172338. /* Process restart marker if needed; may have to suspend */
  172339. if (cinfo->restart_interval) {
  172340. if (entropy->restarts_to_go == 0)
  172341. if (! process_restartp(cinfo))
  172342. return FALSE;
  172343. }
  172344. /* If we've run out of data, just leave the MCU set to zeroes.
  172345. * This way, we return uniform gray for the remainder of the segment.
  172346. */
  172347. if (! entropy->pub.insufficient_data) {
  172348. /* Load up working state */
  172349. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  172350. ASSIGN_STATE(state, entropy->saved);
  172351. /* Outer loop handles each block in the MCU */
  172352. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  172353. block = MCU_data[blkn];
  172354. ci = cinfo->MCU_membership[blkn];
  172355. compptr = cinfo->cur_comp_info[ci];
  172356. tbl = entropy->derived_tbls[compptr->dc_tbl_no];
  172357. /* Decode a single block's worth of coefficients */
  172358. /* Section F.2.2.1: decode the DC coefficient difference */
  172359. HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
  172360. if (s) {
  172361. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  172362. r = GET_BITS(s);
  172363. s = HUFF_EXTEND(r, s);
  172364. }
  172365. /* Convert DC difference to actual value, update last_dc_val */
  172366. s += state.last_dc_val[ci];
  172367. state.last_dc_val[ci] = s;
  172368. /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
  172369. (*block)[0] = (JCOEF) (s << Al);
  172370. }
  172371. /* Completed MCU, so update state */
  172372. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  172373. ASSIGN_STATE(entropy->saved, state);
  172374. }
  172375. /* Account for restart interval (no-op if not using restarts) */
  172376. entropy->restarts_to_go--;
  172377. return TRUE;
  172378. }
  172379. /*
  172380. * MCU decoding for AC initial scan (either spectral selection,
  172381. * or first pass of successive approximation).
  172382. */
  172383. METHODDEF(boolean)
  172384. decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  172385. {
  172386. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172387. int Se = cinfo->Se;
  172388. int Al = cinfo->Al;
  172389. register int s, k, r;
  172390. unsigned int EOBRUN;
  172391. JBLOCKROW block;
  172392. BITREAD_STATE_VARS;
  172393. d_derived_tbl * tbl;
  172394. /* Process restart marker if needed; may have to suspend */
  172395. if (cinfo->restart_interval) {
  172396. if (entropy->restarts_to_go == 0)
  172397. if (! process_restartp(cinfo))
  172398. return FALSE;
  172399. }
  172400. /* If we've run out of data, just leave the MCU set to zeroes.
  172401. * This way, we return uniform gray for the remainder of the segment.
  172402. */
  172403. if (! entropy->pub.insufficient_data) {
  172404. /* Load up working state.
  172405. * We can avoid loading/saving bitread state if in an EOB run.
  172406. */
  172407. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  172408. /* There is always only one block per MCU */
  172409. if (EOBRUN > 0) /* if it's a band of zeroes... */
  172410. EOBRUN--; /* ...process it now (we do nothing) */
  172411. else {
  172412. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  172413. block = MCU_data[0];
  172414. tbl = entropy->ac_derived_tbl;
  172415. for (k = cinfo->Ss; k <= Se; k++) {
  172416. HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
  172417. r = s >> 4;
  172418. s &= 15;
  172419. if (s) {
  172420. k += r;
  172421. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  172422. r = GET_BITS(s);
  172423. s = HUFF_EXTEND(r, s);
  172424. /* Scale and output coefficient in natural (dezigzagged) order */
  172425. (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
  172426. } else {
  172427. if (r == 15) { /* ZRL */
  172428. k += 15; /* skip 15 zeroes in band */
  172429. } else { /* EOBr, run length is 2^r + appended bits */
  172430. EOBRUN = 1 << r;
  172431. if (r) { /* EOBr, r > 0 */
  172432. CHECK_BIT_BUFFER(br_state, r, return FALSE);
  172433. r = GET_BITS(r);
  172434. EOBRUN += r;
  172435. }
  172436. EOBRUN--; /* this band is processed at this moment */
  172437. break; /* force end-of-band */
  172438. }
  172439. }
  172440. }
  172441. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  172442. }
  172443. /* Completed MCU, so update state */
  172444. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  172445. }
  172446. /* Account for restart interval (no-op if not using restarts) */
  172447. entropy->restarts_to_go--;
  172448. return TRUE;
  172449. }
  172450. /*
  172451. * MCU decoding for DC successive approximation refinement scan.
  172452. * Note: we assume such scans can be multi-component, although the spec
  172453. * is not very clear on the point.
  172454. */
  172455. METHODDEF(boolean)
  172456. decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  172457. {
  172458. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172459. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  172460. int blkn;
  172461. JBLOCKROW block;
  172462. BITREAD_STATE_VARS;
  172463. /* Process restart marker if needed; may have to suspend */
  172464. if (cinfo->restart_interval) {
  172465. if (entropy->restarts_to_go == 0)
  172466. if (! process_restartp(cinfo))
  172467. return FALSE;
  172468. }
  172469. /* Not worth the cycles to check insufficient_data here,
  172470. * since we will not change the data anyway if we read zeroes.
  172471. */
  172472. /* Load up working state */
  172473. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  172474. /* Outer loop handles each block in the MCU */
  172475. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  172476. block = MCU_data[blkn];
  172477. /* Encoded data is simply the next bit of the two's-complement DC value */
  172478. CHECK_BIT_BUFFER(br_state, 1, return FALSE);
  172479. if (GET_BITS(1))
  172480. (*block)[0] |= p1;
  172481. /* Note: since we use |=, repeating the assignment later is safe */
  172482. }
  172483. /* Completed MCU, so update state */
  172484. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  172485. /* Account for restart interval (no-op if not using restarts) */
  172486. entropy->restarts_to_go--;
  172487. return TRUE;
  172488. }
  172489. /*
  172490. * MCU decoding for AC successive approximation refinement scan.
  172491. */
  172492. METHODDEF(boolean)
  172493. decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  172494. {
  172495. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172496. int Se = cinfo->Se;
  172497. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  172498. int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
  172499. register int s, k, r;
  172500. unsigned int EOBRUN;
  172501. JBLOCKROW block;
  172502. JCOEFPTR thiscoef;
  172503. BITREAD_STATE_VARS;
  172504. d_derived_tbl * tbl;
  172505. int num_newnz;
  172506. int newnz_pos[DCTSIZE2];
  172507. /* Process restart marker if needed; may have to suspend */
  172508. if (cinfo->restart_interval) {
  172509. if (entropy->restarts_to_go == 0)
  172510. if (! process_restartp(cinfo))
  172511. return FALSE;
  172512. }
  172513. /* If we've run out of data, don't modify the MCU.
  172514. */
  172515. if (! entropy->pub.insufficient_data) {
  172516. /* Load up working state */
  172517. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  172518. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  172519. /* There is always only one block per MCU */
  172520. block = MCU_data[0];
  172521. tbl = entropy->ac_derived_tbl;
  172522. /* If we are forced to suspend, we must undo the assignments to any newly
  172523. * nonzero coefficients in the block, because otherwise we'd get confused
  172524. * next time about which coefficients were already nonzero.
  172525. * But we need not undo addition of bits to already-nonzero coefficients;
  172526. * instead, we can test the current bit to see if we already did it.
  172527. */
  172528. num_newnz = 0;
  172529. /* initialize coefficient loop counter to start of band */
  172530. k = cinfo->Ss;
  172531. if (EOBRUN == 0) {
  172532. for (; k <= Se; k++) {
  172533. HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
  172534. r = s >> 4;
  172535. s &= 15;
  172536. if (s) {
  172537. if (s != 1) /* size of new coef should always be 1 */
  172538. WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
  172539. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  172540. if (GET_BITS(1))
  172541. s = p1; /* newly nonzero coef is positive */
  172542. else
  172543. s = m1; /* newly nonzero coef is negative */
  172544. } else {
  172545. if (r != 15) {
  172546. EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
  172547. if (r) {
  172548. CHECK_BIT_BUFFER(br_state, r, goto undoit);
  172549. r = GET_BITS(r);
  172550. EOBRUN += r;
  172551. }
  172552. break; /* rest of block is handled by EOB logic */
  172553. }
  172554. /* note s = 0 for processing ZRL */
  172555. }
  172556. /* Advance over already-nonzero coefs and r still-zero coefs,
  172557. * appending correction bits to the nonzeroes. A correction bit is 1
  172558. * if the absolute value of the coefficient must be increased.
  172559. */
  172560. do {
  172561. thiscoef = *block + jpeg_natural_order[k];
  172562. if (*thiscoef != 0) {
  172563. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  172564. if (GET_BITS(1)) {
  172565. if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
  172566. if (*thiscoef >= 0)
  172567. *thiscoef += p1;
  172568. else
  172569. *thiscoef += m1;
  172570. }
  172571. }
  172572. } else {
  172573. if (--r < 0)
  172574. break; /* reached target zero coefficient */
  172575. }
  172576. k++;
  172577. } while (k <= Se);
  172578. if (s) {
  172579. int pos = jpeg_natural_order[k];
  172580. /* Output newly nonzero coefficient */
  172581. (*block)[pos] = (JCOEF) s;
  172582. /* Remember its position in case we have to suspend */
  172583. newnz_pos[num_newnz++] = pos;
  172584. }
  172585. }
  172586. }
  172587. if (EOBRUN > 0) {
  172588. /* Scan any remaining coefficient positions after the end-of-band
  172589. * (the last newly nonzero coefficient, if any). Append a correction
  172590. * bit to each already-nonzero coefficient. A correction bit is 1
  172591. * if the absolute value of the coefficient must be increased.
  172592. */
  172593. for (; k <= Se; k++) {
  172594. thiscoef = *block + jpeg_natural_order[k];
  172595. if (*thiscoef != 0) {
  172596. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  172597. if (GET_BITS(1)) {
  172598. if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
  172599. if (*thiscoef >= 0)
  172600. *thiscoef += p1;
  172601. else
  172602. *thiscoef += m1;
  172603. }
  172604. }
  172605. }
  172606. }
  172607. /* Count one block completed in EOB run */
  172608. EOBRUN--;
  172609. }
  172610. /* Completed MCU, so update state */
  172611. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  172612. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  172613. }
  172614. /* Account for restart interval (no-op if not using restarts) */
  172615. entropy->restarts_to_go--;
  172616. return TRUE;
  172617. undoit:
  172618. /* Re-zero any output coefficients that we made newly nonzero */
  172619. while (num_newnz > 0)
  172620. (*block)[newnz_pos[--num_newnz]] = 0;
  172621. return FALSE;
  172622. }
  172623. /*
  172624. * Module initialization routine for progressive Huffman entropy decoding.
  172625. */
  172626. GLOBAL(void)
  172627. jinit_phuff_decoder (j_decompress_ptr cinfo)
  172628. {
  172629. phuff_entropy_ptr2 entropy;
  172630. int *coef_bit_ptr;
  172631. int ci, i;
  172632. entropy = (phuff_entropy_ptr2)
  172633. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172634. SIZEOF(phuff_entropy_decoder));
  172635. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  172636. entropy->pub.start_pass = start_pass_phuff_decoder;
  172637. /* Mark derived tables unallocated */
  172638. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  172639. entropy->derived_tbls[i] = NULL;
  172640. }
  172641. /* Create progression status table */
  172642. cinfo->coef_bits = (int (*)[DCTSIZE2])
  172643. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172644. cinfo->num_components*DCTSIZE2*SIZEOF(int));
  172645. coef_bit_ptr = & cinfo->coef_bits[0][0];
  172646. for (ci = 0; ci < cinfo->num_components; ci++)
  172647. for (i = 0; i < DCTSIZE2; i++)
  172648. *coef_bit_ptr++ = -1;
  172649. }
  172650. #endif /* D_PROGRESSIVE_SUPPORTED */
  172651. /*** End of inlined file: jdphuff.c ***/
  172652. /*** Start of inlined file: jdpostct.c ***/
  172653. #define JPEG_INTERNALS
  172654. /* Private buffer controller object */
  172655. typedef struct {
  172656. struct jpeg_d_post_controller pub; /* public fields */
  172657. /* Color quantization source buffer: this holds output data from
  172658. * the upsample/color conversion step to be passed to the quantizer.
  172659. * For two-pass color quantization, we need a full-image buffer;
  172660. * for one-pass operation, a strip buffer is sufficient.
  172661. */
  172662. jvirt_sarray_ptr whole_image; /* virtual array, or NULL if one-pass */
  172663. JSAMPARRAY buffer; /* strip buffer, or current strip of virtual */
  172664. JDIMENSION strip_height; /* buffer size in rows */
  172665. /* for two-pass mode only: */
  172666. JDIMENSION starting_row; /* row # of first row in current strip */
  172667. JDIMENSION next_row; /* index of next row to fill/empty in strip */
  172668. } my_post_controller;
  172669. typedef my_post_controller * my_post_ptr;
  172670. /* Forward declarations */
  172671. METHODDEF(void) post_process_1pass
  172672. JPP((j_decompress_ptr cinfo,
  172673. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172674. JDIMENSION in_row_groups_avail,
  172675. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172676. JDIMENSION out_rows_avail));
  172677. #ifdef QUANT_2PASS_SUPPORTED
  172678. METHODDEF(void) post_process_prepass
  172679. JPP((j_decompress_ptr cinfo,
  172680. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172681. JDIMENSION in_row_groups_avail,
  172682. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172683. JDIMENSION out_rows_avail));
  172684. METHODDEF(void) post_process_2pass
  172685. JPP((j_decompress_ptr cinfo,
  172686. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172687. JDIMENSION in_row_groups_avail,
  172688. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172689. JDIMENSION out_rows_avail));
  172690. #endif
  172691. /*
  172692. * Initialize for a processing pass.
  172693. */
  172694. METHODDEF(void)
  172695. start_pass_dpost (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  172696. {
  172697. my_post_ptr post = (my_post_ptr) cinfo->post;
  172698. switch (pass_mode) {
  172699. case JBUF_PASS_THRU:
  172700. if (cinfo->quantize_colors) {
  172701. /* Single-pass processing with color quantization. */
  172702. post->pub.post_process_data = post_process_1pass;
  172703. /* We could be doing buffered-image output before starting a 2-pass
  172704. * color quantization; in that case, jinit_d_post_controller did not
  172705. * allocate a strip buffer. Use the virtual-array buffer as workspace.
  172706. */
  172707. if (post->buffer == NULL) {
  172708. post->buffer = (*cinfo->mem->access_virt_sarray)
  172709. ((j_common_ptr) cinfo, post->whole_image,
  172710. (JDIMENSION) 0, post->strip_height, TRUE);
  172711. }
  172712. } else {
  172713. /* For single-pass processing without color quantization,
  172714. * I have no work to do; just call the upsampler directly.
  172715. */
  172716. post->pub.post_process_data = cinfo->upsample->upsample;
  172717. }
  172718. break;
  172719. #ifdef QUANT_2PASS_SUPPORTED
  172720. case JBUF_SAVE_AND_PASS:
  172721. /* First pass of 2-pass quantization */
  172722. if (post->whole_image == NULL)
  172723. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  172724. post->pub.post_process_data = post_process_prepass;
  172725. break;
  172726. case JBUF_CRANK_DEST:
  172727. /* Second pass of 2-pass quantization */
  172728. if (post->whole_image == NULL)
  172729. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  172730. post->pub.post_process_data = post_process_2pass;
  172731. break;
  172732. #endif /* QUANT_2PASS_SUPPORTED */
  172733. default:
  172734. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  172735. break;
  172736. }
  172737. post->starting_row = post->next_row = 0;
  172738. }
  172739. /*
  172740. * Process some data in the one-pass (strip buffer) case.
  172741. * This is used for color precision reduction as well as one-pass quantization.
  172742. */
  172743. METHODDEF(void)
  172744. post_process_1pass (j_decompress_ptr cinfo,
  172745. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172746. JDIMENSION in_row_groups_avail,
  172747. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172748. JDIMENSION out_rows_avail)
  172749. {
  172750. my_post_ptr post = (my_post_ptr) cinfo->post;
  172751. JDIMENSION num_rows, max_rows;
  172752. /* Fill the buffer, but not more than what we can dump out in one go. */
  172753. /* Note we rely on the upsampler to detect bottom of image. */
  172754. max_rows = out_rows_avail - *out_row_ctr;
  172755. if (max_rows > post->strip_height)
  172756. max_rows = post->strip_height;
  172757. num_rows = 0;
  172758. (*cinfo->upsample->upsample) (cinfo,
  172759. input_buf, in_row_group_ctr, in_row_groups_avail,
  172760. post->buffer, &num_rows, max_rows);
  172761. /* Quantize and emit data. */
  172762. (*cinfo->cquantize->color_quantize) (cinfo,
  172763. post->buffer, output_buf + *out_row_ctr, (int) num_rows);
  172764. *out_row_ctr += num_rows;
  172765. }
  172766. #ifdef QUANT_2PASS_SUPPORTED
  172767. /*
  172768. * Process some data in the first pass of 2-pass quantization.
  172769. */
  172770. METHODDEF(void)
  172771. post_process_prepass (j_decompress_ptr cinfo,
  172772. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172773. JDIMENSION in_row_groups_avail,
  172774. JSAMPARRAY, JDIMENSION *out_row_ctr,
  172775. JDIMENSION)
  172776. {
  172777. my_post_ptr post = (my_post_ptr) cinfo->post;
  172778. JDIMENSION old_next_row, num_rows;
  172779. /* Reposition virtual buffer if at start of strip. */
  172780. if (post->next_row == 0) {
  172781. post->buffer = (*cinfo->mem->access_virt_sarray)
  172782. ((j_common_ptr) cinfo, post->whole_image,
  172783. post->starting_row, post->strip_height, TRUE);
  172784. }
  172785. /* Upsample some data (up to a strip height's worth). */
  172786. old_next_row = post->next_row;
  172787. (*cinfo->upsample->upsample) (cinfo,
  172788. input_buf, in_row_group_ctr, in_row_groups_avail,
  172789. post->buffer, &post->next_row, post->strip_height);
  172790. /* Allow quantizer to scan new data. No data is emitted, */
  172791. /* but we advance out_row_ctr so outer loop can tell when we're done. */
  172792. if (post->next_row > old_next_row) {
  172793. num_rows = post->next_row - old_next_row;
  172794. (*cinfo->cquantize->color_quantize) (cinfo, post->buffer + old_next_row,
  172795. (JSAMPARRAY) NULL, (int) num_rows);
  172796. *out_row_ctr += num_rows;
  172797. }
  172798. /* Advance if we filled the strip. */
  172799. if (post->next_row >= post->strip_height) {
  172800. post->starting_row += post->strip_height;
  172801. post->next_row = 0;
  172802. }
  172803. }
  172804. /*
  172805. * Process some data in the second pass of 2-pass quantization.
  172806. */
  172807. METHODDEF(void)
  172808. post_process_2pass (j_decompress_ptr cinfo,
  172809. JSAMPIMAGE, JDIMENSION *,
  172810. JDIMENSION,
  172811. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172812. JDIMENSION out_rows_avail)
  172813. {
  172814. my_post_ptr post = (my_post_ptr) cinfo->post;
  172815. JDIMENSION num_rows, max_rows;
  172816. /* Reposition virtual buffer if at start of strip. */
  172817. if (post->next_row == 0) {
  172818. post->buffer = (*cinfo->mem->access_virt_sarray)
  172819. ((j_common_ptr) cinfo, post->whole_image,
  172820. post->starting_row, post->strip_height, FALSE);
  172821. }
  172822. /* Determine number of rows to emit. */
  172823. num_rows = post->strip_height - post->next_row; /* available in strip */
  172824. max_rows = out_rows_avail - *out_row_ctr; /* available in output area */
  172825. if (num_rows > max_rows)
  172826. num_rows = max_rows;
  172827. /* We have to check bottom of image here, can't depend on upsampler. */
  172828. max_rows = cinfo->output_height - post->starting_row;
  172829. if (num_rows > max_rows)
  172830. num_rows = max_rows;
  172831. /* Quantize and emit data. */
  172832. (*cinfo->cquantize->color_quantize) (cinfo,
  172833. post->buffer + post->next_row, output_buf + *out_row_ctr,
  172834. (int) num_rows);
  172835. *out_row_ctr += num_rows;
  172836. /* Advance if we filled the strip. */
  172837. post->next_row += num_rows;
  172838. if (post->next_row >= post->strip_height) {
  172839. post->starting_row += post->strip_height;
  172840. post->next_row = 0;
  172841. }
  172842. }
  172843. #endif /* QUANT_2PASS_SUPPORTED */
  172844. /*
  172845. * Initialize postprocessing controller.
  172846. */
  172847. GLOBAL(void)
  172848. jinit_d_post_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  172849. {
  172850. my_post_ptr post;
  172851. post = (my_post_ptr)
  172852. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172853. SIZEOF(my_post_controller));
  172854. cinfo->post = (struct jpeg_d_post_controller *) post;
  172855. post->pub.start_pass = start_pass_dpost;
  172856. post->whole_image = NULL; /* flag for no virtual arrays */
  172857. post->buffer = NULL; /* flag for no strip buffer */
  172858. /* Create the quantization buffer, if needed */
  172859. if (cinfo->quantize_colors) {
  172860. /* The buffer strip height is max_v_samp_factor, which is typically
  172861. * an efficient number of rows for upsampling to return.
  172862. * (In the presence of output rescaling, we might want to be smarter?)
  172863. */
  172864. post->strip_height = (JDIMENSION) cinfo->max_v_samp_factor;
  172865. if (need_full_buffer) {
  172866. /* Two-pass color quantization: need full-image storage. */
  172867. /* We round up the number of rows to a multiple of the strip height. */
  172868. #ifdef QUANT_2PASS_SUPPORTED
  172869. post->whole_image = (*cinfo->mem->request_virt_sarray)
  172870. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  172871. cinfo->output_width * cinfo->out_color_components,
  172872. (JDIMENSION) jround_up((long) cinfo->output_height,
  172873. (long) post->strip_height),
  172874. post->strip_height);
  172875. #else
  172876. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  172877. #endif /* QUANT_2PASS_SUPPORTED */
  172878. } else {
  172879. /* One-pass color quantization: just make a strip buffer. */
  172880. post->buffer = (*cinfo->mem->alloc_sarray)
  172881. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172882. cinfo->output_width * cinfo->out_color_components,
  172883. post->strip_height);
  172884. }
  172885. }
  172886. }
  172887. /*** End of inlined file: jdpostct.c ***/
  172888. #undef FIX
  172889. /*** Start of inlined file: jdsample.c ***/
  172890. #define JPEG_INTERNALS
  172891. /* Pointer to routine to upsample a single component */
  172892. typedef JMETHOD(void, upsample1_ptr,
  172893. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  172894. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr));
  172895. /* Private subobject */
  172896. typedef struct {
  172897. struct jpeg_upsampler pub; /* public fields */
  172898. /* Color conversion buffer. When using separate upsampling and color
  172899. * conversion steps, this buffer holds one upsampled row group until it
  172900. * has been color converted and output.
  172901. * Note: we do not allocate any storage for component(s) which are full-size,
  172902. * ie do not need rescaling. The corresponding entry of color_buf[] is
  172903. * simply set to point to the input data array, thereby avoiding copying.
  172904. */
  172905. JSAMPARRAY color_buf[MAX_COMPONENTS];
  172906. /* Per-component upsampling method pointers */
  172907. upsample1_ptr methods[MAX_COMPONENTS];
  172908. int next_row_out; /* counts rows emitted from color_buf */
  172909. JDIMENSION rows_to_go; /* counts rows remaining in image */
  172910. /* Height of an input row group for each component. */
  172911. int rowgroup_height[MAX_COMPONENTS];
  172912. /* These arrays save pixel expansion factors so that int_expand need not
  172913. * recompute them each time. They are unused for other upsampling methods.
  172914. */
  172915. UINT8 h_expand[MAX_COMPONENTS];
  172916. UINT8 v_expand[MAX_COMPONENTS];
  172917. } my_upsampler2;
  172918. typedef my_upsampler2 * my_upsample_ptr2;
  172919. /*
  172920. * Initialize for an upsampling pass.
  172921. */
  172922. METHODDEF(void)
  172923. start_pass_upsample (j_decompress_ptr cinfo)
  172924. {
  172925. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  172926. /* Mark the conversion buffer empty */
  172927. upsample->next_row_out = cinfo->max_v_samp_factor;
  172928. /* Initialize total-height counter for detecting bottom of image */
  172929. upsample->rows_to_go = cinfo->output_height;
  172930. }
  172931. /*
  172932. * Control routine to do upsampling (and color conversion).
  172933. *
  172934. * In this version we upsample each component independently.
  172935. * We upsample one row group into the conversion buffer, then apply
  172936. * color conversion a row at a time.
  172937. */
  172938. METHODDEF(void)
  172939. sep_upsample (j_decompress_ptr cinfo,
  172940. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172941. JDIMENSION,
  172942. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172943. JDIMENSION out_rows_avail)
  172944. {
  172945. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  172946. int ci;
  172947. jpeg_component_info * compptr;
  172948. JDIMENSION num_rows;
  172949. /* Fill the conversion buffer, if it's empty */
  172950. if (upsample->next_row_out >= cinfo->max_v_samp_factor) {
  172951. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  172952. ci++, compptr++) {
  172953. /* Invoke per-component upsample method. Notice we pass a POINTER
  172954. * to color_buf[ci], so that fullsize_upsample can change it.
  172955. */
  172956. (*upsample->methods[ci]) (cinfo, compptr,
  172957. input_buf[ci] + (*in_row_group_ctr * upsample->rowgroup_height[ci]),
  172958. upsample->color_buf + ci);
  172959. }
  172960. upsample->next_row_out = 0;
  172961. }
  172962. /* Color-convert and emit rows */
  172963. /* How many we have in the buffer: */
  172964. num_rows = (JDIMENSION) (cinfo->max_v_samp_factor - upsample->next_row_out);
  172965. /* Not more than the distance to the end of the image. Need this test
  172966. * in case the image height is not a multiple of max_v_samp_factor:
  172967. */
  172968. if (num_rows > upsample->rows_to_go)
  172969. num_rows = upsample->rows_to_go;
  172970. /* And not more than what the client can accept: */
  172971. out_rows_avail -= *out_row_ctr;
  172972. if (num_rows > out_rows_avail)
  172973. num_rows = out_rows_avail;
  172974. (*cinfo->cconvert->color_convert) (cinfo, upsample->color_buf,
  172975. (JDIMENSION) upsample->next_row_out,
  172976. output_buf + *out_row_ctr,
  172977. (int) num_rows);
  172978. /* Adjust counts */
  172979. *out_row_ctr += num_rows;
  172980. upsample->rows_to_go -= num_rows;
  172981. upsample->next_row_out += num_rows;
  172982. /* When the buffer is emptied, declare this input row group consumed */
  172983. if (upsample->next_row_out >= cinfo->max_v_samp_factor)
  172984. (*in_row_group_ctr)++;
  172985. }
  172986. /*
  172987. * These are the routines invoked by sep_upsample to upsample pixel values
  172988. * of a single component. One row group is processed per call.
  172989. */
  172990. /*
  172991. * For full-size components, we just make color_buf[ci] point at the
  172992. * input buffer, and thus avoid copying any data. Note that this is
  172993. * safe only because sep_upsample doesn't declare the input row group
  172994. * "consumed" until we are done color converting and emitting it.
  172995. */
  172996. METHODDEF(void)
  172997. fullsize_upsample (j_decompress_ptr, jpeg_component_info *,
  172998. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  172999. {
  173000. *output_data_ptr = input_data;
  173001. }
  173002. /*
  173003. * This is a no-op version used for "uninteresting" components.
  173004. * These components will not be referenced by color conversion.
  173005. */
  173006. METHODDEF(void)
  173007. noop_upsample (j_decompress_ptr, jpeg_component_info *,
  173008. JSAMPARRAY, JSAMPARRAY * output_data_ptr)
  173009. {
  173010. *output_data_ptr = NULL; /* safety check */
  173011. }
  173012. /*
  173013. * This version handles any integral sampling ratios.
  173014. * This is not used for typical JPEG files, so it need not be fast.
  173015. * Nor, for that matter, is it particularly accurate: the algorithm is
  173016. * simple replication of the input pixel onto the corresponding output
  173017. * pixels. The hi-falutin sampling literature refers to this as a
  173018. * "box filter". A box filter tends to introduce visible artifacts,
  173019. * so if you are actually going to use 3:1 or 4:1 sampling ratios
  173020. * you would be well advised to improve this code.
  173021. */
  173022. METHODDEF(void)
  173023. int_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173024. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173025. {
  173026. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173027. JSAMPARRAY output_data = *output_data_ptr;
  173028. register JSAMPROW inptr, outptr;
  173029. register JSAMPLE invalue;
  173030. register int h;
  173031. JSAMPROW outend;
  173032. int h_expand, v_expand;
  173033. int inrow, outrow;
  173034. h_expand = upsample->h_expand[compptr->component_index];
  173035. v_expand = upsample->v_expand[compptr->component_index];
  173036. inrow = outrow = 0;
  173037. while (outrow < cinfo->max_v_samp_factor) {
  173038. /* Generate one output row with proper horizontal expansion */
  173039. inptr = input_data[inrow];
  173040. outptr = output_data[outrow];
  173041. outend = outptr + cinfo->output_width;
  173042. while (outptr < outend) {
  173043. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173044. for (h = h_expand; h > 0; h--) {
  173045. *outptr++ = invalue;
  173046. }
  173047. }
  173048. /* Generate any additional output rows by duplicating the first one */
  173049. if (v_expand > 1) {
  173050. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  173051. v_expand-1, cinfo->output_width);
  173052. }
  173053. inrow++;
  173054. outrow += v_expand;
  173055. }
  173056. }
  173057. /*
  173058. * Fast processing for the common case of 2:1 horizontal and 1:1 vertical.
  173059. * It's still a box filter.
  173060. */
  173061. METHODDEF(void)
  173062. h2v1_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  173063. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173064. {
  173065. JSAMPARRAY output_data = *output_data_ptr;
  173066. register JSAMPROW inptr, outptr;
  173067. register JSAMPLE invalue;
  173068. JSAMPROW outend;
  173069. int inrow;
  173070. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  173071. inptr = input_data[inrow];
  173072. outptr = output_data[inrow];
  173073. outend = outptr + cinfo->output_width;
  173074. while (outptr < outend) {
  173075. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173076. *outptr++ = invalue;
  173077. *outptr++ = invalue;
  173078. }
  173079. }
  173080. }
  173081. /*
  173082. * Fast processing for the common case of 2:1 horizontal and 2:1 vertical.
  173083. * It's still a box filter.
  173084. */
  173085. METHODDEF(void)
  173086. h2v2_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  173087. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173088. {
  173089. JSAMPARRAY output_data = *output_data_ptr;
  173090. register JSAMPROW inptr, outptr;
  173091. register JSAMPLE invalue;
  173092. JSAMPROW outend;
  173093. int inrow, outrow;
  173094. inrow = outrow = 0;
  173095. while (outrow < cinfo->max_v_samp_factor) {
  173096. inptr = input_data[inrow];
  173097. outptr = output_data[outrow];
  173098. outend = outptr + cinfo->output_width;
  173099. while (outptr < outend) {
  173100. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173101. *outptr++ = invalue;
  173102. *outptr++ = invalue;
  173103. }
  173104. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  173105. 1, cinfo->output_width);
  173106. inrow++;
  173107. outrow += 2;
  173108. }
  173109. }
  173110. /*
  173111. * Fancy processing for the common case of 2:1 horizontal and 1:1 vertical.
  173112. *
  173113. * The upsampling algorithm is linear interpolation between pixel centers,
  173114. * also known as a "triangle filter". This is a good compromise between
  173115. * speed and visual quality. The centers of the output pixels are 1/4 and 3/4
  173116. * of the way between input pixel centers.
  173117. *
  173118. * A note about the "bias" calculations: when rounding fractional values to
  173119. * integer, we do not want to always round 0.5 up to the next integer.
  173120. * If we did that, we'd introduce a noticeable bias towards larger values.
  173121. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  173122. * alternate pixel locations (a simple ordered dither pattern).
  173123. */
  173124. METHODDEF(void)
  173125. h2v1_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173126. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173127. {
  173128. JSAMPARRAY output_data = *output_data_ptr;
  173129. register JSAMPROW inptr, outptr;
  173130. register int invalue;
  173131. register JDIMENSION colctr;
  173132. int inrow;
  173133. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  173134. inptr = input_data[inrow];
  173135. outptr = output_data[inrow];
  173136. /* Special case for first column */
  173137. invalue = GETJSAMPLE(*inptr++);
  173138. *outptr++ = (JSAMPLE) invalue;
  173139. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(*inptr) + 2) >> 2);
  173140. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  173141. /* General case: 3/4 * nearer pixel + 1/4 * further pixel */
  173142. invalue = GETJSAMPLE(*inptr++) * 3;
  173143. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(inptr[-2]) + 1) >> 2);
  173144. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(*inptr) + 2) >> 2);
  173145. }
  173146. /* Special case for last column */
  173147. invalue = GETJSAMPLE(*inptr);
  173148. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(inptr[-1]) + 1) >> 2);
  173149. *outptr++ = (JSAMPLE) invalue;
  173150. }
  173151. }
  173152. /*
  173153. * Fancy processing for the common case of 2:1 horizontal and 2:1 vertical.
  173154. * Again a triangle filter; see comments for h2v1 case, above.
  173155. *
  173156. * It is OK for us to reference the adjacent input rows because we demanded
  173157. * context from the main buffer controller (see initialization code).
  173158. */
  173159. METHODDEF(void)
  173160. h2v2_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173161. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173162. {
  173163. JSAMPARRAY output_data = *output_data_ptr;
  173164. register JSAMPROW inptr0, inptr1, outptr;
  173165. #if BITS_IN_JSAMPLE == 8
  173166. register int thiscolsum, lastcolsum, nextcolsum;
  173167. #else
  173168. register INT32 thiscolsum, lastcolsum, nextcolsum;
  173169. #endif
  173170. register JDIMENSION colctr;
  173171. int inrow, outrow, v;
  173172. inrow = outrow = 0;
  173173. while (outrow < cinfo->max_v_samp_factor) {
  173174. for (v = 0; v < 2; v++) {
  173175. /* inptr0 points to nearest input row, inptr1 points to next nearest */
  173176. inptr0 = input_data[inrow];
  173177. if (v == 0) /* next nearest is row above */
  173178. inptr1 = input_data[inrow-1];
  173179. else /* next nearest is row below */
  173180. inptr1 = input_data[inrow+1];
  173181. outptr = output_data[outrow++];
  173182. /* Special case for first column */
  173183. thiscolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  173184. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  173185. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 8) >> 4);
  173186. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  173187. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  173188. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  173189. /* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */
  173190. /* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */
  173191. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  173192. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  173193. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  173194. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  173195. }
  173196. /* Special case for last column */
  173197. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  173198. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 7) >> 4);
  173199. }
  173200. inrow++;
  173201. }
  173202. }
  173203. /*
  173204. * Module initialization routine for upsampling.
  173205. */
  173206. GLOBAL(void)
  173207. jinit_upsampler (j_decompress_ptr cinfo)
  173208. {
  173209. my_upsample_ptr2 upsample;
  173210. int ci;
  173211. jpeg_component_info * compptr;
  173212. boolean need_buffer, do_fancy;
  173213. int h_in_group, v_in_group, h_out_group, v_out_group;
  173214. upsample = (my_upsample_ptr2)
  173215. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173216. SIZEOF(my_upsampler2));
  173217. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  173218. upsample->pub.start_pass = start_pass_upsample;
  173219. upsample->pub.upsample = sep_upsample;
  173220. upsample->pub.need_context_rows = FALSE; /* until we find out differently */
  173221. if (cinfo->CCIR601_sampling) /* this isn't supported */
  173222. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  173223. /* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1,
  173224. * so don't ask for it.
  173225. */
  173226. do_fancy = cinfo->do_fancy_upsampling && cinfo->min_DCT_scaled_size > 1;
  173227. /* Verify we can handle the sampling factors, select per-component methods,
  173228. * and create storage as needed.
  173229. */
  173230. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  173231. ci++, compptr++) {
  173232. /* Compute size of an "input group" after IDCT scaling. This many samples
  173233. * are to be converted to max_h_samp_factor * max_v_samp_factor pixels.
  173234. */
  173235. h_in_group = (compptr->h_samp_factor * compptr->DCT_scaled_size) /
  173236. cinfo->min_DCT_scaled_size;
  173237. v_in_group = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  173238. cinfo->min_DCT_scaled_size;
  173239. h_out_group = cinfo->max_h_samp_factor;
  173240. v_out_group = cinfo->max_v_samp_factor;
  173241. upsample->rowgroup_height[ci] = v_in_group; /* save for use later */
  173242. need_buffer = TRUE;
  173243. if (! compptr->component_needed) {
  173244. /* Don't bother to upsample an uninteresting component. */
  173245. upsample->methods[ci] = noop_upsample;
  173246. need_buffer = FALSE;
  173247. } else if (h_in_group == h_out_group && v_in_group == v_out_group) {
  173248. /* Fullsize components can be processed without any work. */
  173249. upsample->methods[ci] = fullsize_upsample;
  173250. need_buffer = FALSE;
  173251. } else if (h_in_group * 2 == h_out_group &&
  173252. v_in_group == v_out_group) {
  173253. /* Special cases for 2h1v upsampling */
  173254. if (do_fancy && compptr->downsampled_width > 2)
  173255. upsample->methods[ci] = h2v1_fancy_upsample;
  173256. else
  173257. upsample->methods[ci] = h2v1_upsample;
  173258. } else if (h_in_group * 2 == h_out_group &&
  173259. v_in_group * 2 == v_out_group) {
  173260. /* Special cases for 2h2v upsampling */
  173261. if (do_fancy && compptr->downsampled_width > 2) {
  173262. upsample->methods[ci] = h2v2_fancy_upsample;
  173263. upsample->pub.need_context_rows = TRUE;
  173264. } else
  173265. upsample->methods[ci] = h2v2_upsample;
  173266. } else if ((h_out_group % h_in_group) == 0 &&
  173267. (v_out_group % v_in_group) == 0) {
  173268. /* Generic integral-factors upsampling method */
  173269. upsample->methods[ci] = int_upsample;
  173270. upsample->h_expand[ci] = (UINT8) (h_out_group / h_in_group);
  173271. upsample->v_expand[ci] = (UINT8) (v_out_group / v_in_group);
  173272. } else
  173273. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  173274. if (need_buffer) {
  173275. upsample->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  173276. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173277. (JDIMENSION) jround_up((long) cinfo->output_width,
  173278. (long) cinfo->max_h_samp_factor),
  173279. (JDIMENSION) cinfo->max_v_samp_factor);
  173280. }
  173281. }
  173282. }
  173283. /*** End of inlined file: jdsample.c ***/
  173284. /*** Start of inlined file: jdtrans.c ***/
  173285. #define JPEG_INTERNALS
  173286. /* Forward declarations */
  173287. LOCAL(void) transdecode_master_selection JPP((j_decompress_ptr cinfo));
  173288. /*
  173289. * Read the coefficient arrays from a JPEG file.
  173290. * jpeg_read_header must be completed before calling this.
  173291. *
  173292. * The entire image is read into a set of virtual coefficient-block arrays,
  173293. * one per component. The return value is a pointer to the array of
  173294. * virtual-array descriptors. These can be manipulated directly via the
  173295. * JPEG memory manager, or handed off to jpeg_write_coefficients().
  173296. * To release the memory occupied by the virtual arrays, call
  173297. * jpeg_finish_decompress() when done with the data.
  173298. *
  173299. * An alternative usage is to simply obtain access to the coefficient arrays
  173300. * during a buffered-image-mode decompression operation. This is allowed
  173301. * after any jpeg_finish_output() call. The arrays can be accessed until
  173302. * jpeg_finish_decompress() is called. (Note that any call to the library
  173303. * may reposition the arrays, so don't rely on access_virt_barray() results
  173304. * to stay valid across library calls.)
  173305. *
  173306. * Returns NULL if suspended. This case need be checked only if
  173307. * a suspending data source is used.
  173308. */
  173309. GLOBAL(jvirt_barray_ptr *)
  173310. jpeg_read_coefficients (j_decompress_ptr cinfo)
  173311. {
  173312. if (cinfo->global_state == DSTATE_READY) {
  173313. /* First call: initialize active modules */
  173314. transdecode_master_selection(cinfo);
  173315. cinfo->global_state = DSTATE_RDCOEFS;
  173316. }
  173317. if (cinfo->global_state == DSTATE_RDCOEFS) {
  173318. /* Absorb whole file into the coef buffer */
  173319. for (;;) {
  173320. int retcode;
  173321. /* Call progress monitor hook if present */
  173322. if (cinfo->progress != NULL)
  173323. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  173324. /* Absorb some more input */
  173325. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  173326. if (retcode == JPEG_SUSPENDED)
  173327. return NULL;
  173328. if (retcode == JPEG_REACHED_EOI)
  173329. break;
  173330. /* Advance progress counter if appropriate */
  173331. if (cinfo->progress != NULL &&
  173332. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  173333. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  173334. /* startup underestimated number of scans; ratchet up one scan */
  173335. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  173336. }
  173337. }
  173338. }
  173339. /* Set state so that jpeg_finish_decompress does the right thing */
  173340. cinfo->global_state = DSTATE_STOPPING;
  173341. }
  173342. /* At this point we should be in state DSTATE_STOPPING if being used
  173343. * standalone, or in state DSTATE_BUFIMAGE if being invoked to get access
  173344. * to the coefficients during a full buffered-image-mode decompression.
  173345. */
  173346. if ((cinfo->global_state == DSTATE_STOPPING ||
  173347. cinfo->global_state == DSTATE_BUFIMAGE) && cinfo->buffered_image) {
  173348. return cinfo->coef->coef_arrays;
  173349. }
  173350. /* Oops, improper usage */
  173351. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  173352. return NULL; /* keep compiler happy */
  173353. }
  173354. /*
  173355. * Master selection of decompression modules for transcoding.
  173356. * This substitutes for jdmaster.c's initialization of the full decompressor.
  173357. */
  173358. LOCAL(void)
  173359. transdecode_master_selection (j_decompress_ptr cinfo)
  173360. {
  173361. /* This is effectively a buffered-image operation. */
  173362. cinfo->buffered_image = TRUE;
  173363. /* Entropy decoding: either Huffman or arithmetic coding. */
  173364. if (cinfo->arith_code) {
  173365. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  173366. } else {
  173367. if (cinfo->progressive_mode) {
  173368. #ifdef D_PROGRESSIVE_SUPPORTED
  173369. jinit_phuff_decoder(cinfo);
  173370. #else
  173371. ERREXIT(cinfo, JERR_NOT_COMPILED);
  173372. #endif
  173373. } else
  173374. jinit_huff_decoder(cinfo);
  173375. }
  173376. /* Always get a full-image coefficient buffer. */
  173377. jinit_d_coef_controller(cinfo, TRUE);
  173378. /* We can now tell the memory manager to allocate virtual arrays. */
  173379. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  173380. /* Initialize input side of decompressor to consume first scan. */
  173381. (*cinfo->inputctl->start_input_pass) (cinfo);
  173382. /* Initialize progress monitoring. */
  173383. if (cinfo->progress != NULL) {
  173384. int nscans;
  173385. /* Estimate number of scans to set pass_limit. */
  173386. if (cinfo->progressive_mode) {
  173387. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  173388. nscans = 2 + 3 * cinfo->num_components;
  173389. } else if (cinfo->inputctl->has_multiple_scans) {
  173390. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  173391. nscans = cinfo->num_components;
  173392. } else {
  173393. nscans = 1;
  173394. }
  173395. cinfo->progress->pass_counter = 0L;
  173396. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  173397. cinfo->progress->completed_passes = 0;
  173398. cinfo->progress->total_passes = 1;
  173399. }
  173400. }
  173401. /*** End of inlined file: jdtrans.c ***/
  173402. /*** Start of inlined file: jfdctflt.c ***/
  173403. #define JPEG_INTERNALS
  173404. #ifdef DCT_FLOAT_SUPPORTED
  173405. /*
  173406. * This module is specialized to the case DCTSIZE = 8.
  173407. */
  173408. #if DCTSIZE != 8
  173409. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  173410. #endif
  173411. /*
  173412. * Perform the forward DCT on one block of samples.
  173413. */
  173414. GLOBAL(void)
  173415. jpeg_fdct_float (FAST_FLOAT * data)
  173416. {
  173417. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  173418. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  173419. FAST_FLOAT z1, z2, z3, z4, z5, z11, z13;
  173420. FAST_FLOAT *dataptr;
  173421. int ctr;
  173422. /* Pass 1: process rows. */
  173423. dataptr = data;
  173424. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  173425. tmp0 = dataptr[0] + dataptr[7];
  173426. tmp7 = dataptr[0] - dataptr[7];
  173427. tmp1 = dataptr[1] + dataptr[6];
  173428. tmp6 = dataptr[1] - dataptr[6];
  173429. tmp2 = dataptr[2] + dataptr[5];
  173430. tmp5 = dataptr[2] - dataptr[5];
  173431. tmp3 = dataptr[3] + dataptr[4];
  173432. tmp4 = dataptr[3] - dataptr[4];
  173433. /* Even part */
  173434. tmp10 = tmp0 + tmp3; /* phase 2 */
  173435. tmp13 = tmp0 - tmp3;
  173436. tmp11 = tmp1 + tmp2;
  173437. tmp12 = tmp1 - tmp2;
  173438. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  173439. dataptr[4] = tmp10 - tmp11;
  173440. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  173441. dataptr[2] = tmp13 + z1; /* phase 5 */
  173442. dataptr[6] = tmp13 - z1;
  173443. /* Odd part */
  173444. tmp10 = tmp4 + tmp5; /* phase 2 */
  173445. tmp11 = tmp5 + tmp6;
  173446. tmp12 = tmp6 + tmp7;
  173447. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  173448. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  173449. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  173450. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  173451. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  173452. z11 = tmp7 + z3; /* phase 5 */
  173453. z13 = tmp7 - z3;
  173454. dataptr[5] = z13 + z2; /* phase 6 */
  173455. dataptr[3] = z13 - z2;
  173456. dataptr[1] = z11 + z4;
  173457. dataptr[7] = z11 - z4;
  173458. dataptr += DCTSIZE; /* advance pointer to next row */
  173459. }
  173460. /* Pass 2: process columns. */
  173461. dataptr = data;
  173462. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  173463. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  173464. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  173465. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  173466. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  173467. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  173468. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  173469. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  173470. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  173471. /* Even part */
  173472. tmp10 = tmp0 + tmp3; /* phase 2 */
  173473. tmp13 = tmp0 - tmp3;
  173474. tmp11 = tmp1 + tmp2;
  173475. tmp12 = tmp1 - tmp2;
  173476. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  173477. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  173478. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  173479. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  173480. dataptr[DCTSIZE*6] = tmp13 - z1;
  173481. /* Odd part */
  173482. tmp10 = tmp4 + tmp5; /* phase 2 */
  173483. tmp11 = tmp5 + tmp6;
  173484. tmp12 = tmp6 + tmp7;
  173485. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  173486. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  173487. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  173488. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  173489. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  173490. z11 = tmp7 + z3; /* phase 5 */
  173491. z13 = tmp7 - z3;
  173492. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  173493. dataptr[DCTSIZE*3] = z13 - z2;
  173494. dataptr[DCTSIZE*1] = z11 + z4;
  173495. dataptr[DCTSIZE*7] = z11 - z4;
  173496. dataptr++; /* advance pointer to next column */
  173497. }
  173498. }
  173499. #endif /* DCT_FLOAT_SUPPORTED */
  173500. /*** End of inlined file: jfdctflt.c ***/
  173501. /*** Start of inlined file: jfdctint.c ***/
  173502. #define JPEG_INTERNALS
  173503. #ifdef DCT_ISLOW_SUPPORTED
  173504. /*
  173505. * This module is specialized to the case DCTSIZE = 8.
  173506. */
  173507. #if DCTSIZE != 8
  173508. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  173509. #endif
  173510. /*
  173511. * The poop on this scaling stuff is as follows:
  173512. *
  173513. * Each 1-D DCT step produces outputs which are a factor of sqrt(N)
  173514. * larger than the true DCT outputs. The final outputs are therefore
  173515. * a factor of N larger than desired; since N=8 this can be cured by
  173516. * a simple right shift at the end of the algorithm. The advantage of
  173517. * this arrangement is that we save two multiplications per 1-D DCT,
  173518. * because the y0 and y4 outputs need not be divided by sqrt(N).
  173519. * In the IJG code, this factor of 8 is removed by the quantization step
  173520. * (in jcdctmgr.c), NOT in this module.
  173521. *
  173522. * We have to do addition and subtraction of the integer inputs, which
  173523. * is no problem, and multiplication by fractional constants, which is
  173524. * a problem to do in integer arithmetic. We multiply all the constants
  173525. * by CONST_SCALE and convert them to integer constants (thus retaining
  173526. * CONST_BITS bits of precision in the constants). After doing a
  173527. * multiplication we have to divide the product by CONST_SCALE, with proper
  173528. * rounding, to produce the correct output. This division can be done
  173529. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  173530. * as long as possible so that partial sums can be added together with
  173531. * full fractional precision.
  173532. *
  173533. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  173534. * they are represented to better-than-integral precision. These outputs
  173535. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  173536. * with the recommended scaling. (For 12-bit sample data, the intermediate
  173537. * array is INT32 anyway.)
  173538. *
  173539. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  173540. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  173541. * shows that the values given below are the most effective.
  173542. */
  173543. #if BITS_IN_JSAMPLE == 8
  173544. #define CONST_BITS 13
  173545. #define PASS1_BITS 2
  173546. #else
  173547. #define CONST_BITS 13
  173548. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  173549. #endif
  173550. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  173551. * causing a lot of useless floating-point operations at run time.
  173552. * To get around this we use the following pre-calculated constants.
  173553. * If you change CONST_BITS you may want to add appropriate values.
  173554. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  173555. */
  173556. #if CONST_BITS == 13
  173557. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  173558. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  173559. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  173560. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  173561. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  173562. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  173563. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  173564. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  173565. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  173566. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  173567. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  173568. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  173569. #else
  173570. #define FIX_0_298631336 FIX(0.298631336)
  173571. #define FIX_0_390180644 FIX(0.390180644)
  173572. #define FIX_0_541196100 FIX(0.541196100)
  173573. #define FIX_0_765366865 FIX(0.765366865)
  173574. #define FIX_0_899976223 FIX(0.899976223)
  173575. #define FIX_1_175875602 FIX(1.175875602)
  173576. #define FIX_1_501321110 FIX(1.501321110)
  173577. #define FIX_1_847759065 FIX(1.847759065)
  173578. #define FIX_1_961570560 FIX(1.961570560)
  173579. #define FIX_2_053119869 FIX(2.053119869)
  173580. #define FIX_2_562915447 FIX(2.562915447)
  173581. #define FIX_3_072711026 FIX(3.072711026)
  173582. #endif
  173583. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  173584. * For 8-bit samples with the recommended scaling, all the variable
  173585. * and constant values involved are no more than 16 bits wide, so a
  173586. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  173587. * For 12-bit samples, a full 32-bit multiplication will be needed.
  173588. */
  173589. #if BITS_IN_JSAMPLE == 8
  173590. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  173591. #else
  173592. #define MULTIPLY(var,const) ((var) * (const))
  173593. #endif
  173594. /*
  173595. * Perform the forward DCT on one block of samples.
  173596. */
  173597. GLOBAL(void)
  173598. jpeg_fdct_islow (DCTELEM * data)
  173599. {
  173600. INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  173601. INT32 tmp10, tmp11, tmp12, tmp13;
  173602. INT32 z1, z2, z3, z4, z5;
  173603. DCTELEM *dataptr;
  173604. int ctr;
  173605. SHIFT_TEMPS
  173606. /* Pass 1: process rows. */
  173607. /* Note results are scaled up by sqrt(8) compared to a true DCT; */
  173608. /* furthermore, we scale the results by 2**PASS1_BITS. */
  173609. dataptr = data;
  173610. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  173611. tmp0 = dataptr[0] + dataptr[7];
  173612. tmp7 = dataptr[0] - dataptr[7];
  173613. tmp1 = dataptr[1] + dataptr[6];
  173614. tmp6 = dataptr[1] - dataptr[6];
  173615. tmp2 = dataptr[2] + dataptr[5];
  173616. tmp5 = dataptr[2] - dataptr[5];
  173617. tmp3 = dataptr[3] + dataptr[4];
  173618. tmp4 = dataptr[3] - dataptr[4];
  173619. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  173620. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  173621. */
  173622. tmp10 = tmp0 + tmp3;
  173623. tmp13 = tmp0 - tmp3;
  173624. tmp11 = tmp1 + tmp2;
  173625. tmp12 = tmp1 - tmp2;
  173626. dataptr[0] = (DCTELEM) ((tmp10 + tmp11) << PASS1_BITS);
  173627. dataptr[4] = (DCTELEM) ((tmp10 - tmp11) << PASS1_BITS);
  173628. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  173629. dataptr[2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  173630. CONST_BITS-PASS1_BITS);
  173631. dataptr[6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  173632. CONST_BITS-PASS1_BITS);
  173633. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  173634. * cK represents cos(K*pi/16).
  173635. * i0..i3 in the paper are tmp4..tmp7 here.
  173636. */
  173637. z1 = tmp4 + tmp7;
  173638. z2 = tmp5 + tmp6;
  173639. z3 = tmp4 + tmp6;
  173640. z4 = tmp5 + tmp7;
  173641. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  173642. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  173643. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  173644. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  173645. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  173646. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  173647. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  173648. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  173649. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  173650. z3 += z5;
  173651. z4 += z5;
  173652. dataptr[7] = (DCTELEM) DESCALE(tmp4 + z1 + z3, CONST_BITS-PASS1_BITS);
  173653. dataptr[5] = (DCTELEM) DESCALE(tmp5 + z2 + z4, CONST_BITS-PASS1_BITS);
  173654. dataptr[3] = (DCTELEM) DESCALE(tmp6 + z2 + z3, CONST_BITS-PASS1_BITS);
  173655. dataptr[1] = (DCTELEM) DESCALE(tmp7 + z1 + z4, CONST_BITS-PASS1_BITS);
  173656. dataptr += DCTSIZE; /* advance pointer to next row */
  173657. }
  173658. /* Pass 2: process columns.
  173659. * We remove the PASS1_BITS scaling, but leave the results scaled up
  173660. * by an overall factor of 8.
  173661. */
  173662. dataptr = data;
  173663. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  173664. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  173665. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  173666. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  173667. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  173668. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  173669. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  173670. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  173671. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  173672. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  173673. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  173674. */
  173675. tmp10 = tmp0 + tmp3;
  173676. tmp13 = tmp0 - tmp3;
  173677. tmp11 = tmp1 + tmp2;
  173678. tmp12 = tmp1 - tmp2;
  173679. dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(tmp10 + tmp11, PASS1_BITS);
  173680. dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(tmp10 - tmp11, PASS1_BITS);
  173681. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  173682. dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  173683. CONST_BITS+PASS1_BITS);
  173684. dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  173685. CONST_BITS+PASS1_BITS);
  173686. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  173687. * cK represents cos(K*pi/16).
  173688. * i0..i3 in the paper are tmp4..tmp7 here.
  173689. */
  173690. z1 = tmp4 + tmp7;
  173691. z2 = tmp5 + tmp6;
  173692. z3 = tmp4 + tmp6;
  173693. z4 = tmp5 + tmp7;
  173694. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  173695. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  173696. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  173697. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  173698. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  173699. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  173700. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  173701. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  173702. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  173703. z3 += z5;
  173704. z4 += z5;
  173705. dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp4 + z1 + z3,
  173706. CONST_BITS+PASS1_BITS);
  173707. dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp5 + z2 + z4,
  173708. CONST_BITS+PASS1_BITS);
  173709. dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp6 + z2 + z3,
  173710. CONST_BITS+PASS1_BITS);
  173711. dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp7 + z1 + z4,
  173712. CONST_BITS+PASS1_BITS);
  173713. dataptr++; /* advance pointer to next column */
  173714. }
  173715. }
  173716. #endif /* DCT_ISLOW_SUPPORTED */
  173717. /*** End of inlined file: jfdctint.c ***/
  173718. #undef CONST_BITS
  173719. #undef MULTIPLY
  173720. #undef FIX_0_541196100
  173721. /*** Start of inlined file: jfdctfst.c ***/
  173722. #define JPEG_INTERNALS
  173723. #ifdef DCT_IFAST_SUPPORTED
  173724. /*
  173725. * This module is specialized to the case DCTSIZE = 8.
  173726. */
  173727. #if DCTSIZE != 8
  173728. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  173729. #endif
  173730. /* Scaling decisions are generally the same as in the LL&M algorithm;
  173731. * see jfdctint.c for more details. However, we choose to descale
  173732. * (right shift) multiplication products as soon as they are formed,
  173733. * rather than carrying additional fractional bits into subsequent additions.
  173734. * This compromises accuracy slightly, but it lets us save a few shifts.
  173735. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  173736. * everywhere except in the multiplications proper; this saves a good deal
  173737. * of work on 16-bit-int machines.
  173738. *
  173739. * Again to save a few shifts, the intermediate results between pass 1 and
  173740. * pass 2 are not upscaled, but are represented only to integral precision.
  173741. *
  173742. * A final compromise is to represent the multiplicative constants to only
  173743. * 8 fractional bits, rather than 13. This saves some shifting work on some
  173744. * machines, and may also reduce the cost of multiplication (since there
  173745. * are fewer one-bits in the constants).
  173746. */
  173747. #define CONST_BITS 8
  173748. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  173749. * causing a lot of useless floating-point operations at run time.
  173750. * To get around this we use the following pre-calculated constants.
  173751. * If you change CONST_BITS you may want to add appropriate values.
  173752. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  173753. */
  173754. #if CONST_BITS == 8
  173755. #define FIX_0_382683433 ((INT32) 98) /* FIX(0.382683433) */
  173756. #define FIX_0_541196100 ((INT32) 139) /* FIX(0.541196100) */
  173757. #define FIX_0_707106781 ((INT32) 181) /* FIX(0.707106781) */
  173758. #define FIX_1_306562965 ((INT32) 334) /* FIX(1.306562965) */
  173759. #else
  173760. #define FIX_0_382683433 FIX(0.382683433)
  173761. #define FIX_0_541196100 FIX(0.541196100)
  173762. #define FIX_0_707106781 FIX(0.707106781)
  173763. #define FIX_1_306562965 FIX(1.306562965)
  173764. #endif
  173765. /* We can gain a little more speed, with a further compromise in accuracy,
  173766. * by omitting the addition in a descaling shift. This yields an incorrectly
  173767. * rounded result half the time...
  173768. */
  173769. #ifndef USE_ACCURATE_ROUNDING
  173770. #undef DESCALE
  173771. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  173772. #endif
  173773. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  173774. * descale to yield a DCTELEM result.
  173775. */
  173776. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  173777. /*
  173778. * Perform the forward DCT on one block of samples.
  173779. */
  173780. GLOBAL(void)
  173781. jpeg_fdct_ifast (DCTELEM * data)
  173782. {
  173783. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  173784. DCTELEM tmp10, tmp11, tmp12, tmp13;
  173785. DCTELEM z1, z2, z3, z4, z5, z11, z13;
  173786. DCTELEM *dataptr;
  173787. int ctr;
  173788. SHIFT_TEMPS
  173789. /* Pass 1: process rows. */
  173790. dataptr = data;
  173791. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  173792. tmp0 = dataptr[0] + dataptr[7];
  173793. tmp7 = dataptr[0] - dataptr[7];
  173794. tmp1 = dataptr[1] + dataptr[6];
  173795. tmp6 = dataptr[1] - dataptr[6];
  173796. tmp2 = dataptr[2] + dataptr[5];
  173797. tmp5 = dataptr[2] - dataptr[5];
  173798. tmp3 = dataptr[3] + dataptr[4];
  173799. tmp4 = dataptr[3] - dataptr[4];
  173800. /* Even part */
  173801. tmp10 = tmp0 + tmp3; /* phase 2 */
  173802. tmp13 = tmp0 - tmp3;
  173803. tmp11 = tmp1 + tmp2;
  173804. tmp12 = tmp1 - tmp2;
  173805. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  173806. dataptr[4] = tmp10 - tmp11;
  173807. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  173808. dataptr[2] = tmp13 + z1; /* phase 5 */
  173809. dataptr[6] = tmp13 - z1;
  173810. /* Odd part */
  173811. tmp10 = tmp4 + tmp5; /* phase 2 */
  173812. tmp11 = tmp5 + tmp6;
  173813. tmp12 = tmp6 + tmp7;
  173814. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  173815. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  173816. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  173817. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  173818. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  173819. z11 = tmp7 + z3; /* phase 5 */
  173820. z13 = tmp7 - z3;
  173821. dataptr[5] = z13 + z2; /* phase 6 */
  173822. dataptr[3] = z13 - z2;
  173823. dataptr[1] = z11 + z4;
  173824. dataptr[7] = z11 - z4;
  173825. dataptr += DCTSIZE; /* advance pointer to next row */
  173826. }
  173827. /* Pass 2: process columns. */
  173828. dataptr = data;
  173829. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  173830. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  173831. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  173832. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  173833. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  173834. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  173835. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  173836. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  173837. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  173838. /* Even part */
  173839. tmp10 = tmp0 + tmp3; /* phase 2 */
  173840. tmp13 = tmp0 - tmp3;
  173841. tmp11 = tmp1 + tmp2;
  173842. tmp12 = tmp1 - tmp2;
  173843. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  173844. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  173845. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  173846. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  173847. dataptr[DCTSIZE*6] = tmp13 - z1;
  173848. /* Odd part */
  173849. tmp10 = tmp4 + tmp5; /* phase 2 */
  173850. tmp11 = tmp5 + tmp6;
  173851. tmp12 = tmp6 + tmp7;
  173852. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  173853. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  173854. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  173855. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  173856. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  173857. z11 = tmp7 + z3; /* phase 5 */
  173858. z13 = tmp7 - z3;
  173859. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  173860. dataptr[DCTSIZE*3] = z13 - z2;
  173861. dataptr[DCTSIZE*1] = z11 + z4;
  173862. dataptr[DCTSIZE*7] = z11 - z4;
  173863. dataptr++; /* advance pointer to next column */
  173864. }
  173865. }
  173866. #endif /* DCT_IFAST_SUPPORTED */
  173867. /*** End of inlined file: jfdctfst.c ***/
  173868. #undef FIX_0_541196100
  173869. /*** Start of inlined file: jidctflt.c ***/
  173870. #define JPEG_INTERNALS
  173871. #ifdef DCT_FLOAT_SUPPORTED
  173872. /*
  173873. * This module is specialized to the case DCTSIZE = 8.
  173874. */
  173875. #if DCTSIZE != 8
  173876. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  173877. #endif
  173878. /* Dequantize a coefficient by multiplying it by the multiplier-table
  173879. * entry; produce a float result.
  173880. */
  173881. #define DEQUANTIZE(coef,quantval) (((FAST_FLOAT) (coef)) * (quantval))
  173882. /*
  173883. * Perform dequantization and inverse DCT on one block of coefficients.
  173884. */
  173885. GLOBAL(void)
  173886. jpeg_idct_float (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173887. JCOEFPTR coef_block,
  173888. JSAMPARRAY output_buf, JDIMENSION output_col)
  173889. {
  173890. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  173891. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  173892. FAST_FLOAT z5, z10, z11, z12, z13;
  173893. JCOEFPTR inptr;
  173894. FLOAT_MULT_TYPE * quantptr;
  173895. FAST_FLOAT * wsptr;
  173896. JSAMPROW outptr;
  173897. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  173898. int ctr;
  173899. FAST_FLOAT workspace[DCTSIZE2]; /* buffers data between passes */
  173900. SHIFT_TEMPS
  173901. /* Pass 1: process columns from input, store into work array. */
  173902. inptr = coef_block;
  173903. quantptr = (FLOAT_MULT_TYPE *) compptr->dct_table;
  173904. wsptr = workspace;
  173905. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  173906. /* Due to quantization, we will usually find that many of the input
  173907. * coefficients are zero, especially the AC terms. We can exploit this
  173908. * by short-circuiting the IDCT calculation for any column in which all
  173909. * the AC terms are zero. In that case each output is equal to the
  173910. * DC coefficient (with scale factor as needed).
  173911. * With typical images and quantization tables, half or more of the
  173912. * column DCT calculations can be simplified this way.
  173913. */
  173914. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  173915. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  173916. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  173917. inptr[DCTSIZE*7] == 0) {
  173918. /* AC terms all zero */
  173919. FAST_FLOAT dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  173920. wsptr[DCTSIZE*0] = dcval;
  173921. wsptr[DCTSIZE*1] = dcval;
  173922. wsptr[DCTSIZE*2] = dcval;
  173923. wsptr[DCTSIZE*3] = dcval;
  173924. wsptr[DCTSIZE*4] = dcval;
  173925. wsptr[DCTSIZE*5] = dcval;
  173926. wsptr[DCTSIZE*6] = dcval;
  173927. wsptr[DCTSIZE*7] = dcval;
  173928. inptr++; /* advance pointers to next column */
  173929. quantptr++;
  173930. wsptr++;
  173931. continue;
  173932. }
  173933. /* Even part */
  173934. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  173935. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  173936. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  173937. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  173938. tmp10 = tmp0 + tmp2; /* phase 3 */
  173939. tmp11 = tmp0 - tmp2;
  173940. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  173941. tmp12 = (tmp1 - tmp3) * ((FAST_FLOAT) 1.414213562) - tmp13; /* 2*c4 */
  173942. tmp0 = tmp10 + tmp13; /* phase 2 */
  173943. tmp3 = tmp10 - tmp13;
  173944. tmp1 = tmp11 + tmp12;
  173945. tmp2 = tmp11 - tmp12;
  173946. /* Odd part */
  173947. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  173948. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  173949. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  173950. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  173951. z13 = tmp6 + tmp5; /* phase 6 */
  173952. z10 = tmp6 - tmp5;
  173953. z11 = tmp4 + tmp7;
  173954. z12 = tmp4 - tmp7;
  173955. tmp7 = z11 + z13; /* phase 5 */
  173956. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562); /* 2*c4 */
  173957. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  173958. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  173959. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  173960. tmp6 = tmp12 - tmp7; /* phase 2 */
  173961. tmp5 = tmp11 - tmp6;
  173962. tmp4 = tmp10 + tmp5;
  173963. wsptr[DCTSIZE*0] = tmp0 + tmp7;
  173964. wsptr[DCTSIZE*7] = tmp0 - tmp7;
  173965. wsptr[DCTSIZE*1] = tmp1 + tmp6;
  173966. wsptr[DCTSIZE*6] = tmp1 - tmp6;
  173967. wsptr[DCTSIZE*2] = tmp2 + tmp5;
  173968. wsptr[DCTSIZE*5] = tmp2 - tmp5;
  173969. wsptr[DCTSIZE*4] = tmp3 + tmp4;
  173970. wsptr[DCTSIZE*3] = tmp3 - tmp4;
  173971. inptr++; /* advance pointers to next column */
  173972. quantptr++;
  173973. wsptr++;
  173974. }
  173975. /* Pass 2: process rows from work array, store into output array. */
  173976. /* Note that we must descale the results by a factor of 8 == 2**3. */
  173977. wsptr = workspace;
  173978. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  173979. outptr = output_buf[ctr] + output_col;
  173980. /* Rows of zeroes can be exploited in the same way as we did with columns.
  173981. * However, the column calculation has created many nonzero AC terms, so
  173982. * the simplification applies less often (typically 5% to 10% of the time).
  173983. * And testing floats for zero is relatively expensive, so we don't bother.
  173984. */
  173985. /* Even part */
  173986. tmp10 = wsptr[0] + wsptr[4];
  173987. tmp11 = wsptr[0] - wsptr[4];
  173988. tmp13 = wsptr[2] + wsptr[6];
  173989. tmp12 = (wsptr[2] - wsptr[6]) * ((FAST_FLOAT) 1.414213562) - tmp13;
  173990. tmp0 = tmp10 + tmp13;
  173991. tmp3 = tmp10 - tmp13;
  173992. tmp1 = tmp11 + tmp12;
  173993. tmp2 = tmp11 - tmp12;
  173994. /* Odd part */
  173995. z13 = wsptr[5] + wsptr[3];
  173996. z10 = wsptr[5] - wsptr[3];
  173997. z11 = wsptr[1] + wsptr[7];
  173998. z12 = wsptr[1] - wsptr[7];
  173999. tmp7 = z11 + z13;
  174000. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562);
  174001. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  174002. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  174003. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  174004. tmp6 = tmp12 - tmp7;
  174005. tmp5 = tmp11 - tmp6;
  174006. tmp4 = tmp10 + tmp5;
  174007. /* Final output stage: scale down by a factor of 8 and range-limit */
  174008. outptr[0] = range_limit[(int) DESCALE((INT32) (tmp0 + tmp7), 3)
  174009. & RANGE_MASK];
  174010. outptr[7] = range_limit[(int) DESCALE((INT32) (tmp0 - tmp7), 3)
  174011. & RANGE_MASK];
  174012. outptr[1] = range_limit[(int) DESCALE((INT32) (tmp1 + tmp6), 3)
  174013. & RANGE_MASK];
  174014. outptr[6] = range_limit[(int) DESCALE((INT32) (tmp1 - tmp6), 3)
  174015. & RANGE_MASK];
  174016. outptr[2] = range_limit[(int) DESCALE((INT32) (tmp2 + tmp5), 3)
  174017. & RANGE_MASK];
  174018. outptr[5] = range_limit[(int) DESCALE((INT32) (tmp2 - tmp5), 3)
  174019. & RANGE_MASK];
  174020. outptr[4] = range_limit[(int) DESCALE((INT32) (tmp3 + tmp4), 3)
  174021. & RANGE_MASK];
  174022. outptr[3] = range_limit[(int) DESCALE((INT32) (tmp3 - tmp4), 3)
  174023. & RANGE_MASK];
  174024. wsptr += DCTSIZE; /* advance pointer to next row */
  174025. }
  174026. }
  174027. #endif /* DCT_FLOAT_SUPPORTED */
  174028. /*** End of inlined file: jidctflt.c ***/
  174029. #undef CONST_BITS
  174030. #undef FIX_1_847759065
  174031. #undef MULTIPLY
  174032. #undef DEQUANTIZE
  174033. #undef DESCALE
  174034. /*** Start of inlined file: jidctfst.c ***/
  174035. #define JPEG_INTERNALS
  174036. #ifdef DCT_IFAST_SUPPORTED
  174037. /*
  174038. * This module is specialized to the case DCTSIZE = 8.
  174039. */
  174040. #if DCTSIZE != 8
  174041. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174042. #endif
  174043. /* Scaling decisions are generally the same as in the LL&M algorithm;
  174044. * see jidctint.c for more details. However, we choose to descale
  174045. * (right shift) multiplication products as soon as they are formed,
  174046. * rather than carrying additional fractional bits into subsequent additions.
  174047. * This compromises accuracy slightly, but it lets us save a few shifts.
  174048. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  174049. * everywhere except in the multiplications proper; this saves a good deal
  174050. * of work on 16-bit-int machines.
  174051. *
  174052. * The dequantized coefficients are not integers because the AA&N scaling
  174053. * factors have been incorporated. We represent them scaled up by PASS1_BITS,
  174054. * so that the first and second IDCT rounds have the same input scaling.
  174055. * For 8-bit JSAMPLEs, we choose IFAST_SCALE_BITS = PASS1_BITS so as to
  174056. * avoid a descaling shift; this compromises accuracy rather drastically
  174057. * for small quantization table entries, but it saves a lot of shifts.
  174058. * For 12-bit JSAMPLEs, there's no hope of using 16x16 multiplies anyway,
  174059. * so we use a much larger scaling factor to preserve accuracy.
  174060. *
  174061. * A final compromise is to represent the multiplicative constants to only
  174062. * 8 fractional bits, rather than 13. This saves some shifting work on some
  174063. * machines, and may also reduce the cost of multiplication (since there
  174064. * are fewer one-bits in the constants).
  174065. */
  174066. #if BITS_IN_JSAMPLE == 8
  174067. #define CONST_BITS 8
  174068. #define PASS1_BITS 2
  174069. #else
  174070. #define CONST_BITS 8
  174071. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174072. #endif
  174073. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174074. * causing a lot of useless floating-point operations at run time.
  174075. * To get around this we use the following pre-calculated constants.
  174076. * If you change CONST_BITS you may want to add appropriate values.
  174077. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174078. */
  174079. #if CONST_BITS == 8
  174080. #define FIX_1_082392200 ((INT32) 277) /* FIX(1.082392200) */
  174081. #define FIX_1_414213562 ((INT32) 362) /* FIX(1.414213562) */
  174082. #define FIX_1_847759065 ((INT32) 473) /* FIX(1.847759065) */
  174083. #define FIX_2_613125930 ((INT32) 669) /* FIX(2.613125930) */
  174084. #else
  174085. #define FIX_1_082392200 FIX(1.082392200)
  174086. #define FIX_1_414213562 FIX(1.414213562)
  174087. #define FIX_1_847759065 FIX(1.847759065)
  174088. #define FIX_2_613125930 FIX(2.613125930)
  174089. #endif
  174090. /* We can gain a little more speed, with a further compromise in accuracy,
  174091. * by omitting the addition in a descaling shift. This yields an incorrectly
  174092. * rounded result half the time...
  174093. */
  174094. #ifndef USE_ACCURATE_ROUNDING
  174095. #undef DESCALE
  174096. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  174097. #endif
  174098. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  174099. * descale to yield a DCTELEM result.
  174100. */
  174101. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  174102. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174103. * entry; produce a DCTELEM result. For 8-bit data a 16x16->16
  174104. * multiplication will do. For 12-bit data, the multiplier table is
  174105. * declared INT32, so a 32-bit multiply will be used.
  174106. */
  174107. #if BITS_IN_JSAMPLE == 8
  174108. #define DEQUANTIZE(coef,quantval) (((IFAST_MULT_TYPE) (coef)) * (quantval))
  174109. #else
  174110. #define DEQUANTIZE(coef,quantval) \
  174111. DESCALE((coef)*(quantval), IFAST_SCALE_BITS-PASS1_BITS)
  174112. #endif
  174113. /* Like DESCALE, but applies to a DCTELEM and produces an int.
  174114. * We assume that int right shift is unsigned if INT32 right shift is.
  174115. */
  174116. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  174117. #define ISHIFT_TEMPS DCTELEM ishift_temp;
  174118. #if BITS_IN_JSAMPLE == 8
  174119. #define DCTELEMBITS 16 /* DCTELEM may be 16 or 32 bits */
  174120. #else
  174121. #define DCTELEMBITS 32 /* DCTELEM must be 32 bits */
  174122. #endif
  174123. #define IRIGHT_SHIFT(x,shft) \
  174124. ((ishift_temp = (x)) < 0 ? \
  174125. (ishift_temp >> (shft)) | ((~((DCTELEM) 0)) << (DCTELEMBITS-(shft))) : \
  174126. (ishift_temp >> (shft)))
  174127. #else
  174128. #define ISHIFT_TEMPS
  174129. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  174130. #endif
  174131. #ifdef USE_ACCURATE_ROUNDING
  174132. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT((x) + (1 << ((n)-1)), n))
  174133. #else
  174134. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT(x, n))
  174135. #endif
  174136. /*
  174137. * Perform dequantization and inverse DCT on one block of coefficients.
  174138. */
  174139. GLOBAL(void)
  174140. jpeg_idct_ifast (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174141. JCOEFPTR coef_block,
  174142. JSAMPARRAY output_buf, JDIMENSION output_col)
  174143. {
  174144. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174145. DCTELEM tmp10, tmp11, tmp12, tmp13;
  174146. DCTELEM z5, z10, z11, z12, z13;
  174147. JCOEFPTR inptr;
  174148. IFAST_MULT_TYPE * quantptr;
  174149. int * wsptr;
  174150. JSAMPROW outptr;
  174151. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174152. int ctr;
  174153. int workspace[DCTSIZE2]; /* buffers data between passes */
  174154. SHIFT_TEMPS /* for DESCALE */
  174155. ISHIFT_TEMPS /* for IDESCALE */
  174156. /* Pass 1: process columns from input, store into work array. */
  174157. inptr = coef_block;
  174158. quantptr = (IFAST_MULT_TYPE *) compptr->dct_table;
  174159. wsptr = workspace;
  174160. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  174161. /* Due to quantization, we will usually find that many of the input
  174162. * coefficients are zero, especially the AC terms. We can exploit this
  174163. * by short-circuiting the IDCT calculation for any column in which all
  174164. * the AC terms are zero. In that case each output is equal to the
  174165. * DC coefficient (with scale factor as needed).
  174166. * With typical images and quantization tables, half or more of the
  174167. * column DCT calculations can be simplified this way.
  174168. */
  174169. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  174170. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  174171. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  174172. inptr[DCTSIZE*7] == 0) {
  174173. /* AC terms all zero */
  174174. int dcval = (int) DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174175. wsptr[DCTSIZE*0] = dcval;
  174176. wsptr[DCTSIZE*1] = dcval;
  174177. wsptr[DCTSIZE*2] = dcval;
  174178. wsptr[DCTSIZE*3] = dcval;
  174179. wsptr[DCTSIZE*4] = dcval;
  174180. wsptr[DCTSIZE*5] = dcval;
  174181. wsptr[DCTSIZE*6] = dcval;
  174182. wsptr[DCTSIZE*7] = dcval;
  174183. inptr++; /* advance pointers to next column */
  174184. quantptr++;
  174185. wsptr++;
  174186. continue;
  174187. }
  174188. /* Even part */
  174189. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174190. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  174191. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  174192. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  174193. tmp10 = tmp0 + tmp2; /* phase 3 */
  174194. tmp11 = tmp0 - tmp2;
  174195. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  174196. tmp12 = MULTIPLY(tmp1 - tmp3, FIX_1_414213562) - tmp13; /* 2*c4 */
  174197. tmp0 = tmp10 + tmp13; /* phase 2 */
  174198. tmp3 = tmp10 - tmp13;
  174199. tmp1 = tmp11 + tmp12;
  174200. tmp2 = tmp11 - tmp12;
  174201. /* Odd part */
  174202. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  174203. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  174204. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  174205. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  174206. z13 = tmp6 + tmp5; /* phase 6 */
  174207. z10 = tmp6 - tmp5;
  174208. z11 = tmp4 + tmp7;
  174209. z12 = tmp4 - tmp7;
  174210. tmp7 = z11 + z13; /* phase 5 */
  174211. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  174212. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  174213. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  174214. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  174215. tmp6 = tmp12 - tmp7; /* phase 2 */
  174216. tmp5 = tmp11 - tmp6;
  174217. tmp4 = tmp10 + tmp5;
  174218. wsptr[DCTSIZE*0] = (int) (tmp0 + tmp7);
  174219. wsptr[DCTSIZE*7] = (int) (tmp0 - tmp7);
  174220. wsptr[DCTSIZE*1] = (int) (tmp1 + tmp6);
  174221. wsptr[DCTSIZE*6] = (int) (tmp1 - tmp6);
  174222. wsptr[DCTSIZE*2] = (int) (tmp2 + tmp5);
  174223. wsptr[DCTSIZE*5] = (int) (tmp2 - tmp5);
  174224. wsptr[DCTSIZE*4] = (int) (tmp3 + tmp4);
  174225. wsptr[DCTSIZE*3] = (int) (tmp3 - tmp4);
  174226. inptr++; /* advance pointers to next column */
  174227. quantptr++;
  174228. wsptr++;
  174229. }
  174230. /* Pass 2: process rows from work array, store into output array. */
  174231. /* Note that we must descale the results by a factor of 8 == 2**3, */
  174232. /* and also undo the PASS1_BITS scaling. */
  174233. wsptr = workspace;
  174234. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  174235. outptr = output_buf[ctr] + output_col;
  174236. /* Rows of zeroes can be exploited in the same way as we did with columns.
  174237. * However, the column calculation has created many nonzero AC terms, so
  174238. * the simplification applies less often (typically 5% to 10% of the time).
  174239. * On machines with very fast multiplication, it's possible that the
  174240. * test takes more time than it's worth. In that case this section
  174241. * may be commented out.
  174242. */
  174243. #ifndef NO_ZERO_ROW_TEST
  174244. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  174245. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  174246. /* AC terms all zero */
  174247. JSAMPLE dcval = range_limit[IDESCALE(wsptr[0], PASS1_BITS+3)
  174248. & RANGE_MASK];
  174249. outptr[0] = dcval;
  174250. outptr[1] = dcval;
  174251. outptr[2] = dcval;
  174252. outptr[3] = dcval;
  174253. outptr[4] = dcval;
  174254. outptr[5] = dcval;
  174255. outptr[6] = dcval;
  174256. outptr[7] = dcval;
  174257. wsptr += DCTSIZE; /* advance pointer to next row */
  174258. continue;
  174259. }
  174260. #endif
  174261. /* Even part */
  174262. tmp10 = ((DCTELEM) wsptr[0] + (DCTELEM) wsptr[4]);
  174263. tmp11 = ((DCTELEM) wsptr[0] - (DCTELEM) wsptr[4]);
  174264. tmp13 = ((DCTELEM) wsptr[2] + (DCTELEM) wsptr[6]);
  174265. tmp12 = MULTIPLY((DCTELEM) wsptr[2] - (DCTELEM) wsptr[6], FIX_1_414213562)
  174266. - tmp13;
  174267. tmp0 = tmp10 + tmp13;
  174268. tmp3 = tmp10 - tmp13;
  174269. tmp1 = tmp11 + tmp12;
  174270. tmp2 = tmp11 - tmp12;
  174271. /* Odd part */
  174272. z13 = (DCTELEM) wsptr[5] + (DCTELEM) wsptr[3];
  174273. z10 = (DCTELEM) wsptr[5] - (DCTELEM) wsptr[3];
  174274. z11 = (DCTELEM) wsptr[1] + (DCTELEM) wsptr[7];
  174275. z12 = (DCTELEM) wsptr[1] - (DCTELEM) wsptr[7];
  174276. tmp7 = z11 + z13; /* phase 5 */
  174277. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  174278. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  174279. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  174280. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  174281. tmp6 = tmp12 - tmp7; /* phase 2 */
  174282. tmp5 = tmp11 - tmp6;
  174283. tmp4 = tmp10 + tmp5;
  174284. /* Final output stage: scale down by a factor of 8 and range-limit */
  174285. outptr[0] = range_limit[IDESCALE(tmp0 + tmp7, PASS1_BITS+3)
  174286. & RANGE_MASK];
  174287. outptr[7] = range_limit[IDESCALE(tmp0 - tmp7, PASS1_BITS+3)
  174288. & RANGE_MASK];
  174289. outptr[1] = range_limit[IDESCALE(tmp1 + tmp6, PASS1_BITS+3)
  174290. & RANGE_MASK];
  174291. outptr[6] = range_limit[IDESCALE(tmp1 - tmp6, PASS1_BITS+3)
  174292. & RANGE_MASK];
  174293. outptr[2] = range_limit[IDESCALE(tmp2 + tmp5, PASS1_BITS+3)
  174294. & RANGE_MASK];
  174295. outptr[5] = range_limit[IDESCALE(tmp2 - tmp5, PASS1_BITS+3)
  174296. & RANGE_MASK];
  174297. outptr[4] = range_limit[IDESCALE(tmp3 + tmp4, PASS1_BITS+3)
  174298. & RANGE_MASK];
  174299. outptr[3] = range_limit[IDESCALE(tmp3 - tmp4, PASS1_BITS+3)
  174300. & RANGE_MASK];
  174301. wsptr += DCTSIZE; /* advance pointer to next row */
  174302. }
  174303. }
  174304. #endif /* DCT_IFAST_SUPPORTED */
  174305. /*** End of inlined file: jidctfst.c ***/
  174306. #undef CONST_BITS
  174307. #undef FIX_1_847759065
  174308. #undef MULTIPLY
  174309. #undef DEQUANTIZE
  174310. /*** Start of inlined file: jidctint.c ***/
  174311. #define JPEG_INTERNALS
  174312. #ifdef DCT_ISLOW_SUPPORTED
  174313. /*
  174314. * This module is specialized to the case DCTSIZE = 8.
  174315. */
  174316. #if DCTSIZE != 8
  174317. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174318. #endif
  174319. /*
  174320. * The poop on this scaling stuff is as follows:
  174321. *
  174322. * Each 1-D IDCT step produces outputs which are a factor of sqrt(N)
  174323. * larger than the true IDCT outputs. The final outputs are therefore
  174324. * a factor of N larger than desired; since N=8 this can be cured by
  174325. * a simple right shift at the end of the algorithm. The advantage of
  174326. * this arrangement is that we save two multiplications per 1-D IDCT,
  174327. * because the y0 and y4 inputs need not be divided by sqrt(N).
  174328. *
  174329. * We have to do addition and subtraction of the integer inputs, which
  174330. * is no problem, and multiplication by fractional constants, which is
  174331. * a problem to do in integer arithmetic. We multiply all the constants
  174332. * by CONST_SCALE and convert them to integer constants (thus retaining
  174333. * CONST_BITS bits of precision in the constants). After doing a
  174334. * multiplication we have to divide the product by CONST_SCALE, with proper
  174335. * rounding, to produce the correct output. This division can be done
  174336. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  174337. * as long as possible so that partial sums can be added together with
  174338. * full fractional precision.
  174339. *
  174340. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  174341. * they are represented to better-than-integral precision. These outputs
  174342. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  174343. * with the recommended scaling. (To scale up 12-bit sample data further, an
  174344. * intermediate INT32 array would be needed.)
  174345. *
  174346. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  174347. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  174348. * shows that the values given below are the most effective.
  174349. */
  174350. #if BITS_IN_JSAMPLE == 8
  174351. #define CONST_BITS 13
  174352. #define PASS1_BITS 2
  174353. #else
  174354. #define CONST_BITS 13
  174355. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174356. #endif
  174357. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174358. * causing a lot of useless floating-point operations at run time.
  174359. * To get around this we use the following pre-calculated constants.
  174360. * If you change CONST_BITS you may want to add appropriate values.
  174361. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174362. */
  174363. #if CONST_BITS == 13
  174364. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  174365. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  174366. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  174367. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  174368. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  174369. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  174370. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  174371. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  174372. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  174373. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  174374. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  174375. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  174376. #else
  174377. #define FIX_0_298631336 FIX(0.298631336)
  174378. #define FIX_0_390180644 FIX(0.390180644)
  174379. #define FIX_0_541196100 FIX(0.541196100)
  174380. #define FIX_0_765366865 FIX(0.765366865)
  174381. #define FIX_0_899976223 FIX(0.899976223)
  174382. #define FIX_1_175875602 FIX(1.175875602)
  174383. #define FIX_1_501321110 FIX(1.501321110)
  174384. #define FIX_1_847759065 FIX(1.847759065)
  174385. #define FIX_1_961570560 FIX(1.961570560)
  174386. #define FIX_2_053119869 FIX(2.053119869)
  174387. #define FIX_2_562915447 FIX(2.562915447)
  174388. #define FIX_3_072711026 FIX(3.072711026)
  174389. #endif
  174390. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  174391. * For 8-bit samples with the recommended scaling, all the variable
  174392. * and constant values involved are no more than 16 bits wide, so a
  174393. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  174394. * For 12-bit samples, a full 32-bit multiplication will be needed.
  174395. */
  174396. #if BITS_IN_JSAMPLE == 8
  174397. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  174398. #else
  174399. #define MULTIPLY(var,const) ((var) * (const))
  174400. #endif
  174401. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174402. * entry; produce an int result. In this module, both inputs and result
  174403. * are 16 bits or less, so either int or short multiply will work.
  174404. */
  174405. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  174406. /*
  174407. * Perform dequantization and inverse DCT on one block of coefficients.
  174408. */
  174409. GLOBAL(void)
  174410. jpeg_idct_islow (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174411. JCOEFPTR coef_block,
  174412. JSAMPARRAY output_buf, JDIMENSION output_col)
  174413. {
  174414. INT32 tmp0, tmp1, tmp2, tmp3;
  174415. INT32 tmp10, tmp11, tmp12, tmp13;
  174416. INT32 z1, z2, z3, z4, z5;
  174417. JCOEFPTR inptr;
  174418. ISLOW_MULT_TYPE * quantptr;
  174419. int * wsptr;
  174420. JSAMPROW outptr;
  174421. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174422. int ctr;
  174423. int workspace[DCTSIZE2]; /* buffers data between passes */
  174424. SHIFT_TEMPS
  174425. /* Pass 1: process columns from input, store into work array. */
  174426. /* Note results are scaled up by sqrt(8) compared to a true IDCT; */
  174427. /* furthermore, we scale the results by 2**PASS1_BITS. */
  174428. inptr = coef_block;
  174429. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  174430. wsptr = workspace;
  174431. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  174432. /* Due to quantization, we will usually find that many of the input
  174433. * coefficients are zero, especially the AC terms. We can exploit this
  174434. * by short-circuiting the IDCT calculation for any column in which all
  174435. * the AC terms are zero. In that case each output is equal to the
  174436. * DC coefficient (with scale factor as needed).
  174437. * With typical images and quantization tables, half or more of the
  174438. * column DCT calculations can be simplified this way.
  174439. */
  174440. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  174441. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  174442. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  174443. inptr[DCTSIZE*7] == 0) {
  174444. /* AC terms all zero */
  174445. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  174446. wsptr[DCTSIZE*0] = dcval;
  174447. wsptr[DCTSIZE*1] = dcval;
  174448. wsptr[DCTSIZE*2] = dcval;
  174449. wsptr[DCTSIZE*3] = dcval;
  174450. wsptr[DCTSIZE*4] = dcval;
  174451. wsptr[DCTSIZE*5] = dcval;
  174452. wsptr[DCTSIZE*6] = dcval;
  174453. wsptr[DCTSIZE*7] = dcval;
  174454. inptr++; /* advance pointers to next column */
  174455. quantptr++;
  174456. wsptr++;
  174457. continue;
  174458. }
  174459. /* Even part: reverse the even part of the forward DCT. */
  174460. /* The rotator is sqrt(2)*c(-6). */
  174461. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  174462. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  174463. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  174464. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  174465. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  174466. z2 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174467. z3 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  174468. tmp0 = (z2 + z3) << CONST_BITS;
  174469. tmp1 = (z2 - z3) << CONST_BITS;
  174470. tmp10 = tmp0 + tmp3;
  174471. tmp13 = tmp0 - tmp3;
  174472. tmp11 = tmp1 + tmp2;
  174473. tmp12 = tmp1 - tmp2;
  174474. /* Odd part per figure 8; the matrix is unitary and hence its
  174475. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  174476. */
  174477. tmp0 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  174478. tmp1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  174479. tmp2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  174480. tmp3 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  174481. z1 = tmp0 + tmp3;
  174482. z2 = tmp1 + tmp2;
  174483. z3 = tmp0 + tmp2;
  174484. z4 = tmp1 + tmp3;
  174485. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174486. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174487. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174488. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174489. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174490. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174491. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174492. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174493. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174494. z3 += z5;
  174495. z4 += z5;
  174496. tmp0 += z1 + z3;
  174497. tmp1 += z2 + z4;
  174498. tmp2 += z2 + z3;
  174499. tmp3 += z1 + z4;
  174500. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  174501. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp3, CONST_BITS-PASS1_BITS);
  174502. wsptr[DCTSIZE*7] = (int) DESCALE(tmp10 - tmp3, CONST_BITS-PASS1_BITS);
  174503. wsptr[DCTSIZE*1] = (int) DESCALE(tmp11 + tmp2, CONST_BITS-PASS1_BITS);
  174504. wsptr[DCTSIZE*6] = (int) DESCALE(tmp11 - tmp2, CONST_BITS-PASS1_BITS);
  174505. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 + tmp1, CONST_BITS-PASS1_BITS);
  174506. wsptr[DCTSIZE*5] = (int) DESCALE(tmp12 - tmp1, CONST_BITS-PASS1_BITS);
  174507. wsptr[DCTSIZE*3] = (int) DESCALE(tmp13 + tmp0, CONST_BITS-PASS1_BITS);
  174508. wsptr[DCTSIZE*4] = (int) DESCALE(tmp13 - tmp0, CONST_BITS-PASS1_BITS);
  174509. inptr++; /* advance pointers to next column */
  174510. quantptr++;
  174511. wsptr++;
  174512. }
  174513. /* Pass 2: process rows from work array, store into output array. */
  174514. /* Note that we must descale the results by a factor of 8 == 2**3, */
  174515. /* and also undo the PASS1_BITS scaling. */
  174516. wsptr = workspace;
  174517. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  174518. outptr = output_buf[ctr] + output_col;
  174519. /* Rows of zeroes can be exploited in the same way as we did with columns.
  174520. * However, the column calculation has created many nonzero AC terms, so
  174521. * the simplification applies less often (typically 5% to 10% of the time).
  174522. * On machines with very fast multiplication, it's possible that the
  174523. * test takes more time than it's worth. In that case this section
  174524. * may be commented out.
  174525. */
  174526. #ifndef NO_ZERO_ROW_TEST
  174527. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  174528. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  174529. /* AC terms all zero */
  174530. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  174531. & RANGE_MASK];
  174532. outptr[0] = dcval;
  174533. outptr[1] = dcval;
  174534. outptr[2] = dcval;
  174535. outptr[3] = dcval;
  174536. outptr[4] = dcval;
  174537. outptr[5] = dcval;
  174538. outptr[6] = dcval;
  174539. outptr[7] = dcval;
  174540. wsptr += DCTSIZE; /* advance pointer to next row */
  174541. continue;
  174542. }
  174543. #endif
  174544. /* Even part: reverse the even part of the forward DCT. */
  174545. /* The rotator is sqrt(2)*c(-6). */
  174546. z2 = (INT32) wsptr[2];
  174547. z3 = (INT32) wsptr[6];
  174548. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  174549. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  174550. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  174551. tmp0 = ((INT32) wsptr[0] + (INT32) wsptr[4]) << CONST_BITS;
  174552. tmp1 = ((INT32) wsptr[0] - (INT32) wsptr[4]) << CONST_BITS;
  174553. tmp10 = tmp0 + tmp3;
  174554. tmp13 = tmp0 - tmp3;
  174555. tmp11 = tmp1 + tmp2;
  174556. tmp12 = tmp1 - tmp2;
  174557. /* Odd part per figure 8; the matrix is unitary and hence its
  174558. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  174559. */
  174560. tmp0 = (INT32) wsptr[7];
  174561. tmp1 = (INT32) wsptr[5];
  174562. tmp2 = (INT32) wsptr[3];
  174563. tmp3 = (INT32) wsptr[1];
  174564. z1 = tmp0 + tmp3;
  174565. z2 = tmp1 + tmp2;
  174566. z3 = tmp0 + tmp2;
  174567. z4 = tmp1 + tmp3;
  174568. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174569. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174570. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174571. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174572. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174573. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174574. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174575. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174576. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174577. z3 += z5;
  174578. z4 += z5;
  174579. tmp0 += z1 + z3;
  174580. tmp1 += z2 + z4;
  174581. tmp2 += z2 + z3;
  174582. tmp3 += z1 + z4;
  174583. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  174584. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp3,
  174585. CONST_BITS+PASS1_BITS+3)
  174586. & RANGE_MASK];
  174587. outptr[7] = range_limit[(int) DESCALE(tmp10 - tmp3,
  174588. CONST_BITS+PASS1_BITS+3)
  174589. & RANGE_MASK];
  174590. outptr[1] = range_limit[(int) DESCALE(tmp11 + tmp2,
  174591. CONST_BITS+PASS1_BITS+3)
  174592. & RANGE_MASK];
  174593. outptr[6] = range_limit[(int) DESCALE(tmp11 - tmp2,
  174594. CONST_BITS+PASS1_BITS+3)
  174595. & RANGE_MASK];
  174596. outptr[2] = range_limit[(int) DESCALE(tmp12 + tmp1,
  174597. CONST_BITS+PASS1_BITS+3)
  174598. & RANGE_MASK];
  174599. outptr[5] = range_limit[(int) DESCALE(tmp12 - tmp1,
  174600. CONST_BITS+PASS1_BITS+3)
  174601. & RANGE_MASK];
  174602. outptr[3] = range_limit[(int) DESCALE(tmp13 + tmp0,
  174603. CONST_BITS+PASS1_BITS+3)
  174604. & RANGE_MASK];
  174605. outptr[4] = range_limit[(int) DESCALE(tmp13 - tmp0,
  174606. CONST_BITS+PASS1_BITS+3)
  174607. & RANGE_MASK];
  174608. wsptr += DCTSIZE; /* advance pointer to next row */
  174609. }
  174610. }
  174611. #endif /* DCT_ISLOW_SUPPORTED */
  174612. /*** End of inlined file: jidctint.c ***/
  174613. /*** Start of inlined file: jidctred.c ***/
  174614. #define JPEG_INTERNALS
  174615. #ifdef IDCT_SCALING_SUPPORTED
  174616. /*
  174617. * This module is specialized to the case DCTSIZE = 8.
  174618. */
  174619. #if DCTSIZE != 8
  174620. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174621. #endif
  174622. /* Scaling is the same as in jidctint.c. */
  174623. #if BITS_IN_JSAMPLE == 8
  174624. #define CONST_BITS 13
  174625. #define PASS1_BITS 2
  174626. #else
  174627. #define CONST_BITS 13
  174628. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174629. #endif
  174630. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174631. * causing a lot of useless floating-point operations at run time.
  174632. * To get around this we use the following pre-calculated constants.
  174633. * If you change CONST_BITS you may want to add appropriate values.
  174634. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174635. */
  174636. #if CONST_BITS == 13
  174637. #define FIX_0_211164243 ((INT32) 1730) /* FIX(0.211164243) */
  174638. #define FIX_0_509795579 ((INT32) 4176) /* FIX(0.509795579) */
  174639. #define FIX_0_601344887 ((INT32) 4926) /* FIX(0.601344887) */
  174640. #define FIX_0_720959822 ((INT32) 5906) /* FIX(0.720959822) */
  174641. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  174642. #define FIX_0_850430095 ((INT32) 6967) /* FIX(0.850430095) */
  174643. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  174644. #define FIX_1_061594337 ((INT32) 8697) /* FIX(1.061594337) */
  174645. #define FIX_1_272758580 ((INT32) 10426) /* FIX(1.272758580) */
  174646. #define FIX_1_451774981 ((INT32) 11893) /* FIX(1.451774981) */
  174647. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  174648. #define FIX_2_172734803 ((INT32) 17799) /* FIX(2.172734803) */
  174649. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  174650. #define FIX_3_624509785 ((INT32) 29692) /* FIX(3.624509785) */
  174651. #else
  174652. #define FIX_0_211164243 FIX(0.211164243)
  174653. #define FIX_0_509795579 FIX(0.509795579)
  174654. #define FIX_0_601344887 FIX(0.601344887)
  174655. #define FIX_0_720959822 FIX(0.720959822)
  174656. #define FIX_0_765366865 FIX(0.765366865)
  174657. #define FIX_0_850430095 FIX(0.850430095)
  174658. #define FIX_0_899976223 FIX(0.899976223)
  174659. #define FIX_1_061594337 FIX(1.061594337)
  174660. #define FIX_1_272758580 FIX(1.272758580)
  174661. #define FIX_1_451774981 FIX(1.451774981)
  174662. #define FIX_1_847759065 FIX(1.847759065)
  174663. #define FIX_2_172734803 FIX(2.172734803)
  174664. #define FIX_2_562915447 FIX(2.562915447)
  174665. #define FIX_3_624509785 FIX(3.624509785)
  174666. #endif
  174667. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  174668. * For 8-bit samples with the recommended scaling, all the variable
  174669. * and constant values involved are no more than 16 bits wide, so a
  174670. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  174671. * For 12-bit samples, a full 32-bit multiplication will be needed.
  174672. */
  174673. #if BITS_IN_JSAMPLE == 8
  174674. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  174675. #else
  174676. #define MULTIPLY(var,const) ((var) * (const))
  174677. #endif
  174678. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174679. * entry; produce an int result. In this module, both inputs and result
  174680. * are 16 bits or less, so either int or short multiply will work.
  174681. */
  174682. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  174683. /*
  174684. * Perform dequantization and inverse DCT on one block of coefficients,
  174685. * producing a reduced-size 4x4 output block.
  174686. */
  174687. GLOBAL(void)
  174688. jpeg_idct_4x4 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174689. JCOEFPTR coef_block,
  174690. JSAMPARRAY output_buf, JDIMENSION output_col)
  174691. {
  174692. INT32 tmp0, tmp2, tmp10, tmp12;
  174693. INT32 z1, z2, z3, z4;
  174694. JCOEFPTR inptr;
  174695. ISLOW_MULT_TYPE * quantptr;
  174696. int * wsptr;
  174697. JSAMPROW outptr;
  174698. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174699. int ctr;
  174700. int workspace[DCTSIZE*4]; /* buffers data between passes */
  174701. SHIFT_TEMPS
  174702. /* Pass 1: process columns from input, store into work array. */
  174703. inptr = coef_block;
  174704. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  174705. wsptr = workspace;
  174706. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  174707. /* Don't bother to process column 4, because second pass won't use it */
  174708. if (ctr == DCTSIZE-4)
  174709. continue;
  174710. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  174711. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*5] == 0 &&
  174712. inptr[DCTSIZE*6] == 0 && inptr[DCTSIZE*7] == 0) {
  174713. /* AC terms all zero; we need not examine term 4 for 4x4 output */
  174714. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  174715. wsptr[DCTSIZE*0] = dcval;
  174716. wsptr[DCTSIZE*1] = dcval;
  174717. wsptr[DCTSIZE*2] = dcval;
  174718. wsptr[DCTSIZE*3] = dcval;
  174719. continue;
  174720. }
  174721. /* Even part */
  174722. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174723. tmp0 <<= (CONST_BITS+1);
  174724. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  174725. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  174726. tmp2 = MULTIPLY(z2, FIX_1_847759065) + MULTIPLY(z3, - FIX_0_765366865);
  174727. tmp10 = tmp0 + tmp2;
  174728. tmp12 = tmp0 - tmp2;
  174729. /* Odd part */
  174730. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  174731. z2 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  174732. z3 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  174733. z4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  174734. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  174735. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  174736. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  174737. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  174738. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  174739. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  174740. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  174741. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  174742. /* Final output stage */
  174743. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp2, CONST_BITS-PASS1_BITS+1);
  174744. wsptr[DCTSIZE*3] = (int) DESCALE(tmp10 - tmp2, CONST_BITS-PASS1_BITS+1);
  174745. wsptr[DCTSIZE*1] = (int) DESCALE(tmp12 + tmp0, CONST_BITS-PASS1_BITS+1);
  174746. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 - tmp0, CONST_BITS-PASS1_BITS+1);
  174747. }
  174748. /* Pass 2: process 4 rows from work array, store into output array. */
  174749. wsptr = workspace;
  174750. for (ctr = 0; ctr < 4; ctr++) {
  174751. outptr = output_buf[ctr] + output_col;
  174752. /* It's not clear whether a zero row test is worthwhile here ... */
  174753. #ifndef NO_ZERO_ROW_TEST
  174754. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 &&
  174755. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  174756. /* AC terms all zero */
  174757. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  174758. & RANGE_MASK];
  174759. outptr[0] = dcval;
  174760. outptr[1] = dcval;
  174761. outptr[2] = dcval;
  174762. outptr[3] = dcval;
  174763. wsptr += DCTSIZE; /* advance pointer to next row */
  174764. continue;
  174765. }
  174766. #endif
  174767. /* Even part */
  174768. tmp0 = ((INT32) wsptr[0]) << (CONST_BITS+1);
  174769. tmp2 = MULTIPLY((INT32) wsptr[2], FIX_1_847759065)
  174770. + MULTIPLY((INT32) wsptr[6], - FIX_0_765366865);
  174771. tmp10 = tmp0 + tmp2;
  174772. tmp12 = tmp0 - tmp2;
  174773. /* Odd part */
  174774. z1 = (INT32) wsptr[7];
  174775. z2 = (INT32) wsptr[5];
  174776. z3 = (INT32) wsptr[3];
  174777. z4 = (INT32) wsptr[1];
  174778. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  174779. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  174780. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  174781. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  174782. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  174783. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  174784. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  174785. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  174786. /* Final output stage */
  174787. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp2,
  174788. CONST_BITS+PASS1_BITS+3+1)
  174789. & RANGE_MASK];
  174790. outptr[3] = range_limit[(int) DESCALE(tmp10 - tmp2,
  174791. CONST_BITS+PASS1_BITS+3+1)
  174792. & RANGE_MASK];
  174793. outptr[1] = range_limit[(int) DESCALE(tmp12 + tmp0,
  174794. CONST_BITS+PASS1_BITS+3+1)
  174795. & RANGE_MASK];
  174796. outptr[2] = range_limit[(int) DESCALE(tmp12 - tmp0,
  174797. CONST_BITS+PASS1_BITS+3+1)
  174798. & RANGE_MASK];
  174799. wsptr += DCTSIZE; /* advance pointer to next row */
  174800. }
  174801. }
  174802. /*
  174803. * Perform dequantization and inverse DCT on one block of coefficients,
  174804. * producing a reduced-size 2x2 output block.
  174805. */
  174806. GLOBAL(void)
  174807. jpeg_idct_2x2 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174808. JCOEFPTR coef_block,
  174809. JSAMPARRAY output_buf, JDIMENSION output_col)
  174810. {
  174811. INT32 tmp0, tmp10, z1;
  174812. JCOEFPTR inptr;
  174813. ISLOW_MULT_TYPE * quantptr;
  174814. int * wsptr;
  174815. JSAMPROW outptr;
  174816. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174817. int ctr;
  174818. int workspace[DCTSIZE*2]; /* buffers data between passes */
  174819. SHIFT_TEMPS
  174820. /* Pass 1: process columns from input, store into work array. */
  174821. inptr = coef_block;
  174822. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  174823. wsptr = workspace;
  174824. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  174825. /* Don't bother to process columns 2,4,6 */
  174826. if (ctr == DCTSIZE-2 || ctr == DCTSIZE-4 || ctr == DCTSIZE-6)
  174827. continue;
  174828. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*3] == 0 &&
  174829. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*7] == 0) {
  174830. /* AC terms all zero; we need not examine terms 2,4,6 for 2x2 output */
  174831. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  174832. wsptr[DCTSIZE*0] = dcval;
  174833. wsptr[DCTSIZE*1] = dcval;
  174834. continue;
  174835. }
  174836. /* Even part */
  174837. z1 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174838. tmp10 = z1 << (CONST_BITS+2);
  174839. /* Odd part */
  174840. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  174841. tmp0 = MULTIPLY(z1, - FIX_0_720959822); /* sqrt(2) * (c7-c5+c3-c1) */
  174842. z1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  174843. tmp0 += MULTIPLY(z1, FIX_0_850430095); /* sqrt(2) * (-c1+c3+c5+c7) */
  174844. z1 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  174845. tmp0 += MULTIPLY(z1, - FIX_1_272758580); /* sqrt(2) * (-c1+c3-c5-c7) */
  174846. z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  174847. tmp0 += MULTIPLY(z1, FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  174848. /* Final output stage */
  174849. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp0, CONST_BITS-PASS1_BITS+2);
  174850. wsptr[DCTSIZE*1] = (int) DESCALE(tmp10 - tmp0, CONST_BITS-PASS1_BITS+2);
  174851. }
  174852. /* Pass 2: process 2 rows from work array, store into output array. */
  174853. wsptr = workspace;
  174854. for (ctr = 0; ctr < 2; ctr++) {
  174855. outptr = output_buf[ctr] + output_col;
  174856. /* It's not clear whether a zero row test is worthwhile here ... */
  174857. #ifndef NO_ZERO_ROW_TEST
  174858. if (wsptr[1] == 0 && wsptr[3] == 0 && wsptr[5] == 0 && wsptr[7] == 0) {
  174859. /* AC terms all zero */
  174860. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  174861. & RANGE_MASK];
  174862. outptr[0] = dcval;
  174863. outptr[1] = dcval;
  174864. wsptr += DCTSIZE; /* advance pointer to next row */
  174865. continue;
  174866. }
  174867. #endif
  174868. /* Even part */
  174869. tmp10 = ((INT32) wsptr[0]) << (CONST_BITS+2);
  174870. /* Odd part */
  174871. tmp0 = MULTIPLY((INT32) wsptr[7], - FIX_0_720959822) /* sqrt(2) * (c7-c5+c3-c1) */
  174872. + MULTIPLY((INT32) wsptr[5], FIX_0_850430095) /* sqrt(2) * (-c1+c3+c5+c7) */
  174873. + MULTIPLY((INT32) wsptr[3], - FIX_1_272758580) /* sqrt(2) * (-c1+c3-c5-c7) */
  174874. + MULTIPLY((INT32) wsptr[1], FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  174875. /* Final output stage */
  174876. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp0,
  174877. CONST_BITS+PASS1_BITS+3+2)
  174878. & RANGE_MASK];
  174879. outptr[1] = range_limit[(int) DESCALE(tmp10 - tmp0,
  174880. CONST_BITS+PASS1_BITS+3+2)
  174881. & RANGE_MASK];
  174882. wsptr += DCTSIZE; /* advance pointer to next row */
  174883. }
  174884. }
  174885. /*
  174886. * Perform dequantization and inverse DCT on one block of coefficients,
  174887. * producing a reduced-size 1x1 output block.
  174888. */
  174889. GLOBAL(void)
  174890. jpeg_idct_1x1 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174891. JCOEFPTR coef_block,
  174892. JSAMPARRAY output_buf, JDIMENSION output_col)
  174893. {
  174894. int dcval;
  174895. ISLOW_MULT_TYPE * quantptr;
  174896. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174897. SHIFT_TEMPS
  174898. /* We hardly need an inverse DCT routine for this: just take the
  174899. * average pixel value, which is one-eighth of the DC coefficient.
  174900. */
  174901. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  174902. dcval = DEQUANTIZE(coef_block[0], quantptr[0]);
  174903. dcval = (int) DESCALE((INT32) dcval, 3);
  174904. output_buf[0][output_col] = range_limit[dcval & RANGE_MASK];
  174905. }
  174906. #endif /* IDCT_SCALING_SUPPORTED */
  174907. /*** End of inlined file: jidctred.c ***/
  174908. /*** Start of inlined file: jmemmgr.c ***/
  174909. #define JPEG_INTERNALS
  174910. #define AM_MEMORY_MANAGER /* we define jvirt_Xarray_control structs */
  174911. /*** Start of inlined file: jmemsys.h ***/
  174912. #ifndef __jmemsys_h__
  174913. #define __jmemsys_h__
  174914. /* Short forms of external names for systems with brain-damaged linkers. */
  174915. #ifdef NEED_SHORT_EXTERNAL_NAMES
  174916. #define jpeg_get_small jGetSmall
  174917. #define jpeg_free_small jFreeSmall
  174918. #define jpeg_get_large jGetLarge
  174919. #define jpeg_free_large jFreeLarge
  174920. #define jpeg_mem_available jMemAvail
  174921. #define jpeg_open_backing_store jOpenBackStore
  174922. #define jpeg_mem_init jMemInit
  174923. #define jpeg_mem_term jMemTerm
  174924. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  174925. /*
  174926. * These two functions are used to allocate and release small chunks of
  174927. * memory. (Typically the total amount requested through jpeg_get_small is
  174928. * no more than 20K or so; this will be requested in chunks of a few K each.)
  174929. * Behavior should be the same as for the standard library functions malloc
  174930. * and free; in particular, jpeg_get_small must return NULL on failure.
  174931. * On most systems, these ARE malloc and free. jpeg_free_small is passed the
  174932. * size of the object being freed, just in case it's needed.
  174933. * On an 80x86 machine using small-data memory model, these manage near heap.
  174934. */
  174935. EXTERN(void *) jpeg_get_small JPP((j_common_ptr cinfo, size_t sizeofobject));
  174936. EXTERN(void) jpeg_free_small JPP((j_common_ptr cinfo, void * object,
  174937. size_t sizeofobject));
  174938. /*
  174939. * These two functions are used to allocate and release large chunks of
  174940. * memory (up to the total free space designated by jpeg_mem_available).
  174941. * The interface is the same as above, except that on an 80x86 machine,
  174942. * far pointers are used. On most other machines these are identical to
  174943. * the jpeg_get/free_small routines; but we keep them separate anyway,
  174944. * in case a different allocation strategy is desirable for large chunks.
  174945. */
  174946. EXTERN(void FAR *) jpeg_get_large JPP((j_common_ptr cinfo,
  174947. size_t sizeofobject));
  174948. EXTERN(void) jpeg_free_large JPP((j_common_ptr cinfo, void FAR * object,
  174949. size_t sizeofobject));
  174950. /*
  174951. * The macro MAX_ALLOC_CHUNK designates the maximum number of bytes that may
  174952. * be requested in a single call to jpeg_get_large (and jpeg_get_small for that
  174953. * matter, but that case should never come into play). This macro is needed
  174954. * to model the 64Kb-segment-size limit of far addressing on 80x86 machines.
  174955. * On those machines, we expect that jconfig.h will provide a proper value.
  174956. * On machines with 32-bit flat address spaces, any large constant may be used.
  174957. *
  174958. * NB: jmemmgr.c expects that MAX_ALLOC_CHUNK will be representable as type
  174959. * size_t and will be a multiple of sizeof(align_type).
  174960. */
  174961. #ifndef MAX_ALLOC_CHUNK /* may be overridden in jconfig.h */
  174962. #define MAX_ALLOC_CHUNK 1000000000L
  174963. #endif
  174964. /*
  174965. * This routine computes the total space still available for allocation by
  174966. * jpeg_get_large. If more space than this is needed, backing store will be
  174967. * used. NOTE: any memory already allocated must not be counted.
  174968. *
  174969. * There is a minimum space requirement, corresponding to the minimum
  174970. * feasible buffer sizes; jmemmgr.c will request that much space even if
  174971. * jpeg_mem_available returns zero. The maximum space needed, enough to hold
  174972. * all working storage in memory, is also passed in case it is useful.
  174973. * Finally, the total space already allocated is passed. If no better
  174974. * method is available, cinfo->mem->max_memory_to_use - already_allocated
  174975. * is often a suitable calculation.
  174976. *
  174977. * It is OK for jpeg_mem_available to underestimate the space available
  174978. * (that'll just lead to more backing-store access than is really necessary).
  174979. * However, an overestimate will lead to failure. Hence it's wise to subtract
  174980. * a slop factor from the true available space. 5% should be enough.
  174981. *
  174982. * On machines with lots of virtual memory, any large constant may be returned.
  174983. * Conversely, zero may be returned to always use the minimum amount of memory.
  174984. */
  174985. EXTERN(long) jpeg_mem_available JPP((j_common_ptr cinfo,
  174986. long min_bytes_needed,
  174987. long max_bytes_needed,
  174988. long already_allocated));
  174989. /*
  174990. * This structure holds whatever state is needed to access a single
  174991. * backing-store object. The read/write/close method pointers are called
  174992. * by jmemmgr.c to manipulate the backing-store object; all other fields
  174993. * are private to the system-dependent backing store routines.
  174994. */
  174995. #define TEMP_NAME_LENGTH 64 /* max length of a temporary file's name */
  174996. #ifdef USE_MSDOS_MEMMGR /* DOS-specific junk */
  174997. typedef unsigned short XMSH; /* type of extended-memory handles */
  174998. typedef unsigned short EMSH; /* type of expanded-memory handles */
  174999. typedef union {
  175000. short file_handle; /* DOS file handle if it's a temp file */
  175001. XMSH xms_handle; /* handle if it's a chunk of XMS */
  175002. EMSH ems_handle; /* handle if it's a chunk of EMS */
  175003. } handle_union;
  175004. #endif /* USE_MSDOS_MEMMGR */
  175005. #ifdef USE_MAC_MEMMGR /* Mac-specific junk */
  175006. #include <Files.h>
  175007. #endif /* USE_MAC_MEMMGR */
  175008. //typedef struct backing_store_struct * backing_store_ptr;
  175009. typedef struct backing_store_struct {
  175010. /* Methods for reading/writing/closing this backing-store object */
  175011. JMETHOD(void, read_backing_store, (j_common_ptr cinfo,
  175012. struct backing_store_struct *info,
  175013. void FAR * buffer_address,
  175014. long file_offset, long byte_count));
  175015. JMETHOD(void, write_backing_store, (j_common_ptr cinfo,
  175016. struct backing_store_struct *info,
  175017. void FAR * buffer_address,
  175018. long file_offset, long byte_count));
  175019. JMETHOD(void, close_backing_store, (j_common_ptr cinfo,
  175020. struct backing_store_struct *info));
  175021. /* Private fields for system-dependent backing-store management */
  175022. #ifdef USE_MSDOS_MEMMGR
  175023. /* For the MS-DOS manager (jmemdos.c), we need: */
  175024. handle_union handle; /* reference to backing-store storage object */
  175025. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  175026. #else
  175027. #ifdef USE_MAC_MEMMGR
  175028. /* For the Mac manager (jmemmac.c), we need: */
  175029. short temp_file; /* file reference number to temp file */
  175030. FSSpec tempSpec; /* the FSSpec for the temp file */
  175031. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  175032. #else
  175033. /* For a typical implementation with temp files, we need: */
  175034. FILE * temp_file; /* stdio reference to temp file */
  175035. char temp_name[TEMP_NAME_LENGTH]; /* name of temp file */
  175036. #endif
  175037. #endif
  175038. } backing_store_info;
  175039. /*
  175040. * Initial opening of a backing-store object. This must fill in the
  175041. * read/write/close pointers in the object. The read/write routines
  175042. * may take an error exit if the specified maximum file size is exceeded.
  175043. * (If jpeg_mem_available always returns a large value, this routine can
  175044. * just take an error exit.)
  175045. */
  175046. EXTERN(void) jpeg_open_backing_store JPP((j_common_ptr cinfo,
  175047. struct backing_store_struct *info,
  175048. long total_bytes_needed));
  175049. /*
  175050. * These routines take care of any system-dependent initialization and
  175051. * cleanup required. jpeg_mem_init will be called before anything is
  175052. * allocated (and, therefore, nothing in cinfo is of use except the error
  175053. * manager pointer). It should return a suitable default value for
  175054. * max_memory_to_use; this may subsequently be overridden by the surrounding
  175055. * application. (Note that max_memory_to_use is only important if
  175056. * jpeg_mem_available chooses to consult it ... no one else will.)
  175057. * jpeg_mem_term may assume that all requested memory has been freed and that
  175058. * all opened backing-store objects have been closed.
  175059. */
  175060. EXTERN(long) jpeg_mem_init JPP((j_common_ptr cinfo));
  175061. EXTERN(void) jpeg_mem_term JPP((j_common_ptr cinfo));
  175062. #endif
  175063. /*** End of inlined file: jmemsys.h ***/
  175064. /* import the system-dependent declarations */
  175065. #ifndef NO_GETENV
  175066. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare getenv() */
  175067. extern char * getenv JPP((const char * name));
  175068. #endif
  175069. #endif
  175070. /*
  175071. * Some important notes:
  175072. * The allocation routines provided here must never return NULL.
  175073. * They should exit to error_exit if unsuccessful.
  175074. *
  175075. * It's not a good idea to try to merge the sarray and barray routines,
  175076. * even though they are textually almost the same, because samples are
  175077. * usually stored as bytes while coefficients are shorts or ints. Thus,
  175078. * in machines where byte pointers have a different representation from
  175079. * word pointers, the resulting machine code could not be the same.
  175080. */
  175081. /*
  175082. * Many machines require storage alignment: longs must start on 4-byte
  175083. * boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc()
  175084. * always returns pointers that are multiples of the worst-case alignment
  175085. * requirement, and we had better do so too.
  175086. * There isn't any really portable way to determine the worst-case alignment
  175087. * requirement. This module assumes that the alignment requirement is
  175088. * multiples of sizeof(ALIGN_TYPE).
  175089. * By default, we define ALIGN_TYPE as double. This is necessary on some
  175090. * workstations (where doubles really do need 8-byte alignment) and will work
  175091. * fine on nearly everything. If your machine has lesser alignment needs,
  175092. * you can save a few bytes by making ALIGN_TYPE smaller.
  175093. * The only place I know of where this will NOT work is certain Macintosh
  175094. * 680x0 compilers that define double as a 10-byte IEEE extended float.
  175095. * Doing 10-byte alignment is counterproductive because longwords won't be
  175096. * aligned well. Put "#define ALIGN_TYPE long" in jconfig.h if you have
  175097. * such a compiler.
  175098. */
  175099. #ifndef ALIGN_TYPE /* so can override from jconfig.h */
  175100. #define ALIGN_TYPE double
  175101. #endif
  175102. /*
  175103. * We allocate objects from "pools", where each pool is gotten with a single
  175104. * request to jpeg_get_small() or jpeg_get_large(). There is no per-object
  175105. * overhead within a pool, except for alignment padding. Each pool has a
  175106. * header with a link to the next pool of the same class.
  175107. * Small and large pool headers are identical except that the latter's
  175108. * link pointer must be FAR on 80x86 machines.
  175109. * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
  175110. * field. This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
  175111. * of the alignment requirement of ALIGN_TYPE.
  175112. */
  175113. typedef union small_pool_struct * small_pool_ptr;
  175114. typedef union small_pool_struct {
  175115. struct {
  175116. small_pool_ptr next; /* next in list of pools */
  175117. size_t bytes_used; /* how many bytes already used within pool */
  175118. size_t bytes_left; /* bytes still available in this pool */
  175119. } hdr;
  175120. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  175121. } small_pool_hdr;
  175122. typedef union large_pool_struct FAR * large_pool_ptr;
  175123. typedef union large_pool_struct {
  175124. struct {
  175125. large_pool_ptr next; /* next in list of pools */
  175126. size_t bytes_used; /* how many bytes already used within pool */
  175127. size_t bytes_left; /* bytes still available in this pool */
  175128. } hdr;
  175129. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  175130. } large_pool_hdr;
  175131. /*
  175132. * Here is the full definition of a memory manager object.
  175133. */
  175134. typedef struct {
  175135. struct jpeg_memory_mgr pub; /* public fields */
  175136. /* Each pool identifier (lifetime class) names a linked list of pools. */
  175137. small_pool_ptr small_list[JPOOL_NUMPOOLS];
  175138. large_pool_ptr large_list[JPOOL_NUMPOOLS];
  175139. /* Since we only have one lifetime class of virtual arrays, only one
  175140. * linked list is necessary (for each datatype). Note that the virtual
  175141. * array control blocks being linked together are actually stored somewhere
  175142. * in the small-pool list.
  175143. */
  175144. jvirt_sarray_ptr virt_sarray_list;
  175145. jvirt_barray_ptr virt_barray_list;
  175146. /* This counts total space obtained from jpeg_get_small/large */
  175147. long total_space_allocated;
  175148. /* alloc_sarray and alloc_barray set this value for use by virtual
  175149. * array routines.
  175150. */
  175151. JDIMENSION last_rowsperchunk; /* from most recent alloc_sarray/barray */
  175152. } my_memory_mgr;
  175153. typedef my_memory_mgr * my_mem_ptr;
  175154. /*
  175155. * The control blocks for virtual arrays.
  175156. * Note that these blocks are allocated in the "small" pool area.
  175157. * System-dependent info for the associated backing store (if any) is hidden
  175158. * inside the backing_store_info struct.
  175159. */
  175160. struct jvirt_sarray_control {
  175161. JSAMPARRAY mem_buffer; /* => the in-memory buffer */
  175162. JDIMENSION rows_in_array; /* total virtual array height */
  175163. JDIMENSION samplesperrow; /* width of array (and of memory buffer) */
  175164. JDIMENSION maxaccess; /* max rows accessed by access_virt_sarray */
  175165. JDIMENSION rows_in_mem; /* height of memory buffer */
  175166. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  175167. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  175168. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  175169. boolean pre_zero; /* pre-zero mode requested? */
  175170. boolean dirty; /* do current buffer contents need written? */
  175171. boolean b_s_open; /* is backing-store data valid? */
  175172. jvirt_sarray_ptr next; /* link to next virtual sarray control block */
  175173. backing_store_info b_s_info; /* System-dependent control info */
  175174. };
  175175. struct jvirt_barray_control {
  175176. JBLOCKARRAY mem_buffer; /* => the in-memory buffer */
  175177. JDIMENSION rows_in_array; /* total virtual array height */
  175178. JDIMENSION blocksperrow; /* width of array (and of memory buffer) */
  175179. JDIMENSION maxaccess; /* max rows accessed by access_virt_barray */
  175180. JDIMENSION rows_in_mem; /* height of memory buffer */
  175181. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  175182. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  175183. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  175184. boolean pre_zero; /* pre-zero mode requested? */
  175185. boolean dirty; /* do current buffer contents need written? */
  175186. boolean b_s_open; /* is backing-store data valid? */
  175187. jvirt_barray_ptr next; /* link to next virtual barray control block */
  175188. backing_store_info b_s_info; /* System-dependent control info */
  175189. };
  175190. #ifdef MEM_STATS /* optional extra stuff for statistics */
  175191. LOCAL(void)
  175192. print_mem_stats (j_common_ptr cinfo, int pool_id)
  175193. {
  175194. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175195. small_pool_ptr shdr_ptr;
  175196. large_pool_ptr lhdr_ptr;
  175197. /* Since this is only a debugging stub, we can cheat a little by using
  175198. * fprintf directly rather than going through the trace message code.
  175199. * This is helpful because message parm array can't handle longs.
  175200. */
  175201. fprintf(stderr, "Freeing pool %d, total space = %ld\n",
  175202. pool_id, mem->total_space_allocated);
  175203. for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;
  175204. lhdr_ptr = lhdr_ptr->hdr.next) {
  175205. fprintf(stderr, " Large chunk used %ld\n",
  175206. (long) lhdr_ptr->hdr.bytes_used);
  175207. }
  175208. for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;
  175209. shdr_ptr = shdr_ptr->hdr.next) {
  175210. fprintf(stderr, " Small chunk used %ld free %ld\n",
  175211. (long) shdr_ptr->hdr.bytes_used,
  175212. (long) shdr_ptr->hdr.bytes_left);
  175213. }
  175214. }
  175215. #endif /* MEM_STATS */
  175216. LOCAL(void)
  175217. out_of_memory (j_common_ptr cinfo, int which)
  175218. /* Report an out-of-memory error and stop execution */
  175219. /* If we compiled MEM_STATS support, report alloc requests before dying */
  175220. {
  175221. #ifdef MEM_STATS
  175222. cinfo->err->trace_level = 2; /* force self_destruct to report stats */
  175223. #endif
  175224. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
  175225. }
  175226. /*
  175227. * Allocation of "small" objects.
  175228. *
  175229. * For these, we use pooled storage. When a new pool must be created,
  175230. * we try to get enough space for the current request plus a "slop" factor,
  175231. * where the slop will be the amount of leftover space in the new pool.
  175232. * The speed vs. space tradeoff is largely determined by the slop values.
  175233. * A different slop value is provided for each pool class (lifetime),
  175234. * and we also distinguish the first pool of a class from later ones.
  175235. * NOTE: the values given work fairly well on both 16- and 32-bit-int
  175236. * machines, but may be too small if longs are 64 bits or more.
  175237. */
  175238. static const size_t first_pool_slop[JPOOL_NUMPOOLS] =
  175239. {
  175240. 1600, /* first PERMANENT pool */
  175241. 16000 /* first IMAGE pool */
  175242. };
  175243. static const size_t extra_pool_slop[JPOOL_NUMPOOLS] =
  175244. {
  175245. 0, /* additional PERMANENT pools */
  175246. 5000 /* additional IMAGE pools */
  175247. };
  175248. #define MIN_SLOP 50 /* greater than 0 to avoid futile looping */
  175249. METHODDEF(void *)
  175250. alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  175251. /* Allocate a "small" object */
  175252. {
  175253. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175254. small_pool_ptr hdr_ptr, prev_hdr_ptr;
  175255. char * data_ptr;
  175256. size_t odd_bytes, min_request, slop;
  175257. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  175258. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr)))
  175259. out_of_memory(cinfo, 1); /* request exceeds malloc's ability */
  175260. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  175261. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  175262. if (odd_bytes > 0)
  175263. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  175264. /* See if space is available in any existing pool */
  175265. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  175266. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  175267. prev_hdr_ptr = NULL;
  175268. hdr_ptr = mem->small_list[pool_id];
  175269. while (hdr_ptr != NULL) {
  175270. if (hdr_ptr->hdr.bytes_left >= sizeofobject)
  175271. break; /* found pool with enough space */
  175272. prev_hdr_ptr = hdr_ptr;
  175273. hdr_ptr = hdr_ptr->hdr.next;
  175274. }
  175275. /* Time to make a new pool? */
  175276. if (hdr_ptr == NULL) {
  175277. /* min_request is what we need now, slop is what will be leftover */
  175278. min_request = sizeofobject + SIZEOF(small_pool_hdr);
  175279. if (prev_hdr_ptr == NULL) /* first pool in class? */
  175280. slop = first_pool_slop[pool_id];
  175281. else
  175282. slop = extra_pool_slop[pool_id];
  175283. /* Don't ask for more than MAX_ALLOC_CHUNK */
  175284. if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request))
  175285. slop = (size_t) (MAX_ALLOC_CHUNK-min_request);
  175286. /* Try to get space, if fail reduce slop and try again */
  175287. for (;;) {
  175288. hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop);
  175289. if (hdr_ptr != NULL)
  175290. break;
  175291. slop /= 2;
  175292. if (slop < MIN_SLOP) /* give up when it gets real small */
  175293. out_of_memory(cinfo, 2); /* jpeg_get_small failed */
  175294. }
  175295. mem->total_space_allocated += min_request + slop;
  175296. /* Success, initialize the new pool header and add to end of list */
  175297. hdr_ptr->hdr.next = NULL;
  175298. hdr_ptr->hdr.bytes_used = 0;
  175299. hdr_ptr->hdr.bytes_left = sizeofobject + slop;
  175300. if (prev_hdr_ptr == NULL) /* first pool in class? */
  175301. mem->small_list[pool_id] = hdr_ptr;
  175302. else
  175303. prev_hdr_ptr->hdr.next = hdr_ptr;
  175304. }
  175305. /* OK, allocate the object from the current pool */
  175306. data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
  175307. data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
  175308. hdr_ptr->hdr.bytes_used += sizeofobject;
  175309. hdr_ptr->hdr.bytes_left -= sizeofobject;
  175310. return (void *) data_ptr;
  175311. }
  175312. /*
  175313. * Allocation of "large" objects.
  175314. *
  175315. * The external semantics of these are the same as "small" objects,
  175316. * except that FAR pointers are used on 80x86. However the pool
  175317. * management heuristics are quite different. We assume that each
  175318. * request is large enough that it may as well be passed directly to
  175319. * jpeg_get_large; the pool management just links everything together
  175320. * so that we can free it all on demand.
  175321. * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
  175322. * structures. The routines that create these structures (see below)
  175323. * deliberately bunch rows together to ensure a large request size.
  175324. */
  175325. METHODDEF(void FAR *)
  175326. alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  175327. /* Allocate a "large" object */
  175328. {
  175329. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175330. large_pool_ptr hdr_ptr;
  175331. size_t odd_bytes;
  175332. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  175333. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)))
  175334. out_of_memory(cinfo, 3); /* request exceeds malloc's ability */
  175335. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  175336. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  175337. if (odd_bytes > 0)
  175338. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  175339. /* Always make a new pool */
  175340. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  175341. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  175342. hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject +
  175343. SIZEOF(large_pool_hdr));
  175344. if (hdr_ptr == NULL)
  175345. out_of_memory(cinfo, 4); /* jpeg_get_large failed */
  175346. mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr);
  175347. /* Success, initialize the new pool header and add to list */
  175348. hdr_ptr->hdr.next = mem->large_list[pool_id];
  175349. /* We maintain space counts in each pool header for statistical purposes,
  175350. * even though they are not needed for allocation.
  175351. */
  175352. hdr_ptr->hdr.bytes_used = sizeofobject;
  175353. hdr_ptr->hdr.bytes_left = 0;
  175354. mem->large_list[pool_id] = hdr_ptr;
  175355. return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */
  175356. }
  175357. /*
  175358. * Creation of 2-D sample arrays.
  175359. * The pointers are in near heap, the samples themselves in FAR heap.
  175360. *
  175361. * To minimize allocation overhead and to allow I/O of large contiguous
  175362. * blocks, we allocate the sample rows in groups of as many rows as possible
  175363. * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
  175364. * NB: the virtual array control routines, later in this file, know about
  175365. * this chunking of rows. The rowsperchunk value is left in the mem manager
  175366. * object so that it can be saved away if this sarray is the workspace for
  175367. * a virtual array.
  175368. */
  175369. METHODDEF(JSAMPARRAY)
  175370. alloc_sarray (j_common_ptr cinfo, int pool_id,
  175371. JDIMENSION samplesperrow, JDIMENSION numrows)
  175372. /* Allocate a 2-D sample array */
  175373. {
  175374. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175375. JSAMPARRAY result;
  175376. JSAMPROW workspace;
  175377. JDIMENSION rowsperchunk, currow, i;
  175378. long ltemp;
  175379. /* Calculate max # of rows allowed in one allocation chunk */
  175380. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  175381. ((long) samplesperrow * SIZEOF(JSAMPLE));
  175382. if (ltemp <= 0)
  175383. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  175384. if (ltemp < (long) numrows)
  175385. rowsperchunk = (JDIMENSION) ltemp;
  175386. else
  175387. rowsperchunk = numrows;
  175388. mem->last_rowsperchunk = rowsperchunk;
  175389. /* Get space for row pointers (small object) */
  175390. result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
  175391. (size_t) (numrows * SIZEOF(JSAMPROW)));
  175392. /* Get the rows themselves (large objects) */
  175393. currow = 0;
  175394. while (currow < numrows) {
  175395. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  175396. workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
  175397. (size_t) ((size_t) rowsperchunk * (size_t) samplesperrow
  175398. * SIZEOF(JSAMPLE)));
  175399. for (i = rowsperchunk; i > 0; i--) {
  175400. result[currow++] = workspace;
  175401. workspace += samplesperrow;
  175402. }
  175403. }
  175404. return result;
  175405. }
  175406. /*
  175407. * Creation of 2-D coefficient-block arrays.
  175408. * This is essentially the same as the code for sample arrays, above.
  175409. */
  175410. METHODDEF(JBLOCKARRAY)
  175411. alloc_barray (j_common_ptr cinfo, int pool_id,
  175412. JDIMENSION blocksperrow, JDIMENSION numrows)
  175413. /* Allocate a 2-D coefficient-block array */
  175414. {
  175415. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175416. JBLOCKARRAY result;
  175417. JBLOCKROW workspace;
  175418. JDIMENSION rowsperchunk, currow, i;
  175419. long ltemp;
  175420. /* Calculate max # of rows allowed in one allocation chunk */
  175421. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  175422. ((long) blocksperrow * SIZEOF(JBLOCK));
  175423. if (ltemp <= 0)
  175424. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  175425. if (ltemp < (long) numrows)
  175426. rowsperchunk = (JDIMENSION) ltemp;
  175427. else
  175428. rowsperchunk = numrows;
  175429. mem->last_rowsperchunk = rowsperchunk;
  175430. /* Get space for row pointers (small object) */
  175431. result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
  175432. (size_t) (numrows * SIZEOF(JBLOCKROW)));
  175433. /* Get the rows themselves (large objects) */
  175434. currow = 0;
  175435. while (currow < numrows) {
  175436. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  175437. workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
  175438. (size_t) ((size_t) rowsperchunk * (size_t) blocksperrow
  175439. * SIZEOF(JBLOCK)));
  175440. for (i = rowsperchunk; i > 0; i--) {
  175441. result[currow++] = workspace;
  175442. workspace += blocksperrow;
  175443. }
  175444. }
  175445. return result;
  175446. }
  175447. /*
  175448. * About virtual array management:
  175449. *
  175450. * The above "normal" array routines are only used to allocate strip buffers
  175451. * (as wide as the image, but just a few rows high). Full-image-sized buffers
  175452. * are handled as "virtual" arrays. The array is still accessed a strip at a
  175453. * time, but the memory manager must save the whole array for repeated
  175454. * accesses. The intended implementation is that there is a strip buffer in
  175455. * memory (as high as is possible given the desired memory limit), plus a
  175456. * backing file that holds the rest of the array.
  175457. *
  175458. * The request_virt_array routines are told the total size of the image and
  175459. * the maximum number of rows that will be accessed at once. The in-memory
  175460. * buffer must be at least as large as the maxaccess value.
  175461. *
  175462. * The request routines create control blocks but not the in-memory buffers.
  175463. * That is postponed until realize_virt_arrays is called. At that time the
  175464. * total amount of space needed is known (approximately, anyway), so free
  175465. * memory can be divided up fairly.
  175466. *
  175467. * The access_virt_array routines are responsible for making a specific strip
  175468. * area accessible (after reading or writing the backing file, if necessary).
  175469. * Note that the access routines are told whether the caller intends to modify
  175470. * the accessed strip; during a read-only pass this saves having to rewrite
  175471. * data to disk. The access routines are also responsible for pre-zeroing
  175472. * any newly accessed rows, if pre-zeroing was requested.
  175473. *
  175474. * In current usage, the access requests are usually for nonoverlapping
  175475. * strips; that is, successive access start_row numbers differ by exactly
  175476. * num_rows = maxaccess. This means we can get good performance with simple
  175477. * buffer dump/reload logic, by making the in-memory buffer be a multiple
  175478. * of the access height; then there will never be accesses across bufferload
  175479. * boundaries. The code will still work with overlapping access requests,
  175480. * but it doesn't handle bufferload overlaps very efficiently.
  175481. */
  175482. METHODDEF(jvirt_sarray_ptr)
  175483. request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  175484. JDIMENSION samplesperrow, JDIMENSION numrows,
  175485. JDIMENSION maxaccess)
  175486. /* Request a virtual 2-D sample array */
  175487. {
  175488. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175489. jvirt_sarray_ptr result;
  175490. /* Only IMAGE-lifetime virtual arrays are currently supported */
  175491. if (pool_id != JPOOL_IMAGE)
  175492. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  175493. /* get control block */
  175494. result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
  175495. SIZEOF(struct jvirt_sarray_control));
  175496. result->mem_buffer = NULL; /* marks array not yet realized */
  175497. result->rows_in_array = numrows;
  175498. result->samplesperrow = samplesperrow;
  175499. result->maxaccess = maxaccess;
  175500. result->pre_zero = pre_zero;
  175501. result->b_s_open = FALSE; /* no associated backing-store object */
  175502. result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
  175503. mem->virt_sarray_list = result;
  175504. return result;
  175505. }
  175506. METHODDEF(jvirt_barray_ptr)
  175507. request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  175508. JDIMENSION blocksperrow, JDIMENSION numrows,
  175509. JDIMENSION maxaccess)
  175510. /* Request a virtual 2-D coefficient-block array */
  175511. {
  175512. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175513. jvirt_barray_ptr result;
  175514. /* Only IMAGE-lifetime virtual arrays are currently supported */
  175515. if (pool_id != JPOOL_IMAGE)
  175516. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  175517. /* get control block */
  175518. result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
  175519. SIZEOF(struct jvirt_barray_control));
  175520. result->mem_buffer = NULL; /* marks array not yet realized */
  175521. result->rows_in_array = numrows;
  175522. result->blocksperrow = blocksperrow;
  175523. result->maxaccess = maxaccess;
  175524. result->pre_zero = pre_zero;
  175525. result->b_s_open = FALSE; /* no associated backing-store object */
  175526. result->next = mem->virt_barray_list; /* add to list of virtual arrays */
  175527. mem->virt_barray_list = result;
  175528. return result;
  175529. }
  175530. METHODDEF(void)
  175531. realize_virt_arrays (j_common_ptr cinfo)
  175532. /* Allocate the in-memory buffers for any unrealized virtual arrays */
  175533. {
  175534. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175535. long space_per_minheight, maximum_space, avail_mem;
  175536. long minheights, max_minheights;
  175537. jvirt_sarray_ptr sptr;
  175538. jvirt_barray_ptr bptr;
  175539. /* Compute the minimum space needed (maxaccess rows in each buffer)
  175540. * and the maximum space needed (full image height in each buffer).
  175541. * These may be of use to the system-dependent jpeg_mem_available routine.
  175542. */
  175543. space_per_minheight = 0;
  175544. maximum_space = 0;
  175545. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  175546. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  175547. space_per_minheight += (long) sptr->maxaccess *
  175548. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  175549. maximum_space += (long) sptr->rows_in_array *
  175550. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  175551. }
  175552. }
  175553. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  175554. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  175555. space_per_minheight += (long) bptr->maxaccess *
  175556. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  175557. maximum_space += (long) bptr->rows_in_array *
  175558. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  175559. }
  175560. }
  175561. if (space_per_minheight <= 0)
  175562. return; /* no unrealized arrays, no work */
  175563. /* Determine amount of memory to actually use; this is system-dependent. */
  175564. avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space,
  175565. mem->total_space_allocated);
  175566. /* If the maximum space needed is available, make all the buffers full
  175567. * height; otherwise parcel it out with the same number of minheights
  175568. * in each buffer.
  175569. */
  175570. if (avail_mem >= maximum_space)
  175571. max_minheights = 1000000000L;
  175572. else {
  175573. max_minheights = avail_mem / space_per_minheight;
  175574. /* If there doesn't seem to be enough space, try to get the minimum
  175575. * anyway. This allows a "stub" implementation of jpeg_mem_available().
  175576. */
  175577. if (max_minheights <= 0)
  175578. max_minheights = 1;
  175579. }
  175580. /* Allocate the in-memory buffers and initialize backing store as needed. */
  175581. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  175582. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  175583. minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L;
  175584. if (minheights <= max_minheights) {
  175585. /* This buffer fits in memory */
  175586. sptr->rows_in_mem = sptr->rows_in_array;
  175587. } else {
  175588. /* It doesn't fit in memory, create backing store. */
  175589. sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess);
  175590. jpeg_open_backing_store(cinfo, & sptr->b_s_info,
  175591. (long) sptr->rows_in_array *
  175592. (long) sptr->samplesperrow *
  175593. (long) SIZEOF(JSAMPLE));
  175594. sptr->b_s_open = TRUE;
  175595. }
  175596. sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,
  175597. sptr->samplesperrow, sptr->rows_in_mem);
  175598. sptr->rowsperchunk = mem->last_rowsperchunk;
  175599. sptr->cur_start_row = 0;
  175600. sptr->first_undef_row = 0;
  175601. sptr->dirty = FALSE;
  175602. }
  175603. }
  175604. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  175605. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  175606. minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;
  175607. if (minheights <= max_minheights) {
  175608. /* This buffer fits in memory */
  175609. bptr->rows_in_mem = bptr->rows_in_array;
  175610. } else {
  175611. /* It doesn't fit in memory, create backing store. */
  175612. bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess);
  175613. jpeg_open_backing_store(cinfo, & bptr->b_s_info,
  175614. (long) bptr->rows_in_array *
  175615. (long) bptr->blocksperrow *
  175616. (long) SIZEOF(JBLOCK));
  175617. bptr->b_s_open = TRUE;
  175618. }
  175619. bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
  175620. bptr->blocksperrow, bptr->rows_in_mem);
  175621. bptr->rowsperchunk = mem->last_rowsperchunk;
  175622. bptr->cur_start_row = 0;
  175623. bptr->first_undef_row = 0;
  175624. bptr->dirty = FALSE;
  175625. }
  175626. }
  175627. }
  175628. LOCAL(void)
  175629. do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
  175630. /* Do backing store read or write of a virtual sample array */
  175631. {
  175632. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  175633. bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE);
  175634. file_offset = ptr->cur_start_row * bytesperrow;
  175635. /* Loop to read or write each allocation chunk in mem_buffer */
  175636. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  175637. /* One chunk, but check for short chunk at end of buffer */
  175638. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  175639. /* Transfer no more than is currently defined */
  175640. thisrow = (long) ptr->cur_start_row + i;
  175641. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  175642. /* Transfer no more than fits in file */
  175643. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  175644. if (rows <= 0) /* this chunk might be past end of file! */
  175645. break;
  175646. byte_count = rows * bytesperrow;
  175647. if (writing)
  175648. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  175649. (void FAR *) ptr->mem_buffer[i],
  175650. file_offset, byte_count);
  175651. else
  175652. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  175653. (void FAR *) ptr->mem_buffer[i],
  175654. file_offset, byte_count);
  175655. file_offset += byte_count;
  175656. }
  175657. }
  175658. LOCAL(void)
  175659. do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
  175660. /* Do backing store read or write of a virtual coefficient-block array */
  175661. {
  175662. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  175663. bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);
  175664. file_offset = ptr->cur_start_row * bytesperrow;
  175665. /* Loop to read or write each allocation chunk in mem_buffer */
  175666. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  175667. /* One chunk, but check for short chunk at end of buffer */
  175668. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  175669. /* Transfer no more than is currently defined */
  175670. thisrow = (long) ptr->cur_start_row + i;
  175671. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  175672. /* Transfer no more than fits in file */
  175673. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  175674. if (rows <= 0) /* this chunk might be past end of file! */
  175675. break;
  175676. byte_count = rows * bytesperrow;
  175677. if (writing)
  175678. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  175679. (void FAR *) ptr->mem_buffer[i],
  175680. file_offset, byte_count);
  175681. else
  175682. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  175683. (void FAR *) ptr->mem_buffer[i],
  175684. file_offset, byte_count);
  175685. file_offset += byte_count;
  175686. }
  175687. }
  175688. METHODDEF(JSAMPARRAY)
  175689. access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
  175690. JDIMENSION start_row, JDIMENSION num_rows,
  175691. boolean writable)
  175692. /* Access the part of a virtual sample array starting at start_row */
  175693. /* and extending for num_rows rows. writable is true if */
  175694. /* caller intends to modify the accessed area. */
  175695. {
  175696. JDIMENSION end_row = start_row + num_rows;
  175697. JDIMENSION undef_row;
  175698. /* debugging check */
  175699. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  175700. ptr->mem_buffer == NULL)
  175701. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  175702. /* Make the desired part of the virtual array accessible */
  175703. if (start_row < ptr->cur_start_row ||
  175704. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  175705. if (! ptr->b_s_open)
  175706. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  175707. /* Flush old buffer contents if necessary */
  175708. if (ptr->dirty) {
  175709. do_sarray_io(cinfo, ptr, TRUE);
  175710. ptr->dirty = FALSE;
  175711. }
  175712. /* Decide what part of virtual array to access.
  175713. * Algorithm: if target address > current window, assume forward scan,
  175714. * load starting at target address. If target address < current window,
  175715. * assume backward scan, load so that target area is top of window.
  175716. * Note that when switching from forward write to forward read, will have
  175717. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  175718. */
  175719. if (start_row > ptr->cur_start_row) {
  175720. ptr->cur_start_row = start_row;
  175721. } else {
  175722. /* use long arithmetic here to avoid overflow & unsigned problems */
  175723. long ltemp;
  175724. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  175725. if (ltemp < 0)
  175726. ltemp = 0; /* don't fall off front end of file */
  175727. ptr->cur_start_row = (JDIMENSION) ltemp;
  175728. }
  175729. /* Read in the selected part of the array.
  175730. * During the initial write pass, we will do no actual read
  175731. * because the selected part is all undefined.
  175732. */
  175733. do_sarray_io(cinfo, ptr, FALSE);
  175734. }
  175735. /* Ensure the accessed part of the array is defined; prezero if needed.
  175736. * To improve locality of access, we only prezero the part of the array
  175737. * that the caller is about to access, not the entire in-memory array.
  175738. */
  175739. if (ptr->first_undef_row < end_row) {
  175740. if (ptr->first_undef_row < start_row) {
  175741. if (writable) /* writer skipped over a section of array */
  175742. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  175743. undef_row = start_row; /* but reader is allowed to read ahead */
  175744. } else {
  175745. undef_row = ptr->first_undef_row;
  175746. }
  175747. if (writable)
  175748. ptr->first_undef_row = end_row;
  175749. if (ptr->pre_zero) {
  175750. size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE);
  175751. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  175752. end_row -= ptr->cur_start_row;
  175753. while (undef_row < end_row) {
  175754. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  175755. undef_row++;
  175756. }
  175757. } else {
  175758. if (! writable) /* reader looking at undefined data */
  175759. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  175760. }
  175761. }
  175762. /* Flag the buffer dirty if caller will write in it */
  175763. if (writable)
  175764. ptr->dirty = TRUE;
  175765. /* Return address of proper part of the buffer */
  175766. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  175767. }
  175768. METHODDEF(JBLOCKARRAY)
  175769. access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
  175770. JDIMENSION start_row, JDIMENSION num_rows,
  175771. boolean writable)
  175772. /* Access the part of a virtual block array starting at start_row */
  175773. /* and extending for num_rows rows. writable is true if */
  175774. /* caller intends to modify the accessed area. */
  175775. {
  175776. JDIMENSION end_row = start_row + num_rows;
  175777. JDIMENSION undef_row;
  175778. /* debugging check */
  175779. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  175780. ptr->mem_buffer == NULL)
  175781. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  175782. /* Make the desired part of the virtual array accessible */
  175783. if (start_row < ptr->cur_start_row ||
  175784. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  175785. if (! ptr->b_s_open)
  175786. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  175787. /* Flush old buffer contents if necessary */
  175788. if (ptr->dirty) {
  175789. do_barray_io(cinfo, ptr, TRUE);
  175790. ptr->dirty = FALSE;
  175791. }
  175792. /* Decide what part of virtual array to access.
  175793. * Algorithm: if target address > current window, assume forward scan,
  175794. * load starting at target address. If target address < current window,
  175795. * assume backward scan, load so that target area is top of window.
  175796. * Note that when switching from forward write to forward read, will have
  175797. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  175798. */
  175799. if (start_row > ptr->cur_start_row) {
  175800. ptr->cur_start_row = start_row;
  175801. } else {
  175802. /* use long arithmetic here to avoid overflow & unsigned problems */
  175803. long ltemp;
  175804. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  175805. if (ltemp < 0)
  175806. ltemp = 0; /* don't fall off front end of file */
  175807. ptr->cur_start_row = (JDIMENSION) ltemp;
  175808. }
  175809. /* Read in the selected part of the array.
  175810. * During the initial write pass, we will do no actual read
  175811. * because the selected part is all undefined.
  175812. */
  175813. do_barray_io(cinfo, ptr, FALSE);
  175814. }
  175815. /* Ensure the accessed part of the array is defined; prezero if needed.
  175816. * To improve locality of access, we only prezero the part of the array
  175817. * that the caller is about to access, not the entire in-memory array.
  175818. */
  175819. if (ptr->first_undef_row < end_row) {
  175820. if (ptr->first_undef_row < start_row) {
  175821. if (writable) /* writer skipped over a section of array */
  175822. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  175823. undef_row = start_row; /* but reader is allowed to read ahead */
  175824. } else {
  175825. undef_row = ptr->first_undef_row;
  175826. }
  175827. if (writable)
  175828. ptr->first_undef_row = end_row;
  175829. if (ptr->pre_zero) {
  175830. size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK);
  175831. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  175832. end_row -= ptr->cur_start_row;
  175833. while (undef_row < end_row) {
  175834. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  175835. undef_row++;
  175836. }
  175837. } else {
  175838. if (! writable) /* reader looking at undefined data */
  175839. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  175840. }
  175841. }
  175842. /* Flag the buffer dirty if caller will write in it */
  175843. if (writable)
  175844. ptr->dirty = TRUE;
  175845. /* Return address of proper part of the buffer */
  175846. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  175847. }
  175848. /*
  175849. * Release all objects belonging to a specified pool.
  175850. */
  175851. METHODDEF(void)
  175852. free_pool (j_common_ptr cinfo, int pool_id)
  175853. {
  175854. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175855. small_pool_ptr shdr_ptr;
  175856. large_pool_ptr lhdr_ptr;
  175857. size_t space_freed;
  175858. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  175859. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  175860. #ifdef MEM_STATS
  175861. if (cinfo->err->trace_level > 1)
  175862. print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
  175863. #endif
  175864. /* If freeing IMAGE pool, close any virtual arrays first */
  175865. if (pool_id == JPOOL_IMAGE) {
  175866. jvirt_sarray_ptr sptr;
  175867. jvirt_barray_ptr bptr;
  175868. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  175869. if (sptr->b_s_open) { /* there may be no backing store */
  175870. sptr->b_s_open = FALSE; /* prevent recursive close if error */
  175871. (*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
  175872. }
  175873. }
  175874. mem->virt_sarray_list = NULL;
  175875. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  175876. if (bptr->b_s_open) { /* there may be no backing store */
  175877. bptr->b_s_open = FALSE; /* prevent recursive close if error */
  175878. (*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
  175879. }
  175880. }
  175881. mem->virt_barray_list = NULL;
  175882. }
  175883. /* Release large objects */
  175884. lhdr_ptr = mem->large_list[pool_id];
  175885. mem->large_list[pool_id] = NULL;
  175886. while (lhdr_ptr != NULL) {
  175887. large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
  175888. space_freed = lhdr_ptr->hdr.bytes_used +
  175889. lhdr_ptr->hdr.bytes_left +
  175890. SIZEOF(large_pool_hdr);
  175891. jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);
  175892. mem->total_space_allocated -= space_freed;
  175893. lhdr_ptr = next_lhdr_ptr;
  175894. }
  175895. /* Release small objects */
  175896. shdr_ptr = mem->small_list[pool_id];
  175897. mem->small_list[pool_id] = NULL;
  175898. while (shdr_ptr != NULL) {
  175899. small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
  175900. space_freed = shdr_ptr->hdr.bytes_used +
  175901. shdr_ptr->hdr.bytes_left +
  175902. SIZEOF(small_pool_hdr);
  175903. jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);
  175904. mem->total_space_allocated -= space_freed;
  175905. shdr_ptr = next_shdr_ptr;
  175906. }
  175907. }
  175908. /*
  175909. * Close up shop entirely.
  175910. * Note that this cannot be called unless cinfo->mem is non-NULL.
  175911. */
  175912. METHODDEF(void)
  175913. self_destruct (j_common_ptr cinfo)
  175914. {
  175915. int pool;
  175916. /* Close all backing store, release all memory.
  175917. * Releasing pools in reverse order might help avoid fragmentation
  175918. * with some (brain-damaged) malloc libraries.
  175919. */
  175920. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  175921. free_pool(cinfo, pool);
  175922. }
  175923. /* Release the memory manager control block too. */
  175924. jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));
  175925. cinfo->mem = NULL; /* ensures I will be called only once */
  175926. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  175927. }
  175928. /*
  175929. * Memory manager initialization.
  175930. * When this is called, only the error manager pointer is valid in cinfo!
  175931. */
  175932. GLOBAL(void)
  175933. jinit_memory_mgr (j_common_ptr cinfo)
  175934. {
  175935. my_mem_ptr mem;
  175936. long max_to_use;
  175937. int pool;
  175938. size_t test_mac;
  175939. cinfo->mem = NULL; /* for safety if init fails */
  175940. /* Check for configuration errors.
  175941. * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
  175942. * doesn't reflect any real hardware alignment requirement.
  175943. * The test is a little tricky: for X>0, X and X-1 have no one-bits
  175944. * in common if and only if X is a power of 2, ie has only one one-bit.
  175945. * Some compilers may give an "unreachable code" warning here; ignore it.
  175946. */
  175947. if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
  175948. ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
  175949. /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
  175950. * a multiple of SIZEOF(ALIGN_TYPE).
  175951. * Again, an "unreachable code" warning may be ignored here.
  175952. * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
  175953. */
  175954. test_mac = (size_t) MAX_ALLOC_CHUNK;
  175955. if ((long) test_mac != MAX_ALLOC_CHUNK ||
  175956. (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)
  175957. ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
  175958. max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
  175959. /* Attempt to allocate memory manager's control block */
  175960. mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));
  175961. if (mem == NULL) {
  175962. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  175963. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
  175964. }
  175965. /* OK, fill in the method pointers */
  175966. mem->pub.alloc_small = alloc_small;
  175967. mem->pub.alloc_large = alloc_large;
  175968. mem->pub.alloc_sarray = alloc_sarray;
  175969. mem->pub.alloc_barray = alloc_barray;
  175970. mem->pub.request_virt_sarray = request_virt_sarray;
  175971. mem->pub.request_virt_barray = request_virt_barray;
  175972. mem->pub.realize_virt_arrays = realize_virt_arrays;
  175973. mem->pub.access_virt_sarray = access_virt_sarray;
  175974. mem->pub.access_virt_barray = access_virt_barray;
  175975. mem->pub.free_pool = free_pool;
  175976. mem->pub.self_destruct = self_destruct;
  175977. /* Make MAX_ALLOC_CHUNK accessible to other modules */
  175978. mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK;
  175979. /* Initialize working state */
  175980. mem->pub.max_memory_to_use = max_to_use;
  175981. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  175982. mem->small_list[pool] = NULL;
  175983. mem->large_list[pool] = NULL;
  175984. }
  175985. mem->virt_sarray_list = NULL;
  175986. mem->virt_barray_list = NULL;
  175987. mem->total_space_allocated = SIZEOF(my_memory_mgr);
  175988. /* Declare ourselves open for business */
  175989. cinfo->mem = & mem->pub;
  175990. /* Check for an environment variable JPEGMEM; if found, override the
  175991. * default max_memory setting from jpeg_mem_init. Note that the
  175992. * surrounding application may again override this value.
  175993. * If your system doesn't support getenv(), define NO_GETENV to disable
  175994. * this feature.
  175995. */
  175996. #ifndef NO_GETENV
  175997. { char * memenv;
  175998. if ((memenv = getenv("JPEGMEM")) != NULL) {
  175999. char ch = 'x';
  176000. if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
  176001. if (ch == 'm' || ch == 'M')
  176002. max_to_use *= 1000L;
  176003. mem->pub.max_memory_to_use = max_to_use * 1000L;
  176004. }
  176005. }
  176006. }
  176007. #endif
  176008. }
  176009. /*** End of inlined file: jmemmgr.c ***/
  176010. /*** Start of inlined file: jmemnobs.c ***/
  176011. #define JPEG_INTERNALS
  176012. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc(),free() */
  176013. extern void * malloc JPP((size_t size));
  176014. extern void free JPP((void *ptr));
  176015. #endif
  176016. /*
  176017. * Memory allocation and freeing are controlled by the regular library
  176018. * routines malloc() and free().
  176019. */
  176020. GLOBAL(void *)
  176021. jpeg_get_small (j_common_ptr , size_t sizeofobject)
  176022. {
  176023. return (void *) malloc(sizeofobject);
  176024. }
  176025. GLOBAL(void)
  176026. jpeg_free_small (j_common_ptr , void * object, size_t)
  176027. {
  176028. free(object);
  176029. }
  176030. /*
  176031. * "Large" objects are treated the same as "small" ones.
  176032. * NB: although we include FAR keywords in the routine declarations,
  176033. * this file won't actually work in 80x86 small/medium model; at least,
  176034. * you probably won't be able to process useful-size images in only 64KB.
  176035. */
  176036. GLOBAL(void FAR *)
  176037. jpeg_get_large (j_common_ptr, size_t sizeofobject)
  176038. {
  176039. return (void FAR *) malloc(sizeofobject);
  176040. }
  176041. GLOBAL(void)
  176042. jpeg_free_large (j_common_ptr, void FAR * object, size_t)
  176043. {
  176044. free(object);
  176045. }
  176046. /*
  176047. * This routine computes the total memory space available for allocation.
  176048. * Here we always say, "we got all you want bud!"
  176049. */
  176050. GLOBAL(long)
  176051. jpeg_mem_available (j_common_ptr, long,
  176052. long max_bytes_needed, long)
  176053. {
  176054. return max_bytes_needed;
  176055. }
  176056. /*
  176057. * Backing store (temporary file) management.
  176058. * Since jpeg_mem_available always promised the moon,
  176059. * this should never be called and we can just error out.
  176060. */
  176061. GLOBAL(void)
  176062. jpeg_open_backing_store (j_common_ptr cinfo, struct backing_store_struct *,
  176063. long )
  176064. {
  176065. ERREXIT(cinfo, JERR_NO_BACKING_STORE);
  176066. }
  176067. /*
  176068. * These routines take care of any system-dependent initialization and
  176069. * cleanup required. Here, there isn't any.
  176070. */
  176071. GLOBAL(long)
  176072. jpeg_mem_init (j_common_ptr)
  176073. {
  176074. return 0; /* just set max_memory_to_use to 0 */
  176075. }
  176076. GLOBAL(void)
  176077. jpeg_mem_term (j_common_ptr)
  176078. {
  176079. /* no work */
  176080. }
  176081. /*** End of inlined file: jmemnobs.c ***/
  176082. /*** Start of inlined file: jquant1.c ***/
  176083. #define JPEG_INTERNALS
  176084. #ifdef QUANT_1PASS_SUPPORTED
  176085. /*
  176086. * The main purpose of 1-pass quantization is to provide a fast, if not very
  176087. * high quality, colormapped output capability. A 2-pass quantizer usually
  176088. * gives better visual quality; however, for quantized grayscale output this
  176089. * quantizer is perfectly adequate. Dithering is highly recommended with this
  176090. * quantizer, though you can turn it off if you really want to.
  176091. *
  176092. * In 1-pass quantization the colormap must be chosen in advance of seeing the
  176093. * image. We use a map consisting of all combinations of Ncolors[i] color
  176094. * values for the i'th component. The Ncolors[] values are chosen so that
  176095. * their product, the total number of colors, is no more than that requested.
  176096. * (In most cases, the product will be somewhat less.)
  176097. *
  176098. * Since the colormap is orthogonal, the representative value for each color
  176099. * component can be determined without considering the other components;
  176100. * then these indexes can be combined into a colormap index by a standard
  176101. * N-dimensional-array-subscript calculation. Most of the arithmetic involved
  176102. * can be precalculated and stored in the lookup table colorindex[].
  176103. * colorindex[i][j] maps pixel value j in component i to the nearest
  176104. * representative value (grid plane) for that component; this index is
  176105. * multiplied by the array stride for component i, so that the
  176106. * index of the colormap entry closest to a given pixel value is just
  176107. * sum( colorindex[component-number][pixel-component-value] )
  176108. * Aside from being fast, this scheme allows for variable spacing between
  176109. * representative values with no additional lookup cost.
  176110. *
  176111. * If gamma correction has been applied in color conversion, it might be wise
  176112. * to adjust the color grid spacing so that the representative colors are
  176113. * equidistant in linear space. At this writing, gamma correction is not
  176114. * implemented by jdcolor, so nothing is done here.
  176115. */
  176116. /* Declarations for ordered dithering.
  176117. *
  176118. * We use a standard 16x16 ordered dither array. The basic concept of ordered
  176119. * dithering is described in many references, for instance Dale Schumacher's
  176120. * chapter II.2 of Graphics Gems II (James Arvo, ed. Academic Press, 1991).
  176121. * In place of Schumacher's comparisons against a "threshold" value, we add a
  176122. * "dither" value to the input pixel and then round the result to the nearest
  176123. * output value. The dither value is equivalent to (0.5 - threshold) times
  176124. * the distance between output values. For ordered dithering, we assume that
  176125. * the output colors are equally spaced; if not, results will probably be
  176126. * worse, since the dither may be too much or too little at a given point.
  176127. *
  176128. * The normal calculation would be to form pixel value + dither, range-limit
  176129. * this to 0..MAXJSAMPLE, and then index into the colorindex table as usual.
  176130. * We can skip the separate range-limiting step by extending the colorindex
  176131. * table in both directions.
  176132. */
  176133. #define ODITHER_SIZE 16 /* dimension of dither matrix */
  176134. /* NB: if ODITHER_SIZE is not a power of 2, ODITHER_MASK uses will break */
  176135. #define ODITHER_CELLS (ODITHER_SIZE*ODITHER_SIZE) /* # cells in matrix */
  176136. #define ODITHER_MASK (ODITHER_SIZE-1) /* mask for wrapping around counters */
  176137. typedef int ODITHER_MATRIX[ODITHER_SIZE][ODITHER_SIZE];
  176138. typedef int (*ODITHER_MATRIX_PTR)[ODITHER_SIZE];
  176139. static const UINT8 base_dither_matrix[ODITHER_SIZE][ODITHER_SIZE] = {
  176140. /* Bayer's order-4 dither array. Generated by the code given in
  176141. * Stephen Hawley's article "Ordered Dithering" in Graphics Gems I.
  176142. * The values in this array must range from 0 to ODITHER_CELLS-1.
  176143. */
  176144. { 0,192, 48,240, 12,204, 60,252, 3,195, 51,243, 15,207, 63,255 },
  176145. { 128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127 },
  176146. { 32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223 },
  176147. { 160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95 },
  176148. { 8,200, 56,248, 4,196, 52,244, 11,203, 59,251, 7,199, 55,247 },
  176149. { 136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119 },
  176150. { 40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215 },
  176151. { 168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87 },
  176152. { 2,194, 50,242, 14,206, 62,254, 1,193, 49,241, 13,205, 61,253 },
  176153. { 130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125 },
  176154. { 34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221 },
  176155. { 162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93 },
  176156. { 10,202, 58,250, 6,198, 54,246, 9,201, 57,249, 5,197, 53,245 },
  176157. { 138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117 },
  176158. { 42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213 },
  176159. { 170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85 }
  176160. };
  176161. /* Declarations for Floyd-Steinberg dithering.
  176162. *
  176163. * Errors are accumulated into the array fserrors[], at a resolution of
  176164. * 1/16th of a pixel count. The error at a given pixel is propagated
  176165. * to its not-yet-processed neighbors using the standard F-S fractions,
  176166. * ... (here) 7/16
  176167. * 3/16 5/16 1/16
  176168. * We work left-to-right on even rows, right-to-left on odd rows.
  176169. *
  176170. * We can get away with a single array (holding one row's worth of errors)
  176171. * by using it to store the current row's errors at pixel columns not yet
  176172. * processed, but the next row's errors at columns already processed. We
  176173. * need only a few extra variables to hold the errors immediately around the
  176174. * current column. (If we are lucky, those variables are in registers, but
  176175. * even if not, they're probably cheaper to access than array elements are.)
  176176. *
  176177. * The fserrors[] array is indexed [component#][position].
  176178. * We provide (#columns + 2) entries per component; the extra entry at each
  176179. * end saves us from special-casing the first and last pixels.
  176180. *
  176181. * Note: on a wide image, we might not have enough room in a PC's near data
  176182. * segment to hold the error array; so it is allocated with alloc_large.
  176183. */
  176184. #if BITS_IN_JSAMPLE == 8
  176185. typedef INT16 FSERROR; /* 16 bits should be enough */
  176186. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  176187. #else
  176188. typedef INT32 FSERROR; /* may need more than 16 bits */
  176189. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  176190. #endif
  176191. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  176192. /* Private subobject */
  176193. #define MAX_Q_COMPS 4 /* max components I can handle */
  176194. typedef struct {
  176195. struct jpeg_color_quantizer pub; /* public fields */
  176196. /* Initially allocated colormap is saved here */
  176197. JSAMPARRAY sv_colormap; /* The color map as a 2-D pixel array */
  176198. int sv_actual; /* number of entries in use */
  176199. JSAMPARRAY colorindex; /* Precomputed mapping for speed */
  176200. /* colorindex[i][j] = index of color closest to pixel value j in component i,
  176201. * premultiplied as described above. Since colormap indexes must fit into
  176202. * JSAMPLEs, the entries of this array will too.
  176203. */
  176204. boolean is_padded; /* is the colorindex padded for odither? */
  176205. int Ncolors[MAX_Q_COMPS]; /* # of values alloced to each component */
  176206. /* Variables for ordered dithering */
  176207. int row_index; /* cur row's vertical index in dither matrix */
  176208. ODITHER_MATRIX_PTR odither[MAX_Q_COMPS]; /* one dither array per component */
  176209. /* Variables for Floyd-Steinberg dithering */
  176210. FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */
  176211. boolean on_odd_row; /* flag to remember which row we are on */
  176212. } my_cquantizer;
  176213. typedef my_cquantizer * my_cquantize_ptr;
  176214. /*
  176215. * Policy-making subroutines for create_colormap and create_colorindex.
  176216. * These routines determine the colormap to be used. The rest of the module
  176217. * only assumes that the colormap is orthogonal.
  176218. *
  176219. * * select_ncolors decides how to divvy up the available colors
  176220. * among the components.
  176221. * * output_value defines the set of representative values for a component.
  176222. * * largest_input_value defines the mapping from input values to
  176223. * representative values for a component.
  176224. * Note that the latter two routines may impose different policies for
  176225. * different components, though this is not currently done.
  176226. */
  176227. LOCAL(int)
  176228. select_ncolors (j_decompress_ptr cinfo, int Ncolors[])
  176229. /* Determine allocation of desired colors to components, */
  176230. /* and fill in Ncolors[] array to indicate choice. */
  176231. /* Return value is total number of colors (product of Ncolors[] values). */
  176232. {
  176233. int nc = cinfo->out_color_components; /* number of color components */
  176234. int max_colors = cinfo->desired_number_of_colors;
  176235. int total_colors, iroot, i, j;
  176236. boolean changed;
  176237. long temp;
  176238. static const int RGB_order[3] = { RGB_GREEN, RGB_RED, RGB_BLUE };
  176239. /* We can allocate at least the nc'th root of max_colors per component. */
  176240. /* Compute floor(nc'th root of max_colors). */
  176241. iroot = 1;
  176242. do {
  176243. iroot++;
  176244. temp = iroot; /* set temp = iroot ** nc */
  176245. for (i = 1; i < nc; i++)
  176246. temp *= iroot;
  176247. } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */
  176248. iroot--; /* now iroot = floor(root) */
  176249. /* Must have at least 2 color values per component */
  176250. if (iroot < 2)
  176251. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, (int) temp);
  176252. /* Initialize to iroot color values for each component */
  176253. total_colors = 1;
  176254. for (i = 0; i < nc; i++) {
  176255. Ncolors[i] = iroot;
  176256. total_colors *= iroot;
  176257. }
  176258. /* We may be able to increment the count for one or more components without
  176259. * exceeding max_colors, though we know not all can be incremented.
  176260. * Sometimes, the first component can be incremented more than once!
  176261. * (Example: for 16 colors, we start at 2*2*2, go to 3*2*2, then 4*2*2.)
  176262. * In RGB colorspace, try to increment G first, then R, then B.
  176263. */
  176264. do {
  176265. changed = FALSE;
  176266. for (i = 0; i < nc; i++) {
  176267. j = (cinfo->out_color_space == JCS_RGB ? RGB_order[i] : i);
  176268. /* calculate new total_colors if Ncolors[j] is incremented */
  176269. temp = total_colors / Ncolors[j];
  176270. temp *= Ncolors[j]+1; /* done in long arith to avoid oflo */
  176271. if (temp > (long) max_colors)
  176272. break; /* won't fit, done with this pass */
  176273. Ncolors[j]++; /* OK, apply the increment */
  176274. total_colors = (int) temp;
  176275. changed = TRUE;
  176276. }
  176277. } while (changed);
  176278. return total_colors;
  176279. }
  176280. LOCAL(int)
  176281. output_value (j_decompress_ptr, int, int j, int maxj)
  176282. /* Return j'th output value, where j will range from 0 to maxj */
  176283. /* The output values must fall in 0..MAXJSAMPLE in increasing order */
  176284. {
  176285. /* We always provide values 0 and MAXJSAMPLE for each component;
  176286. * any additional values are equally spaced between these limits.
  176287. * (Forcing the upper and lower values to the limits ensures that
  176288. * dithering can't produce a color outside the selected gamut.)
  176289. */
  176290. return (int) (((INT32) j * MAXJSAMPLE + maxj/2) / maxj);
  176291. }
  176292. LOCAL(int)
  176293. largest_input_value (j_decompress_ptr, int, int j, int maxj)
  176294. /* Return largest input value that should map to j'th output value */
  176295. /* Must have largest(j=0) >= 0, and largest(j=maxj) >= MAXJSAMPLE */
  176296. {
  176297. /* Breakpoints are halfway between values returned by output_value */
  176298. return (int) (((INT32) (2*j + 1) * MAXJSAMPLE + maxj) / (2*maxj));
  176299. }
  176300. /*
  176301. * Create the colormap.
  176302. */
  176303. LOCAL(void)
  176304. create_colormap (j_decompress_ptr cinfo)
  176305. {
  176306. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176307. JSAMPARRAY colormap; /* Created colormap */
  176308. int total_colors; /* Number of distinct output colors */
  176309. int i,j,k, nci, blksize, blkdist, ptr, val;
  176310. /* Select number of colors for each component */
  176311. total_colors = select_ncolors(cinfo, cquantize->Ncolors);
  176312. /* Report selected color counts */
  176313. if (cinfo->out_color_components == 3)
  176314. TRACEMS4(cinfo, 1, JTRC_QUANT_3_NCOLORS,
  176315. total_colors, cquantize->Ncolors[0],
  176316. cquantize->Ncolors[1], cquantize->Ncolors[2]);
  176317. else
  176318. TRACEMS1(cinfo, 1, JTRC_QUANT_NCOLORS, total_colors);
  176319. /* Allocate and fill in the colormap. */
  176320. /* The colors are ordered in the map in standard row-major order, */
  176321. /* i.e. rightmost (highest-indexed) color changes most rapidly. */
  176322. colormap = (*cinfo->mem->alloc_sarray)
  176323. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  176324. (JDIMENSION) total_colors, (JDIMENSION) cinfo->out_color_components);
  176325. /* blksize is number of adjacent repeated entries for a component */
  176326. /* blkdist is distance between groups of identical entries for a component */
  176327. blkdist = total_colors;
  176328. for (i = 0; i < cinfo->out_color_components; i++) {
  176329. /* fill in colormap entries for i'th color component */
  176330. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  176331. blksize = blkdist / nci;
  176332. for (j = 0; j < nci; j++) {
  176333. /* Compute j'th output value (out of nci) for component */
  176334. val = output_value(cinfo, i, j, nci-1);
  176335. /* Fill in all colormap entries that have this value of this component */
  176336. for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) {
  176337. /* fill in blksize entries beginning at ptr */
  176338. for (k = 0; k < blksize; k++)
  176339. colormap[i][ptr+k] = (JSAMPLE) val;
  176340. }
  176341. }
  176342. blkdist = blksize; /* blksize of this color is blkdist of next */
  176343. }
  176344. /* Save the colormap in private storage,
  176345. * where it will survive color quantization mode changes.
  176346. */
  176347. cquantize->sv_colormap = colormap;
  176348. cquantize->sv_actual = total_colors;
  176349. }
  176350. /*
  176351. * Create the color index table.
  176352. */
  176353. LOCAL(void)
  176354. create_colorindex (j_decompress_ptr cinfo)
  176355. {
  176356. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176357. JSAMPROW indexptr;
  176358. int i,j,k, nci, blksize, val, pad;
  176359. /* For ordered dither, we pad the color index tables by MAXJSAMPLE in
  176360. * each direction (input index values can be -MAXJSAMPLE .. 2*MAXJSAMPLE).
  176361. * This is not necessary in the other dithering modes. However, we
  176362. * flag whether it was done in case user changes dithering mode.
  176363. */
  176364. if (cinfo->dither_mode == JDITHER_ORDERED) {
  176365. pad = MAXJSAMPLE*2;
  176366. cquantize->is_padded = TRUE;
  176367. } else {
  176368. pad = 0;
  176369. cquantize->is_padded = FALSE;
  176370. }
  176371. cquantize->colorindex = (*cinfo->mem->alloc_sarray)
  176372. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  176373. (JDIMENSION) (MAXJSAMPLE+1 + pad),
  176374. (JDIMENSION) cinfo->out_color_components);
  176375. /* blksize is number of adjacent repeated entries for a component */
  176376. blksize = cquantize->sv_actual;
  176377. for (i = 0; i < cinfo->out_color_components; i++) {
  176378. /* fill in colorindex entries for i'th color component */
  176379. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  176380. blksize = blksize / nci;
  176381. /* adjust colorindex pointers to provide padding at negative indexes. */
  176382. if (pad)
  176383. cquantize->colorindex[i] += MAXJSAMPLE;
  176384. /* in loop, val = index of current output value, */
  176385. /* and k = largest j that maps to current val */
  176386. indexptr = cquantize->colorindex[i];
  176387. val = 0;
  176388. k = largest_input_value(cinfo, i, 0, nci-1);
  176389. for (j = 0; j <= MAXJSAMPLE; j++) {
  176390. while (j > k) /* advance val if past boundary */
  176391. k = largest_input_value(cinfo, i, ++val, nci-1);
  176392. /* premultiply so that no multiplication needed in main processing */
  176393. indexptr[j] = (JSAMPLE) (val * blksize);
  176394. }
  176395. /* Pad at both ends if necessary */
  176396. if (pad)
  176397. for (j = 1; j <= MAXJSAMPLE; j++) {
  176398. indexptr[-j] = indexptr[0];
  176399. indexptr[MAXJSAMPLE+j] = indexptr[MAXJSAMPLE];
  176400. }
  176401. }
  176402. }
  176403. /*
  176404. * Create an ordered-dither array for a component having ncolors
  176405. * distinct output values.
  176406. */
  176407. LOCAL(ODITHER_MATRIX_PTR)
  176408. make_odither_array (j_decompress_ptr cinfo, int ncolors)
  176409. {
  176410. ODITHER_MATRIX_PTR odither;
  176411. int j,k;
  176412. INT32 num,den;
  176413. odither = (ODITHER_MATRIX_PTR)
  176414. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  176415. SIZEOF(ODITHER_MATRIX));
  176416. /* The inter-value distance for this color is MAXJSAMPLE/(ncolors-1).
  176417. * Hence the dither value for the matrix cell with fill order f
  176418. * (f=0..N-1) should be (N-1-2*f)/(2*N) * MAXJSAMPLE/(ncolors-1).
  176419. * On 16-bit-int machine, be careful to avoid overflow.
  176420. */
  176421. den = 2 * ODITHER_CELLS * ((INT32) (ncolors - 1));
  176422. for (j = 0; j < ODITHER_SIZE; j++) {
  176423. for (k = 0; k < ODITHER_SIZE; k++) {
  176424. num = ((INT32) (ODITHER_CELLS-1 - 2*((int)base_dither_matrix[j][k])))
  176425. * MAXJSAMPLE;
  176426. /* Ensure round towards zero despite C's lack of consistency
  176427. * about rounding negative values in integer division...
  176428. */
  176429. odither[j][k] = (int) (num<0 ? -((-num)/den) : num/den);
  176430. }
  176431. }
  176432. return odither;
  176433. }
  176434. /*
  176435. * Create the ordered-dither tables.
  176436. * Components having the same number of representative colors may
  176437. * share a dither table.
  176438. */
  176439. LOCAL(void)
  176440. create_odither_tables (j_decompress_ptr cinfo)
  176441. {
  176442. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176443. ODITHER_MATRIX_PTR odither;
  176444. int i, j, nci;
  176445. for (i = 0; i < cinfo->out_color_components; i++) {
  176446. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  176447. odither = NULL; /* search for matching prior component */
  176448. for (j = 0; j < i; j++) {
  176449. if (nci == cquantize->Ncolors[j]) {
  176450. odither = cquantize->odither[j];
  176451. break;
  176452. }
  176453. }
  176454. if (odither == NULL) /* need a new table? */
  176455. odither = make_odither_array(cinfo, nci);
  176456. cquantize->odither[i] = odither;
  176457. }
  176458. }
  176459. /*
  176460. * Map some rows of pixels to the output colormapped representation.
  176461. */
  176462. METHODDEF(void)
  176463. color_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  176464. JSAMPARRAY output_buf, int num_rows)
  176465. /* General case, no dithering */
  176466. {
  176467. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176468. JSAMPARRAY colorindex = cquantize->colorindex;
  176469. register int pixcode, ci;
  176470. register JSAMPROW ptrin, ptrout;
  176471. int row;
  176472. JDIMENSION col;
  176473. JDIMENSION width = cinfo->output_width;
  176474. register int nc = cinfo->out_color_components;
  176475. for (row = 0; row < num_rows; row++) {
  176476. ptrin = input_buf[row];
  176477. ptrout = output_buf[row];
  176478. for (col = width; col > 0; col--) {
  176479. pixcode = 0;
  176480. for (ci = 0; ci < nc; ci++) {
  176481. pixcode += GETJSAMPLE(colorindex[ci][GETJSAMPLE(*ptrin++)]);
  176482. }
  176483. *ptrout++ = (JSAMPLE) pixcode;
  176484. }
  176485. }
  176486. }
  176487. METHODDEF(void)
  176488. color_quantize3 (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  176489. JSAMPARRAY output_buf, int num_rows)
  176490. /* Fast path for out_color_components==3, no dithering */
  176491. {
  176492. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176493. register int pixcode;
  176494. register JSAMPROW ptrin, ptrout;
  176495. JSAMPROW colorindex0 = cquantize->colorindex[0];
  176496. JSAMPROW colorindex1 = cquantize->colorindex[1];
  176497. JSAMPROW colorindex2 = cquantize->colorindex[2];
  176498. int row;
  176499. JDIMENSION col;
  176500. JDIMENSION width = cinfo->output_width;
  176501. for (row = 0; row < num_rows; row++) {
  176502. ptrin = input_buf[row];
  176503. ptrout = output_buf[row];
  176504. for (col = width; col > 0; col--) {
  176505. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*ptrin++)]);
  176506. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*ptrin++)]);
  176507. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*ptrin++)]);
  176508. *ptrout++ = (JSAMPLE) pixcode;
  176509. }
  176510. }
  176511. }
  176512. METHODDEF(void)
  176513. quantize_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  176514. JSAMPARRAY output_buf, int num_rows)
  176515. /* General case, with ordered dithering */
  176516. {
  176517. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176518. register JSAMPROW input_ptr;
  176519. register JSAMPROW output_ptr;
  176520. JSAMPROW colorindex_ci;
  176521. int * dither; /* points to active row of dither matrix */
  176522. int row_index, col_index; /* current indexes into dither matrix */
  176523. int nc = cinfo->out_color_components;
  176524. int ci;
  176525. int row;
  176526. JDIMENSION col;
  176527. JDIMENSION width = cinfo->output_width;
  176528. for (row = 0; row < num_rows; row++) {
  176529. /* Initialize output values to 0 so can process components separately */
  176530. jzero_far((void FAR *) output_buf[row],
  176531. (size_t) (width * SIZEOF(JSAMPLE)));
  176532. row_index = cquantize->row_index;
  176533. for (ci = 0; ci < nc; ci++) {
  176534. input_ptr = input_buf[row] + ci;
  176535. output_ptr = output_buf[row];
  176536. colorindex_ci = cquantize->colorindex[ci];
  176537. dither = cquantize->odither[ci][row_index];
  176538. col_index = 0;
  176539. for (col = width; col > 0; col--) {
  176540. /* Form pixel value + dither, range-limit to 0..MAXJSAMPLE,
  176541. * select output value, accumulate into output code for this pixel.
  176542. * Range-limiting need not be done explicitly, as we have extended
  176543. * the colorindex table to produce the right answers for out-of-range
  176544. * inputs. The maximum dither is +- MAXJSAMPLE; this sets the
  176545. * required amount of padding.
  176546. */
  176547. *output_ptr += colorindex_ci[GETJSAMPLE(*input_ptr)+dither[col_index]];
  176548. input_ptr += nc;
  176549. output_ptr++;
  176550. col_index = (col_index + 1) & ODITHER_MASK;
  176551. }
  176552. }
  176553. /* Advance row index for next row */
  176554. row_index = (row_index + 1) & ODITHER_MASK;
  176555. cquantize->row_index = row_index;
  176556. }
  176557. }
  176558. METHODDEF(void)
  176559. quantize3_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  176560. JSAMPARRAY output_buf, int num_rows)
  176561. /* Fast path for out_color_components==3, with ordered dithering */
  176562. {
  176563. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176564. register int pixcode;
  176565. register JSAMPROW input_ptr;
  176566. register JSAMPROW output_ptr;
  176567. JSAMPROW colorindex0 = cquantize->colorindex[0];
  176568. JSAMPROW colorindex1 = cquantize->colorindex[1];
  176569. JSAMPROW colorindex2 = cquantize->colorindex[2];
  176570. int * dither0; /* points to active row of dither matrix */
  176571. int * dither1;
  176572. int * dither2;
  176573. int row_index, col_index; /* current indexes into dither matrix */
  176574. int row;
  176575. JDIMENSION col;
  176576. JDIMENSION width = cinfo->output_width;
  176577. for (row = 0; row < num_rows; row++) {
  176578. row_index = cquantize->row_index;
  176579. input_ptr = input_buf[row];
  176580. output_ptr = output_buf[row];
  176581. dither0 = cquantize->odither[0][row_index];
  176582. dither1 = cquantize->odither[1][row_index];
  176583. dither2 = cquantize->odither[2][row_index];
  176584. col_index = 0;
  176585. for (col = width; col > 0; col--) {
  176586. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*input_ptr++) +
  176587. dither0[col_index]]);
  176588. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*input_ptr++) +
  176589. dither1[col_index]]);
  176590. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*input_ptr++) +
  176591. dither2[col_index]]);
  176592. *output_ptr++ = (JSAMPLE) pixcode;
  176593. col_index = (col_index + 1) & ODITHER_MASK;
  176594. }
  176595. row_index = (row_index + 1) & ODITHER_MASK;
  176596. cquantize->row_index = row_index;
  176597. }
  176598. }
  176599. METHODDEF(void)
  176600. quantize_fs_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  176601. JSAMPARRAY output_buf, int num_rows)
  176602. /* General case, with Floyd-Steinberg dithering */
  176603. {
  176604. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176605. register LOCFSERROR cur; /* current error or pixel value */
  176606. LOCFSERROR belowerr; /* error for pixel below cur */
  176607. LOCFSERROR bpreverr; /* error for below/prev col */
  176608. LOCFSERROR bnexterr; /* error for below/next col */
  176609. LOCFSERROR delta;
  176610. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  176611. register JSAMPROW input_ptr;
  176612. register JSAMPROW output_ptr;
  176613. JSAMPROW colorindex_ci;
  176614. JSAMPROW colormap_ci;
  176615. int pixcode;
  176616. int nc = cinfo->out_color_components;
  176617. int dir; /* 1 for left-to-right, -1 for right-to-left */
  176618. int dirnc; /* dir * nc */
  176619. int ci;
  176620. int row;
  176621. JDIMENSION col;
  176622. JDIMENSION width = cinfo->output_width;
  176623. JSAMPLE *range_limit = cinfo->sample_range_limit;
  176624. SHIFT_TEMPS
  176625. for (row = 0; row < num_rows; row++) {
  176626. /* Initialize output values to 0 so can process components separately */
  176627. jzero_far((void FAR *) output_buf[row],
  176628. (size_t) (width * SIZEOF(JSAMPLE)));
  176629. for (ci = 0; ci < nc; ci++) {
  176630. input_ptr = input_buf[row] + ci;
  176631. output_ptr = output_buf[row];
  176632. if (cquantize->on_odd_row) {
  176633. /* work right to left in this row */
  176634. input_ptr += (width-1) * nc; /* so point to rightmost pixel */
  176635. output_ptr += width-1;
  176636. dir = -1;
  176637. dirnc = -nc;
  176638. errorptr = cquantize->fserrors[ci] + (width+1); /* => entry after last column */
  176639. } else {
  176640. /* work left to right in this row */
  176641. dir = 1;
  176642. dirnc = nc;
  176643. errorptr = cquantize->fserrors[ci]; /* => entry before first column */
  176644. }
  176645. colorindex_ci = cquantize->colorindex[ci];
  176646. colormap_ci = cquantize->sv_colormap[ci];
  176647. /* Preset error values: no error propagated to first pixel from left */
  176648. cur = 0;
  176649. /* and no error propagated to row below yet */
  176650. belowerr = bpreverr = 0;
  176651. for (col = width; col > 0; col--) {
  176652. /* cur holds the error propagated from the previous pixel on the
  176653. * current line. Add the error propagated from the previous line
  176654. * to form the complete error correction term for this pixel, and
  176655. * round the error term (which is expressed * 16) to an integer.
  176656. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  176657. * for either sign of the error value.
  176658. * Note: errorptr points to *previous* column's array entry.
  176659. */
  176660. cur = RIGHT_SHIFT(cur + errorptr[dir] + 8, 4);
  176661. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  176662. * The maximum error is +- MAXJSAMPLE; this sets the required size
  176663. * of the range_limit array.
  176664. */
  176665. cur += GETJSAMPLE(*input_ptr);
  176666. cur = GETJSAMPLE(range_limit[cur]);
  176667. /* Select output value, accumulate into output code for this pixel */
  176668. pixcode = GETJSAMPLE(colorindex_ci[cur]);
  176669. *output_ptr += (JSAMPLE) pixcode;
  176670. /* Compute actual representation error at this pixel */
  176671. /* Note: we can do this even though we don't have the final */
  176672. /* pixel code, because the colormap is orthogonal. */
  176673. cur -= GETJSAMPLE(colormap_ci[pixcode]);
  176674. /* Compute error fractions to be propagated to adjacent pixels.
  176675. * Add these into the running sums, and simultaneously shift the
  176676. * next-line error sums left by 1 column.
  176677. */
  176678. bnexterr = cur;
  176679. delta = cur * 2;
  176680. cur += delta; /* form error * 3 */
  176681. errorptr[0] = (FSERROR) (bpreverr + cur);
  176682. cur += delta; /* form error * 5 */
  176683. bpreverr = belowerr + cur;
  176684. belowerr = bnexterr;
  176685. cur += delta; /* form error * 7 */
  176686. /* At this point cur contains the 7/16 error value to be propagated
  176687. * to the next pixel on the current line, and all the errors for the
  176688. * next line have been shifted over. We are therefore ready to move on.
  176689. */
  176690. input_ptr += dirnc; /* advance input ptr to next column */
  176691. output_ptr += dir; /* advance output ptr to next column */
  176692. errorptr += dir; /* advance errorptr to current column */
  176693. }
  176694. /* Post-loop cleanup: we must unload the final error value into the
  176695. * final fserrors[] entry. Note we need not unload belowerr because
  176696. * it is for the dummy column before or after the actual array.
  176697. */
  176698. errorptr[0] = (FSERROR) bpreverr; /* unload prev err into array */
  176699. }
  176700. cquantize->on_odd_row = (cquantize->on_odd_row ? FALSE : TRUE);
  176701. }
  176702. }
  176703. /*
  176704. * Allocate workspace for Floyd-Steinberg errors.
  176705. */
  176706. LOCAL(void)
  176707. alloc_fs_workspace (j_decompress_ptr cinfo)
  176708. {
  176709. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176710. size_t arraysize;
  176711. int i;
  176712. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  176713. for (i = 0; i < cinfo->out_color_components; i++) {
  176714. cquantize->fserrors[i] = (FSERRPTR)
  176715. (*cinfo->mem->alloc_large)((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  176716. }
  176717. }
  176718. /*
  176719. * Initialize for one-pass color quantization.
  176720. */
  176721. METHODDEF(void)
  176722. start_pass_1_quant (j_decompress_ptr cinfo, boolean)
  176723. {
  176724. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176725. size_t arraysize;
  176726. int i;
  176727. /* Install my colormap. */
  176728. cinfo->colormap = cquantize->sv_colormap;
  176729. cinfo->actual_number_of_colors = cquantize->sv_actual;
  176730. /* Initialize for desired dithering mode. */
  176731. switch (cinfo->dither_mode) {
  176732. case JDITHER_NONE:
  176733. if (cinfo->out_color_components == 3)
  176734. cquantize->pub.color_quantize = color_quantize3;
  176735. else
  176736. cquantize->pub.color_quantize = color_quantize;
  176737. break;
  176738. case JDITHER_ORDERED:
  176739. if (cinfo->out_color_components == 3)
  176740. cquantize->pub.color_quantize = quantize3_ord_dither;
  176741. else
  176742. cquantize->pub.color_quantize = quantize_ord_dither;
  176743. cquantize->row_index = 0; /* initialize state for ordered dither */
  176744. /* If user changed to ordered dither from another mode,
  176745. * we must recreate the color index table with padding.
  176746. * This will cost extra space, but probably isn't very likely.
  176747. */
  176748. if (! cquantize->is_padded)
  176749. create_colorindex(cinfo);
  176750. /* Create ordered-dither tables if we didn't already. */
  176751. if (cquantize->odither[0] == NULL)
  176752. create_odither_tables(cinfo);
  176753. break;
  176754. case JDITHER_FS:
  176755. cquantize->pub.color_quantize = quantize_fs_dither;
  176756. cquantize->on_odd_row = FALSE; /* initialize state for F-S dither */
  176757. /* Allocate Floyd-Steinberg workspace if didn't already. */
  176758. if (cquantize->fserrors[0] == NULL)
  176759. alloc_fs_workspace(cinfo);
  176760. /* Initialize the propagated errors to zero. */
  176761. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  176762. for (i = 0; i < cinfo->out_color_components; i++)
  176763. jzero_far((void FAR *) cquantize->fserrors[i], arraysize);
  176764. break;
  176765. default:
  176766. ERREXIT(cinfo, JERR_NOT_COMPILED);
  176767. break;
  176768. }
  176769. }
  176770. /*
  176771. * Finish up at the end of the pass.
  176772. */
  176773. METHODDEF(void)
  176774. finish_pass_1_quant (j_decompress_ptr)
  176775. {
  176776. /* no work in 1-pass case */
  176777. }
  176778. /*
  176779. * Switch to a new external colormap between output passes.
  176780. * Shouldn't get to this module!
  176781. */
  176782. METHODDEF(void)
  176783. new_color_map_1_quant (j_decompress_ptr cinfo)
  176784. {
  176785. ERREXIT(cinfo, JERR_MODE_CHANGE);
  176786. }
  176787. /*
  176788. * Module initialization routine for 1-pass color quantization.
  176789. */
  176790. GLOBAL(void)
  176791. jinit_1pass_quantizer (j_decompress_ptr cinfo)
  176792. {
  176793. my_cquantize_ptr cquantize;
  176794. cquantize = (my_cquantize_ptr)
  176795. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  176796. SIZEOF(my_cquantizer));
  176797. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  176798. cquantize->pub.start_pass = start_pass_1_quant;
  176799. cquantize->pub.finish_pass = finish_pass_1_quant;
  176800. cquantize->pub.new_color_map = new_color_map_1_quant;
  176801. cquantize->fserrors[0] = NULL; /* Flag FS workspace not allocated */
  176802. cquantize->odither[0] = NULL; /* Also flag odither arrays not allocated */
  176803. /* Make sure my internal arrays won't overflow */
  176804. if (cinfo->out_color_components > MAX_Q_COMPS)
  176805. ERREXIT1(cinfo, JERR_QUANT_COMPONENTS, MAX_Q_COMPS);
  176806. /* Make sure colormap indexes can be represented by JSAMPLEs */
  176807. if (cinfo->desired_number_of_colors > (MAXJSAMPLE+1))
  176808. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXJSAMPLE+1);
  176809. /* Create the colormap and color index table. */
  176810. create_colormap(cinfo);
  176811. create_colorindex(cinfo);
  176812. /* Allocate Floyd-Steinberg workspace now if requested.
  176813. * We do this now since it is FAR storage and may affect the memory
  176814. * manager's space calculations. If the user changes to FS dither
  176815. * mode in a later pass, we will allocate the space then, and will
  176816. * possibly overrun the max_memory_to_use setting.
  176817. */
  176818. if (cinfo->dither_mode == JDITHER_FS)
  176819. alloc_fs_workspace(cinfo);
  176820. }
  176821. #endif /* QUANT_1PASS_SUPPORTED */
  176822. /*** End of inlined file: jquant1.c ***/
  176823. /*** Start of inlined file: jquant2.c ***/
  176824. #define JPEG_INTERNALS
  176825. #ifdef QUANT_2PASS_SUPPORTED
  176826. /*
  176827. * This module implements the well-known Heckbert paradigm for color
  176828. * quantization. Most of the ideas used here can be traced back to
  176829. * Heckbert's seminal paper
  176830. * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
  176831. * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
  176832. *
  176833. * In the first pass over the image, we accumulate a histogram showing the
  176834. * usage count of each possible color. To keep the histogram to a reasonable
  176835. * size, we reduce the precision of the input; typical practice is to retain
  176836. * 5 or 6 bits per color, so that 8 or 4 different input values are counted
  176837. * in the same histogram cell.
  176838. *
  176839. * Next, the color-selection step begins with a box representing the whole
  176840. * color space, and repeatedly splits the "largest" remaining box until we
  176841. * have as many boxes as desired colors. Then the mean color in each
  176842. * remaining box becomes one of the possible output colors.
  176843. *
  176844. * The second pass over the image maps each input pixel to the closest output
  176845. * color (optionally after applying a Floyd-Steinberg dithering correction).
  176846. * This mapping is logically trivial, but making it go fast enough requires
  176847. * considerable care.
  176848. *
  176849. * Heckbert-style quantizers vary a good deal in their policies for choosing
  176850. * the "largest" box and deciding where to cut it. The particular policies
  176851. * used here have proved out well in experimental comparisons, but better ones
  176852. * may yet be found.
  176853. *
  176854. * In earlier versions of the IJG code, this module quantized in YCbCr color
  176855. * space, processing the raw upsampled data without a color conversion step.
  176856. * This allowed the color conversion math to be done only once per colormap
  176857. * entry, not once per pixel. However, that optimization precluded other
  176858. * useful optimizations (such as merging color conversion with upsampling)
  176859. * and it also interfered with desired capabilities such as quantizing to an
  176860. * externally-supplied colormap. We have therefore abandoned that approach.
  176861. * The present code works in the post-conversion color space, typically RGB.
  176862. *
  176863. * To improve the visual quality of the results, we actually work in scaled
  176864. * RGB space, giving G distances more weight than R, and R in turn more than
  176865. * B. To do everything in integer math, we must use integer scale factors.
  176866. * The 2/3/1 scale factors used here correspond loosely to the relative
  176867. * weights of the colors in the NTSC grayscale equation.
  176868. * If you want to use this code to quantize a non-RGB color space, you'll
  176869. * probably need to change these scale factors.
  176870. */
  176871. #define R_SCALE 2 /* scale R distances by this much */
  176872. #define G_SCALE 3 /* scale G distances by this much */
  176873. #define B_SCALE 1 /* and B by this much */
  176874. /* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
  176875. * in jmorecfg.h. As the code stands, it will do the right thing for R,G,B
  176876. * and B,G,R orders. If you define some other weird order in jmorecfg.h,
  176877. * you'll get compile errors until you extend this logic. In that case
  176878. * you'll probably want to tweak the histogram sizes too.
  176879. */
  176880. #if RGB_RED == 0
  176881. #define C0_SCALE R_SCALE
  176882. #endif
  176883. #if RGB_BLUE == 0
  176884. #define C0_SCALE B_SCALE
  176885. #endif
  176886. #if RGB_GREEN == 1
  176887. #define C1_SCALE G_SCALE
  176888. #endif
  176889. #if RGB_RED == 2
  176890. #define C2_SCALE R_SCALE
  176891. #endif
  176892. #if RGB_BLUE == 2
  176893. #define C2_SCALE B_SCALE
  176894. #endif
  176895. /*
  176896. * First we have the histogram data structure and routines for creating it.
  176897. *
  176898. * The number of bits of precision can be adjusted by changing these symbols.
  176899. * We recommend keeping 6 bits for G and 5 each for R and B.
  176900. * If you have plenty of memory and cycles, 6 bits all around gives marginally
  176901. * better results; if you are short of memory, 5 bits all around will save
  176902. * some space but degrade the results.
  176903. * To maintain a fully accurate histogram, we'd need to allocate a "long"
  176904. * (preferably unsigned long) for each cell. In practice this is overkill;
  176905. * we can get by with 16 bits per cell. Few of the cell counts will overflow,
  176906. * and clamping those that do overflow to the maximum value will give close-
  176907. * enough results. This reduces the recommended histogram size from 256Kb
  176908. * to 128Kb, which is a useful savings on PC-class machines.
  176909. * (In the second pass the histogram space is re-used for pixel mapping data;
  176910. * in that capacity, each cell must be able to store zero to the number of
  176911. * desired colors. 16 bits/cell is plenty for that too.)
  176912. * Since the JPEG code is intended to run in small memory model on 80x86
  176913. * machines, we can't just allocate the histogram in one chunk. Instead
  176914. * of a true 3-D array, we use a row of pointers to 2-D arrays. Each
  176915. * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
  176916. * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
  176917. * on 80x86 machines, the pointer row is in near memory but the actual
  176918. * arrays are in far memory (same arrangement as we use for image arrays).
  176919. */
  176920. #define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
  176921. /* These will do the right thing for either R,G,B or B,G,R color order,
  176922. * but you may not like the results for other color orders.
  176923. */
  176924. #define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
  176925. #define HIST_C1_BITS 6 /* bits of precision in G histogram */
  176926. #define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
  176927. /* Number of elements along histogram axes. */
  176928. #define HIST_C0_ELEMS (1<<HIST_C0_BITS)
  176929. #define HIST_C1_ELEMS (1<<HIST_C1_BITS)
  176930. #define HIST_C2_ELEMS (1<<HIST_C2_BITS)
  176931. /* These are the amounts to shift an input value to get a histogram index. */
  176932. #define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
  176933. #define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
  176934. #define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
  176935. typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
  176936. typedef histcell FAR * histptr; /* for pointers to histogram cells */
  176937. typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
  176938. typedef hist1d FAR * hist2d; /* type for the 2nd-level pointers */
  176939. typedef hist2d * hist3d; /* type for top-level pointer */
  176940. /* Declarations for Floyd-Steinberg dithering.
  176941. *
  176942. * Errors are accumulated into the array fserrors[], at a resolution of
  176943. * 1/16th of a pixel count. The error at a given pixel is propagated
  176944. * to its not-yet-processed neighbors using the standard F-S fractions,
  176945. * ... (here) 7/16
  176946. * 3/16 5/16 1/16
  176947. * We work left-to-right on even rows, right-to-left on odd rows.
  176948. *
  176949. * We can get away with a single array (holding one row's worth of errors)
  176950. * by using it to store the current row's errors at pixel columns not yet
  176951. * processed, but the next row's errors at columns already processed. We
  176952. * need only a few extra variables to hold the errors immediately around the
  176953. * current column. (If we are lucky, those variables are in registers, but
  176954. * even if not, they're probably cheaper to access than array elements are.)
  176955. *
  176956. * The fserrors[] array has (#columns + 2) entries; the extra entry at
  176957. * each end saves us from special-casing the first and last pixels.
  176958. * Each entry is three values long, one value for each color component.
  176959. *
  176960. * Note: on a wide image, we might not have enough room in a PC's near data
  176961. * segment to hold the error array; so it is allocated with alloc_large.
  176962. */
  176963. #if BITS_IN_JSAMPLE == 8
  176964. typedef INT16 FSERROR; /* 16 bits should be enough */
  176965. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  176966. #else
  176967. typedef INT32 FSERROR; /* may need more than 16 bits */
  176968. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  176969. #endif
  176970. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  176971. /* Private subobject */
  176972. typedef struct {
  176973. struct jpeg_color_quantizer pub; /* public fields */
  176974. /* Space for the eventually created colormap is stashed here */
  176975. JSAMPARRAY sv_colormap; /* colormap allocated at init time */
  176976. int desired; /* desired # of colors = size of colormap */
  176977. /* Variables for accumulating image statistics */
  176978. hist3d histogram; /* pointer to the histogram */
  176979. boolean needs_zeroed; /* TRUE if next pass must zero histogram */
  176980. /* Variables for Floyd-Steinberg dithering */
  176981. FSERRPTR fserrors; /* accumulated errors */
  176982. boolean on_odd_row; /* flag to remember which row we are on */
  176983. int * error_limiter; /* table for clamping the applied error */
  176984. } my_cquantizer2;
  176985. typedef my_cquantizer2 * my_cquantize_ptr2;
  176986. /*
  176987. * Prescan some rows of pixels.
  176988. * In this module the prescan simply updates the histogram, which has been
  176989. * initialized to zeroes by start_pass.
  176990. * An output_buf parameter is required by the method signature, but no data
  176991. * is actually output (in fact the buffer controller is probably passing a
  176992. * NULL pointer).
  176993. */
  176994. METHODDEF(void)
  176995. prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  176996. JSAMPARRAY, int num_rows)
  176997. {
  176998. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  176999. register JSAMPROW ptr;
  177000. register histptr histp;
  177001. register hist3d histogram = cquantize->histogram;
  177002. int row;
  177003. JDIMENSION col;
  177004. JDIMENSION width = cinfo->output_width;
  177005. for (row = 0; row < num_rows; row++) {
  177006. ptr = input_buf[row];
  177007. for (col = width; col > 0; col--) {
  177008. /* get pixel value and index into the histogram */
  177009. histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
  177010. [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
  177011. [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
  177012. /* increment, check for overflow and undo increment if so. */
  177013. if (++(*histp) <= 0)
  177014. (*histp)--;
  177015. ptr += 3;
  177016. }
  177017. }
  177018. }
  177019. /*
  177020. * Next we have the really interesting routines: selection of a colormap
  177021. * given the completed histogram.
  177022. * These routines work with a list of "boxes", each representing a rectangular
  177023. * subset of the input color space (to histogram precision).
  177024. */
  177025. typedef struct {
  177026. /* The bounds of the box (inclusive); expressed as histogram indexes */
  177027. int c0min, c0max;
  177028. int c1min, c1max;
  177029. int c2min, c2max;
  177030. /* The volume (actually 2-norm) of the box */
  177031. INT32 volume;
  177032. /* The number of nonzero histogram cells within this box */
  177033. long colorcount;
  177034. } box;
  177035. typedef box * boxptr;
  177036. LOCAL(boxptr)
  177037. find_biggest_color_pop (boxptr boxlist, int numboxes)
  177038. /* Find the splittable box with the largest color population */
  177039. /* Returns NULL if no splittable boxes remain */
  177040. {
  177041. register boxptr boxp;
  177042. register int i;
  177043. register long maxc = 0;
  177044. boxptr which = NULL;
  177045. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  177046. if (boxp->colorcount > maxc && boxp->volume > 0) {
  177047. which = boxp;
  177048. maxc = boxp->colorcount;
  177049. }
  177050. }
  177051. return which;
  177052. }
  177053. LOCAL(boxptr)
  177054. find_biggest_volume (boxptr boxlist, int numboxes)
  177055. /* Find the splittable box with the largest (scaled) volume */
  177056. /* Returns NULL if no splittable boxes remain */
  177057. {
  177058. register boxptr boxp;
  177059. register int i;
  177060. register INT32 maxv = 0;
  177061. boxptr which = NULL;
  177062. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  177063. if (boxp->volume > maxv) {
  177064. which = boxp;
  177065. maxv = boxp->volume;
  177066. }
  177067. }
  177068. return which;
  177069. }
  177070. LOCAL(void)
  177071. update_box (j_decompress_ptr cinfo, boxptr boxp)
  177072. /* Shrink the min/max bounds of a box to enclose only nonzero elements, */
  177073. /* and recompute its volume and population */
  177074. {
  177075. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177076. hist3d histogram = cquantize->histogram;
  177077. histptr histp;
  177078. int c0,c1,c2;
  177079. int c0min,c0max,c1min,c1max,c2min,c2max;
  177080. INT32 dist0,dist1,dist2;
  177081. long ccount;
  177082. c0min = boxp->c0min; c0max = boxp->c0max;
  177083. c1min = boxp->c1min; c1max = boxp->c1max;
  177084. c2min = boxp->c2min; c2max = boxp->c2max;
  177085. if (c0max > c0min)
  177086. for (c0 = c0min; c0 <= c0max; c0++)
  177087. for (c1 = c1min; c1 <= c1max; c1++) {
  177088. histp = & histogram[c0][c1][c2min];
  177089. for (c2 = c2min; c2 <= c2max; c2++)
  177090. if (*histp++ != 0) {
  177091. boxp->c0min = c0min = c0;
  177092. goto have_c0min;
  177093. }
  177094. }
  177095. have_c0min:
  177096. if (c0max > c0min)
  177097. for (c0 = c0max; c0 >= c0min; c0--)
  177098. for (c1 = c1min; c1 <= c1max; c1++) {
  177099. histp = & histogram[c0][c1][c2min];
  177100. for (c2 = c2min; c2 <= c2max; c2++)
  177101. if (*histp++ != 0) {
  177102. boxp->c0max = c0max = c0;
  177103. goto have_c0max;
  177104. }
  177105. }
  177106. have_c0max:
  177107. if (c1max > c1min)
  177108. for (c1 = c1min; c1 <= c1max; c1++)
  177109. for (c0 = c0min; c0 <= c0max; c0++) {
  177110. histp = & histogram[c0][c1][c2min];
  177111. for (c2 = c2min; c2 <= c2max; c2++)
  177112. if (*histp++ != 0) {
  177113. boxp->c1min = c1min = c1;
  177114. goto have_c1min;
  177115. }
  177116. }
  177117. have_c1min:
  177118. if (c1max > c1min)
  177119. for (c1 = c1max; c1 >= c1min; c1--)
  177120. for (c0 = c0min; c0 <= c0max; c0++) {
  177121. histp = & histogram[c0][c1][c2min];
  177122. for (c2 = c2min; c2 <= c2max; c2++)
  177123. if (*histp++ != 0) {
  177124. boxp->c1max = c1max = c1;
  177125. goto have_c1max;
  177126. }
  177127. }
  177128. have_c1max:
  177129. if (c2max > c2min)
  177130. for (c2 = c2min; c2 <= c2max; c2++)
  177131. for (c0 = c0min; c0 <= c0max; c0++) {
  177132. histp = & histogram[c0][c1min][c2];
  177133. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  177134. if (*histp != 0) {
  177135. boxp->c2min = c2min = c2;
  177136. goto have_c2min;
  177137. }
  177138. }
  177139. have_c2min:
  177140. if (c2max > c2min)
  177141. for (c2 = c2max; c2 >= c2min; c2--)
  177142. for (c0 = c0min; c0 <= c0max; c0++) {
  177143. histp = & histogram[c0][c1min][c2];
  177144. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  177145. if (*histp != 0) {
  177146. boxp->c2max = c2max = c2;
  177147. goto have_c2max;
  177148. }
  177149. }
  177150. have_c2max:
  177151. /* Update box volume.
  177152. * We use 2-norm rather than real volume here; this biases the method
  177153. * against making long narrow boxes, and it has the side benefit that
  177154. * a box is splittable iff norm > 0.
  177155. * Since the differences are expressed in histogram-cell units,
  177156. * we have to shift back to JSAMPLE units to get consistent distances;
  177157. * after which, we scale according to the selected distance scale factors.
  177158. */
  177159. dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
  177160. dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
  177161. dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
  177162. boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
  177163. /* Now scan remaining volume of box and compute population */
  177164. ccount = 0;
  177165. for (c0 = c0min; c0 <= c0max; c0++)
  177166. for (c1 = c1min; c1 <= c1max; c1++) {
  177167. histp = & histogram[c0][c1][c2min];
  177168. for (c2 = c2min; c2 <= c2max; c2++, histp++)
  177169. if (*histp != 0) {
  177170. ccount++;
  177171. }
  177172. }
  177173. boxp->colorcount = ccount;
  177174. }
  177175. LOCAL(int)
  177176. median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
  177177. int desired_colors)
  177178. /* Repeatedly select and split the largest box until we have enough boxes */
  177179. {
  177180. int n,lb;
  177181. int c0,c1,c2,cmax;
  177182. register boxptr b1,b2;
  177183. while (numboxes < desired_colors) {
  177184. /* Select box to split.
  177185. * Current algorithm: by population for first half, then by volume.
  177186. */
  177187. if (numboxes*2 <= desired_colors) {
  177188. b1 = find_biggest_color_pop(boxlist, numboxes);
  177189. } else {
  177190. b1 = find_biggest_volume(boxlist, numboxes);
  177191. }
  177192. if (b1 == NULL) /* no splittable boxes left! */
  177193. break;
  177194. b2 = &boxlist[numboxes]; /* where new box will go */
  177195. /* Copy the color bounds to the new box. */
  177196. b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
  177197. b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
  177198. /* Choose which axis to split the box on.
  177199. * Current algorithm: longest scaled axis.
  177200. * See notes in update_box about scaling distances.
  177201. */
  177202. c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
  177203. c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
  177204. c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
  177205. /* We want to break any ties in favor of green, then red, blue last.
  177206. * This code does the right thing for R,G,B or B,G,R color orders only.
  177207. */
  177208. #if RGB_RED == 0
  177209. cmax = c1; n = 1;
  177210. if (c0 > cmax) { cmax = c0; n = 0; }
  177211. if (c2 > cmax) { n = 2; }
  177212. #else
  177213. cmax = c1; n = 1;
  177214. if (c2 > cmax) { cmax = c2; n = 2; }
  177215. if (c0 > cmax) { n = 0; }
  177216. #endif
  177217. /* Choose split point along selected axis, and update box bounds.
  177218. * Current algorithm: split at halfway point.
  177219. * (Since the box has been shrunk to minimum volume,
  177220. * any split will produce two nonempty subboxes.)
  177221. * Note that lb value is max for lower box, so must be < old max.
  177222. */
  177223. switch (n) {
  177224. case 0:
  177225. lb = (b1->c0max + b1->c0min) / 2;
  177226. b1->c0max = lb;
  177227. b2->c0min = lb+1;
  177228. break;
  177229. case 1:
  177230. lb = (b1->c1max + b1->c1min) / 2;
  177231. b1->c1max = lb;
  177232. b2->c1min = lb+1;
  177233. break;
  177234. case 2:
  177235. lb = (b1->c2max + b1->c2min) / 2;
  177236. b1->c2max = lb;
  177237. b2->c2min = lb+1;
  177238. break;
  177239. }
  177240. /* Update stats for boxes */
  177241. update_box(cinfo, b1);
  177242. update_box(cinfo, b2);
  177243. numboxes++;
  177244. }
  177245. return numboxes;
  177246. }
  177247. LOCAL(void)
  177248. compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
  177249. /* Compute representative color for a box, put it in colormap[icolor] */
  177250. {
  177251. /* Current algorithm: mean weighted by pixels (not colors) */
  177252. /* Note it is important to get the rounding correct! */
  177253. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177254. hist3d histogram = cquantize->histogram;
  177255. histptr histp;
  177256. int c0,c1,c2;
  177257. int c0min,c0max,c1min,c1max,c2min,c2max;
  177258. long count;
  177259. long total = 0;
  177260. long c0total = 0;
  177261. long c1total = 0;
  177262. long c2total = 0;
  177263. c0min = boxp->c0min; c0max = boxp->c0max;
  177264. c1min = boxp->c1min; c1max = boxp->c1max;
  177265. c2min = boxp->c2min; c2max = boxp->c2max;
  177266. for (c0 = c0min; c0 <= c0max; c0++)
  177267. for (c1 = c1min; c1 <= c1max; c1++) {
  177268. histp = & histogram[c0][c1][c2min];
  177269. for (c2 = c2min; c2 <= c2max; c2++) {
  177270. if ((count = *histp++) != 0) {
  177271. total += count;
  177272. c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
  177273. c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
  177274. c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
  177275. }
  177276. }
  177277. }
  177278. cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
  177279. cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
  177280. cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
  177281. }
  177282. LOCAL(void)
  177283. select_colors (j_decompress_ptr cinfo, int desired_colors)
  177284. /* Master routine for color selection */
  177285. {
  177286. boxptr boxlist;
  177287. int numboxes;
  177288. int i;
  177289. /* Allocate workspace for box list */
  177290. boxlist = (boxptr) (*cinfo->mem->alloc_small)
  177291. ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box));
  177292. /* Initialize one box containing whole space */
  177293. numboxes = 1;
  177294. boxlist[0].c0min = 0;
  177295. boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
  177296. boxlist[0].c1min = 0;
  177297. boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
  177298. boxlist[0].c2min = 0;
  177299. boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
  177300. /* Shrink it to actually-used volume and set its statistics */
  177301. update_box(cinfo, & boxlist[0]);
  177302. /* Perform median-cut to produce final box list */
  177303. numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
  177304. /* Compute the representative color for each box, fill colormap */
  177305. for (i = 0; i < numboxes; i++)
  177306. compute_color(cinfo, & boxlist[i], i);
  177307. cinfo->actual_number_of_colors = numboxes;
  177308. TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
  177309. }
  177310. /*
  177311. * These routines are concerned with the time-critical task of mapping input
  177312. * colors to the nearest color in the selected colormap.
  177313. *
  177314. * We re-use the histogram space as an "inverse color map", essentially a
  177315. * cache for the results of nearest-color searches. All colors within a
  177316. * histogram cell will be mapped to the same colormap entry, namely the one
  177317. * closest to the cell's center. This may not be quite the closest entry to
  177318. * the actual input color, but it's almost as good. A zero in the cache
  177319. * indicates we haven't found the nearest color for that cell yet; the array
  177320. * is cleared to zeroes before starting the mapping pass. When we find the
  177321. * nearest color for a cell, its colormap index plus one is recorded in the
  177322. * cache for future use. The pass2 scanning routines call fill_inverse_cmap
  177323. * when they need to use an unfilled entry in the cache.
  177324. *
  177325. * Our method of efficiently finding nearest colors is based on the "locally
  177326. * sorted search" idea described by Heckbert and on the incremental distance
  177327. * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
  177328. * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
  177329. * the distances from a given colormap entry to each cell of the histogram can
  177330. * be computed quickly using an incremental method: the differences between
  177331. * distances to adjacent cells themselves differ by a constant. This allows a
  177332. * fairly fast implementation of the "brute force" approach of computing the
  177333. * distance from every colormap entry to every histogram cell. Unfortunately,
  177334. * it needs a work array to hold the best-distance-so-far for each histogram
  177335. * cell (because the inner loop has to be over cells, not colormap entries).
  177336. * The work array elements have to be INT32s, so the work array would need
  177337. * 256Kb at our recommended precision. This is not feasible in DOS machines.
  177338. *
  177339. * To get around these problems, we apply Thomas' method to compute the
  177340. * nearest colors for only the cells within a small subbox of the histogram.
  177341. * The work array need be only as big as the subbox, so the memory usage
  177342. * problem is solved. Furthermore, we need not fill subboxes that are never
  177343. * referenced in pass2; many images use only part of the color gamut, so a
  177344. * fair amount of work is saved. An additional advantage of this
  177345. * approach is that we can apply Heckbert's locality criterion to quickly
  177346. * eliminate colormap entries that are far away from the subbox; typically
  177347. * three-fourths of the colormap entries are rejected by Heckbert's criterion,
  177348. * and we need not compute their distances to individual cells in the subbox.
  177349. * The speed of this approach is heavily influenced by the subbox size: too
  177350. * small means too much overhead, too big loses because Heckbert's criterion
  177351. * can't eliminate as many colormap entries. Empirically the best subbox
  177352. * size seems to be about 1/512th of the histogram (1/8th in each direction).
  177353. *
  177354. * Thomas' article also describes a refined method which is asymptotically
  177355. * faster than the brute-force method, but it is also far more complex and
  177356. * cannot efficiently be applied to small subboxes. It is therefore not
  177357. * useful for programs intended to be portable to DOS machines. On machines
  177358. * with plenty of memory, filling the whole histogram in one shot with Thomas'
  177359. * refined method might be faster than the present code --- but then again,
  177360. * it might not be any faster, and it's certainly more complicated.
  177361. */
  177362. /* log2(histogram cells in update box) for each axis; this can be adjusted */
  177363. #define BOX_C0_LOG (HIST_C0_BITS-3)
  177364. #define BOX_C1_LOG (HIST_C1_BITS-3)
  177365. #define BOX_C2_LOG (HIST_C2_BITS-3)
  177366. #define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
  177367. #define BOX_C1_ELEMS (1<<BOX_C1_LOG)
  177368. #define BOX_C2_ELEMS (1<<BOX_C2_LOG)
  177369. #define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
  177370. #define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
  177371. #define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
  177372. /*
  177373. * The next three routines implement inverse colormap filling. They could
  177374. * all be folded into one big routine, but splitting them up this way saves
  177375. * some stack space (the mindist[] and bestdist[] arrays need not coexist)
  177376. * and may allow some compilers to produce better code by registerizing more
  177377. * inner-loop variables.
  177378. */
  177379. LOCAL(int)
  177380. find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  177381. JSAMPLE colorlist[])
  177382. /* Locate the colormap entries close enough to an update box to be candidates
  177383. * for the nearest entry to some cell(s) in the update box. The update box
  177384. * is specified by the center coordinates of its first cell. The number of
  177385. * candidate colormap entries is returned, and their colormap indexes are
  177386. * placed in colorlist[].
  177387. * This routine uses Heckbert's "locally sorted search" criterion to select
  177388. * the colors that need further consideration.
  177389. */
  177390. {
  177391. int numcolors = cinfo->actual_number_of_colors;
  177392. int maxc0, maxc1, maxc2;
  177393. int centerc0, centerc1, centerc2;
  177394. int i, x, ncolors;
  177395. INT32 minmaxdist, min_dist, max_dist, tdist;
  177396. INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
  177397. /* Compute true coordinates of update box's upper corner and center.
  177398. * Actually we compute the coordinates of the center of the upper-corner
  177399. * histogram cell, which are the upper bounds of the volume we care about.
  177400. * Note that since ">>" rounds down, the "center" values may be closer to
  177401. * min than to max; hence comparisons to them must be "<=", not "<".
  177402. */
  177403. maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
  177404. centerc0 = (minc0 + maxc0) >> 1;
  177405. maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
  177406. centerc1 = (minc1 + maxc1) >> 1;
  177407. maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
  177408. centerc2 = (minc2 + maxc2) >> 1;
  177409. /* For each color in colormap, find:
  177410. * 1. its minimum squared-distance to any point in the update box
  177411. * (zero if color is within update box);
  177412. * 2. its maximum squared-distance to any point in the update box.
  177413. * Both of these can be found by considering only the corners of the box.
  177414. * We save the minimum distance for each color in mindist[];
  177415. * only the smallest maximum distance is of interest.
  177416. */
  177417. minmaxdist = 0x7FFFFFFFL;
  177418. for (i = 0; i < numcolors; i++) {
  177419. /* We compute the squared-c0-distance term, then add in the other two. */
  177420. x = GETJSAMPLE(cinfo->colormap[0][i]);
  177421. if (x < minc0) {
  177422. tdist = (x - minc0) * C0_SCALE;
  177423. min_dist = tdist*tdist;
  177424. tdist = (x - maxc0) * C0_SCALE;
  177425. max_dist = tdist*tdist;
  177426. } else if (x > maxc0) {
  177427. tdist = (x - maxc0) * C0_SCALE;
  177428. min_dist = tdist*tdist;
  177429. tdist = (x - minc0) * C0_SCALE;
  177430. max_dist = tdist*tdist;
  177431. } else {
  177432. /* within cell range so no contribution to min_dist */
  177433. min_dist = 0;
  177434. if (x <= centerc0) {
  177435. tdist = (x - maxc0) * C0_SCALE;
  177436. max_dist = tdist*tdist;
  177437. } else {
  177438. tdist = (x - minc0) * C0_SCALE;
  177439. max_dist = tdist*tdist;
  177440. }
  177441. }
  177442. x = GETJSAMPLE(cinfo->colormap[1][i]);
  177443. if (x < minc1) {
  177444. tdist = (x - minc1) * C1_SCALE;
  177445. min_dist += tdist*tdist;
  177446. tdist = (x - maxc1) * C1_SCALE;
  177447. max_dist += tdist*tdist;
  177448. } else if (x > maxc1) {
  177449. tdist = (x - maxc1) * C1_SCALE;
  177450. min_dist += tdist*tdist;
  177451. tdist = (x - minc1) * C1_SCALE;
  177452. max_dist += tdist*tdist;
  177453. } else {
  177454. /* within cell range so no contribution to min_dist */
  177455. if (x <= centerc1) {
  177456. tdist = (x - maxc1) * C1_SCALE;
  177457. max_dist += tdist*tdist;
  177458. } else {
  177459. tdist = (x - minc1) * C1_SCALE;
  177460. max_dist += tdist*tdist;
  177461. }
  177462. }
  177463. x = GETJSAMPLE(cinfo->colormap[2][i]);
  177464. if (x < minc2) {
  177465. tdist = (x - minc2) * C2_SCALE;
  177466. min_dist += tdist*tdist;
  177467. tdist = (x - maxc2) * C2_SCALE;
  177468. max_dist += tdist*tdist;
  177469. } else if (x > maxc2) {
  177470. tdist = (x - maxc2) * C2_SCALE;
  177471. min_dist += tdist*tdist;
  177472. tdist = (x - minc2) * C2_SCALE;
  177473. max_dist += tdist*tdist;
  177474. } else {
  177475. /* within cell range so no contribution to min_dist */
  177476. if (x <= centerc2) {
  177477. tdist = (x - maxc2) * C2_SCALE;
  177478. max_dist += tdist*tdist;
  177479. } else {
  177480. tdist = (x - minc2) * C2_SCALE;
  177481. max_dist += tdist*tdist;
  177482. }
  177483. }
  177484. mindist[i] = min_dist; /* save away the results */
  177485. if (max_dist < minmaxdist)
  177486. minmaxdist = max_dist;
  177487. }
  177488. /* Now we know that no cell in the update box is more than minmaxdist
  177489. * away from some colormap entry. Therefore, only colors that are
  177490. * within minmaxdist of some part of the box need be considered.
  177491. */
  177492. ncolors = 0;
  177493. for (i = 0; i < numcolors; i++) {
  177494. if (mindist[i] <= minmaxdist)
  177495. colorlist[ncolors++] = (JSAMPLE) i;
  177496. }
  177497. return ncolors;
  177498. }
  177499. LOCAL(void)
  177500. find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  177501. int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
  177502. /* Find the closest colormap entry for each cell in the update box,
  177503. * given the list of candidate colors prepared by find_nearby_colors.
  177504. * Return the indexes of the closest entries in the bestcolor[] array.
  177505. * This routine uses Thomas' incremental distance calculation method to
  177506. * find the distance from a colormap entry to successive cells in the box.
  177507. */
  177508. {
  177509. int ic0, ic1, ic2;
  177510. int i, icolor;
  177511. register INT32 * bptr; /* pointer into bestdist[] array */
  177512. JSAMPLE * cptr; /* pointer into bestcolor[] array */
  177513. INT32 dist0, dist1; /* initial distance values */
  177514. register INT32 dist2; /* current distance in inner loop */
  177515. INT32 xx0, xx1; /* distance increments */
  177516. register INT32 xx2;
  177517. INT32 inc0, inc1, inc2; /* initial values for increments */
  177518. /* This array holds the distance to the nearest-so-far color for each cell */
  177519. INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  177520. /* Initialize best-distance for each cell of the update box */
  177521. bptr = bestdist;
  177522. for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
  177523. *bptr++ = 0x7FFFFFFFL;
  177524. /* For each color selected by find_nearby_colors,
  177525. * compute its distance to the center of each cell in the box.
  177526. * If that's less than best-so-far, update best distance and color number.
  177527. */
  177528. /* Nominal steps between cell centers ("x" in Thomas article) */
  177529. #define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
  177530. #define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
  177531. #define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
  177532. for (i = 0; i < numcolors; i++) {
  177533. icolor = GETJSAMPLE(colorlist[i]);
  177534. /* Compute (square of) distance from minc0/c1/c2 to this color */
  177535. inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
  177536. dist0 = inc0*inc0;
  177537. inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
  177538. dist0 += inc1*inc1;
  177539. inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
  177540. dist0 += inc2*inc2;
  177541. /* Form the initial difference increments */
  177542. inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
  177543. inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
  177544. inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
  177545. /* Now loop over all cells in box, updating distance per Thomas method */
  177546. bptr = bestdist;
  177547. cptr = bestcolor;
  177548. xx0 = inc0;
  177549. for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
  177550. dist1 = dist0;
  177551. xx1 = inc1;
  177552. for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
  177553. dist2 = dist1;
  177554. xx2 = inc2;
  177555. for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
  177556. if (dist2 < *bptr) {
  177557. *bptr = dist2;
  177558. *cptr = (JSAMPLE) icolor;
  177559. }
  177560. dist2 += xx2;
  177561. xx2 += 2 * STEP_C2 * STEP_C2;
  177562. bptr++;
  177563. cptr++;
  177564. }
  177565. dist1 += xx1;
  177566. xx1 += 2 * STEP_C1 * STEP_C1;
  177567. }
  177568. dist0 += xx0;
  177569. xx0 += 2 * STEP_C0 * STEP_C0;
  177570. }
  177571. }
  177572. }
  177573. LOCAL(void)
  177574. fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
  177575. /* Fill the inverse-colormap entries in the update box that contains */
  177576. /* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
  177577. /* we can fill as many others as we wish.) */
  177578. {
  177579. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177580. hist3d histogram = cquantize->histogram;
  177581. int minc0, minc1, minc2; /* lower left corner of update box */
  177582. int ic0, ic1, ic2;
  177583. register JSAMPLE * cptr; /* pointer into bestcolor[] array */
  177584. register histptr cachep; /* pointer into main cache array */
  177585. /* This array lists the candidate colormap indexes. */
  177586. JSAMPLE colorlist[MAXNUMCOLORS];
  177587. int numcolors; /* number of candidate colors */
  177588. /* This array holds the actually closest colormap index for each cell. */
  177589. JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  177590. /* Convert cell coordinates to update box ID */
  177591. c0 >>= BOX_C0_LOG;
  177592. c1 >>= BOX_C1_LOG;
  177593. c2 >>= BOX_C2_LOG;
  177594. /* Compute true coordinates of update box's origin corner.
  177595. * Actually we compute the coordinates of the center of the corner
  177596. * histogram cell, which are the lower bounds of the volume we care about.
  177597. */
  177598. minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
  177599. minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
  177600. minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
  177601. /* Determine which colormap entries are close enough to be candidates
  177602. * for the nearest entry to some cell in the update box.
  177603. */
  177604. numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
  177605. /* Determine the actually nearest colors. */
  177606. find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
  177607. bestcolor);
  177608. /* Save the best color numbers (plus 1) in the main cache array */
  177609. c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
  177610. c1 <<= BOX_C1_LOG;
  177611. c2 <<= BOX_C2_LOG;
  177612. cptr = bestcolor;
  177613. for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
  177614. for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
  177615. cachep = & histogram[c0+ic0][c1+ic1][c2];
  177616. for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
  177617. *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
  177618. }
  177619. }
  177620. }
  177621. }
  177622. /*
  177623. * Map some rows of pixels to the output colormapped representation.
  177624. */
  177625. METHODDEF(void)
  177626. pass2_no_dither (j_decompress_ptr cinfo,
  177627. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  177628. /* This version performs no dithering */
  177629. {
  177630. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177631. hist3d histogram = cquantize->histogram;
  177632. register JSAMPROW inptr, outptr;
  177633. register histptr cachep;
  177634. register int c0, c1, c2;
  177635. int row;
  177636. JDIMENSION col;
  177637. JDIMENSION width = cinfo->output_width;
  177638. for (row = 0; row < num_rows; row++) {
  177639. inptr = input_buf[row];
  177640. outptr = output_buf[row];
  177641. for (col = width; col > 0; col--) {
  177642. /* get pixel value and index into the cache */
  177643. c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
  177644. c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
  177645. c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
  177646. cachep = & histogram[c0][c1][c2];
  177647. /* If we have not seen this color before, find nearest colormap entry */
  177648. /* and update the cache */
  177649. if (*cachep == 0)
  177650. fill_inverse_cmap(cinfo, c0,c1,c2);
  177651. /* Now emit the colormap index for this cell */
  177652. *outptr++ = (JSAMPLE) (*cachep - 1);
  177653. }
  177654. }
  177655. }
  177656. METHODDEF(void)
  177657. pass2_fs_dither (j_decompress_ptr cinfo,
  177658. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  177659. /* This version performs Floyd-Steinberg dithering */
  177660. {
  177661. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177662. hist3d histogram = cquantize->histogram;
  177663. register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
  177664. LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
  177665. LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
  177666. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  177667. JSAMPROW inptr; /* => current input pixel */
  177668. JSAMPROW outptr; /* => current output pixel */
  177669. histptr cachep;
  177670. int dir; /* +1 or -1 depending on direction */
  177671. int dir3; /* 3*dir, for advancing inptr & errorptr */
  177672. int row;
  177673. JDIMENSION col;
  177674. JDIMENSION width = cinfo->output_width;
  177675. JSAMPLE *range_limit = cinfo->sample_range_limit;
  177676. int *error_limit = cquantize->error_limiter;
  177677. JSAMPROW colormap0 = cinfo->colormap[0];
  177678. JSAMPROW colormap1 = cinfo->colormap[1];
  177679. JSAMPROW colormap2 = cinfo->colormap[2];
  177680. SHIFT_TEMPS
  177681. for (row = 0; row < num_rows; row++) {
  177682. inptr = input_buf[row];
  177683. outptr = output_buf[row];
  177684. if (cquantize->on_odd_row) {
  177685. /* work right to left in this row */
  177686. inptr += (width-1) * 3; /* so point to rightmost pixel */
  177687. outptr += width-1;
  177688. dir = -1;
  177689. dir3 = -3;
  177690. errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
  177691. cquantize->on_odd_row = FALSE; /* flip for next time */
  177692. } else {
  177693. /* work left to right in this row */
  177694. dir = 1;
  177695. dir3 = 3;
  177696. errorptr = cquantize->fserrors; /* => entry before first real column */
  177697. cquantize->on_odd_row = TRUE; /* flip for next time */
  177698. }
  177699. /* Preset error values: no error propagated to first pixel from left */
  177700. cur0 = cur1 = cur2 = 0;
  177701. /* and no error propagated to row below yet */
  177702. belowerr0 = belowerr1 = belowerr2 = 0;
  177703. bpreverr0 = bpreverr1 = bpreverr2 = 0;
  177704. for (col = width; col > 0; col--) {
  177705. /* curN holds the error propagated from the previous pixel on the
  177706. * current line. Add the error propagated from the previous line
  177707. * to form the complete error correction term for this pixel, and
  177708. * round the error term (which is expressed * 16) to an integer.
  177709. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  177710. * for either sign of the error value.
  177711. * Note: errorptr points to *previous* column's array entry.
  177712. */
  177713. cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
  177714. cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
  177715. cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
  177716. /* Limit the error using transfer function set by init_error_limit.
  177717. * See comments with init_error_limit for rationale.
  177718. */
  177719. cur0 = error_limit[cur0];
  177720. cur1 = error_limit[cur1];
  177721. cur2 = error_limit[cur2];
  177722. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  177723. * The maximum error is +- MAXJSAMPLE (or less with error limiting);
  177724. * this sets the required size of the range_limit array.
  177725. */
  177726. cur0 += GETJSAMPLE(inptr[0]);
  177727. cur1 += GETJSAMPLE(inptr[1]);
  177728. cur2 += GETJSAMPLE(inptr[2]);
  177729. cur0 = GETJSAMPLE(range_limit[cur0]);
  177730. cur1 = GETJSAMPLE(range_limit[cur1]);
  177731. cur2 = GETJSAMPLE(range_limit[cur2]);
  177732. /* Index into the cache with adjusted pixel value */
  177733. cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
  177734. /* If we have not seen this color before, find nearest colormap */
  177735. /* entry and update the cache */
  177736. if (*cachep == 0)
  177737. fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
  177738. /* Now emit the colormap index for this cell */
  177739. { register int pixcode = *cachep - 1;
  177740. *outptr = (JSAMPLE) pixcode;
  177741. /* Compute representation error for this pixel */
  177742. cur0 -= GETJSAMPLE(colormap0[pixcode]);
  177743. cur1 -= GETJSAMPLE(colormap1[pixcode]);
  177744. cur2 -= GETJSAMPLE(colormap2[pixcode]);
  177745. }
  177746. /* Compute error fractions to be propagated to adjacent pixels.
  177747. * Add these into the running sums, and simultaneously shift the
  177748. * next-line error sums left by 1 column.
  177749. */
  177750. { register LOCFSERROR bnexterr, delta;
  177751. bnexterr = cur0; /* Process component 0 */
  177752. delta = cur0 * 2;
  177753. cur0 += delta; /* form error * 3 */
  177754. errorptr[0] = (FSERROR) (bpreverr0 + cur0);
  177755. cur0 += delta; /* form error * 5 */
  177756. bpreverr0 = belowerr0 + cur0;
  177757. belowerr0 = bnexterr;
  177758. cur0 += delta; /* form error * 7 */
  177759. bnexterr = cur1; /* Process component 1 */
  177760. delta = cur1 * 2;
  177761. cur1 += delta; /* form error * 3 */
  177762. errorptr[1] = (FSERROR) (bpreverr1 + cur1);
  177763. cur1 += delta; /* form error * 5 */
  177764. bpreverr1 = belowerr1 + cur1;
  177765. belowerr1 = bnexterr;
  177766. cur1 += delta; /* form error * 7 */
  177767. bnexterr = cur2; /* Process component 2 */
  177768. delta = cur2 * 2;
  177769. cur2 += delta; /* form error * 3 */
  177770. errorptr[2] = (FSERROR) (bpreverr2 + cur2);
  177771. cur2 += delta; /* form error * 5 */
  177772. bpreverr2 = belowerr2 + cur2;
  177773. belowerr2 = bnexterr;
  177774. cur2 += delta; /* form error * 7 */
  177775. }
  177776. /* At this point curN contains the 7/16 error value to be propagated
  177777. * to the next pixel on the current line, and all the errors for the
  177778. * next line have been shifted over. We are therefore ready to move on.
  177779. */
  177780. inptr += dir3; /* Advance pixel pointers to next column */
  177781. outptr += dir;
  177782. errorptr += dir3; /* advance errorptr to current column */
  177783. }
  177784. /* Post-loop cleanup: we must unload the final error values into the
  177785. * final fserrors[] entry. Note we need not unload belowerrN because
  177786. * it is for the dummy column before or after the actual array.
  177787. */
  177788. errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
  177789. errorptr[1] = (FSERROR) bpreverr1;
  177790. errorptr[2] = (FSERROR) bpreverr2;
  177791. }
  177792. }
  177793. /*
  177794. * Initialize the error-limiting transfer function (lookup table).
  177795. * The raw F-S error computation can potentially compute error values of up to
  177796. * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
  177797. * much less, otherwise obviously wrong pixels will be created. (Typical
  177798. * effects include weird fringes at color-area boundaries, isolated bright
  177799. * pixels in a dark area, etc.) The standard advice for avoiding this problem
  177800. * is to ensure that the "corners" of the color cube are allocated as output
  177801. * colors; then repeated errors in the same direction cannot cause cascading
  177802. * error buildup. However, that only prevents the error from getting
  177803. * completely out of hand; Aaron Giles reports that error limiting improves
  177804. * the results even with corner colors allocated.
  177805. * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
  177806. * well, but the smoother transfer function used below is even better. Thanks
  177807. * to Aaron Giles for this idea.
  177808. */
  177809. LOCAL(void)
  177810. init_error_limit (j_decompress_ptr cinfo)
  177811. /* Allocate and fill in the error_limiter table */
  177812. {
  177813. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177814. int * table;
  177815. int in, out;
  177816. table = (int *) (*cinfo->mem->alloc_small)
  177817. ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
  177818. table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
  177819. cquantize->error_limiter = table;
  177820. #define STEPSIZE ((MAXJSAMPLE+1)/16)
  177821. /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
  177822. out = 0;
  177823. for (in = 0; in < STEPSIZE; in++, out++) {
  177824. table[in] = out; table[-in] = -out;
  177825. }
  177826. /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
  177827. for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
  177828. table[in] = out; table[-in] = -out;
  177829. }
  177830. /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
  177831. for (; in <= MAXJSAMPLE; in++) {
  177832. table[in] = out; table[-in] = -out;
  177833. }
  177834. #undef STEPSIZE
  177835. }
  177836. /*
  177837. * Finish up at the end of each pass.
  177838. */
  177839. METHODDEF(void)
  177840. finish_pass1 (j_decompress_ptr cinfo)
  177841. {
  177842. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177843. /* Select the representative colors and fill in cinfo->colormap */
  177844. cinfo->colormap = cquantize->sv_colormap;
  177845. select_colors(cinfo, cquantize->desired);
  177846. /* Force next pass to zero the color index table */
  177847. cquantize->needs_zeroed = TRUE;
  177848. }
  177849. METHODDEF(void)
  177850. finish_pass2 (j_decompress_ptr)
  177851. {
  177852. /* no work */
  177853. }
  177854. /*
  177855. * Initialize for each processing pass.
  177856. */
  177857. METHODDEF(void)
  177858. start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  177859. {
  177860. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177861. hist3d histogram = cquantize->histogram;
  177862. int i;
  177863. /* Only F-S dithering or no dithering is supported. */
  177864. /* If user asks for ordered dither, give him F-S. */
  177865. if (cinfo->dither_mode != JDITHER_NONE)
  177866. cinfo->dither_mode = JDITHER_FS;
  177867. if (is_pre_scan) {
  177868. /* Set up method pointers */
  177869. cquantize->pub.color_quantize = prescan_quantize;
  177870. cquantize->pub.finish_pass = finish_pass1;
  177871. cquantize->needs_zeroed = TRUE; /* Always zero histogram */
  177872. } else {
  177873. /* Set up method pointers */
  177874. if (cinfo->dither_mode == JDITHER_FS)
  177875. cquantize->pub.color_quantize = pass2_fs_dither;
  177876. else
  177877. cquantize->pub.color_quantize = pass2_no_dither;
  177878. cquantize->pub.finish_pass = finish_pass2;
  177879. /* Make sure color count is acceptable */
  177880. i = cinfo->actual_number_of_colors;
  177881. if (i < 1)
  177882. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
  177883. if (i > MAXNUMCOLORS)
  177884. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  177885. if (cinfo->dither_mode == JDITHER_FS) {
  177886. size_t arraysize = (size_t) ((cinfo->output_width + 2) *
  177887. (3 * SIZEOF(FSERROR)));
  177888. /* Allocate Floyd-Steinberg workspace if we didn't already. */
  177889. if (cquantize->fserrors == NULL)
  177890. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  177891. ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  177892. /* Initialize the propagated errors to zero. */
  177893. jzero_far((void FAR *) cquantize->fserrors, arraysize);
  177894. /* Make the error-limit table if we didn't already. */
  177895. if (cquantize->error_limiter == NULL)
  177896. init_error_limit(cinfo);
  177897. cquantize->on_odd_row = FALSE;
  177898. }
  177899. }
  177900. /* Zero the histogram or inverse color map, if necessary */
  177901. if (cquantize->needs_zeroed) {
  177902. for (i = 0; i < HIST_C0_ELEMS; i++) {
  177903. jzero_far((void FAR *) histogram[i],
  177904. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  177905. }
  177906. cquantize->needs_zeroed = FALSE;
  177907. }
  177908. }
  177909. /*
  177910. * Switch to a new external colormap between output passes.
  177911. */
  177912. METHODDEF(void)
  177913. new_color_map_2_quant (j_decompress_ptr cinfo)
  177914. {
  177915. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177916. /* Reset the inverse color map */
  177917. cquantize->needs_zeroed = TRUE;
  177918. }
  177919. /*
  177920. * Module initialization routine for 2-pass color quantization.
  177921. */
  177922. GLOBAL(void)
  177923. jinit_2pass_quantizer (j_decompress_ptr cinfo)
  177924. {
  177925. my_cquantize_ptr2 cquantize;
  177926. int i;
  177927. cquantize = (my_cquantize_ptr2)
  177928. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177929. SIZEOF(my_cquantizer2));
  177930. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  177931. cquantize->pub.start_pass = start_pass_2_quant;
  177932. cquantize->pub.new_color_map = new_color_map_2_quant;
  177933. cquantize->fserrors = NULL; /* flag optional arrays not allocated */
  177934. cquantize->error_limiter = NULL;
  177935. /* Make sure jdmaster didn't give me a case I can't handle */
  177936. if (cinfo->out_color_components != 3)
  177937. ERREXIT(cinfo, JERR_NOTIMPL);
  177938. /* Allocate the histogram/inverse colormap storage */
  177939. cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
  177940. ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
  177941. for (i = 0; i < HIST_C0_ELEMS; i++) {
  177942. cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
  177943. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177944. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  177945. }
  177946. cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
  177947. /* Allocate storage for the completed colormap, if required.
  177948. * We do this now since it is FAR storage and may affect
  177949. * the memory manager's space calculations.
  177950. */
  177951. if (cinfo->enable_2pass_quant) {
  177952. /* Make sure color count is acceptable */
  177953. int desired = cinfo->desired_number_of_colors;
  177954. /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
  177955. if (desired < 8)
  177956. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
  177957. /* Make sure colormap indexes can be represented by JSAMPLEs */
  177958. if (desired > MAXNUMCOLORS)
  177959. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  177960. cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
  177961. ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3);
  177962. cquantize->desired = desired;
  177963. } else
  177964. cquantize->sv_colormap = NULL;
  177965. /* Only F-S dithering or no dithering is supported. */
  177966. /* If user asks for ordered dither, give him F-S. */
  177967. if (cinfo->dither_mode != JDITHER_NONE)
  177968. cinfo->dither_mode = JDITHER_FS;
  177969. /* Allocate Floyd-Steinberg workspace if necessary.
  177970. * This isn't really needed until pass 2, but again it is FAR storage.
  177971. * Although we will cope with a later change in dither_mode,
  177972. * we do not promise to honor max_memory_to_use if dither_mode changes.
  177973. */
  177974. if (cinfo->dither_mode == JDITHER_FS) {
  177975. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  177976. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177977. (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))));
  177978. /* Might as well create the error-limiting table too. */
  177979. init_error_limit(cinfo);
  177980. }
  177981. }
  177982. #endif /* QUANT_2PASS_SUPPORTED */
  177983. /*** End of inlined file: jquant2.c ***/
  177984. /*** Start of inlined file: jutils.c ***/
  177985. #define JPEG_INTERNALS
  177986. /*
  177987. * jpeg_zigzag_order[i] is the zigzag-order position of the i'th element
  177988. * of a DCT block read in natural order (left to right, top to bottom).
  177989. */
  177990. #if 0 /* This table is not actually needed in v6a */
  177991. const int jpeg_zigzag_order[DCTSIZE2] = {
  177992. 0, 1, 5, 6, 14, 15, 27, 28,
  177993. 2, 4, 7, 13, 16, 26, 29, 42,
  177994. 3, 8, 12, 17, 25, 30, 41, 43,
  177995. 9, 11, 18, 24, 31, 40, 44, 53,
  177996. 10, 19, 23, 32, 39, 45, 52, 54,
  177997. 20, 22, 33, 38, 46, 51, 55, 60,
  177998. 21, 34, 37, 47, 50, 56, 59, 61,
  177999. 35, 36, 48, 49, 57, 58, 62, 63
  178000. };
  178001. #endif
  178002. /*
  178003. * jpeg_natural_order[i] is the natural-order position of the i'th element
  178004. * of zigzag order.
  178005. *
  178006. * When reading corrupted data, the Huffman decoders could attempt
  178007. * to reference an entry beyond the end of this array (if the decoded
  178008. * zero run length reaches past the end of the block). To prevent
  178009. * wild stores without adding an inner-loop test, we put some extra
  178010. * "63"s after the real entries. This will cause the extra coefficient
  178011. * to be stored in location 63 of the block, not somewhere random.
  178012. * The worst case would be a run-length of 15, which means we need 16
  178013. * fake entries.
  178014. */
  178015. const int jpeg_natural_order[DCTSIZE2+16] = {
  178016. 0, 1, 8, 16, 9, 2, 3, 10,
  178017. 17, 24, 32, 25, 18, 11, 4, 5,
  178018. 12, 19, 26, 33, 40, 48, 41, 34,
  178019. 27, 20, 13, 6, 7, 14, 21, 28,
  178020. 35, 42, 49, 56, 57, 50, 43, 36,
  178021. 29, 22, 15, 23, 30, 37, 44, 51,
  178022. 58, 59, 52, 45, 38, 31, 39, 46,
  178023. 53, 60, 61, 54, 47, 55, 62, 63,
  178024. 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */
  178025. 63, 63, 63, 63, 63, 63, 63, 63
  178026. };
  178027. /*
  178028. * Arithmetic utilities
  178029. */
  178030. GLOBAL(long)
  178031. jdiv_round_up (long a, long b)
  178032. /* Compute a/b rounded up to next integer, ie, ceil(a/b) */
  178033. /* Assumes a >= 0, b > 0 */
  178034. {
  178035. return (a + b - 1L) / b;
  178036. }
  178037. GLOBAL(long)
  178038. jround_up (long a, long b)
  178039. /* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */
  178040. /* Assumes a >= 0, b > 0 */
  178041. {
  178042. a += b - 1L;
  178043. return a - (a % b);
  178044. }
  178045. /* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays
  178046. * and coefficient-block arrays. This won't work on 80x86 because the arrays
  178047. * are FAR and we're assuming a small-pointer memory model. However, some
  178048. * DOS compilers provide far-pointer versions of memcpy() and memset() even
  178049. * in the small-model libraries. These will be used if USE_FMEM is defined.
  178050. * Otherwise, the routines below do it the hard way. (The performance cost
  178051. * is not all that great, because these routines aren't very heavily used.)
  178052. */
  178053. #ifndef NEED_FAR_POINTERS /* normal case, same as regular macros */
  178054. #define FMEMCOPY(dest,src,size) MEMCOPY(dest,src,size)
  178055. #define FMEMZERO(target,size) MEMZERO(target,size)
  178056. #else /* 80x86 case, define if we can */
  178057. #ifdef USE_FMEM
  178058. #define FMEMCOPY(dest,src,size) _fmemcpy((void FAR *)(dest), (const void FAR *)(src), (size_t)(size))
  178059. #define FMEMZERO(target,size) _fmemset((void FAR *)(target), 0, (size_t)(size))
  178060. #endif
  178061. #endif
  178062. GLOBAL(void)
  178063. jcopy_sample_rows (JSAMPARRAY input_array, int source_row,
  178064. JSAMPARRAY output_array, int dest_row,
  178065. int num_rows, JDIMENSION num_cols)
  178066. /* Copy some rows of samples from one place to another.
  178067. * num_rows rows are copied from input_array[source_row++]
  178068. * to output_array[dest_row++]; these areas may overlap for duplication.
  178069. * The source and destination arrays must be at least as wide as num_cols.
  178070. */
  178071. {
  178072. register JSAMPROW inptr, outptr;
  178073. #ifdef FMEMCOPY
  178074. register size_t count = (size_t) (num_cols * SIZEOF(JSAMPLE));
  178075. #else
  178076. register JDIMENSION count;
  178077. #endif
  178078. register int row;
  178079. input_array += source_row;
  178080. output_array += dest_row;
  178081. for (row = num_rows; row > 0; row--) {
  178082. inptr = *input_array++;
  178083. outptr = *output_array++;
  178084. #ifdef FMEMCOPY
  178085. FMEMCOPY(outptr, inptr, count);
  178086. #else
  178087. for (count = num_cols; count > 0; count--)
  178088. *outptr++ = *inptr++; /* needn't bother with GETJSAMPLE() here */
  178089. #endif
  178090. }
  178091. }
  178092. GLOBAL(void)
  178093. jcopy_block_row (JBLOCKROW input_row, JBLOCKROW output_row,
  178094. JDIMENSION num_blocks)
  178095. /* Copy a row of coefficient blocks from one place to another. */
  178096. {
  178097. #ifdef FMEMCOPY
  178098. FMEMCOPY(output_row, input_row, num_blocks * (DCTSIZE2 * SIZEOF(JCOEF)));
  178099. #else
  178100. register JCOEFPTR inptr, outptr;
  178101. register long count;
  178102. inptr = (JCOEFPTR) input_row;
  178103. outptr = (JCOEFPTR) output_row;
  178104. for (count = (long) num_blocks * DCTSIZE2; count > 0; count--) {
  178105. *outptr++ = *inptr++;
  178106. }
  178107. #endif
  178108. }
  178109. GLOBAL(void)
  178110. jzero_far (void FAR * target, size_t bytestozero)
  178111. /* Zero out a chunk of FAR memory. */
  178112. /* This might be sample-array data, block-array data, or alloc_large data. */
  178113. {
  178114. #ifdef FMEMZERO
  178115. FMEMZERO(target, bytestozero);
  178116. #else
  178117. register char FAR * ptr = (char FAR *) target;
  178118. register size_t count;
  178119. for (count = bytestozero; count > 0; count--) {
  178120. *ptr++ = 0;
  178121. }
  178122. #endif
  178123. }
  178124. /*** End of inlined file: jutils.c ***/
  178125. /*** Start of inlined file: transupp.c ***/
  178126. /* Although this file really shouldn't have access to the library internals,
  178127. * it's helpful to let it call jround_up() and jcopy_block_row().
  178128. */
  178129. #define JPEG_INTERNALS
  178130. /*** Start of inlined file: transupp.h ***/
  178131. /* If you happen not to want the image transform support, disable it here */
  178132. #ifndef TRANSFORMS_SUPPORTED
  178133. #define TRANSFORMS_SUPPORTED 1 /* 0 disables transform code */
  178134. #endif
  178135. /* Short forms of external names for systems with brain-damaged linkers. */
  178136. #ifdef NEED_SHORT_EXTERNAL_NAMES
  178137. #define jtransform_request_workspace jTrRequest
  178138. #define jtransform_adjust_parameters jTrAdjust
  178139. #define jtransform_execute_transformation jTrExec
  178140. #define jcopy_markers_setup jCMrkSetup
  178141. #define jcopy_markers_execute jCMrkExec
  178142. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  178143. /*
  178144. * Codes for supported types of image transformations.
  178145. */
  178146. typedef enum {
  178147. JXFORM_NONE, /* no transformation */
  178148. JXFORM_FLIP_H, /* horizontal flip */
  178149. JXFORM_FLIP_V, /* vertical flip */
  178150. JXFORM_TRANSPOSE, /* transpose across UL-to-LR axis */
  178151. JXFORM_TRANSVERSE, /* transpose across UR-to-LL axis */
  178152. JXFORM_ROT_90, /* 90-degree clockwise rotation */
  178153. JXFORM_ROT_180, /* 180-degree rotation */
  178154. JXFORM_ROT_270 /* 270-degree clockwise (or 90 ccw) */
  178155. } JXFORM_CODE;
  178156. /*
  178157. * Although rotating and flipping data expressed as DCT coefficients is not
  178158. * hard, there is an asymmetry in the JPEG format specification for images
  178159. * whose dimensions aren't multiples of the iMCU size. The right and bottom
  178160. * image edges are padded out to the next iMCU boundary with junk data; but
  178161. * no padding is possible at the top and left edges. If we were to flip
  178162. * the whole image including the pad data, then pad garbage would become
  178163. * visible at the top and/or left, and real pixels would disappear into the
  178164. * pad margins --- perhaps permanently, since encoders & decoders may not
  178165. * bother to preserve DCT blocks that appear to be completely outside the
  178166. * nominal image area. So, we have to exclude any partial iMCUs from the
  178167. * basic transformation.
  178168. *
  178169. * Transpose is the only transformation that can handle partial iMCUs at the
  178170. * right and bottom edges completely cleanly. flip_h can flip partial iMCUs
  178171. * at the bottom, but leaves any partial iMCUs at the right edge untouched.
  178172. * Similarly flip_v leaves any partial iMCUs at the bottom edge untouched.
  178173. * The other transforms are defined as combinations of these basic transforms
  178174. * and process edge blocks in a way that preserves the equivalence.
  178175. *
  178176. * The "trim" option causes untransformable partial iMCUs to be dropped;
  178177. * this is not strictly lossless, but it usually gives the best-looking
  178178. * result for odd-size images. Note that when this option is active,
  178179. * the expected mathematical equivalences between the transforms may not hold.
  178180. * (For example, -rot 270 -trim trims only the bottom edge, but -rot 90 -trim
  178181. * followed by -rot 180 -trim trims both edges.)
  178182. *
  178183. * We also offer a "force to grayscale" option, which simply discards the
  178184. * chrominance channels of a YCbCr image. This is lossless in the sense that
  178185. * the luminance channel is preserved exactly. It's not the same kind of
  178186. * thing as the rotate/flip transformations, but it's convenient to handle it
  178187. * as part of this package, mainly because the transformation routines have to
  178188. * be aware of the option to know how many components to work on.
  178189. */
  178190. typedef struct {
  178191. /* Options: set by caller */
  178192. JXFORM_CODE transform; /* image transform operator */
  178193. boolean trim; /* if TRUE, trim partial MCUs as needed */
  178194. boolean force_grayscale; /* if TRUE, convert color image to grayscale */
  178195. /* Internal workspace: caller should not touch these */
  178196. int num_components; /* # of components in workspace */
  178197. jvirt_barray_ptr * workspace_coef_arrays; /* workspace for transformations */
  178198. } jpeg_transform_info;
  178199. #if TRANSFORMS_SUPPORTED
  178200. /* Request any required workspace */
  178201. EXTERN(void) jtransform_request_workspace
  178202. JPP((j_decompress_ptr srcinfo, jpeg_transform_info *info));
  178203. /* Adjust output image parameters */
  178204. EXTERN(jvirt_barray_ptr *) jtransform_adjust_parameters
  178205. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178206. jvirt_barray_ptr *src_coef_arrays,
  178207. jpeg_transform_info *info));
  178208. /* Execute the actual transformation, if any */
  178209. EXTERN(void) jtransform_execute_transformation
  178210. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178211. jvirt_barray_ptr *src_coef_arrays,
  178212. jpeg_transform_info *info));
  178213. #endif /* TRANSFORMS_SUPPORTED */
  178214. /*
  178215. * Support for copying optional markers from source to destination file.
  178216. */
  178217. typedef enum {
  178218. JCOPYOPT_NONE, /* copy no optional markers */
  178219. JCOPYOPT_COMMENTS, /* copy only comment (COM) markers */
  178220. JCOPYOPT_ALL /* copy all optional markers */
  178221. } JCOPY_OPTION;
  178222. #define JCOPYOPT_DEFAULT JCOPYOPT_COMMENTS /* recommended default */
  178223. /* Setup decompression object to save desired markers in memory */
  178224. EXTERN(void) jcopy_markers_setup
  178225. JPP((j_decompress_ptr srcinfo, JCOPY_OPTION option));
  178226. /* Copy markers saved in the given source object to the destination object */
  178227. EXTERN(void) jcopy_markers_execute
  178228. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178229. JCOPY_OPTION option));
  178230. /*** End of inlined file: transupp.h ***/
  178231. /* My own external interface */
  178232. #if TRANSFORMS_SUPPORTED
  178233. /*
  178234. * Lossless image transformation routines. These routines work on DCT
  178235. * coefficient arrays and thus do not require any lossy decompression
  178236. * or recompression of the image.
  178237. * Thanks to Guido Vollbeding for the initial design and code of this feature.
  178238. *
  178239. * Horizontal flipping is done in-place, using a single top-to-bottom
  178240. * pass through the virtual source array. It will thus be much the
  178241. * fastest option for images larger than main memory.
  178242. *
  178243. * The other routines require a set of destination virtual arrays, so they
  178244. * need twice as much memory as jpegtran normally does. The destination
  178245. * arrays are always written in normal scan order (top to bottom) because
  178246. * the virtual array manager expects this. The source arrays will be scanned
  178247. * in the corresponding order, which means multiple passes through the source
  178248. * arrays for most of the transforms. That could result in much thrashing
  178249. * if the image is larger than main memory.
  178250. *
  178251. * Some notes about the operating environment of the individual transform
  178252. * routines:
  178253. * 1. Both the source and destination virtual arrays are allocated from the
  178254. * source JPEG object, and therefore should be manipulated by calling the
  178255. * source's memory manager.
  178256. * 2. The destination's component count should be used. It may be smaller
  178257. * than the source's when forcing to grayscale.
  178258. * 3. Likewise the destination's sampling factors should be used. When
  178259. * forcing to grayscale the destination's sampling factors will be all 1,
  178260. * and we may as well take that as the effective iMCU size.
  178261. * 4. When "trim" is in effect, the destination's dimensions will be the
  178262. * trimmed values but the source's will be untrimmed.
  178263. * 5. All the routines assume that the source and destination buffers are
  178264. * padded out to a full iMCU boundary. This is true, although for the
  178265. * source buffer it is an undocumented property of jdcoefct.c.
  178266. * Notes 2,3,4 boil down to this: generally we should use the destination's
  178267. * dimensions and ignore the source's.
  178268. */
  178269. LOCAL(void)
  178270. do_flip_h (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178271. jvirt_barray_ptr *src_coef_arrays)
  178272. /* Horizontal flip; done in-place, so no separate dest array is required */
  178273. {
  178274. JDIMENSION MCU_cols, comp_width, blk_x, blk_y;
  178275. int ci, k, offset_y;
  178276. JBLOCKARRAY buffer;
  178277. JCOEFPTR ptr1, ptr2;
  178278. JCOEF temp1, temp2;
  178279. jpeg_component_info *compptr;
  178280. /* Horizontal mirroring of DCT blocks is accomplished by swapping
  178281. * pairs of blocks in-place. Within a DCT block, we perform horizontal
  178282. * mirroring by changing the signs of odd-numbered columns.
  178283. * Partial iMCUs at the right edge are left untouched.
  178284. */
  178285. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  178286. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178287. compptr = dstinfo->comp_info + ci;
  178288. comp_width = MCU_cols * compptr->h_samp_factor;
  178289. for (blk_y = 0; blk_y < compptr->height_in_blocks;
  178290. blk_y += compptr->v_samp_factor) {
  178291. buffer = (*srcinfo->mem->access_virt_barray)
  178292. ((j_common_ptr) srcinfo, src_coef_arrays[ci], blk_y,
  178293. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178294. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178295. for (blk_x = 0; blk_x * 2 < comp_width; blk_x++) {
  178296. ptr1 = buffer[offset_y][blk_x];
  178297. ptr2 = buffer[offset_y][comp_width - blk_x - 1];
  178298. /* this unrolled loop doesn't need to know which row it's on... */
  178299. for (k = 0; k < DCTSIZE2; k += 2) {
  178300. temp1 = *ptr1; /* swap even column */
  178301. temp2 = *ptr2;
  178302. *ptr1++ = temp2;
  178303. *ptr2++ = temp1;
  178304. temp1 = *ptr1; /* swap odd column with sign change */
  178305. temp2 = *ptr2;
  178306. *ptr1++ = -temp2;
  178307. *ptr2++ = -temp1;
  178308. }
  178309. }
  178310. }
  178311. }
  178312. }
  178313. }
  178314. LOCAL(void)
  178315. do_flip_v (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178316. jvirt_barray_ptr *src_coef_arrays,
  178317. jvirt_barray_ptr *dst_coef_arrays)
  178318. /* Vertical flip */
  178319. {
  178320. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  178321. int ci, i, j, offset_y;
  178322. JBLOCKARRAY src_buffer, dst_buffer;
  178323. JBLOCKROW src_row_ptr, dst_row_ptr;
  178324. JCOEFPTR src_ptr, dst_ptr;
  178325. jpeg_component_info *compptr;
  178326. /* We output into a separate array because we can't touch different
  178327. * rows of the source virtual array simultaneously. Otherwise, this
  178328. * is a pretty straightforward analog of horizontal flip.
  178329. * Within a DCT block, vertical mirroring is done by changing the signs
  178330. * of odd-numbered rows.
  178331. * Partial iMCUs at the bottom edge are copied verbatim.
  178332. */
  178333. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  178334. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178335. compptr = dstinfo->comp_info + ci;
  178336. comp_height = MCU_rows * compptr->v_samp_factor;
  178337. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  178338. dst_blk_y += compptr->v_samp_factor) {
  178339. dst_buffer = (*srcinfo->mem->access_virt_barray)
  178340. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  178341. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178342. if (dst_blk_y < comp_height) {
  178343. /* Row is within the mirrorable area. */
  178344. src_buffer = (*srcinfo->mem->access_virt_barray)
  178345. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  178346. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  178347. (JDIMENSION) compptr->v_samp_factor, FALSE);
  178348. } else {
  178349. /* Bottom-edge blocks will be copied verbatim. */
  178350. src_buffer = (*srcinfo->mem->access_virt_barray)
  178351. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  178352. (JDIMENSION) compptr->v_samp_factor, FALSE);
  178353. }
  178354. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178355. if (dst_blk_y < comp_height) {
  178356. /* Row is within the mirrorable area. */
  178357. dst_row_ptr = dst_buffer[offset_y];
  178358. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  178359. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  178360. dst_blk_x++) {
  178361. dst_ptr = dst_row_ptr[dst_blk_x];
  178362. src_ptr = src_row_ptr[dst_blk_x];
  178363. for (i = 0; i < DCTSIZE; i += 2) {
  178364. /* copy even row */
  178365. for (j = 0; j < DCTSIZE; j++)
  178366. *dst_ptr++ = *src_ptr++;
  178367. /* copy odd row with sign change */
  178368. for (j = 0; j < DCTSIZE; j++)
  178369. *dst_ptr++ = - *src_ptr++;
  178370. }
  178371. }
  178372. } else {
  178373. /* Just copy row verbatim. */
  178374. jcopy_block_row(src_buffer[offset_y], dst_buffer[offset_y],
  178375. compptr->width_in_blocks);
  178376. }
  178377. }
  178378. }
  178379. }
  178380. }
  178381. LOCAL(void)
  178382. do_transpose (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178383. jvirt_barray_ptr *src_coef_arrays,
  178384. jvirt_barray_ptr *dst_coef_arrays)
  178385. /* Transpose source into destination */
  178386. {
  178387. JDIMENSION dst_blk_x, dst_blk_y;
  178388. int ci, i, j, offset_x, offset_y;
  178389. JBLOCKARRAY src_buffer, dst_buffer;
  178390. JCOEFPTR src_ptr, dst_ptr;
  178391. jpeg_component_info *compptr;
  178392. /* Transposing pixels within a block just requires transposing the
  178393. * DCT coefficients.
  178394. * Partial iMCUs at the edges require no special treatment; we simply
  178395. * process all the available DCT blocks for every component.
  178396. */
  178397. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178398. compptr = dstinfo->comp_info + ci;
  178399. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  178400. dst_blk_y += compptr->v_samp_factor) {
  178401. dst_buffer = (*srcinfo->mem->access_virt_barray)
  178402. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  178403. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178404. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178405. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  178406. dst_blk_x += compptr->h_samp_factor) {
  178407. src_buffer = (*srcinfo->mem->access_virt_barray)
  178408. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  178409. (JDIMENSION) compptr->h_samp_factor, FALSE);
  178410. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  178411. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  178412. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  178413. for (i = 0; i < DCTSIZE; i++)
  178414. for (j = 0; j < DCTSIZE; j++)
  178415. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178416. }
  178417. }
  178418. }
  178419. }
  178420. }
  178421. }
  178422. LOCAL(void)
  178423. do_rot_90 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178424. jvirt_barray_ptr *src_coef_arrays,
  178425. jvirt_barray_ptr *dst_coef_arrays)
  178426. /* 90 degree rotation is equivalent to
  178427. * 1. Transposing the image;
  178428. * 2. Horizontal mirroring.
  178429. * These two steps are merged into a single processing routine.
  178430. */
  178431. {
  178432. JDIMENSION MCU_cols, comp_width, dst_blk_x, dst_blk_y;
  178433. int ci, i, j, offset_x, offset_y;
  178434. JBLOCKARRAY src_buffer, dst_buffer;
  178435. JCOEFPTR src_ptr, dst_ptr;
  178436. jpeg_component_info *compptr;
  178437. /* Because of the horizontal mirror step, we can't process partial iMCUs
  178438. * at the (output) right edge properly. They just get transposed and
  178439. * not mirrored.
  178440. */
  178441. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  178442. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178443. compptr = dstinfo->comp_info + ci;
  178444. comp_width = MCU_cols * compptr->h_samp_factor;
  178445. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  178446. dst_blk_y += compptr->v_samp_factor) {
  178447. dst_buffer = (*srcinfo->mem->access_virt_barray)
  178448. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  178449. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178450. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178451. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  178452. dst_blk_x += compptr->h_samp_factor) {
  178453. src_buffer = (*srcinfo->mem->access_virt_barray)
  178454. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  178455. (JDIMENSION) compptr->h_samp_factor, FALSE);
  178456. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  178457. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  178458. if (dst_blk_x < comp_width) {
  178459. /* Block is within the mirrorable area. */
  178460. dst_ptr = dst_buffer[offset_y]
  178461. [comp_width - dst_blk_x - offset_x - 1];
  178462. for (i = 0; i < DCTSIZE; i++) {
  178463. for (j = 0; j < DCTSIZE; j++)
  178464. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178465. i++;
  178466. for (j = 0; j < DCTSIZE; j++)
  178467. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  178468. }
  178469. } else {
  178470. /* Edge blocks are transposed but not mirrored. */
  178471. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  178472. for (i = 0; i < DCTSIZE; i++)
  178473. for (j = 0; j < DCTSIZE; j++)
  178474. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178475. }
  178476. }
  178477. }
  178478. }
  178479. }
  178480. }
  178481. }
  178482. LOCAL(void)
  178483. do_rot_270 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178484. jvirt_barray_ptr *src_coef_arrays,
  178485. jvirt_barray_ptr *dst_coef_arrays)
  178486. /* 270 degree rotation is equivalent to
  178487. * 1. Horizontal mirroring;
  178488. * 2. Transposing the image.
  178489. * These two steps are merged into a single processing routine.
  178490. */
  178491. {
  178492. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  178493. int ci, i, j, offset_x, offset_y;
  178494. JBLOCKARRAY src_buffer, dst_buffer;
  178495. JCOEFPTR src_ptr, dst_ptr;
  178496. jpeg_component_info *compptr;
  178497. /* Because of the horizontal mirror step, we can't process partial iMCUs
  178498. * at the (output) bottom edge properly. They just get transposed and
  178499. * not mirrored.
  178500. */
  178501. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  178502. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178503. compptr = dstinfo->comp_info + ci;
  178504. comp_height = MCU_rows * compptr->v_samp_factor;
  178505. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  178506. dst_blk_y += compptr->v_samp_factor) {
  178507. dst_buffer = (*srcinfo->mem->access_virt_barray)
  178508. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  178509. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178510. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178511. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  178512. dst_blk_x += compptr->h_samp_factor) {
  178513. src_buffer = (*srcinfo->mem->access_virt_barray)
  178514. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  178515. (JDIMENSION) compptr->h_samp_factor, FALSE);
  178516. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  178517. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  178518. if (dst_blk_y < comp_height) {
  178519. /* Block is within the mirrorable area. */
  178520. src_ptr = src_buffer[offset_x]
  178521. [comp_height - dst_blk_y - offset_y - 1];
  178522. for (i = 0; i < DCTSIZE; i++) {
  178523. for (j = 0; j < DCTSIZE; j++) {
  178524. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178525. j++;
  178526. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  178527. }
  178528. }
  178529. } else {
  178530. /* Edge blocks are transposed but not mirrored. */
  178531. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  178532. for (i = 0; i < DCTSIZE; i++)
  178533. for (j = 0; j < DCTSIZE; j++)
  178534. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178535. }
  178536. }
  178537. }
  178538. }
  178539. }
  178540. }
  178541. }
  178542. LOCAL(void)
  178543. do_rot_180 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178544. jvirt_barray_ptr *src_coef_arrays,
  178545. jvirt_barray_ptr *dst_coef_arrays)
  178546. /* 180 degree rotation is equivalent to
  178547. * 1. Vertical mirroring;
  178548. * 2. Horizontal mirroring.
  178549. * These two steps are merged into a single processing routine.
  178550. */
  178551. {
  178552. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  178553. int ci, i, j, offset_y;
  178554. JBLOCKARRAY src_buffer, dst_buffer;
  178555. JBLOCKROW src_row_ptr, dst_row_ptr;
  178556. JCOEFPTR src_ptr, dst_ptr;
  178557. jpeg_component_info *compptr;
  178558. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  178559. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  178560. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178561. compptr = dstinfo->comp_info + ci;
  178562. comp_width = MCU_cols * compptr->h_samp_factor;
  178563. comp_height = MCU_rows * compptr->v_samp_factor;
  178564. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  178565. dst_blk_y += compptr->v_samp_factor) {
  178566. dst_buffer = (*srcinfo->mem->access_virt_barray)
  178567. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  178568. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178569. if (dst_blk_y < comp_height) {
  178570. /* Row is within the vertically mirrorable area. */
  178571. src_buffer = (*srcinfo->mem->access_virt_barray)
  178572. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  178573. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  178574. (JDIMENSION) compptr->v_samp_factor, FALSE);
  178575. } else {
  178576. /* Bottom-edge rows are only mirrored horizontally. */
  178577. src_buffer = (*srcinfo->mem->access_virt_barray)
  178578. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  178579. (JDIMENSION) compptr->v_samp_factor, FALSE);
  178580. }
  178581. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178582. if (dst_blk_y < comp_height) {
  178583. /* Row is within the mirrorable area. */
  178584. dst_row_ptr = dst_buffer[offset_y];
  178585. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  178586. /* Process the blocks that can be mirrored both ways. */
  178587. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  178588. dst_ptr = dst_row_ptr[dst_blk_x];
  178589. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  178590. for (i = 0; i < DCTSIZE; i += 2) {
  178591. /* For even row, negate every odd column. */
  178592. for (j = 0; j < DCTSIZE; j += 2) {
  178593. *dst_ptr++ = *src_ptr++;
  178594. *dst_ptr++ = - *src_ptr++;
  178595. }
  178596. /* For odd row, negate every even column. */
  178597. for (j = 0; j < DCTSIZE; j += 2) {
  178598. *dst_ptr++ = - *src_ptr++;
  178599. *dst_ptr++ = *src_ptr++;
  178600. }
  178601. }
  178602. }
  178603. /* Any remaining right-edge blocks are only mirrored vertically. */
  178604. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  178605. dst_ptr = dst_row_ptr[dst_blk_x];
  178606. src_ptr = src_row_ptr[dst_blk_x];
  178607. for (i = 0; i < DCTSIZE; i += 2) {
  178608. for (j = 0; j < DCTSIZE; j++)
  178609. *dst_ptr++ = *src_ptr++;
  178610. for (j = 0; j < DCTSIZE; j++)
  178611. *dst_ptr++ = - *src_ptr++;
  178612. }
  178613. }
  178614. } else {
  178615. /* Remaining rows are just mirrored horizontally. */
  178616. dst_row_ptr = dst_buffer[offset_y];
  178617. src_row_ptr = src_buffer[offset_y];
  178618. /* Process the blocks that can be mirrored. */
  178619. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  178620. dst_ptr = dst_row_ptr[dst_blk_x];
  178621. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  178622. for (i = 0; i < DCTSIZE2; i += 2) {
  178623. *dst_ptr++ = *src_ptr++;
  178624. *dst_ptr++ = - *src_ptr++;
  178625. }
  178626. }
  178627. /* Any remaining right-edge blocks are only copied. */
  178628. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  178629. dst_ptr = dst_row_ptr[dst_blk_x];
  178630. src_ptr = src_row_ptr[dst_blk_x];
  178631. for (i = 0; i < DCTSIZE2; i++)
  178632. *dst_ptr++ = *src_ptr++;
  178633. }
  178634. }
  178635. }
  178636. }
  178637. }
  178638. }
  178639. LOCAL(void)
  178640. do_transverse (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178641. jvirt_barray_ptr *src_coef_arrays,
  178642. jvirt_barray_ptr *dst_coef_arrays)
  178643. /* Transverse transpose is equivalent to
  178644. * 1. 180 degree rotation;
  178645. * 2. Transposition;
  178646. * or
  178647. * 1. Horizontal mirroring;
  178648. * 2. Transposition;
  178649. * 3. Horizontal mirroring.
  178650. * These steps are merged into a single processing routine.
  178651. */
  178652. {
  178653. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  178654. int ci, i, j, offset_x, offset_y;
  178655. JBLOCKARRAY src_buffer, dst_buffer;
  178656. JCOEFPTR src_ptr, dst_ptr;
  178657. jpeg_component_info *compptr;
  178658. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  178659. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  178660. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178661. compptr = dstinfo->comp_info + ci;
  178662. comp_width = MCU_cols * compptr->h_samp_factor;
  178663. comp_height = MCU_rows * compptr->v_samp_factor;
  178664. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  178665. dst_blk_y += compptr->v_samp_factor) {
  178666. dst_buffer = (*srcinfo->mem->access_virt_barray)
  178667. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  178668. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178669. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178670. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  178671. dst_blk_x += compptr->h_samp_factor) {
  178672. src_buffer = (*srcinfo->mem->access_virt_barray)
  178673. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  178674. (JDIMENSION) compptr->h_samp_factor, FALSE);
  178675. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  178676. if (dst_blk_y < comp_height) {
  178677. src_ptr = src_buffer[offset_x]
  178678. [comp_height - dst_blk_y - offset_y - 1];
  178679. if (dst_blk_x < comp_width) {
  178680. /* Block is within the mirrorable area. */
  178681. dst_ptr = dst_buffer[offset_y]
  178682. [comp_width - dst_blk_x - offset_x - 1];
  178683. for (i = 0; i < DCTSIZE; i++) {
  178684. for (j = 0; j < DCTSIZE; j++) {
  178685. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178686. j++;
  178687. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  178688. }
  178689. i++;
  178690. for (j = 0; j < DCTSIZE; j++) {
  178691. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  178692. j++;
  178693. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178694. }
  178695. }
  178696. } else {
  178697. /* Right-edge blocks are mirrored in y only */
  178698. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  178699. for (i = 0; i < DCTSIZE; i++) {
  178700. for (j = 0; j < DCTSIZE; j++) {
  178701. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178702. j++;
  178703. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  178704. }
  178705. }
  178706. }
  178707. } else {
  178708. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  178709. if (dst_blk_x < comp_width) {
  178710. /* Bottom-edge blocks are mirrored in x only */
  178711. dst_ptr = dst_buffer[offset_y]
  178712. [comp_width - dst_blk_x - offset_x - 1];
  178713. for (i = 0; i < DCTSIZE; i++) {
  178714. for (j = 0; j < DCTSIZE; j++)
  178715. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178716. i++;
  178717. for (j = 0; j < DCTSIZE; j++)
  178718. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  178719. }
  178720. } else {
  178721. /* At lower right corner, just transpose, no mirroring */
  178722. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  178723. for (i = 0; i < DCTSIZE; i++)
  178724. for (j = 0; j < DCTSIZE; j++)
  178725. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178726. }
  178727. }
  178728. }
  178729. }
  178730. }
  178731. }
  178732. }
  178733. }
  178734. /* Request any required workspace.
  178735. *
  178736. * We allocate the workspace virtual arrays from the source decompression
  178737. * object, so that all the arrays (both the original data and the workspace)
  178738. * will be taken into account while making memory management decisions.
  178739. * Hence, this routine must be called after jpeg_read_header (which reads
  178740. * the image dimensions) and before jpeg_read_coefficients (which realizes
  178741. * the source's virtual arrays).
  178742. */
  178743. GLOBAL(void)
  178744. jtransform_request_workspace (j_decompress_ptr srcinfo,
  178745. jpeg_transform_info *info)
  178746. {
  178747. jvirt_barray_ptr *coef_arrays = NULL;
  178748. jpeg_component_info *compptr;
  178749. int ci;
  178750. if (info->force_grayscale &&
  178751. srcinfo->jpeg_color_space == JCS_YCbCr &&
  178752. srcinfo->num_components == 3) {
  178753. /* We'll only process the first component */
  178754. info->num_components = 1;
  178755. } else {
  178756. /* Process all the components */
  178757. info->num_components = srcinfo->num_components;
  178758. }
  178759. switch (info->transform) {
  178760. case JXFORM_NONE:
  178761. case JXFORM_FLIP_H:
  178762. /* Don't need a workspace array */
  178763. break;
  178764. case JXFORM_FLIP_V:
  178765. case JXFORM_ROT_180:
  178766. /* Need workspace arrays having same dimensions as source image.
  178767. * Note that we allocate arrays padded out to the next iMCU boundary,
  178768. * so that transform routines need not worry about missing edge blocks.
  178769. */
  178770. coef_arrays = (jvirt_barray_ptr *)
  178771. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  178772. SIZEOF(jvirt_barray_ptr) * info->num_components);
  178773. for (ci = 0; ci < info->num_components; ci++) {
  178774. compptr = srcinfo->comp_info + ci;
  178775. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  178776. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  178777. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  178778. (long) compptr->h_samp_factor),
  178779. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  178780. (long) compptr->v_samp_factor),
  178781. (JDIMENSION) compptr->v_samp_factor);
  178782. }
  178783. break;
  178784. case JXFORM_TRANSPOSE:
  178785. case JXFORM_TRANSVERSE:
  178786. case JXFORM_ROT_90:
  178787. case JXFORM_ROT_270:
  178788. /* Need workspace arrays having transposed dimensions.
  178789. * Note that we allocate arrays padded out to the next iMCU boundary,
  178790. * so that transform routines need not worry about missing edge blocks.
  178791. */
  178792. coef_arrays = (jvirt_barray_ptr *)
  178793. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  178794. SIZEOF(jvirt_barray_ptr) * info->num_components);
  178795. for (ci = 0; ci < info->num_components; ci++) {
  178796. compptr = srcinfo->comp_info + ci;
  178797. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  178798. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  178799. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  178800. (long) compptr->v_samp_factor),
  178801. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  178802. (long) compptr->h_samp_factor),
  178803. (JDIMENSION) compptr->h_samp_factor);
  178804. }
  178805. break;
  178806. }
  178807. info->workspace_coef_arrays = coef_arrays;
  178808. }
  178809. /* Transpose destination image parameters */
  178810. LOCAL(void)
  178811. transpose_critical_parameters (j_compress_ptr dstinfo)
  178812. {
  178813. int tblno, i, j, ci, itemp;
  178814. jpeg_component_info *compptr;
  178815. JQUANT_TBL *qtblptr;
  178816. JDIMENSION dtemp;
  178817. UINT16 qtemp;
  178818. /* Transpose basic image dimensions */
  178819. dtemp = dstinfo->image_width;
  178820. dstinfo->image_width = dstinfo->image_height;
  178821. dstinfo->image_height = dtemp;
  178822. /* Transpose sampling factors */
  178823. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178824. compptr = dstinfo->comp_info + ci;
  178825. itemp = compptr->h_samp_factor;
  178826. compptr->h_samp_factor = compptr->v_samp_factor;
  178827. compptr->v_samp_factor = itemp;
  178828. }
  178829. /* Transpose quantization tables */
  178830. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  178831. qtblptr = dstinfo->quant_tbl_ptrs[tblno];
  178832. if (qtblptr != NULL) {
  178833. for (i = 0; i < DCTSIZE; i++) {
  178834. for (j = 0; j < i; j++) {
  178835. qtemp = qtblptr->quantval[i*DCTSIZE+j];
  178836. qtblptr->quantval[i*DCTSIZE+j] = qtblptr->quantval[j*DCTSIZE+i];
  178837. qtblptr->quantval[j*DCTSIZE+i] = qtemp;
  178838. }
  178839. }
  178840. }
  178841. }
  178842. }
  178843. /* Trim off any partial iMCUs on the indicated destination edge */
  178844. LOCAL(void)
  178845. trim_right_edge (j_compress_ptr dstinfo)
  178846. {
  178847. int ci, max_h_samp_factor;
  178848. JDIMENSION MCU_cols;
  178849. /* We have to compute max_h_samp_factor ourselves,
  178850. * because it hasn't been set yet in the destination
  178851. * (and we don't want to use the source's value).
  178852. */
  178853. max_h_samp_factor = 1;
  178854. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178855. int h_samp_factor = dstinfo->comp_info[ci].h_samp_factor;
  178856. max_h_samp_factor = MAX(max_h_samp_factor, h_samp_factor);
  178857. }
  178858. MCU_cols = dstinfo->image_width / (max_h_samp_factor * DCTSIZE);
  178859. if (MCU_cols > 0) /* can't trim to 0 pixels */
  178860. dstinfo->image_width = MCU_cols * (max_h_samp_factor * DCTSIZE);
  178861. }
  178862. LOCAL(void)
  178863. trim_bottom_edge (j_compress_ptr dstinfo)
  178864. {
  178865. int ci, max_v_samp_factor;
  178866. JDIMENSION MCU_rows;
  178867. /* We have to compute max_v_samp_factor ourselves,
  178868. * because it hasn't been set yet in the destination
  178869. * (and we don't want to use the source's value).
  178870. */
  178871. max_v_samp_factor = 1;
  178872. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178873. int v_samp_factor = dstinfo->comp_info[ci].v_samp_factor;
  178874. max_v_samp_factor = MAX(max_v_samp_factor, v_samp_factor);
  178875. }
  178876. MCU_rows = dstinfo->image_height / (max_v_samp_factor * DCTSIZE);
  178877. if (MCU_rows > 0) /* can't trim to 0 pixels */
  178878. dstinfo->image_height = MCU_rows * (max_v_samp_factor * DCTSIZE);
  178879. }
  178880. /* Adjust output image parameters as needed.
  178881. *
  178882. * This must be called after jpeg_copy_critical_parameters()
  178883. * and before jpeg_write_coefficients().
  178884. *
  178885. * The return value is the set of virtual coefficient arrays to be written
  178886. * (either the ones allocated by jtransform_request_workspace, or the
  178887. * original source data arrays). The caller will need to pass this value
  178888. * to jpeg_write_coefficients().
  178889. */
  178890. GLOBAL(jvirt_barray_ptr *)
  178891. jtransform_adjust_parameters (j_decompress_ptr,
  178892. j_compress_ptr dstinfo,
  178893. jvirt_barray_ptr *src_coef_arrays,
  178894. jpeg_transform_info *info)
  178895. {
  178896. /* If force-to-grayscale is requested, adjust destination parameters */
  178897. if (info->force_grayscale) {
  178898. /* We use jpeg_set_colorspace to make sure subsidiary settings get fixed
  178899. * properly. Among other things, the target h_samp_factor & v_samp_factor
  178900. * will get set to 1, which typically won't match the source.
  178901. * In fact we do this even if the source is already grayscale; that
  178902. * provides an easy way of coercing a grayscale JPEG with funny sampling
  178903. * factors to the customary 1,1. (Some decoders fail on other factors.)
  178904. */
  178905. if ((dstinfo->jpeg_color_space == JCS_YCbCr &&
  178906. dstinfo->num_components == 3) ||
  178907. (dstinfo->jpeg_color_space == JCS_GRAYSCALE &&
  178908. dstinfo->num_components == 1)) {
  178909. /* We have to preserve the source's quantization table number. */
  178910. int sv_quant_tbl_no = dstinfo->comp_info[0].quant_tbl_no;
  178911. jpeg_set_colorspace(dstinfo, JCS_GRAYSCALE);
  178912. dstinfo->comp_info[0].quant_tbl_no = sv_quant_tbl_no;
  178913. } else {
  178914. /* Sorry, can't do it */
  178915. ERREXIT(dstinfo, JERR_CONVERSION_NOTIMPL);
  178916. }
  178917. }
  178918. /* Correct the destination's image dimensions etc if necessary */
  178919. switch (info->transform) {
  178920. case JXFORM_NONE:
  178921. /* Nothing to do */
  178922. break;
  178923. case JXFORM_FLIP_H:
  178924. if (info->trim)
  178925. trim_right_edge(dstinfo);
  178926. break;
  178927. case JXFORM_FLIP_V:
  178928. if (info->trim)
  178929. trim_bottom_edge(dstinfo);
  178930. break;
  178931. case JXFORM_TRANSPOSE:
  178932. transpose_critical_parameters(dstinfo);
  178933. /* transpose does NOT have to trim anything */
  178934. break;
  178935. case JXFORM_TRANSVERSE:
  178936. transpose_critical_parameters(dstinfo);
  178937. if (info->trim) {
  178938. trim_right_edge(dstinfo);
  178939. trim_bottom_edge(dstinfo);
  178940. }
  178941. break;
  178942. case JXFORM_ROT_90:
  178943. transpose_critical_parameters(dstinfo);
  178944. if (info->trim)
  178945. trim_right_edge(dstinfo);
  178946. break;
  178947. case JXFORM_ROT_180:
  178948. if (info->trim) {
  178949. trim_right_edge(dstinfo);
  178950. trim_bottom_edge(dstinfo);
  178951. }
  178952. break;
  178953. case JXFORM_ROT_270:
  178954. transpose_critical_parameters(dstinfo);
  178955. if (info->trim)
  178956. trim_bottom_edge(dstinfo);
  178957. break;
  178958. }
  178959. /* Return the appropriate output data set */
  178960. if (info->workspace_coef_arrays != NULL)
  178961. return info->workspace_coef_arrays;
  178962. return src_coef_arrays;
  178963. }
  178964. /* Execute the actual transformation, if any.
  178965. *
  178966. * This must be called *after* jpeg_write_coefficients, because it depends
  178967. * on jpeg_write_coefficients to have computed subsidiary values such as
  178968. * the per-component width and height fields in the destination object.
  178969. *
  178970. * Note that some transformations will modify the source data arrays!
  178971. */
  178972. GLOBAL(void)
  178973. jtransform_execute_transformation (j_decompress_ptr srcinfo,
  178974. j_compress_ptr dstinfo,
  178975. jvirt_barray_ptr *src_coef_arrays,
  178976. jpeg_transform_info *info)
  178977. {
  178978. jvirt_barray_ptr *dst_coef_arrays = info->workspace_coef_arrays;
  178979. switch (info->transform) {
  178980. case JXFORM_NONE:
  178981. break;
  178982. case JXFORM_FLIP_H:
  178983. do_flip_h(srcinfo, dstinfo, src_coef_arrays);
  178984. break;
  178985. case JXFORM_FLIP_V:
  178986. do_flip_v(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  178987. break;
  178988. case JXFORM_TRANSPOSE:
  178989. do_transpose(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  178990. break;
  178991. case JXFORM_TRANSVERSE:
  178992. do_transverse(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  178993. break;
  178994. case JXFORM_ROT_90:
  178995. do_rot_90(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  178996. break;
  178997. case JXFORM_ROT_180:
  178998. do_rot_180(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  178999. break;
  179000. case JXFORM_ROT_270:
  179001. do_rot_270(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179002. break;
  179003. }
  179004. }
  179005. #endif /* TRANSFORMS_SUPPORTED */
  179006. /* Setup decompression object to save desired markers in memory.
  179007. * This must be called before jpeg_read_header() to have the desired effect.
  179008. */
  179009. GLOBAL(void)
  179010. jcopy_markers_setup (j_decompress_ptr srcinfo, JCOPY_OPTION option)
  179011. {
  179012. #ifdef SAVE_MARKERS_SUPPORTED
  179013. int m;
  179014. /* Save comments except under NONE option */
  179015. if (option != JCOPYOPT_NONE) {
  179016. jpeg_save_markers(srcinfo, JPEG_COM, 0xFFFF);
  179017. }
  179018. /* Save all types of APPn markers iff ALL option */
  179019. if (option == JCOPYOPT_ALL) {
  179020. for (m = 0; m < 16; m++)
  179021. jpeg_save_markers(srcinfo, JPEG_APP0 + m, 0xFFFF);
  179022. }
  179023. #endif /* SAVE_MARKERS_SUPPORTED */
  179024. }
  179025. /* Copy markers saved in the given source object to the destination object.
  179026. * This should be called just after jpeg_start_compress() or
  179027. * jpeg_write_coefficients().
  179028. * Note that those routines will have written the SOI, and also the
  179029. * JFIF APP0 or Adobe APP14 markers if selected.
  179030. */
  179031. GLOBAL(void)
  179032. jcopy_markers_execute (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179033. JCOPY_OPTION)
  179034. {
  179035. jpeg_saved_marker_ptr marker;
  179036. /* In the current implementation, we don't actually need to examine the
  179037. * option flag here; we just copy everything that got saved.
  179038. * But to avoid confusion, we do not output JFIF and Adobe APP14 markers
  179039. * if the encoder library already wrote one.
  179040. */
  179041. for (marker = srcinfo->marker_list; marker != NULL; marker = marker->next) {
  179042. if (dstinfo->write_JFIF_header &&
  179043. marker->marker == JPEG_APP0 &&
  179044. marker->data_length >= 5 &&
  179045. GETJOCTET(marker->data[0]) == 0x4A &&
  179046. GETJOCTET(marker->data[1]) == 0x46 &&
  179047. GETJOCTET(marker->data[2]) == 0x49 &&
  179048. GETJOCTET(marker->data[3]) == 0x46 &&
  179049. GETJOCTET(marker->data[4]) == 0)
  179050. continue; /* reject duplicate JFIF */
  179051. if (dstinfo->write_Adobe_marker &&
  179052. marker->marker == JPEG_APP0+14 &&
  179053. marker->data_length >= 5 &&
  179054. GETJOCTET(marker->data[0]) == 0x41 &&
  179055. GETJOCTET(marker->data[1]) == 0x64 &&
  179056. GETJOCTET(marker->data[2]) == 0x6F &&
  179057. GETJOCTET(marker->data[3]) == 0x62 &&
  179058. GETJOCTET(marker->data[4]) == 0x65)
  179059. continue; /* reject duplicate Adobe */
  179060. #ifdef NEED_FAR_POINTERS
  179061. /* We could use jpeg_write_marker if the data weren't FAR... */
  179062. {
  179063. unsigned int i;
  179064. jpeg_write_m_header(dstinfo, marker->marker, marker->data_length);
  179065. for (i = 0; i < marker->data_length; i++)
  179066. jpeg_write_m_byte(dstinfo, marker->data[i]);
  179067. }
  179068. #else
  179069. jpeg_write_marker(dstinfo, marker->marker,
  179070. marker->data, marker->data_length);
  179071. #endif
  179072. }
  179073. }
  179074. /*** End of inlined file: transupp.c ***/
  179075. }
  179076. #else
  179077. #define JPEG_INTERNALS
  179078. #undef FAR
  179079. #include <jpeglib.h>
  179080. #endif
  179081. }
  179082. #undef max
  179083. #undef min
  179084. #if JUCE_MSVC
  179085. #pragma warning (pop)
  179086. #endif
  179087. BEGIN_JUCE_NAMESPACE
  179088. namespace JPEGHelpers
  179089. {
  179090. using namespace jpeglibNamespace;
  179091. #if ! JUCE_MSVC
  179092. using jpeglibNamespace::boolean;
  179093. #endif
  179094. struct JPEGDecodingFailure {};
  179095. static void fatalErrorHandler (j_common_ptr)
  179096. {
  179097. throw JPEGDecodingFailure();
  179098. }
  179099. static void silentErrorCallback1 (j_common_ptr) {}
  179100. static void silentErrorCallback2 (j_common_ptr, int) {}
  179101. static void silentErrorCallback3 (j_common_ptr, char*) {}
  179102. static void setupSilentErrorHandler (struct jpeg_error_mgr& err)
  179103. {
  179104. zerostruct (err);
  179105. err.error_exit = fatalErrorHandler;
  179106. err.emit_message = silentErrorCallback2;
  179107. err.output_message = silentErrorCallback1;
  179108. err.format_message = silentErrorCallback3;
  179109. err.reset_error_mgr = silentErrorCallback1;
  179110. }
  179111. static void dummyCallback1 (j_decompress_ptr)
  179112. {
  179113. }
  179114. static void jpegSkip (j_decompress_ptr decompStruct, long num)
  179115. {
  179116. decompStruct->src->next_input_byte += num;
  179117. num = jmin (num, (long) decompStruct->src->bytes_in_buffer);
  179118. decompStruct->src->bytes_in_buffer -= num;
  179119. }
  179120. static boolean jpegFill (j_decompress_ptr)
  179121. {
  179122. return 0;
  179123. }
  179124. static const int jpegBufferSize = 512;
  179125. struct JuceJpegDest : public jpeg_destination_mgr
  179126. {
  179127. OutputStream* output;
  179128. char* buffer;
  179129. };
  179130. static void jpegWriteInit (j_compress_ptr)
  179131. {
  179132. }
  179133. static void jpegWriteTerminate (j_compress_ptr cinfo)
  179134. {
  179135. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  179136. const size_t numToWrite = jpegBufferSize - dest->free_in_buffer;
  179137. dest->output->write (dest->buffer, (int) numToWrite);
  179138. }
  179139. static boolean jpegWriteFlush (j_compress_ptr cinfo)
  179140. {
  179141. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  179142. const int numToWrite = jpegBufferSize;
  179143. dest->next_output_byte = reinterpret_cast <JOCTET*> (dest->buffer);
  179144. dest->free_in_buffer = jpegBufferSize;
  179145. return dest->output->write (dest->buffer, numToWrite);
  179146. }
  179147. }
  179148. JPEGImageFormat::JPEGImageFormat()
  179149. : quality (-1.0f)
  179150. {
  179151. }
  179152. JPEGImageFormat::~JPEGImageFormat() {}
  179153. void JPEGImageFormat::setQuality (const float newQuality)
  179154. {
  179155. quality = newQuality;
  179156. }
  179157. const String JPEGImageFormat::getFormatName()
  179158. {
  179159. return "JPEG";
  179160. }
  179161. bool JPEGImageFormat::canUnderstand (InputStream& in)
  179162. {
  179163. const int bytesNeeded = 10;
  179164. uint8 header [bytesNeeded];
  179165. if (in.read (header, bytesNeeded) == bytesNeeded)
  179166. {
  179167. return header[0] == 0xff
  179168. && header[1] == 0xd8
  179169. && header[2] == 0xff
  179170. && (header[3] == 0xe0 || header[3] == 0xe1);
  179171. }
  179172. return false;
  179173. }
  179174. const Image JPEGImageFormat::decodeImage (InputStream& in)
  179175. {
  179176. using namespace jpeglibNamespace;
  179177. using namespace JPEGHelpers;
  179178. MemoryBlock mb;
  179179. in.readIntoMemoryBlock (mb);
  179180. Image image;
  179181. if (mb.getSize() > 16)
  179182. {
  179183. struct jpeg_decompress_struct jpegDecompStruct;
  179184. struct jpeg_error_mgr jerr;
  179185. setupSilentErrorHandler (jerr);
  179186. jpegDecompStruct.err = &jerr;
  179187. jpeg_create_decompress (&jpegDecompStruct);
  179188. jpegDecompStruct.src = (jpeg_source_mgr*)(jpegDecompStruct.mem->alloc_small)
  179189. ((j_common_ptr)(&jpegDecompStruct), JPOOL_PERMANENT, sizeof (jpeg_source_mgr));
  179190. jpegDecompStruct.src->init_source = dummyCallback1;
  179191. jpegDecompStruct.src->fill_input_buffer = jpegFill;
  179192. jpegDecompStruct.src->skip_input_data = jpegSkip;
  179193. jpegDecompStruct.src->resync_to_restart = jpeg_resync_to_restart;
  179194. jpegDecompStruct.src->term_source = dummyCallback1;
  179195. jpegDecompStruct.src->next_input_byte = static_cast <const unsigned char*> (mb.getData());
  179196. jpegDecompStruct.src->bytes_in_buffer = mb.getSize();
  179197. try
  179198. {
  179199. jpeg_read_header (&jpegDecompStruct, TRUE);
  179200. jpeg_calc_output_dimensions (&jpegDecompStruct);
  179201. const int width = jpegDecompStruct.output_width;
  179202. const int height = jpegDecompStruct.output_height;
  179203. jpegDecompStruct.out_color_space = JCS_RGB;
  179204. JSAMPARRAY buffer
  179205. = (*jpegDecompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegDecompStruct,
  179206. JPOOL_IMAGE,
  179207. width * 3, 1);
  179208. if (jpeg_start_decompress (&jpegDecompStruct))
  179209. {
  179210. image = Image (Image::RGB, width, height, false);
  179211. const bool hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  179212. const Image::BitmapData destData (image, 0, 0, width, height, true);
  179213. for (int y = 0; y < height; ++y)
  179214. {
  179215. jpeg_read_scanlines (&jpegDecompStruct, buffer, 1);
  179216. const uint8* src = *buffer;
  179217. uint8* dest = destData.getLinePointer (y);
  179218. if (hasAlphaChan)
  179219. {
  179220. for (int i = width; --i >= 0;)
  179221. {
  179222. ((PixelARGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  179223. ((PixelARGB*) dest)->premultiply();
  179224. dest += destData.pixelStride;
  179225. src += 3;
  179226. }
  179227. }
  179228. else
  179229. {
  179230. for (int i = width; --i >= 0;)
  179231. {
  179232. ((PixelRGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  179233. dest += destData.pixelStride;
  179234. src += 3;
  179235. }
  179236. }
  179237. }
  179238. jpeg_finish_decompress (&jpegDecompStruct);
  179239. in.setPosition (((char*) jpegDecompStruct.src->next_input_byte) - (char*) mb.getData());
  179240. }
  179241. jpeg_destroy_decompress (&jpegDecompStruct);
  179242. }
  179243. catch (...)
  179244. {}
  179245. }
  179246. return image;
  179247. }
  179248. bool JPEGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  179249. {
  179250. using namespace jpeglibNamespace;
  179251. using namespace JPEGHelpers;
  179252. if (image.hasAlphaChannel())
  179253. {
  179254. // this method could fill the background in white and still save the image..
  179255. jassertfalse;
  179256. return true;
  179257. }
  179258. struct jpeg_compress_struct jpegCompStruct;
  179259. struct jpeg_error_mgr jerr;
  179260. setupSilentErrorHandler (jerr);
  179261. jpegCompStruct.err = &jerr;
  179262. jpeg_create_compress (&jpegCompStruct);
  179263. JuceJpegDest dest;
  179264. jpegCompStruct.dest = &dest;
  179265. dest.output = &out;
  179266. HeapBlock <char> tempBuffer (jpegBufferSize);
  179267. dest.buffer = tempBuffer;
  179268. dest.next_output_byte = (JOCTET*) dest.buffer;
  179269. dest.free_in_buffer = jpegBufferSize;
  179270. dest.init_destination = jpegWriteInit;
  179271. dest.empty_output_buffer = jpegWriteFlush;
  179272. dest.term_destination = jpegWriteTerminate;
  179273. jpegCompStruct.image_width = image.getWidth();
  179274. jpegCompStruct.image_height = image.getHeight();
  179275. jpegCompStruct.input_components = 3;
  179276. jpegCompStruct.in_color_space = JCS_RGB;
  179277. jpegCompStruct.write_JFIF_header = 1;
  179278. jpegCompStruct.X_density = 72;
  179279. jpegCompStruct.Y_density = 72;
  179280. jpeg_set_defaults (&jpegCompStruct);
  179281. jpegCompStruct.dct_method = JDCT_FLOAT;
  179282. jpegCompStruct.optimize_coding = 1;
  179283. //jpegCompStruct.smoothing_factor = 10;
  179284. if (quality < 0.0f)
  179285. quality = 0.85f;
  179286. jpeg_set_quality (&jpegCompStruct, jlimit (0, 100, roundToInt (quality * 100.0f)), TRUE);
  179287. jpeg_start_compress (&jpegCompStruct, TRUE);
  179288. const int strideBytes = jpegCompStruct.image_width * jpegCompStruct.input_components;
  179289. JSAMPARRAY buffer = (*jpegCompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegCompStruct,
  179290. JPOOL_IMAGE, strideBytes, 1);
  179291. const Image::BitmapData srcData (image, 0, 0, jpegCompStruct.image_width, jpegCompStruct.image_height);
  179292. while (jpegCompStruct.next_scanline < jpegCompStruct.image_height)
  179293. {
  179294. const uint8* src = srcData.getLinePointer (jpegCompStruct.next_scanline);
  179295. uint8* dst = *buffer;
  179296. for (int i = jpegCompStruct.image_width; --i >= 0;)
  179297. {
  179298. *dst++ = ((const PixelRGB*) src)->getRed();
  179299. *dst++ = ((const PixelRGB*) src)->getGreen();
  179300. *dst++ = ((const PixelRGB*) src)->getBlue();
  179301. src += srcData.pixelStride;
  179302. }
  179303. jpeg_write_scanlines (&jpegCompStruct, buffer, 1);
  179304. }
  179305. jpeg_finish_compress (&jpegCompStruct);
  179306. jpeg_destroy_compress (&jpegCompStruct);
  179307. out.flush();
  179308. return true;
  179309. }
  179310. END_JUCE_NAMESPACE
  179311. /*** End of inlined file: juce_JPEGLoader.cpp ***/
  179312. /*** Start of inlined file: juce_PNGLoader.cpp ***/
  179313. #if JUCE_MSVC
  179314. #pragma warning (push)
  179315. #pragma warning (disable: 4390 4611)
  179316. #endif
  179317. namespace zlibNamespace
  179318. {
  179319. #if JUCE_INCLUDE_ZLIB_CODE
  179320. #undef OS_CODE
  179321. #undef fdopen
  179322. #undef OS_CODE
  179323. #else
  179324. #include <zlib.h>
  179325. #endif
  179326. }
  179327. namespace pnglibNamespace
  179328. {
  179329. using namespace zlibNamespace;
  179330. #if JUCE_INCLUDE_PNGLIB_CODE
  179331. #if _MSC_VER != 1310
  179332. using ::calloc; // (causes conflict in VS.NET 2003)
  179333. using ::malloc;
  179334. using ::free;
  179335. #endif
  179336. extern "C"
  179337. {
  179338. using ::abs;
  179339. #define PNG_INTERNAL
  179340. #define NO_DUMMY_DECL
  179341. #define PNG_SETJMP_NOT_SUPPORTED
  179342. /*** Start of inlined file: png.h ***/
  179343. /* png.h - header file for PNG reference library
  179344. *
  179345. * libpng version 1.2.21 - October 4, 2007
  179346. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  179347. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  179348. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  179349. *
  179350. * Authors and maintainers:
  179351. * libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat
  179352. * libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger
  179353. * libpng versions 0.97, January 1998, through 1.2.21 - October 4, 2007: Glenn
  179354. * See also "Contributing Authors", below.
  179355. *
  179356. * Note about libpng version numbers:
  179357. *
  179358. * Due to various miscommunications, unforeseen code incompatibilities
  179359. * and occasional factors outside the authors' control, version numbering
  179360. * on the library has not always been consistent and straightforward.
  179361. * The following table summarizes matters since version 0.89c, which was
  179362. * the first widely used release:
  179363. *
  179364. * source png.h png.h shared-lib
  179365. * version string int version
  179366. * ------- ------ ----- ----------
  179367. * 0.89c "1.0 beta 3" 0.89 89 1.0.89
  179368. * 0.90 "1.0 beta 4" 0.90 90 0.90 [should have been 2.0.90]
  179369. * 0.95 "1.0 beta 5" 0.95 95 0.95 [should have been 2.0.95]
  179370. * 0.96 "1.0 beta 6" 0.96 96 0.96 [should have been 2.0.96]
  179371. * 0.97b "1.00.97 beta 7" 1.00.97 97 1.0.1 [should have been 2.0.97]
  179372. * 0.97c 0.97 97 2.0.97
  179373. * 0.98 0.98 98 2.0.98
  179374. * 0.99 0.99 98 2.0.99
  179375. * 0.99a-m 0.99 99 2.0.99
  179376. * 1.00 1.00 100 2.1.0 [100 should be 10000]
  179377. * 1.0.0 (from here on, the 100 2.1.0 [100 should be 10000]
  179378. * 1.0.1 png.h string is 10001 2.1.0
  179379. * 1.0.1a-e identical to the 10002 from here on, the shared library
  179380. * 1.0.2 source version) 10002 is 2.V where V is the source code
  179381. * 1.0.2a-b 10003 version, except as noted.
  179382. * 1.0.3 10003
  179383. * 1.0.3a-d 10004
  179384. * 1.0.4 10004
  179385. * 1.0.4a-f 10005
  179386. * 1.0.5 (+ 2 patches) 10005
  179387. * 1.0.5a-d 10006
  179388. * 1.0.5e-r 10100 (not source compatible)
  179389. * 1.0.5s-v 10006 (not binary compatible)
  179390. * 1.0.6 (+ 3 patches) 10006 (still binary incompatible)
  179391. * 1.0.6d-f 10007 (still binary incompatible)
  179392. * 1.0.6g 10007
  179393. * 1.0.6h 10007 10.6h (testing xy.z so-numbering)
  179394. * 1.0.6i 10007 10.6i
  179395. * 1.0.6j 10007 2.1.0.6j (incompatible with 1.0.0)
  179396. * 1.0.7beta11-14 DLLNUM 10007 2.1.0.7beta11-14 (binary compatible)
  179397. * 1.0.7beta15-18 1 10007 2.1.0.7beta15-18 (binary compatible)
  179398. * 1.0.7rc1-2 1 10007 2.1.0.7rc1-2 (binary compatible)
  179399. * 1.0.7 1 10007 (still compatible)
  179400. * 1.0.8beta1-4 1 10008 2.1.0.8beta1-4
  179401. * 1.0.8rc1 1 10008 2.1.0.8rc1
  179402. * 1.0.8 1 10008 2.1.0.8
  179403. * 1.0.9beta1-6 1 10009 2.1.0.9beta1-6
  179404. * 1.0.9rc1 1 10009 2.1.0.9rc1
  179405. * 1.0.9beta7-10 1 10009 2.1.0.9beta7-10
  179406. * 1.0.9rc2 1 10009 2.1.0.9rc2
  179407. * 1.0.9 1 10009 2.1.0.9
  179408. * 1.0.10beta1 1 10010 2.1.0.10beta1
  179409. * 1.0.10rc1 1 10010 2.1.0.10rc1
  179410. * 1.0.10 1 10010 2.1.0.10
  179411. * 1.0.11beta1-3 1 10011 2.1.0.11beta1-3
  179412. * 1.0.11rc1 1 10011 2.1.0.11rc1
  179413. * 1.0.11 1 10011 2.1.0.11
  179414. * 1.0.12beta1-2 2 10012 2.1.0.12beta1-2
  179415. * 1.0.12rc1 2 10012 2.1.0.12rc1
  179416. * 1.0.12 2 10012 2.1.0.12
  179417. * 1.1.0a-f - 10100 2.1.1.0a-f (branch abandoned)
  179418. * 1.2.0beta1-2 2 10200 2.1.2.0beta1-2
  179419. * 1.2.0beta3-5 3 10200 3.1.2.0beta3-5
  179420. * 1.2.0rc1 3 10200 3.1.2.0rc1
  179421. * 1.2.0 3 10200 3.1.2.0
  179422. * 1.2.1beta1-4 3 10201 3.1.2.1beta1-4
  179423. * 1.2.1rc1-2 3 10201 3.1.2.1rc1-2
  179424. * 1.2.1 3 10201 3.1.2.1
  179425. * 1.2.2beta1-6 12 10202 12.so.0.1.2.2beta1-6
  179426. * 1.0.13beta1 10 10013 10.so.0.1.0.13beta1
  179427. * 1.0.13rc1 10 10013 10.so.0.1.0.13rc1
  179428. * 1.2.2rc1 12 10202 12.so.0.1.2.2rc1
  179429. * 1.0.13 10 10013 10.so.0.1.0.13
  179430. * 1.2.2 12 10202 12.so.0.1.2.2
  179431. * 1.2.3rc1-6 12 10203 12.so.0.1.2.3rc1-6
  179432. * 1.2.3 12 10203 12.so.0.1.2.3
  179433. * 1.2.4beta1-3 13 10204 12.so.0.1.2.4beta1-3
  179434. * 1.0.14rc1 13 10014 10.so.0.1.0.14rc1
  179435. * 1.2.4rc1 13 10204 12.so.0.1.2.4rc1
  179436. * 1.0.14 10 10014 10.so.0.1.0.14
  179437. * 1.2.4 13 10204 12.so.0.1.2.4
  179438. * 1.2.5beta1-2 13 10205 12.so.0.1.2.5beta1-2
  179439. * 1.0.15rc1-3 10 10015 10.so.0.1.0.15rc1-3
  179440. * 1.2.5rc1-3 13 10205 12.so.0.1.2.5rc1-3
  179441. * 1.0.15 10 10015 10.so.0.1.0.15
  179442. * 1.2.5 13 10205 12.so.0.1.2.5
  179443. * 1.2.6beta1-4 13 10206 12.so.0.1.2.6beta1-4
  179444. * 1.0.16 10 10016 10.so.0.1.0.16
  179445. * 1.2.6 13 10206 12.so.0.1.2.6
  179446. * 1.2.7beta1-2 13 10207 12.so.0.1.2.7beta1-2
  179447. * 1.0.17rc1 10 10017 10.so.0.1.0.17rc1
  179448. * 1.2.7rc1 13 10207 12.so.0.1.2.7rc1
  179449. * 1.0.17 10 10017 10.so.0.1.0.17
  179450. * 1.2.7 13 10207 12.so.0.1.2.7
  179451. * 1.2.8beta1-5 13 10208 12.so.0.1.2.8beta1-5
  179452. * 1.0.18rc1-5 10 10018 10.so.0.1.0.18rc1-5
  179453. * 1.2.8rc1-5 13 10208 12.so.0.1.2.8rc1-5
  179454. * 1.0.18 10 10018 10.so.0.1.0.18
  179455. * 1.2.8 13 10208 12.so.0.1.2.8
  179456. * 1.2.9beta1-3 13 10209 12.so.0.1.2.9beta1-3
  179457. * 1.2.9beta4-11 13 10209 12.so.0.9[.0]
  179458. * 1.2.9rc1 13 10209 12.so.0.9[.0]
  179459. * 1.2.9 13 10209 12.so.0.9[.0]
  179460. * 1.2.10beta1-8 13 10210 12.so.0.10[.0]
  179461. * 1.2.10rc1-3 13 10210 12.so.0.10[.0]
  179462. * 1.2.10 13 10210 12.so.0.10[.0]
  179463. * 1.2.11beta1-4 13 10211 12.so.0.11[.0]
  179464. * 1.0.19rc1-5 10 10019 10.so.0.19[.0]
  179465. * 1.2.11rc1-5 13 10211 12.so.0.11[.0]
  179466. * 1.0.19 10 10019 10.so.0.19[.0]
  179467. * 1.2.11 13 10211 12.so.0.11[.0]
  179468. * 1.0.20 10 10020 10.so.0.20[.0]
  179469. * 1.2.12 13 10212 12.so.0.12[.0]
  179470. * 1.2.13beta1 13 10213 12.so.0.13[.0]
  179471. * 1.0.21 10 10021 10.so.0.21[.0]
  179472. * 1.2.13 13 10213 12.so.0.13[.0]
  179473. * 1.2.14beta1-2 13 10214 12.so.0.14[.0]
  179474. * 1.0.22rc1 10 10022 10.so.0.22[.0]
  179475. * 1.2.14rc1 13 10214 12.so.0.14[.0]
  179476. * 1.0.22 10 10022 10.so.0.22[.0]
  179477. * 1.2.14 13 10214 12.so.0.14[.0]
  179478. * 1.2.15beta1-6 13 10215 12.so.0.15[.0]
  179479. * 1.0.23rc1-5 10 10023 10.so.0.23[.0]
  179480. * 1.2.15rc1-5 13 10215 12.so.0.15[.0]
  179481. * 1.0.23 10 10023 10.so.0.23[.0]
  179482. * 1.2.15 13 10215 12.so.0.15[.0]
  179483. * 1.2.16beta1-2 13 10216 12.so.0.16[.0]
  179484. * 1.2.16rc1 13 10216 12.so.0.16[.0]
  179485. * 1.0.24 10 10024 10.so.0.24[.0]
  179486. * 1.2.16 13 10216 12.so.0.16[.0]
  179487. * 1.2.17beta1-2 13 10217 12.so.0.17[.0]
  179488. * 1.0.25rc1 10 10025 10.so.0.25[.0]
  179489. * 1.2.17rc1-3 13 10217 12.so.0.17[.0]
  179490. * 1.0.25 10 10025 10.so.0.25[.0]
  179491. * 1.2.17 13 10217 12.so.0.17[.0]
  179492. * 1.0.26 10 10026 10.so.0.26[.0]
  179493. * 1.2.18 13 10218 12.so.0.18[.0]
  179494. * 1.2.19beta1-31 13 10219 12.so.0.19[.0]
  179495. * 1.0.27rc1-6 10 10027 10.so.0.27[.0]
  179496. * 1.2.19rc1-6 13 10219 12.so.0.19[.0]
  179497. * 1.0.27 10 10027 10.so.0.27[.0]
  179498. * 1.2.19 13 10219 12.so.0.19[.0]
  179499. * 1.2.20beta01-04 13 10220 12.so.0.20[.0]
  179500. * 1.0.28rc1-6 10 10028 10.so.0.28[.0]
  179501. * 1.2.20rc1-6 13 10220 12.so.0.20[.0]
  179502. * 1.0.28 10 10028 10.so.0.28[.0]
  179503. * 1.2.20 13 10220 12.so.0.20[.0]
  179504. * 1.2.21beta1-2 13 10221 12.so.0.21[.0]
  179505. * 1.2.21rc1-3 13 10221 12.so.0.21[.0]
  179506. * 1.0.29 10 10029 10.so.0.29[.0]
  179507. * 1.2.21 13 10221 12.so.0.21[.0]
  179508. *
  179509. * Henceforth the source version will match the shared-library major
  179510. * and minor numbers; the shared-library major version number will be
  179511. * used for changes in backward compatibility, as it is intended. The
  179512. * PNG_LIBPNG_VER macro, which is not used within libpng but is available
  179513. * for applications, is an unsigned integer of the form xyyzz corresponding
  179514. * to the source version x.y.z (leading zeros in y and z). Beta versions
  179515. * were given the previous public release number plus a letter, until
  179516. * version 1.0.6j; from then on they were given the upcoming public
  179517. * release number plus "betaNN" or "rcN".
  179518. *
  179519. * Binary incompatibility exists only when applications make direct access
  179520. * to the info_ptr or png_ptr members through png.h, and the compiled
  179521. * application is loaded with a different version of the library.
  179522. *
  179523. * DLLNUM will change each time there are forward or backward changes
  179524. * in binary compatibility (e.g., when a new feature is added).
  179525. *
  179526. * See libpng.txt or libpng.3 for more information. The PNG specification
  179527. * is available as a W3C Recommendation and as an ISO Specification,
  179528. * <http://www.w3.org/TR/2003/REC-PNG-20031110/
  179529. */
  179530. /*
  179531. * COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
  179532. *
  179533. * If you modify libpng you may insert additional notices immediately following
  179534. * this sentence.
  179535. *
  179536. * libpng versions 1.2.6, August 15, 2004, through 1.2.21, October 4, 2007, are
  179537. * Copyright (c) 2004, 2006-2007 Glenn Randers-Pehrson, and are
  179538. * distributed according to the same disclaimer and license as libpng-1.2.5
  179539. * with the following individual added to the list of Contributing Authors:
  179540. *
  179541. * Cosmin Truta
  179542. *
  179543. * libpng versions 1.0.7, July 1, 2000, through 1.2.5, October 3, 2002, are
  179544. * Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
  179545. * distributed according to the same disclaimer and license as libpng-1.0.6
  179546. * with the following individuals added to the list of Contributing Authors:
  179547. *
  179548. * Simon-Pierre Cadieux
  179549. * Eric S. Raymond
  179550. * Gilles Vollant
  179551. *
  179552. * and with the following additions to the disclaimer:
  179553. *
  179554. * There is no warranty against interference with your enjoyment of the
  179555. * library or against infringement. There is no warranty that our
  179556. * efforts or the library will fulfill any of your particular purposes
  179557. * or needs. This library is provided with all faults, and the entire
  179558. * risk of satisfactory quality, performance, accuracy, and effort is with
  179559. * the user.
  179560. *
  179561. * libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
  179562. * Copyright (c) 1998, 1999, 2000 Glenn Randers-Pehrson, and are
  179563. * distributed according to the same disclaimer and license as libpng-0.96,
  179564. * with the following individuals added to the list of Contributing Authors:
  179565. *
  179566. * Tom Lane
  179567. * Glenn Randers-Pehrson
  179568. * Willem van Schaik
  179569. *
  179570. * libpng versions 0.89, June 1996, through 0.96, May 1997, are
  179571. * Copyright (c) 1996, 1997 Andreas Dilger
  179572. * Distributed according to the same disclaimer and license as libpng-0.88,
  179573. * with the following individuals added to the list of Contributing Authors:
  179574. *
  179575. * John Bowler
  179576. * Kevin Bracey
  179577. * Sam Bushell
  179578. * Magnus Holmgren
  179579. * Greg Roelofs
  179580. * Tom Tanner
  179581. *
  179582. * libpng versions 0.5, May 1995, through 0.88, January 1996, are
  179583. * Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
  179584. *
  179585. * For the purposes of this copyright and license, "Contributing Authors"
  179586. * is defined as the following set of individuals:
  179587. *
  179588. * Andreas Dilger
  179589. * Dave Martindale
  179590. * Guy Eric Schalnat
  179591. * Paul Schmidt
  179592. * Tim Wegner
  179593. *
  179594. * The PNG Reference Library is supplied "AS IS". The Contributing Authors
  179595. * and Group 42, Inc. disclaim all warranties, expressed or implied,
  179596. * including, without limitation, the warranties of merchantability and of
  179597. * fitness for any purpose. The Contributing Authors and Group 42, Inc.
  179598. * assume no liability for direct, indirect, incidental, special, exemplary,
  179599. * or consequential damages, which may result from the use of the PNG
  179600. * Reference Library, even if advised of the possibility of such damage.
  179601. *
  179602. * Permission is hereby granted to use, copy, modify, and distribute this
  179603. * source code, or portions hereof, for any purpose, without fee, subject
  179604. * to the following restrictions:
  179605. *
  179606. * 1. The origin of this source code must not be misrepresented.
  179607. *
  179608. * 2. Altered versions must be plainly marked as such and
  179609. * must not be misrepresented as being the original source.
  179610. *
  179611. * 3. This Copyright notice may not be removed or altered from
  179612. * any source or altered source distribution.
  179613. *
  179614. * The Contributing Authors and Group 42, Inc. specifically permit, without
  179615. * fee, and encourage the use of this source code as a component to
  179616. * supporting the PNG file format in commercial products. If you use this
  179617. * source code in a product, acknowledgment is not required but would be
  179618. * appreciated.
  179619. */
  179620. /*
  179621. * A "png_get_copyright" function is available, for convenient use in "about"
  179622. * boxes and the like:
  179623. *
  179624. * printf("%s",png_get_copyright(NULL));
  179625. *
  179626. * Also, the PNG logo (in PNG format, of course) is supplied in the
  179627. * files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
  179628. */
  179629. /*
  179630. * Libpng is OSI Certified Open Source Software. OSI Certified is a
  179631. * certification mark of the Open Source Initiative.
  179632. */
  179633. /*
  179634. * The contributing authors would like to thank all those who helped
  179635. * with testing, bug fixes, and patience. This wouldn't have been
  179636. * possible without all of you.
  179637. *
  179638. * Thanks to Frank J. T. Wojcik for helping with the documentation.
  179639. */
  179640. /*
  179641. * Y2K compliance in libpng:
  179642. * =========================
  179643. *
  179644. * October 4, 2007
  179645. *
  179646. * Since the PNG Development group is an ad-hoc body, we can't make
  179647. * an official declaration.
  179648. *
  179649. * This is your unofficial assurance that libpng from version 0.71 and
  179650. * upward through 1.2.21 are Y2K compliant. It is my belief that earlier
  179651. * versions were also Y2K compliant.
  179652. *
  179653. * Libpng only has three year fields. One is a 2-byte unsigned integer
  179654. * that will hold years up to 65535. The other two hold the date in text
  179655. * format, and will hold years up to 9999.
  179656. *
  179657. * The integer is
  179658. * "png_uint_16 year" in png_time_struct.
  179659. *
  179660. * The strings are
  179661. * "png_charp time_buffer" in png_struct and
  179662. * "near_time_buffer", which is a local character string in png.c.
  179663. *
  179664. * There are seven time-related functions:
  179665. * png.c: png_convert_to_rfc_1123() in png.c
  179666. * (formerly png_convert_to_rfc_1152() in error)
  179667. * png_convert_from_struct_tm() in pngwrite.c, called in pngwrite.c
  179668. * png_convert_from_time_t() in pngwrite.c
  179669. * png_get_tIME() in pngget.c
  179670. * png_handle_tIME() in pngrutil.c, called in pngread.c
  179671. * png_set_tIME() in pngset.c
  179672. * png_write_tIME() in pngwutil.c, called in pngwrite.c
  179673. *
  179674. * All handle dates properly in a Y2K environment. The
  179675. * png_convert_from_time_t() function calls gmtime() to convert from system
  179676. * clock time, which returns (year - 1900), which we properly convert to
  179677. * the full 4-digit year. There is a possibility that applications using
  179678. * libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
  179679. * function, or that they are incorrectly passing only a 2-digit year
  179680. * instead of "year - 1900" into the png_convert_from_struct_tm() function,
  179681. * but this is not under our control. The libpng documentation has always
  179682. * stated that it works with 4-digit years, and the APIs have been
  179683. * documented as such.
  179684. *
  179685. * The tIME chunk itself is also Y2K compliant. It uses a 2-byte unsigned
  179686. * integer to hold the year, and can hold years as large as 65535.
  179687. *
  179688. * zlib, upon which libpng depends, is also Y2K compliant. It contains
  179689. * no date-related code.
  179690. *
  179691. * Glenn Randers-Pehrson
  179692. * libpng maintainer
  179693. * PNG Development Group
  179694. */
  179695. #ifndef PNG_H
  179696. #define PNG_H
  179697. /* This is not the place to learn how to use libpng. The file libpng.txt
  179698. * describes how to use libpng, and the file example.c summarizes it
  179699. * with some code on which to build. This file is useful for looking
  179700. * at the actual function definitions and structure components.
  179701. */
  179702. /* Version information for png.h - this should match the version in png.c */
  179703. #define PNG_LIBPNG_VER_STRING "1.2.21"
  179704. #define PNG_HEADER_VERSION_STRING \
  179705. " libpng version 1.2.21 - October 4, 2007\n"
  179706. #define PNG_LIBPNG_VER_SONUM 0
  179707. #define PNG_LIBPNG_VER_DLLNUM 13
  179708. /* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
  179709. #define PNG_LIBPNG_VER_MAJOR 1
  179710. #define PNG_LIBPNG_VER_MINOR 2
  179711. #define PNG_LIBPNG_VER_RELEASE 21
  179712. /* This should match the numeric part of the final component of
  179713. * PNG_LIBPNG_VER_STRING, omitting any leading zero: */
  179714. #define PNG_LIBPNG_VER_BUILD 0
  179715. /* Release Status */
  179716. #define PNG_LIBPNG_BUILD_ALPHA 1
  179717. #define PNG_LIBPNG_BUILD_BETA 2
  179718. #define PNG_LIBPNG_BUILD_RC 3
  179719. #define PNG_LIBPNG_BUILD_STABLE 4
  179720. #define PNG_LIBPNG_BUILD_RELEASE_STATUS_MASK 7
  179721. /* Release-Specific Flags */
  179722. #define PNG_LIBPNG_BUILD_PATCH 8 /* Can be OR'ed with
  179723. PNG_LIBPNG_BUILD_STABLE only */
  179724. #define PNG_LIBPNG_BUILD_PRIVATE 16 /* Cannot be OR'ed with
  179725. PNG_LIBPNG_BUILD_SPECIAL */
  179726. #define PNG_LIBPNG_BUILD_SPECIAL 32 /* Cannot be OR'ed with
  179727. PNG_LIBPNG_BUILD_PRIVATE */
  179728. #define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_STABLE
  179729. /* Careful here. At one time, Guy wanted to use 082, but that would be octal.
  179730. * We must not include leading zeros.
  179731. * Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only
  179732. * version 1.0.0 was mis-numbered 100 instead of 10000). From
  179733. * version 1.0.1 it's xxyyzz, where x=major, y=minor, z=release */
  179734. #define PNG_LIBPNG_VER 10221 /* 1.2.21 */
  179735. #ifndef PNG_VERSION_INFO_ONLY
  179736. /* include the compression library's header */
  179737. #endif
  179738. /* include all user configurable info, including optional assembler routines */
  179739. /*** Start of inlined file: pngconf.h ***/
  179740. /* pngconf.h - machine configurable file for libpng
  179741. *
  179742. * libpng version 1.2.21 - October 4, 2007
  179743. * For conditions of distribution and use, see copyright notice in png.h
  179744. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  179745. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  179746. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  179747. */
  179748. /* Any machine specific code is near the front of this file, so if you
  179749. * are configuring libpng for a machine, you may want to read the section
  179750. * starting here down to where it starts to typedef png_color, png_text,
  179751. * and png_info.
  179752. */
  179753. #ifndef PNGCONF_H
  179754. #define PNGCONF_H
  179755. #define PNG_1_2_X
  179756. // These are some Juce config settings that should remove any unnecessary code bloat..
  179757. #define PNG_NO_STDIO 1
  179758. #define PNG_DEBUG 0
  179759. #define PNG_NO_WARNINGS 1
  179760. #define PNG_NO_ERROR_TEXT 1
  179761. #define PNG_NO_ERROR_NUMBERS 1
  179762. #define PNG_NO_USER_MEM 1
  179763. #define PNG_NO_READ_iCCP 1
  179764. #define PNG_NO_READ_UNKNOWN_CHUNKS 1
  179765. #define PNG_NO_READ_USER_CHUNKS 1
  179766. #define PNG_NO_READ_iTXt 1
  179767. #define PNG_NO_READ_sCAL 1
  179768. #define PNG_NO_READ_sPLT 1
  179769. #define png_error(a, b) png_err(a)
  179770. #define png_warning(a, b)
  179771. #define png_chunk_error(a, b) png_err(a)
  179772. #define png_chunk_warning(a, b)
  179773. /*
  179774. * PNG_USER_CONFIG has to be defined on the compiler command line. This
  179775. * includes the resource compiler for Windows DLL configurations.
  179776. */
  179777. #ifdef PNG_USER_CONFIG
  179778. # ifndef PNG_USER_PRIVATEBUILD
  179779. # define PNG_USER_PRIVATEBUILD
  179780. # endif
  179781. #include "pngusr.h"
  179782. #endif
  179783. /* PNG_CONFIGURE_LIBPNG is set by the "configure" script. */
  179784. #ifdef PNG_CONFIGURE_LIBPNG
  179785. #ifdef HAVE_CONFIG_H
  179786. #include "config.h"
  179787. #endif
  179788. #endif
  179789. /*
  179790. * Added at libpng-1.2.8
  179791. *
  179792. * If you create a private DLL you need to define in "pngusr.h" the followings:
  179793. * #define PNG_USER_PRIVATEBUILD <Describes by whom and why this version of
  179794. * the DLL was built>
  179795. * e.g. #define PNG_USER_PRIVATEBUILD "Build by MyCompany for xyz reasons."
  179796. * #define PNG_USER_DLLFNAME_POSTFIX <two-letter postfix that serve to
  179797. * distinguish your DLL from those of the official release. These
  179798. * correspond to the trailing letters that come after the version
  179799. * number and must match your private DLL name>
  179800. * e.g. // private DLL "libpng13gx.dll"
  179801. * #define PNG_USER_DLLFNAME_POSTFIX "gx"
  179802. *
  179803. * The following macros are also at your disposal if you want to complete the
  179804. * DLL VERSIONINFO structure.
  179805. * - PNG_USER_VERSIONINFO_COMMENTS
  179806. * - PNG_USER_VERSIONINFO_COMPANYNAME
  179807. * - PNG_USER_VERSIONINFO_LEGALTRADEMARKS
  179808. */
  179809. #ifdef __STDC__
  179810. #ifdef SPECIALBUILD
  179811. # pragma message("PNG_LIBPNG_SPECIALBUILD (and deprecated SPECIALBUILD)\
  179812. are now LIBPNG reserved macros. Use PNG_USER_PRIVATEBUILD instead.")
  179813. #endif
  179814. #ifdef PRIVATEBUILD
  179815. # pragma message("PRIVATEBUILD is deprecated.\
  179816. Use PNG_USER_PRIVATEBUILD instead.")
  179817. # define PNG_USER_PRIVATEBUILD PRIVATEBUILD
  179818. #endif
  179819. #endif /* __STDC__ */
  179820. #ifndef PNG_VERSION_INFO_ONLY
  179821. /* End of material added to libpng-1.2.8 */
  179822. /* Added at libpng-1.2.19, removed at libpng-1.2.20 because it caused trouble
  179823. Restored at libpng-1.2.21 */
  179824. # define PNG_WARN_UNINITIALIZED_ROW 1
  179825. /* End of material added at libpng-1.2.19/1.2.21 */
  179826. /* This is the size of the compression buffer, and thus the size of
  179827. * an IDAT chunk. Make this whatever size you feel is best for your
  179828. * machine. One of these will be allocated per png_struct. When this
  179829. * is full, it writes the data to the disk, and does some other
  179830. * calculations. Making this an extremely small size will slow
  179831. * the library down, but you may want to experiment to determine
  179832. * where it becomes significant, if you are concerned with memory
  179833. * usage. Note that zlib allocates at least 32Kb also. For readers,
  179834. * this describes the size of the buffer available to read the data in.
  179835. * Unless this gets smaller than the size of a row (compressed),
  179836. * it should not make much difference how big this is.
  179837. */
  179838. #ifndef PNG_ZBUF_SIZE
  179839. # define PNG_ZBUF_SIZE 8192
  179840. #endif
  179841. /* Enable if you want a write-only libpng */
  179842. #ifndef PNG_NO_READ_SUPPORTED
  179843. # define PNG_READ_SUPPORTED
  179844. #endif
  179845. /* Enable if you want a read-only libpng */
  179846. #ifndef PNG_NO_WRITE_SUPPORTED
  179847. # define PNG_WRITE_SUPPORTED
  179848. #endif
  179849. /* Enabled by default in 1.2.0. You can disable this if you don't need to
  179850. support PNGs that are embedded in MNG datastreams */
  179851. #if !defined(PNG_1_0_X) && !defined(PNG_NO_MNG_FEATURES)
  179852. # ifndef PNG_MNG_FEATURES_SUPPORTED
  179853. # define PNG_MNG_FEATURES_SUPPORTED
  179854. # endif
  179855. #endif
  179856. #ifndef PNG_NO_FLOATING_POINT_SUPPORTED
  179857. # ifndef PNG_FLOATING_POINT_SUPPORTED
  179858. # define PNG_FLOATING_POINT_SUPPORTED
  179859. # endif
  179860. #endif
  179861. /* If you are running on a machine where you cannot allocate more
  179862. * than 64K of memory at once, uncomment this. While libpng will not
  179863. * normally need that much memory in a chunk (unless you load up a very
  179864. * large file), zlib needs to know how big of a chunk it can use, and
  179865. * libpng thus makes sure to check any memory allocation to verify it
  179866. * will fit into memory.
  179867. #define PNG_MAX_MALLOC_64K
  179868. */
  179869. #if defined(MAXSEG_64K) && !defined(PNG_MAX_MALLOC_64K)
  179870. # define PNG_MAX_MALLOC_64K
  179871. #endif
  179872. /* Special munging to support doing things the 'cygwin' way:
  179873. * 'Normal' png-on-win32 defines/defaults:
  179874. * PNG_BUILD_DLL -- building dll
  179875. * PNG_USE_DLL -- building an application, linking to dll
  179876. * (no define) -- building static library, or building an
  179877. * application and linking to the static lib
  179878. * 'Cygwin' defines/defaults:
  179879. * PNG_BUILD_DLL -- (ignored) building the dll
  179880. * (no define) -- (ignored) building an application, linking to the dll
  179881. * PNG_STATIC -- (ignored) building the static lib, or building an
  179882. * application that links to the static lib.
  179883. * ALL_STATIC -- (ignored) building various static libs, or building an
  179884. * application that links to the static libs.
  179885. * Thus,
  179886. * a cygwin user should define either PNG_BUILD_DLL or PNG_STATIC, and
  179887. * this bit of #ifdefs will define the 'correct' config variables based on
  179888. * that. If a cygwin user *wants* to define 'PNG_USE_DLL' that's okay, but
  179889. * unnecessary.
  179890. *
  179891. * Also, the precedence order is:
  179892. * ALL_STATIC (since we can't #undef something outside our namespace)
  179893. * PNG_BUILD_DLL
  179894. * PNG_STATIC
  179895. * (nothing) == PNG_USE_DLL
  179896. *
  179897. * CYGWIN (2002-01-20): The preceding is now obsolete. With the advent
  179898. * of auto-import in binutils, we no longer need to worry about
  179899. * __declspec(dllexport) / __declspec(dllimport) and friends. Therefore,
  179900. * we don't need to worry about PNG_STATIC or ALL_STATIC when it comes
  179901. * to __declspec() stuff. However, we DO need to worry about
  179902. * PNG_BUILD_DLL and PNG_STATIC because those change some defaults
  179903. * such as CONSOLE_IO and whether GLOBAL_ARRAYS are allowed.
  179904. */
  179905. #if defined(__CYGWIN__)
  179906. # if defined(ALL_STATIC)
  179907. # if defined(PNG_BUILD_DLL)
  179908. # undef PNG_BUILD_DLL
  179909. # endif
  179910. # if defined(PNG_USE_DLL)
  179911. # undef PNG_USE_DLL
  179912. # endif
  179913. # if defined(PNG_DLL)
  179914. # undef PNG_DLL
  179915. # endif
  179916. # if !defined(PNG_STATIC)
  179917. # define PNG_STATIC
  179918. # endif
  179919. # else
  179920. # if defined (PNG_BUILD_DLL)
  179921. # if defined(PNG_STATIC)
  179922. # undef PNG_STATIC
  179923. # endif
  179924. # if defined(PNG_USE_DLL)
  179925. # undef PNG_USE_DLL
  179926. # endif
  179927. # if !defined(PNG_DLL)
  179928. # define PNG_DLL
  179929. # endif
  179930. # else
  179931. # if defined(PNG_STATIC)
  179932. # if defined(PNG_USE_DLL)
  179933. # undef PNG_USE_DLL
  179934. # endif
  179935. # if defined(PNG_DLL)
  179936. # undef PNG_DLL
  179937. # endif
  179938. # else
  179939. # if !defined(PNG_USE_DLL)
  179940. # define PNG_USE_DLL
  179941. # endif
  179942. # if !defined(PNG_DLL)
  179943. # define PNG_DLL
  179944. # endif
  179945. # endif
  179946. # endif
  179947. # endif
  179948. #endif
  179949. /* This protects us against compilers that run on a windowing system
  179950. * and thus don't have or would rather us not use the stdio types:
  179951. * stdin, stdout, and stderr. The only one currently used is stderr
  179952. * in png_error() and png_warning(). #defining PNG_NO_CONSOLE_IO will
  179953. * prevent these from being compiled and used. #defining PNG_NO_STDIO
  179954. * will also prevent these, plus will prevent the entire set of stdio
  179955. * macros and functions (FILE *, printf, etc.) from being compiled and used,
  179956. * unless (PNG_DEBUG > 0) has been #defined.
  179957. *
  179958. * #define PNG_NO_CONSOLE_IO
  179959. * #define PNG_NO_STDIO
  179960. */
  179961. #if defined(_WIN32_WCE)
  179962. # include <windows.h>
  179963. /* Console I/O functions are not supported on WindowsCE */
  179964. # define PNG_NO_CONSOLE_IO
  179965. # ifdef PNG_DEBUG
  179966. # undef PNG_DEBUG
  179967. # endif
  179968. #endif
  179969. #ifdef PNG_BUILD_DLL
  179970. # ifndef PNG_CONSOLE_IO_SUPPORTED
  179971. # ifndef PNG_NO_CONSOLE_IO
  179972. # define PNG_NO_CONSOLE_IO
  179973. # endif
  179974. # endif
  179975. #endif
  179976. # ifdef PNG_NO_STDIO
  179977. # ifndef PNG_NO_CONSOLE_IO
  179978. # define PNG_NO_CONSOLE_IO
  179979. # endif
  179980. # ifdef PNG_DEBUG
  179981. # if (PNG_DEBUG > 0)
  179982. # include <stdio.h>
  179983. # endif
  179984. # endif
  179985. # else
  179986. # if !defined(_WIN32_WCE)
  179987. /* "stdio.h" functions are not supported on WindowsCE */
  179988. # include <stdio.h>
  179989. # endif
  179990. # endif
  179991. /* This macro protects us against machines that don't have function
  179992. * prototypes (ie K&R style headers). If your compiler does not handle
  179993. * function prototypes, define this macro and use the included ansi2knr.
  179994. * I've always been able to use _NO_PROTO as the indicator, but you may
  179995. * need to drag the empty declaration out in front of here, or change the
  179996. * ifdef to suit your own needs.
  179997. */
  179998. #ifndef PNGARG
  179999. #ifdef OF /* zlib prototype munger */
  180000. # define PNGARG(arglist) OF(arglist)
  180001. #else
  180002. #ifdef _NO_PROTO
  180003. # define PNGARG(arglist) ()
  180004. # ifndef PNG_TYPECAST_NULL
  180005. # define PNG_TYPECAST_NULL
  180006. # endif
  180007. #else
  180008. # define PNGARG(arglist) arglist
  180009. #endif /* _NO_PROTO */
  180010. #endif /* OF */
  180011. #endif /* PNGARG */
  180012. /* Try to determine if we are compiling on a Mac. Note that testing for
  180013. * just __MWERKS__ is not good enough, because the Codewarrior is now used
  180014. * on non-Mac platforms.
  180015. */
  180016. #ifndef MACOS
  180017. # if (defined(__MWERKS__) && defined(macintosh)) || defined(applec) || \
  180018. defined(THINK_C) || defined(__SC__) || defined(TARGET_OS_MAC)
  180019. # define MACOS
  180020. # endif
  180021. #endif
  180022. /* enough people need this for various reasons to include it here */
  180023. #if !defined(MACOS) && !defined(RISCOS) && !defined(_WIN32_WCE)
  180024. # include <sys/types.h>
  180025. #endif
  180026. #if !defined(PNG_SETJMP_NOT_SUPPORTED) && !defined(PNG_NO_SETJMP_SUPPORTED)
  180027. # define PNG_SETJMP_SUPPORTED
  180028. #endif
  180029. #ifdef PNG_SETJMP_SUPPORTED
  180030. /* This is an attempt to force a single setjmp behaviour on Linux. If
  180031. * the X config stuff didn't define _BSD_SOURCE we wouldn't need this.
  180032. */
  180033. # ifdef __linux__
  180034. # ifdef _BSD_SOURCE
  180035. # define PNG_SAVE_BSD_SOURCE
  180036. # undef _BSD_SOURCE
  180037. # endif
  180038. # ifdef _SETJMP_H
  180039. /* If you encounter a compiler error here, see the explanation
  180040. * near the end of INSTALL.
  180041. */
  180042. __png.h__ already includes setjmp.h;
  180043. __dont__ include it again.;
  180044. # endif
  180045. # endif /* __linux__ */
  180046. /* include setjmp.h for error handling */
  180047. # include <setjmp.h>
  180048. # ifdef __linux__
  180049. # ifdef PNG_SAVE_BSD_SOURCE
  180050. # define _BSD_SOURCE
  180051. # undef PNG_SAVE_BSD_SOURCE
  180052. # endif
  180053. # endif /* __linux__ */
  180054. #endif /* PNG_SETJMP_SUPPORTED */
  180055. #ifdef BSD
  180056. #if ! JUCE_MAC
  180057. # include <strings.h>
  180058. #endif
  180059. #else
  180060. # include <string.h>
  180061. #endif
  180062. /* Other defines for things like memory and the like can go here. */
  180063. #ifdef PNG_INTERNAL
  180064. #include <stdlib.h>
  180065. /* The functions exported by PNG_EXTERN are PNG_INTERNAL functions, which
  180066. * aren't usually used outside the library (as far as I know), so it is
  180067. * debatable if they should be exported at all. In the future, when it is
  180068. * possible to have run-time registry of chunk-handling functions, some of
  180069. * these will be made available again.
  180070. #define PNG_EXTERN extern
  180071. */
  180072. #define PNG_EXTERN
  180073. /* Other defines specific to compilers can go here. Try to keep
  180074. * them inside an appropriate ifdef/endif pair for portability.
  180075. */
  180076. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  180077. # if defined(MACOS)
  180078. /* We need to check that <math.h> hasn't already been included earlier
  180079. * as it seems it doesn't agree with <fp.h>, yet we should really use
  180080. * <fp.h> if possible.
  180081. */
  180082. # if !defined(__MATH_H__) && !defined(__MATH_H) && !defined(__cmath__)
  180083. # include <fp.h>
  180084. # endif
  180085. # else
  180086. # include <math.h>
  180087. # endif
  180088. # if defined(_AMIGA) && defined(__SASC) && defined(_M68881)
  180089. /* Amiga SAS/C: We must include builtin FPU functions when compiling using
  180090. * MATH=68881
  180091. */
  180092. # include <m68881.h>
  180093. # endif
  180094. #endif
  180095. /* Codewarrior on NT has linking problems without this. */
  180096. #if (defined(__MWERKS__) && defined(WIN32)) || defined(__STDC__)
  180097. # define PNG_ALWAYS_EXTERN
  180098. #endif
  180099. /* This provides the non-ANSI (far) memory allocation routines. */
  180100. #if defined(__TURBOC__) && defined(__MSDOS__)
  180101. # include <mem.h>
  180102. # include <alloc.h>
  180103. #endif
  180104. /* I have no idea why is this necessary... */
  180105. #if defined(_MSC_VER) && (defined(WIN32) || defined(_Windows) || \
  180106. defined(_WINDOWS) || defined(_WIN32) || defined(__WIN32__))
  180107. # include <malloc.h>
  180108. #endif
  180109. /* This controls how fine the dithering gets. As this allocates
  180110. * a largish chunk of memory (32K), those who are not as concerned
  180111. * with dithering quality can decrease some or all of these.
  180112. */
  180113. #ifndef PNG_DITHER_RED_BITS
  180114. # define PNG_DITHER_RED_BITS 5
  180115. #endif
  180116. #ifndef PNG_DITHER_GREEN_BITS
  180117. # define PNG_DITHER_GREEN_BITS 5
  180118. #endif
  180119. #ifndef PNG_DITHER_BLUE_BITS
  180120. # define PNG_DITHER_BLUE_BITS 5
  180121. #endif
  180122. /* This controls how fine the gamma correction becomes when you
  180123. * are only interested in 8 bits anyway. Increasing this value
  180124. * results in more memory being used, and more pow() functions
  180125. * being called to fill in the gamma tables. Don't set this value
  180126. * less then 8, and even that may not work (I haven't tested it).
  180127. */
  180128. #ifndef PNG_MAX_GAMMA_8
  180129. # define PNG_MAX_GAMMA_8 11
  180130. #endif
  180131. /* This controls how much a difference in gamma we can tolerate before
  180132. * we actually start doing gamma conversion.
  180133. */
  180134. #ifndef PNG_GAMMA_THRESHOLD
  180135. # define PNG_GAMMA_THRESHOLD 0.05
  180136. #endif
  180137. #endif /* PNG_INTERNAL */
  180138. /* The following uses const char * instead of char * for error
  180139. * and warning message functions, so some compilers won't complain.
  180140. * If you do not want to use const, define PNG_NO_CONST here.
  180141. */
  180142. #ifndef PNG_NO_CONST
  180143. # define PNG_CONST const
  180144. #else
  180145. # define PNG_CONST
  180146. #endif
  180147. /* The following defines give you the ability to remove code from the
  180148. * library that you will not be using. I wish I could figure out how to
  180149. * automate this, but I can't do that without making it seriously hard
  180150. * on the users. So if you are not using an ability, change the #define
  180151. * to and #undef, and that part of the library will not be compiled. If
  180152. * your linker can't find a function, you may want to make sure the
  180153. * ability is defined here. Some of these depend upon some others being
  180154. * defined. I haven't figured out all the interactions here, so you may
  180155. * have to experiment awhile to get everything to compile. If you are
  180156. * creating or using a shared library, you probably shouldn't touch this,
  180157. * as it will affect the size of the structures, and this will cause bad
  180158. * things to happen if the library and/or application ever change.
  180159. */
  180160. /* Any features you will not be using can be undef'ed here */
  180161. /* GR-P, 0.96a: Set "*TRANSFORMS_SUPPORTED as default but allow user
  180162. * to turn it off with "*TRANSFORMS_NOT_SUPPORTED" or *PNG_NO_*_TRANSFORMS
  180163. * on the compile line, then pick and choose which ones to define without
  180164. * having to edit this file. It is safe to use the *TRANSFORMS_NOT_SUPPORTED
  180165. * if you only want to have a png-compliant reader/writer but don't need
  180166. * any of the extra transformations. This saves about 80 kbytes in a
  180167. * typical installation of the library. (PNG_NO_* form added in version
  180168. * 1.0.1c, for consistency)
  180169. */
  180170. /* The size of the png_text structure changed in libpng-1.0.6 when
  180171. * iTXt support was added. iTXt support was turned off by default through
  180172. * libpng-1.2.x, to support old apps that malloc the png_text structure
  180173. * instead of calling png_set_text() and letting libpng malloc it. It
  180174. * was turned on by default in libpng-1.3.0.
  180175. */
  180176. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  180177. # ifndef PNG_NO_iTXt_SUPPORTED
  180178. # define PNG_NO_iTXt_SUPPORTED
  180179. # endif
  180180. # ifndef PNG_NO_READ_iTXt
  180181. # define PNG_NO_READ_iTXt
  180182. # endif
  180183. # ifndef PNG_NO_WRITE_iTXt
  180184. # define PNG_NO_WRITE_iTXt
  180185. # endif
  180186. #endif
  180187. #if !defined(PNG_NO_iTXt_SUPPORTED)
  180188. # if !defined(PNG_READ_iTXt_SUPPORTED) && !defined(PNG_NO_READ_iTXt)
  180189. # define PNG_READ_iTXt
  180190. # endif
  180191. # if !defined(PNG_WRITE_iTXt_SUPPORTED) && !defined(PNG_NO_WRITE_iTXt)
  180192. # define PNG_WRITE_iTXt
  180193. # endif
  180194. #endif
  180195. /* The following support, added after version 1.0.0, can be turned off here en
  180196. * masse by defining PNG_LEGACY_SUPPORTED in case you need binary compatibility
  180197. * with old applications that require the length of png_struct and png_info
  180198. * to remain unchanged.
  180199. */
  180200. #ifdef PNG_LEGACY_SUPPORTED
  180201. # define PNG_NO_FREE_ME
  180202. # define PNG_NO_READ_UNKNOWN_CHUNKS
  180203. # define PNG_NO_WRITE_UNKNOWN_CHUNKS
  180204. # define PNG_NO_READ_USER_CHUNKS
  180205. # define PNG_NO_READ_iCCP
  180206. # define PNG_NO_WRITE_iCCP
  180207. # define PNG_NO_READ_iTXt
  180208. # define PNG_NO_WRITE_iTXt
  180209. # define PNG_NO_READ_sCAL
  180210. # define PNG_NO_WRITE_sCAL
  180211. # define PNG_NO_READ_sPLT
  180212. # define PNG_NO_WRITE_sPLT
  180213. # define PNG_NO_INFO_IMAGE
  180214. # define PNG_NO_READ_RGB_TO_GRAY
  180215. # define PNG_NO_READ_USER_TRANSFORM
  180216. # define PNG_NO_WRITE_USER_TRANSFORM
  180217. # define PNG_NO_USER_MEM
  180218. # define PNG_NO_READ_EMPTY_PLTE
  180219. # define PNG_NO_MNG_FEATURES
  180220. # define PNG_NO_FIXED_POINT_SUPPORTED
  180221. #endif
  180222. /* Ignore attempt to turn off both floating and fixed point support */
  180223. #if !defined(PNG_FLOATING_POINT_SUPPORTED) || \
  180224. !defined(PNG_NO_FIXED_POINT_SUPPORTED)
  180225. # define PNG_FIXED_POINT_SUPPORTED
  180226. #endif
  180227. #ifndef PNG_NO_FREE_ME
  180228. # define PNG_FREE_ME_SUPPORTED
  180229. #endif
  180230. #if defined(PNG_READ_SUPPORTED)
  180231. #if !defined(PNG_READ_TRANSFORMS_NOT_SUPPORTED) && \
  180232. !defined(PNG_NO_READ_TRANSFORMS)
  180233. # define PNG_READ_TRANSFORMS_SUPPORTED
  180234. #endif
  180235. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  180236. # ifndef PNG_NO_READ_EXPAND
  180237. # define PNG_READ_EXPAND_SUPPORTED
  180238. # endif
  180239. # ifndef PNG_NO_READ_SHIFT
  180240. # define PNG_READ_SHIFT_SUPPORTED
  180241. # endif
  180242. # ifndef PNG_NO_READ_PACK
  180243. # define PNG_READ_PACK_SUPPORTED
  180244. # endif
  180245. # ifndef PNG_NO_READ_BGR
  180246. # define PNG_READ_BGR_SUPPORTED
  180247. # endif
  180248. # ifndef PNG_NO_READ_SWAP
  180249. # define PNG_READ_SWAP_SUPPORTED
  180250. # endif
  180251. # ifndef PNG_NO_READ_PACKSWAP
  180252. # define PNG_READ_PACKSWAP_SUPPORTED
  180253. # endif
  180254. # ifndef PNG_NO_READ_INVERT
  180255. # define PNG_READ_INVERT_SUPPORTED
  180256. # endif
  180257. # ifndef PNG_NO_READ_DITHER
  180258. # define PNG_READ_DITHER_SUPPORTED
  180259. # endif
  180260. # ifndef PNG_NO_READ_BACKGROUND
  180261. # define PNG_READ_BACKGROUND_SUPPORTED
  180262. # endif
  180263. # ifndef PNG_NO_READ_16_TO_8
  180264. # define PNG_READ_16_TO_8_SUPPORTED
  180265. # endif
  180266. # ifndef PNG_NO_READ_FILLER
  180267. # define PNG_READ_FILLER_SUPPORTED
  180268. # endif
  180269. # ifndef PNG_NO_READ_GAMMA
  180270. # define PNG_READ_GAMMA_SUPPORTED
  180271. # endif
  180272. # ifndef PNG_NO_READ_GRAY_TO_RGB
  180273. # define PNG_READ_GRAY_TO_RGB_SUPPORTED
  180274. # endif
  180275. # ifndef PNG_NO_READ_SWAP_ALPHA
  180276. # define PNG_READ_SWAP_ALPHA_SUPPORTED
  180277. # endif
  180278. # ifndef PNG_NO_READ_INVERT_ALPHA
  180279. # define PNG_READ_INVERT_ALPHA_SUPPORTED
  180280. # endif
  180281. # ifndef PNG_NO_READ_STRIP_ALPHA
  180282. # define PNG_READ_STRIP_ALPHA_SUPPORTED
  180283. # endif
  180284. # ifndef PNG_NO_READ_USER_TRANSFORM
  180285. # define PNG_READ_USER_TRANSFORM_SUPPORTED
  180286. # endif
  180287. # ifndef PNG_NO_READ_RGB_TO_GRAY
  180288. # define PNG_READ_RGB_TO_GRAY_SUPPORTED
  180289. # endif
  180290. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  180291. #if !defined(PNG_NO_PROGRESSIVE_READ) && \
  180292. !defined(PNG_PROGRESSIVE_READ_SUPPORTED) /* if you don't do progressive */
  180293. # define PNG_PROGRESSIVE_READ_SUPPORTED /* reading. This is not talking */
  180294. #endif /* about interlacing capability! You'll */
  180295. /* still have interlacing unless you change the following line: */
  180296. #define PNG_READ_INTERLACING_SUPPORTED /* required in PNG-compliant decoders */
  180297. #ifndef PNG_NO_READ_COMPOSITE_NODIV
  180298. # ifndef PNG_NO_READ_COMPOSITED_NODIV /* libpng-1.0.x misspelling */
  180299. # define PNG_READ_COMPOSITE_NODIV_SUPPORTED /* well tested on Intel, SGI */
  180300. # endif
  180301. #endif
  180302. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  180303. /* Deprecated, will be removed from version 2.0.0.
  180304. Use PNG_MNG_FEATURES_SUPPORTED instead. */
  180305. #ifndef PNG_NO_READ_EMPTY_PLTE
  180306. # define PNG_READ_EMPTY_PLTE_SUPPORTED
  180307. #endif
  180308. #endif
  180309. #endif /* PNG_READ_SUPPORTED */
  180310. #if defined(PNG_WRITE_SUPPORTED)
  180311. # if !defined(PNG_WRITE_TRANSFORMS_NOT_SUPPORTED) && \
  180312. !defined(PNG_NO_WRITE_TRANSFORMS)
  180313. # define PNG_WRITE_TRANSFORMS_SUPPORTED
  180314. #endif
  180315. #ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
  180316. # ifndef PNG_NO_WRITE_SHIFT
  180317. # define PNG_WRITE_SHIFT_SUPPORTED
  180318. # endif
  180319. # ifndef PNG_NO_WRITE_PACK
  180320. # define PNG_WRITE_PACK_SUPPORTED
  180321. # endif
  180322. # ifndef PNG_NO_WRITE_BGR
  180323. # define PNG_WRITE_BGR_SUPPORTED
  180324. # endif
  180325. # ifndef PNG_NO_WRITE_SWAP
  180326. # define PNG_WRITE_SWAP_SUPPORTED
  180327. # endif
  180328. # ifndef PNG_NO_WRITE_PACKSWAP
  180329. # define PNG_WRITE_PACKSWAP_SUPPORTED
  180330. # endif
  180331. # ifndef PNG_NO_WRITE_INVERT
  180332. # define PNG_WRITE_INVERT_SUPPORTED
  180333. # endif
  180334. # ifndef PNG_NO_WRITE_FILLER
  180335. # define PNG_WRITE_FILLER_SUPPORTED /* same as WRITE_STRIP_ALPHA */
  180336. # endif
  180337. # ifndef PNG_NO_WRITE_SWAP_ALPHA
  180338. # define PNG_WRITE_SWAP_ALPHA_SUPPORTED
  180339. # endif
  180340. # ifndef PNG_NO_WRITE_INVERT_ALPHA
  180341. # define PNG_WRITE_INVERT_ALPHA_SUPPORTED
  180342. # endif
  180343. # ifndef PNG_NO_WRITE_USER_TRANSFORM
  180344. # define PNG_WRITE_USER_TRANSFORM_SUPPORTED
  180345. # endif
  180346. #endif /* PNG_WRITE_TRANSFORMS_SUPPORTED */
  180347. #if !defined(PNG_NO_WRITE_INTERLACING_SUPPORTED) && \
  180348. !defined(PNG_WRITE_INTERLACING_SUPPORTED)
  180349. #define PNG_WRITE_INTERLACING_SUPPORTED /* not required for PNG-compliant
  180350. encoders, but can cause trouble
  180351. if left undefined */
  180352. #endif
  180353. #if !defined(PNG_NO_WRITE_WEIGHTED_FILTER) && \
  180354. !defined(PNG_WRITE_WEIGHTED_FILTER) && \
  180355. defined(PNG_FLOATING_POINT_SUPPORTED)
  180356. # define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  180357. #endif
  180358. #ifndef PNG_NO_WRITE_FLUSH
  180359. # define PNG_WRITE_FLUSH_SUPPORTED
  180360. #endif
  180361. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  180362. /* Deprecated, see PNG_MNG_FEATURES_SUPPORTED, above */
  180363. #ifndef PNG_NO_WRITE_EMPTY_PLTE
  180364. # define PNG_WRITE_EMPTY_PLTE_SUPPORTED
  180365. #endif
  180366. #endif
  180367. #endif /* PNG_WRITE_SUPPORTED */
  180368. #ifndef PNG_1_0_X
  180369. # ifndef PNG_NO_ERROR_NUMBERS
  180370. # define PNG_ERROR_NUMBERS_SUPPORTED
  180371. # endif
  180372. #endif /* PNG_1_0_X */
  180373. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  180374. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  180375. # ifndef PNG_NO_USER_TRANSFORM_PTR
  180376. # define PNG_USER_TRANSFORM_PTR_SUPPORTED
  180377. # endif
  180378. #endif
  180379. #ifndef PNG_NO_STDIO
  180380. # define PNG_TIME_RFC1123_SUPPORTED
  180381. #endif
  180382. /* This adds extra functions in pngget.c for accessing data from the
  180383. * info pointer (added in version 0.99)
  180384. * png_get_image_width()
  180385. * png_get_image_height()
  180386. * png_get_bit_depth()
  180387. * png_get_color_type()
  180388. * png_get_compression_type()
  180389. * png_get_filter_type()
  180390. * png_get_interlace_type()
  180391. * png_get_pixel_aspect_ratio()
  180392. * png_get_pixels_per_meter()
  180393. * png_get_x_offset_pixels()
  180394. * png_get_y_offset_pixels()
  180395. * png_get_x_offset_microns()
  180396. * png_get_y_offset_microns()
  180397. */
  180398. #if !defined(PNG_NO_EASY_ACCESS) && !defined(PNG_EASY_ACCESS_SUPPORTED)
  180399. # define PNG_EASY_ACCESS_SUPPORTED
  180400. #endif
  180401. /* PNG_ASSEMBLER_CODE was enabled by default in version 1.2.0
  180402. * and removed from version 1.2.20. The following will be removed
  180403. * from libpng-1.4.0
  180404. */
  180405. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_OPTIMIZED_CODE)
  180406. # ifndef PNG_OPTIMIZED_CODE_SUPPORTED
  180407. # define PNG_OPTIMIZED_CODE_SUPPORTED
  180408. # endif
  180409. #endif
  180410. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_ASSEMBLER_CODE)
  180411. # ifndef PNG_ASSEMBLER_CODE_SUPPORTED
  180412. # define PNG_ASSEMBLER_CODE_SUPPORTED
  180413. # endif
  180414. # if defined(__GNUC__) && defined(__x86_64__) && (__GNUC__ < 4)
  180415. /* work around 64-bit gcc compiler bugs in gcc-3.x */
  180416. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  180417. # define PNG_NO_MMX_CODE
  180418. # endif
  180419. # endif
  180420. # if defined(__APPLE__)
  180421. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  180422. # define PNG_NO_MMX_CODE
  180423. # endif
  180424. # endif
  180425. # if (defined(__MWERKS__) && ((__MWERKS__ < 0x0900) || macintosh))
  180426. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  180427. # define PNG_NO_MMX_CODE
  180428. # endif
  180429. # endif
  180430. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  180431. # define PNG_MMX_CODE_SUPPORTED
  180432. # endif
  180433. #endif
  180434. /* end of obsolete code to be removed from libpng-1.4.0 */
  180435. #if !defined(PNG_1_0_X)
  180436. #if !defined(PNG_NO_USER_MEM) && !defined(PNG_USER_MEM_SUPPORTED)
  180437. # define PNG_USER_MEM_SUPPORTED
  180438. #endif
  180439. #endif /* PNG_1_0_X */
  180440. /* Added at libpng-1.2.6 */
  180441. #if !defined(PNG_1_0_X)
  180442. #ifndef PNG_SET_USER_LIMITS_SUPPORTED
  180443. #if !defined(PNG_NO_SET_USER_LIMITS) && !defined(PNG_SET_USER_LIMITS_SUPPORTED)
  180444. # define PNG_SET_USER_LIMITS_SUPPORTED
  180445. #endif
  180446. #endif
  180447. #endif /* PNG_1_0_X */
  180448. /* Added at libpng-1.0.16 and 1.2.6. To accept all valid PNGS no matter
  180449. * how large, set these limits to 0x7fffffffL
  180450. */
  180451. #ifndef PNG_USER_WIDTH_MAX
  180452. # define PNG_USER_WIDTH_MAX 1000000L
  180453. #endif
  180454. #ifndef PNG_USER_HEIGHT_MAX
  180455. # define PNG_USER_HEIGHT_MAX 1000000L
  180456. #endif
  180457. /* These are currently experimental features, define them if you want */
  180458. /* very little testing */
  180459. /*
  180460. #ifdef PNG_READ_SUPPORTED
  180461. # ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  180462. # define PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  180463. # endif
  180464. #endif
  180465. */
  180466. /* This is only for PowerPC big-endian and 680x0 systems */
  180467. /* some testing */
  180468. /*
  180469. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  180470. # define PNG_READ_BIG_ENDIAN_SUPPORTED
  180471. #endif
  180472. */
  180473. /* Buggy compilers (e.g., gcc 2.7.2.2) need this */
  180474. /*
  180475. #define PNG_NO_POINTER_INDEXING
  180476. */
  180477. /* These functions are turned off by default, as they will be phased out. */
  180478. /*
  180479. #define PNG_USELESS_TESTS_SUPPORTED
  180480. #define PNG_CORRECT_PALETTE_SUPPORTED
  180481. */
  180482. /* Any chunks you are not interested in, you can undef here. The
  180483. * ones that allocate memory may be expecially important (hIST,
  180484. * tEXt, zTXt, tRNS, pCAL). Others will just save time and make png_info
  180485. * a bit smaller.
  180486. */
  180487. #if defined(PNG_READ_SUPPORTED) && \
  180488. !defined(PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  180489. !defined(PNG_NO_READ_ANCILLARY_CHUNKS)
  180490. # define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  180491. #endif
  180492. #if defined(PNG_WRITE_SUPPORTED) && \
  180493. !defined(PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  180494. !defined(PNG_NO_WRITE_ANCILLARY_CHUNKS)
  180495. # define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  180496. #endif
  180497. #ifdef PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  180498. #ifdef PNG_NO_READ_TEXT
  180499. # define PNG_NO_READ_iTXt
  180500. # define PNG_NO_READ_tEXt
  180501. # define PNG_NO_READ_zTXt
  180502. #endif
  180503. #ifndef PNG_NO_READ_bKGD
  180504. # define PNG_READ_bKGD_SUPPORTED
  180505. # define PNG_bKGD_SUPPORTED
  180506. #endif
  180507. #ifndef PNG_NO_READ_cHRM
  180508. # define PNG_READ_cHRM_SUPPORTED
  180509. # define PNG_cHRM_SUPPORTED
  180510. #endif
  180511. #ifndef PNG_NO_READ_gAMA
  180512. # define PNG_READ_gAMA_SUPPORTED
  180513. # define PNG_gAMA_SUPPORTED
  180514. #endif
  180515. #ifndef PNG_NO_READ_hIST
  180516. # define PNG_READ_hIST_SUPPORTED
  180517. # define PNG_hIST_SUPPORTED
  180518. #endif
  180519. #ifndef PNG_NO_READ_iCCP
  180520. # define PNG_READ_iCCP_SUPPORTED
  180521. # define PNG_iCCP_SUPPORTED
  180522. #endif
  180523. #ifndef PNG_NO_READ_iTXt
  180524. # ifndef PNG_READ_iTXt_SUPPORTED
  180525. # define PNG_READ_iTXt_SUPPORTED
  180526. # endif
  180527. # ifndef PNG_iTXt_SUPPORTED
  180528. # define PNG_iTXt_SUPPORTED
  180529. # endif
  180530. #endif
  180531. #ifndef PNG_NO_READ_oFFs
  180532. # define PNG_READ_oFFs_SUPPORTED
  180533. # define PNG_oFFs_SUPPORTED
  180534. #endif
  180535. #ifndef PNG_NO_READ_pCAL
  180536. # define PNG_READ_pCAL_SUPPORTED
  180537. # define PNG_pCAL_SUPPORTED
  180538. #endif
  180539. #ifndef PNG_NO_READ_sCAL
  180540. # define PNG_READ_sCAL_SUPPORTED
  180541. # define PNG_sCAL_SUPPORTED
  180542. #endif
  180543. #ifndef PNG_NO_READ_pHYs
  180544. # define PNG_READ_pHYs_SUPPORTED
  180545. # define PNG_pHYs_SUPPORTED
  180546. #endif
  180547. #ifndef PNG_NO_READ_sBIT
  180548. # define PNG_READ_sBIT_SUPPORTED
  180549. # define PNG_sBIT_SUPPORTED
  180550. #endif
  180551. #ifndef PNG_NO_READ_sPLT
  180552. # define PNG_READ_sPLT_SUPPORTED
  180553. # define PNG_sPLT_SUPPORTED
  180554. #endif
  180555. #ifndef PNG_NO_READ_sRGB
  180556. # define PNG_READ_sRGB_SUPPORTED
  180557. # define PNG_sRGB_SUPPORTED
  180558. #endif
  180559. #ifndef PNG_NO_READ_tEXt
  180560. # define PNG_READ_tEXt_SUPPORTED
  180561. # define PNG_tEXt_SUPPORTED
  180562. #endif
  180563. #ifndef PNG_NO_READ_tIME
  180564. # define PNG_READ_tIME_SUPPORTED
  180565. # define PNG_tIME_SUPPORTED
  180566. #endif
  180567. #ifndef PNG_NO_READ_tRNS
  180568. # define PNG_READ_tRNS_SUPPORTED
  180569. # define PNG_tRNS_SUPPORTED
  180570. #endif
  180571. #ifndef PNG_NO_READ_zTXt
  180572. # define PNG_READ_zTXt_SUPPORTED
  180573. # define PNG_zTXt_SUPPORTED
  180574. #endif
  180575. #ifndef PNG_NO_READ_UNKNOWN_CHUNKS
  180576. # define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
  180577. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  180578. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  180579. # endif
  180580. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  180581. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  180582. # endif
  180583. #endif
  180584. #if !defined(PNG_NO_READ_USER_CHUNKS) && \
  180585. defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  180586. # define PNG_READ_USER_CHUNKS_SUPPORTED
  180587. # define PNG_USER_CHUNKS_SUPPORTED
  180588. # ifdef PNG_NO_READ_UNKNOWN_CHUNKS
  180589. # undef PNG_NO_READ_UNKNOWN_CHUNKS
  180590. # endif
  180591. # ifdef PNG_NO_HANDLE_AS_UNKNOWN
  180592. # undef PNG_NO_HANDLE_AS_UNKNOWN
  180593. # endif
  180594. #endif
  180595. #ifndef PNG_NO_READ_OPT_PLTE
  180596. # define PNG_READ_OPT_PLTE_SUPPORTED /* only affects support of the */
  180597. #endif /* optional PLTE chunk in RGB and RGBA images */
  180598. #if defined(PNG_READ_iTXt_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) || \
  180599. defined(PNG_READ_zTXt_SUPPORTED)
  180600. # define PNG_READ_TEXT_SUPPORTED
  180601. # define PNG_TEXT_SUPPORTED
  180602. #endif
  180603. #endif /* PNG_READ_ANCILLARY_CHUNKS_SUPPORTED */
  180604. #ifdef PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  180605. #ifdef PNG_NO_WRITE_TEXT
  180606. # define PNG_NO_WRITE_iTXt
  180607. # define PNG_NO_WRITE_tEXt
  180608. # define PNG_NO_WRITE_zTXt
  180609. #endif
  180610. #ifndef PNG_NO_WRITE_bKGD
  180611. # define PNG_WRITE_bKGD_SUPPORTED
  180612. # ifndef PNG_bKGD_SUPPORTED
  180613. # define PNG_bKGD_SUPPORTED
  180614. # endif
  180615. #endif
  180616. #ifndef PNG_NO_WRITE_cHRM
  180617. # define PNG_WRITE_cHRM_SUPPORTED
  180618. # ifndef PNG_cHRM_SUPPORTED
  180619. # define PNG_cHRM_SUPPORTED
  180620. # endif
  180621. #endif
  180622. #ifndef PNG_NO_WRITE_gAMA
  180623. # define PNG_WRITE_gAMA_SUPPORTED
  180624. # ifndef PNG_gAMA_SUPPORTED
  180625. # define PNG_gAMA_SUPPORTED
  180626. # endif
  180627. #endif
  180628. #ifndef PNG_NO_WRITE_hIST
  180629. # define PNG_WRITE_hIST_SUPPORTED
  180630. # ifndef PNG_hIST_SUPPORTED
  180631. # define PNG_hIST_SUPPORTED
  180632. # endif
  180633. #endif
  180634. #ifndef PNG_NO_WRITE_iCCP
  180635. # define PNG_WRITE_iCCP_SUPPORTED
  180636. # ifndef PNG_iCCP_SUPPORTED
  180637. # define PNG_iCCP_SUPPORTED
  180638. # endif
  180639. #endif
  180640. #ifndef PNG_NO_WRITE_iTXt
  180641. # ifndef PNG_WRITE_iTXt_SUPPORTED
  180642. # define PNG_WRITE_iTXt_SUPPORTED
  180643. # endif
  180644. # ifndef PNG_iTXt_SUPPORTED
  180645. # define PNG_iTXt_SUPPORTED
  180646. # endif
  180647. #endif
  180648. #ifndef PNG_NO_WRITE_oFFs
  180649. # define PNG_WRITE_oFFs_SUPPORTED
  180650. # ifndef PNG_oFFs_SUPPORTED
  180651. # define PNG_oFFs_SUPPORTED
  180652. # endif
  180653. #endif
  180654. #ifndef PNG_NO_WRITE_pCAL
  180655. # define PNG_WRITE_pCAL_SUPPORTED
  180656. # ifndef PNG_pCAL_SUPPORTED
  180657. # define PNG_pCAL_SUPPORTED
  180658. # endif
  180659. #endif
  180660. #ifndef PNG_NO_WRITE_sCAL
  180661. # define PNG_WRITE_sCAL_SUPPORTED
  180662. # ifndef PNG_sCAL_SUPPORTED
  180663. # define PNG_sCAL_SUPPORTED
  180664. # endif
  180665. #endif
  180666. #ifndef PNG_NO_WRITE_pHYs
  180667. # define PNG_WRITE_pHYs_SUPPORTED
  180668. # ifndef PNG_pHYs_SUPPORTED
  180669. # define PNG_pHYs_SUPPORTED
  180670. # endif
  180671. #endif
  180672. #ifndef PNG_NO_WRITE_sBIT
  180673. # define PNG_WRITE_sBIT_SUPPORTED
  180674. # ifndef PNG_sBIT_SUPPORTED
  180675. # define PNG_sBIT_SUPPORTED
  180676. # endif
  180677. #endif
  180678. #ifndef PNG_NO_WRITE_sPLT
  180679. # define PNG_WRITE_sPLT_SUPPORTED
  180680. # ifndef PNG_sPLT_SUPPORTED
  180681. # define PNG_sPLT_SUPPORTED
  180682. # endif
  180683. #endif
  180684. #ifndef PNG_NO_WRITE_sRGB
  180685. # define PNG_WRITE_sRGB_SUPPORTED
  180686. # ifndef PNG_sRGB_SUPPORTED
  180687. # define PNG_sRGB_SUPPORTED
  180688. # endif
  180689. #endif
  180690. #ifndef PNG_NO_WRITE_tEXt
  180691. # define PNG_WRITE_tEXt_SUPPORTED
  180692. # ifndef PNG_tEXt_SUPPORTED
  180693. # define PNG_tEXt_SUPPORTED
  180694. # endif
  180695. #endif
  180696. #ifndef PNG_NO_WRITE_tIME
  180697. # define PNG_WRITE_tIME_SUPPORTED
  180698. # ifndef PNG_tIME_SUPPORTED
  180699. # define PNG_tIME_SUPPORTED
  180700. # endif
  180701. #endif
  180702. #ifndef PNG_NO_WRITE_tRNS
  180703. # define PNG_WRITE_tRNS_SUPPORTED
  180704. # ifndef PNG_tRNS_SUPPORTED
  180705. # define PNG_tRNS_SUPPORTED
  180706. # endif
  180707. #endif
  180708. #ifndef PNG_NO_WRITE_zTXt
  180709. # define PNG_WRITE_zTXt_SUPPORTED
  180710. # ifndef PNG_zTXt_SUPPORTED
  180711. # define PNG_zTXt_SUPPORTED
  180712. # endif
  180713. #endif
  180714. #ifndef PNG_NO_WRITE_UNKNOWN_CHUNKS
  180715. # define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
  180716. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  180717. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  180718. # endif
  180719. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  180720. # ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  180721. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  180722. # endif
  180723. # endif
  180724. #endif
  180725. #if defined(PNG_WRITE_iTXt_SUPPORTED) || defined(PNG_WRITE_tEXt_SUPPORTED) || \
  180726. defined(PNG_WRITE_zTXt_SUPPORTED)
  180727. # define PNG_WRITE_TEXT_SUPPORTED
  180728. # ifndef PNG_TEXT_SUPPORTED
  180729. # define PNG_TEXT_SUPPORTED
  180730. # endif
  180731. #endif
  180732. #endif /* PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED */
  180733. /* Turn this off to disable png_read_png() and
  180734. * png_write_png() and leave the row_pointers member
  180735. * out of the info structure.
  180736. */
  180737. #ifndef PNG_NO_INFO_IMAGE
  180738. # define PNG_INFO_IMAGE_SUPPORTED
  180739. #endif
  180740. /* need the time information for reading tIME chunks */
  180741. #if defined(PNG_tIME_SUPPORTED)
  180742. # if !defined(_WIN32_WCE)
  180743. /* "time.h" functions are not supported on WindowsCE */
  180744. # include <time.h>
  180745. # endif
  180746. #endif
  180747. /* Some typedefs to get us started. These should be safe on most of the
  180748. * common platforms. The typedefs should be at least as large as the
  180749. * numbers suggest (a png_uint_32 must be at least 32 bits long), but they
  180750. * don't have to be exactly that size. Some compilers dislike passing
  180751. * unsigned shorts as function parameters, so you may be better off using
  180752. * unsigned int for png_uint_16. Likewise, for 64-bit systems, you may
  180753. * want to have unsigned int for png_uint_32 instead of unsigned long.
  180754. */
  180755. typedef unsigned long png_uint_32;
  180756. typedef long png_int_32;
  180757. typedef unsigned short png_uint_16;
  180758. typedef short png_int_16;
  180759. typedef unsigned char png_byte;
  180760. /* This is usually size_t. It is typedef'ed just in case you need it to
  180761. change (I'm not sure if you will or not, so I thought I'd be safe) */
  180762. #ifdef PNG_SIZE_T
  180763. typedef PNG_SIZE_T png_size_t;
  180764. # define png_sizeof(x) png_convert_size(sizeof (x))
  180765. #else
  180766. typedef size_t png_size_t;
  180767. # define png_sizeof(x) sizeof (x)
  180768. #endif
  180769. /* The following is needed for medium model support. It cannot be in the
  180770. * PNG_INTERNAL section. Needs modification for other compilers besides
  180771. * MSC. Model independent support declares all arrays and pointers to be
  180772. * large using the far keyword. The zlib version used must also support
  180773. * model independent data. As of version zlib 1.0.4, the necessary changes
  180774. * have been made in zlib. The USE_FAR_KEYWORD define triggers other
  180775. * changes that are needed. (Tim Wegner)
  180776. */
  180777. /* Separate compiler dependencies (problem here is that zlib.h always
  180778. defines FAR. (SJT) */
  180779. #ifdef __BORLANDC__
  180780. # if defined(__LARGE__) || defined(__HUGE__) || defined(__COMPACT__)
  180781. # define LDATA 1
  180782. # else
  180783. # define LDATA 0
  180784. # endif
  180785. /* GRR: why is Cygwin in here? Cygwin is not Borland C... */
  180786. # if !defined(__WIN32__) && !defined(__FLAT__) && !defined(__CYGWIN__)
  180787. # define PNG_MAX_MALLOC_64K
  180788. # if (LDATA != 1)
  180789. # ifndef FAR
  180790. # define FAR __far
  180791. # endif
  180792. # define USE_FAR_KEYWORD
  180793. # endif /* LDATA != 1 */
  180794. /* Possibly useful for moving data out of default segment.
  180795. * Uncomment it if you want. Could also define FARDATA as
  180796. * const if your compiler supports it. (SJT)
  180797. # define FARDATA FAR
  180798. */
  180799. # endif /* __WIN32__, __FLAT__, __CYGWIN__ */
  180800. #endif /* __BORLANDC__ */
  180801. /* Suggest testing for specific compiler first before testing for
  180802. * FAR. The Watcom compiler defines both __MEDIUM__ and M_I86MM,
  180803. * making reliance oncertain keywords suspect. (SJT)
  180804. */
  180805. /* MSC Medium model */
  180806. #if defined(FAR)
  180807. # if defined(M_I86MM)
  180808. # define USE_FAR_KEYWORD
  180809. # define FARDATA FAR
  180810. # include <dos.h>
  180811. # endif
  180812. #endif
  180813. /* SJT: default case */
  180814. #ifndef FAR
  180815. # define FAR
  180816. #endif
  180817. /* At this point FAR is always defined */
  180818. #ifndef FARDATA
  180819. # define FARDATA
  180820. #endif
  180821. /* Typedef for floating-point numbers that are converted
  180822. to fixed-point with a multiple of 100,000, e.g., int_gamma */
  180823. typedef png_int_32 png_fixed_point;
  180824. /* Add typedefs for pointers */
  180825. typedef void FAR * png_voidp;
  180826. typedef png_byte FAR * png_bytep;
  180827. typedef png_uint_32 FAR * png_uint_32p;
  180828. typedef png_int_32 FAR * png_int_32p;
  180829. typedef png_uint_16 FAR * png_uint_16p;
  180830. typedef png_int_16 FAR * png_int_16p;
  180831. typedef PNG_CONST char FAR * png_const_charp;
  180832. typedef char FAR * png_charp;
  180833. typedef png_fixed_point FAR * png_fixed_point_p;
  180834. #ifndef PNG_NO_STDIO
  180835. #if defined(_WIN32_WCE)
  180836. typedef HANDLE png_FILE_p;
  180837. #else
  180838. typedef FILE * png_FILE_p;
  180839. #endif
  180840. #endif
  180841. #ifdef PNG_FLOATING_POINT_SUPPORTED
  180842. typedef double FAR * png_doublep;
  180843. #endif
  180844. /* Pointers to pointers; i.e. arrays */
  180845. typedef png_byte FAR * FAR * png_bytepp;
  180846. typedef png_uint_32 FAR * FAR * png_uint_32pp;
  180847. typedef png_int_32 FAR * FAR * png_int_32pp;
  180848. typedef png_uint_16 FAR * FAR * png_uint_16pp;
  180849. typedef png_int_16 FAR * FAR * png_int_16pp;
  180850. typedef PNG_CONST char FAR * FAR * png_const_charpp;
  180851. typedef char FAR * FAR * png_charpp;
  180852. typedef png_fixed_point FAR * FAR * png_fixed_point_pp;
  180853. #ifdef PNG_FLOATING_POINT_SUPPORTED
  180854. typedef double FAR * FAR * png_doublepp;
  180855. #endif
  180856. /* Pointers to pointers to pointers; i.e., pointer to array */
  180857. typedef char FAR * FAR * FAR * png_charppp;
  180858. #if 0
  180859. /* SPC - Is this stuff deprecated? */
  180860. /* It'll be removed as of libpng-1.3.0 - GR-P */
  180861. /* libpng typedefs for types in zlib. If zlib changes
  180862. * or another compression library is used, then change these.
  180863. * Eliminates need to change all the source files.
  180864. */
  180865. typedef charf * png_zcharp;
  180866. typedef charf * FAR * png_zcharpp;
  180867. typedef z_stream FAR * png_zstreamp;
  180868. #endif /* (PNG_1_0_X) || defined(PNG_1_2_X) */
  180869. /*
  180870. * Define PNG_BUILD_DLL if the module being built is a Windows
  180871. * LIBPNG DLL.
  180872. *
  180873. * Define PNG_USE_DLL if you want to *link* to the Windows LIBPNG DLL.
  180874. * It is equivalent to Microsoft predefined macro _DLL that is
  180875. * automatically defined when you compile using the share
  180876. * version of the CRT (C Run-Time library)
  180877. *
  180878. * The cygwin mods make this behavior a little different:
  180879. * Define PNG_BUILD_DLL if you are building a dll for use with cygwin
  180880. * Define PNG_STATIC if you are building a static library for use with cygwin,
  180881. * -or- if you are building an application that you want to link to the
  180882. * static library.
  180883. * PNG_USE_DLL is defined by default (no user action needed) unless one of
  180884. * the other flags is defined.
  180885. */
  180886. #if !defined(PNG_DLL) && (defined(PNG_BUILD_DLL) || defined(PNG_USE_DLL))
  180887. # define PNG_DLL
  180888. #endif
  180889. /* If CYGWIN, then disallow GLOBAL ARRAYS unless building a static lib.
  180890. * When building a static lib, default to no GLOBAL ARRAYS, but allow
  180891. * command-line override
  180892. */
  180893. #if defined(__CYGWIN__)
  180894. # if !defined(PNG_STATIC)
  180895. # if defined(PNG_USE_GLOBAL_ARRAYS)
  180896. # undef PNG_USE_GLOBAL_ARRAYS
  180897. # endif
  180898. # if !defined(PNG_USE_LOCAL_ARRAYS)
  180899. # define PNG_USE_LOCAL_ARRAYS
  180900. # endif
  180901. # else
  180902. # if defined(PNG_USE_LOCAL_ARRAYS) || defined(PNG_NO_GLOBAL_ARRAYS)
  180903. # if defined(PNG_USE_GLOBAL_ARRAYS)
  180904. # undef PNG_USE_GLOBAL_ARRAYS
  180905. # endif
  180906. # endif
  180907. # endif
  180908. # if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  180909. # define PNG_USE_LOCAL_ARRAYS
  180910. # endif
  180911. #endif
  180912. /* Do not use global arrays (helps with building DLL's)
  180913. * They are no longer used in libpng itself, since version 1.0.5c,
  180914. * but might be required for some pre-1.0.5c applications.
  180915. */
  180916. #if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  180917. # if defined(PNG_NO_GLOBAL_ARRAYS) || \
  180918. (defined(__GNUC__) && defined(PNG_DLL)) || defined(_MSC_VER)
  180919. # define PNG_USE_LOCAL_ARRAYS
  180920. # else
  180921. # define PNG_USE_GLOBAL_ARRAYS
  180922. # endif
  180923. #endif
  180924. #if defined(__CYGWIN__)
  180925. # undef PNGAPI
  180926. # define PNGAPI __cdecl
  180927. # undef PNG_IMPEXP
  180928. # define PNG_IMPEXP
  180929. #endif
  180930. /* If you define PNGAPI, e.g., with compiler option "-DPNGAPI=__stdcall",
  180931. * you may get warnings regarding the linkage of png_zalloc and png_zfree.
  180932. * Don't ignore those warnings; you must also reset the default calling
  180933. * convention in your compiler to match your PNGAPI, and you must build
  180934. * zlib and your applications the same way you build libpng.
  180935. */
  180936. #if defined(__MINGW32__) && !defined(PNG_MODULEDEF)
  180937. # ifndef PNG_NO_MODULEDEF
  180938. # define PNG_NO_MODULEDEF
  180939. # endif
  180940. #endif
  180941. #if !defined(PNG_IMPEXP) && defined(PNG_BUILD_DLL) && !defined(PNG_NO_MODULEDEF)
  180942. # define PNG_IMPEXP
  180943. #endif
  180944. #if defined(PNG_DLL) || defined(_DLL) || defined(__DLL__ ) || \
  180945. (( defined(_Windows) || defined(_WINDOWS) || \
  180946. defined(WIN32) || defined(_WIN32) || defined(__WIN32__) ))
  180947. # ifndef PNGAPI
  180948. # if defined(__GNUC__) || (defined (_MSC_VER) && (_MSC_VER >= 800))
  180949. # define PNGAPI __cdecl
  180950. # else
  180951. # define PNGAPI _cdecl
  180952. # endif
  180953. # endif
  180954. # if !defined(PNG_IMPEXP) && (!defined(PNG_DLL) || \
  180955. 0 /* WINCOMPILER_WITH_NO_SUPPORT_FOR_DECLIMPEXP */)
  180956. # define PNG_IMPEXP
  180957. # endif
  180958. # if !defined(PNG_IMPEXP)
  180959. # define PNG_EXPORT_TYPE1(type,symbol) PNG_IMPEXP type PNGAPI symbol
  180960. # define PNG_EXPORT_TYPE2(type,symbol) type PNG_IMPEXP PNGAPI symbol
  180961. /* Borland/Microsoft */
  180962. # if defined(_MSC_VER) || defined(__BORLANDC__)
  180963. # if (_MSC_VER >= 800) || (__BORLANDC__ >= 0x500)
  180964. # define PNG_EXPORT PNG_EXPORT_TYPE1
  180965. # else
  180966. # define PNG_EXPORT PNG_EXPORT_TYPE2
  180967. # if defined(PNG_BUILD_DLL)
  180968. # define PNG_IMPEXP __export
  180969. # else
  180970. # define PNG_IMPEXP /*__import */ /* doesn't exist AFAIK in
  180971. VC++ */
  180972. # endif /* Exists in Borland C++ for
  180973. C++ classes (== huge) */
  180974. # endif
  180975. # endif
  180976. # if !defined(PNG_IMPEXP)
  180977. # if defined(PNG_BUILD_DLL)
  180978. # define PNG_IMPEXP __declspec(dllexport)
  180979. # else
  180980. # define PNG_IMPEXP __declspec(dllimport)
  180981. # endif
  180982. # endif
  180983. # endif /* PNG_IMPEXP */
  180984. #else /* !(DLL || non-cygwin WINDOWS) */
  180985. # if (defined(__IBMC__) || defined(__IBMCPP__)) && defined(__OS2__)
  180986. # ifndef PNGAPI
  180987. # define PNGAPI _System
  180988. # endif
  180989. # else
  180990. # if 0 /* ... other platforms, with other meanings */
  180991. # endif
  180992. # endif
  180993. #endif
  180994. #ifndef PNGAPI
  180995. # define PNGAPI
  180996. #endif
  180997. #ifndef PNG_IMPEXP
  180998. # define PNG_IMPEXP
  180999. #endif
  181000. #ifdef PNG_BUILDSYMS
  181001. # ifndef PNG_EXPORT
  181002. # define PNG_EXPORT(type,symbol) PNG_FUNCTION_EXPORT symbol END
  181003. # endif
  181004. # ifdef PNG_USE_GLOBAL_ARRAYS
  181005. # ifndef PNG_EXPORT_VAR
  181006. # define PNG_EXPORT_VAR(type) PNG_DATA_EXPORT
  181007. # endif
  181008. # endif
  181009. #endif
  181010. #ifndef PNG_EXPORT
  181011. # define PNG_EXPORT(type,symbol) PNG_IMPEXP type PNGAPI symbol
  181012. #endif
  181013. #ifdef PNG_USE_GLOBAL_ARRAYS
  181014. # ifndef PNG_EXPORT_VAR
  181015. # define PNG_EXPORT_VAR(type) extern PNG_IMPEXP type
  181016. # endif
  181017. #endif
  181018. /* User may want to use these so they are not in PNG_INTERNAL. Any library
  181019. * functions that are passed far data must be model independent.
  181020. */
  181021. #ifndef PNG_ABORT
  181022. # define PNG_ABORT() abort()
  181023. #endif
  181024. #ifdef PNG_SETJMP_SUPPORTED
  181025. # define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf)
  181026. #else
  181027. # define png_jmpbuf(png_ptr) \
  181028. (LIBPNG_WAS_COMPILED_WITH__PNG_SETJMP_NOT_SUPPORTED)
  181029. #endif
  181030. #if defined(USE_FAR_KEYWORD) /* memory model independent fns */
  181031. /* use this to make far-to-near assignments */
  181032. # define CHECK 1
  181033. # define NOCHECK 0
  181034. # define CVT_PTR(ptr) (png_far_to_near(png_ptr,ptr,CHECK))
  181035. # define CVT_PTR_NOCHECK(ptr) (png_far_to_near(png_ptr,ptr,NOCHECK))
  181036. # define png_snprintf _fsnprintf /* Added to v 1.2.19 */
  181037. # define png_strcpy _fstrcpy
  181038. # define png_strncpy _fstrncpy /* Added to v 1.2.6 */
  181039. # define png_strlen _fstrlen
  181040. # define png_memcmp _fmemcmp /* SJT: added */
  181041. # define png_memcpy _fmemcpy
  181042. # define png_memset _fmemset
  181043. #else /* use the usual functions */
  181044. # define CVT_PTR(ptr) (ptr)
  181045. # define CVT_PTR_NOCHECK(ptr) (ptr)
  181046. # ifndef PNG_NO_SNPRINTF
  181047. # ifdef _MSC_VER
  181048. # define png_snprintf _snprintf /* Added to v 1.2.19 */
  181049. # define png_snprintf2 _snprintf
  181050. # define png_snprintf6 _snprintf
  181051. # else
  181052. # define png_snprintf snprintf /* Added to v 1.2.19 */
  181053. # define png_snprintf2 snprintf
  181054. # define png_snprintf6 snprintf
  181055. # endif
  181056. # else
  181057. /* You don't have or don't want to use snprintf(). Caution: Using
  181058. * sprintf instead of snprintf exposes your application to accidental
  181059. * or malevolent buffer overflows. If you don't have snprintf()
  181060. * as a general rule you should provide one (you can get one from
  181061. * Portable OpenSSH). */
  181062. # define png_snprintf(s1,n,fmt,x1) sprintf(s1,fmt,x1)
  181063. # define png_snprintf2(s1,n,fmt,x1,x2) sprintf(s1,fmt,x1,x2)
  181064. # define png_snprintf6(s1,n,fmt,x1,x2,x3,x4,x5,x6) \
  181065. sprintf(s1,fmt,x1,x2,x3,x4,x5,x6)
  181066. # endif
  181067. # define png_strcpy strcpy
  181068. # define png_strncpy strncpy /* Added to v 1.2.6 */
  181069. # define png_strlen strlen
  181070. # define png_memcmp memcmp /* SJT: added */
  181071. # define png_memcpy memcpy
  181072. # define png_memset memset
  181073. #endif
  181074. /* End of memory model independent support */
  181075. /* Just a little check that someone hasn't tried to define something
  181076. * contradictory.
  181077. */
  181078. #if (PNG_ZBUF_SIZE > 65536L) && defined(PNG_MAX_MALLOC_64K)
  181079. # undef PNG_ZBUF_SIZE
  181080. # define PNG_ZBUF_SIZE 65536L
  181081. #endif
  181082. /* Added at libpng-1.2.8 */
  181083. #endif /* PNG_VERSION_INFO_ONLY */
  181084. #endif /* PNGCONF_H */
  181085. /*** End of inlined file: pngconf.h ***/
  181086. #ifdef _MSC_VER
  181087. #pragma warning (disable: 4996 4100)
  181088. #endif
  181089. /*
  181090. * Added at libpng-1.2.8 */
  181091. /* Ref MSDN: Private as priority over Special
  181092. * VS_FF_PRIVATEBUILD File *was not* built using standard release
  181093. * procedures. If this value is given, the StringFileInfo block must
  181094. * contain a PrivateBuild string.
  181095. *
  181096. * VS_FF_SPECIALBUILD File *was* built by the original company using
  181097. * standard release procedures but is a variation of the standard
  181098. * file of the same version number. If this value is given, the
  181099. * StringFileInfo block must contain a SpecialBuild string.
  181100. */
  181101. #if defined(PNG_USER_PRIVATEBUILD)
  181102. # define PNG_LIBPNG_BUILD_TYPE \
  181103. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_PRIVATE)
  181104. #else
  181105. # if defined(PNG_LIBPNG_SPECIALBUILD)
  181106. # define PNG_LIBPNG_BUILD_TYPE \
  181107. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_SPECIAL)
  181108. # else
  181109. # define PNG_LIBPNG_BUILD_TYPE (PNG_LIBPNG_BUILD_BASE_TYPE)
  181110. # endif
  181111. #endif
  181112. #ifndef PNG_VERSION_INFO_ONLY
  181113. /* Inhibit C++ name-mangling for libpng functions but not for system calls. */
  181114. #ifdef __cplusplus
  181115. extern "C" {
  181116. #endif /* __cplusplus */
  181117. /* This file is arranged in several sections. The first section contains
  181118. * structure and type definitions. The second section contains the external
  181119. * library functions, while the third has the internal library functions,
  181120. * which applications aren't expected to use directly.
  181121. */
  181122. #ifndef PNG_NO_TYPECAST_NULL
  181123. #define int_p_NULL (int *)NULL
  181124. #define png_bytep_NULL (png_bytep)NULL
  181125. #define png_bytepp_NULL (png_bytepp)NULL
  181126. #define png_doublep_NULL (png_doublep)NULL
  181127. #define png_error_ptr_NULL (png_error_ptr)NULL
  181128. #define png_flush_ptr_NULL (png_flush_ptr)NULL
  181129. #define png_free_ptr_NULL (png_free_ptr)NULL
  181130. #define png_infopp_NULL (png_infopp)NULL
  181131. #define png_malloc_ptr_NULL (png_malloc_ptr)NULL
  181132. #define png_read_status_ptr_NULL (png_read_status_ptr)NULL
  181133. #define png_rw_ptr_NULL (png_rw_ptr)NULL
  181134. #define png_structp_NULL (png_structp)NULL
  181135. #define png_uint_16p_NULL (png_uint_16p)NULL
  181136. #define png_voidp_NULL (png_voidp)NULL
  181137. #define png_write_status_ptr_NULL (png_write_status_ptr)NULL
  181138. #else
  181139. #define int_p_NULL NULL
  181140. #define png_bytep_NULL NULL
  181141. #define png_bytepp_NULL NULL
  181142. #define png_doublep_NULL NULL
  181143. #define png_error_ptr_NULL NULL
  181144. #define png_flush_ptr_NULL NULL
  181145. #define png_free_ptr_NULL NULL
  181146. #define png_infopp_NULL NULL
  181147. #define png_malloc_ptr_NULL NULL
  181148. #define png_read_status_ptr_NULL NULL
  181149. #define png_rw_ptr_NULL NULL
  181150. #define png_structp_NULL NULL
  181151. #define png_uint_16p_NULL NULL
  181152. #define png_voidp_NULL NULL
  181153. #define png_write_status_ptr_NULL NULL
  181154. #endif
  181155. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  181156. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  181157. /* Version information for C files, stored in png.c. This had better match
  181158. * the version above.
  181159. */
  181160. #ifdef PNG_USE_GLOBAL_ARRAYS
  181161. PNG_EXPORT_VAR (PNG_CONST char) png_libpng_ver[18];
  181162. /* need room for 99.99.99beta99z */
  181163. #else
  181164. #define png_libpng_ver png_get_header_ver(NULL)
  181165. #endif
  181166. #ifdef PNG_USE_GLOBAL_ARRAYS
  181167. /* This was removed in version 1.0.5c */
  181168. /* Structures to facilitate easy interlacing. See png.c for more details */
  181169. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_start[7];
  181170. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_inc[7];
  181171. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_ystart[7];
  181172. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_yinc[7];
  181173. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_mask[7];
  181174. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_dsp_mask[7];
  181175. /* This isn't currently used. If you need it, see png.c for more details.
  181176. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_height[7];
  181177. */
  181178. #endif
  181179. #endif /* PNG_NO_EXTERN */
  181180. /* Three color definitions. The order of the red, green, and blue, (and the
  181181. * exact size) is not important, although the size of the fields need to
  181182. * be png_byte or png_uint_16 (as defined below).
  181183. */
  181184. typedef struct png_color_struct
  181185. {
  181186. png_byte red;
  181187. png_byte green;
  181188. png_byte blue;
  181189. } png_color;
  181190. typedef png_color FAR * png_colorp;
  181191. typedef png_color FAR * FAR * png_colorpp;
  181192. typedef struct png_color_16_struct
  181193. {
  181194. png_byte index; /* used for palette files */
  181195. png_uint_16 red; /* for use in red green blue files */
  181196. png_uint_16 green;
  181197. png_uint_16 blue;
  181198. png_uint_16 gray; /* for use in grayscale files */
  181199. } png_color_16;
  181200. typedef png_color_16 FAR * png_color_16p;
  181201. typedef png_color_16 FAR * FAR * png_color_16pp;
  181202. typedef struct png_color_8_struct
  181203. {
  181204. png_byte red; /* for use in red green blue files */
  181205. png_byte green;
  181206. png_byte blue;
  181207. png_byte gray; /* for use in grayscale files */
  181208. png_byte alpha; /* for alpha channel files */
  181209. } png_color_8;
  181210. typedef png_color_8 FAR * png_color_8p;
  181211. typedef png_color_8 FAR * FAR * png_color_8pp;
  181212. /*
  181213. * The following two structures are used for the in-core representation
  181214. * of sPLT chunks.
  181215. */
  181216. typedef struct png_sPLT_entry_struct
  181217. {
  181218. png_uint_16 red;
  181219. png_uint_16 green;
  181220. png_uint_16 blue;
  181221. png_uint_16 alpha;
  181222. png_uint_16 frequency;
  181223. } png_sPLT_entry;
  181224. typedef png_sPLT_entry FAR * png_sPLT_entryp;
  181225. typedef png_sPLT_entry FAR * FAR * png_sPLT_entrypp;
  181226. /* When the depth of the sPLT palette is 8 bits, the color and alpha samples
  181227. * occupy the LSB of their respective members, and the MSB of each member
  181228. * is zero-filled. The frequency member always occupies the full 16 bits.
  181229. */
  181230. typedef struct png_sPLT_struct
  181231. {
  181232. png_charp name; /* palette name */
  181233. png_byte depth; /* depth of palette samples */
  181234. png_sPLT_entryp entries; /* palette entries */
  181235. png_int_32 nentries; /* number of palette entries */
  181236. } png_sPLT_t;
  181237. typedef png_sPLT_t FAR * png_sPLT_tp;
  181238. typedef png_sPLT_t FAR * FAR * png_sPLT_tpp;
  181239. #ifdef PNG_TEXT_SUPPORTED
  181240. /* png_text holds the contents of a text/ztxt/itxt chunk in a PNG file,
  181241. * and whether that contents is compressed or not. The "key" field
  181242. * points to a regular zero-terminated C string. The "text", "lang", and
  181243. * "lang_key" fields can be regular C strings, empty strings, or NULL pointers.
  181244. * However, the * structure returned by png_get_text() will always contain
  181245. * regular zero-terminated C strings (possibly empty), never NULL pointers,
  181246. * so they can be safely used in printf() and other string-handling functions.
  181247. */
  181248. typedef struct png_text_struct
  181249. {
  181250. int compression; /* compression value:
  181251. -1: tEXt, none
  181252. 0: zTXt, deflate
  181253. 1: iTXt, none
  181254. 2: iTXt, deflate */
  181255. png_charp key; /* keyword, 1-79 character description of "text" */
  181256. png_charp text; /* comment, may be an empty string (ie "")
  181257. or a NULL pointer */
  181258. png_size_t text_length; /* length of the text string */
  181259. #ifdef PNG_iTXt_SUPPORTED
  181260. png_size_t itxt_length; /* length of the itxt string */
  181261. png_charp lang; /* language code, 0-79 characters
  181262. or a NULL pointer */
  181263. png_charp lang_key; /* keyword translated UTF-8 string, 0 or more
  181264. chars or a NULL pointer */
  181265. #endif
  181266. } png_text;
  181267. typedef png_text FAR * png_textp;
  181268. typedef png_text FAR * FAR * png_textpp;
  181269. #endif
  181270. /* Supported compression types for text in PNG files (tEXt, and zTXt).
  181271. * The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */
  181272. #define PNG_TEXT_COMPRESSION_NONE_WR -3
  181273. #define PNG_TEXT_COMPRESSION_zTXt_WR -2
  181274. #define PNG_TEXT_COMPRESSION_NONE -1
  181275. #define PNG_TEXT_COMPRESSION_zTXt 0
  181276. #define PNG_ITXT_COMPRESSION_NONE 1
  181277. #define PNG_ITXT_COMPRESSION_zTXt 2
  181278. #define PNG_TEXT_COMPRESSION_LAST 3 /* Not a valid value */
  181279. /* png_time is a way to hold the time in an machine independent way.
  181280. * Two conversions are provided, both from time_t and struct tm. There
  181281. * is no portable way to convert to either of these structures, as far
  181282. * as I know. If you know of a portable way, send it to me. As a side
  181283. * note - PNG has always been Year 2000 compliant!
  181284. */
  181285. typedef struct png_time_struct
  181286. {
  181287. png_uint_16 year; /* full year, as in, 1995 */
  181288. png_byte month; /* month of year, 1 - 12 */
  181289. png_byte day; /* day of month, 1 - 31 */
  181290. png_byte hour; /* hour of day, 0 - 23 */
  181291. png_byte minute; /* minute of hour, 0 - 59 */
  181292. png_byte second; /* second of minute, 0 - 60 (for leap seconds) */
  181293. } png_time;
  181294. typedef png_time FAR * png_timep;
  181295. typedef png_time FAR * FAR * png_timepp;
  181296. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  181297. /* png_unknown_chunk is a structure to hold queued chunks for which there is
  181298. * no specific support. The idea is that we can use this to queue
  181299. * up private chunks for output even though the library doesn't actually
  181300. * know about their semantics.
  181301. */
  181302. typedef struct png_unknown_chunk_t
  181303. {
  181304. png_byte name[5];
  181305. png_byte *data;
  181306. png_size_t size;
  181307. /* libpng-using applications should NOT directly modify this byte. */
  181308. png_byte location; /* mode of operation at read time */
  181309. }
  181310. png_unknown_chunk;
  181311. typedef png_unknown_chunk FAR * png_unknown_chunkp;
  181312. typedef png_unknown_chunk FAR * FAR * png_unknown_chunkpp;
  181313. #endif
  181314. /* png_info is a structure that holds the information in a PNG file so
  181315. * that the application can find out the characteristics of the image.
  181316. * If you are reading the file, this structure will tell you what is
  181317. * in the PNG file. If you are writing the file, fill in the information
  181318. * you want to put into the PNG file, then call png_write_info().
  181319. * The names chosen should be very close to the PNG specification, so
  181320. * consult that document for information about the meaning of each field.
  181321. *
  181322. * With libpng < 0.95, it was only possible to directly set and read the
  181323. * the values in the png_info_struct, which meant that the contents and
  181324. * order of the values had to remain fixed. With libpng 0.95 and later,
  181325. * however, there are now functions that abstract the contents of
  181326. * png_info_struct from the application, so this makes it easier to use
  181327. * libpng with dynamic libraries, and even makes it possible to use
  181328. * libraries that don't have all of the libpng ancillary chunk-handing
  181329. * functionality.
  181330. *
  181331. * In any case, the order of the parameters in png_info_struct should NOT
  181332. * be changed for as long as possible to keep compatibility with applications
  181333. * that use the old direct-access method with png_info_struct.
  181334. *
  181335. * The following members may have allocated storage attached that should be
  181336. * cleaned up before the structure is discarded: palette, trans, text,
  181337. * pcal_purpose, pcal_units, pcal_params, hist, iccp_name, iccp_profile,
  181338. * splt_palettes, scal_unit, row_pointers, and unknowns. By default, these
  181339. * are automatically freed when the info structure is deallocated, if they were
  181340. * allocated internally by libpng. This behavior can be changed by means
  181341. * of the png_data_freer() function.
  181342. *
  181343. * More allocation details: all the chunk-reading functions that
  181344. * change these members go through the corresponding png_set_*
  181345. * functions. A function to clear these members is available: see
  181346. * png_free_data(). The png_set_* functions do not depend on being
  181347. * able to point info structure members to any of the storage they are
  181348. * passed (they make their own copies), EXCEPT that the png_set_text
  181349. * functions use the same storage passed to them in the text_ptr or
  181350. * itxt_ptr structure argument, and the png_set_rows and png_set_unknowns
  181351. * functions do not make their own copies.
  181352. */
  181353. typedef struct png_info_struct
  181354. {
  181355. /* the following are necessary for every PNG file */
  181356. png_uint_32 width; /* width of image in pixels (from IHDR) */
  181357. png_uint_32 height; /* height of image in pixels (from IHDR) */
  181358. png_uint_32 valid; /* valid chunk data (see PNG_INFO_ below) */
  181359. png_uint_32 rowbytes; /* bytes needed to hold an untransformed row */
  181360. png_colorp palette; /* array of color values (valid & PNG_INFO_PLTE) */
  181361. png_uint_16 num_palette; /* number of color entries in "palette" (PLTE) */
  181362. png_uint_16 num_trans; /* number of transparent palette color (tRNS) */
  181363. png_byte bit_depth; /* 1, 2, 4, 8, or 16 bits/channel (from IHDR) */
  181364. png_byte color_type; /* see PNG_COLOR_TYPE_ below (from IHDR) */
  181365. /* The following three should have been named *_method not *_type */
  181366. png_byte compression_type; /* must be PNG_COMPRESSION_TYPE_BASE (IHDR) */
  181367. png_byte filter_type; /* must be PNG_FILTER_TYPE_BASE (from IHDR) */
  181368. png_byte interlace_type; /* One of PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  181369. /* The following is informational only on read, and not used on writes. */
  181370. png_byte channels; /* number of data channels per pixel (1, 2, 3, 4) */
  181371. png_byte pixel_depth; /* number of bits per pixel */
  181372. png_byte spare_byte; /* to align the data, and for future use */
  181373. png_byte signature[8]; /* magic bytes read by libpng from start of file */
  181374. /* The rest of the data is optional. If you are reading, check the
  181375. * valid field to see if the information in these are valid. If you
  181376. * are writing, set the valid field to those chunks you want written,
  181377. * and initialize the appropriate fields below.
  181378. */
  181379. #if defined(PNG_gAMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  181380. /* The gAMA chunk describes the gamma characteristics of the system
  181381. * on which the image was created, normally in the range [1.0, 2.5].
  181382. * Data is valid if (valid & PNG_INFO_gAMA) is non-zero.
  181383. */
  181384. float gamma; /* gamma value of image, if (valid & PNG_INFO_gAMA) */
  181385. #endif
  181386. #if defined(PNG_sRGB_SUPPORTED)
  181387. /* GR-P, 0.96a */
  181388. /* Data valid if (valid & PNG_INFO_sRGB) non-zero. */
  181389. png_byte srgb_intent; /* sRGB rendering intent [0, 1, 2, or 3] */
  181390. #endif
  181391. #if defined(PNG_TEXT_SUPPORTED)
  181392. /* The tEXt, and zTXt chunks contain human-readable textual data in
  181393. * uncompressed, compressed, and optionally compressed forms, respectively.
  181394. * The data in "text" is an array of pointers to uncompressed,
  181395. * null-terminated C strings. Each chunk has a keyword that describes the
  181396. * textual data contained in that chunk. Keywords are not required to be
  181397. * unique, and the text string may be empty. Any number of text chunks may
  181398. * be in an image.
  181399. */
  181400. int num_text; /* number of comments read/to write */
  181401. int max_text; /* current size of text array */
  181402. png_textp text; /* array of comments read/to write */
  181403. #endif /* PNG_TEXT_SUPPORTED */
  181404. #if defined(PNG_tIME_SUPPORTED)
  181405. /* The tIME chunk holds the last time the displayed image data was
  181406. * modified. See the png_time struct for the contents of this struct.
  181407. */
  181408. png_time mod_time;
  181409. #endif
  181410. #if defined(PNG_sBIT_SUPPORTED)
  181411. /* The sBIT chunk specifies the number of significant high-order bits
  181412. * in the pixel data. Values are in the range [1, bit_depth], and are
  181413. * only specified for the channels in the pixel data. The contents of
  181414. * the low-order bits is not specified. Data is valid if
  181415. * (valid & PNG_INFO_sBIT) is non-zero.
  181416. */
  181417. png_color_8 sig_bit; /* significant bits in color channels */
  181418. #endif
  181419. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_EXPAND_SUPPORTED) || \
  181420. defined(PNG_READ_BACKGROUND_SUPPORTED)
  181421. /* The tRNS chunk supplies transparency data for paletted images and
  181422. * other image types that don't need a full alpha channel. There are
  181423. * "num_trans" transparency values for a paletted image, stored in the
  181424. * same order as the palette colors, starting from index 0. Values
  181425. * for the data are in the range [0, 255], ranging from fully transparent
  181426. * to fully opaque, respectively. For non-paletted images, there is a
  181427. * single color specified that should be treated as fully transparent.
  181428. * Data is valid if (valid & PNG_INFO_tRNS) is non-zero.
  181429. */
  181430. png_bytep trans; /* transparent values for paletted image */
  181431. png_color_16 trans_values; /* transparent color for non-palette image */
  181432. #endif
  181433. #if defined(PNG_bKGD_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  181434. /* The bKGD chunk gives the suggested image background color if the
  181435. * display program does not have its own background color and the image
  181436. * is needs to composited onto a background before display. The colors
  181437. * in "background" are normally in the same color space/depth as the
  181438. * pixel data. Data is valid if (valid & PNG_INFO_bKGD) is non-zero.
  181439. */
  181440. png_color_16 background;
  181441. #endif
  181442. #if defined(PNG_oFFs_SUPPORTED)
  181443. /* The oFFs chunk gives the offset in "offset_unit_type" units rightwards
  181444. * and downwards from the top-left corner of the display, page, or other
  181445. * application-specific co-ordinate space. See the PNG_OFFSET_ defines
  181446. * below for the unit types. Valid if (valid & PNG_INFO_oFFs) non-zero.
  181447. */
  181448. png_int_32 x_offset; /* x offset on page */
  181449. png_int_32 y_offset; /* y offset on page */
  181450. png_byte offset_unit_type; /* offset units type */
  181451. #endif
  181452. #if defined(PNG_pHYs_SUPPORTED)
  181453. /* The pHYs chunk gives the physical pixel density of the image for
  181454. * display or printing in "phys_unit_type" units (see PNG_RESOLUTION_
  181455. * defines below). Data is valid if (valid & PNG_INFO_pHYs) is non-zero.
  181456. */
  181457. png_uint_32 x_pixels_per_unit; /* horizontal pixel density */
  181458. png_uint_32 y_pixels_per_unit; /* vertical pixel density */
  181459. png_byte phys_unit_type; /* resolution type (see PNG_RESOLUTION_ below) */
  181460. #endif
  181461. #if defined(PNG_hIST_SUPPORTED)
  181462. /* The hIST chunk contains the relative frequency or importance of the
  181463. * various palette entries, so that a viewer can intelligently select a
  181464. * reduced-color palette, if required. Data is an array of "num_palette"
  181465. * values in the range [0,65535]. Data valid if (valid & PNG_INFO_hIST)
  181466. * is non-zero.
  181467. */
  181468. png_uint_16p hist;
  181469. #endif
  181470. #ifdef PNG_cHRM_SUPPORTED
  181471. /* The cHRM chunk describes the CIE color characteristics of the monitor
  181472. * on which the PNG was created. This data allows the viewer to do gamut
  181473. * mapping of the input image to ensure that the viewer sees the same
  181474. * colors in the image as the creator. Values are in the range
  181475. * [0.0, 0.8]. Data valid if (valid & PNG_INFO_cHRM) non-zero.
  181476. */
  181477. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181478. float x_white;
  181479. float y_white;
  181480. float x_red;
  181481. float y_red;
  181482. float x_green;
  181483. float y_green;
  181484. float x_blue;
  181485. float y_blue;
  181486. #endif
  181487. #endif
  181488. #if defined(PNG_pCAL_SUPPORTED)
  181489. /* The pCAL chunk describes a transformation between the stored pixel
  181490. * values and original physical data values used to create the image.
  181491. * The integer range [0, 2^bit_depth - 1] maps to the floating-point
  181492. * range given by [pcal_X0, pcal_X1], and are further transformed by a
  181493. * (possibly non-linear) transformation function given by "pcal_type"
  181494. * and "pcal_params" into "pcal_units". Please see the PNG_EQUATION_
  181495. * defines below, and the PNG-Group's PNG extensions document for a
  181496. * complete description of the transformations and how they should be
  181497. * implemented, and for a description of the ASCII parameter strings.
  181498. * Data values are valid if (valid & PNG_INFO_pCAL) non-zero.
  181499. */
  181500. png_charp pcal_purpose; /* pCAL chunk description string */
  181501. png_int_32 pcal_X0; /* minimum value */
  181502. png_int_32 pcal_X1; /* maximum value */
  181503. png_charp pcal_units; /* Latin-1 string giving physical units */
  181504. png_charpp pcal_params; /* ASCII strings containing parameter values */
  181505. png_byte pcal_type; /* equation type (see PNG_EQUATION_ below) */
  181506. png_byte pcal_nparams; /* number of parameters given in pcal_params */
  181507. #endif
  181508. /* New members added in libpng-1.0.6 */
  181509. #ifdef PNG_FREE_ME_SUPPORTED
  181510. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  181511. #endif
  181512. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  181513. /* storage for unknown chunks that the library doesn't recognize. */
  181514. png_unknown_chunkp unknown_chunks;
  181515. png_size_t unknown_chunks_num;
  181516. #endif
  181517. #if defined(PNG_iCCP_SUPPORTED)
  181518. /* iCCP chunk data. */
  181519. png_charp iccp_name; /* profile name */
  181520. png_charp iccp_profile; /* International Color Consortium profile data */
  181521. /* Note to maintainer: should be png_bytep */
  181522. png_uint_32 iccp_proflen; /* ICC profile data length */
  181523. png_byte iccp_compression; /* Always zero */
  181524. #endif
  181525. #if defined(PNG_sPLT_SUPPORTED)
  181526. /* data on sPLT chunks (there may be more than one). */
  181527. png_sPLT_tp splt_palettes;
  181528. png_uint_32 splt_palettes_num;
  181529. #endif
  181530. #if defined(PNG_sCAL_SUPPORTED)
  181531. /* The sCAL chunk describes the actual physical dimensions of the
  181532. * subject matter of the graphic. The chunk contains a unit specification
  181533. * a byte value, and two ASCII strings representing floating-point
  181534. * values. The values are width and height corresponsing to one pixel
  181535. * in the image. This external representation is converted to double
  181536. * here. Data values are valid if (valid & PNG_INFO_sCAL) is non-zero.
  181537. */
  181538. png_byte scal_unit; /* unit of physical scale */
  181539. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181540. double scal_pixel_width; /* width of one pixel */
  181541. double scal_pixel_height; /* height of one pixel */
  181542. #endif
  181543. #ifdef PNG_FIXED_POINT_SUPPORTED
  181544. png_charp scal_s_width; /* string containing height */
  181545. png_charp scal_s_height; /* string containing width */
  181546. #endif
  181547. #endif
  181548. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  181549. /* Memory has been allocated if (valid & PNG_ALLOCATED_INFO_ROWS) non-zero */
  181550. /* Data valid if (valid & PNG_INFO_IDAT) non-zero */
  181551. png_bytepp row_pointers; /* the image bits */
  181552. #endif
  181553. #if defined(PNG_FIXED_POINT_SUPPORTED) && defined(PNG_gAMA_SUPPORTED)
  181554. png_fixed_point int_gamma; /* gamma of image, if (valid & PNG_INFO_gAMA) */
  181555. #endif
  181556. #if defined(PNG_cHRM_SUPPORTED) && defined(PNG_FIXED_POINT_SUPPORTED)
  181557. png_fixed_point int_x_white;
  181558. png_fixed_point int_y_white;
  181559. png_fixed_point int_x_red;
  181560. png_fixed_point int_y_red;
  181561. png_fixed_point int_x_green;
  181562. png_fixed_point int_y_green;
  181563. png_fixed_point int_x_blue;
  181564. png_fixed_point int_y_blue;
  181565. #endif
  181566. } png_info;
  181567. typedef png_info FAR * png_infop;
  181568. typedef png_info FAR * FAR * png_infopp;
  181569. /* Maximum positive integer used in PNG is (2^31)-1 */
  181570. #define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL)
  181571. #define PNG_UINT_32_MAX ((png_uint_32)(-1))
  181572. #define PNG_SIZE_MAX ((png_size_t)(-1))
  181573. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181574. /* PNG_MAX_UINT is deprecated; use PNG_UINT_31_MAX instead. */
  181575. #define PNG_MAX_UINT PNG_UINT_31_MAX
  181576. #endif
  181577. /* These describe the color_type field in png_info. */
  181578. /* color type masks */
  181579. #define PNG_COLOR_MASK_PALETTE 1
  181580. #define PNG_COLOR_MASK_COLOR 2
  181581. #define PNG_COLOR_MASK_ALPHA 4
  181582. /* color types. Note that not all combinations are legal */
  181583. #define PNG_COLOR_TYPE_GRAY 0
  181584. #define PNG_COLOR_TYPE_PALETTE (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
  181585. #define PNG_COLOR_TYPE_RGB (PNG_COLOR_MASK_COLOR)
  181586. #define PNG_COLOR_TYPE_RGB_ALPHA (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
  181587. #define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
  181588. /* aliases */
  181589. #define PNG_COLOR_TYPE_RGBA PNG_COLOR_TYPE_RGB_ALPHA
  181590. #define PNG_COLOR_TYPE_GA PNG_COLOR_TYPE_GRAY_ALPHA
  181591. /* This is for compression type. PNG 1.0-1.2 only define the single type. */
  181592. #define PNG_COMPRESSION_TYPE_BASE 0 /* Deflate method 8, 32K window */
  181593. #define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE
  181594. /* This is for filter type. PNG 1.0-1.2 only define the single type. */
  181595. #define PNG_FILTER_TYPE_BASE 0 /* Single row per-byte filtering */
  181596. #define PNG_INTRAPIXEL_DIFFERENCING 64 /* Used only in MNG datastreams */
  181597. #define PNG_FILTER_TYPE_DEFAULT PNG_FILTER_TYPE_BASE
  181598. /* These are for the interlacing type. These values should NOT be changed. */
  181599. #define PNG_INTERLACE_NONE 0 /* Non-interlaced image */
  181600. #define PNG_INTERLACE_ADAM7 1 /* Adam7 interlacing */
  181601. #define PNG_INTERLACE_LAST 2 /* Not a valid value */
  181602. /* These are for the oFFs chunk. These values should NOT be changed. */
  181603. #define PNG_OFFSET_PIXEL 0 /* Offset in pixels */
  181604. #define PNG_OFFSET_MICROMETER 1 /* Offset in micrometers (1/10^6 meter) */
  181605. #define PNG_OFFSET_LAST 2 /* Not a valid value */
  181606. /* These are for the pCAL chunk. These values should NOT be changed. */
  181607. #define PNG_EQUATION_LINEAR 0 /* Linear transformation */
  181608. #define PNG_EQUATION_BASE_E 1 /* Exponential base e transform */
  181609. #define PNG_EQUATION_ARBITRARY 2 /* Arbitrary base exponential transform */
  181610. #define PNG_EQUATION_HYPERBOLIC 3 /* Hyperbolic sine transformation */
  181611. #define PNG_EQUATION_LAST 4 /* Not a valid value */
  181612. /* These are for the sCAL chunk. These values should NOT be changed. */
  181613. #define PNG_SCALE_UNKNOWN 0 /* unknown unit (image scale) */
  181614. #define PNG_SCALE_METER 1 /* meters per pixel */
  181615. #define PNG_SCALE_RADIAN 2 /* radians per pixel */
  181616. #define PNG_SCALE_LAST 3 /* Not a valid value */
  181617. /* These are for the pHYs chunk. These values should NOT be changed. */
  181618. #define PNG_RESOLUTION_UNKNOWN 0 /* pixels/unknown unit (aspect ratio) */
  181619. #define PNG_RESOLUTION_METER 1 /* pixels/meter */
  181620. #define PNG_RESOLUTION_LAST 2 /* Not a valid value */
  181621. /* These are for the sRGB chunk. These values should NOT be changed. */
  181622. #define PNG_sRGB_INTENT_PERCEPTUAL 0
  181623. #define PNG_sRGB_INTENT_RELATIVE 1
  181624. #define PNG_sRGB_INTENT_SATURATION 2
  181625. #define PNG_sRGB_INTENT_ABSOLUTE 3
  181626. #define PNG_sRGB_INTENT_LAST 4 /* Not a valid value */
  181627. /* This is for text chunks */
  181628. #define PNG_KEYWORD_MAX_LENGTH 79
  181629. /* Maximum number of entries in PLTE/sPLT/tRNS arrays */
  181630. #define PNG_MAX_PALETTE_LENGTH 256
  181631. /* These determine if an ancillary chunk's data has been successfully read
  181632. * from the PNG header, or if the application has filled in the corresponding
  181633. * data in the info_struct to be written into the output file. The values
  181634. * of the PNG_INFO_<chunk> defines should NOT be changed.
  181635. */
  181636. #define PNG_INFO_gAMA 0x0001
  181637. #define PNG_INFO_sBIT 0x0002
  181638. #define PNG_INFO_cHRM 0x0004
  181639. #define PNG_INFO_PLTE 0x0008
  181640. #define PNG_INFO_tRNS 0x0010
  181641. #define PNG_INFO_bKGD 0x0020
  181642. #define PNG_INFO_hIST 0x0040
  181643. #define PNG_INFO_pHYs 0x0080
  181644. #define PNG_INFO_oFFs 0x0100
  181645. #define PNG_INFO_tIME 0x0200
  181646. #define PNG_INFO_pCAL 0x0400
  181647. #define PNG_INFO_sRGB 0x0800 /* GR-P, 0.96a */
  181648. #define PNG_INFO_iCCP 0x1000 /* ESR, 1.0.6 */
  181649. #define PNG_INFO_sPLT 0x2000 /* ESR, 1.0.6 */
  181650. #define PNG_INFO_sCAL 0x4000 /* ESR, 1.0.6 */
  181651. #define PNG_INFO_IDAT 0x8000L /* ESR, 1.0.6 */
  181652. /* This is used for the transformation routines, as some of them
  181653. * change these values for the row. It also should enable using
  181654. * the routines for other purposes.
  181655. */
  181656. typedef struct png_row_info_struct
  181657. {
  181658. png_uint_32 width; /* width of row */
  181659. png_uint_32 rowbytes; /* number of bytes in row */
  181660. png_byte color_type; /* color type of row */
  181661. png_byte bit_depth; /* bit depth of row */
  181662. png_byte channels; /* number of channels (1, 2, 3, or 4) */
  181663. png_byte pixel_depth; /* bits per pixel (depth * channels) */
  181664. } png_row_info;
  181665. typedef png_row_info FAR * png_row_infop;
  181666. typedef png_row_info FAR * FAR * png_row_infopp;
  181667. /* These are the function types for the I/O functions and for the functions
  181668. * that allow the user to override the default I/O functions with his or her
  181669. * own. The png_error_ptr type should match that of user-supplied warning
  181670. * and error functions, while the png_rw_ptr type should match that of the
  181671. * user read/write data functions.
  181672. */
  181673. typedef struct png_struct_def png_struct;
  181674. typedef png_struct FAR * png_structp;
  181675. typedef void (PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp));
  181676. typedef void (PNGAPI *png_rw_ptr) PNGARG((png_structp, png_bytep, png_size_t));
  181677. typedef void (PNGAPI *png_flush_ptr) PNGARG((png_structp));
  181678. typedef void (PNGAPI *png_read_status_ptr) PNGARG((png_structp, png_uint_32,
  181679. int));
  181680. typedef void (PNGAPI *png_write_status_ptr) PNGARG((png_structp, png_uint_32,
  181681. int));
  181682. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  181683. typedef void (PNGAPI *png_progressive_info_ptr) PNGARG((png_structp, png_infop));
  181684. typedef void (PNGAPI *png_progressive_end_ptr) PNGARG((png_structp, png_infop));
  181685. typedef void (PNGAPI *png_progressive_row_ptr) PNGARG((png_structp, png_bytep,
  181686. png_uint_32, int));
  181687. #endif
  181688. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  181689. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  181690. defined(PNG_LEGACY_SUPPORTED)
  181691. typedef void (PNGAPI *png_user_transform_ptr) PNGARG((png_structp,
  181692. png_row_infop, png_bytep));
  181693. #endif
  181694. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  181695. typedef int (PNGAPI *png_user_chunk_ptr) PNGARG((png_structp, png_unknown_chunkp));
  181696. #endif
  181697. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  181698. typedef void (PNGAPI *png_unknown_chunk_ptr) PNGARG((png_structp));
  181699. #endif
  181700. /* Transform masks for the high-level interface */
  181701. #define PNG_TRANSFORM_IDENTITY 0x0000 /* read and write */
  181702. #define PNG_TRANSFORM_STRIP_16 0x0001 /* read only */
  181703. #define PNG_TRANSFORM_STRIP_ALPHA 0x0002 /* read only */
  181704. #define PNG_TRANSFORM_PACKING 0x0004 /* read and write */
  181705. #define PNG_TRANSFORM_PACKSWAP 0x0008 /* read and write */
  181706. #define PNG_TRANSFORM_EXPAND 0x0010 /* read only */
  181707. #define PNG_TRANSFORM_INVERT_MONO 0x0020 /* read and write */
  181708. #define PNG_TRANSFORM_SHIFT 0x0040 /* read and write */
  181709. #define PNG_TRANSFORM_BGR 0x0080 /* read and write */
  181710. #define PNG_TRANSFORM_SWAP_ALPHA 0x0100 /* read and write */
  181711. #define PNG_TRANSFORM_SWAP_ENDIAN 0x0200 /* read and write */
  181712. #define PNG_TRANSFORM_INVERT_ALPHA 0x0400 /* read and write */
  181713. #define PNG_TRANSFORM_STRIP_FILLER 0x0800 /* WRITE only */
  181714. /* Flags for MNG supported features */
  181715. #define PNG_FLAG_MNG_EMPTY_PLTE 0x01
  181716. #define PNG_FLAG_MNG_FILTER_64 0x04
  181717. #define PNG_ALL_MNG_FEATURES 0x05
  181718. typedef png_voidp (*png_malloc_ptr) PNGARG((png_structp, png_size_t));
  181719. typedef void (*png_free_ptr) PNGARG((png_structp, png_voidp));
  181720. /* The structure that holds the information to read and write PNG files.
  181721. * The only people who need to care about what is inside of this are the
  181722. * people who will be modifying the library for their own special needs.
  181723. * It should NOT be accessed directly by an application, except to store
  181724. * the jmp_buf.
  181725. */
  181726. struct png_struct_def
  181727. {
  181728. #ifdef PNG_SETJMP_SUPPORTED
  181729. jmp_buf jmpbuf; /* used in png_error */
  181730. #endif
  181731. png_error_ptr error_fn; /* function for printing errors and aborting */
  181732. png_error_ptr warning_fn; /* function for printing warnings */
  181733. png_voidp error_ptr; /* user supplied struct for error functions */
  181734. png_rw_ptr write_data_fn; /* function for writing output data */
  181735. png_rw_ptr read_data_fn; /* function for reading input data */
  181736. png_voidp io_ptr; /* ptr to application struct for I/O functions */
  181737. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  181738. png_user_transform_ptr read_user_transform_fn; /* user read transform */
  181739. #endif
  181740. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  181741. png_user_transform_ptr write_user_transform_fn; /* user write transform */
  181742. #endif
  181743. /* These were added in libpng-1.0.2 */
  181744. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  181745. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  181746. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  181747. png_voidp user_transform_ptr; /* user supplied struct for user transform */
  181748. png_byte user_transform_depth; /* bit depth of user transformed pixels */
  181749. png_byte user_transform_channels; /* channels in user transformed pixels */
  181750. #endif
  181751. #endif
  181752. png_uint_32 mode; /* tells us where we are in the PNG file */
  181753. png_uint_32 flags; /* flags indicating various things to libpng */
  181754. png_uint_32 transformations; /* which transformations to perform */
  181755. z_stream zstream; /* pointer to decompression structure (below) */
  181756. png_bytep zbuf; /* buffer for zlib */
  181757. png_size_t zbuf_size; /* size of zbuf */
  181758. int zlib_level; /* holds zlib compression level */
  181759. int zlib_method; /* holds zlib compression method */
  181760. int zlib_window_bits; /* holds zlib compression window bits */
  181761. int zlib_mem_level; /* holds zlib compression memory level */
  181762. int zlib_strategy; /* holds zlib compression strategy */
  181763. png_uint_32 width; /* width of image in pixels */
  181764. png_uint_32 height; /* height of image in pixels */
  181765. png_uint_32 num_rows; /* number of rows in current pass */
  181766. png_uint_32 usr_width; /* width of row at start of write */
  181767. png_uint_32 rowbytes; /* size of row in bytes */
  181768. png_uint_32 irowbytes; /* size of current interlaced row in bytes */
  181769. png_uint_32 iwidth; /* width of current interlaced row in pixels */
  181770. png_uint_32 row_number; /* current row in interlace pass */
  181771. png_bytep prev_row; /* buffer to save previous (unfiltered) row */
  181772. png_bytep row_buf; /* buffer to save current (unfiltered) row */
  181773. png_bytep sub_row; /* buffer to save "sub" row when filtering */
  181774. png_bytep up_row; /* buffer to save "up" row when filtering */
  181775. png_bytep avg_row; /* buffer to save "avg" row when filtering */
  181776. png_bytep paeth_row; /* buffer to save "Paeth" row when filtering */
  181777. png_row_info row_info; /* used for transformation routines */
  181778. png_uint_32 idat_size; /* current IDAT size for read */
  181779. png_uint_32 crc; /* current chunk CRC value */
  181780. png_colorp palette; /* palette from the input file */
  181781. png_uint_16 num_palette; /* number of color entries in palette */
  181782. png_uint_16 num_trans; /* number of transparency values */
  181783. png_byte chunk_name[5]; /* null-terminated name of current chunk */
  181784. png_byte compression; /* file compression type (always 0) */
  181785. png_byte filter; /* file filter type (always 0) */
  181786. png_byte interlaced; /* PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  181787. png_byte pass; /* current interlace pass (0 - 6) */
  181788. png_byte do_filter; /* row filter flags (see PNG_FILTER_ below ) */
  181789. png_byte color_type; /* color type of file */
  181790. png_byte bit_depth; /* bit depth of file */
  181791. png_byte usr_bit_depth; /* bit depth of users row */
  181792. png_byte pixel_depth; /* number of bits per pixel */
  181793. png_byte channels; /* number of channels in file */
  181794. png_byte usr_channels; /* channels at start of write */
  181795. png_byte sig_bytes; /* magic bytes read/written from start of file */
  181796. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  181797. #ifdef PNG_LEGACY_SUPPORTED
  181798. png_byte filler; /* filler byte for pixel expansion */
  181799. #else
  181800. png_uint_16 filler; /* filler bytes for pixel expansion */
  181801. #endif
  181802. #endif
  181803. #if defined(PNG_bKGD_SUPPORTED)
  181804. png_byte background_gamma_type;
  181805. # ifdef PNG_FLOATING_POINT_SUPPORTED
  181806. float background_gamma;
  181807. # endif
  181808. png_color_16 background; /* background color in screen gamma space */
  181809. #if defined(PNG_READ_GAMMA_SUPPORTED)
  181810. png_color_16 background_1; /* background normalized to gamma 1.0 */
  181811. #endif
  181812. #endif /* PNG_bKGD_SUPPORTED */
  181813. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  181814. png_flush_ptr output_flush_fn;/* Function for flushing output */
  181815. png_uint_32 flush_dist; /* how many rows apart to flush, 0 - no flush */
  181816. png_uint_32 flush_rows; /* number of rows written since last flush */
  181817. #endif
  181818. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  181819. int gamma_shift; /* number of "insignificant" bits 16-bit gamma */
  181820. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181821. float gamma; /* file gamma value */
  181822. float screen_gamma; /* screen gamma value (display_exponent) */
  181823. #endif
  181824. #endif
  181825. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  181826. png_bytep gamma_table; /* gamma table for 8-bit depth files */
  181827. png_bytep gamma_from_1; /* converts from 1.0 to screen */
  181828. png_bytep gamma_to_1; /* converts from file to 1.0 */
  181829. png_uint_16pp gamma_16_table; /* gamma table for 16-bit depth files */
  181830. png_uint_16pp gamma_16_from_1; /* converts from 1.0 to screen */
  181831. png_uint_16pp gamma_16_to_1; /* converts from file to 1.0 */
  181832. #endif
  181833. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_sBIT_SUPPORTED)
  181834. png_color_8 sig_bit; /* significant bits in each available channel */
  181835. #endif
  181836. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  181837. png_color_8 shift; /* shift for significant bit tranformation */
  181838. #endif
  181839. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) \
  181840. || defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  181841. png_bytep trans; /* transparency values for paletted files */
  181842. png_color_16 trans_values; /* transparency values for non-paletted files */
  181843. #endif
  181844. png_read_status_ptr read_row_fn; /* called after each row is decoded */
  181845. png_write_status_ptr write_row_fn; /* called after each row is encoded */
  181846. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  181847. png_progressive_info_ptr info_fn; /* called after header data fully read */
  181848. png_progressive_row_ptr row_fn; /* called after each prog. row is decoded */
  181849. png_progressive_end_ptr end_fn; /* called after image is complete */
  181850. png_bytep save_buffer_ptr; /* current location in save_buffer */
  181851. png_bytep save_buffer; /* buffer for previously read data */
  181852. png_bytep current_buffer_ptr; /* current location in current_buffer */
  181853. png_bytep current_buffer; /* buffer for recently used data */
  181854. png_uint_32 push_length; /* size of current input chunk */
  181855. png_uint_32 skip_length; /* bytes to skip in input data */
  181856. png_size_t save_buffer_size; /* amount of data now in save_buffer */
  181857. png_size_t save_buffer_max; /* total size of save_buffer */
  181858. png_size_t buffer_size; /* total amount of available input data */
  181859. png_size_t current_buffer_size; /* amount of data now in current_buffer */
  181860. int process_mode; /* what push library is currently doing */
  181861. int cur_palette; /* current push library palette index */
  181862. # if defined(PNG_TEXT_SUPPORTED)
  181863. png_size_t current_text_size; /* current size of text input data */
  181864. png_size_t current_text_left; /* how much text left to read in input */
  181865. png_charp current_text; /* current text chunk buffer */
  181866. png_charp current_text_ptr; /* current location in current_text */
  181867. # endif /* PNG_TEXT_SUPPORTED */
  181868. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  181869. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  181870. /* for the Borland special 64K segment handler */
  181871. png_bytepp offset_table_ptr;
  181872. png_bytep offset_table;
  181873. png_uint_16 offset_table_number;
  181874. png_uint_16 offset_table_count;
  181875. png_uint_16 offset_table_count_free;
  181876. #endif
  181877. #if defined(PNG_READ_DITHER_SUPPORTED)
  181878. png_bytep palette_lookup; /* lookup table for dithering */
  181879. png_bytep dither_index; /* index translation for palette files */
  181880. #endif
  181881. #if defined(PNG_READ_DITHER_SUPPORTED) || defined(PNG_hIST_SUPPORTED)
  181882. png_uint_16p hist; /* histogram */
  181883. #endif
  181884. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  181885. png_byte heuristic_method; /* heuristic for row filter selection */
  181886. png_byte num_prev_filters; /* number of weights for previous rows */
  181887. png_bytep prev_filters; /* filter type(s) of previous row(s) */
  181888. png_uint_16p filter_weights; /* weight(s) for previous line(s) */
  181889. png_uint_16p inv_filter_weights; /* 1/weight(s) for previous line(s) */
  181890. png_uint_16p filter_costs; /* relative filter calculation cost */
  181891. png_uint_16p inv_filter_costs; /* 1/relative filter calculation cost */
  181892. #endif
  181893. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  181894. png_charp time_buffer; /* String to hold RFC 1123 time text */
  181895. #endif
  181896. /* New members added in libpng-1.0.6 */
  181897. #ifdef PNG_FREE_ME_SUPPORTED
  181898. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  181899. #endif
  181900. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  181901. png_voidp user_chunk_ptr;
  181902. png_user_chunk_ptr read_user_chunk_fn; /* user read chunk handler */
  181903. #endif
  181904. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  181905. int num_chunk_list;
  181906. png_bytep chunk_list;
  181907. #endif
  181908. /* New members added in libpng-1.0.3 */
  181909. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  181910. png_byte rgb_to_gray_status;
  181911. /* These were changed from png_byte in libpng-1.0.6 */
  181912. png_uint_16 rgb_to_gray_red_coeff;
  181913. png_uint_16 rgb_to_gray_green_coeff;
  181914. png_uint_16 rgb_to_gray_blue_coeff;
  181915. #endif
  181916. /* New member added in libpng-1.0.4 (renamed in 1.0.9) */
  181917. #if defined(PNG_MNG_FEATURES_SUPPORTED) || \
  181918. defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  181919. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  181920. /* changed from png_byte to png_uint_32 at version 1.2.0 */
  181921. #ifdef PNG_1_0_X
  181922. png_byte mng_features_permitted;
  181923. #else
  181924. png_uint_32 mng_features_permitted;
  181925. #endif /* PNG_1_0_X */
  181926. #endif
  181927. /* New member added in libpng-1.0.7 */
  181928. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  181929. png_fixed_point int_gamma;
  181930. #endif
  181931. /* New member added in libpng-1.0.9, ifdef'ed out in 1.0.12, enabled in 1.2.0 */
  181932. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  181933. png_byte filter_type;
  181934. #endif
  181935. #if defined(PNG_1_0_X)
  181936. /* New member added in libpng-1.0.10, ifdef'ed out in 1.2.0 */
  181937. png_uint_32 row_buf_size;
  181938. #endif
  181939. /* New members added in libpng-1.2.0 */
  181940. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  181941. # if !defined(PNG_1_0_X)
  181942. # if defined(PNG_MMX_CODE_SUPPORTED)
  181943. png_byte mmx_bitdepth_threshold;
  181944. png_uint_32 mmx_rowbytes_threshold;
  181945. # endif
  181946. png_uint_32 asm_flags;
  181947. # endif
  181948. #endif
  181949. /* New members added in libpng-1.0.2 but first enabled by default in 1.2.0 */
  181950. #ifdef PNG_USER_MEM_SUPPORTED
  181951. png_voidp mem_ptr; /* user supplied struct for mem functions */
  181952. png_malloc_ptr malloc_fn; /* function for allocating memory */
  181953. png_free_ptr free_fn; /* function for freeing memory */
  181954. #endif
  181955. /* New member added in libpng-1.0.13 and 1.2.0 */
  181956. png_bytep big_row_buf; /* buffer to save current (unfiltered) row */
  181957. #if defined(PNG_READ_DITHER_SUPPORTED)
  181958. /* The following three members were added at version 1.0.14 and 1.2.4 */
  181959. png_bytep dither_sort; /* working sort array */
  181960. png_bytep index_to_palette; /* where the original index currently is */
  181961. /* in the palette */
  181962. png_bytep palette_to_index; /* which original index points to this */
  181963. /* palette color */
  181964. #endif
  181965. /* New members added in libpng-1.0.16 and 1.2.6 */
  181966. png_byte compression_type;
  181967. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  181968. png_uint_32 user_width_max;
  181969. png_uint_32 user_height_max;
  181970. #endif
  181971. /* New member added in libpng-1.0.25 and 1.2.17 */
  181972. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  181973. /* storage for unknown chunk that the library doesn't recognize. */
  181974. png_unknown_chunk unknown_chunk;
  181975. #endif
  181976. };
  181977. /* This triggers a compiler error in png.c, if png.c and png.h
  181978. * do not agree upon the version number.
  181979. */
  181980. typedef png_structp version_1_2_21;
  181981. typedef png_struct FAR * FAR * png_structpp;
  181982. /* Here are the function definitions most commonly used. This is not
  181983. * the place to find out how to use libpng. See libpng.txt for the
  181984. * full explanation, see example.c for the summary. This just provides
  181985. * a simple one line description of the use of each function.
  181986. */
  181987. /* Returns the version number of the library */
  181988. extern PNG_EXPORT(png_uint_32,png_access_version_number) PNGARG((void));
  181989. /* Tell lib we have already handled the first <num_bytes> magic bytes.
  181990. * Handling more than 8 bytes from the beginning of the file is an error.
  181991. */
  181992. extern PNG_EXPORT(void,png_set_sig_bytes) PNGARG((png_structp png_ptr,
  181993. int num_bytes));
  181994. /* Check sig[start] through sig[start + num_to_check - 1] to see if it's a
  181995. * PNG file. Returns zero if the supplied bytes match the 8-byte PNG
  181996. * signature, and non-zero otherwise. Having num_to_check == 0 or
  181997. * start > 7 will always fail (ie return non-zero).
  181998. */
  181999. extern PNG_EXPORT(int,png_sig_cmp) PNGARG((png_bytep sig, png_size_t start,
  182000. png_size_t num_to_check));
  182001. /* Simple signature checking function. This is the same as calling
  182002. * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n).
  182003. */
  182004. extern PNG_EXPORT(int,png_check_sig) PNGARG((png_bytep sig, int num));
  182005. /* Allocate and initialize png_ptr struct for reading, and any other memory. */
  182006. extern PNG_EXPORT(png_structp,png_create_read_struct)
  182007. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182008. png_error_ptr error_fn, png_error_ptr warn_fn));
  182009. /* Allocate and initialize png_ptr struct for writing, and any other memory */
  182010. extern PNG_EXPORT(png_structp,png_create_write_struct)
  182011. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182012. png_error_ptr error_fn, png_error_ptr warn_fn));
  182013. #ifdef PNG_WRITE_SUPPORTED
  182014. extern PNG_EXPORT(png_uint_32,png_get_compression_buffer_size)
  182015. PNGARG((png_structp png_ptr));
  182016. #endif
  182017. #ifdef PNG_WRITE_SUPPORTED
  182018. extern PNG_EXPORT(void,png_set_compression_buffer_size)
  182019. PNGARG((png_structp png_ptr, png_uint_32 size));
  182020. #endif
  182021. /* Reset the compression stream */
  182022. extern PNG_EXPORT(int,png_reset_zstream) PNGARG((png_structp png_ptr));
  182023. /* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */
  182024. #ifdef PNG_USER_MEM_SUPPORTED
  182025. extern PNG_EXPORT(png_structp,png_create_read_struct_2)
  182026. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182027. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  182028. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  182029. extern PNG_EXPORT(png_structp,png_create_write_struct_2)
  182030. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182031. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  182032. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  182033. #endif
  182034. /* Write a PNG chunk - size, type, (optional) data, CRC. */
  182035. extern PNG_EXPORT(void,png_write_chunk) PNGARG((png_structp png_ptr,
  182036. png_bytep chunk_name, png_bytep data, png_size_t length));
  182037. /* Write the start of a PNG chunk - length and chunk name. */
  182038. extern PNG_EXPORT(void,png_write_chunk_start) PNGARG((png_structp png_ptr,
  182039. png_bytep chunk_name, png_uint_32 length));
  182040. /* Write the data of a PNG chunk started with png_write_chunk_start(). */
  182041. extern PNG_EXPORT(void,png_write_chunk_data) PNGARG((png_structp png_ptr,
  182042. png_bytep data, png_size_t length));
  182043. /* Finish a chunk started with png_write_chunk_start() (includes CRC). */
  182044. extern PNG_EXPORT(void,png_write_chunk_end) PNGARG((png_structp png_ptr));
  182045. /* Allocate and initialize the info structure */
  182046. extern PNG_EXPORT(png_infop,png_create_info_struct)
  182047. PNGARG((png_structp png_ptr));
  182048. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182049. /* Initialize the info structure (old interface - DEPRECATED) */
  182050. extern PNG_EXPORT(void,png_info_init) PNGARG((png_infop info_ptr));
  182051. #undef png_info_init
  182052. #define png_info_init(info_ptr) png_info_init_3(&info_ptr,\
  182053. png_sizeof(png_info));
  182054. #endif
  182055. extern PNG_EXPORT(void,png_info_init_3) PNGARG((png_infopp info_ptr,
  182056. png_size_t png_info_struct_size));
  182057. /* Writes all the PNG information before the image. */
  182058. extern PNG_EXPORT(void,png_write_info_before_PLTE) PNGARG((png_structp png_ptr,
  182059. png_infop info_ptr));
  182060. extern PNG_EXPORT(void,png_write_info) PNGARG((png_structp png_ptr,
  182061. png_infop info_ptr));
  182062. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182063. /* read the information before the actual image data. */
  182064. extern PNG_EXPORT(void,png_read_info) PNGARG((png_structp png_ptr,
  182065. png_infop info_ptr));
  182066. #endif
  182067. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  182068. extern PNG_EXPORT(png_charp,png_convert_to_rfc1123)
  182069. PNGARG((png_structp png_ptr, png_timep ptime));
  182070. #endif
  182071. #if !defined(_WIN32_WCE)
  182072. /* "time.h" functions are not supported on WindowsCE */
  182073. #if defined(PNG_WRITE_tIME_SUPPORTED)
  182074. /* convert from a struct tm to png_time */
  182075. extern PNG_EXPORT(void,png_convert_from_struct_tm) PNGARG((png_timep ptime,
  182076. struct tm FAR * ttime));
  182077. /* convert from time_t to png_time. Uses gmtime() */
  182078. extern PNG_EXPORT(void,png_convert_from_time_t) PNGARG((png_timep ptime,
  182079. time_t ttime));
  182080. #endif /* PNG_WRITE_tIME_SUPPORTED */
  182081. #endif /* _WIN32_WCE */
  182082. #if defined(PNG_READ_EXPAND_SUPPORTED)
  182083. /* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */
  182084. extern PNG_EXPORT(void,png_set_expand) PNGARG((png_structp png_ptr));
  182085. #if !defined(PNG_1_0_X)
  182086. extern PNG_EXPORT(void,png_set_expand_gray_1_2_4_to_8) PNGARG((png_structp
  182087. png_ptr));
  182088. #endif
  182089. extern PNG_EXPORT(void,png_set_palette_to_rgb) PNGARG((png_structp png_ptr));
  182090. extern PNG_EXPORT(void,png_set_tRNS_to_alpha) PNGARG((png_structp png_ptr));
  182091. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182092. /* Deprecated */
  182093. extern PNG_EXPORT(void,png_set_gray_1_2_4_to_8) PNGARG((png_structp png_ptr));
  182094. #endif
  182095. #endif
  182096. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  182097. /* Use blue, green, red order for pixels. */
  182098. extern PNG_EXPORT(void,png_set_bgr) PNGARG((png_structp png_ptr));
  182099. #endif
  182100. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  182101. /* Expand the grayscale to 24-bit RGB if necessary. */
  182102. extern PNG_EXPORT(void,png_set_gray_to_rgb) PNGARG((png_structp png_ptr));
  182103. #endif
  182104. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  182105. /* Reduce RGB to grayscale. */
  182106. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182107. extern PNG_EXPORT(void,png_set_rgb_to_gray) PNGARG((png_structp png_ptr,
  182108. int error_action, double red, double green ));
  182109. #endif
  182110. extern PNG_EXPORT(void,png_set_rgb_to_gray_fixed) PNGARG((png_structp png_ptr,
  182111. int error_action, png_fixed_point red, png_fixed_point green ));
  182112. extern PNG_EXPORT(png_byte,png_get_rgb_to_gray_status) PNGARG((png_structp
  182113. png_ptr));
  182114. #endif
  182115. extern PNG_EXPORT(void,png_build_grayscale_palette) PNGARG((int bit_depth,
  182116. png_colorp palette));
  182117. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  182118. extern PNG_EXPORT(void,png_set_strip_alpha) PNGARG((png_structp png_ptr));
  182119. #endif
  182120. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  182121. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  182122. extern PNG_EXPORT(void,png_set_swap_alpha) PNGARG((png_structp png_ptr));
  182123. #endif
  182124. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  182125. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  182126. extern PNG_EXPORT(void,png_set_invert_alpha) PNGARG((png_structp png_ptr));
  182127. #endif
  182128. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  182129. /* Add a filler byte to 8-bit Gray or 24-bit RGB images. */
  182130. extern PNG_EXPORT(void,png_set_filler) PNGARG((png_structp png_ptr,
  182131. png_uint_32 filler, int flags));
  182132. /* The values of the PNG_FILLER_ defines should NOT be changed */
  182133. #define PNG_FILLER_BEFORE 0
  182134. #define PNG_FILLER_AFTER 1
  182135. /* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
  182136. #if !defined(PNG_1_0_X)
  182137. extern PNG_EXPORT(void,png_set_add_alpha) PNGARG((png_structp png_ptr,
  182138. png_uint_32 filler, int flags));
  182139. #endif
  182140. #endif /* PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED */
  182141. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  182142. /* Swap bytes in 16-bit depth files. */
  182143. extern PNG_EXPORT(void,png_set_swap) PNGARG((png_structp png_ptr));
  182144. #endif
  182145. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  182146. /* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */
  182147. extern PNG_EXPORT(void,png_set_packing) PNGARG((png_structp png_ptr));
  182148. #endif
  182149. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  182150. /* Swap packing order of pixels in bytes. */
  182151. extern PNG_EXPORT(void,png_set_packswap) PNGARG((png_structp png_ptr));
  182152. #endif
  182153. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  182154. /* Converts files to legal bit depths. */
  182155. extern PNG_EXPORT(void,png_set_shift) PNGARG((png_structp png_ptr,
  182156. png_color_8p true_bits));
  182157. #endif
  182158. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  182159. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  182160. /* Have the code handle the interlacing. Returns the number of passes. */
  182161. extern PNG_EXPORT(int,png_set_interlace_handling) PNGARG((png_structp png_ptr));
  182162. #endif
  182163. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  182164. /* Invert monochrome files */
  182165. extern PNG_EXPORT(void,png_set_invert_mono) PNGARG((png_structp png_ptr));
  182166. #endif
  182167. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  182168. /* Handle alpha and tRNS by replacing with a background color. */
  182169. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182170. extern PNG_EXPORT(void,png_set_background) PNGARG((png_structp png_ptr,
  182171. png_color_16p background_color, int background_gamma_code,
  182172. int need_expand, double background_gamma));
  182173. #endif
  182174. #define PNG_BACKGROUND_GAMMA_UNKNOWN 0
  182175. #define PNG_BACKGROUND_GAMMA_SCREEN 1
  182176. #define PNG_BACKGROUND_GAMMA_FILE 2
  182177. #define PNG_BACKGROUND_GAMMA_UNIQUE 3
  182178. #endif
  182179. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  182180. /* strip the second byte of information from a 16-bit depth file. */
  182181. extern PNG_EXPORT(void,png_set_strip_16) PNGARG((png_structp png_ptr));
  182182. #endif
  182183. #if defined(PNG_READ_DITHER_SUPPORTED)
  182184. /* Turn on dithering, and reduce the palette to the number of colors available. */
  182185. extern PNG_EXPORT(void,png_set_dither) PNGARG((png_structp png_ptr,
  182186. png_colorp palette, int num_palette, int maximum_colors,
  182187. png_uint_16p histogram, int full_dither));
  182188. #endif
  182189. #if defined(PNG_READ_GAMMA_SUPPORTED)
  182190. /* Handle gamma correction. Screen_gamma=(display_exponent) */
  182191. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182192. extern PNG_EXPORT(void,png_set_gamma) PNGARG((png_structp png_ptr,
  182193. double screen_gamma, double default_file_gamma));
  182194. #endif
  182195. #endif
  182196. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182197. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  182198. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  182199. /* Permit or disallow empty PLTE (0: not permitted, 1: permitted) */
  182200. /* Deprecated and will be removed. Use png_permit_mng_features() instead. */
  182201. extern PNG_EXPORT(void,png_permit_empty_plte) PNGARG((png_structp png_ptr,
  182202. int empty_plte_permitted));
  182203. #endif
  182204. #endif
  182205. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  182206. /* Set how many lines between output flushes - 0 for no flushing */
  182207. extern PNG_EXPORT(void,png_set_flush) PNGARG((png_structp png_ptr, int nrows));
  182208. /* Flush the current PNG output buffer */
  182209. extern PNG_EXPORT(void,png_write_flush) PNGARG((png_structp png_ptr));
  182210. #endif
  182211. /* optional update palette with requested transformations */
  182212. extern PNG_EXPORT(void,png_start_read_image) PNGARG((png_structp png_ptr));
  182213. /* optional call to update the users info structure */
  182214. extern PNG_EXPORT(void,png_read_update_info) PNGARG((png_structp png_ptr,
  182215. png_infop info_ptr));
  182216. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182217. /* read one or more rows of image data. */
  182218. extern PNG_EXPORT(void,png_read_rows) PNGARG((png_structp png_ptr,
  182219. png_bytepp row, png_bytepp display_row, png_uint_32 num_rows));
  182220. #endif
  182221. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182222. /* read a row of data. */
  182223. extern PNG_EXPORT(void,png_read_row) PNGARG((png_structp png_ptr,
  182224. png_bytep row,
  182225. png_bytep display_row));
  182226. #endif
  182227. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182228. /* read the whole image into memory at once. */
  182229. extern PNG_EXPORT(void,png_read_image) PNGARG((png_structp png_ptr,
  182230. png_bytepp image));
  182231. #endif
  182232. /* write a row of image data */
  182233. extern PNG_EXPORT(void,png_write_row) PNGARG((png_structp png_ptr,
  182234. png_bytep row));
  182235. /* write a few rows of image data */
  182236. extern PNG_EXPORT(void,png_write_rows) PNGARG((png_structp png_ptr,
  182237. png_bytepp row, png_uint_32 num_rows));
  182238. /* write the image data */
  182239. extern PNG_EXPORT(void,png_write_image) PNGARG((png_structp png_ptr,
  182240. png_bytepp image));
  182241. /* writes the end of the PNG file. */
  182242. extern PNG_EXPORT(void,png_write_end) PNGARG((png_structp png_ptr,
  182243. png_infop info_ptr));
  182244. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182245. /* read the end of the PNG file. */
  182246. extern PNG_EXPORT(void,png_read_end) PNGARG((png_structp png_ptr,
  182247. png_infop info_ptr));
  182248. #endif
  182249. /* free any memory associated with the png_info_struct */
  182250. extern PNG_EXPORT(void,png_destroy_info_struct) PNGARG((png_structp png_ptr,
  182251. png_infopp info_ptr_ptr));
  182252. /* free any memory associated with the png_struct and the png_info_structs */
  182253. extern PNG_EXPORT(void,png_destroy_read_struct) PNGARG((png_structpp
  182254. png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr));
  182255. /* free all memory used by the read (old method - NOT DLL EXPORTED) */
  182256. extern void png_read_destroy PNGARG((png_structp png_ptr, png_infop info_ptr,
  182257. png_infop end_info_ptr));
  182258. /* free any memory associated with the png_struct and the png_info_structs */
  182259. extern PNG_EXPORT(void,png_destroy_write_struct)
  182260. PNGARG((png_structpp png_ptr_ptr, png_infopp info_ptr_ptr));
  182261. /* free any memory used in png_ptr struct (old method - NOT DLL EXPORTED) */
  182262. extern void png_write_destroy PNGARG((png_structp png_ptr));
  182263. /* set the libpng method of handling chunk CRC errors */
  182264. extern PNG_EXPORT(void,png_set_crc_action) PNGARG((png_structp png_ptr,
  182265. int crit_action, int ancil_action));
  182266. /* Values for png_set_crc_action() to say how to handle CRC errors in
  182267. * ancillary and critical chunks, and whether to use the data contained
  182268. * therein. Note that it is impossible to "discard" data in a critical
  182269. * chunk. For versions prior to 0.90, the action was always error/quit,
  182270. * whereas in version 0.90 and later, the action for CRC errors in ancillary
  182271. * chunks is warn/discard. These values should NOT be changed.
  182272. *
  182273. * value action:critical action:ancillary
  182274. */
  182275. #define PNG_CRC_DEFAULT 0 /* error/quit warn/discard data */
  182276. #define PNG_CRC_ERROR_QUIT 1 /* error/quit error/quit */
  182277. #define PNG_CRC_WARN_DISCARD 2 /* (INVALID) warn/discard data */
  182278. #define PNG_CRC_WARN_USE 3 /* warn/use data warn/use data */
  182279. #define PNG_CRC_QUIET_USE 4 /* quiet/use data quiet/use data */
  182280. #define PNG_CRC_NO_CHANGE 5 /* use current value use current value */
  182281. /* These functions give the user control over the scan-line filtering in
  182282. * libpng and the compression methods used by zlib. These functions are
  182283. * mainly useful for testing, as the defaults should work with most users.
  182284. * Those users who are tight on memory or want faster performance at the
  182285. * expense of compression can modify them. See the compression library
  182286. * header file (zlib.h) for an explination of the compression functions.
  182287. */
  182288. /* set the filtering method(s) used by libpng. Currently, the only valid
  182289. * value for "method" is 0.
  182290. */
  182291. extern PNG_EXPORT(void,png_set_filter) PNGARG((png_structp png_ptr, int method,
  182292. int filters));
  182293. /* Flags for png_set_filter() to say which filters to use. The flags
  182294. * are chosen so that they don't conflict with real filter types
  182295. * below, in case they are supplied instead of the #defined constants.
  182296. * These values should NOT be changed.
  182297. */
  182298. #define PNG_NO_FILTERS 0x00
  182299. #define PNG_FILTER_NONE 0x08
  182300. #define PNG_FILTER_SUB 0x10
  182301. #define PNG_FILTER_UP 0x20
  182302. #define PNG_FILTER_AVG 0x40
  182303. #define PNG_FILTER_PAETH 0x80
  182304. #define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \
  182305. PNG_FILTER_AVG | PNG_FILTER_PAETH)
  182306. /* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now.
  182307. * These defines should NOT be changed.
  182308. */
  182309. #define PNG_FILTER_VALUE_NONE 0
  182310. #define PNG_FILTER_VALUE_SUB 1
  182311. #define PNG_FILTER_VALUE_UP 2
  182312. #define PNG_FILTER_VALUE_AVG 3
  182313. #define PNG_FILTER_VALUE_PAETH 4
  182314. #define PNG_FILTER_VALUE_LAST 5
  182315. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* EXPERIMENTAL */
  182316. /* The "heuristic_method" is given by one of the PNG_FILTER_HEURISTIC_
  182317. * defines, either the default (minimum-sum-of-absolute-differences), or
  182318. * the experimental method (weighted-minimum-sum-of-absolute-differences).
  182319. *
  182320. * Weights are factors >= 1.0, indicating how important it is to keep the
  182321. * filter type consistent between rows. Larger numbers mean the current
  182322. * filter is that many times as likely to be the same as the "num_weights"
  182323. * previous filters. This is cumulative for each previous row with a weight.
  182324. * There needs to be "num_weights" values in "filter_weights", or it can be
  182325. * NULL if the weights aren't being specified. Weights have no influence on
  182326. * the selection of the first row filter. Well chosen weights can (in theory)
  182327. * improve the compression for a given image.
  182328. *
  182329. * Costs are factors >= 1.0 indicating the relative decoding costs of a
  182330. * filter type. Higher costs indicate more decoding expense, and are
  182331. * therefore less likely to be selected over a filter with lower computational
  182332. * costs. There needs to be a value in "filter_costs" for each valid filter
  182333. * type (given by PNG_FILTER_VALUE_LAST), or it can be NULL if you aren't
  182334. * setting the costs. Costs try to improve the speed of decompression without
  182335. * unduly increasing the compressed image size.
  182336. *
  182337. * A negative weight or cost indicates the default value is to be used, and
  182338. * values in the range [0.0, 1.0) indicate the value is to remain unchanged.
  182339. * The default values for both weights and costs are currently 1.0, but may
  182340. * change if good general weighting/cost heuristics can be found. If both
  182341. * the weights and costs are set to 1.0, this degenerates the WEIGHTED method
  182342. * to the UNWEIGHTED method, but with added encoding time/computation.
  182343. */
  182344. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182345. extern PNG_EXPORT(void,png_set_filter_heuristics) PNGARG((png_structp png_ptr,
  182346. int heuristic_method, int num_weights, png_doublep filter_weights,
  182347. png_doublep filter_costs));
  182348. #endif
  182349. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  182350. /* Heuristic used for row filter selection. These defines should NOT be
  182351. * changed.
  182352. */
  182353. #define PNG_FILTER_HEURISTIC_DEFAULT 0 /* Currently "UNWEIGHTED" */
  182354. #define PNG_FILTER_HEURISTIC_UNWEIGHTED 1 /* Used by libpng < 0.95 */
  182355. #define PNG_FILTER_HEURISTIC_WEIGHTED 2 /* Experimental feature */
  182356. #define PNG_FILTER_HEURISTIC_LAST 3 /* Not a valid value */
  182357. /* Set the library compression level. Currently, valid values range from
  182358. * 0 - 9, corresponding directly to the zlib compression levels 0 - 9
  182359. * (0 - no compression, 9 - "maximal" compression). Note that tests have
  182360. * shown that zlib compression levels 3-6 usually perform as well as level 9
  182361. * for PNG images, and do considerably fewer caclulations. In the future,
  182362. * these values may not correspond directly to the zlib compression levels.
  182363. */
  182364. extern PNG_EXPORT(void,png_set_compression_level) PNGARG((png_structp png_ptr,
  182365. int level));
  182366. extern PNG_EXPORT(void,png_set_compression_mem_level)
  182367. PNGARG((png_structp png_ptr, int mem_level));
  182368. extern PNG_EXPORT(void,png_set_compression_strategy)
  182369. PNGARG((png_structp png_ptr, int strategy));
  182370. extern PNG_EXPORT(void,png_set_compression_window_bits)
  182371. PNGARG((png_structp png_ptr, int window_bits));
  182372. extern PNG_EXPORT(void,png_set_compression_method) PNGARG((png_structp png_ptr,
  182373. int method));
  182374. /* These next functions are called for input/output, memory, and error
  182375. * handling. They are in the file pngrio.c, pngwio.c, and pngerror.c,
  182376. * and call standard C I/O routines such as fread(), fwrite(), and
  182377. * fprintf(). These functions can be made to use other I/O routines
  182378. * at run time for those applications that need to handle I/O in a
  182379. * different manner by calling png_set_???_fn(). See libpng.txt for
  182380. * more information.
  182381. */
  182382. #if !defined(PNG_NO_STDIO)
  182383. /* Initialize the input/output for the PNG file to the default functions. */
  182384. extern PNG_EXPORT(void,png_init_io) PNGARG((png_structp png_ptr, png_FILE_p fp));
  182385. #endif
  182386. /* Replace the (error and abort), and warning functions with user
  182387. * supplied functions. If no messages are to be printed you must still
  182388. * write and use replacement functions. The replacement error_fn should
  182389. * still do a longjmp to the last setjmp location if you are using this
  182390. * method of error handling. If error_fn or warning_fn is NULL, the
  182391. * default function will be used.
  182392. */
  182393. extern PNG_EXPORT(void,png_set_error_fn) PNGARG((png_structp png_ptr,
  182394. png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn));
  182395. /* Return the user pointer associated with the error functions */
  182396. extern PNG_EXPORT(png_voidp,png_get_error_ptr) PNGARG((png_structp png_ptr));
  182397. /* Replace the default data output functions with a user supplied one(s).
  182398. * If buffered output is not used, then output_flush_fn can be set to NULL.
  182399. * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time
  182400. * output_flush_fn will be ignored (and thus can be NULL).
  182401. */
  182402. extern PNG_EXPORT(void,png_set_write_fn) PNGARG((png_structp png_ptr,
  182403. png_voidp io_ptr, png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn));
  182404. /* Replace the default data input function with a user supplied one. */
  182405. extern PNG_EXPORT(void,png_set_read_fn) PNGARG((png_structp png_ptr,
  182406. png_voidp io_ptr, png_rw_ptr read_data_fn));
  182407. /* Return the user pointer associated with the I/O functions */
  182408. extern PNG_EXPORT(png_voidp,png_get_io_ptr) PNGARG((png_structp png_ptr));
  182409. extern PNG_EXPORT(void,png_set_read_status_fn) PNGARG((png_structp png_ptr,
  182410. png_read_status_ptr read_row_fn));
  182411. extern PNG_EXPORT(void,png_set_write_status_fn) PNGARG((png_structp png_ptr,
  182412. png_write_status_ptr write_row_fn));
  182413. #ifdef PNG_USER_MEM_SUPPORTED
  182414. /* Replace the default memory allocation functions with user supplied one(s). */
  182415. extern PNG_EXPORT(void,png_set_mem_fn) PNGARG((png_structp png_ptr,
  182416. png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  182417. /* Return the user pointer associated with the memory functions */
  182418. extern PNG_EXPORT(png_voidp,png_get_mem_ptr) PNGARG((png_structp png_ptr));
  182419. #endif
  182420. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182421. defined(PNG_LEGACY_SUPPORTED)
  182422. extern PNG_EXPORT(void,png_set_read_user_transform_fn) PNGARG((png_structp
  182423. png_ptr, png_user_transform_ptr read_user_transform_fn));
  182424. #endif
  182425. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  182426. defined(PNG_LEGACY_SUPPORTED)
  182427. extern PNG_EXPORT(void,png_set_write_user_transform_fn) PNGARG((png_structp
  182428. png_ptr, png_user_transform_ptr write_user_transform_fn));
  182429. #endif
  182430. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182431. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  182432. defined(PNG_LEGACY_SUPPORTED)
  182433. extern PNG_EXPORT(void,png_set_user_transform_info) PNGARG((png_structp
  182434. png_ptr, png_voidp user_transform_ptr, int user_transform_depth,
  182435. int user_transform_channels));
  182436. /* Return the user pointer associated with the user transform functions */
  182437. extern PNG_EXPORT(png_voidp,png_get_user_transform_ptr)
  182438. PNGARG((png_structp png_ptr));
  182439. #endif
  182440. #ifdef PNG_USER_CHUNKS_SUPPORTED
  182441. extern PNG_EXPORT(void,png_set_read_user_chunk_fn) PNGARG((png_structp png_ptr,
  182442. png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn));
  182443. extern PNG_EXPORT(png_voidp,png_get_user_chunk_ptr) PNGARG((png_structp
  182444. png_ptr));
  182445. #endif
  182446. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182447. /* Sets the function callbacks for the push reader, and a pointer to a
  182448. * user-defined structure available to the callback functions.
  182449. */
  182450. extern PNG_EXPORT(void,png_set_progressive_read_fn) PNGARG((png_structp png_ptr,
  182451. png_voidp progressive_ptr,
  182452. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  182453. png_progressive_end_ptr end_fn));
  182454. /* returns the user pointer associated with the push read functions */
  182455. extern PNG_EXPORT(png_voidp,png_get_progressive_ptr)
  182456. PNGARG((png_structp png_ptr));
  182457. /* function to be called when data becomes available */
  182458. extern PNG_EXPORT(void,png_process_data) PNGARG((png_structp png_ptr,
  182459. png_infop info_ptr, png_bytep buffer, png_size_t buffer_size));
  182460. /* function that combines rows. Not very much different than the
  182461. * png_combine_row() call. Is this even used?????
  182462. */
  182463. extern PNG_EXPORT(void,png_progressive_combine_row) PNGARG((png_structp png_ptr,
  182464. png_bytep old_row, png_bytep new_row));
  182465. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  182466. extern PNG_EXPORT(png_voidp,png_malloc) PNGARG((png_structp png_ptr,
  182467. png_uint_32 size));
  182468. #if defined(PNG_1_0_X)
  182469. # define png_malloc_warn png_malloc
  182470. #else
  182471. /* Added at libpng version 1.2.4 */
  182472. extern PNG_EXPORT(png_voidp,png_malloc_warn) PNGARG((png_structp png_ptr,
  182473. png_uint_32 size));
  182474. #endif
  182475. /* frees a pointer allocated by png_malloc() */
  182476. extern PNG_EXPORT(void,png_free) PNGARG((png_structp png_ptr, png_voidp ptr));
  182477. #if defined(PNG_1_0_X)
  182478. /* Function to allocate memory for zlib. */
  182479. extern PNG_EXPORT(voidpf,png_zalloc) PNGARG((voidpf png_ptr, uInt items,
  182480. uInt size));
  182481. /* Function to free memory for zlib */
  182482. extern PNG_EXPORT(void,png_zfree) PNGARG((voidpf png_ptr, voidpf ptr));
  182483. #endif
  182484. /* Free data that was allocated internally */
  182485. extern PNG_EXPORT(void,png_free_data) PNGARG((png_structp png_ptr,
  182486. png_infop info_ptr, png_uint_32 free_me, int num));
  182487. #ifdef PNG_FREE_ME_SUPPORTED
  182488. /* Reassign responsibility for freeing existing data, whether allocated
  182489. * by libpng or by the application */
  182490. extern PNG_EXPORT(void,png_data_freer) PNGARG((png_structp png_ptr,
  182491. png_infop info_ptr, int freer, png_uint_32 mask));
  182492. #endif
  182493. /* assignments for png_data_freer */
  182494. #define PNG_DESTROY_WILL_FREE_DATA 1
  182495. #define PNG_SET_WILL_FREE_DATA 1
  182496. #define PNG_USER_WILL_FREE_DATA 2
  182497. /* Flags for png_ptr->free_me and info_ptr->free_me */
  182498. #define PNG_FREE_HIST 0x0008
  182499. #define PNG_FREE_ICCP 0x0010
  182500. #define PNG_FREE_SPLT 0x0020
  182501. #define PNG_FREE_ROWS 0x0040
  182502. #define PNG_FREE_PCAL 0x0080
  182503. #define PNG_FREE_SCAL 0x0100
  182504. #define PNG_FREE_UNKN 0x0200
  182505. #define PNG_FREE_LIST 0x0400
  182506. #define PNG_FREE_PLTE 0x1000
  182507. #define PNG_FREE_TRNS 0x2000
  182508. #define PNG_FREE_TEXT 0x4000
  182509. #define PNG_FREE_ALL 0x7fff
  182510. #define PNG_FREE_MUL 0x4220 /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */
  182511. #ifdef PNG_USER_MEM_SUPPORTED
  182512. extern PNG_EXPORT(png_voidp,png_malloc_default) PNGARG((png_structp png_ptr,
  182513. png_uint_32 size));
  182514. extern PNG_EXPORT(void,png_free_default) PNGARG((png_structp png_ptr,
  182515. png_voidp ptr));
  182516. #endif
  182517. extern PNG_EXPORT(png_voidp,png_memcpy_check) PNGARG((png_structp png_ptr,
  182518. png_voidp s1, png_voidp s2, png_uint_32 size));
  182519. extern PNG_EXPORT(png_voidp,png_memset_check) PNGARG((png_structp png_ptr,
  182520. png_voidp s1, int value, png_uint_32 size));
  182521. #if defined(USE_FAR_KEYWORD) /* memory model conversion function */
  182522. extern void *png_far_to_near PNGARG((png_structp png_ptr,png_voidp ptr,
  182523. int check));
  182524. #endif /* USE_FAR_KEYWORD */
  182525. #ifndef PNG_NO_ERROR_TEXT
  182526. /* Fatal error in PNG image of libpng - can't continue */
  182527. extern PNG_EXPORT(void,png_error) PNGARG((png_structp png_ptr,
  182528. png_const_charp error_message));
  182529. /* The same, but the chunk name is prepended to the error string. */
  182530. extern PNG_EXPORT(void,png_chunk_error) PNGARG((png_structp png_ptr,
  182531. png_const_charp error_message));
  182532. #else
  182533. /* Fatal error in PNG image of libpng - can't continue */
  182534. extern PNG_EXPORT(void,png_err) PNGARG((png_structp png_ptr));
  182535. #endif
  182536. #ifndef PNG_NO_WARNINGS
  182537. /* Non-fatal error in libpng. Can continue, but may have a problem. */
  182538. extern PNG_EXPORT(void,png_warning) PNGARG((png_structp png_ptr,
  182539. png_const_charp warning_message));
  182540. #ifdef PNG_READ_SUPPORTED
  182541. /* Non-fatal error in libpng, chunk name is prepended to message. */
  182542. extern PNG_EXPORT(void,png_chunk_warning) PNGARG((png_structp png_ptr,
  182543. png_const_charp warning_message));
  182544. #endif /* PNG_READ_SUPPORTED */
  182545. #endif /* PNG_NO_WARNINGS */
  182546. /* The png_set_<chunk> functions are for storing values in the png_info_struct.
  182547. * Similarly, the png_get_<chunk> calls are used to read values from the
  182548. * png_info_struct, either storing the parameters in the passed variables, or
  182549. * setting pointers into the png_info_struct where the data is stored. The
  182550. * png_get_<chunk> functions return a non-zero value if the data was available
  182551. * in info_ptr, or return zero and do not change any of the parameters if the
  182552. * data was not available.
  182553. *
  182554. * These functions should be used instead of directly accessing png_info
  182555. * to avoid problems with future changes in the size and internal layout of
  182556. * png_info_struct.
  182557. */
  182558. /* Returns "flag" if chunk data is valid in info_ptr. */
  182559. extern PNG_EXPORT(png_uint_32,png_get_valid) PNGARG((png_structp png_ptr,
  182560. png_infop info_ptr, png_uint_32 flag));
  182561. /* Returns number of bytes needed to hold a transformed row. */
  182562. extern PNG_EXPORT(png_uint_32,png_get_rowbytes) PNGARG((png_structp png_ptr,
  182563. png_infop info_ptr));
  182564. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  182565. /* Returns row_pointers, which is an array of pointers to scanlines that was
  182566. returned from png_read_png(). */
  182567. extern PNG_EXPORT(png_bytepp,png_get_rows) PNGARG((png_structp png_ptr,
  182568. png_infop info_ptr));
  182569. /* Set row_pointers, which is an array of pointers to scanlines for use
  182570. by png_write_png(). */
  182571. extern PNG_EXPORT(void,png_set_rows) PNGARG((png_structp png_ptr,
  182572. png_infop info_ptr, png_bytepp row_pointers));
  182573. #endif
  182574. /* Returns number of color channels in image. */
  182575. extern PNG_EXPORT(png_byte,png_get_channels) PNGARG((png_structp png_ptr,
  182576. png_infop info_ptr));
  182577. #ifdef PNG_EASY_ACCESS_SUPPORTED
  182578. /* Returns image width in pixels. */
  182579. extern PNG_EXPORT(png_uint_32, png_get_image_width) PNGARG((png_structp
  182580. png_ptr, png_infop info_ptr));
  182581. /* Returns image height in pixels. */
  182582. extern PNG_EXPORT(png_uint_32, png_get_image_height) PNGARG((png_structp
  182583. png_ptr, png_infop info_ptr));
  182584. /* Returns image bit_depth. */
  182585. extern PNG_EXPORT(png_byte, png_get_bit_depth) PNGARG((png_structp
  182586. png_ptr, png_infop info_ptr));
  182587. /* Returns image color_type. */
  182588. extern PNG_EXPORT(png_byte, png_get_color_type) PNGARG((png_structp
  182589. png_ptr, png_infop info_ptr));
  182590. /* Returns image filter_type. */
  182591. extern PNG_EXPORT(png_byte, png_get_filter_type) PNGARG((png_structp
  182592. png_ptr, png_infop info_ptr));
  182593. /* Returns image interlace_type. */
  182594. extern PNG_EXPORT(png_byte, png_get_interlace_type) PNGARG((png_structp
  182595. png_ptr, png_infop info_ptr));
  182596. /* Returns image compression_type. */
  182597. extern PNG_EXPORT(png_byte, png_get_compression_type) PNGARG((png_structp
  182598. png_ptr, png_infop info_ptr));
  182599. /* Returns image resolution in pixels per meter, from pHYs chunk data. */
  182600. extern PNG_EXPORT(png_uint_32, png_get_pixels_per_meter) PNGARG((png_structp
  182601. png_ptr, png_infop info_ptr));
  182602. extern PNG_EXPORT(png_uint_32, png_get_x_pixels_per_meter) PNGARG((png_structp
  182603. png_ptr, png_infop info_ptr));
  182604. extern PNG_EXPORT(png_uint_32, png_get_y_pixels_per_meter) PNGARG((png_structp
  182605. png_ptr, png_infop info_ptr));
  182606. /* Returns pixel aspect ratio, computed from pHYs chunk data. */
  182607. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182608. extern PNG_EXPORT(float, png_get_pixel_aspect_ratio) PNGARG((png_structp
  182609. png_ptr, png_infop info_ptr));
  182610. #endif
  182611. /* Returns image x, y offset in pixels or microns, from oFFs chunk data. */
  182612. extern PNG_EXPORT(png_int_32, png_get_x_offset_pixels) PNGARG((png_structp
  182613. png_ptr, png_infop info_ptr));
  182614. extern PNG_EXPORT(png_int_32, png_get_y_offset_pixels) PNGARG((png_structp
  182615. png_ptr, png_infop info_ptr));
  182616. extern PNG_EXPORT(png_int_32, png_get_x_offset_microns) PNGARG((png_structp
  182617. png_ptr, png_infop info_ptr));
  182618. extern PNG_EXPORT(png_int_32, png_get_y_offset_microns) PNGARG((png_structp
  182619. png_ptr, png_infop info_ptr));
  182620. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  182621. /* Returns pointer to signature string read from PNG header */
  182622. extern PNG_EXPORT(png_bytep,png_get_signature) PNGARG((png_structp png_ptr,
  182623. png_infop info_ptr));
  182624. #if defined(PNG_bKGD_SUPPORTED)
  182625. extern PNG_EXPORT(png_uint_32,png_get_bKGD) PNGARG((png_structp png_ptr,
  182626. png_infop info_ptr, png_color_16p *background));
  182627. #endif
  182628. #if defined(PNG_bKGD_SUPPORTED)
  182629. extern PNG_EXPORT(void,png_set_bKGD) PNGARG((png_structp png_ptr,
  182630. png_infop info_ptr, png_color_16p background));
  182631. #endif
  182632. #if defined(PNG_cHRM_SUPPORTED)
  182633. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182634. extern PNG_EXPORT(png_uint_32,png_get_cHRM) PNGARG((png_structp png_ptr,
  182635. png_infop info_ptr, double *white_x, double *white_y, double *red_x,
  182636. double *red_y, double *green_x, double *green_y, double *blue_x,
  182637. double *blue_y));
  182638. #endif
  182639. #ifdef PNG_FIXED_POINT_SUPPORTED
  182640. extern PNG_EXPORT(png_uint_32,png_get_cHRM_fixed) PNGARG((png_structp png_ptr,
  182641. png_infop info_ptr, png_fixed_point *int_white_x, png_fixed_point
  182642. *int_white_y, png_fixed_point *int_red_x, png_fixed_point *int_red_y,
  182643. png_fixed_point *int_green_x, png_fixed_point *int_green_y, png_fixed_point
  182644. *int_blue_x, png_fixed_point *int_blue_y));
  182645. #endif
  182646. #endif
  182647. #if defined(PNG_cHRM_SUPPORTED)
  182648. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182649. extern PNG_EXPORT(void,png_set_cHRM) PNGARG((png_structp png_ptr,
  182650. png_infop info_ptr, double white_x, double white_y, double red_x,
  182651. double red_y, double green_x, double green_y, double blue_x, double blue_y));
  182652. #endif
  182653. #ifdef PNG_FIXED_POINT_SUPPORTED
  182654. extern PNG_EXPORT(void,png_set_cHRM_fixed) PNGARG((png_structp png_ptr,
  182655. png_infop info_ptr, png_fixed_point int_white_x, png_fixed_point int_white_y,
  182656. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  182657. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  182658. png_fixed_point int_blue_y));
  182659. #endif
  182660. #endif
  182661. #if defined(PNG_gAMA_SUPPORTED)
  182662. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182663. extern PNG_EXPORT(png_uint_32,png_get_gAMA) PNGARG((png_structp png_ptr,
  182664. png_infop info_ptr, double *file_gamma));
  182665. #endif
  182666. extern PNG_EXPORT(png_uint_32,png_get_gAMA_fixed) PNGARG((png_structp png_ptr,
  182667. png_infop info_ptr, png_fixed_point *int_file_gamma));
  182668. #endif
  182669. #if defined(PNG_gAMA_SUPPORTED)
  182670. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182671. extern PNG_EXPORT(void,png_set_gAMA) PNGARG((png_structp png_ptr,
  182672. png_infop info_ptr, double file_gamma));
  182673. #endif
  182674. extern PNG_EXPORT(void,png_set_gAMA_fixed) PNGARG((png_structp png_ptr,
  182675. png_infop info_ptr, png_fixed_point int_file_gamma));
  182676. #endif
  182677. #if defined(PNG_hIST_SUPPORTED)
  182678. extern PNG_EXPORT(png_uint_32,png_get_hIST) PNGARG((png_structp png_ptr,
  182679. png_infop info_ptr, png_uint_16p *hist));
  182680. #endif
  182681. #if defined(PNG_hIST_SUPPORTED)
  182682. extern PNG_EXPORT(void,png_set_hIST) PNGARG((png_structp png_ptr,
  182683. png_infop info_ptr, png_uint_16p hist));
  182684. #endif
  182685. extern PNG_EXPORT(png_uint_32,png_get_IHDR) PNGARG((png_structp png_ptr,
  182686. png_infop info_ptr, png_uint_32 *width, png_uint_32 *height,
  182687. int *bit_depth, int *color_type, int *interlace_method,
  182688. int *compression_method, int *filter_method));
  182689. extern PNG_EXPORT(void,png_set_IHDR) PNGARG((png_structp png_ptr,
  182690. png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth,
  182691. int color_type, int interlace_method, int compression_method,
  182692. int filter_method));
  182693. #if defined(PNG_oFFs_SUPPORTED)
  182694. extern PNG_EXPORT(png_uint_32,png_get_oFFs) PNGARG((png_structp png_ptr,
  182695. png_infop info_ptr, png_int_32 *offset_x, png_int_32 *offset_y,
  182696. int *unit_type));
  182697. #endif
  182698. #if defined(PNG_oFFs_SUPPORTED)
  182699. extern PNG_EXPORT(void,png_set_oFFs) PNGARG((png_structp png_ptr,
  182700. png_infop info_ptr, png_int_32 offset_x, png_int_32 offset_y,
  182701. int unit_type));
  182702. #endif
  182703. #if defined(PNG_pCAL_SUPPORTED)
  182704. extern PNG_EXPORT(png_uint_32,png_get_pCAL) PNGARG((png_structp png_ptr,
  182705. png_infop info_ptr, png_charp *purpose, png_int_32 *X0, png_int_32 *X1,
  182706. int *type, int *nparams, png_charp *units, png_charpp *params));
  182707. #endif
  182708. #if defined(PNG_pCAL_SUPPORTED)
  182709. extern PNG_EXPORT(void,png_set_pCAL) PNGARG((png_structp png_ptr,
  182710. png_infop info_ptr, png_charp purpose, png_int_32 X0, png_int_32 X1,
  182711. int type, int nparams, png_charp units, png_charpp params));
  182712. #endif
  182713. #if defined(PNG_pHYs_SUPPORTED)
  182714. extern PNG_EXPORT(png_uint_32,png_get_pHYs) PNGARG((png_structp png_ptr,
  182715. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  182716. #endif
  182717. #if defined(PNG_pHYs_SUPPORTED)
  182718. extern PNG_EXPORT(void,png_set_pHYs) PNGARG((png_structp png_ptr,
  182719. png_infop info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type));
  182720. #endif
  182721. extern PNG_EXPORT(png_uint_32,png_get_PLTE) PNGARG((png_structp png_ptr,
  182722. png_infop info_ptr, png_colorp *palette, int *num_palette));
  182723. extern PNG_EXPORT(void,png_set_PLTE) PNGARG((png_structp png_ptr,
  182724. png_infop info_ptr, png_colorp palette, int num_palette));
  182725. #if defined(PNG_sBIT_SUPPORTED)
  182726. extern PNG_EXPORT(png_uint_32,png_get_sBIT) PNGARG((png_structp png_ptr,
  182727. png_infop info_ptr, png_color_8p *sig_bit));
  182728. #endif
  182729. #if defined(PNG_sBIT_SUPPORTED)
  182730. extern PNG_EXPORT(void,png_set_sBIT) PNGARG((png_structp png_ptr,
  182731. png_infop info_ptr, png_color_8p sig_bit));
  182732. #endif
  182733. #if defined(PNG_sRGB_SUPPORTED)
  182734. extern PNG_EXPORT(png_uint_32,png_get_sRGB) PNGARG((png_structp png_ptr,
  182735. png_infop info_ptr, int *intent));
  182736. #endif
  182737. #if defined(PNG_sRGB_SUPPORTED)
  182738. extern PNG_EXPORT(void,png_set_sRGB) PNGARG((png_structp png_ptr,
  182739. png_infop info_ptr, int intent));
  182740. extern PNG_EXPORT(void,png_set_sRGB_gAMA_and_cHRM) PNGARG((png_structp png_ptr,
  182741. png_infop info_ptr, int intent));
  182742. #endif
  182743. #if defined(PNG_iCCP_SUPPORTED)
  182744. extern PNG_EXPORT(png_uint_32,png_get_iCCP) PNGARG((png_structp png_ptr,
  182745. png_infop info_ptr, png_charpp name, int *compression_type,
  182746. png_charpp profile, png_uint_32 *proflen));
  182747. /* Note to maintainer: profile should be png_bytepp */
  182748. #endif
  182749. #if defined(PNG_iCCP_SUPPORTED)
  182750. extern PNG_EXPORT(void,png_set_iCCP) PNGARG((png_structp png_ptr,
  182751. png_infop info_ptr, png_charp name, int compression_type,
  182752. png_charp profile, png_uint_32 proflen));
  182753. /* Note to maintainer: profile should be png_bytep */
  182754. #endif
  182755. #if defined(PNG_sPLT_SUPPORTED)
  182756. extern PNG_EXPORT(png_uint_32,png_get_sPLT) PNGARG((png_structp png_ptr,
  182757. png_infop info_ptr, png_sPLT_tpp entries));
  182758. #endif
  182759. #if defined(PNG_sPLT_SUPPORTED)
  182760. extern PNG_EXPORT(void,png_set_sPLT) PNGARG((png_structp png_ptr,
  182761. png_infop info_ptr, png_sPLT_tp entries, int nentries));
  182762. #endif
  182763. #if defined(PNG_TEXT_SUPPORTED)
  182764. /* png_get_text also returns the number of text chunks in *num_text */
  182765. extern PNG_EXPORT(png_uint_32,png_get_text) PNGARG((png_structp png_ptr,
  182766. png_infop info_ptr, png_textp *text_ptr, int *num_text));
  182767. #endif
  182768. /*
  182769. * Note while png_set_text() will accept a structure whose text,
  182770. * language, and translated keywords are NULL pointers, the structure
  182771. * returned by png_get_text will always contain regular
  182772. * zero-terminated C strings. They might be empty strings but
  182773. * they will never be NULL pointers.
  182774. */
  182775. #if defined(PNG_TEXT_SUPPORTED)
  182776. extern PNG_EXPORT(void,png_set_text) PNGARG((png_structp png_ptr,
  182777. png_infop info_ptr, png_textp text_ptr, int num_text));
  182778. #endif
  182779. #if defined(PNG_tIME_SUPPORTED)
  182780. extern PNG_EXPORT(png_uint_32,png_get_tIME) PNGARG((png_structp png_ptr,
  182781. png_infop info_ptr, png_timep *mod_time));
  182782. #endif
  182783. #if defined(PNG_tIME_SUPPORTED)
  182784. extern PNG_EXPORT(void,png_set_tIME) PNGARG((png_structp png_ptr,
  182785. png_infop info_ptr, png_timep mod_time));
  182786. #endif
  182787. #if defined(PNG_tRNS_SUPPORTED)
  182788. extern PNG_EXPORT(png_uint_32,png_get_tRNS) PNGARG((png_structp png_ptr,
  182789. png_infop info_ptr, png_bytep *trans, int *num_trans,
  182790. png_color_16p *trans_values));
  182791. #endif
  182792. #if defined(PNG_tRNS_SUPPORTED)
  182793. extern PNG_EXPORT(void,png_set_tRNS) PNGARG((png_structp png_ptr,
  182794. png_infop info_ptr, png_bytep trans, int num_trans,
  182795. png_color_16p trans_values));
  182796. #endif
  182797. #if defined(PNG_tRNS_SUPPORTED)
  182798. #endif
  182799. #if defined(PNG_sCAL_SUPPORTED)
  182800. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182801. extern PNG_EXPORT(png_uint_32,png_get_sCAL) PNGARG((png_structp png_ptr,
  182802. png_infop info_ptr, int *unit, double *width, double *height));
  182803. #else
  182804. #ifdef PNG_FIXED_POINT_SUPPORTED
  182805. extern PNG_EXPORT(png_uint_32,png_get_sCAL_s) PNGARG((png_structp png_ptr,
  182806. png_infop info_ptr, int *unit, png_charpp swidth, png_charpp sheight));
  182807. #endif
  182808. #endif
  182809. #endif /* PNG_sCAL_SUPPORTED */
  182810. #if defined(PNG_sCAL_SUPPORTED)
  182811. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182812. extern PNG_EXPORT(void,png_set_sCAL) PNGARG((png_structp png_ptr,
  182813. png_infop info_ptr, int unit, double width, double height));
  182814. #else
  182815. #ifdef PNG_FIXED_POINT_SUPPORTED
  182816. extern PNG_EXPORT(void,png_set_sCAL_s) PNGARG((png_structp png_ptr,
  182817. png_infop info_ptr, int unit, png_charp swidth, png_charp sheight));
  182818. #endif
  182819. #endif
  182820. #endif /* PNG_sCAL_SUPPORTED || PNG_WRITE_sCAL_SUPPORTED */
  182821. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182822. /* provide a list of chunks and how they are to be handled, if the built-in
  182823. handling or default unknown chunk handling is not desired. Any chunks not
  182824. listed will be handled in the default manner. The IHDR and IEND chunks
  182825. must not be listed.
  182826. keep = 0: follow default behaviour
  182827. = 1: do not keep
  182828. = 2: keep only if safe-to-copy
  182829. = 3: keep even if unsafe-to-copy
  182830. */
  182831. extern PNG_EXPORT(void, png_set_keep_unknown_chunks) PNGARG((png_structp
  182832. png_ptr, int keep, png_bytep chunk_list, int num_chunks));
  182833. extern PNG_EXPORT(void, png_set_unknown_chunks) PNGARG((png_structp png_ptr,
  182834. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns));
  182835. extern PNG_EXPORT(void, png_set_unknown_chunk_location)
  182836. PNGARG((png_structp png_ptr, png_infop info_ptr, int chunk, int location));
  182837. extern PNG_EXPORT(png_uint_32,png_get_unknown_chunks) PNGARG((png_structp
  182838. png_ptr, png_infop info_ptr, png_unknown_chunkpp entries));
  182839. #endif
  182840. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  182841. PNG_EXPORT(int,png_handle_as_unknown) PNGARG((png_structp png_ptr, png_bytep
  182842. chunk_name));
  182843. #endif
  182844. /* Png_free_data() will turn off the "valid" flag for anything it frees.
  182845. If you need to turn it off for a chunk that your application has freed,
  182846. you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK); */
  182847. extern PNG_EXPORT(void, png_set_invalid) PNGARG((png_structp png_ptr,
  182848. png_infop info_ptr, int mask));
  182849. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  182850. /* The "params" pointer is currently not used and is for future expansion. */
  182851. extern PNG_EXPORT(void, png_read_png) PNGARG((png_structp png_ptr,
  182852. png_infop info_ptr,
  182853. int transforms,
  182854. png_voidp params));
  182855. extern PNG_EXPORT(void, png_write_png) PNGARG((png_structp png_ptr,
  182856. png_infop info_ptr,
  182857. int transforms,
  182858. png_voidp params));
  182859. #endif
  182860. /* Define PNG_DEBUG at compile time for debugging information. Higher
  182861. * numbers for PNG_DEBUG mean more debugging information. This has
  182862. * only been added since version 0.95 so it is not implemented throughout
  182863. * libpng yet, but more support will be added as needed.
  182864. */
  182865. #ifdef PNG_DEBUG
  182866. #if (PNG_DEBUG > 0)
  182867. #if !defined(PNG_DEBUG_FILE) && defined(_MSC_VER)
  182868. #include <crtdbg.h>
  182869. #if (PNG_DEBUG > 1)
  182870. #define png_debug(l,m) _RPT0(_CRT_WARN,m)
  182871. #define png_debug1(l,m,p1) _RPT1(_CRT_WARN,m,p1)
  182872. #define png_debug2(l,m,p1,p2) _RPT2(_CRT_WARN,m,p1,p2)
  182873. #endif
  182874. #else /* PNG_DEBUG_FILE || !_MSC_VER */
  182875. #ifndef PNG_DEBUG_FILE
  182876. #define PNG_DEBUG_FILE stderr
  182877. #endif /* PNG_DEBUG_FILE */
  182878. #if (PNG_DEBUG > 1)
  182879. #define png_debug(l,m) \
  182880. { \
  182881. int num_tabs=l; \
  182882. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  182883. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":"")))); \
  182884. }
  182885. #define png_debug1(l,m,p1) \
  182886. { \
  182887. int num_tabs=l; \
  182888. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  182889. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1); \
  182890. }
  182891. #define png_debug2(l,m,p1,p2) \
  182892. { \
  182893. int num_tabs=l; \
  182894. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  182895. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1,p2); \
  182896. }
  182897. #endif /* (PNG_DEBUG > 1) */
  182898. #endif /* _MSC_VER */
  182899. #endif /* (PNG_DEBUG > 0) */
  182900. #endif /* PNG_DEBUG */
  182901. #ifndef png_debug
  182902. #define png_debug(l, m)
  182903. #endif
  182904. #ifndef png_debug1
  182905. #define png_debug1(l, m, p1)
  182906. #endif
  182907. #ifndef png_debug2
  182908. #define png_debug2(l, m, p1, p2)
  182909. #endif
  182910. extern PNG_EXPORT(png_charp,png_get_copyright) PNGARG((png_structp png_ptr));
  182911. extern PNG_EXPORT(png_charp,png_get_header_ver) PNGARG((png_structp png_ptr));
  182912. extern PNG_EXPORT(png_charp,png_get_header_version) PNGARG((png_structp png_ptr));
  182913. extern PNG_EXPORT(png_charp,png_get_libpng_ver) PNGARG((png_structp png_ptr));
  182914. #ifdef PNG_MNG_FEATURES_SUPPORTED
  182915. extern PNG_EXPORT(png_uint_32,png_permit_mng_features) PNGARG((png_structp
  182916. png_ptr, png_uint_32 mng_features_permitted));
  182917. #endif
  182918. /* For use in png_set_keep_unknown, added to version 1.2.6 */
  182919. #define PNG_HANDLE_CHUNK_AS_DEFAULT 0
  182920. #define PNG_HANDLE_CHUNK_NEVER 1
  182921. #define PNG_HANDLE_CHUNK_IF_SAFE 2
  182922. #define PNG_HANDLE_CHUNK_ALWAYS 3
  182923. /* Added to version 1.2.0 */
  182924. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  182925. #if defined(PNG_MMX_CODE_SUPPORTED)
  182926. #define PNG_ASM_FLAG_MMX_SUPPORT_COMPILED 0x01 /* not user-settable */
  182927. #define PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU 0x02 /* not user-settable */
  182928. #define PNG_ASM_FLAG_MMX_READ_COMBINE_ROW 0x04
  182929. #define PNG_ASM_FLAG_MMX_READ_INTERLACE 0x08
  182930. #define PNG_ASM_FLAG_MMX_READ_FILTER_SUB 0x10
  182931. #define PNG_ASM_FLAG_MMX_READ_FILTER_UP 0x20
  182932. #define PNG_ASM_FLAG_MMX_READ_FILTER_AVG 0x40
  182933. #define PNG_ASM_FLAG_MMX_READ_FILTER_PAETH 0x80
  182934. #define PNG_ASM_FLAGS_INITIALIZED 0x80000000 /* not user-settable */
  182935. #define PNG_MMX_READ_FLAGS ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \
  182936. | PNG_ASM_FLAG_MMX_READ_INTERLACE \
  182937. | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \
  182938. | PNG_ASM_FLAG_MMX_READ_FILTER_UP \
  182939. | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \
  182940. | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH )
  182941. #define PNG_MMX_WRITE_FLAGS ( 0 )
  182942. #define PNG_MMX_FLAGS ( PNG_ASM_FLAG_MMX_SUPPORT_COMPILED \
  182943. | PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU \
  182944. | PNG_MMX_READ_FLAGS \
  182945. | PNG_MMX_WRITE_FLAGS )
  182946. #define PNG_SELECT_READ 1
  182947. #define PNG_SELECT_WRITE 2
  182948. #endif /* PNG_MMX_CODE_SUPPORTED */
  182949. #if !defined(PNG_1_0_X)
  182950. /* pngget.c */
  182951. extern PNG_EXPORT(png_uint_32,png_get_mmx_flagmask)
  182952. PNGARG((int flag_select, int *compilerID));
  182953. /* pngget.c */
  182954. extern PNG_EXPORT(png_uint_32,png_get_asm_flagmask)
  182955. PNGARG((int flag_select));
  182956. /* pngget.c */
  182957. extern PNG_EXPORT(png_uint_32,png_get_asm_flags)
  182958. PNGARG((png_structp png_ptr));
  182959. /* pngget.c */
  182960. extern PNG_EXPORT(png_byte,png_get_mmx_bitdepth_threshold)
  182961. PNGARG((png_structp png_ptr));
  182962. /* pngget.c */
  182963. extern PNG_EXPORT(png_uint_32,png_get_mmx_rowbytes_threshold)
  182964. PNGARG((png_structp png_ptr));
  182965. /* pngset.c */
  182966. extern PNG_EXPORT(void,png_set_asm_flags)
  182967. PNGARG((png_structp png_ptr, png_uint_32 asm_flags));
  182968. /* pngset.c */
  182969. extern PNG_EXPORT(void,png_set_mmx_thresholds)
  182970. PNGARG((png_structp png_ptr, png_byte mmx_bitdepth_threshold,
  182971. png_uint_32 mmx_rowbytes_threshold));
  182972. #endif /* PNG_1_0_X */
  182973. #if !defined(PNG_1_0_X)
  182974. /* png.c, pnggccrd.c, or pngvcrd.c */
  182975. extern PNG_EXPORT(int,png_mmx_support) PNGARG((void));
  182976. #endif /* PNG_ASSEMBLER_CODE_SUPPORTED */
  182977. /* Strip the prepended error numbers ("#nnn ") from error and warning
  182978. * messages before passing them to the error or warning handler. */
  182979. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  182980. extern PNG_EXPORT(void,png_set_strip_error_numbers) PNGARG((png_structp
  182981. png_ptr, png_uint_32 strip_mode));
  182982. #endif
  182983. #endif /* PNG_1_0_X */
  182984. /* Added at libpng-1.2.6 */
  182985. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  182986. extern PNG_EXPORT(void,png_set_user_limits) PNGARG((png_structp
  182987. png_ptr, png_uint_32 user_width_max, png_uint_32 user_height_max));
  182988. extern PNG_EXPORT(png_uint_32,png_get_user_width_max) PNGARG((png_structp
  182989. png_ptr));
  182990. extern PNG_EXPORT(png_uint_32,png_get_user_height_max) PNGARG((png_structp
  182991. png_ptr));
  182992. #endif
  182993. /* Maintainer: Put new public prototypes here ^, in libpng.3, and project defs */
  182994. #ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED
  182995. /* With these routines we avoid an integer divide, which will be slower on
  182996. * most machines. However, it does take more operations than the corresponding
  182997. * divide method, so it may be slower on a few RISC systems. There are two
  182998. * shifts (by 8 or 16 bits) and an addition, versus a single integer divide.
  182999. *
  183000. * Note that the rounding factors are NOT supposed to be the same! 128 and
  183001. * 32768 are correct for the NODIV code; 127 and 32767 are correct for the
  183002. * standard method.
  183003. *
  183004. * [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ]
  183005. */
  183006. /* fg and bg should be in `gamma 1.0' space; alpha is the opacity */
  183007. # define png_composite(composite, fg, alpha, bg) \
  183008. { png_uint_16 temp = (png_uint_16)((png_uint_16)(fg) * (png_uint_16)(alpha) \
  183009. + (png_uint_16)(bg)*(png_uint_16)(255 - \
  183010. (png_uint_16)(alpha)) + (png_uint_16)128); \
  183011. (composite) = (png_byte)((temp + (temp >> 8)) >> 8); }
  183012. # define png_composite_16(composite, fg, alpha, bg) \
  183013. { png_uint_32 temp = (png_uint_32)((png_uint_32)(fg) * (png_uint_32)(alpha) \
  183014. + (png_uint_32)(bg)*(png_uint_32)(65535L - \
  183015. (png_uint_32)(alpha)) + (png_uint_32)32768L); \
  183016. (composite) = (png_uint_16)((temp + (temp >> 16)) >> 16); }
  183017. #else /* standard method using integer division */
  183018. # define png_composite(composite, fg, alpha, bg) \
  183019. (composite) = (png_byte)(((png_uint_16)(fg) * (png_uint_16)(alpha) + \
  183020. (png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) + \
  183021. (png_uint_16)127) / 255)
  183022. # define png_composite_16(composite, fg, alpha, bg) \
  183023. (composite) = (png_uint_16)(((png_uint_32)(fg) * (png_uint_32)(alpha) + \
  183024. (png_uint_32)(bg)*(png_uint_32)(65535L - (png_uint_32)(alpha)) + \
  183025. (png_uint_32)32767) / (png_uint_32)65535L)
  183026. #endif /* PNG_READ_COMPOSITE_NODIV_SUPPORTED */
  183027. /* Inline macros to do direct reads of bytes from the input buffer. These
  183028. * require that you are using an architecture that uses PNG byte ordering
  183029. * (MSB first) and supports unaligned data storage. I think that PowerPC
  183030. * in big-endian mode and 680x0 are the only ones that will support this.
  183031. * The x86 line of processors definitely do not. The png_get_int_32()
  183032. * routine also assumes we are using two's complement format for negative
  183033. * values, which is almost certainly true.
  183034. */
  183035. #if defined(PNG_READ_BIG_ENDIAN_SUPPORTED)
  183036. # define png_get_uint_32(buf) ( *((png_uint_32p) (buf)))
  183037. # define png_get_uint_16(buf) ( *((png_uint_16p) (buf)))
  183038. # define png_get_int_32(buf) ( *((png_int_32p) (buf)))
  183039. #else
  183040. extern PNG_EXPORT(png_uint_32,png_get_uint_32) PNGARG((png_bytep buf));
  183041. extern PNG_EXPORT(png_uint_16,png_get_uint_16) PNGARG((png_bytep buf));
  183042. extern PNG_EXPORT(png_int_32,png_get_int_32) PNGARG((png_bytep buf));
  183043. #endif /* !PNG_READ_BIG_ENDIAN_SUPPORTED */
  183044. extern PNG_EXPORT(png_uint_32,png_get_uint_31)
  183045. PNGARG((png_structp png_ptr, png_bytep buf));
  183046. /* No png_get_int_16 -- may be added if there's a real need for it. */
  183047. /* Place a 32-bit number into a buffer in PNG byte order (big-endian).
  183048. */
  183049. extern PNG_EXPORT(void,png_save_uint_32)
  183050. PNGARG((png_bytep buf, png_uint_32 i));
  183051. extern PNG_EXPORT(void,png_save_int_32)
  183052. PNGARG((png_bytep buf, png_int_32 i));
  183053. /* Place a 16-bit number into a buffer in PNG byte order.
  183054. * The parameter is declared unsigned int, not png_uint_16,
  183055. * just to avoid potential problems on pre-ANSI C compilers.
  183056. */
  183057. extern PNG_EXPORT(void,png_save_uint_16)
  183058. PNGARG((png_bytep buf, unsigned int i));
  183059. /* No png_save_int_16 -- may be added if there's a real need for it. */
  183060. /* ************************************************************************* */
  183061. /* These next functions are used internally in the code. They generally
  183062. * shouldn't be used unless you are writing code to add or replace some
  183063. * functionality in libpng. More information about most functions can
  183064. * be found in the files where the functions are located.
  183065. */
  183066. /* Various modes of operation, that are visible to applications because
  183067. * they are used for unknown chunk location.
  183068. */
  183069. #define PNG_HAVE_IHDR 0x01
  183070. #define PNG_HAVE_PLTE 0x02
  183071. #define PNG_HAVE_IDAT 0x04
  183072. #define PNG_AFTER_IDAT 0x08 /* Have complete zlib datastream */
  183073. #define PNG_HAVE_IEND 0x10
  183074. #if defined(PNG_INTERNAL)
  183075. /* More modes of operation. Note that after an init, mode is set to
  183076. * zero automatically when the structure is created.
  183077. */
  183078. #define PNG_HAVE_gAMA 0x20
  183079. #define PNG_HAVE_cHRM 0x40
  183080. #define PNG_HAVE_sRGB 0x80
  183081. #define PNG_HAVE_CHUNK_HEADER 0x100
  183082. #define PNG_WROTE_tIME 0x200
  183083. #define PNG_WROTE_INFO_BEFORE_PLTE 0x400
  183084. #define PNG_BACKGROUND_IS_GRAY 0x800
  183085. #define PNG_HAVE_PNG_SIGNATURE 0x1000
  183086. #define PNG_HAVE_CHUNK_AFTER_IDAT 0x2000 /* Have another chunk after IDAT */
  183087. /* flags for the transformations the PNG library does on the image data */
  183088. #define PNG_BGR 0x0001
  183089. #define PNG_INTERLACE 0x0002
  183090. #define PNG_PACK 0x0004
  183091. #define PNG_SHIFT 0x0008
  183092. #define PNG_SWAP_BYTES 0x0010
  183093. #define PNG_INVERT_MONO 0x0020
  183094. #define PNG_DITHER 0x0040
  183095. #define PNG_BACKGROUND 0x0080
  183096. #define PNG_BACKGROUND_EXPAND 0x0100
  183097. /* 0x0200 unused */
  183098. #define PNG_16_TO_8 0x0400
  183099. #define PNG_RGBA 0x0800
  183100. #define PNG_EXPAND 0x1000
  183101. #define PNG_GAMMA 0x2000
  183102. #define PNG_GRAY_TO_RGB 0x4000
  183103. #define PNG_FILLER 0x8000L
  183104. #define PNG_PACKSWAP 0x10000L
  183105. #define PNG_SWAP_ALPHA 0x20000L
  183106. #define PNG_STRIP_ALPHA 0x40000L
  183107. #define PNG_INVERT_ALPHA 0x80000L
  183108. #define PNG_USER_TRANSFORM 0x100000L
  183109. #define PNG_RGB_TO_GRAY_ERR 0x200000L
  183110. #define PNG_RGB_TO_GRAY_WARN 0x400000L
  183111. #define PNG_RGB_TO_GRAY 0x600000L /* two bits, RGB_TO_GRAY_ERR|WARN */
  183112. /* 0x800000L Unused */
  183113. #define PNG_ADD_ALPHA 0x1000000L /* Added to libpng-1.2.7 */
  183114. #define PNG_EXPAND_tRNS 0x2000000L /* Added to libpng-1.2.9 */
  183115. /* 0x4000000L unused */
  183116. /* 0x8000000L unused */
  183117. /* 0x10000000L unused */
  183118. /* 0x20000000L unused */
  183119. /* 0x40000000L unused */
  183120. /* flags for png_create_struct */
  183121. #define PNG_STRUCT_PNG 0x0001
  183122. #define PNG_STRUCT_INFO 0x0002
  183123. /* Scaling factor for filter heuristic weighting calculations */
  183124. #define PNG_WEIGHT_SHIFT 8
  183125. #define PNG_WEIGHT_FACTOR (1<<(PNG_WEIGHT_SHIFT))
  183126. #define PNG_COST_SHIFT 3
  183127. #define PNG_COST_FACTOR (1<<(PNG_COST_SHIFT))
  183128. /* flags for the png_ptr->flags rather than declaring a byte for each one */
  183129. #define PNG_FLAG_ZLIB_CUSTOM_STRATEGY 0x0001
  183130. #define PNG_FLAG_ZLIB_CUSTOM_LEVEL 0x0002
  183131. #define PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL 0x0004
  183132. #define PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS 0x0008
  183133. #define PNG_FLAG_ZLIB_CUSTOM_METHOD 0x0010
  183134. #define PNG_FLAG_ZLIB_FINISHED 0x0020
  183135. #define PNG_FLAG_ROW_INIT 0x0040
  183136. #define PNG_FLAG_FILLER_AFTER 0x0080
  183137. #define PNG_FLAG_CRC_ANCILLARY_USE 0x0100
  183138. #define PNG_FLAG_CRC_ANCILLARY_NOWARN 0x0200
  183139. #define PNG_FLAG_CRC_CRITICAL_USE 0x0400
  183140. #define PNG_FLAG_CRC_CRITICAL_IGNORE 0x0800
  183141. #define PNG_FLAG_FREE_PLTE 0x1000
  183142. #define PNG_FLAG_FREE_TRNS 0x2000
  183143. #define PNG_FLAG_FREE_HIST 0x4000
  183144. #define PNG_FLAG_KEEP_UNKNOWN_CHUNKS 0x8000L
  183145. #define PNG_FLAG_KEEP_UNSAFE_CHUNKS 0x10000L
  183146. #define PNG_FLAG_LIBRARY_MISMATCH 0x20000L
  183147. #define PNG_FLAG_STRIP_ERROR_NUMBERS 0x40000L
  183148. #define PNG_FLAG_STRIP_ERROR_TEXT 0x80000L
  183149. #define PNG_FLAG_MALLOC_NULL_MEM_OK 0x100000L
  183150. #define PNG_FLAG_ADD_ALPHA 0x200000L /* Added to libpng-1.2.8 */
  183151. #define PNG_FLAG_STRIP_ALPHA 0x400000L /* Added to libpng-1.2.8 */
  183152. /* 0x800000L unused */
  183153. /* 0x1000000L unused */
  183154. /* 0x2000000L unused */
  183155. /* 0x4000000L unused */
  183156. /* 0x8000000L unused */
  183157. /* 0x10000000L unused */
  183158. /* 0x20000000L unused */
  183159. /* 0x40000000L unused */
  183160. #define PNG_FLAG_CRC_ANCILLARY_MASK (PNG_FLAG_CRC_ANCILLARY_USE | \
  183161. PNG_FLAG_CRC_ANCILLARY_NOWARN)
  183162. #define PNG_FLAG_CRC_CRITICAL_MASK (PNG_FLAG_CRC_CRITICAL_USE | \
  183163. PNG_FLAG_CRC_CRITICAL_IGNORE)
  183164. #define PNG_FLAG_CRC_MASK (PNG_FLAG_CRC_ANCILLARY_MASK | \
  183165. PNG_FLAG_CRC_CRITICAL_MASK)
  183166. /* save typing and make code easier to understand */
  183167. #define PNG_COLOR_DIST(c1, c2) (abs((int)((c1).red) - (int)((c2).red)) + \
  183168. abs((int)((c1).green) - (int)((c2).green)) + \
  183169. abs((int)((c1).blue) - (int)((c2).blue)))
  183170. /* Added to libpng-1.2.6 JB */
  183171. #define PNG_ROWBYTES(pixel_bits, width) \
  183172. ((pixel_bits) >= 8 ? \
  183173. ((width) * (((png_uint_32)(pixel_bits)) >> 3)) : \
  183174. (( ((width) * ((png_uint_32)(pixel_bits))) + 7) >> 3) )
  183175. /* PNG_OUT_OF_RANGE returns true if value is outside the range
  183176. ideal-delta..ideal+delta. Each argument is evaluated twice.
  183177. "ideal" and "delta" should be constants, normally simple
  183178. integers, "value" a variable. Added to libpng-1.2.6 JB */
  183179. #define PNG_OUT_OF_RANGE(value, ideal, delta) \
  183180. ( (value) < (ideal)-(delta) || (value) > (ideal)+(delta) )
  183181. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  183182. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  183183. /* place to hold the signature string for a PNG file. */
  183184. #ifdef PNG_USE_GLOBAL_ARRAYS
  183185. PNG_EXPORT_VAR (PNG_CONST png_byte FARDATA) png_sig[8];
  183186. #else
  183187. #endif
  183188. #endif /* PNG_NO_EXTERN */
  183189. /* Constant strings for known chunk types. If you need to add a chunk,
  183190. * define the name here, and add an invocation of the macro in png.c and
  183191. * wherever it's needed.
  183192. */
  183193. #define PNG_IHDR png_byte png_IHDR[5] = { 73, 72, 68, 82, '\0'}
  183194. #define PNG_IDAT png_byte png_IDAT[5] = { 73, 68, 65, 84, '\0'}
  183195. #define PNG_IEND png_byte png_IEND[5] = { 73, 69, 78, 68, '\0'}
  183196. #define PNG_PLTE png_byte png_PLTE[5] = { 80, 76, 84, 69, '\0'}
  183197. #define PNG_bKGD png_byte png_bKGD[5] = { 98, 75, 71, 68, '\0'}
  183198. #define PNG_cHRM png_byte png_cHRM[5] = { 99, 72, 82, 77, '\0'}
  183199. #define PNG_gAMA png_byte png_gAMA[5] = {103, 65, 77, 65, '\0'}
  183200. #define PNG_hIST png_byte png_hIST[5] = {104, 73, 83, 84, '\0'}
  183201. #define PNG_iCCP png_byte png_iCCP[5] = {105, 67, 67, 80, '\0'}
  183202. #define PNG_iTXt png_byte png_iTXt[5] = {105, 84, 88, 116, '\0'}
  183203. #define PNG_oFFs png_byte png_oFFs[5] = {111, 70, 70, 115, '\0'}
  183204. #define PNG_pCAL png_byte png_pCAL[5] = {112, 67, 65, 76, '\0'}
  183205. #define PNG_sCAL png_byte png_sCAL[5] = {115, 67, 65, 76, '\0'}
  183206. #define PNG_pHYs png_byte png_pHYs[5] = {112, 72, 89, 115, '\0'}
  183207. #define PNG_sBIT png_byte png_sBIT[5] = {115, 66, 73, 84, '\0'}
  183208. #define PNG_sPLT png_byte png_sPLT[5] = {115, 80, 76, 84, '\0'}
  183209. #define PNG_sRGB png_byte png_sRGB[5] = {115, 82, 71, 66, '\0'}
  183210. #define PNG_tEXt png_byte png_tEXt[5] = {116, 69, 88, 116, '\0'}
  183211. #define PNG_tIME png_byte png_tIME[5] = {116, 73, 77, 69, '\0'}
  183212. #define PNG_tRNS png_byte png_tRNS[5] = {116, 82, 78, 83, '\0'}
  183213. #define PNG_zTXt png_byte png_zTXt[5] = {122, 84, 88, 116, '\0'}
  183214. #ifdef PNG_USE_GLOBAL_ARRAYS
  183215. PNG_EXPORT_VAR (png_byte FARDATA) png_IHDR[5];
  183216. PNG_EXPORT_VAR (png_byte FARDATA) png_IDAT[5];
  183217. PNG_EXPORT_VAR (png_byte FARDATA) png_IEND[5];
  183218. PNG_EXPORT_VAR (png_byte FARDATA) png_PLTE[5];
  183219. PNG_EXPORT_VAR (png_byte FARDATA) png_bKGD[5];
  183220. PNG_EXPORT_VAR (png_byte FARDATA) png_cHRM[5];
  183221. PNG_EXPORT_VAR (png_byte FARDATA) png_gAMA[5];
  183222. PNG_EXPORT_VAR (png_byte FARDATA) png_hIST[5];
  183223. PNG_EXPORT_VAR (png_byte FARDATA) png_iCCP[5];
  183224. PNG_EXPORT_VAR (png_byte FARDATA) png_iTXt[5];
  183225. PNG_EXPORT_VAR (png_byte FARDATA) png_oFFs[5];
  183226. PNG_EXPORT_VAR (png_byte FARDATA) png_pCAL[5];
  183227. PNG_EXPORT_VAR (png_byte FARDATA) png_sCAL[5];
  183228. PNG_EXPORT_VAR (png_byte FARDATA) png_pHYs[5];
  183229. PNG_EXPORT_VAR (png_byte FARDATA) png_sBIT[5];
  183230. PNG_EXPORT_VAR (png_byte FARDATA) png_sPLT[5];
  183231. PNG_EXPORT_VAR (png_byte FARDATA) png_sRGB[5];
  183232. PNG_EXPORT_VAR (png_byte FARDATA) png_tEXt[5];
  183233. PNG_EXPORT_VAR (png_byte FARDATA) png_tIME[5];
  183234. PNG_EXPORT_VAR (png_byte FARDATA) png_tRNS[5];
  183235. PNG_EXPORT_VAR (png_byte FARDATA) png_zTXt[5];
  183236. #endif /* PNG_USE_GLOBAL_ARRAYS */
  183237. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183238. /* Initialize png_ptr struct for reading, and allocate any other memory.
  183239. * (old interface - DEPRECATED - use png_create_read_struct instead).
  183240. */
  183241. extern PNG_EXPORT(void,png_read_init) PNGARG((png_structp png_ptr));
  183242. #undef png_read_init
  183243. #define png_read_init(png_ptr) png_read_init_3(&png_ptr, \
  183244. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  183245. #endif
  183246. extern PNG_EXPORT(void,png_read_init_3) PNGARG((png_structpp ptr_ptr,
  183247. png_const_charp user_png_ver, png_size_t png_struct_size));
  183248. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183249. extern PNG_EXPORT(void,png_read_init_2) PNGARG((png_structp png_ptr,
  183250. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  183251. png_info_size));
  183252. #endif
  183253. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183254. /* Initialize png_ptr struct for writing, and allocate any other memory.
  183255. * (old interface - DEPRECATED - use png_create_write_struct instead).
  183256. */
  183257. extern PNG_EXPORT(void,png_write_init) PNGARG((png_structp png_ptr));
  183258. #undef png_write_init
  183259. #define png_write_init(png_ptr) png_write_init_3(&png_ptr, \
  183260. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  183261. #endif
  183262. extern PNG_EXPORT(void,png_write_init_3) PNGARG((png_structpp ptr_ptr,
  183263. png_const_charp user_png_ver, png_size_t png_struct_size));
  183264. extern PNG_EXPORT(void,png_write_init_2) PNGARG((png_structp png_ptr,
  183265. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  183266. png_info_size));
  183267. /* Allocate memory for an internal libpng struct */
  183268. PNG_EXTERN png_voidp png_create_struct PNGARG((int type));
  183269. /* Free memory from internal libpng struct */
  183270. PNG_EXTERN void png_destroy_struct PNGARG((png_voidp struct_ptr));
  183271. PNG_EXTERN png_voidp png_create_struct_2 PNGARG((int type, png_malloc_ptr
  183272. malloc_fn, png_voidp mem_ptr));
  183273. PNG_EXTERN void png_destroy_struct_2 PNGARG((png_voidp struct_ptr,
  183274. png_free_ptr free_fn, png_voidp mem_ptr));
  183275. /* Free any memory that info_ptr points to and reset struct. */
  183276. PNG_EXTERN void png_info_destroy PNGARG((png_structp png_ptr,
  183277. png_infop info_ptr));
  183278. #ifndef PNG_1_0_X
  183279. /* Function to allocate memory for zlib. */
  183280. PNG_EXTERN voidpf png_zalloc PNGARG((voidpf png_ptr, uInt items, uInt size));
  183281. /* Function to free memory for zlib */
  183282. PNG_EXTERN void png_zfree PNGARG((voidpf png_ptr, voidpf ptr));
  183283. #ifdef PNG_SIZE_T
  183284. /* Function to convert a sizeof an item to png_sizeof item */
  183285. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  183286. #endif
  183287. /* Next four functions are used internally as callbacks. PNGAPI is required
  183288. * but not PNG_EXPORT. PNGAPI added at libpng version 1.2.3. */
  183289. PNG_EXTERN void PNGAPI png_default_read_data PNGARG((png_structp png_ptr,
  183290. png_bytep data, png_size_t length));
  183291. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183292. PNG_EXTERN void PNGAPI png_push_fill_buffer PNGARG((png_structp png_ptr,
  183293. png_bytep buffer, png_size_t length));
  183294. #endif
  183295. PNG_EXTERN void PNGAPI png_default_write_data PNGARG((png_structp png_ptr,
  183296. png_bytep data, png_size_t length));
  183297. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  183298. #if !defined(PNG_NO_STDIO)
  183299. PNG_EXTERN void PNGAPI png_default_flush PNGARG((png_structp png_ptr));
  183300. #endif
  183301. #endif
  183302. #else /* PNG_1_0_X */
  183303. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183304. PNG_EXTERN void png_push_fill_buffer PNGARG((png_structp png_ptr,
  183305. png_bytep buffer, png_size_t length));
  183306. #endif
  183307. #endif /* PNG_1_0_X */
  183308. /* Reset the CRC variable */
  183309. PNG_EXTERN void png_reset_crc PNGARG((png_structp png_ptr));
  183310. /* Write the "data" buffer to whatever output you are using. */
  183311. PNG_EXTERN void png_write_data PNGARG((png_structp png_ptr, png_bytep data,
  183312. png_size_t length));
  183313. /* Read data from whatever input you are using into the "data" buffer */
  183314. PNG_EXTERN void png_read_data PNGARG((png_structp png_ptr, png_bytep data,
  183315. png_size_t length));
  183316. /* Read bytes into buf, and update png_ptr->crc */
  183317. PNG_EXTERN void png_crc_read PNGARG((png_structp png_ptr, png_bytep buf,
  183318. png_size_t length));
  183319. /* Decompress data in a chunk that uses compression */
  183320. #if defined(PNG_zTXt_SUPPORTED) || defined(PNG_iTXt_SUPPORTED) || \
  183321. defined(PNG_iCCP_SUPPORTED) || defined(PNG_sPLT_SUPPORTED)
  183322. PNG_EXTERN png_charp png_decompress_chunk PNGARG((png_structp png_ptr,
  183323. int comp_type, png_charp chunkdata, png_size_t chunklength,
  183324. png_size_t prefix_length, png_size_t *data_length));
  183325. #endif
  183326. /* Read "skip" bytes, read the file crc, and (optionally) verify png_ptr->crc */
  183327. PNG_EXTERN int png_crc_finish PNGARG((png_structp png_ptr, png_uint_32 skip));
  183328. /* Read the CRC from the file and compare it to the libpng calculated CRC */
  183329. PNG_EXTERN int png_crc_error PNGARG((png_structp png_ptr));
  183330. /* Calculate the CRC over a section of data. Note that we are only
  183331. * passing a maximum of 64K on systems that have this as a memory limit,
  183332. * since this is the maximum buffer size we can specify.
  183333. */
  183334. PNG_EXTERN void png_calculate_crc PNGARG((png_structp png_ptr, png_bytep ptr,
  183335. png_size_t length));
  183336. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  183337. PNG_EXTERN void png_flush PNGARG((png_structp png_ptr));
  183338. #endif
  183339. /* simple function to write the signature */
  183340. PNG_EXTERN void png_write_sig PNGARG((png_structp png_ptr));
  183341. /* write various chunks */
  183342. /* Write the IHDR chunk, and update the png_struct with the necessary
  183343. * information.
  183344. */
  183345. PNG_EXTERN void png_write_IHDR PNGARG((png_structp png_ptr, png_uint_32 width,
  183346. png_uint_32 height,
  183347. int bit_depth, int color_type, int compression_method, int filter_method,
  183348. int interlace_method));
  183349. PNG_EXTERN void png_write_PLTE PNGARG((png_structp png_ptr, png_colorp palette,
  183350. png_uint_32 num_pal));
  183351. PNG_EXTERN void png_write_IDAT PNGARG((png_structp png_ptr, png_bytep data,
  183352. png_size_t length));
  183353. PNG_EXTERN void png_write_IEND PNGARG((png_structp png_ptr));
  183354. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  183355. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183356. PNG_EXTERN void png_write_gAMA PNGARG((png_structp png_ptr, double file_gamma));
  183357. #endif
  183358. #ifdef PNG_FIXED_POINT_SUPPORTED
  183359. PNG_EXTERN void png_write_gAMA_fixed PNGARG((png_structp png_ptr, png_fixed_point
  183360. file_gamma));
  183361. #endif
  183362. #endif
  183363. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  183364. PNG_EXTERN void png_write_sBIT PNGARG((png_structp png_ptr, png_color_8p sbit,
  183365. int color_type));
  183366. #endif
  183367. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  183368. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183369. PNG_EXTERN void png_write_cHRM PNGARG((png_structp png_ptr,
  183370. double white_x, double white_y,
  183371. double red_x, double red_y, double green_x, double green_y,
  183372. double blue_x, double blue_y));
  183373. #endif
  183374. #ifdef PNG_FIXED_POINT_SUPPORTED
  183375. PNG_EXTERN void png_write_cHRM_fixed PNGARG((png_structp png_ptr,
  183376. png_fixed_point int_white_x, png_fixed_point int_white_y,
  183377. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  183378. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  183379. png_fixed_point int_blue_y));
  183380. #endif
  183381. #endif
  183382. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  183383. PNG_EXTERN void png_write_sRGB PNGARG((png_structp png_ptr,
  183384. int intent));
  183385. #endif
  183386. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  183387. PNG_EXTERN void png_write_iCCP PNGARG((png_structp png_ptr,
  183388. png_charp name, int compression_type,
  183389. png_charp profile, int proflen));
  183390. /* Note to maintainer: profile should be png_bytep */
  183391. #endif
  183392. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  183393. PNG_EXTERN void png_write_sPLT PNGARG((png_structp png_ptr,
  183394. png_sPLT_tp palette));
  183395. #endif
  183396. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  183397. PNG_EXTERN void png_write_tRNS PNGARG((png_structp png_ptr, png_bytep trans,
  183398. png_color_16p values, int number, int color_type));
  183399. #endif
  183400. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  183401. PNG_EXTERN void png_write_bKGD PNGARG((png_structp png_ptr,
  183402. png_color_16p values, int color_type));
  183403. #endif
  183404. #if defined(PNG_WRITE_hIST_SUPPORTED)
  183405. PNG_EXTERN void png_write_hIST PNGARG((png_structp png_ptr, png_uint_16p hist,
  183406. int num_hist));
  183407. #endif
  183408. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  183409. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  183410. PNG_EXTERN png_size_t png_check_keyword PNGARG((png_structp png_ptr,
  183411. png_charp key, png_charpp new_key));
  183412. #endif
  183413. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  183414. PNG_EXTERN void png_write_tEXt PNGARG((png_structp png_ptr, png_charp key,
  183415. png_charp text, png_size_t text_len));
  183416. #endif
  183417. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  183418. PNG_EXTERN void png_write_zTXt PNGARG((png_structp png_ptr, png_charp key,
  183419. png_charp text, png_size_t text_len, int compression));
  183420. #endif
  183421. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  183422. PNG_EXTERN void png_write_iTXt PNGARG((png_structp png_ptr,
  183423. int compression, png_charp key, png_charp lang, png_charp lang_key,
  183424. png_charp text));
  183425. #endif
  183426. #if defined(PNG_TEXT_SUPPORTED) /* Added at version 1.0.14 and 1.2.4 */
  183427. PNG_EXTERN int png_set_text_2 PNGARG((png_structp png_ptr,
  183428. png_infop info_ptr, png_textp text_ptr, int num_text));
  183429. #endif
  183430. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  183431. PNG_EXTERN void png_write_oFFs PNGARG((png_structp png_ptr,
  183432. png_int_32 x_offset, png_int_32 y_offset, int unit_type));
  183433. #endif
  183434. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  183435. PNG_EXTERN void png_write_pCAL PNGARG((png_structp png_ptr, png_charp purpose,
  183436. png_int_32 X0, png_int_32 X1, int type, int nparams,
  183437. png_charp units, png_charpp params));
  183438. #endif
  183439. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  183440. PNG_EXTERN void png_write_pHYs PNGARG((png_structp png_ptr,
  183441. png_uint_32 x_pixels_per_unit, png_uint_32 y_pixels_per_unit,
  183442. int unit_type));
  183443. #endif
  183444. #if defined(PNG_WRITE_tIME_SUPPORTED)
  183445. PNG_EXTERN void png_write_tIME PNGARG((png_structp png_ptr,
  183446. png_timep mod_time));
  183447. #endif
  183448. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  183449. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  183450. PNG_EXTERN void png_write_sCAL PNGARG((png_structp png_ptr,
  183451. int unit, double width, double height));
  183452. #else
  183453. #ifdef PNG_FIXED_POINT_SUPPORTED
  183454. PNG_EXTERN void png_write_sCAL_s PNGARG((png_structp png_ptr,
  183455. int unit, png_charp width, png_charp height));
  183456. #endif
  183457. #endif
  183458. #endif
  183459. /* Called when finished processing a row of data */
  183460. PNG_EXTERN void png_write_finish_row PNGARG((png_structp png_ptr));
  183461. /* Internal use only. Called before first row of data */
  183462. PNG_EXTERN void png_write_start_row PNGARG((png_structp png_ptr));
  183463. #if defined(PNG_READ_GAMMA_SUPPORTED)
  183464. PNG_EXTERN void png_build_gamma_table PNGARG((png_structp png_ptr));
  183465. #endif
  183466. /* combine a row of data, dealing with alpha, etc. if requested */
  183467. PNG_EXTERN void png_combine_row PNGARG((png_structp png_ptr, png_bytep row,
  183468. int mask));
  183469. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  183470. /* expand an interlaced row */
  183471. /* OLD pre-1.0.9 interface:
  183472. PNG_EXTERN void png_do_read_interlace PNGARG((png_row_infop row_info,
  183473. png_bytep row, int pass, png_uint_32 transformations));
  183474. */
  183475. PNG_EXTERN void png_do_read_interlace PNGARG((png_structp png_ptr));
  183476. #endif
  183477. /* GRR TO DO (2.0 or whenever): simplify other internal calling interfaces */
  183478. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  183479. /* grab pixels out of a row for an interlaced pass */
  183480. PNG_EXTERN void png_do_write_interlace PNGARG((png_row_infop row_info,
  183481. png_bytep row, int pass));
  183482. #endif
  183483. /* unfilter a row */
  183484. PNG_EXTERN void png_read_filter_row PNGARG((png_structp png_ptr,
  183485. png_row_infop row_info, png_bytep row, png_bytep prev_row, int filter));
  183486. /* Choose the best filter to use and filter the row data */
  183487. PNG_EXTERN void png_write_find_filter PNGARG((png_structp png_ptr,
  183488. png_row_infop row_info));
  183489. /* Write out the filtered row. */
  183490. PNG_EXTERN void png_write_filtered_row PNGARG((png_structp png_ptr,
  183491. png_bytep filtered_row));
  183492. /* finish a row while reading, dealing with interlacing passes, etc. */
  183493. PNG_EXTERN void png_read_finish_row PNGARG((png_structp png_ptr));
  183494. /* initialize the row buffers, etc. */
  183495. PNG_EXTERN void png_read_start_row PNGARG((png_structp png_ptr));
  183496. /* optional call to update the users info structure */
  183497. PNG_EXTERN void png_read_transform_info PNGARG((png_structp png_ptr,
  183498. png_infop info_ptr));
  183499. /* these are the functions that do the transformations */
  183500. #if defined(PNG_READ_FILLER_SUPPORTED)
  183501. PNG_EXTERN void png_do_read_filler PNGARG((png_row_infop row_info,
  183502. png_bytep row, png_uint_32 filler, png_uint_32 flags));
  183503. #endif
  183504. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  183505. PNG_EXTERN void png_do_read_swap_alpha PNGARG((png_row_infop row_info,
  183506. png_bytep row));
  183507. #endif
  183508. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  183509. PNG_EXTERN void png_do_write_swap_alpha PNGARG((png_row_infop row_info,
  183510. png_bytep row));
  183511. #endif
  183512. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  183513. PNG_EXTERN void png_do_read_invert_alpha PNGARG((png_row_infop row_info,
  183514. png_bytep row));
  183515. #endif
  183516. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  183517. PNG_EXTERN void png_do_write_invert_alpha PNGARG((png_row_infop row_info,
  183518. png_bytep row));
  183519. #endif
  183520. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  183521. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  183522. PNG_EXTERN void png_do_strip_filler PNGARG((png_row_infop row_info,
  183523. png_bytep row, png_uint_32 flags));
  183524. #endif
  183525. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  183526. PNG_EXTERN void png_do_swap PNGARG((png_row_infop row_info, png_bytep row));
  183527. #endif
  183528. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  183529. PNG_EXTERN void png_do_packswap PNGARG((png_row_infop row_info, png_bytep row));
  183530. #endif
  183531. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  183532. PNG_EXTERN int png_do_rgb_to_gray PNGARG((png_structp png_ptr, png_row_infop
  183533. row_info, png_bytep row));
  183534. #endif
  183535. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  183536. PNG_EXTERN void png_do_gray_to_rgb PNGARG((png_row_infop row_info,
  183537. png_bytep row));
  183538. #endif
  183539. #if defined(PNG_READ_PACK_SUPPORTED)
  183540. PNG_EXTERN void png_do_unpack PNGARG((png_row_infop row_info, png_bytep row));
  183541. #endif
  183542. #if defined(PNG_READ_SHIFT_SUPPORTED)
  183543. PNG_EXTERN void png_do_unshift PNGARG((png_row_infop row_info, png_bytep row,
  183544. png_color_8p sig_bits));
  183545. #endif
  183546. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  183547. PNG_EXTERN void png_do_invert PNGARG((png_row_infop row_info, png_bytep row));
  183548. #endif
  183549. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  183550. PNG_EXTERN void png_do_chop PNGARG((png_row_infop row_info, png_bytep row));
  183551. #endif
  183552. #if defined(PNG_READ_DITHER_SUPPORTED)
  183553. PNG_EXTERN void png_do_dither PNGARG((png_row_infop row_info,
  183554. png_bytep row, png_bytep palette_lookup, png_bytep dither_lookup));
  183555. # if defined(PNG_CORRECT_PALETTE_SUPPORTED)
  183556. PNG_EXTERN void png_correct_palette PNGARG((png_structp png_ptr,
  183557. png_colorp palette, int num_palette));
  183558. # endif
  183559. #endif
  183560. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  183561. PNG_EXTERN void png_do_bgr PNGARG((png_row_infop row_info, png_bytep row));
  183562. #endif
  183563. #if defined(PNG_WRITE_PACK_SUPPORTED)
  183564. PNG_EXTERN void png_do_pack PNGARG((png_row_infop row_info,
  183565. png_bytep row, png_uint_32 bit_depth));
  183566. #endif
  183567. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  183568. PNG_EXTERN void png_do_shift PNGARG((png_row_infop row_info, png_bytep row,
  183569. png_color_8p bit_depth));
  183570. #endif
  183571. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  183572. #if defined(PNG_READ_GAMMA_SUPPORTED)
  183573. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  183574. png_color_16p trans_values, png_color_16p background,
  183575. png_color_16p background_1,
  183576. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  183577. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  183578. png_uint_16pp gamma_16_to_1, int gamma_shift));
  183579. #else
  183580. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  183581. png_color_16p trans_values, png_color_16p background));
  183582. #endif
  183583. #endif
  183584. #if defined(PNG_READ_GAMMA_SUPPORTED)
  183585. PNG_EXTERN void png_do_gamma PNGARG((png_row_infop row_info, png_bytep row,
  183586. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  183587. int gamma_shift));
  183588. #endif
  183589. #if defined(PNG_READ_EXPAND_SUPPORTED)
  183590. PNG_EXTERN void png_do_expand_palette PNGARG((png_row_infop row_info,
  183591. png_bytep row, png_colorp palette, png_bytep trans, int num_trans));
  183592. PNG_EXTERN void png_do_expand PNGARG((png_row_infop row_info,
  183593. png_bytep row, png_color_16p trans_value));
  183594. #endif
  183595. /* The following decodes the appropriate chunks, and does error correction,
  183596. * then calls the appropriate callback for the chunk if it is valid.
  183597. */
  183598. /* decode the IHDR chunk */
  183599. PNG_EXTERN void png_handle_IHDR PNGARG((png_structp png_ptr, png_infop info_ptr,
  183600. png_uint_32 length));
  183601. PNG_EXTERN void png_handle_PLTE PNGARG((png_structp png_ptr, png_infop info_ptr,
  183602. png_uint_32 length));
  183603. PNG_EXTERN void png_handle_IEND PNGARG((png_structp png_ptr, png_infop info_ptr,
  183604. png_uint_32 length));
  183605. #if defined(PNG_READ_bKGD_SUPPORTED)
  183606. PNG_EXTERN void png_handle_bKGD PNGARG((png_structp png_ptr, png_infop info_ptr,
  183607. png_uint_32 length));
  183608. #endif
  183609. #if defined(PNG_READ_cHRM_SUPPORTED)
  183610. PNG_EXTERN void png_handle_cHRM PNGARG((png_structp png_ptr, png_infop info_ptr,
  183611. png_uint_32 length));
  183612. #endif
  183613. #if defined(PNG_READ_gAMA_SUPPORTED)
  183614. PNG_EXTERN void png_handle_gAMA PNGARG((png_structp png_ptr, png_infop info_ptr,
  183615. png_uint_32 length));
  183616. #endif
  183617. #if defined(PNG_READ_hIST_SUPPORTED)
  183618. PNG_EXTERN void png_handle_hIST PNGARG((png_structp png_ptr, png_infop info_ptr,
  183619. png_uint_32 length));
  183620. #endif
  183621. #if defined(PNG_READ_iCCP_SUPPORTED)
  183622. extern void png_handle_iCCP PNGARG((png_structp png_ptr, png_infop info_ptr,
  183623. png_uint_32 length));
  183624. #endif /* PNG_READ_iCCP_SUPPORTED */
  183625. #if defined(PNG_READ_iTXt_SUPPORTED)
  183626. PNG_EXTERN void png_handle_iTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  183627. png_uint_32 length));
  183628. #endif
  183629. #if defined(PNG_READ_oFFs_SUPPORTED)
  183630. PNG_EXTERN void png_handle_oFFs PNGARG((png_structp png_ptr, png_infop info_ptr,
  183631. png_uint_32 length));
  183632. #endif
  183633. #if defined(PNG_READ_pCAL_SUPPORTED)
  183634. PNG_EXTERN void png_handle_pCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  183635. png_uint_32 length));
  183636. #endif
  183637. #if defined(PNG_READ_pHYs_SUPPORTED)
  183638. PNG_EXTERN void png_handle_pHYs PNGARG((png_structp png_ptr, png_infop info_ptr,
  183639. png_uint_32 length));
  183640. #endif
  183641. #if defined(PNG_READ_sBIT_SUPPORTED)
  183642. PNG_EXTERN void png_handle_sBIT PNGARG((png_structp png_ptr, png_infop info_ptr,
  183643. png_uint_32 length));
  183644. #endif
  183645. #if defined(PNG_READ_sCAL_SUPPORTED)
  183646. PNG_EXTERN void png_handle_sCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  183647. png_uint_32 length));
  183648. #endif
  183649. #if defined(PNG_READ_sPLT_SUPPORTED)
  183650. extern void png_handle_sPLT PNGARG((png_structp png_ptr, png_infop info_ptr,
  183651. png_uint_32 length));
  183652. #endif /* PNG_READ_sPLT_SUPPORTED */
  183653. #if defined(PNG_READ_sRGB_SUPPORTED)
  183654. PNG_EXTERN void png_handle_sRGB PNGARG((png_structp png_ptr, png_infop info_ptr,
  183655. png_uint_32 length));
  183656. #endif
  183657. #if defined(PNG_READ_tEXt_SUPPORTED)
  183658. PNG_EXTERN void png_handle_tEXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  183659. png_uint_32 length));
  183660. #endif
  183661. #if defined(PNG_READ_tIME_SUPPORTED)
  183662. PNG_EXTERN void png_handle_tIME PNGARG((png_structp png_ptr, png_infop info_ptr,
  183663. png_uint_32 length));
  183664. #endif
  183665. #if defined(PNG_READ_tRNS_SUPPORTED)
  183666. PNG_EXTERN void png_handle_tRNS PNGARG((png_structp png_ptr, png_infop info_ptr,
  183667. png_uint_32 length));
  183668. #endif
  183669. #if defined(PNG_READ_zTXt_SUPPORTED)
  183670. PNG_EXTERN void png_handle_zTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  183671. png_uint_32 length));
  183672. #endif
  183673. PNG_EXTERN void png_handle_unknown PNGARG((png_structp png_ptr,
  183674. png_infop info_ptr, png_uint_32 length));
  183675. PNG_EXTERN void png_check_chunk_name PNGARG((png_structp png_ptr,
  183676. png_bytep chunk_name));
  183677. /* handle the transformations for reading and writing */
  183678. PNG_EXTERN void png_do_read_transformations PNGARG((png_structp png_ptr));
  183679. PNG_EXTERN void png_do_write_transformations PNGARG((png_structp png_ptr));
  183680. PNG_EXTERN void png_init_read_transformations PNGARG((png_structp png_ptr));
  183681. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183682. PNG_EXTERN void png_push_read_chunk PNGARG((png_structp png_ptr,
  183683. png_infop info_ptr));
  183684. PNG_EXTERN void png_push_read_sig PNGARG((png_structp png_ptr,
  183685. png_infop info_ptr));
  183686. PNG_EXTERN void png_push_check_crc PNGARG((png_structp png_ptr));
  183687. PNG_EXTERN void png_push_crc_skip PNGARG((png_structp png_ptr,
  183688. png_uint_32 length));
  183689. PNG_EXTERN void png_push_crc_finish PNGARG((png_structp png_ptr));
  183690. PNG_EXTERN void png_push_save_buffer PNGARG((png_structp png_ptr));
  183691. PNG_EXTERN void png_push_restore_buffer PNGARG((png_structp png_ptr,
  183692. png_bytep buffer, png_size_t buffer_length));
  183693. PNG_EXTERN void png_push_read_IDAT PNGARG((png_structp png_ptr));
  183694. PNG_EXTERN void png_process_IDAT_data PNGARG((png_structp png_ptr,
  183695. png_bytep buffer, png_size_t buffer_length));
  183696. PNG_EXTERN void png_push_process_row PNGARG((png_structp png_ptr));
  183697. PNG_EXTERN void png_push_handle_unknown PNGARG((png_structp png_ptr,
  183698. png_infop info_ptr, png_uint_32 length));
  183699. PNG_EXTERN void png_push_have_info PNGARG((png_structp png_ptr,
  183700. png_infop info_ptr));
  183701. PNG_EXTERN void png_push_have_end PNGARG((png_structp png_ptr,
  183702. png_infop info_ptr));
  183703. PNG_EXTERN void png_push_have_row PNGARG((png_structp png_ptr, png_bytep row));
  183704. PNG_EXTERN void png_push_read_end PNGARG((png_structp png_ptr,
  183705. png_infop info_ptr));
  183706. PNG_EXTERN void png_process_some_data PNGARG((png_structp png_ptr,
  183707. png_infop info_ptr));
  183708. PNG_EXTERN void png_read_push_finish_row PNGARG((png_structp png_ptr));
  183709. #if defined(PNG_READ_tEXt_SUPPORTED)
  183710. PNG_EXTERN void png_push_handle_tEXt PNGARG((png_structp png_ptr,
  183711. png_infop info_ptr, png_uint_32 length));
  183712. PNG_EXTERN void png_push_read_tEXt PNGARG((png_structp png_ptr,
  183713. png_infop info_ptr));
  183714. #endif
  183715. #if defined(PNG_READ_zTXt_SUPPORTED)
  183716. PNG_EXTERN void png_push_handle_zTXt PNGARG((png_structp png_ptr,
  183717. png_infop info_ptr, png_uint_32 length));
  183718. PNG_EXTERN void png_push_read_zTXt PNGARG((png_structp png_ptr,
  183719. png_infop info_ptr));
  183720. #endif
  183721. #if defined(PNG_READ_iTXt_SUPPORTED)
  183722. PNG_EXTERN void png_push_handle_iTXt PNGARG((png_structp png_ptr,
  183723. png_infop info_ptr, png_uint_32 length));
  183724. PNG_EXTERN void png_push_read_iTXt PNGARG((png_structp png_ptr,
  183725. png_infop info_ptr));
  183726. #endif
  183727. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  183728. #ifdef PNG_MNG_FEATURES_SUPPORTED
  183729. PNG_EXTERN void png_do_read_intrapixel PNGARG((png_row_infop row_info,
  183730. png_bytep row));
  183731. PNG_EXTERN void png_do_write_intrapixel PNGARG((png_row_infop row_info,
  183732. png_bytep row));
  183733. #endif
  183734. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  183735. #if defined(PNG_MMX_CODE_SUPPORTED)
  183736. /* png.c */ /* PRIVATE */
  183737. PNG_EXTERN void png_init_mmx_flags PNGARG((png_structp png_ptr));
  183738. #endif
  183739. #endif
  183740. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  183741. PNG_EXTERN png_uint_32 png_get_pixels_per_inch PNGARG((png_structp png_ptr,
  183742. png_infop info_ptr));
  183743. PNG_EXTERN png_uint_32 png_get_x_pixels_per_inch PNGARG((png_structp png_ptr,
  183744. png_infop info_ptr));
  183745. PNG_EXTERN png_uint_32 png_get_y_pixels_per_inch PNGARG((png_structp png_ptr,
  183746. png_infop info_ptr));
  183747. PNG_EXTERN float png_get_x_offset_inches PNGARG((png_structp png_ptr,
  183748. png_infop info_ptr));
  183749. PNG_EXTERN float png_get_y_offset_inches PNGARG((png_structp png_ptr,
  183750. png_infop info_ptr));
  183751. #if defined(PNG_pHYs_SUPPORTED)
  183752. PNG_EXTERN png_uint_32 png_get_pHYs_dpi PNGARG((png_structp png_ptr,
  183753. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  183754. #endif /* PNG_pHYs_SUPPORTED */
  183755. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  183756. /* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */
  183757. #endif /* PNG_INTERNAL */
  183758. #ifdef __cplusplus
  183759. }
  183760. #endif
  183761. #endif /* PNG_VERSION_INFO_ONLY */
  183762. /* do not put anything past this line */
  183763. #endif /* PNG_H */
  183764. /*** End of inlined file: png.h ***/
  183765. #define PNG_NO_EXTERN
  183766. /*** Start of inlined file: png.c ***/
  183767. /* png.c - location for general purpose libpng functions
  183768. *
  183769. * Last changed in libpng 1.2.21 [October 4, 2007]
  183770. * For conditions of distribution and use, see copyright notice in png.h
  183771. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  183772. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  183773. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  183774. */
  183775. #define PNG_INTERNAL
  183776. #define PNG_NO_EXTERN
  183777. /* Generate a compiler error if there is an old png.h in the search path. */
  183778. typedef version_1_2_21 Your_png_h_is_not_version_1_2_21;
  183779. /* Version information for C files. This had better match the version
  183780. * string defined in png.h. */
  183781. #ifdef PNG_USE_GLOBAL_ARRAYS
  183782. /* png_libpng_ver was changed to a function in version 1.0.5c */
  183783. PNG_CONST char png_libpng_ver[18] = PNG_LIBPNG_VER_STRING;
  183784. #ifdef PNG_READ_SUPPORTED
  183785. /* png_sig was changed to a function in version 1.0.5c */
  183786. /* Place to hold the signature string for a PNG file. */
  183787. PNG_CONST png_byte FARDATA png_sig[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  183788. #endif /* PNG_READ_SUPPORTED */
  183789. /* Invoke global declarations for constant strings for known chunk types */
  183790. PNG_IHDR;
  183791. PNG_IDAT;
  183792. PNG_IEND;
  183793. PNG_PLTE;
  183794. PNG_bKGD;
  183795. PNG_cHRM;
  183796. PNG_gAMA;
  183797. PNG_hIST;
  183798. PNG_iCCP;
  183799. PNG_iTXt;
  183800. PNG_oFFs;
  183801. PNG_pCAL;
  183802. PNG_sCAL;
  183803. PNG_pHYs;
  183804. PNG_sBIT;
  183805. PNG_sPLT;
  183806. PNG_sRGB;
  183807. PNG_tEXt;
  183808. PNG_tIME;
  183809. PNG_tRNS;
  183810. PNG_zTXt;
  183811. #ifdef PNG_READ_SUPPORTED
  183812. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  183813. /* start of interlace block */
  183814. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  183815. /* offset to next interlace block */
  183816. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  183817. /* start of interlace block in the y direction */
  183818. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  183819. /* offset to next interlace block in the y direction */
  183820. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  183821. /* Height of interlace block. This is not currently used - if you need
  183822. * it, uncomment it here and in png.h
  183823. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  183824. */
  183825. /* Mask to determine which pixels are valid in a pass */
  183826. PNG_CONST int FARDATA png_pass_mask[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  183827. /* Mask to determine which pixels to overwrite while displaying */
  183828. PNG_CONST int FARDATA png_pass_dsp_mask[]
  183829. = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  183830. #endif /* PNG_READ_SUPPORTED */
  183831. #endif /* PNG_USE_GLOBAL_ARRAYS */
  183832. /* Tells libpng that we have already handled the first "num_bytes" bytes
  183833. * of the PNG file signature. If the PNG data is embedded into another
  183834. * stream we can set num_bytes = 8 so that libpng will not attempt to read
  183835. * or write any of the magic bytes before it starts on the IHDR.
  183836. */
  183837. #ifdef PNG_READ_SUPPORTED
  183838. void PNGAPI
  183839. png_set_sig_bytes(png_structp png_ptr, int num_bytes)
  183840. {
  183841. if(png_ptr == NULL) return;
  183842. png_debug(1, "in png_set_sig_bytes\n");
  183843. if (num_bytes > 8)
  183844. png_error(png_ptr, "Too many bytes for PNG signature.");
  183845. png_ptr->sig_bytes = (png_byte)(num_bytes < 0 ? 0 : num_bytes);
  183846. }
  183847. /* Checks whether the supplied bytes match the PNG signature. We allow
  183848. * checking less than the full 8-byte signature so that those apps that
  183849. * already read the first few bytes of a file to determine the file type
  183850. * can simply check the remaining bytes for extra assurance. Returns
  183851. * an integer less than, equal to, or greater than zero if sig is found,
  183852. * respectively, to be less than, to match, or be greater than the correct
  183853. * PNG signature (this is the same behaviour as strcmp, memcmp, etc).
  183854. */
  183855. int PNGAPI
  183856. png_sig_cmp(png_bytep sig, png_size_t start, png_size_t num_to_check)
  183857. {
  183858. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  183859. if (num_to_check > 8)
  183860. num_to_check = 8;
  183861. else if (num_to_check < 1)
  183862. return (-1);
  183863. if (start > 7)
  183864. return (-1);
  183865. if (start + num_to_check > 8)
  183866. num_to_check = 8 - start;
  183867. return ((int)(png_memcmp(&sig[start], &png_signature[start], num_to_check)));
  183868. }
  183869. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  183870. /* (Obsolete) function to check signature bytes. It does not allow one
  183871. * to check a partial signature. This function might be removed in the
  183872. * future - use png_sig_cmp(). Returns true (nonzero) if the file is PNG.
  183873. */
  183874. int PNGAPI
  183875. png_check_sig(png_bytep sig, int num)
  183876. {
  183877. return ((int)!png_sig_cmp(sig, (png_size_t)0, (png_size_t)num));
  183878. }
  183879. #endif
  183880. #endif /* PNG_READ_SUPPORTED */
  183881. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  183882. /* Function to allocate memory for zlib and clear it to 0. */
  183883. #ifdef PNG_1_0_X
  183884. voidpf PNGAPI
  183885. #else
  183886. voidpf /* private */
  183887. #endif
  183888. png_zalloc(voidpf png_ptr, uInt items, uInt size)
  183889. {
  183890. png_voidp ptr;
  183891. png_structp p=(png_structp)png_ptr;
  183892. png_uint_32 save_flags=p->flags;
  183893. png_uint_32 num_bytes;
  183894. if(png_ptr == NULL) return (NULL);
  183895. if (items > PNG_UINT_32_MAX/size)
  183896. {
  183897. png_warning (p, "Potential overflow in png_zalloc()");
  183898. return (NULL);
  183899. }
  183900. num_bytes = (png_uint_32)items * size;
  183901. p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  183902. ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes);
  183903. p->flags=save_flags;
  183904. #if defined(PNG_1_0_X) && !defined(PNG_NO_ZALLOC_ZERO)
  183905. if (ptr == NULL)
  183906. return ((voidpf)ptr);
  183907. if (num_bytes > (png_uint_32)0x8000L)
  183908. {
  183909. png_memset(ptr, 0, (png_size_t)0x8000L);
  183910. png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0,
  183911. (png_size_t)(num_bytes - (png_uint_32)0x8000L));
  183912. }
  183913. else
  183914. {
  183915. png_memset(ptr, 0, (png_size_t)num_bytes);
  183916. }
  183917. #endif
  183918. return ((voidpf)ptr);
  183919. }
  183920. /* function to free memory for zlib */
  183921. #ifdef PNG_1_0_X
  183922. void PNGAPI
  183923. #else
  183924. void /* private */
  183925. #endif
  183926. png_zfree(voidpf png_ptr, voidpf ptr)
  183927. {
  183928. png_free((png_structp)png_ptr, (png_voidp)ptr);
  183929. }
  183930. /* Reset the CRC variable to 32 bits of 1's. Care must be taken
  183931. * in case CRC is > 32 bits to leave the top bits 0.
  183932. */
  183933. void /* PRIVATE */
  183934. png_reset_crc(png_structp png_ptr)
  183935. {
  183936. png_ptr->crc = crc32(0, Z_NULL, 0);
  183937. }
  183938. /* Calculate the CRC over a section of data. We can only pass as
  183939. * much data to this routine as the largest single buffer size. We
  183940. * also check that this data will actually be used before going to the
  183941. * trouble of calculating it.
  183942. */
  183943. void /* PRIVATE */
  183944. png_calculate_crc(png_structp png_ptr, png_bytep ptr, png_size_t length)
  183945. {
  183946. int need_crc = 1;
  183947. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  183948. {
  183949. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  183950. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  183951. need_crc = 0;
  183952. }
  183953. else /* critical */
  183954. {
  183955. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  183956. need_crc = 0;
  183957. }
  183958. if (need_crc)
  183959. png_ptr->crc = crc32(png_ptr->crc, ptr, (uInt)length);
  183960. }
  183961. /* Allocate the memory for an info_struct for the application. We don't
  183962. * really need the png_ptr, but it could potentially be useful in the
  183963. * future. This should be used in favour of malloc(png_sizeof(png_info))
  183964. * and png_info_init() so that applications that want to use a shared
  183965. * libpng don't have to be recompiled if png_info changes size.
  183966. */
  183967. png_infop PNGAPI
  183968. png_create_info_struct(png_structp png_ptr)
  183969. {
  183970. png_infop info_ptr;
  183971. png_debug(1, "in png_create_info_struct\n");
  183972. if(png_ptr == NULL) return (NULL);
  183973. #ifdef PNG_USER_MEM_SUPPORTED
  183974. info_ptr = (png_infop)png_create_struct_2(PNG_STRUCT_INFO,
  183975. png_ptr->malloc_fn, png_ptr->mem_ptr);
  183976. #else
  183977. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  183978. #endif
  183979. if (info_ptr != NULL)
  183980. png_info_init_3(&info_ptr, png_sizeof(png_info));
  183981. return (info_ptr);
  183982. }
  183983. /* This function frees the memory associated with a single info struct.
  183984. * Normally, one would use either png_destroy_read_struct() or
  183985. * png_destroy_write_struct() to free an info struct, but this may be
  183986. * useful for some applications.
  183987. */
  183988. void PNGAPI
  183989. png_destroy_info_struct(png_structp png_ptr, png_infopp info_ptr_ptr)
  183990. {
  183991. png_infop info_ptr = NULL;
  183992. if(png_ptr == NULL) return;
  183993. png_debug(1, "in png_destroy_info_struct\n");
  183994. if (info_ptr_ptr != NULL)
  183995. info_ptr = *info_ptr_ptr;
  183996. if (info_ptr != NULL)
  183997. {
  183998. png_info_destroy(png_ptr, info_ptr);
  183999. #ifdef PNG_USER_MEM_SUPPORTED
  184000. png_destroy_struct_2((png_voidp)info_ptr, png_ptr->free_fn,
  184001. png_ptr->mem_ptr);
  184002. #else
  184003. png_destroy_struct((png_voidp)info_ptr);
  184004. #endif
  184005. *info_ptr_ptr = NULL;
  184006. }
  184007. }
  184008. /* Initialize the info structure. This is now an internal function (0.89)
  184009. * and applications using it are urged to use png_create_info_struct()
  184010. * instead.
  184011. */
  184012. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  184013. #undef png_info_init
  184014. void PNGAPI
  184015. png_info_init(png_infop info_ptr)
  184016. {
  184017. /* We only come here via pre-1.0.12-compiled applications */
  184018. png_info_init_3(&info_ptr, 0);
  184019. }
  184020. #endif
  184021. void PNGAPI
  184022. png_info_init_3(png_infopp ptr_ptr, png_size_t png_info_struct_size)
  184023. {
  184024. png_infop info_ptr = *ptr_ptr;
  184025. if(info_ptr == NULL) return;
  184026. png_debug(1, "in png_info_init_3\n");
  184027. if(png_sizeof(png_info) > png_info_struct_size)
  184028. {
  184029. png_destroy_struct(info_ptr);
  184030. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  184031. *ptr_ptr = info_ptr;
  184032. }
  184033. /* set everything to 0 */
  184034. png_memset(info_ptr, 0, png_sizeof (png_info));
  184035. }
  184036. #ifdef PNG_FREE_ME_SUPPORTED
  184037. void PNGAPI
  184038. png_data_freer(png_structp png_ptr, png_infop info_ptr,
  184039. int freer, png_uint_32 mask)
  184040. {
  184041. png_debug(1, "in png_data_freer\n");
  184042. if (png_ptr == NULL || info_ptr == NULL)
  184043. return;
  184044. if(freer == PNG_DESTROY_WILL_FREE_DATA)
  184045. info_ptr->free_me |= mask;
  184046. else if(freer == PNG_USER_WILL_FREE_DATA)
  184047. info_ptr->free_me &= ~mask;
  184048. else
  184049. png_warning(png_ptr,
  184050. "Unknown freer parameter in png_data_freer.");
  184051. }
  184052. #endif
  184053. void PNGAPI
  184054. png_free_data(png_structp png_ptr, png_infop info_ptr, png_uint_32 mask,
  184055. int num)
  184056. {
  184057. png_debug(1, "in png_free_data\n");
  184058. if (png_ptr == NULL || info_ptr == NULL)
  184059. return;
  184060. #if defined(PNG_TEXT_SUPPORTED)
  184061. /* free text item num or (if num == -1) all text items */
  184062. #ifdef PNG_FREE_ME_SUPPORTED
  184063. if ((mask & PNG_FREE_TEXT) & info_ptr->free_me)
  184064. #else
  184065. if (mask & PNG_FREE_TEXT)
  184066. #endif
  184067. {
  184068. if (num != -1)
  184069. {
  184070. if (info_ptr->text && info_ptr->text[num].key)
  184071. {
  184072. png_free(png_ptr, info_ptr->text[num].key);
  184073. info_ptr->text[num].key = NULL;
  184074. }
  184075. }
  184076. else
  184077. {
  184078. int i;
  184079. for (i = 0; i < info_ptr->num_text; i++)
  184080. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, i);
  184081. png_free(png_ptr, info_ptr->text);
  184082. info_ptr->text = NULL;
  184083. info_ptr->num_text=0;
  184084. }
  184085. }
  184086. #endif
  184087. #if defined(PNG_tRNS_SUPPORTED)
  184088. /* free any tRNS entry */
  184089. #ifdef PNG_FREE_ME_SUPPORTED
  184090. if ((mask & PNG_FREE_TRNS) & info_ptr->free_me)
  184091. #else
  184092. if ((mask & PNG_FREE_TRNS) && (png_ptr->flags & PNG_FLAG_FREE_TRNS))
  184093. #endif
  184094. {
  184095. png_free(png_ptr, info_ptr->trans);
  184096. info_ptr->valid &= ~PNG_INFO_tRNS;
  184097. #ifndef PNG_FREE_ME_SUPPORTED
  184098. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  184099. #endif
  184100. info_ptr->trans = NULL;
  184101. }
  184102. #endif
  184103. #if defined(PNG_sCAL_SUPPORTED)
  184104. /* free any sCAL entry */
  184105. #ifdef PNG_FREE_ME_SUPPORTED
  184106. if ((mask & PNG_FREE_SCAL) & info_ptr->free_me)
  184107. #else
  184108. if (mask & PNG_FREE_SCAL)
  184109. #endif
  184110. {
  184111. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  184112. png_free(png_ptr, info_ptr->scal_s_width);
  184113. png_free(png_ptr, info_ptr->scal_s_height);
  184114. info_ptr->scal_s_width = NULL;
  184115. info_ptr->scal_s_height = NULL;
  184116. #endif
  184117. info_ptr->valid &= ~PNG_INFO_sCAL;
  184118. }
  184119. #endif
  184120. #if defined(PNG_pCAL_SUPPORTED)
  184121. /* free any pCAL entry */
  184122. #ifdef PNG_FREE_ME_SUPPORTED
  184123. if ((mask & PNG_FREE_PCAL) & info_ptr->free_me)
  184124. #else
  184125. if (mask & PNG_FREE_PCAL)
  184126. #endif
  184127. {
  184128. png_free(png_ptr, info_ptr->pcal_purpose);
  184129. png_free(png_ptr, info_ptr->pcal_units);
  184130. info_ptr->pcal_purpose = NULL;
  184131. info_ptr->pcal_units = NULL;
  184132. if (info_ptr->pcal_params != NULL)
  184133. {
  184134. int i;
  184135. for (i = 0; i < (int)info_ptr->pcal_nparams; i++)
  184136. {
  184137. png_free(png_ptr, info_ptr->pcal_params[i]);
  184138. info_ptr->pcal_params[i]=NULL;
  184139. }
  184140. png_free(png_ptr, info_ptr->pcal_params);
  184141. info_ptr->pcal_params = NULL;
  184142. }
  184143. info_ptr->valid &= ~PNG_INFO_pCAL;
  184144. }
  184145. #endif
  184146. #if defined(PNG_iCCP_SUPPORTED)
  184147. /* free any iCCP entry */
  184148. #ifdef PNG_FREE_ME_SUPPORTED
  184149. if ((mask & PNG_FREE_ICCP) & info_ptr->free_me)
  184150. #else
  184151. if (mask & PNG_FREE_ICCP)
  184152. #endif
  184153. {
  184154. png_free(png_ptr, info_ptr->iccp_name);
  184155. png_free(png_ptr, info_ptr->iccp_profile);
  184156. info_ptr->iccp_name = NULL;
  184157. info_ptr->iccp_profile = NULL;
  184158. info_ptr->valid &= ~PNG_INFO_iCCP;
  184159. }
  184160. #endif
  184161. #if defined(PNG_sPLT_SUPPORTED)
  184162. /* free a given sPLT entry, or (if num == -1) all sPLT entries */
  184163. #ifdef PNG_FREE_ME_SUPPORTED
  184164. if ((mask & PNG_FREE_SPLT) & info_ptr->free_me)
  184165. #else
  184166. if (mask & PNG_FREE_SPLT)
  184167. #endif
  184168. {
  184169. if (num != -1)
  184170. {
  184171. if(info_ptr->splt_palettes)
  184172. {
  184173. png_free(png_ptr, info_ptr->splt_palettes[num].name);
  184174. png_free(png_ptr, info_ptr->splt_palettes[num].entries);
  184175. info_ptr->splt_palettes[num].name = NULL;
  184176. info_ptr->splt_palettes[num].entries = NULL;
  184177. }
  184178. }
  184179. else
  184180. {
  184181. if(info_ptr->splt_palettes_num)
  184182. {
  184183. int i;
  184184. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  184185. png_free_data(png_ptr, info_ptr, PNG_FREE_SPLT, i);
  184186. png_free(png_ptr, info_ptr->splt_palettes);
  184187. info_ptr->splt_palettes = NULL;
  184188. info_ptr->splt_palettes_num = 0;
  184189. }
  184190. info_ptr->valid &= ~PNG_INFO_sPLT;
  184191. }
  184192. }
  184193. #endif
  184194. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  184195. if(png_ptr->unknown_chunk.data)
  184196. {
  184197. png_free(png_ptr, png_ptr->unknown_chunk.data);
  184198. png_ptr->unknown_chunk.data = NULL;
  184199. }
  184200. #ifdef PNG_FREE_ME_SUPPORTED
  184201. if ((mask & PNG_FREE_UNKN) & info_ptr->free_me)
  184202. #else
  184203. if (mask & PNG_FREE_UNKN)
  184204. #endif
  184205. {
  184206. if (num != -1)
  184207. {
  184208. if(info_ptr->unknown_chunks)
  184209. {
  184210. png_free(png_ptr, info_ptr->unknown_chunks[num].data);
  184211. info_ptr->unknown_chunks[num].data = NULL;
  184212. }
  184213. }
  184214. else
  184215. {
  184216. int i;
  184217. if(info_ptr->unknown_chunks_num)
  184218. {
  184219. for (i = 0; i < (int)info_ptr->unknown_chunks_num; i++)
  184220. png_free_data(png_ptr, info_ptr, PNG_FREE_UNKN, i);
  184221. png_free(png_ptr, info_ptr->unknown_chunks);
  184222. info_ptr->unknown_chunks = NULL;
  184223. info_ptr->unknown_chunks_num = 0;
  184224. }
  184225. }
  184226. }
  184227. #endif
  184228. #if defined(PNG_hIST_SUPPORTED)
  184229. /* free any hIST entry */
  184230. #ifdef PNG_FREE_ME_SUPPORTED
  184231. if ((mask & PNG_FREE_HIST) & info_ptr->free_me)
  184232. #else
  184233. if ((mask & PNG_FREE_HIST) && (png_ptr->flags & PNG_FLAG_FREE_HIST))
  184234. #endif
  184235. {
  184236. png_free(png_ptr, info_ptr->hist);
  184237. info_ptr->hist = NULL;
  184238. info_ptr->valid &= ~PNG_INFO_hIST;
  184239. #ifndef PNG_FREE_ME_SUPPORTED
  184240. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  184241. #endif
  184242. }
  184243. #endif
  184244. /* free any PLTE entry that was internally allocated */
  184245. #ifdef PNG_FREE_ME_SUPPORTED
  184246. if ((mask & PNG_FREE_PLTE) & info_ptr->free_me)
  184247. #else
  184248. if ((mask & PNG_FREE_PLTE) && (png_ptr->flags & PNG_FLAG_FREE_PLTE))
  184249. #endif
  184250. {
  184251. png_zfree(png_ptr, info_ptr->palette);
  184252. info_ptr->palette = NULL;
  184253. info_ptr->valid &= ~PNG_INFO_PLTE;
  184254. #ifndef PNG_FREE_ME_SUPPORTED
  184255. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  184256. #endif
  184257. info_ptr->num_palette = 0;
  184258. }
  184259. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  184260. /* free any image bits attached to the info structure */
  184261. #ifdef PNG_FREE_ME_SUPPORTED
  184262. if ((mask & PNG_FREE_ROWS) & info_ptr->free_me)
  184263. #else
  184264. if (mask & PNG_FREE_ROWS)
  184265. #endif
  184266. {
  184267. if(info_ptr->row_pointers)
  184268. {
  184269. int row;
  184270. for (row = 0; row < (int)info_ptr->height; row++)
  184271. {
  184272. png_free(png_ptr, info_ptr->row_pointers[row]);
  184273. info_ptr->row_pointers[row]=NULL;
  184274. }
  184275. png_free(png_ptr, info_ptr->row_pointers);
  184276. info_ptr->row_pointers=NULL;
  184277. }
  184278. info_ptr->valid &= ~PNG_INFO_IDAT;
  184279. }
  184280. #endif
  184281. #ifdef PNG_FREE_ME_SUPPORTED
  184282. if(num == -1)
  184283. info_ptr->free_me &= ~mask;
  184284. else
  184285. info_ptr->free_me &= ~(mask & ~PNG_FREE_MUL);
  184286. #endif
  184287. }
  184288. /* This is an internal routine to free any memory that the info struct is
  184289. * pointing to before re-using it or freeing the struct itself. Recall
  184290. * that png_free() checks for NULL pointers for us.
  184291. */
  184292. void /* PRIVATE */
  184293. png_info_destroy(png_structp png_ptr, png_infop info_ptr)
  184294. {
  184295. png_debug(1, "in png_info_destroy\n");
  184296. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  184297. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  184298. if (png_ptr->num_chunk_list)
  184299. {
  184300. png_free(png_ptr, png_ptr->chunk_list);
  184301. png_ptr->chunk_list=NULL;
  184302. png_ptr->num_chunk_list=0;
  184303. }
  184304. #endif
  184305. png_info_init_3(&info_ptr, png_sizeof(png_info));
  184306. }
  184307. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  184308. /* This function returns a pointer to the io_ptr associated with the user
  184309. * functions. The application should free any memory associated with this
  184310. * pointer before png_write_destroy() or png_read_destroy() are called.
  184311. */
  184312. png_voidp PNGAPI
  184313. png_get_io_ptr(png_structp png_ptr)
  184314. {
  184315. if(png_ptr == NULL) return (NULL);
  184316. return (png_ptr->io_ptr);
  184317. }
  184318. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184319. #if !defined(PNG_NO_STDIO)
  184320. /* Initialize the default input/output functions for the PNG file. If you
  184321. * use your own read or write routines, you can call either png_set_read_fn()
  184322. * or png_set_write_fn() instead of png_init_io(). If you have defined
  184323. * PNG_NO_STDIO, you must use a function of your own because "FILE *" isn't
  184324. * necessarily available.
  184325. */
  184326. void PNGAPI
  184327. png_init_io(png_structp png_ptr, png_FILE_p fp)
  184328. {
  184329. png_debug(1, "in png_init_io\n");
  184330. if(png_ptr == NULL) return;
  184331. png_ptr->io_ptr = (png_voidp)fp;
  184332. }
  184333. #endif
  184334. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  184335. /* Convert the supplied time into an RFC 1123 string suitable for use in
  184336. * a "Creation Time" or other text-based time string.
  184337. */
  184338. png_charp PNGAPI
  184339. png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime)
  184340. {
  184341. static PNG_CONST char short_months[12][4] =
  184342. {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  184343. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  184344. if(png_ptr == NULL) return (NULL);
  184345. if (png_ptr->time_buffer == NULL)
  184346. {
  184347. png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29*
  184348. png_sizeof(char)));
  184349. }
  184350. #if defined(_WIN32_WCE)
  184351. {
  184352. wchar_t time_buf[29];
  184353. wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"),
  184354. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  184355. ptime->year, ptime->hour % 24, ptime->minute % 60,
  184356. ptime->second % 61);
  184357. WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer, 29,
  184358. NULL, NULL);
  184359. }
  184360. #else
  184361. #ifdef USE_FAR_KEYWORD
  184362. {
  184363. char near_time_buf[29];
  184364. png_snprintf6(near_time_buf,29,"%d %s %d %02d:%02d:%02d +0000",
  184365. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  184366. ptime->year, ptime->hour % 24, ptime->minute % 60,
  184367. ptime->second % 61);
  184368. png_memcpy(png_ptr->time_buffer, near_time_buf,
  184369. 29*png_sizeof(char));
  184370. }
  184371. #else
  184372. png_snprintf6(png_ptr->time_buffer,29,"%d %s %d %02d:%02d:%02d +0000",
  184373. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  184374. ptime->year, ptime->hour % 24, ptime->minute % 60,
  184375. ptime->second % 61);
  184376. #endif
  184377. #endif /* _WIN32_WCE */
  184378. return ((png_charp)png_ptr->time_buffer);
  184379. }
  184380. #endif /* PNG_TIME_RFC1123_SUPPORTED */
  184381. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  184382. png_charp PNGAPI
  184383. png_get_copyright(png_structp png_ptr)
  184384. {
  184385. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  184386. return ((png_charp) "\n libpng version 1.2.21 - October 4, 2007\n\
  184387. Copyright (c) 1998-2007 Glenn Randers-Pehrson\n\
  184388. Copyright (c) 1996-1997 Andreas Dilger\n\
  184389. Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.\n");
  184390. }
  184391. /* The following return the library version as a short string in the
  184392. * format 1.0.0 through 99.99.99zz. To get the version of *.h files
  184393. * used with your application, print out PNG_LIBPNG_VER_STRING, which
  184394. * is defined in png.h.
  184395. * Note: now there is no difference between png_get_libpng_ver() and
  184396. * png_get_header_ver(). Due to the version_nn_nn_nn typedef guard,
  184397. * it is guaranteed that png.c uses the correct version of png.h.
  184398. */
  184399. png_charp PNGAPI
  184400. png_get_libpng_ver(png_structp png_ptr)
  184401. {
  184402. /* Version of *.c files used when building libpng */
  184403. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  184404. return ((png_charp) PNG_LIBPNG_VER_STRING);
  184405. }
  184406. png_charp PNGAPI
  184407. png_get_header_ver(png_structp png_ptr)
  184408. {
  184409. /* Version of *.h files used when building libpng */
  184410. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  184411. return ((png_charp) PNG_LIBPNG_VER_STRING);
  184412. }
  184413. png_charp PNGAPI
  184414. png_get_header_version(png_structp png_ptr)
  184415. {
  184416. /* Returns longer string containing both version and date */
  184417. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  184418. return ((png_charp) PNG_HEADER_VERSION_STRING
  184419. #ifndef PNG_READ_SUPPORTED
  184420. " (NO READ SUPPORT)"
  184421. #endif
  184422. "\n");
  184423. }
  184424. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184425. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  184426. int PNGAPI
  184427. png_handle_as_unknown(png_structp png_ptr, png_bytep chunk_name)
  184428. {
  184429. /* check chunk_name and return "keep" value if it's on the list, else 0 */
  184430. int i;
  184431. png_bytep p;
  184432. if(png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list<=0)
  184433. return 0;
  184434. p=png_ptr->chunk_list+png_ptr->num_chunk_list*5-5;
  184435. for (i = png_ptr->num_chunk_list; i; i--, p-=5)
  184436. if (!png_memcmp(chunk_name, p, 4))
  184437. return ((int)*(p+4));
  184438. return 0;
  184439. }
  184440. #endif
  184441. /* This function, added to libpng-1.0.6g, is untested. */
  184442. int PNGAPI
  184443. png_reset_zstream(png_structp png_ptr)
  184444. {
  184445. if (png_ptr == NULL) return Z_STREAM_ERROR;
  184446. return (inflateReset(&png_ptr->zstream));
  184447. }
  184448. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  184449. /* This function was added to libpng-1.0.7 */
  184450. png_uint_32 PNGAPI
  184451. png_access_version_number(void)
  184452. {
  184453. /* Version of *.c files used when building libpng */
  184454. return((png_uint_32) PNG_LIBPNG_VER);
  184455. }
  184456. #if defined(PNG_READ_SUPPORTED) && defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  184457. #if !defined(PNG_1_0_X)
  184458. /* this function was added to libpng 1.2.0 */
  184459. int PNGAPI
  184460. png_mmx_support(void)
  184461. {
  184462. /* obsolete, to be removed from libpng-1.4.0 */
  184463. return -1;
  184464. }
  184465. #endif /* PNG_1_0_X */
  184466. #endif /* PNG_READ_SUPPORTED && PNG_ASSEMBLER_CODE_SUPPORTED */
  184467. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184468. #ifdef PNG_SIZE_T
  184469. /* Added at libpng version 1.2.6 */
  184470. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  184471. png_size_t PNGAPI
  184472. png_convert_size(size_t size)
  184473. {
  184474. if (size > (png_size_t)-1)
  184475. PNG_ABORT(); /* We haven't got access to png_ptr, so no png_error() */
  184476. return ((png_size_t)size);
  184477. }
  184478. #endif /* PNG_SIZE_T */
  184479. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  184480. /*** End of inlined file: png.c ***/
  184481. /*** Start of inlined file: pngerror.c ***/
  184482. /* pngerror.c - stub functions for i/o and memory allocation
  184483. *
  184484. * Last changed in libpng 1.2.20 October 4, 2007
  184485. * For conditions of distribution and use, see copyright notice in png.h
  184486. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  184487. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  184488. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  184489. *
  184490. * This file provides a location for all error handling. Users who
  184491. * need special error handling are expected to write replacement functions
  184492. * and use png_set_error_fn() to use those functions. See the instructions
  184493. * at each function.
  184494. */
  184495. #define PNG_INTERNAL
  184496. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184497. static void /* PRIVATE */
  184498. png_default_error PNGARG((png_structp png_ptr,
  184499. png_const_charp error_message));
  184500. #ifndef PNG_NO_WARNINGS
  184501. static void /* PRIVATE */
  184502. png_default_warning PNGARG((png_structp png_ptr,
  184503. png_const_charp warning_message));
  184504. #endif /* PNG_NO_WARNINGS */
  184505. /* This function is called whenever there is a fatal error. This function
  184506. * should not be changed. If there is a need to handle errors differently,
  184507. * you should supply a replacement error function and use png_set_error_fn()
  184508. * to replace the error function at run-time.
  184509. */
  184510. #ifndef PNG_NO_ERROR_TEXT
  184511. void PNGAPI
  184512. png_error(png_structp png_ptr, png_const_charp error_message)
  184513. {
  184514. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  184515. char msg[16];
  184516. if (png_ptr != NULL)
  184517. {
  184518. if (png_ptr->flags&
  184519. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  184520. {
  184521. if (*error_message == '#')
  184522. {
  184523. int offset;
  184524. for (offset=1; offset<15; offset++)
  184525. if (*(error_message+offset) == ' ')
  184526. break;
  184527. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  184528. {
  184529. int i;
  184530. for (i=0; i<offset-1; i++)
  184531. msg[i]=error_message[i+1];
  184532. msg[i]='\0';
  184533. error_message=msg;
  184534. }
  184535. else
  184536. error_message+=offset;
  184537. }
  184538. else
  184539. {
  184540. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  184541. {
  184542. msg[0]='0';
  184543. msg[1]='\0';
  184544. error_message=msg;
  184545. }
  184546. }
  184547. }
  184548. }
  184549. #endif
  184550. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  184551. (*(png_ptr->error_fn))(png_ptr, error_message);
  184552. /* If the custom handler doesn't exist, or if it returns,
  184553. use the default handler, which will not return. */
  184554. png_default_error(png_ptr, error_message);
  184555. }
  184556. #else
  184557. void PNGAPI
  184558. png_err(png_structp png_ptr)
  184559. {
  184560. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  184561. (*(png_ptr->error_fn))(png_ptr, '\0');
  184562. /* If the custom handler doesn't exist, or if it returns,
  184563. use the default handler, which will not return. */
  184564. png_default_error(png_ptr, '\0');
  184565. }
  184566. #endif /* PNG_NO_ERROR_TEXT */
  184567. #ifndef PNG_NO_WARNINGS
  184568. /* This function is called whenever there is a non-fatal error. This function
  184569. * should not be changed. If there is a need to handle warnings differently,
  184570. * you should supply a replacement warning function and use
  184571. * png_set_error_fn() to replace the warning function at run-time.
  184572. */
  184573. void PNGAPI
  184574. png_warning(png_structp png_ptr, png_const_charp warning_message)
  184575. {
  184576. int offset = 0;
  184577. if (png_ptr != NULL)
  184578. {
  184579. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  184580. if (png_ptr->flags&
  184581. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  184582. #endif
  184583. {
  184584. if (*warning_message == '#')
  184585. {
  184586. for (offset=1; offset<15; offset++)
  184587. if (*(warning_message+offset) == ' ')
  184588. break;
  184589. }
  184590. }
  184591. if (png_ptr != NULL && png_ptr->warning_fn != NULL)
  184592. (*(png_ptr->warning_fn))(png_ptr, warning_message+offset);
  184593. }
  184594. else
  184595. png_default_warning(png_ptr, warning_message+offset);
  184596. }
  184597. #endif /* PNG_NO_WARNINGS */
  184598. /* These utilities are used internally to build an error message that relates
  184599. * to the current chunk. The chunk name comes from png_ptr->chunk_name,
  184600. * this is used to prefix the message. The message is limited in length
  184601. * to 63 bytes, the name characters are output as hex digits wrapped in []
  184602. * if the character is invalid.
  184603. */
  184604. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  184605. /*static PNG_CONST char png_digit[16] = {
  184606. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  184607. 'A', 'B', 'C', 'D', 'E', 'F'
  184608. };*/
  184609. #if !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT)
  184610. static void /* PRIVATE */
  184611. png_format_buffer(png_structp png_ptr, png_charp buffer, png_const_charp
  184612. error_message)
  184613. {
  184614. int iout = 0, iin = 0;
  184615. while (iin < 4)
  184616. {
  184617. int c = png_ptr->chunk_name[iin++];
  184618. if (isnonalpha(c))
  184619. {
  184620. buffer[iout++] = '[';
  184621. buffer[iout++] = png_digit[(c & 0xf0) >> 4];
  184622. buffer[iout++] = png_digit[c & 0x0f];
  184623. buffer[iout++] = ']';
  184624. }
  184625. else
  184626. {
  184627. buffer[iout++] = (png_byte)c;
  184628. }
  184629. }
  184630. if (error_message == NULL)
  184631. buffer[iout] = 0;
  184632. else
  184633. {
  184634. buffer[iout++] = ':';
  184635. buffer[iout++] = ' ';
  184636. png_strncpy(buffer+iout, error_message, 63);
  184637. buffer[iout+63] = 0;
  184638. }
  184639. }
  184640. #ifdef PNG_READ_SUPPORTED
  184641. void PNGAPI
  184642. png_chunk_error(png_structp png_ptr, png_const_charp error_message)
  184643. {
  184644. char msg[18+64];
  184645. if (png_ptr == NULL)
  184646. png_error(png_ptr, error_message);
  184647. else
  184648. {
  184649. png_format_buffer(png_ptr, msg, error_message);
  184650. png_error(png_ptr, msg);
  184651. }
  184652. }
  184653. #endif /* PNG_READ_SUPPORTED */
  184654. #endif /* !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT) */
  184655. #ifndef PNG_NO_WARNINGS
  184656. void PNGAPI
  184657. png_chunk_warning(png_structp png_ptr, png_const_charp warning_message)
  184658. {
  184659. char msg[18+64];
  184660. if (png_ptr == NULL)
  184661. png_warning(png_ptr, warning_message);
  184662. else
  184663. {
  184664. png_format_buffer(png_ptr, msg, warning_message);
  184665. png_warning(png_ptr, msg);
  184666. }
  184667. }
  184668. #endif /* PNG_NO_WARNINGS */
  184669. /* This is the default error handling function. Note that replacements for
  184670. * this function MUST NOT RETURN, or the program will likely crash. This
  184671. * function is used by default, or if the program supplies NULL for the
  184672. * error function pointer in png_set_error_fn().
  184673. */
  184674. static void /* PRIVATE */
  184675. png_default_error(png_structp, png_const_charp error_message)
  184676. {
  184677. #ifndef PNG_NO_CONSOLE_IO
  184678. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  184679. if (*error_message == '#')
  184680. {
  184681. int offset;
  184682. char error_number[16];
  184683. for (offset=0; offset<15; offset++)
  184684. {
  184685. error_number[offset] = *(error_message+offset+1);
  184686. if (*(error_message+offset) == ' ')
  184687. break;
  184688. }
  184689. if((offset > 1) && (offset < 15))
  184690. {
  184691. error_number[offset-1]='\0';
  184692. fprintf(stderr, "libpng error no. %s: %s\n", error_number,
  184693. error_message+offset);
  184694. }
  184695. else
  184696. fprintf(stderr, "libpng error: %s, offset=%d\n", error_message,offset);
  184697. }
  184698. else
  184699. #endif
  184700. fprintf(stderr, "libpng error: %s\n", error_message);
  184701. #endif
  184702. #ifdef PNG_SETJMP_SUPPORTED
  184703. if (png_ptr)
  184704. {
  184705. # ifdef USE_FAR_KEYWORD
  184706. {
  184707. jmp_buf jmpbuf;
  184708. png_memcpy(jmpbuf, png_ptr->jmpbuf, png_sizeof(jmp_buf));
  184709. longjmp(jmpbuf, 1);
  184710. }
  184711. # else
  184712. longjmp(png_ptr->jmpbuf, 1);
  184713. # endif
  184714. }
  184715. #else
  184716. PNG_ABORT();
  184717. #endif
  184718. #ifdef PNG_NO_CONSOLE_IO
  184719. error_message = error_message; /* make compiler happy */
  184720. #endif
  184721. }
  184722. #ifndef PNG_NO_WARNINGS
  184723. /* This function is called when there is a warning, but the library thinks
  184724. * it can continue anyway. Replacement functions don't have to do anything
  184725. * here if you don't want them to. In the default configuration, png_ptr is
  184726. * not used, but it is passed in case it may be useful.
  184727. */
  184728. static void /* PRIVATE */
  184729. png_default_warning(png_structp png_ptr, png_const_charp warning_message)
  184730. {
  184731. #ifndef PNG_NO_CONSOLE_IO
  184732. # ifdef PNG_ERROR_NUMBERS_SUPPORTED
  184733. if (*warning_message == '#')
  184734. {
  184735. int offset;
  184736. char warning_number[16];
  184737. for (offset=0; offset<15; offset++)
  184738. {
  184739. warning_number[offset]=*(warning_message+offset+1);
  184740. if (*(warning_message+offset) == ' ')
  184741. break;
  184742. }
  184743. if((offset > 1) && (offset < 15))
  184744. {
  184745. warning_number[offset-1]='\0';
  184746. fprintf(stderr, "libpng warning no. %s: %s\n", warning_number,
  184747. warning_message+offset);
  184748. }
  184749. else
  184750. fprintf(stderr, "libpng warning: %s\n", warning_message);
  184751. }
  184752. else
  184753. # endif
  184754. fprintf(stderr, "libpng warning: %s\n", warning_message);
  184755. #else
  184756. warning_message = warning_message; /* make compiler happy */
  184757. #endif
  184758. png_ptr = png_ptr; /* make compiler happy */
  184759. }
  184760. #endif /* PNG_NO_WARNINGS */
  184761. /* This function is called when the application wants to use another method
  184762. * of handling errors and warnings. Note that the error function MUST NOT
  184763. * return to the calling routine or serious problems will occur. The return
  184764. * method used in the default routine calls longjmp(png_ptr->jmpbuf, 1)
  184765. */
  184766. void PNGAPI
  184767. png_set_error_fn(png_structp png_ptr, png_voidp error_ptr,
  184768. png_error_ptr error_fn, png_error_ptr warning_fn)
  184769. {
  184770. if (png_ptr == NULL)
  184771. return;
  184772. png_ptr->error_ptr = error_ptr;
  184773. png_ptr->error_fn = error_fn;
  184774. png_ptr->warning_fn = warning_fn;
  184775. }
  184776. /* This function returns a pointer to the error_ptr associated with the user
  184777. * functions. The application should free any memory associated with this
  184778. * pointer before png_write_destroy and png_read_destroy are called.
  184779. */
  184780. png_voidp PNGAPI
  184781. png_get_error_ptr(png_structp png_ptr)
  184782. {
  184783. if (png_ptr == NULL)
  184784. return NULL;
  184785. return ((png_voidp)png_ptr->error_ptr);
  184786. }
  184787. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  184788. void PNGAPI
  184789. png_set_strip_error_numbers(png_structp png_ptr, png_uint_32 strip_mode)
  184790. {
  184791. if(png_ptr != NULL)
  184792. {
  184793. png_ptr->flags &=
  184794. ((~(PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))&strip_mode);
  184795. }
  184796. }
  184797. #endif
  184798. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  184799. /*** End of inlined file: pngerror.c ***/
  184800. /*** Start of inlined file: pngget.c ***/
  184801. /* pngget.c - retrieval of values from info struct
  184802. *
  184803. * Last changed in libpng 1.2.15 January 5, 2007
  184804. * For conditions of distribution and use, see copyright notice in png.h
  184805. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  184806. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  184807. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  184808. */
  184809. #define PNG_INTERNAL
  184810. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184811. png_uint_32 PNGAPI
  184812. png_get_valid(png_structp png_ptr, png_infop info_ptr, png_uint_32 flag)
  184813. {
  184814. if (png_ptr != NULL && info_ptr != NULL)
  184815. return(info_ptr->valid & flag);
  184816. else
  184817. return(0);
  184818. }
  184819. png_uint_32 PNGAPI
  184820. png_get_rowbytes(png_structp png_ptr, png_infop info_ptr)
  184821. {
  184822. if (png_ptr != NULL && info_ptr != NULL)
  184823. return(info_ptr->rowbytes);
  184824. else
  184825. return(0);
  184826. }
  184827. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  184828. png_bytepp PNGAPI
  184829. png_get_rows(png_structp png_ptr, png_infop info_ptr)
  184830. {
  184831. if (png_ptr != NULL && info_ptr != NULL)
  184832. return(info_ptr->row_pointers);
  184833. else
  184834. return(0);
  184835. }
  184836. #endif
  184837. #ifdef PNG_EASY_ACCESS_SUPPORTED
  184838. /* easy access to info, added in libpng-0.99 */
  184839. png_uint_32 PNGAPI
  184840. png_get_image_width(png_structp png_ptr, png_infop info_ptr)
  184841. {
  184842. if (png_ptr != NULL && info_ptr != NULL)
  184843. {
  184844. return info_ptr->width;
  184845. }
  184846. return (0);
  184847. }
  184848. png_uint_32 PNGAPI
  184849. png_get_image_height(png_structp png_ptr, png_infop info_ptr)
  184850. {
  184851. if (png_ptr != NULL && info_ptr != NULL)
  184852. {
  184853. return info_ptr->height;
  184854. }
  184855. return (0);
  184856. }
  184857. png_byte PNGAPI
  184858. png_get_bit_depth(png_structp png_ptr, png_infop info_ptr)
  184859. {
  184860. if (png_ptr != NULL && info_ptr != NULL)
  184861. {
  184862. return info_ptr->bit_depth;
  184863. }
  184864. return (0);
  184865. }
  184866. png_byte PNGAPI
  184867. png_get_color_type(png_structp png_ptr, png_infop info_ptr)
  184868. {
  184869. if (png_ptr != NULL && info_ptr != NULL)
  184870. {
  184871. return info_ptr->color_type;
  184872. }
  184873. return (0);
  184874. }
  184875. png_byte PNGAPI
  184876. png_get_filter_type(png_structp png_ptr, png_infop info_ptr)
  184877. {
  184878. if (png_ptr != NULL && info_ptr != NULL)
  184879. {
  184880. return info_ptr->filter_type;
  184881. }
  184882. return (0);
  184883. }
  184884. png_byte PNGAPI
  184885. png_get_interlace_type(png_structp png_ptr, png_infop info_ptr)
  184886. {
  184887. if (png_ptr != NULL && info_ptr != NULL)
  184888. {
  184889. return info_ptr->interlace_type;
  184890. }
  184891. return (0);
  184892. }
  184893. png_byte PNGAPI
  184894. png_get_compression_type(png_structp png_ptr, png_infop info_ptr)
  184895. {
  184896. if (png_ptr != NULL && info_ptr != NULL)
  184897. {
  184898. return info_ptr->compression_type;
  184899. }
  184900. return (0);
  184901. }
  184902. png_uint_32 PNGAPI
  184903. png_get_x_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  184904. {
  184905. if (png_ptr != NULL && info_ptr != NULL)
  184906. #if defined(PNG_pHYs_SUPPORTED)
  184907. if (info_ptr->valid & PNG_INFO_pHYs)
  184908. {
  184909. png_debug1(1, "in %s retrieval function\n", "png_get_x_pixels_per_meter");
  184910. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  184911. return (0);
  184912. else return (info_ptr->x_pixels_per_unit);
  184913. }
  184914. #else
  184915. return (0);
  184916. #endif
  184917. return (0);
  184918. }
  184919. png_uint_32 PNGAPI
  184920. png_get_y_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  184921. {
  184922. if (png_ptr != NULL && info_ptr != NULL)
  184923. #if defined(PNG_pHYs_SUPPORTED)
  184924. if (info_ptr->valid & PNG_INFO_pHYs)
  184925. {
  184926. png_debug1(1, "in %s retrieval function\n", "png_get_y_pixels_per_meter");
  184927. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  184928. return (0);
  184929. else return (info_ptr->y_pixels_per_unit);
  184930. }
  184931. #else
  184932. return (0);
  184933. #endif
  184934. return (0);
  184935. }
  184936. png_uint_32 PNGAPI
  184937. png_get_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  184938. {
  184939. if (png_ptr != NULL && info_ptr != NULL)
  184940. #if defined(PNG_pHYs_SUPPORTED)
  184941. if (info_ptr->valid & PNG_INFO_pHYs)
  184942. {
  184943. png_debug1(1, "in %s retrieval function\n", "png_get_pixels_per_meter");
  184944. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER ||
  184945. info_ptr->x_pixels_per_unit != info_ptr->y_pixels_per_unit)
  184946. return (0);
  184947. else return (info_ptr->x_pixels_per_unit);
  184948. }
  184949. #else
  184950. return (0);
  184951. #endif
  184952. return (0);
  184953. }
  184954. #ifdef PNG_FLOATING_POINT_SUPPORTED
  184955. float PNGAPI
  184956. png_get_pixel_aspect_ratio(png_structp png_ptr, png_infop info_ptr)
  184957. {
  184958. if (png_ptr != NULL && info_ptr != NULL)
  184959. #if defined(PNG_pHYs_SUPPORTED)
  184960. if (info_ptr->valid & PNG_INFO_pHYs)
  184961. {
  184962. png_debug1(1, "in %s retrieval function\n", "png_get_aspect_ratio");
  184963. if (info_ptr->x_pixels_per_unit == 0)
  184964. return ((float)0.0);
  184965. else
  184966. return ((float)((float)info_ptr->y_pixels_per_unit
  184967. /(float)info_ptr->x_pixels_per_unit));
  184968. }
  184969. #else
  184970. return (0.0);
  184971. #endif
  184972. return ((float)0.0);
  184973. }
  184974. #endif
  184975. png_int_32 PNGAPI
  184976. png_get_x_offset_microns(png_structp png_ptr, png_infop info_ptr)
  184977. {
  184978. if (png_ptr != NULL && info_ptr != NULL)
  184979. #if defined(PNG_oFFs_SUPPORTED)
  184980. if (info_ptr->valid & PNG_INFO_oFFs)
  184981. {
  184982. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  184983. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  184984. return (0);
  184985. else return (info_ptr->x_offset);
  184986. }
  184987. #else
  184988. return (0);
  184989. #endif
  184990. return (0);
  184991. }
  184992. png_int_32 PNGAPI
  184993. png_get_y_offset_microns(png_structp png_ptr, png_infop info_ptr)
  184994. {
  184995. if (png_ptr != NULL && info_ptr != NULL)
  184996. #if defined(PNG_oFFs_SUPPORTED)
  184997. if (info_ptr->valid & PNG_INFO_oFFs)
  184998. {
  184999. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  185000. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  185001. return (0);
  185002. else return (info_ptr->y_offset);
  185003. }
  185004. #else
  185005. return (0);
  185006. #endif
  185007. return (0);
  185008. }
  185009. png_int_32 PNGAPI
  185010. png_get_x_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  185011. {
  185012. if (png_ptr != NULL && info_ptr != NULL)
  185013. #if defined(PNG_oFFs_SUPPORTED)
  185014. if (info_ptr->valid & PNG_INFO_oFFs)
  185015. {
  185016. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  185017. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  185018. return (0);
  185019. else return (info_ptr->x_offset);
  185020. }
  185021. #else
  185022. return (0);
  185023. #endif
  185024. return (0);
  185025. }
  185026. png_int_32 PNGAPI
  185027. png_get_y_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  185028. {
  185029. if (png_ptr != NULL && info_ptr != NULL)
  185030. #if defined(PNG_oFFs_SUPPORTED)
  185031. if (info_ptr->valid & PNG_INFO_oFFs)
  185032. {
  185033. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  185034. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  185035. return (0);
  185036. else return (info_ptr->y_offset);
  185037. }
  185038. #else
  185039. return (0);
  185040. #endif
  185041. return (0);
  185042. }
  185043. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  185044. png_uint_32 PNGAPI
  185045. png_get_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185046. {
  185047. return ((png_uint_32)((float)png_get_pixels_per_meter(png_ptr, info_ptr)
  185048. *.0254 +.5));
  185049. }
  185050. png_uint_32 PNGAPI
  185051. png_get_x_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185052. {
  185053. return ((png_uint_32)((float)png_get_x_pixels_per_meter(png_ptr, info_ptr)
  185054. *.0254 +.5));
  185055. }
  185056. png_uint_32 PNGAPI
  185057. png_get_y_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185058. {
  185059. return ((png_uint_32)((float)png_get_y_pixels_per_meter(png_ptr, info_ptr)
  185060. *.0254 +.5));
  185061. }
  185062. float PNGAPI
  185063. png_get_x_offset_inches(png_structp png_ptr, png_infop info_ptr)
  185064. {
  185065. return ((float)png_get_x_offset_microns(png_ptr, info_ptr)
  185066. *.00003937);
  185067. }
  185068. float PNGAPI
  185069. png_get_y_offset_inches(png_structp png_ptr, png_infop info_ptr)
  185070. {
  185071. return ((float)png_get_y_offset_microns(png_ptr, info_ptr)
  185072. *.00003937);
  185073. }
  185074. #if defined(PNG_pHYs_SUPPORTED)
  185075. png_uint_32 PNGAPI
  185076. png_get_pHYs_dpi(png_structp png_ptr, png_infop info_ptr,
  185077. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  185078. {
  185079. png_uint_32 retval = 0;
  185080. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  185081. {
  185082. png_debug1(1, "in %s retrieval function\n", "pHYs");
  185083. if (res_x != NULL)
  185084. {
  185085. *res_x = info_ptr->x_pixels_per_unit;
  185086. retval |= PNG_INFO_pHYs;
  185087. }
  185088. if (res_y != NULL)
  185089. {
  185090. *res_y = info_ptr->y_pixels_per_unit;
  185091. retval |= PNG_INFO_pHYs;
  185092. }
  185093. if (unit_type != NULL)
  185094. {
  185095. *unit_type = (int)info_ptr->phys_unit_type;
  185096. retval |= PNG_INFO_pHYs;
  185097. if(*unit_type == 1)
  185098. {
  185099. if (res_x != NULL) *res_x = (png_uint_32)(*res_x * .0254 + .50);
  185100. if (res_y != NULL) *res_y = (png_uint_32)(*res_y * .0254 + .50);
  185101. }
  185102. }
  185103. }
  185104. return (retval);
  185105. }
  185106. #endif /* PNG_pHYs_SUPPORTED */
  185107. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  185108. /* png_get_channels really belongs in here, too, but it's been around longer */
  185109. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  185110. png_byte PNGAPI
  185111. png_get_channels(png_structp png_ptr, png_infop info_ptr)
  185112. {
  185113. if (png_ptr != NULL && info_ptr != NULL)
  185114. return(info_ptr->channels);
  185115. else
  185116. return (0);
  185117. }
  185118. png_bytep PNGAPI
  185119. png_get_signature(png_structp png_ptr, png_infop info_ptr)
  185120. {
  185121. if (png_ptr != NULL && info_ptr != NULL)
  185122. return(info_ptr->signature);
  185123. else
  185124. return (NULL);
  185125. }
  185126. #if defined(PNG_bKGD_SUPPORTED)
  185127. png_uint_32 PNGAPI
  185128. png_get_bKGD(png_structp png_ptr, png_infop info_ptr,
  185129. png_color_16p *background)
  185130. {
  185131. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD)
  185132. && background != NULL)
  185133. {
  185134. png_debug1(1, "in %s retrieval function\n", "bKGD");
  185135. *background = &(info_ptr->background);
  185136. return (PNG_INFO_bKGD);
  185137. }
  185138. return (0);
  185139. }
  185140. #endif
  185141. #if defined(PNG_cHRM_SUPPORTED)
  185142. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185143. png_uint_32 PNGAPI
  185144. png_get_cHRM(png_structp png_ptr, png_infop info_ptr,
  185145. double *white_x, double *white_y, double *red_x, double *red_y,
  185146. double *green_x, double *green_y, double *blue_x, double *blue_y)
  185147. {
  185148. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  185149. {
  185150. png_debug1(1, "in %s retrieval function\n", "cHRM");
  185151. if (white_x != NULL)
  185152. *white_x = (double)info_ptr->x_white;
  185153. if (white_y != NULL)
  185154. *white_y = (double)info_ptr->y_white;
  185155. if (red_x != NULL)
  185156. *red_x = (double)info_ptr->x_red;
  185157. if (red_y != NULL)
  185158. *red_y = (double)info_ptr->y_red;
  185159. if (green_x != NULL)
  185160. *green_x = (double)info_ptr->x_green;
  185161. if (green_y != NULL)
  185162. *green_y = (double)info_ptr->y_green;
  185163. if (blue_x != NULL)
  185164. *blue_x = (double)info_ptr->x_blue;
  185165. if (blue_y != NULL)
  185166. *blue_y = (double)info_ptr->y_blue;
  185167. return (PNG_INFO_cHRM);
  185168. }
  185169. return (0);
  185170. }
  185171. #endif
  185172. #ifdef PNG_FIXED_POINT_SUPPORTED
  185173. png_uint_32 PNGAPI
  185174. png_get_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  185175. png_fixed_point *white_x, png_fixed_point *white_y, png_fixed_point *red_x,
  185176. png_fixed_point *red_y, png_fixed_point *green_x, png_fixed_point *green_y,
  185177. png_fixed_point *blue_x, png_fixed_point *blue_y)
  185178. {
  185179. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  185180. {
  185181. png_debug1(1, "in %s retrieval function\n", "cHRM");
  185182. if (white_x != NULL)
  185183. *white_x = info_ptr->int_x_white;
  185184. if (white_y != NULL)
  185185. *white_y = info_ptr->int_y_white;
  185186. if (red_x != NULL)
  185187. *red_x = info_ptr->int_x_red;
  185188. if (red_y != NULL)
  185189. *red_y = info_ptr->int_y_red;
  185190. if (green_x != NULL)
  185191. *green_x = info_ptr->int_x_green;
  185192. if (green_y != NULL)
  185193. *green_y = info_ptr->int_y_green;
  185194. if (blue_x != NULL)
  185195. *blue_x = info_ptr->int_x_blue;
  185196. if (blue_y != NULL)
  185197. *blue_y = info_ptr->int_y_blue;
  185198. return (PNG_INFO_cHRM);
  185199. }
  185200. return (0);
  185201. }
  185202. #endif
  185203. #endif
  185204. #if defined(PNG_gAMA_SUPPORTED)
  185205. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185206. png_uint_32 PNGAPI
  185207. png_get_gAMA(png_structp png_ptr, png_infop info_ptr, double *file_gamma)
  185208. {
  185209. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  185210. && file_gamma != NULL)
  185211. {
  185212. png_debug1(1, "in %s retrieval function\n", "gAMA");
  185213. *file_gamma = (double)info_ptr->gamma;
  185214. return (PNG_INFO_gAMA);
  185215. }
  185216. return (0);
  185217. }
  185218. #endif
  185219. #ifdef PNG_FIXED_POINT_SUPPORTED
  185220. png_uint_32 PNGAPI
  185221. png_get_gAMA_fixed(png_structp png_ptr, png_infop info_ptr,
  185222. png_fixed_point *int_file_gamma)
  185223. {
  185224. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  185225. && int_file_gamma != NULL)
  185226. {
  185227. png_debug1(1, "in %s retrieval function\n", "gAMA");
  185228. *int_file_gamma = info_ptr->int_gamma;
  185229. return (PNG_INFO_gAMA);
  185230. }
  185231. return (0);
  185232. }
  185233. #endif
  185234. #endif
  185235. #if defined(PNG_sRGB_SUPPORTED)
  185236. png_uint_32 PNGAPI
  185237. png_get_sRGB(png_structp png_ptr, png_infop info_ptr, int *file_srgb_intent)
  185238. {
  185239. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB)
  185240. && file_srgb_intent != NULL)
  185241. {
  185242. png_debug1(1, "in %s retrieval function\n", "sRGB");
  185243. *file_srgb_intent = (int)info_ptr->srgb_intent;
  185244. return (PNG_INFO_sRGB);
  185245. }
  185246. return (0);
  185247. }
  185248. #endif
  185249. #if defined(PNG_iCCP_SUPPORTED)
  185250. png_uint_32 PNGAPI
  185251. png_get_iCCP(png_structp png_ptr, png_infop info_ptr,
  185252. png_charpp name, int *compression_type,
  185253. png_charpp profile, png_uint_32 *proflen)
  185254. {
  185255. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP)
  185256. && name != NULL && profile != NULL && proflen != NULL)
  185257. {
  185258. png_debug1(1, "in %s retrieval function\n", "iCCP");
  185259. *name = info_ptr->iccp_name;
  185260. *profile = info_ptr->iccp_profile;
  185261. /* compression_type is a dummy so the API won't have to change
  185262. if we introduce multiple compression types later. */
  185263. *proflen = (int)info_ptr->iccp_proflen;
  185264. *compression_type = (int)info_ptr->iccp_compression;
  185265. return (PNG_INFO_iCCP);
  185266. }
  185267. return (0);
  185268. }
  185269. #endif
  185270. #if defined(PNG_sPLT_SUPPORTED)
  185271. png_uint_32 PNGAPI
  185272. png_get_sPLT(png_structp png_ptr, png_infop info_ptr,
  185273. png_sPLT_tpp spalettes)
  185274. {
  185275. if (png_ptr != NULL && info_ptr != NULL && spalettes != NULL)
  185276. {
  185277. *spalettes = info_ptr->splt_palettes;
  185278. return ((png_uint_32)info_ptr->splt_palettes_num);
  185279. }
  185280. return (0);
  185281. }
  185282. #endif
  185283. #if defined(PNG_hIST_SUPPORTED)
  185284. png_uint_32 PNGAPI
  185285. png_get_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p *hist)
  185286. {
  185287. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST)
  185288. && hist != NULL)
  185289. {
  185290. png_debug1(1, "in %s retrieval function\n", "hIST");
  185291. *hist = info_ptr->hist;
  185292. return (PNG_INFO_hIST);
  185293. }
  185294. return (0);
  185295. }
  185296. #endif
  185297. png_uint_32 PNGAPI
  185298. png_get_IHDR(png_structp png_ptr, png_infop info_ptr,
  185299. png_uint_32 *width, png_uint_32 *height, int *bit_depth,
  185300. int *color_type, int *interlace_type, int *compression_type,
  185301. int *filter_type)
  185302. {
  185303. if (png_ptr != NULL && info_ptr != NULL && width != NULL && height != NULL &&
  185304. bit_depth != NULL && color_type != NULL)
  185305. {
  185306. png_debug1(1, "in %s retrieval function\n", "IHDR");
  185307. *width = info_ptr->width;
  185308. *height = info_ptr->height;
  185309. *bit_depth = info_ptr->bit_depth;
  185310. if (info_ptr->bit_depth < 1 || info_ptr->bit_depth > 16)
  185311. png_error(png_ptr, "Invalid bit depth");
  185312. *color_type = info_ptr->color_type;
  185313. if (info_ptr->color_type > 6)
  185314. png_error(png_ptr, "Invalid color type");
  185315. if (compression_type != NULL)
  185316. *compression_type = info_ptr->compression_type;
  185317. if (filter_type != NULL)
  185318. *filter_type = info_ptr->filter_type;
  185319. if (interlace_type != NULL)
  185320. *interlace_type = info_ptr->interlace_type;
  185321. /* check for potential overflow of rowbytes */
  185322. if (*width == 0 || *width > PNG_UINT_31_MAX)
  185323. png_error(png_ptr, "Invalid image width");
  185324. if (*height == 0 || *height > PNG_UINT_31_MAX)
  185325. png_error(png_ptr, "Invalid image height");
  185326. if (info_ptr->width > (PNG_UINT_32_MAX
  185327. >> 3) /* 8-byte RGBA pixels */
  185328. - 64 /* bigrowbuf hack */
  185329. - 1 /* filter byte */
  185330. - 7*8 /* rounding of width to multiple of 8 pixels */
  185331. - 8) /* extra max_pixel_depth pad */
  185332. {
  185333. png_warning(png_ptr,
  185334. "Width too large for libpng to process image data.");
  185335. }
  185336. return (1);
  185337. }
  185338. return (0);
  185339. }
  185340. #if defined(PNG_oFFs_SUPPORTED)
  185341. png_uint_32 PNGAPI
  185342. png_get_oFFs(png_structp png_ptr, png_infop info_ptr,
  185343. png_int_32 *offset_x, png_int_32 *offset_y, int *unit_type)
  185344. {
  185345. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs)
  185346. && offset_x != NULL && offset_y != NULL && unit_type != NULL)
  185347. {
  185348. png_debug1(1, "in %s retrieval function\n", "oFFs");
  185349. *offset_x = info_ptr->x_offset;
  185350. *offset_y = info_ptr->y_offset;
  185351. *unit_type = (int)info_ptr->offset_unit_type;
  185352. return (PNG_INFO_oFFs);
  185353. }
  185354. return (0);
  185355. }
  185356. #endif
  185357. #if defined(PNG_pCAL_SUPPORTED)
  185358. png_uint_32 PNGAPI
  185359. png_get_pCAL(png_structp png_ptr, png_infop info_ptr,
  185360. png_charp *purpose, png_int_32 *X0, png_int_32 *X1, int *type, int *nparams,
  185361. png_charp *units, png_charpp *params)
  185362. {
  185363. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL)
  185364. && purpose != NULL && X0 != NULL && X1 != NULL && type != NULL &&
  185365. nparams != NULL && units != NULL && params != NULL)
  185366. {
  185367. png_debug1(1, "in %s retrieval function\n", "pCAL");
  185368. *purpose = info_ptr->pcal_purpose;
  185369. *X0 = info_ptr->pcal_X0;
  185370. *X1 = info_ptr->pcal_X1;
  185371. *type = (int)info_ptr->pcal_type;
  185372. *nparams = (int)info_ptr->pcal_nparams;
  185373. *units = info_ptr->pcal_units;
  185374. *params = info_ptr->pcal_params;
  185375. return (PNG_INFO_pCAL);
  185376. }
  185377. return (0);
  185378. }
  185379. #endif
  185380. #if defined(PNG_sCAL_SUPPORTED)
  185381. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185382. png_uint_32 PNGAPI
  185383. png_get_sCAL(png_structp png_ptr, png_infop info_ptr,
  185384. int *unit, double *width, double *height)
  185385. {
  185386. if (png_ptr != NULL && info_ptr != NULL &&
  185387. (info_ptr->valid & PNG_INFO_sCAL))
  185388. {
  185389. *unit = info_ptr->scal_unit;
  185390. *width = info_ptr->scal_pixel_width;
  185391. *height = info_ptr->scal_pixel_height;
  185392. return (PNG_INFO_sCAL);
  185393. }
  185394. return(0);
  185395. }
  185396. #else
  185397. #ifdef PNG_FIXED_POINT_SUPPORTED
  185398. png_uint_32 PNGAPI
  185399. png_get_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  185400. int *unit, png_charpp width, png_charpp height)
  185401. {
  185402. if (png_ptr != NULL && info_ptr != NULL &&
  185403. (info_ptr->valid & PNG_INFO_sCAL))
  185404. {
  185405. *unit = info_ptr->scal_unit;
  185406. *width = info_ptr->scal_s_width;
  185407. *height = info_ptr->scal_s_height;
  185408. return (PNG_INFO_sCAL);
  185409. }
  185410. return(0);
  185411. }
  185412. #endif
  185413. #endif
  185414. #endif
  185415. #if defined(PNG_pHYs_SUPPORTED)
  185416. png_uint_32 PNGAPI
  185417. png_get_pHYs(png_structp png_ptr, png_infop info_ptr,
  185418. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  185419. {
  185420. png_uint_32 retval = 0;
  185421. if (png_ptr != NULL && info_ptr != NULL &&
  185422. (info_ptr->valid & PNG_INFO_pHYs))
  185423. {
  185424. png_debug1(1, "in %s retrieval function\n", "pHYs");
  185425. if (res_x != NULL)
  185426. {
  185427. *res_x = info_ptr->x_pixels_per_unit;
  185428. retval |= PNG_INFO_pHYs;
  185429. }
  185430. if (res_y != NULL)
  185431. {
  185432. *res_y = info_ptr->y_pixels_per_unit;
  185433. retval |= PNG_INFO_pHYs;
  185434. }
  185435. if (unit_type != NULL)
  185436. {
  185437. *unit_type = (int)info_ptr->phys_unit_type;
  185438. retval |= PNG_INFO_pHYs;
  185439. }
  185440. }
  185441. return (retval);
  185442. }
  185443. #endif
  185444. png_uint_32 PNGAPI
  185445. png_get_PLTE(png_structp png_ptr, png_infop info_ptr, png_colorp *palette,
  185446. int *num_palette)
  185447. {
  185448. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_PLTE)
  185449. && palette != NULL)
  185450. {
  185451. png_debug1(1, "in %s retrieval function\n", "PLTE");
  185452. *palette = info_ptr->palette;
  185453. *num_palette = info_ptr->num_palette;
  185454. png_debug1(3, "num_palette = %d\n", *num_palette);
  185455. return (PNG_INFO_PLTE);
  185456. }
  185457. return (0);
  185458. }
  185459. #if defined(PNG_sBIT_SUPPORTED)
  185460. png_uint_32 PNGAPI
  185461. png_get_sBIT(png_structp png_ptr, png_infop info_ptr, png_color_8p *sig_bit)
  185462. {
  185463. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT)
  185464. && sig_bit != NULL)
  185465. {
  185466. png_debug1(1, "in %s retrieval function\n", "sBIT");
  185467. *sig_bit = &(info_ptr->sig_bit);
  185468. return (PNG_INFO_sBIT);
  185469. }
  185470. return (0);
  185471. }
  185472. #endif
  185473. #if defined(PNG_TEXT_SUPPORTED)
  185474. png_uint_32 PNGAPI
  185475. png_get_text(png_structp png_ptr, png_infop info_ptr, png_textp *text_ptr,
  185476. int *num_text)
  185477. {
  185478. if (png_ptr != NULL && info_ptr != NULL && info_ptr->num_text > 0)
  185479. {
  185480. png_debug1(1, "in %s retrieval function\n",
  185481. (png_ptr->chunk_name[0] == '\0' ? "text"
  185482. : (png_const_charp)png_ptr->chunk_name));
  185483. if (text_ptr != NULL)
  185484. *text_ptr = info_ptr->text;
  185485. if (num_text != NULL)
  185486. *num_text = info_ptr->num_text;
  185487. return ((png_uint_32)info_ptr->num_text);
  185488. }
  185489. if (num_text != NULL)
  185490. *num_text = 0;
  185491. return(0);
  185492. }
  185493. #endif
  185494. #if defined(PNG_tIME_SUPPORTED)
  185495. png_uint_32 PNGAPI
  185496. png_get_tIME(png_structp png_ptr, png_infop info_ptr, png_timep *mod_time)
  185497. {
  185498. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME)
  185499. && mod_time != NULL)
  185500. {
  185501. png_debug1(1, "in %s retrieval function\n", "tIME");
  185502. *mod_time = &(info_ptr->mod_time);
  185503. return (PNG_INFO_tIME);
  185504. }
  185505. return (0);
  185506. }
  185507. #endif
  185508. #if defined(PNG_tRNS_SUPPORTED)
  185509. png_uint_32 PNGAPI
  185510. png_get_tRNS(png_structp png_ptr, png_infop info_ptr,
  185511. png_bytep *trans, int *num_trans, png_color_16p *trans_values)
  185512. {
  185513. png_uint_32 retval = 0;
  185514. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  185515. {
  185516. png_debug1(1, "in %s retrieval function\n", "tRNS");
  185517. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  185518. {
  185519. if (trans != NULL)
  185520. {
  185521. *trans = info_ptr->trans;
  185522. retval |= PNG_INFO_tRNS;
  185523. }
  185524. if (trans_values != NULL)
  185525. *trans_values = &(info_ptr->trans_values);
  185526. }
  185527. else /* if (info_ptr->color_type != PNG_COLOR_TYPE_PALETTE) */
  185528. {
  185529. if (trans_values != NULL)
  185530. {
  185531. *trans_values = &(info_ptr->trans_values);
  185532. retval |= PNG_INFO_tRNS;
  185533. }
  185534. if(trans != NULL)
  185535. *trans = NULL;
  185536. }
  185537. if(num_trans != NULL)
  185538. {
  185539. *num_trans = info_ptr->num_trans;
  185540. retval |= PNG_INFO_tRNS;
  185541. }
  185542. }
  185543. return (retval);
  185544. }
  185545. #endif
  185546. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  185547. png_uint_32 PNGAPI
  185548. png_get_unknown_chunks(png_structp png_ptr, png_infop info_ptr,
  185549. png_unknown_chunkpp unknowns)
  185550. {
  185551. if (png_ptr != NULL && info_ptr != NULL && unknowns != NULL)
  185552. {
  185553. *unknowns = info_ptr->unknown_chunks;
  185554. return ((png_uint_32)info_ptr->unknown_chunks_num);
  185555. }
  185556. return (0);
  185557. }
  185558. #endif
  185559. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  185560. png_byte PNGAPI
  185561. png_get_rgb_to_gray_status (png_structp png_ptr)
  185562. {
  185563. return (png_byte)(png_ptr? png_ptr->rgb_to_gray_status : 0);
  185564. }
  185565. #endif
  185566. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  185567. png_voidp PNGAPI
  185568. png_get_user_chunk_ptr(png_structp png_ptr)
  185569. {
  185570. return (png_ptr? png_ptr->user_chunk_ptr : NULL);
  185571. }
  185572. #endif
  185573. #ifdef PNG_WRITE_SUPPORTED
  185574. png_uint_32 PNGAPI
  185575. png_get_compression_buffer_size(png_structp png_ptr)
  185576. {
  185577. return (png_uint_32)(png_ptr? png_ptr->zbuf_size : 0L);
  185578. }
  185579. #endif
  185580. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  185581. #ifndef PNG_1_0_X
  185582. /* this function was added to libpng 1.2.0 and should exist by default */
  185583. png_uint_32 PNGAPI
  185584. png_get_asm_flags (png_structp png_ptr)
  185585. {
  185586. /* obsolete, to be removed from libpng-1.4.0 */
  185587. return (png_ptr? 0L: 0L);
  185588. }
  185589. /* this function was added to libpng 1.2.0 and should exist by default */
  185590. png_uint_32 PNGAPI
  185591. png_get_asm_flagmask (int flag_select)
  185592. {
  185593. /* obsolete, to be removed from libpng-1.4.0 */
  185594. flag_select=flag_select;
  185595. return 0L;
  185596. }
  185597. /* GRR: could add this: && defined(PNG_MMX_CODE_SUPPORTED) */
  185598. /* this function was added to libpng 1.2.0 */
  185599. png_uint_32 PNGAPI
  185600. png_get_mmx_flagmask (int flag_select, int *compilerID)
  185601. {
  185602. /* obsolete, to be removed from libpng-1.4.0 */
  185603. flag_select=flag_select;
  185604. *compilerID = -1; /* unknown (i.e., no asm/MMX code compiled) */
  185605. return 0L;
  185606. }
  185607. /* this function was added to libpng 1.2.0 */
  185608. png_byte PNGAPI
  185609. png_get_mmx_bitdepth_threshold (png_structp png_ptr)
  185610. {
  185611. /* obsolete, to be removed from libpng-1.4.0 */
  185612. return (png_ptr? 0: 0);
  185613. }
  185614. /* this function was added to libpng 1.2.0 */
  185615. png_uint_32 PNGAPI
  185616. png_get_mmx_rowbytes_threshold (png_structp png_ptr)
  185617. {
  185618. /* obsolete, to be removed from libpng-1.4.0 */
  185619. return (png_ptr? 0L: 0L);
  185620. }
  185621. #endif /* ?PNG_1_0_X */
  185622. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  185623. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  185624. /* these functions were added to libpng 1.2.6 */
  185625. png_uint_32 PNGAPI
  185626. png_get_user_width_max (png_structp png_ptr)
  185627. {
  185628. return (png_ptr? png_ptr->user_width_max : 0);
  185629. }
  185630. png_uint_32 PNGAPI
  185631. png_get_user_height_max (png_structp png_ptr)
  185632. {
  185633. return (png_ptr? png_ptr->user_height_max : 0);
  185634. }
  185635. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  185636. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  185637. /*** End of inlined file: pngget.c ***/
  185638. /*** Start of inlined file: pngmem.c ***/
  185639. /* pngmem.c - stub functions for memory allocation
  185640. *
  185641. * Last changed in libpng 1.2.13 November 13, 2006
  185642. * For conditions of distribution and use, see copyright notice in png.h
  185643. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  185644. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185645. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185646. *
  185647. * This file provides a location for all memory allocation. Users who
  185648. * need special memory handling are expected to supply replacement
  185649. * functions for png_malloc() and png_free(), and to use
  185650. * png_create_read_struct_2() and png_create_write_struct_2() to
  185651. * identify the replacement functions.
  185652. */
  185653. #define PNG_INTERNAL
  185654. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185655. /* Borland DOS special memory handler */
  185656. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  185657. /* if you change this, be sure to change the one in png.h also */
  185658. /* Allocate memory for a png_struct. The malloc and memset can be replaced
  185659. by a single call to calloc() if this is thought to improve performance. */
  185660. png_voidp /* PRIVATE */
  185661. png_create_struct(int type)
  185662. {
  185663. #ifdef PNG_USER_MEM_SUPPORTED
  185664. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  185665. }
  185666. /* Alternate version of png_create_struct, for use with user-defined malloc. */
  185667. png_voidp /* PRIVATE */
  185668. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  185669. {
  185670. #endif /* PNG_USER_MEM_SUPPORTED */
  185671. png_size_t size;
  185672. png_voidp struct_ptr;
  185673. if (type == PNG_STRUCT_INFO)
  185674. size = png_sizeof(png_info);
  185675. else if (type == PNG_STRUCT_PNG)
  185676. size = png_sizeof(png_struct);
  185677. else
  185678. return (png_get_copyright(NULL));
  185679. #ifdef PNG_USER_MEM_SUPPORTED
  185680. if(malloc_fn != NULL)
  185681. {
  185682. png_struct dummy_struct;
  185683. png_structp png_ptr = &dummy_struct;
  185684. png_ptr->mem_ptr=mem_ptr;
  185685. struct_ptr = (*(malloc_fn))(png_ptr, (png_uint_32)size);
  185686. }
  185687. else
  185688. #endif /* PNG_USER_MEM_SUPPORTED */
  185689. struct_ptr = (png_voidp)farmalloc(size);
  185690. if (struct_ptr != NULL)
  185691. png_memset(struct_ptr, 0, size);
  185692. return (struct_ptr);
  185693. }
  185694. /* Free memory allocated by a png_create_struct() call */
  185695. void /* PRIVATE */
  185696. png_destroy_struct(png_voidp struct_ptr)
  185697. {
  185698. #ifdef PNG_USER_MEM_SUPPORTED
  185699. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  185700. }
  185701. /* Free memory allocated by a png_create_struct() call */
  185702. void /* PRIVATE */
  185703. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  185704. png_voidp mem_ptr)
  185705. {
  185706. #endif
  185707. if (struct_ptr != NULL)
  185708. {
  185709. #ifdef PNG_USER_MEM_SUPPORTED
  185710. if(free_fn != NULL)
  185711. {
  185712. png_struct dummy_struct;
  185713. png_structp png_ptr = &dummy_struct;
  185714. png_ptr->mem_ptr=mem_ptr;
  185715. (*(free_fn))(png_ptr, struct_ptr);
  185716. return;
  185717. }
  185718. #endif /* PNG_USER_MEM_SUPPORTED */
  185719. farfree (struct_ptr);
  185720. }
  185721. }
  185722. /* Allocate memory. For reasonable files, size should never exceed
  185723. * 64K. However, zlib may allocate more then 64K if you don't tell
  185724. * it not to. See zconf.h and png.h for more information. zlib does
  185725. * need to allocate exactly 64K, so whatever you call here must
  185726. * have the ability to do that.
  185727. *
  185728. * Borland seems to have a problem in DOS mode for exactly 64K.
  185729. * It gives you a segment with an offset of 8 (perhaps to store its
  185730. * memory stuff). zlib doesn't like this at all, so we have to
  185731. * detect and deal with it. This code should not be needed in
  185732. * Windows or OS/2 modes, and only in 16 bit mode. This code has
  185733. * been updated by Alexander Lehmann for version 0.89 to waste less
  185734. * memory.
  185735. *
  185736. * Note that we can't use png_size_t for the "size" declaration,
  185737. * since on some systems a png_size_t is a 16-bit quantity, and as a
  185738. * result, we would be truncating potentially larger memory requests
  185739. * (which should cause a fatal error) and introducing major problems.
  185740. */
  185741. png_voidp PNGAPI
  185742. png_malloc(png_structp png_ptr, png_uint_32 size)
  185743. {
  185744. png_voidp ret;
  185745. if (png_ptr == NULL || size == 0)
  185746. return (NULL);
  185747. #ifdef PNG_USER_MEM_SUPPORTED
  185748. if(png_ptr->malloc_fn != NULL)
  185749. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  185750. else
  185751. ret = (png_malloc_default(png_ptr, size));
  185752. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  185753. png_error(png_ptr, "Out of memory!");
  185754. return (ret);
  185755. }
  185756. png_voidp PNGAPI
  185757. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  185758. {
  185759. png_voidp ret;
  185760. #endif /* PNG_USER_MEM_SUPPORTED */
  185761. if (png_ptr == NULL || size == 0)
  185762. return (NULL);
  185763. #ifdef PNG_MAX_MALLOC_64K
  185764. if (size > (png_uint_32)65536L)
  185765. {
  185766. png_warning(png_ptr, "Cannot Allocate > 64K");
  185767. ret = NULL;
  185768. }
  185769. else
  185770. #endif
  185771. if (size != (size_t)size)
  185772. ret = NULL;
  185773. else if (size == (png_uint_32)65536L)
  185774. {
  185775. if (png_ptr->offset_table == NULL)
  185776. {
  185777. /* try to see if we need to do any of this fancy stuff */
  185778. ret = farmalloc(size);
  185779. if (ret == NULL || ((png_size_t)ret & 0xffff))
  185780. {
  185781. int num_blocks;
  185782. png_uint_32 total_size;
  185783. png_bytep table;
  185784. int i;
  185785. png_byte huge * hptr;
  185786. if (ret != NULL)
  185787. {
  185788. farfree(ret);
  185789. ret = NULL;
  185790. }
  185791. if(png_ptr->zlib_window_bits > 14)
  185792. num_blocks = (int)(1 << (png_ptr->zlib_window_bits - 14));
  185793. else
  185794. num_blocks = 1;
  185795. if (png_ptr->zlib_mem_level >= 7)
  185796. num_blocks += (int)(1 << (png_ptr->zlib_mem_level - 7));
  185797. else
  185798. num_blocks++;
  185799. total_size = ((png_uint_32)65536L) * (png_uint_32)num_blocks+16;
  185800. table = farmalloc(total_size);
  185801. if (table == NULL)
  185802. {
  185803. #ifndef PNG_USER_MEM_SUPPORTED
  185804. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  185805. png_error(png_ptr, "Out Of Memory."); /* Note "O" and "M" */
  185806. else
  185807. png_warning(png_ptr, "Out Of Memory.");
  185808. #endif
  185809. return (NULL);
  185810. }
  185811. if ((png_size_t)table & 0xfff0)
  185812. {
  185813. #ifndef PNG_USER_MEM_SUPPORTED
  185814. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  185815. png_error(png_ptr,
  185816. "Farmalloc didn't return normalized pointer");
  185817. else
  185818. png_warning(png_ptr,
  185819. "Farmalloc didn't return normalized pointer");
  185820. #endif
  185821. return (NULL);
  185822. }
  185823. png_ptr->offset_table = table;
  185824. png_ptr->offset_table_ptr = farmalloc(num_blocks *
  185825. png_sizeof (png_bytep));
  185826. if (png_ptr->offset_table_ptr == NULL)
  185827. {
  185828. #ifndef PNG_USER_MEM_SUPPORTED
  185829. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  185830. png_error(png_ptr, "Out Of memory."); /* Note "O" and "M" */
  185831. else
  185832. png_warning(png_ptr, "Out Of memory.");
  185833. #endif
  185834. return (NULL);
  185835. }
  185836. hptr = (png_byte huge *)table;
  185837. if ((png_size_t)hptr & 0xf)
  185838. {
  185839. hptr = (png_byte huge *)((long)(hptr) & 0xfffffff0L);
  185840. hptr = hptr + 16L; /* "hptr += 16L" fails on Turbo C++ 3.0 */
  185841. }
  185842. for (i = 0; i < num_blocks; i++)
  185843. {
  185844. png_ptr->offset_table_ptr[i] = (png_bytep)hptr;
  185845. hptr = hptr + (png_uint_32)65536L; /* "+=" fails on TC++3.0 */
  185846. }
  185847. png_ptr->offset_table_number = num_blocks;
  185848. png_ptr->offset_table_count = 0;
  185849. png_ptr->offset_table_count_free = 0;
  185850. }
  185851. }
  185852. if (png_ptr->offset_table_count >= png_ptr->offset_table_number)
  185853. {
  185854. #ifndef PNG_USER_MEM_SUPPORTED
  185855. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  185856. png_error(png_ptr, "Out of Memory."); /* Note "o" and "M" */
  185857. else
  185858. png_warning(png_ptr, "Out of Memory.");
  185859. #endif
  185860. return (NULL);
  185861. }
  185862. ret = png_ptr->offset_table_ptr[png_ptr->offset_table_count++];
  185863. }
  185864. else
  185865. ret = farmalloc(size);
  185866. #ifndef PNG_USER_MEM_SUPPORTED
  185867. if (ret == NULL)
  185868. {
  185869. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  185870. png_error(png_ptr, "Out of memory."); /* Note "o" and "m" */
  185871. else
  185872. png_warning(png_ptr, "Out of memory."); /* Note "o" and "m" */
  185873. }
  185874. #endif
  185875. return (ret);
  185876. }
  185877. /* free a pointer allocated by png_malloc(). In the default
  185878. configuration, png_ptr is not used, but is passed in case it
  185879. is needed. If ptr is NULL, return without taking any action. */
  185880. void PNGAPI
  185881. png_free(png_structp png_ptr, png_voidp ptr)
  185882. {
  185883. if (png_ptr == NULL || ptr == NULL)
  185884. return;
  185885. #ifdef PNG_USER_MEM_SUPPORTED
  185886. if (png_ptr->free_fn != NULL)
  185887. {
  185888. (*(png_ptr->free_fn))(png_ptr, ptr);
  185889. return;
  185890. }
  185891. else png_free_default(png_ptr, ptr);
  185892. }
  185893. void PNGAPI
  185894. png_free_default(png_structp png_ptr, png_voidp ptr)
  185895. {
  185896. #endif /* PNG_USER_MEM_SUPPORTED */
  185897. if(png_ptr == NULL) return;
  185898. if (png_ptr->offset_table != NULL)
  185899. {
  185900. int i;
  185901. for (i = 0; i < png_ptr->offset_table_count; i++)
  185902. {
  185903. if (ptr == png_ptr->offset_table_ptr[i])
  185904. {
  185905. ptr = NULL;
  185906. png_ptr->offset_table_count_free++;
  185907. break;
  185908. }
  185909. }
  185910. if (png_ptr->offset_table_count_free == png_ptr->offset_table_count)
  185911. {
  185912. farfree(png_ptr->offset_table);
  185913. farfree(png_ptr->offset_table_ptr);
  185914. png_ptr->offset_table = NULL;
  185915. png_ptr->offset_table_ptr = NULL;
  185916. }
  185917. }
  185918. if (ptr != NULL)
  185919. {
  185920. farfree(ptr);
  185921. }
  185922. }
  185923. #else /* Not the Borland DOS special memory handler */
  185924. /* Allocate memory for a png_struct or a png_info. The malloc and
  185925. memset can be replaced by a single call to calloc() if this is thought
  185926. to improve performance noticably. */
  185927. png_voidp /* PRIVATE */
  185928. png_create_struct(int type)
  185929. {
  185930. #ifdef PNG_USER_MEM_SUPPORTED
  185931. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  185932. }
  185933. /* Allocate memory for a png_struct or a png_info. The malloc and
  185934. memset can be replaced by a single call to calloc() if this is thought
  185935. to improve performance noticably. */
  185936. png_voidp /* PRIVATE */
  185937. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  185938. {
  185939. #endif /* PNG_USER_MEM_SUPPORTED */
  185940. png_size_t size;
  185941. png_voidp struct_ptr;
  185942. if (type == PNG_STRUCT_INFO)
  185943. size = png_sizeof(png_info);
  185944. else if (type == PNG_STRUCT_PNG)
  185945. size = png_sizeof(png_struct);
  185946. else
  185947. return (NULL);
  185948. #ifdef PNG_USER_MEM_SUPPORTED
  185949. if(malloc_fn != NULL)
  185950. {
  185951. png_struct dummy_struct;
  185952. png_structp png_ptr = &dummy_struct;
  185953. png_ptr->mem_ptr=mem_ptr;
  185954. struct_ptr = (*(malloc_fn))(png_ptr, size);
  185955. if (struct_ptr != NULL)
  185956. png_memset(struct_ptr, 0, size);
  185957. return (struct_ptr);
  185958. }
  185959. #endif /* PNG_USER_MEM_SUPPORTED */
  185960. #if defined(__TURBOC__) && !defined(__FLAT__)
  185961. struct_ptr = (png_voidp)farmalloc(size);
  185962. #else
  185963. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  185964. struct_ptr = (png_voidp)halloc(size,1);
  185965. # else
  185966. struct_ptr = (png_voidp)malloc(size);
  185967. # endif
  185968. #endif
  185969. if (struct_ptr != NULL)
  185970. png_memset(struct_ptr, 0, size);
  185971. return (struct_ptr);
  185972. }
  185973. /* Free memory allocated by a png_create_struct() call */
  185974. void /* PRIVATE */
  185975. png_destroy_struct(png_voidp struct_ptr)
  185976. {
  185977. #ifdef PNG_USER_MEM_SUPPORTED
  185978. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  185979. }
  185980. /* Free memory allocated by a png_create_struct() call */
  185981. void /* PRIVATE */
  185982. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  185983. png_voidp mem_ptr)
  185984. {
  185985. #endif /* PNG_USER_MEM_SUPPORTED */
  185986. if (struct_ptr != NULL)
  185987. {
  185988. #ifdef PNG_USER_MEM_SUPPORTED
  185989. if(free_fn != NULL)
  185990. {
  185991. png_struct dummy_struct;
  185992. png_structp png_ptr = &dummy_struct;
  185993. png_ptr->mem_ptr=mem_ptr;
  185994. (*(free_fn))(png_ptr, struct_ptr);
  185995. return;
  185996. }
  185997. #endif /* PNG_USER_MEM_SUPPORTED */
  185998. #if defined(__TURBOC__) && !defined(__FLAT__)
  185999. farfree(struct_ptr);
  186000. #else
  186001. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186002. hfree(struct_ptr);
  186003. # else
  186004. free(struct_ptr);
  186005. # endif
  186006. #endif
  186007. }
  186008. }
  186009. /* Allocate memory. For reasonable files, size should never exceed
  186010. 64K. However, zlib may allocate more then 64K if you don't tell
  186011. it not to. See zconf.h and png.h for more information. zlib does
  186012. need to allocate exactly 64K, so whatever you call here must
  186013. have the ability to do that. */
  186014. png_voidp PNGAPI
  186015. png_malloc(png_structp png_ptr, png_uint_32 size)
  186016. {
  186017. png_voidp ret;
  186018. #ifdef PNG_USER_MEM_SUPPORTED
  186019. if (png_ptr == NULL || size == 0)
  186020. return (NULL);
  186021. if(png_ptr->malloc_fn != NULL)
  186022. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  186023. else
  186024. ret = (png_malloc_default(png_ptr, size));
  186025. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186026. png_error(png_ptr, "Out of Memory!");
  186027. return (ret);
  186028. }
  186029. png_voidp PNGAPI
  186030. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  186031. {
  186032. png_voidp ret;
  186033. #endif /* PNG_USER_MEM_SUPPORTED */
  186034. if (png_ptr == NULL || size == 0)
  186035. return (NULL);
  186036. #ifdef PNG_MAX_MALLOC_64K
  186037. if (size > (png_uint_32)65536L)
  186038. {
  186039. #ifndef PNG_USER_MEM_SUPPORTED
  186040. if(png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186041. png_error(png_ptr, "Cannot Allocate > 64K");
  186042. else
  186043. #endif
  186044. return NULL;
  186045. }
  186046. #endif
  186047. /* Check for overflow */
  186048. #if defined(__TURBOC__) && !defined(__FLAT__)
  186049. if (size != (unsigned long)size)
  186050. ret = NULL;
  186051. else
  186052. ret = farmalloc(size);
  186053. #else
  186054. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186055. if (size != (unsigned long)size)
  186056. ret = NULL;
  186057. else
  186058. ret = halloc(size, 1);
  186059. # else
  186060. if (size != (size_t)size)
  186061. ret = NULL;
  186062. else
  186063. ret = malloc((size_t)size);
  186064. # endif
  186065. #endif
  186066. #ifndef PNG_USER_MEM_SUPPORTED
  186067. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186068. png_error(png_ptr, "Out of Memory");
  186069. #endif
  186070. return (ret);
  186071. }
  186072. /* Free a pointer allocated by png_malloc(). If ptr is NULL, return
  186073. without taking any action. */
  186074. void PNGAPI
  186075. png_free(png_structp png_ptr, png_voidp ptr)
  186076. {
  186077. if (png_ptr == NULL || ptr == NULL)
  186078. return;
  186079. #ifdef PNG_USER_MEM_SUPPORTED
  186080. if (png_ptr->free_fn != NULL)
  186081. {
  186082. (*(png_ptr->free_fn))(png_ptr, ptr);
  186083. return;
  186084. }
  186085. else png_free_default(png_ptr, ptr);
  186086. }
  186087. void PNGAPI
  186088. png_free_default(png_structp png_ptr, png_voidp ptr)
  186089. {
  186090. if (png_ptr == NULL || ptr == NULL)
  186091. return;
  186092. #endif /* PNG_USER_MEM_SUPPORTED */
  186093. #if defined(__TURBOC__) && !defined(__FLAT__)
  186094. farfree(ptr);
  186095. #else
  186096. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186097. hfree(ptr);
  186098. # else
  186099. free(ptr);
  186100. # endif
  186101. #endif
  186102. }
  186103. #endif /* Not Borland DOS special memory handler */
  186104. #if defined(PNG_1_0_X)
  186105. # define png_malloc_warn png_malloc
  186106. #else
  186107. /* This function was added at libpng version 1.2.3. The png_malloc_warn()
  186108. * function will set up png_malloc() to issue a png_warning and return NULL
  186109. * instead of issuing a png_error, if it fails to allocate the requested
  186110. * memory.
  186111. */
  186112. png_voidp PNGAPI
  186113. png_malloc_warn(png_structp png_ptr, png_uint_32 size)
  186114. {
  186115. png_voidp ptr;
  186116. png_uint_32 save_flags;
  186117. if(png_ptr == NULL) return (NULL);
  186118. save_flags=png_ptr->flags;
  186119. png_ptr->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  186120. ptr = (png_voidp)png_malloc((png_structp)png_ptr, size);
  186121. png_ptr->flags=save_flags;
  186122. return(ptr);
  186123. }
  186124. #endif
  186125. png_voidp PNGAPI
  186126. png_memcpy_check (png_structp png_ptr, png_voidp s1, png_voidp s2,
  186127. png_uint_32 length)
  186128. {
  186129. png_size_t size;
  186130. size = (png_size_t)length;
  186131. if ((png_uint_32)size != length)
  186132. png_error(png_ptr,"Overflow in png_memcpy_check.");
  186133. return(png_memcpy (s1, s2, size));
  186134. }
  186135. png_voidp PNGAPI
  186136. png_memset_check (png_structp png_ptr, png_voidp s1, int value,
  186137. png_uint_32 length)
  186138. {
  186139. png_size_t size;
  186140. size = (png_size_t)length;
  186141. if ((png_uint_32)size != length)
  186142. png_error(png_ptr,"Overflow in png_memset_check.");
  186143. return (png_memset (s1, value, size));
  186144. }
  186145. #ifdef PNG_USER_MEM_SUPPORTED
  186146. /* This function is called when the application wants to use another method
  186147. * of allocating and freeing memory.
  186148. */
  186149. void PNGAPI
  186150. png_set_mem_fn(png_structp png_ptr, png_voidp mem_ptr, png_malloc_ptr
  186151. malloc_fn, png_free_ptr free_fn)
  186152. {
  186153. if(png_ptr != NULL) {
  186154. png_ptr->mem_ptr = mem_ptr;
  186155. png_ptr->malloc_fn = malloc_fn;
  186156. png_ptr->free_fn = free_fn;
  186157. }
  186158. }
  186159. /* This function returns a pointer to the mem_ptr associated with the user
  186160. * functions. The application should free any memory associated with this
  186161. * pointer before png_write_destroy and png_read_destroy are called.
  186162. */
  186163. png_voidp PNGAPI
  186164. png_get_mem_ptr(png_structp png_ptr)
  186165. {
  186166. if(png_ptr == NULL) return (NULL);
  186167. return ((png_voidp)png_ptr->mem_ptr);
  186168. }
  186169. #endif /* PNG_USER_MEM_SUPPORTED */
  186170. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  186171. /*** End of inlined file: pngmem.c ***/
  186172. /*** Start of inlined file: pngread.c ***/
  186173. /* pngread.c - read a PNG file
  186174. *
  186175. * Last changed in libpng 1.2.20 September 7, 2007
  186176. * For conditions of distribution and use, see copyright notice in png.h
  186177. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  186178. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  186179. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  186180. *
  186181. * This file contains routines that an application calls directly to
  186182. * read a PNG file or stream.
  186183. */
  186184. #define PNG_INTERNAL
  186185. #if defined(PNG_READ_SUPPORTED)
  186186. /* Create a PNG structure for reading, and allocate any memory needed. */
  186187. png_structp PNGAPI
  186188. png_create_read_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  186189. png_error_ptr error_fn, png_error_ptr warn_fn)
  186190. {
  186191. #ifdef PNG_USER_MEM_SUPPORTED
  186192. return (png_create_read_struct_2(user_png_ver, error_ptr, error_fn,
  186193. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  186194. }
  186195. /* Alternate create PNG structure for reading, and allocate any memory needed. */
  186196. png_structp PNGAPI
  186197. png_create_read_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  186198. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  186199. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  186200. {
  186201. #endif /* PNG_USER_MEM_SUPPORTED */
  186202. png_structp png_ptr;
  186203. #ifdef PNG_SETJMP_SUPPORTED
  186204. #ifdef USE_FAR_KEYWORD
  186205. jmp_buf jmpbuf;
  186206. #endif
  186207. #endif
  186208. int i;
  186209. png_debug(1, "in png_create_read_struct\n");
  186210. #ifdef PNG_USER_MEM_SUPPORTED
  186211. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  186212. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  186213. #else
  186214. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  186215. #endif
  186216. if (png_ptr == NULL)
  186217. return (NULL);
  186218. /* added at libpng-1.2.6 */
  186219. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  186220. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  186221. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  186222. #endif
  186223. #ifdef PNG_SETJMP_SUPPORTED
  186224. #ifdef USE_FAR_KEYWORD
  186225. if (setjmp(jmpbuf))
  186226. #else
  186227. if (setjmp(png_ptr->jmpbuf))
  186228. #endif
  186229. {
  186230. png_free(png_ptr, png_ptr->zbuf);
  186231. png_ptr->zbuf=NULL;
  186232. #ifdef PNG_USER_MEM_SUPPORTED
  186233. png_destroy_struct_2((png_voidp)png_ptr,
  186234. (png_free_ptr)free_fn, (png_voidp)mem_ptr);
  186235. #else
  186236. png_destroy_struct((png_voidp)png_ptr);
  186237. #endif
  186238. return (NULL);
  186239. }
  186240. #ifdef USE_FAR_KEYWORD
  186241. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  186242. #endif
  186243. #endif
  186244. #ifdef PNG_USER_MEM_SUPPORTED
  186245. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  186246. #endif
  186247. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  186248. i=0;
  186249. do
  186250. {
  186251. if(user_png_ver[i] != png_libpng_ver[i])
  186252. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  186253. } while (png_libpng_ver[i++]);
  186254. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  186255. {
  186256. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  186257. * we must recompile any applications that use any older library version.
  186258. * For versions after libpng 1.0, we will be compatible, so we need
  186259. * only check the first digit.
  186260. */
  186261. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  186262. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  186263. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  186264. {
  186265. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  186266. char msg[80];
  186267. if (user_png_ver)
  186268. {
  186269. png_snprintf(msg, 80,
  186270. "Application was compiled with png.h from libpng-%.20s",
  186271. user_png_ver);
  186272. png_warning(png_ptr, msg);
  186273. }
  186274. png_snprintf(msg, 80,
  186275. "Application is running with png.c from libpng-%.20s",
  186276. png_libpng_ver);
  186277. png_warning(png_ptr, msg);
  186278. #endif
  186279. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  186280. png_ptr->flags=0;
  186281. #endif
  186282. png_error(png_ptr,
  186283. "Incompatible libpng version in application and library");
  186284. }
  186285. }
  186286. /* initialize zbuf - compression buffer */
  186287. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  186288. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  186289. (png_uint_32)png_ptr->zbuf_size);
  186290. png_ptr->zstream.zalloc = png_zalloc;
  186291. png_ptr->zstream.zfree = png_zfree;
  186292. png_ptr->zstream.opaque = (voidpf)png_ptr;
  186293. switch (inflateInit(&png_ptr->zstream))
  186294. {
  186295. case Z_OK: /* Do nothing */ break;
  186296. case Z_MEM_ERROR:
  186297. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break;
  186298. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error"); break;
  186299. default: png_error(png_ptr, "Unknown zlib error");
  186300. }
  186301. png_ptr->zstream.next_out = png_ptr->zbuf;
  186302. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  186303. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  186304. #ifdef PNG_SETJMP_SUPPORTED
  186305. /* Applications that neglect to set up their own setjmp() and then encounter
  186306. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  186307. abort instead of returning. */
  186308. #ifdef USE_FAR_KEYWORD
  186309. if (setjmp(jmpbuf))
  186310. PNG_ABORT();
  186311. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  186312. #else
  186313. if (setjmp(png_ptr->jmpbuf))
  186314. PNG_ABORT();
  186315. #endif
  186316. #endif
  186317. return (png_ptr);
  186318. }
  186319. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  186320. /* Initialize PNG structure for reading, and allocate any memory needed.
  186321. This interface is deprecated in favour of the png_create_read_struct(),
  186322. and it will disappear as of libpng-1.3.0. */
  186323. #undef png_read_init
  186324. void PNGAPI
  186325. png_read_init(png_structp png_ptr)
  186326. {
  186327. /* We only come here via pre-1.0.7-compiled applications */
  186328. png_read_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  186329. }
  186330. void PNGAPI
  186331. png_read_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  186332. png_size_t png_struct_size, png_size_t png_info_size)
  186333. {
  186334. /* We only come here via pre-1.0.12-compiled applications */
  186335. if(png_ptr == NULL) return;
  186336. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  186337. if(png_sizeof(png_struct) > png_struct_size ||
  186338. png_sizeof(png_info) > png_info_size)
  186339. {
  186340. char msg[80];
  186341. png_ptr->warning_fn=NULL;
  186342. if (user_png_ver)
  186343. {
  186344. png_snprintf(msg, 80,
  186345. "Application was compiled with png.h from libpng-%.20s",
  186346. user_png_ver);
  186347. png_warning(png_ptr, msg);
  186348. }
  186349. png_snprintf(msg, 80,
  186350. "Application is running with png.c from libpng-%.20s",
  186351. png_libpng_ver);
  186352. png_warning(png_ptr, msg);
  186353. }
  186354. #endif
  186355. if(png_sizeof(png_struct) > png_struct_size)
  186356. {
  186357. png_ptr->error_fn=NULL;
  186358. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  186359. png_ptr->flags=0;
  186360. #endif
  186361. png_error(png_ptr,
  186362. "The png struct allocated by the application for reading is too small.");
  186363. }
  186364. if(png_sizeof(png_info) > png_info_size)
  186365. {
  186366. png_ptr->error_fn=NULL;
  186367. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  186368. png_ptr->flags=0;
  186369. #endif
  186370. png_error(png_ptr,
  186371. "The info struct allocated by application for reading is too small.");
  186372. }
  186373. png_read_init_3(&png_ptr, user_png_ver, png_struct_size);
  186374. }
  186375. #endif /* PNG_1_0_X || PNG_1_2_X */
  186376. void PNGAPI
  186377. png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  186378. png_size_t png_struct_size)
  186379. {
  186380. #ifdef PNG_SETJMP_SUPPORTED
  186381. jmp_buf tmp_jmp; /* to save current jump buffer */
  186382. #endif
  186383. int i=0;
  186384. png_structp png_ptr=*ptr_ptr;
  186385. if(png_ptr == NULL) return;
  186386. do
  186387. {
  186388. if(user_png_ver[i] != png_libpng_ver[i])
  186389. {
  186390. #ifdef PNG_LEGACY_SUPPORTED
  186391. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  186392. #else
  186393. png_ptr->warning_fn=NULL;
  186394. png_warning(png_ptr,
  186395. "Application uses deprecated png_read_init() and should be recompiled.");
  186396. break;
  186397. #endif
  186398. }
  186399. } while (png_libpng_ver[i++]);
  186400. png_debug(1, "in png_read_init_3\n");
  186401. #ifdef PNG_SETJMP_SUPPORTED
  186402. /* save jump buffer and error functions */
  186403. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  186404. #endif
  186405. if(png_sizeof(png_struct) > png_struct_size)
  186406. {
  186407. png_destroy_struct(png_ptr);
  186408. *ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  186409. png_ptr = *ptr_ptr;
  186410. }
  186411. /* reset all variables to 0 */
  186412. png_memset(png_ptr, 0, png_sizeof (png_struct));
  186413. #ifdef PNG_SETJMP_SUPPORTED
  186414. /* restore jump buffer */
  186415. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  186416. #endif
  186417. /* added at libpng-1.2.6 */
  186418. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  186419. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  186420. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  186421. #endif
  186422. /* initialize zbuf - compression buffer */
  186423. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  186424. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  186425. (png_uint_32)png_ptr->zbuf_size);
  186426. png_ptr->zstream.zalloc = png_zalloc;
  186427. png_ptr->zstream.zfree = png_zfree;
  186428. png_ptr->zstream.opaque = (voidpf)png_ptr;
  186429. switch (inflateInit(&png_ptr->zstream))
  186430. {
  186431. case Z_OK: /* Do nothing */ break;
  186432. case Z_MEM_ERROR:
  186433. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory"); break;
  186434. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version"); break;
  186435. default: png_error(png_ptr, "Unknown zlib error");
  186436. }
  186437. png_ptr->zstream.next_out = png_ptr->zbuf;
  186438. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  186439. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  186440. }
  186441. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  186442. /* Read the information before the actual image data. This has been
  186443. * changed in v0.90 to allow reading a file that already has the magic
  186444. * bytes read from the stream. You can tell libpng how many bytes have
  186445. * been read from the beginning of the stream (up to the maximum of 8)
  186446. * via png_set_sig_bytes(), and we will only check the remaining bytes
  186447. * here. The application can then have access to the signature bytes we
  186448. * read if it is determined that this isn't a valid PNG file.
  186449. */
  186450. void PNGAPI
  186451. png_read_info(png_structp png_ptr, png_infop info_ptr)
  186452. {
  186453. if(png_ptr == NULL) return;
  186454. png_debug(1, "in png_read_info\n");
  186455. /* If we haven't checked all of the PNG signature bytes, do so now. */
  186456. if (png_ptr->sig_bytes < 8)
  186457. {
  186458. png_size_t num_checked = png_ptr->sig_bytes,
  186459. num_to_check = 8 - num_checked;
  186460. png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check);
  186461. png_ptr->sig_bytes = 8;
  186462. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  186463. {
  186464. if (num_checked < 4 &&
  186465. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  186466. png_error(png_ptr, "Not a PNG file");
  186467. else
  186468. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  186469. }
  186470. if (num_checked < 3)
  186471. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  186472. }
  186473. for(;;)
  186474. {
  186475. #ifdef PNG_USE_LOCAL_ARRAYS
  186476. PNG_CONST PNG_IHDR;
  186477. PNG_CONST PNG_IDAT;
  186478. PNG_CONST PNG_IEND;
  186479. PNG_CONST PNG_PLTE;
  186480. #if defined(PNG_READ_bKGD_SUPPORTED)
  186481. PNG_CONST PNG_bKGD;
  186482. #endif
  186483. #if defined(PNG_READ_cHRM_SUPPORTED)
  186484. PNG_CONST PNG_cHRM;
  186485. #endif
  186486. #if defined(PNG_READ_gAMA_SUPPORTED)
  186487. PNG_CONST PNG_gAMA;
  186488. #endif
  186489. #if defined(PNG_READ_hIST_SUPPORTED)
  186490. PNG_CONST PNG_hIST;
  186491. #endif
  186492. #if defined(PNG_READ_iCCP_SUPPORTED)
  186493. PNG_CONST PNG_iCCP;
  186494. #endif
  186495. #if defined(PNG_READ_iTXt_SUPPORTED)
  186496. PNG_CONST PNG_iTXt;
  186497. #endif
  186498. #if defined(PNG_READ_oFFs_SUPPORTED)
  186499. PNG_CONST PNG_oFFs;
  186500. #endif
  186501. #if defined(PNG_READ_pCAL_SUPPORTED)
  186502. PNG_CONST PNG_pCAL;
  186503. #endif
  186504. #if defined(PNG_READ_pHYs_SUPPORTED)
  186505. PNG_CONST PNG_pHYs;
  186506. #endif
  186507. #if defined(PNG_READ_sBIT_SUPPORTED)
  186508. PNG_CONST PNG_sBIT;
  186509. #endif
  186510. #if defined(PNG_READ_sCAL_SUPPORTED)
  186511. PNG_CONST PNG_sCAL;
  186512. #endif
  186513. #if defined(PNG_READ_sPLT_SUPPORTED)
  186514. PNG_CONST PNG_sPLT;
  186515. #endif
  186516. #if defined(PNG_READ_sRGB_SUPPORTED)
  186517. PNG_CONST PNG_sRGB;
  186518. #endif
  186519. #if defined(PNG_READ_tEXt_SUPPORTED)
  186520. PNG_CONST PNG_tEXt;
  186521. #endif
  186522. #if defined(PNG_READ_tIME_SUPPORTED)
  186523. PNG_CONST PNG_tIME;
  186524. #endif
  186525. #if defined(PNG_READ_tRNS_SUPPORTED)
  186526. PNG_CONST PNG_tRNS;
  186527. #endif
  186528. #if defined(PNG_READ_zTXt_SUPPORTED)
  186529. PNG_CONST PNG_zTXt;
  186530. #endif
  186531. #endif /* PNG_USE_LOCAL_ARRAYS */
  186532. png_byte chunk_length[4];
  186533. png_uint_32 length;
  186534. png_read_data(png_ptr, chunk_length, 4);
  186535. length = png_get_uint_31(png_ptr,chunk_length);
  186536. png_reset_crc(png_ptr);
  186537. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  186538. png_debug2(0, "Reading %s chunk, length=%lu.\n", png_ptr->chunk_name,
  186539. length);
  186540. /* This should be a binary subdivision search or a hash for
  186541. * matching the chunk name rather than a linear search.
  186542. */
  186543. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  186544. if(png_ptr->mode & PNG_AFTER_IDAT)
  186545. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  186546. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  186547. png_handle_IHDR(png_ptr, info_ptr, length);
  186548. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  186549. png_handle_IEND(png_ptr, info_ptr, length);
  186550. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  186551. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  186552. {
  186553. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  186554. png_ptr->mode |= PNG_HAVE_IDAT;
  186555. png_handle_unknown(png_ptr, info_ptr, length);
  186556. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  186557. png_ptr->mode |= PNG_HAVE_PLTE;
  186558. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  186559. {
  186560. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  186561. png_error(png_ptr, "Missing IHDR before IDAT");
  186562. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  186563. !(png_ptr->mode & PNG_HAVE_PLTE))
  186564. png_error(png_ptr, "Missing PLTE before IDAT");
  186565. break;
  186566. }
  186567. }
  186568. #endif
  186569. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  186570. png_handle_PLTE(png_ptr, info_ptr, length);
  186571. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  186572. {
  186573. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  186574. png_error(png_ptr, "Missing IHDR before IDAT");
  186575. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  186576. !(png_ptr->mode & PNG_HAVE_PLTE))
  186577. png_error(png_ptr, "Missing PLTE before IDAT");
  186578. png_ptr->idat_size = length;
  186579. png_ptr->mode |= PNG_HAVE_IDAT;
  186580. break;
  186581. }
  186582. #if defined(PNG_READ_bKGD_SUPPORTED)
  186583. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  186584. png_handle_bKGD(png_ptr, info_ptr, length);
  186585. #endif
  186586. #if defined(PNG_READ_cHRM_SUPPORTED)
  186587. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  186588. png_handle_cHRM(png_ptr, info_ptr, length);
  186589. #endif
  186590. #if defined(PNG_READ_gAMA_SUPPORTED)
  186591. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  186592. png_handle_gAMA(png_ptr, info_ptr, length);
  186593. #endif
  186594. #if defined(PNG_READ_hIST_SUPPORTED)
  186595. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  186596. png_handle_hIST(png_ptr, info_ptr, length);
  186597. #endif
  186598. #if defined(PNG_READ_oFFs_SUPPORTED)
  186599. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  186600. png_handle_oFFs(png_ptr, info_ptr, length);
  186601. #endif
  186602. #if defined(PNG_READ_pCAL_SUPPORTED)
  186603. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  186604. png_handle_pCAL(png_ptr, info_ptr, length);
  186605. #endif
  186606. #if defined(PNG_READ_sCAL_SUPPORTED)
  186607. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  186608. png_handle_sCAL(png_ptr, info_ptr, length);
  186609. #endif
  186610. #if defined(PNG_READ_pHYs_SUPPORTED)
  186611. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  186612. png_handle_pHYs(png_ptr, info_ptr, length);
  186613. #endif
  186614. #if defined(PNG_READ_sBIT_SUPPORTED)
  186615. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  186616. png_handle_sBIT(png_ptr, info_ptr, length);
  186617. #endif
  186618. #if defined(PNG_READ_sRGB_SUPPORTED)
  186619. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  186620. png_handle_sRGB(png_ptr, info_ptr, length);
  186621. #endif
  186622. #if defined(PNG_READ_iCCP_SUPPORTED)
  186623. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  186624. png_handle_iCCP(png_ptr, info_ptr, length);
  186625. #endif
  186626. #if defined(PNG_READ_sPLT_SUPPORTED)
  186627. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  186628. png_handle_sPLT(png_ptr, info_ptr, length);
  186629. #endif
  186630. #if defined(PNG_READ_tEXt_SUPPORTED)
  186631. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  186632. png_handle_tEXt(png_ptr, info_ptr, length);
  186633. #endif
  186634. #if defined(PNG_READ_tIME_SUPPORTED)
  186635. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  186636. png_handle_tIME(png_ptr, info_ptr, length);
  186637. #endif
  186638. #if defined(PNG_READ_tRNS_SUPPORTED)
  186639. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  186640. png_handle_tRNS(png_ptr, info_ptr, length);
  186641. #endif
  186642. #if defined(PNG_READ_zTXt_SUPPORTED)
  186643. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  186644. png_handle_zTXt(png_ptr, info_ptr, length);
  186645. #endif
  186646. #if defined(PNG_READ_iTXt_SUPPORTED)
  186647. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  186648. png_handle_iTXt(png_ptr, info_ptr, length);
  186649. #endif
  186650. else
  186651. png_handle_unknown(png_ptr, info_ptr, length);
  186652. }
  186653. }
  186654. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  186655. /* optional call to update the users info_ptr structure */
  186656. void PNGAPI
  186657. png_read_update_info(png_structp png_ptr, png_infop info_ptr)
  186658. {
  186659. png_debug(1, "in png_read_update_info\n");
  186660. if(png_ptr == NULL) return;
  186661. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  186662. png_read_start_row(png_ptr);
  186663. else
  186664. png_warning(png_ptr,
  186665. "Ignoring extra png_read_update_info() call; row buffer not reallocated");
  186666. png_read_transform_info(png_ptr, info_ptr);
  186667. }
  186668. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  186669. /* Initialize palette, background, etc, after transformations
  186670. * are set, but before any reading takes place. This allows
  186671. * the user to obtain a gamma-corrected palette, for example.
  186672. * If the user doesn't call this, we will do it ourselves.
  186673. */
  186674. void PNGAPI
  186675. png_start_read_image(png_structp png_ptr)
  186676. {
  186677. png_debug(1, "in png_start_read_image\n");
  186678. if(png_ptr == NULL) return;
  186679. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  186680. png_read_start_row(png_ptr);
  186681. }
  186682. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  186683. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  186684. void PNGAPI
  186685. png_read_row(png_structp png_ptr, png_bytep row, png_bytep dsp_row)
  186686. {
  186687. #ifdef PNG_USE_LOCAL_ARRAYS
  186688. PNG_CONST PNG_IDAT;
  186689. PNG_CONST int png_pass_dsp_mask[7] = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
  186690. 0xff};
  186691. PNG_CONST int png_pass_mask[7] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  186692. #endif
  186693. int ret;
  186694. if(png_ptr == NULL) return;
  186695. png_debug2(1, "in png_read_row (row %lu, pass %d)\n",
  186696. png_ptr->row_number, png_ptr->pass);
  186697. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  186698. png_read_start_row(png_ptr);
  186699. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  186700. {
  186701. /* check for transforms that have been set but were defined out */
  186702. #if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
  186703. if (png_ptr->transformations & PNG_INVERT_MONO)
  186704. png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined.");
  186705. #endif
  186706. #if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
  186707. if (png_ptr->transformations & PNG_FILLER)
  186708. png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined.");
  186709. #endif
  186710. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && !defined(PNG_READ_PACKSWAP_SUPPORTED)
  186711. if (png_ptr->transformations & PNG_PACKSWAP)
  186712. png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined.");
  186713. #endif
  186714. #if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
  186715. if (png_ptr->transformations & PNG_PACK)
  186716. png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined.");
  186717. #endif
  186718. #if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
  186719. if (png_ptr->transformations & PNG_SHIFT)
  186720. png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined.");
  186721. #endif
  186722. #if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
  186723. if (png_ptr->transformations & PNG_BGR)
  186724. png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined.");
  186725. #endif
  186726. #if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
  186727. if (png_ptr->transformations & PNG_SWAP_BYTES)
  186728. png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined.");
  186729. #endif
  186730. }
  186731. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  186732. /* if interlaced and we do not need a new row, combine row and return */
  186733. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  186734. {
  186735. switch (png_ptr->pass)
  186736. {
  186737. case 0:
  186738. if (png_ptr->row_number & 0x07)
  186739. {
  186740. if (dsp_row != NULL)
  186741. png_combine_row(png_ptr, dsp_row,
  186742. png_pass_dsp_mask[png_ptr->pass]);
  186743. png_read_finish_row(png_ptr);
  186744. return;
  186745. }
  186746. break;
  186747. case 1:
  186748. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  186749. {
  186750. if (dsp_row != NULL)
  186751. png_combine_row(png_ptr, dsp_row,
  186752. png_pass_dsp_mask[png_ptr->pass]);
  186753. png_read_finish_row(png_ptr);
  186754. return;
  186755. }
  186756. break;
  186757. case 2:
  186758. if ((png_ptr->row_number & 0x07) != 4)
  186759. {
  186760. if (dsp_row != NULL && (png_ptr->row_number & 4))
  186761. png_combine_row(png_ptr, dsp_row,
  186762. png_pass_dsp_mask[png_ptr->pass]);
  186763. png_read_finish_row(png_ptr);
  186764. return;
  186765. }
  186766. break;
  186767. case 3:
  186768. if ((png_ptr->row_number & 3) || png_ptr->width < 3)
  186769. {
  186770. if (dsp_row != NULL)
  186771. png_combine_row(png_ptr, dsp_row,
  186772. png_pass_dsp_mask[png_ptr->pass]);
  186773. png_read_finish_row(png_ptr);
  186774. return;
  186775. }
  186776. break;
  186777. case 4:
  186778. if ((png_ptr->row_number & 3) != 2)
  186779. {
  186780. if (dsp_row != NULL && (png_ptr->row_number & 2))
  186781. png_combine_row(png_ptr, dsp_row,
  186782. png_pass_dsp_mask[png_ptr->pass]);
  186783. png_read_finish_row(png_ptr);
  186784. return;
  186785. }
  186786. break;
  186787. case 5:
  186788. if ((png_ptr->row_number & 1) || png_ptr->width < 2)
  186789. {
  186790. if (dsp_row != NULL)
  186791. png_combine_row(png_ptr, dsp_row,
  186792. png_pass_dsp_mask[png_ptr->pass]);
  186793. png_read_finish_row(png_ptr);
  186794. return;
  186795. }
  186796. break;
  186797. case 6:
  186798. if (!(png_ptr->row_number & 1))
  186799. {
  186800. png_read_finish_row(png_ptr);
  186801. return;
  186802. }
  186803. break;
  186804. }
  186805. }
  186806. #endif
  186807. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  186808. png_error(png_ptr, "Invalid attempt to read row data");
  186809. png_ptr->zstream.next_out = png_ptr->row_buf;
  186810. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  186811. do
  186812. {
  186813. if (!(png_ptr->zstream.avail_in))
  186814. {
  186815. while (!png_ptr->idat_size)
  186816. {
  186817. png_byte chunk_length[4];
  186818. png_crc_finish(png_ptr, 0);
  186819. png_read_data(png_ptr, chunk_length, 4);
  186820. png_ptr->idat_size = png_get_uint_31(png_ptr,chunk_length);
  186821. png_reset_crc(png_ptr);
  186822. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  186823. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  186824. png_error(png_ptr, "Not enough image data");
  186825. }
  186826. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  186827. png_ptr->zstream.next_in = png_ptr->zbuf;
  186828. if (png_ptr->zbuf_size > png_ptr->idat_size)
  186829. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  186830. png_crc_read(png_ptr, png_ptr->zbuf,
  186831. (png_size_t)png_ptr->zstream.avail_in);
  186832. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  186833. }
  186834. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  186835. if (ret == Z_STREAM_END)
  186836. {
  186837. if (png_ptr->zstream.avail_out || png_ptr->zstream.avail_in ||
  186838. png_ptr->idat_size)
  186839. png_error(png_ptr, "Extra compressed data");
  186840. png_ptr->mode |= PNG_AFTER_IDAT;
  186841. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  186842. break;
  186843. }
  186844. if (ret != Z_OK)
  186845. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  186846. "Decompression error");
  186847. } while (png_ptr->zstream.avail_out);
  186848. png_ptr->row_info.color_type = png_ptr->color_type;
  186849. png_ptr->row_info.width = png_ptr->iwidth;
  186850. png_ptr->row_info.channels = png_ptr->channels;
  186851. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  186852. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  186853. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  186854. png_ptr->row_info.width);
  186855. if(png_ptr->row_buf[0])
  186856. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  186857. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  186858. (int)(png_ptr->row_buf[0]));
  186859. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  186860. png_ptr->rowbytes + 1);
  186861. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  186862. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  186863. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  186864. {
  186865. /* Intrapixel differencing */
  186866. png_do_read_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186867. }
  186868. #endif
  186869. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  186870. png_do_read_transformations(png_ptr);
  186871. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  186872. /* blow up interlaced rows to full size */
  186873. if (png_ptr->interlaced &&
  186874. (png_ptr->transformations & PNG_INTERLACE))
  186875. {
  186876. if (png_ptr->pass < 6)
  186877. /* old interface (pre-1.0.9):
  186878. png_do_read_interlace(&(png_ptr->row_info),
  186879. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  186880. */
  186881. png_do_read_interlace(png_ptr);
  186882. if (dsp_row != NULL)
  186883. png_combine_row(png_ptr, dsp_row,
  186884. png_pass_dsp_mask[png_ptr->pass]);
  186885. if (row != NULL)
  186886. png_combine_row(png_ptr, row,
  186887. png_pass_mask[png_ptr->pass]);
  186888. }
  186889. else
  186890. #endif
  186891. {
  186892. if (row != NULL)
  186893. png_combine_row(png_ptr, row, 0xff);
  186894. if (dsp_row != NULL)
  186895. png_combine_row(png_ptr, dsp_row, 0xff);
  186896. }
  186897. png_read_finish_row(png_ptr);
  186898. if (png_ptr->read_row_fn != NULL)
  186899. (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  186900. }
  186901. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  186902. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  186903. /* Read one or more rows of image data. If the image is interlaced,
  186904. * and png_set_interlace_handling() has been called, the rows need to
  186905. * contain the contents of the rows from the previous pass. If the
  186906. * image has alpha or transparency, and png_handle_alpha()[*] has been
  186907. * called, the rows contents must be initialized to the contents of the
  186908. * screen.
  186909. *
  186910. * "row" holds the actual image, and pixels are placed in it
  186911. * as they arrive. If the image is displayed after each pass, it will
  186912. * appear to "sparkle" in. "display_row" can be used to display a
  186913. * "chunky" progressive image, with finer detail added as it becomes
  186914. * available. If you do not want this "chunky" display, you may pass
  186915. * NULL for display_row. If you do not want the sparkle display, and
  186916. * you have not called png_handle_alpha(), you may pass NULL for rows.
  186917. * If you have called png_handle_alpha(), and the image has either an
  186918. * alpha channel or a transparency chunk, you must provide a buffer for
  186919. * rows. In this case, you do not have to provide a display_row buffer
  186920. * also, but you may. If the image is not interlaced, or if you have
  186921. * not called png_set_interlace_handling(), the display_row buffer will
  186922. * be ignored, so pass NULL to it.
  186923. *
  186924. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  186925. */
  186926. void PNGAPI
  186927. png_read_rows(png_structp png_ptr, png_bytepp row,
  186928. png_bytepp display_row, png_uint_32 num_rows)
  186929. {
  186930. png_uint_32 i;
  186931. png_bytepp rp;
  186932. png_bytepp dp;
  186933. png_debug(1, "in png_read_rows\n");
  186934. if(png_ptr == NULL) return;
  186935. rp = row;
  186936. dp = display_row;
  186937. if (rp != NULL && dp != NULL)
  186938. for (i = 0; i < num_rows; i++)
  186939. {
  186940. png_bytep rptr = *rp++;
  186941. png_bytep dptr = *dp++;
  186942. png_read_row(png_ptr, rptr, dptr);
  186943. }
  186944. else if(rp != NULL)
  186945. for (i = 0; i < num_rows; i++)
  186946. {
  186947. png_bytep rptr = *rp;
  186948. png_read_row(png_ptr, rptr, png_bytep_NULL);
  186949. rp++;
  186950. }
  186951. else if(dp != NULL)
  186952. for (i = 0; i < num_rows; i++)
  186953. {
  186954. png_bytep dptr = *dp;
  186955. png_read_row(png_ptr, png_bytep_NULL, dptr);
  186956. dp++;
  186957. }
  186958. }
  186959. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  186960. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  186961. /* Read the entire image. If the image has an alpha channel or a tRNS
  186962. * chunk, and you have called png_handle_alpha()[*], you will need to
  186963. * initialize the image to the current image that PNG will be overlaying.
  186964. * We set the num_rows again here, in case it was incorrectly set in
  186965. * png_read_start_row() by a call to png_read_update_info() or
  186966. * png_start_read_image() if png_set_interlace_handling() wasn't called
  186967. * prior to either of these functions like it should have been. You can
  186968. * only call this function once. If you desire to have an image for
  186969. * each pass of a interlaced image, use png_read_rows() instead.
  186970. *
  186971. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  186972. */
  186973. void PNGAPI
  186974. png_read_image(png_structp png_ptr, png_bytepp image)
  186975. {
  186976. png_uint_32 i,image_height;
  186977. int pass, j;
  186978. png_bytepp rp;
  186979. png_debug(1, "in png_read_image\n");
  186980. if(png_ptr == NULL) return;
  186981. #ifdef PNG_READ_INTERLACING_SUPPORTED
  186982. pass = png_set_interlace_handling(png_ptr);
  186983. #else
  186984. if (png_ptr->interlaced)
  186985. png_error(png_ptr,
  186986. "Cannot read interlaced image -- interlace handler disabled.");
  186987. pass = 1;
  186988. #endif
  186989. image_height=png_ptr->height;
  186990. png_ptr->num_rows = image_height; /* Make sure this is set correctly */
  186991. for (j = 0; j < pass; j++)
  186992. {
  186993. rp = image;
  186994. for (i = 0; i < image_height; i++)
  186995. {
  186996. png_read_row(png_ptr, *rp, png_bytep_NULL);
  186997. rp++;
  186998. }
  186999. }
  187000. }
  187001. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187002. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187003. /* Read the end of the PNG file. Will not read past the end of the
  187004. * file, will verify the end is accurate, and will read any comments
  187005. * or time information at the end of the file, if info is not NULL.
  187006. */
  187007. void PNGAPI
  187008. png_read_end(png_structp png_ptr, png_infop info_ptr)
  187009. {
  187010. png_byte chunk_length[4];
  187011. png_uint_32 length;
  187012. png_debug(1, "in png_read_end\n");
  187013. if(png_ptr == NULL) return;
  187014. png_crc_finish(png_ptr, 0); /* Finish off CRC from last IDAT chunk */
  187015. do
  187016. {
  187017. #ifdef PNG_USE_LOCAL_ARRAYS
  187018. PNG_CONST PNG_IHDR;
  187019. PNG_CONST PNG_IDAT;
  187020. PNG_CONST PNG_IEND;
  187021. PNG_CONST PNG_PLTE;
  187022. #if defined(PNG_READ_bKGD_SUPPORTED)
  187023. PNG_CONST PNG_bKGD;
  187024. #endif
  187025. #if defined(PNG_READ_cHRM_SUPPORTED)
  187026. PNG_CONST PNG_cHRM;
  187027. #endif
  187028. #if defined(PNG_READ_gAMA_SUPPORTED)
  187029. PNG_CONST PNG_gAMA;
  187030. #endif
  187031. #if defined(PNG_READ_hIST_SUPPORTED)
  187032. PNG_CONST PNG_hIST;
  187033. #endif
  187034. #if defined(PNG_READ_iCCP_SUPPORTED)
  187035. PNG_CONST PNG_iCCP;
  187036. #endif
  187037. #if defined(PNG_READ_iTXt_SUPPORTED)
  187038. PNG_CONST PNG_iTXt;
  187039. #endif
  187040. #if defined(PNG_READ_oFFs_SUPPORTED)
  187041. PNG_CONST PNG_oFFs;
  187042. #endif
  187043. #if defined(PNG_READ_pCAL_SUPPORTED)
  187044. PNG_CONST PNG_pCAL;
  187045. #endif
  187046. #if defined(PNG_READ_pHYs_SUPPORTED)
  187047. PNG_CONST PNG_pHYs;
  187048. #endif
  187049. #if defined(PNG_READ_sBIT_SUPPORTED)
  187050. PNG_CONST PNG_sBIT;
  187051. #endif
  187052. #if defined(PNG_READ_sCAL_SUPPORTED)
  187053. PNG_CONST PNG_sCAL;
  187054. #endif
  187055. #if defined(PNG_READ_sPLT_SUPPORTED)
  187056. PNG_CONST PNG_sPLT;
  187057. #endif
  187058. #if defined(PNG_READ_sRGB_SUPPORTED)
  187059. PNG_CONST PNG_sRGB;
  187060. #endif
  187061. #if defined(PNG_READ_tEXt_SUPPORTED)
  187062. PNG_CONST PNG_tEXt;
  187063. #endif
  187064. #if defined(PNG_READ_tIME_SUPPORTED)
  187065. PNG_CONST PNG_tIME;
  187066. #endif
  187067. #if defined(PNG_READ_tRNS_SUPPORTED)
  187068. PNG_CONST PNG_tRNS;
  187069. #endif
  187070. #if defined(PNG_READ_zTXt_SUPPORTED)
  187071. PNG_CONST PNG_zTXt;
  187072. #endif
  187073. #endif /* PNG_USE_LOCAL_ARRAYS */
  187074. png_read_data(png_ptr, chunk_length, 4);
  187075. length = png_get_uint_31(png_ptr,chunk_length);
  187076. png_reset_crc(png_ptr);
  187077. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187078. png_debug1(0, "Reading %s chunk.\n", png_ptr->chunk_name);
  187079. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  187080. png_handle_IHDR(png_ptr, info_ptr, length);
  187081. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  187082. png_handle_IEND(png_ptr, info_ptr, length);
  187083. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  187084. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  187085. {
  187086. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187087. {
  187088. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  187089. png_error(png_ptr, "Too many IDAT's found");
  187090. }
  187091. png_handle_unknown(png_ptr, info_ptr, length);
  187092. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187093. png_ptr->mode |= PNG_HAVE_PLTE;
  187094. }
  187095. #endif
  187096. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187097. {
  187098. /* Zero length IDATs are legal after the last IDAT has been
  187099. * read, but not after other chunks have been read.
  187100. */
  187101. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  187102. png_error(png_ptr, "Too many IDAT's found");
  187103. png_crc_finish(png_ptr, length);
  187104. }
  187105. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187106. png_handle_PLTE(png_ptr, info_ptr, length);
  187107. #if defined(PNG_READ_bKGD_SUPPORTED)
  187108. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  187109. png_handle_bKGD(png_ptr, info_ptr, length);
  187110. #endif
  187111. #if defined(PNG_READ_cHRM_SUPPORTED)
  187112. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  187113. png_handle_cHRM(png_ptr, info_ptr, length);
  187114. #endif
  187115. #if defined(PNG_READ_gAMA_SUPPORTED)
  187116. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  187117. png_handle_gAMA(png_ptr, info_ptr, length);
  187118. #endif
  187119. #if defined(PNG_READ_hIST_SUPPORTED)
  187120. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  187121. png_handle_hIST(png_ptr, info_ptr, length);
  187122. #endif
  187123. #if defined(PNG_READ_oFFs_SUPPORTED)
  187124. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  187125. png_handle_oFFs(png_ptr, info_ptr, length);
  187126. #endif
  187127. #if defined(PNG_READ_pCAL_SUPPORTED)
  187128. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  187129. png_handle_pCAL(png_ptr, info_ptr, length);
  187130. #endif
  187131. #if defined(PNG_READ_sCAL_SUPPORTED)
  187132. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  187133. png_handle_sCAL(png_ptr, info_ptr, length);
  187134. #endif
  187135. #if defined(PNG_READ_pHYs_SUPPORTED)
  187136. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  187137. png_handle_pHYs(png_ptr, info_ptr, length);
  187138. #endif
  187139. #if defined(PNG_READ_sBIT_SUPPORTED)
  187140. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  187141. png_handle_sBIT(png_ptr, info_ptr, length);
  187142. #endif
  187143. #if defined(PNG_READ_sRGB_SUPPORTED)
  187144. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  187145. png_handle_sRGB(png_ptr, info_ptr, length);
  187146. #endif
  187147. #if defined(PNG_READ_iCCP_SUPPORTED)
  187148. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  187149. png_handle_iCCP(png_ptr, info_ptr, length);
  187150. #endif
  187151. #if defined(PNG_READ_sPLT_SUPPORTED)
  187152. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  187153. png_handle_sPLT(png_ptr, info_ptr, length);
  187154. #endif
  187155. #if defined(PNG_READ_tEXt_SUPPORTED)
  187156. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  187157. png_handle_tEXt(png_ptr, info_ptr, length);
  187158. #endif
  187159. #if defined(PNG_READ_tIME_SUPPORTED)
  187160. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  187161. png_handle_tIME(png_ptr, info_ptr, length);
  187162. #endif
  187163. #if defined(PNG_READ_tRNS_SUPPORTED)
  187164. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  187165. png_handle_tRNS(png_ptr, info_ptr, length);
  187166. #endif
  187167. #if defined(PNG_READ_zTXt_SUPPORTED)
  187168. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  187169. png_handle_zTXt(png_ptr, info_ptr, length);
  187170. #endif
  187171. #if defined(PNG_READ_iTXt_SUPPORTED)
  187172. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  187173. png_handle_iTXt(png_ptr, info_ptr, length);
  187174. #endif
  187175. else
  187176. png_handle_unknown(png_ptr, info_ptr, length);
  187177. } while (!(png_ptr->mode & PNG_HAVE_IEND));
  187178. }
  187179. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187180. /* free all memory used by the read */
  187181. void PNGAPI
  187182. png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
  187183. png_infopp end_info_ptr_ptr)
  187184. {
  187185. png_structp png_ptr = NULL;
  187186. png_infop info_ptr = NULL, end_info_ptr = NULL;
  187187. #ifdef PNG_USER_MEM_SUPPORTED
  187188. png_free_ptr free_fn;
  187189. png_voidp mem_ptr;
  187190. #endif
  187191. png_debug(1, "in png_destroy_read_struct\n");
  187192. if (png_ptr_ptr != NULL)
  187193. png_ptr = *png_ptr_ptr;
  187194. if (info_ptr_ptr != NULL)
  187195. info_ptr = *info_ptr_ptr;
  187196. if (end_info_ptr_ptr != NULL)
  187197. end_info_ptr = *end_info_ptr_ptr;
  187198. #ifdef PNG_USER_MEM_SUPPORTED
  187199. free_fn = png_ptr->free_fn;
  187200. mem_ptr = png_ptr->mem_ptr;
  187201. #endif
  187202. png_read_destroy(png_ptr, info_ptr, end_info_ptr);
  187203. if (info_ptr != NULL)
  187204. {
  187205. #if defined(PNG_TEXT_SUPPORTED)
  187206. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, -1);
  187207. #endif
  187208. #ifdef PNG_USER_MEM_SUPPORTED
  187209. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  187210. (png_voidp)mem_ptr);
  187211. #else
  187212. png_destroy_struct((png_voidp)info_ptr);
  187213. #endif
  187214. *info_ptr_ptr = NULL;
  187215. }
  187216. if (end_info_ptr != NULL)
  187217. {
  187218. #if defined(PNG_READ_TEXT_SUPPORTED)
  187219. png_free_data(png_ptr, end_info_ptr, PNG_FREE_TEXT, -1);
  187220. #endif
  187221. #ifdef PNG_USER_MEM_SUPPORTED
  187222. png_destroy_struct_2((png_voidp)end_info_ptr, (png_free_ptr)free_fn,
  187223. (png_voidp)mem_ptr);
  187224. #else
  187225. png_destroy_struct((png_voidp)end_info_ptr);
  187226. #endif
  187227. *end_info_ptr_ptr = NULL;
  187228. }
  187229. if (png_ptr != NULL)
  187230. {
  187231. #ifdef PNG_USER_MEM_SUPPORTED
  187232. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  187233. (png_voidp)mem_ptr);
  187234. #else
  187235. png_destroy_struct((png_voidp)png_ptr);
  187236. #endif
  187237. *png_ptr_ptr = NULL;
  187238. }
  187239. }
  187240. /* free all memory used by the read (old method) */
  187241. void /* PRIVATE */
  187242. png_read_destroy(png_structp png_ptr, png_infop info_ptr, png_infop end_info_ptr)
  187243. {
  187244. #ifdef PNG_SETJMP_SUPPORTED
  187245. jmp_buf tmp_jmp;
  187246. #endif
  187247. png_error_ptr error_fn;
  187248. png_error_ptr warning_fn;
  187249. png_voidp error_ptr;
  187250. #ifdef PNG_USER_MEM_SUPPORTED
  187251. png_free_ptr free_fn;
  187252. #endif
  187253. png_debug(1, "in png_read_destroy\n");
  187254. if (info_ptr != NULL)
  187255. png_info_destroy(png_ptr, info_ptr);
  187256. if (end_info_ptr != NULL)
  187257. png_info_destroy(png_ptr, end_info_ptr);
  187258. png_free(png_ptr, png_ptr->zbuf);
  187259. png_free(png_ptr, png_ptr->big_row_buf);
  187260. png_free(png_ptr, png_ptr->prev_row);
  187261. #if defined(PNG_READ_DITHER_SUPPORTED)
  187262. png_free(png_ptr, png_ptr->palette_lookup);
  187263. png_free(png_ptr, png_ptr->dither_index);
  187264. #endif
  187265. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187266. png_free(png_ptr, png_ptr->gamma_table);
  187267. #endif
  187268. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  187269. png_free(png_ptr, png_ptr->gamma_from_1);
  187270. png_free(png_ptr, png_ptr->gamma_to_1);
  187271. #endif
  187272. #ifdef PNG_FREE_ME_SUPPORTED
  187273. if (png_ptr->free_me & PNG_FREE_PLTE)
  187274. png_zfree(png_ptr, png_ptr->palette);
  187275. png_ptr->free_me &= ~PNG_FREE_PLTE;
  187276. #else
  187277. if (png_ptr->flags & PNG_FLAG_FREE_PLTE)
  187278. png_zfree(png_ptr, png_ptr->palette);
  187279. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  187280. #endif
  187281. #if defined(PNG_tRNS_SUPPORTED) || \
  187282. defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  187283. #ifdef PNG_FREE_ME_SUPPORTED
  187284. if (png_ptr->free_me & PNG_FREE_TRNS)
  187285. png_free(png_ptr, png_ptr->trans);
  187286. png_ptr->free_me &= ~PNG_FREE_TRNS;
  187287. #else
  187288. if (png_ptr->flags & PNG_FLAG_FREE_TRNS)
  187289. png_free(png_ptr, png_ptr->trans);
  187290. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  187291. #endif
  187292. #endif
  187293. #if defined(PNG_READ_hIST_SUPPORTED)
  187294. #ifdef PNG_FREE_ME_SUPPORTED
  187295. if (png_ptr->free_me & PNG_FREE_HIST)
  187296. png_free(png_ptr, png_ptr->hist);
  187297. png_ptr->free_me &= ~PNG_FREE_HIST;
  187298. #else
  187299. if (png_ptr->flags & PNG_FLAG_FREE_HIST)
  187300. png_free(png_ptr, png_ptr->hist);
  187301. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  187302. #endif
  187303. #endif
  187304. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187305. if (png_ptr->gamma_16_table != NULL)
  187306. {
  187307. int i;
  187308. int istop = (1 << (8 - png_ptr->gamma_shift));
  187309. for (i = 0; i < istop; i++)
  187310. {
  187311. png_free(png_ptr, png_ptr->gamma_16_table[i]);
  187312. }
  187313. png_free(png_ptr, png_ptr->gamma_16_table);
  187314. }
  187315. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  187316. if (png_ptr->gamma_16_from_1 != NULL)
  187317. {
  187318. int i;
  187319. int istop = (1 << (8 - png_ptr->gamma_shift));
  187320. for (i = 0; i < istop; i++)
  187321. {
  187322. png_free(png_ptr, png_ptr->gamma_16_from_1[i]);
  187323. }
  187324. png_free(png_ptr, png_ptr->gamma_16_from_1);
  187325. }
  187326. if (png_ptr->gamma_16_to_1 != NULL)
  187327. {
  187328. int i;
  187329. int istop = (1 << (8 - png_ptr->gamma_shift));
  187330. for (i = 0; i < istop; i++)
  187331. {
  187332. png_free(png_ptr, png_ptr->gamma_16_to_1[i]);
  187333. }
  187334. png_free(png_ptr, png_ptr->gamma_16_to_1);
  187335. }
  187336. #endif
  187337. #endif
  187338. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  187339. png_free(png_ptr, png_ptr->time_buffer);
  187340. #endif
  187341. inflateEnd(&png_ptr->zstream);
  187342. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  187343. png_free(png_ptr, png_ptr->save_buffer);
  187344. #endif
  187345. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  187346. #ifdef PNG_TEXT_SUPPORTED
  187347. png_free(png_ptr, png_ptr->current_text);
  187348. #endif /* PNG_TEXT_SUPPORTED */
  187349. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  187350. /* Save the important info out of the png_struct, in case it is
  187351. * being used again.
  187352. */
  187353. #ifdef PNG_SETJMP_SUPPORTED
  187354. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  187355. #endif
  187356. error_fn = png_ptr->error_fn;
  187357. warning_fn = png_ptr->warning_fn;
  187358. error_ptr = png_ptr->error_ptr;
  187359. #ifdef PNG_USER_MEM_SUPPORTED
  187360. free_fn = png_ptr->free_fn;
  187361. #endif
  187362. png_memset(png_ptr, 0, png_sizeof (png_struct));
  187363. png_ptr->error_fn = error_fn;
  187364. png_ptr->warning_fn = warning_fn;
  187365. png_ptr->error_ptr = error_ptr;
  187366. #ifdef PNG_USER_MEM_SUPPORTED
  187367. png_ptr->free_fn = free_fn;
  187368. #endif
  187369. #ifdef PNG_SETJMP_SUPPORTED
  187370. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  187371. #endif
  187372. }
  187373. void PNGAPI
  187374. png_set_read_status_fn(png_structp png_ptr, png_read_status_ptr read_row_fn)
  187375. {
  187376. if(png_ptr == NULL) return;
  187377. png_ptr->read_row_fn = read_row_fn;
  187378. }
  187379. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187380. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  187381. void PNGAPI
  187382. png_read_png(png_structp png_ptr, png_infop info_ptr,
  187383. int transforms,
  187384. voidp params)
  187385. {
  187386. int row;
  187387. if(png_ptr == NULL) return;
  187388. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  187389. /* invert the alpha channel from opacity to transparency
  187390. */
  187391. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  187392. png_set_invert_alpha(png_ptr);
  187393. #endif
  187394. /* png_read_info() gives us all of the information from the
  187395. * PNG file before the first IDAT (image data chunk).
  187396. */
  187397. png_read_info(png_ptr, info_ptr);
  187398. if (info_ptr->height > PNG_UINT_32_MAX/png_sizeof(png_bytep))
  187399. png_error(png_ptr,"Image is too high to process with png_read_png()");
  187400. /* -------------- image transformations start here ------------------- */
  187401. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  187402. /* tell libpng to strip 16 bit/color files down to 8 bits per color
  187403. */
  187404. if (transforms & PNG_TRANSFORM_STRIP_16)
  187405. png_set_strip_16(png_ptr);
  187406. #endif
  187407. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  187408. /* Strip alpha bytes from the input data without combining with
  187409. * the background (not recommended).
  187410. */
  187411. if (transforms & PNG_TRANSFORM_STRIP_ALPHA)
  187412. png_set_strip_alpha(png_ptr);
  187413. #endif
  187414. #if defined(PNG_READ_PACK_SUPPORTED) && !defined(PNG_READ_EXPAND_SUPPORTED)
  187415. /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
  187416. * byte into separate bytes (useful for paletted and grayscale images).
  187417. */
  187418. if (transforms & PNG_TRANSFORM_PACKING)
  187419. png_set_packing(png_ptr);
  187420. #endif
  187421. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  187422. /* Change the order of packed pixels to least significant bit first
  187423. * (not useful if you are using png_set_packing).
  187424. */
  187425. if (transforms & PNG_TRANSFORM_PACKSWAP)
  187426. png_set_packswap(png_ptr);
  187427. #endif
  187428. #if defined(PNG_READ_EXPAND_SUPPORTED)
  187429. /* Expand paletted colors into true RGB triplets
  187430. * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
  187431. * Expand paletted or RGB images with transparency to full alpha
  187432. * channels so the data will be available as RGBA quartets.
  187433. */
  187434. if (transforms & PNG_TRANSFORM_EXPAND)
  187435. if ((png_ptr->bit_depth < 8) ||
  187436. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ||
  187437. (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)))
  187438. png_set_expand(png_ptr);
  187439. #endif
  187440. /* We don't handle background color or gamma transformation or dithering.
  187441. */
  187442. #if defined(PNG_READ_INVERT_SUPPORTED)
  187443. /* invert monochrome files to have 0 as white and 1 as black
  187444. */
  187445. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  187446. png_set_invert_mono(png_ptr);
  187447. #endif
  187448. #if defined(PNG_READ_SHIFT_SUPPORTED)
  187449. /* If you want to shift the pixel values from the range [0,255] or
  187450. * [0,65535] to the original [0,7] or [0,31], or whatever range the
  187451. * colors were originally in:
  187452. */
  187453. if ((transforms & PNG_TRANSFORM_SHIFT)
  187454. && png_get_valid(png_ptr, info_ptr, PNG_INFO_sBIT))
  187455. {
  187456. png_color_8p sig_bit;
  187457. png_get_sBIT(png_ptr, info_ptr, &sig_bit);
  187458. png_set_shift(png_ptr, sig_bit);
  187459. }
  187460. #endif
  187461. #if defined(PNG_READ_BGR_SUPPORTED)
  187462. /* flip the RGB pixels to BGR (or RGBA to BGRA)
  187463. */
  187464. if (transforms & PNG_TRANSFORM_BGR)
  187465. png_set_bgr(png_ptr);
  187466. #endif
  187467. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  187468. /* swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR)
  187469. */
  187470. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  187471. png_set_swap_alpha(png_ptr);
  187472. #endif
  187473. #if defined(PNG_READ_SWAP_SUPPORTED)
  187474. /* swap bytes of 16 bit files to least significant byte first
  187475. */
  187476. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  187477. png_set_swap(png_ptr);
  187478. #endif
  187479. /* We don't handle adding filler bytes */
  187480. /* Optional call to gamma correct and add the background to the palette
  187481. * and update info structure. REQUIRED if you are expecting libpng to
  187482. * update the palette for you (i.e., you selected such a transform above).
  187483. */
  187484. png_read_update_info(png_ptr, info_ptr);
  187485. /* -------------- image transformations end here ------------------- */
  187486. #ifdef PNG_FREE_ME_SUPPORTED
  187487. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  187488. #endif
  187489. if(info_ptr->row_pointers == NULL)
  187490. {
  187491. info_ptr->row_pointers = (png_bytepp)png_malloc(png_ptr,
  187492. info_ptr->height * png_sizeof(png_bytep));
  187493. #ifdef PNG_FREE_ME_SUPPORTED
  187494. info_ptr->free_me |= PNG_FREE_ROWS;
  187495. #endif
  187496. for (row = 0; row < (int)info_ptr->height; row++)
  187497. {
  187498. info_ptr->row_pointers[row] = (png_bytep)png_malloc(png_ptr,
  187499. png_get_rowbytes(png_ptr, info_ptr));
  187500. }
  187501. }
  187502. png_read_image(png_ptr, info_ptr->row_pointers);
  187503. info_ptr->valid |= PNG_INFO_IDAT;
  187504. /* read rest of file, and get additional chunks in info_ptr - REQUIRED */
  187505. png_read_end(png_ptr, info_ptr);
  187506. transforms = transforms; /* quiet compiler warnings */
  187507. params = params;
  187508. }
  187509. #endif /* PNG_INFO_IMAGE_SUPPORTED */
  187510. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187511. #endif /* PNG_READ_SUPPORTED */
  187512. /*** End of inlined file: pngread.c ***/
  187513. /*** Start of inlined file: pngpread.c ***/
  187514. /* pngpread.c - read a png file in push mode
  187515. *
  187516. * Last changed in libpng 1.2.21 October 4, 2007
  187517. * For conditions of distribution and use, see copyright notice in png.h
  187518. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  187519. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  187520. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  187521. */
  187522. #define PNG_INTERNAL
  187523. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  187524. /* push model modes */
  187525. #define PNG_READ_SIG_MODE 0
  187526. #define PNG_READ_CHUNK_MODE 1
  187527. #define PNG_READ_IDAT_MODE 2
  187528. #define PNG_SKIP_MODE 3
  187529. #define PNG_READ_tEXt_MODE 4
  187530. #define PNG_READ_zTXt_MODE 5
  187531. #define PNG_READ_DONE_MODE 6
  187532. #define PNG_READ_iTXt_MODE 7
  187533. #define PNG_ERROR_MODE 8
  187534. void PNGAPI
  187535. png_process_data(png_structp png_ptr, png_infop info_ptr,
  187536. png_bytep buffer, png_size_t buffer_size)
  187537. {
  187538. if(png_ptr == NULL) return;
  187539. png_push_restore_buffer(png_ptr, buffer, buffer_size);
  187540. while (png_ptr->buffer_size)
  187541. {
  187542. png_process_some_data(png_ptr, info_ptr);
  187543. }
  187544. }
  187545. /* What we do with the incoming data depends on what we were previously
  187546. * doing before we ran out of data...
  187547. */
  187548. void /* PRIVATE */
  187549. png_process_some_data(png_structp png_ptr, png_infop info_ptr)
  187550. {
  187551. if(png_ptr == NULL) return;
  187552. switch (png_ptr->process_mode)
  187553. {
  187554. case PNG_READ_SIG_MODE:
  187555. {
  187556. png_push_read_sig(png_ptr, info_ptr);
  187557. break;
  187558. }
  187559. case PNG_READ_CHUNK_MODE:
  187560. {
  187561. png_push_read_chunk(png_ptr, info_ptr);
  187562. break;
  187563. }
  187564. case PNG_READ_IDAT_MODE:
  187565. {
  187566. png_push_read_IDAT(png_ptr);
  187567. break;
  187568. }
  187569. #if defined(PNG_READ_tEXt_SUPPORTED)
  187570. case PNG_READ_tEXt_MODE:
  187571. {
  187572. png_push_read_tEXt(png_ptr, info_ptr);
  187573. break;
  187574. }
  187575. #endif
  187576. #if defined(PNG_READ_zTXt_SUPPORTED)
  187577. case PNG_READ_zTXt_MODE:
  187578. {
  187579. png_push_read_zTXt(png_ptr, info_ptr);
  187580. break;
  187581. }
  187582. #endif
  187583. #if defined(PNG_READ_iTXt_SUPPORTED)
  187584. case PNG_READ_iTXt_MODE:
  187585. {
  187586. png_push_read_iTXt(png_ptr, info_ptr);
  187587. break;
  187588. }
  187589. #endif
  187590. case PNG_SKIP_MODE:
  187591. {
  187592. png_push_crc_finish(png_ptr);
  187593. break;
  187594. }
  187595. default:
  187596. {
  187597. png_ptr->buffer_size = 0;
  187598. break;
  187599. }
  187600. }
  187601. }
  187602. /* Read any remaining signature bytes from the stream and compare them with
  187603. * the correct PNG signature. It is possible that this routine is called
  187604. * with bytes already read from the signature, either because they have been
  187605. * checked by the calling application, or because of multiple calls to this
  187606. * routine.
  187607. */
  187608. void /* PRIVATE */
  187609. png_push_read_sig(png_structp png_ptr, png_infop info_ptr)
  187610. {
  187611. png_size_t num_checked = png_ptr->sig_bytes,
  187612. num_to_check = 8 - num_checked;
  187613. if (png_ptr->buffer_size < num_to_check)
  187614. {
  187615. num_to_check = png_ptr->buffer_size;
  187616. }
  187617. png_push_fill_buffer(png_ptr, &(info_ptr->signature[num_checked]),
  187618. num_to_check);
  187619. png_ptr->sig_bytes = (png_byte)(png_ptr->sig_bytes+num_to_check);
  187620. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  187621. {
  187622. if (num_checked < 4 &&
  187623. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  187624. png_error(png_ptr, "Not a PNG file");
  187625. else
  187626. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  187627. }
  187628. else
  187629. {
  187630. if (png_ptr->sig_bytes >= 8)
  187631. {
  187632. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  187633. }
  187634. }
  187635. }
  187636. void /* PRIVATE */
  187637. png_push_read_chunk(png_structp png_ptr, png_infop info_ptr)
  187638. {
  187639. #ifdef PNG_USE_LOCAL_ARRAYS
  187640. PNG_CONST PNG_IHDR;
  187641. PNG_CONST PNG_IDAT;
  187642. PNG_CONST PNG_IEND;
  187643. PNG_CONST PNG_PLTE;
  187644. #if defined(PNG_READ_bKGD_SUPPORTED)
  187645. PNG_CONST PNG_bKGD;
  187646. #endif
  187647. #if defined(PNG_READ_cHRM_SUPPORTED)
  187648. PNG_CONST PNG_cHRM;
  187649. #endif
  187650. #if defined(PNG_READ_gAMA_SUPPORTED)
  187651. PNG_CONST PNG_gAMA;
  187652. #endif
  187653. #if defined(PNG_READ_hIST_SUPPORTED)
  187654. PNG_CONST PNG_hIST;
  187655. #endif
  187656. #if defined(PNG_READ_iCCP_SUPPORTED)
  187657. PNG_CONST PNG_iCCP;
  187658. #endif
  187659. #if defined(PNG_READ_iTXt_SUPPORTED)
  187660. PNG_CONST PNG_iTXt;
  187661. #endif
  187662. #if defined(PNG_READ_oFFs_SUPPORTED)
  187663. PNG_CONST PNG_oFFs;
  187664. #endif
  187665. #if defined(PNG_READ_pCAL_SUPPORTED)
  187666. PNG_CONST PNG_pCAL;
  187667. #endif
  187668. #if defined(PNG_READ_pHYs_SUPPORTED)
  187669. PNG_CONST PNG_pHYs;
  187670. #endif
  187671. #if defined(PNG_READ_sBIT_SUPPORTED)
  187672. PNG_CONST PNG_sBIT;
  187673. #endif
  187674. #if defined(PNG_READ_sCAL_SUPPORTED)
  187675. PNG_CONST PNG_sCAL;
  187676. #endif
  187677. #if defined(PNG_READ_sRGB_SUPPORTED)
  187678. PNG_CONST PNG_sRGB;
  187679. #endif
  187680. #if defined(PNG_READ_sPLT_SUPPORTED)
  187681. PNG_CONST PNG_sPLT;
  187682. #endif
  187683. #if defined(PNG_READ_tEXt_SUPPORTED)
  187684. PNG_CONST PNG_tEXt;
  187685. #endif
  187686. #if defined(PNG_READ_tIME_SUPPORTED)
  187687. PNG_CONST PNG_tIME;
  187688. #endif
  187689. #if defined(PNG_READ_tRNS_SUPPORTED)
  187690. PNG_CONST PNG_tRNS;
  187691. #endif
  187692. #if defined(PNG_READ_zTXt_SUPPORTED)
  187693. PNG_CONST PNG_zTXt;
  187694. #endif
  187695. #endif /* PNG_USE_LOCAL_ARRAYS */
  187696. /* First we make sure we have enough data for the 4 byte chunk name
  187697. * and the 4 byte chunk length before proceeding with decoding the
  187698. * chunk data. To fully decode each of these chunks, we also make
  187699. * sure we have enough data in the buffer for the 4 byte CRC at the
  187700. * end of every chunk (except IDAT, which is handled separately).
  187701. */
  187702. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  187703. {
  187704. png_byte chunk_length[4];
  187705. if (png_ptr->buffer_size < 8)
  187706. {
  187707. png_push_save_buffer(png_ptr);
  187708. return;
  187709. }
  187710. png_push_fill_buffer(png_ptr, chunk_length, 4);
  187711. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  187712. png_reset_crc(png_ptr);
  187713. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187714. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  187715. }
  187716. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187717. if(png_ptr->mode & PNG_AFTER_IDAT)
  187718. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  187719. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  187720. {
  187721. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187722. {
  187723. png_push_save_buffer(png_ptr);
  187724. return;
  187725. }
  187726. png_handle_IHDR(png_ptr, info_ptr, png_ptr->push_length);
  187727. }
  187728. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  187729. {
  187730. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187731. {
  187732. png_push_save_buffer(png_ptr);
  187733. return;
  187734. }
  187735. png_handle_IEND(png_ptr, info_ptr, png_ptr->push_length);
  187736. png_ptr->process_mode = PNG_READ_DONE_MODE;
  187737. png_push_have_end(png_ptr, info_ptr);
  187738. }
  187739. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  187740. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  187741. {
  187742. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187743. {
  187744. png_push_save_buffer(png_ptr);
  187745. return;
  187746. }
  187747. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187748. png_ptr->mode |= PNG_HAVE_IDAT;
  187749. png_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  187750. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187751. png_ptr->mode |= PNG_HAVE_PLTE;
  187752. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187753. {
  187754. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187755. png_error(png_ptr, "Missing IHDR before IDAT");
  187756. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  187757. !(png_ptr->mode & PNG_HAVE_PLTE))
  187758. png_error(png_ptr, "Missing PLTE before IDAT");
  187759. }
  187760. }
  187761. #endif
  187762. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187763. {
  187764. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187765. {
  187766. png_push_save_buffer(png_ptr);
  187767. return;
  187768. }
  187769. png_handle_PLTE(png_ptr, info_ptr, png_ptr->push_length);
  187770. }
  187771. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187772. {
  187773. /* If we reach an IDAT chunk, this means we have read all of the
  187774. * header chunks, and we can start reading the image (or if this
  187775. * is called after the image has been read - we have an error).
  187776. */
  187777. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187778. png_error(png_ptr, "Missing IHDR before IDAT");
  187779. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  187780. !(png_ptr->mode & PNG_HAVE_PLTE))
  187781. png_error(png_ptr, "Missing PLTE before IDAT");
  187782. if (png_ptr->mode & PNG_HAVE_IDAT)
  187783. {
  187784. if (!(png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  187785. if (png_ptr->push_length == 0)
  187786. return;
  187787. if (png_ptr->mode & PNG_AFTER_IDAT)
  187788. png_error(png_ptr, "Too many IDAT's found");
  187789. }
  187790. png_ptr->idat_size = png_ptr->push_length;
  187791. png_ptr->mode |= PNG_HAVE_IDAT;
  187792. png_ptr->process_mode = PNG_READ_IDAT_MODE;
  187793. png_push_have_info(png_ptr, info_ptr);
  187794. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  187795. png_ptr->zstream.next_out = png_ptr->row_buf;
  187796. return;
  187797. }
  187798. #if defined(PNG_READ_gAMA_SUPPORTED)
  187799. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  187800. {
  187801. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187802. {
  187803. png_push_save_buffer(png_ptr);
  187804. return;
  187805. }
  187806. png_handle_gAMA(png_ptr, info_ptr, png_ptr->push_length);
  187807. }
  187808. #endif
  187809. #if defined(PNG_READ_sBIT_SUPPORTED)
  187810. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  187811. {
  187812. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187813. {
  187814. png_push_save_buffer(png_ptr);
  187815. return;
  187816. }
  187817. png_handle_sBIT(png_ptr, info_ptr, png_ptr->push_length);
  187818. }
  187819. #endif
  187820. #if defined(PNG_READ_cHRM_SUPPORTED)
  187821. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  187822. {
  187823. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187824. {
  187825. png_push_save_buffer(png_ptr);
  187826. return;
  187827. }
  187828. png_handle_cHRM(png_ptr, info_ptr, png_ptr->push_length);
  187829. }
  187830. #endif
  187831. #if defined(PNG_READ_sRGB_SUPPORTED)
  187832. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  187833. {
  187834. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187835. {
  187836. png_push_save_buffer(png_ptr);
  187837. return;
  187838. }
  187839. png_handle_sRGB(png_ptr, info_ptr, png_ptr->push_length);
  187840. }
  187841. #endif
  187842. #if defined(PNG_READ_iCCP_SUPPORTED)
  187843. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  187844. {
  187845. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187846. {
  187847. png_push_save_buffer(png_ptr);
  187848. return;
  187849. }
  187850. png_handle_iCCP(png_ptr, info_ptr, png_ptr->push_length);
  187851. }
  187852. #endif
  187853. #if defined(PNG_READ_sPLT_SUPPORTED)
  187854. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  187855. {
  187856. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187857. {
  187858. png_push_save_buffer(png_ptr);
  187859. return;
  187860. }
  187861. png_handle_sPLT(png_ptr, info_ptr, png_ptr->push_length);
  187862. }
  187863. #endif
  187864. #if defined(PNG_READ_tRNS_SUPPORTED)
  187865. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  187866. {
  187867. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187868. {
  187869. png_push_save_buffer(png_ptr);
  187870. return;
  187871. }
  187872. png_handle_tRNS(png_ptr, info_ptr, png_ptr->push_length);
  187873. }
  187874. #endif
  187875. #if defined(PNG_READ_bKGD_SUPPORTED)
  187876. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  187877. {
  187878. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187879. {
  187880. png_push_save_buffer(png_ptr);
  187881. return;
  187882. }
  187883. png_handle_bKGD(png_ptr, info_ptr, png_ptr->push_length);
  187884. }
  187885. #endif
  187886. #if defined(PNG_READ_hIST_SUPPORTED)
  187887. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  187888. {
  187889. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187890. {
  187891. png_push_save_buffer(png_ptr);
  187892. return;
  187893. }
  187894. png_handle_hIST(png_ptr, info_ptr, png_ptr->push_length);
  187895. }
  187896. #endif
  187897. #if defined(PNG_READ_pHYs_SUPPORTED)
  187898. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  187899. {
  187900. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187901. {
  187902. png_push_save_buffer(png_ptr);
  187903. return;
  187904. }
  187905. png_handle_pHYs(png_ptr, info_ptr, png_ptr->push_length);
  187906. }
  187907. #endif
  187908. #if defined(PNG_READ_oFFs_SUPPORTED)
  187909. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  187910. {
  187911. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187912. {
  187913. png_push_save_buffer(png_ptr);
  187914. return;
  187915. }
  187916. png_handle_oFFs(png_ptr, info_ptr, png_ptr->push_length);
  187917. }
  187918. #endif
  187919. #if defined(PNG_READ_pCAL_SUPPORTED)
  187920. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  187921. {
  187922. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187923. {
  187924. png_push_save_buffer(png_ptr);
  187925. return;
  187926. }
  187927. png_handle_pCAL(png_ptr, info_ptr, png_ptr->push_length);
  187928. }
  187929. #endif
  187930. #if defined(PNG_READ_sCAL_SUPPORTED)
  187931. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  187932. {
  187933. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187934. {
  187935. png_push_save_buffer(png_ptr);
  187936. return;
  187937. }
  187938. png_handle_sCAL(png_ptr, info_ptr, png_ptr->push_length);
  187939. }
  187940. #endif
  187941. #if defined(PNG_READ_tIME_SUPPORTED)
  187942. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  187943. {
  187944. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187945. {
  187946. png_push_save_buffer(png_ptr);
  187947. return;
  187948. }
  187949. png_handle_tIME(png_ptr, info_ptr, png_ptr->push_length);
  187950. }
  187951. #endif
  187952. #if defined(PNG_READ_tEXt_SUPPORTED)
  187953. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  187954. {
  187955. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187956. {
  187957. png_push_save_buffer(png_ptr);
  187958. return;
  187959. }
  187960. png_push_handle_tEXt(png_ptr, info_ptr, png_ptr->push_length);
  187961. }
  187962. #endif
  187963. #if defined(PNG_READ_zTXt_SUPPORTED)
  187964. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  187965. {
  187966. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187967. {
  187968. png_push_save_buffer(png_ptr);
  187969. return;
  187970. }
  187971. png_push_handle_zTXt(png_ptr, info_ptr, png_ptr->push_length);
  187972. }
  187973. #endif
  187974. #if defined(PNG_READ_iTXt_SUPPORTED)
  187975. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  187976. {
  187977. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187978. {
  187979. png_push_save_buffer(png_ptr);
  187980. return;
  187981. }
  187982. png_push_handle_iTXt(png_ptr, info_ptr, png_ptr->push_length);
  187983. }
  187984. #endif
  187985. else
  187986. {
  187987. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187988. {
  187989. png_push_save_buffer(png_ptr);
  187990. return;
  187991. }
  187992. png_push_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  187993. }
  187994. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  187995. }
  187996. void /* PRIVATE */
  187997. png_push_crc_skip(png_structp png_ptr, png_uint_32 skip)
  187998. {
  187999. png_ptr->process_mode = PNG_SKIP_MODE;
  188000. png_ptr->skip_length = skip;
  188001. }
  188002. void /* PRIVATE */
  188003. png_push_crc_finish(png_structp png_ptr)
  188004. {
  188005. if (png_ptr->skip_length && png_ptr->save_buffer_size)
  188006. {
  188007. png_size_t save_size;
  188008. if (png_ptr->skip_length < (png_uint_32)png_ptr->save_buffer_size)
  188009. save_size = (png_size_t)png_ptr->skip_length;
  188010. else
  188011. save_size = png_ptr->save_buffer_size;
  188012. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  188013. png_ptr->skip_length -= save_size;
  188014. png_ptr->buffer_size -= save_size;
  188015. png_ptr->save_buffer_size -= save_size;
  188016. png_ptr->save_buffer_ptr += save_size;
  188017. }
  188018. if (png_ptr->skip_length && png_ptr->current_buffer_size)
  188019. {
  188020. png_size_t save_size;
  188021. if (png_ptr->skip_length < (png_uint_32)png_ptr->current_buffer_size)
  188022. save_size = (png_size_t)png_ptr->skip_length;
  188023. else
  188024. save_size = png_ptr->current_buffer_size;
  188025. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  188026. png_ptr->skip_length -= save_size;
  188027. png_ptr->buffer_size -= save_size;
  188028. png_ptr->current_buffer_size -= save_size;
  188029. png_ptr->current_buffer_ptr += save_size;
  188030. }
  188031. if (!png_ptr->skip_length)
  188032. {
  188033. if (png_ptr->buffer_size < 4)
  188034. {
  188035. png_push_save_buffer(png_ptr);
  188036. return;
  188037. }
  188038. png_crc_finish(png_ptr, 0);
  188039. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188040. }
  188041. }
  188042. void PNGAPI
  188043. png_push_fill_buffer(png_structp png_ptr, png_bytep buffer, png_size_t length)
  188044. {
  188045. png_bytep ptr;
  188046. if(png_ptr == NULL) return;
  188047. ptr = buffer;
  188048. if (png_ptr->save_buffer_size)
  188049. {
  188050. png_size_t save_size;
  188051. if (length < png_ptr->save_buffer_size)
  188052. save_size = length;
  188053. else
  188054. save_size = png_ptr->save_buffer_size;
  188055. png_memcpy(ptr, png_ptr->save_buffer_ptr, save_size);
  188056. length -= save_size;
  188057. ptr += save_size;
  188058. png_ptr->buffer_size -= save_size;
  188059. png_ptr->save_buffer_size -= save_size;
  188060. png_ptr->save_buffer_ptr += save_size;
  188061. }
  188062. if (length && png_ptr->current_buffer_size)
  188063. {
  188064. png_size_t save_size;
  188065. if (length < png_ptr->current_buffer_size)
  188066. save_size = length;
  188067. else
  188068. save_size = png_ptr->current_buffer_size;
  188069. png_memcpy(ptr, png_ptr->current_buffer_ptr, save_size);
  188070. png_ptr->buffer_size -= save_size;
  188071. png_ptr->current_buffer_size -= save_size;
  188072. png_ptr->current_buffer_ptr += save_size;
  188073. }
  188074. }
  188075. void /* PRIVATE */
  188076. png_push_save_buffer(png_structp png_ptr)
  188077. {
  188078. if (png_ptr->save_buffer_size)
  188079. {
  188080. if (png_ptr->save_buffer_ptr != png_ptr->save_buffer)
  188081. {
  188082. png_size_t i,istop;
  188083. png_bytep sp;
  188084. png_bytep dp;
  188085. istop = png_ptr->save_buffer_size;
  188086. for (i = 0, sp = png_ptr->save_buffer_ptr, dp = png_ptr->save_buffer;
  188087. i < istop; i++, sp++, dp++)
  188088. {
  188089. *dp = *sp;
  188090. }
  188091. }
  188092. }
  188093. if (png_ptr->save_buffer_size + png_ptr->current_buffer_size >
  188094. png_ptr->save_buffer_max)
  188095. {
  188096. png_size_t new_max;
  188097. png_bytep old_buffer;
  188098. if (png_ptr->save_buffer_size > PNG_SIZE_MAX -
  188099. (png_ptr->current_buffer_size + 256))
  188100. {
  188101. png_error(png_ptr, "Potential overflow of save_buffer");
  188102. }
  188103. new_max = png_ptr->save_buffer_size + png_ptr->current_buffer_size + 256;
  188104. old_buffer = png_ptr->save_buffer;
  188105. png_ptr->save_buffer = (png_bytep)png_malloc(png_ptr,
  188106. (png_uint_32)new_max);
  188107. png_memcpy(png_ptr->save_buffer, old_buffer, png_ptr->save_buffer_size);
  188108. png_free(png_ptr, old_buffer);
  188109. png_ptr->save_buffer_max = new_max;
  188110. }
  188111. if (png_ptr->current_buffer_size)
  188112. {
  188113. png_memcpy(png_ptr->save_buffer + png_ptr->save_buffer_size,
  188114. png_ptr->current_buffer_ptr, png_ptr->current_buffer_size);
  188115. png_ptr->save_buffer_size += png_ptr->current_buffer_size;
  188116. png_ptr->current_buffer_size = 0;
  188117. }
  188118. png_ptr->save_buffer_ptr = png_ptr->save_buffer;
  188119. png_ptr->buffer_size = 0;
  188120. }
  188121. void /* PRIVATE */
  188122. png_push_restore_buffer(png_structp png_ptr, png_bytep buffer,
  188123. png_size_t buffer_length)
  188124. {
  188125. png_ptr->current_buffer = buffer;
  188126. png_ptr->current_buffer_size = buffer_length;
  188127. png_ptr->buffer_size = buffer_length + png_ptr->save_buffer_size;
  188128. png_ptr->current_buffer_ptr = png_ptr->current_buffer;
  188129. }
  188130. void /* PRIVATE */
  188131. png_push_read_IDAT(png_structp png_ptr)
  188132. {
  188133. #ifdef PNG_USE_LOCAL_ARRAYS
  188134. PNG_CONST PNG_IDAT;
  188135. #endif
  188136. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  188137. {
  188138. png_byte chunk_length[4];
  188139. if (png_ptr->buffer_size < 8)
  188140. {
  188141. png_push_save_buffer(png_ptr);
  188142. return;
  188143. }
  188144. png_push_fill_buffer(png_ptr, chunk_length, 4);
  188145. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  188146. png_reset_crc(png_ptr);
  188147. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  188148. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  188149. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188150. {
  188151. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188152. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  188153. png_error(png_ptr, "Not enough compressed data");
  188154. return;
  188155. }
  188156. png_ptr->idat_size = png_ptr->push_length;
  188157. }
  188158. if (png_ptr->idat_size && png_ptr->save_buffer_size)
  188159. {
  188160. png_size_t save_size;
  188161. if (png_ptr->idat_size < (png_uint_32)png_ptr->save_buffer_size)
  188162. {
  188163. save_size = (png_size_t)png_ptr->idat_size;
  188164. /* check for overflow */
  188165. if((png_uint_32)save_size != png_ptr->idat_size)
  188166. png_error(png_ptr, "save_size overflowed in pngpread");
  188167. }
  188168. else
  188169. save_size = png_ptr->save_buffer_size;
  188170. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  188171. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  188172. png_process_IDAT_data(png_ptr, png_ptr->save_buffer_ptr, save_size);
  188173. png_ptr->idat_size -= save_size;
  188174. png_ptr->buffer_size -= save_size;
  188175. png_ptr->save_buffer_size -= save_size;
  188176. png_ptr->save_buffer_ptr += save_size;
  188177. }
  188178. if (png_ptr->idat_size && png_ptr->current_buffer_size)
  188179. {
  188180. png_size_t save_size;
  188181. if (png_ptr->idat_size < (png_uint_32)png_ptr->current_buffer_size)
  188182. {
  188183. save_size = (png_size_t)png_ptr->idat_size;
  188184. /* check for overflow */
  188185. if((png_uint_32)save_size != png_ptr->idat_size)
  188186. png_error(png_ptr, "save_size overflowed in pngpread");
  188187. }
  188188. else
  188189. save_size = png_ptr->current_buffer_size;
  188190. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  188191. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  188192. png_process_IDAT_data(png_ptr, png_ptr->current_buffer_ptr, save_size);
  188193. png_ptr->idat_size -= save_size;
  188194. png_ptr->buffer_size -= save_size;
  188195. png_ptr->current_buffer_size -= save_size;
  188196. png_ptr->current_buffer_ptr += save_size;
  188197. }
  188198. if (!png_ptr->idat_size)
  188199. {
  188200. if (png_ptr->buffer_size < 4)
  188201. {
  188202. png_push_save_buffer(png_ptr);
  188203. return;
  188204. }
  188205. png_crc_finish(png_ptr, 0);
  188206. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  188207. png_ptr->mode |= PNG_AFTER_IDAT;
  188208. }
  188209. }
  188210. void /* PRIVATE */
  188211. png_process_IDAT_data(png_structp png_ptr, png_bytep buffer,
  188212. png_size_t buffer_length)
  188213. {
  188214. int ret;
  188215. if ((png_ptr->flags & PNG_FLAG_ZLIB_FINISHED) && buffer_length)
  188216. png_error(png_ptr, "Extra compression data");
  188217. png_ptr->zstream.next_in = buffer;
  188218. png_ptr->zstream.avail_in = (uInt)buffer_length;
  188219. for(;;)
  188220. {
  188221. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  188222. if (ret != Z_OK)
  188223. {
  188224. if (ret == Z_STREAM_END)
  188225. {
  188226. if (png_ptr->zstream.avail_in)
  188227. png_error(png_ptr, "Extra compressed data");
  188228. if (!(png_ptr->zstream.avail_out))
  188229. {
  188230. png_push_process_row(png_ptr);
  188231. }
  188232. png_ptr->mode |= PNG_AFTER_IDAT;
  188233. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  188234. break;
  188235. }
  188236. else if (ret == Z_BUF_ERROR)
  188237. break;
  188238. else
  188239. png_error(png_ptr, "Decompression Error");
  188240. }
  188241. if (!(png_ptr->zstream.avail_out))
  188242. {
  188243. if ((
  188244. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  188245. png_ptr->interlaced && png_ptr->pass > 6) ||
  188246. (!png_ptr->interlaced &&
  188247. #endif
  188248. png_ptr->row_number == png_ptr->num_rows))
  188249. {
  188250. if (png_ptr->zstream.avail_in)
  188251. {
  188252. png_warning(png_ptr, "Too much data in IDAT chunks");
  188253. }
  188254. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  188255. break;
  188256. }
  188257. png_push_process_row(png_ptr);
  188258. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  188259. png_ptr->zstream.next_out = png_ptr->row_buf;
  188260. }
  188261. else
  188262. break;
  188263. }
  188264. }
  188265. void /* PRIVATE */
  188266. png_push_process_row(png_structp png_ptr)
  188267. {
  188268. png_ptr->row_info.color_type = png_ptr->color_type;
  188269. png_ptr->row_info.width = png_ptr->iwidth;
  188270. png_ptr->row_info.channels = png_ptr->channels;
  188271. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  188272. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  188273. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  188274. png_ptr->row_info.width);
  188275. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  188276. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  188277. (int)(png_ptr->row_buf[0]));
  188278. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  188279. png_ptr->rowbytes + 1);
  188280. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  188281. png_do_read_transformations(png_ptr);
  188282. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  188283. /* blow up interlaced rows to full size */
  188284. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  188285. {
  188286. if (png_ptr->pass < 6)
  188287. /* old interface (pre-1.0.9):
  188288. png_do_read_interlace(&(png_ptr->row_info),
  188289. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  188290. */
  188291. png_do_read_interlace(png_ptr);
  188292. switch (png_ptr->pass)
  188293. {
  188294. case 0:
  188295. {
  188296. int i;
  188297. for (i = 0; i < 8 && png_ptr->pass == 0; i++)
  188298. {
  188299. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188300. png_read_push_finish_row(png_ptr); /* updates png_ptr->pass */
  188301. }
  188302. if (png_ptr->pass == 2) /* pass 1 might be empty */
  188303. {
  188304. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  188305. {
  188306. png_push_have_row(png_ptr, png_bytep_NULL);
  188307. png_read_push_finish_row(png_ptr);
  188308. }
  188309. }
  188310. if (png_ptr->pass == 4 && png_ptr->height <= 4)
  188311. {
  188312. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188313. {
  188314. png_push_have_row(png_ptr, png_bytep_NULL);
  188315. png_read_push_finish_row(png_ptr);
  188316. }
  188317. }
  188318. if (png_ptr->pass == 6 && png_ptr->height <= 4)
  188319. {
  188320. png_push_have_row(png_ptr, png_bytep_NULL);
  188321. png_read_push_finish_row(png_ptr);
  188322. }
  188323. break;
  188324. }
  188325. case 1:
  188326. {
  188327. int i;
  188328. for (i = 0; i < 8 && png_ptr->pass == 1; i++)
  188329. {
  188330. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188331. png_read_push_finish_row(png_ptr);
  188332. }
  188333. if (png_ptr->pass == 2) /* skip top 4 generated rows */
  188334. {
  188335. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  188336. {
  188337. png_push_have_row(png_ptr, png_bytep_NULL);
  188338. png_read_push_finish_row(png_ptr);
  188339. }
  188340. }
  188341. break;
  188342. }
  188343. case 2:
  188344. {
  188345. int i;
  188346. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  188347. {
  188348. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188349. png_read_push_finish_row(png_ptr);
  188350. }
  188351. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  188352. {
  188353. png_push_have_row(png_ptr, png_bytep_NULL);
  188354. png_read_push_finish_row(png_ptr);
  188355. }
  188356. if (png_ptr->pass == 4) /* pass 3 might be empty */
  188357. {
  188358. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188359. {
  188360. png_push_have_row(png_ptr, png_bytep_NULL);
  188361. png_read_push_finish_row(png_ptr);
  188362. }
  188363. }
  188364. break;
  188365. }
  188366. case 3:
  188367. {
  188368. int i;
  188369. for (i = 0; i < 4 && png_ptr->pass == 3; i++)
  188370. {
  188371. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188372. png_read_push_finish_row(png_ptr);
  188373. }
  188374. if (png_ptr->pass == 4) /* skip top two generated rows */
  188375. {
  188376. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188377. {
  188378. png_push_have_row(png_ptr, png_bytep_NULL);
  188379. png_read_push_finish_row(png_ptr);
  188380. }
  188381. }
  188382. break;
  188383. }
  188384. case 4:
  188385. {
  188386. int i;
  188387. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188388. {
  188389. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188390. png_read_push_finish_row(png_ptr);
  188391. }
  188392. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188393. {
  188394. png_push_have_row(png_ptr, png_bytep_NULL);
  188395. png_read_push_finish_row(png_ptr);
  188396. }
  188397. if (png_ptr->pass == 6) /* pass 5 might be empty */
  188398. {
  188399. png_push_have_row(png_ptr, png_bytep_NULL);
  188400. png_read_push_finish_row(png_ptr);
  188401. }
  188402. break;
  188403. }
  188404. case 5:
  188405. {
  188406. int i;
  188407. for (i = 0; i < 2 && png_ptr->pass == 5; i++)
  188408. {
  188409. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188410. png_read_push_finish_row(png_ptr);
  188411. }
  188412. if (png_ptr->pass == 6) /* skip top generated row */
  188413. {
  188414. png_push_have_row(png_ptr, png_bytep_NULL);
  188415. png_read_push_finish_row(png_ptr);
  188416. }
  188417. break;
  188418. }
  188419. case 6:
  188420. {
  188421. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188422. png_read_push_finish_row(png_ptr);
  188423. if (png_ptr->pass != 6)
  188424. break;
  188425. png_push_have_row(png_ptr, png_bytep_NULL);
  188426. png_read_push_finish_row(png_ptr);
  188427. }
  188428. }
  188429. }
  188430. else
  188431. #endif
  188432. {
  188433. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188434. png_read_push_finish_row(png_ptr);
  188435. }
  188436. }
  188437. void /* PRIVATE */
  188438. png_read_push_finish_row(png_structp png_ptr)
  188439. {
  188440. #ifdef PNG_USE_LOCAL_ARRAYS
  188441. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  188442. /* start of interlace block */
  188443. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  188444. /* offset to next interlace block */
  188445. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  188446. /* start of interlace block in the y direction */
  188447. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  188448. /* offset to next interlace block in the y direction */
  188449. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  188450. /* Height of interlace block. This is not currently used - if you need
  188451. * it, uncomment it here and in png.h
  188452. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  188453. */
  188454. #endif
  188455. png_ptr->row_number++;
  188456. if (png_ptr->row_number < png_ptr->num_rows)
  188457. return;
  188458. if (png_ptr->interlaced)
  188459. {
  188460. png_ptr->row_number = 0;
  188461. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  188462. png_ptr->rowbytes + 1);
  188463. do
  188464. {
  188465. png_ptr->pass++;
  188466. if ((png_ptr->pass == 1 && png_ptr->width < 5) ||
  188467. (png_ptr->pass == 3 && png_ptr->width < 3) ||
  188468. (png_ptr->pass == 5 && png_ptr->width < 2))
  188469. png_ptr->pass++;
  188470. if (png_ptr->pass > 7)
  188471. png_ptr->pass--;
  188472. if (png_ptr->pass >= 7)
  188473. break;
  188474. png_ptr->iwidth = (png_ptr->width +
  188475. png_pass_inc[png_ptr->pass] - 1 -
  188476. png_pass_start[png_ptr->pass]) /
  188477. png_pass_inc[png_ptr->pass];
  188478. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  188479. png_ptr->iwidth) + 1;
  188480. if (png_ptr->transformations & PNG_INTERLACE)
  188481. break;
  188482. png_ptr->num_rows = (png_ptr->height +
  188483. png_pass_yinc[png_ptr->pass] - 1 -
  188484. png_pass_ystart[png_ptr->pass]) /
  188485. png_pass_yinc[png_ptr->pass];
  188486. } while (png_ptr->iwidth == 0 || png_ptr->num_rows == 0);
  188487. }
  188488. }
  188489. #if defined(PNG_READ_tEXt_SUPPORTED)
  188490. void /* PRIVATE */
  188491. png_push_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  188492. length)
  188493. {
  188494. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  188495. {
  188496. png_error(png_ptr, "Out of place tEXt");
  188497. info_ptr = info_ptr; /* to quiet some compiler warnings */
  188498. }
  188499. #ifdef PNG_MAX_MALLOC_64K
  188500. png_ptr->skip_length = 0; /* This may not be necessary */
  188501. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  188502. {
  188503. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  188504. png_ptr->skip_length = length - (png_uint_32)65535L;
  188505. length = (png_uint_32)65535L;
  188506. }
  188507. #endif
  188508. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  188509. (png_uint_32)(length+1));
  188510. png_ptr->current_text[length] = '\0';
  188511. png_ptr->current_text_ptr = png_ptr->current_text;
  188512. png_ptr->current_text_size = (png_size_t)length;
  188513. png_ptr->current_text_left = (png_size_t)length;
  188514. png_ptr->process_mode = PNG_READ_tEXt_MODE;
  188515. }
  188516. void /* PRIVATE */
  188517. png_push_read_tEXt(png_structp png_ptr, png_infop info_ptr)
  188518. {
  188519. if (png_ptr->buffer_size && png_ptr->current_text_left)
  188520. {
  188521. png_size_t text_size;
  188522. if (png_ptr->buffer_size < png_ptr->current_text_left)
  188523. text_size = png_ptr->buffer_size;
  188524. else
  188525. text_size = png_ptr->current_text_left;
  188526. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  188527. png_ptr->current_text_left -= text_size;
  188528. png_ptr->current_text_ptr += text_size;
  188529. }
  188530. if (!(png_ptr->current_text_left))
  188531. {
  188532. png_textp text_ptr;
  188533. png_charp text;
  188534. png_charp key;
  188535. int ret;
  188536. if (png_ptr->buffer_size < 4)
  188537. {
  188538. png_push_save_buffer(png_ptr);
  188539. return;
  188540. }
  188541. png_push_crc_finish(png_ptr);
  188542. #if defined(PNG_MAX_MALLOC_64K)
  188543. if (png_ptr->skip_length)
  188544. return;
  188545. #endif
  188546. key = png_ptr->current_text;
  188547. for (text = key; *text; text++)
  188548. /* empty loop */ ;
  188549. if (text < key + png_ptr->current_text_size)
  188550. text++;
  188551. text_ptr = (png_textp)png_malloc(png_ptr,
  188552. (png_uint_32)png_sizeof(png_text));
  188553. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  188554. text_ptr->key = key;
  188555. #ifdef PNG_iTXt_SUPPORTED
  188556. text_ptr->lang = NULL;
  188557. text_ptr->lang_key = NULL;
  188558. #endif
  188559. text_ptr->text = text;
  188560. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  188561. png_free(png_ptr, key);
  188562. png_free(png_ptr, text_ptr);
  188563. png_ptr->current_text = NULL;
  188564. if (ret)
  188565. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  188566. }
  188567. }
  188568. #endif
  188569. #if defined(PNG_READ_zTXt_SUPPORTED)
  188570. void /* PRIVATE */
  188571. png_push_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  188572. length)
  188573. {
  188574. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  188575. {
  188576. png_error(png_ptr, "Out of place zTXt");
  188577. info_ptr = info_ptr; /* to quiet some compiler warnings */
  188578. }
  188579. #ifdef PNG_MAX_MALLOC_64K
  188580. /* We can't handle zTXt chunks > 64K, since we don't have enough space
  188581. * to be able to store the uncompressed data. Actually, the threshold
  188582. * is probably around 32K, but it isn't as definite as 64K is.
  188583. */
  188584. if (length > (png_uint_32)65535L)
  188585. {
  188586. png_warning(png_ptr, "zTXt chunk too large to fit in memory");
  188587. png_push_crc_skip(png_ptr, length);
  188588. return;
  188589. }
  188590. #endif
  188591. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  188592. (png_uint_32)(length+1));
  188593. png_ptr->current_text[length] = '\0';
  188594. png_ptr->current_text_ptr = png_ptr->current_text;
  188595. png_ptr->current_text_size = (png_size_t)length;
  188596. png_ptr->current_text_left = (png_size_t)length;
  188597. png_ptr->process_mode = PNG_READ_zTXt_MODE;
  188598. }
  188599. void /* PRIVATE */
  188600. png_push_read_zTXt(png_structp png_ptr, png_infop info_ptr)
  188601. {
  188602. if (png_ptr->buffer_size && png_ptr->current_text_left)
  188603. {
  188604. png_size_t text_size;
  188605. if (png_ptr->buffer_size < (png_uint_32)png_ptr->current_text_left)
  188606. text_size = png_ptr->buffer_size;
  188607. else
  188608. text_size = png_ptr->current_text_left;
  188609. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  188610. png_ptr->current_text_left -= text_size;
  188611. png_ptr->current_text_ptr += text_size;
  188612. }
  188613. if (!(png_ptr->current_text_left))
  188614. {
  188615. png_textp text_ptr;
  188616. png_charp text;
  188617. png_charp key;
  188618. int ret;
  188619. png_size_t text_size, key_size;
  188620. if (png_ptr->buffer_size < 4)
  188621. {
  188622. png_push_save_buffer(png_ptr);
  188623. return;
  188624. }
  188625. png_push_crc_finish(png_ptr);
  188626. key = png_ptr->current_text;
  188627. for (text = key; *text; text++)
  188628. /* empty loop */ ;
  188629. /* zTXt can't have zero text */
  188630. if (text >= key + png_ptr->current_text_size)
  188631. {
  188632. png_ptr->current_text = NULL;
  188633. png_free(png_ptr, key);
  188634. return;
  188635. }
  188636. text++;
  188637. if (*text != PNG_TEXT_COMPRESSION_zTXt) /* check compression byte */
  188638. {
  188639. png_ptr->current_text = NULL;
  188640. png_free(png_ptr, key);
  188641. return;
  188642. }
  188643. text++;
  188644. png_ptr->zstream.next_in = (png_bytep )text;
  188645. png_ptr->zstream.avail_in = (uInt)(png_ptr->current_text_size -
  188646. (text - key));
  188647. png_ptr->zstream.next_out = png_ptr->zbuf;
  188648. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  188649. key_size = text - key;
  188650. text_size = 0;
  188651. text = NULL;
  188652. ret = Z_STREAM_END;
  188653. while (png_ptr->zstream.avail_in)
  188654. {
  188655. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  188656. if (ret != Z_OK && ret != Z_STREAM_END)
  188657. {
  188658. inflateReset(&png_ptr->zstream);
  188659. png_ptr->zstream.avail_in = 0;
  188660. png_ptr->current_text = NULL;
  188661. png_free(png_ptr, key);
  188662. png_free(png_ptr, text);
  188663. return;
  188664. }
  188665. if (!(png_ptr->zstream.avail_out) || ret == Z_STREAM_END)
  188666. {
  188667. if (text == NULL)
  188668. {
  188669. text = (png_charp)png_malloc(png_ptr,
  188670. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  188671. + key_size + 1));
  188672. png_memcpy(text + key_size, png_ptr->zbuf,
  188673. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  188674. png_memcpy(text, key, key_size);
  188675. text_size = key_size + png_ptr->zbuf_size -
  188676. png_ptr->zstream.avail_out;
  188677. *(text + text_size) = '\0';
  188678. }
  188679. else
  188680. {
  188681. png_charp tmp;
  188682. tmp = text;
  188683. text = (png_charp)png_malloc(png_ptr, text_size +
  188684. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  188685. + 1));
  188686. png_memcpy(text, tmp, text_size);
  188687. png_free(png_ptr, tmp);
  188688. png_memcpy(text + text_size, png_ptr->zbuf,
  188689. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  188690. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  188691. *(text + text_size) = '\0';
  188692. }
  188693. if (ret != Z_STREAM_END)
  188694. {
  188695. png_ptr->zstream.next_out = png_ptr->zbuf;
  188696. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  188697. }
  188698. }
  188699. else
  188700. {
  188701. break;
  188702. }
  188703. if (ret == Z_STREAM_END)
  188704. break;
  188705. }
  188706. inflateReset(&png_ptr->zstream);
  188707. png_ptr->zstream.avail_in = 0;
  188708. if (ret != Z_STREAM_END)
  188709. {
  188710. png_ptr->current_text = NULL;
  188711. png_free(png_ptr, key);
  188712. png_free(png_ptr, text);
  188713. return;
  188714. }
  188715. png_ptr->current_text = NULL;
  188716. png_free(png_ptr, key);
  188717. key = text;
  188718. text += key_size;
  188719. text_ptr = (png_textp)png_malloc(png_ptr,
  188720. (png_uint_32)png_sizeof(png_text));
  188721. text_ptr->compression = PNG_TEXT_COMPRESSION_zTXt;
  188722. text_ptr->key = key;
  188723. #ifdef PNG_iTXt_SUPPORTED
  188724. text_ptr->lang = NULL;
  188725. text_ptr->lang_key = NULL;
  188726. #endif
  188727. text_ptr->text = text;
  188728. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  188729. png_free(png_ptr, key);
  188730. png_free(png_ptr, text_ptr);
  188731. if (ret)
  188732. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  188733. }
  188734. }
  188735. #endif
  188736. #if defined(PNG_READ_iTXt_SUPPORTED)
  188737. void /* PRIVATE */
  188738. png_push_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  188739. length)
  188740. {
  188741. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  188742. {
  188743. png_error(png_ptr, "Out of place iTXt");
  188744. info_ptr = info_ptr; /* to quiet some compiler warnings */
  188745. }
  188746. #ifdef PNG_MAX_MALLOC_64K
  188747. png_ptr->skip_length = 0; /* This may not be necessary */
  188748. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  188749. {
  188750. png_warning(png_ptr, "iTXt chunk too large to fit in memory");
  188751. png_ptr->skip_length = length - (png_uint_32)65535L;
  188752. length = (png_uint_32)65535L;
  188753. }
  188754. #endif
  188755. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  188756. (png_uint_32)(length+1));
  188757. png_ptr->current_text[length] = '\0';
  188758. png_ptr->current_text_ptr = png_ptr->current_text;
  188759. png_ptr->current_text_size = (png_size_t)length;
  188760. png_ptr->current_text_left = (png_size_t)length;
  188761. png_ptr->process_mode = PNG_READ_iTXt_MODE;
  188762. }
  188763. void /* PRIVATE */
  188764. png_push_read_iTXt(png_structp png_ptr, png_infop info_ptr)
  188765. {
  188766. if (png_ptr->buffer_size && png_ptr->current_text_left)
  188767. {
  188768. png_size_t text_size;
  188769. if (png_ptr->buffer_size < png_ptr->current_text_left)
  188770. text_size = png_ptr->buffer_size;
  188771. else
  188772. text_size = png_ptr->current_text_left;
  188773. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  188774. png_ptr->current_text_left -= text_size;
  188775. png_ptr->current_text_ptr += text_size;
  188776. }
  188777. if (!(png_ptr->current_text_left))
  188778. {
  188779. png_textp text_ptr;
  188780. png_charp key;
  188781. int comp_flag;
  188782. png_charp lang;
  188783. png_charp lang_key;
  188784. png_charp text;
  188785. int ret;
  188786. if (png_ptr->buffer_size < 4)
  188787. {
  188788. png_push_save_buffer(png_ptr);
  188789. return;
  188790. }
  188791. png_push_crc_finish(png_ptr);
  188792. #if defined(PNG_MAX_MALLOC_64K)
  188793. if (png_ptr->skip_length)
  188794. return;
  188795. #endif
  188796. key = png_ptr->current_text;
  188797. for (lang = key; *lang; lang++)
  188798. /* empty loop */ ;
  188799. if (lang < key + png_ptr->current_text_size - 3)
  188800. lang++;
  188801. comp_flag = *lang++;
  188802. lang++; /* skip comp_type, always zero */
  188803. for (lang_key = lang; *lang_key; lang_key++)
  188804. /* empty loop */ ;
  188805. lang_key++; /* skip NUL separator */
  188806. text=lang_key;
  188807. if (lang_key < key + png_ptr->current_text_size - 1)
  188808. {
  188809. for (; *text; text++)
  188810. /* empty loop */ ;
  188811. }
  188812. if (text < key + png_ptr->current_text_size)
  188813. text++;
  188814. text_ptr = (png_textp)png_malloc(png_ptr,
  188815. (png_uint_32)png_sizeof(png_text));
  188816. text_ptr->compression = comp_flag + 2;
  188817. text_ptr->key = key;
  188818. text_ptr->lang = lang;
  188819. text_ptr->lang_key = lang_key;
  188820. text_ptr->text = text;
  188821. text_ptr->text_length = 0;
  188822. text_ptr->itxt_length = png_strlen(text);
  188823. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  188824. png_ptr->current_text = NULL;
  188825. png_free(png_ptr, text_ptr);
  188826. if (ret)
  188827. png_warning(png_ptr, "Insufficient memory to store iTXt chunk.");
  188828. }
  188829. }
  188830. #endif
  188831. /* This function is called when we haven't found a handler for this
  188832. * chunk. If there isn't a problem with the chunk itself (ie a bad chunk
  188833. * name or a critical chunk), the chunk is (currently) silently ignored.
  188834. */
  188835. void /* PRIVATE */
  188836. png_push_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32
  188837. length)
  188838. {
  188839. png_uint_32 skip=0;
  188840. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  188841. if (!(png_ptr->chunk_name[0] & 0x20))
  188842. {
  188843. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  188844. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  188845. PNG_HANDLE_CHUNK_ALWAYS
  188846. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  188847. && png_ptr->read_user_chunk_fn == NULL
  188848. #endif
  188849. )
  188850. #endif
  188851. png_chunk_error(png_ptr, "unknown critical chunk");
  188852. info_ptr = info_ptr; /* to quiet some compiler warnings */
  188853. }
  188854. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  188855. if (png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS)
  188856. {
  188857. #ifdef PNG_MAX_MALLOC_64K
  188858. if (length > (png_uint_32)65535L)
  188859. {
  188860. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  188861. skip = length - (png_uint_32)65535L;
  188862. length = (png_uint_32)65535L;
  188863. }
  188864. #endif
  188865. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  188866. (png_charp)png_ptr->chunk_name, 5);
  188867. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  188868. png_ptr->unknown_chunk.size = (png_size_t)length;
  188869. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  188870. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  188871. if(png_ptr->read_user_chunk_fn != NULL)
  188872. {
  188873. /* callback to user unknown chunk handler */
  188874. int ret;
  188875. ret = (*(png_ptr->read_user_chunk_fn))
  188876. (png_ptr, &png_ptr->unknown_chunk);
  188877. if (ret < 0)
  188878. png_chunk_error(png_ptr, "error in user chunk");
  188879. if (ret == 0)
  188880. {
  188881. if (!(png_ptr->chunk_name[0] & 0x20))
  188882. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  188883. PNG_HANDLE_CHUNK_ALWAYS)
  188884. png_chunk_error(png_ptr, "unknown critical chunk");
  188885. png_set_unknown_chunks(png_ptr, info_ptr,
  188886. &png_ptr->unknown_chunk, 1);
  188887. }
  188888. }
  188889. #else
  188890. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  188891. #endif
  188892. png_free(png_ptr, png_ptr->unknown_chunk.data);
  188893. png_ptr->unknown_chunk.data = NULL;
  188894. }
  188895. else
  188896. #endif
  188897. skip=length;
  188898. png_push_crc_skip(png_ptr, skip);
  188899. }
  188900. void /* PRIVATE */
  188901. png_push_have_info(png_structp png_ptr, png_infop info_ptr)
  188902. {
  188903. if (png_ptr->info_fn != NULL)
  188904. (*(png_ptr->info_fn))(png_ptr, info_ptr);
  188905. }
  188906. void /* PRIVATE */
  188907. png_push_have_end(png_structp png_ptr, png_infop info_ptr)
  188908. {
  188909. if (png_ptr->end_fn != NULL)
  188910. (*(png_ptr->end_fn))(png_ptr, info_ptr);
  188911. }
  188912. void /* PRIVATE */
  188913. png_push_have_row(png_structp png_ptr, png_bytep row)
  188914. {
  188915. if (png_ptr->row_fn != NULL)
  188916. (*(png_ptr->row_fn))(png_ptr, row, png_ptr->row_number,
  188917. (int)png_ptr->pass);
  188918. }
  188919. void PNGAPI
  188920. png_progressive_combine_row (png_structp png_ptr,
  188921. png_bytep old_row, png_bytep new_row)
  188922. {
  188923. #ifdef PNG_USE_LOCAL_ARRAYS
  188924. PNG_CONST int FARDATA png_pass_dsp_mask[7] =
  188925. {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  188926. #endif
  188927. if(png_ptr == NULL) return;
  188928. if (new_row != NULL) /* new_row must == png_ptr->row_buf here. */
  188929. png_combine_row(png_ptr, old_row, png_pass_dsp_mask[png_ptr->pass]);
  188930. }
  188931. void PNGAPI
  188932. png_set_progressive_read_fn(png_structp png_ptr, png_voidp progressive_ptr,
  188933. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  188934. png_progressive_end_ptr end_fn)
  188935. {
  188936. if(png_ptr == NULL) return;
  188937. png_ptr->info_fn = info_fn;
  188938. png_ptr->row_fn = row_fn;
  188939. png_ptr->end_fn = end_fn;
  188940. png_set_read_fn(png_ptr, progressive_ptr, png_push_fill_buffer);
  188941. }
  188942. png_voidp PNGAPI
  188943. png_get_progressive_ptr(png_structp png_ptr)
  188944. {
  188945. if(png_ptr == NULL) return (NULL);
  188946. return png_ptr->io_ptr;
  188947. }
  188948. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  188949. /*** End of inlined file: pngpread.c ***/
  188950. /*** Start of inlined file: pngrio.c ***/
  188951. /* pngrio.c - functions for data input
  188952. *
  188953. * Last changed in libpng 1.2.13 November 13, 2006
  188954. * For conditions of distribution and use, see copyright notice in png.h
  188955. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  188956. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  188957. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  188958. *
  188959. * This file provides a location for all input. Users who need
  188960. * special handling are expected to write a function that has the same
  188961. * arguments as this and performs a similar function, but that possibly
  188962. * has a different input method. Note that you shouldn't change this
  188963. * function, but rather write a replacement function and then make
  188964. * libpng use it at run time with png_set_read_fn(...).
  188965. */
  188966. #define PNG_INTERNAL
  188967. #if defined(PNG_READ_SUPPORTED)
  188968. /* Read the data from whatever input you are using. The default routine
  188969. reads from a file pointer. Note that this routine sometimes gets called
  188970. with very small lengths, so you should implement some kind of simple
  188971. buffering if you are using unbuffered reads. This should never be asked
  188972. to read more then 64K on a 16 bit machine. */
  188973. void /* PRIVATE */
  188974. png_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  188975. {
  188976. png_debug1(4,"reading %d bytes\n", (int)length);
  188977. if (png_ptr->read_data_fn != NULL)
  188978. (*(png_ptr->read_data_fn))(png_ptr, data, length);
  188979. else
  188980. png_error(png_ptr, "Call to NULL read function");
  188981. }
  188982. #if !defined(PNG_NO_STDIO)
  188983. /* This is the function that does the actual reading of data. If you are
  188984. not reading from a standard C stream, you should create a replacement
  188985. read_data function and use it at run time with png_set_read_fn(), rather
  188986. than changing the library. */
  188987. #ifndef USE_FAR_KEYWORD
  188988. void PNGAPI
  188989. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  188990. {
  188991. png_size_t check;
  188992. if(png_ptr == NULL) return;
  188993. /* fread() returns 0 on error, so it is OK to store this in a png_size_t
  188994. * instead of an int, which is what fread() actually returns.
  188995. */
  188996. #if defined(_WIN32_WCE)
  188997. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  188998. check = 0;
  188999. #else
  189000. check = (png_size_t)fread(data, (png_size_t)1, length,
  189001. (png_FILE_p)png_ptr->io_ptr);
  189002. #endif
  189003. if (check != length)
  189004. png_error(png_ptr, "Read Error");
  189005. }
  189006. #else
  189007. /* this is the model-independent version. Since the standard I/O library
  189008. can't handle far buffers in the medium and small models, we have to copy
  189009. the data.
  189010. */
  189011. #define NEAR_BUF_SIZE 1024
  189012. #define MIN(a,b) (a <= b ? a : b)
  189013. static void PNGAPI
  189014. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189015. {
  189016. int check;
  189017. png_byte *n_data;
  189018. png_FILE_p io_ptr;
  189019. if(png_ptr == NULL) return;
  189020. /* Check if data really is near. If so, use usual code. */
  189021. n_data = (png_byte *)CVT_PTR_NOCHECK(data);
  189022. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  189023. if ((png_bytep)n_data == data)
  189024. {
  189025. #if defined(_WIN32_WCE)
  189026. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  189027. check = 0;
  189028. #else
  189029. check = fread(n_data, 1, length, io_ptr);
  189030. #endif
  189031. }
  189032. else
  189033. {
  189034. png_byte buf[NEAR_BUF_SIZE];
  189035. png_size_t read, remaining, err;
  189036. check = 0;
  189037. remaining = length;
  189038. do
  189039. {
  189040. read = MIN(NEAR_BUF_SIZE, remaining);
  189041. #if defined(_WIN32_WCE)
  189042. if ( !ReadFile((HANDLE)(io_ptr), buf, read, &err, NULL) )
  189043. err = 0;
  189044. #else
  189045. err = fread(buf, (png_size_t)1, read, io_ptr);
  189046. #endif
  189047. png_memcpy(data, buf, read); /* copy far buffer to near buffer */
  189048. if(err != read)
  189049. break;
  189050. else
  189051. check += err;
  189052. data += read;
  189053. remaining -= read;
  189054. }
  189055. while (remaining != 0);
  189056. }
  189057. if ((png_uint_32)check != (png_uint_32)length)
  189058. png_error(png_ptr, "read Error");
  189059. }
  189060. #endif
  189061. #endif
  189062. /* This function allows the application to supply a new input function
  189063. for libpng if standard C streams aren't being used.
  189064. This function takes as its arguments:
  189065. png_ptr - pointer to a png input data structure
  189066. io_ptr - pointer to user supplied structure containing info about
  189067. the input functions. May be NULL.
  189068. read_data_fn - pointer to a new input function that takes as its
  189069. arguments a pointer to a png_struct, a pointer to
  189070. a location where input data can be stored, and a 32-bit
  189071. unsigned int that is the number of bytes to be read.
  189072. To exit and output any fatal error messages the new write
  189073. function should call png_error(png_ptr, "Error msg"). */
  189074. void PNGAPI
  189075. png_set_read_fn(png_structp png_ptr, png_voidp io_ptr,
  189076. png_rw_ptr read_data_fn)
  189077. {
  189078. if(png_ptr == NULL) return;
  189079. png_ptr->io_ptr = io_ptr;
  189080. #if !defined(PNG_NO_STDIO)
  189081. if (read_data_fn != NULL)
  189082. png_ptr->read_data_fn = read_data_fn;
  189083. else
  189084. png_ptr->read_data_fn = png_default_read_data;
  189085. #else
  189086. png_ptr->read_data_fn = read_data_fn;
  189087. #endif
  189088. /* It is an error to write to a read device */
  189089. if (png_ptr->write_data_fn != NULL)
  189090. {
  189091. png_ptr->write_data_fn = NULL;
  189092. png_warning(png_ptr,
  189093. "It's an error to set both read_data_fn and write_data_fn in the ");
  189094. png_warning(png_ptr,
  189095. "same structure. Resetting write_data_fn to NULL.");
  189096. }
  189097. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  189098. png_ptr->output_flush_fn = NULL;
  189099. #endif
  189100. }
  189101. #endif /* PNG_READ_SUPPORTED */
  189102. /*** End of inlined file: pngrio.c ***/
  189103. /*** Start of inlined file: pngrtran.c ***/
  189104. /* pngrtran.c - transforms the data in a row for PNG readers
  189105. *
  189106. * Last changed in libpng 1.2.21 [October 4, 2007]
  189107. * For conditions of distribution and use, see copyright notice in png.h
  189108. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  189109. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  189110. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  189111. *
  189112. * This file contains functions optionally called by an application
  189113. * in order to tell libpng how to handle data when reading a PNG.
  189114. * Transformations that are used in both reading and writing are
  189115. * in pngtrans.c.
  189116. */
  189117. #define PNG_INTERNAL
  189118. #if defined(PNG_READ_SUPPORTED)
  189119. /* Set the action on getting a CRC error for an ancillary or critical chunk. */
  189120. void PNGAPI
  189121. png_set_crc_action(png_structp png_ptr, int crit_action, int ancil_action)
  189122. {
  189123. png_debug(1, "in png_set_crc_action\n");
  189124. /* Tell libpng how we react to CRC errors in critical chunks */
  189125. if(png_ptr == NULL) return;
  189126. switch (crit_action)
  189127. {
  189128. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  189129. break;
  189130. case PNG_CRC_WARN_USE: /* warn/use data */
  189131. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  189132. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE;
  189133. break;
  189134. case PNG_CRC_QUIET_USE: /* quiet/use data */
  189135. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  189136. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE |
  189137. PNG_FLAG_CRC_CRITICAL_IGNORE;
  189138. break;
  189139. case PNG_CRC_WARN_DISCARD: /* not a valid action for critical data */
  189140. png_warning(png_ptr, "Can't discard critical data on CRC error.");
  189141. case PNG_CRC_ERROR_QUIT: /* error/quit */
  189142. case PNG_CRC_DEFAULT:
  189143. default:
  189144. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  189145. break;
  189146. }
  189147. switch (ancil_action)
  189148. {
  189149. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  189150. break;
  189151. case PNG_CRC_WARN_USE: /* warn/use data */
  189152. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189153. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE;
  189154. break;
  189155. case PNG_CRC_QUIET_USE: /* quiet/use data */
  189156. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189157. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE |
  189158. PNG_FLAG_CRC_ANCILLARY_NOWARN;
  189159. break;
  189160. case PNG_CRC_ERROR_QUIT: /* error/quit */
  189161. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189162. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_NOWARN;
  189163. break;
  189164. case PNG_CRC_WARN_DISCARD: /* warn/discard data */
  189165. case PNG_CRC_DEFAULT:
  189166. default:
  189167. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189168. break;
  189169. }
  189170. }
  189171. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  189172. defined(PNG_FLOATING_POINT_SUPPORTED)
  189173. /* handle alpha and tRNS via a background color */
  189174. void PNGAPI
  189175. png_set_background(png_structp png_ptr,
  189176. png_color_16p background_color, int background_gamma_code,
  189177. int need_expand, double background_gamma)
  189178. {
  189179. png_debug(1, "in png_set_background\n");
  189180. if(png_ptr == NULL) return;
  189181. if (background_gamma_code == PNG_BACKGROUND_GAMMA_UNKNOWN)
  189182. {
  189183. png_warning(png_ptr, "Application must supply a known background gamma");
  189184. return;
  189185. }
  189186. png_ptr->transformations |= PNG_BACKGROUND;
  189187. png_memcpy(&(png_ptr->background), background_color,
  189188. png_sizeof(png_color_16));
  189189. png_ptr->background_gamma = (float)background_gamma;
  189190. png_ptr->background_gamma_type = (png_byte)(background_gamma_code);
  189191. png_ptr->transformations |= (need_expand ? PNG_BACKGROUND_EXPAND : 0);
  189192. }
  189193. #endif
  189194. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  189195. /* strip 16 bit depth files to 8 bit depth */
  189196. void PNGAPI
  189197. png_set_strip_16(png_structp png_ptr)
  189198. {
  189199. png_debug(1, "in png_set_strip_16\n");
  189200. if(png_ptr == NULL) return;
  189201. png_ptr->transformations |= PNG_16_TO_8;
  189202. }
  189203. #endif
  189204. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  189205. void PNGAPI
  189206. png_set_strip_alpha(png_structp png_ptr)
  189207. {
  189208. png_debug(1, "in png_set_strip_alpha\n");
  189209. if(png_ptr == NULL) return;
  189210. png_ptr->flags |= PNG_FLAG_STRIP_ALPHA;
  189211. }
  189212. #endif
  189213. #if defined(PNG_READ_DITHER_SUPPORTED)
  189214. /* Dither file to 8 bit. Supply a palette, the current number
  189215. * of elements in the palette, the maximum number of elements
  189216. * allowed, and a histogram if possible. If the current number
  189217. * of colors is greater then the maximum number, the palette will be
  189218. * modified to fit in the maximum number. "full_dither" indicates
  189219. * whether we need a dithering cube set up for RGB images, or if we
  189220. * simply are reducing the number of colors in a paletted image.
  189221. */
  189222. typedef struct png_dsort_struct
  189223. {
  189224. struct png_dsort_struct FAR * next;
  189225. png_byte left;
  189226. png_byte right;
  189227. } png_dsort;
  189228. typedef png_dsort FAR * png_dsortp;
  189229. typedef png_dsort FAR * FAR * png_dsortpp;
  189230. void PNGAPI
  189231. png_set_dither(png_structp png_ptr, png_colorp palette,
  189232. int num_palette, int maximum_colors, png_uint_16p histogram,
  189233. int full_dither)
  189234. {
  189235. png_debug(1, "in png_set_dither\n");
  189236. if(png_ptr == NULL) return;
  189237. png_ptr->transformations |= PNG_DITHER;
  189238. if (!full_dither)
  189239. {
  189240. int i;
  189241. png_ptr->dither_index = (png_bytep)png_malloc(png_ptr,
  189242. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  189243. for (i = 0; i < num_palette; i++)
  189244. png_ptr->dither_index[i] = (png_byte)i;
  189245. }
  189246. if (num_palette > maximum_colors)
  189247. {
  189248. if (histogram != NULL)
  189249. {
  189250. /* This is easy enough, just throw out the least used colors.
  189251. Perhaps not the best solution, but good enough. */
  189252. int i;
  189253. /* initialize an array to sort colors */
  189254. png_ptr->dither_sort = (png_bytep)png_malloc(png_ptr,
  189255. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  189256. /* initialize the dither_sort array */
  189257. for (i = 0; i < num_palette; i++)
  189258. png_ptr->dither_sort[i] = (png_byte)i;
  189259. /* Find the least used palette entries by starting a
  189260. bubble sort, and running it until we have sorted
  189261. out enough colors. Note that we don't care about
  189262. sorting all the colors, just finding which are
  189263. least used. */
  189264. for (i = num_palette - 1; i >= maximum_colors; i--)
  189265. {
  189266. int done; /* to stop early if the list is pre-sorted */
  189267. int j;
  189268. done = 1;
  189269. for (j = 0; j < i; j++)
  189270. {
  189271. if (histogram[png_ptr->dither_sort[j]]
  189272. < histogram[png_ptr->dither_sort[j + 1]])
  189273. {
  189274. png_byte t;
  189275. t = png_ptr->dither_sort[j];
  189276. png_ptr->dither_sort[j] = png_ptr->dither_sort[j + 1];
  189277. png_ptr->dither_sort[j + 1] = t;
  189278. done = 0;
  189279. }
  189280. }
  189281. if (done)
  189282. break;
  189283. }
  189284. /* swap the palette around, and set up a table, if necessary */
  189285. if (full_dither)
  189286. {
  189287. int j = num_palette;
  189288. /* put all the useful colors within the max, but don't
  189289. move the others */
  189290. for (i = 0; i < maximum_colors; i++)
  189291. {
  189292. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  189293. {
  189294. do
  189295. j--;
  189296. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  189297. palette[i] = palette[j];
  189298. }
  189299. }
  189300. }
  189301. else
  189302. {
  189303. int j = num_palette;
  189304. /* move all the used colors inside the max limit, and
  189305. develop a translation table */
  189306. for (i = 0; i < maximum_colors; i++)
  189307. {
  189308. /* only move the colors we need to */
  189309. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  189310. {
  189311. png_color tmp_color;
  189312. do
  189313. j--;
  189314. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  189315. tmp_color = palette[j];
  189316. palette[j] = palette[i];
  189317. palette[i] = tmp_color;
  189318. /* indicate where the color went */
  189319. png_ptr->dither_index[j] = (png_byte)i;
  189320. png_ptr->dither_index[i] = (png_byte)j;
  189321. }
  189322. }
  189323. /* find closest color for those colors we are not using */
  189324. for (i = 0; i < num_palette; i++)
  189325. {
  189326. if ((int)png_ptr->dither_index[i] >= maximum_colors)
  189327. {
  189328. int min_d, k, min_k, d_index;
  189329. /* find the closest color to one we threw out */
  189330. d_index = png_ptr->dither_index[i];
  189331. min_d = PNG_COLOR_DIST(palette[d_index], palette[0]);
  189332. for (k = 1, min_k = 0; k < maximum_colors; k++)
  189333. {
  189334. int d;
  189335. d = PNG_COLOR_DIST(palette[d_index], palette[k]);
  189336. if (d < min_d)
  189337. {
  189338. min_d = d;
  189339. min_k = k;
  189340. }
  189341. }
  189342. /* point to closest color */
  189343. png_ptr->dither_index[i] = (png_byte)min_k;
  189344. }
  189345. }
  189346. }
  189347. png_free(png_ptr, png_ptr->dither_sort);
  189348. png_ptr->dither_sort=NULL;
  189349. }
  189350. else
  189351. {
  189352. /* This is much harder to do simply (and quickly). Perhaps
  189353. we need to go through a median cut routine, but those
  189354. don't always behave themselves with only a few colors
  189355. as input. So we will just find the closest two colors,
  189356. and throw out one of them (chosen somewhat randomly).
  189357. [We don't understand this at all, so if someone wants to
  189358. work on improving it, be our guest - AED, GRP]
  189359. */
  189360. int i;
  189361. int max_d;
  189362. int num_new_palette;
  189363. png_dsortp t;
  189364. png_dsortpp hash;
  189365. t=NULL;
  189366. /* initialize palette index arrays */
  189367. png_ptr->index_to_palette = (png_bytep)png_malloc(png_ptr,
  189368. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  189369. png_ptr->palette_to_index = (png_bytep)png_malloc(png_ptr,
  189370. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  189371. /* initialize the sort array */
  189372. for (i = 0; i < num_palette; i++)
  189373. {
  189374. png_ptr->index_to_palette[i] = (png_byte)i;
  189375. png_ptr->palette_to_index[i] = (png_byte)i;
  189376. }
  189377. hash = (png_dsortpp)png_malloc(png_ptr, (png_uint_32)(769 *
  189378. png_sizeof (png_dsortp)));
  189379. for (i = 0; i < 769; i++)
  189380. hash[i] = NULL;
  189381. /* png_memset(hash, 0, 769 * png_sizeof (png_dsortp)); */
  189382. num_new_palette = num_palette;
  189383. /* initial wild guess at how far apart the farthest pixel
  189384. pair we will be eliminating will be. Larger
  189385. numbers mean more areas will be allocated, Smaller
  189386. numbers run the risk of not saving enough data, and
  189387. having to do this all over again.
  189388. I have not done extensive checking on this number.
  189389. */
  189390. max_d = 96;
  189391. while (num_new_palette > maximum_colors)
  189392. {
  189393. for (i = 0; i < num_new_palette - 1; i++)
  189394. {
  189395. int j;
  189396. for (j = i + 1; j < num_new_palette; j++)
  189397. {
  189398. int d;
  189399. d = PNG_COLOR_DIST(palette[i], palette[j]);
  189400. if (d <= max_d)
  189401. {
  189402. t = (png_dsortp)png_malloc_warn(png_ptr,
  189403. (png_uint_32)(png_sizeof(png_dsort)));
  189404. if (t == NULL)
  189405. break;
  189406. t->next = hash[d];
  189407. t->left = (png_byte)i;
  189408. t->right = (png_byte)j;
  189409. hash[d] = t;
  189410. }
  189411. }
  189412. if (t == NULL)
  189413. break;
  189414. }
  189415. if (t != NULL)
  189416. for (i = 0; i <= max_d; i++)
  189417. {
  189418. if (hash[i] != NULL)
  189419. {
  189420. png_dsortp p;
  189421. for (p = hash[i]; p; p = p->next)
  189422. {
  189423. if ((int)png_ptr->index_to_palette[p->left]
  189424. < num_new_palette &&
  189425. (int)png_ptr->index_to_palette[p->right]
  189426. < num_new_palette)
  189427. {
  189428. int j, next_j;
  189429. if (num_new_palette & 0x01)
  189430. {
  189431. j = p->left;
  189432. next_j = p->right;
  189433. }
  189434. else
  189435. {
  189436. j = p->right;
  189437. next_j = p->left;
  189438. }
  189439. num_new_palette--;
  189440. palette[png_ptr->index_to_palette[j]]
  189441. = palette[num_new_palette];
  189442. if (!full_dither)
  189443. {
  189444. int k;
  189445. for (k = 0; k < num_palette; k++)
  189446. {
  189447. if (png_ptr->dither_index[k] ==
  189448. png_ptr->index_to_palette[j])
  189449. png_ptr->dither_index[k] =
  189450. png_ptr->index_to_palette[next_j];
  189451. if ((int)png_ptr->dither_index[k] ==
  189452. num_new_palette)
  189453. png_ptr->dither_index[k] =
  189454. png_ptr->index_to_palette[j];
  189455. }
  189456. }
  189457. png_ptr->index_to_palette[png_ptr->palette_to_index
  189458. [num_new_palette]] = png_ptr->index_to_palette[j];
  189459. png_ptr->palette_to_index[png_ptr->index_to_palette[j]]
  189460. = png_ptr->palette_to_index[num_new_palette];
  189461. png_ptr->index_to_palette[j] = (png_byte)num_new_palette;
  189462. png_ptr->palette_to_index[num_new_palette] = (png_byte)j;
  189463. }
  189464. if (num_new_palette <= maximum_colors)
  189465. break;
  189466. }
  189467. if (num_new_palette <= maximum_colors)
  189468. break;
  189469. }
  189470. }
  189471. for (i = 0; i < 769; i++)
  189472. {
  189473. if (hash[i] != NULL)
  189474. {
  189475. png_dsortp p = hash[i];
  189476. while (p)
  189477. {
  189478. t = p->next;
  189479. png_free(png_ptr, p);
  189480. p = t;
  189481. }
  189482. }
  189483. hash[i] = 0;
  189484. }
  189485. max_d += 96;
  189486. }
  189487. png_free(png_ptr, hash);
  189488. png_free(png_ptr, png_ptr->palette_to_index);
  189489. png_free(png_ptr, png_ptr->index_to_palette);
  189490. png_ptr->palette_to_index=NULL;
  189491. png_ptr->index_to_palette=NULL;
  189492. }
  189493. num_palette = maximum_colors;
  189494. }
  189495. if (png_ptr->palette == NULL)
  189496. {
  189497. png_ptr->palette = palette;
  189498. }
  189499. png_ptr->num_palette = (png_uint_16)num_palette;
  189500. if (full_dither)
  189501. {
  189502. int i;
  189503. png_bytep distance;
  189504. int total_bits = PNG_DITHER_RED_BITS + PNG_DITHER_GREEN_BITS +
  189505. PNG_DITHER_BLUE_BITS;
  189506. int num_red = (1 << PNG_DITHER_RED_BITS);
  189507. int num_green = (1 << PNG_DITHER_GREEN_BITS);
  189508. int num_blue = (1 << PNG_DITHER_BLUE_BITS);
  189509. png_size_t num_entries = ((png_size_t)1 << total_bits);
  189510. png_ptr->palette_lookup = (png_bytep )png_malloc(png_ptr,
  189511. (png_uint_32)(num_entries * png_sizeof (png_byte)));
  189512. png_memset(png_ptr->palette_lookup, 0, num_entries *
  189513. png_sizeof (png_byte));
  189514. distance = (png_bytep)png_malloc(png_ptr, (png_uint_32)(num_entries *
  189515. png_sizeof(png_byte)));
  189516. png_memset(distance, 0xff, num_entries * png_sizeof(png_byte));
  189517. for (i = 0; i < num_palette; i++)
  189518. {
  189519. int ir, ig, ib;
  189520. int r = (palette[i].red >> (8 - PNG_DITHER_RED_BITS));
  189521. int g = (palette[i].green >> (8 - PNG_DITHER_GREEN_BITS));
  189522. int b = (palette[i].blue >> (8 - PNG_DITHER_BLUE_BITS));
  189523. for (ir = 0; ir < num_red; ir++)
  189524. {
  189525. /* int dr = abs(ir - r); */
  189526. int dr = ((ir > r) ? ir - r : r - ir);
  189527. int index_r = (ir << (PNG_DITHER_BLUE_BITS + PNG_DITHER_GREEN_BITS));
  189528. for (ig = 0; ig < num_green; ig++)
  189529. {
  189530. /* int dg = abs(ig - g); */
  189531. int dg = ((ig > g) ? ig - g : g - ig);
  189532. int dt = dr + dg;
  189533. int dm = ((dr > dg) ? dr : dg);
  189534. int index_g = index_r | (ig << PNG_DITHER_BLUE_BITS);
  189535. for (ib = 0; ib < num_blue; ib++)
  189536. {
  189537. int d_index = index_g | ib;
  189538. /* int db = abs(ib - b); */
  189539. int db = ((ib > b) ? ib - b : b - ib);
  189540. int dmax = ((dm > db) ? dm : db);
  189541. int d = dmax + dt + db;
  189542. if (d < (int)distance[d_index])
  189543. {
  189544. distance[d_index] = (png_byte)d;
  189545. png_ptr->palette_lookup[d_index] = (png_byte)i;
  189546. }
  189547. }
  189548. }
  189549. }
  189550. }
  189551. png_free(png_ptr, distance);
  189552. }
  189553. }
  189554. #endif
  189555. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  189556. /* Transform the image from the file_gamma to the screen_gamma. We
  189557. * only do transformations on images where the file_gamma and screen_gamma
  189558. * are not close reciprocals, otherwise it slows things down slightly, and
  189559. * also needlessly introduces small errors.
  189560. *
  189561. * We will turn off gamma transformation later if no semitransparent entries
  189562. * are present in the tRNS array for palette images. We can't do it here
  189563. * because we don't necessarily have the tRNS chunk yet.
  189564. */
  189565. void PNGAPI
  189566. png_set_gamma(png_structp png_ptr, double scrn_gamma, double file_gamma)
  189567. {
  189568. png_debug(1, "in png_set_gamma\n");
  189569. if(png_ptr == NULL) return;
  189570. if ((fabs(scrn_gamma * file_gamma - 1.0) > PNG_GAMMA_THRESHOLD) ||
  189571. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) ||
  189572. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE))
  189573. png_ptr->transformations |= PNG_GAMMA;
  189574. png_ptr->gamma = (float)file_gamma;
  189575. png_ptr->screen_gamma = (float)scrn_gamma;
  189576. }
  189577. #endif
  189578. #if defined(PNG_READ_EXPAND_SUPPORTED)
  189579. /* Expand paletted images to RGB, expand grayscale images of
  189580. * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
  189581. * to alpha channels.
  189582. */
  189583. void PNGAPI
  189584. png_set_expand(png_structp png_ptr)
  189585. {
  189586. png_debug(1, "in png_set_expand\n");
  189587. if(png_ptr == NULL) return;
  189588. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  189589. #ifdef PNG_WARN_UNINITIALIZED_ROW
  189590. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  189591. #endif
  189592. }
  189593. /* GRR 19990627: the following three functions currently are identical
  189594. * to png_set_expand(). However, it is entirely reasonable that someone
  189595. * might wish to expand an indexed image to RGB but *not* expand a single,
  189596. * fully transparent palette entry to a full alpha channel--perhaps instead
  189597. * convert tRNS to the grayscale/RGB format (16-bit RGB value), or replace
  189598. * the transparent color with a particular RGB value, or drop tRNS entirely.
  189599. * IOW, a future version of the library may make the transformations flag
  189600. * a bit more fine-grained, with separate bits for each of these three
  189601. * functions.
  189602. *
  189603. * More to the point, these functions make it obvious what libpng will be
  189604. * doing, whereas "expand" can (and does) mean any number of things.
  189605. *
  189606. * GRP 20060307: In libpng-1.4.0, png_set_gray_1_2_4_to_8() was modified
  189607. * to expand only the sample depth but not to expand the tRNS to alpha.
  189608. */
  189609. /* Expand paletted images to RGB. */
  189610. void PNGAPI
  189611. png_set_palette_to_rgb(png_structp png_ptr)
  189612. {
  189613. png_debug(1, "in png_set_palette_to_rgb\n");
  189614. if(png_ptr == NULL) return;
  189615. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  189616. #ifdef PNG_WARN_UNINITIALIZED_ROW
  189617. png_ptr->flags &= !(PNG_FLAG_ROW_INIT);
  189618. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  189619. #endif
  189620. }
  189621. #if !defined(PNG_1_0_X)
  189622. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  189623. void PNGAPI
  189624. png_set_expand_gray_1_2_4_to_8(png_structp png_ptr)
  189625. {
  189626. png_debug(1, "in png_set_expand_gray_1_2_4_to_8\n");
  189627. if(png_ptr == NULL) return;
  189628. png_ptr->transformations |= PNG_EXPAND;
  189629. #ifdef PNG_WARN_UNINITIALIZED_ROW
  189630. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  189631. #endif
  189632. }
  189633. #endif
  189634. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  189635. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  189636. /* Deprecated as of libpng-1.2.9 */
  189637. void PNGAPI
  189638. png_set_gray_1_2_4_to_8(png_structp png_ptr)
  189639. {
  189640. png_debug(1, "in png_set_gray_1_2_4_to_8\n");
  189641. if(png_ptr == NULL) return;
  189642. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  189643. }
  189644. #endif
  189645. /* Expand tRNS chunks to alpha channels. */
  189646. void PNGAPI
  189647. png_set_tRNS_to_alpha(png_structp png_ptr)
  189648. {
  189649. png_debug(1, "in png_set_tRNS_to_alpha\n");
  189650. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  189651. #ifdef PNG_WARN_UNINITIALIZED_ROW
  189652. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  189653. #endif
  189654. }
  189655. #endif /* defined(PNG_READ_EXPAND_SUPPORTED) */
  189656. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  189657. void PNGAPI
  189658. png_set_gray_to_rgb(png_structp png_ptr)
  189659. {
  189660. png_debug(1, "in png_set_gray_to_rgb\n");
  189661. png_ptr->transformations |= PNG_GRAY_TO_RGB;
  189662. #ifdef PNG_WARN_UNINITIALIZED_ROW
  189663. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  189664. #endif
  189665. }
  189666. #endif
  189667. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  189668. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  189669. /* Convert a RGB image to a grayscale of the same width. This allows us,
  189670. * for example, to convert a 24 bpp RGB image into an 8 bpp grayscale image.
  189671. */
  189672. void PNGAPI
  189673. png_set_rgb_to_gray(png_structp png_ptr, int error_action, double red,
  189674. double green)
  189675. {
  189676. int red_fixed = (int)((float)red*100000.0 + 0.5);
  189677. int green_fixed = (int)((float)green*100000.0 + 0.5);
  189678. if(png_ptr == NULL) return;
  189679. png_set_rgb_to_gray_fixed(png_ptr, error_action, red_fixed, green_fixed);
  189680. }
  189681. #endif
  189682. void PNGAPI
  189683. png_set_rgb_to_gray_fixed(png_structp png_ptr, int error_action,
  189684. png_fixed_point red, png_fixed_point green)
  189685. {
  189686. png_debug(1, "in png_set_rgb_to_gray\n");
  189687. if(png_ptr == NULL) return;
  189688. switch(error_action)
  189689. {
  189690. case 1: png_ptr->transformations |= PNG_RGB_TO_GRAY;
  189691. break;
  189692. case 2: png_ptr->transformations |= PNG_RGB_TO_GRAY_WARN;
  189693. break;
  189694. case 3: png_ptr->transformations |= PNG_RGB_TO_GRAY_ERR;
  189695. }
  189696. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  189697. #if defined(PNG_READ_EXPAND_SUPPORTED)
  189698. png_ptr->transformations |= PNG_EXPAND;
  189699. #else
  189700. {
  189701. png_warning(png_ptr, "Cannot do RGB_TO_GRAY without EXPAND_SUPPORTED.");
  189702. png_ptr->transformations &= ~PNG_RGB_TO_GRAY;
  189703. }
  189704. #endif
  189705. {
  189706. png_uint_16 red_int, green_int;
  189707. if(red < 0 || green < 0)
  189708. {
  189709. red_int = 6968; /* .212671 * 32768 + .5 */
  189710. green_int = 23434; /* .715160 * 32768 + .5 */
  189711. }
  189712. else if(red + green < 100000L)
  189713. {
  189714. red_int = (png_uint_16)(((png_uint_32)red*32768L)/100000L);
  189715. green_int = (png_uint_16)(((png_uint_32)green*32768L)/100000L);
  189716. }
  189717. else
  189718. {
  189719. png_warning(png_ptr, "ignoring out of range rgb_to_gray coefficients");
  189720. red_int = 6968;
  189721. green_int = 23434;
  189722. }
  189723. png_ptr->rgb_to_gray_red_coeff = red_int;
  189724. png_ptr->rgb_to_gray_green_coeff = green_int;
  189725. png_ptr->rgb_to_gray_blue_coeff = (png_uint_16)(32768-red_int-green_int);
  189726. }
  189727. }
  189728. #endif
  189729. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  189730. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  189731. defined(PNG_LEGACY_SUPPORTED)
  189732. void PNGAPI
  189733. png_set_read_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  189734. read_user_transform_fn)
  189735. {
  189736. png_debug(1, "in png_set_read_user_transform_fn\n");
  189737. if(png_ptr == NULL) return;
  189738. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  189739. png_ptr->transformations |= PNG_USER_TRANSFORM;
  189740. png_ptr->read_user_transform_fn = read_user_transform_fn;
  189741. #endif
  189742. #ifdef PNG_LEGACY_SUPPORTED
  189743. if(read_user_transform_fn)
  189744. png_warning(png_ptr,
  189745. "This version of libpng does not support user transforms");
  189746. #endif
  189747. }
  189748. #endif
  189749. /* Initialize everything needed for the read. This includes modifying
  189750. * the palette.
  189751. */
  189752. void /* PRIVATE */
  189753. png_init_read_transformations(png_structp png_ptr)
  189754. {
  189755. png_debug(1, "in png_init_read_transformations\n");
  189756. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  189757. if(png_ptr != NULL)
  189758. #endif
  189759. {
  189760. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || defined(PNG_READ_SHIFT_SUPPORTED) \
  189761. || defined(PNG_READ_GAMMA_SUPPORTED)
  189762. int color_type = png_ptr->color_type;
  189763. #endif
  189764. #if defined(PNG_READ_EXPAND_SUPPORTED) && defined(PNG_READ_BACKGROUND_SUPPORTED)
  189765. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  189766. /* Detect gray background and attempt to enable optimization
  189767. * for gray --> RGB case */
  189768. /* Note: if PNG_BACKGROUND_EXPAND is set and color_type is either RGB or
  189769. * RGB_ALPHA (in which case need_expand is superfluous anyway), the
  189770. * background color might actually be gray yet not be flagged as such.
  189771. * This is not a problem for the current code, which uses
  189772. * PNG_BACKGROUND_IS_GRAY only to decide when to do the
  189773. * png_do_gray_to_rgb() transformation.
  189774. */
  189775. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  189776. !(color_type & PNG_COLOR_MASK_COLOR))
  189777. {
  189778. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  189779. } else if ((png_ptr->transformations & PNG_BACKGROUND) &&
  189780. !(png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  189781. (png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  189782. png_ptr->background.red == png_ptr->background.green &&
  189783. png_ptr->background.red == png_ptr->background.blue)
  189784. {
  189785. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  189786. png_ptr->background.gray = png_ptr->background.red;
  189787. }
  189788. #endif
  189789. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  189790. (png_ptr->transformations & PNG_EXPAND))
  189791. {
  189792. if (!(color_type & PNG_COLOR_MASK_COLOR)) /* i.e., GRAY or GRAY_ALPHA */
  189793. {
  189794. /* expand background and tRNS chunks */
  189795. switch (png_ptr->bit_depth)
  189796. {
  189797. case 1:
  189798. png_ptr->background.gray *= (png_uint_16)0xff;
  189799. png_ptr->background.red = png_ptr->background.green
  189800. = png_ptr->background.blue = png_ptr->background.gray;
  189801. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  189802. {
  189803. png_ptr->trans_values.gray *= (png_uint_16)0xff;
  189804. png_ptr->trans_values.red = png_ptr->trans_values.green
  189805. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  189806. }
  189807. break;
  189808. case 2:
  189809. png_ptr->background.gray *= (png_uint_16)0x55;
  189810. png_ptr->background.red = png_ptr->background.green
  189811. = png_ptr->background.blue = png_ptr->background.gray;
  189812. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  189813. {
  189814. png_ptr->trans_values.gray *= (png_uint_16)0x55;
  189815. png_ptr->trans_values.red = png_ptr->trans_values.green
  189816. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  189817. }
  189818. break;
  189819. case 4:
  189820. png_ptr->background.gray *= (png_uint_16)0x11;
  189821. png_ptr->background.red = png_ptr->background.green
  189822. = png_ptr->background.blue = png_ptr->background.gray;
  189823. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  189824. {
  189825. png_ptr->trans_values.gray *= (png_uint_16)0x11;
  189826. png_ptr->trans_values.red = png_ptr->trans_values.green
  189827. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  189828. }
  189829. break;
  189830. case 8:
  189831. case 16:
  189832. png_ptr->background.red = png_ptr->background.green
  189833. = png_ptr->background.blue = png_ptr->background.gray;
  189834. break;
  189835. }
  189836. }
  189837. else if (color_type == PNG_COLOR_TYPE_PALETTE)
  189838. {
  189839. png_ptr->background.red =
  189840. png_ptr->palette[png_ptr->background.index].red;
  189841. png_ptr->background.green =
  189842. png_ptr->palette[png_ptr->background.index].green;
  189843. png_ptr->background.blue =
  189844. png_ptr->palette[png_ptr->background.index].blue;
  189845. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  189846. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  189847. {
  189848. #if defined(PNG_READ_EXPAND_SUPPORTED)
  189849. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  189850. #endif
  189851. {
  189852. /* invert the alpha channel (in tRNS) unless the pixels are
  189853. going to be expanded, in which case leave it for later */
  189854. int i,istop;
  189855. istop=(int)png_ptr->num_trans;
  189856. for (i=0; i<istop; i++)
  189857. png_ptr->trans[i] = (png_byte)(255 - png_ptr->trans[i]);
  189858. }
  189859. }
  189860. #endif
  189861. }
  189862. }
  189863. #endif
  189864. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  189865. png_ptr->background_1 = png_ptr->background;
  189866. #endif
  189867. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  189868. if ((color_type == PNG_COLOR_TYPE_PALETTE && png_ptr->num_trans != 0)
  189869. && (fabs(png_ptr->screen_gamma * png_ptr->gamma - 1.0)
  189870. < PNG_GAMMA_THRESHOLD))
  189871. {
  189872. int i,k;
  189873. k=0;
  189874. for (i=0; i<png_ptr->num_trans; i++)
  189875. {
  189876. if (png_ptr->trans[i] != 0 && png_ptr->trans[i] != 0xff)
  189877. k=1; /* partial transparency is present */
  189878. }
  189879. if (k == 0)
  189880. png_ptr->transformations &= (~PNG_GAMMA);
  189881. }
  189882. if ((png_ptr->transformations & (PNG_GAMMA | PNG_RGB_TO_GRAY)) &&
  189883. png_ptr->gamma != 0.0)
  189884. {
  189885. png_build_gamma_table(png_ptr);
  189886. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  189887. if (png_ptr->transformations & PNG_BACKGROUND)
  189888. {
  189889. if (color_type == PNG_COLOR_TYPE_PALETTE)
  189890. {
  189891. /* could skip if no transparency and
  189892. */
  189893. png_color back, back_1;
  189894. png_colorp palette = png_ptr->palette;
  189895. int num_palette = png_ptr->num_palette;
  189896. int i;
  189897. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  189898. {
  189899. back.red = png_ptr->gamma_table[png_ptr->background.red];
  189900. back.green = png_ptr->gamma_table[png_ptr->background.green];
  189901. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  189902. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  189903. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  189904. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  189905. }
  189906. else
  189907. {
  189908. double g, gs;
  189909. switch (png_ptr->background_gamma_type)
  189910. {
  189911. case PNG_BACKGROUND_GAMMA_SCREEN:
  189912. g = (png_ptr->screen_gamma);
  189913. gs = 1.0;
  189914. break;
  189915. case PNG_BACKGROUND_GAMMA_FILE:
  189916. g = 1.0 / (png_ptr->gamma);
  189917. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  189918. break;
  189919. case PNG_BACKGROUND_GAMMA_UNIQUE:
  189920. g = 1.0 / (png_ptr->background_gamma);
  189921. gs = 1.0 / (png_ptr->background_gamma *
  189922. png_ptr->screen_gamma);
  189923. break;
  189924. default:
  189925. g = 1.0; /* back_1 */
  189926. gs = 1.0; /* back */
  189927. }
  189928. if ( fabs(gs - 1.0) < PNG_GAMMA_THRESHOLD)
  189929. {
  189930. back.red = (png_byte)png_ptr->background.red;
  189931. back.green = (png_byte)png_ptr->background.green;
  189932. back.blue = (png_byte)png_ptr->background.blue;
  189933. }
  189934. else
  189935. {
  189936. back.red = (png_byte)(pow(
  189937. (double)png_ptr->background.red/255, gs) * 255.0 + .5);
  189938. back.green = (png_byte)(pow(
  189939. (double)png_ptr->background.green/255, gs) * 255.0 + .5);
  189940. back.blue = (png_byte)(pow(
  189941. (double)png_ptr->background.blue/255, gs) * 255.0 + .5);
  189942. }
  189943. back_1.red = (png_byte)(pow(
  189944. (double)png_ptr->background.red/255, g) * 255.0 + .5);
  189945. back_1.green = (png_byte)(pow(
  189946. (double)png_ptr->background.green/255, g) * 255.0 + .5);
  189947. back_1.blue = (png_byte)(pow(
  189948. (double)png_ptr->background.blue/255, g) * 255.0 + .5);
  189949. }
  189950. for (i = 0; i < num_palette; i++)
  189951. {
  189952. if (i < (int)png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  189953. {
  189954. if (png_ptr->trans[i] == 0)
  189955. {
  189956. palette[i] = back;
  189957. }
  189958. else /* if (png_ptr->trans[i] != 0xff) */
  189959. {
  189960. png_byte v, w;
  189961. v = png_ptr->gamma_to_1[palette[i].red];
  189962. png_composite(w, v, png_ptr->trans[i], back_1.red);
  189963. palette[i].red = png_ptr->gamma_from_1[w];
  189964. v = png_ptr->gamma_to_1[palette[i].green];
  189965. png_composite(w, v, png_ptr->trans[i], back_1.green);
  189966. palette[i].green = png_ptr->gamma_from_1[w];
  189967. v = png_ptr->gamma_to_1[palette[i].blue];
  189968. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  189969. palette[i].blue = png_ptr->gamma_from_1[w];
  189970. }
  189971. }
  189972. else
  189973. {
  189974. palette[i].red = png_ptr->gamma_table[palette[i].red];
  189975. palette[i].green = png_ptr->gamma_table[palette[i].green];
  189976. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  189977. }
  189978. }
  189979. }
  189980. /* if (png_ptr->background_gamma_type!=PNG_BACKGROUND_GAMMA_UNKNOWN) */
  189981. else
  189982. /* color_type != PNG_COLOR_TYPE_PALETTE */
  189983. {
  189984. double m = (double)(((png_uint_32)1 << png_ptr->bit_depth) - 1);
  189985. double g = 1.0;
  189986. double gs = 1.0;
  189987. switch (png_ptr->background_gamma_type)
  189988. {
  189989. case PNG_BACKGROUND_GAMMA_SCREEN:
  189990. g = (png_ptr->screen_gamma);
  189991. gs = 1.0;
  189992. break;
  189993. case PNG_BACKGROUND_GAMMA_FILE:
  189994. g = 1.0 / (png_ptr->gamma);
  189995. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  189996. break;
  189997. case PNG_BACKGROUND_GAMMA_UNIQUE:
  189998. g = 1.0 / (png_ptr->background_gamma);
  189999. gs = 1.0 / (png_ptr->background_gamma *
  190000. png_ptr->screen_gamma);
  190001. break;
  190002. }
  190003. png_ptr->background_1.gray = (png_uint_16)(pow(
  190004. (double)png_ptr->background.gray / m, g) * m + .5);
  190005. png_ptr->background.gray = (png_uint_16)(pow(
  190006. (double)png_ptr->background.gray / m, gs) * m + .5);
  190007. if ((png_ptr->background.red != png_ptr->background.green) ||
  190008. (png_ptr->background.red != png_ptr->background.blue) ||
  190009. (png_ptr->background.red != png_ptr->background.gray))
  190010. {
  190011. /* RGB or RGBA with color background */
  190012. png_ptr->background_1.red = (png_uint_16)(pow(
  190013. (double)png_ptr->background.red / m, g) * m + .5);
  190014. png_ptr->background_1.green = (png_uint_16)(pow(
  190015. (double)png_ptr->background.green / m, g) * m + .5);
  190016. png_ptr->background_1.blue = (png_uint_16)(pow(
  190017. (double)png_ptr->background.blue / m, g) * m + .5);
  190018. png_ptr->background.red = (png_uint_16)(pow(
  190019. (double)png_ptr->background.red / m, gs) * m + .5);
  190020. png_ptr->background.green = (png_uint_16)(pow(
  190021. (double)png_ptr->background.green / m, gs) * m + .5);
  190022. png_ptr->background.blue = (png_uint_16)(pow(
  190023. (double)png_ptr->background.blue / m, gs) * m + .5);
  190024. }
  190025. else
  190026. {
  190027. /* GRAY, GRAY ALPHA, RGB, or RGBA with gray background */
  190028. png_ptr->background_1.red = png_ptr->background_1.green
  190029. = png_ptr->background_1.blue = png_ptr->background_1.gray;
  190030. png_ptr->background.red = png_ptr->background.green
  190031. = png_ptr->background.blue = png_ptr->background.gray;
  190032. }
  190033. }
  190034. }
  190035. else
  190036. /* transformation does not include PNG_BACKGROUND */
  190037. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  190038. if (color_type == PNG_COLOR_TYPE_PALETTE)
  190039. {
  190040. png_colorp palette = png_ptr->palette;
  190041. int num_palette = png_ptr->num_palette;
  190042. int i;
  190043. for (i = 0; i < num_palette; i++)
  190044. {
  190045. palette[i].red = png_ptr->gamma_table[palette[i].red];
  190046. palette[i].green = png_ptr->gamma_table[palette[i].green];
  190047. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  190048. }
  190049. }
  190050. }
  190051. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190052. else
  190053. #endif
  190054. #endif /* PNG_READ_GAMMA_SUPPORTED && PNG_FLOATING_POINT_SUPPORTED */
  190055. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190056. /* No GAMMA transformation */
  190057. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190058. (color_type == PNG_COLOR_TYPE_PALETTE))
  190059. {
  190060. int i;
  190061. int istop = (int)png_ptr->num_trans;
  190062. png_color back;
  190063. png_colorp palette = png_ptr->palette;
  190064. back.red = (png_byte)png_ptr->background.red;
  190065. back.green = (png_byte)png_ptr->background.green;
  190066. back.blue = (png_byte)png_ptr->background.blue;
  190067. for (i = 0; i < istop; i++)
  190068. {
  190069. if (png_ptr->trans[i] == 0)
  190070. {
  190071. palette[i] = back;
  190072. }
  190073. else if (png_ptr->trans[i] != 0xff)
  190074. {
  190075. /* The png_composite() macro is defined in png.h */
  190076. png_composite(palette[i].red, palette[i].red,
  190077. png_ptr->trans[i], back.red);
  190078. png_composite(palette[i].green, palette[i].green,
  190079. png_ptr->trans[i], back.green);
  190080. png_composite(palette[i].blue, palette[i].blue,
  190081. png_ptr->trans[i], back.blue);
  190082. }
  190083. }
  190084. }
  190085. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  190086. #if defined(PNG_READ_SHIFT_SUPPORTED)
  190087. if ((png_ptr->transformations & PNG_SHIFT) &&
  190088. (color_type == PNG_COLOR_TYPE_PALETTE))
  190089. {
  190090. png_uint_16 i;
  190091. png_uint_16 istop = png_ptr->num_palette;
  190092. int sr = 8 - png_ptr->sig_bit.red;
  190093. int sg = 8 - png_ptr->sig_bit.green;
  190094. int sb = 8 - png_ptr->sig_bit.blue;
  190095. if (sr < 0 || sr > 8)
  190096. sr = 0;
  190097. if (sg < 0 || sg > 8)
  190098. sg = 0;
  190099. if (sb < 0 || sb > 8)
  190100. sb = 0;
  190101. for (i = 0; i < istop; i++)
  190102. {
  190103. png_ptr->palette[i].red >>= sr;
  190104. png_ptr->palette[i].green >>= sg;
  190105. png_ptr->palette[i].blue >>= sb;
  190106. }
  190107. }
  190108. #endif /* PNG_READ_SHIFT_SUPPORTED */
  190109. }
  190110. #if !defined(PNG_READ_GAMMA_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED) \
  190111. && !defined(PNG_READ_BACKGROUND_SUPPORTED)
  190112. if(png_ptr)
  190113. return;
  190114. #endif
  190115. }
  190116. /* Modify the info structure to reflect the transformations. The
  190117. * info should be updated so a PNG file could be written with it,
  190118. * assuming the transformations result in valid PNG data.
  190119. */
  190120. void /* PRIVATE */
  190121. png_read_transform_info(png_structp png_ptr, png_infop info_ptr)
  190122. {
  190123. png_debug(1, "in png_read_transform_info\n");
  190124. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190125. if (png_ptr->transformations & PNG_EXPAND)
  190126. {
  190127. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190128. {
  190129. if (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND_tRNS))
  190130. info_ptr->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  190131. else
  190132. info_ptr->color_type = PNG_COLOR_TYPE_RGB;
  190133. info_ptr->bit_depth = 8;
  190134. info_ptr->num_trans = 0;
  190135. }
  190136. else
  190137. {
  190138. if (png_ptr->num_trans)
  190139. {
  190140. if (png_ptr->transformations & PNG_EXPAND_tRNS)
  190141. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  190142. else
  190143. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  190144. }
  190145. if (info_ptr->bit_depth < 8)
  190146. info_ptr->bit_depth = 8;
  190147. info_ptr->num_trans = 0;
  190148. }
  190149. }
  190150. #endif
  190151. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190152. if (png_ptr->transformations & PNG_BACKGROUND)
  190153. {
  190154. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  190155. info_ptr->num_trans = 0;
  190156. info_ptr->background = png_ptr->background;
  190157. }
  190158. #endif
  190159. #if defined(PNG_READ_GAMMA_SUPPORTED)
  190160. if (png_ptr->transformations & PNG_GAMMA)
  190161. {
  190162. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190163. info_ptr->gamma = png_ptr->gamma;
  190164. #endif
  190165. #ifdef PNG_FIXED_POINT_SUPPORTED
  190166. info_ptr->int_gamma = png_ptr->int_gamma;
  190167. #endif
  190168. }
  190169. #endif
  190170. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  190171. if ((png_ptr->transformations & PNG_16_TO_8) && (info_ptr->bit_depth == 16))
  190172. info_ptr->bit_depth = 8;
  190173. #endif
  190174. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190175. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  190176. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  190177. #endif
  190178. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190179. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  190180. info_ptr->color_type &= ~PNG_COLOR_MASK_COLOR;
  190181. #endif
  190182. #if defined(PNG_READ_DITHER_SUPPORTED)
  190183. if (png_ptr->transformations & PNG_DITHER)
  190184. {
  190185. if (((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  190186. (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)) &&
  190187. png_ptr->palette_lookup && info_ptr->bit_depth == 8)
  190188. {
  190189. info_ptr->color_type = PNG_COLOR_TYPE_PALETTE;
  190190. }
  190191. }
  190192. #endif
  190193. #if defined(PNG_READ_PACK_SUPPORTED)
  190194. if ((png_ptr->transformations & PNG_PACK) && (info_ptr->bit_depth < 8))
  190195. info_ptr->bit_depth = 8;
  190196. #endif
  190197. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190198. info_ptr->channels = 1;
  190199. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  190200. info_ptr->channels = 3;
  190201. else
  190202. info_ptr->channels = 1;
  190203. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  190204. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  190205. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  190206. #endif
  190207. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  190208. info_ptr->channels++;
  190209. #if defined(PNG_READ_FILLER_SUPPORTED)
  190210. /* STRIP_ALPHA and FILLER allowed: MASK_ALPHA bit stripped above */
  190211. if ((png_ptr->transformations & PNG_FILLER) &&
  190212. ((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  190213. (info_ptr->color_type == PNG_COLOR_TYPE_GRAY)))
  190214. {
  190215. info_ptr->channels++;
  190216. /* if adding a true alpha channel not just filler */
  190217. #if !defined(PNG_1_0_X)
  190218. if (png_ptr->transformations & PNG_ADD_ALPHA)
  190219. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  190220. #endif
  190221. }
  190222. #endif
  190223. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) && \
  190224. defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  190225. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  190226. {
  190227. if(info_ptr->bit_depth < png_ptr->user_transform_depth)
  190228. info_ptr->bit_depth = png_ptr->user_transform_depth;
  190229. if(info_ptr->channels < png_ptr->user_transform_channels)
  190230. info_ptr->channels = png_ptr->user_transform_channels;
  190231. }
  190232. #endif
  190233. info_ptr->pixel_depth = (png_byte)(info_ptr->channels *
  190234. info_ptr->bit_depth);
  190235. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,info_ptr->width);
  190236. #if !defined(PNG_READ_EXPAND_SUPPORTED)
  190237. if(png_ptr)
  190238. return;
  190239. #endif
  190240. }
  190241. /* Transform the row. The order of transformations is significant,
  190242. * and is very touchy. If you add a transformation, take care to
  190243. * decide how it fits in with the other transformations here.
  190244. */
  190245. void /* PRIVATE */
  190246. png_do_read_transformations(png_structp png_ptr)
  190247. {
  190248. png_debug(1, "in png_do_read_transformations\n");
  190249. if (png_ptr->row_buf == NULL)
  190250. {
  190251. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  190252. char msg[50];
  190253. png_snprintf2(msg, 50,
  190254. "NULL row buffer for row %ld, pass %d", png_ptr->row_number,
  190255. png_ptr->pass);
  190256. png_error(png_ptr, msg);
  190257. #else
  190258. png_error(png_ptr, "NULL row buffer");
  190259. #endif
  190260. }
  190261. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190262. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  190263. /* Application has failed to call either png_read_start_image()
  190264. * or png_read_update_info() after setting transforms that expand
  190265. * pixels. This check added to libpng-1.2.19 */
  190266. #if (PNG_WARN_UNINITIALIZED_ROW==1)
  190267. png_error(png_ptr, "Uninitialized row");
  190268. #else
  190269. png_warning(png_ptr, "Uninitialized row");
  190270. #endif
  190271. #endif
  190272. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190273. if (png_ptr->transformations & PNG_EXPAND)
  190274. {
  190275. if (png_ptr->row_info.color_type == PNG_COLOR_TYPE_PALETTE)
  190276. {
  190277. png_do_expand_palette(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190278. png_ptr->palette, png_ptr->trans, png_ptr->num_trans);
  190279. }
  190280. else
  190281. {
  190282. if (png_ptr->num_trans &&
  190283. (png_ptr->transformations & PNG_EXPAND_tRNS))
  190284. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190285. &(png_ptr->trans_values));
  190286. else
  190287. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190288. NULL);
  190289. }
  190290. }
  190291. #endif
  190292. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  190293. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  190294. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190295. PNG_FLAG_FILLER_AFTER | (png_ptr->flags & PNG_FLAG_STRIP_ALPHA));
  190296. #endif
  190297. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190298. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  190299. {
  190300. int rgb_error =
  190301. png_do_rgb_to_gray(png_ptr, &(png_ptr->row_info), png_ptr->row_buf + 1);
  190302. if(rgb_error)
  190303. {
  190304. png_ptr->rgb_to_gray_status=1;
  190305. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  190306. PNG_RGB_TO_GRAY_WARN)
  190307. png_warning(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  190308. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  190309. PNG_RGB_TO_GRAY_ERR)
  190310. png_error(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  190311. }
  190312. }
  190313. #endif
  190314. /*
  190315. From Andreas Dilger e-mail to png-implement, 26 March 1998:
  190316. In most cases, the "simple transparency" should be done prior to doing
  190317. gray-to-RGB, or you will have to test 3x as many bytes to check if a
  190318. pixel is transparent. You would also need to make sure that the
  190319. transparency information is upgraded to RGB.
  190320. To summarize, the current flow is:
  190321. - Gray + simple transparency -> compare 1 or 2 gray bytes and composite
  190322. with background "in place" if transparent,
  190323. convert to RGB if necessary
  190324. - Gray + alpha -> composite with gray background and remove alpha bytes,
  190325. convert to RGB if necessary
  190326. To support RGB backgrounds for gray images we need:
  190327. - Gray + simple transparency -> convert to RGB + simple transparency, compare
  190328. 3 or 6 bytes and composite with background
  190329. "in place" if transparent (3x compare/pixel
  190330. compared to doing composite with gray bkgrnd)
  190331. - Gray + alpha -> convert to RGB + alpha, composite with background and
  190332. remove alpha bytes (3x float operations/pixel
  190333. compared with composite on gray background)
  190334. Greg's change will do this. The reason it wasn't done before is for
  190335. performance, as this increases the per-pixel operations. If we would check
  190336. in advance if the background was gray or RGB, and position the gray-to-RGB
  190337. transform appropriately, then it would save a lot of work/time.
  190338. */
  190339. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190340. /* if gray -> RGB, do so now only if background is non-gray; else do later
  190341. * for performance reasons */
  190342. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  190343. !(png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  190344. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190345. #endif
  190346. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190347. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190348. ((png_ptr->num_trans != 0 ) ||
  190349. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA)))
  190350. png_do_background(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190351. &(png_ptr->trans_values), &(png_ptr->background)
  190352. #if defined(PNG_READ_GAMMA_SUPPORTED)
  190353. , &(png_ptr->background_1),
  190354. png_ptr->gamma_table, png_ptr->gamma_from_1,
  190355. png_ptr->gamma_to_1, png_ptr->gamma_16_table,
  190356. png_ptr->gamma_16_from_1, png_ptr->gamma_16_to_1,
  190357. png_ptr->gamma_shift
  190358. #endif
  190359. );
  190360. #endif
  190361. #if defined(PNG_READ_GAMMA_SUPPORTED)
  190362. if ((png_ptr->transformations & PNG_GAMMA) &&
  190363. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190364. !((png_ptr->transformations & PNG_BACKGROUND) &&
  190365. ((png_ptr->num_trans != 0) ||
  190366. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA))) &&
  190367. #endif
  190368. (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE))
  190369. png_do_gamma(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190370. png_ptr->gamma_table, png_ptr->gamma_16_table,
  190371. png_ptr->gamma_shift);
  190372. #endif
  190373. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  190374. if (png_ptr->transformations & PNG_16_TO_8)
  190375. png_do_chop(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190376. #endif
  190377. #if defined(PNG_READ_DITHER_SUPPORTED)
  190378. if (png_ptr->transformations & PNG_DITHER)
  190379. {
  190380. png_do_dither((png_row_infop)&(png_ptr->row_info), png_ptr->row_buf + 1,
  190381. png_ptr->palette_lookup, png_ptr->dither_index);
  190382. if(png_ptr->row_info.rowbytes == (png_uint_32)0)
  190383. png_error(png_ptr, "png_do_dither returned rowbytes=0");
  190384. }
  190385. #endif
  190386. #if defined(PNG_READ_INVERT_SUPPORTED)
  190387. if (png_ptr->transformations & PNG_INVERT_MONO)
  190388. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190389. #endif
  190390. #if defined(PNG_READ_SHIFT_SUPPORTED)
  190391. if (png_ptr->transformations & PNG_SHIFT)
  190392. png_do_unshift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190393. &(png_ptr->shift));
  190394. #endif
  190395. #if defined(PNG_READ_PACK_SUPPORTED)
  190396. if (png_ptr->transformations & PNG_PACK)
  190397. png_do_unpack(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190398. #endif
  190399. #if defined(PNG_READ_BGR_SUPPORTED)
  190400. if (png_ptr->transformations & PNG_BGR)
  190401. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190402. #endif
  190403. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  190404. if (png_ptr->transformations & PNG_PACKSWAP)
  190405. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190406. #endif
  190407. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190408. /* if gray -> RGB, do so now only if we did not do so above */
  190409. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  190410. (png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  190411. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190412. #endif
  190413. #if defined(PNG_READ_FILLER_SUPPORTED)
  190414. if (png_ptr->transformations & PNG_FILLER)
  190415. png_do_read_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190416. (png_uint_32)png_ptr->filler, png_ptr->flags);
  190417. #endif
  190418. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  190419. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  190420. png_do_read_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190421. #endif
  190422. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  190423. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  190424. png_do_read_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190425. #endif
  190426. #if defined(PNG_READ_SWAP_SUPPORTED)
  190427. if (png_ptr->transformations & PNG_SWAP_BYTES)
  190428. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190429. #endif
  190430. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  190431. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  190432. {
  190433. if(png_ptr->read_user_transform_fn != NULL)
  190434. (*(png_ptr->read_user_transform_fn)) /* user read transform function */
  190435. (png_ptr, /* png_ptr */
  190436. &(png_ptr->row_info), /* row_info: */
  190437. /* png_uint_32 width; width of row */
  190438. /* png_uint_32 rowbytes; number of bytes in row */
  190439. /* png_byte color_type; color type of pixels */
  190440. /* png_byte bit_depth; bit depth of samples */
  190441. /* png_byte channels; number of channels (1-4) */
  190442. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  190443. png_ptr->row_buf + 1); /* start of pixel data for row */
  190444. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  190445. if(png_ptr->user_transform_depth)
  190446. png_ptr->row_info.bit_depth = png_ptr->user_transform_depth;
  190447. if(png_ptr->user_transform_channels)
  190448. png_ptr->row_info.channels = png_ptr->user_transform_channels;
  190449. #endif
  190450. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  190451. png_ptr->row_info.channels);
  190452. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  190453. png_ptr->row_info.width);
  190454. }
  190455. #endif
  190456. }
  190457. #if defined(PNG_READ_PACK_SUPPORTED)
  190458. /* Unpack pixels of 1, 2, or 4 bits per pixel into 1 byte per pixel,
  190459. * without changing the actual values. Thus, if you had a row with
  190460. * a bit depth of 1, you would end up with bytes that only contained
  190461. * the numbers 0 or 1. If you would rather they contain 0 and 255, use
  190462. * png_do_shift() after this.
  190463. */
  190464. void /* PRIVATE */
  190465. png_do_unpack(png_row_infop row_info, png_bytep row)
  190466. {
  190467. png_debug(1, "in png_do_unpack\n");
  190468. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190469. if (row != NULL && row_info != NULL && row_info->bit_depth < 8)
  190470. #else
  190471. if (row_info->bit_depth < 8)
  190472. #endif
  190473. {
  190474. png_uint_32 i;
  190475. png_uint_32 row_width=row_info->width;
  190476. switch (row_info->bit_depth)
  190477. {
  190478. case 1:
  190479. {
  190480. png_bytep sp = row + (png_size_t)((row_width - 1) >> 3);
  190481. png_bytep dp = row + (png_size_t)row_width - 1;
  190482. png_uint_32 shift = 7 - (int)((row_width + 7) & 0x07);
  190483. for (i = 0; i < row_width; i++)
  190484. {
  190485. *dp = (png_byte)((*sp >> shift) & 0x01);
  190486. if (shift == 7)
  190487. {
  190488. shift = 0;
  190489. sp--;
  190490. }
  190491. else
  190492. shift++;
  190493. dp--;
  190494. }
  190495. break;
  190496. }
  190497. case 2:
  190498. {
  190499. png_bytep sp = row + (png_size_t)((row_width - 1) >> 2);
  190500. png_bytep dp = row + (png_size_t)row_width - 1;
  190501. png_uint_32 shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  190502. for (i = 0; i < row_width; i++)
  190503. {
  190504. *dp = (png_byte)((*sp >> shift) & 0x03);
  190505. if (shift == 6)
  190506. {
  190507. shift = 0;
  190508. sp--;
  190509. }
  190510. else
  190511. shift += 2;
  190512. dp--;
  190513. }
  190514. break;
  190515. }
  190516. case 4:
  190517. {
  190518. png_bytep sp = row + (png_size_t)((row_width - 1) >> 1);
  190519. png_bytep dp = row + (png_size_t)row_width - 1;
  190520. png_uint_32 shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  190521. for (i = 0; i < row_width; i++)
  190522. {
  190523. *dp = (png_byte)((*sp >> shift) & 0x0f);
  190524. if (shift == 4)
  190525. {
  190526. shift = 0;
  190527. sp--;
  190528. }
  190529. else
  190530. shift = 4;
  190531. dp--;
  190532. }
  190533. break;
  190534. }
  190535. }
  190536. row_info->bit_depth = 8;
  190537. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  190538. row_info->rowbytes = row_width * row_info->channels;
  190539. }
  190540. }
  190541. #endif
  190542. #if defined(PNG_READ_SHIFT_SUPPORTED)
  190543. /* Reverse the effects of png_do_shift. This routine merely shifts the
  190544. * pixels back to their significant bits values. Thus, if you have
  190545. * a row of bit depth 8, but only 5 are significant, this will shift
  190546. * the values back to 0 through 31.
  190547. */
  190548. void /* PRIVATE */
  190549. png_do_unshift(png_row_infop row_info, png_bytep row, png_color_8p sig_bits)
  190550. {
  190551. png_debug(1, "in png_do_unshift\n");
  190552. if (
  190553. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190554. row != NULL && row_info != NULL && sig_bits != NULL &&
  190555. #endif
  190556. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  190557. {
  190558. int shift[4];
  190559. int channels = 0;
  190560. int c;
  190561. png_uint_16 value = 0;
  190562. png_uint_32 row_width = row_info->width;
  190563. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  190564. {
  190565. shift[channels++] = row_info->bit_depth - sig_bits->red;
  190566. shift[channels++] = row_info->bit_depth - sig_bits->green;
  190567. shift[channels++] = row_info->bit_depth - sig_bits->blue;
  190568. }
  190569. else
  190570. {
  190571. shift[channels++] = row_info->bit_depth - sig_bits->gray;
  190572. }
  190573. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  190574. {
  190575. shift[channels++] = row_info->bit_depth - sig_bits->alpha;
  190576. }
  190577. for (c = 0; c < channels; c++)
  190578. {
  190579. if (shift[c] <= 0)
  190580. shift[c] = 0;
  190581. else
  190582. value = 1;
  190583. }
  190584. if (!value)
  190585. return;
  190586. switch (row_info->bit_depth)
  190587. {
  190588. case 2:
  190589. {
  190590. png_bytep bp;
  190591. png_uint_32 i;
  190592. png_uint_32 istop = row_info->rowbytes;
  190593. for (bp = row, i = 0; i < istop; i++)
  190594. {
  190595. *bp >>= 1;
  190596. *bp++ &= 0x55;
  190597. }
  190598. break;
  190599. }
  190600. case 4:
  190601. {
  190602. png_bytep bp = row;
  190603. png_uint_32 i;
  190604. png_uint_32 istop = row_info->rowbytes;
  190605. png_byte mask = (png_byte)((((int)0xf0 >> shift[0]) & (int)0xf0) |
  190606. (png_byte)((int)0xf >> shift[0]));
  190607. for (i = 0; i < istop; i++)
  190608. {
  190609. *bp >>= shift[0];
  190610. *bp++ &= mask;
  190611. }
  190612. break;
  190613. }
  190614. case 8:
  190615. {
  190616. png_bytep bp = row;
  190617. png_uint_32 i;
  190618. png_uint_32 istop = row_width * channels;
  190619. for (i = 0; i < istop; i++)
  190620. {
  190621. *bp++ >>= shift[i%channels];
  190622. }
  190623. break;
  190624. }
  190625. case 16:
  190626. {
  190627. png_bytep bp = row;
  190628. png_uint_32 i;
  190629. png_uint_32 istop = channels * row_width;
  190630. for (i = 0; i < istop; i++)
  190631. {
  190632. value = (png_uint_16)((*bp << 8) + *(bp + 1));
  190633. value >>= shift[i%channels];
  190634. *bp++ = (png_byte)(value >> 8);
  190635. *bp++ = (png_byte)(value & 0xff);
  190636. }
  190637. break;
  190638. }
  190639. }
  190640. }
  190641. }
  190642. #endif
  190643. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  190644. /* chop rows of bit depth 16 down to 8 */
  190645. void /* PRIVATE */
  190646. png_do_chop(png_row_infop row_info, png_bytep row)
  190647. {
  190648. png_debug(1, "in png_do_chop\n");
  190649. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190650. if (row != NULL && row_info != NULL && row_info->bit_depth == 16)
  190651. #else
  190652. if (row_info->bit_depth == 16)
  190653. #endif
  190654. {
  190655. png_bytep sp = row;
  190656. png_bytep dp = row;
  190657. png_uint_32 i;
  190658. png_uint_32 istop = row_info->width * row_info->channels;
  190659. for (i = 0; i<istop; i++, sp += 2, dp++)
  190660. {
  190661. #if defined(PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED)
  190662. /* This does a more accurate scaling of the 16-bit color
  190663. * value, rather than a simple low-byte truncation.
  190664. *
  190665. * What the ideal calculation should be:
  190666. * *dp = (((((png_uint_32)(*sp) << 8) |
  190667. * (png_uint_32)(*(sp + 1))) * 255 + 127) / (png_uint_32)65535L;
  190668. *
  190669. * GRR: no, I think this is what it really should be:
  190670. * *dp = (((((png_uint_32)(*sp) << 8) |
  190671. * (png_uint_32)(*(sp + 1))) + 128L) / (png_uint_32)257L;
  190672. *
  190673. * GRR: here's the exact calculation with shifts:
  190674. * temp = (((png_uint_32)(*sp) << 8) | (png_uint_32)(*(sp + 1))) + 128L;
  190675. * *dp = (temp - (temp >> 8)) >> 8;
  190676. *
  190677. * Approximate calculation with shift/add instead of multiply/divide:
  190678. * *dp = ((((png_uint_32)(*sp) << 8) |
  190679. * (png_uint_32)((int)(*(sp + 1)) - *sp)) + 128) >> 8;
  190680. *
  190681. * What we actually do to avoid extra shifting and conversion:
  190682. */
  190683. *dp = *sp + ((((int)(*(sp + 1)) - *sp) > 128) ? 1 : 0);
  190684. #else
  190685. /* Simply discard the low order byte */
  190686. *dp = *sp;
  190687. #endif
  190688. }
  190689. row_info->bit_depth = 8;
  190690. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  190691. row_info->rowbytes = row_info->width * row_info->channels;
  190692. }
  190693. }
  190694. #endif
  190695. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  190696. void /* PRIVATE */
  190697. png_do_read_swap_alpha(png_row_infop row_info, png_bytep row)
  190698. {
  190699. png_debug(1, "in png_do_read_swap_alpha\n");
  190700. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190701. if (row != NULL && row_info != NULL)
  190702. #endif
  190703. {
  190704. png_uint_32 row_width = row_info->width;
  190705. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  190706. {
  190707. /* This converts from RGBA to ARGB */
  190708. if (row_info->bit_depth == 8)
  190709. {
  190710. png_bytep sp = row + row_info->rowbytes;
  190711. png_bytep dp = sp;
  190712. png_byte save;
  190713. png_uint_32 i;
  190714. for (i = 0; i < row_width; i++)
  190715. {
  190716. save = *(--sp);
  190717. *(--dp) = *(--sp);
  190718. *(--dp) = *(--sp);
  190719. *(--dp) = *(--sp);
  190720. *(--dp) = save;
  190721. }
  190722. }
  190723. /* This converts from RRGGBBAA to AARRGGBB */
  190724. else
  190725. {
  190726. png_bytep sp = row + row_info->rowbytes;
  190727. png_bytep dp = sp;
  190728. png_byte save[2];
  190729. png_uint_32 i;
  190730. for (i = 0; i < row_width; i++)
  190731. {
  190732. save[0] = *(--sp);
  190733. save[1] = *(--sp);
  190734. *(--dp) = *(--sp);
  190735. *(--dp) = *(--sp);
  190736. *(--dp) = *(--sp);
  190737. *(--dp) = *(--sp);
  190738. *(--dp) = *(--sp);
  190739. *(--dp) = *(--sp);
  190740. *(--dp) = save[0];
  190741. *(--dp) = save[1];
  190742. }
  190743. }
  190744. }
  190745. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  190746. {
  190747. /* This converts from GA to AG */
  190748. if (row_info->bit_depth == 8)
  190749. {
  190750. png_bytep sp = row + row_info->rowbytes;
  190751. png_bytep dp = sp;
  190752. png_byte save;
  190753. png_uint_32 i;
  190754. for (i = 0; i < row_width; i++)
  190755. {
  190756. save = *(--sp);
  190757. *(--dp) = *(--sp);
  190758. *(--dp) = save;
  190759. }
  190760. }
  190761. /* This converts from GGAA to AAGG */
  190762. else
  190763. {
  190764. png_bytep sp = row + row_info->rowbytes;
  190765. png_bytep dp = sp;
  190766. png_byte save[2];
  190767. png_uint_32 i;
  190768. for (i = 0; i < row_width; i++)
  190769. {
  190770. save[0] = *(--sp);
  190771. save[1] = *(--sp);
  190772. *(--dp) = *(--sp);
  190773. *(--dp) = *(--sp);
  190774. *(--dp) = save[0];
  190775. *(--dp) = save[1];
  190776. }
  190777. }
  190778. }
  190779. }
  190780. }
  190781. #endif
  190782. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  190783. void /* PRIVATE */
  190784. png_do_read_invert_alpha(png_row_infop row_info, png_bytep row)
  190785. {
  190786. png_debug(1, "in png_do_read_invert_alpha\n");
  190787. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190788. if (row != NULL && row_info != NULL)
  190789. #endif
  190790. {
  190791. png_uint_32 row_width = row_info->width;
  190792. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  190793. {
  190794. /* This inverts the alpha channel in RGBA */
  190795. if (row_info->bit_depth == 8)
  190796. {
  190797. png_bytep sp = row + row_info->rowbytes;
  190798. png_bytep dp = sp;
  190799. png_uint_32 i;
  190800. for (i = 0; i < row_width; i++)
  190801. {
  190802. *(--dp) = (png_byte)(255 - *(--sp));
  190803. /* This does nothing:
  190804. *(--dp) = *(--sp);
  190805. *(--dp) = *(--sp);
  190806. *(--dp) = *(--sp);
  190807. We can replace it with:
  190808. */
  190809. sp-=3;
  190810. dp=sp;
  190811. }
  190812. }
  190813. /* This inverts the alpha channel in RRGGBBAA */
  190814. else
  190815. {
  190816. png_bytep sp = row + row_info->rowbytes;
  190817. png_bytep dp = sp;
  190818. png_uint_32 i;
  190819. for (i = 0; i < row_width; i++)
  190820. {
  190821. *(--dp) = (png_byte)(255 - *(--sp));
  190822. *(--dp) = (png_byte)(255 - *(--sp));
  190823. /* This does nothing:
  190824. *(--dp) = *(--sp);
  190825. *(--dp) = *(--sp);
  190826. *(--dp) = *(--sp);
  190827. *(--dp) = *(--sp);
  190828. *(--dp) = *(--sp);
  190829. *(--dp) = *(--sp);
  190830. We can replace it with:
  190831. */
  190832. sp-=6;
  190833. dp=sp;
  190834. }
  190835. }
  190836. }
  190837. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  190838. {
  190839. /* This inverts the alpha channel in GA */
  190840. if (row_info->bit_depth == 8)
  190841. {
  190842. png_bytep sp = row + row_info->rowbytes;
  190843. png_bytep dp = sp;
  190844. png_uint_32 i;
  190845. for (i = 0; i < row_width; i++)
  190846. {
  190847. *(--dp) = (png_byte)(255 - *(--sp));
  190848. *(--dp) = *(--sp);
  190849. }
  190850. }
  190851. /* This inverts the alpha channel in GGAA */
  190852. else
  190853. {
  190854. png_bytep sp = row + row_info->rowbytes;
  190855. png_bytep dp = sp;
  190856. png_uint_32 i;
  190857. for (i = 0; i < row_width; i++)
  190858. {
  190859. *(--dp) = (png_byte)(255 - *(--sp));
  190860. *(--dp) = (png_byte)(255 - *(--sp));
  190861. /*
  190862. *(--dp) = *(--sp);
  190863. *(--dp) = *(--sp);
  190864. */
  190865. sp-=2;
  190866. dp=sp;
  190867. }
  190868. }
  190869. }
  190870. }
  190871. }
  190872. #endif
  190873. #if defined(PNG_READ_FILLER_SUPPORTED)
  190874. /* Add filler channel if we have RGB color */
  190875. void /* PRIVATE */
  190876. png_do_read_filler(png_row_infop row_info, png_bytep row,
  190877. png_uint_32 filler, png_uint_32 flags)
  190878. {
  190879. png_uint_32 i;
  190880. png_uint_32 row_width = row_info->width;
  190881. png_byte hi_filler = (png_byte)((filler>>8) & 0xff);
  190882. png_byte lo_filler = (png_byte)(filler & 0xff);
  190883. png_debug(1, "in png_do_read_filler\n");
  190884. if (
  190885. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190886. row != NULL && row_info != NULL &&
  190887. #endif
  190888. row_info->color_type == PNG_COLOR_TYPE_GRAY)
  190889. {
  190890. if(row_info->bit_depth == 8)
  190891. {
  190892. /* This changes the data from G to GX */
  190893. if (flags & PNG_FLAG_FILLER_AFTER)
  190894. {
  190895. png_bytep sp = row + (png_size_t)row_width;
  190896. png_bytep dp = sp + (png_size_t)row_width;
  190897. for (i = 1; i < row_width; i++)
  190898. {
  190899. *(--dp) = lo_filler;
  190900. *(--dp) = *(--sp);
  190901. }
  190902. *(--dp) = lo_filler;
  190903. row_info->channels = 2;
  190904. row_info->pixel_depth = 16;
  190905. row_info->rowbytes = row_width * 2;
  190906. }
  190907. /* This changes the data from G to XG */
  190908. else
  190909. {
  190910. png_bytep sp = row + (png_size_t)row_width;
  190911. png_bytep dp = sp + (png_size_t)row_width;
  190912. for (i = 0; i < row_width; i++)
  190913. {
  190914. *(--dp) = *(--sp);
  190915. *(--dp) = lo_filler;
  190916. }
  190917. row_info->channels = 2;
  190918. row_info->pixel_depth = 16;
  190919. row_info->rowbytes = row_width * 2;
  190920. }
  190921. }
  190922. else if(row_info->bit_depth == 16)
  190923. {
  190924. /* This changes the data from GG to GGXX */
  190925. if (flags & PNG_FLAG_FILLER_AFTER)
  190926. {
  190927. png_bytep sp = row + (png_size_t)row_width * 2;
  190928. png_bytep dp = sp + (png_size_t)row_width * 2;
  190929. for (i = 1; i < row_width; i++)
  190930. {
  190931. *(--dp) = hi_filler;
  190932. *(--dp) = lo_filler;
  190933. *(--dp) = *(--sp);
  190934. *(--dp) = *(--sp);
  190935. }
  190936. *(--dp) = hi_filler;
  190937. *(--dp) = lo_filler;
  190938. row_info->channels = 2;
  190939. row_info->pixel_depth = 32;
  190940. row_info->rowbytes = row_width * 4;
  190941. }
  190942. /* This changes the data from GG to XXGG */
  190943. else
  190944. {
  190945. png_bytep sp = row + (png_size_t)row_width * 2;
  190946. png_bytep dp = sp + (png_size_t)row_width * 2;
  190947. for (i = 0; i < row_width; i++)
  190948. {
  190949. *(--dp) = *(--sp);
  190950. *(--dp) = *(--sp);
  190951. *(--dp) = hi_filler;
  190952. *(--dp) = lo_filler;
  190953. }
  190954. row_info->channels = 2;
  190955. row_info->pixel_depth = 32;
  190956. row_info->rowbytes = row_width * 4;
  190957. }
  190958. }
  190959. } /* COLOR_TYPE == GRAY */
  190960. else if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  190961. {
  190962. if(row_info->bit_depth == 8)
  190963. {
  190964. /* This changes the data from RGB to RGBX */
  190965. if (flags & PNG_FLAG_FILLER_AFTER)
  190966. {
  190967. png_bytep sp = row + (png_size_t)row_width * 3;
  190968. png_bytep dp = sp + (png_size_t)row_width;
  190969. for (i = 1; i < row_width; i++)
  190970. {
  190971. *(--dp) = lo_filler;
  190972. *(--dp) = *(--sp);
  190973. *(--dp) = *(--sp);
  190974. *(--dp) = *(--sp);
  190975. }
  190976. *(--dp) = lo_filler;
  190977. row_info->channels = 4;
  190978. row_info->pixel_depth = 32;
  190979. row_info->rowbytes = row_width * 4;
  190980. }
  190981. /* This changes the data from RGB to XRGB */
  190982. else
  190983. {
  190984. png_bytep sp = row + (png_size_t)row_width * 3;
  190985. png_bytep dp = sp + (png_size_t)row_width;
  190986. for (i = 0; i < row_width; i++)
  190987. {
  190988. *(--dp) = *(--sp);
  190989. *(--dp) = *(--sp);
  190990. *(--dp) = *(--sp);
  190991. *(--dp) = lo_filler;
  190992. }
  190993. row_info->channels = 4;
  190994. row_info->pixel_depth = 32;
  190995. row_info->rowbytes = row_width * 4;
  190996. }
  190997. }
  190998. else if(row_info->bit_depth == 16)
  190999. {
  191000. /* This changes the data from RRGGBB to RRGGBBXX */
  191001. if (flags & PNG_FLAG_FILLER_AFTER)
  191002. {
  191003. png_bytep sp = row + (png_size_t)row_width * 6;
  191004. png_bytep dp = sp + (png_size_t)row_width * 2;
  191005. for (i = 1; i < row_width; i++)
  191006. {
  191007. *(--dp) = hi_filler;
  191008. *(--dp) = lo_filler;
  191009. *(--dp) = *(--sp);
  191010. *(--dp) = *(--sp);
  191011. *(--dp) = *(--sp);
  191012. *(--dp) = *(--sp);
  191013. *(--dp) = *(--sp);
  191014. *(--dp) = *(--sp);
  191015. }
  191016. *(--dp) = hi_filler;
  191017. *(--dp) = lo_filler;
  191018. row_info->channels = 4;
  191019. row_info->pixel_depth = 64;
  191020. row_info->rowbytes = row_width * 8;
  191021. }
  191022. /* This changes the data from RRGGBB to XXRRGGBB */
  191023. else
  191024. {
  191025. png_bytep sp = row + (png_size_t)row_width * 6;
  191026. png_bytep dp = sp + (png_size_t)row_width * 2;
  191027. for (i = 0; i < row_width; i++)
  191028. {
  191029. *(--dp) = *(--sp);
  191030. *(--dp) = *(--sp);
  191031. *(--dp) = *(--sp);
  191032. *(--dp) = *(--sp);
  191033. *(--dp) = *(--sp);
  191034. *(--dp) = *(--sp);
  191035. *(--dp) = hi_filler;
  191036. *(--dp) = lo_filler;
  191037. }
  191038. row_info->channels = 4;
  191039. row_info->pixel_depth = 64;
  191040. row_info->rowbytes = row_width * 8;
  191041. }
  191042. }
  191043. } /* COLOR_TYPE == RGB */
  191044. }
  191045. #endif
  191046. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191047. /* expand grayscale files to RGB, with or without alpha */
  191048. void /* PRIVATE */
  191049. png_do_gray_to_rgb(png_row_infop row_info, png_bytep row)
  191050. {
  191051. png_uint_32 i;
  191052. png_uint_32 row_width = row_info->width;
  191053. png_debug(1, "in png_do_gray_to_rgb\n");
  191054. if (row_info->bit_depth >= 8 &&
  191055. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191056. row != NULL && row_info != NULL &&
  191057. #endif
  191058. !(row_info->color_type & PNG_COLOR_MASK_COLOR))
  191059. {
  191060. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  191061. {
  191062. if (row_info->bit_depth == 8)
  191063. {
  191064. png_bytep sp = row + (png_size_t)row_width - 1;
  191065. png_bytep dp = sp + (png_size_t)row_width * 2;
  191066. for (i = 0; i < row_width; i++)
  191067. {
  191068. *(dp--) = *sp;
  191069. *(dp--) = *sp;
  191070. *(dp--) = *(sp--);
  191071. }
  191072. }
  191073. else
  191074. {
  191075. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  191076. png_bytep dp = sp + (png_size_t)row_width * 4;
  191077. for (i = 0; i < row_width; i++)
  191078. {
  191079. *(dp--) = *sp;
  191080. *(dp--) = *(sp - 1);
  191081. *(dp--) = *sp;
  191082. *(dp--) = *(sp - 1);
  191083. *(dp--) = *(sp--);
  191084. *(dp--) = *(sp--);
  191085. }
  191086. }
  191087. }
  191088. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191089. {
  191090. if (row_info->bit_depth == 8)
  191091. {
  191092. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  191093. png_bytep dp = sp + (png_size_t)row_width * 2;
  191094. for (i = 0; i < row_width; i++)
  191095. {
  191096. *(dp--) = *(sp--);
  191097. *(dp--) = *sp;
  191098. *(dp--) = *sp;
  191099. *(dp--) = *(sp--);
  191100. }
  191101. }
  191102. else
  191103. {
  191104. png_bytep sp = row + (png_size_t)row_width * 4 - 1;
  191105. png_bytep dp = sp + (png_size_t)row_width * 4;
  191106. for (i = 0; i < row_width; i++)
  191107. {
  191108. *(dp--) = *(sp--);
  191109. *(dp--) = *(sp--);
  191110. *(dp--) = *sp;
  191111. *(dp--) = *(sp - 1);
  191112. *(dp--) = *sp;
  191113. *(dp--) = *(sp - 1);
  191114. *(dp--) = *(sp--);
  191115. *(dp--) = *(sp--);
  191116. }
  191117. }
  191118. }
  191119. row_info->channels += (png_byte)2;
  191120. row_info->color_type |= PNG_COLOR_MASK_COLOR;
  191121. row_info->pixel_depth = (png_byte)(row_info->channels *
  191122. row_info->bit_depth);
  191123. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  191124. }
  191125. }
  191126. #endif
  191127. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  191128. /* reduce RGB files to grayscale, with or without alpha
  191129. * using the equation given in Poynton's ColorFAQ at
  191130. * <http://www.inforamp.net/~poynton/>
  191131. * Copyright (c) 1998-01-04 Charles Poynton poynton at inforamp.net
  191132. *
  191133. * Y = 0.212671 * R + 0.715160 * G + 0.072169 * B
  191134. *
  191135. * We approximate this with
  191136. *
  191137. * Y = 0.21268 * R + 0.7151 * G + 0.07217 * B
  191138. *
  191139. * which can be expressed with integers as
  191140. *
  191141. * Y = (6969 * R + 23434 * G + 2365 * B)/32768
  191142. *
  191143. * The calculation is to be done in a linear colorspace.
  191144. *
  191145. * Other integer coefficents can be used via png_set_rgb_to_gray().
  191146. */
  191147. int /* PRIVATE */
  191148. png_do_rgb_to_gray(png_structp png_ptr, png_row_infop row_info, png_bytep row)
  191149. {
  191150. png_uint_32 i;
  191151. png_uint_32 row_width = row_info->width;
  191152. int rgb_error = 0;
  191153. png_debug(1, "in png_do_rgb_to_gray\n");
  191154. if (
  191155. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191156. row != NULL && row_info != NULL &&
  191157. #endif
  191158. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  191159. {
  191160. png_uint_32 rc = png_ptr->rgb_to_gray_red_coeff;
  191161. png_uint_32 gc = png_ptr->rgb_to_gray_green_coeff;
  191162. png_uint_32 bc = png_ptr->rgb_to_gray_blue_coeff;
  191163. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  191164. {
  191165. if (row_info->bit_depth == 8)
  191166. {
  191167. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  191168. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  191169. {
  191170. png_bytep sp = row;
  191171. png_bytep dp = row;
  191172. for (i = 0; i < row_width; i++)
  191173. {
  191174. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  191175. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  191176. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  191177. if(red != green || red != blue)
  191178. {
  191179. rgb_error |= 1;
  191180. *(dp++) = png_ptr->gamma_from_1[
  191181. (rc*red+gc*green+bc*blue)>>15];
  191182. }
  191183. else
  191184. *(dp++) = *(sp-1);
  191185. }
  191186. }
  191187. else
  191188. #endif
  191189. {
  191190. png_bytep sp = row;
  191191. png_bytep dp = row;
  191192. for (i = 0; i < row_width; i++)
  191193. {
  191194. png_byte red = *(sp++);
  191195. png_byte green = *(sp++);
  191196. png_byte blue = *(sp++);
  191197. if(red != green || red != blue)
  191198. {
  191199. rgb_error |= 1;
  191200. *(dp++) = (png_byte)((rc*red+gc*green+bc*blue)>>15);
  191201. }
  191202. else
  191203. *(dp++) = *(sp-1);
  191204. }
  191205. }
  191206. }
  191207. else /* RGB bit_depth == 16 */
  191208. {
  191209. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  191210. if (png_ptr->gamma_16_to_1 != NULL &&
  191211. png_ptr->gamma_16_from_1 != NULL)
  191212. {
  191213. png_bytep sp = row;
  191214. png_bytep dp = row;
  191215. for (i = 0; i < row_width; i++)
  191216. {
  191217. png_uint_16 red, green, blue, w;
  191218. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191219. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191220. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191221. if(red == green && red == blue)
  191222. w = red;
  191223. else
  191224. {
  191225. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  191226. png_ptr->gamma_shift][red>>8];
  191227. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  191228. png_ptr->gamma_shift][green>>8];
  191229. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  191230. png_ptr->gamma_shift][blue>>8];
  191231. png_uint_16 gray16 = (png_uint_16)((rc*red_1 + gc*green_1
  191232. + bc*blue_1)>>15);
  191233. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  191234. png_ptr->gamma_shift][gray16 >> 8];
  191235. rgb_error |= 1;
  191236. }
  191237. *(dp++) = (png_byte)((w>>8) & 0xff);
  191238. *(dp++) = (png_byte)(w & 0xff);
  191239. }
  191240. }
  191241. else
  191242. #endif
  191243. {
  191244. png_bytep sp = row;
  191245. png_bytep dp = row;
  191246. for (i = 0; i < row_width; i++)
  191247. {
  191248. png_uint_16 red, green, blue, gray16;
  191249. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191250. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191251. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191252. if(red != green || red != blue)
  191253. rgb_error |= 1;
  191254. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  191255. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  191256. *(dp++) = (png_byte)(gray16 & 0xff);
  191257. }
  191258. }
  191259. }
  191260. }
  191261. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191262. {
  191263. if (row_info->bit_depth == 8)
  191264. {
  191265. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  191266. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  191267. {
  191268. png_bytep sp = row;
  191269. png_bytep dp = row;
  191270. for (i = 0; i < row_width; i++)
  191271. {
  191272. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  191273. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  191274. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  191275. if(red != green || red != blue)
  191276. rgb_error |= 1;
  191277. *(dp++) = png_ptr->gamma_from_1
  191278. [(rc*red + gc*green + bc*blue)>>15];
  191279. *(dp++) = *(sp++); /* alpha */
  191280. }
  191281. }
  191282. else
  191283. #endif
  191284. {
  191285. png_bytep sp = row;
  191286. png_bytep dp = row;
  191287. for (i = 0; i < row_width; i++)
  191288. {
  191289. png_byte red = *(sp++);
  191290. png_byte green = *(sp++);
  191291. png_byte blue = *(sp++);
  191292. if(red != green || red != blue)
  191293. rgb_error |= 1;
  191294. *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15);
  191295. *(dp++) = *(sp++); /* alpha */
  191296. }
  191297. }
  191298. }
  191299. else /* RGBA bit_depth == 16 */
  191300. {
  191301. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  191302. if (png_ptr->gamma_16_to_1 != NULL &&
  191303. png_ptr->gamma_16_from_1 != NULL)
  191304. {
  191305. png_bytep sp = row;
  191306. png_bytep dp = row;
  191307. for (i = 0; i < row_width; i++)
  191308. {
  191309. png_uint_16 red, green, blue, w;
  191310. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191311. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191312. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191313. if(red == green && red == blue)
  191314. w = red;
  191315. else
  191316. {
  191317. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  191318. png_ptr->gamma_shift][red>>8];
  191319. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  191320. png_ptr->gamma_shift][green>>8];
  191321. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  191322. png_ptr->gamma_shift][blue>>8];
  191323. png_uint_16 gray16 = (png_uint_16)((rc * red_1
  191324. + gc * green_1 + bc * blue_1)>>15);
  191325. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  191326. png_ptr->gamma_shift][gray16 >> 8];
  191327. rgb_error |= 1;
  191328. }
  191329. *(dp++) = (png_byte)((w>>8) & 0xff);
  191330. *(dp++) = (png_byte)(w & 0xff);
  191331. *(dp++) = *(sp++); /* alpha */
  191332. *(dp++) = *(sp++);
  191333. }
  191334. }
  191335. else
  191336. #endif
  191337. {
  191338. png_bytep sp = row;
  191339. png_bytep dp = row;
  191340. for (i = 0; i < row_width; i++)
  191341. {
  191342. png_uint_16 red, green, blue, gray16;
  191343. red = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  191344. green = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  191345. blue = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  191346. if(red != green || red != blue)
  191347. rgb_error |= 1;
  191348. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  191349. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  191350. *(dp++) = (png_byte)(gray16 & 0xff);
  191351. *(dp++) = *(sp++); /* alpha */
  191352. *(dp++) = *(sp++);
  191353. }
  191354. }
  191355. }
  191356. }
  191357. row_info->channels -= (png_byte)2;
  191358. row_info->color_type &= ~PNG_COLOR_MASK_COLOR;
  191359. row_info->pixel_depth = (png_byte)(row_info->channels *
  191360. row_info->bit_depth);
  191361. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  191362. }
  191363. return rgb_error;
  191364. }
  191365. #endif
  191366. /* Build a grayscale palette. Palette is assumed to be 1 << bit_depth
  191367. * large of png_color. This lets grayscale images be treated as
  191368. * paletted. Most useful for gamma correction and simplification
  191369. * of code.
  191370. */
  191371. void PNGAPI
  191372. png_build_grayscale_palette(int bit_depth, png_colorp palette)
  191373. {
  191374. int num_palette;
  191375. int color_inc;
  191376. int i;
  191377. int v;
  191378. png_debug(1, "in png_do_build_grayscale_palette\n");
  191379. if (palette == NULL)
  191380. return;
  191381. switch (bit_depth)
  191382. {
  191383. case 1:
  191384. num_palette = 2;
  191385. color_inc = 0xff;
  191386. break;
  191387. case 2:
  191388. num_palette = 4;
  191389. color_inc = 0x55;
  191390. break;
  191391. case 4:
  191392. num_palette = 16;
  191393. color_inc = 0x11;
  191394. break;
  191395. case 8:
  191396. num_palette = 256;
  191397. color_inc = 1;
  191398. break;
  191399. default:
  191400. num_palette = 0;
  191401. color_inc = 0;
  191402. break;
  191403. }
  191404. for (i = 0, v = 0; i < num_palette; i++, v += color_inc)
  191405. {
  191406. palette[i].red = (png_byte)v;
  191407. palette[i].green = (png_byte)v;
  191408. palette[i].blue = (png_byte)v;
  191409. }
  191410. }
  191411. /* This function is currently unused. Do we really need it? */
  191412. #if defined(PNG_READ_DITHER_SUPPORTED) && defined(PNG_CORRECT_PALETTE_SUPPORTED)
  191413. void /* PRIVATE */
  191414. png_correct_palette(png_structp png_ptr, png_colorp palette,
  191415. int num_palette)
  191416. {
  191417. png_debug(1, "in png_correct_palette\n");
  191418. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  191419. defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  191420. if (png_ptr->transformations & (PNG_GAMMA | PNG_BACKGROUND))
  191421. {
  191422. png_color back, back_1;
  191423. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  191424. {
  191425. back.red = png_ptr->gamma_table[png_ptr->background.red];
  191426. back.green = png_ptr->gamma_table[png_ptr->background.green];
  191427. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  191428. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  191429. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  191430. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  191431. }
  191432. else
  191433. {
  191434. double g;
  191435. g = 1.0 / (png_ptr->background_gamma * png_ptr->screen_gamma);
  191436. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_SCREEN ||
  191437. fabs(g - 1.0) < PNG_GAMMA_THRESHOLD)
  191438. {
  191439. back.red = png_ptr->background.red;
  191440. back.green = png_ptr->background.green;
  191441. back.blue = png_ptr->background.blue;
  191442. }
  191443. else
  191444. {
  191445. back.red =
  191446. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  191447. 255.0 + 0.5);
  191448. back.green =
  191449. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  191450. 255.0 + 0.5);
  191451. back.blue =
  191452. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  191453. 255.0 + 0.5);
  191454. }
  191455. g = 1.0 / png_ptr->background_gamma;
  191456. back_1.red =
  191457. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  191458. 255.0 + 0.5);
  191459. back_1.green =
  191460. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  191461. 255.0 + 0.5);
  191462. back_1.blue =
  191463. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  191464. 255.0 + 0.5);
  191465. }
  191466. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191467. {
  191468. png_uint_32 i;
  191469. for (i = 0; i < (png_uint_32)num_palette; i++)
  191470. {
  191471. if (i < png_ptr->num_trans && png_ptr->trans[i] == 0)
  191472. {
  191473. palette[i] = back;
  191474. }
  191475. else if (i < png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  191476. {
  191477. png_byte v, w;
  191478. v = png_ptr->gamma_to_1[png_ptr->palette[i].red];
  191479. png_composite(w, v, png_ptr->trans[i], back_1.red);
  191480. palette[i].red = png_ptr->gamma_from_1[w];
  191481. v = png_ptr->gamma_to_1[png_ptr->palette[i].green];
  191482. png_composite(w, v, png_ptr->trans[i], back_1.green);
  191483. palette[i].green = png_ptr->gamma_from_1[w];
  191484. v = png_ptr->gamma_to_1[png_ptr->palette[i].blue];
  191485. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  191486. palette[i].blue = png_ptr->gamma_from_1[w];
  191487. }
  191488. else
  191489. {
  191490. palette[i].red = png_ptr->gamma_table[palette[i].red];
  191491. palette[i].green = png_ptr->gamma_table[palette[i].green];
  191492. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  191493. }
  191494. }
  191495. }
  191496. else
  191497. {
  191498. int i;
  191499. for (i = 0; i < num_palette; i++)
  191500. {
  191501. if (palette[i].red == (png_byte)png_ptr->trans_values.gray)
  191502. {
  191503. palette[i] = back;
  191504. }
  191505. else
  191506. {
  191507. palette[i].red = png_ptr->gamma_table[palette[i].red];
  191508. palette[i].green = png_ptr->gamma_table[palette[i].green];
  191509. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  191510. }
  191511. }
  191512. }
  191513. }
  191514. else
  191515. #endif
  191516. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191517. if (png_ptr->transformations & PNG_GAMMA)
  191518. {
  191519. int i;
  191520. for (i = 0; i < num_palette; i++)
  191521. {
  191522. palette[i].red = png_ptr->gamma_table[palette[i].red];
  191523. palette[i].green = png_ptr->gamma_table[palette[i].green];
  191524. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  191525. }
  191526. }
  191527. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191528. else
  191529. #endif
  191530. #endif
  191531. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191532. if (png_ptr->transformations & PNG_BACKGROUND)
  191533. {
  191534. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191535. {
  191536. png_color back;
  191537. back.red = (png_byte)png_ptr->background.red;
  191538. back.green = (png_byte)png_ptr->background.green;
  191539. back.blue = (png_byte)png_ptr->background.blue;
  191540. for (i = 0; i < (int)png_ptr->num_trans; i++)
  191541. {
  191542. if (png_ptr->trans[i] == 0)
  191543. {
  191544. palette[i].red = back.red;
  191545. palette[i].green = back.green;
  191546. palette[i].blue = back.blue;
  191547. }
  191548. else if (png_ptr->trans[i] != 0xff)
  191549. {
  191550. png_composite(palette[i].red, png_ptr->palette[i].red,
  191551. png_ptr->trans[i], back.red);
  191552. png_composite(palette[i].green, png_ptr->palette[i].green,
  191553. png_ptr->trans[i], back.green);
  191554. png_composite(palette[i].blue, png_ptr->palette[i].blue,
  191555. png_ptr->trans[i], back.blue);
  191556. }
  191557. }
  191558. }
  191559. else /* assume grayscale palette (what else could it be?) */
  191560. {
  191561. int i;
  191562. for (i = 0; i < num_palette; i++)
  191563. {
  191564. if (i == (png_byte)png_ptr->trans_values.gray)
  191565. {
  191566. palette[i].red = (png_byte)png_ptr->background.red;
  191567. palette[i].green = (png_byte)png_ptr->background.green;
  191568. palette[i].blue = (png_byte)png_ptr->background.blue;
  191569. }
  191570. }
  191571. }
  191572. }
  191573. #endif
  191574. }
  191575. #endif
  191576. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191577. /* Replace any alpha or transparency with the supplied background color.
  191578. * "background" is already in the screen gamma, while "background_1" is
  191579. * at a gamma of 1.0. Paletted files have already been taken care of.
  191580. */
  191581. void /* PRIVATE */
  191582. png_do_background(png_row_infop row_info, png_bytep row,
  191583. png_color_16p trans_values, png_color_16p background
  191584. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191585. , png_color_16p background_1,
  191586. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  191587. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  191588. png_uint_16pp gamma_16_to_1, int gamma_shift
  191589. #endif
  191590. )
  191591. {
  191592. png_bytep sp, dp;
  191593. png_uint_32 i;
  191594. png_uint_32 row_width=row_info->width;
  191595. int shift;
  191596. png_debug(1, "in png_do_background\n");
  191597. if (background != NULL &&
  191598. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191599. row != NULL && row_info != NULL &&
  191600. #endif
  191601. (!(row_info->color_type & PNG_COLOR_MASK_ALPHA) ||
  191602. (row_info->color_type != PNG_COLOR_TYPE_PALETTE && trans_values)))
  191603. {
  191604. switch (row_info->color_type)
  191605. {
  191606. case PNG_COLOR_TYPE_GRAY:
  191607. {
  191608. switch (row_info->bit_depth)
  191609. {
  191610. case 1:
  191611. {
  191612. sp = row;
  191613. shift = 7;
  191614. for (i = 0; i < row_width; i++)
  191615. {
  191616. if ((png_uint_16)((*sp >> shift) & 0x01)
  191617. == trans_values->gray)
  191618. {
  191619. *sp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  191620. *sp |= (png_byte)(background->gray << shift);
  191621. }
  191622. if (!shift)
  191623. {
  191624. shift = 7;
  191625. sp++;
  191626. }
  191627. else
  191628. shift--;
  191629. }
  191630. break;
  191631. }
  191632. case 2:
  191633. {
  191634. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191635. if (gamma_table != NULL)
  191636. {
  191637. sp = row;
  191638. shift = 6;
  191639. for (i = 0; i < row_width; i++)
  191640. {
  191641. if ((png_uint_16)((*sp >> shift) & 0x03)
  191642. == trans_values->gray)
  191643. {
  191644. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  191645. *sp |= (png_byte)(background->gray << shift);
  191646. }
  191647. else
  191648. {
  191649. png_byte p = (png_byte)((*sp >> shift) & 0x03);
  191650. png_byte g = (png_byte)((gamma_table [p | (p << 2) |
  191651. (p << 4) | (p << 6)] >> 6) & 0x03);
  191652. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  191653. *sp |= (png_byte)(g << shift);
  191654. }
  191655. if (!shift)
  191656. {
  191657. shift = 6;
  191658. sp++;
  191659. }
  191660. else
  191661. shift -= 2;
  191662. }
  191663. }
  191664. else
  191665. #endif
  191666. {
  191667. sp = row;
  191668. shift = 6;
  191669. for (i = 0; i < row_width; i++)
  191670. {
  191671. if ((png_uint_16)((*sp >> shift) & 0x03)
  191672. == trans_values->gray)
  191673. {
  191674. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  191675. *sp |= (png_byte)(background->gray << shift);
  191676. }
  191677. if (!shift)
  191678. {
  191679. shift = 6;
  191680. sp++;
  191681. }
  191682. else
  191683. shift -= 2;
  191684. }
  191685. }
  191686. break;
  191687. }
  191688. case 4:
  191689. {
  191690. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191691. if (gamma_table != NULL)
  191692. {
  191693. sp = row;
  191694. shift = 4;
  191695. for (i = 0; i < row_width; i++)
  191696. {
  191697. if ((png_uint_16)((*sp >> shift) & 0x0f)
  191698. == trans_values->gray)
  191699. {
  191700. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  191701. *sp |= (png_byte)(background->gray << shift);
  191702. }
  191703. else
  191704. {
  191705. png_byte p = (png_byte)((*sp >> shift) & 0x0f);
  191706. png_byte g = (png_byte)((gamma_table[p |
  191707. (p << 4)] >> 4) & 0x0f);
  191708. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  191709. *sp |= (png_byte)(g << shift);
  191710. }
  191711. if (!shift)
  191712. {
  191713. shift = 4;
  191714. sp++;
  191715. }
  191716. else
  191717. shift -= 4;
  191718. }
  191719. }
  191720. else
  191721. #endif
  191722. {
  191723. sp = row;
  191724. shift = 4;
  191725. for (i = 0; i < row_width; i++)
  191726. {
  191727. if ((png_uint_16)((*sp >> shift) & 0x0f)
  191728. == trans_values->gray)
  191729. {
  191730. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  191731. *sp |= (png_byte)(background->gray << shift);
  191732. }
  191733. if (!shift)
  191734. {
  191735. shift = 4;
  191736. sp++;
  191737. }
  191738. else
  191739. shift -= 4;
  191740. }
  191741. }
  191742. break;
  191743. }
  191744. case 8:
  191745. {
  191746. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191747. if (gamma_table != NULL)
  191748. {
  191749. sp = row;
  191750. for (i = 0; i < row_width; i++, sp++)
  191751. {
  191752. if (*sp == trans_values->gray)
  191753. {
  191754. *sp = (png_byte)background->gray;
  191755. }
  191756. else
  191757. {
  191758. *sp = gamma_table[*sp];
  191759. }
  191760. }
  191761. }
  191762. else
  191763. #endif
  191764. {
  191765. sp = row;
  191766. for (i = 0; i < row_width; i++, sp++)
  191767. {
  191768. if (*sp == trans_values->gray)
  191769. {
  191770. *sp = (png_byte)background->gray;
  191771. }
  191772. }
  191773. }
  191774. break;
  191775. }
  191776. case 16:
  191777. {
  191778. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191779. if (gamma_16 != NULL)
  191780. {
  191781. sp = row;
  191782. for (i = 0; i < row_width; i++, sp += 2)
  191783. {
  191784. png_uint_16 v;
  191785. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  191786. if (v == trans_values->gray)
  191787. {
  191788. /* background is already in screen gamma */
  191789. *sp = (png_byte)((background->gray >> 8) & 0xff);
  191790. *(sp + 1) = (png_byte)(background->gray & 0xff);
  191791. }
  191792. else
  191793. {
  191794. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  191795. *sp = (png_byte)((v >> 8) & 0xff);
  191796. *(sp + 1) = (png_byte)(v & 0xff);
  191797. }
  191798. }
  191799. }
  191800. else
  191801. #endif
  191802. {
  191803. sp = row;
  191804. for (i = 0; i < row_width; i++, sp += 2)
  191805. {
  191806. png_uint_16 v;
  191807. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  191808. if (v == trans_values->gray)
  191809. {
  191810. *sp = (png_byte)((background->gray >> 8) & 0xff);
  191811. *(sp + 1) = (png_byte)(background->gray & 0xff);
  191812. }
  191813. }
  191814. }
  191815. break;
  191816. }
  191817. }
  191818. break;
  191819. }
  191820. case PNG_COLOR_TYPE_RGB:
  191821. {
  191822. if (row_info->bit_depth == 8)
  191823. {
  191824. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191825. if (gamma_table != NULL)
  191826. {
  191827. sp = row;
  191828. for (i = 0; i < row_width; i++, sp += 3)
  191829. {
  191830. if (*sp == trans_values->red &&
  191831. *(sp + 1) == trans_values->green &&
  191832. *(sp + 2) == trans_values->blue)
  191833. {
  191834. *sp = (png_byte)background->red;
  191835. *(sp + 1) = (png_byte)background->green;
  191836. *(sp + 2) = (png_byte)background->blue;
  191837. }
  191838. else
  191839. {
  191840. *sp = gamma_table[*sp];
  191841. *(sp + 1) = gamma_table[*(sp + 1)];
  191842. *(sp + 2) = gamma_table[*(sp + 2)];
  191843. }
  191844. }
  191845. }
  191846. else
  191847. #endif
  191848. {
  191849. sp = row;
  191850. for (i = 0; i < row_width; i++, sp += 3)
  191851. {
  191852. if (*sp == trans_values->red &&
  191853. *(sp + 1) == trans_values->green &&
  191854. *(sp + 2) == trans_values->blue)
  191855. {
  191856. *sp = (png_byte)background->red;
  191857. *(sp + 1) = (png_byte)background->green;
  191858. *(sp + 2) = (png_byte)background->blue;
  191859. }
  191860. }
  191861. }
  191862. }
  191863. else /* if (row_info->bit_depth == 16) */
  191864. {
  191865. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191866. if (gamma_16 != NULL)
  191867. {
  191868. sp = row;
  191869. for (i = 0; i < row_width; i++, sp += 6)
  191870. {
  191871. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  191872. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  191873. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  191874. if (r == trans_values->red && g == trans_values->green &&
  191875. b == trans_values->blue)
  191876. {
  191877. /* background is already in screen gamma */
  191878. *sp = (png_byte)((background->red >> 8) & 0xff);
  191879. *(sp + 1) = (png_byte)(background->red & 0xff);
  191880. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  191881. *(sp + 3) = (png_byte)(background->green & 0xff);
  191882. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  191883. *(sp + 5) = (png_byte)(background->blue & 0xff);
  191884. }
  191885. else
  191886. {
  191887. png_uint_16 v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  191888. *sp = (png_byte)((v >> 8) & 0xff);
  191889. *(sp + 1) = (png_byte)(v & 0xff);
  191890. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  191891. *(sp + 2) = (png_byte)((v >> 8) & 0xff);
  191892. *(sp + 3) = (png_byte)(v & 0xff);
  191893. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  191894. *(sp + 4) = (png_byte)((v >> 8) & 0xff);
  191895. *(sp + 5) = (png_byte)(v & 0xff);
  191896. }
  191897. }
  191898. }
  191899. else
  191900. #endif
  191901. {
  191902. sp = row;
  191903. for (i = 0; i < row_width; i++, sp += 6)
  191904. {
  191905. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp+1));
  191906. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  191907. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  191908. if (r == trans_values->red && g == trans_values->green &&
  191909. b == trans_values->blue)
  191910. {
  191911. *sp = (png_byte)((background->red >> 8) & 0xff);
  191912. *(sp + 1) = (png_byte)(background->red & 0xff);
  191913. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  191914. *(sp + 3) = (png_byte)(background->green & 0xff);
  191915. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  191916. *(sp + 5) = (png_byte)(background->blue & 0xff);
  191917. }
  191918. }
  191919. }
  191920. }
  191921. break;
  191922. }
  191923. case PNG_COLOR_TYPE_GRAY_ALPHA:
  191924. {
  191925. if (row_info->bit_depth == 8)
  191926. {
  191927. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191928. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  191929. gamma_table != NULL)
  191930. {
  191931. sp = row;
  191932. dp = row;
  191933. for (i = 0; i < row_width; i++, sp += 2, dp++)
  191934. {
  191935. png_uint_16 a = *(sp + 1);
  191936. if (a == 0xff)
  191937. {
  191938. *dp = gamma_table[*sp];
  191939. }
  191940. else if (a == 0)
  191941. {
  191942. /* background is already in screen gamma */
  191943. *dp = (png_byte)background->gray;
  191944. }
  191945. else
  191946. {
  191947. png_byte v, w;
  191948. v = gamma_to_1[*sp];
  191949. png_composite(w, v, a, background_1->gray);
  191950. *dp = gamma_from_1[w];
  191951. }
  191952. }
  191953. }
  191954. else
  191955. #endif
  191956. {
  191957. sp = row;
  191958. dp = row;
  191959. for (i = 0; i < row_width; i++, sp += 2, dp++)
  191960. {
  191961. png_byte a = *(sp + 1);
  191962. if (a == 0xff)
  191963. {
  191964. *dp = *sp;
  191965. }
  191966. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191967. else if (a == 0)
  191968. {
  191969. *dp = (png_byte)background->gray;
  191970. }
  191971. else
  191972. {
  191973. png_composite(*dp, *sp, a, background_1->gray);
  191974. }
  191975. #else
  191976. *dp = (png_byte)background->gray;
  191977. #endif
  191978. }
  191979. }
  191980. }
  191981. else /* if (png_ptr->bit_depth == 16) */
  191982. {
  191983. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191984. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  191985. gamma_16_to_1 != NULL)
  191986. {
  191987. sp = row;
  191988. dp = row;
  191989. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  191990. {
  191991. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  191992. if (a == (png_uint_16)0xffff)
  191993. {
  191994. png_uint_16 v;
  191995. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  191996. *dp = (png_byte)((v >> 8) & 0xff);
  191997. *(dp + 1) = (png_byte)(v & 0xff);
  191998. }
  191999. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192000. else if (a == 0)
  192001. #else
  192002. else
  192003. #endif
  192004. {
  192005. /* background is already in screen gamma */
  192006. *dp = (png_byte)((background->gray >> 8) & 0xff);
  192007. *(dp + 1) = (png_byte)(background->gray & 0xff);
  192008. }
  192009. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192010. else
  192011. {
  192012. png_uint_16 g, v, w;
  192013. g = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  192014. png_composite_16(v, g, a, background_1->gray);
  192015. w = gamma_16_from_1[(v&0xff) >> gamma_shift][v >> 8];
  192016. *dp = (png_byte)((w >> 8) & 0xff);
  192017. *(dp + 1) = (png_byte)(w & 0xff);
  192018. }
  192019. #endif
  192020. }
  192021. }
  192022. else
  192023. #endif
  192024. {
  192025. sp = row;
  192026. dp = row;
  192027. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  192028. {
  192029. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192030. if (a == (png_uint_16)0xffff)
  192031. {
  192032. png_memcpy(dp, sp, 2);
  192033. }
  192034. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192035. else if (a == 0)
  192036. #else
  192037. else
  192038. #endif
  192039. {
  192040. *dp = (png_byte)((background->gray >> 8) & 0xff);
  192041. *(dp + 1) = (png_byte)(background->gray & 0xff);
  192042. }
  192043. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192044. else
  192045. {
  192046. png_uint_16 g, v;
  192047. g = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192048. png_composite_16(v, g, a, background_1->gray);
  192049. *dp = (png_byte)((v >> 8) & 0xff);
  192050. *(dp + 1) = (png_byte)(v & 0xff);
  192051. }
  192052. #endif
  192053. }
  192054. }
  192055. }
  192056. break;
  192057. }
  192058. case PNG_COLOR_TYPE_RGB_ALPHA:
  192059. {
  192060. if (row_info->bit_depth == 8)
  192061. {
  192062. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192063. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  192064. gamma_table != NULL)
  192065. {
  192066. sp = row;
  192067. dp = row;
  192068. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  192069. {
  192070. png_byte a = *(sp + 3);
  192071. if (a == 0xff)
  192072. {
  192073. *dp = gamma_table[*sp];
  192074. *(dp + 1) = gamma_table[*(sp + 1)];
  192075. *(dp + 2) = gamma_table[*(sp + 2)];
  192076. }
  192077. else if (a == 0)
  192078. {
  192079. /* background is already in screen gamma */
  192080. *dp = (png_byte)background->red;
  192081. *(dp + 1) = (png_byte)background->green;
  192082. *(dp + 2) = (png_byte)background->blue;
  192083. }
  192084. else
  192085. {
  192086. png_byte v, w;
  192087. v = gamma_to_1[*sp];
  192088. png_composite(w, v, a, background_1->red);
  192089. *dp = gamma_from_1[w];
  192090. v = gamma_to_1[*(sp + 1)];
  192091. png_composite(w, v, a, background_1->green);
  192092. *(dp + 1) = gamma_from_1[w];
  192093. v = gamma_to_1[*(sp + 2)];
  192094. png_composite(w, v, a, background_1->blue);
  192095. *(dp + 2) = gamma_from_1[w];
  192096. }
  192097. }
  192098. }
  192099. else
  192100. #endif
  192101. {
  192102. sp = row;
  192103. dp = row;
  192104. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  192105. {
  192106. png_byte a = *(sp + 3);
  192107. if (a == 0xff)
  192108. {
  192109. *dp = *sp;
  192110. *(dp + 1) = *(sp + 1);
  192111. *(dp + 2) = *(sp + 2);
  192112. }
  192113. else if (a == 0)
  192114. {
  192115. *dp = (png_byte)background->red;
  192116. *(dp + 1) = (png_byte)background->green;
  192117. *(dp + 2) = (png_byte)background->blue;
  192118. }
  192119. else
  192120. {
  192121. png_composite(*dp, *sp, a, background->red);
  192122. png_composite(*(dp + 1), *(sp + 1), a,
  192123. background->green);
  192124. png_composite(*(dp + 2), *(sp + 2), a,
  192125. background->blue);
  192126. }
  192127. }
  192128. }
  192129. }
  192130. else /* if (row_info->bit_depth == 16) */
  192131. {
  192132. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192133. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  192134. gamma_16_to_1 != NULL)
  192135. {
  192136. sp = row;
  192137. dp = row;
  192138. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  192139. {
  192140. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  192141. << 8) + (png_uint_16)(*(sp + 7)));
  192142. if (a == (png_uint_16)0xffff)
  192143. {
  192144. png_uint_16 v;
  192145. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192146. *dp = (png_byte)((v >> 8) & 0xff);
  192147. *(dp + 1) = (png_byte)(v & 0xff);
  192148. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  192149. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  192150. *(dp + 3) = (png_byte)(v & 0xff);
  192151. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  192152. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  192153. *(dp + 5) = (png_byte)(v & 0xff);
  192154. }
  192155. else if (a == 0)
  192156. {
  192157. /* background is already in screen gamma */
  192158. *dp = (png_byte)((background->red >> 8) & 0xff);
  192159. *(dp + 1) = (png_byte)(background->red & 0xff);
  192160. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192161. *(dp + 3) = (png_byte)(background->green & 0xff);
  192162. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192163. *(dp + 5) = (png_byte)(background->blue & 0xff);
  192164. }
  192165. else
  192166. {
  192167. png_uint_16 v, w, x;
  192168. v = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  192169. png_composite_16(w, v, a, background_1->red);
  192170. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  192171. *dp = (png_byte)((x >> 8) & 0xff);
  192172. *(dp + 1) = (png_byte)(x & 0xff);
  192173. v = gamma_16_to_1[*(sp + 3) >> gamma_shift][*(sp + 2)];
  192174. png_composite_16(w, v, a, background_1->green);
  192175. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  192176. *(dp + 2) = (png_byte)((x >> 8) & 0xff);
  192177. *(dp + 3) = (png_byte)(x & 0xff);
  192178. v = gamma_16_to_1[*(sp + 5) >> gamma_shift][*(sp + 4)];
  192179. png_composite_16(w, v, a, background_1->blue);
  192180. x = gamma_16_from_1[(w & 0xff) >> gamma_shift][w >> 8];
  192181. *(dp + 4) = (png_byte)((x >> 8) & 0xff);
  192182. *(dp + 5) = (png_byte)(x & 0xff);
  192183. }
  192184. }
  192185. }
  192186. else
  192187. #endif
  192188. {
  192189. sp = row;
  192190. dp = row;
  192191. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  192192. {
  192193. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  192194. << 8) + (png_uint_16)(*(sp + 7)));
  192195. if (a == (png_uint_16)0xffff)
  192196. {
  192197. png_memcpy(dp, sp, 6);
  192198. }
  192199. else if (a == 0)
  192200. {
  192201. *dp = (png_byte)((background->red >> 8) & 0xff);
  192202. *(dp + 1) = (png_byte)(background->red & 0xff);
  192203. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192204. *(dp + 3) = (png_byte)(background->green & 0xff);
  192205. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192206. *(dp + 5) = (png_byte)(background->blue & 0xff);
  192207. }
  192208. else
  192209. {
  192210. png_uint_16 v;
  192211. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192212. png_uint_16 g = (png_uint_16)(((*(sp + 2)) << 8)
  192213. + *(sp + 3));
  192214. png_uint_16 b = (png_uint_16)(((*(sp + 4)) << 8)
  192215. + *(sp + 5));
  192216. png_composite_16(v, r, a, background->red);
  192217. *dp = (png_byte)((v >> 8) & 0xff);
  192218. *(dp + 1) = (png_byte)(v & 0xff);
  192219. png_composite_16(v, g, a, background->green);
  192220. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  192221. *(dp + 3) = (png_byte)(v & 0xff);
  192222. png_composite_16(v, b, a, background->blue);
  192223. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  192224. *(dp + 5) = (png_byte)(v & 0xff);
  192225. }
  192226. }
  192227. }
  192228. }
  192229. break;
  192230. }
  192231. }
  192232. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  192233. {
  192234. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  192235. row_info->channels--;
  192236. row_info->pixel_depth = (png_byte)(row_info->channels *
  192237. row_info->bit_depth);
  192238. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192239. }
  192240. }
  192241. }
  192242. #endif
  192243. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192244. /* Gamma correct the image, avoiding the alpha channel. Make sure
  192245. * you do this after you deal with the transparency issue on grayscale
  192246. * or RGB images. If your bit depth is 8, use gamma_table, if it
  192247. * is 16, use gamma_16_table and gamma_shift. Build these with
  192248. * build_gamma_table().
  192249. */
  192250. void /* PRIVATE */
  192251. png_do_gamma(png_row_infop row_info, png_bytep row,
  192252. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  192253. int gamma_shift)
  192254. {
  192255. png_bytep sp;
  192256. png_uint_32 i;
  192257. png_uint_32 row_width=row_info->width;
  192258. png_debug(1, "in png_do_gamma\n");
  192259. if (
  192260. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192261. row != NULL && row_info != NULL &&
  192262. #endif
  192263. ((row_info->bit_depth <= 8 && gamma_table != NULL) ||
  192264. (row_info->bit_depth == 16 && gamma_16_table != NULL)))
  192265. {
  192266. switch (row_info->color_type)
  192267. {
  192268. case PNG_COLOR_TYPE_RGB:
  192269. {
  192270. if (row_info->bit_depth == 8)
  192271. {
  192272. sp = row;
  192273. for (i = 0; i < row_width; i++)
  192274. {
  192275. *sp = gamma_table[*sp];
  192276. sp++;
  192277. *sp = gamma_table[*sp];
  192278. sp++;
  192279. *sp = gamma_table[*sp];
  192280. sp++;
  192281. }
  192282. }
  192283. else /* if (row_info->bit_depth == 16) */
  192284. {
  192285. sp = row;
  192286. for (i = 0; i < row_width; i++)
  192287. {
  192288. png_uint_16 v;
  192289. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192290. *sp = (png_byte)((v >> 8) & 0xff);
  192291. *(sp + 1) = (png_byte)(v & 0xff);
  192292. sp += 2;
  192293. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192294. *sp = (png_byte)((v >> 8) & 0xff);
  192295. *(sp + 1) = (png_byte)(v & 0xff);
  192296. sp += 2;
  192297. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192298. *sp = (png_byte)((v >> 8) & 0xff);
  192299. *(sp + 1) = (png_byte)(v & 0xff);
  192300. sp += 2;
  192301. }
  192302. }
  192303. break;
  192304. }
  192305. case PNG_COLOR_TYPE_RGB_ALPHA:
  192306. {
  192307. if (row_info->bit_depth == 8)
  192308. {
  192309. sp = row;
  192310. for (i = 0; i < row_width; i++)
  192311. {
  192312. *sp = gamma_table[*sp];
  192313. sp++;
  192314. *sp = gamma_table[*sp];
  192315. sp++;
  192316. *sp = gamma_table[*sp];
  192317. sp++;
  192318. sp++;
  192319. }
  192320. }
  192321. else /* if (row_info->bit_depth == 16) */
  192322. {
  192323. sp = row;
  192324. for (i = 0; i < row_width; i++)
  192325. {
  192326. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192327. *sp = (png_byte)((v >> 8) & 0xff);
  192328. *(sp + 1) = (png_byte)(v & 0xff);
  192329. sp += 2;
  192330. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192331. *sp = (png_byte)((v >> 8) & 0xff);
  192332. *(sp + 1) = (png_byte)(v & 0xff);
  192333. sp += 2;
  192334. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192335. *sp = (png_byte)((v >> 8) & 0xff);
  192336. *(sp + 1) = (png_byte)(v & 0xff);
  192337. sp += 4;
  192338. }
  192339. }
  192340. break;
  192341. }
  192342. case PNG_COLOR_TYPE_GRAY_ALPHA:
  192343. {
  192344. if (row_info->bit_depth == 8)
  192345. {
  192346. sp = row;
  192347. for (i = 0; i < row_width; i++)
  192348. {
  192349. *sp = gamma_table[*sp];
  192350. sp += 2;
  192351. }
  192352. }
  192353. else /* if (row_info->bit_depth == 16) */
  192354. {
  192355. sp = row;
  192356. for (i = 0; i < row_width; i++)
  192357. {
  192358. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192359. *sp = (png_byte)((v >> 8) & 0xff);
  192360. *(sp + 1) = (png_byte)(v & 0xff);
  192361. sp += 4;
  192362. }
  192363. }
  192364. break;
  192365. }
  192366. case PNG_COLOR_TYPE_GRAY:
  192367. {
  192368. if (row_info->bit_depth == 2)
  192369. {
  192370. sp = row;
  192371. for (i = 0; i < row_width; i += 4)
  192372. {
  192373. int a = *sp & 0xc0;
  192374. int b = *sp & 0x30;
  192375. int c = *sp & 0x0c;
  192376. int d = *sp & 0x03;
  192377. *sp = (png_byte)(
  192378. ((((int)gamma_table[a|(a>>2)|(a>>4)|(a>>6)]) ) & 0xc0)|
  192379. ((((int)gamma_table[(b<<2)|b|(b>>2)|(b>>4)])>>2) & 0x30)|
  192380. ((((int)gamma_table[(c<<4)|(c<<2)|c|(c>>2)])>>4) & 0x0c)|
  192381. ((((int)gamma_table[(d<<6)|(d<<4)|(d<<2)|d])>>6) ));
  192382. sp++;
  192383. }
  192384. }
  192385. if (row_info->bit_depth == 4)
  192386. {
  192387. sp = row;
  192388. for (i = 0; i < row_width; i += 2)
  192389. {
  192390. int msb = *sp & 0xf0;
  192391. int lsb = *sp & 0x0f;
  192392. *sp = (png_byte)((((int)gamma_table[msb | (msb >> 4)]) & 0xf0)
  192393. | (((int)gamma_table[(lsb << 4) | lsb]) >> 4));
  192394. sp++;
  192395. }
  192396. }
  192397. else if (row_info->bit_depth == 8)
  192398. {
  192399. sp = row;
  192400. for (i = 0; i < row_width; i++)
  192401. {
  192402. *sp = gamma_table[*sp];
  192403. sp++;
  192404. }
  192405. }
  192406. else if (row_info->bit_depth == 16)
  192407. {
  192408. sp = row;
  192409. for (i = 0; i < row_width; i++)
  192410. {
  192411. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192412. *sp = (png_byte)((v >> 8) & 0xff);
  192413. *(sp + 1) = (png_byte)(v & 0xff);
  192414. sp += 2;
  192415. }
  192416. }
  192417. break;
  192418. }
  192419. }
  192420. }
  192421. }
  192422. #endif
  192423. #if defined(PNG_READ_EXPAND_SUPPORTED)
  192424. /* Expands a palette row to an RGB or RGBA row depending
  192425. * upon whether you supply trans and num_trans.
  192426. */
  192427. void /* PRIVATE */
  192428. png_do_expand_palette(png_row_infop row_info, png_bytep row,
  192429. png_colorp palette, png_bytep trans, int num_trans)
  192430. {
  192431. int shift, value;
  192432. png_bytep sp, dp;
  192433. png_uint_32 i;
  192434. png_uint_32 row_width=row_info->width;
  192435. png_debug(1, "in png_do_expand_palette\n");
  192436. if (
  192437. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192438. row != NULL && row_info != NULL &&
  192439. #endif
  192440. row_info->color_type == PNG_COLOR_TYPE_PALETTE)
  192441. {
  192442. if (row_info->bit_depth < 8)
  192443. {
  192444. switch (row_info->bit_depth)
  192445. {
  192446. case 1:
  192447. {
  192448. sp = row + (png_size_t)((row_width - 1) >> 3);
  192449. dp = row + (png_size_t)row_width - 1;
  192450. shift = 7 - (int)((row_width + 7) & 0x07);
  192451. for (i = 0; i < row_width; i++)
  192452. {
  192453. if ((*sp >> shift) & 0x01)
  192454. *dp = 1;
  192455. else
  192456. *dp = 0;
  192457. if (shift == 7)
  192458. {
  192459. shift = 0;
  192460. sp--;
  192461. }
  192462. else
  192463. shift++;
  192464. dp--;
  192465. }
  192466. break;
  192467. }
  192468. case 2:
  192469. {
  192470. sp = row + (png_size_t)((row_width - 1) >> 2);
  192471. dp = row + (png_size_t)row_width - 1;
  192472. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  192473. for (i = 0; i < row_width; i++)
  192474. {
  192475. value = (*sp >> shift) & 0x03;
  192476. *dp = (png_byte)value;
  192477. if (shift == 6)
  192478. {
  192479. shift = 0;
  192480. sp--;
  192481. }
  192482. else
  192483. shift += 2;
  192484. dp--;
  192485. }
  192486. break;
  192487. }
  192488. case 4:
  192489. {
  192490. sp = row + (png_size_t)((row_width - 1) >> 1);
  192491. dp = row + (png_size_t)row_width - 1;
  192492. shift = (int)((row_width & 0x01) << 2);
  192493. for (i = 0; i < row_width; i++)
  192494. {
  192495. value = (*sp >> shift) & 0x0f;
  192496. *dp = (png_byte)value;
  192497. if (shift == 4)
  192498. {
  192499. shift = 0;
  192500. sp--;
  192501. }
  192502. else
  192503. shift += 4;
  192504. dp--;
  192505. }
  192506. break;
  192507. }
  192508. }
  192509. row_info->bit_depth = 8;
  192510. row_info->pixel_depth = 8;
  192511. row_info->rowbytes = row_width;
  192512. }
  192513. switch (row_info->bit_depth)
  192514. {
  192515. case 8:
  192516. {
  192517. if (trans != NULL)
  192518. {
  192519. sp = row + (png_size_t)row_width - 1;
  192520. dp = row + (png_size_t)(row_width << 2) - 1;
  192521. for (i = 0; i < row_width; i++)
  192522. {
  192523. if ((int)(*sp) >= num_trans)
  192524. *dp-- = 0xff;
  192525. else
  192526. *dp-- = trans[*sp];
  192527. *dp-- = palette[*sp].blue;
  192528. *dp-- = palette[*sp].green;
  192529. *dp-- = palette[*sp].red;
  192530. sp--;
  192531. }
  192532. row_info->bit_depth = 8;
  192533. row_info->pixel_depth = 32;
  192534. row_info->rowbytes = row_width * 4;
  192535. row_info->color_type = 6;
  192536. row_info->channels = 4;
  192537. }
  192538. else
  192539. {
  192540. sp = row + (png_size_t)row_width - 1;
  192541. dp = row + (png_size_t)(row_width * 3) - 1;
  192542. for (i = 0; i < row_width; i++)
  192543. {
  192544. *dp-- = palette[*sp].blue;
  192545. *dp-- = palette[*sp].green;
  192546. *dp-- = palette[*sp].red;
  192547. sp--;
  192548. }
  192549. row_info->bit_depth = 8;
  192550. row_info->pixel_depth = 24;
  192551. row_info->rowbytes = row_width * 3;
  192552. row_info->color_type = 2;
  192553. row_info->channels = 3;
  192554. }
  192555. break;
  192556. }
  192557. }
  192558. }
  192559. }
  192560. /* If the bit depth < 8, it is expanded to 8. Also, if the already
  192561. * expanded transparency value is supplied, an alpha channel is built.
  192562. */
  192563. void /* PRIVATE */
  192564. png_do_expand(png_row_infop row_info, png_bytep row,
  192565. png_color_16p trans_value)
  192566. {
  192567. int shift, value;
  192568. png_bytep sp, dp;
  192569. png_uint_32 i;
  192570. png_uint_32 row_width=row_info->width;
  192571. png_debug(1, "in png_do_expand\n");
  192572. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192573. if (row != NULL && row_info != NULL)
  192574. #endif
  192575. {
  192576. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  192577. {
  192578. png_uint_16 gray = (png_uint_16)(trans_value ? trans_value->gray : 0);
  192579. if (row_info->bit_depth < 8)
  192580. {
  192581. switch (row_info->bit_depth)
  192582. {
  192583. case 1:
  192584. {
  192585. gray = (png_uint_16)((gray&0x01)*0xff);
  192586. sp = row + (png_size_t)((row_width - 1) >> 3);
  192587. dp = row + (png_size_t)row_width - 1;
  192588. shift = 7 - (int)((row_width + 7) & 0x07);
  192589. for (i = 0; i < row_width; i++)
  192590. {
  192591. if ((*sp >> shift) & 0x01)
  192592. *dp = 0xff;
  192593. else
  192594. *dp = 0;
  192595. if (shift == 7)
  192596. {
  192597. shift = 0;
  192598. sp--;
  192599. }
  192600. else
  192601. shift++;
  192602. dp--;
  192603. }
  192604. break;
  192605. }
  192606. case 2:
  192607. {
  192608. gray = (png_uint_16)((gray&0x03)*0x55);
  192609. sp = row + (png_size_t)((row_width - 1) >> 2);
  192610. dp = row + (png_size_t)row_width - 1;
  192611. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  192612. for (i = 0; i < row_width; i++)
  192613. {
  192614. value = (*sp >> shift) & 0x03;
  192615. *dp = (png_byte)(value | (value << 2) | (value << 4) |
  192616. (value << 6));
  192617. if (shift == 6)
  192618. {
  192619. shift = 0;
  192620. sp--;
  192621. }
  192622. else
  192623. shift += 2;
  192624. dp--;
  192625. }
  192626. break;
  192627. }
  192628. case 4:
  192629. {
  192630. gray = (png_uint_16)((gray&0x0f)*0x11);
  192631. sp = row + (png_size_t)((row_width - 1) >> 1);
  192632. dp = row + (png_size_t)row_width - 1;
  192633. shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  192634. for (i = 0; i < row_width; i++)
  192635. {
  192636. value = (*sp >> shift) & 0x0f;
  192637. *dp = (png_byte)(value | (value << 4));
  192638. if (shift == 4)
  192639. {
  192640. shift = 0;
  192641. sp--;
  192642. }
  192643. else
  192644. shift = 4;
  192645. dp--;
  192646. }
  192647. break;
  192648. }
  192649. }
  192650. row_info->bit_depth = 8;
  192651. row_info->pixel_depth = 8;
  192652. row_info->rowbytes = row_width;
  192653. }
  192654. if (trans_value != NULL)
  192655. {
  192656. if (row_info->bit_depth == 8)
  192657. {
  192658. gray = gray & 0xff;
  192659. sp = row + (png_size_t)row_width - 1;
  192660. dp = row + (png_size_t)(row_width << 1) - 1;
  192661. for (i = 0; i < row_width; i++)
  192662. {
  192663. if (*sp == gray)
  192664. *dp-- = 0;
  192665. else
  192666. *dp-- = 0xff;
  192667. *dp-- = *sp--;
  192668. }
  192669. }
  192670. else if (row_info->bit_depth == 16)
  192671. {
  192672. png_byte gray_high = (gray >> 8) & 0xff;
  192673. png_byte gray_low = gray & 0xff;
  192674. sp = row + row_info->rowbytes - 1;
  192675. dp = row + (row_info->rowbytes << 1) - 1;
  192676. for (i = 0; i < row_width; i++)
  192677. {
  192678. if (*(sp-1) == gray_high && *(sp) == gray_low)
  192679. {
  192680. *dp-- = 0;
  192681. *dp-- = 0;
  192682. }
  192683. else
  192684. {
  192685. *dp-- = 0xff;
  192686. *dp-- = 0xff;
  192687. }
  192688. *dp-- = *sp--;
  192689. *dp-- = *sp--;
  192690. }
  192691. }
  192692. row_info->color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
  192693. row_info->channels = 2;
  192694. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 1);
  192695. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  192696. row_width);
  192697. }
  192698. }
  192699. else if (row_info->color_type == PNG_COLOR_TYPE_RGB && trans_value)
  192700. {
  192701. if (row_info->bit_depth == 8)
  192702. {
  192703. png_byte red = trans_value->red & 0xff;
  192704. png_byte green = trans_value->green & 0xff;
  192705. png_byte blue = trans_value->blue & 0xff;
  192706. sp = row + (png_size_t)row_info->rowbytes - 1;
  192707. dp = row + (png_size_t)(row_width << 2) - 1;
  192708. for (i = 0; i < row_width; i++)
  192709. {
  192710. if (*(sp - 2) == red && *(sp - 1) == green && *(sp) == blue)
  192711. *dp-- = 0;
  192712. else
  192713. *dp-- = 0xff;
  192714. *dp-- = *sp--;
  192715. *dp-- = *sp--;
  192716. *dp-- = *sp--;
  192717. }
  192718. }
  192719. else if (row_info->bit_depth == 16)
  192720. {
  192721. png_byte red_high = (trans_value->red >> 8) & 0xff;
  192722. png_byte green_high = (trans_value->green >> 8) & 0xff;
  192723. png_byte blue_high = (trans_value->blue >> 8) & 0xff;
  192724. png_byte red_low = trans_value->red & 0xff;
  192725. png_byte green_low = trans_value->green & 0xff;
  192726. png_byte blue_low = trans_value->blue & 0xff;
  192727. sp = row + row_info->rowbytes - 1;
  192728. dp = row + (png_size_t)(row_width << 3) - 1;
  192729. for (i = 0; i < row_width; i++)
  192730. {
  192731. if (*(sp - 5) == red_high &&
  192732. *(sp - 4) == red_low &&
  192733. *(sp - 3) == green_high &&
  192734. *(sp - 2) == green_low &&
  192735. *(sp - 1) == blue_high &&
  192736. *(sp ) == blue_low)
  192737. {
  192738. *dp-- = 0;
  192739. *dp-- = 0;
  192740. }
  192741. else
  192742. {
  192743. *dp-- = 0xff;
  192744. *dp-- = 0xff;
  192745. }
  192746. *dp-- = *sp--;
  192747. *dp-- = *sp--;
  192748. *dp-- = *sp--;
  192749. *dp-- = *sp--;
  192750. *dp-- = *sp--;
  192751. *dp-- = *sp--;
  192752. }
  192753. }
  192754. row_info->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  192755. row_info->channels = 4;
  192756. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 2);
  192757. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192758. }
  192759. }
  192760. }
  192761. #endif
  192762. #if defined(PNG_READ_DITHER_SUPPORTED)
  192763. void /* PRIVATE */
  192764. png_do_dither(png_row_infop row_info, png_bytep row,
  192765. png_bytep palette_lookup, png_bytep dither_lookup)
  192766. {
  192767. png_bytep sp, dp;
  192768. png_uint_32 i;
  192769. png_uint_32 row_width=row_info->width;
  192770. png_debug(1, "in png_do_dither\n");
  192771. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192772. if (row != NULL && row_info != NULL)
  192773. #endif
  192774. {
  192775. if (row_info->color_type == PNG_COLOR_TYPE_RGB &&
  192776. palette_lookup && row_info->bit_depth == 8)
  192777. {
  192778. int r, g, b, p;
  192779. sp = row;
  192780. dp = row;
  192781. for (i = 0; i < row_width; i++)
  192782. {
  192783. r = *sp++;
  192784. g = *sp++;
  192785. b = *sp++;
  192786. /* this looks real messy, but the compiler will reduce
  192787. it down to a reasonable formula. For example, with
  192788. 5 bits per color, we get:
  192789. p = (((r >> 3) & 0x1f) << 10) |
  192790. (((g >> 3) & 0x1f) << 5) |
  192791. ((b >> 3) & 0x1f);
  192792. */
  192793. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  192794. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  192795. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  192796. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  192797. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  192798. (PNG_DITHER_BLUE_BITS)) |
  192799. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  192800. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  192801. *dp++ = palette_lookup[p];
  192802. }
  192803. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  192804. row_info->channels = 1;
  192805. row_info->pixel_depth = row_info->bit_depth;
  192806. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192807. }
  192808. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  192809. palette_lookup != NULL && row_info->bit_depth == 8)
  192810. {
  192811. int r, g, b, p;
  192812. sp = row;
  192813. dp = row;
  192814. for (i = 0; i < row_width; i++)
  192815. {
  192816. r = *sp++;
  192817. g = *sp++;
  192818. b = *sp++;
  192819. sp++;
  192820. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  192821. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  192822. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  192823. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  192824. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  192825. (PNG_DITHER_BLUE_BITS)) |
  192826. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  192827. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  192828. *dp++ = palette_lookup[p];
  192829. }
  192830. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  192831. row_info->channels = 1;
  192832. row_info->pixel_depth = row_info->bit_depth;
  192833. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192834. }
  192835. else if (row_info->color_type == PNG_COLOR_TYPE_PALETTE &&
  192836. dither_lookup && row_info->bit_depth == 8)
  192837. {
  192838. sp = row;
  192839. for (i = 0; i < row_width; i++, sp++)
  192840. {
  192841. *sp = dither_lookup[*sp];
  192842. }
  192843. }
  192844. }
  192845. }
  192846. #endif
  192847. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192848. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192849. static PNG_CONST int png_gamma_shift[] =
  192850. {0x10, 0x21, 0x42, 0x84, 0x110, 0x248, 0x550, 0xff0, 0x00};
  192851. /* We build the 8- or 16-bit gamma tables here. Note that for 16-bit
  192852. * tables, we don't make a full table if we are reducing to 8-bit in
  192853. * the future. Note also how the gamma_16 tables are segmented so that
  192854. * we don't need to allocate > 64K chunks for a full 16-bit table.
  192855. */
  192856. void /* PRIVATE */
  192857. png_build_gamma_table(png_structp png_ptr)
  192858. {
  192859. png_debug(1, "in png_build_gamma_table\n");
  192860. if (png_ptr->bit_depth <= 8)
  192861. {
  192862. int i;
  192863. double g;
  192864. if (png_ptr->screen_gamma > .000001)
  192865. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  192866. else
  192867. g = 1.0;
  192868. png_ptr->gamma_table = (png_bytep)png_malloc(png_ptr,
  192869. (png_uint_32)256);
  192870. for (i = 0; i < 256; i++)
  192871. {
  192872. png_ptr->gamma_table[i] = (png_byte)(pow((double)i / 255.0,
  192873. g) * 255.0 + .5);
  192874. }
  192875. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  192876. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  192877. if (png_ptr->transformations & ((PNG_BACKGROUND) | PNG_RGB_TO_GRAY))
  192878. {
  192879. g = 1.0 / (png_ptr->gamma);
  192880. png_ptr->gamma_to_1 = (png_bytep)png_malloc(png_ptr,
  192881. (png_uint_32)256);
  192882. for (i = 0; i < 256; i++)
  192883. {
  192884. png_ptr->gamma_to_1[i] = (png_byte)(pow((double)i / 255.0,
  192885. g) * 255.0 + .5);
  192886. }
  192887. png_ptr->gamma_from_1 = (png_bytep)png_malloc(png_ptr,
  192888. (png_uint_32)256);
  192889. if(png_ptr->screen_gamma > 0.000001)
  192890. g = 1.0 / png_ptr->screen_gamma;
  192891. else
  192892. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  192893. for (i = 0; i < 256; i++)
  192894. {
  192895. png_ptr->gamma_from_1[i] = (png_byte)(pow((double)i / 255.0,
  192896. g) * 255.0 + .5);
  192897. }
  192898. }
  192899. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  192900. }
  192901. else
  192902. {
  192903. double g;
  192904. int i, j, shift, num;
  192905. int sig_bit;
  192906. png_uint_32 ig;
  192907. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  192908. {
  192909. sig_bit = (int)png_ptr->sig_bit.red;
  192910. if ((int)png_ptr->sig_bit.green > sig_bit)
  192911. sig_bit = png_ptr->sig_bit.green;
  192912. if ((int)png_ptr->sig_bit.blue > sig_bit)
  192913. sig_bit = png_ptr->sig_bit.blue;
  192914. }
  192915. else
  192916. {
  192917. sig_bit = (int)png_ptr->sig_bit.gray;
  192918. }
  192919. if (sig_bit > 0)
  192920. shift = 16 - sig_bit;
  192921. else
  192922. shift = 0;
  192923. if (png_ptr->transformations & PNG_16_TO_8)
  192924. {
  192925. if (shift < (16 - PNG_MAX_GAMMA_8))
  192926. shift = (16 - PNG_MAX_GAMMA_8);
  192927. }
  192928. if (shift > 8)
  192929. shift = 8;
  192930. if (shift < 0)
  192931. shift = 0;
  192932. png_ptr->gamma_shift = (png_byte)shift;
  192933. num = (1 << (8 - shift));
  192934. if (png_ptr->screen_gamma > .000001)
  192935. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  192936. else
  192937. g = 1.0;
  192938. png_ptr->gamma_16_table = (png_uint_16pp)png_malloc(png_ptr,
  192939. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  192940. if (png_ptr->transformations & (PNG_16_TO_8 | PNG_BACKGROUND))
  192941. {
  192942. double fin, fout;
  192943. png_uint_32 last, max;
  192944. for (i = 0; i < num; i++)
  192945. {
  192946. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  192947. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  192948. }
  192949. g = 1.0 / g;
  192950. last = 0;
  192951. for (i = 0; i < 256; i++)
  192952. {
  192953. fout = ((double)i + 0.5) / 256.0;
  192954. fin = pow(fout, g);
  192955. max = (png_uint_32)(fin * (double)((png_uint_32)num << 8));
  192956. while (last <= max)
  192957. {
  192958. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  192959. [(int)(last >> (8 - shift))] = (png_uint_16)(
  192960. (png_uint_16)i | ((png_uint_16)i << 8));
  192961. last++;
  192962. }
  192963. }
  192964. while (last < ((png_uint_32)num << 8))
  192965. {
  192966. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  192967. [(int)(last >> (8 - shift))] = (png_uint_16)65535L;
  192968. last++;
  192969. }
  192970. }
  192971. else
  192972. {
  192973. for (i = 0; i < num; i++)
  192974. {
  192975. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  192976. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  192977. ig = (((png_uint_32)i * (png_uint_32)png_gamma_shift[shift]) >> 4);
  192978. for (j = 0; j < 256; j++)
  192979. {
  192980. png_ptr->gamma_16_table[i][j] =
  192981. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  192982. 65535.0, g) * 65535.0 + .5);
  192983. }
  192984. }
  192985. }
  192986. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  192987. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  192988. if (png_ptr->transformations & (PNG_BACKGROUND | PNG_RGB_TO_GRAY))
  192989. {
  192990. g = 1.0 / (png_ptr->gamma);
  192991. png_ptr->gamma_16_to_1 = (png_uint_16pp)png_malloc(png_ptr,
  192992. (png_uint_32)(num * png_sizeof (png_uint_16p )));
  192993. for (i = 0; i < num; i++)
  192994. {
  192995. png_ptr->gamma_16_to_1[i] = (png_uint_16p)png_malloc(png_ptr,
  192996. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  192997. ig = (((png_uint_32)i *
  192998. (png_uint_32)png_gamma_shift[shift]) >> 4);
  192999. for (j = 0; j < 256; j++)
  193000. {
  193001. png_ptr->gamma_16_to_1[i][j] =
  193002. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193003. 65535.0, g) * 65535.0 + .5);
  193004. }
  193005. }
  193006. if(png_ptr->screen_gamma > 0.000001)
  193007. g = 1.0 / png_ptr->screen_gamma;
  193008. else
  193009. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  193010. png_ptr->gamma_16_from_1 = (png_uint_16pp)png_malloc(png_ptr,
  193011. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  193012. for (i = 0; i < num; i++)
  193013. {
  193014. png_ptr->gamma_16_from_1[i] = (png_uint_16p)png_malloc(png_ptr,
  193015. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193016. ig = (((png_uint_32)i *
  193017. (png_uint_32)png_gamma_shift[shift]) >> 4);
  193018. for (j = 0; j < 256; j++)
  193019. {
  193020. png_ptr->gamma_16_from_1[i][j] =
  193021. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193022. 65535.0, g) * 65535.0 + .5);
  193023. }
  193024. }
  193025. }
  193026. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  193027. }
  193028. }
  193029. #endif
  193030. /* To do: install integer version of png_build_gamma_table here */
  193031. #endif
  193032. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  193033. /* undoes intrapixel differencing */
  193034. void /* PRIVATE */
  193035. png_do_read_intrapixel(png_row_infop row_info, png_bytep row)
  193036. {
  193037. png_debug(1, "in png_do_read_intrapixel\n");
  193038. if (
  193039. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193040. row != NULL && row_info != NULL &&
  193041. #endif
  193042. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  193043. {
  193044. int bytes_per_pixel;
  193045. png_uint_32 row_width = row_info->width;
  193046. if (row_info->bit_depth == 8)
  193047. {
  193048. png_bytep rp;
  193049. png_uint_32 i;
  193050. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  193051. bytes_per_pixel = 3;
  193052. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193053. bytes_per_pixel = 4;
  193054. else
  193055. return;
  193056. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  193057. {
  193058. *(rp) = (png_byte)((256 + *rp + *(rp+1))&0xff);
  193059. *(rp+2) = (png_byte)((256 + *(rp+2) + *(rp+1))&0xff);
  193060. }
  193061. }
  193062. else if (row_info->bit_depth == 16)
  193063. {
  193064. png_bytep rp;
  193065. png_uint_32 i;
  193066. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  193067. bytes_per_pixel = 6;
  193068. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193069. bytes_per_pixel = 8;
  193070. else
  193071. return;
  193072. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  193073. {
  193074. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  193075. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  193076. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  193077. png_uint_32 red = (png_uint_32)((s0+s1+65536L) & 0xffffL);
  193078. png_uint_32 blue = (png_uint_32)((s2+s1+65536L) & 0xffffL);
  193079. *(rp ) = (png_byte)((red >> 8) & 0xff);
  193080. *(rp+1) = (png_byte)(red & 0xff);
  193081. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  193082. *(rp+5) = (png_byte)(blue & 0xff);
  193083. }
  193084. }
  193085. }
  193086. }
  193087. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  193088. #endif /* PNG_READ_SUPPORTED */
  193089. /*** End of inlined file: pngrtran.c ***/
  193090. /*** Start of inlined file: pngrutil.c ***/
  193091. /* pngrutil.c - utilities to read a PNG file
  193092. *
  193093. * Last changed in libpng 1.2.21 [October 4, 2007]
  193094. * For conditions of distribution and use, see copyright notice in png.h
  193095. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  193096. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  193097. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  193098. *
  193099. * This file contains routines that are only called from within
  193100. * libpng itself during the course of reading an image.
  193101. */
  193102. #define PNG_INTERNAL
  193103. #if defined(PNG_READ_SUPPORTED)
  193104. #if defined(_WIN32_WCE) && (_WIN32_WCE<0x500)
  193105. # define WIN32_WCE_OLD
  193106. #endif
  193107. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193108. # if defined(WIN32_WCE_OLD)
  193109. /* strtod() function is not supported on WindowsCE */
  193110. __inline double png_strtod(png_structp png_ptr, PNG_CONST char *nptr, char **endptr)
  193111. {
  193112. double result = 0;
  193113. int len;
  193114. wchar_t *str, *end;
  193115. len = MultiByteToWideChar(CP_ACP, 0, nptr, -1, NULL, 0);
  193116. str = (wchar_t *)png_malloc(png_ptr, len * sizeof(wchar_t));
  193117. if ( NULL != str )
  193118. {
  193119. MultiByteToWideChar(CP_ACP, 0, nptr, -1, str, len);
  193120. result = wcstod(str, &end);
  193121. len = WideCharToMultiByte(CP_ACP, 0, end, -1, NULL, 0, NULL, NULL);
  193122. *endptr = (char *)nptr + (png_strlen(nptr) - len + 1);
  193123. png_free(png_ptr, str);
  193124. }
  193125. return result;
  193126. }
  193127. # else
  193128. # define png_strtod(p,a,b) strtod(a,b)
  193129. # endif
  193130. #endif
  193131. png_uint_32 PNGAPI
  193132. png_get_uint_31(png_structp png_ptr, png_bytep buf)
  193133. {
  193134. png_uint_32 i = png_get_uint_32(buf);
  193135. if (i > PNG_UINT_31_MAX)
  193136. png_error(png_ptr, "PNG unsigned integer out of range.");
  193137. return (i);
  193138. }
  193139. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  193140. /* Grab an unsigned 32-bit integer from a buffer in big-endian format. */
  193141. png_uint_32 PNGAPI
  193142. png_get_uint_32(png_bytep buf)
  193143. {
  193144. png_uint_32 i = ((png_uint_32)(*buf) << 24) +
  193145. ((png_uint_32)(*(buf + 1)) << 16) +
  193146. ((png_uint_32)(*(buf + 2)) << 8) +
  193147. (png_uint_32)(*(buf + 3));
  193148. return (i);
  193149. }
  193150. /* Grab a signed 32-bit integer from a buffer in big-endian format. The
  193151. * data is stored in the PNG file in two's complement format, and it is
  193152. * assumed that the machine format for signed integers is the same. */
  193153. png_int_32 PNGAPI
  193154. png_get_int_32(png_bytep buf)
  193155. {
  193156. png_int_32 i = ((png_int_32)(*buf) << 24) +
  193157. ((png_int_32)(*(buf + 1)) << 16) +
  193158. ((png_int_32)(*(buf + 2)) << 8) +
  193159. (png_int_32)(*(buf + 3));
  193160. return (i);
  193161. }
  193162. /* Grab an unsigned 16-bit integer from a buffer in big-endian format. */
  193163. png_uint_16 PNGAPI
  193164. png_get_uint_16(png_bytep buf)
  193165. {
  193166. png_uint_16 i = (png_uint_16)(((png_uint_16)(*buf) << 8) +
  193167. (png_uint_16)(*(buf + 1)));
  193168. return (i);
  193169. }
  193170. #endif /* PNG_READ_BIG_ENDIAN_SUPPORTED */
  193171. /* Read data, and (optionally) run it through the CRC. */
  193172. void /* PRIVATE */
  193173. png_crc_read(png_structp png_ptr, png_bytep buf, png_size_t length)
  193174. {
  193175. if(png_ptr == NULL) return;
  193176. png_read_data(png_ptr, buf, length);
  193177. png_calculate_crc(png_ptr, buf, length);
  193178. }
  193179. /* Optionally skip data and then check the CRC. Depending on whether we
  193180. are reading a ancillary or critical chunk, and how the program has set
  193181. things up, we may calculate the CRC on the data and print a message.
  193182. Returns '1' if there was a CRC error, '0' otherwise. */
  193183. int /* PRIVATE */
  193184. png_crc_finish(png_structp png_ptr, png_uint_32 skip)
  193185. {
  193186. png_size_t i;
  193187. png_size_t istop = png_ptr->zbuf_size;
  193188. for (i = (png_size_t)skip; i > istop; i -= istop)
  193189. {
  193190. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  193191. }
  193192. if (i)
  193193. {
  193194. png_crc_read(png_ptr, png_ptr->zbuf, i);
  193195. }
  193196. if (png_crc_error(png_ptr))
  193197. {
  193198. if (((png_ptr->chunk_name[0] & 0x20) && /* Ancillary */
  193199. !(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)) ||
  193200. (!(png_ptr->chunk_name[0] & 0x20) && /* Critical */
  193201. (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE)))
  193202. {
  193203. png_chunk_warning(png_ptr, "CRC error");
  193204. }
  193205. else
  193206. {
  193207. png_chunk_error(png_ptr, "CRC error");
  193208. }
  193209. return (1);
  193210. }
  193211. return (0);
  193212. }
  193213. /* Compare the CRC stored in the PNG file with that calculated by libpng from
  193214. the data it has read thus far. */
  193215. int /* PRIVATE */
  193216. png_crc_error(png_structp png_ptr)
  193217. {
  193218. png_byte crc_bytes[4];
  193219. png_uint_32 crc;
  193220. int need_crc = 1;
  193221. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  193222. {
  193223. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  193224. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  193225. need_crc = 0;
  193226. }
  193227. else /* critical */
  193228. {
  193229. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  193230. need_crc = 0;
  193231. }
  193232. png_read_data(png_ptr, crc_bytes, 4);
  193233. if (need_crc)
  193234. {
  193235. crc = png_get_uint_32(crc_bytes);
  193236. return ((int)(crc != png_ptr->crc));
  193237. }
  193238. else
  193239. return (0);
  193240. }
  193241. #if defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) || \
  193242. defined(PNG_READ_iCCP_SUPPORTED)
  193243. /*
  193244. * Decompress trailing data in a chunk. The assumption is that chunkdata
  193245. * points at an allocated area holding the contents of a chunk with a
  193246. * trailing compressed part. What we get back is an allocated area
  193247. * holding the original prefix part and an uncompressed version of the
  193248. * trailing part (the malloc area passed in is freed).
  193249. */
  193250. png_charp /* PRIVATE */
  193251. png_decompress_chunk(png_structp png_ptr, int comp_type,
  193252. png_charp chunkdata, png_size_t chunklength,
  193253. png_size_t prefix_size, png_size_t *newlength)
  193254. {
  193255. static PNG_CONST char msg[] = "Error decoding compressed text";
  193256. png_charp text;
  193257. png_size_t text_size;
  193258. if (comp_type == PNG_COMPRESSION_TYPE_BASE)
  193259. {
  193260. int ret = Z_OK;
  193261. png_ptr->zstream.next_in = (png_bytep)(chunkdata + prefix_size);
  193262. png_ptr->zstream.avail_in = (uInt)(chunklength - prefix_size);
  193263. png_ptr->zstream.next_out = png_ptr->zbuf;
  193264. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  193265. text_size = 0;
  193266. text = NULL;
  193267. while (png_ptr->zstream.avail_in)
  193268. {
  193269. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  193270. if (ret != Z_OK && ret != Z_STREAM_END)
  193271. {
  193272. if (png_ptr->zstream.msg != NULL)
  193273. png_warning(png_ptr, png_ptr->zstream.msg);
  193274. else
  193275. png_warning(png_ptr, msg);
  193276. inflateReset(&png_ptr->zstream);
  193277. png_ptr->zstream.avail_in = 0;
  193278. if (text == NULL)
  193279. {
  193280. text_size = prefix_size + png_sizeof(msg) + 1;
  193281. text = (png_charp)png_malloc_warn(png_ptr, text_size);
  193282. if (text == NULL)
  193283. {
  193284. png_free(png_ptr,chunkdata);
  193285. png_error(png_ptr,"Not enough memory to decompress chunk");
  193286. }
  193287. png_memcpy(text, chunkdata, prefix_size);
  193288. }
  193289. text[text_size - 1] = 0x00;
  193290. /* Copy what we can of the error message into the text chunk */
  193291. text_size = (png_size_t)(chunklength - (text - chunkdata) - 1);
  193292. text_size = png_sizeof(msg) > text_size ? text_size :
  193293. png_sizeof(msg);
  193294. png_memcpy(text + prefix_size, msg, text_size + 1);
  193295. break;
  193296. }
  193297. if (!png_ptr->zstream.avail_out || ret == Z_STREAM_END)
  193298. {
  193299. if (text == NULL)
  193300. {
  193301. text_size = prefix_size +
  193302. png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  193303. text = (png_charp)png_malloc_warn(png_ptr, text_size + 1);
  193304. if (text == NULL)
  193305. {
  193306. png_free(png_ptr,chunkdata);
  193307. png_error(png_ptr,"Not enough memory to decompress chunk.");
  193308. }
  193309. png_memcpy(text + prefix_size, png_ptr->zbuf,
  193310. text_size - prefix_size);
  193311. png_memcpy(text, chunkdata, prefix_size);
  193312. *(text + text_size) = 0x00;
  193313. }
  193314. else
  193315. {
  193316. png_charp tmp;
  193317. tmp = text;
  193318. text = (png_charp)png_malloc_warn(png_ptr,
  193319. (png_uint_32)(text_size +
  193320. png_ptr->zbuf_size - png_ptr->zstream.avail_out + 1));
  193321. if (text == NULL)
  193322. {
  193323. png_free(png_ptr, tmp);
  193324. png_free(png_ptr, chunkdata);
  193325. png_error(png_ptr,"Not enough memory to decompress chunk..");
  193326. }
  193327. png_memcpy(text, tmp, text_size);
  193328. png_free(png_ptr, tmp);
  193329. png_memcpy(text + text_size, png_ptr->zbuf,
  193330. (png_ptr->zbuf_size - png_ptr->zstream.avail_out));
  193331. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  193332. *(text + text_size) = 0x00;
  193333. }
  193334. if (ret == Z_STREAM_END)
  193335. break;
  193336. else
  193337. {
  193338. png_ptr->zstream.next_out = png_ptr->zbuf;
  193339. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  193340. }
  193341. }
  193342. }
  193343. if (ret != Z_STREAM_END)
  193344. {
  193345. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  193346. char umsg[52];
  193347. if (ret == Z_BUF_ERROR)
  193348. png_snprintf(umsg, 52,
  193349. "Buffer error in compressed datastream in %s chunk",
  193350. png_ptr->chunk_name);
  193351. else if (ret == Z_DATA_ERROR)
  193352. png_snprintf(umsg, 52,
  193353. "Data error in compressed datastream in %s chunk",
  193354. png_ptr->chunk_name);
  193355. else
  193356. png_snprintf(umsg, 52,
  193357. "Incomplete compressed datastream in %s chunk",
  193358. png_ptr->chunk_name);
  193359. png_warning(png_ptr, umsg);
  193360. #else
  193361. png_warning(png_ptr,
  193362. "Incomplete compressed datastream in chunk other than IDAT");
  193363. #endif
  193364. text_size=prefix_size;
  193365. if (text == NULL)
  193366. {
  193367. text = (png_charp)png_malloc_warn(png_ptr, text_size+1);
  193368. if (text == NULL)
  193369. {
  193370. png_free(png_ptr, chunkdata);
  193371. png_error(png_ptr,"Not enough memory for text.");
  193372. }
  193373. png_memcpy(text, chunkdata, prefix_size);
  193374. }
  193375. *(text + text_size) = 0x00;
  193376. }
  193377. inflateReset(&png_ptr->zstream);
  193378. png_ptr->zstream.avail_in = 0;
  193379. png_free(png_ptr, chunkdata);
  193380. chunkdata = text;
  193381. *newlength=text_size;
  193382. }
  193383. else /* if (comp_type != PNG_COMPRESSION_TYPE_BASE) */
  193384. {
  193385. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  193386. char umsg[50];
  193387. png_snprintf(umsg, 50,
  193388. "Unknown zTXt compression type %d", comp_type);
  193389. png_warning(png_ptr, umsg);
  193390. #else
  193391. png_warning(png_ptr, "Unknown zTXt compression type");
  193392. #endif
  193393. *(chunkdata + prefix_size) = 0x00;
  193394. *newlength=prefix_size;
  193395. }
  193396. return chunkdata;
  193397. }
  193398. #endif
  193399. /* read and check the IDHR chunk */
  193400. void /* PRIVATE */
  193401. png_handle_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193402. {
  193403. png_byte buf[13];
  193404. png_uint_32 width, height;
  193405. int bit_depth, color_type, compression_type, filter_type;
  193406. int interlace_type;
  193407. png_debug(1, "in png_handle_IHDR\n");
  193408. if (png_ptr->mode & PNG_HAVE_IHDR)
  193409. png_error(png_ptr, "Out of place IHDR");
  193410. /* check the length */
  193411. if (length != 13)
  193412. png_error(png_ptr, "Invalid IHDR chunk");
  193413. png_ptr->mode |= PNG_HAVE_IHDR;
  193414. png_crc_read(png_ptr, buf, 13);
  193415. png_crc_finish(png_ptr, 0);
  193416. width = png_get_uint_31(png_ptr, buf);
  193417. height = png_get_uint_31(png_ptr, buf + 4);
  193418. bit_depth = buf[8];
  193419. color_type = buf[9];
  193420. compression_type = buf[10];
  193421. filter_type = buf[11];
  193422. interlace_type = buf[12];
  193423. /* set internal variables */
  193424. png_ptr->width = width;
  193425. png_ptr->height = height;
  193426. png_ptr->bit_depth = (png_byte)bit_depth;
  193427. png_ptr->interlaced = (png_byte)interlace_type;
  193428. png_ptr->color_type = (png_byte)color_type;
  193429. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  193430. png_ptr->filter_type = (png_byte)filter_type;
  193431. #endif
  193432. png_ptr->compression_type = (png_byte)compression_type;
  193433. /* find number of channels */
  193434. switch (png_ptr->color_type)
  193435. {
  193436. case PNG_COLOR_TYPE_GRAY:
  193437. case PNG_COLOR_TYPE_PALETTE:
  193438. png_ptr->channels = 1;
  193439. break;
  193440. case PNG_COLOR_TYPE_RGB:
  193441. png_ptr->channels = 3;
  193442. break;
  193443. case PNG_COLOR_TYPE_GRAY_ALPHA:
  193444. png_ptr->channels = 2;
  193445. break;
  193446. case PNG_COLOR_TYPE_RGB_ALPHA:
  193447. png_ptr->channels = 4;
  193448. break;
  193449. }
  193450. /* set up other useful info */
  193451. png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth *
  193452. png_ptr->channels);
  193453. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->width);
  193454. png_debug1(3,"bit_depth = %d\n", png_ptr->bit_depth);
  193455. png_debug1(3,"channels = %d\n", png_ptr->channels);
  193456. png_debug1(3,"rowbytes = %lu\n", png_ptr->rowbytes);
  193457. png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
  193458. color_type, interlace_type, compression_type, filter_type);
  193459. }
  193460. /* read and check the palette */
  193461. void /* PRIVATE */
  193462. png_handle_PLTE(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193463. {
  193464. png_color palette[PNG_MAX_PALETTE_LENGTH];
  193465. int num, i;
  193466. #ifndef PNG_NO_POINTER_INDEXING
  193467. png_colorp pal_ptr;
  193468. #endif
  193469. png_debug(1, "in png_handle_PLTE\n");
  193470. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  193471. png_error(png_ptr, "Missing IHDR before PLTE");
  193472. else if (png_ptr->mode & PNG_HAVE_IDAT)
  193473. {
  193474. png_warning(png_ptr, "Invalid PLTE after IDAT");
  193475. png_crc_finish(png_ptr, length);
  193476. return;
  193477. }
  193478. else if (png_ptr->mode & PNG_HAVE_PLTE)
  193479. png_error(png_ptr, "Duplicate PLTE chunk");
  193480. png_ptr->mode |= PNG_HAVE_PLTE;
  193481. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  193482. {
  193483. png_warning(png_ptr,
  193484. "Ignoring PLTE chunk in grayscale PNG");
  193485. png_crc_finish(png_ptr, length);
  193486. return;
  193487. }
  193488. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  193489. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  193490. {
  193491. png_crc_finish(png_ptr, length);
  193492. return;
  193493. }
  193494. #endif
  193495. if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
  193496. {
  193497. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  193498. {
  193499. png_warning(png_ptr, "Invalid palette chunk");
  193500. png_crc_finish(png_ptr, length);
  193501. return;
  193502. }
  193503. else
  193504. {
  193505. png_error(png_ptr, "Invalid palette chunk");
  193506. }
  193507. }
  193508. num = (int)length / 3;
  193509. #ifndef PNG_NO_POINTER_INDEXING
  193510. for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
  193511. {
  193512. png_byte buf[3];
  193513. png_crc_read(png_ptr, buf, 3);
  193514. pal_ptr->red = buf[0];
  193515. pal_ptr->green = buf[1];
  193516. pal_ptr->blue = buf[2];
  193517. }
  193518. #else
  193519. for (i = 0; i < num; i++)
  193520. {
  193521. png_byte buf[3];
  193522. png_crc_read(png_ptr, buf, 3);
  193523. /* don't depend upon png_color being any order */
  193524. palette[i].red = buf[0];
  193525. palette[i].green = buf[1];
  193526. palette[i].blue = buf[2];
  193527. }
  193528. #endif
  193529. /* If we actually NEED the PLTE chunk (ie for a paletted image), we do
  193530. whatever the normal CRC configuration tells us. However, if we
  193531. have an RGB image, the PLTE can be considered ancillary, so
  193532. we will act as though it is. */
  193533. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  193534. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  193535. #endif
  193536. {
  193537. png_crc_finish(png_ptr, 0);
  193538. }
  193539. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  193540. else if (png_crc_error(png_ptr)) /* Only if we have a CRC error */
  193541. {
  193542. /* If we don't want to use the data from an ancillary chunk,
  193543. we have two options: an error abort, or a warning and we
  193544. ignore the data in this chunk (which should be OK, since
  193545. it's considered ancillary for a RGB or RGBA image). */
  193546. if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE))
  193547. {
  193548. if (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)
  193549. {
  193550. png_chunk_error(png_ptr, "CRC error");
  193551. }
  193552. else
  193553. {
  193554. png_chunk_warning(png_ptr, "CRC error");
  193555. return;
  193556. }
  193557. }
  193558. /* Otherwise, we (optionally) emit a warning and use the chunk. */
  193559. else if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN))
  193560. {
  193561. png_chunk_warning(png_ptr, "CRC error");
  193562. }
  193563. }
  193564. #endif
  193565. png_set_PLTE(png_ptr, info_ptr, palette, num);
  193566. #if defined(PNG_READ_tRNS_SUPPORTED)
  193567. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  193568. {
  193569. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  193570. {
  193571. if (png_ptr->num_trans > (png_uint_16)num)
  193572. {
  193573. png_warning(png_ptr, "Truncating incorrect tRNS chunk length");
  193574. png_ptr->num_trans = (png_uint_16)num;
  193575. }
  193576. if (info_ptr->num_trans > (png_uint_16)num)
  193577. {
  193578. png_warning(png_ptr, "Truncating incorrect info tRNS chunk length");
  193579. info_ptr->num_trans = (png_uint_16)num;
  193580. }
  193581. }
  193582. }
  193583. #endif
  193584. }
  193585. void /* PRIVATE */
  193586. png_handle_IEND(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193587. {
  193588. png_debug(1, "in png_handle_IEND\n");
  193589. if (!(png_ptr->mode & PNG_HAVE_IHDR) || !(png_ptr->mode & PNG_HAVE_IDAT))
  193590. {
  193591. png_error(png_ptr, "No image in file");
  193592. }
  193593. png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND);
  193594. if (length != 0)
  193595. {
  193596. png_warning(png_ptr, "Incorrect IEND chunk length");
  193597. }
  193598. png_crc_finish(png_ptr, length);
  193599. info_ptr =info_ptr; /* quiet compiler warnings about unused info_ptr */
  193600. }
  193601. #if defined(PNG_READ_gAMA_SUPPORTED)
  193602. void /* PRIVATE */
  193603. png_handle_gAMA(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193604. {
  193605. png_fixed_point igamma;
  193606. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193607. float file_gamma;
  193608. #endif
  193609. png_byte buf[4];
  193610. png_debug(1, "in png_handle_gAMA\n");
  193611. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  193612. png_error(png_ptr, "Missing IHDR before gAMA");
  193613. else if (png_ptr->mode & PNG_HAVE_IDAT)
  193614. {
  193615. png_warning(png_ptr, "Invalid gAMA after IDAT");
  193616. png_crc_finish(png_ptr, length);
  193617. return;
  193618. }
  193619. else if (png_ptr->mode & PNG_HAVE_PLTE)
  193620. /* Should be an error, but we can cope with it */
  193621. png_warning(png_ptr, "Out of place gAMA chunk");
  193622. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  193623. #if defined(PNG_READ_sRGB_SUPPORTED)
  193624. && !(info_ptr->valid & PNG_INFO_sRGB)
  193625. #endif
  193626. )
  193627. {
  193628. png_warning(png_ptr, "Duplicate gAMA chunk");
  193629. png_crc_finish(png_ptr, length);
  193630. return;
  193631. }
  193632. if (length != 4)
  193633. {
  193634. png_warning(png_ptr, "Incorrect gAMA chunk length");
  193635. png_crc_finish(png_ptr, length);
  193636. return;
  193637. }
  193638. png_crc_read(png_ptr, buf, 4);
  193639. if (png_crc_finish(png_ptr, 0))
  193640. return;
  193641. igamma = (png_fixed_point)png_get_uint_32(buf);
  193642. /* check for zero gamma */
  193643. if (igamma == 0)
  193644. {
  193645. png_warning(png_ptr,
  193646. "Ignoring gAMA chunk with gamma=0");
  193647. return;
  193648. }
  193649. #if defined(PNG_READ_sRGB_SUPPORTED)
  193650. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  193651. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  193652. {
  193653. png_warning(png_ptr,
  193654. "Ignoring incorrect gAMA value when sRGB is also present");
  193655. #ifndef PNG_NO_CONSOLE_IO
  193656. fprintf(stderr, "gamma = (%d/100000)\n", (int)igamma);
  193657. #endif
  193658. return;
  193659. }
  193660. #endif /* PNG_READ_sRGB_SUPPORTED */
  193661. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193662. file_gamma = (float)igamma / (float)100000.0;
  193663. # ifdef PNG_READ_GAMMA_SUPPORTED
  193664. png_ptr->gamma = file_gamma;
  193665. # endif
  193666. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  193667. #endif
  193668. #ifdef PNG_FIXED_POINT_SUPPORTED
  193669. png_set_gAMA_fixed(png_ptr, info_ptr, igamma);
  193670. #endif
  193671. }
  193672. #endif
  193673. #if defined(PNG_READ_sBIT_SUPPORTED)
  193674. void /* PRIVATE */
  193675. png_handle_sBIT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193676. {
  193677. png_size_t truelen;
  193678. png_byte buf[4];
  193679. png_debug(1, "in png_handle_sBIT\n");
  193680. buf[0] = buf[1] = buf[2] = buf[3] = 0;
  193681. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  193682. png_error(png_ptr, "Missing IHDR before sBIT");
  193683. else if (png_ptr->mode & PNG_HAVE_IDAT)
  193684. {
  193685. png_warning(png_ptr, "Invalid sBIT after IDAT");
  193686. png_crc_finish(png_ptr, length);
  193687. return;
  193688. }
  193689. else if (png_ptr->mode & PNG_HAVE_PLTE)
  193690. {
  193691. /* Should be an error, but we can cope with it */
  193692. png_warning(png_ptr, "Out of place sBIT chunk");
  193693. }
  193694. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT))
  193695. {
  193696. png_warning(png_ptr, "Duplicate sBIT chunk");
  193697. png_crc_finish(png_ptr, length);
  193698. return;
  193699. }
  193700. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  193701. truelen = 3;
  193702. else
  193703. truelen = (png_size_t)png_ptr->channels;
  193704. if (length != truelen || length > 4)
  193705. {
  193706. png_warning(png_ptr, "Incorrect sBIT chunk length");
  193707. png_crc_finish(png_ptr, length);
  193708. return;
  193709. }
  193710. png_crc_read(png_ptr, buf, truelen);
  193711. if (png_crc_finish(png_ptr, 0))
  193712. return;
  193713. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  193714. {
  193715. png_ptr->sig_bit.red = buf[0];
  193716. png_ptr->sig_bit.green = buf[1];
  193717. png_ptr->sig_bit.blue = buf[2];
  193718. png_ptr->sig_bit.alpha = buf[3];
  193719. }
  193720. else
  193721. {
  193722. png_ptr->sig_bit.gray = buf[0];
  193723. png_ptr->sig_bit.red = buf[0];
  193724. png_ptr->sig_bit.green = buf[0];
  193725. png_ptr->sig_bit.blue = buf[0];
  193726. png_ptr->sig_bit.alpha = buf[1];
  193727. }
  193728. png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit));
  193729. }
  193730. #endif
  193731. #if defined(PNG_READ_cHRM_SUPPORTED)
  193732. void /* PRIVATE */
  193733. png_handle_cHRM(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193734. {
  193735. png_byte buf[4];
  193736. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193737. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  193738. #endif
  193739. png_fixed_point int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  193740. int_y_green, int_x_blue, int_y_blue;
  193741. png_uint_32 uint_x, uint_y;
  193742. png_debug(1, "in png_handle_cHRM\n");
  193743. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  193744. png_error(png_ptr, "Missing IHDR before cHRM");
  193745. else if (png_ptr->mode & PNG_HAVE_IDAT)
  193746. {
  193747. png_warning(png_ptr, "Invalid cHRM after IDAT");
  193748. png_crc_finish(png_ptr, length);
  193749. return;
  193750. }
  193751. else if (png_ptr->mode & PNG_HAVE_PLTE)
  193752. /* Should be an error, but we can cope with it */
  193753. png_warning(png_ptr, "Missing PLTE before cHRM");
  193754. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM)
  193755. #if defined(PNG_READ_sRGB_SUPPORTED)
  193756. && !(info_ptr->valid & PNG_INFO_sRGB)
  193757. #endif
  193758. )
  193759. {
  193760. png_warning(png_ptr, "Duplicate cHRM chunk");
  193761. png_crc_finish(png_ptr, length);
  193762. return;
  193763. }
  193764. if (length != 32)
  193765. {
  193766. png_warning(png_ptr, "Incorrect cHRM chunk length");
  193767. png_crc_finish(png_ptr, length);
  193768. return;
  193769. }
  193770. png_crc_read(png_ptr, buf, 4);
  193771. uint_x = png_get_uint_32(buf);
  193772. png_crc_read(png_ptr, buf, 4);
  193773. uint_y = png_get_uint_32(buf);
  193774. if (uint_x > 80000L || uint_y > 80000L ||
  193775. uint_x + uint_y > 100000L)
  193776. {
  193777. png_warning(png_ptr, "Invalid cHRM white point");
  193778. png_crc_finish(png_ptr, 24);
  193779. return;
  193780. }
  193781. int_x_white = (png_fixed_point)uint_x;
  193782. int_y_white = (png_fixed_point)uint_y;
  193783. png_crc_read(png_ptr, buf, 4);
  193784. uint_x = png_get_uint_32(buf);
  193785. png_crc_read(png_ptr, buf, 4);
  193786. uint_y = png_get_uint_32(buf);
  193787. if (uint_x + uint_y > 100000L)
  193788. {
  193789. png_warning(png_ptr, "Invalid cHRM red point");
  193790. png_crc_finish(png_ptr, 16);
  193791. return;
  193792. }
  193793. int_x_red = (png_fixed_point)uint_x;
  193794. int_y_red = (png_fixed_point)uint_y;
  193795. png_crc_read(png_ptr, buf, 4);
  193796. uint_x = png_get_uint_32(buf);
  193797. png_crc_read(png_ptr, buf, 4);
  193798. uint_y = png_get_uint_32(buf);
  193799. if (uint_x + uint_y > 100000L)
  193800. {
  193801. png_warning(png_ptr, "Invalid cHRM green point");
  193802. png_crc_finish(png_ptr, 8);
  193803. return;
  193804. }
  193805. int_x_green = (png_fixed_point)uint_x;
  193806. int_y_green = (png_fixed_point)uint_y;
  193807. png_crc_read(png_ptr, buf, 4);
  193808. uint_x = png_get_uint_32(buf);
  193809. png_crc_read(png_ptr, buf, 4);
  193810. uint_y = png_get_uint_32(buf);
  193811. if (uint_x + uint_y > 100000L)
  193812. {
  193813. png_warning(png_ptr, "Invalid cHRM blue point");
  193814. png_crc_finish(png_ptr, 0);
  193815. return;
  193816. }
  193817. int_x_blue = (png_fixed_point)uint_x;
  193818. int_y_blue = (png_fixed_point)uint_y;
  193819. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193820. white_x = (float)int_x_white / (float)100000.0;
  193821. white_y = (float)int_y_white / (float)100000.0;
  193822. red_x = (float)int_x_red / (float)100000.0;
  193823. red_y = (float)int_y_red / (float)100000.0;
  193824. green_x = (float)int_x_green / (float)100000.0;
  193825. green_y = (float)int_y_green / (float)100000.0;
  193826. blue_x = (float)int_x_blue / (float)100000.0;
  193827. blue_y = (float)int_y_blue / (float)100000.0;
  193828. #endif
  193829. #if defined(PNG_READ_sRGB_SUPPORTED)
  193830. if ((info_ptr != NULL) && (info_ptr->valid & PNG_INFO_sRGB))
  193831. {
  193832. if (PNG_OUT_OF_RANGE(int_x_white, 31270, 1000) ||
  193833. PNG_OUT_OF_RANGE(int_y_white, 32900, 1000) ||
  193834. PNG_OUT_OF_RANGE(int_x_red, 64000L, 1000) ||
  193835. PNG_OUT_OF_RANGE(int_y_red, 33000, 1000) ||
  193836. PNG_OUT_OF_RANGE(int_x_green, 30000, 1000) ||
  193837. PNG_OUT_OF_RANGE(int_y_green, 60000L, 1000) ||
  193838. PNG_OUT_OF_RANGE(int_x_blue, 15000, 1000) ||
  193839. PNG_OUT_OF_RANGE(int_y_blue, 6000, 1000))
  193840. {
  193841. png_warning(png_ptr,
  193842. "Ignoring incorrect cHRM value when sRGB is also present");
  193843. #ifndef PNG_NO_CONSOLE_IO
  193844. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193845. fprintf(stderr,"wx=%f, wy=%f, rx=%f, ry=%f\n",
  193846. white_x, white_y, red_x, red_y);
  193847. fprintf(stderr,"gx=%f, gy=%f, bx=%f, by=%f\n",
  193848. green_x, green_y, blue_x, blue_y);
  193849. #else
  193850. fprintf(stderr,"wx=%ld, wy=%ld, rx=%ld, ry=%ld\n",
  193851. int_x_white, int_y_white, int_x_red, int_y_red);
  193852. fprintf(stderr,"gx=%ld, gy=%ld, bx=%ld, by=%ld\n",
  193853. int_x_green, int_y_green, int_x_blue, int_y_blue);
  193854. #endif
  193855. #endif /* PNG_NO_CONSOLE_IO */
  193856. }
  193857. png_crc_finish(png_ptr, 0);
  193858. return;
  193859. }
  193860. #endif /* PNG_READ_sRGB_SUPPORTED */
  193861. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193862. png_set_cHRM(png_ptr, info_ptr,
  193863. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  193864. #endif
  193865. #ifdef PNG_FIXED_POINT_SUPPORTED
  193866. png_set_cHRM_fixed(png_ptr, info_ptr,
  193867. int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  193868. int_y_green, int_x_blue, int_y_blue);
  193869. #endif
  193870. if (png_crc_finish(png_ptr, 0))
  193871. return;
  193872. }
  193873. #endif
  193874. #if defined(PNG_READ_sRGB_SUPPORTED)
  193875. void /* PRIVATE */
  193876. png_handle_sRGB(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193877. {
  193878. int intent;
  193879. png_byte buf[1];
  193880. png_debug(1, "in png_handle_sRGB\n");
  193881. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  193882. png_error(png_ptr, "Missing IHDR before sRGB");
  193883. else if (png_ptr->mode & PNG_HAVE_IDAT)
  193884. {
  193885. png_warning(png_ptr, "Invalid sRGB after IDAT");
  193886. png_crc_finish(png_ptr, length);
  193887. return;
  193888. }
  193889. else if (png_ptr->mode & PNG_HAVE_PLTE)
  193890. /* Should be an error, but we can cope with it */
  193891. png_warning(png_ptr, "Out of place sRGB chunk");
  193892. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  193893. {
  193894. png_warning(png_ptr, "Duplicate sRGB chunk");
  193895. png_crc_finish(png_ptr, length);
  193896. return;
  193897. }
  193898. if (length != 1)
  193899. {
  193900. png_warning(png_ptr, "Incorrect sRGB chunk length");
  193901. png_crc_finish(png_ptr, length);
  193902. return;
  193903. }
  193904. png_crc_read(png_ptr, buf, 1);
  193905. if (png_crc_finish(png_ptr, 0))
  193906. return;
  193907. intent = buf[0];
  193908. /* check for bad intent */
  193909. if (intent >= PNG_sRGB_INTENT_LAST)
  193910. {
  193911. png_warning(png_ptr, "Unknown sRGB intent");
  193912. return;
  193913. }
  193914. #if defined(PNG_READ_gAMA_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  193915. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA))
  193916. {
  193917. png_fixed_point igamma;
  193918. #ifdef PNG_FIXED_POINT_SUPPORTED
  193919. igamma=info_ptr->int_gamma;
  193920. #else
  193921. # ifdef PNG_FLOATING_POINT_SUPPORTED
  193922. igamma=(png_fixed_point)(info_ptr->gamma * 100000.);
  193923. # endif
  193924. #endif
  193925. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  193926. {
  193927. png_warning(png_ptr,
  193928. "Ignoring incorrect gAMA value when sRGB is also present");
  193929. #ifndef PNG_NO_CONSOLE_IO
  193930. # ifdef PNG_FIXED_POINT_SUPPORTED
  193931. fprintf(stderr,"incorrect gamma=(%d/100000)\n",(int)png_ptr->int_gamma);
  193932. # else
  193933. # ifdef PNG_FLOATING_POINT_SUPPORTED
  193934. fprintf(stderr,"incorrect gamma=%f\n",png_ptr->gamma);
  193935. # endif
  193936. # endif
  193937. #endif
  193938. }
  193939. }
  193940. #endif /* PNG_READ_gAMA_SUPPORTED */
  193941. #ifdef PNG_READ_cHRM_SUPPORTED
  193942. #ifdef PNG_FIXED_POINT_SUPPORTED
  193943. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  193944. if (PNG_OUT_OF_RANGE(info_ptr->int_x_white, 31270, 1000) ||
  193945. PNG_OUT_OF_RANGE(info_ptr->int_y_white, 32900, 1000) ||
  193946. PNG_OUT_OF_RANGE(info_ptr->int_x_red, 64000L, 1000) ||
  193947. PNG_OUT_OF_RANGE(info_ptr->int_y_red, 33000, 1000) ||
  193948. PNG_OUT_OF_RANGE(info_ptr->int_x_green, 30000, 1000) ||
  193949. PNG_OUT_OF_RANGE(info_ptr->int_y_green, 60000L, 1000) ||
  193950. PNG_OUT_OF_RANGE(info_ptr->int_x_blue, 15000, 1000) ||
  193951. PNG_OUT_OF_RANGE(info_ptr->int_y_blue, 6000, 1000))
  193952. {
  193953. png_warning(png_ptr,
  193954. "Ignoring incorrect cHRM value when sRGB is also present");
  193955. }
  193956. #endif /* PNG_FIXED_POINT_SUPPORTED */
  193957. #endif /* PNG_READ_cHRM_SUPPORTED */
  193958. png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr, intent);
  193959. }
  193960. #endif /* PNG_READ_sRGB_SUPPORTED */
  193961. #if defined(PNG_READ_iCCP_SUPPORTED)
  193962. void /* PRIVATE */
  193963. png_handle_iCCP(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193964. /* Note: this does not properly handle chunks that are > 64K under DOS */
  193965. {
  193966. png_charp chunkdata;
  193967. png_byte compression_type;
  193968. png_bytep pC;
  193969. png_charp profile;
  193970. png_uint_32 skip = 0;
  193971. png_uint_32 profile_size, profile_length;
  193972. png_size_t slength, prefix_length, data_length;
  193973. png_debug(1, "in png_handle_iCCP\n");
  193974. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  193975. png_error(png_ptr, "Missing IHDR before iCCP");
  193976. else if (png_ptr->mode & PNG_HAVE_IDAT)
  193977. {
  193978. png_warning(png_ptr, "Invalid iCCP after IDAT");
  193979. png_crc_finish(png_ptr, length);
  193980. return;
  193981. }
  193982. else if (png_ptr->mode & PNG_HAVE_PLTE)
  193983. /* Should be an error, but we can cope with it */
  193984. png_warning(png_ptr, "Out of place iCCP chunk");
  193985. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP))
  193986. {
  193987. png_warning(png_ptr, "Duplicate iCCP chunk");
  193988. png_crc_finish(png_ptr, length);
  193989. return;
  193990. }
  193991. #ifdef PNG_MAX_MALLOC_64K
  193992. if (length > (png_uint_32)65535L)
  193993. {
  193994. png_warning(png_ptr, "iCCP chunk too large to fit in memory");
  193995. skip = length - (png_uint_32)65535L;
  193996. length = (png_uint_32)65535L;
  193997. }
  193998. #endif
  193999. chunkdata = (png_charp)png_malloc(png_ptr, length + 1);
  194000. slength = (png_size_t)length;
  194001. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  194002. if (png_crc_finish(png_ptr, skip))
  194003. {
  194004. png_free(png_ptr, chunkdata);
  194005. return;
  194006. }
  194007. chunkdata[slength] = 0x00;
  194008. for (profile = chunkdata; *profile; profile++)
  194009. /* empty loop to find end of name */ ;
  194010. ++profile;
  194011. /* there should be at least one zero (the compression type byte)
  194012. following the separator, and we should be on it */
  194013. if ( profile >= chunkdata + slength - 1)
  194014. {
  194015. png_free(png_ptr, chunkdata);
  194016. png_warning(png_ptr, "Malformed iCCP chunk");
  194017. return;
  194018. }
  194019. /* compression_type should always be zero */
  194020. compression_type = *profile++;
  194021. if (compression_type)
  194022. {
  194023. png_warning(png_ptr, "Ignoring nonzero compression type in iCCP chunk");
  194024. compression_type=0x00; /* Reset it to zero (libpng-1.0.6 through 1.0.8
  194025. wrote nonzero) */
  194026. }
  194027. prefix_length = profile - chunkdata;
  194028. chunkdata = png_decompress_chunk(png_ptr, compression_type, chunkdata,
  194029. slength, prefix_length, &data_length);
  194030. profile_length = data_length - prefix_length;
  194031. if ( prefix_length > data_length || profile_length < 4)
  194032. {
  194033. png_free(png_ptr, chunkdata);
  194034. png_warning(png_ptr, "Profile size field missing from iCCP chunk");
  194035. return;
  194036. }
  194037. /* Check the profile_size recorded in the first 32 bits of the ICC profile */
  194038. pC = (png_bytep)(chunkdata+prefix_length);
  194039. profile_size = ((*(pC ))<<24) |
  194040. ((*(pC+1))<<16) |
  194041. ((*(pC+2))<< 8) |
  194042. ((*(pC+3)) );
  194043. if(profile_size < profile_length)
  194044. profile_length = profile_size;
  194045. if(profile_size > profile_length)
  194046. {
  194047. png_free(png_ptr, chunkdata);
  194048. png_warning(png_ptr, "Ignoring truncated iCCP profile.");
  194049. return;
  194050. }
  194051. png_set_iCCP(png_ptr, info_ptr, chunkdata, compression_type,
  194052. chunkdata + prefix_length, profile_length);
  194053. png_free(png_ptr, chunkdata);
  194054. }
  194055. #endif /* PNG_READ_iCCP_SUPPORTED */
  194056. #if defined(PNG_READ_sPLT_SUPPORTED)
  194057. void /* PRIVATE */
  194058. png_handle_sPLT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194059. /* Note: this does not properly handle chunks that are > 64K under DOS */
  194060. {
  194061. png_bytep chunkdata;
  194062. png_bytep entry_start;
  194063. png_sPLT_t new_palette;
  194064. #ifdef PNG_NO_POINTER_INDEXING
  194065. png_sPLT_entryp pp;
  194066. #endif
  194067. int data_length, entry_size, i;
  194068. png_uint_32 skip = 0;
  194069. png_size_t slength;
  194070. png_debug(1, "in png_handle_sPLT\n");
  194071. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194072. png_error(png_ptr, "Missing IHDR before sPLT");
  194073. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194074. {
  194075. png_warning(png_ptr, "Invalid sPLT after IDAT");
  194076. png_crc_finish(png_ptr, length);
  194077. return;
  194078. }
  194079. #ifdef PNG_MAX_MALLOC_64K
  194080. if (length > (png_uint_32)65535L)
  194081. {
  194082. png_warning(png_ptr, "sPLT chunk too large to fit in memory");
  194083. skip = length - (png_uint_32)65535L;
  194084. length = (png_uint_32)65535L;
  194085. }
  194086. #endif
  194087. chunkdata = (png_bytep)png_malloc(png_ptr, length + 1);
  194088. slength = (png_size_t)length;
  194089. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  194090. if (png_crc_finish(png_ptr, skip))
  194091. {
  194092. png_free(png_ptr, chunkdata);
  194093. return;
  194094. }
  194095. chunkdata[slength] = 0x00;
  194096. for (entry_start = chunkdata; *entry_start; entry_start++)
  194097. /* empty loop to find end of name */ ;
  194098. ++entry_start;
  194099. /* a sample depth should follow the separator, and we should be on it */
  194100. if (entry_start > chunkdata + slength - 2)
  194101. {
  194102. png_free(png_ptr, chunkdata);
  194103. png_warning(png_ptr, "malformed sPLT chunk");
  194104. return;
  194105. }
  194106. new_palette.depth = *entry_start++;
  194107. entry_size = (new_palette.depth == 8 ? 6 : 10);
  194108. data_length = (slength - (entry_start - chunkdata));
  194109. /* integrity-check the data length */
  194110. if (data_length % entry_size)
  194111. {
  194112. png_free(png_ptr, chunkdata);
  194113. png_warning(png_ptr, "sPLT chunk has bad length");
  194114. return;
  194115. }
  194116. new_palette.nentries = (png_int_32) ( data_length / entry_size);
  194117. if ((png_uint_32) new_palette.nentries > (png_uint_32) (PNG_SIZE_MAX /
  194118. png_sizeof(png_sPLT_entry)))
  194119. {
  194120. png_warning(png_ptr, "sPLT chunk too long");
  194121. return;
  194122. }
  194123. new_palette.entries = (png_sPLT_entryp)png_malloc_warn(
  194124. png_ptr, new_palette.nentries * png_sizeof(png_sPLT_entry));
  194125. if (new_palette.entries == NULL)
  194126. {
  194127. png_warning(png_ptr, "sPLT chunk requires too much memory");
  194128. return;
  194129. }
  194130. #ifndef PNG_NO_POINTER_INDEXING
  194131. for (i = 0; i < new_palette.nentries; i++)
  194132. {
  194133. png_sPLT_entryp pp = new_palette.entries + i;
  194134. if (new_palette.depth == 8)
  194135. {
  194136. pp->red = *entry_start++;
  194137. pp->green = *entry_start++;
  194138. pp->blue = *entry_start++;
  194139. pp->alpha = *entry_start++;
  194140. }
  194141. else
  194142. {
  194143. pp->red = png_get_uint_16(entry_start); entry_start += 2;
  194144. pp->green = png_get_uint_16(entry_start); entry_start += 2;
  194145. pp->blue = png_get_uint_16(entry_start); entry_start += 2;
  194146. pp->alpha = png_get_uint_16(entry_start); entry_start += 2;
  194147. }
  194148. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  194149. }
  194150. #else
  194151. pp = new_palette.entries;
  194152. for (i = 0; i < new_palette.nentries; i++)
  194153. {
  194154. if (new_palette.depth == 8)
  194155. {
  194156. pp[i].red = *entry_start++;
  194157. pp[i].green = *entry_start++;
  194158. pp[i].blue = *entry_start++;
  194159. pp[i].alpha = *entry_start++;
  194160. }
  194161. else
  194162. {
  194163. pp[i].red = png_get_uint_16(entry_start); entry_start += 2;
  194164. pp[i].green = png_get_uint_16(entry_start); entry_start += 2;
  194165. pp[i].blue = png_get_uint_16(entry_start); entry_start += 2;
  194166. pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2;
  194167. }
  194168. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  194169. }
  194170. #endif
  194171. /* discard all chunk data except the name and stash that */
  194172. new_palette.name = (png_charp)chunkdata;
  194173. png_set_sPLT(png_ptr, info_ptr, &new_palette, 1);
  194174. png_free(png_ptr, chunkdata);
  194175. png_free(png_ptr, new_palette.entries);
  194176. }
  194177. #endif /* PNG_READ_sPLT_SUPPORTED */
  194178. #if defined(PNG_READ_tRNS_SUPPORTED)
  194179. void /* PRIVATE */
  194180. png_handle_tRNS(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194181. {
  194182. png_byte readbuf[PNG_MAX_PALETTE_LENGTH];
  194183. int bit_mask;
  194184. png_debug(1, "in png_handle_tRNS\n");
  194185. /* For non-indexed color, mask off any bits in the tRNS value that
  194186. * exceed the bit depth. Some creators were writing extra bits there.
  194187. * This is not needed for indexed color. */
  194188. bit_mask = (1 << png_ptr->bit_depth) - 1;
  194189. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194190. png_error(png_ptr, "Missing IHDR before tRNS");
  194191. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194192. {
  194193. png_warning(png_ptr, "Invalid tRNS after IDAT");
  194194. png_crc_finish(png_ptr, length);
  194195. return;
  194196. }
  194197. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  194198. {
  194199. png_warning(png_ptr, "Duplicate tRNS chunk");
  194200. png_crc_finish(png_ptr, length);
  194201. return;
  194202. }
  194203. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  194204. {
  194205. png_byte buf[2];
  194206. if (length != 2)
  194207. {
  194208. png_warning(png_ptr, "Incorrect tRNS chunk length");
  194209. png_crc_finish(png_ptr, length);
  194210. return;
  194211. }
  194212. png_crc_read(png_ptr, buf, 2);
  194213. png_ptr->num_trans = 1;
  194214. png_ptr->trans_values.gray = png_get_uint_16(buf) & bit_mask;
  194215. }
  194216. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  194217. {
  194218. png_byte buf[6];
  194219. if (length != 6)
  194220. {
  194221. png_warning(png_ptr, "Incorrect tRNS chunk length");
  194222. png_crc_finish(png_ptr, length);
  194223. return;
  194224. }
  194225. png_crc_read(png_ptr, buf, (png_size_t)length);
  194226. png_ptr->num_trans = 1;
  194227. png_ptr->trans_values.red = png_get_uint_16(buf) & bit_mask;
  194228. png_ptr->trans_values.green = png_get_uint_16(buf + 2) & bit_mask;
  194229. png_ptr->trans_values.blue = png_get_uint_16(buf + 4) & bit_mask;
  194230. }
  194231. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194232. {
  194233. if (!(png_ptr->mode & PNG_HAVE_PLTE))
  194234. {
  194235. /* Should be an error, but we can cope with it. */
  194236. png_warning(png_ptr, "Missing PLTE before tRNS");
  194237. }
  194238. if (length > (png_uint_32)png_ptr->num_palette ||
  194239. length > PNG_MAX_PALETTE_LENGTH)
  194240. {
  194241. png_warning(png_ptr, "Incorrect tRNS chunk length");
  194242. png_crc_finish(png_ptr, length);
  194243. return;
  194244. }
  194245. if (length == 0)
  194246. {
  194247. png_warning(png_ptr, "Zero length tRNS chunk");
  194248. png_crc_finish(png_ptr, length);
  194249. return;
  194250. }
  194251. png_crc_read(png_ptr, readbuf, (png_size_t)length);
  194252. png_ptr->num_trans = (png_uint_16)length;
  194253. }
  194254. else
  194255. {
  194256. png_warning(png_ptr, "tRNS chunk not allowed with alpha channel");
  194257. png_crc_finish(png_ptr, length);
  194258. return;
  194259. }
  194260. if (png_crc_finish(png_ptr, 0))
  194261. {
  194262. png_ptr->num_trans = 0;
  194263. return;
  194264. }
  194265. png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans,
  194266. &(png_ptr->trans_values));
  194267. }
  194268. #endif
  194269. #if defined(PNG_READ_bKGD_SUPPORTED)
  194270. void /* PRIVATE */
  194271. png_handle_bKGD(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194272. {
  194273. png_size_t truelen;
  194274. png_byte buf[6];
  194275. png_debug(1, "in png_handle_bKGD\n");
  194276. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194277. png_error(png_ptr, "Missing IHDR before bKGD");
  194278. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194279. {
  194280. png_warning(png_ptr, "Invalid bKGD after IDAT");
  194281. png_crc_finish(png_ptr, length);
  194282. return;
  194283. }
  194284. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  194285. !(png_ptr->mode & PNG_HAVE_PLTE))
  194286. {
  194287. png_warning(png_ptr, "Missing PLTE before bKGD");
  194288. png_crc_finish(png_ptr, length);
  194289. return;
  194290. }
  194291. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD))
  194292. {
  194293. png_warning(png_ptr, "Duplicate bKGD chunk");
  194294. png_crc_finish(png_ptr, length);
  194295. return;
  194296. }
  194297. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194298. truelen = 1;
  194299. else if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  194300. truelen = 6;
  194301. else
  194302. truelen = 2;
  194303. if (length != truelen)
  194304. {
  194305. png_warning(png_ptr, "Incorrect bKGD chunk length");
  194306. png_crc_finish(png_ptr, length);
  194307. return;
  194308. }
  194309. png_crc_read(png_ptr, buf, truelen);
  194310. if (png_crc_finish(png_ptr, 0))
  194311. return;
  194312. /* We convert the index value into RGB components so that we can allow
  194313. * arbitrary RGB values for background when we have transparency, and
  194314. * so it is easy to determine the RGB values of the background color
  194315. * from the info_ptr struct. */
  194316. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194317. {
  194318. png_ptr->background.index = buf[0];
  194319. if(info_ptr->num_palette)
  194320. {
  194321. if(buf[0] > info_ptr->num_palette)
  194322. {
  194323. png_warning(png_ptr, "Incorrect bKGD chunk index value");
  194324. return;
  194325. }
  194326. png_ptr->background.red =
  194327. (png_uint_16)png_ptr->palette[buf[0]].red;
  194328. png_ptr->background.green =
  194329. (png_uint_16)png_ptr->palette[buf[0]].green;
  194330. png_ptr->background.blue =
  194331. (png_uint_16)png_ptr->palette[buf[0]].blue;
  194332. }
  194333. }
  194334. else if (!(png_ptr->color_type & PNG_COLOR_MASK_COLOR)) /* GRAY */
  194335. {
  194336. png_ptr->background.red =
  194337. png_ptr->background.green =
  194338. png_ptr->background.blue =
  194339. png_ptr->background.gray = png_get_uint_16(buf);
  194340. }
  194341. else
  194342. {
  194343. png_ptr->background.red = png_get_uint_16(buf);
  194344. png_ptr->background.green = png_get_uint_16(buf + 2);
  194345. png_ptr->background.blue = png_get_uint_16(buf + 4);
  194346. }
  194347. png_set_bKGD(png_ptr, info_ptr, &(png_ptr->background));
  194348. }
  194349. #endif
  194350. #if defined(PNG_READ_hIST_SUPPORTED)
  194351. void /* PRIVATE */
  194352. png_handle_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194353. {
  194354. unsigned int num, i;
  194355. png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH];
  194356. png_debug(1, "in png_handle_hIST\n");
  194357. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194358. png_error(png_ptr, "Missing IHDR before hIST");
  194359. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194360. {
  194361. png_warning(png_ptr, "Invalid hIST after IDAT");
  194362. png_crc_finish(png_ptr, length);
  194363. return;
  194364. }
  194365. else if (!(png_ptr->mode & PNG_HAVE_PLTE))
  194366. {
  194367. png_warning(png_ptr, "Missing PLTE before hIST");
  194368. png_crc_finish(png_ptr, length);
  194369. return;
  194370. }
  194371. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST))
  194372. {
  194373. png_warning(png_ptr, "Duplicate hIST chunk");
  194374. png_crc_finish(png_ptr, length);
  194375. return;
  194376. }
  194377. num = length / 2 ;
  194378. if (num != (unsigned int) png_ptr->num_palette || num >
  194379. (unsigned int) PNG_MAX_PALETTE_LENGTH)
  194380. {
  194381. png_warning(png_ptr, "Incorrect hIST chunk length");
  194382. png_crc_finish(png_ptr, length);
  194383. return;
  194384. }
  194385. for (i = 0; i < num; i++)
  194386. {
  194387. png_byte buf[2];
  194388. png_crc_read(png_ptr, buf, 2);
  194389. readbuf[i] = png_get_uint_16(buf);
  194390. }
  194391. if (png_crc_finish(png_ptr, 0))
  194392. return;
  194393. png_set_hIST(png_ptr, info_ptr, readbuf);
  194394. }
  194395. #endif
  194396. #if defined(PNG_READ_pHYs_SUPPORTED)
  194397. void /* PRIVATE */
  194398. png_handle_pHYs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194399. {
  194400. png_byte buf[9];
  194401. png_uint_32 res_x, res_y;
  194402. int unit_type;
  194403. png_debug(1, "in png_handle_pHYs\n");
  194404. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194405. png_error(png_ptr, "Missing IHDR before pHYs");
  194406. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194407. {
  194408. png_warning(png_ptr, "Invalid pHYs after IDAT");
  194409. png_crc_finish(png_ptr, length);
  194410. return;
  194411. }
  194412. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  194413. {
  194414. png_warning(png_ptr, "Duplicate pHYs chunk");
  194415. png_crc_finish(png_ptr, length);
  194416. return;
  194417. }
  194418. if (length != 9)
  194419. {
  194420. png_warning(png_ptr, "Incorrect pHYs chunk length");
  194421. png_crc_finish(png_ptr, length);
  194422. return;
  194423. }
  194424. png_crc_read(png_ptr, buf, 9);
  194425. if (png_crc_finish(png_ptr, 0))
  194426. return;
  194427. res_x = png_get_uint_32(buf);
  194428. res_y = png_get_uint_32(buf + 4);
  194429. unit_type = buf[8];
  194430. png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
  194431. }
  194432. #endif
  194433. #if defined(PNG_READ_oFFs_SUPPORTED)
  194434. void /* PRIVATE */
  194435. png_handle_oFFs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194436. {
  194437. png_byte buf[9];
  194438. png_int_32 offset_x, offset_y;
  194439. int unit_type;
  194440. png_debug(1, "in png_handle_oFFs\n");
  194441. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194442. png_error(png_ptr, "Missing IHDR before oFFs");
  194443. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194444. {
  194445. png_warning(png_ptr, "Invalid oFFs after IDAT");
  194446. png_crc_finish(png_ptr, length);
  194447. return;
  194448. }
  194449. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs))
  194450. {
  194451. png_warning(png_ptr, "Duplicate oFFs chunk");
  194452. png_crc_finish(png_ptr, length);
  194453. return;
  194454. }
  194455. if (length != 9)
  194456. {
  194457. png_warning(png_ptr, "Incorrect oFFs chunk length");
  194458. png_crc_finish(png_ptr, length);
  194459. return;
  194460. }
  194461. png_crc_read(png_ptr, buf, 9);
  194462. if (png_crc_finish(png_ptr, 0))
  194463. return;
  194464. offset_x = png_get_int_32(buf);
  194465. offset_y = png_get_int_32(buf + 4);
  194466. unit_type = buf[8];
  194467. png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);
  194468. }
  194469. #endif
  194470. #if defined(PNG_READ_pCAL_SUPPORTED)
  194471. /* read the pCAL chunk (described in the PNG Extensions document) */
  194472. void /* PRIVATE */
  194473. png_handle_pCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194474. {
  194475. png_charp purpose;
  194476. png_int_32 X0, X1;
  194477. png_byte type, nparams;
  194478. png_charp buf, units, endptr;
  194479. png_charpp params;
  194480. png_size_t slength;
  194481. int i;
  194482. png_debug(1, "in png_handle_pCAL\n");
  194483. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194484. png_error(png_ptr, "Missing IHDR before pCAL");
  194485. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194486. {
  194487. png_warning(png_ptr, "Invalid pCAL after IDAT");
  194488. png_crc_finish(png_ptr, length);
  194489. return;
  194490. }
  194491. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL))
  194492. {
  194493. png_warning(png_ptr, "Duplicate pCAL chunk");
  194494. png_crc_finish(png_ptr, length);
  194495. return;
  194496. }
  194497. png_debug1(2, "Allocating and reading pCAL chunk data (%lu bytes)\n",
  194498. length + 1);
  194499. purpose = (png_charp)png_malloc_warn(png_ptr, length + 1);
  194500. if (purpose == NULL)
  194501. {
  194502. png_warning(png_ptr, "No memory for pCAL purpose.");
  194503. return;
  194504. }
  194505. slength = (png_size_t)length;
  194506. png_crc_read(png_ptr, (png_bytep)purpose, slength);
  194507. if (png_crc_finish(png_ptr, 0))
  194508. {
  194509. png_free(png_ptr, purpose);
  194510. return;
  194511. }
  194512. purpose[slength] = 0x00; /* null terminate the last string */
  194513. png_debug(3, "Finding end of pCAL purpose string\n");
  194514. for (buf = purpose; *buf; buf++)
  194515. /* empty loop */ ;
  194516. endptr = purpose + slength;
  194517. /* We need to have at least 12 bytes after the purpose string
  194518. in order to get the parameter information. */
  194519. if (endptr <= buf + 12)
  194520. {
  194521. png_warning(png_ptr, "Invalid pCAL data");
  194522. png_free(png_ptr, purpose);
  194523. return;
  194524. }
  194525. png_debug(3, "Reading pCAL X0, X1, type, nparams, and units\n");
  194526. X0 = png_get_int_32((png_bytep)buf+1);
  194527. X1 = png_get_int_32((png_bytep)buf+5);
  194528. type = buf[9];
  194529. nparams = buf[10];
  194530. units = buf + 11;
  194531. png_debug(3, "Checking pCAL equation type and number of parameters\n");
  194532. /* Check that we have the right number of parameters for known
  194533. equation types. */
  194534. if ((type == PNG_EQUATION_LINEAR && nparams != 2) ||
  194535. (type == PNG_EQUATION_BASE_E && nparams != 3) ||
  194536. (type == PNG_EQUATION_ARBITRARY && nparams != 3) ||
  194537. (type == PNG_EQUATION_HYPERBOLIC && nparams != 4))
  194538. {
  194539. png_warning(png_ptr, "Invalid pCAL parameters for equation type");
  194540. png_free(png_ptr, purpose);
  194541. return;
  194542. }
  194543. else if (type >= PNG_EQUATION_LAST)
  194544. {
  194545. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  194546. }
  194547. for (buf = units; *buf; buf++)
  194548. /* Empty loop to move past the units string. */ ;
  194549. png_debug(3, "Allocating pCAL parameters array\n");
  194550. params = (png_charpp)png_malloc_warn(png_ptr, (png_uint_32)(nparams
  194551. *png_sizeof(png_charp))) ;
  194552. if (params == NULL)
  194553. {
  194554. png_free(png_ptr, purpose);
  194555. png_warning(png_ptr, "No memory for pCAL params.");
  194556. return;
  194557. }
  194558. /* Get pointers to the start of each parameter string. */
  194559. for (i = 0; i < (int)nparams; i++)
  194560. {
  194561. buf++; /* Skip the null string terminator from previous parameter. */
  194562. png_debug1(3, "Reading pCAL parameter %d\n", i);
  194563. for (params[i] = buf; buf <= endptr && *buf != 0x00; buf++)
  194564. /* Empty loop to move past each parameter string */ ;
  194565. /* Make sure we haven't run out of data yet */
  194566. if (buf > endptr)
  194567. {
  194568. png_warning(png_ptr, "Invalid pCAL data");
  194569. png_free(png_ptr, purpose);
  194570. png_free(png_ptr, params);
  194571. return;
  194572. }
  194573. }
  194574. png_set_pCAL(png_ptr, info_ptr, purpose, X0, X1, type, nparams,
  194575. units, params);
  194576. png_free(png_ptr, purpose);
  194577. png_free(png_ptr, params);
  194578. }
  194579. #endif
  194580. #if defined(PNG_READ_sCAL_SUPPORTED)
  194581. /* read the sCAL chunk */
  194582. void /* PRIVATE */
  194583. png_handle_sCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194584. {
  194585. png_charp buffer, ep;
  194586. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194587. double width, height;
  194588. png_charp vp;
  194589. #else
  194590. #ifdef PNG_FIXED_POINT_SUPPORTED
  194591. png_charp swidth, sheight;
  194592. #endif
  194593. #endif
  194594. png_size_t slength;
  194595. png_debug(1, "in png_handle_sCAL\n");
  194596. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194597. png_error(png_ptr, "Missing IHDR before sCAL");
  194598. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194599. {
  194600. png_warning(png_ptr, "Invalid sCAL after IDAT");
  194601. png_crc_finish(png_ptr, length);
  194602. return;
  194603. }
  194604. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL))
  194605. {
  194606. png_warning(png_ptr, "Duplicate sCAL chunk");
  194607. png_crc_finish(png_ptr, length);
  194608. return;
  194609. }
  194610. png_debug1(2, "Allocating and reading sCAL chunk data (%lu bytes)\n",
  194611. length + 1);
  194612. buffer = (png_charp)png_malloc_warn(png_ptr, length + 1);
  194613. if (buffer == NULL)
  194614. {
  194615. png_warning(png_ptr, "Out of memory while processing sCAL chunk");
  194616. return;
  194617. }
  194618. slength = (png_size_t)length;
  194619. png_crc_read(png_ptr, (png_bytep)buffer, slength);
  194620. if (png_crc_finish(png_ptr, 0))
  194621. {
  194622. png_free(png_ptr, buffer);
  194623. return;
  194624. }
  194625. buffer[slength] = 0x00; /* null terminate the last string */
  194626. ep = buffer + 1; /* skip unit byte */
  194627. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194628. width = png_strtod(png_ptr, ep, &vp);
  194629. if (*vp)
  194630. {
  194631. png_warning(png_ptr, "malformed width string in sCAL chunk");
  194632. return;
  194633. }
  194634. #else
  194635. #ifdef PNG_FIXED_POINT_SUPPORTED
  194636. swidth = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  194637. if (swidth == NULL)
  194638. {
  194639. png_warning(png_ptr, "Out of memory while processing sCAL chunk width");
  194640. return;
  194641. }
  194642. png_memcpy(swidth, ep, (png_size_t)png_strlen(ep));
  194643. #endif
  194644. #endif
  194645. for (ep = buffer; *ep; ep++)
  194646. /* empty loop */ ;
  194647. ep++;
  194648. if (buffer + slength < ep)
  194649. {
  194650. png_warning(png_ptr, "Truncated sCAL chunk");
  194651. #if defined(PNG_FIXED_POINT_SUPPORTED) && \
  194652. !defined(PNG_FLOATING_POINT_SUPPORTED)
  194653. png_free(png_ptr, swidth);
  194654. #endif
  194655. png_free(png_ptr, buffer);
  194656. return;
  194657. }
  194658. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194659. height = png_strtod(png_ptr, ep, &vp);
  194660. if (*vp)
  194661. {
  194662. png_warning(png_ptr, "malformed height string in sCAL chunk");
  194663. return;
  194664. }
  194665. #else
  194666. #ifdef PNG_FIXED_POINT_SUPPORTED
  194667. sheight = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  194668. if (swidth == NULL)
  194669. {
  194670. png_warning(png_ptr, "Out of memory while processing sCAL chunk height");
  194671. return;
  194672. }
  194673. png_memcpy(sheight, ep, (png_size_t)png_strlen(ep));
  194674. #endif
  194675. #endif
  194676. if (buffer + slength < ep
  194677. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194678. || width <= 0. || height <= 0.
  194679. #endif
  194680. )
  194681. {
  194682. png_warning(png_ptr, "Invalid sCAL data");
  194683. png_free(png_ptr, buffer);
  194684. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  194685. png_free(png_ptr, swidth);
  194686. png_free(png_ptr, sheight);
  194687. #endif
  194688. return;
  194689. }
  194690. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194691. png_set_sCAL(png_ptr, info_ptr, buffer[0], width, height);
  194692. #else
  194693. #ifdef PNG_FIXED_POINT_SUPPORTED
  194694. png_set_sCAL_s(png_ptr, info_ptr, buffer[0], swidth, sheight);
  194695. #endif
  194696. #endif
  194697. png_free(png_ptr, buffer);
  194698. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  194699. png_free(png_ptr, swidth);
  194700. png_free(png_ptr, sheight);
  194701. #endif
  194702. }
  194703. #endif
  194704. #if defined(PNG_READ_tIME_SUPPORTED)
  194705. void /* PRIVATE */
  194706. png_handle_tIME(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194707. {
  194708. png_byte buf[7];
  194709. png_time mod_time;
  194710. png_debug(1, "in png_handle_tIME\n");
  194711. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194712. png_error(png_ptr, "Out of place tIME chunk");
  194713. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME))
  194714. {
  194715. png_warning(png_ptr, "Duplicate tIME chunk");
  194716. png_crc_finish(png_ptr, length);
  194717. return;
  194718. }
  194719. if (png_ptr->mode & PNG_HAVE_IDAT)
  194720. png_ptr->mode |= PNG_AFTER_IDAT;
  194721. if (length != 7)
  194722. {
  194723. png_warning(png_ptr, "Incorrect tIME chunk length");
  194724. png_crc_finish(png_ptr, length);
  194725. return;
  194726. }
  194727. png_crc_read(png_ptr, buf, 7);
  194728. if (png_crc_finish(png_ptr, 0))
  194729. return;
  194730. mod_time.second = buf[6];
  194731. mod_time.minute = buf[5];
  194732. mod_time.hour = buf[4];
  194733. mod_time.day = buf[3];
  194734. mod_time.month = buf[2];
  194735. mod_time.year = png_get_uint_16(buf);
  194736. png_set_tIME(png_ptr, info_ptr, &mod_time);
  194737. }
  194738. #endif
  194739. #if defined(PNG_READ_tEXt_SUPPORTED)
  194740. /* Note: this does not properly handle chunks that are > 64K under DOS */
  194741. void /* PRIVATE */
  194742. png_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194743. {
  194744. png_textp text_ptr;
  194745. png_charp key;
  194746. png_charp text;
  194747. png_uint_32 skip = 0;
  194748. png_size_t slength;
  194749. int ret;
  194750. png_debug(1, "in png_handle_tEXt\n");
  194751. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194752. png_error(png_ptr, "Missing IHDR before tEXt");
  194753. if (png_ptr->mode & PNG_HAVE_IDAT)
  194754. png_ptr->mode |= PNG_AFTER_IDAT;
  194755. #ifdef PNG_MAX_MALLOC_64K
  194756. if (length > (png_uint_32)65535L)
  194757. {
  194758. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  194759. skip = length - (png_uint_32)65535L;
  194760. length = (png_uint_32)65535L;
  194761. }
  194762. #endif
  194763. key = (png_charp)png_malloc_warn(png_ptr, length + 1);
  194764. if (key == NULL)
  194765. {
  194766. png_warning(png_ptr, "No memory to process text chunk.");
  194767. return;
  194768. }
  194769. slength = (png_size_t)length;
  194770. png_crc_read(png_ptr, (png_bytep)key, slength);
  194771. if (png_crc_finish(png_ptr, skip))
  194772. {
  194773. png_free(png_ptr, key);
  194774. return;
  194775. }
  194776. key[slength] = 0x00;
  194777. for (text = key; *text; text++)
  194778. /* empty loop to find end of key */ ;
  194779. if (text != key + slength)
  194780. text++;
  194781. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  194782. (png_uint_32)png_sizeof(png_text));
  194783. if (text_ptr == NULL)
  194784. {
  194785. png_warning(png_ptr, "Not enough memory to process text chunk.");
  194786. png_free(png_ptr, key);
  194787. return;
  194788. }
  194789. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  194790. text_ptr->key = key;
  194791. #ifdef PNG_iTXt_SUPPORTED
  194792. text_ptr->lang = NULL;
  194793. text_ptr->lang_key = NULL;
  194794. text_ptr->itxt_length = 0;
  194795. #endif
  194796. text_ptr->text = text;
  194797. text_ptr->text_length = png_strlen(text);
  194798. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  194799. png_free(png_ptr, key);
  194800. png_free(png_ptr, text_ptr);
  194801. if (ret)
  194802. png_warning(png_ptr, "Insufficient memory to process text chunk.");
  194803. }
  194804. #endif
  194805. #if defined(PNG_READ_zTXt_SUPPORTED)
  194806. /* note: this does not correctly handle chunks that are > 64K under DOS */
  194807. void /* PRIVATE */
  194808. png_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194809. {
  194810. png_textp text_ptr;
  194811. png_charp chunkdata;
  194812. png_charp text;
  194813. int comp_type;
  194814. int ret;
  194815. png_size_t slength, prefix_len, data_len;
  194816. png_debug(1, "in png_handle_zTXt\n");
  194817. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194818. png_error(png_ptr, "Missing IHDR before zTXt");
  194819. if (png_ptr->mode & PNG_HAVE_IDAT)
  194820. png_ptr->mode |= PNG_AFTER_IDAT;
  194821. #ifdef PNG_MAX_MALLOC_64K
  194822. /* We will no doubt have problems with chunks even half this size, but
  194823. there is no hard and fast rule to tell us where to stop. */
  194824. if (length > (png_uint_32)65535L)
  194825. {
  194826. png_warning(png_ptr,"zTXt chunk too large to fit in memory");
  194827. png_crc_finish(png_ptr, length);
  194828. return;
  194829. }
  194830. #endif
  194831. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  194832. if (chunkdata == NULL)
  194833. {
  194834. png_warning(png_ptr,"Out of memory processing zTXt chunk.");
  194835. return;
  194836. }
  194837. slength = (png_size_t)length;
  194838. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  194839. if (png_crc_finish(png_ptr, 0))
  194840. {
  194841. png_free(png_ptr, chunkdata);
  194842. return;
  194843. }
  194844. chunkdata[slength] = 0x00;
  194845. for (text = chunkdata; *text; text++)
  194846. /* empty loop */ ;
  194847. /* zTXt must have some text after the chunkdataword */
  194848. if (text >= chunkdata + slength - 2)
  194849. {
  194850. png_warning(png_ptr, "Truncated zTXt chunk");
  194851. png_free(png_ptr, chunkdata);
  194852. return;
  194853. }
  194854. else
  194855. {
  194856. comp_type = *(++text);
  194857. if (comp_type != PNG_TEXT_COMPRESSION_zTXt)
  194858. {
  194859. png_warning(png_ptr, "Unknown compression type in zTXt chunk");
  194860. comp_type = PNG_TEXT_COMPRESSION_zTXt;
  194861. }
  194862. text++; /* skip the compression_method byte */
  194863. }
  194864. prefix_len = text - chunkdata;
  194865. chunkdata = (png_charp)png_decompress_chunk(png_ptr, comp_type, chunkdata,
  194866. (png_size_t)length, prefix_len, &data_len);
  194867. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  194868. (png_uint_32)png_sizeof(png_text));
  194869. if (text_ptr == NULL)
  194870. {
  194871. png_warning(png_ptr,"Not enough memory to process zTXt chunk.");
  194872. png_free(png_ptr, chunkdata);
  194873. return;
  194874. }
  194875. text_ptr->compression = comp_type;
  194876. text_ptr->key = chunkdata;
  194877. #ifdef PNG_iTXt_SUPPORTED
  194878. text_ptr->lang = NULL;
  194879. text_ptr->lang_key = NULL;
  194880. text_ptr->itxt_length = 0;
  194881. #endif
  194882. text_ptr->text = chunkdata + prefix_len;
  194883. text_ptr->text_length = data_len;
  194884. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  194885. png_free(png_ptr, text_ptr);
  194886. png_free(png_ptr, chunkdata);
  194887. if (ret)
  194888. png_error(png_ptr, "Insufficient memory to store zTXt chunk.");
  194889. }
  194890. #endif
  194891. #if defined(PNG_READ_iTXt_SUPPORTED)
  194892. /* note: this does not correctly handle chunks that are > 64K under DOS */
  194893. void /* PRIVATE */
  194894. png_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194895. {
  194896. png_textp text_ptr;
  194897. png_charp chunkdata;
  194898. png_charp key, lang, text, lang_key;
  194899. int comp_flag;
  194900. int comp_type = 0;
  194901. int ret;
  194902. png_size_t slength, prefix_len, data_len;
  194903. png_debug(1, "in png_handle_iTXt\n");
  194904. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194905. png_error(png_ptr, "Missing IHDR before iTXt");
  194906. if (png_ptr->mode & PNG_HAVE_IDAT)
  194907. png_ptr->mode |= PNG_AFTER_IDAT;
  194908. #ifdef PNG_MAX_MALLOC_64K
  194909. /* We will no doubt have problems with chunks even half this size, but
  194910. there is no hard and fast rule to tell us where to stop. */
  194911. if (length > (png_uint_32)65535L)
  194912. {
  194913. png_warning(png_ptr,"iTXt chunk too large to fit in memory");
  194914. png_crc_finish(png_ptr, length);
  194915. return;
  194916. }
  194917. #endif
  194918. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  194919. if (chunkdata == NULL)
  194920. {
  194921. png_warning(png_ptr, "No memory to process iTXt chunk.");
  194922. return;
  194923. }
  194924. slength = (png_size_t)length;
  194925. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  194926. if (png_crc_finish(png_ptr, 0))
  194927. {
  194928. png_free(png_ptr, chunkdata);
  194929. return;
  194930. }
  194931. chunkdata[slength] = 0x00;
  194932. for (lang = chunkdata; *lang; lang++)
  194933. /* empty loop */ ;
  194934. lang++; /* skip NUL separator */
  194935. /* iTXt must have a language tag (possibly empty), two compression bytes,
  194936. translated keyword (possibly empty), and possibly some text after the
  194937. keyword */
  194938. if (lang >= chunkdata + slength - 3)
  194939. {
  194940. png_warning(png_ptr, "Truncated iTXt chunk");
  194941. png_free(png_ptr, chunkdata);
  194942. return;
  194943. }
  194944. else
  194945. {
  194946. comp_flag = *lang++;
  194947. comp_type = *lang++;
  194948. }
  194949. for (lang_key = lang; *lang_key; lang_key++)
  194950. /* empty loop */ ;
  194951. lang_key++; /* skip NUL separator */
  194952. if (lang_key >= chunkdata + slength)
  194953. {
  194954. png_warning(png_ptr, "Truncated iTXt chunk");
  194955. png_free(png_ptr, chunkdata);
  194956. return;
  194957. }
  194958. for (text = lang_key; *text; text++)
  194959. /* empty loop */ ;
  194960. text++; /* skip NUL separator */
  194961. if (text >= chunkdata + slength)
  194962. {
  194963. png_warning(png_ptr, "Malformed iTXt chunk");
  194964. png_free(png_ptr, chunkdata);
  194965. return;
  194966. }
  194967. prefix_len = text - chunkdata;
  194968. key=chunkdata;
  194969. if (comp_flag)
  194970. chunkdata = png_decompress_chunk(png_ptr, comp_type, chunkdata,
  194971. (size_t)length, prefix_len, &data_len);
  194972. else
  194973. data_len=png_strlen(chunkdata + prefix_len);
  194974. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  194975. (png_uint_32)png_sizeof(png_text));
  194976. if (text_ptr == NULL)
  194977. {
  194978. png_warning(png_ptr,"Not enough memory to process iTXt chunk.");
  194979. png_free(png_ptr, chunkdata);
  194980. return;
  194981. }
  194982. text_ptr->compression = (int)comp_flag + 1;
  194983. text_ptr->lang_key = chunkdata+(lang_key-key);
  194984. text_ptr->lang = chunkdata+(lang-key);
  194985. text_ptr->itxt_length = data_len;
  194986. text_ptr->text_length = 0;
  194987. text_ptr->key = chunkdata;
  194988. text_ptr->text = chunkdata + prefix_len;
  194989. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  194990. png_free(png_ptr, text_ptr);
  194991. png_free(png_ptr, chunkdata);
  194992. if (ret)
  194993. png_error(png_ptr, "Insufficient memory to store iTXt chunk.");
  194994. }
  194995. #endif
  194996. /* This function is called when we haven't found a handler for a
  194997. chunk. If there isn't a problem with the chunk itself (ie bad
  194998. chunk name, CRC, or a critical chunk), the chunk is silently ignored
  194999. -- unless the PNG_FLAG_UNKNOWN_CHUNKS_SUPPORTED flag is on in which
  195000. case it will be saved away to be written out later. */
  195001. void /* PRIVATE */
  195002. png_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195003. {
  195004. png_uint_32 skip = 0;
  195005. png_debug(1, "in png_handle_unknown\n");
  195006. if (png_ptr->mode & PNG_HAVE_IDAT)
  195007. {
  195008. #ifdef PNG_USE_LOCAL_ARRAYS
  195009. PNG_CONST PNG_IDAT;
  195010. #endif
  195011. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) /* not an IDAT */
  195012. png_ptr->mode |= PNG_AFTER_IDAT;
  195013. }
  195014. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  195015. if (!(png_ptr->chunk_name[0] & 0x20))
  195016. {
  195017. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  195018. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  195019. PNG_HANDLE_CHUNK_ALWAYS
  195020. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195021. && png_ptr->read_user_chunk_fn == NULL
  195022. #endif
  195023. )
  195024. #endif
  195025. png_chunk_error(png_ptr, "unknown critical chunk");
  195026. }
  195027. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  195028. if ((png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS) ||
  195029. (png_ptr->read_user_chunk_fn != NULL))
  195030. {
  195031. #ifdef PNG_MAX_MALLOC_64K
  195032. if (length > (png_uint_32)65535L)
  195033. {
  195034. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  195035. skip = length - (png_uint_32)65535L;
  195036. length = (png_uint_32)65535L;
  195037. }
  195038. #endif
  195039. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  195040. (png_charp)png_ptr->chunk_name, 5);
  195041. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  195042. png_ptr->unknown_chunk.size = (png_size_t)length;
  195043. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  195044. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195045. if(png_ptr->read_user_chunk_fn != NULL)
  195046. {
  195047. /* callback to user unknown chunk handler */
  195048. int ret;
  195049. ret = (*(png_ptr->read_user_chunk_fn))
  195050. (png_ptr, &png_ptr->unknown_chunk);
  195051. if (ret < 0)
  195052. png_chunk_error(png_ptr, "error in user chunk");
  195053. if (ret == 0)
  195054. {
  195055. if (!(png_ptr->chunk_name[0] & 0x20))
  195056. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  195057. PNG_HANDLE_CHUNK_ALWAYS)
  195058. png_chunk_error(png_ptr, "unknown critical chunk");
  195059. png_set_unknown_chunks(png_ptr, info_ptr,
  195060. &png_ptr->unknown_chunk, 1);
  195061. }
  195062. }
  195063. #else
  195064. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  195065. #endif
  195066. png_free(png_ptr, png_ptr->unknown_chunk.data);
  195067. png_ptr->unknown_chunk.data = NULL;
  195068. }
  195069. else
  195070. #endif
  195071. skip = length;
  195072. png_crc_finish(png_ptr, skip);
  195073. #if !defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195074. info_ptr = info_ptr; /* quiet compiler warnings about unused info_ptr */
  195075. #endif
  195076. }
  195077. /* This function is called to verify that a chunk name is valid.
  195078. This function can't have the "critical chunk check" incorporated
  195079. into it, since in the future we will need to be able to call user
  195080. functions to handle unknown critical chunks after we check that
  195081. the chunk name itself is valid. */
  195082. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  195083. void /* PRIVATE */
  195084. png_check_chunk_name(png_structp png_ptr, png_bytep chunk_name)
  195085. {
  195086. png_debug(1, "in png_check_chunk_name\n");
  195087. if (isnonalpha(chunk_name[0]) || isnonalpha(chunk_name[1]) ||
  195088. isnonalpha(chunk_name[2]) || isnonalpha(chunk_name[3]))
  195089. {
  195090. png_chunk_error(png_ptr, "invalid chunk type");
  195091. }
  195092. }
  195093. /* Combines the row recently read in with the existing pixels in the
  195094. row. This routine takes care of alpha and transparency if requested.
  195095. This routine also handles the two methods of progressive display
  195096. of interlaced images, depending on the mask value.
  195097. The mask value describes which pixels are to be combined with
  195098. the row. The pattern always repeats every 8 pixels, so just 8
  195099. bits are needed. A one indicates the pixel is to be combined,
  195100. a zero indicates the pixel is to be skipped. This is in addition
  195101. to any alpha or transparency value associated with the pixel. If
  195102. you want all pixels to be combined, pass 0xff (255) in mask. */
  195103. void /* PRIVATE */
  195104. png_combine_row(png_structp png_ptr, png_bytep row, int mask)
  195105. {
  195106. png_debug(1,"in png_combine_row\n");
  195107. if (mask == 0xff)
  195108. {
  195109. png_memcpy(row, png_ptr->row_buf + 1,
  195110. PNG_ROWBYTES(png_ptr->row_info.pixel_depth, png_ptr->width));
  195111. }
  195112. else
  195113. {
  195114. switch (png_ptr->row_info.pixel_depth)
  195115. {
  195116. case 1:
  195117. {
  195118. png_bytep sp = png_ptr->row_buf + 1;
  195119. png_bytep dp = row;
  195120. int s_inc, s_start, s_end;
  195121. int m = 0x80;
  195122. int shift;
  195123. png_uint_32 i;
  195124. png_uint_32 row_width = png_ptr->width;
  195125. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195126. if (png_ptr->transformations & PNG_PACKSWAP)
  195127. {
  195128. s_start = 0;
  195129. s_end = 7;
  195130. s_inc = 1;
  195131. }
  195132. else
  195133. #endif
  195134. {
  195135. s_start = 7;
  195136. s_end = 0;
  195137. s_inc = -1;
  195138. }
  195139. shift = s_start;
  195140. for (i = 0; i < row_width; i++)
  195141. {
  195142. if (m & mask)
  195143. {
  195144. int value;
  195145. value = (*sp >> shift) & 0x01;
  195146. *dp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  195147. *dp |= (png_byte)(value << shift);
  195148. }
  195149. if (shift == s_end)
  195150. {
  195151. shift = s_start;
  195152. sp++;
  195153. dp++;
  195154. }
  195155. else
  195156. shift += s_inc;
  195157. if (m == 1)
  195158. m = 0x80;
  195159. else
  195160. m >>= 1;
  195161. }
  195162. break;
  195163. }
  195164. case 2:
  195165. {
  195166. png_bytep sp = png_ptr->row_buf + 1;
  195167. png_bytep dp = row;
  195168. int s_start, s_end, s_inc;
  195169. int m = 0x80;
  195170. int shift;
  195171. png_uint_32 i;
  195172. png_uint_32 row_width = png_ptr->width;
  195173. int value;
  195174. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195175. if (png_ptr->transformations & PNG_PACKSWAP)
  195176. {
  195177. s_start = 0;
  195178. s_end = 6;
  195179. s_inc = 2;
  195180. }
  195181. else
  195182. #endif
  195183. {
  195184. s_start = 6;
  195185. s_end = 0;
  195186. s_inc = -2;
  195187. }
  195188. shift = s_start;
  195189. for (i = 0; i < row_width; i++)
  195190. {
  195191. if (m & mask)
  195192. {
  195193. value = (*sp >> shift) & 0x03;
  195194. *dp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  195195. *dp |= (png_byte)(value << shift);
  195196. }
  195197. if (shift == s_end)
  195198. {
  195199. shift = s_start;
  195200. sp++;
  195201. dp++;
  195202. }
  195203. else
  195204. shift += s_inc;
  195205. if (m == 1)
  195206. m = 0x80;
  195207. else
  195208. m >>= 1;
  195209. }
  195210. break;
  195211. }
  195212. case 4:
  195213. {
  195214. png_bytep sp = png_ptr->row_buf + 1;
  195215. png_bytep dp = row;
  195216. int s_start, s_end, s_inc;
  195217. int m = 0x80;
  195218. int shift;
  195219. png_uint_32 i;
  195220. png_uint_32 row_width = png_ptr->width;
  195221. int value;
  195222. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195223. if (png_ptr->transformations & PNG_PACKSWAP)
  195224. {
  195225. s_start = 0;
  195226. s_end = 4;
  195227. s_inc = 4;
  195228. }
  195229. else
  195230. #endif
  195231. {
  195232. s_start = 4;
  195233. s_end = 0;
  195234. s_inc = -4;
  195235. }
  195236. shift = s_start;
  195237. for (i = 0; i < row_width; i++)
  195238. {
  195239. if (m & mask)
  195240. {
  195241. value = (*sp >> shift) & 0xf;
  195242. *dp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  195243. *dp |= (png_byte)(value << shift);
  195244. }
  195245. if (shift == s_end)
  195246. {
  195247. shift = s_start;
  195248. sp++;
  195249. dp++;
  195250. }
  195251. else
  195252. shift += s_inc;
  195253. if (m == 1)
  195254. m = 0x80;
  195255. else
  195256. m >>= 1;
  195257. }
  195258. break;
  195259. }
  195260. default:
  195261. {
  195262. png_bytep sp = png_ptr->row_buf + 1;
  195263. png_bytep dp = row;
  195264. png_size_t pixel_bytes = (png_ptr->row_info.pixel_depth >> 3);
  195265. png_uint_32 i;
  195266. png_uint_32 row_width = png_ptr->width;
  195267. png_byte m = 0x80;
  195268. for (i = 0; i < row_width; i++)
  195269. {
  195270. if (m & mask)
  195271. {
  195272. png_memcpy(dp, sp, pixel_bytes);
  195273. }
  195274. sp += pixel_bytes;
  195275. dp += pixel_bytes;
  195276. if (m == 1)
  195277. m = 0x80;
  195278. else
  195279. m >>= 1;
  195280. }
  195281. break;
  195282. }
  195283. }
  195284. }
  195285. }
  195286. #ifdef PNG_READ_INTERLACING_SUPPORTED
  195287. /* OLD pre-1.0.9 interface:
  195288. void png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass,
  195289. png_uint_32 transformations)
  195290. */
  195291. void /* PRIVATE */
  195292. png_do_read_interlace(png_structp png_ptr)
  195293. {
  195294. png_row_infop row_info = &(png_ptr->row_info);
  195295. png_bytep row = png_ptr->row_buf + 1;
  195296. int pass = png_ptr->pass;
  195297. png_uint_32 transformations = png_ptr->transformations;
  195298. #ifdef PNG_USE_LOCAL_ARRAYS
  195299. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  195300. /* offset to next interlace block */
  195301. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  195302. #endif
  195303. png_debug(1,"in png_do_read_interlace\n");
  195304. if (row != NULL && row_info != NULL)
  195305. {
  195306. png_uint_32 final_width;
  195307. final_width = row_info->width * png_pass_inc[pass];
  195308. switch (row_info->pixel_depth)
  195309. {
  195310. case 1:
  195311. {
  195312. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 3);
  195313. png_bytep dp = row + (png_size_t)((final_width - 1) >> 3);
  195314. int sshift, dshift;
  195315. int s_start, s_end, s_inc;
  195316. int jstop = png_pass_inc[pass];
  195317. png_byte v;
  195318. png_uint_32 i;
  195319. int j;
  195320. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195321. if (transformations & PNG_PACKSWAP)
  195322. {
  195323. sshift = (int)((row_info->width + 7) & 0x07);
  195324. dshift = (int)((final_width + 7) & 0x07);
  195325. s_start = 7;
  195326. s_end = 0;
  195327. s_inc = -1;
  195328. }
  195329. else
  195330. #endif
  195331. {
  195332. sshift = 7 - (int)((row_info->width + 7) & 0x07);
  195333. dshift = 7 - (int)((final_width + 7) & 0x07);
  195334. s_start = 0;
  195335. s_end = 7;
  195336. s_inc = 1;
  195337. }
  195338. for (i = 0; i < row_info->width; i++)
  195339. {
  195340. v = (png_byte)((*sp >> sshift) & 0x01);
  195341. for (j = 0; j < jstop; j++)
  195342. {
  195343. *dp &= (png_byte)((0x7f7f >> (7 - dshift)) & 0xff);
  195344. *dp |= (png_byte)(v << dshift);
  195345. if (dshift == s_end)
  195346. {
  195347. dshift = s_start;
  195348. dp--;
  195349. }
  195350. else
  195351. dshift += s_inc;
  195352. }
  195353. if (sshift == s_end)
  195354. {
  195355. sshift = s_start;
  195356. sp--;
  195357. }
  195358. else
  195359. sshift += s_inc;
  195360. }
  195361. break;
  195362. }
  195363. case 2:
  195364. {
  195365. png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
  195366. png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
  195367. int sshift, dshift;
  195368. int s_start, s_end, s_inc;
  195369. int jstop = png_pass_inc[pass];
  195370. png_uint_32 i;
  195371. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195372. if (transformations & PNG_PACKSWAP)
  195373. {
  195374. sshift = (int)(((row_info->width + 3) & 0x03) << 1);
  195375. dshift = (int)(((final_width + 3) & 0x03) << 1);
  195376. s_start = 6;
  195377. s_end = 0;
  195378. s_inc = -2;
  195379. }
  195380. else
  195381. #endif
  195382. {
  195383. sshift = (int)((3 - ((row_info->width + 3) & 0x03)) << 1);
  195384. dshift = (int)((3 - ((final_width + 3) & 0x03)) << 1);
  195385. s_start = 0;
  195386. s_end = 6;
  195387. s_inc = 2;
  195388. }
  195389. for (i = 0; i < row_info->width; i++)
  195390. {
  195391. png_byte v;
  195392. int j;
  195393. v = (png_byte)((*sp >> sshift) & 0x03);
  195394. for (j = 0; j < jstop; j++)
  195395. {
  195396. *dp &= (png_byte)((0x3f3f >> (6 - dshift)) & 0xff);
  195397. *dp |= (png_byte)(v << dshift);
  195398. if (dshift == s_end)
  195399. {
  195400. dshift = s_start;
  195401. dp--;
  195402. }
  195403. else
  195404. dshift += s_inc;
  195405. }
  195406. if (sshift == s_end)
  195407. {
  195408. sshift = s_start;
  195409. sp--;
  195410. }
  195411. else
  195412. sshift += s_inc;
  195413. }
  195414. break;
  195415. }
  195416. case 4:
  195417. {
  195418. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1);
  195419. png_bytep dp = row + (png_size_t)((final_width - 1) >> 1);
  195420. int sshift, dshift;
  195421. int s_start, s_end, s_inc;
  195422. png_uint_32 i;
  195423. int jstop = png_pass_inc[pass];
  195424. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195425. if (transformations & PNG_PACKSWAP)
  195426. {
  195427. sshift = (int)(((row_info->width + 1) & 0x01) << 2);
  195428. dshift = (int)(((final_width + 1) & 0x01) << 2);
  195429. s_start = 4;
  195430. s_end = 0;
  195431. s_inc = -4;
  195432. }
  195433. else
  195434. #endif
  195435. {
  195436. sshift = (int)((1 - ((row_info->width + 1) & 0x01)) << 2);
  195437. dshift = (int)((1 - ((final_width + 1) & 0x01)) << 2);
  195438. s_start = 0;
  195439. s_end = 4;
  195440. s_inc = 4;
  195441. }
  195442. for (i = 0; i < row_info->width; i++)
  195443. {
  195444. png_byte v = (png_byte)((*sp >> sshift) & 0xf);
  195445. int j;
  195446. for (j = 0; j < jstop; j++)
  195447. {
  195448. *dp &= (png_byte)((0xf0f >> (4 - dshift)) & 0xff);
  195449. *dp |= (png_byte)(v << dshift);
  195450. if (dshift == s_end)
  195451. {
  195452. dshift = s_start;
  195453. dp--;
  195454. }
  195455. else
  195456. dshift += s_inc;
  195457. }
  195458. if (sshift == s_end)
  195459. {
  195460. sshift = s_start;
  195461. sp--;
  195462. }
  195463. else
  195464. sshift += s_inc;
  195465. }
  195466. break;
  195467. }
  195468. default:
  195469. {
  195470. png_size_t pixel_bytes = (row_info->pixel_depth >> 3);
  195471. png_bytep sp = row + (png_size_t)(row_info->width - 1) * pixel_bytes;
  195472. png_bytep dp = row + (png_size_t)(final_width - 1) * pixel_bytes;
  195473. int jstop = png_pass_inc[pass];
  195474. png_uint_32 i;
  195475. for (i = 0; i < row_info->width; i++)
  195476. {
  195477. png_byte v[8];
  195478. int j;
  195479. png_memcpy(v, sp, pixel_bytes);
  195480. for (j = 0; j < jstop; j++)
  195481. {
  195482. png_memcpy(dp, v, pixel_bytes);
  195483. dp -= pixel_bytes;
  195484. }
  195485. sp -= pixel_bytes;
  195486. }
  195487. break;
  195488. }
  195489. }
  195490. row_info->width = final_width;
  195491. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,final_width);
  195492. }
  195493. #if !defined(PNG_READ_PACKSWAP_SUPPORTED)
  195494. transformations = transformations; /* silence compiler warning */
  195495. #endif
  195496. }
  195497. #endif /* PNG_READ_INTERLACING_SUPPORTED */
  195498. void /* PRIVATE */
  195499. png_read_filter_row(png_structp, png_row_infop row_info, png_bytep row,
  195500. png_bytep prev_row, int filter)
  195501. {
  195502. png_debug(1, "in png_read_filter_row\n");
  195503. png_debug2(2,"row = %lu, filter = %d\n", png_ptr->row_number, filter);
  195504. switch (filter)
  195505. {
  195506. case PNG_FILTER_VALUE_NONE:
  195507. break;
  195508. case PNG_FILTER_VALUE_SUB:
  195509. {
  195510. png_uint_32 i;
  195511. png_uint_32 istop = row_info->rowbytes;
  195512. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  195513. png_bytep rp = row + bpp;
  195514. png_bytep lp = row;
  195515. for (i = bpp; i < istop; i++)
  195516. {
  195517. *rp = (png_byte)(((int)(*rp) + (int)(*lp++)) & 0xff);
  195518. rp++;
  195519. }
  195520. break;
  195521. }
  195522. case PNG_FILTER_VALUE_UP:
  195523. {
  195524. png_uint_32 i;
  195525. png_uint_32 istop = row_info->rowbytes;
  195526. png_bytep rp = row;
  195527. png_bytep pp = prev_row;
  195528. for (i = 0; i < istop; i++)
  195529. {
  195530. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  195531. rp++;
  195532. }
  195533. break;
  195534. }
  195535. case PNG_FILTER_VALUE_AVG:
  195536. {
  195537. png_uint_32 i;
  195538. png_bytep rp = row;
  195539. png_bytep pp = prev_row;
  195540. png_bytep lp = row;
  195541. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  195542. png_uint_32 istop = row_info->rowbytes - bpp;
  195543. for (i = 0; i < bpp; i++)
  195544. {
  195545. *rp = (png_byte)(((int)(*rp) +
  195546. ((int)(*pp++) / 2 )) & 0xff);
  195547. rp++;
  195548. }
  195549. for (i = 0; i < istop; i++)
  195550. {
  195551. *rp = (png_byte)(((int)(*rp) +
  195552. (int)(*pp++ + *lp++) / 2 ) & 0xff);
  195553. rp++;
  195554. }
  195555. break;
  195556. }
  195557. case PNG_FILTER_VALUE_PAETH:
  195558. {
  195559. png_uint_32 i;
  195560. png_bytep rp = row;
  195561. png_bytep pp = prev_row;
  195562. png_bytep lp = row;
  195563. png_bytep cp = prev_row;
  195564. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  195565. png_uint_32 istop=row_info->rowbytes - bpp;
  195566. for (i = 0; i < bpp; i++)
  195567. {
  195568. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  195569. rp++;
  195570. }
  195571. for (i = 0; i < istop; i++) /* use leftover rp,pp */
  195572. {
  195573. int a, b, c, pa, pb, pc, p;
  195574. a = *lp++;
  195575. b = *pp++;
  195576. c = *cp++;
  195577. p = b - c;
  195578. pc = a - c;
  195579. #ifdef PNG_USE_ABS
  195580. pa = abs(p);
  195581. pb = abs(pc);
  195582. pc = abs(p + pc);
  195583. #else
  195584. pa = p < 0 ? -p : p;
  195585. pb = pc < 0 ? -pc : pc;
  195586. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  195587. #endif
  195588. /*
  195589. if (pa <= pb && pa <= pc)
  195590. p = a;
  195591. else if (pb <= pc)
  195592. p = b;
  195593. else
  195594. p = c;
  195595. */
  195596. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  195597. *rp = (png_byte)(((int)(*rp) + p) & 0xff);
  195598. rp++;
  195599. }
  195600. break;
  195601. }
  195602. default:
  195603. png_warning(png_ptr, "Ignoring bad adaptive filter type");
  195604. *row=0;
  195605. break;
  195606. }
  195607. }
  195608. void /* PRIVATE */
  195609. png_read_finish_row(png_structp png_ptr)
  195610. {
  195611. #ifdef PNG_USE_LOCAL_ARRAYS
  195612. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  195613. /* start of interlace block */
  195614. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  195615. /* offset to next interlace block */
  195616. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  195617. /* start of interlace block in the y direction */
  195618. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  195619. /* offset to next interlace block in the y direction */
  195620. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  195621. #endif
  195622. png_debug(1, "in png_read_finish_row\n");
  195623. png_ptr->row_number++;
  195624. if (png_ptr->row_number < png_ptr->num_rows)
  195625. return;
  195626. if (png_ptr->interlaced)
  195627. {
  195628. png_ptr->row_number = 0;
  195629. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  195630. png_ptr->rowbytes + 1);
  195631. do
  195632. {
  195633. png_ptr->pass++;
  195634. if (png_ptr->pass >= 7)
  195635. break;
  195636. png_ptr->iwidth = (png_ptr->width +
  195637. png_pass_inc[png_ptr->pass] - 1 -
  195638. png_pass_start[png_ptr->pass]) /
  195639. png_pass_inc[png_ptr->pass];
  195640. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  195641. png_ptr->iwidth) + 1;
  195642. if (!(png_ptr->transformations & PNG_INTERLACE))
  195643. {
  195644. png_ptr->num_rows = (png_ptr->height +
  195645. png_pass_yinc[png_ptr->pass] - 1 -
  195646. png_pass_ystart[png_ptr->pass]) /
  195647. png_pass_yinc[png_ptr->pass];
  195648. if (!(png_ptr->num_rows))
  195649. continue;
  195650. }
  195651. else /* if (png_ptr->transformations & PNG_INTERLACE) */
  195652. break;
  195653. } while (png_ptr->iwidth == 0);
  195654. if (png_ptr->pass < 7)
  195655. return;
  195656. }
  195657. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  195658. {
  195659. #ifdef PNG_USE_LOCAL_ARRAYS
  195660. PNG_CONST PNG_IDAT;
  195661. #endif
  195662. char extra;
  195663. int ret;
  195664. png_ptr->zstream.next_out = (Bytef *)&extra;
  195665. png_ptr->zstream.avail_out = (uInt)1;
  195666. for(;;)
  195667. {
  195668. if (!(png_ptr->zstream.avail_in))
  195669. {
  195670. while (!png_ptr->idat_size)
  195671. {
  195672. png_byte chunk_length[4];
  195673. png_crc_finish(png_ptr, 0);
  195674. png_read_data(png_ptr, chunk_length, 4);
  195675. png_ptr->idat_size = png_get_uint_31(png_ptr, chunk_length);
  195676. png_reset_crc(png_ptr);
  195677. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  195678. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  195679. png_error(png_ptr, "Not enough image data");
  195680. }
  195681. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  195682. png_ptr->zstream.next_in = png_ptr->zbuf;
  195683. if (png_ptr->zbuf_size > png_ptr->idat_size)
  195684. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  195685. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zstream.avail_in);
  195686. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  195687. }
  195688. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  195689. if (ret == Z_STREAM_END)
  195690. {
  195691. if (!(png_ptr->zstream.avail_out) || png_ptr->zstream.avail_in ||
  195692. png_ptr->idat_size)
  195693. png_warning(png_ptr, "Extra compressed data");
  195694. png_ptr->mode |= PNG_AFTER_IDAT;
  195695. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  195696. break;
  195697. }
  195698. if (ret != Z_OK)
  195699. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  195700. "Decompression Error");
  195701. if (!(png_ptr->zstream.avail_out))
  195702. {
  195703. png_warning(png_ptr, "Extra compressed data.");
  195704. png_ptr->mode |= PNG_AFTER_IDAT;
  195705. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  195706. break;
  195707. }
  195708. }
  195709. png_ptr->zstream.avail_out = 0;
  195710. }
  195711. if (png_ptr->idat_size || png_ptr->zstream.avail_in)
  195712. png_warning(png_ptr, "Extra compression data");
  195713. inflateReset(&png_ptr->zstream);
  195714. png_ptr->mode |= PNG_AFTER_IDAT;
  195715. }
  195716. void /* PRIVATE */
  195717. png_read_start_row(png_structp png_ptr)
  195718. {
  195719. #ifdef PNG_USE_LOCAL_ARRAYS
  195720. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  195721. /* start of interlace block */
  195722. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  195723. /* offset to next interlace block */
  195724. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  195725. /* start of interlace block in the y direction */
  195726. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  195727. /* offset to next interlace block in the y direction */
  195728. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  195729. #endif
  195730. int max_pixel_depth;
  195731. png_uint_32 row_bytes;
  195732. png_debug(1, "in png_read_start_row\n");
  195733. png_ptr->zstream.avail_in = 0;
  195734. png_init_read_transformations(png_ptr);
  195735. if (png_ptr->interlaced)
  195736. {
  195737. if (!(png_ptr->transformations & PNG_INTERLACE))
  195738. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  195739. png_pass_ystart[0]) / png_pass_yinc[0];
  195740. else
  195741. png_ptr->num_rows = png_ptr->height;
  195742. png_ptr->iwidth = (png_ptr->width +
  195743. png_pass_inc[png_ptr->pass] - 1 -
  195744. png_pass_start[png_ptr->pass]) /
  195745. png_pass_inc[png_ptr->pass];
  195746. row_bytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->iwidth) + 1;
  195747. png_ptr->irowbytes = (png_size_t)row_bytes;
  195748. if((png_uint_32)png_ptr->irowbytes != row_bytes)
  195749. png_error(png_ptr, "Rowbytes overflow in png_read_start_row");
  195750. }
  195751. else
  195752. {
  195753. png_ptr->num_rows = png_ptr->height;
  195754. png_ptr->iwidth = png_ptr->width;
  195755. png_ptr->irowbytes = png_ptr->rowbytes + 1;
  195756. }
  195757. max_pixel_depth = png_ptr->pixel_depth;
  195758. #if defined(PNG_READ_PACK_SUPPORTED)
  195759. if ((png_ptr->transformations & PNG_PACK) && png_ptr->bit_depth < 8)
  195760. max_pixel_depth = 8;
  195761. #endif
  195762. #if defined(PNG_READ_EXPAND_SUPPORTED)
  195763. if (png_ptr->transformations & PNG_EXPAND)
  195764. {
  195765. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195766. {
  195767. if (png_ptr->num_trans)
  195768. max_pixel_depth = 32;
  195769. else
  195770. max_pixel_depth = 24;
  195771. }
  195772. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  195773. {
  195774. if (max_pixel_depth < 8)
  195775. max_pixel_depth = 8;
  195776. if (png_ptr->num_trans)
  195777. max_pixel_depth *= 2;
  195778. }
  195779. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  195780. {
  195781. if (png_ptr->num_trans)
  195782. {
  195783. max_pixel_depth *= 4;
  195784. max_pixel_depth /= 3;
  195785. }
  195786. }
  195787. }
  195788. #endif
  195789. #if defined(PNG_READ_FILLER_SUPPORTED)
  195790. if (png_ptr->transformations & (PNG_FILLER))
  195791. {
  195792. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195793. max_pixel_depth = 32;
  195794. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  195795. {
  195796. if (max_pixel_depth <= 8)
  195797. max_pixel_depth = 16;
  195798. else
  195799. max_pixel_depth = 32;
  195800. }
  195801. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  195802. {
  195803. if (max_pixel_depth <= 32)
  195804. max_pixel_depth = 32;
  195805. else
  195806. max_pixel_depth = 64;
  195807. }
  195808. }
  195809. #endif
  195810. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  195811. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  195812. {
  195813. if (
  195814. #if defined(PNG_READ_EXPAND_SUPPORTED)
  195815. (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND)) ||
  195816. #endif
  195817. #if defined(PNG_READ_FILLER_SUPPORTED)
  195818. (png_ptr->transformations & (PNG_FILLER)) ||
  195819. #endif
  195820. png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  195821. {
  195822. if (max_pixel_depth <= 16)
  195823. max_pixel_depth = 32;
  195824. else
  195825. max_pixel_depth = 64;
  195826. }
  195827. else
  195828. {
  195829. if (max_pixel_depth <= 8)
  195830. {
  195831. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  195832. max_pixel_depth = 32;
  195833. else
  195834. max_pixel_depth = 24;
  195835. }
  195836. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  195837. max_pixel_depth = 64;
  195838. else
  195839. max_pixel_depth = 48;
  195840. }
  195841. }
  195842. #endif
  195843. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \
  195844. defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  195845. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  195846. {
  195847. int user_pixel_depth=png_ptr->user_transform_depth*
  195848. png_ptr->user_transform_channels;
  195849. if(user_pixel_depth > max_pixel_depth)
  195850. max_pixel_depth=user_pixel_depth;
  195851. }
  195852. #endif
  195853. /* align the width on the next larger 8 pixels. Mainly used
  195854. for interlacing */
  195855. row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7));
  195856. /* calculate the maximum bytes needed, adding a byte and a pixel
  195857. for safety's sake */
  195858. row_bytes = PNG_ROWBYTES(max_pixel_depth,row_bytes) +
  195859. 1 + ((max_pixel_depth + 7) >> 3);
  195860. #ifdef PNG_MAX_MALLOC_64K
  195861. if (row_bytes > (png_uint_32)65536L)
  195862. png_error(png_ptr, "This image requires a row greater than 64KB");
  195863. #endif
  195864. png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes+64);
  195865. png_ptr->row_buf = png_ptr->big_row_buf+32;
  195866. #ifdef PNG_MAX_MALLOC_64K
  195867. if ((png_uint_32)png_ptr->rowbytes + 1 > (png_uint_32)65536L)
  195868. png_error(png_ptr, "This image requires a row greater than 64KB");
  195869. #endif
  195870. if ((png_uint_32)png_ptr->rowbytes > (png_uint_32)(PNG_SIZE_MAX - 1))
  195871. png_error(png_ptr, "Row has too many bytes to allocate in memory.");
  195872. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(
  195873. png_ptr->rowbytes + 1));
  195874. png_memset_check(png_ptr, png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
  195875. png_debug1(3, "width = %lu,\n", png_ptr->width);
  195876. png_debug1(3, "height = %lu,\n", png_ptr->height);
  195877. png_debug1(3, "iwidth = %lu,\n", png_ptr->iwidth);
  195878. png_debug1(3, "num_rows = %lu\n", png_ptr->num_rows);
  195879. png_debug1(3, "rowbytes = %lu,\n", png_ptr->rowbytes);
  195880. png_debug1(3, "irowbytes = %lu,\n", png_ptr->irowbytes);
  195881. png_ptr->flags |= PNG_FLAG_ROW_INIT;
  195882. }
  195883. #endif /* PNG_READ_SUPPORTED */
  195884. /*** End of inlined file: pngrutil.c ***/
  195885. /*** Start of inlined file: pngset.c ***/
  195886. /* pngset.c - storage of image information into info struct
  195887. *
  195888. * Last changed in libpng 1.2.21 [October 4, 2007]
  195889. * For conditions of distribution and use, see copyright notice in png.h
  195890. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  195891. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  195892. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  195893. *
  195894. * The functions here are used during reads to store data from the file
  195895. * into the info struct, and during writes to store application data
  195896. * into the info struct for writing into the file. This abstracts the
  195897. * info struct and allows us to change the structure in the future.
  195898. */
  195899. #define PNG_INTERNAL
  195900. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  195901. #if defined(PNG_bKGD_SUPPORTED)
  195902. void PNGAPI
  195903. png_set_bKGD(png_structp png_ptr, png_infop info_ptr, png_color_16p background)
  195904. {
  195905. png_debug1(1, "in %s storage function\n", "bKGD");
  195906. if (png_ptr == NULL || info_ptr == NULL)
  195907. return;
  195908. png_memcpy(&(info_ptr->background), background, png_sizeof(png_color_16));
  195909. info_ptr->valid |= PNG_INFO_bKGD;
  195910. }
  195911. #endif
  195912. #if defined(PNG_cHRM_SUPPORTED)
  195913. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195914. void PNGAPI
  195915. png_set_cHRM(png_structp png_ptr, png_infop info_ptr,
  195916. double white_x, double white_y, double red_x, double red_y,
  195917. double green_x, double green_y, double blue_x, double blue_y)
  195918. {
  195919. png_debug1(1, "in %s storage function\n", "cHRM");
  195920. if (png_ptr == NULL || info_ptr == NULL)
  195921. return;
  195922. if (white_x < 0.0 || white_y < 0.0 ||
  195923. red_x < 0.0 || red_y < 0.0 ||
  195924. green_x < 0.0 || green_y < 0.0 ||
  195925. blue_x < 0.0 || blue_y < 0.0)
  195926. {
  195927. png_warning(png_ptr,
  195928. "Ignoring attempt to set negative chromaticity value");
  195929. return;
  195930. }
  195931. if (white_x > 21474.83 || white_y > 21474.83 ||
  195932. red_x > 21474.83 || red_y > 21474.83 ||
  195933. green_x > 21474.83 || green_y > 21474.83 ||
  195934. blue_x > 21474.83 || blue_y > 21474.83)
  195935. {
  195936. png_warning(png_ptr,
  195937. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  195938. return;
  195939. }
  195940. info_ptr->x_white = (float)white_x;
  195941. info_ptr->y_white = (float)white_y;
  195942. info_ptr->x_red = (float)red_x;
  195943. info_ptr->y_red = (float)red_y;
  195944. info_ptr->x_green = (float)green_x;
  195945. info_ptr->y_green = (float)green_y;
  195946. info_ptr->x_blue = (float)blue_x;
  195947. info_ptr->y_blue = (float)blue_y;
  195948. #ifdef PNG_FIXED_POINT_SUPPORTED
  195949. info_ptr->int_x_white = (png_fixed_point)(white_x*100000.+0.5);
  195950. info_ptr->int_y_white = (png_fixed_point)(white_y*100000.+0.5);
  195951. info_ptr->int_x_red = (png_fixed_point)( red_x*100000.+0.5);
  195952. info_ptr->int_y_red = (png_fixed_point)( red_y*100000.+0.5);
  195953. info_ptr->int_x_green = (png_fixed_point)(green_x*100000.+0.5);
  195954. info_ptr->int_y_green = (png_fixed_point)(green_y*100000.+0.5);
  195955. info_ptr->int_x_blue = (png_fixed_point)( blue_x*100000.+0.5);
  195956. info_ptr->int_y_blue = (png_fixed_point)( blue_y*100000.+0.5);
  195957. #endif
  195958. info_ptr->valid |= PNG_INFO_cHRM;
  195959. }
  195960. #endif
  195961. #ifdef PNG_FIXED_POINT_SUPPORTED
  195962. void PNGAPI
  195963. png_set_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  195964. png_fixed_point white_x, png_fixed_point white_y, png_fixed_point red_x,
  195965. png_fixed_point red_y, png_fixed_point green_x, png_fixed_point green_y,
  195966. png_fixed_point blue_x, png_fixed_point blue_y)
  195967. {
  195968. png_debug1(1, "in %s storage function\n", "cHRM");
  195969. if (png_ptr == NULL || info_ptr == NULL)
  195970. return;
  195971. if (white_x < 0 || white_y < 0 ||
  195972. red_x < 0 || red_y < 0 ||
  195973. green_x < 0 || green_y < 0 ||
  195974. blue_x < 0 || blue_y < 0)
  195975. {
  195976. png_warning(png_ptr,
  195977. "Ignoring attempt to set negative chromaticity value");
  195978. return;
  195979. }
  195980. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195981. if (white_x > (double) PNG_UINT_31_MAX ||
  195982. white_y > (double) PNG_UINT_31_MAX ||
  195983. red_x > (double) PNG_UINT_31_MAX ||
  195984. red_y > (double) PNG_UINT_31_MAX ||
  195985. green_x > (double) PNG_UINT_31_MAX ||
  195986. green_y > (double) PNG_UINT_31_MAX ||
  195987. blue_x > (double) PNG_UINT_31_MAX ||
  195988. blue_y > (double) PNG_UINT_31_MAX)
  195989. #else
  195990. if (white_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  195991. white_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  195992. red_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  195993. red_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  195994. green_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  195995. green_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  195996. blue_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  195997. blue_y > (png_fixed_point) PNG_UINT_31_MAX/100000L)
  195998. #endif
  195999. {
  196000. png_warning(png_ptr,
  196001. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  196002. return;
  196003. }
  196004. info_ptr->int_x_white = white_x;
  196005. info_ptr->int_y_white = white_y;
  196006. info_ptr->int_x_red = red_x;
  196007. info_ptr->int_y_red = red_y;
  196008. info_ptr->int_x_green = green_x;
  196009. info_ptr->int_y_green = green_y;
  196010. info_ptr->int_x_blue = blue_x;
  196011. info_ptr->int_y_blue = blue_y;
  196012. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196013. info_ptr->x_white = (float)(white_x/100000.);
  196014. info_ptr->y_white = (float)(white_y/100000.);
  196015. info_ptr->x_red = (float)( red_x/100000.);
  196016. info_ptr->y_red = (float)( red_y/100000.);
  196017. info_ptr->x_green = (float)(green_x/100000.);
  196018. info_ptr->y_green = (float)(green_y/100000.);
  196019. info_ptr->x_blue = (float)( blue_x/100000.);
  196020. info_ptr->y_blue = (float)( blue_y/100000.);
  196021. #endif
  196022. info_ptr->valid |= PNG_INFO_cHRM;
  196023. }
  196024. #endif
  196025. #endif
  196026. #if defined(PNG_gAMA_SUPPORTED)
  196027. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196028. void PNGAPI
  196029. png_set_gAMA(png_structp png_ptr, png_infop info_ptr, double file_gamma)
  196030. {
  196031. double gamma;
  196032. png_debug1(1, "in %s storage function\n", "gAMA");
  196033. if (png_ptr == NULL || info_ptr == NULL)
  196034. return;
  196035. /* Check for overflow */
  196036. if (file_gamma > 21474.83)
  196037. {
  196038. png_warning(png_ptr, "Limiting gamma to 21474.83");
  196039. gamma=21474.83;
  196040. }
  196041. else
  196042. gamma=file_gamma;
  196043. info_ptr->gamma = (float)gamma;
  196044. #ifdef PNG_FIXED_POINT_SUPPORTED
  196045. info_ptr->int_gamma = (int)(gamma*100000.+.5);
  196046. #endif
  196047. info_ptr->valid |= PNG_INFO_gAMA;
  196048. if(gamma == 0.0)
  196049. png_warning(png_ptr, "Setting gamma=0");
  196050. }
  196051. #endif
  196052. void PNGAPI
  196053. png_set_gAMA_fixed(png_structp png_ptr, png_infop info_ptr, png_fixed_point
  196054. int_gamma)
  196055. {
  196056. png_fixed_point gamma;
  196057. png_debug1(1, "in %s storage function\n", "gAMA");
  196058. if (png_ptr == NULL || info_ptr == NULL)
  196059. return;
  196060. if (int_gamma > (png_fixed_point) PNG_UINT_31_MAX)
  196061. {
  196062. png_warning(png_ptr, "Limiting gamma to 21474.83");
  196063. gamma=PNG_UINT_31_MAX;
  196064. }
  196065. else
  196066. {
  196067. if (int_gamma < 0)
  196068. {
  196069. png_warning(png_ptr, "Setting negative gamma to zero");
  196070. gamma=0;
  196071. }
  196072. else
  196073. gamma=int_gamma;
  196074. }
  196075. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196076. info_ptr->gamma = (float)(gamma/100000.);
  196077. #endif
  196078. #ifdef PNG_FIXED_POINT_SUPPORTED
  196079. info_ptr->int_gamma = gamma;
  196080. #endif
  196081. info_ptr->valid |= PNG_INFO_gAMA;
  196082. if(gamma == 0)
  196083. png_warning(png_ptr, "Setting gamma=0");
  196084. }
  196085. #endif
  196086. #if defined(PNG_hIST_SUPPORTED)
  196087. void PNGAPI
  196088. png_set_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p hist)
  196089. {
  196090. int i;
  196091. png_debug1(1, "in %s storage function\n", "hIST");
  196092. if (png_ptr == NULL || info_ptr == NULL)
  196093. return;
  196094. if (info_ptr->num_palette == 0 || info_ptr->num_palette
  196095. > PNG_MAX_PALETTE_LENGTH)
  196096. {
  196097. png_warning(png_ptr,
  196098. "Invalid palette size, hIST allocation skipped.");
  196099. return;
  196100. }
  196101. #ifdef PNG_FREE_ME_SUPPORTED
  196102. png_free_data(png_ptr, info_ptr, PNG_FREE_HIST, 0);
  196103. #endif
  196104. /* Changed from info->num_palette to PNG_MAX_PALETTE_LENGTH in version
  196105. 1.2.1 */
  196106. png_ptr->hist = (png_uint_16p)png_malloc_warn(png_ptr,
  196107. (png_uint_32)(PNG_MAX_PALETTE_LENGTH * png_sizeof (png_uint_16)));
  196108. if (png_ptr->hist == NULL)
  196109. {
  196110. png_warning(png_ptr, "Insufficient memory for hIST chunk data.");
  196111. return;
  196112. }
  196113. for (i = 0; i < info_ptr->num_palette; i++)
  196114. png_ptr->hist[i] = hist[i];
  196115. info_ptr->hist = png_ptr->hist;
  196116. info_ptr->valid |= PNG_INFO_hIST;
  196117. #ifdef PNG_FREE_ME_SUPPORTED
  196118. info_ptr->free_me |= PNG_FREE_HIST;
  196119. #else
  196120. png_ptr->flags |= PNG_FLAG_FREE_HIST;
  196121. #endif
  196122. }
  196123. #endif
  196124. void PNGAPI
  196125. png_set_IHDR(png_structp png_ptr, png_infop info_ptr,
  196126. png_uint_32 width, png_uint_32 height, int bit_depth,
  196127. int color_type, int interlace_type, int compression_type,
  196128. int filter_type)
  196129. {
  196130. png_debug1(1, "in %s storage function\n", "IHDR");
  196131. if (png_ptr == NULL || info_ptr == NULL)
  196132. return;
  196133. /* check for width and height valid values */
  196134. if (width == 0 || height == 0)
  196135. png_error(png_ptr, "Image width or height is zero in IHDR");
  196136. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  196137. if (width > png_ptr->user_width_max || height > png_ptr->user_height_max)
  196138. png_error(png_ptr, "image size exceeds user limits in IHDR");
  196139. #else
  196140. if (width > PNG_USER_WIDTH_MAX || height > PNG_USER_HEIGHT_MAX)
  196141. png_error(png_ptr, "image size exceeds user limits in IHDR");
  196142. #endif
  196143. if (width > PNG_UINT_31_MAX || height > PNG_UINT_31_MAX)
  196144. png_error(png_ptr, "Invalid image size in IHDR");
  196145. if ( width > (PNG_UINT_32_MAX
  196146. >> 3) /* 8-byte RGBA pixels */
  196147. - 64 /* bigrowbuf hack */
  196148. - 1 /* filter byte */
  196149. - 7*8 /* rounding of width to multiple of 8 pixels */
  196150. - 8) /* extra max_pixel_depth pad */
  196151. png_warning(png_ptr, "Width is too large for libpng to process pixels");
  196152. /* check other values */
  196153. if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&
  196154. bit_depth != 8 && bit_depth != 16)
  196155. png_error(png_ptr, "Invalid bit depth in IHDR");
  196156. if (color_type < 0 || color_type == 1 ||
  196157. color_type == 5 || color_type > 6)
  196158. png_error(png_ptr, "Invalid color type in IHDR");
  196159. if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) ||
  196160. ((color_type == PNG_COLOR_TYPE_RGB ||
  196161. color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
  196162. color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8))
  196163. png_error(png_ptr, "Invalid color type/bit depth combination in IHDR");
  196164. if (interlace_type >= PNG_INTERLACE_LAST)
  196165. png_error(png_ptr, "Unknown interlace method in IHDR");
  196166. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  196167. png_error(png_ptr, "Unknown compression method in IHDR");
  196168. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  196169. /* Accept filter_method 64 (intrapixel differencing) only if
  196170. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  196171. * 2. Libpng did not read a PNG signature (this filter_method is only
  196172. * used in PNG datastreams that are embedded in MNG datastreams) and
  196173. * 3. The application called png_permit_mng_features with a mask that
  196174. * included PNG_FLAG_MNG_FILTER_64 and
  196175. * 4. The filter_method is 64 and
  196176. * 5. The color_type is RGB or RGBA
  196177. */
  196178. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&png_ptr->mng_features_permitted)
  196179. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  196180. if(filter_type != PNG_FILTER_TYPE_BASE)
  196181. {
  196182. if(!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  196183. (filter_type == PNG_INTRAPIXEL_DIFFERENCING) &&
  196184. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  196185. (color_type == PNG_COLOR_TYPE_RGB ||
  196186. color_type == PNG_COLOR_TYPE_RGB_ALPHA)))
  196187. png_error(png_ptr, "Unknown filter method in IHDR");
  196188. if(png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)
  196189. png_warning(png_ptr, "Invalid filter method in IHDR");
  196190. }
  196191. #else
  196192. if(filter_type != PNG_FILTER_TYPE_BASE)
  196193. png_error(png_ptr, "Unknown filter method in IHDR");
  196194. #endif
  196195. info_ptr->width = width;
  196196. info_ptr->height = height;
  196197. info_ptr->bit_depth = (png_byte)bit_depth;
  196198. info_ptr->color_type =(png_byte) color_type;
  196199. info_ptr->compression_type = (png_byte)compression_type;
  196200. info_ptr->filter_type = (png_byte)filter_type;
  196201. info_ptr->interlace_type = (png_byte)interlace_type;
  196202. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196203. info_ptr->channels = 1;
  196204. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  196205. info_ptr->channels = 3;
  196206. else
  196207. info_ptr->channels = 1;
  196208. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  196209. info_ptr->channels++;
  196210. info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth);
  196211. /* check for potential overflow */
  196212. if (width > (PNG_UINT_32_MAX
  196213. >> 3) /* 8-byte RGBA pixels */
  196214. - 64 /* bigrowbuf hack */
  196215. - 1 /* filter byte */
  196216. - 7*8 /* rounding of width to multiple of 8 pixels */
  196217. - 8) /* extra max_pixel_depth pad */
  196218. info_ptr->rowbytes = (png_size_t)0;
  196219. else
  196220. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,width);
  196221. }
  196222. #if defined(PNG_oFFs_SUPPORTED)
  196223. void PNGAPI
  196224. png_set_oFFs(png_structp png_ptr, png_infop info_ptr,
  196225. png_int_32 offset_x, png_int_32 offset_y, int unit_type)
  196226. {
  196227. png_debug1(1, "in %s storage function\n", "oFFs");
  196228. if (png_ptr == NULL || info_ptr == NULL)
  196229. return;
  196230. info_ptr->x_offset = offset_x;
  196231. info_ptr->y_offset = offset_y;
  196232. info_ptr->offset_unit_type = (png_byte)unit_type;
  196233. info_ptr->valid |= PNG_INFO_oFFs;
  196234. }
  196235. #endif
  196236. #if defined(PNG_pCAL_SUPPORTED)
  196237. void PNGAPI
  196238. png_set_pCAL(png_structp png_ptr, png_infop info_ptr,
  196239. png_charp purpose, png_int_32 X0, png_int_32 X1, int type, int nparams,
  196240. png_charp units, png_charpp params)
  196241. {
  196242. png_uint_32 length;
  196243. int i;
  196244. png_debug1(1, "in %s storage function\n", "pCAL");
  196245. if (png_ptr == NULL || info_ptr == NULL)
  196246. return;
  196247. length = png_strlen(purpose) + 1;
  196248. png_debug1(3, "allocating purpose for info (%lu bytes)\n", length);
  196249. info_ptr->pcal_purpose = (png_charp)png_malloc_warn(png_ptr, length);
  196250. if (info_ptr->pcal_purpose == NULL)
  196251. {
  196252. png_warning(png_ptr, "Insufficient memory for pCAL purpose.");
  196253. return;
  196254. }
  196255. png_memcpy(info_ptr->pcal_purpose, purpose, (png_size_t)length);
  196256. png_debug(3, "storing X0, X1, type, and nparams in info\n");
  196257. info_ptr->pcal_X0 = X0;
  196258. info_ptr->pcal_X1 = X1;
  196259. info_ptr->pcal_type = (png_byte)type;
  196260. info_ptr->pcal_nparams = (png_byte)nparams;
  196261. length = png_strlen(units) + 1;
  196262. png_debug1(3, "allocating units for info (%lu bytes)\n", length);
  196263. info_ptr->pcal_units = (png_charp)png_malloc_warn(png_ptr, length);
  196264. if (info_ptr->pcal_units == NULL)
  196265. {
  196266. png_warning(png_ptr, "Insufficient memory for pCAL units.");
  196267. return;
  196268. }
  196269. png_memcpy(info_ptr->pcal_units, units, (png_size_t)length);
  196270. info_ptr->pcal_params = (png_charpp)png_malloc_warn(png_ptr,
  196271. (png_uint_32)((nparams + 1) * png_sizeof(png_charp)));
  196272. if (info_ptr->pcal_params == NULL)
  196273. {
  196274. png_warning(png_ptr, "Insufficient memory for pCAL params.");
  196275. return;
  196276. }
  196277. info_ptr->pcal_params[nparams] = NULL;
  196278. for (i = 0; i < nparams; i++)
  196279. {
  196280. length = png_strlen(params[i]) + 1;
  196281. png_debug2(3, "allocating parameter %d for info (%lu bytes)\n", i, length);
  196282. info_ptr->pcal_params[i] = (png_charp)png_malloc_warn(png_ptr, length);
  196283. if (info_ptr->pcal_params[i] == NULL)
  196284. {
  196285. png_warning(png_ptr, "Insufficient memory for pCAL parameter.");
  196286. return;
  196287. }
  196288. png_memcpy(info_ptr->pcal_params[i], params[i], (png_size_t)length);
  196289. }
  196290. info_ptr->valid |= PNG_INFO_pCAL;
  196291. #ifdef PNG_FREE_ME_SUPPORTED
  196292. info_ptr->free_me |= PNG_FREE_PCAL;
  196293. #endif
  196294. }
  196295. #endif
  196296. #if defined(PNG_READ_sCAL_SUPPORTED) || defined(PNG_WRITE_sCAL_SUPPORTED)
  196297. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196298. void PNGAPI
  196299. png_set_sCAL(png_structp png_ptr, png_infop info_ptr,
  196300. int unit, double width, double height)
  196301. {
  196302. png_debug1(1, "in %s storage function\n", "sCAL");
  196303. if (png_ptr == NULL || info_ptr == NULL)
  196304. return;
  196305. info_ptr->scal_unit = (png_byte)unit;
  196306. info_ptr->scal_pixel_width = width;
  196307. info_ptr->scal_pixel_height = height;
  196308. info_ptr->valid |= PNG_INFO_sCAL;
  196309. }
  196310. #else
  196311. #ifdef PNG_FIXED_POINT_SUPPORTED
  196312. void PNGAPI
  196313. png_set_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  196314. int unit, png_charp swidth, png_charp sheight)
  196315. {
  196316. png_uint_32 length;
  196317. png_debug1(1, "in %s storage function\n", "sCAL");
  196318. if (png_ptr == NULL || info_ptr == NULL)
  196319. return;
  196320. info_ptr->scal_unit = (png_byte)unit;
  196321. length = png_strlen(swidth) + 1;
  196322. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  196323. info_ptr->scal_s_width = (png_charp)png_malloc_warn(png_ptr, length);
  196324. if (info_ptr->scal_s_width == NULL)
  196325. {
  196326. png_warning(png_ptr,
  196327. "Memory allocation failed while processing sCAL.");
  196328. }
  196329. png_memcpy(info_ptr->scal_s_width, swidth, (png_size_t)length);
  196330. length = png_strlen(sheight) + 1;
  196331. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  196332. info_ptr->scal_s_height = (png_charp)png_malloc_warn(png_ptr, length);
  196333. if (info_ptr->scal_s_height == NULL)
  196334. {
  196335. png_free (png_ptr, info_ptr->scal_s_width);
  196336. png_warning(png_ptr,
  196337. "Memory allocation failed while processing sCAL.");
  196338. }
  196339. png_memcpy(info_ptr->scal_s_height, sheight, (png_size_t)length);
  196340. info_ptr->valid |= PNG_INFO_sCAL;
  196341. #ifdef PNG_FREE_ME_SUPPORTED
  196342. info_ptr->free_me |= PNG_FREE_SCAL;
  196343. #endif
  196344. }
  196345. #endif
  196346. #endif
  196347. #endif
  196348. #if defined(PNG_pHYs_SUPPORTED)
  196349. void PNGAPI
  196350. png_set_pHYs(png_structp png_ptr, png_infop info_ptr,
  196351. png_uint_32 res_x, png_uint_32 res_y, int unit_type)
  196352. {
  196353. png_debug1(1, "in %s storage function\n", "pHYs");
  196354. if (png_ptr == NULL || info_ptr == NULL)
  196355. return;
  196356. info_ptr->x_pixels_per_unit = res_x;
  196357. info_ptr->y_pixels_per_unit = res_y;
  196358. info_ptr->phys_unit_type = (png_byte)unit_type;
  196359. info_ptr->valid |= PNG_INFO_pHYs;
  196360. }
  196361. #endif
  196362. void PNGAPI
  196363. png_set_PLTE(png_structp png_ptr, png_infop info_ptr,
  196364. png_colorp palette, int num_palette)
  196365. {
  196366. png_debug1(1, "in %s storage function\n", "PLTE");
  196367. if (png_ptr == NULL || info_ptr == NULL)
  196368. return;
  196369. if (num_palette < 0 || num_palette > PNG_MAX_PALETTE_LENGTH)
  196370. {
  196371. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196372. png_error(png_ptr, "Invalid palette length");
  196373. else
  196374. {
  196375. png_warning(png_ptr, "Invalid palette length");
  196376. return;
  196377. }
  196378. }
  196379. /*
  196380. * It may not actually be necessary to set png_ptr->palette here;
  196381. * we do it for backward compatibility with the way the png_handle_tRNS
  196382. * function used to do the allocation.
  196383. */
  196384. #ifdef PNG_FREE_ME_SUPPORTED
  196385. png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0);
  196386. #endif
  196387. /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead
  196388. of num_palette entries,
  196389. in case of an invalid PNG file that has too-large sample values. */
  196390. png_ptr->palette = (png_colorp)png_malloc(png_ptr,
  196391. PNG_MAX_PALETTE_LENGTH * png_sizeof(png_color));
  196392. png_memset(png_ptr->palette, 0, PNG_MAX_PALETTE_LENGTH *
  196393. png_sizeof(png_color));
  196394. png_memcpy(png_ptr->palette, palette, num_palette * png_sizeof (png_color));
  196395. info_ptr->palette = png_ptr->palette;
  196396. info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette;
  196397. #ifdef PNG_FREE_ME_SUPPORTED
  196398. info_ptr->free_me |= PNG_FREE_PLTE;
  196399. #else
  196400. png_ptr->flags |= PNG_FLAG_FREE_PLTE;
  196401. #endif
  196402. info_ptr->valid |= PNG_INFO_PLTE;
  196403. }
  196404. #if defined(PNG_sBIT_SUPPORTED)
  196405. void PNGAPI
  196406. png_set_sBIT(png_structp png_ptr, png_infop info_ptr,
  196407. png_color_8p sig_bit)
  196408. {
  196409. png_debug1(1, "in %s storage function\n", "sBIT");
  196410. if (png_ptr == NULL || info_ptr == NULL)
  196411. return;
  196412. png_memcpy(&(info_ptr->sig_bit), sig_bit, png_sizeof (png_color_8));
  196413. info_ptr->valid |= PNG_INFO_sBIT;
  196414. }
  196415. #endif
  196416. #if defined(PNG_sRGB_SUPPORTED)
  196417. void PNGAPI
  196418. png_set_sRGB(png_structp png_ptr, png_infop info_ptr, int intent)
  196419. {
  196420. png_debug1(1, "in %s storage function\n", "sRGB");
  196421. if (png_ptr == NULL || info_ptr == NULL)
  196422. return;
  196423. info_ptr->srgb_intent = (png_byte)intent;
  196424. info_ptr->valid |= PNG_INFO_sRGB;
  196425. }
  196426. void PNGAPI
  196427. png_set_sRGB_gAMA_and_cHRM(png_structp png_ptr, png_infop info_ptr,
  196428. int intent)
  196429. {
  196430. #if defined(PNG_gAMA_SUPPORTED)
  196431. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196432. float file_gamma;
  196433. #endif
  196434. #ifdef PNG_FIXED_POINT_SUPPORTED
  196435. png_fixed_point int_file_gamma;
  196436. #endif
  196437. #endif
  196438. #if defined(PNG_cHRM_SUPPORTED)
  196439. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196440. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  196441. #endif
  196442. #ifdef PNG_FIXED_POINT_SUPPORTED
  196443. png_fixed_point int_white_x, int_white_y, int_red_x, int_red_y, int_green_x,
  196444. int_green_y, int_blue_x, int_blue_y;
  196445. #endif
  196446. #endif
  196447. png_debug1(1, "in %s storage function\n", "sRGB_gAMA_and_cHRM");
  196448. if (png_ptr == NULL || info_ptr == NULL)
  196449. return;
  196450. png_set_sRGB(png_ptr, info_ptr, intent);
  196451. #if defined(PNG_gAMA_SUPPORTED)
  196452. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196453. file_gamma = (float).45455;
  196454. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  196455. #endif
  196456. #ifdef PNG_FIXED_POINT_SUPPORTED
  196457. int_file_gamma = 45455L;
  196458. png_set_gAMA_fixed(png_ptr, info_ptr, int_file_gamma);
  196459. #endif
  196460. #endif
  196461. #if defined(PNG_cHRM_SUPPORTED)
  196462. #ifdef PNG_FIXED_POINT_SUPPORTED
  196463. int_white_x = 31270L;
  196464. int_white_y = 32900L;
  196465. int_red_x = 64000L;
  196466. int_red_y = 33000L;
  196467. int_green_x = 30000L;
  196468. int_green_y = 60000L;
  196469. int_blue_x = 15000L;
  196470. int_blue_y = 6000L;
  196471. png_set_cHRM_fixed(png_ptr, info_ptr,
  196472. int_white_x, int_white_y, int_red_x, int_red_y, int_green_x, int_green_y,
  196473. int_blue_x, int_blue_y);
  196474. #endif
  196475. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196476. white_x = (float).3127;
  196477. white_y = (float).3290;
  196478. red_x = (float).64;
  196479. red_y = (float).33;
  196480. green_x = (float).30;
  196481. green_y = (float).60;
  196482. blue_x = (float).15;
  196483. blue_y = (float).06;
  196484. png_set_cHRM(png_ptr, info_ptr,
  196485. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  196486. #endif
  196487. #endif
  196488. }
  196489. #endif
  196490. #if defined(PNG_iCCP_SUPPORTED)
  196491. void PNGAPI
  196492. png_set_iCCP(png_structp png_ptr, png_infop info_ptr,
  196493. png_charp name, int compression_type,
  196494. png_charp profile, png_uint_32 proflen)
  196495. {
  196496. png_charp new_iccp_name;
  196497. png_charp new_iccp_profile;
  196498. png_debug1(1, "in %s storage function\n", "iCCP");
  196499. if (png_ptr == NULL || info_ptr == NULL || name == NULL || profile == NULL)
  196500. return;
  196501. new_iccp_name = (png_charp)png_malloc_warn(png_ptr, png_strlen(name)+1);
  196502. if (new_iccp_name == NULL)
  196503. {
  196504. png_warning(png_ptr, "Insufficient memory to process iCCP chunk.");
  196505. return;
  196506. }
  196507. png_strncpy(new_iccp_name, name, png_strlen(name)+1);
  196508. new_iccp_profile = (png_charp)png_malloc_warn(png_ptr, proflen);
  196509. if (new_iccp_profile == NULL)
  196510. {
  196511. png_free (png_ptr, new_iccp_name);
  196512. png_warning(png_ptr, "Insufficient memory to process iCCP profile.");
  196513. return;
  196514. }
  196515. png_memcpy(new_iccp_profile, profile, (png_size_t)proflen);
  196516. png_free_data(png_ptr, info_ptr, PNG_FREE_ICCP, 0);
  196517. info_ptr->iccp_proflen = proflen;
  196518. info_ptr->iccp_name = new_iccp_name;
  196519. info_ptr->iccp_profile = new_iccp_profile;
  196520. /* Compression is always zero but is here so the API and info structure
  196521. * does not have to change if we introduce multiple compression types */
  196522. info_ptr->iccp_compression = (png_byte)compression_type;
  196523. #ifdef PNG_FREE_ME_SUPPORTED
  196524. info_ptr->free_me |= PNG_FREE_ICCP;
  196525. #endif
  196526. info_ptr->valid |= PNG_INFO_iCCP;
  196527. }
  196528. #endif
  196529. #if defined(PNG_TEXT_SUPPORTED)
  196530. void PNGAPI
  196531. png_set_text(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  196532. int num_text)
  196533. {
  196534. int ret;
  196535. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, num_text);
  196536. if (ret)
  196537. png_error(png_ptr, "Insufficient memory to store text");
  196538. }
  196539. int /* PRIVATE */
  196540. png_set_text_2(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  196541. int num_text)
  196542. {
  196543. int i;
  196544. png_debug1(1, "in %s storage function\n", (png_ptr->chunk_name[0] == '\0' ?
  196545. "text" : (png_const_charp)png_ptr->chunk_name));
  196546. if (png_ptr == NULL || info_ptr == NULL || num_text == 0)
  196547. return(0);
  196548. /* Make sure we have enough space in the "text" array in info_struct
  196549. * to hold all of the incoming text_ptr objects.
  196550. */
  196551. if (info_ptr->num_text + num_text > info_ptr->max_text)
  196552. {
  196553. if (info_ptr->text != NULL)
  196554. {
  196555. png_textp old_text;
  196556. int old_max;
  196557. old_max = info_ptr->max_text;
  196558. info_ptr->max_text = info_ptr->num_text + num_text + 8;
  196559. old_text = info_ptr->text;
  196560. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  196561. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  196562. if (info_ptr->text == NULL)
  196563. {
  196564. png_free(png_ptr, old_text);
  196565. return(1);
  196566. }
  196567. png_memcpy(info_ptr->text, old_text, (png_size_t)(old_max *
  196568. png_sizeof(png_text)));
  196569. png_free(png_ptr, old_text);
  196570. }
  196571. else
  196572. {
  196573. info_ptr->max_text = num_text + 8;
  196574. info_ptr->num_text = 0;
  196575. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  196576. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  196577. if (info_ptr->text == NULL)
  196578. return(1);
  196579. #ifdef PNG_FREE_ME_SUPPORTED
  196580. info_ptr->free_me |= PNG_FREE_TEXT;
  196581. #endif
  196582. }
  196583. png_debug1(3, "allocated %d entries for info_ptr->text\n",
  196584. info_ptr->max_text);
  196585. }
  196586. for (i = 0; i < num_text; i++)
  196587. {
  196588. png_size_t text_length,key_len;
  196589. png_size_t lang_len,lang_key_len;
  196590. png_textp textp = &(info_ptr->text[info_ptr->num_text]);
  196591. if (text_ptr[i].key == NULL)
  196592. continue;
  196593. key_len = png_strlen(text_ptr[i].key);
  196594. if(text_ptr[i].compression <= 0)
  196595. {
  196596. lang_len = 0;
  196597. lang_key_len = 0;
  196598. }
  196599. else
  196600. #ifdef PNG_iTXt_SUPPORTED
  196601. {
  196602. /* set iTXt data */
  196603. if (text_ptr[i].lang != NULL)
  196604. lang_len = png_strlen(text_ptr[i].lang);
  196605. else
  196606. lang_len = 0;
  196607. if (text_ptr[i].lang_key != NULL)
  196608. lang_key_len = png_strlen(text_ptr[i].lang_key);
  196609. else
  196610. lang_key_len = 0;
  196611. }
  196612. #else
  196613. {
  196614. png_warning(png_ptr, "iTXt chunk not supported.");
  196615. continue;
  196616. }
  196617. #endif
  196618. if (text_ptr[i].text == NULL || text_ptr[i].text[0] == '\0')
  196619. {
  196620. text_length = 0;
  196621. #ifdef PNG_iTXt_SUPPORTED
  196622. if(text_ptr[i].compression > 0)
  196623. textp->compression = PNG_ITXT_COMPRESSION_NONE;
  196624. else
  196625. #endif
  196626. textp->compression = PNG_TEXT_COMPRESSION_NONE;
  196627. }
  196628. else
  196629. {
  196630. text_length = png_strlen(text_ptr[i].text);
  196631. textp->compression = text_ptr[i].compression;
  196632. }
  196633. textp->key = (png_charp)png_malloc_warn(png_ptr,
  196634. (png_uint_32)(key_len + text_length + lang_len + lang_key_len + 4));
  196635. if (textp->key == NULL)
  196636. return(1);
  196637. png_debug2(2, "Allocated %lu bytes at %x in png_set_text\n",
  196638. (png_uint_32)(key_len + lang_len + lang_key_len + text_length + 4),
  196639. (int)textp->key);
  196640. png_memcpy(textp->key, text_ptr[i].key,
  196641. (png_size_t)(key_len));
  196642. *(textp->key+key_len) = '\0';
  196643. #ifdef PNG_iTXt_SUPPORTED
  196644. if (text_ptr[i].compression > 0)
  196645. {
  196646. textp->lang=textp->key + key_len + 1;
  196647. png_memcpy(textp->lang, text_ptr[i].lang, lang_len);
  196648. *(textp->lang+lang_len) = '\0';
  196649. textp->lang_key=textp->lang + lang_len + 1;
  196650. png_memcpy(textp->lang_key, text_ptr[i].lang_key, lang_key_len);
  196651. *(textp->lang_key+lang_key_len) = '\0';
  196652. textp->text=textp->lang_key + lang_key_len + 1;
  196653. }
  196654. else
  196655. #endif
  196656. {
  196657. #ifdef PNG_iTXt_SUPPORTED
  196658. textp->lang=NULL;
  196659. textp->lang_key=NULL;
  196660. #endif
  196661. textp->text=textp->key + key_len + 1;
  196662. }
  196663. if(text_length)
  196664. png_memcpy(textp->text, text_ptr[i].text,
  196665. (png_size_t)(text_length));
  196666. *(textp->text+text_length) = '\0';
  196667. #ifdef PNG_iTXt_SUPPORTED
  196668. if(textp->compression > 0)
  196669. {
  196670. textp->text_length = 0;
  196671. textp->itxt_length = text_length;
  196672. }
  196673. else
  196674. #endif
  196675. {
  196676. textp->text_length = text_length;
  196677. #ifdef PNG_iTXt_SUPPORTED
  196678. textp->itxt_length = 0;
  196679. #endif
  196680. }
  196681. info_ptr->num_text++;
  196682. png_debug1(3, "transferred text chunk %d\n", info_ptr->num_text);
  196683. }
  196684. return(0);
  196685. }
  196686. #endif
  196687. #if defined(PNG_tIME_SUPPORTED)
  196688. void PNGAPI
  196689. png_set_tIME(png_structp png_ptr, png_infop info_ptr, png_timep mod_time)
  196690. {
  196691. png_debug1(1, "in %s storage function\n", "tIME");
  196692. if (png_ptr == NULL || info_ptr == NULL ||
  196693. (png_ptr->mode & PNG_WROTE_tIME))
  196694. return;
  196695. png_memcpy(&(info_ptr->mod_time), mod_time, png_sizeof (png_time));
  196696. info_ptr->valid |= PNG_INFO_tIME;
  196697. }
  196698. #endif
  196699. #if defined(PNG_tRNS_SUPPORTED)
  196700. void PNGAPI
  196701. png_set_tRNS(png_structp png_ptr, png_infop info_ptr,
  196702. png_bytep trans, int num_trans, png_color_16p trans_values)
  196703. {
  196704. png_debug1(1, "in %s storage function\n", "tRNS");
  196705. if (png_ptr == NULL || info_ptr == NULL)
  196706. return;
  196707. if (trans != NULL)
  196708. {
  196709. /*
  196710. * It may not actually be necessary to set png_ptr->trans here;
  196711. * we do it for backward compatibility with the way the png_handle_tRNS
  196712. * function used to do the allocation.
  196713. */
  196714. #ifdef PNG_FREE_ME_SUPPORTED
  196715. png_free_data(png_ptr, info_ptr, PNG_FREE_TRNS, 0);
  196716. #endif
  196717. /* Changed from num_trans to PNG_MAX_PALETTE_LENGTH in version 1.2.1 */
  196718. png_ptr->trans = info_ptr->trans = (png_bytep)png_malloc(png_ptr,
  196719. (png_uint_32)PNG_MAX_PALETTE_LENGTH);
  196720. if (num_trans <= PNG_MAX_PALETTE_LENGTH)
  196721. png_memcpy(info_ptr->trans, trans, (png_size_t)num_trans);
  196722. #ifdef PNG_FREE_ME_SUPPORTED
  196723. info_ptr->free_me |= PNG_FREE_TRNS;
  196724. #else
  196725. png_ptr->flags |= PNG_FLAG_FREE_TRNS;
  196726. #endif
  196727. }
  196728. if (trans_values != NULL)
  196729. {
  196730. png_memcpy(&(info_ptr->trans_values), trans_values,
  196731. png_sizeof(png_color_16));
  196732. if (num_trans == 0)
  196733. num_trans = 1;
  196734. }
  196735. info_ptr->num_trans = (png_uint_16)num_trans;
  196736. info_ptr->valid |= PNG_INFO_tRNS;
  196737. }
  196738. #endif
  196739. #if defined(PNG_sPLT_SUPPORTED)
  196740. void PNGAPI
  196741. png_set_sPLT(png_structp png_ptr,
  196742. png_infop info_ptr, png_sPLT_tp entries, int nentries)
  196743. {
  196744. png_sPLT_tp np;
  196745. int i;
  196746. if (png_ptr == NULL || info_ptr == NULL)
  196747. return;
  196748. np = (png_sPLT_tp)png_malloc_warn(png_ptr,
  196749. (info_ptr->splt_palettes_num + nentries) * png_sizeof(png_sPLT_t));
  196750. if (np == NULL)
  196751. {
  196752. png_warning(png_ptr, "No memory for sPLT palettes.");
  196753. return;
  196754. }
  196755. png_memcpy(np, info_ptr->splt_palettes,
  196756. info_ptr->splt_palettes_num * png_sizeof(png_sPLT_t));
  196757. png_free(png_ptr, info_ptr->splt_palettes);
  196758. info_ptr->splt_palettes=NULL;
  196759. for (i = 0; i < nentries; i++)
  196760. {
  196761. png_sPLT_tp to = np + info_ptr->splt_palettes_num + i;
  196762. png_sPLT_tp from = entries + i;
  196763. to->name = (png_charp)png_malloc_warn(png_ptr,
  196764. png_strlen(from->name) + 1);
  196765. if (to->name == NULL)
  196766. {
  196767. png_warning(png_ptr,
  196768. "Out of memory while processing sPLT chunk");
  196769. }
  196770. /* TODO: use png_malloc_warn */
  196771. png_strncpy(to->name, from->name, png_strlen(from->name)+1);
  196772. to->entries = (png_sPLT_entryp)png_malloc_warn(png_ptr,
  196773. from->nentries * png_sizeof(png_sPLT_entry));
  196774. /* TODO: use png_malloc_warn */
  196775. png_memcpy(to->entries, from->entries,
  196776. from->nentries * png_sizeof(png_sPLT_entry));
  196777. if (to->entries == NULL)
  196778. {
  196779. png_warning(png_ptr,
  196780. "Out of memory while processing sPLT chunk");
  196781. png_free(png_ptr,to->name);
  196782. to->name = NULL;
  196783. }
  196784. to->nentries = from->nentries;
  196785. to->depth = from->depth;
  196786. }
  196787. info_ptr->splt_palettes = np;
  196788. info_ptr->splt_palettes_num += nentries;
  196789. info_ptr->valid |= PNG_INFO_sPLT;
  196790. #ifdef PNG_FREE_ME_SUPPORTED
  196791. info_ptr->free_me |= PNG_FREE_SPLT;
  196792. #endif
  196793. }
  196794. #endif /* PNG_sPLT_SUPPORTED */
  196795. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  196796. void PNGAPI
  196797. png_set_unknown_chunks(png_structp png_ptr,
  196798. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns)
  196799. {
  196800. png_unknown_chunkp np;
  196801. int i;
  196802. if (png_ptr == NULL || info_ptr == NULL || num_unknowns == 0)
  196803. return;
  196804. np = (png_unknown_chunkp)png_malloc_warn(png_ptr,
  196805. (info_ptr->unknown_chunks_num + num_unknowns) *
  196806. png_sizeof(png_unknown_chunk));
  196807. if (np == NULL)
  196808. {
  196809. png_warning(png_ptr,
  196810. "Out of memory while processing unknown chunk.");
  196811. return;
  196812. }
  196813. png_memcpy(np, info_ptr->unknown_chunks,
  196814. info_ptr->unknown_chunks_num * png_sizeof(png_unknown_chunk));
  196815. png_free(png_ptr, info_ptr->unknown_chunks);
  196816. info_ptr->unknown_chunks=NULL;
  196817. for (i = 0; i < num_unknowns; i++)
  196818. {
  196819. png_unknown_chunkp to = np + info_ptr->unknown_chunks_num + i;
  196820. png_unknown_chunkp from = unknowns + i;
  196821. png_strncpy((png_charp)to->name, (png_charp)from->name, 5);
  196822. to->data = (png_bytep)png_malloc_warn(png_ptr, from->size);
  196823. if (to->data == NULL)
  196824. {
  196825. png_warning(png_ptr,
  196826. "Out of memory while processing unknown chunk.");
  196827. }
  196828. else
  196829. {
  196830. png_memcpy(to->data, from->data, from->size);
  196831. to->size = from->size;
  196832. /* note our location in the read or write sequence */
  196833. to->location = (png_byte)(png_ptr->mode & 0xff);
  196834. }
  196835. }
  196836. info_ptr->unknown_chunks = np;
  196837. info_ptr->unknown_chunks_num += num_unknowns;
  196838. #ifdef PNG_FREE_ME_SUPPORTED
  196839. info_ptr->free_me |= PNG_FREE_UNKN;
  196840. #endif
  196841. }
  196842. void PNGAPI
  196843. png_set_unknown_chunk_location(png_structp png_ptr, png_infop info_ptr,
  196844. int chunk, int location)
  196845. {
  196846. if(png_ptr != NULL && info_ptr != NULL && chunk >= 0 && chunk <
  196847. (int)info_ptr->unknown_chunks_num)
  196848. info_ptr->unknown_chunks[chunk].location = (png_byte)location;
  196849. }
  196850. #endif
  196851. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  196852. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  196853. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  196854. void PNGAPI
  196855. png_permit_empty_plte (png_structp png_ptr, int empty_plte_permitted)
  196856. {
  196857. /* This function is deprecated in favor of png_permit_mng_features()
  196858. and will be removed from libpng-1.3.0 */
  196859. png_debug(1, "in png_permit_empty_plte, DEPRECATED.\n");
  196860. if (png_ptr == NULL)
  196861. return;
  196862. png_ptr->mng_features_permitted = (png_byte)
  196863. ((png_ptr->mng_features_permitted & (~(PNG_FLAG_MNG_EMPTY_PLTE))) |
  196864. ((empty_plte_permitted & PNG_FLAG_MNG_EMPTY_PLTE)));
  196865. }
  196866. #endif
  196867. #endif
  196868. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  196869. png_uint_32 PNGAPI
  196870. png_permit_mng_features (png_structp png_ptr, png_uint_32 mng_features)
  196871. {
  196872. png_debug(1, "in png_permit_mng_features\n");
  196873. if (png_ptr == NULL)
  196874. return (png_uint_32)0;
  196875. png_ptr->mng_features_permitted =
  196876. (png_byte)(mng_features & PNG_ALL_MNG_FEATURES);
  196877. return (png_uint_32)png_ptr->mng_features_permitted;
  196878. }
  196879. #endif
  196880. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  196881. void PNGAPI
  196882. png_set_keep_unknown_chunks(png_structp png_ptr, int keep, png_bytep
  196883. chunk_list, int num_chunks)
  196884. {
  196885. png_bytep new_list, p;
  196886. int i, old_num_chunks;
  196887. if (png_ptr == NULL)
  196888. return;
  196889. if (num_chunks == 0)
  196890. {
  196891. if(keep == PNG_HANDLE_CHUNK_ALWAYS || keep == PNG_HANDLE_CHUNK_IF_SAFE)
  196892. png_ptr->flags |= PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  196893. else
  196894. png_ptr->flags &= ~PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  196895. if(keep == PNG_HANDLE_CHUNK_ALWAYS)
  196896. png_ptr->flags |= PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  196897. else
  196898. png_ptr->flags &= ~PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  196899. return;
  196900. }
  196901. if (chunk_list == NULL)
  196902. return;
  196903. old_num_chunks=png_ptr->num_chunk_list;
  196904. new_list=(png_bytep)png_malloc(png_ptr,
  196905. (png_uint_32)(5*(num_chunks+old_num_chunks)));
  196906. if(png_ptr->chunk_list != NULL)
  196907. {
  196908. png_memcpy(new_list, png_ptr->chunk_list,
  196909. (png_size_t)(5*old_num_chunks));
  196910. png_free(png_ptr, png_ptr->chunk_list);
  196911. png_ptr->chunk_list=NULL;
  196912. }
  196913. png_memcpy(new_list+5*old_num_chunks, chunk_list,
  196914. (png_size_t)(5*num_chunks));
  196915. for (p=new_list+5*old_num_chunks+4, i=0; i<num_chunks; i++, p+=5)
  196916. *p=(png_byte)keep;
  196917. png_ptr->num_chunk_list=old_num_chunks+num_chunks;
  196918. png_ptr->chunk_list=new_list;
  196919. #ifdef PNG_FREE_ME_SUPPORTED
  196920. png_ptr->free_me |= PNG_FREE_LIST;
  196921. #endif
  196922. }
  196923. #endif
  196924. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  196925. void PNGAPI
  196926. png_set_read_user_chunk_fn(png_structp png_ptr, png_voidp user_chunk_ptr,
  196927. png_user_chunk_ptr read_user_chunk_fn)
  196928. {
  196929. png_debug(1, "in png_set_read_user_chunk_fn\n");
  196930. if (png_ptr == NULL)
  196931. return;
  196932. png_ptr->read_user_chunk_fn = read_user_chunk_fn;
  196933. png_ptr->user_chunk_ptr = user_chunk_ptr;
  196934. }
  196935. #endif
  196936. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  196937. void PNGAPI
  196938. png_set_rows(png_structp png_ptr, png_infop info_ptr, png_bytepp row_pointers)
  196939. {
  196940. png_debug1(1, "in %s storage function\n", "rows");
  196941. if (png_ptr == NULL || info_ptr == NULL)
  196942. return;
  196943. if(info_ptr->row_pointers && (info_ptr->row_pointers != row_pointers))
  196944. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  196945. info_ptr->row_pointers = row_pointers;
  196946. if(row_pointers)
  196947. info_ptr->valid |= PNG_INFO_IDAT;
  196948. }
  196949. #endif
  196950. #ifdef PNG_WRITE_SUPPORTED
  196951. void PNGAPI
  196952. png_set_compression_buffer_size(png_structp png_ptr, png_uint_32 size)
  196953. {
  196954. if (png_ptr == NULL)
  196955. return;
  196956. if(png_ptr->zbuf)
  196957. png_free(png_ptr, png_ptr->zbuf);
  196958. png_ptr->zbuf_size = (png_size_t)size;
  196959. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, size);
  196960. png_ptr->zstream.next_out = png_ptr->zbuf;
  196961. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  196962. }
  196963. #endif
  196964. void PNGAPI
  196965. png_set_invalid(png_structp png_ptr, png_infop info_ptr, int mask)
  196966. {
  196967. if (png_ptr && info_ptr)
  196968. info_ptr->valid &= ~(mask);
  196969. }
  196970. #ifndef PNG_1_0_X
  196971. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  196972. /* function was added to libpng 1.2.0 and should always exist by default */
  196973. void PNGAPI
  196974. png_set_asm_flags (png_structp png_ptr, png_uint_32)
  196975. {
  196976. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  196977. if (png_ptr != NULL)
  196978. png_ptr->asm_flags = 0;
  196979. }
  196980. /* this function was added to libpng 1.2.0 */
  196981. void PNGAPI
  196982. png_set_mmx_thresholds (png_structp png_ptr,
  196983. png_byte,
  196984. png_uint_32)
  196985. {
  196986. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  196987. if (png_ptr == NULL)
  196988. return;
  196989. }
  196990. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  196991. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  196992. /* this function was added to libpng 1.2.6 */
  196993. void PNGAPI
  196994. png_set_user_limits (png_structp png_ptr, png_uint_32 user_width_max,
  196995. png_uint_32 user_height_max)
  196996. {
  196997. /* Images with dimensions larger than these limits will be
  196998. * rejected by png_set_IHDR(). To accept any PNG datastream
  196999. * regardless of dimensions, set both limits to 0x7ffffffL.
  197000. */
  197001. if(png_ptr == NULL) return;
  197002. png_ptr->user_width_max = user_width_max;
  197003. png_ptr->user_height_max = user_height_max;
  197004. }
  197005. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  197006. #endif /* ?PNG_1_0_X */
  197007. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  197008. /*** End of inlined file: pngset.c ***/
  197009. /*** Start of inlined file: pngtrans.c ***/
  197010. /* pngtrans.c - transforms the data in a row (used by both readers and writers)
  197011. *
  197012. * Last changed in libpng 1.2.17 May 15, 2007
  197013. * For conditions of distribution and use, see copyright notice in png.h
  197014. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  197015. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  197016. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  197017. */
  197018. #define PNG_INTERNAL
  197019. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  197020. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  197021. /* turn on BGR-to-RGB mapping */
  197022. void PNGAPI
  197023. png_set_bgr(png_structp png_ptr)
  197024. {
  197025. png_debug(1, "in png_set_bgr\n");
  197026. if(png_ptr == NULL) return;
  197027. png_ptr->transformations |= PNG_BGR;
  197028. }
  197029. #endif
  197030. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  197031. /* turn on 16 bit byte swapping */
  197032. void PNGAPI
  197033. png_set_swap(png_structp png_ptr)
  197034. {
  197035. png_debug(1, "in png_set_swap\n");
  197036. if(png_ptr == NULL) return;
  197037. if (png_ptr->bit_depth == 16)
  197038. png_ptr->transformations |= PNG_SWAP_BYTES;
  197039. }
  197040. #endif
  197041. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  197042. /* turn on pixel packing */
  197043. void PNGAPI
  197044. png_set_packing(png_structp png_ptr)
  197045. {
  197046. png_debug(1, "in png_set_packing\n");
  197047. if(png_ptr == NULL) return;
  197048. if (png_ptr->bit_depth < 8)
  197049. {
  197050. png_ptr->transformations |= PNG_PACK;
  197051. png_ptr->usr_bit_depth = 8;
  197052. }
  197053. }
  197054. #endif
  197055. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  197056. /* turn on packed pixel swapping */
  197057. void PNGAPI
  197058. png_set_packswap(png_structp png_ptr)
  197059. {
  197060. png_debug(1, "in png_set_packswap\n");
  197061. if(png_ptr == NULL) return;
  197062. if (png_ptr->bit_depth < 8)
  197063. png_ptr->transformations |= PNG_PACKSWAP;
  197064. }
  197065. #endif
  197066. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  197067. void PNGAPI
  197068. png_set_shift(png_structp png_ptr, png_color_8p true_bits)
  197069. {
  197070. png_debug(1, "in png_set_shift\n");
  197071. if(png_ptr == NULL) return;
  197072. png_ptr->transformations |= PNG_SHIFT;
  197073. png_ptr->shift = *true_bits;
  197074. }
  197075. #endif
  197076. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  197077. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  197078. int PNGAPI
  197079. png_set_interlace_handling(png_structp png_ptr)
  197080. {
  197081. png_debug(1, "in png_set_interlace handling\n");
  197082. if (png_ptr && png_ptr->interlaced)
  197083. {
  197084. png_ptr->transformations |= PNG_INTERLACE;
  197085. return (7);
  197086. }
  197087. return (1);
  197088. }
  197089. #endif
  197090. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  197091. /* Add a filler byte on read, or remove a filler or alpha byte on write.
  197092. * The filler type has changed in v0.95 to allow future 2-byte fillers
  197093. * for 48-bit input data, as well as to avoid problems with some compilers
  197094. * that don't like bytes as parameters.
  197095. */
  197096. void PNGAPI
  197097. png_set_filler(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  197098. {
  197099. png_debug(1, "in png_set_filler\n");
  197100. if(png_ptr == NULL) return;
  197101. png_ptr->transformations |= PNG_FILLER;
  197102. png_ptr->filler = (png_byte)filler;
  197103. if (filler_loc == PNG_FILLER_AFTER)
  197104. png_ptr->flags |= PNG_FLAG_FILLER_AFTER;
  197105. else
  197106. png_ptr->flags &= ~PNG_FLAG_FILLER_AFTER;
  197107. /* This should probably go in the "do_read_filler" routine.
  197108. * I attempted to do that in libpng-1.0.1a but that caused problems
  197109. * so I restored it in libpng-1.0.2a
  197110. */
  197111. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  197112. {
  197113. png_ptr->usr_channels = 4;
  197114. }
  197115. /* Also I added this in libpng-1.0.2a (what happens when we expand
  197116. * a less-than-8-bit grayscale to GA? */
  197117. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY && png_ptr->bit_depth >= 8)
  197118. {
  197119. png_ptr->usr_channels = 2;
  197120. }
  197121. }
  197122. #if !defined(PNG_1_0_X)
  197123. /* Added to libpng-1.2.7 */
  197124. void PNGAPI
  197125. png_set_add_alpha(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  197126. {
  197127. png_debug(1, "in png_set_add_alpha\n");
  197128. if(png_ptr == NULL) return;
  197129. png_set_filler(png_ptr, filler, filler_loc);
  197130. png_ptr->transformations |= PNG_ADD_ALPHA;
  197131. }
  197132. #endif
  197133. #endif
  197134. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  197135. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  197136. void PNGAPI
  197137. png_set_swap_alpha(png_structp png_ptr)
  197138. {
  197139. png_debug(1, "in png_set_swap_alpha\n");
  197140. if(png_ptr == NULL) return;
  197141. png_ptr->transformations |= PNG_SWAP_ALPHA;
  197142. }
  197143. #endif
  197144. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  197145. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  197146. void PNGAPI
  197147. png_set_invert_alpha(png_structp png_ptr)
  197148. {
  197149. png_debug(1, "in png_set_invert_alpha\n");
  197150. if(png_ptr == NULL) return;
  197151. png_ptr->transformations |= PNG_INVERT_ALPHA;
  197152. }
  197153. #endif
  197154. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  197155. void PNGAPI
  197156. png_set_invert_mono(png_structp png_ptr)
  197157. {
  197158. png_debug(1, "in png_set_invert_mono\n");
  197159. if(png_ptr == NULL) return;
  197160. png_ptr->transformations |= PNG_INVERT_MONO;
  197161. }
  197162. /* invert monochrome grayscale data */
  197163. void /* PRIVATE */
  197164. png_do_invert(png_row_infop row_info, png_bytep row)
  197165. {
  197166. png_debug(1, "in png_do_invert\n");
  197167. /* This test removed from libpng version 1.0.13 and 1.2.0:
  197168. * if (row_info->bit_depth == 1 &&
  197169. */
  197170. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197171. if (row == NULL || row_info == NULL)
  197172. return;
  197173. #endif
  197174. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  197175. {
  197176. png_bytep rp = row;
  197177. png_uint_32 i;
  197178. png_uint_32 istop = row_info->rowbytes;
  197179. for (i = 0; i < istop; i++)
  197180. {
  197181. *rp = (png_byte)(~(*rp));
  197182. rp++;
  197183. }
  197184. }
  197185. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  197186. row_info->bit_depth == 8)
  197187. {
  197188. png_bytep rp = row;
  197189. png_uint_32 i;
  197190. png_uint_32 istop = row_info->rowbytes;
  197191. for (i = 0; i < istop; i+=2)
  197192. {
  197193. *rp = (png_byte)(~(*rp));
  197194. rp+=2;
  197195. }
  197196. }
  197197. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  197198. row_info->bit_depth == 16)
  197199. {
  197200. png_bytep rp = row;
  197201. png_uint_32 i;
  197202. png_uint_32 istop = row_info->rowbytes;
  197203. for (i = 0; i < istop; i+=4)
  197204. {
  197205. *rp = (png_byte)(~(*rp));
  197206. *(rp+1) = (png_byte)(~(*(rp+1)));
  197207. rp+=4;
  197208. }
  197209. }
  197210. }
  197211. #endif
  197212. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  197213. /* swaps byte order on 16 bit depth images */
  197214. void /* PRIVATE */
  197215. png_do_swap(png_row_infop row_info, png_bytep row)
  197216. {
  197217. png_debug(1, "in png_do_swap\n");
  197218. if (
  197219. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197220. row != NULL && row_info != NULL &&
  197221. #endif
  197222. row_info->bit_depth == 16)
  197223. {
  197224. png_bytep rp = row;
  197225. png_uint_32 i;
  197226. png_uint_32 istop= row_info->width * row_info->channels;
  197227. for (i = 0; i < istop; i++, rp += 2)
  197228. {
  197229. png_byte t = *rp;
  197230. *rp = *(rp + 1);
  197231. *(rp + 1) = t;
  197232. }
  197233. }
  197234. }
  197235. #endif
  197236. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  197237. static PNG_CONST png_byte onebppswaptable[256] = {
  197238. 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0,
  197239. 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0,
  197240. 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8,
  197241. 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8,
  197242. 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4,
  197243. 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4,
  197244. 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC,
  197245. 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC,
  197246. 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2,
  197247. 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2,
  197248. 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA,
  197249. 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
  197250. 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6,
  197251. 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6,
  197252. 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE,
  197253. 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE,
  197254. 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1,
  197255. 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
  197256. 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9,
  197257. 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9,
  197258. 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5,
  197259. 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5,
  197260. 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED,
  197261. 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
  197262. 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3,
  197263. 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3,
  197264. 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB,
  197265. 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB,
  197266. 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7,
  197267. 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7,
  197268. 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF,
  197269. 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF
  197270. };
  197271. static PNG_CONST png_byte twobppswaptable[256] = {
  197272. 0x00, 0x40, 0x80, 0xC0, 0x10, 0x50, 0x90, 0xD0,
  197273. 0x20, 0x60, 0xA0, 0xE0, 0x30, 0x70, 0xB0, 0xF0,
  197274. 0x04, 0x44, 0x84, 0xC4, 0x14, 0x54, 0x94, 0xD4,
  197275. 0x24, 0x64, 0xA4, 0xE4, 0x34, 0x74, 0xB4, 0xF4,
  197276. 0x08, 0x48, 0x88, 0xC8, 0x18, 0x58, 0x98, 0xD8,
  197277. 0x28, 0x68, 0xA8, 0xE8, 0x38, 0x78, 0xB8, 0xF8,
  197278. 0x0C, 0x4C, 0x8C, 0xCC, 0x1C, 0x5C, 0x9C, 0xDC,
  197279. 0x2C, 0x6C, 0xAC, 0xEC, 0x3C, 0x7C, 0xBC, 0xFC,
  197280. 0x01, 0x41, 0x81, 0xC1, 0x11, 0x51, 0x91, 0xD1,
  197281. 0x21, 0x61, 0xA1, 0xE1, 0x31, 0x71, 0xB1, 0xF1,
  197282. 0x05, 0x45, 0x85, 0xC5, 0x15, 0x55, 0x95, 0xD5,
  197283. 0x25, 0x65, 0xA5, 0xE5, 0x35, 0x75, 0xB5, 0xF5,
  197284. 0x09, 0x49, 0x89, 0xC9, 0x19, 0x59, 0x99, 0xD9,
  197285. 0x29, 0x69, 0xA9, 0xE9, 0x39, 0x79, 0xB9, 0xF9,
  197286. 0x0D, 0x4D, 0x8D, 0xCD, 0x1D, 0x5D, 0x9D, 0xDD,
  197287. 0x2D, 0x6D, 0xAD, 0xED, 0x3D, 0x7D, 0xBD, 0xFD,
  197288. 0x02, 0x42, 0x82, 0xC2, 0x12, 0x52, 0x92, 0xD2,
  197289. 0x22, 0x62, 0xA2, 0xE2, 0x32, 0x72, 0xB2, 0xF2,
  197290. 0x06, 0x46, 0x86, 0xC6, 0x16, 0x56, 0x96, 0xD6,
  197291. 0x26, 0x66, 0xA6, 0xE6, 0x36, 0x76, 0xB6, 0xF6,
  197292. 0x0A, 0x4A, 0x8A, 0xCA, 0x1A, 0x5A, 0x9A, 0xDA,
  197293. 0x2A, 0x6A, 0xAA, 0xEA, 0x3A, 0x7A, 0xBA, 0xFA,
  197294. 0x0E, 0x4E, 0x8E, 0xCE, 0x1E, 0x5E, 0x9E, 0xDE,
  197295. 0x2E, 0x6E, 0xAE, 0xEE, 0x3E, 0x7E, 0xBE, 0xFE,
  197296. 0x03, 0x43, 0x83, 0xC3, 0x13, 0x53, 0x93, 0xD3,
  197297. 0x23, 0x63, 0xA3, 0xE3, 0x33, 0x73, 0xB3, 0xF3,
  197298. 0x07, 0x47, 0x87, 0xC7, 0x17, 0x57, 0x97, 0xD7,
  197299. 0x27, 0x67, 0xA7, 0xE7, 0x37, 0x77, 0xB7, 0xF7,
  197300. 0x0B, 0x4B, 0x8B, 0xCB, 0x1B, 0x5B, 0x9B, 0xDB,
  197301. 0x2B, 0x6B, 0xAB, 0xEB, 0x3B, 0x7B, 0xBB, 0xFB,
  197302. 0x0F, 0x4F, 0x8F, 0xCF, 0x1F, 0x5F, 0x9F, 0xDF,
  197303. 0x2F, 0x6F, 0xAF, 0xEF, 0x3F, 0x7F, 0xBF, 0xFF
  197304. };
  197305. static PNG_CONST png_byte fourbppswaptable[256] = {
  197306. 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70,
  197307. 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0,
  197308. 0x01, 0x11, 0x21, 0x31, 0x41, 0x51, 0x61, 0x71,
  197309. 0x81, 0x91, 0xA1, 0xB1, 0xC1, 0xD1, 0xE1, 0xF1,
  197310. 0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72,
  197311. 0x82, 0x92, 0xA2, 0xB2, 0xC2, 0xD2, 0xE2, 0xF2,
  197312. 0x03, 0x13, 0x23, 0x33, 0x43, 0x53, 0x63, 0x73,
  197313. 0x83, 0x93, 0xA3, 0xB3, 0xC3, 0xD3, 0xE3, 0xF3,
  197314. 0x04, 0x14, 0x24, 0x34, 0x44, 0x54, 0x64, 0x74,
  197315. 0x84, 0x94, 0xA4, 0xB4, 0xC4, 0xD4, 0xE4, 0xF4,
  197316. 0x05, 0x15, 0x25, 0x35, 0x45, 0x55, 0x65, 0x75,
  197317. 0x85, 0x95, 0xA5, 0xB5, 0xC5, 0xD5, 0xE5, 0xF5,
  197318. 0x06, 0x16, 0x26, 0x36, 0x46, 0x56, 0x66, 0x76,
  197319. 0x86, 0x96, 0xA6, 0xB6, 0xC6, 0xD6, 0xE6, 0xF6,
  197320. 0x07, 0x17, 0x27, 0x37, 0x47, 0x57, 0x67, 0x77,
  197321. 0x87, 0x97, 0xA7, 0xB7, 0xC7, 0xD7, 0xE7, 0xF7,
  197322. 0x08, 0x18, 0x28, 0x38, 0x48, 0x58, 0x68, 0x78,
  197323. 0x88, 0x98, 0xA8, 0xB8, 0xC8, 0xD8, 0xE8, 0xF8,
  197324. 0x09, 0x19, 0x29, 0x39, 0x49, 0x59, 0x69, 0x79,
  197325. 0x89, 0x99, 0xA9, 0xB9, 0xC9, 0xD9, 0xE9, 0xF9,
  197326. 0x0A, 0x1A, 0x2A, 0x3A, 0x4A, 0x5A, 0x6A, 0x7A,
  197327. 0x8A, 0x9A, 0xAA, 0xBA, 0xCA, 0xDA, 0xEA, 0xFA,
  197328. 0x0B, 0x1B, 0x2B, 0x3B, 0x4B, 0x5B, 0x6B, 0x7B,
  197329. 0x8B, 0x9B, 0xAB, 0xBB, 0xCB, 0xDB, 0xEB, 0xFB,
  197330. 0x0C, 0x1C, 0x2C, 0x3C, 0x4C, 0x5C, 0x6C, 0x7C,
  197331. 0x8C, 0x9C, 0xAC, 0xBC, 0xCC, 0xDC, 0xEC, 0xFC,
  197332. 0x0D, 0x1D, 0x2D, 0x3D, 0x4D, 0x5D, 0x6D, 0x7D,
  197333. 0x8D, 0x9D, 0xAD, 0xBD, 0xCD, 0xDD, 0xED, 0xFD,
  197334. 0x0E, 0x1E, 0x2E, 0x3E, 0x4E, 0x5E, 0x6E, 0x7E,
  197335. 0x8E, 0x9E, 0xAE, 0xBE, 0xCE, 0xDE, 0xEE, 0xFE,
  197336. 0x0F, 0x1F, 0x2F, 0x3F, 0x4F, 0x5F, 0x6F, 0x7F,
  197337. 0x8F, 0x9F, 0xAF, 0xBF, 0xCF, 0xDF, 0xEF, 0xFF
  197338. };
  197339. /* swaps pixel packing order within bytes */
  197340. void /* PRIVATE */
  197341. png_do_packswap(png_row_infop row_info, png_bytep row)
  197342. {
  197343. png_debug(1, "in png_do_packswap\n");
  197344. if (
  197345. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197346. row != NULL && row_info != NULL &&
  197347. #endif
  197348. row_info->bit_depth < 8)
  197349. {
  197350. png_bytep rp, end, table;
  197351. end = row + row_info->rowbytes;
  197352. if (row_info->bit_depth == 1)
  197353. table = (png_bytep)onebppswaptable;
  197354. else if (row_info->bit_depth == 2)
  197355. table = (png_bytep)twobppswaptable;
  197356. else if (row_info->bit_depth == 4)
  197357. table = (png_bytep)fourbppswaptable;
  197358. else
  197359. return;
  197360. for (rp = row; rp < end; rp++)
  197361. *rp = table[*rp];
  197362. }
  197363. }
  197364. #endif /* PNG_READ_PACKSWAP_SUPPORTED or PNG_WRITE_PACKSWAP_SUPPORTED */
  197365. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  197366. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  197367. /* remove filler or alpha byte(s) */
  197368. void /* PRIVATE */
  197369. png_do_strip_filler(png_row_infop row_info, png_bytep row, png_uint_32 flags)
  197370. {
  197371. png_debug(1, "in png_do_strip_filler\n");
  197372. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197373. if (row != NULL && row_info != NULL)
  197374. #endif
  197375. {
  197376. png_bytep sp=row;
  197377. png_bytep dp=row;
  197378. png_uint_32 row_width=row_info->width;
  197379. png_uint_32 i;
  197380. if ((row_info->color_type == PNG_COLOR_TYPE_RGB ||
  197381. (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  197382. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  197383. row_info->channels == 4)
  197384. {
  197385. if (row_info->bit_depth == 8)
  197386. {
  197387. /* This converts from RGBX or RGBA to RGB */
  197388. if (flags & PNG_FLAG_FILLER_AFTER)
  197389. {
  197390. dp+=3; sp+=4;
  197391. for (i = 1; i < row_width; i++)
  197392. {
  197393. *dp++ = *sp++;
  197394. *dp++ = *sp++;
  197395. *dp++ = *sp++;
  197396. sp++;
  197397. }
  197398. }
  197399. /* This converts from XRGB or ARGB to RGB */
  197400. else
  197401. {
  197402. for (i = 0; i < row_width; i++)
  197403. {
  197404. sp++;
  197405. *dp++ = *sp++;
  197406. *dp++ = *sp++;
  197407. *dp++ = *sp++;
  197408. }
  197409. }
  197410. row_info->pixel_depth = 24;
  197411. row_info->rowbytes = row_width * 3;
  197412. }
  197413. else /* if (row_info->bit_depth == 16) */
  197414. {
  197415. if (flags & PNG_FLAG_FILLER_AFTER)
  197416. {
  197417. /* This converts from RRGGBBXX or RRGGBBAA to RRGGBB */
  197418. sp += 8; dp += 6;
  197419. for (i = 1; i < row_width; i++)
  197420. {
  197421. /* This could be (although png_memcpy is probably slower):
  197422. png_memcpy(dp, sp, 6);
  197423. sp += 8;
  197424. dp += 6;
  197425. */
  197426. *dp++ = *sp++;
  197427. *dp++ = *sp++;
  197428. *dp++ = *sp++;
  197429. *dp++ = *sp++;
  197430. *dp++ = *sp++;
  197431. *dp++ = *sp++;
  197432. sp += 2;
  197433. }
  197434. }
  197435. else
  197436. {
  197437. /* This converts from XXRRGGBB or AARRGGBB to RRGGBB */
  197438. for (i = 0; i < row_width; i++)
  197439. {
  197440. /* This could be (although png_memcpy is probably slower):
  197441. png_memcpy(dp, sp, 6);
  197442. sp += 8;
  197443. dp += 6;
  197444. */
  197445. sp+=2;
  197446. *dp++ = *sp++;
  197447. *dp++ = *sp++;
  197448. *dp++ = *sp++;
  197449. *dp++ = *sp++;
  197450. *dp++ = *sp++;
  197451. *dp++ = *sp++;
  197452. }
  197453. }
  197454. row_info->pixel_depth = 48;
  197455. row_info->rowbytes = row_width * 6;
  197456. }
  197457. row_info->channels = 3;
  197458. }
  197459. else if ((row_info->color_type == PNG_COLOR_TYPE_GRAY ||
  197460. (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  197461. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  197462. row_info->channels == 2)
  197463. {
  197464. if (row_info->bit_depth == 8)
  197465. {
  197466. /* This converts from GX or GA to G */
  197467. if (flags & PNG_FLAG_FILLER_AFTER)
  197468. {
  197469. for (i = 0; i < row_width; i++)
  197470. {
  197471. *dp++ = *sp++;
  197472. sp++;
  197473. }
  197474. }
  197475. /* This converts from XG or AG to G */
  197476. else
  197477. {
  197478. for (i = 0; i < row_width; i++)
  197479. {
  197480. sp++;
  197481. *dp++ = *sp++;
  197482. }
  197483. }
  197484. row_info->pixel_depth = 8;
  197485. row_info->rowbytes = row_width;
  197486. }
  197487. else /* if (row_info->bit_depth == 16) */
  197488. {
  197489. if (flags & PNG_FLAG_FILLER_AFTER)
  197490. {
  197491. /* This converts from GGXX or GGAA to GG */
  197492. sp += 4; dp += 2;
  197493. for (i = 1; i < row_width; i++)
  197494. {
  197495. *dp++ = *sp++;
  197496. *dp++ = *sp++;
  197497. sp += 2;
  197498. }
  197499. }
  197500. else
  197501. {
  197502. /* This converts from XXGG or AAGG to GG */
  197503. for (i = 0; i < row_width; i++)
  197504. {
  197505. sp += 2;
  197506. *dp++ = *sp++;
  197507. *dp++ = *sp++;
  197508. }
  197509. }
  197510. row_info->pixel_depth = 16;
  197511. row_info->rowbytes = row_width * 2;
  197512. }
  197513. row_info->channels = 1;
  197514. }
  197515. if (flags & PNG_FLAG_STRIP_ALPHA)
  197516. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  197517. }
  197518. }
  197519. #endif
  197520. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  197521. /* swaps red and blue bytes within a pixel */
  197522. void /* PRIVATE */
  197523. png_do_bgr(png_row_infop row_info, png_bytep row)
  197524. {
  197525. png_debug(1, "in png_do_bgr\n");
  197526. if (
  197527. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197528. row != NULL && row_info != NULL &&
  197529. #endif
  197530. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  197531. {
  197532. png_uint_32 row_width = row_info->width;
  197533. if (row_info->bit_depth == 8)
  197534. {
  197535. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  197536. {
  197537. png_bytep rp;
  197538. png_uint_32 i;
  197539. for (i = 0, rp = row; i < row_width; i++, rp += 3)
  197540. {
  197541. png_byte save = *rp;
  197542. *rp = *(rp + 2);
  197543. *(rp + 2) = save;
  197544. }
  197545. }
  197546. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  197547. {
  197548. png_bytep rp;
  197549. png_uint_32 i;
  197550. for (i = 0, rp = row; i < row_width; i++, rp += 4)
  197551. {
  197552. png_byte save = *rp;
  197553. *rp = *(rp + 2);
  197554. *(rp + 2) = save;
  197555. }
  197556. }
  197557. }
  197558. else if (row_info->bit_depth == 16)
  197559. {
  197560. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  197561. {
  197562. png_bytep rp;
  197563. png_uint_32 i;
  197564. for (i = 0, rp = row; i < row_width; i++, rp += 6)
  197565. {
  197566. png_byte save = *rp;
  197567. *rp = *(rp + 4);
  197568. *(rp + 4) = save;
  197569. save = *(rp + 1);
  197570. *(rp + 1) = *(rp + 5);
  197571. *(rp + 5) = save;
  197572. }
  197573. }
  197574. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  197575. {
  197576. png_bytep rp;
  197577. png_uint_32 i;
  197578. for (i = 0, rp = row; i < row_width; i++, rp += 8)
  197579. {
  197580. png_byte save = *rp;
  197581. *rp = *(rp + 4);
  197582. *(rp + 4) = save;
  197583. save = *(rp + 1);
  197584. *(rp + 1) = *(rp + 5);
  197585. *(rp + 5) = save;
  197586. }
  197587. }
  197588. }
  197589. }
  197590. }
  197591. #endif /* PNG_READ_BGR_SUPPORTED or PNG_WRITE_BGR_SUPPORTED */
  197592. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  197593. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  197594. defined(PNG_LEGACY_SUPPORTED)
  197595. void PNGAPI
  197596. png_set_user_transform_info(png_structp png_ptr, png_voidp
  197597. user_transform_ptr, int user_transform_depth, int user_transform_channels)
  197598. {
  197599. png_debug(1, "in png_set_user_transform_info\n");
  197600. if(png_ptr == NULL) return;
  197601. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  197602. png_ptr->user_transform_ptr = user_transform_ptr;
  197603. png_ptr->user_transform_depth = (png_byte)user_transform_depth;
  197604. png_ptr->user_transform_channels = (png_byte)user_transform_channels;
  197605. #else
  197606. if(user_transform_ptr || user_transform_depth || user_transform_channels)
  197607. png_warning(png_ptr,
  197608. "This version of libpng does not support user transform info");
  197609. #endif
  197610. }
  197611. #endif
  197612. /* This function returns a pointer to the user_transform_ptr associated with
  197613. * the user transform functions. The application should free any memory
  197614. * associated with this pointer before png_write_destroy and png_read_destroy
  197615. * are called.
  197616. */
  197617. png_voidp PNGAPI
  197618. png_get_user_transform_ptr(png_structp png_ptr)
  197619. {
  197620. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  197621. if (png_ptr == NULL) return (NULL);
  197622. return ((png_voidp)png_ptr->user_transform_ptr);
  197623. #else
  197624. return (NULL);
  197625. #endif
  197626. }
  197627. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  197628. /*** End of inlined file: pngtrans.c ***/
  197629. /*** Start of inlined file: pngwio.c ***/
  197630. /* pngwio.c - functions for data output
  197631. *
  197632. * Last changed in libpng 1.2.13 November 13, 2006
  197633. * For conditions of distribution and use, see copyright notice in png.h
  197634. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  197635. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  197636. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  197637. *
  197638. * This file provides a location for all output. Users who need
  197639. * special handling are expected to write functions that have the same
  197640. * arguments as these and perform similar functions, but that possibly
  197641. * use different output methods. Note that you shouldn't change these
  197642. * functions, but rather write replacement functions and then change
  197643. * them at run time with png_set_write_fn(...).
  197644. */
  197645. #define PNG_INTERNAL
  197646. #ifdef PNG_WRITE_SUPPORTED
  197647. /* Write the data to whatever output you are using. The default routine
  197648. writes to a file pointer. Note that this routine sometimes gets called
  197649. with very small lengths, so you should implement some kind of simple
  197650. buffering if you are using unbuffered writes. This should never be asked
  197651. to write more than 64K on a 16 bit machine. */
  197652. void /* PRIVATE */
  197653. png_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  197654. {
  197655. if (png_ptr->write_data_fn != NULL )
  197656. (*(png_ptr->write_data_fn))(png_ptr, data, length);
  197657. else
  197658. png_error(png_ptr, "Call to NULL write function");
  197659. }
  197660. #if !defined(PNG_NO_STDIO)
  197661. /* This is the function that does the actual writing of data. If you are
  197662. not writing to a standard C stream, you should create a replacement
  197663. write_data function and use it at run time with png_set_write_fn(), rather
  197664. than changing the library. */
  197665. #ifndef USE_FAR_KEYWORD
  197666. void PNGAPI
  197667. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  197668. {
  197669. png_uint_32 check;
  197670. if(png_ptr == NULL) return;
  197671. #if defined(_WIN32_WCE)
  197672. if ( !WriteFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  197673. check = 0;
  197674. #else
  197675. check = fwrite(data, 1, length, (png_FILE_p)(png_ptr->io_ptr));
  197676. #endif
  197677. if (check != length)
  197678. png_error(png_ptr, "Write Error");
  197679. }
  197680. #else
  197681. /* this is the model-independent version. Since the standard I/O library
  197682. can't handle far buffers in the medium and small models, we have to copy
  197683. the data.
  197684. */
  197685. #define NEAR_BUF_SIZE 1024
  197686. #define MIN(a,b) (a <= b ? a : b)
  197687. void PNGAPI
  197688. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  197689. {
  197690. png_uint_32 check;
  197691. png_byte *near_data; /* Needs to be "png_byte *" instead of "png_bytep" */
  197692. png_FILE_p io_ptr;
  197693. if(png_ptr == NULL) return;
  197694. /* Check if data really is near. If so, use usual code. */
  197695. near_data = (png_byte *)CVT_PTR_NOCHECK(data);
  197696. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  197697. if ((png_bytep)near_data == data)
  197698. {
  197699. #if defined(_WIN32_WCE)
  197700. if ( !WriteFile(io_ptr, near_data, length, &check, NULL) )
  197701. check = 0;
  197702. #else
  197703. check = fwrite(near_data, 1, length, io_ptr);
  197704. #endif
  197705. }
  197706. else
  197707. {
  197708. png_byte buf[NEAR_BUF_SIZE];
  197709. png_size_t written, remaining, err;
  197710. check = 0;
  197711. remaining = length;
  197712. do
  197713. {
  197714. written = MIN(NEAR_BUF_SIZE, remaining);
  197715. png_memcpy(buf, data, written); /* copy far buffer to near buffer */
  197716. #if defined(_WIN32_WCE)
  197717. if ( !WriteFile(io_ptr, buf, written, &err, NULL) )
  197718. err = 0;
  197719. #else
  197720. err = fwrite(buf, 1, written, io_ptr);
  197721. #endif
  197722. if (err != written)
  197723. break;
  197724. else
  197725. check += err;
  197726. data += written;
  197727. remaining -= written;
  197728. }
  197729. while (remaining != 0);
  197730. }
  197731. if (check != length)
  197732. png_error(png_ptr, "Write Error");
  197733. }
  197734. #endif
  197735. #endif
  197736. /* This function is called to output any data pending writing (normally
  197737. to disk). After png_flush is called, there should be no data pending
  197738. writing in any buffers. */
  197739. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  197740. void /* PRIVATE */
  197741. png_flush(png_structp png_ptr)
  197742. {
  197743. if (png_ptr->output_flush_fn != NULL)
  197744. (*(png_ptr->output_flush_fn))(png_ptr);
  197745. }
  197746. #if !defined(PNG_NO_STDIO)
  197747. void PNGAPI
  197748. png_default_flush(png_structp png_ptr)
  197749. {
  197750. #if !defined(_WIN32_WCE)
  197751. png_FILE_p io_ptr;
  197752. #endif
  197753. if(png_ptr == NULL) return;
  197754. #if !defined(_WIN32_WCE)
  197755. io_ptr = (png_FILE_p)CVT_PTR((png_ptr->io_ptr));
  197756. if (io_ptr != NULL)
  197757. fflush(io_ptr);
  197758. #endif
  197759. }
  197760. #endif
  197761. #endif
  197762. /* This function allows the application to supply new output functions for
  197763. libpng if standard C streams aren't being used.
  197764. This function takes as its arguments:
  197765. png_ptr - pointer to a png output data structure
  197766. io_ptr - pointer to user supplied structure containing info about
  197767. the output functions. May be NULL.
  197768. write_data_fn - pointer to a new output function that takes as its
  197769. arguments a pointer to a png_struct, a pointer to
  197770. data to be written, and a 32-bit unsigned int that is
  197771. the number of bytes to be written. The new write
  197772. function should call png_error(png_ptr, "Error msg")
  197773. to exit and output any fatal error messages.
  197774. flush_data_fn - pointer to a new flush function that takes as its
  197775. arguments a pointer to a png_struct. After a call to
  197776. the flush function, there should be no data in any buffers
  197777. or pending transmission. If the output method doesn't do
  197778. any buffering of ouput, a function prototype must still be
  197779. supplied although it doesn't have to do anything. If
  197780. PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile
  197781. time, output_flush_fn will be ignored, although it must be
  197782. supplied for compatibility. */
  197783. void PNGAPI
  197784. png_set_write_fn(png_structp png_ptr, png_voidp io_ptr,
  197785. png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn)
  197786. {
  197787. if(png_ptr == NULL) return;
  197788. png_ptr->io_ptr = io_ptr;
  197789. #if !defined(PNG_NO_STDIO)
  197790. if (write_data_fn != NULL)
  197791. png_ptr->write_data_fn = write_data_fn;
  197792. else
  197793. png_ptr->write_data_fn = png_default_write_data;
  197794. #else
  197795. png_ptr->write_data_fn = write_data_fn;
  197796. #endif
  197797. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  197798. #if !defined(PNG_NO_STDIO)
  197799. if (output_flush_fn != NULL)
  197800. png_ptr->output_flush_fn = output_flush_fn;
  197801. else
  197802. png_ptr->output_flush_fn = png_default_flush;
  197803. #else
  197804. png_ptr->output_flush_fn = output_flush_fn;
  197805. #endif
  197806. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  197807. /* It is an error to read while writing a png file */
  197808. if (png_ptr->read_data_fn != NULL)
  197809. {
  197810. png_ptr->read_data_fn = NULL;
  197811. png_warning(png_ptr,
  197812. "Attempted to set both read_data_fn and write_data_fn in");
  197813. png_warning(png_ptr,
  197814. "the same structure. Resetting read_data_fn to NULL.");
  197815. }
  197816. }
  197817. #if defined(USE_FAR_KEYWORD)
  197818. #if defined(_MSC_VER)
  197819. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  197820. {
  197821. void *near_ptr;
  197822. void FAR *far_ptr;
  197823. FP_OFF(near_ptr) = FP_OFF(ptr);
  197824. far_ptr = (void FAR *)near_ptr;
  197825. if(check != 0)
  197826. if(FP_SEG(ptr) != FP_SEG(far_ptr))
  197827. png_error(png_ptr,"segment lost in conversion");
  197828. return(near_ptr);
  197829. }
  197830. # else
  197831. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  197832. {
  197833. void *near_ptr;
  197834. void FAR *far_ptr;
  197835. near_ptr = (void FAR *)ptr;
  197836. far_ptr = (void FAR *)near_ptr;
  197837. if(check != 0)
  197838. if(far_ptr != ptr)
  197839. png_error(png_ptr,"segment lost in conversion");
  197840. return(near_ptr);
  197841. }
  197842. # endif
  197843. # endif
  197844. #endif /* PNG_WRITE_SUPPORTED */
  197845. /*** End of inlined file: pngwio.c ***/
  197846. /*** Start of inlined file: pngwrite.c ***/
  197847. /* pngwrite.c - general routines to write a PNG file
  197848. *
  197849. * Last changed in libpng 1.2.15 January 5, 2007
  197850. * For conditions of distribution and use, see copyright notice in png.h
  197851. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  197852. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  197853. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  197854. */
  197855. /* get internal access to png.h */
  197856. #define PNG_INTERNAL
  197857. #ifdef PNG_WRITE_SUPPORTED
  197858. /* Writes all the PNG information. This is the suggested way to use the
  197859. * library. If you have a new chunk to add, make a function to write it,
  197860. * and put it in the correct location here. If you want the chunk written
  197861. * after the image data, put it in png_write_end(). I strongly encourage
  197862. * you to supply a PNG_INFO_ flag, and check info_ptr->valid before writing
  197863. * the chunk, as that will keep the code from breaking if you want to just
  197864. * write a plain PNG file. If you have long comments, I suggest writing
  197865. * them in png_write_end(), and compressing them.
  197866. */
  197867. void PNGAPI
  197868. png_write_info_before_PLTE(png_structp png_ptr, png_infop info_ptr)
  197869. {
  197870. png_debug(1, "in png_write_info_before_PLTE\n");
  197871. if (png_ptr == NULL || info_ptr == NULL)
  197872. return;
  197873. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  197874. {
  197875. png_write_sig(png_ptr); /* write PNG signature */
  197876. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197877. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&(png_ptr->mng_features_permitted))
  197878. {
  197879. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  197880. png_ptr->mng_features_permitted=0;
  197881. }
  197882. #endif
  197883. /* write IHDR information. */
  197884. png_write_IHDR(png_ptr, info_ptr->width, info_ptr->height,
  197885. info_ptr->bit_depth, info_ptr->color_type, info_ptr->compression_type,
  197886. info_ptr->filter_type,
  197887. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  197888. info_ptr->interlace_type);
  197889. #else
  197890. 0);
  197891. #endif
  197892. /* the rest of these check to see if the valid field has the appropriate
  197893. flag set, and if it does, writes the chunk. */
  197894. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  197895. if (info_ptr->valid & PNG_INFO_gAMA)
  197896. {
  197897. # ifdef PNG_FLOATING_POINT_SUPPORTED
  197898. png_write_gAMA(png_ptr, info_ptr->gamma);
  197899. #else
  197900. #ifdef PNG_FIXED_POINT_SUPPORTED
  197901. png_write_gAMA_fixed(png_ptr, info_ptr->int_gamma);
  197902. # endif
  197903. #endif
  197904. }
  197905. #endif
  197906. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  197907. if (info_ptr->valid & PNG_INFO_sRGB)
  197908. png_write_sRGB(png_ptr, (int)info_ptr->srgb_intent);
  197909. #endif
  197910. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  197911. if (info_ptr->valid & PNG_INFO_iCCP)
  197912. png_write_iCCP(png_ptr, info_ptr->iccp_name, PNG_COMPRESSION_TYPE_BASE,
  197913. info_ptr->iccp_profile, (int)info_ptr->iccp_proflen);
  197914. #endif
  197915. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  197916. if (info_ptr->valid & PNG_INFO_sBIT)
  197917. png_write_sBIT(png_ptr, &(info_ptr->sig_bit), info_ptr->color_type);
  197918. #endif
  197919. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  197920. if (info_ptr->valid & PNG_INFO_cHRM)
  197921. {
  197922. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197923. png_write_cHRM(png_ptr,
  197924. info_ptr->x_white, info_ptr->y_white,
  197925. info_ptr->x_red, info_ptr->y_red,
  197926. info_ptr->x_green, info_ptr->y_green,
  197927. info_ptr->x_blue, info_ptr->y_blue);
  197928. #else
  197929. # ifdef PNG_FIXED_POINT_SUPPORTED
  197930. png_write_cHRM_fixed(png_ptr,
  197931. info_ptr->int_x_white, info_ptr->int_y_white,
  197932. info_ptr->int_x_red, info_ptr->int_y_red,
  197933. info_ptr->int_x_green, info_ptr->int_y_green,
  197934. info_ptr->int_x_blue, info_ptr->int_y_blue);
  197935. # endif
  197936. #endif
  197937. }
  197938. #endif
  197939. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  197940. if (info_ptr->unknown_chunks_num)
  197941. {
  197942. png_unknown_chunk *up;
  197943. png_debug(5, "writing extra chunks\n");
  197944. for (up = info_ptr->unknown_chunks;
  197945. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  197946. up++)
  197947. {
  197948. int keep=png_handle_as_unknown(png_ptr, up->name);
  197949. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  197950. up->location && !(up->location & PNG_HAVE_PLTE) &&
  197951. !(up->location & PNG_HAVE_IDAT) &&
  197952. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  197953. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  197954. {
  197955. png_write_chunk(png_ptr, up->name, up->data, up->size);
  197956. }
  197957. }
  197958. }
  197959. #endif
  197960. png_ptr->mode |= PNG_WROTE_INFO_BEFORE_PLTE;
  197961. }
  197962. }
  197963. void PNGAPI
  197964. png_write_info(png_structp png_ptr, png_infop info_ptr)
  197965. {
  197966. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  197967. int i;
  197968. #endif
  197969. png_debug(1, "in png_write_info\n");
  197970. if (png_ptr == NULL || info_ptr == NULL)
  197971. return;
  197972. png_write_info_before_PLTE(png_ptr, info_ptr);
  197973. if (info_ptr->valid & PNG_INFO_PLTE)
  197974. png_write_PLTE(png_ptr, info_ptr->palette,
  197975. (png_uint_32)info_ptr->num_palette);
  197976. else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  197977. png_error(png_ptr, "Valid palette required for paletted images");
  197978. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  197979. if (info_ptr->valid & PNG_INFO_tRNS)
  197980. {
  197981. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  197982. /* invert the alpha channel (in tRNS) */
  197983. if ((png_ptr->transformations & PNG_INVERT_ALPHA) &&
  197984. info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  197985. {
  197986. int j;
  197987. for (j=0; j<(int)info_ptr->num_trans; j++)
  197988. info_ptr->trans[j] = (png_byte)(255 - info_ptr->trans[j]);
  197989. }
  197990. #endif
  197991. png_write_tRNS(png_ptr, info_ptr->trans, &(info_ptr->trans_values),
  197992. info_ptr->num_trans, info_ptr->color_type);
  197993. }
  197994. #endif
  197995. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  197996. if (info_ptr->valid & PNG_INFO_bKGD)
  197997. png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type);
  197998. #endif
  197999. #if defined(PNG_WRITE_hIST_SUPPORTED)
  198000. if (info_ptr->valid & PNG_INFO_hIST)
  198001. png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette);
  198002. #endif
  198003. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  198004. if (info_ptr->valid & PNG_INFO_oFFs)
  198005. png_write_oFFs(png_ptr, info_ptr->x_offset, info_ptr->y_offset,
  198006. info_ptr->offset_unit_type);
  198007. #endif
  198008. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  198009. if (info_ptr->valid & PNG_INFO_pCAL)
  198010. png_write_pCAL(png_ptr, info_ptr->pcal_purpose, info_ptr->pcal_X0,
  198011. info_ptr->pcal_X1, info_ptr->pcal_type, info_ptr->pcal_nparams,
  198012. info_ptr->pcal_units, info_ptr->pcal_params);
  198013. #endif
  198014. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  198015. if (info_ptr->valid & PNG_INFO_sCAL)
  198016. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  198017. png_write_sCAL(png_ptr, (int)info_ptr->scal_unit,
  198018. info_ptr->scal_pixel_width, info_ptr->scal_pixel_height);
  198019. #else
  198020. #ifdef PNG_FIXED_POINT_SUPPORTED
  198021. png_write_sCAL_s(png_ptr, (int)info_ptr->scal_unit,
  198022. info_ptr->scal_s_width, info_ptr->scal_s_height);
  198023. #else
  198024. png_warning(png_ptr,
  198025. "png_write_sCAL not supported; sCAL chunk not written.");
  198026. #endif
  198027. #endif
  198028. #endif
  198029. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  198030. if (info_ptr->valid & PNG_INFO_pHYs)
  198031. png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit,
  198032. info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type);
  198033. #endif
  198034. #if defined(PNG_WRITE_tIME_SUPPORTED)
  198035. if (info_ptr->valid & PNG_INFO_tIME)
  198036. {
  198037. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  198038. png_ptr->mode |= PNG_WROTE_tIME;
  198039. }
  198040. #endif
  198041. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  198042. if (info_ptr->valid & PNG_INFO_sPLT)
  198043. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  198044. png_write_sPLT(png_ptr, info_ptr->splt_palettes + i);
  198045. #endif
  198046. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  198047. /* Check to see if we need to write text chunks */
  198048. for (i = 0; i < info_ptr->num_text; i++)
  198049. {
  198050. png_debug2(2, "Writing header text chunk %d, type %d\n", i,
  198051. info_ptr->text[i].compression);
  198052. /* an internationalized chunk? */
  198053. if (info_ptr->text[i].compression > 0)
  198054. {
  198055. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  198056. /* write international chunk */
  198057. png_write_iTXt(png_ptr,
  198058. info_ptr->text[i].compression,
  198059. info_ptr->text[i].key,
  198060. info_ptr->text[i].lang,
  198061. info_ptr->text[i].lang_key,
  198062. info_ptr->text[i].text);
  198063. #else
  198064. png_warning(png_ptr, "Unable to write international text");
  198065. #endif
  198066. /* Mark this chunk as written */
  198067. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198068. }
  198069. /* If we want a compressed text chunk */
  198070. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt)
  198071. {
  198072. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  198073. /* write compressed chunk */
  198074. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  198075. info_ptr->text[i].text, 0,
  198076. info_ptr->text[i].compression);
  198077. #else
  198078. png_warning(png_ptr, "Unable to write compressed text");
  198079. #endif
  198080. /* Mark this chunk as written */
  198081. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  198082. }
  198083. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  198084. {
  198085. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  198086. /* write uncompressed chunk */
  198087. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  198088. info_ptr->text[i].text,
  198089. 0);
  198090. #else
  198091. png_warning(png_ptr, "Unable to write uncompressed text");
  198092. #endif
  198093. /* Mark this chunk as written */
  198094. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198095. }
  198096. }
  198097. #endif
  198098. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  198099. if (info_ptr->unknown_chunks_num)
  198100. {
  198101. png_unknown_chunk *up;
  198102. png_debug(5, "writing extra chunks\n");
  198103. for (up = info_ptr->unknown_chunks;
  198104. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  198105. up++)
  198106. {
  198107. int keep=png_handle_as_unknown(png_ptr, up->name);
  198108. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  198109. up->location && (up->location & PNG_HAVE_PLTE) &&
  198110. !(up->location & PNG_HAVE_IDAT) &&
  198111. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  198112. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  198113. {
  198114. png_write_chunk(png_ptr, up->name, up->data, up->size);
  198115. }
  198116. }
  198117. }
  198118. #endif
  198119. }
  198120. /* Writes the end of the PNG file. If you don't want to write comments or
  198121. * time information, you can pass NULL for info. If you already wrote these
  198122. * in png_write_info(), do not write them again here. If you have long
  198123. * comments, I suggest writing them here, and compressing them.
  198124. */
  198125. void PNGAPI
  198126. png_write_end(png_structp png_ptr, png_infop info_ptr)
  198127. {
  198128. png_debug(1, "in png_write_end\n");
  198129. if (png_ptr == NULL)
  198130. return;
  198131. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  198132. png_error(png_ptr, "No IDATs written into file");
  198133. /* see if user wants us to write information chunks */
  198134. if (info_ptr != NULL)
  198135. {
  198136. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  198137. int i; /* local index variable */
  198138. #endif
  198139. #if defined(PNG_WRITE_tIME_SUPPORTED)
  198140. /* check to see if user has supplied a time chunk */
  198141. if ((info_ptr->valid & PNG_INFO_tIME) &&
  198142. !(png_ptr->mode & PNG_WROTE_tIME))
  198143. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  198144. #endif
  198145. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  198146. /* loop through comment chunks */
  198147. for (i = 0; i < info_ptr->num_text; i++)
  198148. {
  198149. png_debug2(2, "Writing trailer text chunk %d, type %d\n", i,
  198150. info_ptr->text[i].compression);
  198151. /* an internationalized chunk? */
  198152. if (info_ptr->text[i].compression > 0)
  198153. {
  198154. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  198155. /* write international chunk */
  198156. png_write_iTXt(png_ptr,
  198157. info_ptr->text[i].compression,
  198158. info_ptr->text[i].key,
  198159. info_ptr->text[i].lang,
  198160. info_ptr->text[i].lang_key,
  198161. info_ptr->text[i].text);
  198162. #else
  198163. png_warning(png_ptr, "Unable to write international text");
  198164. #endif
  198165. /* Mark this chunk as written */
  198166. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198167. }
  198168. else if (info_ptr->text[i].compression >= PNG_TEXT_COMPRESSION_zTXt)
  198169. {
  198170. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  198171. /* write compressed chunk */
  198172. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  198173. info_ptr->text[i].text, 0,
  198174. info_ptr->text[i].compression);
  198175. #else
  198176. png_warning(png_ptr, "Unable to write compressed text");
  198177. #endif
  198178. /* Mark this chunk as written */
  198179. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  198180. }
  198181. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  198182. {
  198183. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  198184. /* write uncompressed chunk */
  198185. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  198186. info_ptr->text[i].text, 0);
  198187. #else
  198188. png_warning(png_ptr, "Unable to write uncompressed text");
  198189. #endif
  198190. /* Mark this chunk as written */
  198191. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198192. }
  198193. }
  198194. #endif
  198195. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  198196. if (info_ptr->unknown_chunks_num)
  198197. {
  198198. png_unknown_chunk *up;
  198199. png_debug(5, "writing extra chunks\n");
  198200. for (up = info_ptr->unknown_chunks;
  198201. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  198202. up++)
  198203. {
  198204. int keep=png_handle_as_unknown(png_ptr, up->name);
  198205. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  198206. up->location && (up->location & PNG_AFTER_IDAT) &&
  198207. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  198208. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  198209. {
  198210. png_write_chunk(png_ptr, up->name, up->data, up->size);
  198211. }
  198212. }
  198213. }
  198214. #endif
  198215. }
  198216. png_ptr->mode |= PNG_AFTER_IDAT;
  198217. /* write end of PNG file */
  198218. png_write_IEND(png_ptr);
  198219. }
  198220. #if defined(PNG_WRITE_tIME_SUPPORTED)
  198221. #if !defined(_WIN32_WCE)
  198222. /* "time.h" functions are not supported on WindowsCE */
  198223. void PNGAPI
  198224. png_convert_from_struct_tm(png_timep ptime, struct tm FAR * ttime)
  198225. {
  198226. png_debug(1, "in png_convert_from_struct_tm\n");
  198227. ptime->year = (png_uint_16)(1900 + ttime->tm_year);
  198228. ptime->month = (png_byte)(ttime->tm_mon + 1);
  198229. ptime->day = (png_byte)ttime->tm_mday;
  198230. ptime->hour = (png_byte)ttime->tm_hour;
  198231. ptime->minute = (png_byte)ttime->tm_min;
  198232. ptime->second = (png_byte)ttime->tm_sec;
  198233. }
  198234. void PNGAPI
  198235. png_convert_from_time_t(png_timep ptime, time_t ttime)
  198236. {
  198237. struct tm *tbuf;
  198238. png_debug(1, "in png_convert_from_time_t\n");
  198239. tbuf = gmtime(&ttime);
  198240. png_convert_from_struct_tm(ptime, tbuf);
  198241. }
  198242. #endif
  198243. #endif
  198244. /* Initialize png_ptr structure, and allocate any memory needed */
  198245. png_structp PNGAPI
  198246. png_create_write_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  198247. png_error_ptr error_fn, png_error_ptr warn_fn)
  198248. {
  198249. #ifdef PNG_USER_MEM_SUPPORTED
  198250. return (png_create_write_struct_2(user_png_ver, error_ptr, error_fn,
  198251. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  198252. }
  198253. /* Alternate initialize png_ptr structure, and allocate any memory needed */
  198254. png_structp PNGAPI
  198255. png_create_write_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  198256. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  198257. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  198258. {
  198259. #endif /* PNG_USER_MEM_SUPPORTED */
  198260. png_structp png_ptr;
  198261. #ifdef PNG_SETJMP_SUPPORTED
  198262. #ifdef USE_FAR_KEYWORD
  198263. jmp_buf jmpbuf;
  198264. #endif
  198265. #endif
  198266. int i;
  198267. png_debug(1, "in png_create_write_struct\n");
  198268. #ifdef PNG_USER_MEM_SUPPORTED
  198269. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  198270. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  198271. #else
  198272. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  198273. #endif /* PNG_USER_MEM_SUPPORTED */
  198274. if (png_ptr == NULL)
  198275. return (NULL);
  198276. /* added at libpng-1.2.6 */
  198277. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  198278. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  198279. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  198280. #endif
  198281. #ifdef PNG_SETJMP_SUPPORTED
  198282. #ifdef USE_FAR_KEYWORD
  198283. if (setjmp(jmpbuf))
  198284. #else
  198285. if (setjmp(png_ptr->jmpbuf))
  198286. #endif
  198287. {
  198288. png_free(png_ptr, png_ptr->zbuf);
  198289. png_ptr->zbuf=NULL;
  198290. png_destroy_struct(png_ptr);
  198291. return (NULL);
  198292. }
  198293. #ifdef USE_FAR_KEYWORD
  198294. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  198295. #endif
  198296. #endif
  198297. #ifdef PNG_USER_MEM_SUPPORTED
  198298. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  198299. #endif /* PNG_USER_MEM_SUPPORTED */
  198300. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  198301. i=0;
  198302. do
  198303. {
  198304. if(user_png_ver[i] != png_libpng_ver[i])
  198305. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  198306. } while (png_libpng_ver[i++]);
  198307. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  198308. {
  198309. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  198310. * we must recompile any applications that use any older library version.
  198311. * For versions after libpng 1.0, we will be compatible, so we need
  198312. * only check the first digit.
  198313. */
  198314. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  198315. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  198316. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  198317. {
  198318. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  198319. char msg[80];
  198320. if (user_png_ver)
  198321. {
  198322. png_snprintf(msg, 80,
  198323. "Application was compiled with png.h from libpng-%.20s",
  198324. user_png_ver);
  198325. png_warning(png_ptr, msg);
  198326. }
  198327. png_snprintf(msg, 80,
  198328. "Application is running with png.c from libpng-%.20s",
  198329. png_libpng_ver);
  198330. png_warning(png_ptr, msg);
  198331. #endif
  198332. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  198333. png_ptr->flags=0;
  198334. #endif
  198335. png_error(png_ptr,
  198336. "Incompatible libpng version in application and library");
  198337. }
  198338. }
  198339. /* initialize zbuf - compression buffer */
  198340. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  198341. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  198342. (png_uint_32)png_ptr->zbuf_size);
  198343. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  198344. png_flush_ptr_NULL);
  198345. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198346. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  198347. 1, png_doublep_NULL, png_doublep_NULL);
  198348. #endif
  198349. #ifdef PNG_SETJMP_SUPPORTED
  198350. /* Applications that neglect to set up their own setjmp() and then encounter
  198351. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  198352. abort instead of returning. */
  198353. #ifdef USE_FAR_KEYWORD
  198354. if (setjmp(jmpbuf))
  198355. PNG_ABORT();
  198356. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  198357. #else
  198358. if (setjmp(png_ptr->jmpbuf))
  198359. PNG_ABORT();
  198360. #endif
  198361. #endif
  198362. return (png_ptr);
  198363. }
  198364. /* Initialize png_ptr structure, and allocate any memory needed */
  198365. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  198366. /* Deprecated. */
  198367. #undef png_write_init
  198368. void PNGAPI
  198369. png_write_init(png_structp png_ptr)
  198370. {
  198371. /* We only come here via pre-1.0.7-compiled applications */
  198372. png_write_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  198373. }
  198374. void PNGAPI
  198375. png_write_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  198376. png_size_t png_struct_size, png_size_t png_info_size)
  198377. {
  198378. /* We only come here via pre-1.0.12-compiled applications */
  198379. if(png_ptr == NULL) return;
  198380. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  198381. if(png_sizeof(png_struct) > png_struct_size ||
  198382. png_sizeof(png_info) > png_info_size)
  198383. {
  198384. char msg[80];
  198385. png_ptr->warning_fn=NULL;
  198386. if (user_png_ver)
  198387. {
  198388. png_snprintf(msg, 80,
  198389. "Application was compiled with png.h from libpng-%.20s",
  198390. user_png_ver);
  198391. png_warning(png_ptr, msg);
  198392. }
  198393. png_snprintf(msg, 80,
  198394. "Application is running with png.c from libpng-%.20s",
  198395. png_libpng_ver);
  198396. png_warning(png_ptr, msg);
  198397. }
  198398. #endif
  198399. if(png_sizeof(png_struct) > png_struct_size)
  198400. {
  198401. png_ptr->error_fn=NULL;
  198402. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  198403. png_ptr->flags=0;
  198404. #endif
  198405. png_error(png_ptr,
  198406. "The png struct allocated by the application for writing is too small.");
  198407. }
  198408. if(png_sizeof(png_info) > png_info_size)
  198409. {
  198410. png_ptr->error_fn=NULL;
  198411. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  198412. png_ptr->flags=0;
  198413. #endif
  198414. png_error(png_ptr,
  198415. "The info struct allocated by the application for writing is too small.");
  198416. }
  198417. png_write_init_3(&png_ptr, user_png_ver, png_struct_size);
  198418. }
  198419. #endif /* PNG_1_0_X || PNG_1_2_X */
  198420. void PNGAPI
  198421. png_write_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  198422. png_size_t png_struct_size)
  198423. {
  198424. png_structp png_ptr=*ptr_ptr;
  198425. #ifdef PNG_SETJMP_SUPPORTED
  198426. jmp_buf tmp_jmp; /* to save current jump buffer */
  198427. #endif
  198428. int i = 0;
  198429. if (png_ptr == NULL)
  198430. return;
  198431. do
  198432. {
  198433. if (user_png_ver[i] != png_libpng_ver[i])
  198434. {
  198435. #ifdef PNG_LEGACY_SUPPORTED
  198436. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  198437. #else
  198438. png_ptr->warning_fn=NULL;
  198439. png_warning(png_ptr,
  198440. "Application uses deprecated png_write_init() and should be recompiled.");
  198441. break;
  198442. #endif
  198443. }
  198444. } while (png_libpng_ver[i++]);
  198445. png_debug(1, "in png_write_init_3\n");
  198446. #ifdef PNG_SETJMP_SUPPORTED
  198447. /* save jump buffer and error functions */
  198448. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  198449. #endif
  198450. if (png_sizeof(png_struct) > png_struct_size)
  198451. {
  198452. png_destroy_struct(png_ptr);
  198453. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  198454. *ptr_ptr = png_ptr;
  198455. }
  198456. /* reset all variables to 0 */
  198457. png_memset(png_ptr, 0, png_sizeof (png_struct));
  198458. /* added at libpng-1.2.6 */
  198459. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  198460. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  198461. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  198462. #endif
  198463. #ifdef PNG_SETJMP_SUPPORTED
  198464. /* restore jump buffer */
  198465. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  198466. #endif
  198467. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  198468. png_flush_ptr_NULL);
  198469. /* initialize zbuf - compression buffer */
  198470. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  198471. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  198472. (png_uint_32)png_ptr->zbuf_size);
  198473. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198474. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  198475. 1, png_doublep_NULL, png_doublep_NULL);
  198476. #endif
  198477. }
  198478. /* Write a few rows of image data. If the image is interlaced,
  198479. * either you will have to write the 7 sub images, or, if you
  198480. * have called png_set_interlace_handling(), you will have to
  198481. * "write" the image seven times.
  198482. */
  198483. void PNGAPI
  198484. png_write_rows(png_structp png_ptr, png_bytepp row,
  198485. png_uint_32 num_rows)
  198486. {
  198487. png_uint_32 i; /* row counter */
  198488. png_bytepp rp; /* row pointer */
  198489. png_debug(1, "in png_write_rows\n");
  198490. if (png_ptr == NULL)
  198491. return;
  198492. /* loop through the rows */
  198493. for (i = 0, rp = row; i < num_rows; i++, rp++)
  198494. {
  198495. png_write_row(png_ptr, *rp);
  198496. }
  198497. }
  198498. /* Write the image. You only need to call this function once, even
  198499. * if you are writing an interlaced image.
  198500. */
  198501. void PNGAPI
  198502. png_write_image(png_structp png_ptr, png_bytepp image)
  198503. {
  198504. png_uint_32 i; /* row index */
  198505. int pass, num_pass; /* pass variables */
  198506. png_bytepp rp; /* points to current row */
  198507. if (png_ptr == NULL)
  198508. return;
  198509. png_debug(1, "in png_write_image\n");
  198510. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198511. /* intialize interlace handling. If image is not interlaced,
  198512. this will set pass to 1 */
  198513. num_pass = png_set_interlace_handling(png_ptr);
  198514. #else
  198515. num_pass = 1;
  198516. #endif
  198517. /* loop through passes */
  198518. for (pass = 0; pass < num_pass; pass++)
  198519. {
  198520. /* loop through image */
  198521. for (i = 0, rp = image; i < png_ptr->height; i++, rp++)
  198522. {
  198523. png_write_row(png_ptr, *rp);
  198524. }
  198525. }
  198526. }
  198527. /* called by user to write a row of image data */
  198528. void PNGAPI
  198529. png_write_row(png_structp png_ptr, png_bytep row)
  198530. {
  198531. if (png_ptr == NULL)
  198532. return;
  198533. png_debug2(1, "in png_write_row (row %ld, pass %d)\n",
  198534. png_ptr->row_number, png_ptr->pass);
  198535. /* initialize transformations and other stuff if first time */
  198536. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  198537. {
  198538. /* make sure we wrote the header info */
  198539. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  198540. png_error(png_ptr,
  198541. "png_write_info was never called before png_write_row.");
  198542. /* check for transforms that have been set but were defined out */
  198543. #if !defined(PNG_WRITE_INVERT_SUPPORTED) && defined(PNG_READ_INVERT_SUPPORTED)
  198544. if (png_ptr->transformations & PNG_INVERT_MONO)
  198545. png_warning(png_ptr, "PNG_WRITE_INVERT_SUPPORTED is not defined.");
  198546. #endif
  198547. #if !defined(PNG_WRITE_FILLER_SUPPORTED) && defined(PNG_READ_FILLER_SUPPORTED)
  198548. if (png_ptr->transformations & PNG_FILLER)
  198549. png_warning(png_ptr, "PNG_WRITE_FILLER_SUPPORTED is not defined.");
  198550. #endif
  198551. #if !defined(PNG_WRITE_PACKSWAP_SUPPORTED) && defined(PNG_READ_PACKSWAP_SUPPORTED)
  198552. if (png_ptr->transformations & PNG_PACKSWAP)
  198553. png_warning(png_ptr, "PNG_WRITE_PACKSWAP_SUPPORTED is not defined.");
  198554. #endif
  198555. #if !defined(PNG_WRITE_PACK_SUPPORTED) && defined(PNG_READ_PACK_SUPPORTED)
  198556. if (png_ptr->transformations & PNG_PACK)
  198557. png_warning(png_ptr, "PNG_WRITE_PACK_SUPPORTED is not defined.");
  198558. #endif
  198559. #if !defined(PNG_WRITE_SHIFT_SUPPORTED) && defined(PNG_READ_SHIFT_SUPPORTED)
  198560. if (png_ptr->transformations & PNG_SHIFT)
  198561. png_warning(png_ptr, "PNG_WRITE_SHIFT_SUPPORTED is not defined.");
  198562. #endif
  198563. #if !defined(PNG_WRITE_BGR_SUPPORTED) && defined(PNG_READ_BGR_SUPPORTED)
  198564. if (png_ptr->transformations & PNG_BGR)
  198565. png_warning(png_ptr, "PNG_WRITE_BGR_SUPPORTED is not defined.");
  198566. #endif
  198567. #if !defined(PNG_WRITE_SWAP_SUPPORTED) && defined(PNG_READ_SWAP_SUPPORTED)
  198568. if (png_ptr->transformations & PNG_SWAP_BYTES)
  198569. png_warning(png_ptr, "PNG_WRITE_SWAP_SUPPORTED is not defined.");
  198570. #endif
  198571. png_write_start_row(png_ptr);
  198572. }
  198573. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198574. /* if interlaced and not interested in row, return */
  198575. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  198576. {
  198577. switch (png_ptr->pass)
  198578. {
  198579. case 0:
  198580. if (png_ptr->row_number & 0x07)
  198581. {
  198582. png_write_finish_row(png_ptr);
  198583. return;
  198584. }
  198585. break;
  198586. case 1:
  198587. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  198588. {
  198589. png_write_finish_row(png_ptr);
  198590. return;
  198591. }
  198592. break;
  198593. case 2:
  198594. if ((png_ptr->row_number & 0x07) != 4)
  198595. {
  198596. png_write_finish_row(png_ptr);
  198597. return;
  198598. }
  198599. break;
  198600. case 3:
  198601. if ((png_ptr->row_number & 0x03) || png_ptr->width < 3)
  198602. {
  198603. png_write_finish_row(png_ptr);
  198604. return;
  198605. }
  198606. break;
  198607. case 4:
  198608. if ((png_ptr->row_number & 0x03) != 2)
  198609. {
  198610. png_write_finish_row(png_ptr);
  198611. return;
  198612. }
  198613. break;
  198614. case 5:
  198615. if ((png_ptr->row_number & 0x01) || png_ptr->width < 2)
  198616. {
  198617. png_write_finish_row(png_ptr);
  198618. return;
  198619. }
  198620. break;
  198621. case 6:
  198622. if (!(png_ptr->row_number & 0x01))
  198623. {
  198624. png_write_finish_row(png_ptr);
  198625. return;
  198626. }
  198627. break;
  198628. }
  198629. }
  198630. #endif
  198631. /* set up row info for transformations */
  198632. png_ptr->row_info.color_type = png_ptr->color_type;
  198633. png_ptr->row_info.width = png_ptr->usr_width;
  198634. png_ptr->row_info.channels = png_ptr->usr_channels;
  198635. png_ptr->row_info.bit_depth = png_ptr->usr_bit_depth;
  198636. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  198637. png_ptr->row_info.channels);
  198638. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  198639. png_ptr->row_info.width);
  198640. png_debug1(3, "row_info->color_type = %d\n", png_ptr->row_info.color_type);
  198641. png_debug1(3, "row_info->width = %lu\n", png_ptr->row_info.width);
  198642. png_debug1(3, "row_info->channels = %d\n", png_ptr->row_info.channels);
  198643. png_debug1(3, "row_info->bit_depth = %d\n", png_ptr->row_info.bit_depth);
  198644. png_debug1(3, "row_info->pixel_depth = %d\n", png_ptr->row_info.pixel_depth);
  198645. png_debug1(3, "row_info->rowbytes = %lu\n", png_ptr->row_info.rowbytes);
  198646. /* Copy user's row into buffer, leaving room for filter byte. */
  198647. png_memcpy_check(png_ptr, png_ptr->row_buf + 1, row,
  198648. png_ptr->row_info.rowbytes);
  198649. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198650. /* handle interlacing */
  198651. if (png_ptr->interlaced && png_ptr->pass < 6 &&
  198652. (png_ptr->transformations & PNG_INTERLACE))
  198653. {
  198654. png_do_write_interlace(&(png_ptr->row_info),
  198655. png_ptr->row_buf + 1, png_ptr->pass);
  198656. /* this should always get caught above, but still ... */
  198657. if (!(png_ptr->row_info.width))
  198658. {
  198659. png_write_finish_row(png_ptr);
  198660. return;
  198661. }
  198662. }
  198663. #endif
  198664. /* handle other transformations */
  198665. if (png_ptr->transformations)
  198666. png_do_write_transformations(png_ptr);
  198667. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  198668. /* Write filter_method 64 (intrapixel differencing) only if
  198669. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  198670. * 2. Libpng did not write a PNG signature (this filter_method is only
  198671. * used in PNG datastreams that are embedded in MNG datastreams) and
  198672. * 3. The application called png_permit_mng_features with a mask that
  198673. * included PNG_FLAG_MNG_FILTER_64 and
  198674. * 4. The filter_method is 64 and
  198675. * 5. The color_type is RGB or RGBA
  198676. */
  198677. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  198678. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  198679. {
  198680. /* Intrapixel differencing */
  198681. png_do_write_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  198682. }
  198683. #endif
  198684. /* Find a filter if necessary, filter the row and write it out. */
  198685. png_write_find_filter(png_ptr, &(png_ptr->row_info));
  198686. if (png_ptr->write_row_fn != NULL)
  198687. (*(png_ptr->write_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  198688. }
  198689. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198690. /* Set the automatic flush interval or 0 to turn flushing off */
  198691. void PNGAPI
  198692. png_set_flush(png_structp png_ptr, int nrows)
  198693. {
  198694. png_debug(1, "in png_set_flush\n");
  198695. if (png_ptr == NULL)
  198696. return;
  198697. png_ptr->flush_dist = (nrows < 0 ? 0 : nrows);
  198698. }
  198699. /* flush the current output buffers now */
  198700. void PNGAPI
  198701. png_write_flush(png_structp png_ptr)
  198702. {
  198703. int wrote_IDAT;
  198704. png_debug(1, "in png_write_flush\n");
  198705. if (png_ptr == NULL)
  198706. return;
  198707. /* We have already written out all of the data */
  198708. if (png_ptr->row_number >= png_ptr->num_rows)
  198709. return;
  198710. do
  198711. {
  198712. int ret;
  198713. /* compress the data */
  198714. ret = deflate(&png_ptr->zstream, Z_SYNC_FLUSH);
  198715. wrote_IDAT = 0;
  198716. /* check for compression errors */
  198717. if (ret != Z_OK)
  198718. {
  198719. if (png_ptr->zstream.msg != NULL)
  198720. png_error(png_ptr, png_ptr->zstream.msg);
  198721. else
  198722. png_error(png_ptr, "zlib error");
  198723. }
  198724. if (!(png_ptr->zstream.avail_out))
  198725. {
  198726. /* write the IDAT and reset the zlib output buffer */
  198727. png_write_IDAT(png_ptr, png_ptr->zbuf,
  198728. png_ptr->zbuf_size);
  198729. png_ptr->zstream.next_out = png_ptr->zbuf;
  198730. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  198731. wrote_IDAT = 1;
  198732. }
  198733. } while(wrote_IDAT == 1);
  198734. /* If there is any data left to be output, write it into a new IDAT */
  198735. if (png_ptr->zbuf_size != png_ptr->zstream.avail_out)
  198736. {
  198737. /* write the IDAT and reset the zlib output buffer */
  198738. png_write_IDAT(png_ptr, png_ptr->zbuf,
  198739. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  198740. png_ptr->zstream.next_out = png_ptr->zbuf;
  198741. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  198742. }
  198743. png_ptr->flush_rows = 0;
  198744. png_flush(png_ptr);
  198745. }
  198746. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  198747. /* free all memory used by the write */
  198748. void PNGAPI
  198749. png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr)
  198750. {
  198751. png_structp png_ptr = NULL;
  198752. png_infop info_ptr = NULL;
  198753. #ifdef PNG_USER_MEM_SUPPORTED
  198754. png_free_ptr free_fn = NULL;
  198755. png_voidp mem_ptr = NULL;
  198756. #endif
  198757. png_debug(1, "in png_destroy_write_struct\n");
  198758. if (png_ptr_ptr != NULL)
  198759. {
  198760. png_ptr = *png_ptr_ptr;
  198761. #ifdef PNG_USER_MEM_SUPPORTED
  198762. free_fn = png_ptr->free_fn;
  198763. mem_ptr = png_ptr->mem_ptr;
  198764. #endif
  198765. }
  198766. if (info_ptr_ptr != NULL)
  198767. info_ptr = *info_ptr_ptr;
  198768. if (info_ptr != NULL)
  198769. {
  198770. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  198771. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  198772. if (png_ptr->num_chunk_list)
  198773. {
  198774. png_free(png_ptr, png_ptr->chunk_list);
  198775. png_ptr->chunk_list=NULL;
  198776. png_ptr->num_chunk_list=0;
  198777. }
  198778. #endif
  198779. #ifdef PNG_USER_MEM_SUPPORTED
  198780. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  198781. (png_voidp)mem_ptr);
  198782. #else
  198783. png_destroy_struct((png_voidp)info_ptr);
  198784. #endif
  198785. *info_ptr_ptr = NULL;
  198786. }
  198787. if (png_ptr != NULL)
  198788. {
  198789. png_write_destroy(png_ptr);
  198790. #ifdef PNG_USER_MEM_SUPPORTED
  198791. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  198792. (png_voidp)mem_ptr);
  198793. #else
  198794. png_destroy_struct((png_voidp)png_ptr);
  198795. #endif
  198796. *png_ptr_ptr = NULL;
  198797. }
  198798. }
  198799. /* Free any memory used in png_ptr struct (old method) */
  198800. void /* PRIVATE */
  198801. png_write_destroy(png_structp png_ptr)
  198802. {
  198803. #ifdef PNG_SETJMP_SUPPORTED
  198804. jmp_buf tmp_jmp; /* save jump buffer */
  198805. #endif
  198806. png_error_ptr error_fn;
  198807. png_error_ptr warning_fn;
  198808. png_voidp error_ptr;
  198809. #ifdef PNG_USER_MEM_SUPPORTED
  198810. png_free_ptr free_fn;
  198811. #endif
  198812. png_debug(1, "in png_write_destroy\n");
  198813. /* free any memory zlib uses */
  198814. deflateEnd(&png_ptr->zstream);
  198815. /* free our memory. png_free checks NULL for us. */
  198816. png_free(png_ptr, png_ptr->zbuf);
  198817. png_free(png_ptr, png_ptr->row_buf);
  198818. png_free(png_ptr, png_ptr->prev_row);
  198819. png_free(png_ptr, png_ptr->sub_row);
  198820. png_free(png_ptr, png_ptr->up_row);
  198821. png_free(png_ptr, png_ptr->avg_row);
  198822. png_free(png_ptr, png_ptr->paeth_row);
  198823. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  198824. png_free(png_ptr, png_ptr->time_buffer);
  198825. #endif
  198826. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198827. png_free(png_ptr, png_ptr->prev_filters);
  198828. png_free(png_ptr, png_ptr->filter_weights);
  198829. png_free(png_ptr, png_ptr->inv_filter_weights);
  198830. png_free(png_ptr, png_ptr->filter_costs);
  198831. png_free(png_ptr, png_ptr->inv_filter_costs);
  198832. #endif
  198833. #ifdef PNG_SETJMP_SUPPORTED
  198834. /* reset structure */
  198835. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  198836. #endif
  198837. error_fn = png_ptr->error_fn;
  198838. warning_fn = png_ptr->warning_fn;
  198839. error_ptr = png_ptr->error_ptr;
  198840. #ifdef PNG_USER_MEM_SUPPORTED
  198841. free_fn = png_ptr->free_fn;
  198842. #endif
  198843. png_memset(png_ptr, 0, png_sizeof (png_struct));
  198844. png_ptr->error_fn = error_fn;
  198845. png_ptr->warning_fn = warning_fn;
  198846. png_ptr->error_ptr = error_ptr;
  198847. #ifdef PNG_USER_MEM_SUPPORTED
  198848. png_ptr->free_fn = free_fn;
  198849. #endif
  198850. #ifdef PNG_SETJMP_SUPPORTED
  198851. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  198852. #endif
  198853. }
  198854. /* Allow the application to select one or more row filters to use. */
  198855. void PNGAPI
  198856. png_set_filter(png_structp png_ptr, int method, int filters)
  198857. {
  198858. png_debug(1, "in png_set_filter\n");
  198859. if (png_ptr == NULL)
  198860. return;
  198861. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  198862. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  198863. (method == PNG_INTRAPIXEL_DIFFERENCING))
  198864. method = PNG_FILTER_TYPE_BASE;
  198865. #endif
  198866. if (method == PNG_FILTER_TYPE_BASE)
  198867. {
  198868. switch (filters & (PNG_ALL_FILTERS | 0x07))
  198869. {
  198870. #ifndef PNG_NO_WRITE_FILTER
  198871. case 5:
  198872. case 6:
  198873. case 7: png_warning(png_ptr, "Unknown row filter for method 0");
  198874. #endif /* PNG_NO_WRITE_FILTER */
  198875. case PNG_FILTER_VALUE_NONE:
  198876. png_ptr->do_filter=PNG_FILTER_NONE; break;
  198877. #ifndef PNG_NO_WRITE_FILTER
  198878. case PNG_FILTER_VALUE_SUB:
  198879. png_ptr->do_filter=PNG_FILTER_SUB; break;
  198880. case PNG_FILTER_VALUE_UP:
  198881. png_ptr->do_filter=PNG_FILTER_UP; break;
  198882. case PNG_FILTER_VALUE_AVG:
  198883. png_ptr->do_filter=PNG_FILTER_AVG; break;
  198884. case PNG_FILTER_VALUE_PAETH:
  198885. png_ptr->do_filter=PNG_FILTER_PAETH; break;
  198886. default: png_ptr->do_filter = (png_byte)filters; break;
  198887. #else
  198888. default: png_warning(png_ptr, "Unknown row filter for method 0");
  198889. #endif /* PNG_NO_WRITE_FILTER */
  198890. }
  198891. /* If we have allocated the row_buf, this means we have already started
  198892. * with the image and we should have allocated all of the filter buffers
  198893. * that have been selected. If prev_row isn't already allocated, then
  198894. * it is too late to start using the filters that need it, since we
  198895. * will be missing the data in the previous row. If an application
  198896. * wants to start and stop using particular filters during compression,
  198897. * it should start out with all of the filters, and then add and
  198898. * remove them after the start of compression.
  198899. */
  198900. if (png_ptr->row_buf != NULL)
  198901. {
  198902. #ifndef PNG_NO_WRITE_FILTER
  198903. if ((png_ptr->do_filter & PNG_FILTER_SUB) && png_ptr->sub_row == NULL)
  198904. {
  198905. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  198906. (png_ptr->rowbytes + 1));
  198907. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  198908. }
  198909. if ((png_ptr->do_filter & PNG_FILTER_UP) && png_ptr->up_row == NULL)
  198910. {
  198911. if (png_ptr->prev_row == NULL)
  198912. {
  198913. png_warning(png_ptr, "Can't add Up filter after starting");
  198914. png_ptr->do_filter &= ~PNG_FILTER_UP;
  198915. }
  198916. else
  198917. {
  198918. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  198919. (png_ptr->rowbytes + 1));
  198920. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  198921. }
  198922. }
  198923. if ((png_ptr->do_filter & PNG_FILTER_AVG) && png_ptr->avg_row == NULL)
  198924. {
  198925. if (png_ptr->prev_row == NULL)
  198926. {
  198927. png_warning(png_ptr, "Can't add Average filter after starting");
  198928. png_ptr->do_filter &= ~PNG_FILTER_AVG;
  198929. }
  198930. else
  198931. {
  198932. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  198933. (png_ptr->rowbytes + 1));
  198934. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  198935. }
  198936. }
  198937. if ((png_ptr->do_filter & PNG_FILTER_PAETH) &&
  198938. png_ptr->paeth_row == NULL)
  198939. {
  198940. if (png_ptr->prev_row == NULL)
  198941. {
  198942. png_warning(png_ptr, "Can't add Paeth filter after starting");
  198943. png_ptr->do_filter &= (png_byte)(~PNG_FILTER_PAETH);
  198944. }
  198945. else
  198946. {
  198947. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  198948. (png_ptr->rowbytes + 1));
  198949. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  198950. }
  198951. }
  198952. if (png_ptr->do_filter == PNG_NO_FILTERS)
  198953. #endif /* PNG_NO_WRITE_FILTER */
  198954. png_ptr->do_filter = PNG_FILTER_NONE;
  198955. }
  198956. }
  198957. else
  198958. png_error(png_ptr, "Unknown custom filter method");
  198959. }
  198960. /* This allows us to influence the way in which libpng chooses the "best"
  198961. * filter for the current scanline. While the "minimum-sum-of-absolute-
  198962. * differences metric is relatively fast and effective, there is some
  198963. * question as to whether it can be improved upon by trying to keep the
  198964. * filtered data going to zlib more consistent, hopefully resulting in
  198965. * better compression.
  198966. */
  198967. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* GRR 970116 */
  198968. void PNGAPI
  198969. png_set_filter_heuristics(png_structp png_ptr, int heuristic_method,
  198970. int num_weights, png_doublep filter_weights,
  198971. png_doublep filter_costs)
  198972. {
  198973. int i;
  198974. png_debug(1, "in png_set_filter_heuristics\n");
  198975. if (png_ptr == NULL)
  198976. return;
  198977. if (heuristic_method >= PNG_FILTER_HEURISTIC_LAST)
  198978. {
  198979. png_warning(png_ptr, "Unknown filter heuristic method");
  198980. return;
  198981. }
  198982. if (heuristic_method == PNG_FILTER_HEURISTIC_DEFAULT)
  198983. {
  198984. heuristic_method = PNG_FILTER_HEURISTIC_UNWEIGHTED;
  198985. }
  198986. if (num_weights < 0 || filter_weights == NULL ||
  198987. heuristic_method == PNG_FILTER_HEURISTIC_UNWEIGHTED)
  198988. {
  198989. num_weights = 0;
  198990. }
  198991. png_ptr->num_prev_filters = (png_byte)num_weights;
  198992. png_ptr->heuristic_method = (png_byte)heuristic_method;
  198993. if (num_weights > 0)
  198994. {
  198995. if (png_ptr->prev_filters == NULL)
  198996. {
  198997. png_ptr->prev_filters = (png_bytep)png_malloc(png_ptr,
  198998. (png_uint_32)(png_sizeof(png_byte) * num_weights));
  198999. /* To make sure that the weighting starts out fairly */
  199000. for (i = 0; i < num_weights; i++)
  199001. {
  199002. png_ptr->prev_filters[i] = 255;
  199003. }
  199004. }
  199005. if (png_ptr->filter_weights == NULL)
  199006. {
  199007. png_ptr->filter_weights = (png_uint_16p)png_malloc(png_ptr,
  199008. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  199009. png_ptr->inv_filter_weights = (png_uint_16p)png_malloc(png_ptr,
  199010. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  199011. for (i = 0; i < num_weights; i++)
  199012. {
  199013. png_ptr->inv_filter_weights[i] =
  199014. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  199015. }
  199016. }
  199017. for (i = 0; i < num_weights; i++)
  199018. {
  199019. if (filter_weights[i] < 0.0)
  199020. {
  199021. png_ptr->inv_filter_weights[i] =
  199022. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  199023. }
  199024. else
  199025. {
  199026. png_ptr->inv_filter_weights[i] =
  199027. (png_uint_16)((double)PNG_WEIGHT_FACTOR*filter_weights[i]+0.5);
  199028. png_ptr->filter_weights[i] =
  199029. (png_uint_16)((double)PNG_WEIGHT_FACTOR/filter_weights[i]+0.5);
  199030. }
  199031. }
  199032. }
  199033. /* If, in the future, there are other filter methods, this would
  199034. * need to be based on png_ptr->filter.
  199035. */
  199036. if (png_ptr->filter_costs == NULL)
  199037. {
  199038. png_ptr->filter_costs = (png_uint_16p)png_malloc(png_ptr,
  199039. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  199040. png_ptr->inv_filter_costs = (png_uint_16p)png_malloc(png_ptr,
  199041. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  199042. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  199043. {
  199044. png_ptr->inv_filter_costs[i] =
  199045. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  199046. }
  199047. }
  199048. /* Here is where we set the relative costs of the different filters. We
  199049. * should take the desired compression level into account when setting
  199050. * the costs, so that Paeth, for instance, has a high relative cost at low
  199051. * compression levels, while it has a lower relative cost at higher
  199052. * compression settings. The filter types are in order of increasing
  199053. * relative cost, so it would be possible to do this with an algorithm.
  199054. */
  199055. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  199056. {
  199057. if (filter_costs == NULL || filter_costs[i] < 0.0)
  199058. {
  199059. png_ptr->inv_filter_costs[i] =
  199060. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  199061. }
  199062. else if (filter_costs[i] >= 1.0)
  199063. {
  199064. png_ptr->inv_filter_costs[i] =
  199065. (png_uint_16)((double)PNG_COST_FACTOR / filter_costs[i] + 0.5);
  199066. png_ptr->filter_costs[i] =
  199067. (png_uint_16)((double)PNG_COST_FACTOR * filter_costs[i] + 0.5);
  199068. }
  199069. }
  199070. }
  199071. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  199072. void PNGAPI
  199073. png_set_compression_level(png_structp png_ptr, int level)
  199074. {
  199075. png_debug(1, "in png_set_compression_level\n");
  199076. if (png_ptr == NULL)
  199077. return;
  199078. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_LEVEL;
  199079. png_ptr->zlib_level = level;
  199080. }
  199081. void PNGAPI
  199082. png_set_compression_mem_level(png_structp png_ptr, int mem_level)
  199083. {
  199084. png_debug(1, "in png_set_compression_mem_level\n");
  199085. if (png_ptr == NULL)
  199086. return;
  199087. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL;
  199088. png_ptr->zlib_mem_level = mem_level;
  199089. }
  199090. void PNGAPI
  199091. png_set_compression_strategy(png_structp png_ptr, int strategy)
  199092. {
  199093. png_debug(1, "in png_set_compression_strategy\n");
  199094. if (png_ptr == NULL)
  199095. return;
  199096. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_STRATEGY;
  199097. png_ptr->zlib_strategy = strategy;
  199098. }
  199099. void PNGAPI
  199100. png_set_compression_window_bits(png_structp png_ptr, int window_bits)
  199101. {
  199102. if (png_ptr == NULL)
  199103. return;
  199104. if (window_bits > 15)
  199105. png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
  199106. else if (window_bits < 8)
  199107. png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
  199108. #ifndef WBITS_8_OK
  199109. /* avoid libpng bug with 256-byte windows */
  199110. if (window_bits == 8)
  199111. {
  199112. png_warning(png_ptr, "Compression window is being reset to 512");
  199113. window_bits=9;
  199114. }
  199115. #endif
  199116. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS;
  199117. png_ptr->zlib_window_bits = window_bits;
  199118. }
  199119. void PNGAPI
  199120. png_set_compression_method(png_structp png_ptr, int method)
  199121. {
  199122. png_debug(1, "in png_set_compression_method\n");
  199123. if (png_ptr == NULL)
  199124. return;
  199125. if (method != 8)
  199126. png_warning(png_ptr, "Only compression method 8 is supported by PNG");
  199127. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_METHOD;
  199128. png_ptr->zlib_method = method;
  199129. }
  199130. void PNGAPI
  199131. png_set_write_status_fn(png_structp png_ptr, png_write_status_ptr write_row_fn)
  199132. {
  199133. if (png_ptr == NULL)
  199134. return;
  199135. png_ptr->write_row_fn = write_row_fn;
  199136. }
  199137. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  199138. void PNGAPI
  199139. png_set_write_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  199140. write_user_transform_fn)
  199141. {
  199142. png_debug(1, "in png_set_write_user_transform_fn\n");
  199143. if (png_ptr == NULL)
  199144. return;
  199145. png_ptr->transformations |= PNG_USER_TRANSFORM;
  199146. png_ptr->write_user_transform_fn = write_user_transform_fn;
  199147. }
  199148. #endif
  199149. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  199150. void PNGAPI
  199151. png_write_png(png_structp png_ptr, png_infop info_ptr,
  199152. int transforms, voidp params)
  199153. {
  199154. if (png_ptr == NULL || info_ptr == NULL)
  199155. return;
  199156. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  199157. /* invert the alpha channel from opacity to transparency */
  199158. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  199159. png_set_invert_alpha(png_ptr);
  199160. #endif
  199161. /* Write the file header information. */
  199162. png_write_info(png_ptr, info_ptr);
  199163. /* ------ these transformations don't touch the info structure ------- */
  199164. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  199165. /* invert monochrome pixels */
  199166. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  199167. png_set_invert_mono(png_ptr);
  199168. #endif
  199169. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  199170. /* Shift the pixels up to a legal bit depth and fill in
  199171. * as appropriate to correctly scale the image.
  199172. */
  199173. if ((transforms & PNG_TRANSFORM_SHIFT)
  199174. && (info_ptr->valid & PNG_INFO_sBIT))
  199175. png_set_shift(png_ptr, &info_ptr->sig_bit);
  199176. #endif
  199177. #if defined(PNG_WRITE_PACK_SUPPORTED)
  199178. /* pack pixels into bytes */
  199179. if (transforms & PNG_TRANSFORM_PACKING)
  199180. png_set_packing(png_ptr);
  199181. #endif
  199182. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  199183. /* swap location of alpha bytes from ARGB to RGBA */
  199184. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  199185. png_set_swap_alpha(png_ptr);
  199186. #endif
  199187. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  199188. /* Get rid of filler (OR ALPHA) bytes, pack XRGB/RGBX/ARGB/RGBA into
  199189. * RGB (4 channels -> 3 channels). The second parameter is not used.
  199190. */
  199191. if (transforms & PNG_TRANSFORM_STRIP_FILLER)
  199192. png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
  199193. #endif
  199194. #if defined(PNG_WRITE_BGR_SUPPORTED)
  199195. /* flip BGR pixels to RGB */
  199196. if (transforms & PNG_TRANSFORM_BGR)
  199197. png_set_bgr(png_ptr);
  199198. #endif
  199199. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  199200. /* swap bytes of 16-bit files to most significant byte first */
  199201. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  199202. png_set_swap(png_ptr);
  199203. #endif
  199204. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  199205. /* swap bits of 1, 2, 4 bit packed pixel formats */
  199206. if (transforms & PNG_TRANSFORM_PACKSWAP)
  199207. png_set_packswap(png_ptr);
  199208. #endif
  199209. /* ----------------------- end of transformations ------------------- */
  199210. /* write the bits */
  199211. if (info_ptr->valid & PNG_INFO_IDAT)
  199212. png_write_image(png_ptr, info_ptr->row_pointers);
  199213. /* It is REQUIRED to call this to finish writing the rest of the file */
  199214. png_write_end(png_ptr, info_ptr);
  199215. transforms = transforms; /* quiet compiler warnings */
  199216. params = params;
  199217. }
  199218. #endif
  199219. #endif /* PNG_WRITE_SUPPORTED */
  199220. /*** End of inlined file: pngwrite.c ***/
  199221. /*** Start of inlined file: pngwtran.c ***/
  199222. /* pngwtran.c - transforms the data in a row for PNG writers
  199223. *
  199224. * Last changed in libpng 1.2.9 April 14, 2006
  199225. * For conditions of distribution and use, see copyright notice in png.h
  199226. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  199227. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  199228. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  199229. */
  199230. #define PNG_INTERNAL
  199231. #ifdef PNG_WRITE_SUPPORTED
  199232. /* Transform the data according to the user's wishes. The order of
  199233. * transformations is significant.
  199234. */
  199235. void /* PRIVATE */
  199236. png_do_write_transformations(png_structp png_ptr)
  199237. {
  199238. png_debug(1, "in png_do_write_transformations\n");
  199239. if (png_ptr == NULL)
  199240. return;
  199241. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  199242. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  199243. if(png_ptr->write_user_transform_fn != NULL)
  199244. (*(png_ptr->write_user_transform_fn)) /* user write transform function */
  199245. (png_ptr, /* png_ptr */
  199246. &(png_ptr->row_info), /* row_info: */
  199247. /* png_uint_32 width; width of row */
  199248. /* png_uint_32 rowbytes; number of bytes in row */
  199249. /* png_byte color_type; color type of pixels */
  199250. /* png_byte bit_depth; bit depth of samples */
  199251. /* png_byte channels; number of channels (1-4) */
  199252. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  199253. png_ptr->row_buf + 1); /* start of pixel data for row */
  199254. #endif
  199255. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  199256. if (png_ptr->transformations & PNG_FILLER)
  199257. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  199258. png_ptr->flags);
  199259. #endif
  199260. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  199261. if (png_ptr->transformations & PNG_PACKSWAP)
  199262. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199263. #endif
  199264. #if defined(PNG_WRITE_PACK_SUPPORTED)
  199265. if (png_ptr->transformations & PNG_PACK)
  199266. png_do_pack(&(png_ptr->row_info), png_ptr->row_buf + 1,
  199267. (png_uint_32)png_ptr->bit_depth);
  199268. #endif
  199269. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  199270. if (png_ptr->transformations & PNG_SWAP_BYTES)
  199271. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199272. #endif
  199273. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  199274. if (png_ptr->transformations & PNG_SHIFT)
  199275. png_do_shift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  199276. &(png_ptr->shift));
  199277. #endif
  199278. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  199279. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  199280. png_do_write_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199281. #endif
  199282. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  199283. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  199284. png_do_write_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199285. #endif
  199286. #if defined(PNG_WRITE_BGR_SUPPORTED)
  199287. if (png_ptr->transformations & PNG_BGR)
  199288. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199289. #endif
  199290. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  199291. if (png_ptr->transformations & PNG_INVERT_MONO)
  199292. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199293. #endif
  199294. }
  199295. #if defined(PNG_WRITE_PACK_SUPPORTED)
  199296. /* Pack pixels into bytes. Pass the true bit depth in bit_depth. The
  199297. * row_info bit depth should be 8 (one pixel per byte). The channels
  199298. * should be 1 (this only happens on grayscale and paletted images).
  199299. */
  199300. void /* PRIVATE */
  199301. png_do_pack(png_row_infop row_info, png_bytep row, png_uint_32 bit_depth)
  199302. {
  199303. png_debug(1, "in png_do_pack\n");
  199304. if (row_info->bit_depth == 8 &&
  199305. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  199306. row != NULL && row_info != NULL &&
  199307. #endif
  199308. row_info->channels == 1)
  199309. {
  199310. switch ((int)bit_depth)
  199311. {
  199312. case 1:
  199313. {
  199314. png_bytep sp, dp;
  199315. int mask, v;
  199316. png_uint_32 i;
  199317. png_uint_32 row_width = row_info->width;
  199318. sp = row;
  199319. dp = row;
  199320. mask = 0x80;
  199321. v = 0;
  199322. for (i = 0; i < row_width; i++)
  199323. {
  199324. if (*sp != 0)
  199325. v |= mask;
  199326. sp++;
  199327. if (mask > 1)
  199328. mask >>= 1;
  199329. else
  199330. {
  199331. mask = 0x80;
  199332. *dp = (png_byte)v;
  199333. dp++;
  199334. v = 0;
  199335. }
  199336. }
  199337. if (mask != 0x80)
  199338. *dp = (png_byte)v;
  199339. break;
  199340. }
  199341. case 2:
  199342. {
  199343. png_bytep sp, dp;
  199344. int shift, v;
  199345. png_uint_32 i;
  199346. png_uint_32 row_width = row_info->width;
  199347. sp = row;
  199348. dp = row;
  199349. shift = 6;
  199350. v = 0;
  199351. for (i = 0; i < row_width; i++)
  199352. {
  199353. png_byte value;
  199354. value = (png_byte)(*sp & 0x03);
  199355. v |= (value << shift);
  199356. if (shift == 0)
  199357. {
  199358. shift = 6;
  199359. *dp = (png_byte)v;
  199360. dp++;
  199361. v = 0;
  199362. }
  199363. else
  199364. shift -= 2;
  199365. sp++;
  199366. }
  199367. if (shift != 6)
  199368. *dp = (png_byte)v;
  199369. break;
  199370. }
  199371. case 4:
  199372. {
  199373. png_bytep sp, dp;
  199374. int shift, v;
  199375. png_uint_32 i;
  199376. png_uint_32 row_width = row_info->width;
  199377. sp = row;
  199378. dp = row;
  199379. shift = 4;
  199380. v = 0;
  199381. for (i = 0; i < row_width; i++)
  199382. {
  199383. png_byte value;
  199384. value = (png_byte)(*sp & 0x0f);
  199385. v |= (value << shift);
  199386. if (shift == 0)
  199387. {
  199388. shift = 4;
  199389. *dp = (png_byte)v;
  199390. dp++;
  199391. v = 0;
  199392. }
  199393. else
  199394. shift -= 4;
  199395. sp++;
  199396. }
  199397. if (shift != 4)
  199398. *dp = (png_byte)v;
  199399. break;
  199400. }
  199401. }
  199402. row_info->bit_depth = (png_byte)bit_depth;
  199403. row_info->pixel_depth = (png_byte)(bit_depth * row_info->channels);
  199404. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  199405. row_info->width);
  199406. }
  199407. }
  199408. #endif
  199409. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  199410. /* Shift pixel values to take advantage of whole range. Pass the
  199411. * true number of bits in bit_depth. The row should be packed
  199412. * according to row_info->bit_depth. Thus, if you had a row of
  199413. * bit depth 4, but the pixels only had values from 0 to 7, you
  199414. * would pass 3 as bit_depth, and this routine would translate the
  199415. * data to 0 to 15.
  199416. */
  199417. void /* PRIVATE */
  199418. png_do_shift(png_row_infop row_info, png_bytep row, png_color_8p bit_depth)
  199419. {
  199420. png_debug(1, "in png_do_shift\n");
  199421. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  199422. if (row != NULL && row_info != NULL &&
  199423. #else
  199424. if (
  199425. #endif
  199426. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  199427. {
  199428. int shift_start[4], shift_dec[4];
  199429. int channels = 0;
  199430. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  199431. {
  199432. shift_start[channels] = row_info->bit_depth - bit_depth->red;
  199433. shift_dec[channels] = bit_depth->red;
  199434. channels++;
  199435. shift_start[channels] = row_info->bit_depth - bit_depth->green;
  199436. shift_dec[channels] = bit_depth->green;
  199437. channels++;
  199438. shift_start[channels] = row_info->bit_depth - bit_depth->blue;
  199439. shift_dec[channels] = bit_depth->blue;
  199440. channels++;
  199441. }
  199442. else
  199443. {
  199444. shift_start[channels] = row_info->bit_depth - bit_depth->gray;
  199445. shift_dec[channels] = bit_depth->gray;
  199446. channels++;
  199447. }
  199448. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  199449. {
  199450. shift_start[channels] = row_info->bit_depth - bit_depth->alpha;
  199451. shift_dec[channels] = bit_depth->alpha;
  199452. channels++;
  199453. }
  199454. /* with low row depths, could only be grayscale, so one channel */
  199455. if (row_info->bit_depth < 8)
  199456. {
  199457. png_bytep bp = row;
  199458. png_uint_32 i;
  199459. png_byte mask;
  199460. png_uint_32 row_bytes = row_info->rowbytes;
  199461. if (bit_depth->gray == 1 && row_info->bit_depth == 2)
  199462. mask = 0x55;
  199463. else if (row_info->bit_depth == 4 && bit_depth->gray == 3)
  199464. mask = 0x11;
  199465. else
  199466. mask = 0xff;
  199467. for (i = 0; i < row_bytes; i++, bp++)
  199468. {
  199469. png_uint_16 v;
  199470. int j;
  199471. v = *bp;
  199472. *bp = 0;
  199473. for (j = shift_start[0]; j > -shift_dec[0]; j -= shift_dec[0])
  199474. {
  199475. if (j > 0)
  199476. *bp |= (png_byte)((v << j) & 0xff);
  199477. else
  199478. *bp |= (png_byte)((v >> (-j)) & mask);
  199479. }
  199480. }
  199481. }
  199482. else if (row_info->bit_depth == 8)
  199483. {
  199484. png_bytep bp = row;
  199485. png_uint_32 i;
  199486. png_uint_32 istop = channels * row_info->width;
  199487. for (i = 0; i < istop; i++, bp++)
  199488. {
  199489. png_uint_16 v;
  199490. int j;
  199491. int c = (int)(i%channels);
  199492. v = *bp;
  199493. *bp = 0;
  199494. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  199495. {
  199496. if (j > 0)
  199497. *bp |= (png_byte)((v << j) & 0xff);
  199498. else
  199499. *bp |= (png_byte)((v >> (-j)) & 0xff);
  199500. }
  199501. }
  199502. }
  199503. else
  199504. {
  199505. png_bytep bp;
  199506. png_uint_32 i;
  199507. png_uint_32 istop = channels * row_info->width;
  199508. for (bp = row, i = 0; i < istop; i++)
  199509. {
  199510. int c = (int)(i%channels);
  199511. png_uint_16 value, v;
  199512. int j;
  199513. v = (png_uint_16)(((png_uint_16)(*bp) << 8) + *(bp + 1));
  199514. value = 0;
  199515. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  199516. {
  199517. if (j > 0)
  199518. value |= (png_uint_16)((v << j) & (png_uint_16)0xffff);
  199519. else
  199520. value |= (png_uint_16)((v >> (-j)) & (png_uint_16)0xffff);
  199521. }
  199522. *bp++ = (png_byte)(value >> 8);
  199523. *bp++ = (png_byte)(value & 0xff);
  199524. }
  199525. }
  199526. }
  199527. }
  199528. #endif
  199529. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  199530. void /* PRIVATE */
  199531. png_do_write_swap_alpha(png_row_infop row_info, png_bytep row)
  199532. {
  199533. png_debug(1, "in png_do_write_swap_alpha\n");
  199534. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  199535. if (row != NULL && row_info != NULL)
  199536. #endif
  199537. {
  199538. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  199539. {
  199540. /* This converts from ARGB to RGBA */
  199541. if (row_info->bit_depth == 8)
  199542. {
  199543. png_bytep sp, dp;
  199544. png_uint_32 i;
  199545. png_uint_32 row_width = row_info->width;
  199546. for (i = 0, sp = dp = row; i < row_width; i++)
  199547. {
  199548. png_byte save = *(sp++);
  199549. *(dp++) = *(sp++);
  199550. *(dp++) = *(sp++);
  199551. *(dp++) = *(sp++);
  199552. *(dp++) = save;
  199553. }
  199554. }
  199555. /* This converts from AARRGGBB to RRGGBBAA */
  199556. else
  199557. {
  199558. png_bytep sp, dp;
  199559. png_uint_32 i;
  199560. png_uint_32 row_width = row_info->width;
  199561. for (i = 0, sp = dp = row; i < row_width; i++)
  199562. {
  199563. png_byte save[2];
  199564. save[0] = *(sp++);
  199565. save[1] = *(sp++);
  199566. *(dp++) = *(sp++);
  199567. *(dp++) = *(sp++);
  199568. *(dp++) = *(sp++);
  199569. *(dp++) = *(sp++);
  199570. *(dp++) = *(sp++);
  199571. *(dp++) = *(sp++);
  199572. *(dp++) = save[0];
  199573. *(dp++) = save[1];
  199574. }
  199575. }
  199576. }
  199577. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  199578. {
  199579. /* This converts from AG to GA */
  199580. if (row_info->bit_depth == 8)
  199581. {
  199582. png_bytep sp, dp;
  199583. png_uint_32 i;
  199584. png_uint_32 row_width = row_info->width;
  199585. for (i = 0, sp = dp = row; i < row_width; i++)
  199586. {
  199587. png_byte save = *(sp++);
  199588. *(dp++) = *(sp++);
  199589. *(dp++) = save;
  199590. }
  199591. }
  199592. /* This converts from AAGG to GGAA */
  199593. else
  199594. {
  199595. png_bytep sp, dp;
  199596. png_uint_32 i;
  199597. png_uint_32 row_width = row_info->width;
  199598. for (i = 0, sp = dp = row; i < row_width; i++)
  199599. {
  199600. png_byte save[2];
  199601. save[0] = *(sp++);
  199602. save[1] = *(sp++);
  199603. *(dp++) = *(sp++);
  199604. *(dp++) = *(sp++);
  199605. *(dp++) = save[0];
  199606. *(dp++) = save[1];
  199607. }
  199608. }
  199609. }
  199610. }
  199611. }
  199612. #endif
  199613. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  199614. void /* PRIVATE */
  199615. png_do_write_invert_alpha(png_row_infop row_info, png_bytep row)
  199616. {
  199617. png_debug(1, "in png_do_write_invert_alpha\n");
  199618. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  199619. if (row != NULL && row_info != NULL)
  199620. #endif
  199621. {
  199622. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  199623. {
  199624. /* This inverts the alpha channel in RGBA */
  199625. if (row_info->bit_depth == 8)
  199626. {
  199627. png_bytep sp, dp;
  199628. png_uint_32 i;
  199629. png_uint_32 row_width = row_info->width;
  199630. for (i = 0, sp = dp = row; i < row_width; i++)
  199631. {
  199632. /* does nothing
  199633. *(dp++) = *(sp++);
  199634. *(dp++) = *(sp++);
  199635. *(dp++) = *(sp++);
  199636. */
  199637. sp+=3; dp = sp;
  199638. *(dp++) = (png_byte)(255 - *(sp++));
  199639. }
  199640. }
  199641. /* This inverts the alpha channel in RRGGBBAA */
  199642. else
  199643. {
  199644. png_bytep sp, dp;
  199645. png_uint_32 i;
  199646. png_uint_32 row_width = row_info->width;
  199647. for (i = 0, sp = dp = row; i < row_width; i++)
  199648. {
  199649. /* does nothing
  199650. *(dp++) = *(sp++);
  199651. *(dp++) = *(sp++);
  199652. *(dp++) = *(sp++);
  199653. *(dp++) = *(sp++);
  199654. *(dp++) = *(sp++);
  199655. *(dp++) = *(sp++);
  199656. */
  199657. sp+=6; dp = sp;
  199658. *(dp++) = (png_byte)(255 - *(sp++));
  199659. *(dp++) = (png_byte)(255 - *(sp++));
  199660. }
  199661. }
  199662. }
  199663. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  199664. {
  199665. /* This inverts the alpha channel in GA */
  199666. if (row_info->bit_depth == 8)
  199667. {
  199668. png_bytep sp, dp;
  199669. png_uint_32 i;
  199670. png_uint_32 row_width = row_info->width;
  199671. for (i = 0, sp = dp = row; i < row_width; i++)
  199672. {
  199673. *(dp++) = *(sp++);
  199674. *(dp++) = (png_byte)(255 - *(sp++));
  199675. }
  199676. }
  199677. /* This inverts the alpha channel in GGAA */
  199678. else
  199679. {
  199680. png_bytep sp, dp;
  199681. png_uint_32 i;
  199682. png_uint_32 row_width = row_info->width;
  199683. for (i = 0, sp = dp = row; i < row_width; i++)
  199684. {
  199685. /* does nothing
  199686. *(dp++) = *(sp++);
  199687. *(dp++) = *(sp++);
  199688. */
  199689. sp+=2; dp = sp;
  199690. *(dp++) = (png_byte)(255 - *(sp++));
  199691. *(dp++) = (png_byte)(255 - *(sp++));
  199692. }
  199693. }
  199694. }
  199695. }
  199696. }
  199697. #endif
  199698. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199699. /* undoes intrapixel differencing */
  199700. void /* PRIVATE */
  199701. png_do_write_intrapixel(png_row_infop row_info, png_bytep row)
  199702. {
  199703. png_debug(1, "in png_do_write_intrapixel\n");
  199704. if (
  199705. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  199706. row != NULL && row_info != NULL &&
  199707. #endif
  199708. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  199709. {
  199710. int bytes_per_pixel;
  199711. png_uint_32 row_width = row_info->width;
  199712. if (row_info->bit_depth == 8)
  199713. {
  199714. png_bytep rp;
  199715. png_uint_32 i;
  199716. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  199717. bytes_per_pixel = 3;
  199718. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  199719. bytes_per_pixel = 4;
  199720. else
  199721. return;
  199722. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  199723. {
  199724. *(rp) = (png_byte)((*rp - *(rp+1))&0xff);
  199725. *(rp+2) = (png_byte)((*(rp+2) - *(rp+1))&0xff);
  199726. }
  199727. }
  199728. else if (row_info->bit_depth == 16)
  199729. {
  199730. png_bytep rp;
  199731. png_uint_32 i;
  199732. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  199733. bytes_per_pixel = 6;
  199734. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  199735. bytes_per_pixel = 8;
  199736. else
  199737. return;
  199738. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  199739. {
  199740. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  199741. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  199742. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  199743. png_uint_32 red = (png_uint_32)((s0-s1) & 0xffffL);
  199744. png_uint_32 blue = (png_uint_32)((s2-s1) & 0xffffL);
  199745. *(rp ) = (png_byte)((red >> 8) & 0xff);
  199746. *(rp+1) = (png_byte)(red & 0xff);
  199747. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  199748. *(rp+5) = (png_byte)(blue & 0xff);
  199749. }
  199750. }
  199751. }
  199752. }
  199753. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  199754. #endif /* PNG_WRITE_SUPPORTED */
  199755. /*** End of inlined file: pngwtran.c ***/
  199756. /*** Start of inlined file: pngwutil.c ***/
  199757. /* pngwutil.c - utilities to write a PNG file
  199758. *
  199759. * Last changed in libpng 1.2.20 Septhember 3, 2007
  199760. * For conditions of distribution and use, see copyright notice in png.h
  199761. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  199762. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  199763. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  199764. */
  199765. #define PNG_INTERNAL
  199766. #ifdef PNG_WRITE_SUPPORTED
  199767. /* Place a 32-bit number into a buffer in PNG byte order. We work
  199768. * with unsigned numbers for convenience, although one supported
  199769. * ancillary chunk uses signed (two's complement) numbers.
  199770. */
  199771. void PNGAPI
  199772. png_save_uint_32(png_bytep buf, png_uint_32 i)
  199773. {
  199774. buf[0] = (png_byte)((i >> 24) & 0xff);
  199775. buf[1] = (png_byte)((i >> 16) & 0xff);
  199776. buf[2] = (png_byte)((i >> 8) & 0xff);
  199777. buf[3] = (png_byte)(i & 0xff);
  199778. }
  199779. /* The png_save_int_32 function assumes integers are stored in two's
  199780. * complement format. If this isn't the case, then this routine needs to
  199781. * be modified to write data in two's complement format.
  199782. */
  199783. void PNGAPI
  199784. png_save_int_32(png_bytep buf, png_int_32 i)
  199785. {
  199786. buf[0] = (png_byte)((i >> 24) & 0xff);
  199787. buf[1] = (png_byte)((i >> 16) & 0xff);
  199788. buf[2] = (png_byte)((i >> 8) & 0xff);
  199789. buf[3] = (png_byte)(i & 0xff);
  199790. }
  199791. /* Place a 16-bit number into a buffer in PNG byte order.
  199792. * The parameter is declared unsigned int, not png_uint_16,
  199793. * just to avoid potential problems on pre-ANSI C compilers.
  199794. */
  199795. void PNGAPI
  199796. png_save_uint_16(png_bytep buf, unsigned int i)
  199797. {
  199798. buf[0] = (png_byte)((i >> 8) & 0xff);
  199799. buf[1] = (png_byte)(i & 0xff);
  199800. }
  199801. /* Write a PNG chunk all at once. The type is an array of ASCII characters
  199802. * representing the chunk name. The array must be at least 4 bytes in
  199803. * length, and does not need to be null terminated. To be safe, pass the
  199804. * pre-defined chunk names here, and if you need a new one, define it
  199805. * where the others are defined. The length is the length of the data.
  199806. * All the data must be present. If that is not possible, use the
  199807. * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end()
  199808. * functions instead.
  199809. */
  199810. void PNGAPI
  199811. png_write_chunk(png_structp png_ptr, png_bytep chunk_name,
  199812. png_bytep data, png_size_t length)
  199813. {
  199814. if(png_ptr == NULL) return;
  199815. png_write_chunk_start(png_ptr, chunk_name, (png_uint_32)length);
  199816. png_write_chunk_data(png_ptr, data, length);
  199817. png_write_chunk_end(png_ptr);
  199818. }
  199819. /* Write the start of a PNG chunk. The type is the chunk type.
  199820. * The total_length is the sum of the lengths of all the data you will be
  199821. * passing in png_write_chunk_data().
  199822. */
  199823. void PNGAPI
  199824. png_write_chunk_start(png_structp png_ptr, png_bytep chunk_name,
  199825. png_uint_32 length)
  199826. {
  199827. png_byte buf[4];
  199828. png_debug2(0, "Writing %s chunk (%lu bytes)\n", chunk_name, length);
  199829. if(png_ptr == NULL) return;
  199830. /* write the length */
  199831. png_save_uint_32(buf, length);
  199832. png_write_data(png_ptr, buf, (png_size_t)4);
  199833. /* write the chunk name */
  199834. png_write_data(png_ptr, chunk_name, (png_size_t)4);
  199835. /* reset the crc and run it over the chunk name */
  199836. png_reset_crc(png_ptr);
  199837. png_calculate_crc(png_ptr, chunk_name, (png_size_t)4);
  199838. }
  199839. /* Write the data of a PNG chunk started with png_write_chunk_start().
  199840. * Note that multiple calls to this function are allowed, and that the
  199841. * sum of the lengths from these calls *must* add up to the total_length
  199842. * given to png_write_chunk_start().
  199843. */
  199844. void PNGAPI
  199845. png_write_chunk_data(png_structp png_ptr, png_bytep data, png_size_t length)
  199846. {
  199847. /* write the data, and run the CRC over it */
  199848. if(png_ptr == NULL) return;
  199849. if (data != NULL && length > 0)
  199850. {
  199851. png_calculate_crc(png_ptr, data, length);
  199852. png_write_data(png_ptr, data, length);
  199853. }
  199854. }
  199855. /* Finish a chunk started with png_write_chunk_start(). */
  199856. void PNGAPI
  199857. png_write_chunk_end(png_structp png_ptr)
  199858. {
  199859. png_byte buf[4];
  199860. if(png_ptr == NULL) return;
  199861. /* write the crc */
  199862. png_save_uint_32(buf, png_ptr->crc);
  199863. png_write_data(png_ptr, buf, (png_size_t)4);
  199864. }
  199865. /* Simple function to write the signature. If we have already written
  199866. * the magic bytes of the signature, or more likely, the PNG stream is
  199867. * being embedded into another stream and doesn't need its own signature,
  199868. * we should call png_set_sig_bytes() to tell libpng how many of the
  199869. * bytes have already been written.
  199870. */
  199871. void /* PRIVATE */
  199872. png_write_sig(png_structp png_ptr)
  199873. {
  199874. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  199875. /* write the rest of the 8 byte signature */
  199876. png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],
  199877. (png_size_t)8 - png_ptr->sig_bytes);
  199878. if(png_ptr->sig_bytes < 3)
  199879. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  199880. }
  199881. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_iCCP_SUPPORTED)
  199882. /*
  199883. * This pair of functions encapsulates the operation of (a) compressing a
  199884. * text string, and (b) issuing it later as a series of chunk data writes.
  199885. * The compression_state structure is shared context for these functions
  199886. * set up by the caller in order to make the whole mess thread-safe.
  199887. */
  199888. typedef struct
  199889. {
  199890. char *input; /* the uncompressed input data */
  199891. int input_len; /* its length */
  199892. int num_output_ptr; /* number of output pointers used */
  199893. int max_output_ptr; /* size of output_ptr */
  199894. png_charpp output_ptr; /* array of pointers to output */
  199895. } compression_state;
  199896. /* compress given text into storage in the png_ptr structure */
  199897. static int /* PRIVATE */
  199898. png_text_compress(png_structp png_ptr,
  199899. png_charp text, png_size_t text_len, int compression,
  199900. compression_state *comp)
  199901. {
  199902. int ret;
  199903. comp->num_output_ptr = 0;
  199904. comp->max_output_ptr = 0;
  199905. comp->output_ptr = NULL;
  199906. comp->input = NULL;
  199907. comp->input_len = 0;
  199908. /* we may just want to pass the text right through */
  199909. if (compression == PNG_TEXT_COMPRESSION_NONE)
  199910. {
  199911. comp->input = text;
  199912. comp->input_len = text_len;
  199913. return((int)text_len);
  199914. }
  199915. if (compression >= PNG_TEXT_COMPRESSION_LAST)
  199916. {
  199917. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  199918. char msg[50];
  199919. png_snprintf(msg, 50, "Unknown compression type %d", compression);
  199920. png_warning(png_ptr, msg);
  199921. #else
  199922. png_warning(png_ptr, "Unknown compression type");
  199923. #endif
  199924. }
  199925. /* We can't write the chunk until we find out how much data we have,
  199926. * which means we need to run the compressor first and save the
  199927. * output. This shouldn't be a problem, as the vast majority of
  199928. * comments should be reasonable, but we will set up an array of
  199929. * malloc'd pointers to be sure.
  199930. *
  199931. * If we knew the application was well behaved, we could simplify this
  199932. * greatly by assuming we can always malloc an output buffer large
  199933. * enough to hold the compressed text ((1001 * text_len / 1000) + 12)
  199934. * and malloc this directly. The only time this would be a bad idea is
  199935. * if we can't malloc more than 64K and we have 64K of random input
  199936. * data, or if the input string is incredibly large (although this
  199937. * wouldn't cause a failure, just a slowdown due to swapping).
  199938. */
  199939. /* set up the compression buffers */
  199940. png_ptr->zstream.avail_in = (uInt)text_len;
  199941. png_ptr->zstream.next_in = (Bytef *)text;
  199942. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199943. png_ptr->zstream.next_out = (Bytef *)png_ptr->zbuf;
  199944. /* this is the same compression loop as in png_write_row() */
  199945. do
  199946. {
  199947. /* compress the data */
  199948. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  199949. if (ret != Z_OK)
  199950. {
  199951. /* error */
  199952. if (png_ptr->zstream.msg != NULL)
  199953. png_error(png_ptr, png_ptr->zstream.msg);
  199954. else
  199955. png_error(png_ptr, "zlib error");
  199956. }
  199957. /* check to see if we need more room */
  199958. if (!(png_ptr->zstream.avail_out))
  199959. {
  199960. /* make sure the output array has room */
  199961. if (comp->num_output_ptr >= comp->max_output_ptr)
  199962. {
  199963. int old_max;
  199964. old_max = comp->max_output_ptr;
  199965. comp->max_output_ptr = comp->num_output_ptr + 4;
  199966. if (comp->output_ptr != NULL)
  199967. {
  199968. png_charpp old_ptr;
  199969. old_ptr = comp->output_ptr;
  199970. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  199971. (png_uint_32)(comp->max_output_ptr *
  199972. png_sizeof (png_charpp)));
  199973. png_memcpy(comp->output_ptr, old_ptr, old_max
  199974. * png_sizeof (png_charp));
  199975. png_free(png_ptr, old_ptr);
  199976. }
  199977. else
  199978. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  199979. (png_uint_32)(comp->max_output_ptr *
  199980. png_sizeof (png_charp)));
  199981. }
  199982. /* save the data */
  199983. comp->output_ptr[comp->num_output_ptr] = (png_charp)png_malloc(png_ptr,
  199984. (png_uint_32)png_ptr->zbuf_size);
  199985. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  199986. png_ptr->zbuf_size);
  199987. comp->num_output_ptr++;
  199988. /* and reset the buffer */
  199989. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199990. png_ptr->zstream.next_out = png_ptr->zbuf;
  199991. }
  199992. /* continue until we don't have any more to compress */
  199993. } while (png_ptr->zstream.avail_in);
  199994. /* finish the compression */
  199995. do
  199996. {
  199997. /* tell zlib we are finished */
  199998. ret = deflate(&png_ptr->zstream, Z_FINISH);
  199999. if (ret == Z_OK)
  200000. {
  200001. /* check to see if we need more room */
  200002. if (!(png_ptr->zstream.avail_out))
  200003. {
  200004. /* check to make sure our output array has room */
  200005. if (comp->num_output_ptr >= comp->max_output_ptr)
  200006. {
  200007. int old_max;
  200008. old_max = comp->max_output_ptr;
  200009. comp->max_output_ptr = comp->num_output_ptr + 4;
  200010. if (comp->output_ptr != NULL)
  200011. {
  200012. png_charpp old_ptr;
  200013. old_ptr = comp->output_ptr;
  200014. /* This could be optimized to realloc() */
  200015. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200016. (png_uint_32)(comp->max_output_ptr *
  200017. png_sizeof (png_charpp)));
  200018. png_memcpy(comp->output_ptr, old_ptr,
  200019. old_max * png_sizeof (png_charp));
  200020. png_free(png_ptr, old_ptr);
  200021. }
  200022. else
  200023. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200024. (png_uint_32)(comp->max_output_ptr *
  200025. png_sizeof (png_charp)));
  200026. }
  200027. /* save off the data */
  200028. comp->output_ptr[comp->num_output_ptr] =
  200029. (png_charp)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size);
  200030. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  200031. png_ptr->zbuf_size);
  200032. comp->num_output_ptr++;
  200033. /* and reset the buffer pointers */
  200034. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200035. png_ptr->zstream.next_out = png_ptr->zbuf;
  200036. }
  200037. }
  200038. else if (ret != Z_STREAM_END)
  200039. {
  200040. /* we got an error */
  200041. if (png_ptr->zstream.msg != NULL)
  200042. png_error(png_ptr, png_ptr->zstream.msg);
  200043. else
  200044. png_error(png_ptr, "zlib error");
  200045. }
  200046. } while (ret != Z_STREAM_END);
  200047. /* text length is number of buffers plus last buffer */
  200048. text_len = png_ptr->zbuf_size * comp->num_output_ptr;
  200049. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  200050. text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;
  200051. return((int)text_len);
  200052. }
  200053. /* ship the compressed text out via chunk writes */
  200054. static void /* PRIVATE */
  200055. png_write_compressed_data_out(png_structp png_ptr, compression_state *comp)
  200056. {
  200057. int i;
  200058. /* handle the no-compression case */
  200059. if (comp->input)
  200060. {
  200061. png_write_chunk_data(png_ptr, (png_bytep)comp->input,
  200062. (png_size_t)comp->input_len);
  200063. return;
  200064. }
  200065. /* write saved output buffers, if any */
  200066. for (i = 0; i < comp->num_output_ptr; i++)
  200067. {
  200068. png_write_chunk_data(png_ptr,(png_bytep)comp->output_ptr[i],
  200069. png_ptr->zbuf_size);
  200070. png_free(png_ptr, comp->output_ptr[i]);
  200071. comp->output_ptr[i]=NULL;
  200072. }
  200073. if (comp->max_output_ptr != 0)
  200074. png_free(png_ptr, comp->output_ptr);
  200075. comp->output_ptr=NULL;
  200076. /* write anything left in zbuf */
  200077. if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size)
  200078. png_write_chunk_data(png_ptr, png_ptr->zbuf,
  200079. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  200080. /* reset zlib for another zTXt/iTXt or image data */
  200081. deflateReset(&png_ptr->zstream);
  200082. png_ptr->zstream.data_type = Z_BINARY;
  200083. }
  200084. #endif
  200085. /* Write the IHDR chunk, and update the png_struct with the necessary
  200086. * information. Note that the rest of this code depends upon this
  200087. * information being correct.
  200088. */
  200089. void /* PRIVATE */
  200090. png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height,
  200091. int bit_depth, int color_type, int compression_type, int filter_type,
  200092. int interlace_type)
  200093. {
  200094. #ifdef PNG_USE_LOCAL_ARRAYS
  200095. PNG_IHDR;
  200096. #endif
  200097. png_byte buf[13]; /* buffer to store the IHDR info */
  200098. png_debug(1, "in png_write_IHDR\n");
  200099. /* Check that we have valid input data from the application info */
  200100. switch (color_type)
  200101. {
  200102. case PNG_COLOR_TYPE_GRAY:
  200103. switch (bit_depth)
  200104. {
  200105. case 1:
  200106. case 2:
  200107. case 4:
  200108. case 8:
  200109. case 16: png_ptr->channels = 1; break;
  200110. default: png_error(png_ptr,"Invalid bit depth for grayscale image");
  200111. }
  200112. break;
  200113. case PNG_COLOR_TYPE_RGB:
  200114. if (bit_depth != 8 && bit_depth != 16)
  200115. png_error(png_ptr, "Invalid bit depth for RGB image");
  200116. png_ptr->channels = 3;
  200117. break;
  200118. case PNG_COLOR_TYPE_PALETTE:
  200119. switch (bit_depth)
  200120. {
  200121. case 1:
  200122. case 2:
  200123. case 4:
  200124. case 8: png_ptr->channels = 1; break;
  200125. default: png_error(png_ptr, "Invalid bit depth for paletted image");
  200126. }
  200127. break;
  200128. case PNG_COLOR_TYPE_GRAY_ALPHA:
  200129. if (bit_depth != 8 && bit_depth != 16)
  200130. png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");
  200131. png_ptr->channels = 2;
  200132. break;
  200133. case PNG_COLOR_TYPE_RGB_ALPHA:
  200134. if (bit_depth != 8 && bit_depth != 16)
  200135. png_error(png_ptr, "Invalid bit depth for RGBA image");
  200136. png_ptr->channels = 4;
  200137. break;
  200138. default:
  200139. png_error(png_ptr, "Invalid image color type specified");
  200140. }
  200141. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  200142. {
  200143. png_warning(png_ptr, "Invalid compression type specified");
  200144. compression_type = PNG_COMPRESSION_TYPE_BASE;
  200145. }
  200146. /* Write filter_method 64 (intrapixel differencing) only if
  200147. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  200148. * 2. Libpng did not write a PNG signature (this filter_method is only
  200149. * used in PNG datastreams that are embedded in MNG datastreams) and
  200150. * 3. The application called png_permit_mng_features with a mask that
  200151. * included PNG_FLAG_MNG_FILTER_64 and
  200152. * 4. The filter_method is 64 and
  200153. * 5. The color_type is RGB or RGBA
  200154. */
  200155. if (
  200156. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200157. !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  200158. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  200159. (color_type == PNG_COLOR_TYPE_RGB ||
  200160. color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
  200161. (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) &&
  200162. #endif
  200163. filter_type != PNG_FILTER_TYPE_BASE)
  200164. {
  200165. png_warning(png_ptr, "Invalid filter type specified");
  200166. filter_type = PNG_FILTER_TYPE_BASE;
  200167. }
  200168. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  200169. if (interlace_type != PNG_INTERLACE_NONE &&
  200170. interlace_type != PNG_INTERLACE_ADAM7)
  200171. {
  200172. png_warning(png_ptr, "Invalid interlace type specified");
  200173. interlace_type = PNG_INTERLACE_ADAM7;
  200174. }
  200175. #else
  200176. interlace_type=PNG_INTERLACE_NONE;
  200177. #endif
  200178. /* save off the relevent information */
  200179. png_ptr->bit_depth = (png_byte)bit_depth;
  200180. png_ptr->color_type = (png_byte)color_type;
  200181. png_ptr->interlaced = (png_byte)interlace_type;
  200182. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200183. png_ptr->filter_type = (png_byte)filter_type;
  200184. #endif
  200185. png_ptr->compression_type = (png_byte)compression_type;
  200186. png_ptr->width = width;
  200187. png_ptr->height = height;
  200188. png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);
  200189. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);
  200190. /* set the usr info, so any transformations can modify it */
  200191. png_ptr->usr_width = png_ptr->width;
  200192. png_ptr->usr_bit_depth = png_ptr->bit_depth;
  200193. png_ptr->usr_channels = png_ptr->channels;
  200194. /* pack the header information into the buffer */
  200195. png_save_uint_32(buf, width);
  200196. png_save_uint_32(buf + 4, height);
  200197. buf[8] = (png_byte)bit_depth;
  200198. buf[9] = (png_byte)color_type;
  200199. buf[10] = (png_byte)compression_type;
  200200. buf[11] = (png_byte)filter_type;
  200201. buf[12] = (png_byte)interlace_type;
  200202. /* write the chunk */
  200203. png_write_chunk(png_ptr, png_IHDR, buf, (png_size_t)13);
  200204. /* initialize zlib with PNG info */
  200205. png_ptr->zstream.zalloc = png_zalloc;
  200206. png_ptr->zstream.zfree = png_zfree;
  200207. png_ptr->zstream.opaque = (voidpf)png_ptr;
  200208. if (!(png_ptr->do_filter))
  200209. {
  200210. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
  200211. png_ptr->bit_depth < 8)
  200212. png_ptr->do_filter = PNG_FILTER_NONE;
  200213. else
  200214. png_ptr->do_filter = PNG_ALL_FILTERS;
  200215. }
  200216. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY))
  200217. {
  200218. if (png_ptr->do_filter != PNG_FILTER_NONE)
  200219. png_ptr->zlib_strategy = Z_FILTERED;
  200220. else
  200221. png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY;
  200222. }
  200223. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL))
  200224. png_ptr->zlib_level = Z_DEFAULT_COMPRESSION;
  200225. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL))
  200226. png_ptr->zlib_mem_level = 8;
  200227. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS))
  200228. png_ptr->zlib_window_bits = 15;
  200229. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD))
  200230. png_ptr->zlib_method = 8;
  200231. if (deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,
  200232. png_ptr->zlib_method, png_ptr->zlib_window_bits,
  200233. png_ptr->zlib_mem_level, png_ptr->zlib_strategy) != Z_OK)
  200234. png_error(png_ptr, "zlib failed to initialize compressor");
  200235. png_ptr->zstream.next_out = png_ptr->zbuf;
  200236. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200237. /* libpng is not interested in zstream.data_type */
  200238. /* set it to a predefined value, to avoid its evaluation inside zlib */
  200239. png_ptr->zstream.data_type = Z_BINARY;
  200240. png_ptr->mode = PNG_HAVE_IHDR;
  200241. }
  200242. /* write the palette. We are careful not to trust png_color to be in the
  200243. * correct order for PNG, so people can redefine it to any convenient
  200244. * structure.
  200245. */
  200246. void /* PRIVATE */
  200247. png_write_PLTE(png_structp png_ptr, png_colorp palette, png_uint_32 num_pal)
  200248. {
  200249. #ifdef PNG_USE_LOCAL_ARRAYS
  200250. PNG_PLTE;
  200251. #endif
  200252. png_uint_32 i;
  200253. png_colorp pal_ptr;
  200254. png_byte buf[3];
  200255. png_debug(1, "in png_write_PLTE\n");
  200256. if ((
  200257. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200258. !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
  200259. #endif
  200260. num_pal == 0) || num_pal > 256)
  200261. {
  200262. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  200263. {
  200264. png_error(png_ptr, "Invalid number of colors in palette");
  200265. }
  200266. else
  200267. {
  200268. png_warning(png_ptr, "Invalid number of colors in palette");
  200269. return;
  200270. }
  200271. }
  200272. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  200273. {
  200274. png_warning(png_ptr,
  200275. "Ignoring request to write a PLTE chunk in grayscale PNG");
  200276. return;
  200277. }
  200278. png_ptr->num_palette = (png_uint_16)num_pal;
  200279. png_debug1(3, "num_palette = %d\n", png_ptr->num_palette);
  200280. png_write_chunk_start(png_ptr, png_PLTE, num_pal * 3);
  200281. #ifndef PNG_NO_POINTER_INDEXING
  200282. for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
  200283. {
  200284. buf[0] = pal_ptr->red;
  200285. buf[1] = pal_ptr->green;
  200286. buf[2] = pal_ptr->blue;
  200287. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  200288. }
  200289. #else
  200290. /* This is a little slower but some buggy compilers need to do this instead */
  200291. pal_ptr=palette;
  200292. for (i = 0; i < num_pal; i++)
  200293. {
  200294. buf[0] = pal_ptr[i].red;
  200295. buf[1] = pal_ptr[i].green;
  200296. buf[2] = pal_ptr[i].blue;
  200297. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  200298. }
  200299. #endif
  200300. png_write_chunk_end(png_ptr);
  200301. png_ptr->mode |= PNG_HAVE_PLTE;
  200302. }
  200303. /* write an IDAT chunk */
  200304. void /* PRIVATE */
  200305. png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length)
  200306. {
  200307. #ifdef PNG_USE_LOCAL_ARRAYS
  200308. PNG_IDAT;
  200309. #endif
  200310. png_debug(1, "in png_write_IDAT\n");
  200311. /* Optimize the CMF field in the zlib stream. */
  200312. /* This hack of the zlib stream is compliant to the stream specification. */
  200313. if (!(png_ptr->mode & PNG_HAVE_IDAT) &&
  200314. png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE)
  200315. {
  200316. unsigned int z_cmf = data[0]; /* zlib compression method and flags */
  200317. if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70)
  200318. {
  200319. /* Avoid memory underflows and multiplication overflows. */
  200320. /* The conditions below are practically always satisfied;
  200321. however, they still must be checked. */
  200322. if (length >= 2 &&
  200323. png_ptr->height < 16384 && png_ptr->width < 16384)
  200324. {
  200325. png_uint_32 uncompressed_idat_size = png_ptr->height *
  200326. ((png_ptr->width *
  200327. png_ptr->channels * png_ptr->bit_depth + 15) >> 3);
  200328. unsigned int z_cinfo = z_cmf >> 4;
  200329. unsigned int half_z_window_size = 1 << (z_cinfo + 7);
  200330. while (uncompressed_idat_size <= half_z_window_size &&
  200331. half_z_window_size >= 256)
  200332. {
  200333. z_cinfo--;
  200334. half_z_window_size >>= 1;
  200335. }
  200336. z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4);
  200337. if (data[0] != (png_byte)z_cmf)
  200338. {
  200339. data[0] = (png_byte)z_cmf;
  200340. data[1] &= 0xe0;
  200341. data[1] += (png_byte)(0x1f - ((z_cmf << 8) + data[1]) % 0x1f);
  200342. }
  200343. }
  200344. }
  200345. else
  200346. png_error(png_ptr,
  200347. "Invalid zlib compression method or flags in IDAT");
  200348. }
  200349. png_write_chunk(png_ptr, png_IDAT, data, length);
  200350. png_ptr->mode |= PNG_HAVE_IDAT;
  200351. }
  200352. /* write an IEND chunk */
  200353. void /* PRIVATE */
  200354. png_write_IEND(png_structp png_ptr)
  200355. {
  200356. #ifdef PNG_USE_LOCAL_ARRAYS
  200357. PNG_IEND;
  200358. #endif
  200359. png_debug(1, "in png_write_IEND\n");
  200360. png_write_chunk(png_ptr, png_IEND, png_bytep_NULL,
  200361. (png_size_t)0);
  200362. png_ptr->mode |= PNG_HAVE_IEND;
  200363. }
  200364. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  200365. /* write a gAMA chunk */
  200366. #ifdef PNG_FLOATING_POINT_SUPPORTED
  200367. void /* PRIVATE */
  200368. png_write_gAMA(png_structp png_ptr, double file_gamma)
  200369. {
  200370. #ifdef PNG_USE_LOCAL_ARRAYS
  200371. PNG_gAMA;
  200372. #endif
  200373. png_uint_32 igamma;
  200374. png_byte buf[4];
  200375. png_debug(1, "in png_write_gAMA\n");
  200376. /* file_gamma is saved in 1/100,000ths */
  200377. igamma = (png_uint_32)(file_gamma * 100000.0 + 0.5);
  200378. png_save_uint_32(buf, igamma);
  200379. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  200380. }
  200381. #endif
  200382. #ifdef PNG_FIXED_POINT_SUPPORTED
  200383. void /* PRIVATE */
  200384. png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma)
  200385. {
  200386. #ifdef PNG_USE_LOCAL_ARRAYS
  200387. PNG_gAMA;
  200388. #endif
  200389. png_byte buf[4];
  200390. png_debug(1, "in png_write_gAMA\n");
  200391. /* file_gamma is saved in 1/100,000ths */
  200392. png_save_uint_32(buf, (png_uint_32)file_gamma);
  200393. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  200394. }
  200395. #endif
  200396. #endif
  200397. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  200398. /* write a sRGB chunk */
  200399. void /* PRIVATE */
  200400. png_write_sRGB(png_structp png_ptr, int srgb_intent)
  200401. {
  200402. #ifdef PNG_USE_LOCAL_ARRAYS
  200403. PNG_sRGB;
  200404. #endif
  200405. png_byte buf[1];
  200406. png_debug(1, "in png_write_sRGB\n");
  200407. if(srgb_intent >= PNG_sRGB_INTENT_LAST)
  200408. png_warning(png_ptr,
  200409. "Invalid sRGB rendering intent specified");
  200410. buf[0]=(png_byte)srgb_intent;
  200411. png_write_chunk(png_ptr, png_sRGB, buf, (png_size_t)1);
  200412. }
  200413. #endif
  200414. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  200415. /* write an iCCP chunk */
  200416. void /* PRIVATE */
  200417. png_write_iCCP(png_structp png_ptr, png_charp name, int compression_type,
  200418. png_charp profile, int profile_len)
  200419. {
  200420. #ifdef PNG_USE_LOCAL_ARRAYS
  200421. PNG_iCCP;
  200422. #endif
  200423. png_size_t name_len;
  200424. png_charp new_name;
  200425. compression_state comp;
  200426. int embedded_profile_len = 0;
  200427. png_debug(1, "in png_write_iCCP\n");
  200428. comp.num_output_ptr = 0;
  200429. comp.max_output_ptr = 0;
  200430. comp.output_ptr = NULL;
  200431. comp.input = NULL;
  200432. comp.input_len = 0;
  200433. if (name == NULL || (name_len = png_check_keyword(png_ptr, name,
  200434. &new_name)) == 0)
  200435. {
  200436. png_warning(png_ptr, "Empty keyword in iCCP chunk");
  200437. return;
  200438. }
  200439. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  200440. png_warning(png_ptr, "Unknown compression type in iCCP chunk");
  200441. if (profile == NULL)
  200442. profile_len = 0;
  200443. if (profile_len > 3)
  200444. embedded_profile_len =
  200445. ((*( (png_bytep)profile ))<<24) |
  200446. ((*( (png_bytep)profile+1))<<16) |
  200447. ((*( (png_bytep)profile+2))<< 8) |
  200448. ((*( (png_bytep)profile+3)) );
  200449. if (profile_len < embedded_profile_len)
  200450. {
  200451. png_warning(png_ptr,
  200452. "Embedded profile length too large in iCCP chunk");
  200453. return;
  200454. }
  200455. if (profile_len > embedded_profile_len)
  200456. {
  200457. png_warning(png_ptr,
  200458. "Truncating profile to actual length in iCCP chunk");
  200459. profile_len = embedded_profile_len;
  200460. }
  200461. if (profile_len)
  200462. profile_len = png_text_compress(png_ptr, profile, (png_size_t)profile_len,
  200463. PNG_COMPRESSION_TYPE_BASE, &comp);
  200464. /* make sure we include the NULL after the name and the compression type */
  200465. png_write_chunk_start(png_ptr, png_iCCP,
  200466. (png_uint_32)name_len+profile_len+2);
  200467. new_name[name_len+1]=0x00;
  200468. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 2);
  200469. if (profile_len)
  200470. png_write_compressed_data_out(png_ptr, &comp);
  200471. png_write_chunk_end(png_ptr);
  200472. png_free(png_ptr, new_name);
  200473. }
  200474. #endif
  200475. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  200476. /* write a sPLT chunk */
  200477. void /* PRIVATE */
  200478. png_write_sPLT(png_structp png_ptr, png_sPLT_tp spalette)
  200479. {
  200480. #ifdef PNG_USE_LOCAL_ARRAYS
  200481. PNG_sPLT;
  200482. #endif
  200483. png_size_t name_len;
  200484. png_charp new_name;
  200485. png_byte entrybuf[10];
  200486. int entry_size = (spalette->depth == 8 ? 6 : 10);
  200487. int palette_size = entry_size * spalette->nentries;
  200488. png_sPLT_entryp ep;
  200489. #ifdef PNG_NO_POINTER_INDEXING
  200490. int i;
  200491. #endif
  200492. png_debug(1, "in png_write_sPLT\n");
  200493. if (spalette->name == NULL || (name_len = png_check_keyword(png_ptr,
  200494. spalette->name, &new_name))==0)
  200495. {
  200496. png_warning(png_ptr, "Empty keyword in sPLT chunk");
  200497. return;
  200498. }
  200499. /* make sure we include the NULL after the name */
  200500. png_write_chunk_start(png_ptr, png_sPLT,
  200501. (png_uint_32)(name_len + 2 + palette_size));
  200502. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 1);
  200503. png_write_chunk_data(png_ptr, (png_bytep)&spalette->depth, 1);
  200504. /* loop through each palette entry, writing appropriately */
  200505. #ifndef PNG_NO_POINTER_INDEXING
  200506. for (ep = spalette->entries; ep<spalette->entries+spalette->nentries; ep++)
  200507. {
  200508. if (spalette->depth == 8)
  200509. {
  200510. entrybuf[0] = (png_byte)ep->red;
  200511. entrybuf[1] = (png_byte)ep->green;
  200512. entrybuf[2] = (png_byte)ep->blue;
  200513. entrybuf[3] = (png_byte)ep->alpha;
  200514. png_save_uint_16(entrybuf + 4, ep->frequency);
  200515. }
  200516. else
  200517. {
  200518. png_save_uint_16(entrybuf + 0, ep->red);
  200519. png_save_uint_16(entrybuf + 2, ep->green);
  200520. png_save_uint_16(entrybuf + 4, ep->blue);
  200521. png_save_uint_16(entrybuf + 6, ep->alpha);
  200522. png_save_uint_16(entrybuf + 8, ep->frequency);
  200523. }
  200524. png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
  200525. }
  200526. #else
  200527. ep=spalette->entries;
  200528. for (i=0; i>spalette->nentries; i++)
  200529. {
  200530. if (spalette->depth == 8)
  200531. {
  200532. entrybuf[0] = (png_byte)ep[i].red;
  200533. entrybuf[1] = (png_byte)ep[i].green;
  200534. entrybuf[2] = (png_byte)ep[i].blue;
  200535. entrybuf[3] = (png_byte)ep[i].alpha;
  200536. png_save_uint_16(entrybuf + 4, ep[i].frequency);
  200537. }
  200538. else
  200539. {
  200540. png_save_uint_16(entrybuf + 0, ep[i].red);
  200541. png_save_uint_16(entrybuf + 2, ep[i].green);
  200542. png_save_uint_16(entrybuf + 4, ep[i].blue);
  200543. png_save_uint_16(entrybuf + 6, ep[i].alpha);
  200544. png_save_uint_16(entrybuf + 8, ep[i].frequency);
  200545. }
  200546. png_write_chunk_data(png_ptr, entrybuf, entry_size);
  200547. }
  200548. #endif
  200549. png_write_chunk_end(png_ptr);
  200550. png_free(png_ptr, new_name);
  200551. }
  200552. #endif
  200553. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  200554. /* write the sBIT chunk */
  200555. void /* PRIVATE */
  200556. png_write_sBIT(png_structp png_ptr, png_color_8p sbit, int color_type)
  200557. {
  200558. #ifdef PNG_USE_LOCAL_ARRAYS
  200559. PNG_sBIT;
  200560. #endif
  200561. png_byte buf[4];
  200562. png_size_t size;
  200563. png_debug(1, "in png_write_sBIT\n");
  200564. /* make sure we don't depend upon the order of PNG_COLOR_8 */
  200565. if (color_type & PNG_COLOR_MASK_COLOR)
  200566. {
  200567. png_byte maxbits;
  200568. maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 :
  200569. png_ptr->usr_bit_depth);
  200570. if (sbit->red == 0 || sbit->red > maxbits ||
  200571. sbit->green == 0 || sbit->green > maxbits ||
  200572. sbit->blue == 0 || sbit->blue > maxbits)
  200573. {
  200574. png_warning(png_ptr, "Invalid sBIT depth specified");
  200575. return;
  200576. }
  200577. buf[0] = sbit->red;
  200578. buf[1] = sbit->green;
  200579. buf[2] = sbit->blue;
  200580. size = 3;
  200581. }
  200582. else
  200583. {
  200584. if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth)
  200585. {
  200586. png_warning(png_ptr, "Invalid sBIT depth specified");
  200587. return;
  200588. }
  200589. buf[0] = sbit->gray;
  200590. size = 1;
  200591. }
  200592. if (color_type & PNG_COLOR_MASK_ALPHA)
  200593. {
  200594. if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth)
  200595. {
  200596. png_warning(png_ptr, "Invalid sBIT depth specified");
  200597. return;
  200598. }
  200599. buf[size++] = sbit->alpha;
  200600. }
  200601. png_write_chunk(png_ptr, png_sBIT, buf, size);
  200602. }
  200603. #endif
  200604. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  200605. /* write the cHRM chunk */
  200606. #ifdef PNG_FLOATING_POINT_SUPPORTED
  200607. void /* PRIVATE */
  200608. png_write_cHRM(png_structp png_ptr, double white_x, double white_y,
  200609. double red_x, double red_y, double green_x, double green_y,
  200610. double blue_x, double blue_y)
  200611. {
  200612. #ifdef PNG_USE_LOCAL_ARRAYS
  200613. PNG_cHRM;
  200614. #endif
  200615. png_byte buf[32];
  200616. png_uint_32 itemp;
  200617. png_debug(1, "in png_write_cHRM\n");
  200618. /* each value is saved in 1/100,000ths */
  200619. if (white_x < 0 || white_x > 0.8 || white_y < 0 || white_y > 0.8 ||
  200620. white_x + white_y > 1.0)
  200621. {
  200622. png_warning(png_ptr, "Invalid cHRM white point specified");
  200623. #if !defined(PNG_NO_CONSOLE_IO)
  200624. fprintf(stderr,"white_x=%f, white_y=%f\n",white_x, white_y);
  200625. #endif
  200626. return;
  200627. }
  200628. itemp = (png_uint_32)(white_x * 100000.0 + 0.5);
  200629. png_save_uint_32(buf, itemp);
  200630. itemp = (png_uint_32)(white_y * 100000.0 + 0.5);
  200631. png_save_uint_32(buf + 4, itemp);
  200632. if (red_x < 0 || red_y < 0 || red_x + red_y > 1.0)
  200633. {
  200634. png_warning(png_ptr, "Invalid cHRM red point specified");
  200635. return;
  200636. }
  200637. itemp = (png_uint_32)(red_x * 100000.0 + 0.5);
  200638. png_save_uint_32(buf + 8, itemp);
  200639. itemp = (png_uint_32)(red_y * 100000.0 + 0.5);
  200640. png_save_uint_32(buf + 12, itemp);
  200641. if (green_x < 0 || green_y < 0 || green_x + green_y > 1.0)
  200642. {
  200643. png_warning(png_ptr, "Invalid cHRM green point specified");
  200644. return;
  200645. }
  200646. itemp = (png_uint_32)(green_x * 100000.0 + 0.5);
  200647. png_save_uint_32(buf + 16, itemp);
  200648. itemp = (png_uint_32)(green_y * 100000.0 + 0.5);
  200649. png_save_uint_32(buf + 20, itemp);
  200650. if (blue_x < 0 || blue_y < 0 || blue_x + blue_y > 1.0)
  200651. {
  200652. png_warning(png_ptr, "Invalid cHRM blue point specified");
  200653. return;
  200654. }
  200655. itemp = (png_uint_32)(blue_x * 100000.0 + 0.5);
  200656. png_save_uint_32(buf + 24, itemp);
  200657. itemp = (png_uint_32)(blue_y * 100000.0 + 0.5);
  200658. png_save_uint_32(buf + 28, itemp);
  200659. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  200660. }
  200661. #endif
  200662. #ifdef PNG_FIXED_POINT_SUPPORTED
  200663. void /* PRIVATE */
  200664. png_write_cHRM_fixed(png_structp png_ptr, png_fixed_point white_x,
  200665. png_fixed_point white_y, png_fixed_point red_x, png_fixed_point red_y,
  200666. png_fixed_point green_x, png_fixed_point green_y, png_fixed_point blue_x,
  200667. png_fixed_point blue_y)
  200668. {
  200669. #ifdef PNG_USE_LOCAL_ARRAYS
  200670. PNG_cHRM;
  200671. #endif
  200672. png_byte buf[32];
  200673. png_debug(1, "in png_write_cHRM\n");
  200674. /* each value is saved in 1/100,000ths */
  200675. if (white_x > 80000L || white_y > 80000L || white_x + white_y > 100000L)
  200676. {
  200677. png_warning(png_ptr, "Invalid fixed cHRM white point specified");
  200678. #if !defined(PNG_NO_CONSOLE_IO)
  200679. fprintf(stderr,"white_x=%ld, white_y=%ld\n",white_x, white_y);
  200680. #endif
  200681. return;
  200682. }
  200683. png_save_uint_32(buf, (png_uint_32)white_x);
  200684. png_save_uint_32(buf + 4, (png_uint_32)white_y);
  200685. if (red_x + red_y > 100000L)
  200686. {
  200687. png_warning(png_ptr, "Invalid cHRM fixed red point specified");
  200688. return;
  200689. }
  200690. png_save_uint_32(buf + 8, (png_uint_32)red_x);
  200691. png_save_uint_32(buf + 12, (png_uint_32)red_y);
  200692. if (green_x + green_y > 100000L)
  200693. {
  200694. png_warning(png_ptr, "Invalid fixed cHRM green point specified");
  200695. return;
  200696. }
  200697. png_save_uint_32(buf + 16, (png_uint_32)green_x);
  200698. png_save_uint_32(buf + 20, (png_uint_32)green_y);
  200699. if (blue_x + blue_y > 100000L)
  200700. {
  200701. png_warning(png_ptr, "Invalid fixed cHRM blue point specified");
  200702. return;
  200703. }
  200704. png_save_uint_32(buf + 24, (png_uint_32)blue_x);
  200705. png_save_uint_32(buf + 28, (png_uint_32)blue_y);
  200706. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  200707. }
  200708. #endif
  200709. #endif
  200710. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  200711. /* write the tRNS chunk */
  200712. void /* PRIVATE */
  200713. png_write_tRNS(png_structp png_ptr, png_bytep trans, png_color_16p tran,
  200714. int num_trans, int color_type)
  200715. {
  200716. #ifdef PNG_USE_LOCAL_ARRAYS
  200717. PNG_tRNS;
  200718. #endif
  200719. png_byte buf[6];
  200720. png_debug(1, "in png_write_tRNS\n");
  200721. if (color_type == PNG_COLOR_TYPE_PALETTE)
  200722. {
  200723. if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette)
  200724. {
  200725. png_warning(png_ptr,"Invalid number of transparent colors specified");
  200726. return;
  200727. }
  200728. /* write the chunk out as it is */
  200729. png_write_chunk(png_ptr, png_tRNS, trans, (png_size_t)num_trans);
  200730. }
  200731. else if (color_type == PNG_COLOR_TYPE_GRAY)
  200732. {
  200733. /* one 16 bit value */
  200734. if(tran->gray >= (1 << png_ptr->bit_depth))
  200735. {
  200736. png_warning(png_ptr,
  200737. "Ignoring attempt to write tRNS chunk out-of-range for bit_depth");
  200738. return;
  200739. }
  200740. png_save_uint_16(buf, tran->gray);
  200741. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)2);
  200742. }
  200743. else if (color_type == PNG_COLOR_TYPE_RGB)
  200744. {
  200745. /* three 16 bit values */
  200746. png_save_uint_16(buf, tran->red);
  200747. png_save_uint_16(buf + 2, tran->green);
  200748. png_save_uint_16(buf + 4, tran->blue);
  200749. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  200750. {
  200751. png_warning(png_ptr,
  200752. "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8");
  200753. return;
  200754. }
  200755. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)6);
  200756. }
  200757. else
  200758. {
  200759. png_warning(png_ptr, "Can't write tRNS with an alpha channel");
  200760. }
  200761. }
  200762. #endif
  200763. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  200764. /* write the background chunk */
  200765. void /* PRIVATE */
  200766. png_write_bKGD(png_structp png_ptr, png_color_16p back, int color_type)
  200767. {
  200768. #ifdef PNG_USE_LOCAL_ARRAYS
  200769. PNG_bKGD;
  200770. #endif
  200771. png_byte buf[6];
  200772. png_debug(1, "in png_write_bKGD\n");
  200773. if (color_type == PNG_COLOR_TYPE_PALETTE)
  200774. {
  200775. if (
  200776. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200777. (png_ptr->num_palette ||
  200778. (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) &&
  200779. #endif
  200780. back->index > png_ptr->num_palette)
  200781. {
  200782. png_warning(png_ptr, "Invalid background palette index");
  200783. return;
  200784. }
  200785. buf[0] = back->index;
  200786. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)1);
  200787. }
  200788. else if (color_type & PNG_COLOR_MASK_COLOR)
  200789. {
  200790. png_save_uint_16(buf, back->red);
  200791. png_save_uint_16(buf + 2, back->green);
  200792. png_save_uint_16(buf + 4, back->blue);
  200793. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  200794. {
  200795. png_warning(png_ptr,
  200796. "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
  200797. return;
  200798. }
  200799. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)6);
  200800. }
  200801. else
  200802. {
  200803. if(back->gray >= (1 << png_ptr->bit_depth))
  200804. {
  200805. png_warning(png_ptr,
  200806. "Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
  200807. return;
  200808. }
  200809. png_save_uint_16(buf, back->gray);
  200810. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)2);
  200811. }
  200812. }
  200813. #endif
  200814. #if defined(PNG_WRITE_hIST_SUPPORTED)
  200815. /* write the histogram */
  200816. void /* PRIVATE */
  200817. png_write_hIST(png_structp png_ptr, png_uint_16p hist, int num_hist)
  200818. {
  200819. #ifdef PNG_USE_LOCAL_ARRAYS
  200820. PNG_hIST;
  200821. #endif
  200822. int i;
  200823. png_byte buf[3];
  200824. png_debug(1, "in png_write_hIST\n");
  200825. if (num_hist > (int)png_ptr->num_palette)
  200826. {
  200827. png_debug2(3, "num_hist = %d, num_palette = %d\n", num_hist,
  200828. png_ptr->num_palette);
  200829. png_warning(png_ptr, "Invalid number of histogram entries specified");
  200830. return;
  200831. }
  200832. png_write_chunk_start(png_ptr, png_hIST, (png_uint_32)(num_hist * 2));
  200833. for (i = 0; i < num_hist; i++)
  200834. {
  200835. png_save_uint_16(buf, hist[i]);
  200836. png_write_chunk_data(png_ptr, buf, (png_size_t)2);
  200837. }
  200838. png_write_chunk_end(png_ptr);
  200839. }
  200840. #endif
  200841. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  200842. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  200843. /* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
  200844. * and if invalid, correct the keyword rather than discarding the entire
  200845. * chunk. The PNG 1.0 specification requires keywords 1-79 characters in
  200846. * length, forbids leading or trailing whitespace, multiple internal spaces,
  200847. * and the non-break space (0x80) from ISO 8859-1. Returns keyword length.
  200848. *
  200849. * The new_key is allocated to hold the corrected keyword and must be freed
  200850. * by the calling routine. This avoids problems with trying to write to
  200851. * static keywords without having to have duplicate copies of the strings.
  200852. */
  200853. png_size_t /* PRIVATE */
  200854. png_check_keyword(png_structp png_ptr, png_charp key, png_charpp new_key)
  200855. {
  200856. png_size_t key_len;
  200857. png_charp kp, dp;
  200858. int kflag;
  200859. int kwarn=0;
  200860. png_debug(1, "in png_check_keyword\n");
  200861. *new_key = NULL;
  200862. if (key == NULL || (key_len = png_strlen(key)) == 0)
  200863. {
  200864. png_warning(png_ptr, "zero length keyword");
  200865. return ((png_size_t)0);
  200866. }
  200867. png_debug1(2, "Keyword to be checked is '%s'\n", key);
  200868. *new_key = (png_charp)png_malloc_warn(png_ptr, (png_uint_32)(key_len + 2));
  200869. if (*new_key == NULL)
  200870. {
  200871. png_warning(png_ptr, "Out of memory while procesing keyword");
  200872. return ((png_size_t)0);
  200873. }
  200874. /* Replace non-printing characters with a blank and print a warning */
  200875. for (kp = key, dp = *new_key; *kp != '\0'; kp++, dp++)
  200876. {
  200877. if ((png_byte)*kp < 0x20 ||
  200878. ((png_byte)*kp > 0x7E && (png_byte)*kp < 0xA1))
  200879. {
  200880. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  200881. char msg[40];
  200882. png_snprintf(msg, 40,
  200883. "invalid keyword character 0x%02X", (png_byte)*kp);
  200884. png_warning(png_ptr, msg);
  200885. #else
  200886. png_warning(png_ptr, "invalid character in keyword");
  200887. #endif
  200888. *dp = ' ';
  200889. }
  200890. else
  200891. {
  200892. *dp = *kp;
  200893. }
  200894. }
  200895. *dp = '\0';
  200896. /* Remove any trailing white space. */
  200897. kp = *new_key + key_len - 1;
  200898. if (*kp == ' ')
  200899. {
  200900. png_warning(png_ptr, "trailing spaces removed from keyword");
  200901. while (*kp == ' ')
  200902. {
  200903. *(kp--) = '\0';
  200904. key_len--;
  200905. }
  200906. }
  200907. /* Remove any leading white space. */
  200908. kp = *new_key;
  200909. if (*kp == ' ')
  200910. {
  200911. png_warning(png_ptr, "leading spaces removed from keyword");
  200912. while (*kp == ' ')
  200913. {
  200914. kp++;
  200915. key_len--;
  200916. }
  200917. }
  200918. png_debug1(2, "Checking for multiple internal spaces in '%s'\n", kp);
  200919. /* Remove multiple internal spaces. */
  200920. for (kflag = 0, dp = *new_key; *kp != '\0'; kp++)
  200921. {
  200922. if (*kp == ' ' && kflag == 0)
  200923. {
  200924. *(dp++) = *kp;
  200925. kflag = 1;
  200926. }
  200927. else if (*kp == ' ')
  200928. {
  200929. key_len--;
  200930. kwarn=1;
  200931. }
  200932. else
  200933. {
  200934. *(dp++) = *kp;
  200935. kflag = 0;
  200936. }
  200937. }
  200938. *dp = '\0';
  200939. if(kwarn)
  200940. png_warning(png_ptr, "extra interior spaces removed from keyword");
  200941. if (key_len == 0)
  200942. {
  200943. png_free(png_ptr, *new_key);
  200944. *new_key=NULL;
  200945. png_warning(png_ptr, "Zero length keyword");
  200946. }
  200947. if (key_len > 79)
  200948. {
  200949. png_warning(png_ptr, "keyword length must be 1 - 79 characters");
  200950. new_key[79] = '\0';
  200951. key_len = 79;
  200952. }
  200953. return (key_len);
  200954. }
  200955. #endif
  200956. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  200957. /* write a tEXt chunk */
  200958. void /* PRIVATE */
  200959. png_write_tEXt(png_structp png_ptr, png_charp key, png_charp text,
  200960. png_size_t text_len)
  200961. {
  200962. #ifdef PNG_USE_LOCAL_ARRAYS
  200963. PNG_tEXt;
  200964. #endif
  200965. png_size_t key_len;
  200966. png_charp new_key;
  200967. png_debug(1, "in png_write_tEXt\n");
  200968. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  200969. {
  200970. png_warning(png_ptr, "Empty keyword in tEXt chunk");
  200971. return;
  200972. }
  200973. if (text == NULL || *text == '\0')
  200974. text_len = 0;
  200975. else
  200976. text_len = png_strlen(text);
  200977. /* make sure we include the 0 after the key */
  200978. png_write_chunk_start(png_ptr, png_tEXt, (png_uint_32)key_len+text_len+1);
  200979. /*
  200980. * We leave it to the application to meet PNG-1.0 requirements on the
  200981. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  200982. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  200983. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  200984. */
  200985. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  200986. if (text_len)
  200987. png_write_chunk_data(png_ptr, (png_bytep)text, text_len);
  200988. png_write_chunk_end(png_ptr);
  200989. png_free(png_ptr, new_key);
  200990. }
  200991. #endif
  200992. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  200993. /* write a compressed text chunk */
  200994. void /* PRIVATE */
  200995. png_write_zTXt(png_structp png_ptr, png_charp key, png_charp text,
  200996. png_size_t text_len, int compression)
  200997. {
  200998. #ifdef PNG_USE_LOCAL_ARRAYS
  200999. PNG_zTXt;
  201000. #endif
  201001. png_size_t key_len;
  201002. char buf[1];
  201003. png_charp new_key;
  201004. compression_state comp;
  201005. png_debug(1, "in png_write_zTXt\n");
  201006. comp.num_output_ptr = 0;
  201007. comp.max_output_ptr = 0;
  201008. comp.output_ptr = NULL;
  201009. comp.input = NULL;
  201010. comp.input_len = 0;
  201011. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201012. {
  201013. png_warning(png_ptr, "Empty keyword in zTXt chunk");
  201014. return;
  201015. }
  201016. if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE)
  201017. {
  201018. png_write_tEXt(png_ptr, new_key, text, (png_size_t)0);
  201019. png_free(png_ptr, new_key);
  201020. return;
  201021. }
  201022. text_len = png_strlen(text);
  201023. /* compute the compressed data; do it now for the length */
  201024. text_len = png_text_compress(png_ptr, text, text_len, compression,
  201025. &comp);
  201026. /* write start of chunk */
  201027. png_write_chunk_start(png_ptr, png_zTXt, (png_uint_32)
  201028. (key_len+text_len+2));
  201029. /* write key */
  201030. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201031. png_free(png_ptr, new_key);
  201032. buf[0] = (png_byte)compression;
  201033. /* write compression */
  201034. png_write_chunk_data(png_ptr, (png_bytep)buf, (png_size_t)1);
  201035. /* write the compressed data */
  201036. png_write_compressed_data_out(png_ptr, &comp);
  201037. /* close the chunk */
  201038. png_write_chunk_end(png_ptr);
  201039. }
  201040. #endif
  201041. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  201042. /* write an iTXt chunk */
  201043. void /* PRIVATE */
  201044. png_write_iTXt(png_structp png_ptr, int compression, png_charp key,
  201045. png_charp lang, png_charp lang_key, png_charp text)
  201046. {
  201047. #ifdef PNG_USE_LOCAL_ARRAYS
  201048. PNG_iTXt;
  201049. #endif
  201050. png_size_t lang_len, key_len, lang_key_len, text_len;
  201051. png_charp new_lang, new_key;
  201052. png_byte cbuf[2];
  201053. compression_state comp;
  201054. png_debug(1, "in png_write_iTXt\n");
  201055. comp.num_output_ptr = 0;
  201056. comp.max_output_ptr = 0;
  201057. comp.output_ptr = NULL;
  201058. comp.input = NULL;
  201059. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201060. {
  201061. png_warning(png_ptr, "Empty keyword in iTXt chunk");
  201062. return;
  201063. }
  201064. if (lang == NULL || (lang_len = png_check_keyword(png_ptr, lang, &new_lang))==0)
  201065. {
  201066. png_warning(png_ptr, "Empty language field in iTXt chunk");
  201067. new_lang = NULL;
  201068. lang_len = 0;
  201069. }
  201070. if (lang_key == NULL)
  201071. lang_key_len = 0;
  201072. else
  201073. lang_key_len = png_strlen(lang_key);
  201074. if (text == NULL)
  201075. text_len = 0;
  201076. else
  201077. text_len = png_strlen(text);
  201078. /* compute the compressed data; do it now for the length */
  201079. text_len = png_text_compress(png_ptr, text, text_len, compression-2,
  201080. &comp);
  201081. /* make sure we include the compression flag, the compression byte,
  201082. * and the NULs after the key, lang, and lang_key parts */
  201083. png_write_chunk_start(png_ptr, png_iTXt,
  201084. (png_uint_32)(
  201085. 5 /* comp byte, comp flag, terminators for key, lang and lang_key */
  201086. + key_len
  201087. + lang_len
  201088. + lang_key_len
  201089. + text_len));
  201090. /*
  201091. * We leave it to the application to meet PNG-1.0 requirements on the
  201092. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  201093. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  201094. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  201095. */
  201096. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201097. /* set the compression flag */
  201098. if (compression == PNG_ITXT_COMPRESSION_NONE || \
  201099. compression == PNG_TEXT_COMPRESSION_NONE)
  201100. cbuf[0] = 0;
  201101. else /* compression == PNG_ITXT_COMPRESSION_zTXt */
  201102. cbuf[0] = 1;
  201103. /* set the compression method */
  201104. cbuf[1] = 0;
  201105. png_write_chunk_data(png_ptr, cbuf, 2);
  201106. cbuf[0] = 0;
  201107. png_write_chunk_data(png_ptr, (new_lang ? (png_bytep)new_lang : cbuf), lang_len + 1);
  201108. png_write_chunk_data(png_ptr, (lang_key ? (png_bytep)lang_key : cbuf), lang_key_len + 1);
  201109. png_write_compressed_data_out(png_ptr, &comp);
  201110. png_write_chunk_end(png_ptr);
  201111. png_free(png_ptr, new_key);
  201112. if (new_lang)
  201113. png_free(png_ptr, new_lang);
  201114. }
  201115. #endif
  201116. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  201117. /* write the oFFs chunk */
  201118. void /* PRIVATE */
  201119. png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
  201120. int unit_type)
  201121. {
  201122. #ifdef PNG_USE_LOCAL_ARRAYS
  201123. PNG_oFFs;
  201124. #endif
  201125. png_byte buf[9];
  201126. png_debug(1, "in png_write_oFFs\n");
  201127. if (unit_type >= PNG_OFFSET_LAST)
  201128. png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");
  201129. png_save_int_32(buf, x_offset);
  201130. png_save_int_32(buf + 4, y_offset);
  201131. buf[8] = (png_byte)unit_type;
  201132. png_write_chunk(png_ptr, png_oFFs, buf, (png_size_t)9);
  201133. }
  201134. #endif
  201135. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  201136. /* write the pCAL chunk (described in the PNG extensions document) */
  201137. void /* PRIVATE */
  201138. png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0,
  201139. png_int_32 X1, int type, int nparams, png_charp units, png_charpp params)
  201140. {
  201141. #ifdef PNG_USE_LOCAL_ARRAYS
  201142. PNG_pCAL;
  201143. #endif
  201144. png_size_t purpose_len, units_len, total_len;
  201145. png_uint_32p params_len;
  201146. png_byte buf[10];
  201147. png_charp new_purpose;
  201148. int i;
  201149. png_debug1(1, "in png_write_pCAL (%d parameters)\n", nparams);
  201150. if (type >= PNG_EQUATION_LAST)
  201151. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  201152. purpose_len = png_check_keyword(png_ptr, purpose, &new_purpose) + 1;
  201153. png_debug1(3, "pCAL purpose length = %d\n", (int)purpose_len);
  201154. units_len = png_strlen(units) + (nparams == 0 ? 0 : 1);
  201155. png_debug1(3, "pCAL units length = %d\n", (int)units_len);
  201156. total_len = purpose_len + units_len + 10;
  201157. params_len = (png_uint_32p)png_malloc(png_ptr, (png_uint_32)(nparams
  201158. *png_sizeof(png_uint_32)));
  201159. /* Find the length of each parameter, making sure we don't count the
  201160. null terminator for the last parameter. */
  201161. for (i = 0; i < nparams; i++)
  201162. {
  201163. params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
  201164. png_debug2(3, "pCAL parameter %d length = %lu\n", i, params_len[i]);
  201165. total_len += (png_size_t)params_len[i];
  201166. }
  201167. png_debug1(3, "pCAL total length = %d\n", (int)total_len);
  201168. png_write_chunk_start(png_ptr, png_pCAL, (png_uint_32)total_len);
  201169. png_write_chunk_data(png_ptr, (png_bytep)new_purpose, purpose_len);
  201170. png_save_int_32(buf, X0);
  201171. png_save_int_32(buf + 4, X1);
  201172. buf[8] = (png_byte)type;
  201173. buf[9] = (png_byte)nparams;
  201174. png_write_chunk_data(png_ptr, buf, (png_size_t)10);
  201175. png_write_chunk_data(png_ptr, (png_bytep)units, (png_size_t)units_len);
  201176. png_free(png_ptr, new_purpose);
  201177. for (i = 0; i < nparams; i++)
  201178. {
  201179. png_write_chunk_data(png_ptr, (png_bytep)params[i],
  201180. (png_size_t)params_len[i]);
  201181. }
  201182. png_free(png_ptr, params_len);
  201183. png_write_chunk_end(png_ptr);
  201184. }
  201185. #endif
  201186. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  201187. /* write the sCAL chunk */
  201188. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  201189. void /* PRIVATE */
  201190. png_write_sCAL(png_structp png_ptr, int unit, double width, double height)
  201191. {
  201192. #ifdef PNG_USE_LOCAL_ARRAYS
  201193. PNG_sCAL;
  201194. #endif
  201195. char buf[64];
  201196. png_size_t total_len;
  201197. png_debug(1, "in png_write_sCAL\n");
  201198. buf[0] = (char)unit;
  201199. #if defined(_WIN32_WCE)
  201200. /* sprintf() function is not supported on WindowsCE */
  201201. {
  201202. wchar_t wc_buf[32];
  201203. size_t wc_len;
  201204. swprintf(wc_buf, TEXT("%12.12e"), width);
  201205. wc_len = wcslen(wc_buf);
  201206. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + 1, wc_len, NULL, NULL);
  201207. total_len = wc_len + 2;
  201208. swprintf(wc_buf, TEXT("%12.12e"), height);
  201209. wc_len = wcslen(wc_buf);
  201210. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + total_len, wc_len,
  201211. NULL, NULL);
  201212. total_len += wc_len;
  201213. }
  201214. #else
  201215. png_snprintf(buf + 1, 63, "%12.12e", width);
  201216. total_len = 1 + png_strlen(buf + 1) + 1;
  201217. png_snprintf(buf + total_len, 64-total_len, "%12.12e", height);
  201218. total_len += png_strlen(buf + total_len);
  201219. #endif
  201220. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  201221. png_write_chunk(png_ptr, png_sCAL, (png_bytep)buf, total_len);
  201222. }
  201223. #else
  201224. #ifdef PNG_FIXED_POINT_SUPPORTED
  201225. void /* PRIVATE */
  201226. png_write_sCAL_s(png_structp png_ptr, int unit, png_charp width,
  201227. png_charp height)
  201228. {
  201229. #ifdef PNG_USE_LOCAL_ARRAYS
  201230. PNG_sCAL;
  201231. #endif
  201232. png_byte buf[64];
  201233. png_size_t wlen, hlen, total_len;
  201234. png_debug(1, "in png_write_sCAL_s\n");
  201235. wlen = png_strlen(width);
  201236. hlen = png_strlen(height);
  201237. total_len = wlen + hlen + 2;
  201238. if (total_len > 64)
  201239. {
  201240. png_warning(png_ptr, "Can't write sCAL (buffer too small)");
  201241. return;
  201242. }
  201243. buf[0] = (png_byte)unit;
  201244. png_memcpy(buf + 1, width, wlen + 1); /* append the '\0' here */
  201245. png_memcpy(buf + wlen + 2, height, hlen); /* do NOT append the '\0' here */
  201246. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  201247. png_write_chunk(png_ptr, png_sCAL, buf, total_len);
  201248. }
  201249. #endif
  201250. #endif
  201251. #endif
  201252. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  201253. /* write the pHYs chunk */
  201254. void /* PRIVATE */
  201255. png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit,
  201256. png_uint_32 y_pixels_per_unit,
  201257. int unit_type)
  201258. {
  201259. #ifdef PNG_USE_LOCAL_ARRAYS
  201260. PNG_pHYs;
  201261. #endif
  201262. png_byte buf[9];
  201263. png_debug(1, "in png_write_pHYs\n");
  201264. if (unit_type >= PNG_RESOLUTION_LAST)
  201265. png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");
  201266. png_save_uint_32(buf, x_pixels_per_unit);
  201267. png_save_uint_32(buf + 4, y_pixels_per_unit);
  201268. buf[8] = (png_byte)unit_type;
  201269. png_write_chunk(png_ptr, png_pHYs, buf, (png_size_t)9);
  201270. }
  201271. #endif
  201272. #if defined(PNG_WRITE_tIME_SUPPORTED)
  201273. /* Write the tIME chunk. Use either png_convert_from_struct_tm()
  201274. * or png_convert_from_time_t(), or fill in the structure yourself.
  201275. */
  201276. void /* PRIVATE */
  201277. png_write_tIME(png_structp png_ptr, png_timep mod_time)
  201278. {
  201279. #ifdef PNG_USE_LOCAL_ARRAYS
  201280. PNG_tIME;
  201281. #endif
  201282. png_byte buf[7];
  201283. png_debug(1, "in png_write_tIME\n");
  201284. if (mod_time->month > 12 || mod_time->month < 1 ||
  201285. mod_time->day > 31 || mod_time->day < 1 ||
  201286. mod_time->hour > 23 || mod_time->second > 60)
  201287. {
  201288. png_warning(png_ptr, "Invalid time specified for tIME chunk");
  201289. return;
  201290. }
  201291. png_save_uint_16(buf, mod_time->year);
  201292. buf[2] = mod_time->month;
  201293. buf[3] = mod_time->day;
  201294. buf[4] = mod_time->hour;
  201295. buf[5] = mod_time->minute;
  201296. buf[6] = mod_time->second;
  201297. png_write_chunk(png_ptr, png_tIME, buf, (png_size_t)7);
  201298. }
  201299. #endif
  201300. /* initializes the row writing capability of libpng */
  201301. void /* PRIVATE */
  201302. png_write_start_row(png_structp png_ptr)
  201303. {
  201304. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201305. #ifdef PNG_USE_LOCAL_ARRAYS
  201306. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  201307. /* start of interlace block */
  201308. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  201309. /* offset to next interlace block */
  201310. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  201311. /* start of interlace block in the y direction */
  201312. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  201313. /* offset to next interlace block in the y direction */
  201314. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  201315. #endif
  201316. #endif
  201317. png_size_t buf_size;
  201318. png_debug(1, "in png_write_start_row\n");
  201319. buf_size = (png_size_t)(PNG_ROWBYTES(
  201320. png_ptr->usr_channels*png_ptr->usr_bit_depth,png_ptr->width)+1);
  201321. /* set up row buffer */
  201322. png_ptr->row_buf = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  201323. png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
  201324. #ifndef PNG_NO_WRITE_FILTERING
  201325. /* set up filtering buffer, if using this filter */
  201326. if (png_ptr->do_filter & PNG_FILTER_SUB)
  201327. {
  201328. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  201329. (png_ptr->rowbytes + 1));
  201330. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  201331. }
  201332. /* We only need to keep the previous row if we are using one of these. */
  201333. if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
  201334. {
  201335. /* set up previous row buffer */
  201336. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  201337. png_memset(png_ptr->prev_row, 0, buf_size);
  201338. if (png_ptr->do_filter & PNG_FILTER_UP)
  201339. {
  201340. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  201341. (png_ptr->rowbytes + 1));
  201342. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  201343. }
  201344. if (png_ptr->do_filter & PNG_FILTER_AVG)
  201345. {
  201346. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  201347. (png_ptr->rowbytes + 1));
  201348. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  201349. }
  201350. if (png_ptr->do_filter & PNG_FILTER_PAETH)
  201351. {
  201352. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  201353. (png_ptr->rowbytes + 1));
  201354. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  201355. }
  201356. #endif /* PNG_NO_WRITE_FILTERING */
  201357. }
  201358. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201359. /* if interlaced, we need to set up width and height of pass */
  201360. if (png_ptr->interlaced)
  201361. {
  201362. if (!(png_ptr->transformations & PNG_INTERLACE))
  201363. {
  201364. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  201365. png_pass_ystart[0]) / png_pass_yinc[0];
  201366. png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
  201367. png_pass_start[0]) / png_pass_inc[0];
  201368. }
  201369. else
  201370. {
  201371. png_ptr->num_rows = png_ptr->height;
  201372. png_ptr->usr_width = png_ptr->width;
  201373. }
  201374. }
  201375. else
  201376. #endif
  201377. {
  201378. png_ptr->num_rows = png_ptr->height;
  201379. png_ptr->usr_width = png_ptr->width;
  201380. }
  201381. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201382. png_ptr->zstream.next_out = png_ptr->zbuf;
  201383. }
  201384. /* Internal use only. Called when finished processing a row of data. */
  201385. void /* PRIVATE */
  201386. png_write_finish_row(png_structp png_ptr)
  201387. {
  201388. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201389. #ifdef PNG_USE_LOCAL_ARRAYS
  201390. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  201391. /* start of interlace block */
  201392. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  201393. /* offset to next interlace block */
  201394. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  201395. /* start of interlace block in the y direction */
  201396. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  201397. /* offset to next interlace block in the y direction */
  201398. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  201399. #endif
  201400. #endif
  201401. int ret;
  201402. png_debug(1, "in png_write_finish_row\n");
  201403. /* next row */
  201404. png_ptr->row_number++;
  201405. /* see if we are done */
  201406. if (png_ptr->row_number < png_ptr->num_rows)
  201407. return;
  201408. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201409. /* if interlaced, go to next pass */
  201410. if (png_ptr->interlaced)
  201411. {
  201412. png_ptr->row_number = 0;
  201413. if (png_ptr->transformations & PNG_INTERLACE)
  201414. {
  201415. png_ptr->pass++;
  201416. }
  201417. else
  201418. {
  201419. /* loop until we find a non-zero width or height pass */
  201420. do
  201421. {
  201422. png_ptr->pass++;
  201423. if (png_ptr->pass >= 7)
  201424. break;
  201425. png_ptr->usr_width = (png_ptr->width +
  201426. png_pass_inc[png_ptr->pass] - 1 -
  201427. png_pass_start[png_ptr->pass]) /
  201428. png_pass_inc[png_ptr->pass];
  201429. png_ptr->num_rows = (png_ptr->height +
  201430. png_pass_yinc[png_ptr->pass] - 1 -
  201431. png_pass_ystart[png_ptr->pass]) /
  201432. png_pass_yinc[png_ptr->pass];
  201433. if (png_ptr->transformations & PNG_INTERLACE)
  201434. break;
  201435. } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
  201436. }
  201437. /* reset the row above the image for the next pass */
  201438. if (png_ptr->pass < 7)
  201439. {
  201440. if (png_ptr->prev_row != NULL)
  201441. png_memset(png_ptr->prev_row, 0,
  201442. (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
  201443. png_ptr->usr_bit_depth,png_ptr->width))+1);
  201444. return;
  201445. }
  201446. }
  201447. #endif
  201448. /* if we get here, we've just written the last row, so we need
  201449. to flush the compressor */
  201450. do
  201451. {
  201452. /* tell the compressor we are done */
  201453. ret = deflate(&png_ptr->zstream, Z_FINISH);
  201454. /* check for an error */
  201455. if (ret == Z_OK)
  201456. {
  201457. /* check to see if we need more room */
  201458. if (!(png_ptr->zstream.avail_out))
  201459. {
  201460. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  201461. png_ptr->zstream.next_out = png_ptr->zbuf;
  201462. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201463. }
  201464. }
  201465. else if (ret != Z_STREAM_END)
  201466. {
  201467. if (png_ptr->zstream.msg != NULL)
  201468. png_error(png_ptr, png_ptr->zstream.msg);
  201469. else
  201470. png_error(png_ptr, "zlib error");
  201471. }
  201472. } while (ret != Z_STREAM_END);
  201473. /* write any extra space */
  201474. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  201475. {
  201476. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
  201477. png_ptr->zstream.avail_out);
  201478. }
  201479. deflateReset(&png_ptr->zstream);
  201480. png_ptr->zstream.data_type = Z_BINARY;
  201481. }
  201482. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  201483. /* Pick out the correct pixels for the interlace pass.
  201484. * The basic idea here is to go through the row with a source
  201485. * pointer and a destination pointer (sp and dp), and copy the
  201486. * correct pixels for the pass. As the row gets compacted,
  201487. * sp will always be >= dp, so we should never overwrite anything.
  201488. * See the default: case for the easiest code to understand.
  201489. */
  201490. void /* PRIVATE */
  201491. png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
  201492. {
  201493. #ifdef PNG_USE_LOCAL_ARRAYS
  201494. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  201495. /* start of interlace block */
  201496. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  201497. /* offset to next interlace block */
  201498. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  201499. #endif
  201500. png_debug(1, "in png_do_write_interlace\n");
  201501. /* we don't have to do anything on the last pass (6) */
  201502. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  201503. if (row != NULL && row_info != NULL && pass < 6)
  201504. #else
  201505. if (pass < 6)
  201506. #endif
  201507. {
  201508. /* each pixel depth is handled separately */
  201509. switch (row_info->pixel_depth)
  201510. {
  201511. case 1:
  201512. {
  201513. png_bytep sp;
  201514. png_bytep dp;
  201515. int shift;
  201516. int d;
  201517. int value;
  201518. png_uint_32 i;
  201519. png_uint_32 row_width = row_info->width;
  201520. dp = row;
  201521. d = 0;
  201522. shift = 7;
  201523. for (i = png_pass_start[pass]; i < row_width;
  201524. i += png_pass_inc[pass])
  201525. {
  201526. sp = row + (png_size_t)(i >> 3);
  201527. value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
  201528. d |= (value << shift);
  201529. if (shift == 0)
  201530. {
  201531. shift = 7;
  201532. *dp++ = (png_byte)d;
  201533. d = 0;
  201534. }
  201535. else
  201536. shift--;
  201537. }
  201538. if (shift != 7)
  201539. *dp = (png_byte)d;
  201540. break;
  201541. }
  201542. case 2:
  201543. {
  201544. png_bytep sp;
  201545. png_bytep dp;
  201546. int shift;
  201547. int d;
  201548. int value;
  201549. png_uint_32 i;
  201550. png_uint_32 row_width = row_info->width;
  201551. dp = row;
  201552. shift = 6;
  201553. d = 0;
  201554. for (i = png_pass_start[pass]; i < row_width;
  201555. i += png_pass_inc[pass])
  201556. {
  201557. sp = row + (png_size_t)(i >> 2);
  201558. value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
  201559. d |= (value << shift);
  201560. if (shift == 0)
  201561. {
  201562. shift = 6;
  201563. *dp++ = (png_byte)d;
  201564. d = 0;
  201565. }
  201566. else
  201567. shift -= 2;
  201568. }
  201569. if (shift != 6)
  201570. *dp = (png_byte)d;
  201571. break;
  201572. }
  201573. case 4:
  201574. {
  201575. png_bytep sp;
  201576. png_bytep dp;
  201577. int shift;
  201578. int d;
  201579. int value;
  201580. png_uint_32 i;
  201581. png_uint_32 row_width = row_info->width;
  201582. dp = row;
  201583. shift = 4;
  201584. d = 0;
  201585. for (i = png_pass_start[pass]; i < row_width;
  201586. i += png_pass_inc[pass])
  201587. {
  201588. sp = row + (png_size_t)(i >> 1);
  201589. value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
  201590. d |= (value << shift);
  201591. if (shift == 0)
  201592. {
  201593. shift = 4;
  201594. *dp++ = (png_byte)d;
  201595. d = 0;
  201596. }
  201597. else
  201598. shift -= 4;
  201599. }
  201600. if (shift != 4)
  201601. *dp = (png_byte)d;
  201602. break;
  201603. }
  201604. default:
  201605. {
  201606. png_bytep sp;
  201607. png_bytep dp;
  201608. png_uint_32 i;
  201609. png_uint_32 row_width = row_info->width;
  201610. png_size_t pixel_bytes;
  201611. /* start at the beginning */
  201612. dp = row;
  201613. /* find out how many bytes each pixel takes up */
  201614. pixel_bytes = (row_info->pixel_depth >> 3);
  201615. /* loop through the row, only looking at the pixels that
  201616. matter */
  201617. for (i = png_pass_start[pass]; i < row_width;
  201618. i += png_pass_inc[pass])
  201619. {
  201620. /* find out where the original pixel is */
  201621. sp = row + (png_size_t)i * pixel_bytes;
  201622. /* move the pixel */
  201623. if (dp != sp)
  201624. png_memcpy(dp, sp, pixel_bytes);
  201625. /* next pixel */
  201626. dp += pixel_bytes;
  201627. }
  201628. break;
  201629. }
  201630. }
  201631. /* set new row width */
  201632. row_info->width = (row_info->width +
  201633. png_pass_inc[pass] - 1 -
  201634. png_pass_start[pass]) /
  201635. png_pass_inc[pass];
  201636. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  201637. row_info->width);
  201638. }
  201639. }
  201640. #endif
  201641. /* This filters the row, chooses which filter to use, if it has not already
  201642. * been specified by the application, and then writes the row out with the
  201643. * chosen filter.
  201644. */
  201645. #define PNG_MAXSUM (((png_uint_32)(-1)) >> 1)
  201646. #define PNG_HISHIFT 10
  201647. #define PNG_LOMASK ((png_uint_32)0xffffL)
  201648. #define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT))
  201649. void /* PRIVATE */
  201650. png_write_find_filter(png_structp png_ptr, png_row_infop row_info)
  201651. {
  201652. png_bytep best_row;
  201653. #ifndef PNG_NO_WRITE_FILTER
  201654. png_bytep prev_row, row_buf;
  201655. png_uint_32 mins, bpp;
  201656. png_byte filter_to_do = png_ptr->do_filter;
  201657. png_uint_32 row_bytes = row_info->rowbytes;
  201658. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  201659. int num_p_filters = (int)png_ptr->num_prev_filters;
  201660. #endif
  201661. png_debug(1, "in png_write_find_filter\n");
  201662. /* find out how many bytes offset each pixel is */
  201663. bpp = (row_info->pixel_depth + 7) >> 3;
  201664. prev_row = png_ptr->prev_row;
  201665. #endif
  201666. best_row = png_ptr->row_buf;
  201667. #ifndef PNG_NO_WRITE_FILTER
  201668. row_buf = best_row;
  201669. mins = PNG_MAXSUM;
  201670. /* The prediction method we use is to find which method provides the
  201671. * smallest value when summing the absolute values of the distances
  201672. * from zero, using anything >= 128 as negative numbers. This is known
  201673. * as the "minimum sum of absolute differences" heuristic. Other
  201674. * heuristics are the "weighted minimum sum of absolute differences"
  201675. * (experimental and can in theory improve compression), and the "zlib
  201676. * predictive" method (not implemented yet), which does test compressions
  201677. * of lines using different filter methods, and then chooses the
  201678. * (series of) filter(s) that give minimum compressed data size (VERY
  201679. * computationally expensive).
  201680. *
  201681. * GRR 980525: consider also
  201682. * (1) minimum sum of absolute differences from running average (i.e.,
  201683. * keep running sum of non-absolute differences & count of bytes)
  201684. * [track dispersion, too? restart average if dispersion too large?]
  201685. * (1b) minimum sum of absolute differences from sliding average, probably
  201686. * with window size <= deflate window (usually 32K)
  201687. * (2) minimum sum of squared differences from zero or running average
  201688. * (i.e., ~ root-mean-square approach)
  201689. */
  201690. /* We don't need to test the 'no filter' case if this is the only filter
  201691. * that has been chosen, as it doesn't actually do anything to the data.
  201692. */
  201693. if ((filter_to_do & PNG_FILTER_NONE) &&
  201694. filter_to_do != PNG_FILTER_NONE)
  201695. {
  201696. png_bytep rp;
  201697. png_uint_32 sum = 0;
  201698. png_uint_32 i;
  201699. int v;
  201700. for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
  201701. {
  201702. v = *rp;
  201703. sum += (v < 128) ? v : 256 - v;
  201704. }
  201705. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  201706. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  201707. {
  201708. png_uint_32 sumhi, sumlo;
  201709. int j;
  201710. sumlo = sum & PNG_LOMASK;
  201711. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; /* Gives us some footroom */
  201712. /* Reduce the sum if we match any of the previous rows */
  201713. for (j = 0; j < num_p_filters; j++)
  201714. {
  201715. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  201716. {
  201717. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  201718. PNG_WEIGHT_SHIFT;
  201719. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  201720. PNG_WEIGHT_SHIFT;
  201721. }
  201722. }
  201723. /* Factor in the cost of this filter (this is here for completeness,
  201724. * but it makes no sense to have a "cost" for the NONE filter, as
  201725. * it has the minimum possible computational cost - none).
  201726. */
  201727. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  201728. PNG_COST_SHIFT;
  201729. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  201730. PNG_COST_SHIFT;
  201731. if (sumhi > PNG_HIMASK)
  201732. sum = PNG_MAXSUM;
  201733. else
  201734. sum = (sumhi << PNG_HISHIFT) + sumlo;
  201735. }
  201736. #endif
  201737. mins = sum;
  201738. }
  201739. /* sub filter */
  201740. if (filter_to_do == PNG_FILTER_SUB)
  201741. /* it's the only filter so no testing is needed */
  201742. {
  201743. png_bytep rp, lp, dp;
  201744. png_uint_32 i;
  201745. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  201746. i++, rp++, dp++)
  201747. {
  201748. *dp = *rp;
  201749. }
  201750. for (lp = row_buf + 1; i < row_bytes;
  201751. i++, rp++, lp++, dp++)
  201752. {
  201753. *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  201754. }
  201755. best_row = png_ptr->sub_row;
  201756. }
  201757. else if (filter_to_do & PNG_FILTER_SUB)
  201758. {
  201759. png_bytep rp, dp, lp;
  201760. png_uint_32 sum = 0, lmins = mins;
  201761. png_uint_32 i;
  201762. int v;
  201763. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  201764. /* We temporarily increase the "minimum sum" by the factor we
  201765. * would reduce the sum of this filter, so that we can do the
  201766. * early exit comparison without scaling the sum each time.
  201767. */
  201768. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  201769. {
  201770. int j;
  201771. png_uint_32 lmhi, lmlo;
  201772. lmlo = lmins & PNG_LOMASK;
  201773. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  201774. for (j = 0; j < num_p_filters; j++)
  201775. {
  201776. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  201777. {
  201778. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  201779. PNG_WEIGHT_SHIFT;
  201780. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  201781. PNG_WEIGHT_SHIFT;
  201782. }
  201783. }
  201784. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  201785. PNG_COST_SHIFT;
  201786. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  201787. PNG_COST_SHIFT;
  201788. if (lmhi > PNG_HIMASK)
  201789. lmins = PNG_MAXSUM;
  201790. else
  201791. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  201792. }
  201793. #endif
  201794. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  201795. i++, rp++, dp++)
  201796. {
  201797. v = *dp = *rp;
  201798. sum += (v < 128) ? v : 256 - v;
  201799. }
  201800. for (lp = row_buf + 1; i < row_bytes;
  201801. i++, rp++, lp++, dp++)
  201802. {
  201803. v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  201804. sum += (v < 128) ? v : 256 - v;
  201805. if (sum > lmins) /* We are already worse, don't continue. */
  201806. break;
  201807. }
  201808. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  201809. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  201810. {
  201811. int j;
  201812. png_uint_32 sumhi, sumlo;
  201813. sumlo = sum & PNG_LOMASK;
  201814. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  201815. for (j = 0; j < num_p_filters; j++)
  201816. {
  201817. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  201818. {
  201819. sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >>
  201820. PNG_WEIGHT_SHIFT;
  201821. sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >>
  201822. PNG_WEIGHT_SHIFT;
  201823. }
  201824. }
  201825. sumlo = (sumlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  201826. PNG_COST_SHIFT;
  201827. sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  201828. PNG_COST_SHIFT;
  201829. if (sumhi > PNG_HIMASK)
  201830. sum = PNG_MAXSUM;
  201831. else
  201832. sum = (sumhi << PNG_HISHIFT) + sumlo;
  201833. }
  201834. #endif
  201835. if (sum < mins)
  201836. {
  201837. mins = sum;
  201838. best_row = png_ptr->sub_row;
  201839. }
  201840. }
  201841. /* up filter */
  201842. if (filter_to_do == PNG_FILTER_UP)
  201843. {
  201844. png_bytep rp, dp, pp;
  201845. png_uint_32 i;
  201846. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  201847. pp = prev_row + 1; i < row_bytes;
  201848. i++, rp++, pp++, dp++)
  201849. {
  201850. *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
  201851. }
  201852. best_row = png_ptr->up_row;
  201853. }
  201854. else if (filter_to_do & PNG_FILTER_UP)
  201855. {
  201856. png_bytep rp, dp, pp;
  201857. png_uint_32 sum = 0, lmins = mins;
  201858. png_uint_32 i;
  201859. int v;
  201860. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  201861. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  201862. {
  201863. int j;
  201864. png_uint_32 lmhi, lmlo;
  201865. lmlo = lmins & PNG_LOMASK;
  201866. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  201867. for (j = 0; j < num_p_filters; j++)
  201868. {
  201869. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  201870. {
  201871. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  201872. PNG_WEIGHT_SHIFT;
  201873. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  201874. PNG_WEIGHT_SHIFT;
  201875. }
  201876. }
  201877. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  201878. PNG_COST_SHIFT;
  201879. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  201880. PNG_COST_SHIFT;
  201881. if (lmhi > PNG_HIMASK)
  201882. lmins = PNG_MAXSUM;
  201883. else
  201884. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  201885. }
  201886. #endif
  201887. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  201888. pp = prev_row + 1; i < row_bytes; i++)
  201889. {
  201890. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  201891. sum += (v < 128) ? v : 256 - v;
  201892. if (sum > lmins) /* We are already worse, don't continue. */
  201893. break;
  201894. }
  201895. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  201896. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  201897. {
  201898. int j;
  201899. png_uint_32 sumhi, sumlo;
  201900. sumlo = sum & PNG_LOMASK;
  201901. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  201902. for (j = 0; j < num_p_filters; j++)
  201903. {
  201904. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  201905. {
  201906. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  201907. PNG_WEIGHT_SHIFT;
  201908. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  201909. PNG_WEIGHT_SHIFT;
  201910. }
  201911. }
  201912. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  201913. PNG_COST_SHIFT;
  201914. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  201915. PNG_COST_SHIFT;
  201916. if (sumhi > PNG_HIMASK)
  201917. sum = PNG_MAXSUM;
  201918. else
  201919. sum = (sumhi << PNG_HISHIFT) + sumlo;
  201920. }
  201921. #endif
  201922. if (sum < mins)
  201923. {
  201924. mins = sum;
  201925. best_row = png_ptr->up_row;
  201926. }
  201927. }
  201928. /* avg filter */
  201929. if (filter_to_do == PNG_FILTER_AVG)
  201930. {
  201931. png_bytep rp, dp, pp, lp;
  201932. png_uint_32 i;
  201933. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  201934. pp = prev_row + 1; i < bpp; i++)
  201935. {
  201936. *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  201937. }
  201938. for (lp = row_buf + 1; i < row_bytes; i++)
  201939. {
  201940. *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
  201941. & 0xff);
  201942. }
  201943. best_row = png_ptr->avg_row;
  201944. }
  201945. else if (filter_to_do & PNG_FILTER_AVG)
  201946. {
  201947. png_bytep rp, dp, pp, lp;
  201948. png_uint_32 sum = 0, lmins = mins;
  201949. png_uint_32 i;
  201950. int v;
  201951. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  201952. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  201953. {
  201954. int j;
  201955. png_uint_32 lmhi, lmlo;
  201956. lmlo = lmins & PNG_LOMASK;
  201957. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  201958. for (j = 0; j < num_p_filters; j++)
  201959. {
  201960. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_AVG)
  201961. {
  201962. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  201963. PNG_WEIGHT_SHIFT;
  201964. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  201965. PNG_WEIGHT_SHIFT;
  201966. }
  201967. }
  201968. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  201969. PNG_COST_SHIFT;
  201970. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  201971. PNG_COST_SHIFT;
  201972. if (lmhi > PNG_HIMASK)
  201973. lmins = PNG_MAXSUM;
  201974. else
  201975. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  201976. }
  201977. #endif
  201978. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  201979. pp = prev_row + 1; i < bpp; i++)
  201980. {
  201981. v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  201982. sum += (v < 128) ? v : 256 - v;
  201983. }
  201984. for (lp = row_buf + 1; i < row_bytes; i++)
  201985. {
  201986. v = *dp++ =
  201987. (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff);
  201988. sum += (v < 128) ? v : 256 - v;
  201989. if (sum > lmins) /* We are already worse, don't continue. */
  201990. break;
  201991. }
  201992. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  201993. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  201994. {
  201995. int j;
  201996. png_uint_32 sumhi, sumlo;
  201997. sumlo = sum & PNG_LOMASK;
  201998. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  201999. for (j = 0; j < num_p_filters; j++)
  202000. {
  202001. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  202002. {
  202003. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202004. PNG_WEIGHT_SHIFT;
  202005. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202006. PNG_WEIGHT_SHIFT;
  202007. }
  202008. }
  202009. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202010. PNG_COST_SHIFT;
  202011. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202012. PNG_COST_SHIFT;
  202013. if (sumhi > PNG_HIMASK)
  202014. sum = PNG_MAXSUM;
  202015. else
  202016. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202017. }
  202018. #endif
  202019. if (sum < mins)
  202020. {
  202021. mins = sum;
  202022. best_row = png_ptr->avg_row;
  202023. }
  202024. }
  202025. /* Paeth filter */
  202026. if (filter_to_do == PNG_FILTER_PAETH)
  202027. {
  202028. png_bytep rp, dp, pp, cp, lp;
  202029. png_uint_32 i;
  202030. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  202031. pp = prev_row + 1; i < bpp; i++)
  202032. {
  202033. *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202034. }
  202035. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  202036. {
  202037. int a, b, c, pa, pb, pc, p;
  202038. b = *pp++;
  202039. c = *cp++;
  202040. a = *lp++;
  202041. p = b - c;
  202042. pc = a - c;
  202043. #ifdef PNG_USE_ABS
  202044. pa = abs(p);
  202045. pb = abs(pc);
  202046. pc = abs(p + pc);
  202047. #else
  202048. pa = p < 0 ? -p : p;
  202049. pb = pc < 0 ? -pc : pc;
  202050. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  202051. #endif
  202052. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  202053. *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  202054. }
  202055. best_row = png_ptr->paeth_row;
  202056. }
  202057. else if (filter_to_do & PNG_FILTER_PAETH)
  202058. {
  202059. png_bytep rp, dp, pp, cp, lp;
  202060. png_uint_32 sum = 0, lmins = mins;
  202061. png_uint_32 i;
  202062. int v;
  202063. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202064. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202065. {
  202066. int j;
  202067. png_uint_32 lmhi, lmlo;
  202068. lmlo = lmins & PNG_LOMASK;
  202069. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202070. for (j = 0; j < num_p_filters; j++)
  202071. {
  202072. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  202073. {
  202074. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202075. PNG_WEIGHT_SHIFT;
  202076. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202077. PNG_WEIGHT_SHIFT;
  202078. }
  202079. }
  202080. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202081. PNG_COST_SHIFT;
  202082. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202083. PNG_COST_SHIFT;
  202084. if (lmhi > PNG_HIMASK)
  202085. lmins = PNG_MAXSUM;
  202086. else
  202087. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202088. }
  202089. #endif
  202090. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  202091. pp = prev_row + 1; i < bpp; i++)
  202092. {
  202093. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202094. sum += (v < 128) ? v : 256 - v;
  202095. }
  202096. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  202097. {
  202098. int a, b, c, pa, pb, pc, p;
  202099. b = *pp++;
  202100. c = *cp++;
  202101. a = *lp++;
  202102. #ifndef PNG_SLOW_PAETH
  202103. p = b - c;
  202104. pc = a - c;
  202105. #ifdef PNG_USE_ABS
  202106. pa = abs(p);
  202107. pb = abs(pc);
  202108. pc = abs(p + pc);
  202109. #else
  202110. pa = p < 0 ? -p : p;
  202111. pb = pc < 0 ? -pc : pc;
  202112. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  202113. #endif
  202114. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  202115. #else /* PNG_SLOW_PAETH */
  202116. p = a + b - c;
  202117. pa = abs(p - a);
  202118. pb = abs(p - b);
  202119. pc = abs(p - c);
  202120. if (pa <= pb && pa <= pc)
  202121. p = a;
  202122. else if (pb <= pc)
  202123. p = b;
  202124. else
  202125. p = c;
  202126. #endif /* PNG_SLOW_PAETH */
  202127. v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  202128. sum += (v < 128) ? v : 256 - v;
  202129. if (sum > lmins) /* We are already worse, don't continue. */
  202130. break;
  202131. }
  202132. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202133. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202134. {
  202135. int j;
  202136. png_uint_32 sumhi, sumlo;
  202137. sumlo = sum & PNG_LOMASK;
  202138. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202139. for (j = 0; j < num_p_filters; j++)
  202140. {
  202141. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  202142. {
  202143. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202144. PNG_WEIGHT_SHIFT;
  202145. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202146. PNG_WEIGHT_SHIFT;
  202147. }
  202148. }
  202149. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202150. PNG_COST_SHIFT;
  202151. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202152. PNG_COST_SHIFT;
  202153. if (sumhi > PNG_HIMASK)
  202154. sum = PNG_MAXSUM;
  202155. else
  202156. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202157. }
  202158. #endif
  202159. if (sum < mins)
  202160. {
  202161. best_row = png_ptr->paeth_row;
  202162. }
  202163. }
  202164. #endif /* PNG_NO_WRITE_FILTER */
  202165. /* Do the actual writing of the filtered row data from the chosen filter. */
  202166. png_write_filtered_row(png_ptr, best_row);
  202167. #ifndef PNG_NO_WRITE_FILTER
  202168. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202169. /* Save the type of filter we picked this time for future calculations */
  202170. if (png_ptr->num_prev_filters > 0)
  202171. {
  202172. int j;
  202173. for (j = 1; j < num_p_filters; j++)
  202174. {
  202175. png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1];
  202176. }
  202177. png_ptr->prev_filters[j] = best_row[0];
  202178. }
  202179. #endif
  202180. #endif /* PNG_NO_WRITE_FILTER */
  202181. }
  202182. /* Do the actual writing of a previously filtered row. */
  202183. void /* PRIVATE */
  202184. png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row)
  202185. {
  202186. png_debug(1, "in png_write_filtered_row\n");
  202187. png_debug1(2, "filter = %d\n", filtered_row[0]);
  202188. /* set up the zlib input buffer */
  202189. png_ptr->zstream.next_in = filtered_row;
  202190. png_ptr->zstream.avail_in = (uInt)png_ptr->row_info.rowbytes + 1;
  202191. /* repeat until we have compressed all the data */
  202192. do
  202193. {
  202194. int ret; /* return of zlib */
  202195. /* compress the data */
  202196. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  202197. /* check for compression errors */
  202198. if (ret != Z_OK)
  202199. {
  202200. if (png_ptr->zstream.msg != NULL)
  202201. png_error(png_ptr, png_ptr->zstream.msg);
  202202. else
  202203. png_error(png_ptr, "zlib error");
  202204. }
  202205. /* see if it is time to write another IDAT */
  202206. if (!(png_ptr->zstream.avail_out))
  202207. {
  202208. /* write the IDAT and reset the zlib output buffer */
  202209. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  202210. png_ptr->zstream.next_out = png_ptr->zbuf;
  202211. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  202212. }
  202213. /* repeat until all data has been compressed */
  202214. } while (png_ptr->zstream.avail_in);
  202215. /* swap the current and previous rows */
  202216. if (png_ptr->prev_row != NULL)
  202217. {
  202218. png_bytep tptr;
  202219. tptr = png_ptr->prev_row;
  202220. png_ptr->prev_row = png_ptr->row_buf;
  202221. png_ptr->row_buf = tptr;
  202222. }
  202223. /* finish row - updates counters and flushes zlib if last row */
  202224. png_write_finish_row(png_ptr);
  202225. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  202226. png_ptr->flush_rows++;
  202227. if (png_ptr->flush_dist > 0 &&
  202228. png_ptr->flush_rows >= png_ptr->flush_dist)
  202229. {
  202230. png_write_flush(png_ptr);
  202231. }
  202232. #endif
  202233. }
  202234. #endif /* PNG_WRITE_SUPPORTED */
  202235. /*** End of inlined file: pngwutil.c ***/
  202236. }
  202237. #else
  202238. extern "C"
  202239. {
  202240. #include <png.h>
  202241. #include <pngconf.h>
  202242. }
  202243. #endif
  202244. }
  202245. #undef max
  202246. #undef min
  202247. #if JUCE_MSVC
  202248. #pragma warning (pop)
  202249. #endif
  202250. BEGIN_JUCE_NAMESPACE
  202251. using ::calloc;
  202252. using ::malloc;
  202253. using ::free;
  202254. namespace PNGHelpers
  202255. {
  202256. using namespace pnglibNamespace;
  202257. static void readCallback (png_structp png, png_bytep data, png_size_t length)
  202258. {
  202259. static_cast<InputStream*> (png_get_io_ptr (png))->read (data, (int) length);
  202260. }
  202261. static void writeDataCallback (png_structp png, png_bytep data, png_size_t length)
  202262. {
  202263. static_cast<OutputStream*> (png_get_io_ptr (png))->write (data, (int) length);
  202264. }
  202265. struct PNGErrorStruct {};
  202266. static void errorCallback (png_structp, png_const_charp)
  202267. {
  202268. throw PNGErrorStruct();
  202269. }
  202270. }
  202271. PNGImageFormat::PNGImageFormat() {}
  202272. PNGImageFormat::~PNGImageFormat() {}
  202273. const String PNGImageFormat::getFormatName()
  202274. {
  202275. return "PNG";
  202276. }
  202277. bool PNGImageFormat::canUnderstand (InputStream& in)
  202278. {
  202279. const int bytesNeeded = 4;
  202280. char header [bytesNeeded];
  202281. return in.read (header, bytesNeeded) == bytesNeeded
  202282. && header[1] == 'P'
  202283. && header[2] == 'N'
  202284. && header[3] == 'G';
  202285. }
  202286. const Image PNGImageFormat::decodeImage (InputStream& in)
  202287. {
  202288. using namespace pnglibNamespace;
  202289. Image image;
  202290. png_structp pngReadStruct;
  202291. png_infop pngInfoStruct;
  202292. pngReadStruct = png_create_read_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  202293. if (pngReadStruct != 0)
  202294. {
  202295. pngInfoStruct = png_create_info_struct (pngReadStruct);
  202296. if (pngInfoStruct == 0)
  202297. {
  202298. png_destroy_read_struct (&pngReadStruct, 0, 0);
  202299. return Image();
  202300. }
  202301. png_set_error_fn (pngReadStruct, 0, PNGHelpers::errorCallback, PNGHelpers::errorCallback );
  202302. // read the header..
  202303. png_set_read_fn (pngReadStruct, &in, PNGHelpers::readCallback);
  202304. png_uint_32 width, height;
  202305. int bitDepth, colorType, interlaceType;
  202306. png_read_info (pngReadStruct, pngInfoStruct);
  202307. png_get_IHDR (pngReadStruct, pngInfoStruct,
  202308. &width, &height,
  202309. &bitDepth, &colorType,
  202310. &interlaceType, 0, 0);
  202311. if (bitDepth == 16)
  202312. png_set_strip_16 (pngReadStruct);
  202313. if (colorType == PNG_COLOR_TYPE_PALETTE)
  202314. png_set_expand (pngReadStruct);
  202315. if (bitDepth < 8)
  202316. png_set_expand (pngReadStruct);
  202317. if (png_get_valid (pngReadStruct, pngInfoStruct, PNG_INFO_tRNS))
  202318. png_set_expand (pngReadStruct);
  202319. if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA)
  202320. png_set_gray_to_rgb (pngReadStruct);
  202321. png_set_add_alpha (pngReadStruct, 0xff, PNG_FILLER_AFTER);
  202322. bool hasAlphaChan = (colorType & PNG_COLOR_MASK_ALPHA) != 0
  202323. || pngInfoStruct->num_trans > 0;
  202324. // Load the image into a temp buffer in the pnglib format..
  202325. HeapBlock <uint8> tempBuffer (height * (width << 2));
  202326. {
  202327. HeapBlock <png_bytep> rows (height);
  202328. for (int y = (int) height; --y >= 0;)
  202329. rows[y] = (png_bytep) (tempBuffer + (width << 2) * y);
  202330. png_read_image (pngReadStruct, rows);
  202331. png_read_end (pngReadStruct, pngInfoStruct);
  202332. }
  202333. png_destroy_read_struct (&pngReadStruct, &pngInfoStruct, 0);
  202334. // now convert the data to a juce image format..
  202335. image = Image (hasAlphaChan ? Image::ARGB : Image::RGB,
  202336. (int) width, (int) height, hasAlphaChan);
  202337. hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  202338. const Image::BitmapData destData (image, 0, 0, (int) width, (int) height, true);
  202339. uint8* srcRow = tempBuffer;
  202340. uint8* destRow = destData.data;
  202341. for (int y = 0; y < (int) height; ++y)
  202342. {
  202343. const uint8* src = srcRow;
  202344. srcRow += (width << 2);
  202345. uint8* dest = destRow;
  202346. destRow += destData.lineStride;
  202347. if (hasAlphaChan)
  202348. {
  202349. for (int i = (int) width; --i >= 0;)
  202350. {
  202351. ((PixelARGB*) dest)->setARGB (src[3], src[0], src[1], src[2]);
  202352. ((PixelARGB*) dest)->premultiply();
  202353. dest += destData.pixelStride;
  202354. src += 4;
  202355. }
  202356. }
  202357. else
  202358. {
  202359. for (int i = (int) width; --i >= 0;)
  202360. {
  202361. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  202362. dest += destData.pixelStride;
  202363. src += 4;
  202364. }
  202365. }
  202366. }
  202367. }
  202368. return image;
  202369. }
  202370. bool PNGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  202371. {
  202372. using namespace pnglibNamespace;
  202373. const int width = image.getWidth();
  202374. const int height = image.getHeight();
  202375. png_structp pngWriteStruct = png_create_write_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  202376. if (pngWriteStruct == 0)
  202377. return false;
  202378. png_infop pngInfoStruct = png_create_info_struct (pngWriteStruct);
  202379. if (pngInfoStruct == 0)
  202380. {
  202381. png_destroy_write_struct (&pngWriteStruct, (png_infopp) 0);
  202382. return false;
  202383. }
  202384. png_set_write_fn (pngWriteStruct, &out, PNGHelpers::writeDataCallback, 0);
  202385. png_set_IHDR (pngWriteStruct, pngInfoStruct, width, height, 8,
  202386. image.hasAlphaChannel() ? PNG_COLOR_TYPE_RGB_ALPHA
  202387. : PNG_COLOR_TYPE_RGB,
  202388. PNG_INTERLACE_NONE,
  202389. PNG_COMPRESSION_TYPE_BASE,
  202390. PNG_FILTER_TYPE_BASE);
  202391. HeapBlock <uint8> rowData (width * 4);
  202392. png_color_8 sig_bit;
  202393. sig_bit.red = 8;
  202394. sig_bit.green = 8;
  202395. sig_bit.blue = 8;
  202396. sig_bit.alpha = 8;
  202397. png_set_sBIT (pngWriteStruct, pngInfoStruct, &sig_bit);
  202398. png_write_info (pngWriteStruct, pngInfoStruct);
  202399. png_set_shift (pngWriteStruct, &sig_bit);
  202400. png_set_packing (pngWriteStruct);
  202401. const Image::BitmapData srcData (image, 0, 0, width, height);
  202402. for (int y = 0; y < height; ++y)
  202403. {
  202404. uint8* dst = rowData;
  202405. const uint8* src = srcData.getLinePointer (y);
  202406. if (image.hasAlphaChannel())
  202407. {
  202408. for (int i = width; --i >= 0;)
  202409. {
  202410. PixelARGB p (*(const PixelARGB*) src);
  202411. p.unpremultiply();
  202412. *dst++ = p.getRed();
  202413. *dst++ = p.getGreen();
  202414. *dst++ = p.getBlue();
  202415. *dst++ = p.getAlpha();
  202416. src += srcData.pixelStride;
  202417. }
  202418. }
  202419. else
  202420. {
  202421. for (int i = width; --i >= 0;)
  202422. {
  202423. *dst++ = ((const PixelRGB*) src)->getRed();
  202424. *dst++ = ((const PixelRGB*) src)->getGreen();
  202425. *dst++ = ((const PixelRGB*) src)->getBlue();
  202426. src += srcData.pixelStride;
  202427. }
  202428. }
  202429. png_write_rows (pngWriteStruct, &rowData, 1);
  202430. }
  202431. png_write_end (pngWriteStruct, pngInfoStruct);
  202432. png_destroy_write_struct (&pngWriteStruct, &pngInfoStruct);
  202433. out.flush();
  202434. return true;
  202435. }
  202436. END_JUCE_NAMESPACE
  202437. /*** End of inlined file: juce_PNGLoader.cpp ***/
  202438. #endif
  202439. //==============================================================================
  202440. #if JUCE_BUILD_NATIVE
  202441. #if JUCE_WINDOWS
  202442. /*** Start of inlined file: juce_win32_NativeCode.cpp ***/
  202443. /*
  202444. This file wraps together all the win32-specific code, so that
  202445. we can include all the native headers just once, and compile all our
  202446. platform-specific stuff in one big lump, keeping it out of the way of
  202447. the rest of the codebase.
  202448. */
  202449. #if JUCE_WINDOWS
  202450. BEGIN_JUCE_NAMESPACE
  202451. #define JUCE_INCLUDED_FILE 1
  202452. // Now include the actual code files..
  202453. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  202454. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  202455. // compiled on its own).
  202456. #if JUCE_INCLUDED_FILE
  202457. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  202458. #ifndef __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  202459. #define __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  202460. #ifndef DOXYGEN
  202461. // use with DynamicLibraryLoader to simplify importing functions
  202462. //
  202463. // functionName: function to import
  202464. // localFunctionName: name you want to use to actually call it (must be different)
  202465. // returnType: the return type
  202466. // object: the DynamicLibraryLoader to use
  202467. // params: list of params (bracketed)
  202468. //
  202469. #define DynamicLibraryImport(functionName, localFunctionName, returnType, object, params) \
  202470. typedef returnType (WINAPI *type##localFunctionName) params; \
  202471. type##localFunctionName localFunctionName \
  202472. = (type##localFunctionName)object.findProcAddress (#functionName);
  202473. // loads and unloads a DLL automatically
  202474. class JUCE_API DynamicLibraryLoader
  202475. {
  202476. public:
  202477. DynamicLibraryLoader (const String& name);
  202478. ~DynamicLibraryLoader();
  202479. void* findProcAddress (const String& functionName);
  202480. private:
  202481. void* libHandle;
  202482. };
  202483. #endif
  202484. #endif // __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  202485. /*** End of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  202486. DynamicLibraryLoader::DynamicLibraryLoader (const String& name)
  202487. {
  202488. libHandle = LoadLibrary (name);
  202489. }
  202490. DynamicLibraryLoader::~DynamicLibraryLoader()
  202491. {
  202492. FreeLibrary ((HMODULE) libHandle);
  202493. }
  202494. void* DynamicLibraryLoader::findProcAddress (const String& functionName)
  202495. {
  202496. return GetProcAddress ((HMODULE) libHandle, functionName.toCString());
  202497. }
  202498. #endif
  202499. /*** End of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  202500. /*** Start of inlined file: juce_win32_SystemStats.cpp ***/
  202501. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  202502. // compiled on its own).
  202503. #if JUCE_INCLUDED_FILE
  202504. extern void juce_initialiseThreadEvents();
  202505. void Logger::outputDebugString (const String& text)
  202506. {
  202507. OutputDebugString (text + "\n");
  202508. }
  202509. static int64 hiResTicksPerSecond;
  202510. static double hiResTicksScaleFactor;
  202511. #if JUCE_USE_INTRINSICS
  202512. // CPU info functions using intrinsics...
  202513. #pragma intrinsic (__cpuid)
  202514. #pragma intrinsic (__rdtsc)
  202515. const String SystemStats::getCpuVendor()
  202516. {
  202517. int info [4];
  202518. __cpuid (info, 0);
  202519. char v [12];
  202520. memcpy (v, info + 1, 4);
  202521. memcpy (v + 4, info + 3, 4);
  202522. memcpy (v + 8, info + 2, 4);
  202523. return String (v, 12);
  202524. }
  202525. #else
  202526. // CPU info functions using old fashioned inline asm...
  202527. static void juce_getCpuVendor (char* const v)
  202528. {
  202529. int vendor[4];
  202530. zeromem (vendor, 16);
  202531. #ifdef JUCE_64BIT
  202532. #else
  202533. #ifndef __MINGW32__
  202534. __try
  202535. #endif
  202536. {
  202537. #if JUCE_GCC
  202538. unsigned int dummy = 0;
  202539. __asm__ ("cpuid" : "=a" (dummy), "=b" (vendor[0]), "=c" (vendor[2]),"=d" (vendor[1]) : "a" (0));
  202540. #else
  202541. __asm
  202542. {
  202543. mov eax, 0
  202544. cpuid
  202545. mov [vendor], ebx
  202546. mov [vendor + 4], edx
  202547. mov [vendor + 8], ecx
  202548. }
  202549. #endif
  202550. }
  202551. #ifndef __MINGW32__
  202552. __except (EXCEPTION_EXECUTE_HANDLER)
  202553. {
  202554. *v = 0;
  202555. }
  202556. #endif
  202557. #endif
  202558. memcpy (v, vendor, 16);
  202559. }
  202560. const String SystemStats::getCpuVendor()
  202561. {
  202562. char v [16];
  202563. juce_getCpuVendor (v);
  202564. return String (v, 16);
  202565. }
  202566. #endif
  202567. void SystemStats::initialiseStats()
  202568. {
  202569. juce_initialiseThreadEvents();
  202570. cpuFlags.hasMMX = IsProcessorFeaturePresent (PF_MMX_INSTRUCTIONS_AVAILABLE) != 0;
  202571. cpuFlags.hasSSE = IsProcessorFeaturePresent (PF_XMMI_INSTRUCTIONS_AVAILABLE) != 0;
  202572. cpuFlags.hasSSE2 = IsProcessorFeaturePresent (PF_XMMI64_INSTRUCTIONS_AVAILABLE) != 0;
  202573. #ifdef PF_AMD3D_INSTRUCTIONS_AVAILABLE
  202574. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_AMD3D_INSTRUCTIONS_AVAILABLE) != 0;
  202575. #else
  202576. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_3DNOW_INSTRUCTIONS_AVAILABLE) != 0;
  202577. #endif
  202578. {
  202579. SYSTEM_INFO systemInfo;
  202580. GetSystemInfo (&systemInfo);
  202581. cpuFlags.numCpus = systemInfo.dwNumberOfProcessors;
  202582. }
  202583. LARGE_INTEGER f;
  202584. QueryPerformanceFrequency (&f);
  202585. hiResTicksPerSecond = f.QuadPart;
  202586. hiResTicksScaleFactor = 1000.0 / hiResTicksPerSecond;
  202587. String s (SystemStats::getJUCEVersion());
  202588. const MMRESULT res = timeBeginPeriod (1);
  202589. (void) res;
  202590. jassert (res == TIMERR_NOERROR);
  202591. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  202592. _CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
  202593. #endif
  202594. }
  202595. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  202596. {
  202597. OSVERSIONINFO info;
  202598. info.dwOSVersionInfoSize = sizeof (info);
  202599. GetVersionEx (&info);
  202600. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  202601. {
  202602. switch (info.dwMajorVersion)
  202603. {
  202604. case 5: return (info.dwMinorVersion == 0) ? Win2000 : WinXP;
  202605. case 6: return (info.dwMinorVersion == 0) ? WinVista : Windows7;
  202606. default: jassertfalse; break; // !! not a supported OS!
  202607. }
  202608. }
  202609. else if (info.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
  202610. {
  202611. jassert (info.dwMinorVersion != 0); // !! still running on Windows 95??
  202612. return Win98;
  202613. }
  202614. return UnknownOS;
  202615. }
  202616. const String SystemStats::getOperatingSystemName()
  202617. {
  202618. const char* name = "Unknown OS";
  202619. switch (getOperatingSystemType())
  202620. {
  202621. case Windows7: name = "Windows 7"; break;
  202622. case WinVista: name = "Windows Vista"; break;
  202623. case WinXP: name = "Windows XP"; break;
  202624. case Win2000: name = "Windows 2000"; break;
  202625. case Win98: name = "Windows 98"; break;
  202626. default: jassertfalse; break; // !! new type of OS?
  202627. }
  202628. return name;
  202629. }
  202630. bool SystemStats::isOperatingSystem64Bit()
  202631. {
  202632. #ifdef _WIN64
  202633. return true;
  202634. #else
  202635. typedef BOOL (WINAPI* LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
  202636. LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle (L"kernel32"), "IsWow64Process");
  202637. BOOL isWow64 = FALSE;
  202638. return (fnIsWow64Process != 0)
  202639. && fnIsWow64Process (GetCurrentProcess(), &isWow64)
  202640. && (isWow64 != FALSE);
  202641. #endif
  202642. }
  202643. int SystemStats::getMemorySizeInMegabytes()
  202644. {
  202645. MEMORYSTATUSEX mem;
  202646. mem.dwLength = sizeof (mem);
  202647. GlobalMemoryStatusEx (&mem);
  202648. return (int) (mem.ullTotalPhys / (1024 * 1024)) + 1;
  202649. }
  202650. uint32 juce_millisecondsSinceStartup() throw()
  202651. {
  202652. return (uint32) GetTickCount();
  202653. }
  202654. int64 Time::getHighResolutionTicks() throw()
  202655. {
  202656. LARGE_INTEGER ticks;
  202657. QueryPerformanceCounter (&ticks);
  202658. const int64 mainCounterAsHiResTicks = (GetTickCount() * hiResTicksPerSecond) / 1000;
  202659. const int64 newOffset = mainCounterAsHiResTicks - ticks.QuadPart;
  202660. // fix for a very obscure PCI hardware bug that can make the counter
  202661. // sometimes jump forwards by a few seconds..
  202662. static int64 hiResTicksOffset = 0;
  202663. const int64 offsetDrift = abs64 (newOffset - hiResTicksOffset);
  202664. if (offsetDrift > (hiResTicksPerSecond >> 1))
  202665. hiResTicksOffset = newOffset;
  202666. return ticks.QuadPart + hiResTicksOffset;
  202667. }
  202668. double Time::getMillisecondCounterHiRes() throw()
  202669. {
  202670. return getHighResolutionTicks() * hiResTicksScaleFactor;
  202671. }
  202672. int64 Time::getHighResolutionTicksPerSecond() throw()
  202673. {
  202674. return hiResTicksPerSecond;
  202675. }
  202676. static int64 juce_getClockCycleCounter() throw()
  202677. {
  202678. #if JUCE_USE_INTRINSICS
  202679. // MS intrinsics version...
  202680. return __rdtsc();
  202681. #elif JUCE_GCC
  202682. // GNU inline asm version...
  202683. unsigned int hi = 0, lo = 0;
  202684. __asm__ __volatile__ (
  202685. "xor %%eax, %%eax \n\
  202686. xor %%edx, %%edx \n\
  202687. rdtsc \n\
  202688. movl %%eax, %[lo] \n\
  202689. movl %%edx, %[hi]"
  202690. :
  202691. : [hi] "m" (hi),
  202692. [lo] "m" (lo)
  202693. : "cc", "eax", "ebx", "ecx", "edx", "memory");
  202694. return (int64) ((((uint64) hi) << 32) | lo);
  202695. #else
  202696. // MSVC inline asm version...
  202697. unsigned int hi = 0, lo = 0;
  202698. __asm
  202699. {
  202700. xor eax, eax
  202701. xor edx, edx
  202702. rdtsc
  202703. mov lo, eax
  202704. mov hi, edx
  202705. }
  202706. return (int64) ((((uint64) hi) << 32) | lo);
  202707. #endif
  202708. }
  202709. int SystemStats::getCpuSpeedInMegaherz()
  202710. {
  202711. const int64 cycles = juce_getClockCycleCounter();
  202712. const uint32 millis = Time::getMillisecondCounter();
  202713. int lastResult = 0;
  202714. for (;;)
  202715. {
  202716. int n = 1000000;
  202717. while (--n > 0) {}
  202718. const uint32 millisElapsed = Time::getMillisecondCounter() - millis;
  202719. const int64 cyclesNow = juce_getClockCycleCounter();
  202720. if (millisElapsed > 80)
  202721. {
  202722. const int newResult = (int) (((cyclesNow - cycles) / millisElapsed) / 1000);
  202723. if (millisElapsed > 500 || (lastResult == newResult && newResult > 100))
  202724. return newResult;
  202725. lastResult = newResult;
  202726. }
  202727. }
  202728. }
  202729. bool Time::setSystemTimeToThisTime() const
  202730. {
  202731. SYSTEMTIME st;
  202732. st.wDayOfWeek = 0;
  202733. st.wYear = (WORD) getYear();
  202734. st.wMonth = (WORD) (getMonth() + 1);
  202735. st.wDay = (WORD) getDayOfMonth();
  202736. st.wHour = (WORD) getHours();
  202737. st.wMinute = (WORD) getMinutes();
  202738. st.wSecond = (WORD) getSeconds();
  202739. st.wMilliseconds = (WORD) (millisSinceEpoch % 1000);
  202740. // do this twice because of daylight saving conversion problems - the
  202741. // first one sets it up, the second one kicks it in.
  202742. return SetLocalTime (&st) != 0
  202743. && SetLocalTime (&st) != 0;
  202744. }
  202745. int SystemStats::getPageSize()
  202746. {
  202747. SYSTEM_INFO systemInfo;
  202748. GetSystemInfo (&systemInfo);
  202749. return systemInfo.dwPageSize;
  202750. }
  202751. const String SystemStats::getLogonName()
  202752. {
  202753. TCHAR text [256];
  202754. DWORD len = numElementsInArray (text) - 2;
  202755. zerostruct (text);
  202756. GetUserName (text, &len);
  202757. return String (text, len);
  202758. }
  202759. const String SystemStats::getFullUserName()
  202760. {
  202761. return getLogonName();
  202762. }
  202763. #endif
  202764. /*** End of inlined file: juce_win32_SystemStats.cpp ***/
  202765. /*** Start of inlined file: juce_win32_Threads.cpp ***/
  202766. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  202767. // compiled on its own).
  202768. #if JUCE_INCLUDED_FILE
  202769. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  202770. extern HWND juce_messageWindowHandle;
  202771. #endif
  202772. #if ! JUCE_USE_INTRINSICS
  202773. // In newer compilers, the inline versions of these are used (in juce_Atomic.h), but in
  202774. // older ones we have to actually call the ops as win32 functions..
  202775. long juce_InterlockedExchange (volatile long* a, long b) throw() { return InterlockedExchange (a, b); }
  202776. long juce_InterlockedIncrement (volatile long* a) throw() { return InterlockedIncrement (a); }
  202777. long juce_InterlockedDecrement (volatile long* a) throw() { return InterlockedDecrement (a); }
  202778. long juce_InterlockedExchangeAdd (volatile long* a, long b) throw() { return InterlockedExchangeAdd (a, b); }
  202779. long juce_InterlockedCompareExchange (volatile long* a, long b, long c) throw() { return InterlockedCompareExchange (a, b, c); }
  202780. __int64 juce_InterlockedCompareExchange64 (volatile __int64* value, __int64 newValue, __int64 valueToCompare) throw()
  202781. {
  202782. jassertfalse; // This operation isn't available in old MS compiler versions!
  202783. __int64 oldValue = *value;
  202784. if (oldValue == valueToCompare)
  202785. *value = newValue;
  202786. return oldValue;
  202787. }
  202788. #endif
  202789. CriticalSection::CriticalSection() throw()
  202790. {
  202791. // (just to check the MS haven't changed this structure and broken things...)
  202792. #if _MSC_VER >= 1400
  202793. static_jassert (sizeof (CRITICAL_SECTION) <= sizeof (internal));
  202794. #else
  202795. static_jassert (sizeof (CRITICAL_SECTION) <= 24);
  202796. #endif
  202797. InitializeCriticalSection ((CRITICAL_SECTION*) internal);
  202798. }
  202799. CriticalSection::~CriticalSection() throw()
  202800. {
  202801. DeleteCriticalSection ((CRITICAL_SECTION*) internal);
  202802. }
  202803. void CriticalSection::enter() const throw()
  202804. {
  202805. EnterCriticalSection ((CRITICAL_SECTION*) internal);
  202806. }
  202807. bool CriticalSection::tryEnter() const throw()
  202808. {
  202809. return TryEnterCriticalSection ((CRITICAL_SECTION*) internal) != FALSE;
  202810. }
  202811. void CriticalSection::exit() const throw()
  202812. {
  202813. LeaveCriticalSection ((CRITICAL_SECTION*) internal);
  202814. }
  202815. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  202816. : internal (CreateEvent (0, manualReset ? TRUE : FALSE, FALSE, 0))
  202817. {
  202818. }
  202819. WaitableEvent::~WaitableEvent() throw()
  202820. {
  202821. CloseHandle (internal);
  202822. }
  202823. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  202824. {
  202825. return WaitForSingleObject (internal, timeOutMillisecs) == WAIT_OBJECT_0;
  202826. }
  202827. void WaitableEvent::signal() const throw()
  202828. {
  202829. SetEvent (internal);
  202830. }
  202831. void WaitableEvent::reset() const throw()
  202832. {
  202833. ResetEvent (internal);
  202834. }
  202835. void JUCE_API juce_threadEntryPoint (void*);
  202836. static unsigned int __stdcall threadEntryProc (void* userData)
  202837. {
  202838. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  202839. AttachThreadInput (GetWindowThreadProcessId (juce_messageWindowHandle, 0),
  202840. GetCurrentThreadId(), TRUE);
  202841. #endif
  202842. juce_threadEntryPoint (userData);
  202843. _endthreadex (0);
  202844. return 0;
  202845. }
  202846. void juce_CloseThreadHandle (void* handle)
  202847. {
  202848. CloseHandle ((HANDLE) handle);
  202849. }
  202850. void* juce_createThread (void* userData)
  202851. {
  202852. unsigned int threadId;
  202853. return (void*) _beginthreadex (0, 0, &threadEntryProc, userData, 0, &threadId);
  202854. }
  202855. void juce_killThread (void* handle)
  202856. {
  202857. if (handle != 0)
  202858. {
  202859. #if JUCE_DEBUG
  202860. OutputDebugString (_T("** Warning - Forced thread termination **\n"));
  202861. #endif
  202862. TerminateThread (handle, 0);
  202863. }
  202864. }
  202865. void juce_setCurrentThreadName (const String& name)
  202866. {
  202867. #if JUCE_DEBUG && JUCE_MSVC
  202868. struct
  202869. {
  202870. DWORD dwType;
  202871. LPCSTR szName;
  202872. DWORD dwThreadID;
  202873. DWORD dwFlags;
  202874. } info;
  202875. info.dwType = 0x1000;
  202876. info.szName = name.toCString();
  202877. info.dwThreadID = GetCurrentThreadId();
  202878. info.dwFlags = 0;
  202879. __try
  202880. {
  202881. RaiseException (0x406d1388 /*MS_VC_EXCEPTION*/, 0, sizeof (info) / sizeof (ULONG_PTR), (ULONG_PTR*) &info);
  202882. }
  202883. __except (EXCEPTION_CONTINUE_EXECUTION)
  202884. {}
  202885. #else
  202886. (void) name;
  202887. #endif
  202888. }
  202889. Thread::ThreadID Thread::getCurrentThreadId()
  202890. {
  202891. return (ThreadID) (pointer_sized_int) GetCurrentThreadId();
  202892. }
  202893. // priority 1 to 10 where 5=normal, 1=low
  202894. bool juce_setThreadPriority (void* threadHandle, int priority)
  202895. {
  202896. int pri = THREAD_PRIORITY_TIME_CRITICAL;
  202897. if (priority < 1)
  202898. pri = THREAD_PRIORITY_IDLE;
  202899. else if (priority < 2)
  202900. pri = THREAD_PRIORITY_LOWEST;
  202901. else if (priority < 5)
  202902. pri = THREAD_PRIORITY_BELOW_NORMAL;
  202903. else if (priority < 7)
  202904. pri = THREAD_PRIORITY_NORMAL;
  202905. else if (priority < 9)
  202906. pri = THREAD_PRIORITY_ABOVE_NORMAL;
  202907. else if (priority < 10)
  202908. pri = THREAD_PRIORITY_HIGHEST;
  202909. if (threadHandle == 0)
  202910. threadHandle = GetCurrentThread();
  202911. return SetThreadPriority (threadHandle, pri) != FALSE;
  202912. }
  202913. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  202914. {
  202915. SetThreadAffinityMask (GetCurrentThread(), affinityMask);
  202916. }
  202917. static HANDLE sleepEvent = 0;
  202918. void juce_initialiseThreadEvents()
  202919. {
  202920. if (sleepEvent == 0)
  202921. #if JUCE_DEBUG
  202922. sleepEvent = CreateEvent (0, 0, 0, _T("Juce Sleep Event"));
  202923. #else
  202924. sleepEvent = CreateEvent (0, 0, 0, 0);
  202925. #endif
  202926. }
  202927. void Thread::yield()
  202928. {
  202929. Sleep (0);
  202930. }
  202931. void JUCE_CALLTYPE Thread::sleep (const int millisecs)
  202932. {
  202933. if (millisecs >= 10)
  202934. {
  202935. Sleep (millisecs);
  202936. }
  202937. else
  202938. {
  202939. jassert (sleepEvent != 0);
  202940. // unlike Sleep() this is guaranteed to return to the current thread after
  202941. // the time expires, so we'll use this for short waits, which are more likely
  202942. // to need to be accurate
  202943. WaitForSingleObject (sleepEvent, millisecs);
  202944. }
  202945. }
  202946. static int lastProcessPriority = -1;
  202947. // called by WindowDriver because Windows does wierd things to process priority
  202948. // when you swap apps, and this forces an update when the app is brought to the front.
  202949. void juce_repeatLastProcessPriority()
  202950. {
  202951. if (lastProcessPriority >= 0) // (avoid changing this if it's not been explicitly set by the app..)
  202952. {
  202953. DWORD p;
  202954. switch (lastProcessPriority)
  202955. {
  202956. case Process::LowPriority: p = IDLE_PRIORITY_CLASS; break;
  202957. case Process::NormalPriority: p = NORMAL_PRIORITY_CLASS; break;
  202958. case Process::HighPriority: p = HIGH_PRIORITY_CLASS; break;
  202959. case Process::RealtimePriority: p = REALTIME_PRIORITY_CLASS; break;
  202960. default: jassertfalse; return; // bad priority value
  202961. }
  202962. SetPriorityClass (GetCurrentProcess(), p);
  202963. }
  202964. }
  202965. void Process::setPriority (ProcessPriority prior)
  202966. {
  202967. if (lastProcessPriority != (int) prior)
  202968. {
  202969. lastProcessPriority = (int) prior;
  202970. juce_repeatLastProcessPriority();
  202971. }
  202972. }
  202973. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  202974. {
  202975. return IsDebuggerPresent() != FALSE;
  202976. }
  202977. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  202978. {
  202979. return juce_isRunningUnderDebugger();
  202980. }
  202981. void Process::raisePrivilege()
  202982. {
  202983. jassertfalse; // xxx not implemented
  202984. }
  202985. void Process::lowerPrivilege()
  202986. {
  202987. jassertfalse; // xxx not implemented
  202988. }
  202989. void Process::terminate()
  202990. {
  202991. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  202992. _CrtDumpMemoryLeaks();
  202993. #endif
  202994. // bullet in the head in case there's a problem shutting down..
  202995. ExitProcess (0);
  202996. }
  202997. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  202998. {
  202999. void* result = 0;
  203000. JUCE_TRY
  203001. {
  203002. result = LoadLibrary (name);
  203003. }
  203004. JUCE_CATCH_ALL
  203005. return result;
  203006. }
  203007. void PlatformUtilities::freeDynamicLibrary (void* h)
  203008. {
  203009. JUCE_TRY
  203010. {
  203011. if (h != 0)
  203012. FreeLibrary ((HMODULE) h);
  203013. }
  203014. JUCE_CATCH_ALL
  203015. }
  203016. void* PlatformUtilities::getProcedureEntryPoint (void* h, const String& name)
  203017. {
  203018. return (h != 0) ? GetProcAddress ((HMODULE) h, name.toCString()) : 0;
  203019. }
  203020. class InterProcessLock::Pimpl
  203021. {
  203022. public:
  203023. Pimpl (const String& name, const int timeOutMillisecs)
  203024. : handle (0), refCount (1)
  203025. {
  203026. handle = CreateMutex (0, TRUE, "Global\\" + name.replaceCharacter ('\\','/'));
  203027. if (handle != 0 && GetLastError() == ERROR_ALREADY_EXISTS)
  203028. {
  203029. if (timeOutMillisecs == 0)
  203030. {
  203031. close();
  203032. return;
  203033. }
  203034. switch (WaitForSingleObject (handle, timeOutMillisecs < 0 ? INFINITE : timeOutMillisecs))
  203035. {
  203036. case WAIT_OBJECT_0:
  203037. case WAIT_ABANDONED:
  203038. break;
  203039. case WAIT_TIMEOUT:
  203040. default:
  203041. close();
  203042. break;
  203043. }
  203044. }
  203045. }
  203046. ~Pimpl()
  203047. {
  203048. close();
  203049. }
  203050. void close()
  203051. {
  203052. if (handle != 0)
  203053. {
  203054. ReleaseMutex (handle);
  203055. CloseHandle (handle);
  203056. handle = 0;
  203057. }
  203058. }
  203059. HANDLE handle;
  203060. int refCount;
  203061. };
  203062. InterProcessLock::InterProcessLock (const String& name_)
  203063. : name (name_)
  203064. {
  203065. }
  203066. InterProcessLock::~InterProcessLock()
  203067. {
  203068. }
  203069. bool InterProcessLock::enter (const int timeOutMillisecs)
  203070. {
  203071. const ScopedLock sl (lock);
  203072. if (pimpl == 0)
  203073. {
  203074. pimpl = new Pimpl (name, timeOutMillisecs);
  203075. if (pimpl->handle == 0)
  203076. pimpl = 0;
  203077. }
  203078. else
  203079. {
  203080. pimpl->refCount++;
  203081. }
  203082. return pimpl != 0;
  203083. }
  203084. void InterProcessLock::exit()
  203085. {
  203086. const ScopedLock sl (lock);
  203087. // Trying to release the lock too many times!
  203088. jassert (pimpl != 0);
  203089. if (pimpl != 0 && --(pimpl->refCount) == 0)
  203090. pimpl = 0;
  203091. }
  203092. #endif
  203093. /*** End of inlined file: juce_win32_Threads.cpp ***/
  203094. /*** Start of inlined file: juce_win32_Files.cpp ***/
  203095. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203096. // compiled on its own).
  203097. #if JUCE_INCLUDED_FILE
  203098. #ifndef CSIDL_MYMUSIC
  203099. #define CSIDL_MYMUSIC 0x000d
  203100. #endif
  203101. #ifndef CSIDL_MYVIDEO
  203102. #define CSIDL_MYVIDEO 0x000e
  203103. #endif
  203104. #ifndef INVALID_FILE_ATTRIBUTES
  203105. #define INVALID_FILE_ATTRIBUTES ((DWORD) -1)
  203106. #endif
  203107. const juce_wchar File::separator = '\\';
  203108. const String File::separatorString ("\\");
  203109. bool File::exists() const
  203110. {
  203111. return fullPath.isNotEmpty()
  203112. && GetFileAttributes (fullPath) != INVALID_FILE_ATTRIBUTES;
  203113. }
  203114. bool File::existsAsFile() const
  203115. {
  203116. return fullPath.isNotEmpty()
  203117. && (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_DIRECTORY) == 0;
  203118. }
  203119. bool File::isDirectory() const
  203120. {
  203121. const DWORD attr = GetFileAttributes (fullPath);
  203122. return ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) && (attr != INVALID_FILE_ATTRIBUTES);
  203123. }
  203124. bool File::hasWriteAccess() const
  203125. {
  203126. if (exists())
  203127. return (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_READONLY) == 0;
  203128. // on windows, it seems that even read-only directories can still be written into,
  203129. // so checking the parent directory's permissions would return the wrong result..
  203130. return true;
  203131. }
  203132. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  203133. {
  203134. DWORD attr = GetFileAttributes (fullPath);
  203135. if (attr == INVALID_FILE_ATTRIBUTES)
  203136. return false;
  203137. if (shouldBeReadOnly == ((attr & FILE_ATTRIBUTE_READONLY) != 0))
  203138. return true;
  203139. if (shouldBeReadOnly)
  203140. attr |= FILE_ATTRIBUTE_READONLY;
  203141. else
  203142. attr &= ~FILE_ATTRIBUTE_READONLY;
  203143. return SetFileAttributes (fullPath, attr) != FALSE;
  203144. }
  203145. bool File::isHidden() const
  203146. {
  203147. return (GetFileAttributes (getFullPathName()) & FILE_ATTRIBUTE_HIDDEN) != 0;
  203148. }
  203149. bool File::deleteFile() const
  203150. {
  203151. if (! exists())
  203152. return true;
  203153. else if (isDirectory())
  203154. return RemoveDirectory (fullPath) != 0;
  203155. else
  203156. return DeleteFile (fullPath) != 0;
  203157. }
  203158. bool File::moveToTrash() const
  203159. {
  203160. if (! exists())
  203161. return true;
  203162. SHFILEOPSTRUCT fos;
  203163. zerostruct (fos);
  203164. // The string we pass in must be double null terminated..
  203165. String doubleNullTermPath (getFullPathName() + " ");
  203166. TCHAR* const p = const_cast <TCHAR*> (static_cast <const TCHAR*> (doubleNullTermPath));
  203167. p [getFullPathName().length()] = 0;
  203168. fos.wFunc = FO_DELETE;
  203169. fos.pFrom = p;
  203170. fos.fFlags = FOF_ALLOWUNDO | FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION
  203171. | FOF_NOCONFIRMMKDIR | FOF_RENAMEONCOLLISION;
  203172. return SHFileOperation (&fos) == 0;
  203173. }
  203174. bool File::copyInternal (const File& dest) const
  203175. {
  203176. return CopyFile (fullPath, dest.getFullPathName(), false) != 0;
  203177. }
  203178. bool File::moveInternal (const File& dest) const
  203179. {
  203180. return MoveFile (fullPath, dest.getFullPathName()) != 0;
  203181. }
  203182. void File::createDirectoryInternal (const String& fileName) const
  203183. {
  203184. CreateDirectory (fileName, 0);
  203185. }
  203186. // return 0 if not possible
  203187. void* juce_fileOpen (const File& file, bool forWriting)
  203188. {
  203189. HANDLE h;
  203190. if (forWriting)
  203191. {
  203192. h = CreateFile (file.getFullPathName(), GENERIC_WRITE, FILE_SHARE_READ, 0,
  203193. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  203194. if (h != INVALID_HANDLE_VALUE)
  203195. SetFilePointer (h, 0, 0, FILE_END);
  203196. else
  203197. h = 0;
  203198. }
  203199. else
  203200. {
  203201. h = CreateFile (file.getFullPathName(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
  203202. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, 0);
  203203. if (h == INVALID_HANDLE_VALUE)
  203204. h = 0;
  203205. }
  203206. return h;
  203207. }
  203208. void juce_fileClose (void* handle)
  203209. {
  203210. CloseHandle (handle);
  203211. }
  203212. int juce_fileRead (void* handle, void* buffer, int size)
  203213. {
  203214. DWORD num = 0;
  203215. ReadFile ((HANDLE) handle, buffer, size, &num, 0);
  203216. return (int) num;
  203217. }
  203218. int juce_fileWrite (void* handle, const void* buffer, int size)
  203219. {
  203220. DWORD num;
  203221. WriteFile ((HANDLE) handle, buffer, size, &num, 0);
  203222. return (int) num;
  203223. }
  203224. int64 juce_fileSetPosition (void* handle, int64 pos)
  203225. {
  203226. LARGE_INTEGER li;
  203227. li.QuadPart = pos;
  203228. li.LowPart = SetFilePointer ((HANDLE) handle, li.LowPart, &li.HighPart, FILE_BEGIN); // (returns -1 if it fails)
  203229. return li.QuadPart;
  203230. }
  203231. int64 FileOutputStream::getPositionInternal() const
  203232. {
  203233. if (fileHandle == 0)
  203234. return -1;
  203235. LARGE_INTEGER li;
  203236. li.QuadPart = 0;
  203237. li.LowPart = SetFilePointer ((HANDLE) fileHandle, 0, &li.HighPart, FILE_CURRENT); // (returns -1 if it fails)
  203238. return jmax ((int64) 0, li.QuadPart);
  203239. }
  203240. void FileOutputStream::flushInternal()
  203241. {
  203242. if (fileHandle != 0)
  203243. FlushFileBuffers ((HANDLE) fileHandle);
  203244. }
  203245. int64 File::getSize() const
  203246. {
  203247. WIN32_FILE_ATTRIBUTE_DATA attributes;
  203248. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  203249. return (((int64) attributes.nFileSizeHigh) << 32) | attributes.nFileSizeLow;
  203250. return 0;
  203251. }
  203252. static int64 fileTimeToTime (const FILETIME* const ft)
  203253. {
  203254. static_jassert (sizeof (ULARGE_INTEGER) == sizeof (FILETIME)); // tell me if this fails!
  203255. return (reinterpret_cast<const ULARGE_INTEGER*> (ft)->QuadPart - literal64bit (116444736000000000)) / 10000;
  203256. }
  203257. static void timeToFileTime (const int64 time, FILETIME* const ft)
  203258. {
  203259. reinterpret_cast<ULARGE_INTEGER*> (ft)->QuadPart = time * 10000 + literal64bit (116444736000000000);
  203260. }
  203261. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  203262. {
  203263. WIN32_FILE_ATTRIBUTE_DATA attributes;
  203264. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  203265. {
  203266. modificationTime = fileTimeToTime (&attributes.ftLastWriteTime);
  203267. creationTime = fileTimeToTime (&attributes.ftCreationTime);
  203268. accessTime = fileTimeToTime (&attributes.ftLastAccessTime);
  203269. }
  203270. else
  203271. {
  203272. creationTime = accessTime = modificationTime = 0;
  203273. }
  203274. }
  203275. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 creationTime) const
  203276. {
  203277. void* const h = juce_fileOpen (fullPath, true);
  203278. bool ok = false;
  203279. if (h != 0)
  203280. {
  203281. FILETIME m, a, c;
  203282. timeToFileTime (modificationTime, &m);
  203283. timeToFileTime (accessTime, &a);
  203284. timeToFileTime (creationTime, &c);
  203285. ok = SetFileTime ((HANDLE) h,
  203286. creationTime > 0 ? &c : 0,
  203287. accessTime > 0 ? &a : 0,
  203288. modificationTime > 0 ? &m : 0) != 0;
  203289. juce_fileClose (h);
  203290. }
  203291. return ok;
  203292. }
  203293. void File::findFileSystemRoots (Array<File>& destArray)
  203294. {
  203295. TCHAR buffer [2048];
  203296. buffer[0] = 0;
  203297. buffer[1] = 0;
  203298. GetLogicalDriveStrings (2048, buffer);
  203299. const TCHAR* n = buffer;
  203300. StringArray roots;
  203301. while (*n != 0)
  203302. {
  203303. roots.add (String (n));
  203304. while (*n++ != 0)
  203305. {}
  203306. }
  203307. roots.sort (true);
  203308. for (int i = 0; i < roots.size(); ++i)
  203309. destArray.add (roots [i]);
  203310. }
  203311. static const String getDriveFromPath (const String& path)
  203312. {
  203313. if (path.isNotEmpty() && path[1] == ':')
  203314. return path.substring (0, 2) + '\\';
  203315. return path;
  203316. }
  203317. const String File::getVolumeLabel() const
  203318. {
  203319. TCHAR dest[64];
  203320. if (! GetVolumeInformation (getDriveFromPath (getFullPathName()), dest,
  203321. numElementsInArray (dest), 0, 0, 0, 0, 0))
  203322. dest[0] = 0;
  203323. return dest;
  203324. }
  203325. int File::getVolumeSerialNumber() const
  203326. {
  203327. TCHAR dest[64];
  203328. DWORD serialNum;
  203329. if (! GetVolumeInformation (getDriveFromPath (getFullPathName()), dest,
  203330. numElementsInArray (dest), &serialNum, 0, 0, 0, 0))
  203331. return 0;
  203332. return (int) serialNum;
  203333. }
  203334. static int64 getDiskSpaceInfo (const String& path, const bool total)
  203335. {
  203336. ULARGE_INTEGER spc, tot, totFree;
  203337. if (GetDiskFreeSpaceEx (getDriveFromPath (path), &spc, &tot, &totFree))
  203338. return total ? (int64) tot.QuadPart
  203339. : (int64) spc.QuadPart;
  203340. return 0;
  203341. }
  203342. int64 File::getBytesFreeOnVolume() const
  203343. {
  203344. return getDiskSpaceInfo (getFullPathName(), false);
  203345. }
  203346. int64 File::getVolumeTotalSize() const
  203347. {
  203348. return getDiskSpaceInfo (getFullPathName(), true);
  203349. }
  203350. static unsigned int getWindowsDriveType (const String& path)
  203351. {
  203352. return GetDriveType (getDriveFromPath (path));
  203353. }
  203354. bool File::isOnCDRomDrive() const
  203355. {
  203356. return getWindowsDriveType (getFullPathName()) == DRIVE_CDROM;
  203357. }
  203358. bool File::isOnHardDisk() const
  203359. {
  203360. if (fullPath.isEmpty())
  203361. return false;
  203362. const unsigned int n = getWindowsDriveType (getFullPathName());
  203363. if (fullPath.toLowerCase()[0] <= 'b' && fullPath[1] == ':')
  203364. return n != DRIVE_REMOVABLE;
  203365. else
  203366. return n != DRIVE_CDROM && n != DRIVE_REMOTE;
  203367. }
  203368. bool File::isOnRemovableDrive() const
  203369. {
  203370. if (fullPath.isEmpty())
  203371. return false;
  203372. const unsigned int n = getWindowsDriveType (getFullPathName());
  203373. return n == DRIVE_CDROM
  203374. || n == DRIVE_REMOTE
  203375. || n == DRIVE_REMOVABLE
  203376. || n == DRIVE_RAMDISK;
  203377. }
  203378. static const File juce_getSpecialFolderPath (int type)
  203379. {
  203380. WCHAR path [MAX_PATH + 256];
  203381. if (SHGetSpecialFolderPath (0, path, type, FALSE))
  203382. return File (String (path));
  203383. return File::nonexistent;
  203384. }
  203385. const File JUCE_CALLTYPE File::getSpecialLocation (const SpecialLocationType type)
  203386. {
  203387. int csidlType = 0;
  203388. switch (type)
  203389. {
  203390. case userHomeDirectory: csidlType = CSIDL_PROFILE; break;
  203391. case userDocumentsDirectory: csidlType = CSIDL_PERSONAL; break;
  203392. case userDesktopDirectory: csidlType = CSIDL_DESKTOP; break;
  203393. case userApplicationDataDirectory: csidlType = CSIDL_APPDATA; break;
  203394. case commonApplicationDataDirectory: csidlType = CSIDL_COMMON_APPDATA; break;
  203395. case globalApplicationsDirectory: csidlType = CSIDL_PROGRAM_FILES; break;
  203396. case userMusicDirectory: csidlType = CSIDL_MYMUSIC; break;
  203397. case userMoviesDirectory: csidlType = CSIDL_MYVIDEO; break;
  203398. case tempDirectory:
  203399. {
  203400. WCHAR dest [2048];
  203401. dest[0] = 0;
  203402. GetTempPath (numElementsInArray (dest), dest);
  203403. return File (String (dest));
  203404. }
  203405. case invokedExecutableFile:
  203406. case currentExecutableFile:
  203407. case currentApplicationFile:
  203408. {
  203409. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  203410. WCHAR dest [MAX_PATH + 256];
  203411. dest[0] = 0;
  203412. GetModuleFileName (moduleHandle, dest, numElementsInArray (dest));
  203413. return File (String (dest));
  203414. }
  203415. break;
  203416. default:
  203417. jassertfalse; // unknown type?
  203418. return File::nonexistent;
  203419. }
  203420. return juce_getSpecialFolderPath (csidlType);
  203421. }
  203422. const File File::getCurrentWorkingDirectory()
  203423. {
  203424. WCHAR dest [MAX_PATH + 256];
  203425. dest[0] = 0;
  203426. GetCurrentDirectory (numElementsInArray (dest), dest);
  203427. return File (String (dest));
  203428. }
  203429. bool File::setAsCurrentWorkingDirectory() const
  203430. {
  203431. return SetCurrentDirectory (getFullPathName()) != FALSE;
  203432. }
  203433. const String File::getVersion() const
  203434. {
  203435. String result;
  203436. DWORD handle = 0;
  203437. DWORD bufferSize = GetFileVersionInfoSize (getFullPathName(), &handle);
  203438. HeapBlock<char> buffer;
  203439. buffer.calloc (bufferSize);
  203440. if (GetFileVersionInfo (getFullPathName(), 0, bufferSize, buffer))
  203441. {
  203442. VS_FIXEDFILEINFO* vffi;
  203443. UINT len = 0;
  203444. if (VerQueryValue (buffer, (LPTSTR) _T("\\"), (LPVOID*) &vffi, &len))
  203445. {
  203446. result << (int) HIWORD (vffi->dwFileVersionMS) << '.'
  203447. << (int) LOWORD (vffi->dwFileVersionMS) << '.'
  203448. << (int) HIWORD (vffi->dwFileVersionLS) << '.'
  203449. << (int) LOWORD (vffi->dwFileVersionLS);
  203450. }
  203451. }
  203452. return result;
  203453. }
  203454. const File File::getLinkedTarget() const
  203455. {
  203456. File result (*this);
  203457. String p (getFullPathName());
  203458. if (! exists())
  203459. p += ".lnk";
  203460. else if (getFileExtension() != ".lnk")
  203461. return result;
  203462. ComSmartPtr <IShellLink> shellLink;
  203463. if (SUCCEEDED (shellLink.CoCreateInstance (CLSID_ShellLink)))
  203464. {
  203465. ComSmartPtr <IPersistFile> persistFile;
  203466. if (SUCCEEDED (shellLink->QueryInterface (IID_IPersistFile, (LPVOID*) &persistFile)))
  203467. {
  203468. if (SUCCEEDED (persistFile->Load ((const WCHAR*) p, STGM_READ))
  203469. && SUCCEEDED (shellLink->Resolve (0, SLR_ANY_MATCH | SLR_NO_UI)))
  203470. {
  203471. WIN32_FIND_DATA winFindData;
  203472. WCHAR resolvedPath [MAX_PATH];
  203473. if (SUCCEEDED (shellLink->GetPath (resolvedPath, MAX_PATH, &winFindData, SLGP_UNCPRIORITY)))
  203474. result = File (resolvedPath);
  203475. }
  203476. }
  203477. }
  203478. return result;
  203479. }
  203480. class DirectoryIterator::NativeIterator::Pimpl
  203481. {
  203482. public:
  203483. Pimpl (const File& directory, const String& wildCard)
  203484. : directoryWithWildCard (File::addTrailingSeparator (directory.getFullPathName()) + wildCard),
  203485. handle (INVALID_HANDLE_VALUE)
  203486. {
  203487. }
  203488. ~Pimpl()
  203489. {
  203490. if (handle != INVALID_HANDLE_VALUE)
  203491. FindClose (handle);
  203492. }
  203493. bool next (String& filenameFound,
  203494. bool* const isDir, bool* const isHidden, int64* const fileSize,
  203495. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  203496. {
  203497. WIN32_FIND_DATA findData;
  203498. if (handle == INVALID_HANDLE_VALUE)
  203499. {
  203500. handle = FindFirstFile (directoryWithWildCard, &findData);
  203501. if (handle == INVALID_HANDLE_VALUE)
  203502. return false;
  203503. }
  203504. else
  203505. {
  203506. if (FindNextFile (handle, &findData) == 0)
  203507. return false;
  203508. }
  203509. filenameFound = findData.cFileName;
  203510. if (isDir != 0) *isDir = ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
  203511. if (isHidden != 0) *isHidden = ((findData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0);
  203512. if (fileSize != 0) *fileSize = findData.nFileSizeLow + (((int64) findData.nFileSizeHigh) << 32);
  203513. if (modTime != 0) *modTime = fileTimeToTime (&findData.ftLastWriteTime);
  203514. if (creationTime != 0) *creationTime = fileTimeToTime (&findData.ftCreationTime);
  203515. if (isReadOnly != 0) *isReadOnly = ((findData.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0);
  203516. return true;
  203517. }
  203518. juce_UseDebuggingNewOperator
  203519. private:
  203520. const String directoryWithWildCard;
  203521. HANDLE handle;
  203522. Pimpl (const Pimpl&);
  203523. Pimpl& operator= (const Pimpl&);
  203524. };
  203525. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  203526. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  203527. {
  203528. }
  203529. DirectoryIterator::NativeIterator::~NativeIterator()
  203530. {
  203531. }
  203532. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  203533. bool* const isDir, bool* const isHidden, int64* const fileSize,
  203534. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  203535. {
  203536. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  203537. }
  203538. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  203539. {
  203540. HINSTANCE hInstance = 0;
  203541. JUCE_TRY
  203542. {
  203543. hInstance = ShellExecute (0, 0, fileName, parameters, 0, SW_SHOWDEFAULT);
  203544. }
  203545. JUCE_CATCH_ALL
  203546. return hInstance > (HINSTANCE) 32;
  203547. }
  203548. void File::revealToUser() const
  203549. {
  203550. if (isDirectory())
  203551. startAsProcess();
  203552. else if (getParentDirectory().exists())
  203553. getParentDirectory().startAsProcess();
  203554. }
  203555. class NamedPipeInternal
  203556. {
  203557. public:
  203558. NamedPipeInternal (const String& file, const bool isPipe_)
  203559. : pipeH (0),
  203560. cancelEvent (0),
  203561. connected (false),
  203562. isPipe (isPipe_)
  203563. {
  203564. cancelEvent = CreateEvent (0, FALSE, FALSE, 0);
  203565. pipeH = isPipe ? CreateNamedPipe (file, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, 0,
  203566. PIPE_UNLIMITED_INSTANCES, 4096, 4096, 0, 0)
  203567. : CreateFile (file, GENERIC_READ | GENERIC_WRITE, 0, 0,
  203568. OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
  203569. }
  203570. ~NamedPipeInternal()
  203571. {
  203572. disconnectPipe();
  203573. if (pipeH != 0)
  203574. CloseHandle (pipeH);
  203575. CloseHandle (cancelEvent);
  203576. }
  203577. bool connect (const int timeOutMs)
  203578. {
  203579. if (! isPipe)
  203580. return true;
  203581. if (! connected)
  203582. {
  203583. OVERLAPPED over;
  203584. zerostruct (over);
  203585. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  203586. if (ConnectNamedPipe (pipeH, &over))
  203587. {
  203588. connected = false; // yes, you read that right. In overlapped mode it should always return 0.
  203589. }
  203590. else
  203591. {
  203592. const int err = GetLastError();
  203593. if (err == ERROR_IO_PENDING || err == ERROR_PIPE_LISTENING)
  203594. {
  203595. HANDLE handles[] = { over.hEvent, cancelEvent };
  203596. if (WaitForMultipleObjects (2, handles, FALSE,
  203597. timeOutMs >= 0 ? timeOutMs : INFINITE) == WAIT_OBJECT_0)
  203598. connected = true;
  203599. }
  203600. else if (err == ERROR_PIPE_CONNECTED)
  203601. {
  203602. connected = true;
  203603. }
  203604. }
  203605. CloseHandle (over.hEvent);
  203606. }
  203607. return connected;
  203608. }
  203609. void disconnectPipe()
  203610. {
  203611. if (connected)
  203612. {
  203613. DisconnectNamedPipe (pipeH);
  203614. connected = false;
  203615. }
  203616. }
  203617. HANDLE pipeH;
  203618. HANDLE cancelEvent;
  203619. bool connected, isPipe;
  203620. };
  203621. void NamedPipe::close()
  203622. {
  203623. cancelPendingReads();
  203624. const ScopedLock sl (lock);
  203625. delete static_cast<NamedPipeInternal*> (internal);
  203626. internal = 0;
  203627. }
  203628. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  203629. {
  203630. close();
  203631. ScopedPointer<NamedPipeInternal> intern (new NamedPipeInternal ("\\\\.\\pipe\\" + pipeName, createPipe));
  203632. if (intern->pipeH != INVALID_HANDLE_VALUE)
  203633. {
  203634. internal = intern.release();
  203635. return true;
  203636. }
  203637. return false;
  203638. }
  203639. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds)
  203640. {
  203641. const ScopedLock sl (lock);
  203642. int bytesRead = -1;
  203643. bool waitAgain = true;
  203644. while (waitAgain && internal != 0)
  203645. {
  203646. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  203647. waitAgain = false;
  203648. if (! intern->connect (timeOutMilliseconds))
  203649. break;
  203650. if (maxBytesToRead <= 0)
  203651. return 0;
  203652. OVERLAPPED over;
  203653. zerostruct (over);
  203654. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  203655. unsigned long numRead;
  203656. if (ReadFile (intern->pipeH, destBuffer, maxBytesToRead, &numRead, &over))
  203657. {
  203658. bytesRead = (int) numRead;
  203659. }
  203660. else if (GetLastError() == ERROR_IO_PENDING)
  203661. {
  203662. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  203663. DWORD waitResult = WaitForMultipleObjects (2, handles, FALSE,
  203664. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  203665. : INFINITE);
  203666. if (waitResult != WAIT_OBJECT_0)
  203667. {
  203668. // if the operation timed out, let's cancel it...
  203669. CancelIo (intern->pipeH);
  203670. WaitForSingleObject (over.hEvent, INFINITE); // makes sure cancel is complete
  203671. }
  203672. if (GetOverlappedResult (intern->pipeH, &over, &numRead, FALSE))
  203673. {
  203674. bytesRead = (int) numRead;
  203675. }
  203676. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  203677. {
  203678. intern->disconnectPipe();
  203679. waitAgain = true;
  203680. }
  203681. }
  203682. else
  203683. {
  203684. waitAgain = internal != 0;
  203685. Sleep (5);
  203686. }
  203687. CloseHandle (over.hEvent);
  203688. }
  203689. return bytesRead;
  203690. }
  203691. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  203692. {
  203693. int bytesWritten = -1;
  203694. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  203695. if (intern != 0 && intern->connect (timeOutMilliseconds))
  203696. {
  203697. if (numBytesToWrite <= 0)
  203698. return 0;
  203699. OVERLAPPED over;
  203700. zerostruct (over);
  203701. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  203702. unsigned long numWritten;
  203703. if (WriteFile (intern->pipeH, sourceBuffer, numBytesToWrite, &numWritten, &over))
  203704. {
  203705. bytesWritten = (int) numWritten;
  203706. }
  203707. else if (GetLastError() == ERROR_IO_PENDING)
  203708. {
  203709. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  203710. DWORD waitResult;
  203711. waitResult = WaitForMultipleObjects (2, handles, FALSE,
  203712. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  203713. : INFINITE);
  203714. if (waitResult != WAIT_OBJECT_0)
  203715. {
  203716. CancelIo (intern->pipeH);
  203717. WaitForSingleObject (over.hEvent, INFINITE);
  203718. }
  203719. if (GetOverlappedResult (intern->pipeH, &over, &numWritten, FALSE))
  203720. {
  203721. bytesWritten = (int) numWritten;
  203722. }
  203723. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  203724. {
  203725. intern->disconnectPipe();
  203726. }
  203727. }
  203728. CloseHandle (over.hEvent);
  203729. }
  203730. return bytesWritten;
  203731. }
  203732. void NamedPipe::cancelPendingReads()
  203733. {
  203734. if (internal != 0)
  203735. SetEvent (static_cast<NamedPipeInternal*> (internal)->cancelEvent);
  203736. }
  203737. #endif
  203738. /*** End of inlined file: juce_win32_Files.cpp ***/
  203739. /*** Start of inlined file: juce_win32_Network.cpp ***/
  203740. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203741. // compiled on its own).
  203742. #if JUCE_INCLUDED_FILE
  203743. #ifndef INTERNET_FLAG_NEED_FILE
  203744. #define INTERNET_FLAG_NEED_FILE 0x00000010
  203745. #endif
  203746. #ifndef INTERNET_OPTION_DISABLE_AUTODIAL
  203747. #define INTERNET_OPTION_DISABLE_AUTODIAL 70
  203748. #endif
  203749. struct ConnectionAndRequestStruct
  203750. {
  203751. HINTERNET connection, request;
  203752. };
  203753. static HINTERNET sessionHandle = 0;
  203754. #ifndef WORKAROUND_TIMEOUT_BUG
  203755. //#define WORKAROUND_TIMEOUT_BUG 1
  203756. #endif
  203757. #if WORKAROUND_TIMEOUT_BUG
  203758. // Required because of a Microsoft bug in setting a timeout
  203759. class InternetConnectThread : public Thread
  203760. {
  203761. public:
  203762. InternetConnectThread (URL_COMPONENTS& uc_, HINTERNET& connection_, const bool isFtp_)
  203763. : Thread ("Internet"), uc (uc_), connection (connection_), isFtp (isFtp_)
  203764. {
  203765. startThread();
  203766. }
  203767. ~InternetConnectThread()
  203768. {
  203769. stopThread (60000);
  203770. }
  203771. void run()
  203772. {
  203773. connection = InternetConnect (sessionHandle, uc.lpszHostName,
  203774. uc.nPort, _T(""), _T(""),
  203775. isFtp ? INTERNET_SERVICE_FTP
  203776. : INTERNET_SERVICE_HTTP,
  203777. 0, 0);
  203778. notify();
  203779. }
  203780. juce_UseDebuggingNewOperator
  203781. private:
  203782. URL_COMPONENTS& uc;
  203783. HINTERNET& connection;
  203784. const bool isFtp;
  203785. InternetConnectThread (const InternetConnectThread&);
  203786. InternetConnectThread& operator= (const InternetConnectThread&);
  203787. };
  203788. #endif
  203789. void* juce_openInternetFile (const String& url,
  203790. const String& headers,
  203791. const MemoryBlock& postData,
  203792. const bool isPost,
  203793. URL::OpenStreamProgressCallback* callback,
  203794. void* callbackContext,
  203795. int timeOutMs)
  203796. {
  203797. if (sessionHandle == 0)
  203798. sessionHandle = InternetOpen (_T("juce"),
  203799. INTERNET_OPEN_TYPE_PRECONFIG,
  203800. 0, 0, 0);
  203801. if (sessionHandle != 0)
  203802. {
  203803. // break up the url..
  203804. TCHAR file[1024], server[1024];
  203805. URL_COMPONENTS uc;
  203806. zerostruct (uc);
  203807. uc.dwStructSize = sizeof (uc);
  203808. uc.dwUrlPathLength = sizeof (file);
  203809. uc.dwHostNameLength = sizeof (server);
  203810. uc.lpszUrlPath = file;
  203811. uc.lpszHostName = server;
  203812. if (InternetCrackUrl (url, 0, 0, &uc))
  203813. {
  203814. int disable = 1;
  203815. InternetSetOption (sessionHandle, INTERNET_OPTION_DISABLE_AUTODIAL, &disable, sizeof (disable));
  203816. if (timeOutMs == 0)
  203817. timeOutMs = 30000;
  203818. else if (timeOutMs < 0)
  203819. timeOutMs = -1;
  203820. InternetSetOption (sessionHandle, INTERNET_OPTION_CONNECT_TIMEOUT, &timeOutMs, sizeof (timeOutMs));
  203821. const bool isFtp = url.startsWithIgnoreCase ("ftp:");
  203822. #if WORKAROUND_TIMEOUT_BUG
  203823. HINTERNET connection = 0;
  203824. {
  203825. InternetConnectThread connectThread (uc, connection, isFtp);
  203826. connectThread.wait (timeOutMs);
  203827. if (connection == 0)
  203828. {
  203829. InternetCloseHandle (sessionHandle);
  203830. sessionHandle = 0;
  203831. }
  203832. }
  203833. #else
  203834. HINTERNET connection = InternetConnect (sessionHandle,
  203835. uc.lpszHostName,
  203836. uc.nPort,
  203837. _T(""), _T(""),
  203838. isFtp ? INTERNET_SERVICE_FTP
  203839. : INTERNET_SERVICE_HTTP,
  203840. 0, 0);
  203841. #endif
  203842. if (connection != 0)
  203843. {
  203844. if (isFtp)
  203845. {
  203846. HINTERNET request = FtpOpenFile (connection,
  203847. uc.lpszUrlPath,
  203848. GENERIC_READ,
  203849. FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_NEED_FILE,
  203850. 0);
  203851. ConnectionAndRequestStruct* const result = new ConnectionAndRequestStruct();
  203852. result->connection = connection;
  203853. result->request = request;
  203854. return result;
  203855. }
  203856. else
  203857. {
  203858. const TCHAR* mimeTypes[] = { _T("*/*"), 0 };
  203859. DWORD flags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_NO_COOKIES;
  203860. if (url.startsWithIgnoreCase ("https:"))
  203861. flags |= INTERNET_FLAG_SECURE; // (this flag only seems necessary if the OS is running IE6 -
  203862. // IE7 seems to automatically work out when it's https)
  203863. HINTERNET request = HttpOpenRequest (connection,
  203864. isPost ? _T("POST")
  203865. : _T("GET"),
  203866. uc.lpszUrlPath,
  203867. 0, 0, mimeTypes, flags, 0);
  203868. if (request != 0)
  203869. {
  203870. INTERNET_BUFFERS buffers;
  203871. zerostruct (buffers);
  203872. buffers.dwStructSize = sizeof (INTERNET_BUFFERS);
  203873. buffers.lpcszHeader = (LPCTSTR) headers;
  203874. buffers.dwHeadersLength = headers.length();
  203875. buffers.dwBufferTotal = (DWORD) postData.getSize();
  203876. ConnectionAndRequestStruct* result = 0;
  203877. if (HttpSendRequestEx (request, &buffers, 0, HSR_INITIATE, 0))
  203878. {
  203879. int bytesSent = 0;
  203880. for (;;)
  203881. {
  203882. const int bytesToDo = jmin (1024, (int) postData.getSize() - bytesSent);
  203883. DWORD bytesDone = 0;
  203884. if (bytesToDo > 0
  203885. && ! InternetWriteFile (request,
  203886. static_cast <const char*> (postData.getData()) + bytesSent,
  203887. bytesToDo, &bytesDone))
  203888. {
  203889. break;
  203890. }
  203891. if (bytesToDo == 0 || (int) bytesDone < bytesToDo)
  203892. {
  203893. result = new ConnectionAndRequestStruct();
  203894. result->connection = connection;
  203895. result->request = request;
  203896. if (! HttpEndRequest (request, 0, 0, 0))
  203897. break;
  203898. return result;
  203899. }
  203900. bytesSent += bytesDone;
  203901. if (callback != 0 && ! callback (callbackContext, bytesSent, postData.getSize()))
  203902. break;
  203903. }
  203904. }
  203905. InternetCloseHandle (request);
  203906. }
  203907. InternetCloseHandle (connection);
  203908. }
  203909. }
  203910. }
  203911. }
  203912. return 0;
  203913. }
  203914. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  203915. {
  203916. DWORD bytesRead = 0;
  203917. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  203918. if (crs != 0)
  203919. InternetReadFile (crs->request,
  203920. buffer, bytesToRead,
  203921. &bytesRead);
  203922. return bytesRead;
  203923. }
  203924. int juce_seekInInternetFile (void* handle, int newPosition)
  203925. {
  203926. if (handle != 0)
  203927. {
  203928. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  203929. return InternetSetFilePointer (crs->request, newPosition, 0, FILE_BEGIN, 0);
  203930. }
  203931. return -1;
  203932. }
  203933. int64 juce_getInternetFileContentLength (void* handle)
  203934. {
  203935. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  203936. if (crs != 0)
  203937. {
  203938. DWORD index = 0, result = 0, size = sizeof (result);
  203939. if (HttpQueryInfo (crs->request, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &result, &size, &index))
  203940. return (int64) result;
  203941. }
  203942. return -1;
  203943. }
  203944. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  203945. {
  203946. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  203947. if (crs != 0)
  203948. {
  203949. DWORD bufferSizeBytes = 4096;
  203950. for (;;)
  203951. {
  203952. HeapBlock<char> buffer ((size_t) bufferSizeBytes);
  203953. if (HttpQueryInfo (crs->request, HTTP_QUERY_RAW_HEADERS_CRLF, buffer.getData(), &bufferSizeBytes, 0))
  203954. {
  203955. StringArray headersArray;
  203956. headersArray.addLines (reinterpret_cast <const WCHAR*> (buffer.getData()));
  203957. for (int i = 0; i < headersArray.size(); ++i)
  203958. {
  203959. const String& header = headersArray[i];
  203960. const String key (header.upToFirstOccurrenceOf (": ", false, false));
  203961. const String value (header.fromFirstOccurrenceOf (": ", false, false));
  203962. const String previousValue (headers [key]);
  203963. headers.set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  203964. }
  203965. break;
  203966. }
  203967. if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
  203968. break;
  203969. }
  203970. }
  203971. }
  203972. void juce_closeInternetFile (void* handle)
  203973. {
  203974. if (handle != 0)
  203975. {
  203976. ScopedPointer <ConnectionAndRequestStruct> crs (static_cast <ConnectionAndRequestStruct*> (handle));
  203977. InternetCloseHandle (crs->request);
  203978. InternetCloseHandle (crs->connection);
  203979. }
  203980. }
  203981. static int getMACAddressViaGetAdaptersInfo (int64* addresses, int maxNum, const bool littleEndian) throw()
  203982. {
  203983. int numFound = 0;
  203984. DynamicLibraryLoader dll ("iphlpapi.dll");
  203985. DynamicLibraryImport (GetAdaptersInfo, getAdaptersInfo, DWORD, dll, (PIP_ADAPTER_INFO, PULONG))
  203986. if (getAdaptersInfo != 0)
  203987. {
  203988. ULONG len = sizeof (IP_ADAPTER_INFO);
  203989. MemoryBlock mb;
  203990. PIP_ADAPTER_INFO adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  203991. if (getAdaptersInfo (adapterInfo, &len) == ERROR_BUFFER_OVERFLOW)
  203992. {
  203993. mb.setSize (len);
  203994. adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  203995. }
  203996. if (getAdaptersInfo (adapterInfo, &len) == NO_ERROR)
  203997. {
  203998. PIP_ADAPTER_INFO adapter = adapterInfo;
  203999. while (adapter != 0)
  204000. {
  204001. int64 mac = 0;
  204002. for (unsigned int i = 0; i < adapter->AddressLength; ++i)
  204003. mac = (mac << 8) | adapter->Address[i];
  204004. if (littleEndian)
  204005. mac = (int64) ByteOrder::swap ((uint64) mac);
  204006. if (numFound < maxNum && mac != 0)
  204007. addresses [numFound++] = mac;
  204008. adapter = adapter->Next;
  204009. }
  204010. }
  204011. }
  204012. return numFound;
  204013. }
  204014. static int getMACAddressesViaNetBios (int64* addresses, int maxNum, const bool littleEndian) throw()
  204015. {
  204016. int numFound = 0;
  204017. DynamicLibraryLoader dll ("netapi32.dll");
  204018. DynamicLibraryImport (Netbios, NetbiosCall, UCHAR, dll, (PNCB))
  204019. if (NetbiosCall != 0)
  204020. {
  204021. NCB ncb;
  204022. zerostruct (ncb);
  204023. struct ASTAT
  204024. {
  204025. ADAPTER_STATUS adapt;
  204026. NAME_BUFFER NameBuff [30];
  204027. };
  204028. ASTAT astat;
  204029. zeromem (&astat, sizeof (astat)); // (can't use zerostruct here in VC6)
  204030. LANA_ENUM enums;
  204031. zerostruct (enums);
  204032. ncb.ncb_command = NCBENUM;
  204033. ncb.ncb_buffer = (unsigned char*) &enums;
  204034. ncb.ncb_length = sizeof (LANA_ENUM);
  204035. NetbiosCall (&ncb);
  204036. for (int i = 0; i < enums.length; ++i)
  204037. {
  204038. zerostruct (ncb);
  204039. ncb.ncb_command = NCBRESET;
  204040. ncb.ncb_lana_num = enums.lana[i];
  204041. if (NetbiosCall (&ncb) == 0)
  204042. {
  204043. zerostruct (ncb);
  204044. memcpy (ncb.ncb_callname, "* ", NCBNAMSZ);
  204045. ncb.ncb_command = NCBASTAT;
  204046. ncb.ncb_lana_num = enums.lana[i];
  204047. ncb.ncb_buffer = (unsigned char*) &astat;
  204048. ncb.ncb_length = sizeof (ASTAT);
  204049. if (NetbiosCall (&ncb) == 0)
  204050. {
  204051. if (astat.adapt.adapter_type == 0xfe)
  204052. {
  204053. uint64 mac = 0;
  204054. for (int i = 6; --i >= 0;)
  204055. mac = (mac << 8) | astat.adapt.adapter_address [littleEndian ? i : (5 - i)];
  204056. if (numFound < maxNum && mac != 0)
  204057. addresses [numFound++] = mac;
  204058. }
  204059. }
  204060. }
  204061. }
  204062. }
  204063. return numFound;
  204064. }
  204065. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  204066. {
  204067. int numFound = getMACAddressViaGetAdaptersInfo (addresses, maxNum, littleEndian);
  204068. if (numFound == 0)
  204069. numFound = getMACAddressesViaNetBios (addresses, maxNum, littleEndian);
  204070. return numFound;
  204071. }
  204072. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  204073. const String& emailSubject,
  204074. const String& bodyText,
  204075. const StringArray& filesToAttach)
  204076. {
  204077. HMODULE h = LoadLibraryA ("MAPI32.dll");
  204078. typedef ULONG (WINAPI *MAPISendMailType) (LHANDLE, ULONG, lpMapiMessage, ::FLAGS, ULONG);
  204079. MAPISendMailType mapiSendMail = (MAPISendMailType) GetProcAddress (h, "MAPISendMail");
  204080. bool ok = false;
  204081. if (mapiSendMail != 0)
  204082. {
  204083. MapiMessage message;
  204084. zerostruct (message);
  204085. message.lpszSubject = (LPSTR) emailSubject.toCString();
  204086. message.lpszNoteText = (LPSTR) bodyText.toCString();
  204087. MapiRecipDesc recip;
  204088. zerostruct (recip);
  204089. recip.ulRecipClass = MAPI_TO;
  204090. String targetEmailAddress_ (targetEmailAddress);
  204091. if (targetEmailAddress_.isEmpty())
  204092. targetEmailAddress_ = " "; // (Windows Mail can't deal with a blank address)
  204093. recip.lpszName = (LPSTR) targetEmailAddress_.toCString();
  204094. message.nRecipCount = 1;
  204095. message.lpRecips = &recip;
  204096. HeapBlock <MapiFileDesc> files;
  204097. files.calloc (filesToAttach.size());
  204098. message.nFileCount = filesToAttach.size();
  204099. message.lpFiles = files;
  204100. for (int i = 0; i < filesToAttach.size(); ++i)
  204101. {
  204102. files[i].nPosition = (ULONG) -1;
  204103. files[i].lpszPathName = (LPSTR) filesToAttach[i].toCString();
  204104. }
  204105. ok = (mapiSendMail (0, 0, &message, MAPI_DIALOG | MAPI_LOGON_UI, 0) == SUCCESS_SUCCESS);
  204106. }
  204107. FreeLibrary (h);
  204108. return ok;
  204109. }
  204110. #endif
  204111. /*** End of inlined file: juce_win32_Network.cpp ***/
  204112. /*** Start of inlined file: juce_win32_PlatformUtils.cpp ***/
  204113. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204114. // compiled on its own).
  204115. #if JUCE_INCLUDED_FILE
  204116. static HKEY findKeyForPath (String name,
  204117. const bool createForWriting,
  204118. String& valueName)
  204119. {
  204120. HKEY rootKey = 0;
  204121. if (name.startsWithIgnoreCase ("HKEY_CURRENT_USER\\"))
  204122. rootKey = HKEY_CURRENT_USER;
  204123. else if (name.startsWithIgnoreCase ("HKEY_LOCAL_MACHINE\\"))
  204124. rootKey = HKEY_LOCAL_MACHINE;
  204125. else if (name.startsWithIgnoreCase ("HKEY_CLASSES_ROOT\\"))
  204126. rootKey = HKEY_CLASSES_ROOT;
  204127. if (rootKey != 0)
  204128. {
  204129. name = name.substring (name.indexOfChar ('\\') + 1);
  204130. const int lastSlash = name.lastIndexOfChar ('\\');
  204131. valueName = name.substring (lastSlash + 1);
  204132. name = name.substring (0, lastSlash);
  204133. HKEY key;
  204134. DWORD result;
  204135. if (createForWriting)
  204136. {
  204137. if (RegCreateKeyEx (rootKey, name, 0, 0, REG_OPTION_NON_VOLATILE,
  204138. (KEY_WRITE | KEY_QUERY_VALUE), 0, &key, &result) == ERROR_SUCCESS)
  204139. return key;
  204140. }
  204141. else
  204142. {
  204143. if (RegOpenKeyEx (rootKey, name, 0, KEY_READ, &key) == ERROR_SUCCESS)
  204144. return key;
  204145. }
  204146. }
  204147. return 0;
  204148. }
  204149. const String PlatformUtilities::getRegistryValue (const String& regValuePath,
  204150. const String& defaultValue)
  204151. {
  204152. String valueName, result (defaultValue);
  204153. HKEY k = findKeyForPath (regValuePath, false, valueName);
  204154. if (k != 0)
  204155. {
  204156. WCHAR buffer [2048];
  204157. unsigned long bufferSize = sizeof (buffer);
  204158. DWORD type = REG_SZ;
  204159. if (RegQueryValueEx (k, valueName, 0, &type, (LPBYTE) buffer, &bufferSize) == ERROR_SUCCESS)
  204160. {
  204161. if (type == REG_SZ)
  204162. result = buffer;
  204163. else if (type == REG_DWORD)
  204164. result = String ((int) *(DWORD*) buffer);
  204165. }
  204166. RegCloseKey (k);
  204167. }
  204168. return result;
  204169. }
  204170. void PlatformUtilities::setRegistryValue (const String& regValuePath,
  204171. const String& value)
  204172. {
  204173. String valueName;
  204174. HKEY k = findKeyForPath (regValuePath, true, valueName);
  204175. if (k != 0)
  204176. {
  204177. RegSetValueEx (k, valueName, 0, REG_SZ,
  204178. (const BYTE*) (const WCHAR*) value,
  204179. sizeof (WCHAR) * (value.length() + 1));
  204180. RegCloseKey (k);
  204181. }
  204182. }
  204183. bool PlatformUtilities::registryValueExists (const String& regValuePath)
  204184. {
  204185. bool exists = false;
  204186. String valueName;
  204187. HKEY k = findKeyForPath (regValuePath, false, valueName);
  204188. if (k != 0)
  204189. {
  204190. unsigned char buffer [2048];
  204191. unsigned long bufferSize = sizeof (buffer);
  204192. DWORD type = 0;
  204193. if (RegQueryValueEx (k, valueName, 0, &type, buffer, &bufferSize) == ERROR_SUCCESS)
  204194. exists = true;
  204195. RegCloseKey (k);
  204196. }
  204197. return exists;
  204198. }
  204199. void PlatformUtilities::deleteRegistryValue (const String& regValuePath)
  204200. {
  204201. String valueName;
  204202. HKEY k = findKeyForPath (regValuePath, true, valueName);
  204203. if (k != 0)
  204204. {
  204205. RegDeleteValue (k, valueName);
  204206. RegCloseKey (k);
  204207. }
  204208. }
  204209. void PlatformUtilities::deleteRegistryKey (const String& regKeyPath)
  204210. {
  204211. String valueName;
  204212. HKEY k = findKeyForPath (regKeyPath, true, valueName);
  204213. if (k != 0)
  204214. {
  204215. RegDeleteKey (k, valueName);
  204216. RegCloseKey (k);
  204217. }
  204218. }
  204219. void PlatformUtilities::registerFileAssociation (const String& fileExtension,
  204220. const String& symbolicDescription,
  204221. const String& fullDescription,
  204222. const File& targetExecutable,
  204223. int iconResourceNumber)
  204224. {
  204225. setRegistryValue ("HKEY_CLASSES_ROOT\\" + fileExtension + "\\", symbolicDescription);
  204226. const String key ("HKEY_CLASSES_ROOT\\" + symbolicDescription);
  204227. if (iconResourceNumber != 0)
  204228. setRegistryValue (key + "\\DefaultIcon\\",
  204229. targetExecutable.getFullPathName() + "," + String (-iconResourceNumber));
  204230. setRegistryValue (key + "\\", fullDescription);
  204231. setRegistryValue (key + "\\shell\\open\\command\\",
  204232. targetExecutable.getFullPathName() + " %1");
  204233. }
  204234. bool juce_IsRunningInWine()
  204235. {
  204236. HKEY key;
  204237. if (RegOpenKeyEx (HKEY_CURRENT_USER, _T("Software\\Wine"), 0, KEY_READ, &key) == ERROR_SUCCESS)
  204238. {
  204239. RegCloseKey (key);
  204240. return true;
  204241. }
  204242. return false;
  204243. }
  204244. const String JUCE_CALLTYPE PlatformUtilities::getCurrentCommandLineParams()
  204245. {
  204246. String s (::GetCommandLineW());
  204247. StringArray tokens;
  204248. tokens.addTokens (s, true); // tokenise so that we can remove the initial filename argument
  204249. return tokens.joinIntoString (" ", 1);
  204250. }
  204251. static void* currentModuleHandle = 0;
  204252. void* PlatformUtilities::getCurrentModuleInstanceHandle() throw()
  204253. {
  204254. if (currentModuleHandle == 0)
  204255. currentModuleHandle = GetModuleHandle (0);
  204256. return currentModuleHandle;
  204257. }
  204258. void PlatformUtilities::setCurrentModuleInstanceHandle (void* const newHandle) throw()
  204259. {
  204260. currentModuleHandle = newHandle;
  204261. }
  204262. void PlatformUtilities::fpuReset()
  204263. {
  204264. #if JUCE_MSVC
  204265. _clearfp();
  204266. #endif
  204267. }
  204268. void PlatformUtilities::beep()
  204269. {
  204270. MessageBeep (MB_OK);
  204271. }
  204272. #endif
  204273. /*** End of inlined file: juce_win32_PlatformUtils.cpp ***/
  204274. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  204275. /*** Start of inlined file: juce_win32_Messaging.cpp ***/
  204276. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204277. // compiled on its own).
  204278. #if JUCE_INCLUDED_FILE
  204279. static const unsigned int specialId = WM_APP + 0x4400;
  204280. static const unsigned int broadcastId = WM_APP + 0x4403;
  204281. static const unsigned int specialCallbackId = WM_APP + 0x4402;
  204282. static const TCHAR* const messageWindowName = _T("JUCEWindow");
  204283. HWND juce_messageWindowHandle = 0;
  204284. extern long improbableWindowNumber; // defined in windowing.cpp
  204285. #ifndef WM_APPCOMMAND
  204286. #define WM_APPCOMMAND 0x0319
  204287. #endif
  204288. static LRESULT CALLBACK juce_MessageWndProc (HWND h,
  204289. const UINT message,
  204290. const WPARAM wParam,
  204291. const LPARAM lParam) throw()
  204292. {
  204293. JUCE_TRY
  204294. {
  204295. if (h == juce_messageWindowHandle)
  204296. {
  204297. if (message == specialCallbackId)
  204298. {
  204299. MessageCallbackFunction* const func = (MessageCallbackFunction*) wParam;
  204300. return (LRESULT) (*func) ((void*) lParam);
  204301. }
  204302. else if (message == specialId)
  204303. {
  204304. // these are trapped early in the dispatch call, but must also be checked
  204305. // here in case there are windows modal dialog boxes doing their own
  204306. // dispatch loop and not calling our version
  204307. MessageManager::getInstance()->deliverMessage ((Message*) lParam);
  204308. return 0;
  204309. }
  204310. else if (message == broadcastId)
  204311. {
  204312. const ScopedPointer <String> messageString ((String*) lParam);
  204313. MessageManager::getInstance()->deliverBroadcastMessage (*messageString);
  204314. return 0;
  204315. }
  204316. else if (message == WM_COPYDATA && ((const COPYDATASTRUCT*) lParam)->dwData == broadcastId)
  204317. {
  204318. const String messageString ((const juce_wchar*) ((const COPYDATASTRUCT*) lParam)->lpData,
  204319. ((const COPYDATASTRUCT*) lParam)->cbData / sizeof (juce_wchar));
  204320. PostMessage (juce_messageWindowHandle, broadcastId, 0, (LPARAM) new String (messageString));
  204321. return 0;
  204322. }
  204323. }
  204324. }
  204325. JUCE_CATCH_EXCEPTION
  204326. return DefWindowProc (h, message, wParam, lParam);
  204327. }
  204328. static bool isEventBlockedByModalComps (MSG& m)
  204329. {
  204330. if (Component::getNumCurrentlyModalComponents() == 0
  204331. || GetWindowLong (m.hwnd, GWLP_USERDATA) == improbableWindowNumber)
  204332. return false;
  204333. switch (m.message)
  204334. {
  204335. case WM_MOUSEMOVE:
  204336. case WM_NCMOUSEMOVE:
  204337. case 0x020A: /* WM_MOUSEWHEEL */
  204338. case 0x020E: /* WM_MOUSEHWHEEL */
  204339. case WM_KEYUP:
  204340. case WM_SYSKEYUP:
  204341. case WM_CHAR:
  204342. case WM_APPCOMMAND:
  204343. case WM_LBUTTONUP:
  204344. case WM_MBUTTONUP:
  204345. case WM_RBUTTONUP:
  204346. case WM_MOUSEACTIVATE:
  204347. case WM_NCMOUSEHOVER:
  204348. case WM_MOUSEHOVER:
  204349. return true;
  204350. case WM_NCLBUTTONDOWN:
  204351. case WM_NCLBUTTONDBLCLK:
  204352. case WM_NCRBUTTONDOWN:
  204353. case WM_NCRBUTTONDBLCLK:
  204354. case WM_NCMBUTTONDOWN:
  204355. case WM_NCMBUTTONDBLCLK:
  204356. case WM_LBUTTONDOWN:
  204357. case WM_LBUTTONDBLCLK:
  204358. case WM_MBUTTONDOWN:
  204359. case WM_MBUTTONDBLCLK:
  204360. case WM_RBUTTONDOWN:
  204361. case WM_RBUTTONDBLCLK:
  204362. case WM_KEYDOWN:
  204363. case WM_SYSKEYDOWN:
  204364. {
  204365. Component* const modal = Component::getCurrentlyModalComponent (0);
  204366. if (modal != 0)
  204367. modal->inputAttemptWhenModal();
  204368. return true;
  204369. }
  204370. default:
  204371. break;
  204372. }
  204373. return false;
  204374. }
  204375. bool juce_dispatchNextMessageOnSystemQueue (const bool returnIfNoPendingMessages)
  204376. {
  204377. MSG m;
  204378. if (returnIfNoPendingMessages && ! PeekMessage (&m, (HWND) 0, 0, 0, 0))
  204379. return false;
  204380. if (GetMessage (&m, (HWND) 0, 0, 0) >= 0)
  204381. {
  204382. if (m.message == specialId && m.hwnd == juce_messageWindowHandle)
  204383. {
  204384. MessageManager::getInstance()->deliverMessage ((Message*) (void*) m.lParam);
  204385. }
  204386. else if (m.message == WM_QUIT)
  204387. {
  204388. if (JUCEApplication::getInstance())
  204389. JUCEApplication::getInstance()->systemRequestedQuit();
  204390. }
  204391. else if (! isEventBlockedByModalComps (m))
  204392. {
  204393. if ((m.message == WM_LBUTTONDOWN || m.message == WM_RBUTTONDOWN)
  204394. && GetWindowLong (m.hwnd, GWLP_USERDATA) != improbableWindowNumber)
  204395. {
  204396. // if it's someone else's window being clicked on, and the focus is
  204397. // currently on a juce window, pass the kb focus over..
  204398. HWND currentFocus = GetFocus();
  204399. if (currentFocus == 0 || GetWindowLong (currentFocus, GWLP_USERDATA) == improbableWindowNumber)
  204400. SetFocus (m.hwnd);
  204401. }
  204402. TranslateMessage (&m);
  204403. DispatchMessage (&m);
  204404. }
  204405. }
  204406. return true;
  204407. }
  204408. bool juce_postMessageToSystemQueue (Message* message)
  204409. {
  204410. return PostMessage (juce_messageWindowHandle, specialId, 0, (LPARAM) message) != 0;
  204411. }
  204412. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  204413. void* userData)
  204414. {
  204415. if (MessageManager::getInstance()->isThisTheMessageThread())
  204416. {
  204417. return (*callback) (userData);
  204418. }
  204419. else
  204420. {
  204421. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  204422. // deadlock because the message manager is blocked from running, and can't
  204423. // call your function..
  204424. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  204425. return (void*) SendMessage (juce_messageWindowHandle,
  204426. specialCallbackId,
  204427. (WPARAM) callback,
  204428. (LPARAM) userData);
  204429. }
  204430. }
  204431. static BOOL CALLBACK BroadcastEnumWindowProc (HWND hwnd, LPARAM lParam)
  204432. {
  204433. if (hwnd != juce_messageWindowHandle)
  204434. reinterpret_cast <Array<void*>*> (lParam)->add ((void*) hwnd);
  204435. return TRUE;
  204436. }
  204437. void MessageManager::broadcastMessage (const String& value) throw()
  204438. {
  204439. Array<void*> windows;
  204440. EnumWindows (&BroadcastEnumWindowProc, (LPARAM) &windows);
  204441. const String localCopy (value);
  204442. COPYDATASTRUCT data;
  204443. data.dwData = broadcastId;
  204444. data.cbData = (localCopy.length() + 1) * sizeof (juce_wchar);
  204445. data.lpData = (void*) static_cast <const juce_wchar*> (localCopy);
  204446. for (int i = windows.size(); --i >= 0;)
  204447. {
  204448. HWND hwnd = (HWND) windows.getUnchecked(i);
  204449. TCHAR windowName [64]; // no need to read longer strings than this
  204450. GetWindowText (hwnd, windowName, 64);
  204451. windowName [63] = 0;
  204452. if (String (windowName) == messageWindowName)
  204453. {
  204454. DWORD_PTR result;
  204455. SendMessageTimeout (hwnd, WM_COPYDATA,
  204456. (WPARAM) juce_messageWindowHandle,
  204457. (LPARAM) &data,
  204458. SMTO_BLOCK | SMTO_ABORTIFHUNG,
  204459. 8000,
  204460. &result);
  204461. }
  204462. }
  204463. }
  204464. static const String getMessageWindowClassName()
  204465. {
  204466. // this name has to be different for each app/dll instance because otherwise
  204467. // poor old Win32 can get a bit confused (even despite it not being a process-global
  204468. // window class).
  204469. static int number = 0;
  204470. if (number == 0)
  204471. number = 0x7fffffff & (int) Time::getHighResolutionTicks();
  204472. return "JUCEcs_" + String (number);
  204473. }
  204474. void MessageManager::doPlatformSpecificInitialisation()
  204475. {
  204476. OleInitialize (0);
  204477. const String className (getMessageWindowClassName());
  204478. HMODULE hmod = (HMODULE) PlatformUtilities::getCurrentModuleInstanceHandle();
  204479. WNDCLASSEX wc;
  204480. zerostruct (wc);
  204481. wc.cbSize = sizeof (wc);
  204482. wc.lpfnWndProc = (WNDPROC) juce_MessageWndProc;
  204483. wc.cbWndExtra = 4;
  204484. wc.hInstance = hmod;
  204485. wc.lpszClassName = className;
  204486. RegisterClassEx (&wc);
  204487. juce_messageWindowHandle = CreateWindow (wc.lpszClassName,
  204488. messageWindowName,
  204489. 0, 0, 0, 0, 0, 0, 0,
  204490. hmod, 0);
  204491. }
  204492. void MessageManager::doPlatformSpecificShutdown()
  204493. {
  204494. DestroyWindow (juce_messageWindowHandle);
  204495. UnregisterClass (getMessageWindowClassName(), 0);
  204496. OleUninitialize();
  204497. }
  204498. #endif
  204499. /*** End of inlined file: juce_win32_Messaging.cpp ***/
  204500. /*** Start of inlined file: juce_win32_Windowing.cpp ***/
  204501. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204502. // compiled on its own).
  204503. #if JUCE_INCLUDED_FILE
  204504. #undef GetSystemMetrics // multimon overrides this for some reason and causes a mess..
  204505. // these are in the windows SDK, but need to be repeated here for GCC..
  204506. #ifndef GET_APPCOMMAND_LPARAM
  204507. #define FAPPCOMMAND_MASK 0xF000
  204508. #define GET_APPCOMMAND_LPARAM(lParam) ((short) (HIWORD (lParam) & ~FAPPCOMMAND_MASK))
  204509. #define APPCOMMAND_MEDIA_NEXTTRACK 11
  204510. #define APPCOMMAND_MEDIA_PREVIOUSTRACK 12
  204511. #define APPCOMMAND_MEDIA_STOP 13
  204512. #define APPCOMMAND_MEDIA_PLAY_PAUSE 14
  204513. #define WM_APPCOMMAND 0x0319
  204514. #endif
  204515. extern void juce_repeatLastProcessPriority(); // in juce_win32_Threads.cpp
  204516. extern void juce_CheckCurrentlyFocusedTopLevelWindow(); // in juce_TopLevelWindow.cpp
  204517. extern bool juce_IsRunningInWine();
  204518. #ifndef ULW_ALPHA
  204519. #define ULW_ALPHA 0x00000002
  204520. #endif
  204521. #ifndef AC_SRC_ALPHA
  204522. #define AC_SRC_ALPHA 0x01
  204523. #endif
  204524. static HPALETTE palette = 0;
  204525. static bool createPaletteIfNeeded = true;
  204526. static bool shouldDeactivateTitleBar = true;
  204527. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY) throw();
  204528. #define WM_TRAYNOTIFY WM_USER + 100
  204529. using ::abs;
  204530. typedef BOOL (WINAPI* UpdateLayeredWinFunc) (HWND, HDC, POINT*, SIZE*, HDC, POINT*, COLORREF, BLENDFUNCTION*, DWORD);
  204531. static UpdateLayeredWinFunc updateLayeredWindow = 0;
  204532. bool Desktop::canUseSemiTransparentWindows() throw()
  204533. {
  204534. if (updateLayeredWindow == 0)
  204535. {
  204536. if (! juce_IsRunningInWine())
  204537. {
  204538. HMODULE user32Mod = GetModuleHandle (_T("user32.dll"));
  204539. updateLayeredWindow = (UpdateLayeredWinFunc) GetProcAddress (user32Mod, "UpdateLayeredWindow");
  204540. }
  204541. }
  204542. return updateLayeredWindow != 0;
  204543. }
  204544. const int extendedKeyModifier = 0x10000;
  204545. const int KeyPress::spaceKey = VK_SPACE;
  204546. const int KeyPress::returnKey = VK_RETURN;
  204547. const int KeyPress::escapeKey = VK_ESCAPE;
  204548. const int KeyPress::backspaceKey = VK_BACK;
  204549. const int KeyPress::deleteKey = VK_DELETE | extendedKeyModifier;
  204550. const int KeyPress::insertKey = VK_INSERT | extendedKeyModifier;
  204551. const int KeyPress::tabKey = VK_TAB;
  204552. const int KeyPress::leftKey = VK_LEFT | extendedKeyModifier;
  204553. const int KeyPress::rightKey = VK_RIGHT | extendedKeyModifier;
  204554. const int KeyPress::upKey = VK_UP | extendedKeyModifier;
  204555. const int KeyPress::downKey = VK_DOWN | extendedKeyModifier;
  204556. const int KeyPress::homeKey = VK_HOME | extendedKeyModifier;
  204557. const int KeyPress::endKey = VK_END | extendedKeyModifier;
  204558. const int KeyPress::pageUpKey = VK_PRIOR | extendedKeyModifier;
  204559. const int KeyPress::pageDownKey = VK_NEXT | extendedKeyModifier;
  204560. const int KeyPress::F1Key = VK_F1 | extendedKeyModifier;
  204561. const int KeyPress::F2Key = VK_F2 | extendedKeyModifier;
  204562. const int KeyPress::F3Key = VK_F3 | extendedKeyModifier;
  204563. const int KeyPress::F4Key = VK_F4 | extendedKeyModifier;
  204564. const int KeyPress::F5Key = VK_F5 | extendedKeyModifier;
  204565. const int KeyPress::F6Key = VK_F6 | extendedKeyModifier;
  204566. const int KeyPress::F7Key = VK_F7 | extendedKeyModifier;
  204567. const int KeyPress::F8Key = VK_F8 | extendedKeyModifier;
  204568. const int KeyPress::F9Key = VK_F9 | extendedKeyModifier;
  204569. const int KeyPress::F10Key = VK_F10 | extendedKeyModifier;
  204570. const int KeyPress::F11Key = VK_F11 | extendedKeyModifier;
  204571. const int KeyPress::F12Key = VK_F12 | extendedKeyModifier;
  204572. const int KeyPress::F13Key = VK_F13 | extendedKeyModifier;
  204573. const int KeyPress::F14Key = VK_F14 | extendedKeyModifier;
  204574. const int KeyPress::F15Key = VK_F15 | extendedKeyModifier;
  204575. const int KeyPress::F16Key = VK_F16 | extendedKeyModifier;
  204576. const int KeyPress::numberPad0 = VK_NUMPAD0 | extendedKeyModifier;
  204577. const int KeyPress::numberPad1 = VK_NUMPAD1 | extendedKeyModifier;
  204578. const int KeyPress::numberPad2 = VK_NUMPAD2 | extendedKeyModifier;
  204579. const int KeyPress::numberPad3 = VK_NUMPAD3 | extendedKeyModifier;
  204580. const int KeyPress::numberPad4 = VK_NUMPAD4 | extendedKeyModifier;
  204581. const int KeyPress::numberPad5 = VK_NUMPAD5 | extendedKeyModifier;
  204582. const int KeyPress::numberPad6 = VK_NUMPAD6 | extendedKeyModifier;
  204583. const int KeyPress::numberPad7 = VK_NUMPAD7 | extendedKeyModifier;
  204584. const int KeyPress::numberPad8 = VK_NUMPAD8 | extendedKeyModifier;
  204585. const int KeyPress::numberPad9 = VK_NUMPAD9 | extendedKeyModifier;
  204586. const int KeyPress::numberPadAdd = VK_ADD | extendedKeyModifier;
  204587. const int KeyPress::numberPadSubtract = VK_SUBTRACT | extendedKeyModifier;
  204588. const int KeyPress::numberPadMultiply = VK_MULTIPLY | extendedKeyModifier;
  204589. const int KeyPress::numberPadDivide = VK_DIVIDE | extendedKeyModifier;
  204590. const int KeyPress::numberPadSeparator = VK_SEPARATOR | extendedKeyModifier;
  204591. const int KeyPress::numberPadDecimalPoint = VK_DECIMAL | extendedKeyModifier;
  204592. const int KeyPress::numberPadEquals = 0x92 /*VK_OEM_NEC_EQUAL*/ | extendedKeyModifier;
  204593. const int KeyPress::numberPadDelete = VK_DELETE | extendedKeyModifier;
  204594. const int KeyPress::playKey = 0x30000;
  204595. const int KeyPress::stopKey = 0x30001;
  204596. const int KeyPress::fastForwardKey = 0x30002;
  204597. const int KeyPress::rewindKey = 0x30003;
  204598. class WindowsBitmapImage : public Image::SharedImage
  204599. {
  204600. public:
  204601. HBITMAP hBitmap;
  204602. BITMAPV4HEADER bitmapInfo;
  204603. HDC hdc;
  204604. unsigned char* bitmapData;
  204605. WindowsBitmapImage (const Image::PixelFormat format_,
  204606. const int w, const int h, const bool clearImage)
  204607. : Image::SharedImage (format_, w, h)
  204608. {
  204609. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  204610. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  204611. zerostruct (bitmapInfo);
  204612. bitmapInfo.bV4Size = sizeof (BITMAPV4HEADER);
  204613. bitmapInfo.bV4Width = w;
  204614. bitmapInfo.bV4Height = h;
  204615. bitmapInfo.bV4Planes = 1;
  204616. bitmapInfo.bV4CSType = 1;
  204617. bitmapInfo.bV4BitCount = (unsigned short) (pixelStride * 8);
  204618. if (format_ == Image::ARGB)
  204619. {
  204620. bitmapInfo.bV4AlphaMask = 0xff000000;
  204621. bitmapInfo.bV4RedMask = 0xff0000;
  204622. bitmapInfo.bV4GreenMask = 0xff00;
  204623. bitmapInfo.bV4BlueMask = 0xff;
  204624. bitmapInfo.bV4V4Compression = BI_BITFIELDS;
  204625. }
  204626. else
  204627. {
  204628. bitmapInfo.bV4V4Compression = BI_RGB;
  204629. }
  204630. lineStride = -((w * pixelStride + 3) & ~3);
  204631. HDC dc = GetDC (0);
  204632. hdc = CreateCompatibleDC (dc);
  204633. ReleaseDC (0, dc);
  204634. SetMapMode (hdc, MM_TEXT);
  204635. hBitmap = CreateDIBSection (hdc,
  204636. (BITMAPINFO*) &(bitmapInfo),
  204637. DIB_RGB_COLORS,
  204638. (void**) &bitmapData,
  204639. 0, 0);
  204640. SelectObject (hdc, hBitmap);
  204641. if (format_ == Image::ARGB && clearImage)
  204642. zeromem (bitmapData, abs (h * lineStride));
  204643. imageData = bitmapData - (lineStride * (h - 1));
  204644. }
  204645. ~WindowsBitmapImage()
  204646. {
  204647. DeleteDC (hdc);
  204648. DeleteObject (hBitmap);
  204649. }
  204650. Image::ImageType getType() const { return Image::NativeImage; }
  204651. LowLevelGraphicsContext* createLowLevelContext()
  204652. {
  204653. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  204654. }
  204655. SharedImage* clone()
  204656. {
  204657. WindowsBitmapImage* im = new WindowsBitmapImage (format, width, height, false);
  204658. for (int i = 0; i < height; ++i)
  204659. memcpy (im->imageData + i * lineStride, imageData + i * lineStride, lineStride);
  204660. return im;
  204661. }
  204662. void blitToWindow (HWND hwnd, HDC dc, const bool transparent,
  204663. const int x, const int y,
  204664. const RectangleList& maskedRegion) throw()
  204665. {
  204666. static HDRAWDIB hdd = 0;
  204667. static bool needToCreateDrawDib = true;
  204668. if (needToCreateDrawDib)
  204669. {
  204670. needToCreateDrawDib = false;
  204671. HDC dc = GetDC (0);
  204672. const int n = GetDeviceCaps (dc, BITSPIXEL);
  204673. ReleaseDC (0, dc);
  204674. // only open if we're not palettised
  204675. if (n > 8)
  204676. hdd = DrawDibOpen();
  204677. }
  204678. if (createPaletteIfNeeded)
  204679. {
  204680. HDC dc = GetDC (0);
  204681. const int n = GetDeviceCaps (dc, BITSPIXEL);
  204682. ReleaseDC (0, dc);
  204683. if (n <= 8)
  204684. palette = CreateHalftonePalette (dc);
  204685. createPaletteIfNeeded = false;
  204686. }
  204687. if (palette != 0)
  204688. {
  204689. SelectPalette (dc, palette, FALSE);
  204690. RealizePalette (dc);
  204691. SetStretchBltMode (dc, HALFTONE);
  204692. }
  204693. SetMapMode (dc, MM_TEXT);
  204694. if (transparent)
  204695. {
  204696. POINT p, pos;
  204697. SIZE size;
  204698. RECT windowBounds;
  204699. GetWindowRect (hwnd, &windowBounds);
  204700. p.x = -x;
  204701. p.y = -y;
  204702. pos.x = windowBounds.left;
  204703. pos.y = windowBounds.top;
  204704. size.cx = windowBounds.right - windowBounds.left;
  204705. size.cy = windowBounds.bottom - windowBounds.top;
  204706. BLENDFUNCTION bf;
  204707. bf.AlphaFormat = AC_SRC_ALPHA;
  204708. bf.BlendFlags = 0;
  204709. bf.BlendOp = AC_SRC_OVER;
  204710. bf.SourceConstantAlpha = 0xff;
  204711. if (! maskedRegion.isEmpty())
  204712. {
  204713. for (RectangleList::Iterator i (maskedRegion); i.next();)
  204714. {
  204715. const Rectangle<int>& r = *i.getRectangle();
  204716. ExcludeClipRect (hdc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  204717. }
  204718. }
  204719. updateLayeredWindow (hwnd, 0, &pos, &size, hdc, &p, 0, &bf, ULW_ALPHA);
  204720. }
  204721. else
  204722. {
  204723. int savedDC = 0;
  204724. if (! maskedRegion.isEmpty())
  204725. {
  204726. savedDC = SaveDC (dc);
  204727. for (RectangleList::Iterator i (maskedRegion); i.next();)
  204728. {
  204729. const Rectangle<int>& r = *i.getRectangle();
  204730. ExcludeClipRect (dc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  204731. }
  204732. }
  204733. if (hdd == 0)
  204734. {
  204735. StretchDIBits (dc,
  204736. x, y, width, height,
  204737. 0, 0, width, height,
  204738. bitmapData, (const BITMAPINFO*) &bitmapInfo,
  204739. DIB_RGB_COLORS, SRCCOPY);
  204740. }
  204741. else
  204742. {
  204743. DrawDibDraw (hdd, dc, x, y, -1, -1,
  204744. (BITMAPINFOHEADER*) &bitmapInfo, bitmapData,
  204745. 0, 0, width, height, 0);
  204746. }
  204747. if (! maskedRegion.isEmpty())
  204748. RestoreDC (dc, savedDC);
  204749. }
  204750. }
  204751. juce_UseDebuggingNewOperator
  204752. private:
  204753. WindowsBitmapImage (const WindowsBitmapImage&);
  204754. WindowsBitmapImage& operator= (const WindowsBitmapImage&);
  204755. };
  204756. long improbableWindowNumber = 0xf965aa01; // also referenced by messaging.cpp
  204757. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  204758. {
  204759. SHORT k = (SHORT) keyCode;
  204760. if ((keyCode & extendedKeyModifier) == 0
  204761. && (k >= (SHORT) 'a' && k <= (SHORT) 'z'))
  204762. k += (SHORT) 'A' - (SHORT) 'a';
  204763. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  204764. (SHORT) '+', VK_OEM_PLUS,
  204765. (SHORT) '-', VK_OEM_MINUS,
  204766. (SHORT) '.', VK_OEM_PERIOD,
  204767. (SHORT) ';', VK_OEM_1,
  204768. (SHORT) ':', VK_OEM_1,
  204769. (SHORT) '/', VK_OEM_2,
  204770. (SHORT) '?', VK_OEM_2,
  204771. (SHORT) '[', VK_OEM_4,
  204772. (SHORT) ']', VK_OEM_6 };
  204773. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  204774. if (k == translatedValues [i])
  204775. k = translatedValues [i + 1];
  204776. return (GetKeyState (k) & 0x8000) != 0;
  204777. }
  204778. static void* callFunctionIfNotLocked (MessageCallbackFunction* callback, void* userData)
  204779. {
  204780. if (MessageManager::getInstance()->currentThreadHasLockedMessageManager())
  204781. return callback (userData);
  204782. else
  204783. return MessageManager::getInstance()->callFunctionOnMessageThread (callback, userData);
  204784. }
  204785. class Win32ComponentPeer : public ComponentPeer
  204786. {
  204787. public:
  204788. Win32ComponentPeer (Component* const component,
  204789. const int windowStyleFlags)
  204790. : ComponentPeer (component, windowStyleFlags),
  204791. dontRepaint (false),
  204792. fullScreen (false),
  204793. isDragging (false),
  204794. isMouseOver (false),
  204795. hasCreatedCaret (false),
  204796. currentWindowIcon (0),
  204797. taskBarIcon (0),
  204798. dropTarget (0)
  204799. {
  204800. callFunctionIfNotLocked (&createWindowCallback, this);
  204801. setTitle (component->getName());
  204802. if ((windowStyleFlags & windowHasDropShadow) != 0
  204803. && Desktop::canUseSemiTransparentWindows())
  204804. {
  204805. shadower = component->getLookAndFeel().createDropShadowerForComponent (component);
  204806. if (shadower != 0)
  204807. shadower->setOwner (component);
  204808. }
  204809. else
  204810. {
  204811. shadower = 0;
  204812. }
  204813. }
  204814. ~Win32ComponentPeer()
  204815. {
  204816. setTaskBarIcon (Image());
  204817. deleteAndZero (shadower);
  204818. // do this before the next bit to avoid messages arriving for this window
  204819. // before it's destroyed
  204820. SetWindowLongPtr (hwnd, GWLP_USERDATA, 0);
  204821. callFunctionIfNotLocked (&destroyWindowCallback, (void*) hwnd);
  204822. if (currentWindowIcon != 0)
  204823. DestroyIcon (currentWindowIcon);
  204824. if (dropTarget != 0)
  204825. {
  204826. dropTarget->Release();
  204827. dropTarget = 0;
  204828. }
  204829. }
  204830. void* getNativeHandle() const
  204831. {
  204832. return hwnd;
  204833. }
  204834. void setVisible (bool shouldBeVisible)
  204835. {
  204836. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  204837. if (shouldBeVisible)
  204838. InvalidateRect (hwnd, 0, 0);
  204839. else
  204840. lastPaintTime = 0;
  204841. }
  204842. void setTitle (const String& title)
  204843. {
  204844. SetWindowText (hwnd, title);
  204845. }
  204846. void setPosition (int x, int y)
  204847. {
  204848. offsetWithinParent (x, y);
  204849. SetWindowPos (hwnd, 0,
  204850. x - windowBorder.getLeft(),
  204851. y - windowBorder.getTop(),
  204852. 0, 0,
  204853. SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  204854. }
  204855. void repaintNowIfTransparent()
  204856. {
  204857. if (isTransparent() && lastPaintTime > 0 && Time::getMillisecondCounter() > lastPaintTime + 30)
  204858. handlePaintMessage();
  204859. }
  204860. void updateBorderSize()
  204861. {
  204862. WINDOWINFO info;
  204863. info.cbSize = sizeof (info);
  204864. if (GetWindowInfo (hwnd, &info))
  204865. {
  204866. windowBorder = BorderSize (info.rcClient.top - info.rcWindow.top,
  204867. info.rcClient.left - info.rcWindow.left,
  204868. info.rcWindow.bottom - info.rcClient.bottom,
  204869. info.rcWindow.right - info.rcClient.right);
  204870. }
  204871. }
  204872. void setSize (int w, int h)
  204873. {
  204874. SetWindowPos (hwnd, 0, 0, 0,
  204875. w + windowBorder.getLeftAndRight(),
  204876. h + windowBorder.getTopAndBottom(),
  204877. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  204878. updateBorderSize();
  204879. repaintNowIfTransparent();
  204880. }
  204881. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  204882. {
  204883. fullScreen = isNowFullScreen;
  204884. offsetWithinParent (x, y);
  204885. SetWindowPos (hwnd, 0,
  204886. x - windowBorder.getLeft(),
  204887. y - windowBorder.getTop(),
  204888. w + windowBorder.getLeftAndRight(),
  204889. h + windowBorder.getTopAndBottom(),
  204890. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  204891. updateBorderSize();
  204892. repaintNowIfTransparent();
  204893. }
  204894. const Rectangle<int> getBounds() const
  204895. {
  204896. RECT r;
  204897. GetWindowRect (hwnd, &r);
  204898. Rectangle<int> bounds (r.left, r.top, r.right - r.left, r.bottom - r.top);
  204899. HWND parentH = GetParent (hwnd);
  204900. if (parentH != 0)
  204901. {
  204902. GetWindowRect (parentH, &r);
  204903. bounds.translate (-r.left, -r.top);
  204904. }
  204905. return windowBorder.subtractedFrom (bounds);
  204906. }
  204907. const Point<int> getScreenPosition() const
  204908. {
  204909. RECT r;
  204910. GetWindowRect (hwnd, &r);
  204911. return Point<int> (r.left + windowBorder.getLeft(),
  204912. r.top + windowBorder.getTop());
  204913. }
  204914. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  204915. {
  204916. return relativePosition + getScreenPosition();
  204917. }
  204918. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  204919. {
  204920. return screenPosition - getScreenPosition();
  204921. }
  204922. void setMinimised (bool shouldBeMinimised)
  204923. {
  204924. if (shouldBeMinimised != isMinimised())
  204925. ShowWindow (hwnd, shouldBeMinimised ? SW_MINIMIZE : SW_SHOWNORMAL);
  204926. }
  204927. bool isMinimised() const
  204928. {
  204929. WINDOWPLACEMENT wp;
  204930. wp.length = sizeof (WINDOWPLACEMENT);
  204931. GetWindowPlacement (hwnd, &wp);
  204932. return wp.showCmd == SW_SHOWMINIMIZED;
  204933. }
  204934. void setFullScreen (bool shouldBeFullScreen)
  204935. {
  204936. setMinimised (false);
  204937. if (fullScreen != shouldBeFullScreen)
  204938. {
  204939. fullScreen = shouldBeFullScreen;
  204940. const Component::SafePointer<Component> deletionChecker (component);
  204941. if (! fullScreen)
  204942. {
  204943. const Rectangle<int> boundsCopy (lastNonFullscreenBounds);
  204944. if (hasTitleBar())
  204945. ShowWindow (hwnd, SW_SHOWNORMAL);
  204946. if (! boundsCopy.isEmpty())
  204947. {
  204948. setBounds (boundsCopy.getX(),
  204949. boundsCopy.getY(),
  204950. boundsCopy.getWidth(),
  204951. boundsCopy.getHeight(),
  204952. false);
  204953. }
  204954. }
  204955. else
  204956. {
  204957. if (hasTitleBar())
  204958. ShowWindow (hwnd, SW_SHOWMAXIMIZED);
  204959. else
  204960. SendMessageW (hwnd, WM_SETTINGCHANGE, 0, 0);
  204961. }
  204962. if (deletionChecker != 0)
  204963. handleMovedOrResized();
  204964. }
  204965. }
  204966. bool isFullScreen() const
  204967. {
  204968. if (! hasTitleBar())
  204969. return fullScreen;
  204970. WINDOWPLACEMENT wp;
  204971. wp.length = sizeof (wp);
  204972. GetWindowPlacement (hwnd, &wp);
  204973. return wp.showCmd == SW_SHOWMAXIMIZED;
  204974. }
  204975. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  204976. {
  204977. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  204978. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  204979. return false;
  204980. RECT r;
  204981. GetWindowRect (hwnd, &r);
  204982. POINT p;
  204983. p.x = position.getX() + r.left + windowBorder.getLeft();
  204984. p.y = position.getY() + r.top + windowBorder.getTop();
  204985. HWND w = WindowFromPoint (p);
  204986. return w == hwnd || (trueIfInAChildWindow && (IsChild (hwnd, w) != 0));
  204987. }
  204988. const BorderSize getFrameSize() const
  204989. {
  204990. return windowBorder;
  204991. }
  204992. bool setAlwaysOnTop (bool alwaysOnTop)
  204993. {
  204994. const bool oldDeactivate = shouldDeactivateTitleBar;
  204995. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  204996. SetWindowPos (hwnd, alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST,
  204997. 0, 0, 0, 0,
  204998. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  204999. shouldDeactivateTitleBar = oldDeactivate;
  205000. if (shadower != 0)
  205001. shadower->componentBroughtToFront (*component);
  205002. return true;
  205003. }
  205004. void toFront (bool makeActive)
  205005. {
  205006. setMinimised (false);
  205007. const bool oldDeactivate = shouldDeactivateTitleBar;
  205008. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  205009. callFunctionIfNotLocked (makeActive ? &toFrontCallback1 : &toFrontCallback2, hwnd);
  205010. shouldDeactivateTitleBar = oldDeactivate;
  205011. if (! makeActive)
  205012. {
  205013. // in this case a broughttofront call won't have occured, so do it now..
  205014. handleBroughtToFront();
  205015. }
  205016. }
  205017. void toBehind (ComponentPeer* other)
  205018. {
  205019. Win32ComponentPeer* const otherPeer = dynamic_cast <Win32ComponentPeer*> (other);
  205020. jassert (otherPeer != 0); // wrong type of window?
  205021. if (otherPeer != 0)
  205022. {
  205023. setMinimised (false);
  205024. // must be careful not to try to put a topmost window behind a normal one, or win32
  205025. // promotes the normal one to be topmost!
  205026. if (getComponent()->isAlwaysOnTop() == otherPeer->getComponent()->isAlwaysOnTop())
  205027. SetWindowPos (hwnd, otherPeer->hwnd, 0, 0, 0, 0,
  205028. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  205029. else if (otherPeer->getComponent()->isAlwaysOnTop())
  205030. SetWindowPos (hwnd, HWND_TOP, 0, 0, 0, 0,
  205031. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  205032. }
  205033. }
  205034. bool isFocused() const
  205035. {
  205036. return callFunctionIfNotLocked (&getFocusCallback, 0) == (void*) hwnd;
  205037. }
  205038. void grabFocus()
  205039. {
  205040. const bool oldDeactivate = shouldDeactivateTitleBar;
  205041. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  205042. callFunctionIfNotLocked (&setFocusCallback, hwnd);
  205043. shouldDeactivateTitleBar = oldDeactivate;
  205044. }
  205045. void textInputRequired (const Point<int>&)
  205046. {
  205047. if (! hasCreatedCaret)
  205048. {
  205049. hasCreatedCaret = true;
  205050. CreateCaret (hwnd, (HBITMAP) 1, 0, 0);
  205051. }
  205052. ShowCaret (hwnd);
  205053. SetCaretPos (0, 0);
  205054. }
  205055. void repaint (const Rectangle<int>& area)
  205056. {
  205057. const RECT r = { area.getX(), area.getY(), area.getRight(), area.getBottom() };
  205058. InvalidateRect (hwnd, &r, FALSE);
  205059. }
  205060. void performAnyPendingRepaintsNow()
  205061. {
  205062. MSG m;
  205063. if (component->isVisible() && PeekMessage (&m, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
  205064. DispatchMessage (&m);
  205065. }
  205066. static Win32ComponentPeer* getOwnerOfWindow (HWND h) throw()
  205067. {
  205068. if (h != 0 && GetWindowLongPtr (h, GWLP_USERDATA) == improbableWindowNumber)
  205069. return (Win32ComponentPeer*) (pointer_sized_int) GetWindowLongPtr (h, 8);
  205070. return 0;
  205071. }
  205072. void setTaskBarIcon (const Image& image)
  205073. {
  205074. if (image.isValid())
  205075. {
  205076. HICON hicon = createHICONFromImage (image, TRUE, 0, 0);
  205077. if (taskBarIcon == 0)
  205078. {
  205079. taskBarIcon = new NOTIFYICONDATA();
  205080. taskBarIcon->cbSize = sizeof (NOTIFYICONDATA);
  205081. taskBarIcon->hWnd = (HWND) hwnd;
  205082. taskBarIcon->uID = (int) (pointer_sized_int) hwnd;
  205083. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  205084. taskBarIcon->uCallbackMessage = WM_TRAYNOTIFY;
  205085. taskBarIcon->hIcon = hicon;
  205086. taskBarIcon->szTip[0] = 0;
  205087. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  205088. }
  205089. else
  205090. {
  205091. HICON oldIcon = taskBarIcon->hIcon;
  205092. taskBarIcon->hIcon = hicon;
  205093. taskBarIcon->uFlags = NIF_ICON;
  205094. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  205095. DestroyIcon (oldIcon);
  205096. }
  205097. DestroyIcon (hicon);
  205098. }
  205099. else if (taskBarIcon != 0)
  205100. {
  205101. taskBarIcon->uFlags = 0;
  205102. Shell_NotifyIcon (NIM_DELETE, taskBarIcon);
  205103. DestroyIcon (taskBarIcon->hIcon);
  205104. deleteAndZero (taskBarIcon);
  205105. }
  205106. }
  205107. void setTaskBarIconToolTip (const String& toolTip) const
  205108. {
  205109. if (taskBarIcon != 0)
  205110. {
  205111. taskBarIcon->uFlags = NIF_TIP;
  205112. toolTip.copyToUnicode (taskBarIcon->szTip, sizeof (taskBarIcon->szTip) - 1);
  205113. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  205114. }
  205115. }
  205116. bool isInside (HWND h) const
  205117. {
  205118. return GetAncestor (hwnd, GA_ROOT) == h;
  205119. }
  205120. static void updateKeyModifiers() throw()
  205121. {
  205122. int keyMods = 0;
  205123. if (GetKeyState (VK_SHIFT) & 0x8000) keyMods |= ModifierKeys::shiftModifier;
  205124. if (GetKeyState (VK_CONTROL) & 0x8000) keyMods |= ModifierKeys::ctrlModifier;
  205125. if (GetKeyState (VK_MENU) & 0x8000) keyMods |= ModifierKeys::altModifier;
  205126. if (GetKeyState (VK_RMENU) & 0x8000) keyMods &= ~(ModifierKeys::ctrlModifier | ModifierKeys::altModifier);
  205127. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  205128. }
  205129. static void updateModifiersFromWParam (const WPARAM wParam)
  205130. {
  205131. int mouseMods = 0;
  205132. if (wParam & MK_LBUTTON) mouseMods |= ModifierKeys::leftButtonModifier;
  205133. if (wParam & MK_RBUTTON) mouseMods |= ModifierKeys::rightButtonModifier;
  205134. if (wParam & MK_MBUTTON) mouseMods |= ModifierKeys::middleButtonModifier;
  205135. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  205136. updateKeyModifiers();
  205137. }
  205138. static int64 getMouseEventTime()
  205139. {
  205140. static int64 eventTimeOffset = 0;
  205141. static DWORD lastMessageTime = 0;
  205142. const DWORD thisMessageTime = GetMessageTime();
  205143. if (thisMessageTime < lastMessageTime || lastMessageTime == 0)
  205144. {
  205145. lastMessageTime = thisMessageTime;
  205146. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  205147. }
  205148. return eventTimeOffset + thisMessageTime;
  205149. }
  205150. juce_UseDebuggingNewOperator
  205151. bool dontRepaint;
  205152. static ModifierKeys currentModifiers;
  205153. static ModifierKeys modifiersAtLastCallback;
  205154. private:
  205155. HWND hwnd;
  205156. DropShadower* shadower;
  205157. bool fullScreen, isDragging, isMouseOver, hasCreatedCaret;
  205158. BorderSize windowBorder;
  205159. HICON currentWindowIcon;
  205160. NOTIFYICONDATA* taskBarIcon;
  205161. IDropTarget* dropTarget;
  205162. class TemporaryImage : public Timer
  205163. {
  205164. public:
  205165. TemporaryImage() {}
  205166. ~TemporaryImage() {}
  205167. const Image& getImage (const bool transparent, const int w, const int h)
  205168. {
  205169. const Image::PixelFormat format = transparent ? Image::ARGB : Image::RGB;
  205170. if ((! image.isValid()) || image.getWidth() < w || image.getHeight() < h || image.getFormat() != format)
  205171. image = Image (new WindowsBitmapImage (format, (w + 31) & ~31, (h + 31) & ~31, false));
  205172. startTimer (3000);
  205173. return image;
  205174. }
  205175. void timerCallback()
  205176. {
  205177. stopTimer();
  205178. image = Image();
  205179. }
  205180. private:
  205181. Image image;
  205182. TemporaryImage (const TemporaryImage&);
  205183. TemporaryImage& operator= (const TemporaryImage&);
  205184. };
  205185. TemporaryImage offscreenImageGenerator;
  205186. class WindowClassHolder : public DeletedAtShutdown
  205187. {
  205188. public:
  205189. WindowClassHolder()
  205190. : windowClassName ("JUCE_")
  205191. {
  205192. // this name has to be different for each app/dll instance because otherwise
  205193. // poor old Win32 can get a bit confused (even despite it not being a process-global
  205194. // window class).
  205195. windowClassName << (int) (Time::currentTimeMillis() & 0x7fffffff);
  205196. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  205197. TCHAR moduleFile [1024];
  205198. moduleFile[0] = 0;
  205199. GetModuleFileName (moduleHandle, moduleFile, 1024);
  205200. WORD iconNum = 0;
  205201. WNDCLASSEX wcex;
  205202. wcex.cbSize = sizeof (wcex);
  205203. wcex.style = CS_OWNDC;
  205204. wcex.lpfnWndProc = (WNDPROC) windowProc;
  205205. wcex.lpszClassName = windowClassName;
  205206. wcex.cbClsExtra = 0;
  205207. wcex.cbWndExtra = 32;
  205208. wcex.hInstance = moduleHandle;
  205209. wcex.hIcon = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  205210. iconNum = 1;
  205211. wcex.hIconSm = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  205212. wcex.hCursor = 0;
  205213. wcex.hbrBackground = 0;
  205214. wcex.lpszMenuName = 0;
  205215. RegisterClassEx (&wcex);
  205216. }
  205217. ~WindowClassHolder()
  205218. {
  205219. if (ComponentPeer::getNumPeers() == 0)
  205220. UnregisterClass (windowClassName, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle());
  205221. clearSingletonInstance();
  205222. }
  205223. String windowClassName;
  205224. juce_DeclareSingleton_SingleThreaded_Minimal (WindowClassHolder);
  205225. };
  205226. static void* createWindowCallback (void* userData)
  205227. {
  205228. static_cast <Win32ComponentPeer*> (userData)->createWindow();
  205229. return 0;
  205230. }
  205231. void createWindow()
  205232. {
  205233. DWORD exstyle = WS_EX_ACCEPTFILES;
  205234. DWORD type = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  205235. if (hasTitleBar())
  205236. {
  205237. type |= WS_OVERLAPPED;
  205238. if ((styleFlags & windowHasCloseButton) != 0)
  205239. {
  205240. type |= WS_SYSMENU;
  205241. }
  205242. else
  205243. {
  205244. // annoyingly, windows won't let you have a min/max button without a close button
  205245. jassert ((styleFlags & (windowHasMinimiseButton | windowHasMaximiseButton)) == 0);
  205246. }
  205247. if ((styleFlags & windowIsResizable) != 0)
  205248. type |= WS_THICKFRAME;
  205249. }
  205250. else
  205251. {
  205252. type |= WS_POPUP | WS_SYSMENU;
  205253. }
  205254. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  205255. exstyle |= WS_EX_TOOLWINDOW;
  205256. else
  205257. exstyle |= WS_EX_APPWINDOW;
  205258. if ((styleFlags & windowHasMinimiseButton) != 0)
  205259. type |= WS_MINIMIZEBOX;
  205260. if ((styleFlags & windowHasMaximiseButton) != 0)
  205261. type |= WS_MAXIMIZEBOX;
  205262. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  205263. exstyle |= WS_EX_TRANSPARENT;
  205264. if ((styleFlags & windowIsSemiTransparent) != 0
  205265. && Desktop::canUseSemiTransparentWindows())
  205266. exstyle |= WS_EX_LAYERED;
  205267. hwnd = CreateWindowEx (exstyle, WindowClassHolder::getInstance()->windowClassName, L"", type, 0, 0, 0, 0, 0, 0, 0, 0);
  205268. if (hwnd != 0)
  205269. {
  205270. SetWindowLongPtr (hwnd, 0, 0);
  205271. SetWindowLongPtr (hwnd, 8, (LONG_PTR) this);
  205272. SetWindowLongPtr (hwnd, GWLP_USERDATA, improbableWindowNumber);
  205273. if (dropTarget == 0)
  205274. dropTarget = new JuceDropTarget (this);
  205275. RegisterDragDrop (hwnd, dropTarget);
  205276. updateBorderSize();
  205277. // Calling this function here is (for some reason) necessary to make Windows
  205278. // correctly enable the menu items that we specify in the wm_initmenu message.
  205279. GetSystemMenu (hwnd, false);
  205280. }
  205281. else
  205282. {
  205283. jassertfalse;
  205284. }
  205285. }
  205286. static void* destroyWindowCallback (void* handle)
  205287. {
  205288. RevokeDragDrop ((HWND) handle);
  205289. DestroyWindow ((HWND) handle);
  205290. return 0;
  205291. }
  205292. static void* toFrontCallback1 (void* h)
  205293. {
  205294. SetForegroundWindow ((HWND) h);
  205295. return 0;
  205296. }
  205297. static void* toFrontCallback2 (void* h)
  205298. {
  205299. SetWindowPos ((HWND) h, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  205300. return 0;
  205301. }
  205302. static void* setFocusCallback (void* h)
  205303. {
  205304. SetFocus ((HWND) h);
  205305. return 0;
  205306. }
  205307. static void* getFocusCallback (void*)
  205308. {
  205309. return GetFocus();
  205310. }
  205311. void offsetWithinParent (int& x, int& y) const
  205312. {
  205313. if (isTransparent())
  205314. {
  205315. HWND parentHwnd = GetParent (hwnd);
  205316. if (parentHwnd != 0)
  205317. {
  205318. RECT parentRect;
  205319. GetWindowRect (parentHwnd, &parentRect);
  205320. x += parentRect.left;
  205321. y += parentRect.top;
  205322. }
  205323. }
  205324. }
  205325. bool isTransparent() const
  205326. {
  205327. return (GetWindowLong (hwnd, GWL_EXSTYLE) & WS_EX_LAYERED) != 0;
  205328. }
  205329. inline bool hasTitleBar() const throw() { return (styleFlags & windowHasTitleBar) != 0; }
  205330. void setIcon (const Image& newIcon)
  205331. {
  205332. HICON hicon = createHICONFromImage (newIcon, TRUE, 0, 0);
  205333. if (hicon != 0)
  205334. {
  205335. SendMessage (hwnd, WM_SETICON, ICON_BIG, (LPARAM) hicon);
  205336. SendMessage (hwnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon);
  205337. if (currentWindowIcon != 0)
  205338. DestroyIcon (currentWindowIcon);
  205339. currentWindowIcon = hicon;
  205340. }
  205341. }
  205342. void handlePaintMessage()
  205343. {
  205344. HRGN rgn = CreateRectRgn (0, 0, 0, 0);
  205345. const int regionType = GetUpdateRgn (hwnd, rgn, false);
  205346. PAINTSTRUCT paintStruct;
  205347. HDC dc = BeginPaint (hwnd, &paintStruct); // Note this can immediately generate a WM_NCPAINT
  205348. // message and become re-entrant, but that's OK
  205349. // if something in a paint handler calls, e.g. a message box, this can become reentrant and
  205350. // corrupt the image it's using to paint into, so do a check here.
  205351. static bool reentrant = false;
  205352. if (reentrant)
  205353. {
  205354. DeleteObject (rgn);
  205355. EndPaint (hwnd, &paintStruct);
  205356. return;
  205357. }
  205358. reentrant = true;
  205359. // this is the rectangle to update..
  205360. int x = paintStruct.rcPaint.left;
  205361. int y = paintStruct.rcPaint.top;
  205362. int w = paintStruct.rcPaint.right - x;
  205363. int h = paintStruct.rcPaint.bottom - y;
  205364. const bool transparent = isTransparent();
  205365. if (transparent)
  205366. {
  205367. // it's not possible to have a transparent window with a title bar at the moment!
  205368. jassert (! hasTitleBar());
  205369. RECT r;
  205370. GetWindowRect (hwnd, &r);
  205371. x = y = 0;
  205372. w = r.right - r.left;
  205373. h = r.bottom - r.top;
  205374. }
  205375. if (w > 0 && h > 0)
  205376. {
  205377. clearMaskedRegion();
  205378. Image offscreenImage (offscreenImageGenerator.getImage (transparent, w, h));
  205379. RectangleList contextClip;
  205380. const Rectangle<int> clipBounds (0, 0, w, h);
  205381. bool needToPaintAll = true;
  205382. if (regionType == COMPLEXREGION && ! transparent)
  205383. {
  205384. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  205385. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  205386. DeleteObject (clipRgn);
  205387. char rgnData [8192];
  205388. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) rgnData);
  205389. if (res > 0 && res <= sizeof (rgnData))
  205390. {
  205391. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) rgnData)->rdh);
  205392. if (hdr->iType == RDH_RECTANGLES
  205393. && hdr->rcBound.right - hdr->rcBound.left >= w
  205394. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  205395. {
  205396. needToPaintAll = false;
  205397. const RECT* rects = (const RECT*) (rgnData + sizeof (RGNDATAHEADER));
  205398. int num = ((RGNDATA*) rgnData)->rdh.nCount;
  205399. while (--num >= 0)
  205400. {
  205401. if (rects->right <= x + w && rects->bottom <= y + h)
  205402. {
  205403. // (need to move this one pixel to the left because of a win32 bug)
  205404. const int cx = jmax (x, (int) rects->left - 1);
  205405. contextClip.addWithoutMerging (Rectangle<int> (cx - x, rects->top - y, rects->right - cx, rects->bottom - rects->top)
  205406. .getIntersection (clipBounds));
  205407. }
  205408. else
  205409. {
  205410. needToPaintAll = true;
  205411. break;
  205412. }
  205413. ++rects;
  205414. }
  205415. }
  205416. }
  205417. }
  205418. if (needToPaintAll)
  205419. {
  205420. contextClip.clear();
  205421. contextClip.addWithoutMerging (Rectangle<int> (0, 0, w, h));
  205422. }
  205423. if (transparent)
  205424. {
  205425. RectangleList::Iterator i (contextClip);
  205426. while (i.next())
  205427. offscreenImage.clear (*i.getRectangle());
  205428. }
  205429. // if the component's not opaque, this won't draw properly unless the platform can support this
  205430. jassert (Desktop::canUseSemiTransparentWindows() || component->isOpaque());
  205431. updateCurrentModifiers();
  205432. LowLevelGraphicsSoftwareRenderer context (offscreenImage, -x, -y, contextClip);
  205433. handlePaint (context);
  205434. if (! dontRepaint)
  205435. static_cast <WindowsBitmapImage*> (offscreenImage.getSharedImage())
  205436. ->blitToWindow (hwnd, dc, transparent, x, y, maskedRegion);
  205437. }
  205438. DeleteObject (rgn);
  205439. EndPaint (hwnd, &paintStruct);
  205440. reentrant = false;
  205441. #ifndef JUCE_GCC //xxx should add this fn for gcc..
  205442. _fpreset(); // because some graphics cards can unmask FP exceptions
  205443. #endif
  205444. lastPaintTime = Time::getMillisecondCounter();
  205445. }
  205446. void doMouseEvent (const Point<int>& position)
  205447. {
  205448. handleMouseEvent (0, position, currentModifiers, getMouseEventTime());
  205449. }
  205450. void doMouseMove (const Point<int>& position)
  205451. {
  205452. if (! isMouseOver)
  205453. {
  205454. isMouseOver = true;
  205455. updateKeyModifiers();
  205456. TRACKMOUSEEVENT tme;
  205457. tme.cbSize = sizeof (tme);
  205458. tme.dwFlags = TME_LEAVE;
  205459. tme.hwndTrack = hwnd;
  205460. tme.dwHoverTime = 0;
  205461. if (! TrackMouseEvent (&tme))
  205462. jassertfalse;
  205463. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  205464. }
  205465. else if (! isDragging)
  205466. {
  205467. if (! contains (position, false))
  205468. return;
  205469. }
  205470. // (Throttling the incoming queue of mouse-events seems to still be required in XP..)
  205471. static uint32 lastMouseTime = 0;
  205472. const uint32 now = Time::getMillisecondCounter();
  205473. const int maxMouseMovesPerSecond = 60;
  205474. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  205475. {
  205476. lastMouseTime = now;
  205477. doMouseEvent (position);
  205478. }
  205479. }
  205480. void doMouseDown (const Point<int>& position, const WPARAM wParam)
  205481. {
  205482. if (GetCapture() != hwnd)
  205483. SetCapture (hwnd);
  205484. doMouseMove (position);
  205485. updateModifiersFromWParam (wParam);
  205486. isDragging = true;
  205487. doMouseEvent (position);
  205488. }
  205489. void doMouseUp (const Point<int>& position, const WPARAM wParam)
  205490. {
  205491. updateModifiersFromWParam (wParam);
  205492. isDragging = false;
  205493. // release the mouse capture if the user has released all buttons
  205494. if ((wParam & (MK_LBUTTON | MK_RBUTTON | MK_MBUTTON)) == 0 && hwnd == GetCapture())
  205495. ReleaseCapture();
  205496. doMouseEvent (position);
  205497. }
  205498. void doCaptureChanged()
  205499. {
  205500. if (isDragging)
  205501. doMouseUp (getCurrentMousePos(), (WPARAM) 0);
  205502. }
  205503. void doMouseExit()
  205504. {
  205505. isMouseOver = false;
  205506. doMouseEvent (getCurrentMousePos());
  205507. }
  205508. void doMouseWheel (const Point<int>& position, const WPARAM wParam, const bool isVertical)
  205509. {
  205510. updateKeyModifiers();
  205511. const float amount = jlimit (-1000.0f, 1000.0f, 0.75f * (short) HIWORD (wParam));
  205512. handleMouseWheel (0, position, getMouseEventTime(),
  205513. isVertical ? 0.0f : amount,
  205514. isVertical ? amount : 0.0f);
  205515. }
  205516. void sendModifierKeyChangeIfNeeded()
  205517. {
  205518. if (modifiersAtLastCallback != currentModifiers)
  205519. {
  205520. modifiersAtLastCallback = currentModifiers;
  205521. handleModifierKeysChange();
  205522. }
  205523. }
  205524. bool doKeyUp (const WPARAM key)
  205525. {
  205526. updateKeyModifiers();
  205527. switch (key)
  205528. {
  205529. case VK_SHIFT:
  205530. case VK_CONTROL:
  205531. case VK_MENU:
  205532. case VK_CAPITAL:
  205533. case VK_LWIN:
  205534. case VK_RWIN:
  205535. case VK_APPS:
  205536. case VK_NUMLOCK:
  205537. case VK_SCROLL:
  205538. case VK_LSHIFT:
  205539. case VK_RSHIFT:
  205540. case VK_LCONTROL:
  205541. case VK_LMENU:
  205542. case VK_RCONTROL:
  205543. case VK_RMENU:
  205544. sendModifierKeyChangeIfNeeded();
  205545. }
  205546. return handleKeyUpOrDown (false)
  205547. || Component::getCurrentlyModalComponent() != 0;
  205548. }
  205549. bool doKeyDown (const WPARAM key)
  205550. {
  205551. updateKeyModifiers();
  205552. bool used = false;
  205553. switch (key)
  205554. {
  205555. case VK_SHIFT:
  205556. case VK_LSHIFT:
  205557. case VK_RSHIFT:
  205558. case VK_CONTROL:
  205559. case VK_LCONTROL:
  205560. case VK_RCONTROL:
  205561. case VK_MENU:
  205562. case VK_LMENU:
  205563. case VK_RMENU:
  205564. case VK_LWIN:
  205565. case VK_RWIN:
  205566. case VK_CAPITAL:
  205567. case VK_NUMLOCK:
  205568. case VK_SCROLL:
  205569. case VK_APPS:
  205570. sendModifierKeyChangeIfNeeded();
  205571. break;
  205572. case VK_LEFT:
  205573. case VK_RIGHT:
  205574. case VK_UP:
  205575. case VK_DOWN:
  205576. case VK_PRIOR:
  205577. case VK_NEXT:
  205578. case VK_HOME:
  205579. case VK_END:
  205580. case VK_DELETE:
  205581. case VK_INSERT:
  205582. case VK_F1:
  205583. case VK_F2:
  205584. case VK_F3:
  205585. case VK_F4:
  205586. case VK_F5:
  205587. case VK_F6:
  205588. case VK_F7:
  205589. case VK_F8:
  205590. case VK_F9:
  205591. case VK_F10:
  205592. case VK_F11:
  205593. case VK_F12:
  205594. case VK_F13:
  205595. case VK_F14:
  205596. case VK_F15:
  205597. case VK_F16:
  205598. used = handleKeyUpOrDown (true);
  205599. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  205600. break;
  205601. case VK_ADD:
  205602. case VK_SUBTRACT:
  205603. case VK_MULTIPLY:
  205604. case VK_DIVIDE:
  205605. case VK_SEPARATOR:
  205606. case VK_DECIMAL:
  205607. used = handleKeyUpOrDown (true);
  205608. break;
  205609. default:
  205610. used = handleKeyUpOrDown (true);
  205611. {
  205612. MSG msg;
  205613. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  205614. {
  205615. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  205616. // manually generate the key-press event that matches this key-down.
  205617. const UINT keyChar = MapVirtualKey (key, 2);
  205618. used = handleKeyPress ((int) LOWORD (keyChar), 0) || used;
  205619. }
  205620. }
  205621. break;
  205622. }
  205623. if (Component::getCurrentlyModalComponent() != 0)
  205624. used = true;
  205625. return used;
  205626. }
  205627. bool doKeyChar (int key, const LPARAM flags)
  205628. {
  205629. updateKeyModifiers();
  205630. juce_wchar textChar = (juce_wchar) key;
  205631. const int virtualScanCode = (flags >> 16) & 0xff;
  205632. if (key >= '0' && key <= '9')
  205633. {
  205634. switch (virtualScanCode) // check for a numeric keypad scan-code
  205635. {
  205636. case 0x52:
  205637. case 0x4f:
  205638. case 0x50:
  205639. case 0x51:
  205640. case 0x4b:
  205641. case 0x4c:
  205642. case 0x4d:
  205643. case 0x47:
  205644. case 0x48:
  205645. case 0x49:
  205646. key = (key - '0') + KeyPress::numberPad0;
  205647. break;
  205648. default:
  205649. break;
  205650. }
  205651. }
  205652. else
  205653. {
  205654. // convert the scan code to an unmodified character code..
  205655. const UINT virtualKey = MapVirtualKey (virtualScanCode, 1);
  205656. UINT keyChar = MapVirtualKey (virtualKey, 2);
  205657. keyChar = LOWORD (keyChar);
  205658. if (keyChar != 0)
  205659. key = (int) keyChar;
  205660. // avoid sending junk text characters for some control-key combinations
  205661. if (textChar < ' ' && currentModifiers.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::altModifier))
  205662. textChar = 0;
  205663. }
  205664. return handleKeyPress (key, textChar);
  205665. }
  205666. bool doAppCommand (const LPARAM lParam)
  205667. {
  205668. int key = 0;
  205669. switch (GET_APPCOMMAND_LPARAM (lParam))
  205670. {
  205671. case APPCOMMAND_MEDIA_PLAY_PAUSE:
  205672. key = KeyPress::playKey;
  205673. break;
  205674. case APPCOMMAND_MEDIA_STOP:
  205675. key = KeyPress::stopKey;
  205676. break;
  205677. case APPCOMMAND_MEDIA_NEXTTRACK:
  205678. key = KeyPress::fastForwardKey;
  205679. break;
  205680. case APPCOMMAND_MEDIA_PREVIOUSTRACK:
  205681. key = KeyPress::rewindKey;
  205682. break;
  205683. }
  205684. if (key != 0)
  205685. {
  205686. updateKeyModifiers();
  205687. if (hwnd == GetActiveWindow())
  205688. {
  205689. handleKeyPress (key, 0);
  205690. return true;
  205691. }
  205692. }
  205693. return false;
  205694. }
  205695. class JuceDropTarget : public ComBaseClassHelper <IDropTarget>
  205696. {
  205697. public:
  205698. JuceDropTarget (Win32ComponentPeer* const owner_)
  205699. : owner (owner_)
  205700. {
  205701. }
  205702. ~JuceDropTarget() {}
  205703. HRESULT __stdcall DragEnter (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  205704. {
  205705. updateFileList (pDataObject);
  205706. owner->handleFileDragMove (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  205707. *pdwEffect = DROPEFFECT_COPY;
  205708. return S_OK;
  205709. }
  205710. HRESULT __stdcall DragLeave()
  205711. {
  205712. owner->handleFileDragExit (files);
  205713. return S_OK;
  205714. }
  205715. HRESULT __stdcall DragOver (DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  205716. {
  205717. owner->handleFileDragMove (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  205718. *pdwEffect = DROPEFFECT_COPY;
  205719. return S_OK;
  205720. }
  205721. HRESULT __stdcall Drop (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  205722. {
  205723. updateFileList (pDataObject);
  205724. owner->handleFileDragDrop (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  205725. *pdwEffect = DROPEFFECT_COPY;
  205726. return S_OK;
  205727. }
  205728. private:
  205729. Win32ComponentPeer* const owner;
  205730. StringArray files;
  205731. void updateFileList (IDataObject* const pDataObject)
  205732. {
  205733. files.clear();
  205734. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  205735. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  205736. if (pDataObject->GetData (&format, &medium) == S_OK)
  205737. {
  205738. const SIZE_T totalLen = GlobalSize (medium.hGlobal);
  205739. const LPDROPFILES pDropFiles = (const LPDROPFILES) GlobalLock (medium.hGlobal);
  205740. unsigned int i = 0;
  205741. if (pDropFiles->fWide)
  205742. {
  205743. const WCHAR* const fname = (WCHAR*) (((const char*) pDropFiles) + sizeof (DROPFILES));
  205744. for (;;)
  205745. {
  205746. unsigned int len = 0;
  205747. while (i + len < totalLen && fname [i + len] != 0)
  205748. ++len;
  205749. if (len == 0)
  205750. break;
  205751. files.add (String (fname + i, len));
  205752. i += len + 1;
  205753. }
  205754. }
  205755. else
  205756. {
  205757. const char* const fname = ((const char*) pDropFiles) + sizeof (DROPFILES);
  205758. for (;;)
  205759. {
  205760. unsigned int len = 0;
  205761. while (i + len < totalLen && fname [i + len] != 0)
  205762. ++len;
  205763. if (len == 0)
  205764. break;
  205765. files.add (String (fname + i, len));
  205766. i += len + 1;
  205767. }
  205768. }
  205769. GlobalUnlock (medium.hGlobal);
  205770. }
  205771. }
  205772. JuceDropTarget (const JuceDropTarget&);
  205773. JuceDropTarget& operator= (const JuceDropTarget&);
  205774. };
  205775. void doSettingChange()
  205776. {
  205777. Desktop::getInstance().refreshMonitorSizes();
  205778. if (fullScreen && ! isMinimised())
  205779. {
  205780. const Rectangle<int> r (component->getParentMonitorArea());
  205781. SetWindowPos (hwnd, 0,
  205782. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  205783. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  205784. }
  205785. }
  205786. public:
  205787. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  205788. {
  205789. Win32ComponentPeer* const peer = getOwnerOfWindow (h);
  205790. if (peer != 0)
  205791. return peer->peerWindowProc (h, message, wParam, lParam);
  205792. return DefWindowProcW (h, message, wParam, lParam);
  205793. }
  205794. private:
  205795. static const Point<int> getPointFromLParam (LPARAM lParam) throw()
  205796. {
  205797. return Point<int> (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam));
  205798. }
  205799. const Point<int> getCurrentMousePos() throw()
  205800. {
  205801. RECT wr;
  205802. GetWindowRect (hwnd, &wr);
  205803. const DWORD mp = GetMessagePos();
  205804. return Point<int> (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  205805. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop());
  205806. }
  205807. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  205808. {
  205809. if (isValidPeer (this))
  205810. {
  205811. switch (message)
  205812. {
  205813. case WM_NCHITTEST:
  205814. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  205815. return HTTRANSPARENT;
  205816. if (hasTitleBar())
  205817. break;
  205818. return HTCLIENT;
  205819. case WM_PAINT:
  205820. handlePaintMessage();
  205821. return 0;
  205822. case WM_NCPAINT:
  205823. if (wParam != 1)
  205824. handlePaintMessage();
  205825. if (hasTitleBar())
  205826. break;
  205827. return 0;
  205828. case WM_ERASEBKGND:
  205829. case WM_NCCALCSIZE:
  205830. if (hasTitleBar())
  205831. break;
  205832. return 1;
  205833. case WM_MOUSEMOVE:
  205834. doMouseMove (getPointFromLParam (lParam));
  205835. return 0;
  205836. case WM_MOUSELEAVE:
  205837. doMouseExit();
  205838. return 0;
  205839. case WM_LBUTTONDOWN:
  205840. case WM_MBUTTONDOWN:
  205841. case WM_RBUTTONDOWN:
  205842. doMouseDown (getPointFromLParam (lParam), wParam);
  205843. return 0;
  205844. case WM_LBUTTONUP:
  205845. case WM_MBUTTONUP:
  205846. case WM_RBUTTONUP:
  205847. doMouseUp (getPointFromLParam (lParam), wParam);
  205848. return 0;
  205849. case WM_CAPTURECHANGED:
  205850. doCaptureChanged();
  205851. return 0;
  205852. case WM_NCMOUSEMOVE:
  205853. if (hasTitleBar())
  205854. break;
  205855. return 0;
  205856. case 0x020A: /* WM_MOUSEWHEEL */
  205857. doMouseWheel (getCurrentMousePos(), wParam, true);
  205858. return 0;
  205859. case 0x020E: /* WM_MOUSEHWHEEL */
  205860. doMouseWheel (getCurrentMousePos(), wParam, false);
  205861. return 0;
  205862. case WM_WINDOWPOSCHANGING:
  205863. if ((styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable))
  205864. {
  205865. WINDOWPOS* const wp = (WINDOWPOS*) lParam;
  205866. if ((wp->flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE))
  205867. {
  205868. if (constrainer != 0)
  205869. {
  205870. const Rectangle<int> current (component->getX() - windowBorder.getLeft(),
  205871. component->getY() - windowBorder.getTop(),
  205872. component->getWidth() + windowBorder.getLeftAndRight(),
  205873. component->getHeight() + windowBorder.getTopAndBottom());
  205874. Rectangle<int> pos (wp->x, wp->y, wp->cx, wp->cy);
  205875. constrainer->checkBounds (pos, current,
  205876. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  205877. pos.getY() != current.getY() && pos.getBottom() == current.getBottom(),
  205878. pos.getX() != current.getX() && pos.getRight() == current.getRight(),
  205879. pos.getY() == current.getY() && pos.getBottom() != current.getBottom(),
  205880. pos.getX() == current.getX() && pos.getRight() != current.getRight());
  205881. wp->x = pos.getX();
  205882. wp->y = pos.getY();
  205883. wp->cx = pos.getWidth();
  205884. wp->cy = pos.getHeight();
  205885. }
  205886. }
  205887. }
  205888. return 0;
  205889. case WM_WINDOWPOSCHANGED:
  205890. handleMovedOrResized();
  205891. if (dontRepaint)
  205892. break; // needed for non-accelerated openGL windows to draw themselves correctly..
  205893. return 0;
  205894. case WM_KEYDOWN:
  205895. case WM_SYSKEYDOWN:
  205896. if (doKeyDown (wParam))
  205897. return 0;
  205898. break;
  205899. case WM_KEYUP:
  205900. case WM_SYSKEYUP:
  205901. if (doKeyUp (wParam))
  205902. return 0;
  205903. break;
  205904. case WM_CHAR:
  205905. if (doKeyChar ((int) wParam, lParam))
  205906. return 0;
  205907. break;
  205908. case WM_APPCOMMAND:
  205909. if (doAppCommand (lParam))
  205910. return TRUE;
  205911. break;
  205912. case WM_SETFOCUS:
  205913. updateKeyModifiers();
  205914. handleFocusGain();
  205915. break;
  205916. case WM_KILLFOCUS:
  205917. if (hasCreatedCaret)
  205918. {
  205919. hasCreatedCaret = false;
  205920. DestroyCaret();
  205921. }
  205922. handleFocusLoss();
  205923. break;
  205924. case WM_ACTIVATEAPP:
  205925. // Windows does weird things to process priority when you swap apps,
  205926. // so this forces an update when the app is brought to the front
  205927. if (wParam != FALSE)
  205928. juce_repeatLastProcessPriority();
  205929. else
  205930. Desktop::getInstance().setKioskModeComponent (0); // turn kiosk mode off if we lose focus
  205931. juce_CheckCurrentlyFocusedTopLevelWindow();
  205932. modifiersAtLastCallback = -1;
  205933. return 0;
  205934. case WM_ACTIVATE:
  205935. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  205936. {
  205937. modifiersAtLastCallback = -1;
  205938. updateKeyModifiers();
  205939. if (isMinimised())
  205940. {
  205941. component->repaint();
  205942. handleMovedOrResized();
  205943. if (! ComponentPeer::isValidPeer (this))
  205944. return 0;
  205945. }
  205946. if (LOWORD (wParam) == WA_CLICKACTIVE
  205947. && component->isCurrentlyBlockedByAnotherModalComponent())
  205948. {
  205949. const Point<int> mousePos (component->getMouseXYRelative());
  205950. Component* const underMouse = component->getComponentAt (mousePos.getX(), mousePos.getY());
  205951. if (underMouse != 0 && underMouse->isCurrentlyBlockedByAnotherModalComponent())
  205952. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  205953. return 0;
  205954. }
  205955. handleBroughtToFront();
  205956. if (component->isCurrentlyBlockedByAnotherModalComponent())
  205957. Component::getCurrentlyModalComponent()->toFront (true);
  205958. return 0;
  205959. }
  205960. break;
  205961. case WM_NCACTIVATE:
  205962. // while a temporary window is being shown, prevent Windows from deactivating the
  205963. // title bars of our main windows.
  205964. if (wParam == 0 && ! shouldDeactivateTitleBar)
  205965. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  205966. break;
  205967. case WM_MOUSEACTIVATE:
  205968. if (! component->getMouseClickGrabsKeyboardFocus())
  205969. return MA_NOACTIVATE;
  205970. break;
  205971. case WM_SHOWWINDOW:
  205972. if (wParam != 0)
  205973. handleBroughtToFront();
  205974. break;
  205975. case WM_CLOSE:
  205976. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  205977. handleUserClosingWindow();
  205978. return 0;
  205979. case WM_QUERYENDSESSION:
  205980. if (JUCEApplication::getInstance() != 0)
  205981. {
  205982. JUCEApplication::getInstance()->systemRequestedQuit();
  205983. return MessageManager::getInstance()->hasStopMessageBeenSent();
  205984. }
  205985. return TRUE;
  205986. case WM_TRAYNOTIFY:
  205987. if (component->isCurrentlyBlockedByAnotherModalComponent())
  205988. {
  205989. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN
  205990. || lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  205991. {
  205992. Component* const current = Component::getCurrentlyModalComponent();
  205993. if (current != 0)
  205994. current->inputAttemptWhenModal();
  205995. }
  205996. }
  205997. else
  205998. {
  205999. ModifierKeys eventMods (ModifierKeys::getCurrentModifiersRealtime());
  206000. if (lParam == WM_LBUTTONDOWN || lParam == WM_LBUTTONDBLCLK)
  206001. eventMods = eventMods.withFlags (ModifierKeys::leftButtonModifier);
  206002. else if (lParam == WM_RBUTTONDOWN || lParam == WM_RBUTTONDBLCLK)
  206003. eventMods = eventMods.withFlags (ModifierKeys::rightButtonModifier);
  206004. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  206005. eventMods = eventMods.withoutMouseButtons();
  206006. const MouseEvent e (Desktop::getInstance().getMainMouseSource(),
  206007. Point<int>(), eventMods, component, component, getMouseEventTime(),
  206008. Point<int>(), getMouseEventTime(), 1, false);
  206009. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN)
  206010. {
  206011. SetFocus (hwnd);
  206012. SetForegroundWindow (hwnd);
  206013. component->mouseDown (e);
  206014. }
  206015. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  206016. {
  206017. component->mouseUp (e);
  206018. }
  206019. else if (lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  206020. {
  206021. component->mouseDoubleClick (e);
  206022. }
  206023. else if (lParam == WM_MOUSEMOVE)
  206024. {
  206025. component->mouseMove (e);
  206026. }
  206027. }
  206028. break;
  206029. case WM_SYNCPAINT:
  206030. return 0;
  206031. case WM_PALETTECHANGED:
  206032. InvalidateRect (h, 0, 0);
  206033. break;
  206034. case WM_DISPLAYCHANGE:
  206035. InvalidateRect (h, 0, 0);
  206036. createPaletteIfNeeded = true;
  206037. // intentional fall-through...
  206038. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  206039. doSettingChange();
  206040. break;
  206041. case WM_INITMENU:
  206042. if (! hasTitleBar())
  206043. {
  206044. if (isFullScreen())
  206045. {
  206046. EnableMenuItem ((HMENU) wParam, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  206047. EnableMenuItem ((HMENU) wParam, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  206048. }
  206049. else if (! isMinimised())
  206050. {
  206051. EnableMenuItem ((HMENU) wParam, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  206052. }
  206053. }
  206054. break;
  206055. case WM_SYSCOMMAND:
  206056. switch (wParam & 0xfff0)
  206057. {
  206058. case SC_CLOSE:
  206059. if (sendInputAttemptWhenModalMessage())
  206060. return 0;
  206061. if (hasTitleBar())
  206062. {
  206063. PostMessage (h, WM_CLOSE, 0, 0);
  206064. return 0;
  206065. }
  206066. break;
  206067. case SC_KEYMENU:
  206068. // (NB mustn't call sendInputAttemptWhenModalMessage() here because of very
  206069. // obscure situations that can arise if a modal loop is started from an alt-key
  206070. // keypress).
  206071. if (hasTitleBar() && h == GetCapture())
  206072. ReleaseCapture();
  206073. break;
  206074. case SC_MAXIMIZE:
  206075. if (sendInputAttemptWhenModalMessage())
  206076. return 0;
  206077. setFullScreen (true);
  206078. return 0;
  206079. case SC_MINIMIZE:
  206080. if (sendInputAttemptWhenModalMessage())
  206081. return 0;
  206082. if (! hasTitleBar())
  206083. {
  206084. setMinimised (true);
  206085. return 0;
  206086. }
  206087. break;
  206088. case SC_RESTORE:
  206089. if (sendInputAttemptWhenModalMessage())
  206090. return 0;
  206091. if (hasTitleBar())
  206092. {
  206093. if (isFullScreen())
  206094. {
  206095. setFullScreen (false);
  206096. return 0;
  206097. }
  206098. }
  206099. else
  206100. {
  206101. if (isMinimised())
  206102. setMinimised (false);
  206103. else if (isFullScreen())
  206104. setFullScreen (false);
  206105. return 0;
  206106. }
  206107. break;
  206108. }
  206109. break;
  206110. case WM_NCLBUTTONDOWN:
  206111. case WM_NCRBUTTONDOWN:
  206112. case WM_NCMBUTTONDOWN:
  206113. sendInputAttemptWhenModalMessage();
  206114. break;
  206115. //case WM_IME_STARTCOMPOSITION;
  206116. // return 0;
  206117. case WM_GETDLGCODE:
  206118. return DLGC_WANTALLKEYS;
  206119. default:
  206120. break;
  206121. }
  206122. }
  206123. return DefWindowProcW (h, message, wParam, lParam);
  206124. }
  206125. bool sendInputAttemptWhenModalMessage()
  206126. {
  206127. if (component->isCurrentlyBlockedByAnotherModalComponent())
  206128. {
  206129. Component* const current = Component::getCurrentlyModalComponent();
  206130. if (current != 0)
  206131. current->inputAttemptWhenModal();
  206132. return true;
  206133. }
  206134. return false;
  206135. }
  206136. Win32ComponentPeer (const Win32ComponentPeer&);
  206137. Win32ComponentPeer& operator= (const Win32ComponentPeer&);
  206138. };
  206139. ModifierKeys Win32ComponentPeer::currentModifiers;
  206140. ModifierKeys Win32ComponentPeer::modifiersAtLastCallback;
  206141. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  206142. {
  206143. return new Win32ComponentPeer (this, styleFlags);
  206144. }
  206145. juce_ImplementSingleton_SingleThreaded (Win32ComponentPeer::WindowClassHolder);
  206146. void ModifierKeys::updateCurrentModifiers() throw()
  206147. {
  206148. currentModifiers = Win32ComponentPeer::currentModifiers;
  206149. }
  206150. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  206151. {
  206152. Win32ComponentPeer::updateKeyModifiers();
  206153. int keyMods = 0;
  206154. if ((GetKeyState (VK_LBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::leftButtonModifier;
  206155. if ((GetKeyState (VK_RBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::rightButtonModifier;
  206156. if ((GetKeyState (VK_MBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::middleButtonModifier;
  206157. Win32ComponentPeer::currentModifiers
  206158. = Win32ComponentPeer::currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  206159. return Win32ComponentPeer::currentModifiers;
  206160. }
  206161. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  206162. {
  206163. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  206164. if (wp != 0)
  206165. wp->setTaskBarIcon (newImage);
  206166. }
  206167. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  206168. {
  206169. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  206170. if (wp != 0)
  206171. wp->setTaskBarIconToolTip (tooltip);
  206172. }
  206173. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw()
  206174. {
  206175. DWORD val = GetWindowLong (h, styleType);
  206176. if (bitIsSet)
  206177. val |= feature;
  206178. else
  206179. val &= ~feature;
  206180. SetWindowLongPtr (h, styleType, val);
  206181. SetWindowPos (h, 0, 0, 0, 0, 0,
  206182. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER
  206183. | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSENDCHANGING);
  206184. }
  206185. bool Process::isForegroundProcess()
  206186. {
  206187. HWND fg = GetForegroundWindow();
  206188. if (fg == 0)
  206189. return true;
  206190. // when running as a plugin in IE8, the browser UI runs in a different process to the plugin, so
  206191. // process ID isn't a reliable way to check if the foreground window belongs to us - instead, we
  206192. // have to see if any of our windows are children of the foreground window
  206193. fg = GetAncestor (fg, GA_ROOT);
  206194. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  206195. {
  206196. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (ComponentPeer::getPeer (i));
  206197. if (wp != 0 && wp->isInside (fg))
  206198. return true;
  206199. }
  206200. return false;
  206201. }
  206202. bool AlertWindow::showNativeDialogBox (const String& title,
  206203. const String& bodyText,
  206204. bool isOkCancel)
  206205. {
  206206. return MessageBox (0, bodyText, title,
  206207. MB_SETFOREGROUND | (isOkCancel ? MB_OKCANCEL
  206208. : MB_OK)) == IDOK;
  206209. }
  206210. void Desktop::createMouseInputSources()
  206211. {
  206212. mouseSources.add (new MouseInputSource (0, true));
  206213. }
  206214. const Point<int> Desktop::getMousePosition()
  206215. {
  206216. POINT mousePos;
  206217. GetCursorPos (&mousePos);
  206218. return Point<int> (mousePos.x, mousePos.y);
  206219. }
  206220. void Desktop::setMousePosition (const Point<int>& newPosition)
  206221. {
  206222. SetCursorPos (newPosition.getX(), newPosition.getY());
  206223. }
  206224. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  206225. {
  206226. return createSoftwareImage (format, width, height, clearImage);
  206227. }
  206228. class ScreenSaverDefeater : public Timer,
  206229. public DeletedAtShutdown
  206230. {
  206231. public:
  206232. ScreenSaverDefeater()
  206233. {
  206234. startTimer (10000);
  206235. timerCallback();
  206236. }
  206237. ~ScreenSaverDefeater() {}
  206238. void timerCallback()
  206239. {
  206240. if (Process::isForegroundProcess())
  206241. {
  206242. // simulate a shift key getting pressed..
  206243. INPUT input[2];
  206244. input[0].type = INPUT_KEYBOARD;
  206245. input[0].ki.wVk = VK_SHIFT;
  206246. input[0].ki.dwFlags = 0;
  206247. input[0].ki.dwExtraInfo = 0;
  206248. input[1].type = INPUT_KEYBOARD;
  206249. input[1].ki.wVk = VK_SHIFT;
  206250. input[1].ki.dwFlags = KEYEVENTF_KEYUP;
  206251. input[1].ki.dwExtraInfo = 0;
  206252. SendInput (2, input, sizeof (INPUT));
  206253. }
  206254. }
  206255. };
  206256. static ScreenSaverDefeater* screenSaverDefeater = 0;
  206257. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  206258. {
  206259. if (isEnabled)
  206260. deleteAndZero (screenSaverDefeater);
  206261. else if (screenSaverDefeater == 0)
  206262. screenSaverDefeater = new ScreenSaverDefeater();
  206263. }
  206264. bool Desktop::isScreenSaverEnabled()
  206265. {
  206266. return screenSaverDefeater == 0;
  206267. }
  206268. /* (The code below is the "correct" way to disable the screen saver, but it
  206269. completely fails on winXP when the saver is password-protected...)
  206270. static bool juce_screenSaverEnabled = true;
  206271. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  206272. {
  206273. juce_screenSaverEnabled = isEnabled;
  206274. SetThreadExecutionState (isEnabled ? ES_CONTINUOUS
  206275. : (ES_DISPLAY_REQUIRED | ES_CONTINUOUS));
  206276. }
  206277. bool Desktop::isScreenSaverEnabled() throw()
  206278. {
  206279. return juce_screenSaverEnabled;
  206280. }
  206281. */
  206282. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool /*allowMenusAndBars*/)
  206283. {
  206284. if (enableOrDisable)
  206285. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  206286. }
  206287. static BOOL CALLBACK enumMonitorsProc (HMONITOR, HDC, LPRECT r, LPARAM userInfo)
  206288. {
  206289. Array <Rectangle<int> >* const monitorCoords = (Array <Rectangle<int> >*) userInfo;
  206290. monitorCoords->add (Rectangle<int> (r->left, r->top, r->right - r->left, r->bottom - r->top));
  206291. return TRUE;
  206292. }
  206293. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  206294. {
  206295. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitorCoords);
  206296. // make sure the first in the list is the main monitor
  206297. for (int i = 1; i < monitorCoords.size(); ++i)
  206298. if (monitorCoords[i].getX() == 0 && monitorCoords[i].getY() == 0)
  206299. monitorCoords.swap (i, 0);
  206300. if (monitorCoords.size() == 0)
  206301. {
  206302. RECT r;
  206303. GetWindowRect (GetDesktopWindow(), &r);
  206304. monitorCoords.add (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  206305. }
  206306. if (clipToWorkArea)
  206307. {
  206308. // clip the main monitor to the active non-taskbar area
  206309. RECT r;
  206310. SystemParametersInfo (SPI_GETWORKAREA, 0, &r, 0);
  206311. Rectangle<int>& screen = monitorCoords.getReference (0);
  206312. screen.setPosition (jmax (screen.getX(), (int) r.left),
  206313. jmax (screen.getY(), (int) r.top));
  206314. screen.setSize (jmin (screen.getRight(), (int) r.right) - screen.getX(),
  206315. jmin (screen.getBottom(), (int) r.bottom) - screen.getY());
  206316. }
  206317. }
  206318. static const Image createImageFromHBITMAP (HBITMAP bitmap) throw()
  206319. {
  206320. Image im;
  206321. if (bitmap != 0)
  206322. {
  206323. BITMAP bm;
  206324. if (GetObject (bitmap, sizeof (BITMAP), &bm)
  206325. && bm.bmWidth > 0 && bm.bmHeight > 0)
  206326. {
  206327. HDC tempDC = GetDC (0);
  206328. HDC dc = CreateCompatibleDC (tempDC);
  206329. ReleaseDC (0, tempDC);
  206330. SelectObject (dc, bitmap);
  206331. im = Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true);
  206332. Image::BitmapData imageData (im, 0, 0, bm.bmWidth, bm.bmHeight, true);
  206333. for (int y = bm.bmHeight; --y >= 0;)
  206334. {
  206335. for (int x = bm.bmWidth; --x >= 0;)
  206336. {
  206337. COLORREF col = GetPixel (dc, x, y);
  206338. imageData.setPixelColour (x, y, Colour ((uint8) GetRValue (col),
  206339. (uint8) GetGValue (col),
  206340. (uint8) GetBValue (col)));
  206341. }
  206342. }
  206343. DeleteDC (dc);
  206344. }
  206345. }
  206346. return im;
  206347. }
  206348. static const Image createImageFromHICON (HICON icon) throw()
  206349. {
  206350. ICONINFO info;
  206351. if (GetIconInfo (icon, &info))
  206352. {
  206353. Image mask (createImageFromHBITMAP (info.hbmMask));
  206354. Image image (createImageFromHBITMAP (info.hbmColor));
  206355. if (mask.isValid() && image.isValid())
  206356. {
  206357. for (int y = image.getHeight(); --y >= 0;)
  206358. {
  206359. for (int x = image.getWidth(); --x >= 0;)
  206360. {
  206361. const float brightness = mask.getPixelAt (x, y).getBrightness();
  206362. if (brightness > 0.0f)
  206363. image.multiplyAlphaAt (x, y, 1.0f - brightness);
  206364. }
  206365. }
  206366. return image;
  206367. }
  206368. }
  206369. return Image();
  206370. }
  206371. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY) throw()
  206372. {
  206373. WindowsBitmapImage* nativeBitmap = new WindowsBitmapImage (Image::ARGB, image.getWidth(), image.getHeight(), true);
  206374. Image bitmap (nativeBitmap);
  206375. {
  206376. Graphics g (bitmap);
  206377. g.drawImageAt (image, 0, 0);
  206378. }
  206379. HBITMAP mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, 0);
  206380. ICONINFO info;
  206381. info.fIcon = isIcon;
  206382. info.xHotspot = hotspotX;
  206383. info.yHotspot = hotspotY;
  206384. info.hbmMask = mask;
  206385. info.hbmColor = nativeBitmap->hBitmap;
  206386. HICON hi = CreateIconIndirect (&info);
  206387. DeleteObject (mask);
  206388. return hi;
  206389. }
  206390. const Image juce_createIconForFile (const File& file)
  206391. {
  206392. Image image;
  206393. WCHAR filename [1024];
  206394. file.getFullPathName().copyToUnicode (filename, 1023);
  206395. WORD iconNum = 0;
  206396. HICON icon = ExtractAssociatedIcon ((HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(),
  206397. filename, &iconNum);
  206398. if (icon != 0)
  206399. {
  206400. image = createImageFromHICON (icon);
  206401. DestroyIcon (icon);
  206402. }
  206403. return image;
  206404. }
  206405. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  206406. {
  206407. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  206408. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  206409. Image im (image);
  206410. if (im.getWidth() > maxW || im.getHeight() > maxH)
  206411. {
  206412. im = im.rescaled (maxW, maxH);
  206413. hotspotX = (hotspotX * maxW) / image.getWidth();
  206414. hotspotY = (hotspotY * maxH) / image.getHeight();
  206415. }
  206416. return createHICONFromImage (im, FALSE, hotspotX, hotspotY);
  206417. }
  206418. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard)
  206419. {
  206420. if (cursorHandle != 0 && ! isStandard)
  206421. DestroyCursor ((HCURSOR) cursorHandle);
  206422. }
  206423. void* MouseCursor::createStandardMouseCursor (const MouseCursor::StandardCursorType type)
  206424. {
  206425. LPCTSTR cursorName = IDC_ARROW;
  206426. switch (type)
  206427. {
  206428. case NormalCursor: break;
  206429. case NoCursor: return 0;
  206430. case WaitCursor: cursorName = IDC_WAIT; break;
  206431. case IBeamCursor: cursorName = IDC_IBEAM; break;
  206432. case PointingHandCursor: cursorName = MAKEINTRESOURCE(32649); break;
  206433. case CrosshairCursor: cursorName = IDC_CROSS; break;
  206434. case CopyingCursor: break; // can't seem to find one of these in the win32 list..
  206435. case LeftRightResizeCursor:
  206436. case LeftEdgeResizeCursor:
  206437. case RightEdgeResizeCursor: cursorName = IDC_SIZEWE; break;
  206438. case UpDownResizeCursor:
  206439. case TopEdgeResizeCursor:
  206440. case BottomEdgeResizeCursor: cursorName = IDC_SIZENS; break;
  206441. case TopLeftCornerResizeCursor:
  206442. case BottomRightCornerResizeCursor: cursorName = IDC_SIZENWSE; break;
  206443. case TopRightCornerResizeCursor:
  206444. case BottomLeftCornerResizeCursor: cursorName = IDC_SIZENESW; break;
  206445. case UpDownLeftRightResizeCursor: cursorName = IDC_SIZEALL; break;
  206446. case DraggingHandCursor:
  206447. {
  206448. static void* dragHandCursor = 0;
  206449. if (dragHandCursor == 0)
  206450. {
  206451. static const unsigned char dragHandData[] =
  206452. { 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,
  206453. 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,
  206454. 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 };
  206455. dragHandCursor = createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, sizeof (dragHandData)), 8, 7);
  206456. }
  206457. return dragHandCursor;
  206458. }
  206459. default:
  206460. jassertfalse; break;
  206461. }
  206462. HCURSOR cursorH = LoadCursor (0, cursorName);
  206463. if (cursorH == 0)
  206464. cursorH = LoadCursor (0, IDC_ARROW);
  206465. return cursorH;
  206466. }
  206467. void MouseCursor::showInWindow (ComponentPeer*) const
  206468. {
  206469. SetCursor ((HCURSOR) getHandle());
  206470. }
  206471. void MouseCursor::showInAllWindows() const
  206472. {
  206473. showInWindow (0);
  206474. }
  206475. class JuceDropSource : public ComBaseClassHelper <IDropSource>
  206476. {
  206477. public:
  206478. JuceDropSource() {}
  206479. ~JuceDropSource() {}
  206480. HRESULT __stdcall QueryContinueDrag (BOOL escapePressed, DWORD keys)
  206481. {
  206482. if (escapePressed)
  206483. return DRAGDROP_S_CANCEL;
  206484. if ((keys & (MK_LBUTTON | MK_RBUTTON)) == 0)
  206485. return DRAGDROP_S_DROP;
  206486. return S_OK;
  206487. }
  206488. HRESULT __stdcall GiveFeedback (DWORD)
  206489. {
  206490. return DRAGDROP_S_USEDEFAULTCURSORS;
  206491. }
  206492. };
  206493. class JuceEnumFormatEtc : public ComBaseClassHelper <IEnumFORMATETC>
  206494. {
  206495. public:
  206496. JuceEnumFormatEtc (const FORMATETC* const format_)
  206497. : format (format_),
  206498. index (0)
  206499. {
  206500. }
  206501. ~JuceEnumFormatEtc() {}
  206502. HRESULT __stdcall Clone (IEnumFORMATETC** result)
  206503. {
  206504. if (result == 0)
  206505. return E_POINTER;
  206506. JuceEnumFormatEtc* const newOne = new JuceEnumFormatEtc (format);
  206507. newOne->index = index;
  206508. *result = newOne;
  206509. return S_OK;
  206510. }
  206511. HRESULT __stdcall Next (ULONG celt, LPFORMATETC lpFormatEtc, ULONG* pceltFetched)
  206512. {
  206513. if (pceltFetched != 0)
  206514. *pceltFetched = 0;
  206515. else if (celt != 1)
  206516. return S_FALSE;
  206517. if (index == 0 && celt > 0 && lpFormatEtc != 0)
  206518. {
  206519. copyFormatEtc (lpFormatEtc [0], *format);
  206520. ++index;
  206521. if (pceltFetched != 0)
  206522. *pceltFetched = 1;
  206523. return S_OK;
  206524. }
  206525. return S_FALSE;
  206526. }
  206527. HRESULT __stdcall Skip (ULONG celt)
  206528. {
  206529. if (index + (int) celt >= 1)
  206530. return S_FALSE;
  206531. index += celt;
  206532. return S_OK;
  206533. }
  206534. HRESULT __stdcall Reset()
  206535. {
  206536. index = 0;
  206537. return S_OK;
  206538. }
  206539. private:
  206540. const FORMATETC* const format;
  206541. int index;
  206542. static void copyFormatEtc (FORMATETC& dest, const FORMATETC& source)
  206543. {
  206544. dest = source;
  206545. if (source.ptd != 0)
  206546. {
  206547. dest.ptd = (DVTARGETDEVICE*) CoTaskMemAlloc (sizeof (DVTARGETDEVICE));
  206548. *(dest.ptd) = *(source.ptd);
  206549. }
  206550. }
  206551. JuceEnumFormatEtc (const JuceEnumFormatEtc&);
  206552. JuceEnumFormatEtc& operator= (const JuceEnumFormatEtc&);
  206553. };
  206554. class JuceDataObject : public ComBaseClassHelper <IDataObject>
  206555. {
  206556. public:
  206557. JuceDataObject (JuceDropSource* const dropSource_,
  206558. const FORMATETC* const format_,
  206559. const STGMEDIUM* const medium_)
  206560. : dropSource (dropSource_),
  206561. format (format_),
  206562. medium (medium_)
  206563. {
  206564. }
  206565. virtual ~JuceDataObject()
  206566. {
  206567. jassert (refCount == 0);
  206568. }
  206569. HRESULT __stdcall GetData (FORMATETC __RPC_FAR* pFormatEtc, STGMEDIUM __RPC_FAR* pMedium)
  206570. {
  206571. if ((pFormatEtc->tymed & format->tymed) != 0
  206572. && pFormatEtc->cfFormat == format->cfFormat
  206573. && pFormatEtc->dwAspect == format->dwAspect)
  206574. {
  206575. pMedium->tymed = format->tymed;
  206576. pMedium->pUnkForRelease = 0;
  206577. if (format->tymed == TYMED_HGLOBAL)
  206578. {
  206579. const SIZE_T len = GlobalSize (medium->hGlobal);
  206580. void* const src = GlobalLock (medium->hGlobal);
  206581. void* const dst = GlobalAlloc (GMEM_FIXED, len);
  206582. memcpy (dst, src, len);
  206583. GlobalUnlock (medium->hGlobal);
  206584. pMedium->hGlobal = dst;
  206585. return S_OK;
  206586. }
  206587. }
  206588. return DV_E_FORMATETC;
  206589. }
  206590. HRESULT __stdcall QueryGetData (FORMATETC __RPC_FAR* f)
  206591. {
  206592. if (f == 0)
  206593. return E_INVALIDARG;
  206594. if (f->tymed == format->tymed
  206595. && f->cfFormat == format->cfFormat
  206596. && f->dwAspect == format->dwAspect)
  206597. return S_OK;
  206598. return DV_E_FORMATETC;
  206599. }
  206600. HRESULT __stdcall GetCanonicalFormatEtc (FORMATETC __RPC_FAR*, FORMATETC __RPC_FAR* pFormatEtcOut)
  206601. {
  206602. pFormatEtcOut->ptd = 0;
  206603. return E_NOTIMPL;
  206604. }
  206605. HRESULT __stdcall EnumFormatEtc (DWORD direction, IEnumFORMATETC __RPC_FAR *__RPC_FAR *result)
  206606. {
  206607. if (result == 0)
  206608. return E_POINTER;
  206609. if (direction == DATADIR_GET)
  206610. {
  206611. *result = new JuceEnumFormatEtc (format);
  206612. return S_OK;
  206613. }
  206614. *result = 0;
  206615. return E_NOTIMPL;
  206616. }
  206617. HRESULT __stdcall GetDataHere (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*) { return DATA_E_FORMATETC; }
  206618. HRESULT __stdcall SetData (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*, BOOL) { return E_NOTIMPL; }
  206619. HRESULT __stdcall DAdvise (FORMATETC __RPC_FAR*, DWORD, IAdviseSink __RPC_FAR*, DWORD __RPC_FAR*) { return OLE_E_ADVISENOTSUPPORTED; }
  206620. HRESULT __stdcall DUnadvise (DWORD) { return E_NOTIMPL; }
  206621. HRESULT __stdcall EnumDAdvise (IEnumSTATDATA __RPC_FAR *__RPC_FAR *) { return OLE_E_ADVISENOTSUPPORTED; }
  206622. private:
  206623. JuceDropSource* const dropSource;
  206624. const FORMATETC* const format;
  206625. const STGMEDIUM* const medium;
  206626. JuceDataObject (const JuceDataObject&);
  206627. JuceDataObject& operator= (const JuceDataObject&);
  206628. };
  206629. static HDROP createHDrop (const StringArray& fileNames) throw()
  206630. {
  206631. int totalChars = 0;
  206632. for (int i = fileNames.size(); --i >= 0;)
  206633. totalChars += fileNames[i].length() + 1;
  206634. HDROP hDrop = (HDROP) GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT,
  206635. sizeof (DROPFILES)
  206636. + sizeof (WCHAR) * (totalChars + 2));
  206637. if (hDrop != 0)
  206638. {
  206639. LPDROPFILES pDropFiles = (LPDROPFILES) GlobalLock (hDrop);
  206640. pDropFiles->pFiles = sizeof (DROPFILES);
  206641. pDropFiles->fWide = true;
  206642. WCHAR* fname = (WCHAR*) (((char*) pDropFiles) + sizeof (DROPFILES));
  206643. for (int i = 0; i < fileNames.size(); ++i)
  206644. {
  206645. fileNames[i].copyToUnicode (fname, 2048);
  206646. fname += fileNames[i].length() + 1;
  206647. }
  206648. *fname = 0;
  206649. GlobalUnlock (hDrop);
  206650. }
  206651. return hDrop;
  206652. }
  206653. static bool performDragDrop (FORMATETC* const format, STGMEDIUM* const medium, const DWORD whatToDo) throw()
  206654. {
  206655. JuceDropSource* const source = new JuceDropSource();
  206656. JuceDataObject* const data = new JuceDataObject (source, format, medium);
  206657. DWORD effect;
  206658. const HRESULT res = DoDragDrop (data, source, whatToDo, &effect);
  206659. data->Release();
  206660. source->Release();
  206661. return res == DRAGDROP_S_DROP;
  206662. }
  206663. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove)
  206664. {
  206665. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  206666. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  206667. medium.hGlobal = createHDrop (files);
  206668. return performDragDrop (&format, &medium, canMove ? (DROPEFFECT_COPY | DROPEFFECT_MOVE)
  206669. : DROPEFFECT_COPY);
  206670. }
  206671. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  206672. {
  206673. FORMATETC format = { CF_TEXT, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  206674. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  206675. const int numChars = text.length();
  206676. medium.hGlobal = GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, (numChars + 2) * sizeof (WCHAR));
  206677. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (medium.hGlobal));
  206678. text.copyToUnicode (data, numChars + 1);
  206679. format.cfFormat = CF_UNICODETEXT;
  206680. GlobalUnlock (medium.hGlobal);
  206681. return performDragDrop (&format, &medium, DROPEFFECT_COPY | DROPEFFECT_MOVE);
  206682. }
  206683. #endif
  206684. /*** End of inlined file: juce_win32_Windowing.cpp ***/
  206685. /*** Start of inlined file: juce_win32_Fonts.cpp ***/
  206686. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  206687. // compiled on its own).
  206688. #if JUCE_INCLUDED_FILE
  206689. static int CALLBACK wfontEnum2 (ENUMLOGFONTEXW* lpelfe,
  206690. NEWTEXTMETRICEXW*,
  206691. int type,
  206692. LPARAM lParam)
  206693. {
  206694. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  206695. {
  206696. const String fontName (lpelfe->elfLogFont.lfFaceName);
  206697. ((StringArray*) lParam)->addIfNotAlreadyThere (fontName.removeCharacters ("@"));
  206698. }
  206699. return 1;
  206700. }
  206701. static int CALLBACK wfontEnum1 (ENUMLOGFONTEXW* lpelfe,
  206702. NEWTEXTMETRICEXW*,
  206703. int type,
  206704. LPARAM lParam)
  206705. {
  206706. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  206707. {
  206708. LOGFONTW lf;
  206709. zerostruct (lf);
  206710. lf.lfWeight = FW_DONTCARE;
  206711. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  206712. lf.lfQuality = DEFAULT_QUALITY;
  206713. lf.lfCharSet = DEFAULT_CHARSET;
  206714. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  206715. lf.lfPitchAndFamily = FF_DONTCARE;
  206716. const String fontName (lpelfe->elfLogFont.lfFaceName);
  206717. fontName.copyToUnicode (lf.lfFaceName, LF_FACESIZE - 1);
  206718. HDC dc = CreateCompatibleDC (0);
  206719. EnumFontFamiliesEx (dc, &lf,
  206720. (FONTENUMPROCW) &wfontEnum2,
  206721. lParam, 0);
  206722. DeleteDC (dc);
  206723. }
  206724. return 1;
  206725. }
  206726. const StringArray Font::findAllTypefaceNames()
  206727. {
  206728. StringArray results;
  206729. HDC dc = CreateCompatibleDC (0);
  206730. {
  206731. LOGFONTW lf;
  206732. zerostruct (lf);
  206733. lf.lfWeight = FW_DONTCARE;
  206734. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  206735. lf.lfQuality = DEFAULT_QUALITY;
  206736. lf.lfCharSet = DEFAULT_CHARSET;
  206737. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  206738. lf.lfPitchAndFamily = FF_DONTCARE;
  206739. lf.lfFaceName[0] = 0;
  206740. EnumFontFamiliesEx (dc, &lf,
  206741. (FONTENUMPROCW) &wfontEnum1,
  206742. (LPARAM) &results, 0);
  206743. }
  206744. DeleteDC (dc);
  206745. results.sort (true);
  206746. return results;
  206747. }
  206748. extern bool juce_IsRunningInWine();
  206749. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  206750. {
  206751. if (juce_IsRunningInWine())
  206752. {
  206753. // If we're running in Wine, then use fonts that might be available on Linux..
  206754. defaultSans = "Bitstream Vera Sans";
  206755. defaultSerif = "Bitstream Vera Serif";
  206756. defaultFixed = "Bitstream Vera Sans Mono";
  206757. }
  206758. else
  206759. {
  206760. defaultSans = "Verdana";
  206761. defaultSerif = "Times";
  206762. defaultFixed = "Lucida Console";
  206763. }
  206764. }
  206765. class FontDCHolder : private DeletedAtShutdown
  206766. {
  206767. public:
  206768. FontDCHolder()
  206769. : dc (0), numKPs (0), size (0),
  206770. bold (false), italic (false)
  206771. {
  206772. }
  206773. ~FontDCHolder()
  206774. {
  206775. if (dc != 0)
  206776. {
  206777. DeleteDC (dc);
  206778. DeleteObject (fontH);
  206779. }
  206780. clearSingletonInstance();
  206781. }
  206782. juce_DeclareSingleton_SingleThreaded_Minimal (FontDCHolder);
  206783. HDC loadFont (const String& fontName_, const bool bold_, const bool italic_, const int size_)
  206784. {
  206785. if (fontName != fontName_ || bold != bold_ || italic != italic_ || size != size_)
  206786. {
  206787. fontName = fontName_;
  206788. bold = bold_;
  206789. italic = italic_;
  206790. size = size_;
  206791. if (dc != 0)
  206792. {
  206793. DeleteDC (dc);
  206794. DeleteObject (fontH);
  206795. kps.free();
  206796. }
  206797. fontH = 0;
  206798. dc = CreateCompatibleDC (0);
  206799. SetMapperFlags (dc, 0);
  206800. SetMapMode (dc, MM_TEXT);
  206801. LOGFONTW lfw;
  206802. zerostruct (lfw);
  206803. lfw.lfCharSet = DEFAULT_CHARSET;
  206804. lfw.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  206805. lfw.lfOutPrecision = OUT_OUTLINE_PRECIS;
  206806. lfw.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
  206807. lfw.lfQuality = PROOF_QUALITY;
  206808. lfw.lfItalic = (BYTE) (italic ? TRUE : FALSE);
  206809. lfw.lfWeight = bold ? FW_BOLD : FW_NORMAL;
  206810. fontName.copyToUnicode (lfw.lfFaceName, LF_FACESIZE - 1);
  206811. lfw.lfHeight = size > 0 ? size : -256;
  206812. HFONT standardSizedFont = CreateFontIndirect (&lfw);
  206813. if (standardSizedFont != 0)
  206814. {
  206815. if (SelectObject (dc, standardSizedFont) != 0)
  206816. {
  206817. fontH = standardSizedFont;
  206818. if (size == 0)
  206819. {
  206820. OUTLINETEXTMETRIC otm;
  206821. if (GetOutlineTextMetrics (dc, sizeof (otm), &otm) != 0)
  206822. {
  206823. lfw.lfHeight = -(int) otm.otmEMSquare;
  206824. fontH = CreateFontIndirect (&lfw);
  206825. SelectObject (dc, fontH);
  206826. DeleteObject (standardSizedFont);
  206827. }
  206828. }
  206829. }
  206830. else
  206831. {
  206832. jassertfalse;
  206833. }
  206834. }
  206835. else
  206836. {
  206837. jassertfalse;
  206838. }
  206839. }
  206840. return dc;
  206841. }
  206842. KERNINGPAIR* getKerningPairs (int& numKPs_)
  206843. {
  206844. if (kps == 0)
  206845. {
  206846. numKPs = GetKerningPairs (dc, 0, 0);
  206847. kps.calloc (numKPs);
  206848. GetKerningPairs (dc, numKPs, kps);
  206849. }
  206850. numKPs_ = numKPs;
  206851. return kps;
  206852. }
  206853. private:
  206854. HFONT fontH;
  206855. HDC dc;
  206856. String fontName;
  206857. HeapBlock <KERNINGPAIR> kps;
  206858. int numKPs, size;
  206859. bool bold, italic;
  206860. FontDCHolder (const FontDCHolder&);
  206861. FontDCHolder& operator= (const FontDCHolder&);
  206862. };
  206863. juce_ImplementSingleton_SingleThreaded (FontDCHolder);
  206864. class WindowsTypeface : public CustomTypeface
  206865. {
  206866. public:
  206867. WindowsTypeface (const Font& font)
  206868. {
  206869. HDC dc = FontDCHolder::getInstance()->loadFont (font.getTypefaceName(),
  206870. font.isBold(), font.isItalic(), 0);
  206871. TEXTMETRIC tm;
  206872. tm.tmAscent = tm.tmHeight = 1;
  206873. tm.tmDefaultChar = 0;
  206874. GetTextMetrics (dc, &tm);
  206875. setCharacteristics (font.getTypefaceName(),
  206876. tm.tmAscent / (float) tm.tmHeight,
  206877. font.isBold(), font.isItalic(),
  206878. tm.tmDefaultChar);
  206879. }
  206880. bool loadGlyphIfPossible (juce_wchar character)
  206881. {
  206882. HDC dc = FontDCHolder::getInstance()->loadFont (name, isBold, isItalic, 0);
  206883. GLYPHMETRICS gm;
  206884. {
  206885. const WCHAR charToTest[] = { (WCHAR) character, 0 };
  206886. WORD index = 0;
  206887. if (GetGlyphIndices (dc, charToTest, 1, &index, GGI_MARK_NONEXISTING_GLYPHS) != GDI_ERROR
  206888. && index == 0xffff)
  206889. {
  206890. return false;
  206891. }
  206892. }
  206893. Path glyphPath;
  206894. TEXTMETRIC tm;
  206895. if (! GetTextMetrics (dc, &tm))
  206896. {
  206897. addGlyph (character, glyphPath, 0);
  206898. return true;
  206899. }
  206900. const float height = (float) tm.tmHeight;
  206901. static const MAT2 identityMatrix = { { 0, 1 }, { 0, 0 }, { 0, 0 }, { 0, 1 } };
  206902. const int bufSize = GetGlyphOutline (dc, character, GGO_NATIVE,
  206903. &gm, 0, 0, &identityMatrix);
  206904. if (bufSize > 0)
  206905. {
  206906. HeapBlock<char> data (bufSize);
  206907. GetGlyphOutline (dc, character, GGO_NATIVE, &gm,
  206908. bufSize, data, &identityMatrix);
  206909. const TTPOLYGONHEADER* pheader = reinterpret_cast<TTPOLYGONHEADER*> (data.getData());
  206910. const float scaleX = 1.0f / height;
  206911. const float scaleY = -1.0f / height;
  206912. while ((char*) pheader < data + bufSize)
  206913. {
  206914. float x = scaleX * pheader->pfxStart.x.value;
  206915. float y = scaleY * pheader->pfxStart.y.value;
  206916. glyphPath.startNewSubPath (x, y);
  206917. const TTPOLYCURVE* curve = (const TTPOLYCURVE*) ((const char*) pheader + sizeof (TTPOLYGONHEADER));
  206918. const char* const curveEnd = ((const char*) pheader) + pheader->cb;
  206919. while ((const char*) curve < curveEnd)
  206920. {
  206921. if (curve->wType == TT_PRIM_LINE)
  206922. {
  206923. for (int i = 0; i < curve->cpfx; ++i)
  206924. {
  206925. x = scaleX * curve->apfx[i].x.value;
  206926. y = scaleY * curve->apfx[i].y.value;
  206927. glyphPath.lineTo (x, y);
  206928. }
  206929. }
  206930. else if (curve->wType == TT_PRIM_QSPLINE)
  206931. {
  206932. for (int i = 0; i < curve->cpfx - 1; ++i)
  206933. {
  206934. const float x2 = scaleX * curve->apfx[i].x.value;
  206935. const float y2 = scaleY * curve->apfx[i].y.value;
  206936. float x3, y3;
  206937. if (i < curve->cpfx - 2)
  206938. {
  206939. x3 = 0.5f * (x2 + scaleX * curve->apfx[i + 1].x.value);
  206940. y3 = 0.5f * (y2 + scaleY * curve->apfx[i + 1].y.value);
  206941. }
  206942. else
  206943. {
  206944. x3 = scaleX * curve->apfx[i + 1].x.value;
  206945. y3 = scaleY * curve->apfx[i + 1].y.value;
  206946. }
  206947. glyphPath.quadraticTo (x2, y2, x3, y3);
  206948. x = x3;
  206949. y = y3;
  206950. }
  206951. }
  206952. curve = (const TTPOLYCURVE*) &(curve->apfx [curve->cpfx]);
  206953. }
  206954. pheader = (const TTPOLYGONHEADER*) curve;
  206955. glyphPath.closeSubPath();
  206956. }
  206957. }
  206958. addGlyph (character, glyphPath, gm.gmCellIncX / height);
  206959. int numKPs;
  206960. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  206961. for (int i = 0; i < numKPs; ++i)
  206962. {
  206963. if (kps[i].wFirst == character)
  206964. addKerningPair (kps[i].wFirst, kps[i].wSecond,
  206965. kps[i].iKernAmount / height);
  206966. }
  206967. return true;
  206968. }
  206969. juce_UseDebuggingNewOperator
  206970. };
  206971. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  206972. {
  206973. return new WindowsTypeface (font);
  206974. }
  206975. #endif
  206976. /*** End of inlined file: juce_win32_Fonts.cpp ***/
  206977. /*** Start of inlined file: juce_win32_FileChooser.cpp ***/
  206978. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  206979. // compiled on its own).
  206980. #if JUCE_INCLUDED_FILE
  206981. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw();
  206982. namespace FileChooserHelpers
  206983. {
  206984. static const void* defaultDirPath = 0;
  206985. static String returnedString; // need this to get non-existent pathnames from the directory chooser
  206986. static Component* currentExtraFileWin = 0;
  206987. static bool areThereAnyAlwaysOnTopWindows()
  206988. {
  206989. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  206990. {
  206991. Component* c = Desktop::getInstance().getComponent (i);
  206992. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  206993. return true;
  206994. }
  206995. return false;
  206996. }
  206997. static int CALLBACK browseCallbackProc (HWND hWnd, UINT msg, LPARAM lParam, LPARAM /*lpData*/)
  206998. {
  206999. if (msg == BFFM_INITIALIZED)
  207000. SendMessage (hWnd, BFFM_SETSELECTIONW, TRUE, (LPARAM) defaultDirPath);
  207001. else if (msg == BFFM_VALIDATEFAILEDW)
  207002. returnedString = (LPCWSTR) lParam;
  207003. else if (msg == BFFM_VALIDATEFAILEDA)
  207004. returnedString = (const char*) lParam;
  207005. return 0;
  207006. }
  207007. static UINT_PTR CALLBACK openCallback (HWND hdlg, UINT uiMsg, WPARAM /*wParam*/, LPARAM lParam)
  207008. {
  207009. if (currentExtraFileWin != 0)
  207010. {
  207011. if (uiMsg == WM_INITDIALOG)
  207012. {
  207013. HWND dialogH = GetParent (hdlg);
  207014. jassert (dialogH != 0);
  207015. if (dialogH == 0)
  207016. dialogH = hdlg;
  207017. RECT r, cr;
  207018. GetWindowRect (dialogH, &r);
  207019. GetClientRect (dialogH, &cr);
  207020. SetWindowPos (dialogH, 0,
  207021. r.left, r.top,
  207022. currentExtraFileWin->getWidth() + jmax (150, (int) (r.right - r.left)),
  207023. jmax (150, (int) (r.bottom - r.top)),
  207024. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  207025. currentExtraFileWin->setBounds (cr.right, cr.top, currentExtraFileWin->getWidth(), cr.bottom - cr.top);
  207026. currentExtraFileWin->getChildComponent(0)->setBounds (0, 0, currentExtraFileWin->getWidth(), currentExtraFileWin->getHeight());
  207027. SetParent ((HWND) currentExtraFileWin->getWindowHandle(), (HWND) dialogH);
  207028. juce_setWindowStyleBit ((HWND)currentExtraFileWin->getWindowHandle(), GWL_STYLE, WS_CHILD, (dialogH != 0));
  207029. juce_setWindowStyleBit ((HWND)currentExtraFileWin->getWindowHandle(), GWL_STYLE, WS_POPUP, (dialogH == 0));
  207030. }
  207031. else if (uiMsg == WM_NOTIFY)
  207032. {
  207033. LPOFNOTIFY ofn = (LPOFNOTIFY) lParam;
  207034. if (ofn->hdr.code == CDN_SELCHANGE)
  207035. {
  207036. FilePreviewComponent* comp = (FilePreviewComponent*) currentExtraFileWin->getChildComponent(0);
  207037. if (comp != 0)
  207038. {
  207039. TCHAR path [MAX_PATH * 2];
  207040. path[0] = 0;
  207041. CommDlg_OpenSave_GetFilePath (GetParent (hdlg), (LPARAM) &path, MAX_PATH);
  207042. const String fn ((const WCHAR*) path);
  207043. comp->selectedFileChanged (File (fn));
  207044. }
  207045. }
  207046. }
  207047. }
  207048. return 0;
  207049. }
  207050. class FPComponentHolder : public Component
  207051. {
  207052. public:
  207053. FPComponentHolder()
  207054. {
  207055. setVisible (true);
  207056. setOpaque (true);
  207057. }
  207058. ~FPComponentHolder()
  207059. {
  207060. }
  207061. void paint (Graphics& g)
  207062. {
  207063. g.fillAll (Colours::lightgrey);
  207064. }
  207065. private:
  207066. FPComponentHolder (const FPComponentHolder&);
  207067. FPComponentHolder& operator= (const FPComponentHolder&);
  207068. };
  207069. }
  207070. void FileChooser::showPlatformDialog (Array<File>& results,
  207071. const String& title,
  207072. const File& currentFileOrDirectory,
  207073. const String& filter,
  207074. bool selectsDirectory,
  207075. bool /*selectsFiles*/,
  207076. bool isSaveDialogue,
  207077. bool warnAboutOverwritingExistingFiles,
  207078. bool selectMultipleFiles,
  207079. FilePreviewComponent* extraInfoComponent)
  207080. {
  207081. using namespace FileChooserHelpers;
  207082. const int numCharsAvailable = 32768;
  207083. MemoryBlock filenameSpace ((numCharsAvailable + 1) * sizeof (WCHAR), true);
  207084. WCHAR* const fname = (WCHAR*) filenameSpace.getData();
  207085. int fnameIdx = 0;
  207086. JUCE_TRY
  207087. {
  207088. // use a modal window as the parent for this dialog box
  207089. // to block input from other app windows
  207090. const Rectangle<int> mainMon (Desktop::getInstance().getMainMonitorArea());
  207091. Component w (String::empty);
  207092. w.setBounds (mainMon.getX() + mainMon.getWidth() / 4,
  207093. mainMon.getY() + mainMon.getHeight() / 4,
  207094. 0, 0);
  207095. w.setOpaque (true);
  207096. w.setAlwaysOnTop (areThereAnyAlwaysOnTopWindows());
  207097. w.addToDesktop (0);
  207098. if (extraInfoComponent == 0)
  207099. w.enterModalState();
  207100. String initialDir;
  207101. if (currentFileOrDirectory.isDirectory())
  207102. {
  207103. initialDir = currentFileOrDirectory.getFullPathName();
  207104. }
  207105. else
  207106. {
  207107. currentFileOrDirectory.getFileName().copyToUnicode (fname, numCharsAvailable);
  207108. initialDir = currentFileOrDirectory.getParentDirectory().getFullPathName();
  207109. }
  207110. if (currentExtraFileWin->isValidComponent())
  207111. {
  207112. jassertfalse;
  207113. return;
  207114. }
  207115. if (selectsDirectory)
  207116. {
  207117. LPITEMIDLIST list = 0;
  207118. filenameSpace.fillWith (0);
  207119. {
  207120. BROWSEINFO bi;
  207121. zerostruct (bi);
  207122. bi.hwndOwner = (HWND) w.getWindowHandle();
  207123. bi.pszDisplayName = fname;
  207124. bi.lpszTitle = title;
  207125. bi.lpfn = browseCallbackProc;
  207126. #ifdef BIF_USENEWUI
  207127. bi.ulFlags = BIF_USENEWUI | BIF_VALIDATE;
  207128. #else
  207129. bi.ulFlags = 0x50;
  207130. #endif
  207131. defaultDirPath = (const WCHAR*) initialDir;
  207132. list = SHBrowseForFolder (&bi);
  207133. if (! SHGetPathFromIDListW (list, fname))
  207134. {
  207135. fname[0] = 0;
  207136. returnedString = String::empty;
  207137. }
  207138. }
  207139. LPMALLOC al;
  207140. if (list != 0 && SUCCEEDED (SHGetMalloc (&al)))
  207141. al->Free (list);
  207142. defaultDirPath = 0;
  207143. if (returnedString.isNotEmpty())
  207144. {
  207145. const String stringFName (fname);
  207146. results.add (File (stringFName).getSiblingFile (returnedString));
  207147. returnedString = String::empty;
  207148. return;
  207149. }
  207150. }
  207151. else
  207152. {
  207153. DWORD flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  207154. if (warnAboutOverwritingExistingFiles)
  207155. flags |= OFN_OVERWRITEPROMPT;
  207156. if (selectMultipleFiles)
  207157. flags |= OFN_ALLOWMULTISELECT;
  207158. if (extraInfoComponent != 0)
  207159. {
  207160. flags |= OFN_ENABLEHOOK;
  207161. currentExtraFileWin = new FPComponentHolder();
  207162. currentExtraFileWin->addAndMakeVisible (extraInfoComponent);
  207163. currentExtraFileWin->setSize (jlimit (20, 800, extraInfoComponent->getWidth()),
  207164. extraInfoComponent->getHeight());
  207165. currentExtraFileWin->addToDesktop (0);
  207166. currentExtraFileWin->enterModalState();
  207167. }
  207168. {
  207169. WCHAR filters [1024];
  207170. zeromem (filters, sizeof (filters));
  207171. filter.copyToUnicode (filters, 1024);
  207172. filter.copyToUnicode (filters + filter.length() + 1,
  207173. 1022 - filter.length());
  207174. OPENFILENAMEW of;
  207175. zerostruct (of);
  207176. #ifdef OPENFILENAME_SIZE_VERSION_400W
  207177. of.lStructSize = OPENFILENAME_SIZE_VERSION_400W;
  207178. #else
  207179. of.lStructSize = sizeof (of);
  207180. #endif
  207181. of.hwndOwner = (HWND) w.getWindowHandle();
  207182. of.lpstrFilter = filters;
  207183. of.nFilterIndex = 1;
  207184. of.lpstrFile = fname;
  207185. of.nMaxFile = numCharsAvailable;
  207186. of.lpstrInitialDir = initialDir;
  207187. of.lpstrTitle = title;
  207188. of.Flags = flags;
  207189. if (extraInfoComponent != 0)
  207190. of.lpfnHook = &openCallback;
  207191. if (isSaveDialogue)
  207192. {
  207193. if (! GetSaveFileName (&of))
  207194. fname[0] = 0;
  207195. else
  207196. fnameIdx = of.nFileOffset;
  207197. }
  207198. else
  207199. {
  207200. if (! GetOpenFileName (&of))
  207201. fname[0] = 0;
  207202. else
  207203. fnameIdx = of.nFileOffset;
  207204. }
  207205. }
  207206. }
  207207. }
  207208. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  207209. catch (...)
  207210. {
  207211. fname[0] = 0;
  207212. }
  207213. #endif
  207214. deleteAndZero (currentExtraFileWin);
  207215. const WCHAR* const files = fname;
  207216. if (selectMultipleFiles && fnameIdx > 0 && files [fnameIdx - 1] == 0)
  207217. {
  207218. const WCHAR* filename = files + fnameIdx;
  207219. while (*filename != 0)
  207220. {
  207221. const String filepath (String (files) + "\\" + String (filename));
  207222. results.add (File (filepath));
  207223. filename += CharacterFunctions::length (filename) + 1;
  207224. }
  207225. }
  207226. else if (files[0] != 0)
  207227. {
  207228. results.add (File (files));
  207229. }
  207230. }
  207231. #endif
  207232. /*** End of inlined file: juce_win32_FileChooser.cpp ***/
  207233. /*** Start of inlined file: juce_win32_Misc.cpp ***/
  207234. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  207235. // compiled on its own).
  207236. #if JUCE_INCLUDED_FILE
  207237. void SystemClipboard::copyTextToClipboard (const String& text)
  207238. {
  207239. if (OpenClipboard (0) != 0)
  207240. {
  207241. if (EmptyClipboard() != 0)
  207242. {
  207243. const int len = text.length();
  207244. if (len > 0)
  207245. {
  207246. HGLOBAL bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE,
  207247. (len + 1) * sizeof (wchar_t));
  207248. if (bufH != 0)
  207249. {
  207250. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (bufH));
  207251. text.copyToUnicode (data, len);
  207252. GlobalUnlock (bufH);
  207253. SetClipboardData (CF_UNICODETEXT, bufH);
  207254. }
  207255. }
  207256. }
  207257. CloseClipboard();
  207258. }
  207259. }
  207260. const String SystemClipboard::getTextFromClipboard()
  207261. {
  207262. String result;
  207263. if (OpenClipboard (0) != 0)
  207264. {
  207265. HANDLE bufH = GetClipboardData (CF_UNICODETEXT);
  207266. if (bufH != 0)
  207267. {
  207268. const wchar_t* const data = (const wchar_t*) GlobalLock (bufH);
  207269. if (data != 0)
  207270. {
  207271. result = String (data, (int) (GlobalSize (bufH) / sizeof (wchar_t)));
  207272. GlobalUnlock (bufH);
  207273. }
  207274. }
  207275. CloseClipboard();
  207276. }
  207277. return result;
  207278. }
  207279. #endif
  207280. /*** End of inlined file: juce_win32_Misc.cpp ***/
  207281. /*** Start of inlined file: juce_win32_ActiveXComponent.cpp ***/
  207282. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  207283. // compiled on its own).
  207284. #if JUCE_INCLUDED_FILE
  207285. namespace ActiveXHelpers
  207286. {
  207287. class JuceIStorage : public ComBaseClassHelper <IStorage>
  207288. {
  207289. public:
  207290. JuceIStorage() {}
  207291. ~JuceIStorage() {}
  207292. HRESULT __stdcall CreateStream (const WCHAR*, DWORD, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  207293. HRESULT __stdcall OpenStream (const WCHAR*, void*, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  207294. HRESULT __stdcall CreateStorage (const WCHAR*, DWORD, DWORD, DWORD, IStorage**) { return E_NOTIMPL; }
  207295. HRESULT __stdcall OpenStorage (const WCHAR*, IStorage*, DWORD, SNB, DWORD, IStorage**) { return E_NOTIMPL; }
  207296. HRESULT __stdcall CopyTo (DWORD, IID const*, SNB, IStorage*) { return E_NOTIMPL; }
  207297. HRESULT __stdcall MoveElementTo (const OLECHAR*,IStorage*, const OLECHAR*, DWORD) { return E_NOTIMPL; }
  207298. HRESULT __stdcall Commit (DWORD) { return E_NOTIMPL; }
  207299. HRESULT __stdcall Revert() { return E_NOTIMPL; }
  207300. HRESULT __stdcall EnumElements (DWORD, void*, DWORD, IEnumSTATSTG**) { return E_NOTIMPL; }
  207301. HRESULT __stdcall DestroyElement (const OLECHAR*) { return E_NOTIMPL; }
  207302. HRESULT __stdcall RenameElement (const WCHAR*, const WCHAR*) { return E_NOTIMPL; }
  207303. HRESULT __stdcall SetElementTimes (const WCHAR*, FILETIME const*, FILETIME const*, FILETIME const*) { return E_NOTIMPL; }
  207304. HRESULT __stdcall SetClass (REFCLSID) { return S_OK; }
  207305. HRESULT __stdcall SetStateBits (DWORD, DWORD) { return E_NOTIMPL; }
  207306. HRESULT __stdcall Stat (STATSTG*, DWORD) { return E_NOTIMPL; }
  207307. juce_UseDebuggingNewOperator
  207308. };
  207309. class JuceOleInPlaceFrame : public ComBaseClassHelper <IOleInPlaceFrame>
  207310. {
  207311. HWND window;
  207312. public:
  207313. JuceOleInPlaceFrame (HWND window_) : window (window_) {}
  207314. ~JuceOleInPlaceFrame() {}
  207315. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  207316. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  207317. HRESULT __stdcall GetBorder (LPRECT) { return E_NOTIMPL; }
  207318. HRESULT __stdcall RequestBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  207319. HRESULT __stdcall SetBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  207320. HRESULT __stdcall SetActiveObject (IOleInPlaceActiveObject*, LPCOLESTR) { return S_OK; }
  207321. HRESULT __stdcall InsertMenus (HMENU, LPOLEMENUGROUPWIDTHS) { return E_NOTIMPL; }
  207322. HRESULT __stdcall SetMenu (HMENU, HOLEMENU, HWND) { return S_OK; }
  207323. HRESULT __stdcall RemoveMenus (HMENU) { return E_NOTIMPL; }
  207324. HRESULT __stdcall SetStatusText (LPCOLESTR) { return S_OK; }
  207325. HRESULT __stdcall EnableModeless (BOOL) { return S_OK; }
  207326. HRESULT __stdcall TranslateAccelerator(LPMSG, WORD) { return E_NOTIMPL; }
  207327. juce_UseDebuggingNewOperator
  207328. };
  207329. class JuceIOleInPlaceSite : public ComBaseClassHelper <IOleInPlaceSite>
  207330. {
  207331. HWND window;
  207332. JuceOleInPlaceFrame* frame;
  207333. public:
  207334. JuceIOleInPlaceSite (HWND window_)
  207335. : window (window_),
  207336. frame (new JuceOleInPlaceFrame (window))
  207337. {}
  207338. ~JuceIOleInPlaceSite()
  207339. {
  207340. frame->Release();
  207341. }
  207342. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  207343. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  207344. HRESULT __stdcall CanInPlaceActivate() { return S_OK; }
  207345. HRESULT __stdcall OnInPlaceActivate() { return S_OK; }
  207346. HRESULT __stdcall OnUIActivate() { return S_OK; }
  207347. HRESULT __stdcall GetWindowContext (LPOLEINPLACEFRAME* lplpFrame, LPOLEINPLACEUIWINDOW* lplpDoc, LPRECT, LPRECT, LPOLEINPLACEFRAMEINFO lpFrameInfo)
  207348. {
  207349. *lplpFrame = frame;
  207350. *lplpDoc = 0;
  207351. lpFrameInfo->fMDIApp = FALSE;
  207352. lpFrameInfo->hwndFrame = window;
  207353. lpFrameInfo->haccel = 0;
  207354. lpFrameInfo->cAccelEntries = 0;
  207355. return S_OK;
  207356. }
  207357. HRESULT __stdcall Scroll (SIZE) { return E_NOTIMPL; }
  207358. HRESULT __stdcall OnUIDeactivate (BOOL) { return S_OK; }
  207359. HRESULT __stdcall OnInPlaceDeactivate() { return S_OK; }
  207360. HRESULT __stdcall DiscardUndoState() { return E_NOTIMPL; }
  207361. HRESULT __stdcall DeactivateAndUndo() { return E_NOTIMPL; }
  207362. HRESULT __stdcall OnPosRectChange (LPCRECT) { return S_OK; }
  207363. juce_UseDebuggingNewOperator
  207364. };
  207365. class JuceIOleClientSite : public ComBaseClassHelper <IOleClientSite>
  207366. {
  207367. JuceIOleInPlaceSite* inplaceSite;
  207368. public:
  207369. JuceIOleClientSite (HWND window)
  207370. : inplaceSite (new JuceIOleInPlaceSite (window))
  207371. {}
  207372. ~JuceIOleClientSite()
  207373. {
  207374. inplaceSite->Release();
  207375. }
  207376. HRESULT __stdcall QueryInterface (REFIID type, void __RPC_FAR* __RPC_FAR* result)
  207377. {
  207378. if (type == IID_IOleInPlaceSite)
  207379. {
  207380. inplaceSite->AddRef();
  207381. *result = static_cast <IOleInPlaceSite*> (inplaceSite);
  207382. return S_OK;
  207383. }
  207384. return ComBaseClassHelper <IOleClientSite>::QueryInterface (type, result);
  207385. }
  207386. HRESULT __stdcall SaveObject() { return E_NOTIMPL; }
  207387. HRESULT __stdcall GetMoniker (DWORD, DWORD, IMoniker**) { return E_NOTIMPL; }
  207388. HRESULT __stdcall GetContainer (LPOLECONTAINER* ppContainer) { *ppContainer = 0; return E_NOINTERFACE; }
  207389. HRESULT __stdcall ShowObject() { return S_OK; }
  207390. HRESULT __stdcall OnShowWindow (BOOL) { return E_NOTIMPL; }
  207391. HRESULT __stdcall RequestNewObjectLayout() { return E_NOTIMPL; }
  207392. juce_UseDebuggingNewOperator
  207393. };
  207394. static Array<ActiveXControlComponent*> activeXComps;
  207395. static HWND getHWND (const ActiveXControlComponent* const component)
  207396. {
  207397. HWND hwnd = 0;
  207398. const IID iid = IID_IOleWindow;
  207399. IOleWindow* const window = (IOleWindow*) component->queryInterface (&iid);
  207400. if (window != 0)
  207401. {
  207402. window->GetWindow (&hwnd);
  207403. window->Release();
  207404. }
  207405. return hwnd;
  207406. }
  207407. static void offerActiveXMouseEventToPeer (ComponentPeer* const peer, HWND hwnd, UINT message, LPARAM lParam)
  207408. {
  207409. RECT activeXRect, peerRect;
  207410. GetWindowRect (hwnd, &activeXRect);
  207411. GetWindowRect ((HWND) peer->getNativeHandle(), &peerRect);
  207412. const Point<int> mousePos (GET_X_LPARAM (lParam) + activeXRect.left - peerRect.left,
  207413. GET_Y_LPARAM (lParam) + activeXRect.top - peerRect.top);
  207414. const int64 mouseEventTime = Win32ComponentPeer::getMouseEventTime();
  207415. ModifierKeys::getCurrentModifiersRealtime(); // to update the mouse button flags
  207416. switch (message)
  207417. {
  207418. case WM_MOUSEMOVE:
  207419. case WM_LBUTTONDOWN:
  207420. case WM_MBUTTONDOWN:
  207421. case WM_RBUTTONDOWN:
  207422. case WM_LBUTTONUP:
  207423. case WM_MBUTTONUP:
  207424. case WM_RBUTTONUP:
  207425. peer->handleMouseEvent (0, mousePos, Win32ComponentPeer::currentModifiers, mouseEventTime);
  207426. break;
  207427. default:
  207428. break;
  207429. }
  207430. }
  207431. }
  207432. class ActiveXControlComponent::Pimpl : public ComponentMovementWatcher
  207433. {
  207434. ActiveXControlComponent* const owner;
  207435. bool wasShowing;
  207436. public:
  207437. HWND controlHWND;
  207438. IStorage* storage;
  207439. IOleClientSite* clientSite;
  207440. IOleObject* control;
  207441. Pimpl (HWND hwnd, ActiveXControlComponent* const owner_)
  207442. : ComponentMovementWatcher (owner_),
  207443. owner (owner_),
  207444. wasShowing (owner_ != 0 && owner_->isShowing()),
  207445. controlHWND (0),
  207446. storage (new ActiveXHelpers::JuceIStorage()),
  207447. clientSite (new ActiveXHelpers::JuceIOleClientSite (hwnd)),
  207448. control (0)
  207449. {
  207450. }
  207451. ~Pimpl()
  207452. {
  207453. if (control != 0)
  207454. {
  207455. control->Close (OLECLOSE_NOSAVE);
  207456. control->Release();
  207457. }
  207458. clientSite->Release();
  207459. storage->Release();
  207460. }
  207461. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  207462. {
  207463. Component* const topComp = owner->getTopLevelComponent();
  207464. if (topComp->getPeer() != 0)
  207465. {
  207466. const Point<int> pos (owner->relativePositionToOtherComponent (topComp, Point<int>()));
  207467. owner->setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), owner->getWidth(), owner->getHeight()));
  207468. }
  207469. }
  207470. void componentPeerChanged()
  207471. {
  207472. const bool isShowingNow = owner->isShowing();
  207473. if (wasShowing != isShowingNow)
  207474. {
  207475. wasShowing = isShowingNow;
  207476. owner->setControlVisible (isShowingNow);
  207477. }
  207478. componentMovedOrResized (true, true);
  207479. }
  207480. void componentVisibilityChanged (Component&)
  207481. {
  207482. componentPeerChanged();
  207483. }
  207484. // intercepts events going to an activeX control, so we can sneakily use the mouse events
  207485. static LRESULT CALLBACK activeXHookWndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  207486. {
  207487. for (int i = ActiveXHelpers::activeXComps.size(); --i >= 0;)
  207488. {
  207489. const ActiveXControlComponent* const ax = ActiveXHelpers::activeXComps.getUnchecked(i);
  207490. if (ax->control != 0 && ax->control->controlHWND == hwnd)
  207491. {
  207492. switch (message)
  207493. {
  207494. case WM_MOUSEMOVE:
  207495. case WM_LBUTTONDOWN:
  207496. case WM_MBUTTONDOWN:
  207497. case WM_RBUTTONDOWN:
  207498. case WM_LBUTTONUP:
  207499. case WM_MBUTTONUP:
  207500. case WM_RBUTTONUP:
  207501. case WM_LBUTTONDBLCLK:
  207502. case WM_MBUTTONDBLCLK:
  207503. case WM_RBUTTONDBLCLK:
  207504. if (ax->isShowing())
  207505. {
  207506. ComponentPeer* const peer = ax->getPeer();
  207507. if (peer != 0)
  207508. {
  207509. ActiveXHelpers::offerActiveXMouseEventToPeer (peer, hwnd, message, lParam);
  207510. if (! ax->areMouseEventsAllowed())
  207511. return 0;
  207512. }
  207513. }
  207514. break;
  207515. default:
  207516. break;
  207517. }
  207518. return CallWindowProc ((WNDPROC) ax->originalWndProc, hwnd, message, wParam, lParam);
  207519. }
  207520. }
  207521. return DefWindowProc (hwnd, message, wParam, lParam);
  207522. }
  207523. };
  207524. ActiveXControlComponent::ActiveXControlComponent()
  207525. : originalWndProc (0),
  207526. mouseEventsAllowed (true)
  207527. {
  207528. ActiveXHelpers::activeXComps.add (this);
  207529. }
  207530. ActiveXControlComponent::~ActiveXControlComponent()
  207531. {
  207532. deleteControl();
  207533. ActiveXHelpers::activeXComps.removeValue (this);
  207534. }
  207535. void ActiveXControlComponent::paint (Graphics& g)
  207536. {
  207537. if (control == 0)
  207538. g.fillAll (Colours::lightgrey);
  207539. }
  207540. bool ActiveXControlComponent::createControl (const void* controlIID)
  207541. {
  207542. deleteControl();
  207543. ComponentPeer* const peer = getPeer();
  207544. // the component must have already been added to a real window when you call this!
  207545. jassert (dynamic_cast <Win32ComponentPeer*> (peer) != 0);
  207546. if (dynamic_cast <Win32ComponentPeer*> (peer) != 0)
  207547. {
  207548. const Point<int> pos (relativePositionToOtherComponent (getTopLevelComponent(), Point<int>()));
  207549. HWND hwnd = (HWND) peer->getNativeHandle();
  207550. ScopedPointer<Pimpl> newControl (new Pimpl (hwnd, this));
  207551. HRESULT hr;
  207552. if ((hr = OleCreate (*(const IID*) controlIID, IID_IOleObject, 1 /*OLERENDER_DRAW*/, 0,
  207553. newControl->clientSite, newControl->storage,
  207554. (void**) &(newControl->control))) == S_OK)
  207555. {
  207556. newControl->control->SetHostNames (L"Juce", 0);
  207557. if (OleSetContainedObject (newControl->control, TRUE) == S_OK)
  207558. {
  207559. RECT rect;
  207560. rect.left = pos.getX();
  207561. rect.top = pos.getY();
  207562. rect.right = pos.getX() + getWidth();
  207563. rect.bottom = pos.getY() + getHeight();
  207564. if (newControl->control->DoVerb (OLEIVERB_SHOW, 0, newControl->clientSite, 0, hwnd, &rect) == S_OK)
  207565. {
  207566. control = newControl;
  207567. setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), getWidth(), getHeight()));
  207568. control->controlHWND = ActiveXHelpers::getHWND (this);
  207569. if (control->controlHWND != 0)
  207570. {
  207571. originalWndProc = (void*) (pointer_sized_int) GetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC);
  207572. SetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC, (LONG_PTR) Pimpl::activeXHookWndProc);
  207573. }
  207574. return true;
  207575. }
  207576. }
  207577. }
  207578. }
  207579. return false;
  207580. }
  207581. void ActiveXControlComponent::deleteControl()
  207582. {
  207583. control = 0;
  207584. originalWndProc = 0;
  207585. }
  207586. void* ActiveXControlComponent::queryInterface (const void* iid) const
  207587. {
  207588. void* result = 0;
  207589. if (control != 0 && control->control != 0
  207590. && SUCCEEDED (control->control->QueryInterface (*(const IID*) iid, &result)))
  207591. return result;
  207592. return 0;
  207593. }
  207594. void ActiveXControlComponent::setControlBounds (const Rectangle<int>& newBounds) const
  207595. {
  207596. if (control->controlHWND != 0)
  207597. MoveWindow (control->controlHWND, newBounds.getX(), newBounds.getY(), newBounds.getWidth(), newBounds.getHeight(), TRUE);
  207598. }
  207599. void ActiveXControlComponent::setControlVisible (const bool shouldBeVisible) const
  207600. {
  207601. if (control->controlHWND != 0)
  207602. ShowWindow (control->controlHWND, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  207603. }
  207604. void ActiveXControlComponent::setMouseEventsAllowed (const bool eventsCanReachControl)
  207605. {
  207606. mouseEventsAllowed = eventsCanReachControl;
  207607. }
  207608. #endif
  207609. /*** End of inlined file: juce_win32_ActiveXComponent.cpp ***/
  207610. /*** Start of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  207611. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  207612. // compiled on its own).
  207613. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  207614. using namespace QTOLibrary;
  207615. using namespace QTOControlLib;
  207616. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  207617. static bool isQTAvailable = false;
  207618. class QuickTimeMovieComponent::Pimpl
  207619. {
  207620. public:
  207621. Pimpl() : dataHandle (0)
  207622. {
  207623. }
  207624. ~Pimpl()
  207625. {
  207626. clearHandle();
  207627. }
  207628. void clearHandle()
  207629. {
  207630. if (dataHandle != 0)
  207631. {
  207632. DisposeHandle (dataHandle);
  207633. dataHandle = 0;
  207634. }
  207635. }
  207636. IQTControlPtr qtControl;
  207637. IQTMoviePtr qtMovie;
  207638. Handle dataHandle;
  207639. };
  207640. QuickTimeMovieComponent::QuickTimeMovieComponent()
  207641. : movieLoaded (false),
  207642. controllerVisible (true)
  207643. {
  207644. pimpl = new Pimpl();
  207645. setMouseEventsAllowed (false);
  207646. }
  207647. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  207648. {
  207649. closeMovie();
  207650. pimpl->qtControl = 0;
  207651. deleteControl();
  207652. pimpl = 0;
  207653. }
  207654. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  207655. {
  207656. if (! isQTAvailable)
  207657. isQTAvailable = (InitializeQTML (0) == noErr) && (EnterMovies() == noErr);
  207658. return isQTAvailable;
  207659. }
  207660. void QuickTimeMovieComponent::createControlIfNeeded()
  207661. {
  207662. if (isShowing() && ! isControlCreated())
  207663. {
  207664. const IID qtIID = __uuidof (QTControl);
  207665. if (createControl (&qtIID))
  207666. {
  207667. const IID qtInterfaceIID = __uuidof (IQTControl);
  207668. pimpl->qtControl = (IQTControl*) queryInterface (&qtInterfaceIID);
  207669. if (pimpl->qtControl != 0)
  207670. {
  207671. pimpl->qtControl->Release(); // it has one ref too many at this point
  207672. pimpl->qtControl->QuickTimeInitialize();
  207673. pimpl->qtControl->PutSizing (qtMovieFitsControl);
  207674. if (movieFile != File::nonexistent)
  207675. loadMovie (movieFile, controllerVisible);
  207676. }
  207677. }
  207678. }
  207679. }
  207680. bool QuickTimeMovieComponent::isControlCreated() const
  207681. {
  207682. return isControlOpen();
  207683. }
  207684. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  207685. const bool isControllerVisible)
  207686. {
  207687. const ScopedPointer<InputStream> movieStreamDeleter (movieStream);
  207688. movieFile = File::nonexistent;
  207689. movieLoaded = false;
  207690. pimpl->qtMovie = 0;
  207691. controllerVisible = isControllerVisible;
  207692. createControlIfNeeded();
  207693. if (isControlCreated())
  207694. {
  207695. if (pimpl->qtControl != 0)
  207696. {
  207697. pimpl->qtControl->Put_MovieHandle (0);
  207698. pimpl->clearHandle();
  207699. Movie movie;
  207700. if (juce_OpenQuickTimeMovieFromStream (movieStream, movie, pimpl->dataHandle))
  207701. {
  207702. pimpl->qtControl->Put_MovieHandle ((long) (pointer_sized_int) movie);
  207703. pimpl->qtMovie = pimpl->qtControl->GetMovie();
  207704. if (pimpl->qtMovie != 0)
  207705. pimpl->qtMovie->PutMovieControllerType (isControllerVisible ? qtMovieControllerTypeStandard
  207706. : qtMovieControllerTypeNone);
  207707. }
  207708. if (movie == 0)
  207709. pimpl->clearHandle();
  207710. }
  207711. movieLoaded = (pimpl->qtMovie != 0);
  207712. }
  207713. else
  207714. {
  207715. // You're trying to open a movie when the control hasn't yet been created, probably because
  207716. // you've not yet added this component to a Window and made the whole component hierarchy visible.
  207717. jassertfalse;
  207718. }
  207719. return movieLoaded;
  207720. }
  207721. void QuickTimeMovieComponent::closeMovie()
  207722. {
  207723. stop();
  207724. movieFile = File::nonexistent;
  207725. movieLoaded = false;
  207726. pimpl->qtMovie = 0;
  207727. if (pimpl->qtControl != 0)
  207728. pimpl->qtControl->Put_MovieHandle (0);
  207729. pimpl->clearHandle();
  207730. }
  207731. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  207732. {
  207733. return movieFile;
  207734. }
  207735. bool QuickTimeMovieComponent::isMovieOpen() const
  207736. {
  207737. return movieLoaded;
  207738. }
  207739. double QuickTimeMovieComponent::getMovieDuration() const
  207740. {
  207741. if (pimpl->qtMovie != 0)
  207742. return pimpl->qtMovie->GetDuration() / (double) pimpl->qtMovie->GetTimeScale();
  207743. return 0.0;
  207744. }
  207745. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  207746. {
  207747. if (pimpl->qtMovie != 0)
  207748. {
  207749. struct QTRECT r = pimpl->qtMovie->GetNaturalRect();
  207750. width = r.right - r.left;
  207751. height = r.bottom - r.top;
  207752. }
  207753. else
  207754. {
  207755. width = height = 0;
  207756. }
  207757. }
  207758. void QuickTimeMovieComponent::play()
  207759. {
  207760. if (pimpl->qtMovie != 0)
  207761. pimpl->qtMovie->Play();
  207762. }
  207763. void QuickTimeMovieComponent::stop()
  207764. {
  207765. if (pimpl->qtMovie != 0)
  207766. pimpl->qtMovie->Stop();
  207767. }
  207768. bool QuickTimeMovieComponent::isPlaying() const
  207769. {
  207770. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetRate() != 0.0f;
  207771. }
  207772. void QuickTimeMovieComponent::setPosition (const double seconds)
  207773. {
  207774. if (pimpl->qtMovie != 0)
  207775. pimpl->qtMovie->PutTime ((long) (seconds * pimpl->qtMovie->GetTimeScale()));
  207776. }
  207777. double QuickTimeMovieComponent::getPosition() const
  207778. {
  207779. if (pimpl->qtMovie != 0)
  207780. return pimpl->qtMovie->GetTime() / (double) pimpl->qtMovie->GetTimeScale();
  207781. return 0.0;
  207782. }
  207783. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  207784. {
  207785. if (pimpl->qtMovie != 0)
  207786. pimpl->qtMovie->PutRate (newSpeed);
  207787. }
  207788. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  207789. {
  207790. if (pimpl->qtMovie != 0)
  207791. {
  207792. pimpl->qtMovie->PutAudioVolume (newVolume);
  207793. pimpl->qtMovie->PutAudioMute (newVolume <= 0);
  207794. }
  207795. }
  207796. float QuickTimeMovieComponent::getMovieVolume() const
  207797. {
  207798. if (pimpl->qtMovie != 0)
  207799. return pimpl->qtMovie->GetAudioVolume();
  207800. return 0.0f;
  207801. }
  207802. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  207803. {
  207804. if (pimpl->qtMovie != 0)
  207805. pimpl->qtMovie->PutLoop (shouldLoop);
  207806. }
  207807. bool QuickTimeMovieComponent::isLooping() const
  207808. {
  207809. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetLoop();
  207810. }
  207811. bool QuickTimeMovieComponent::isControllerVisible() const
  207812. {
  207813. return controllerVisible;
  207814. }
  207815. void QuickTimeMovieComponent::parentHierarchyChanged()
  207816. {
  207817. createControlIfNeeded();
  207818. QTCompBaseClass::parentHierarchyChanged();
  207819. }
  207820. void QuickTimeMovieComponent::visibilityChanged()
  207821. {
  207822. createControlIfNeeded();
  207823. QTCompBaseClass::visibilityChanged();
  207824. }
  207825. void QuickTimeMovieComponent::paint (Graphics& g)
  207826. {
  207827. if (! isControlCreated())
  207828. g.fillAll (Colours::black);
  207829. }
  207830. static Handle createHandleDataRef (Handle dataHandle, const char* fileName)
  207831. {
  207832. Handle dataRef = 0;
  207833. OSStatus err = PtrToHand (&dataHandle, &dataRef, sizeof (Handle));
  207834. if (err == noErr)
  207835. {
  207836. Str255 suffix;
  207837. CharacterFunctions::copy ((char*) suffix, fileName, 128);
  207838. StringPtr name = suffix;
  207839. err = PtrAndHand (name, dataRef, name[0] + 1);
  207840. if (err == noErr)
  207841. {
  207842. long atoms[3];
  207843. atoms[0] = EndianU32_NtoB (3 * sizeof (long));
  207844. atoms[1] = EndianU32_NtoB (kDataRefExtensionMacOSFileType);
  207845. atoms[2] = EndianU32_NtoB (MovieFileType);
  207846. err = PtrAndHand (atoms, dataRef, 3 * sizeof (long));
  207847. if (err == noErr)
  207848. return dataRef;
  207849. }
  207850. DisposeHandle (dataRef);
  207851. }
  207852. return 0;
  207853. }
  207854. static CFStringRef juceStringToCFString (const String& s)
  207855. {
  207856. const int len = s.length();
  207857. const juce_wchar* const t = s;
  207858. HeapBlock <UniChar> temp (len + 2);
  207859. for (int i = 0; i <= len; ++i)
  207860. temp[i] = t[i];
  207861. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  207862. }
  207863. static bool openMovie (QTNewMoviePropertyElement* props, int prop, Movie& movie)
  207864. {
  207865. Boolean trueBool = true;
  207866. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  207867. props[prop].propID = kQTMovieInstantiationPropertyID_DontResolveDataRefs;
  207868. props[prop].propValueSize = sizeof (trueBool);
  207869. props[prop].propValueAddress = &trueBool;
  207870. ++prop;
  207871. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  207872. props[prop].propID = kQTMovieInstantiationPropertyID_AsyncOK;
  207873. props[prop].propValueSize = sizeof (trueBool);
  207874. props[prop].propValueAddress = &trueBool;
  207875. ++prop;
  207876. Boolean isActive = true;
  207877. props[prop].propClass = kQTPropertyClass_NewMovieProperty;
  207878. props[prop].propID = kQTNewMoviePropertyID_Active;
  207879. props[prop].propValueSize = sizeof (isActive);
  207880. props[prop].propValueAddress = &isActive;
  207881. ++prop;
  207882. MacSetPort (0);
  207883. jassert (prop <= 5);
  207884. OSStatus err = NewMovieFromProperties (prop, props, 0, 0, &movie);
  207885. return err == noErr;
  207886. }
  207887. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle)
  207888. {
  207889. if (input == 0)
  207890. return false;
  207891. dataHandle = 0;
  207892. bool ok = false;
  207893. QTNewMoviePropertyElement props[5];
  207894. zeromem (props, sizeof (props));
  207895. int prop = 0;
  207896. DataReferenceRecord dr;
  207897. props[prop].propClass = kQTPropertyClass_DataLocation;
  207898. props[prop].propID = kQTDataLocationPropertyID_DataReference;
  207899. props[prop].propValueSize = sizeof (dr);
  207900. props[prop].propValueAddress = &dr;
  207901. ++prop;
  207902. FileInputStream* const fin = dynamic_cast <FileInputStream*> (input);
  207903. if (fin != 0)
  207904. {
  207905. CFStringRef filePath = juceStringToCFString (fin->getFile().getFullPathName());
  207906. QTNewDataReferenceFromFullPathCFString (filePath, (QTPathStyle) kQTNativeDefaultPathStyle, 0,
  207907. &dr.dataRef, &dr.dataRefType);
  207908. ok = openMovie (props, prop, movie);
  207909. DisposeHandle (dr.dataRef);
  207910. CFRelease (filePath);
  207911. }
  207912. else
  207913. {
  207914. // sanity-check because this currently needs to load the whole stream into memory..
  207915. jassert (input->getTotalLength() < 50 * 1024 * 1024);
  207916. dataHandle = NewHandle ((Size) input->getTotalLength());
  207917. HLock (dataHandle);
  207918. // read the entire stream into memory - this is a pain, but can't get it to work
  207919. // properly using a custom callback to supply the data.
  207920. input->read (*dataHandle, (int) input->getTotalLength());
  207921. HUnlock (dataHandle);
  207922. // different types to get QT to try. (We should really be a bit smarter here by
  207923. // working out in advance which one the stream contains, rather than just trying
  207924. // each one)
  207925. const char* const suffixesToTry[] = { "\04.mov", "\04.mp3",
  207926. "\04.avi", "\04.m4a" };
  207927. for (int i = 0; i < numElementsInArray (suffixesToTry) && ! ok; ++i)
  207928. {
  207929. /* // this fails for some bizarre reason - it can be bodged to work with
  207930. // movies, but can't seem to do it for other file types..
  207931. QTNewMovieUserProcRecord procInfo;
  207932. procInfo.getMovieUserProc = NewGetMovieUPP (readMovieStreamProc);
  207933. procInfo.getMovieUserProcRefcon = this;
  207934. procInfo.defaultDataRef.dataRef = dataRef;
  207935. procInfo.defaultDataRef.dataRefType = HandleDataHandlerSubType;
  207936. props[prop].propClass = kQTPropertyClass_DataLocation;
  207937. props[prop].propID = kQTDataLocationPropertyID_MovieUserProc;
  207938. props[prop].propValueSize = sizeof (procInfo);
  207939. props[prop].propValueAddress = (void*) &procInfo;
  207940. ++prop; */
  207941. dr.dataRef = createHandleDataRef (dataHandle, suffixesToTry [i]);
  207942. dr.dataRefType = HandleDataHandlerSubType;
  207943. ok = openMovie (props, prop, movie);
  207944. DisposeHandle (dr.dataRef);
  207945. }
  207946. }
  207947. return ok;
  207948. }
  207949. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  207950. const bool isControllerVisible)
  207951. {
  207952. const bool ok = loadMovie (static_cast <InputStream*> (movieFile_.createInputStream()), isControllerVisible);
  207953. movieFile = movieFile_;
  207954. return ok;
  207955. }
  207956. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  207957. const bool isControllerVisible)
  207958. {
  207959. return loadMovie (static_cast <InputStream*> (movieURL.createInputStream (false)), isControllerVisible);
  207960. }
  207961. void QuickTimeMovieComponent::goToStart()
  207962. {
  207963. setPosition (0.0);
  207964. }
  207965. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  207966. const RectanglePlacement& placement)
  207967. {
  207968. int normalWidth, normalHeight;
  207969. getMovieNormalSize (normalWidth, normalHeight);
  207970. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  207971. {
  207972. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  207973. placement.applyTo (x, y, w, h,
  207974. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  207975. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  207976. if (w > 0 && h > 0)
  207977. {
  207978. setBounds (roundToInt (x), roundToInt (y),
  207979. roundToInt (w), roundToInt (h));
  207980. }
  207981. }
  207982. else
  207983. {
  207984. setBounds (spaceToFitWithin);
  207985. }
  207986. }
  207987. #endif
  207988. /*** End of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  207989. /*** Start of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  207990. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  207991. // compiled on its own).
  207992. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  207993. class WebBrowserComponentInternal : public ActiveXControlComponent
  207994. {
  207995. public:
  207996. WebBrowserComponentInternal()
  207997. : browser (0),
  207998. connectionPoint (0),
  207999. adviseCookie (0)
  208000. {
  208001. }
  208002. ~WebBrowserComponentInternal()
  208003. {
  208004. if (connectionPoint != 0)
  208005. connectionPoint->Unadvise (adviseCookie);
  208006. if (browser != 0)
  208007. browser->Release();
  208008. }
  208009. void createBrowser()
  208010. {
  208011. createControl (&CLSID_WebBrowser);
  208012. browser = (IWebBrowser2*) queryInterface (&IID_IWebBrowser2);
  208013. IConnectionPointContainer* connectionPointContainer = (IConnectionPointContainer*) queryInterface (&IID_IConnectionPointContainer);
  208014. if (connectionPointContainer != 0)
  208015. {
  208016. connectionPointContainer->FindConnectionPoint (DIID_DWebBrowserEvents2,
  208017. &connectionPoint);
  208018. if (connectionPoint != 0)
  208019. {
  208020. WebBrowserComponent* const owner = dynamic_cast <WebBrowserComponent*> (getParentComponent());
  208021. jassert (owner != 0);
  208022. EventHandler* handler = new EventHandler (owner);
  208023. connectionPoint->Advise (handler, &adviseCookie);
  208024. handler->Release();
  208025. }
  208026. }
  208027. }
  208028. void goToURL (const String& url,
  208029. const StringArray* headers,
  208030. const MemoryBlock* postData)
  208031. {
  208032. if (browser != 0)
  208033. {
  208034. LPSAFEARRAY sa = 0;
  208035. VARIANT flags, frame, postDataVar, headersVar; // (_variant_t isn't available in all compilers)
  208036. VariantInit (&flags);
  208037. VariantInit (&frame);
  208038. VariantInit (&postDataVar);
  208039. VariantInit (&headersVar);
  208040. if (headers != 0)
  208041. {
  208042. V_VT (&headersVar) = VT_BSTR;
  208043. V_BSTR (&headersVar) = SysAllocString ((const OLECHAR*) headers->joinIntoString ("\r\n"));
  208044. }
  208045. if (postData != 0 && postData->getSize() > 0)
  208046. {
  208047. LPSAFEARRAY sa = SafeArrayCreateVector (VT_UI1, 0, postData->getSize());
  208048. if (sa != 0)
  208049. {
  208050. void* data = 0;
  208051. SafeArrayAccessData (sa, &data);
  208052. jassert (data != 0);
  208053. if (data != 0)
  208054. {
  208055. postData->copyTo (data, 0, postData->getSize());
  208056. SafeArrayUnaccessData (sa);
  208057. VARIANT postDataVar2;
  208058. VariantInit (&postDataVar2);
  208059. V_VT (&postDataVar2) = VT_ARRAY | VT_UI1;
  208060. V_ARRAY (&postDataVar2) = sa;
  208061. postDataVar = postDataVar2;
  208062. }
  208063. }
  208064. }
  208065. browser->Navigate ((BSTR) (const OLECHAR*) url,
  208066. &flags, &frame,
  208067. &postDataVar, &headersVar);
  208068. if (sa != 0)
  208069. SafeArrayDestroy (sa);
  208070. VariantClear (&flags);
  208071. VariantClear (&frame);
  208072. VariantClear (&postDataVar);
  208073. VariantClear (&headersVar);
  208074. }
  208075. }
  208076. IWebBrowser2* browser;
  208077. juce_UseDebuggingNewOperator
  208078. private:
  208079. IConnectionPoint* connectionPoint;
  208080. DWORD adviseCookie;
  208081. class EventHandler : public ComBaseClassHelper <IDispatch>,
  208082. public ComponentMovementWatcher
  208083. {
  208084. public:
  208085. EventHandler (WebBrowserComponent* owner_)
  208086. : ComponentMovementWatcher (owner_),
  208087. owner (owner_)
  208088. {
  208089. }
  208090. ~EventHandler()
  208091. {
  208092. }
  208093. HRESULT __stdcall GetTypeInfoCount (UINT __RPC_FAR*) { return E_NOTIMPL; }
  208094. HRESULT __stdcall GetTypeInfo (UINT, LCID, ITypeInfo __RPC_FAR *__RPC_FAR*) { return E_NOTIMPL; }
  208095. HRESULT __stdcall GetIDsOfNames (REFIID, LPOLESTR __RPC_FAR*, UINT, LCID, DISPID __RPC_FAR*) { return E_NOTIMPL; }
  208096. HRESULT __stdcall Invoke (DISPID dispIdMember, REFIID /*riid*/, LCID /*lcid*/,
  208097. WORD /*wFlags*/, DISPPARAMS __RPC_FAR* pDispParams,
  208098. VARIANT __RPC_FAR* /*pVarResult*/, EXCEPINFO __RPC_FAR* /*pExcepInfo*/,
  208099. UINT __RPC_FAR* /*puArgErr*/)
  208100. {
  208101. switch (dispIdMember)
  208102. {
  208103. case DISPID_BEFORENAVIGATE2:
  208104. {
  208105. VARIANT* const vurl = pDispParams->rgvarg[5].pvarVal;
  208106. String url;
  208107. if ((vurl->vt & VT_BYREF) != 0)
  208108. url = *vurl->pbstrVal;
  208109. else
  208110. url = vurl->bstrVal;
  208111. *pDispParams->rgvarg->pboolVal
  208112. = owner->pageAboutToLoad (url) ? VARIANT_FALSE
  208113. : VARIANT_TRUE;
  208114. return S_OK;
  208115. }
  208116. default:
  208117. break;
  208118. }
  208119. return E_NOTIMPL;
  208120. }
  208121. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/) {}
  208122. void componentPeerChanged() {}
  208123. void componentVisibilityChanged (Component&)
  208124. {
  208125. owner->visibilityChanged();
  208126. }
  208127. juce_UseDebuggingNewOperator
  208128. private:
  208129. WebBrowserComponent* const owner;
  208130. EventHandler (const EventHandler&);
  208131. EventHandler& operator= (const EventHandler&);
  208132. };
  208133. };
  208134. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  208135. : browser (0),
  208136. blankPageShown (false),
  208137. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  208138. {
  208139. setOpaque (true);
  208140. addAndMakeVisible (browser = new WebBrowserComponentInternal());
  208141. }
  208142. WebBrowserComponent::~WebBrowserComponent()
  208143. {
  208144. delete browser;
  208145. }
  208146. void WebBrowserComponent::goToURL (const String& url,
  208147. const StringArray* headers,
  208148. const MemoryBlock* postData)
  208149. {
  208150. lastURL = url;
  208151. lastHeaders.clear();
  208152. if (headers != 0)
  208153. lastHeaders = *headers;
  208154. lastPostData.setSize (0);
  208155. if (postData != 0)
  208156. lastPostData = *postData;
  208157. blankPageShown = false;
  208158. browser->goToURL (url, headers, postData);
  208159. }
  208160. void WebBrowserComponent::stop()
  208161. {
  208162. if (browser->browser != 0)
  208163. browser->browser->Stop();
  208164. }
  208165. void WebBrowserComponent::goBack()
  208166. {
  208167. lastURL = String::empty;
  208168. blankPageShown = false;
  208169. if (browser->browser != 0)
  208170. browser->browser->GoBack();
  208171. }
  208172. void WebBrowserComponent::goForward()
  208173. {
  208174. lastURL = String::empty;
  208175. if (browser->browser != 0)
  208176. browser->browser->GoForward();
  208177. }
  208178. void WebBrowserComponent::refresh()
  208179. {
  208180. if (browser->browser != 0)
  208181. browser->browser->Refresh();
  208182. }
  208183. void WebBrowserComponent::paint (Graphics& g)
  208184. {
  208185. if (browser->browser == 0)
  208186. g.fillAll (Colours::white);
  208187. }
  208188. void WebBrowserComponent::checkWindowAssociation()
  208189. {
  208190. if (isShowing())
  208191. {
  208192. if (browser->browser == 0 && getPeer() != 0)
  208193. {
  208194. browser->createBrowser();
  208195. reloadLastURL();
  208196. }
  208197. else
  208198. {
  208199. if (blankPageShown)
  208200. goBack();
  208201. }
  208202. }
  208203. else
  208204. {
  208205. if (browser != 0 && unloadPageWhenBrowserIsHidden && ! blankPageShown)
  208206. {
  208207. // when the component becomes invisible, some stuff like flash
  208208. // carries on playing audio, so we need to force it onto a blank
  208209. // page to avoid this..
  208210. blankPageShown = true;
  208211. browser->goToURL ("about:blank", 0, 0);
  208212. }
  208213. }
  208214. }
  208215. void WebBrowserComponent::reloadLastURL()
  208216. {
  208217. if (lastURL.isNotEmpty())
  208218. {
  208219. goToURL (lastURL, &lastHeaders, &lastPostData);
  208220. lastURL = String::empty;
  208221. }
  208222. }
  208223. void WebBrowserComponent::parentHierarchyChanged()
  208224. {
  208225. checkWindowAssociation();
  208226. }
  208227. void WebBrowserComponent::resized()
  208228. {
  208229. browser->setSize (getWidth(), getHeight());
  208230. }
  208231. void WebBrowserComponent::visibilityChanged()
  208232. {
  208233. checkWindowAssociation();
  208234. }
  208235. bool WebBrowserComponent::pageAboutToLoad (const String&)
  208236. {
  208237. return true;
  208238. }
  208239. #endif
  208240. /*** End of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  208241. /*** Start of inlined file: juce_win32_OpenGLComponent.cpp ***/
  208242. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208243. // compiled on its own).
  208244. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  208245. #define WGL_EXT_FUNCTION_INIT(extType, extFunc) \
  208246. ((extFunc = (extType) wglGetProcAddress (#extFunc)) != 0)
  208247. typedef const char* (WINAPI* PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
  208248. typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
  208249. typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int* piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
  208250. typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
  208251. typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
  208252. #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
  208253. #define WGL_DRAW_TO_WINDOW_ARB 0x2001
  208254. #define WGL_ACCELERATION_ARB 0x2003
  208255. #define WGL_SWAP_METHOD_ARB 0x2007
  208256. #define WGL_SUPPORT_OPENGL_ARB 0x2010
  208257. #define WGL_PIXEL_TYPE_ARB 0x2013
  208258. #define WGL_DOUBLE_BUFFER_ARB 0x2011
  208259. #define WGL_COLOR_BITS_ARB 0x2014
  208260. #define WGL_RED_BITS_ARB 0x2015
  208261. #define WGL_GREEN_BITS_ARB 0x2017
  208262. #define WGL_BLUE_BITS_ARB 0x2019
  208263. #define WGL_ALPHA_BITS_ARB 0x201B
  208264. #define WGL_DEPTH_BITS_ARB 0x2022
  208265. #define WGL_STENCIL_BITS_ARB 0x2023
  208266. #define WGL_FULL_ACCELERATION_ARB 0x2027
  208267. #define WGL_ACCUM_RED_BITS_ARB 0x201E
  208268. #define WGL_ACCUM_GREEN_BITS_ARB 0x201F
  208269. #define WGL_ACCUM_BLUE_BITS_ARB 0x2020
  208270. #define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
  208271. #define WGL_STEREO_ARB 0x2012
  208272. #define WGL_SAMPLE_BUFFERS_ARB 0x2041
  208273. #define WGL_SAMPLES_ARB 0x2042
  208274. #define WGL_TYPE_RGBA_ARB 0x202B
  208275. static void getWglExtensions (HDC dc, StringArray& result) throw()
  208276. {
  208277. PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = 0;
  208278. if (WGL_EXT_FUNCTION_INIT (PFNWGLGETEXTENSIONSSTRINGARBPROC, wglGetExtensionsStringARB))
  208279. result.addTokens (String (wglGetExtensionsStringARB (dc)), false);
  208280. else
  208281. jassertfalse; // If this fails, it may be because you didn't activate the openGL context
  208282. }
  208283. class WindowedGLContext : public OpenGLContext
  208284. {
  208285. public:
  208286. WindowedGLContext (Component* const component_,
  208287. HGLRC contextToShareWith,
  208288. const OpenGLPixelFormat& pixelFormat)
  208289. : renderContext (0),
  208290. nativeWindow (0),
  208291. dc (0),
  208292. component (component_)
  208293. {
  208294. jassert (component != 0);
  208295. createNativeWindow();
  208296. // Use a default pixel format that should be supported everywhere
  208297. PIXELFORMATDESCRIPTOR pfd;
  208298. zerostruct (pfd);
  208299. pfd.nSize = sizeof (pfd);
  208300. pfd.nVersion = 1;
  208301. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  208302. pfd.iPixelType = PFD_TYPE_RGBA;
  208303. pfd.cColorBits = 24;
  208304. pfd.cDepthBits = 16;
  208305. const int format = ChoosePixelFormat (dc, &pfd);
  208306. if (format != 0)
  208307. SetPixelFormat (dc, format, &pfd);
  208308. renderContext = wglCreateContext (dc);
  208309. makeActive();
  208310. setPixelFormat (pixelFormat);
  208311. if (contextToShareWith != 0 && renderContext != 0)
  208312. wglShareLists (contextToShareWith, renderContext);
  208313. }
  208314. ~WindowedGLContext()
  208315. {
  208316. makeInactive();
  208317. wglDeleteContext (renderContext);
  208318. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  208319. delete nativeWindow;
  208320. }
  208321. bool makeActive() const throw()
  208322. {
  208323. jassert (renderContext != 0);
  208324. return wglMakeCurrent (dc, renderContext) != 0;
  208325. }
  208326. bool makeInactive() const throw()
  208327. {
  208328. return (! isActive()) || (wglMakeCurrent (0, 0) != 0);
  208329. }
  208330. bool isActive() const throw()
  208331. {
  208332. return wglGetCurrentContext() == renderContext;
  208333. }
  208334. const OpenGLPixelFormat getPixelFormat() const
  208335. {
  208336. OpenGLPixelFormat pf;
  208337. makeActive();
  208338. StringArray availableExtensions;
  208339. getWglExtensions (dc, availableExtensions);
  208340. fillInPixelFormatDetails (GetPixelFormat (dc), pf, availableExtensions);
  208341. return pf;
  208342. }
  208343. void* getRawContext() const throw()
  208344. {
  208345. return renderContext;
  208346. }
  208347. bool setPixelFormat (const OpenGLPixelFormat& pixelFormat)
  208348. {
  208349. makeActive();
  208350. PIXELFORMATDESCRIPTOR pfd;
  208351. zerostruct (pfd);
  208352. pfd.nSize = sizeof (pfd);
  208353. pfd.nVersion = 1;
  208354. pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
  208355. pfd.iPixelType = PFD_TYPE_RGBA;
  208356. pfd.iLayerType = PFD_MAIN_PLANE;
  208357. pfd.cColorBits = (BYTE) (pixelFormat.redBits + pixelFormat.greenBits + pixelFormat.blueBits);
  208358. pfd.cRedBits = (BYTE) pixelFormat.redBits;
  208359. pfd.cGreenBits = (BYTE) pixelFormat.greenBits;
  208360. pfd.cBlueBits = (BYTE) pixelFormat.blueBits;
  208361. pfd.cAlphaBits = (BYTE) pixelFormat.alphaBits;
  208362. pfd.cDepthBits = (BYTE) pixelFormat.depthBufferBits;
  208363. pfd.cStencilBits = (BYTE) pixelFormat.stencilBufferBits;
  208364. pfd.cAccumBits = (BYTE) (pixelFormat.accumulationBufferRedBits + pixelFormat.accumulationBufferGreenBits
  208365. + pixelFormat.accumulationBufferBlueBits + pixelFormat.accumulationBufferAlphaBits);
  208366. pfd.cAccumRedBits = (BYTE) pixelFormat.accumulationBufferRedBits;
  208367. pfd.cAccumGreenBits = (BYTE) pixelFormat.accumulationBufferGreenBits;
  208368. pfd.cAccumBlueBits = (BYTE) pixelFormat.accumulationBufferBlueBits;
  208369. pfd.cAccumAlphaBits = (BYTE) pixelFormat.accumulationBufferAlphaBits;
  208370. int format = 0;
  208371. PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = 0;
  208372. StringArray availableExtensions;
  208373. getWglExtensions (dc, availableExtensions);
  208374. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  208375. && WGL_EXT_FUNCTION_INIT (PFNWGLCHOOSEPIXELFORMATARBPROC, wglChoosePixelFormatARB))
  208376. {
  208377. int attributes[64];
  208378. int n = 0;
  208379. attributes[n++] = WGL_DRAW_TO_WINDOW_ARB;
  208380. attributes[n++] = GL_TRUE;
  208381. attributes[n++] = WGL_SUPPORT_OPENGL_ARB;
  208382. attributes[n++] = GL_TRUE;
  208383. attributes[n++] = WGL_ACCELERATION_ARB;
  208384. attributes[n++] = WGL_FULL_ACCELERATION_ARB;
  208385. attributes[n++] = WGL_DOUBLE_BUFFER_ARB;
  208386. attributes[n++] = GL_TRUE;
  208387. attributes[n++] = WGL_PIXEL_TYPE_ARB;
  208388. attributes[n++] = WGL_TYPE_RGBA_ARB;
  208389. attributes[n++] = WGL_COLOR_BITS_ARB;
  208390. attributes[n++] = pfd.cColorBits;
  208391. attributes[n++] = WGL_RED_BITS_ARB;
  208392. attributes[n++] = pixelFormat.redBits;
  208393. attributes[n++] = WGL_GREEN_BITS_ARB;
  208394. attributes[n++] = pixelFormat.greenBits;
  208395. attributes[n++] = WGL_BLUE_BITS_ARB;
  208396. attributes[n++] = pixelFormat.blueBits;
  208397. attributes[n++] = WGL_ALPHA_BITS_ARB;
  208398. attributes[n++] = pixelFormat.alphaBits;
  208399. attributes[n++] = WGL_DEPTH_BITS_ARB;
  208400. attributes[n++] = pixelFormat.depthBufferBits;
  208401. if (pixelFormat.stencilBufferBits > 0)
  208402. {
  208403. attributes[n++] = WGL_STENCIL_BITS_ARB;
  208404. attributes[n++] = pixelFormat.stencilBufferBits;
  208405. }
  208406. attributes[n++] = WGL_ACCUM_RED_BITS_ARB;
  208407. attributes[n++] = pixelFormat.accumulationBufferRedBits;
  208408. attributes[n++] = WGL_ACCUM_GREEN_BITS_ARB;
  208409. attributes[n++] = pixelFormat.accumulationBufferGreenBits;
  208410. attributes[n++] = WGL_ACCUM_BLUE_BITS_ARB;
  208411. attributes[n++] = pixelFormat.accumulationBufferBlueBits;
  208412. attributes[n++] = WGL_ACCUM_ALPHA_BITS_ARB;
  208413. attributes[n++] = pixelFormat.accumulationBufferAlphaBits;
  208414. if (availableExtensions.contains ("WGL_ARB_multisample")
  208415. && pixelFormat.fullSceneAntiAliasingNumSamples > 0)
  208416. {
  208417. attributes[n++] = WGL_SAMPLE_BUFFERS_ARB;
  208418. attributes[n++] = 1;
  208419. attributes[n++] = WGL_SAMPLES_ARB;
  208420. attributes[n++] = pixelFormat.fullSceneAntiAliasingNumSamples;
  208421. }
  208422. attributes[n++] = 0;
  208423. UINT formatsCount;
  208424. const BOOL ok = wglChoosePixelFormatARB (dc, attributes, 0, 1, &format, &formatsCount);
  208425. (void) ok;
  208426. jassert (ok);
  208427. }
  208428. else
  208429. {
  208430. format = ChoosePixelFormat (dc, &pfd);
  208431. }
  208432. if (format != 0)
  208433. {
  208434. makeInactive();
  208435. // win32 can't change the pixel format of a window, so need to delete the
  208436. // old one and create a new one..
  208437. jassert (nativeWindow != 0);
  208438. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  208439. delete nativeWindow;
  208440. createNativeWindow();
  208441. if (SetPixelFormat (dc, format, &pfd))
  208442. {
  208443. wglDeleteContext (renderContext);
  208444. renderContext = wglCreateContext (dc);
  208445. jassert (renderContext != 0);
  208446. return renderContext != 0;
  208447. }
  208448. }
  208449. return false;
  208450. }
  208451. void updateWindowPosition (int x, int y, int w, int h, int)
  208452. {
  208453. SetWindowPos ((HWND) nativeWindow->getNativeHandle(), 0,
  208454. x, y, w, h,
  208455. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  208456. }
  208457. void repaint()
  208458. {
  208459. nativeWindow->repaint (nativeWindow->getBounds().withPosition (Point<int>()));
  208460. }
  208461. void swapBuffers()
  208462. {
  208463. SwapBuffers (dc);
  208464. }
  208465. bool setSwapInterval (int numFramesPerSwap)
  208466. {
  208467. makeActive();
  208468. StringArray availableExtensions;
  208469. getWglExtensions (dc, availableExtensions);
  208470. PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = 0;
  208471. return availableExtensions.contains ("WGL_EXT_swap_control")
  208472. && WGL_EXT_FUNCTION_INIT (PFNWGLSWAPINTERVALEXTPROC, wglSwapIntervalEXT)
  208473. && wglSwapIntervalEXT (numFramesPerSwap) != FALSE;
  208474. }
  208475. int getSwapInterval() const
  208476. {
  208477. makeActive();
  208478. StringArray availableExtensions;
  208479. getWglExtensions (dc, availableExtensions);
  208480. PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT = 0;
  208481. if (availableExtensions.contains ("WGL_EXT_swap_control")
  208482. && WGL_EXT_FUNCTION_INIT (PFNWGLGETSWAPINTERVALEXTPROC, wglGetSwapIntervalEXT))
  208483. return wglGetSwapIntervalEXT();
  208484. return 0;
  208485. }
  208486. void findAlternativeOpenGLPixelFormats (OwnedArray <OpenGLPixelFormat>& results)
  208487. {
  208488. jassert (isActive());
  208489. StringArray availableExtensions;
  208490. getWglExtensions (dc, availableExtensions);
  208491. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  208492. int numTypes = 0;
  208493. if (availableExtensions.contains("WGL_ARB_pixel_format")
  208494. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  208495. {
  208496. int attributes = WGL_NUMBER_PIXEL_FORMATS_ARB;
  208497. if (! wglGetPixelFormatAttribivARB (dc, 1, 0, 1, &attributes, &numTypes))
  208498. jassertfalse;
  208499. }
  208500. else
  208501. {
  208502. numTypes = DescribePixelFormat (dc, 0, 0, 0);
  208503. }
  208504. OpenGLPixelFormat pf;
  208505. for (int i = 0; i < numTypes; ++i)
  208506. {
  208507. if (fillInPixelFormatDetails (i + 1, pf, availableExtensions))
  208508. {
  208509. bool alreadyListed = false;
  208510. for (int j = results.size(); --j >= 0;)
  208511. if (pf == *results.getUnchecked(j))
  208512. alreadyListed = true;
  208513. if (! alreadyListed)
  208514. results.add (new OpenGLPixelFormat (pf));
  208515. }
  208516. }
  208517. }
  208518. void* getNativeWindowHandle() const
  208519. {
  208520. return nativeWindow != 0 ? nativeWindow->getNativeHandle() : 0;
  208521. }
  208522. juce_UseDebuggingNewOperator
  208523. HGLRC renderContext;
  208524. private:
  208525. Win32ComponentPeer* nativeWindow;
  208526. Component* const component;
  208527. HDC dc;
  208528. void createNativeWindow()
  208529. {
  208530. nativeWindow = new Win32ComponentPeer (component, 0);
  208531. nativeWindow->dontRepaint = true;
  208532. nativeWindow->setVisible (true);
  208533. HWND hwnd = (HWND) nativeWindow->getNativeHandle();
  208534. Win32ComponentPeer* const peer = dynamic_cast <Win32ComponentPeer*> (component->getTopLevelComponent()->getPeer());
  208535. if (peer != 0)
  208536. {
  208537. SetParent (hwnd, (HWND) peer->getNativeHandle());
  208538. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_CHILD, true);
  208539. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_POPUP, false);
  208540. }
  208541. dc = GetDC (hwnd);
  208542. }
  208543. bool fillInPixelFormatDetails (const int pixelFormatIndex,
  208544. OpenGLPixelFormat& result,
  208545. const StringArray& availableExtensions) const throw()
  208546. {
  208547. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  208548. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  208549. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  208550. {
  208551. int attributes[32];
  208552. int numAttributes = 0;
  208553. attributes[numAttributes++] = WGL_DRAW_TO_WINDOW_ARB;
  208554. attributes[numAttributes++] = WGL_SUPPORT_OPENGL_ARB;
  208555. attributes[numAttributes++] = WGL_ACCELERATION_ARB;
  208556. attributes[numAttributes++] = WGL_DOUBLE_BUFFER_ARB;
  208557. attributes[numAttributes++] = WGL_PIXEL_TYPE_ARB;
  208558. attributes[numAttributes++] = WGL_RED_BITS_ARB;
  208559. attributes[numAttributes++] = WGL_GREEN_BITS_ARB;
  208560. attributes[numAttributes++] = WGL_BLUE_BITS_ARB;
  208561. attributes[numAttributes++] = WGL_ALPHA_BITS_ARB;
  208562. attributes[numAttributes++] = WGL_DEPTH_BITS_ARB;
  208563. attributes[numAttributes++] = WGL_STENCIL_BITS_ARB;
  208564. attributes[numAttributes++] = WGL_ACCUM_RED_BITS_ARB;
  208565. attributes[numAttributes++] = WGL_ACCUM_GREEN_BITS_ARB;
  208566. attributes[numAttributes++] = WGL_ACCUM_BLUE_BITS_ARB;
  208567. attributes[numAttributes++] = WGL_ACCUM_ALPHA_BITS_ARB;
  208568. if (availableExtensions.contains ("WGL_ARB_multisample"))
  208569. attributes[numAttributes++] = WGL_SAMPLES_ARB;
  208570. int values[32];
  208571. zeromem (values, sizeof (values));
  208572. if (wglGetPixelFormatAttribivARB (dc, pixelFormatIndex, 0, numAttributes, attributes, values))
  208573. {
  208574. int n = 0;
  208575. bool isValidFormat = (values[n++] == GL_TRUE); // WGL_DRAW_TO_WINDOW_ARB
  208576. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_SUPPORT_OPENGL_ARB
  208577. isValidFormat = (values[n++] == WGL_FULL_ACCELERATION_ARB) && isValidFormat; // WGL_ACCELERATION_ARB
  208578. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_DOUBLE_BUFFER_ARB:
  208579. isValidFormat = (values[n++] == WGL_TYPE_RGBA_ARB) && isValidFormat; // WGL_PIXEL_TYPE_ARB
  208580. result.redBits = values[n++]; // WGL_RED_BITS_ARB
  208581. result.greenBits = values[n++]; // WGL_GREEN_BITS_ARB
  208582. result.blueBits = values[n++]; // WGL_BLUE_BITS_ARB
  208583. result.alphaBits = values[n++]; // WGL_ALPHA_BITS_ARB
  208584. result.depthBufferBits = values[n++]; // WGL_DEPTH_BITS_ARB
  208585. result.stencilBufferBits = values[n++]; // WGL_STENCIL_BITS_ARB
  208586. result.accumulationBufferRedBits = values[n++]; // WGL_ACCUM_RED_BITS_ARB
  208587. result.accumulationBufferGreenBits = values[n++]; // WGL_ACCUM_GREEN_BITS_ARB
  208588. result.accumulationBufferBlueBits = values[n++]; // WGL_ACCUM_BLUE_BITS_ARB
  208589. result.accumulationBufferAlphaBits = values[n++]; // WGL_ACCUM_ALPHA_BITS_ARB
  208590. result.fullSceneAntiAliasingNumSamples = (uint8) values[n++]; // WGL_SAMPLES_ARB
  208591. return isValidFormat;
  208592. }
  208593. else
  208594. {
  208595. jassertfalse;
  208596. }
  208597. }
  208598. else
  208599. {
  208600. PIXELFORMATDESCRIPTOR pfd;
  208601. if (DescribePixelFormat (dc, pixelFormatIndex, sizeof (pfd), &pfd))
  208602. {
  208603. result.redBits = pfd.cRedBits;
  208604. result.greenBits = pfd.cGreenBits;
  208605. result.blueBits = pfd.cBlueBits;
  208606. result.alphaBits = pfd.cAlphaBits;
  208607. result.depthBufferBits = pfd.cDepthBits;
  208608. result.stencilBufferBits = pfd.cStencilBits;
  208609. result.accumulationBufferRedBits = pfd.cAccumRedBits;
  208610. result.accumulationBufferGreenBits = pfd.cAccumGreenBits;
  208611. result.accumulationBufferBlueBits = pfd.cAccumBlueBits;
  208612. result.accumulationBufferAlphaBits = pfd.cAccumAlphaBits;
  208613. result.fullSceneAntiAliasingNumSamples = 0;
  208614. return true;
  208615. }
  208616. else
  208617. {
  208618. jassertfalse;
  208619. }
  208620. }
  208621. return false;
  208622. }
  208623. WindowedGLContext (const WindowedGLContext&);
  208624. WindowedGLContext& operator= (const WindowedGLContext&);
  208625. };
  208626. OpenGLContext* OpenGLComponent::createContext()
  208627. {
  208628. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this,
  208629. contextToShareListsWith != 0 ? (HGLRC) contextToShareListsWith->getRawContext() : 0,
  208630. preferredPixelFormat));
  208631. return (c->renderContext != 0) ? c.release() : 0;
  208632. }
  208633. void* OpenGLComponent::getNativeWindowHandle() const
  208634. {
  208635. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle() : 0;
  208636. }
  208637. void juce_glViewport (const int w, const int h)
  208638. {
  208639. glViewport (0, 0, w, h);
  208640. }
  208641. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  208642. OwnedArray <OpenGLPixelFormat>& results)
  208643. {
  208644. Component tempComp;
  208645. {
  208646. WindowedGLContext wc (component, 0, OpenGLPixelFormat (8, 8, 16, 0));
  208647. wc.makeActive();
  208648. wc.findAlternativeOpenGLPixelFormats (results);
  208649. }
  208650. }
  208651. #endif
  208652. /*** End of inlined file: juce_win32_OpenGLComponent.cpp ***/
  208653. /*** Start of inlined file: juce_win32_AudioCDReader.cpp ***/
  208654. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208655. // compiled on its own).
  208656. #if JUCE_INCLUDED_FILE
  208657. #if JUCE_USE_CDREADER
  208658. namespace CDReaderHelpers
  208659. {
  208660. //***************************************************************************
  208661. // %%% TARGET STATUS VALUES %%%
  208662. //***************************************************************************
  208663. #define STATUS_GOOD 0x00 // Status Good
  208664. #define STATUS_CHKCOND 0x02 // Check Condition
  208665. #define STATUS_CONDMET 0x04 // Condition Met
  208666. #define STATUS_BUSY 0x08 // Busy
  208667. #define STATUS_INTERM 0x10 // Intermediate
  208668. #define STATUS_INTCDMET 0x14 // Intermediate-condition met
  208669. #define STATUS_RESCONF 0x18 // Reservation conflict
  208670. #define STATUS_COMTERM 0x22 // Command Terminated
  208671. #define STATUS_QFULL 0x28 // Queue full
  208672. //***************************************************************************
  208673. // %%% SCSI MISCELLANEOUS EQUATES %%%
  208674. //***************************************************************************
  208675. #define MAXLUN 7 // Maximum Logical Unit Id
  208676. #define MAXTARG 7 // Maximum Target Id
  208677. #define MAX_SCSI_LUNS 64 // Maximum Number of SCSI LUNs
  208678. #define MAX_NUM_HA 8 // Maximum Number of SCSI HA's
  208679. //***************************************************************************
  208680. // %%% Commands for all Device Types %%%
  208681. //***************************************************************************
  208682. #define SCSI_CHANGE_DEF 0x40 // Change Definition (Optional)
  208683. #define SCSI_COMPARE 0x39 // Compare (O)
  208684. #define SCSI_COPY 0x18 // Copy (O)
  208685. #define SCSI_COP_VERIFY 0x3A // Copy and Verify (O)
  208686. #define SCSI_INQUIRY 0x12 // Inquiry (MANDATORY)
  208687. #define SCSI_LOG_SELECT 0x4C // Log Select (O)
  208688. #define SCSI_LOG_SENSE 0x4D // Log Sense (O)
  208689. #define SCSI_MODE_SEL6 0x15 // Mode Select 6-byte (Device Specific)
  208690. #define SCSI_MODE_SEL10 0x55 // Mode Select 10-byte (Device Specific)
  208691. #define SCSI_MODE_SEN6 0x1A // Mode Sense 6-byte (Device Specific)
  208692. #define SCSI_MODE_SEN10 0x5A // Mode Sense 10-byte (Device Specific)
  208693. #define SCSI_READ_BUFF 0x3C // Read Buffer (O)
  208694. #define SCSI_REQ_SENSE 0x03 // Request Sense (MANDATORY)
  208695. #define SCSI_SEND_DIAG 0x1D // Send Diagnostic (O)
  208696. #define SCSI_TST_U_RDY 0x00 // Test Unit Ready (MANDATORY)
  208697. #define SCSI_WRITE_BUFF 0x3B // Write Buffer (O)
  208698. //***************************************************************************
  208699. // %%% Commands Unique to Direct Access Devices %%%
  208700. //***************************************************************************
  208701. #define SCSI_COMPARE 0x39 // Compare (O)
  208702. #define SCSI_FORMAT 0x04 // Format Unit (MANDATORY)
  208703. #define SCSI_LCK_UN_CAC 0x36 // Lock Unlock Cache (O)
  208704. #define SCSI_PREFETCH 0x34 // Prefetch (O)
  208705. #define SCSI_MED_REMOVL 0x1E // Prevent/Allow medium Removal (O)
  208706. #define SCSI_READ6 0x08 // Read 6-byte (MANDATORY)
  208707. #define SCSI_READ10 0x28 // Read 10-byte (MANDATORY)
  208708. #define SCSI_RD_CAPAC 0x25 // Read Capacity (MANDATORY)
  208709. #define SCSI_RD_DEFECT 0x37 // Read Defect Data (O)
  208710. #define SCSI_READ_LONG 0x3E // Read Long (O)
  208711. #define SCSI_REASS_BLK 0x07 // Reassign Blocks (O)
  208712. #define SCSI_RCV_DIAG 0x1C // Receive Diagnostic Results (O)
  208713. #define SCSI_RELEASE 0x17 // Release Unit (MANDATORY)
  208714. #define SCSI_REZERO 0x01 // Rezero Unit (O)
  208715. #define SCSI_SRCH_DAT_E 0x31 // Search Data Equal (O)
  208716. #define SCSI_SRCH_DAT_H 0x30 // Search Data High (O)
  208717. #define SCSI_SRCH_DAT_L 0x32 // Search Data Low (O)
  208718. #define SCSI_SEEK6 0x0B // Seek 6-Byte (O)
  208719. #define SCSI_SEEK10 0x2B // Seek 10-Byte (O)
  208720. #define SCSI_SEND_DIAG 0x1D // Send Diagnostics (MANDATORY)
  208721. #define SCSI_SET_LIMIT 0x33 // Set Limits (O)
  208722. #define SCSI_START_STP 0x1B // Start/Stop Unit (O)
  208723. #define SCSI_SYNC_CACHE 0x35 // Synchronize Cache (O)
  208724. #define SCSI_VERIFY 0x2F // Verify (O)
  208725. #define SCSI_WRITE6 0x0A // Write 6-Byte (MANDATORY)
  208726. #define SCSI_WRITE10 0x2A // Write 10-Byte (MANDATORY)
  208727. #define SCSI_WRT_VERIFY 0x2E // Write and Verify (O)
  208728. #define SCSI_WRITE_LONG 0x3F // Write Long (O)
  208729. #define SCSI_WRITE_SAME 0x41 // Write Same (O)
  208730. //***************************************************************************
  208731. // %%% Commands Unique to Sequential Access Devices %%%
  208732. //***************************************************************************
  208733. #define SCSI_ERASE 0x19 // Erase (MANDATORY)
  208734. #define SCSI_LOAD_UN 0x1b // Load/Unload (O)
  208735. #define SCSI_LOCATE 0x2B // Locate (O)
  208736. #define SCSI_RD_BLK_LIM 0x05 // Read Block Limits (MANDATORY)
  208737. #define SCSI_READ_POS 0x34 // Read Position (O)
  208738. #define SCSI_READ_REV 0x0F // Read Reverse (O)
  208739. #define SCSI_REC_BF_DAT 0x14 // Recover Buffer Data (O)
  208740. #define SCSI_RESERVE 0x16 // Reserve Unit (MANDATORY)
  208741. #define SCSI_REWIND 0x01 // Rewind (MANDATORY)
  208742. #define SCSI_SPACE 0x11 // Space (MANDATORY)
  208743. #define SCSI_VERIFY_T 0x13 // Verify (Tape) (O)
  208744. #define SCSI_WRT_FILE 0x10 // Write Filemarks (MANDATORY)
  208745. //***************************************************************************
  208746. // %%% Commands Unique to Printer Devices %%%
  208747. //***************************************************************************
  208748. #define SCSI_PRINT 0x0A // Print (MANDATORY)
  208749. #define SCSI_SLEW_PNT 0x0B // Slew and Print (O)
  208750. #define SCSI_STOP_PNT 0x1B // Stop Print (O)
  208751. #define SCSI_SYNC_BUFF 0x10 // Synchronize Buffer (O)
  208752. //***************************************************************************
  208753. // %%% Commands Unique to Processor Devices %%%
  208754. //***************************************************************************
  208755. #define SCSI_RECEIVE 0x08 // Receive (O)
  208756. #define SCSI_SEND 0x0A // Send (O)
  208757. //***************************************************************************
  208758. // %%% Commands Unique to Write-Once Devices %%%
  208759. //***************************************************************************
  208760. #define SCSI_MEDIUM_SCN 0x38 // Medium Scan (O)
  208761. #define SCSI_SRCHDATE10 0x31 // Search Data Equal 10-Byte (O)
  208762. #define SCSI_SRCHDATE12 0xB1 // Search Data Equal 12-Byte (O)
  208763. #define SCSI_SRCHDATH10 0x30 // Search Data High 10-Byte (O)
  208764. #define SCSI_SRCHDATH12 0xB0 // Search Data High 12-Byte (O)
  208765. #define SCSI_SRCHDATL10 0x32 // Search Data Low 10-Byte (O)
  208766. #define SCSI_SRCHDATL12 0xB2 // Search Data Low 12-Byte (O)
  208767. #define SCSI_SET_LIM_10 0x33 // Set Limits 10-Byte (O)
  208768. #define SCSI_SET_LIM_12 0xB3 // Set Limits 10-Byte (O)
  208769. #define SCSI_VERIFY10 0x2F // Verify 10-Byte (O)
  208770. #define SCSI_VERIFY12 0xAF // Verify 12-Byte (O)
  208771. #define SCSI_WRITE12 0xAA // Write 12-Byte (O)
  208772. #define SCSI_WRT_VER10 0x2E // Write and Verify 10-Byte (O)
  208773. #define SCSI_WRT_VER12 0xAE // Write and Verify 12-Byte (O)
  208774. //***************************************************************************
  208775. // %%% Commands Unique to CD-ROM Devices %%%
  208776. //***************************************************************************
  208777. #define SCSI_PLAYAUD_10 0x45 // Play Audio 10-Byte (O)
  208778. #define SCSI_PLAYAUD_12 0xA5 // Play Audio 12-Byte 12-Byte (O)
  208779. #define SCSI_PLAYAUDMSF 0x47 // Play Audio MSF (O)
  208780. #define SCSI_PLAYA_TKIN 0x48 // Play Audio Track/Index (O)
  208781. #define SCSI_PLYTKREL10 0x49 // Play Track Relative 10-Byte (O)
  208782. #define SCSI_PLYTKREL12 0xA9 // Play Track Relative 12-Byte (O)
  208783. #define SCSI_READCDCAP 0x25 // Read CD-ROM Capacity (MANDATORY)
  208784. #define SCSI_READHEADER 0x44 // Read Header (O)
  208785. #define SCSI_SUBCHANNEL 0x42 // Read Subchannel (O)
  208786. #define SCSI_READ_TOC 0x43 // Read TOC (O)
  208787. //***************************************************************************
  208788. // %%% Commands Unique to Scanner Devices %%%
  208789. //***************************************************************************
  208790. #define SCSI_GETDBSTAT 0x34 // Get Data Buffer Status (O)
  208791. #define SCSI_GETWINDOW 0x25 // Get Window (O)
  208792. #define SCSI_OBJECTPOS 0x31 // Object Postion (O)
  208793. #define SCSI_SCAN 0x1B // Scan (O)
  208794. #define SCSI_SETWINDOW 0x24 // Set Window (MANDATORY)
  208795. //***************************************************************************
  208796. // %%% Commands Unique to Optical Memory Devices %%%
  208797. //***************************************************************************
  208798. #define SCSI_UpdateBlk 0x3D // Update Block (O)
  208799. //***************************************************************************
  208800. // %%% Commands Unique to Medium Changer Devices %%%
  208801. //***************************************************************************
  208802. #define SCSI_EXCHMEDIUM 0xA6 // Exchange Medium (O)
  208803. #define SCSI_INITELSTAT 0x07 // Initialize Element Status (O)
  208804. #define SCSI_POSTOELEM 0x2B // Position to Element (O)
  208805. #define SCSI_REQ_VE_ADD 0xB5 // Request Volume Element Address (O)
  208806. #define SCSI_SENDVOLTAG 0xB6 // Send Volume Tag (O)
  208807. //***************************************************************************
  208808. // %%% Commands Unique to Communication Devices %%%
  208809. //***************************************************************************
  208810. #define SCSI_GET_MSG_6 0x08 // Get Message 6-Byte (MANDATORY)
  208811. #define SCSI_GET_MSG_10 0x28 // Get Message 10-Byte (O)
  208812. #define SCSI_GET_MSG_12 0xA8 // Get Message 12-Byte (O)
  208813. #define SCSI_SND_MSG_6 0x0A // Send Message 6-Byte (MANDATORY)
  208814. #define SCSI_SND_MSG_10 0x2A // Send Message 10-Byte (O)
  208815. #define SCSI_SND_MSG_12 0xAA // Send Message 12-Byte (O)
  208816. //***************************************************************************
  208817. // %%% Request Sense Data Format %%%
  208818. //***************************************************************************
  208819. typedef struct {
  208820. BYTE ErrorCode; // Error Code (70H or 71H)
  208821. BYTE SegmentNum; // Number of current segment descriptor
  208822. BYTE SenseKey; // Sense Key(See bit definitions too)
  208823. BYTE InfoByte0; // Information MSB
  208824. BYTE InfoByte1; // Information MID
  208825. BYTE InfoByte2; // Information MID
  208826. BYTE InfoByte3; // Information LSB
  208827. BYTE AddSenLen; // Additional Sense Length
  208828. BYTE ComSpecInf0; // Command Specific Information MSB
  208829. BYTE ComSpecInf1; // Command Specific Information MID
  208830. BYTE ComSpecInf2; // Command Specific Information MID
  208831. BYTE ComSpecInf3; // Command Specific Information LSB
  208832. BYTE AddSenseCode; // Additional Sense Code
  208833. BYTE AddSenQual; // Additional Sense Code Qualifier
  208834. BYTE FieldRepUCode; // Field Replaceable Unit Code
  208835. BYTE SenKeySpec15; // Sense Key Specific 15th byte
  208836. BYTE SenKeySpec16; // Sense Key Specific 16th byte
  208837. BYTE SenKeySpec17; // Sense Key Specific 17th byte
  208838. BYTE AddSenseBytes; // Additional Sense Bytes
  208839. } SENSE_DATA_FMT;
  208840. //***************************************************************************
  208841. // %%% REQUEST SENSE ERROR CODE %%%
  208842. //***************************************************************************
  208843. #define SERROR_CURRENT 0x70 // Current Errors
  208844. #define SERROR_DEFERED 0x71 // Deferred Errors
  208845. //***************************************************************************
  208846. // %%% REQUEST SENSE BIT DEFINITIONS %%%
  208847. //***************************************************************************
  208848. #define SENSE_VALID 0x80 // Byte 0 Bit 7
  208849. #define SENSE_FILEMRK 0x80 // Byte 2 Bit 7
  208850. #define SENSE_EOM 0x40 // Byte 2 Bit 6
  208851. #define SENSE_ILI 0x20 // Byte 2 Bit 5
  208852. //***************************************************************************
  208853. // %%% REQUEST SENSE SENSE KEY DEFINITIONS %%%
  208854. //***************************************************************************
  208855. #define KEY_NOSENSE 0x00 // No Sense
  208856. #define KEY_RECERROR 0x01 // Recovered Error
  208857. #define KEY_NOTREADY 0x02 // Not Ready
  208858. #define KEY_MEDIUMERR 0x03 // Medium Error
  208859. #define KEY_HARDERROR 0x04 // Hardware Error
  208860. #define KEY_ILLGLREQ 0x05 // Illegal Request
  208861. #define KEY_UNITATT 0x06 // Unit Attention
  208862. #define KEY_DATAPROT 0x07 // Data Protect
  208863. #define KEY_BLANKCHK 0x08 // Blank Check
  208864. #define KEY_VENDSPEC 0x09 // Vendor Specific
  208865. #define KEY_COPYABORT 0x0A // Copy Abort
  208866. #define KEY_EQUAL 0x0C // Equal (Search)
  208867. #define KEY_VOLOVRFLW 0x0D // Volume Overflow
  208868. #define KEY_MISCOMP 0x0E // Miscompare (Search)
  208869. #define KEY_RESERVED 0x0F // Reserved
  208870. //***************************************************************************
  208871. // %%% PERIPHERAL DEVICE TYPE DEFINITIONS %%%
  208872. //***************************************************************************
  208873. #define DTYPE_DASD 0x00 // Disk Device
  208874. #define DTYPE_SEQD 0x01 // Tape Device
  208875. #define DTYPE_PRNT 0x02 // Printer
  208876. #define DTYPE_PROC 0x03 // Processor
  208877. #define DTYPE_WORM 0x04 // Write-once read-multiple
  208878. #define DTYPE_CROM 0x05 // CD-ROM device
  208879. #define DTYPE_SCAN 0x06 // Scanner device
  208880. #define DTYPE_OPTI 0x07 // Optical memory device
  208881. #define DTYPE_JUKE 0x08 // Medium Changer device
  208882. #define DTYPE_COMM 0x09 // Communications device
  208883. #define DTYPE_RESL 0x0A // Reserved (low)
  208884. #define DTYPE_RESH 0x1E // Reserved (high)
  208885. #define DTYPE_UNKNOWN 0x1F // Unknown or no device type
  208886. //***************************************************************************
  208887. // %%% ANSI APPROVED VERSION DEFINITIONS %%%
  208888. //***************************************************************************
  208889. #define ANSI_MAYBE 0x0 // Device may or may not be ANSI approved stand
  208890. #define ANSI_SCSI1 0x1 // Device complies to ANSI X3.131-1986 (SCSI-1)
  208891. #define ANSI_SCSI2 0x2 // Device complies to SCSI-2
  208892. #define ANSI_RESLO 0x3 // Reserved (low)
  208893. #define ANSI_RESHI 0x7 // Reserved (high)
  208894. typedef struct
  208895. {
  208896. USHORT Length;
  208897. UCHAR ScsiStatus;
  208898. UCHAR PathId;
  208899. UCHAR TargetId;
  208900. UCHAR Lun;
  208901. UCHAR CdbLength;
  208902. UCHAR SenseInfoLength;
  208903. UCHAR DataIn;
  208904. ULONG DataTransferLength;
  208905. ULONG TimeOutValue;
  208906. ULONG DataBufferOffset;
  208907. ULONG SenseInfoOffset;
  208908. UCHAR Cdb[16];
  208909. } SCSI_PASS_THROUGH, *PSCSI_PASS_THROUGH;
  208910. typedef struct
  208911. {
  208912. USHORT Length;
  208913. UCHAR ScsiStatus;
  208914. UCHAR PathId;
  208915. UCHAR TargetId;
  208916. UCHAR Lun;
  208917. UCHAR CdbLength;
  208918. UCHAR SenseInfoLength;
  208919. UCHAR DataIn;
  208920. ULONG DataTransferLength;
  208921. ULONG TimeOutValue;
  208922. PVOID DataBuffer;
  208923. ULONG SenseInfoOffset;
  208924. UCHAR Cdb[16];
  208925. } SCSI_PASS_THROUGH_DIRECT, *PSCSI_PASS_THROUGH_DIRECT;
  208926. typedef struct
  208927. {
  208928. SCSI_PASS_THROUGH_DIRECT spt;
  208929. ULONG Filler;
  208930. UCHAR ucSenseBuf[32];
  208931. } SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, *PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER;
  208932. typedef struct
  208933. {
  208934. ULONG Length;
  208935. UCHAR PortNumber;
  208936. UCHAR PathId;
  208937. UCHAR TargetId;
  208938. UCHAR Lun;
  208939. } SCSI_ADDRESS, *PSCSI_ADDRESS;
  208940. #define METHOD_BUFFERED 0
  208941. #define METHOD_IN_DIRECT 1
  208942. #define METHOD_OUT_DIRECT 2
  208943. #define METHOD_NEITHER 3
  208944. #define FILE_ANY_ACCESS 0
  208945. #ifndef FILE_READ_ACCESS
  208946. #define FILE_READ_ACCESS (0x0001)
  208947. #endif
  208948. #ifndef FILE_WRITE_ACCESS
  208949. #define FILE_WRITE_ACCESS (0x0002)
  208950. #endif
  208951. #define IOCTL_SCSI_BASE 0x00000004
  208952. #define SCSI_IOCTL_DATA_OUT 0
  208953. #define SCSI_IOCTL_DATA_IN 1
  208954. #define SCSI_IOCTL_DATA_UNSPECIFIED 2
  208955. #define CTL_CODE2( DevType, Function, Method, Access ) ( \
  208956. ((DevType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method) \
  208957. )
  208958. #define IOCTL_SCSI_PASS_THROUGH CTL_CODE2( IOCTL_SCSI_BASE, 0x0401, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  208959. #define IOCTL_SCSI_GET_CAPABILITIES CTL_CODE2( IOCTL_SCSI_BASE, 0x0404, METHOD_BUFFERED, FILE_ANY_ACCESS)
  208960. #define IOCTL_SCSI_PASS_THROUGH_DIRECT CTL_CODE2( IOCTL_SCSI_BASE, 0x0405, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  208961. #define IOCTL_SCSI_GET_ADDRESS CTL_CODE2( IOCTL_SCSI_BASE, 0x0406, METHOD_BUFFERED, FILE_ANY_ACCESS )
  208962. #define SENSE_LEN 14
  208963. #define SRB_DIR_SCSI 0x00
  208964. #define SRB_POSTING 0x01
  208965. #define SRB_ENABLE_RESIDUAL_COUNT 0x04
  208966. #define SRB_DIR_IN 0x08
  208967. #define SRB_DIR_OUT 0x10
  208968. #define SRB_EVENT_NOTIFY 0x40
  208969. #define RESIDUAL_COUNT_SUPPORTED 0x02
  208970. #define MAX_SRB_TIMEOUT 1080001u
  208971. #define DEFAULT_SRB_TIMEOUT 1080001u
  208972. #define SC_HA_INQUIRY 0x00
  208973. #define SC_GET_DEV_TYPE 0x01
  208974. #define SC_EXEC_SCSI_CMD 0x02
  208975. #define SC_ABORT_SRB 0x03
  208976. #define SC_RESET_DEV 0x04
  208977. #define SC_SET_HA_PARMS 0x05
  208978. #define SC_GET_DISK_INFO 0x06
  208979. #define SC_RESCAN_SCSI_BUS 0x07
  208980. #define SC_GETSET_TIMEOUTS 0x08
  208981. #define SS_PENDING 0x00
  208982. #define SS_COMP 0x01
  208983. #define SS_ABORTED 0x02
  208984. #define SS_ABORT_FAIL 0x03
  208985. #define SS_ERR 0x04
  208986. #define SS_INVALID_CMD 0x80
  208987. #define SS_INVALID_HA 0x81
  208988. #define SS_NO_DEVICE 0x82
  208989. #define SS_INVALID_SRB 0xE0
  208990. #define SS_OLD_MANAGER 0xE1
  208991. #define SS_BUFFER_ALIGN 0xE1
  208992. #define SS_ILLEGAL_MODE 0xE2
  208993. #define SS_NO_ASPI 0xE3
  208994. #define SS_FAILED_INIT 0xE4
  208995. #define SS_ASPI_IS_BUSY 0xE5
  208996. #define SS_BUFFER_TO_BIG 0xE6
  208997. #define SS_BUFFER_TOO_BIG 0xE6
  208998. #define SS_MISMATCHED_COMPONENTS 0xE7
  208999. #define SS_NO_ADAPTERS 0xE8
  209000. #define SS_INSUFFICIENT_RESOURCES 0xE9
  209001. #define SS_ASPI_IS_SHUTDOWN 0xEA
  209002. #define SS_BAD_INSTALL 0xEB
  209003. #define HASTAT_OK 0x00
  209004. #define HASTAT_SEL_TO 0x11
  209005. #define HASTAT_DO_DU 0x12
  209006. #define HASTAT_BUS_FREE 0x13
  209007. #define HASTAT_PHASE_ERR 0x14
  209008. #define HASTAT_TIMEOUT 0x09
  209009. #define HASTAT_COMMAND_TIMEOUT 0x0B
  209010. #define HASTAT_MESSAGE_REJECT 0x0D
  209011. #define HASTAT_BUS_RESET 0x0E
  209012. #define HASTAT_PARITY_ERROR 0x0F
  209013. #define HASTAT_REQUEST_SENSE_FAILED 0x10
  209014. #define PACKED
  209015. #pragma pack(1)
  209016. typedef struct
  209017. {
  209018. BYTE SRB_Cmd;
  209019. BYTE SRB_Status;
  209020. BYTE SRB_HaID;
  209021. BYTE SRB_Flags;
  209022. DWORD SRB_Hdr_Rsvd;
  209023. BYTE HA_Count;
  209024. BYTE HA_SCSI_ID;
  209025. BYTE HA_ManagerId[16];
  209026. BYTE HA_Identifier[16];
  209027. BYTE HA_Unique[16];
  209028. WORD HA_Rsvd1;
  209029. BYTE pad[20];
  209030. } PACKED SRB_HAInquiry, *PSRB_HAInquiry, FAR *LPSRB_HAInquiry;
  209031. typedef struct
  209032. {
  209033. BYTE SRB_Cmd;
  209034. BYTE SRB_Status;
  209035. BYTE SRB_HaID;
  209036. BYTE SRB_Flags;
  209037. DWORD SRB_Hdr_Rsvd;
  209038. BYTE SRB_Target;
  209039. BYTE SRB_Lun;
  209040. BYTE SRB_DeviceType;
  209041. BYTE SRB_Rsvd1;
  209042. BYTE pad[68];
  209043. } PACKED SRB_GDEVBlock, *PSRB_GDEVBlock, FAR *LPSRB_GDEVBlock;
  209044. typedef struct
  209045. {
  209046. BYTE SRB_Cmd;
  209047. BYTE SRB_Status;
  209048. BYTE SRB_HaID;
  209049. BYTE SRB_Flags;
  209050. DWORD SRB_Hdr_Rsvd;
  209051. BYTE SRB_Target;
  209052. BYTE SRB_Lun;
  209053. WORD SRB_Rsvd1;
  209054. DWORD SRB_BufLen;
  209055. BYTE FAR *SRB_BufPointer;
  209056. BYTE SRB_SenseLen;
  209057. BYTE SRB_CDBLen;
  209058. BYTE SRB_HaStat;
  209059. BYTE SRB_TargStat;
  209060. VOID FAR *SRB_PostProc;
  209061. BYTE SRB_Rsvd2[20];
  209062. BYTE CDBByte[16];
  209063. BYTE SenseArea[SENSE_LEN+2];
  209064. } PACKED SRB_ExecSCSICmd, *PSRB_ExecSCSICmd, FAR *LPSRB_ExecSCSICmd;
  209065. typedef struct
  209066. {
  209067. BYTE SRB_Cmd;
  209068. BYTE SRB_Status;
  209069. BYTE SRB_HaId;
  209070. BYTE SRB_Flags;
  209071. DWORD SRB_Hdr_Rsvd;
  209072. } PACKED SRB, *PSRB, FAR *LPSRB;
  209073. #pragma pack()
  209074. struct CDDeviceInfo
  209075. {
  209076. char vendor[9];
  209077. char productId[17];
  209078. char rev[5];
  209079. char vendorSpec[21];
  209080. BYTE ha;
  209081. BYTE tgt;
  209082. BYTE lun;
  209083. char scsiDriveLetter; // will be 0 if not using scsi
  209084. };
  209085. class CDReadBuffer
  209086. {
  209087. public:
  209088. int startFrame;
  209089. int numFrames;
  209090. int dataStartOffset;
  209091. int dataLength;
  209092. int bufferSize;
  209093. HeapBlock<BYTE> buffer;
  209094. int index;
  209095. bool wantsIndex;
  209096. CDReadBuffer (const int numberOfFrames)
  209097. : startFrame (0),
  209098. numFrames (0),
  209099. dataStartOffset (0),
  209100. dataLength (0),
  209101. bufferSize (2352 * numberOfFrames),
  209102. buffer (bufferSize),
  209103. index (0),
  209104. wantsIndex (false)
  209105. {
  209106. }
  209107. bool isZero() const throw()
  209108. {
  209109. BYTE* p = buffer + dataStartOffset;
  209110. for (int i = dataLength; --i >= 0;)
  209111. if (*p++ != 0)
  209112. return false;
  209113. return true;
  209114. }
  209115. };
  209116. class CDDeviceHandle;
  209117. class CDController
  209118. {
  209119. public:
  209120. CDController();
  209121. virtual ~CDController();
  209122. virtual bool read (CDReadBuffer* t) = 0;
  209123. virtual void shutDown();
  209124. bool readAudio (CDReadBuffer* t, CDReadBuffer* overlapBuffer = 0);
  209125. int getLastIndex();
  209126. public:
  209127. bool initialised;
  209128. CDDeviceHandle* deviceInfo;
  209129. int framesToCheck, framesOverlap;
  209130. void prepare (SRB_ExecSCSICmd& s);
  209131. void perform (SRB_ExecSCSICmd& s);
  209132. void setPaused (bool paused);
  209133. };
  209134. #pragma pack(1)
  209135. struct TOCTRACK
  209136. {
  209137. BYTE rsvd;
  209138. BYTE ADR;
  209139. BYTE trackNumber;
  209140. BYTE rsvd2;
  209141. BYTE addr[4];
  209142. };
  209143. struct TOC
  209144. {
  209145. WORD tocLen;
  209146. BYTE firstTrack;
  209147. BYTE lastTrack;
  209148. TOCTRACK tracks[100];
  209149. };
  209150. #pragma pack()
  209151. enum
  209152. {
  209153. READTYPE_ANY = 0,
  209154. READTYPE_ATAPI1 = 1,
  209155. READTYPE_ATAPI2 = 2,
  209156. READTYPE_READ6 = 3,
  209157. READTYPE_READ10 = 4,
  209158. READTYPE_READ_D8 = 5,
  209159. READTYPE_READ_D4 = 6,
  209160. READTYPE_READ_D4_1 = 7,
  209161. READTYPE_READ10_2 = 8
  209162. };
  209163. class CDDeviceHandle
  209164. {
  209165. public:
  209166. CDDeviceHandle (const CDDeviceInfo* const device)
  209167. : scsiHandle (0),
  209168. readType (READTYPE_ANY),
  209169. controller (0)
  209170. {
  209171. memcpy (&info, device, sizeof (info));
  209172. }
  209173. ~CDDeviceHandle()
  209174. {
  209175. if (controller != 0)
  209176. {
  209177. controller->shutDown();
  209178. controller = 0;
  209179. }
  209180. if (scsiHandle != 0)
  209181. CloseHandle (scsiHandle);
  209182. }
  209183. bool readTOC (TOC* lpToc, bool useMSF);
  209184. bool readAudio (CDReadBuffer* buffer, CDReadBuffer* overlapBuffer = 0);
  209185. void openDrawer (bool shouldBeOpen);
  209186. CDDeviceInfo info;
  209187. HANDLE scsiHandle;
  209188. BYTE readType;
  209189. private:
  209190. ScopedPointer<CDController> controller;
  209191. bool testController (const int readType,
  209192. CDController* const newController,
  209193. CDReadBuffer* const bufferToUse);
  209194. };
  209195. DWORD (*fGetASPI32SupportInfo)(void);
  209196. DWORD (*fSendASPI32Command)(LPSRB);
  209197. static HINSTANCE winAspiLib = 0;
  209198. static bool usingScsi = false;
  209199. static bool initialised = false;
  209200. static bool InitialiseCDRipper()
  209201. {
  209202. if (! initialised)
  209203. {
  209204. initialised = true;
  209205. OSVERSIONINFO info;
  209206. info.dwOSVersionInfoSize = sizeof (info);
  209207. GetVersionEx (&info);
  209208. usingScsi = (info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4);
  209209. if (! usingScsi)
  209210. {
  209211. fGetASPI32SupportInfo = 0;
  209212. fSendASPI32Command = 0;
  209213. winAspiLib = LoadLibrary (_T("WNASPI32.DLL"));
  209214. if (winAspiLib != 0)
  209215. {
  209216. fGetASPI32SupportInfo = (DWORD(*)(void)) GetProcAddress (winAspiLib, "GetASPI32SupportInfo");
  209217. fSendASPI32Command = (DWORD(*)(LPSRB)) GetProcAddress (winAspiLib, "SendASPI32Command");
  209218. if (fGetASPI32SupportInfo == 0 || fSendASPI32Command == 0)
  209219. return false;
  209220. }
  209221. else
  209222. {
  209223. usingScsi = true;
  209224. }
  209225. }
  209226. }
  209227. return true;
  209228. }
  209229. static void DeinitialiseCDRipper()
  209230. {
  209231. if (winAspiLib != 0)
  209232. {
  209233. fGetASPI32SupportInfo = 0;
  209234. fSendASPI32Command = 0;
  209235. FreeLibrary (winAspiLib);
  209236. winAspiLib = 0;
  209237. }
  209238. initialised = false;
  209239. }
  209240. static HANDLE CreateSCSIDeviceHandle (char driveLetter)
  209241. {
  209242. TCHAR devicePath[] = { '\\', '\\', '.', '\\', driveLetter, ':', 0, 0 };
  209243. OSVERSIONINFO info;
  209244. info.dwOSVersionInfoSize = sizeof (info);
  209245. GetVersionEx (&info);
  209246. DWORD flags = GENERIC_READ;
  209247. if ((info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4))
  209248. flags = GENERIC_READ | GENERIC_WRITE;
  209249. HANDLE h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  209250. if (h == INVALID_HANDLE_VALUE)
  209251. {
  209252. flags ^= GENERIC_WRITE;
  209253. h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  209254. }
  209255. return h;
  209256. }
  209257. static DWORD performScsiPassThroughCommand (const LPSRB_ExecSCSICmd srb,
  209258. const char driveLetter,
  209259. HANDLE& deviceHandle,
  209260. const bool retryOnFailure = true)
  209261. {
  209262. SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER s;
  209263. zerostruct (s);
  209264. s.spt.Length = sizeof (SCSI_PASS_THROUGH);
  209265. s.spt.CdbLength = srb->SRB_CDBLen;
  209266. s.spt.DataIn = (BYTE) ((srb->SRB_Flags & SRB_DIR_IN)
  209267. ? SCSI_IOCTL_DATA_IN
  209268. : ((srb->SRB_Flags & SRB_DIR_OUT)
  209269. ? SCSI_IOCTL_DATA_OUT
  209270. : SCSI_IOCTL_DATA_UNSPECIFIED));
  209271. s.spt.DataTransferLength = srb->SRB_BufLen;
  209272. s.spt.TimeOutValue = 5;
  209273. s.spt.DataBuffer = srb->SRB_BufPointer;
  209274. s.spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  209275. memcpy (s.spt.Cdb, srb->CDBByte, srb->SRB_CDBLen);
  209276. srb->SRB_Status = SS_ERR;
  209277. srb->SRB_TargStat = 0x0004;
  209278. DWORD bytesReturned = 0;
  209279. if (DeviceIoControl (deviceHandle, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  209280. &s, sizeof (s),
  209281. &s, sizeof (s),
  209282. &bytesReturned, 0) != 0)
  209283. {
  209284. srb->SRB_Status = SS_COMP;
  209285. }
  209286. else if (retryOnFailure)
  209287. {
  209288. const DWORD error = GetLastError();
  209289. if ((error == ERROR_MEDIA_CHANGED) || (error == ERROR_INVALID_HANDLE))
  209290. {
  209291. if (error != ERROR_INVALID_HANDLE)
  209292. CloseHandle (deviceHandle);
  209293. deviceHandle = CreateSCSIDeviceHandle (driveLetter);
  209294. return performScsiPassThroughCommand (srb, driveLetter, deviceHandle, false);
  209295. }
  209296. }
  209297. return srb->SRB_Status;
  209298. }
  209299. // Controller types..
  209300. class ControllerType1 : public CDController
  209301. {
  209302. public:
  209303. ControllerType1() {}
  209304. ~ControllerType1() {}
  209305. bool read (CDReadBuffer* rb)
  209306. {
  209307. if (rb->numFrames * 2352 > rb->bufferSize)
  209308. return false;
  209309. SRB_ExecSCSICmd s;
  209310. prepare (s);
  209311. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  209312. s.SRB_BufLen = rb->bufferSize;
  209313. s.SRB_BufPointer = rb->buffer;
  209314. s.SRB_CDBLen = 12;
  209315. s.CDBByte[0] = 0xBE;
  209316. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  209317. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  209318. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  209319. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  209320. s.CDBByte[9] = (BYTE)((deviceInfo->readType == READTYPE_ATAPI1) ? 0x10 : 0xF0);
  209321. perform (s);
  209322. if (s.SRB_Status != SS_COMP)
  209323. return false;
  209324. rb->dataLength = rb->numFrames * 2352;
  209325. rb->dataStartOffset = 0;
  209326. return true;
  209327. }
  209328. };
  209329. class ControllerType2 : public CDController
  209330. {
  209331. public:
  209332. ControllerType2() {}
  209333. ~ControllerType2() {}
  209334. void shutDown()
  209335. {
  209336. if (initialised)
  209337. {
  209338. BYTE bufPointer[] = { 0, 0, 0, 8, 83, 0, 0, 0, 0, 0, 8, 0 };
  209339. SRB_ExecSCSICmd s;
  209340. prepare (s);
  209341. s.SRB_Flags = SRB_EVENT_NOTIFY | SRB_ENABLE_RESIDUAL_COUNT;
  209342. s.SRB_BufLen = 0x0C;
  209343. s.SRB_BufPointer = bufPointer;
  209344. s.SRB_CDBLen = 6;
  209345. s.CDBByte[0] = 0x15;
  209346. s.CDBByte[4] = 0x0C;
  209347. perform (s);
  209348. }
  209349. }
  209350. bool init()
  209351. {
  209352. SRB_ExecSCSICmd s;
  209353. s.SRB_Status = SS_ERR;
  209354. if (deviceInfo->readType == READTYPE_READ10_2)
  209355. {
  209356. BYTE bufPointer1[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 35, 6, 0, 0, 0, 0, 0, 128 };
  209357. BYTE bufPointer2[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 1, 6, 32, 7, 0, 0, 0, 0 };
  209358. for (int i = 0; i < 2; ++i)
  209359. {
  209360. prepare (s);
  209361. s.SRB_Flags = SRB_EVENT_NOTIFY;
  209362. s.SRB_BufLen = 0x14;
  209363. s.SRB_BufPointer = (i == 0) ? bufPointer1 : bufPointer2;
  209364. s.SRB_CDBLen = 6;
  209365. s.CDBByte[0] = 0x15;
  209366. s.CDBByte[1] = 0x10;
  209367. s.CDBByte[4] = 0x14;
  209368. perform (s);
  209369. if (s.SRB_Status != SS_COMP)
  209370. return false;
  209371. }
  209372. }
  209373. else
  209374. {
  209375. BYTE bufPointer[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48 };
  209376. prepare (s);
  209377. s.SRB_Flags = SRB_EVENT_NOTIFY;
  209378. s.SRB_BufLen = 0x0C;
  209379. s.SRB_BufPointer = bufPointer;
  209380. s.SRB_CDBLen = 6;
  209381. s.CDBByte[0] = 0x15;
  209382. s.CDBByte[4] = 0x0C;
  209383. perform (s);
  209384. }
  209385. return s.SRB_Status == SS_COMP;
  209386. }
  209387. bool read (CDReadBuffer* rb)
  209388. {
  209389. if (rb->numFrames * 2352 > rb->bufferSize)
  209390. return false;
  209391. if (!initialised)
  209392. {
  209393. initialised = init();
  209394. if (!initialised)
  209395. return false;
  209396. }
  209397. SRB_ExecSCSICmd s;
  209398. prepare (s);
  209399. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  209400. s.SRB_BufLen = rb->bufferSize;
  209401. s.SRB_BufPointer = rb->buffer;
  209402. s.SRB_CDBLen = 10;
  209403. s.CDBByte[0] = 0x28;
  209404. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  209405. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  209406. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  209407. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  209408. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  209409. perform (s);
  209410. if (s.SRB_Status != SS_COMP)
  209411. return false;
  209412. rb->dataLength = rb->numFrames * 2352;
  209413. rb->dataStartOffset = 0;
  209414. return true;
  209415. }
  209416. };
  209417. class ControllerType3 : public CDController
  209418. {
  209419. public:
  209420. ControllerType3() {}
  209421. ~ControllerType3() {}
  209422. bool read (CDReadBuffer* rb)
  209423. {
  209424. if (rb->numFrames * 2352 > rb->bufferSize)
  209425. return false;
  209426. if (!initialised)
  209427. {
  209428. setPaused (false);
  209429. initialised = true;
  209430. }
  209431. SRB_ExecSCSICmd s;
  209432. prepare (s);
  209433. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  209434. s.SRB_BufLen = rb->numFrames * 2352;
  209435. s.SRB_BufPointer = rb->buffer;
  209436. s.SRB_CDBLen = 12;
  209437. s.CDBByte[0] = 0xD8;
  209438. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  209439. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  209440. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  209441. s.CDBByte[9] = (BYTE)(rb->numFrames & 0xFF);
  209442. perform (s);
  209443. if (s.SRB_Status != SS_COMP)
  209444. return false;
  209445. rb->dataLength = rb->numFrames * 2352;
  209446. rb->dataStartOffset = 0;
  209447. return true;
  209448. }
  209449. };
  209450. class ControllerType4 : public CDController
  209451. {
  209452. public:
  209453. ControllerType4() {}
  209454. ~ControllerType4() {}
  209455. bool selectD4Mode()
  209456. {
  209457. BYTE bufPointer[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 48 };
  209458. SRB_ExecSCSICmd s;
  209459. prepare (s);
  209460. s.SRB_Flags = SRB_EVENT_NOTIFY;
  209461. s.SRB_CDBLen = 6;
  209462. s.SRB_BufLen = 12;
  209463. s.SRB_BufPointer = bufPointer;
  209464. s.CDBByte[0] = 0x15;
  209465. s.CDBByte[1] = 0x10;
  209466. s.CDBByte[4] = 0x08;
  209467. perform (s);
  209468. return s.SRB_Status == SS_COMP;
  209469. }
  209470. bool read (CDReadBuffer* rb)
  209471. {
  209472. if (rb->numFrames * 2352 > rb->bufferSize)
  209473. return false;
  209474. if (!initialised)
  209475. {
  209476. setPaused (true);
  209477. if (deviceInfo->readType == READTYPE_READ_D4_1)
  209478. selectD4Mode();
  209479. initialised = true;
  209480. }
  209481. SRB_ExecSCSICmd s;
  209482. prepare (s);
  209483. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  209484. s.SRB_BufLen = rb->bufferSize;
  209485. s.SRB_BufPointer = rb->buffer;
  209486. s.SRB_CDBLen = 10;
  209487. s.CDBByte[0] = 0xD4;
  209488. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  209489. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  209490. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  209491. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  209492. perform (s);
  209493. if (s.SRB_Status != SS_COMP)
  209494. return false;
  209495. rb->dataLength = rb->numFrames * 2352;
  209496. rb->dataStartOffset = 0;
  209497. return true;
  209498. }
  209499. };
  209500. CDController::CDController() : initialised (false)
  209501. {
  209502. }
  209503. CDController::~CDController()
  209504. {
  209505. }
  209506. void CDController::prepare (SRB_ExecSCSICmd& s)
  209507. {
  209508. zerostruct (s);
  209509. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  209510. s.SRB_HaID = deviceInfo->info.ha;
  209511. s.SRB_Target = deviceInfo->info.tgt;
  209512. s.SRB_Lun = deviceInfo->info.lun;
  209513. s.SRB_SenseLen = SENSE_LEN;
  209514. }
  209515. void CDController::perform (SRB_ExecSCSICmd& s)
  209516. {
  209517. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  209518. s.SRB_PostProc = event;
  209519. ResetEvent (event);
  209520. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s,
  209521. deviceInfo->info.scsiDriveLetter,
  209522. deviceInfo->scsiHandle)
  209523. : fSendASPI32Command ((LPSRB)&s);
  209524. if (status == SS_PENDING)
  209525. WaitForSingleObject (event, 4000);
  209526. CloseHandle (event);
  209527. }
  209528. void CDController::setPaused (bool paused)
  209529. {
  209530. SRB_ExecSCSICmd s;
  209531. prepare (s);
  209532. s.SRB_Flags = SRB_EVENT_NOTIFY;
  209533. s.SRB_CDBLen = 10;
  209534. s.CDBByte[0] = 0x4B;
  209535. s.CDBByte[8] = (BYTE) (paused ? 0 : 1);
  209536. perform (s);
  209537. }
  209538. void CDController::shutDown()
  209539. {
  209540. }
  209541. bool CDController::readAudio (CDReadBuffer* rb, CDReadBuffer* overlapBuffer)
  209542. {
  209543. if (overlapBuffer != 0)
  209544. {
  209545. const bool canDoJitter = (overlapBuffer->bufferSize >= 2352 * framesToCheck);
  209546. const bool doJitter = canDoJitter && ! overlapBuffer->isZero();
  209547. if (doJitter
  209548. && overlapBuffer->startFrame > 0
  209549. && overlapBuffer->numFrames > 0
  209550. && overlapBuffer->dataLength > 0)
  209551. {
  209552. const int numFrames = rb->numFrames;
  209553. if (overlapBuffer->startFrame == (rb->startFrame - framesToCheck))
  209554. {
  209555. rb->startFrame -= framesOverlap;
  209556. if (framesToCheck < framesOverlap
  209557. && numFrames + framesOverlap <= rb->bufferSize / 2352)
  209558. rb->numFrames += framesOverlap;
  209559. }
  209560. else
  209561. {
  209562. overlapBuffer->dataLength = 0;
  209563. overlapBuffer->startFrame = 0;
  209564. overlapBuffer->numFrames = 0;
  209565. }
  209566. }
  209567. if (! read (rb))
  209568. return false;
  209569. if (doJitter)
  209570. {
  209571. const int checkLen = framesToCheck * 2352;
  209572. const int maxToCheck = rb->dataLength - checkLen;
  209573. if (overlapBuffer->dataLength == 0 || overlapBuffer->isZero())
  209574. return true;
  209575. BYTE* const p = overlapBuffer->buffer + overlapBuffer->dataStartOffset;
  209576. bool found = false;
  209577. for (int i = 0; i < maxToCheck; ++i)
  209578. {
  209579. if (memcmp (p, rb->buffer + i, checkLen) == 0)
  209580. {
  209581. i += checkLen;
  209582. rb->dataStartOffset = i;
  209583. rb->dataLength -= i;
  209584. rb->startFrame = overlapBuffer->startFrame + framesToCheck;
  209585. found = true;
  209586. break;
  209587. }
  209588. }
  209589. rb->numFrames = rb->dataLength / 2352;
  209590. rb->dataLength = 2352 * rb->numFrames;
  209591. if (!found)
  209592. return false;
  209593. }
  209594. if (canDoJitter)
  209595. {
  209596. memcpy (overlapBuffer->buffer,
  209597. rb->buffer + rb->dataStartOffset + 2352 * (rb->numFrames - framesToCheck),
  209598. 2352 * framesToCheck);
  209599. overlapBuffer->startFrame = rb->startFrame + rb->numFrames - framesToCheck;
  209600. overlapBuffer->numFrames = framesToCheck;
  209601. overlapBuffer->dataLength = 2352 * framesToCheck;
  209602. overlapBuffer->dataStartOffset = 0;
  209603. }
  209604. else
  209605. {
  209606. overlapBuffer->startFrame = 0;
  209607. overlapBuffer->numFrames = 0;
  209608. overlapBuffer->dataLength = 0;
  209609. }
  209610. return true;
  209611. }
  209612. else
  209613. {
  209614. return read (rb);
  209615. }
  209616. }
  209617. int CDController::getLastIndex()
  209618. {
  209619. char qdata[100];
  209620. SRB_ExecSCSICmd s;
  209621. prepare (s);
  209622. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  209623. s.SRB_BufLen = sizeof (qdata);
  209624. s.SRB_BufPointer = (BYTE*)qdata;
  209625. s.SRB_CDBLen = 12;
  209626. s.CDBByte[0] = 0x42;
  209627. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  209628. s.CDBByte[2] = 64;
  209629. s.CDBByte[3] = 1; // get current position
  209630. s.CDBByte[7] = 0;
  209631. s.CDBByte[8] = (BYTE)sizeof (qdata);
  209632. perform (s);
  209633. if (s.SRB_Status == SS_COMP)
  209634. return qdata[7];
  209635. return 0;
  209636. }
  209637. bool CDDeviceHandle::readTOC (TOC* lpToc, bool useMSF)
  209638. {
  209639. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  209640. SRB_ExecSCSICmd s;
  209641. zerostruct (s);
  209642. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  209643. s.SRB_HaID = info.ha;
  209644. s.SRB_Target = info.tgt;
  209645. s.SRB_Lun = info.lun;
  209646. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  209647. s.SRB_BufLen = 0x324;
  209648. s.SRB_BufPointer = (BYTE*)lpToc;
  209649. s.SRB_SenseLen = 0x0E;
  209650. s.SRB_CDBLen = 0x0A;
  209651. s.SRB_PostProc = event;
  209652. s.CDBByte[0] = 0x43;
  209653. s.CDBByte[1] = (BYTE)(useMSF ? 0x02 : 0x00);
  209654. s.CDBByte[7] = 0x03;
  209655. s.CDBByte[8] = 0x24;
  209656. ResetEvent (event);
  209657. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  209658. : fSendASPI32Command ((LPSRB)&s);
  209659. if (status == SS_PENDING)
  209660. WaitForSingleObject (event, 4000);
  209661. CloseHandle (event);
  209662. return (s.SRB_Status == SS_COMP);
  209663. }
  209664. bool CDDeviceHandle::readAudio (CDReadBuffer* const buffer,
  209665. CDReadBuffer* const overlapBuffer)
  209666. {
  209667. if (controller == 0)
  209668. {
  209669. testController (READTYPE_ATAPI2, new ControllerType1(), buffer)
  209670. || testController (READTYPE_ATAPI1, new ControllerType1(), buffer)
  209671. || testController (READTYPE_READ10_2, new ControllerType2(), buffer)
  209672. || testController (READTYPE_READ10, new ControllerType2(), buffer)
  209673. || testController (READTYPE_READ_D8, new ControllerType3(), buffer)
  209674. || testController (READTYPE_READ_D4, new ControllerType4(), buffer)
  209675. || testController (READTYPE_READ_D4_1, new ControllerType4(), buffer);
  209676. }
  209677. buffer->index = 0;
  209678. if ((controller != 0)
  209679. && controller->readAudio (buffer, overlapBuffer))
  209680. {
  209681. if (buffer->wantsIndex)
  209682. buffer->index = controller->getLastIndex();
  209683. return true;
  209684. }
  209685. return false;
  209686. }
  209687. void CDDeviceHandle::openDrawer (bool shouldBeOpen)
  209688. {
  209689. if (shouldBeOpen)
  209690. {
  209691. if (controller != 0)
  209692. {
  209693. controller->shutDown();
  209694. controller = 0;
  209695. }
  209696. if (scsiHandle != 0)
  209697. {
  209698. CloseHandle (scsiHandle);
  209699. scsiHandle = 0;
  209700. }
  209701. }
  209702. SRB_ExecSCSICmd s;
  209703. zerostruct (s);
  209704. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  209705. s.SRB_HaID = info.ha;
  209706. s.SRB_Target = info.tgt;
  209707. s.SRB_Lun = info.lun;
  209708. s.SRB_SenseLen = SENSE_LEN;
  209709. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  209710. s.SRB_BufLen = 0;
  209711. s.SRB_BufPointer = 0;
  209712. s.SRB_CDBLen = 12;
  209713. s.CDBByte[0] = 0x1b;
  209714. s.CDBByte[1] = (BYTE)(info.lun << 5);
  209715. s.CDBByte[4] = (BYTE)((shouldBeOpen) ? 2 : 3);
  209716. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  209717. s.SRB_PostProc = event;
  209718. ResetEvent (event);
  209719. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  209720. : fSendASPI32Command ((LPSRB)&s);
  209721. if (status == SS_PENDING)
  209722. WaitForSingleObject (event, 4000);
  209723. CloseHandle (event);
  209724. }
  209725. bool CDDeviceHandle::testController (const int type,
  209726. CDController* const newController,
  209727. CDReadBuffer* const rb)
  209728. {
  209729. controller = newController;
  209730. readType = (BYTE)type;
  209731. controller->deviceInfo = this;
  209732. controller->framesToCheck = 1;
  209733. controller->framesOverlap = 3;
  209734. bool passed = false;
  209735. memset (rb->buffer, 0xcd, rb->bufferSize);
  209736. if (controller->read (rb))
  209737. {
  209738. passed = true;
  209739. int* p = (int*) (rb->buffer + rb->dataStartOffset);
  209740. int wrong = 0;
  209741. for (int i = rb->dataLength / 4; --i >= 0;)
  209742. {
  209743. if (*p++ == (int) 0xcdcdcdcd)
  209744. {
  209745. if (++wrong == 4)
  209746. {
  209747. passed = false;
  209748. break;
  209749. }
  209750. }
  209751. else
  209752. {
  209753. wrong = 0;
  209754. }
  209755. }
  209756. }
  209757. if (! passed)
  209758. {
  209759. controller->shutDown();
  209760. controller = 0;
  209761. }
  209762. return passed;
  209763. }
  209764. static void GetAspiDeviceInfo (CDDeviceInfo* dev, BYTE ha, BYTE tgt, BYTE lun)
  209765. {
  209766. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  209767. const int bufSize = 128;
  209768. BYTE buffer[bufSize];
  209769. zeromem (buffer, bufSize);
  209770. SRB_ExecSCSICmd s;
  209771. zerostruct (s);
  209772. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  209773. s.SRB_HaID = ha;
  209774. s.SRB_Target = tgt;
  209775. s.SRB_Lun = lun;
  209776. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  209777. s.SRB_BufLen = bufSize;
  209778. s.SRB_BufPointer = buffer;
  209779. s.SRB_SenseLen = SENSE_LEN;
  209780. s.SRB_CDBLen = 6;
  209781. s.SRB_PostProc = event;
  209782. s.CDBByte[0] = SCSI_INQUIRY;
  209783. s.CDBByte[4] = 100;
  209784. ResetEvent (event);
  209785. if (fSendASPI32Command ((LPSRB)&s) == SS_PENDING)
  209786. WaitForSingleObject (event, 4000);
  209787. CloseHandle (event);
  209788. if (s.SRB_Status == SS_COMP)
  209789. {
  209790. memcpy (dev->vendor, &buffer[8], 8);
  209791. memcpy (dev->productId, &buffer[16], 16);
  209792. memcpy (dev->rev, &buffer[32], 4);
  209793. memcpy (dev->vendorSpec, &buffer[36], 20);
  209794. }
  209795. }
  209796. static int FindCDDevices (CDDeviceInfo* const list,
  209797. int maxItems)
  209798. {
  209799. int count = 0;
  209800. if (usingScsi)
  209801. {
  209802. for (char driveLetter = 'b'; driveLetter <= 'z'; ++driveLetter)
  209803. {
  209804. TCHAR drivePath[8];
  209805. drivePath[0] = driveLetter;
  209806. drivePath[1] = ':';
  209807. drivePath[2] = '\\';
  209808. drivePath[3] = 0;
  209809. if (GetDriveType (drivePath) == DRIVE_CDROM)
  209810. {
  209811. HANDLE h = CreateSCSIDeviceHandle (driveLetter);
  209812. if (h != INVALID_HANDLE_VALUE)
  209813. {
  209814. BYTE buffer[100], passThroughStruct[1024];
  209815. zeromem (buffer, sizeof (buffer));
  209816. zeromem (passThroughStruct, sizeof (passThroughStruct));
  209817. PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER p = (PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER)passThroughStruct;
  209818. p->spt.Length = sizeof (SCSI_PASS_THROUGH);
  209819. p->spt.CdbLength = 6;
  209820. p->spt.SenseInfoLength = 24;
  209821. p->spt.DataIn = SCSI_IOCTL_DATA_IN;
  209822. p->spt.DataTransferLength = 100;
  209823. p->spt.TimeOutValue = 2;
  209824. p->spt.DataBuffer = buffer;
  209825. p->spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  209826. p->spt.Cdb[0] = 0x12;
  209827. p->spt.Cdb[4] = 100;
  209828. DWORD bytesReturned = 0;
  209829. if (DeviceIoControl (h, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  209830. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  209831. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  209832. &bytesReturned, 0) != 0)
  209833. {
  209834. zeromem (&list[count], sizeof (CDDeviceInfo));
  209835. list[count].scsiDriveLetter = driveLetter;
  209836. memcpy (list[count].vendor, &buffer[8], 8);
  209837. memcpy (list[count].productId, &buffer[16], 16);
  209838. memcpy (list[count].rev, &buffer[32], 4);
  209839. memcpy (list[count].vendorSpec, &buffer[36], 20);
  209840. zeromem (passThroughStruct, sizeof (passThroughStruct));
  209841. PSCSI_ADDRESS scsiAddr = (PSCSI_ADDRESS)passThroughStruct;
  209842. scsiAddr->Length = sizeof (SCSI_ADDRESS);
  209843. if (DeviceIoControl (h, IOCTL_SCSI_GET_ADDRESS,
  209844. 0, 0, scsiAddr, sizeof (SCSI_ADDRESS),
  209845. &bytesReturned, 0) != 0)
  209846. {
  209847. list[count].ha = scsiAddr->PortNumber;
  209848. list[count].tgt = scsiAddr->TargetId;
  209849. list[count].lun = scsiAddr->Lun;
  209850. ++count;
  209851. }
  209852. }
  209853. CloseHandle (h);
  209854. }
  209855. }
  209856. }
  209857. }
  209858. else
  209859. {
  209860. const DWORD d = fGetASPI32SupportInfo();
  209861. BYTE status = HIBYTE (LOWORD (d));
  209862. if (status != SS_COMP || status == SS_NO_ADAPTERS)
  209863. return 0;
  209864. const int numAdapters = LOBYTE (LOWORD (d));
  209865. for (BYTE ha = 0; ha < numAdapters; ++ha)
  209866. {
  209867. SRB_HAInquiry s;
  209868. zerostruct (s);
  209869. s.SRB_Cmd = SC_HA_INQUIRY;
  209870. s.SRB_HaID = ha;
  209871. fSendASPI32Command ((LPSRB)&s);
  209872. if (s.SRB_Status == SS_COMP)
  209873. {
  209874. maxItems = (int)s.HA_Unique[3];
  209875. if (maxItems == 0)
  209876. maxItems = 8;
  209877. for (BYTE tgt = 0; tgt < maxItems; ++tgt)
  209878. {
  209879. for (BYTE lun = 0; lun < 8; ++lun)
  209880. {
  209881. SRB_GDEVBlock sb;
  209882. zerostruct (sb);
  209883. sb.SRB_Cmd = SC_GET_DEV_TYPE;
  209884. sb.SRB_HaID = ha;
  209885. sb.SRB_Target = tgt;
  209886. sb.SRB_Lun = lun;
  209887. fSendASPI32Command ((LPSRB) &sb);
  209888. if (sb.SRB_Status == SS_COMP
  209889. && sb.SRB_DeviceType == DTYPE_CROM)
  209890. {
  209891. zeromem (&list[count], sizeof (CDDeviceInfo));
  209892. list[count].ha = ha;
  209893. list[count].tgt = tgt;
  209894. list[count].lun = lun;
  209895. GetAspiDeviceInfo (&(list[count]), ha, tgt, lun);
  209896. ++count;
  209897. }
  209898. }
  209899. }
  209900. }
  209901. }
  209902. }
  209903. return count;
  209904. }
  209905. static int ripperUsers = 0;
  209906. static bool initialisedOk = false;
  209907. class DeinitialiseTimer : private Timer,
  209908. private DeletedAtShutdown
  209909. {
  209910. DeinitialiseTimer (const DeinitialiseTimer&);
  209911. DeinitialiseTimer& operator= (const DeinitialiseTimer&);
  209912. public:
  209913. DeinitialiseTimer()
  209914. {
  209915. startTimer (4000);
  209916. }
  209917. ~DeinitialiseTimer()
  209918. {
  209919. if (--ripperUsers == 0)
  209920. DeinitialiseCDRipper();
  209921. }
  209922. void timerCallback()
  209923. {
  209924. delete this;
  209925. }
  209926. juce_UseDebuggingNewOperator
  209927. };
  209928. static void incUserCount()
  209929. {
  209930. if (ripperUsers++ == 0)
  209931. initialisedOk = InitialiseCDRipper();
  209932. }
  209933. static void decUserCount()
  209934. {
  209935. new DeinitialiseTimer();
  209936. }
  209937. struct CDDeviceWrapper
  209938. {
  209939. ScopedPointer<CDDeviceHandle> cdH;
  209940. ScopedPointer<CDReadBuffer> overlapBuffer;
  209941. bool jitter;
  209942. };
  209943. static int getAddressOf (const TOCTRACK* const t)
  209944. {
  209945. return (((DWORD)t->addr[0]) << 24) + (((DWORD)t->addr[1]) << 16) +
  209946. (((DWORD)t->addr[2]) << 8) + ((DWORD)t->addr[3]);
  209947. }
  209948. static int getMSFAddressOf (const TOCTRACK* const t)
  209949. {
  209950. return 60 * t->addr[1] + t->addr[2];
  209951. }
  209952. static const int samplesPerFrame = 44100 / 75;
  209953. static const int bytesPerFrame = samplesPerFrame * 4;
  209954. static CDDeviceHandle* openHandle (const CDDeviceInfo* const device)
  209955. {
  209956. SRB_GDEVBlock s;
  209957. zerostruct (s);
  209958. s.SRB_Cmd = SC_GET_DEV_TYPE;
  209959. s.SRB_HaID = device->ha;
  209960. s.SRB_Target = device->tgt;
  209961. s.SRB_Lun = device->lun;
  209962. if (usingScsi)
  209963. {
  209964. HANDLE h = CreateSCSIDeviceHandle (device->scsiDriveLetter);
  209965. if (h != INVALID_HANDLE_VALUE)
  209966. {
  209967. CDDeviceHandle* cdh = new CDDeviceHandle (device);
  209968. cdh->scsiHandle = h;
  209969. return cdh;
  209970. }
  209971. }
  209972. else
  209973. {
  209974. if (fSendASPI32Command ((LPSRB)&s) == SS_COMP
  209975. && s.SRB_DeviceType == DTYPE_CROM)
  209976. {
  209977. return new CDDeviceHandle (device);
  209978. }
  209979. }
  209980. return 0;
  209981. }
  209982. }
  209983. const StringArray AudioCDReader::getAvailableCDNames()
  209984. {
  209985. using namespace CDReaderHelpers;
  209986. StringArray results;
  209987. incUserCount();
  209988. if (initialisedOk)
  209989. {
  209990. CDDeviceInfo list[8];
  209991. const int num = FindCDDevices (list, 8);
  209992. decUserCount();
  209993. for (int i = 0; i < num; ++i)
  209994. {
  209995. String s;
  209996. if (list[i].scsiDriveLetter > 0)
  209997. s << String::charToString (list[i].scsiDriveLetter).toUpperCase() << ": ";
  209998. s << String (list[i].vendor).trim()
  209999. << ' ' << String (list[i].productId).trim()
  210000. << ' ' << String (list[i].rev).trim();
  210001. results.add (s);
  210002. }
  210003. }
  210004. return results;
  210005. }
  210006. AudioCDReader* AudioCDReader::createReaderForCD (const int deviceIndex)
  210007. {
  210008. using namespace CDReaderHelpers;
  210009. incUserCount();
  210010. if (initialisedOk)
  210011. {
  210012. CDDeviceInfo list[8];
  210013. const int num = FindCDDevices (list, 8);
  210014. if (((unsigned int) deviceIndex) < (unsigned int) num)
  210015. {
  210016. CDDeviceHandle* const handle = openHandle (&(list[deviceIndex]));
  210017. if (handle != 0)
  210018. {
  210019. CDDeviceWrapper* const d = new CDDeviceWrapper();
  210020. d->cdH = handle;
  210021. d->overlapBuffer = new CDReadBuffer(3);
  210022. return new AudioCDReader (d);
  210023. }
  210024. }
  210025. }
  210026. decUserCount();
  210027. return 0;
  210028. }
  210029. AudioCDReader::AudioCDReader (void* handle_)
  210030. : AudioFormatReader (0, "CD Audio"),
  210031. handle (handle_),
  210032. indexingEnabled (false),
  210033. lastIndex (0),
  210034. firstFrameInBuffer (0),
  210035. samplesInBuffer (0)
  210036. {
  210037. using namespace CDReaderHelpers;
  210038. jassert (handle_ != 0);
  210039. refreshTrackLengths();
  210040. sampleRate = 44100.0;
  210041. bitsPerSample = 16;
  210042. lengthInSamples = getPositionOfTrackStart (numTracks);
  210043. numChannels = 2;
  210044. usesFloatingPointData = false;
  210045. buffer.setSize (4 * bytesPerFrame, true);
  210046. }
  210047. AudioCDReader::~AudioCDReader()
  210048. {
  210049. using namespace CDReaderHelpers;
  210050. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  210051. delete device;
  210052. decUserCount();
  210053. }
  210054. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  210055. int64 startSampleInFile, int numSamples)
  210056. {
  210057. using namespace CDReaderHelpers;
  210058. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  210059. bool ok = true;
  210060. while (numSamples > 0)
  210061. {
  210062. const int bufferStartSample = firstFrameInBuffer * samplesPerFrame;
  210063. const int bufferEndSample = bufferStartSample + samplesInBuffer;
  210064. if (startSampleInFile >= bufferStartSample
  210065. && startSampleInFile < bufferEndSample)
  210066. {
  210067. const int toDo = (int) jmin ((int64) numSamples, bufferEndSample - startSampleInFile);
  210068. int* const l = destSamples[0] + startOffsetInDestBuffer;
  210069. int* const r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  210070. const short* src = (const short*) buffer.getData();
  210071. src += 2 * (startSampleInFile - bufferStartSample);
  210072. for (int i = 0; i < toDo; ++i)
  210073. {
  210074. l[i] = src [i << 1] << 16;
  210075. if (r != 0)
  210076. r[i] = src [(i << 1) + 1] << 16;
  210077. }
  210078. startOffsetInDestBuffer += toDo;
  210079. startSampleInFile += toDo;
  210080. numSamples -= toDo;
  210081. }
  210082. else
  210083. {
  210084. const int framesInBuffer = buffer.getSize() / bytesPerFrame;
  210085. const int frameNeeded = (int) (startSampleInFile / samplesPerFrame);
  210086. if (firstFrameInBuffer + framesInBuffer != frameNeeded)
  210087. {
  210088. device->overlapBuffer->dataLength = 0;
  210089. device->overlapBuffer->startFrame = 0;
  210090. device->overlapBuffer->numFrames = 0;
  210091. device->jitter = false;
  210092. }
  210093. firstFrameInBuffer = frameNeeded;
  210094. lastIndex = 0;
  210095. CDReadBuffer readBuffer (framesInBuffer + 4);
  210096. readBuffer.wantsIndex = indexingEnabled;
  210097. int i;
  210098. for (i = 5; --i >= 0;)
  210099. {
  210100. readBuffer.startFrame = frameNeeded;
  210101. readBuffer.numFrames = framesInBuffer;
  210102. if (device->cdH->readAudio (&readBuffer, (device->jitter) ? device->overlapBuffer : 0))
  210103. break;
  210104. else
  210105. device->overlapBuffer->dataLength = 0;
  210106. }
  210107. if (i >= 0)
  210108. {
  210109. memcpy ((char*) buffer.getData(),
  210110. readBuffer.buffer + readBuffer.dataStartOffset,
  210111. readBuffer.dataLength);
  210112. samplesInBuffer = readBuffer.dataLength >> 2;
  210113. lastIndex = readBuffer.index;
  210114. }
  210115. else
  210116. {
  210117. int* l = destSamples[0] + startOffsetInDestBuffer;
  210118. int* r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  210119. while (--numSamples >= 0)
  210120. {
  210121. *l++ = 0;
  210122. if (r != 0)
  210123. *r++ = 0;
  210124. }
  210125. // sometimes the read fails for just the very last couple of blocks, so
  210126. // we'll ignore and errors in the last half-second of the disk..
  210127. ok = startSampleInFile > (trackStarts [numTracks] - 20000);
  210128. break;
  210129. }
  210130. }
  210131. }
  210132. return ok;
  210133. }
  210134. bool AudioCDReader::isCDStillPresent() const
  210135. {
  210136. using namespace CDReaderHelpers;
  210137. TOC toc;
  210138. zerostruct (toc);
  210139. return ((CDDeviceWrapper*) handle)->cdH->readTOC (&toc, false);
  210140. }
  210141. int AudioCDReader::getNumTracks() const
  210142. {
  210143. return numTracks;
  210144. }
  210145. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  210146. {
  210147. using namespace CDReaderHelpers;
  210148. return (trackNum >= 0 && trackNum <= numTracks) ? trackStarts [trackNum] * samplesPerFrame
  210149. : 0;
  210150. }
  210151. void AudioCDReader::refreshTrackLengths()
  210152. {
  210153. using namespace CDReaderHelpers;
  210154. zeromem (trackStarts, sizeof (trackStarts));
  210155. zeromem (audioTracks, sizeof (audioTracks));
  210156. TOC toc;
  210157. zerostruct (toc);
  210158. if (((CDDeviceWrapper*)handle)->cdH->readTOC (&toc, false))
  210159. {
  210160. numTracks = 1 + toc.lastTrack - toc.firstTrack;
  210161. for (int i = 0; i <= numTracks; ++i)
  210162. {
  210163. trackStarts[i] = getAddressOf (&toc.tracks[i]);
  210164. audioTracks[i] = ((toc.tracks[i].ADR & 4) == 0);
  210165. }
  210166. }
  210167. else
  210168. {
  210169. numTracks = 0;
  210170. }
  210171. }
  210172. bool AudioCDReader::isTrackAudio (int trackNum) const
  210173. {
  210174. return (trackNum >= 0 && trackNum <= numTracks) ? audioTracks [trackNum]
  210175. : false;
  210176. }
  210177. void AudioCDReader::enableIndexScanning (bool b)
  210178. {
  210179. indexingEnabled = b;
  210180. }
  210181. int AudioCDReader::getLastIndex() const
  210182. {
  210183. return lastIndex;
  210184. }
  210185. const int framesPerIndexRead = 4;
  210186. int AudioCDReader::getIndexAt (int samplePos)
  210187. {
  210188. using namespace CDReaderHelpers;
  210189. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  210190. const int frameNeeded = samplePos / samplesPerFrame;
  210191. device->overlapBuffer->dataLength = 0;
  210192. device->overlapBuffer->startFrame = 0;
  210193. device->overlapBuffer->numFrames = 0;
  210194. device->jitter = false;
  210195. firstFrameInBuffer = 0;
  210196. lastIndex = 0;
  210197. CDReadBuffer readBuffer (4 + framesPerIndexRead);
  210198. readBuffer.wantsIndex = true;
  210199. int i;
  210200. for (i = 5; --i >= 0;)
  210201. {
  210202. readBuffer.startFrame = frameNeeded;
  210203. readBuffer.numFrames = framesPerIndexRead;
  210204. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  210205. break;
  210206. }
  210207. if (i >= 0)
  210208. return readBuffer.index;
  210209. return -1;
  210210. }
  210211. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  210212. {
  210213. using namespace CDReaderHelpers;
  210214. Array <int> indexes;
  210215. const int trackStart = getPositionOfTrackStart (trackNumber);
  210216. const int trackEnd = getPositionOfTrackStart (trackNumber + 1);
  210217. bool needToScan = true;
  210218. if (trackEnd - trackStart > 20 * 44100)
  210219. {
  210220. // check the end of the track for indexes before scanning the whole thing
  210221. needToScan = false;
  210222. int pos = jmax (trackStart, trackEnd - 44100 * 5);
  210223. bool seenAnIndex = false;
  210224. while (pos <= trackEnd - samplesPerFrame)
  210225. {
  210226. const int index = getIndexAt (pos);
  210227. if (index == 0)
  210228. {
  210229. // lead-out, so skip back a bit if we've not found any indexes yet..
  210230. if (seenAnIndex)
  210231. break;
  210232. pos -= 44100 * 5;
  210233. if (pos < trackStart)
  210234. break;
  210235. }
  210236. else
  210237. {
  210238. if (index > 0)
  210239. seenAnIndex = true;
  210240. if (index > 1)
  210241. {
  210242. needToScan = true;
  210243. break;
  210244. }
  210245. pos += samplesPerFrame * framesPerIndexRead;
  210246. }
  210247. }
  210248. }
  210249. if (needToScan)
  210250. {
  210251. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  210252. int pos = trackStart;
  210253. int last = -1;
  210254. while (pos < trackEnd - samplesPerFrame * 10)
  210255. {
  210256. const int frameNeeded = pos / samplesPerFrame;
  210257. device->overlapBuffer->dataLength = 0;
  210258. device->overlapBuffer->startFrame = 0;
  210259. device->overlapBuffer->numFrames = 0;
  210260. device->jitter = false;
  210261. firstFrameInBuffer = 0;
  210262. CDReadBuffer readBuffer (4);
  210263. readBuffer.wantsIndex = true;
  210264. int i;
  210265. for (i = 5; --i >= 0;)
  210266. {
  210267. readBuffer.startFrame = frameNeeded;
  210268. readBuffer.numFrames = framesPerIndexRead;
  210269. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  210270. break;
  210271. }
  210272. if (i < 0)
  210273. break;
  210274. if (readBuffer.index > last && readBuffer.index > 1)
  210275. {
  210276. last = readBuffer.index;
  210277. indexes.add (pos);
  210278. }
  210279. pos += samplesPerFrame * framesPerIndexRead;
  210280. }
  210281. indexes.removeValue (trackStart);
  210282. }
  210283. return indexes;
  210284. }
  210285. int AudioCDReader::getCDDBId()
  210286. {
  210287. using namespace CDReaderHelpers;
  210288. refreshTrackLengths();
  210289. if (numTracks > 0)
  210290. {
  210291. TOC toc;
  210292. zerostruct (toc);
  210293. if (((CDDeviceWrapper*) handle)->cdH->readTOC (&toc, true))
  210294. {
  210295. int n = 0;
  210296. for (int i = numTracks; --i >= 0;)
  210297. {
  210298. int j = getMSFAddressOf (&toc.tracks[i]);
  210299. while (j > 0)
  210300. {
  210301. n += (j % 10);
  210302. j /= 10;
  210303. }
  210304. }
  210305. if (n != 0)
  210306. {
  210307. const int t = getMSFAddressOf (&toc.tracks[numTracks])
  210308. - getMSFAddressOf (&toc.tracks[0]);
  210309. return ((n % 0xff) << 24) | (t << 8) | numTracks;
  210310. }
  210311. }
  210312. }
  210313. return 0;
  210314. }
  210315. void AudioCDReader::ejectDisk()
  210316. {
  210317. using namespace CDReaderHelpers;
  210318. ((CDDeviceWrapper*) handle)->cdH->openDrawer (true);
  210319. }
  210320. #endif
  210321. #if JUCE_USE_CDBURNER
  210322. static IDiscRecorder* enumCDBurners (StringArray* list, int indexToOpen, IDiscMaster** master)
  210323. {
  210324. CoInitialize (0);
  210325. IDiscMaster* dm;
  210326. IDiscRecorder* result = 0;
  210327. if (SUCCEEDED (CoCreateInstance (CLSID_MSDiscMasterObj, 0,
  210328. CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER,
  210329. IID_IDiscMaster,
  210330. (void**) &dm)))
  210331. {
  210332. if (SUCCEEDED (dm->Open()))
  210333. {
  210334. IEnumDiscRecorders* drEnum = 0;
  210335. if (SUCCEEDED (dm->EnumDiscRecorders (&drEnum)))
  210336. {
  210337. IDiscRecorder* dr = 0;
  210338. DWORD dummy;
  210339. int index = 0;
  210340. while (drEnum->Next (1, &dr, &dummy) == S_OK)
  210341. {
  210342. if (indexToOpen == index)
  210343. {
  210344. result = dr;
  210345. break;
  210346. }
  210347. else if (list != 0)
  210348. {
  210349. BSTR path;
  210350. if (SUCCEEDED (dr->GetPath (&path)))
  210351. list->add ((const WCHAR*) path);
  210352. }
  210353. ++index;
  210354. dr->Release();
  210355. }
  210356. drEnum->Release();
  210357. }
  210358. if (master == 0)
  210359. dm->Close();
  210360. }
  210361. if (master != 0)
  210362. *master = dm;
  210363. else
  210364. dm->Release();
  210365. }
  210366. return result;
  210367. }
  210368. class AudioCDBurner::Pimpl : public ComBaseClassHelper <IDiscMasterProgressEvents>,
  210369. public Timer
  210370. {
  210371. public:
  210372. Pimpl (AudioCDBurner& owner_, IDiscMaster* discMaster_, IDiscRecorder* discRecorder_)
  210373. : owner (owner_), discMaster (discMaster_), discRecorder (discRecorder_), redbook (0),
  210374. listener (0), progress (0), shouldCancel (false)
  210375. {
  210376. HRESULT hr = discMaster->SetActiveDiscMasterFormat (IID_IRedbookDiscMaster, (void**) &redbook);
  210377. jassert (SUCCEEDED (hr));
  210378. hr = discMaster->SetActiveDiscRecorder (discRecorder);
  210379. //jassert (SUCCEEDED (hr));
  210380. lastState = getDiskState();
  210381. startTimer (2000);
  210382. }
  210383. ~Pimpl() {}
  210384. void releaseObjects()
  210385. {
  210386. discRecorder->Close();
  210387. if (redbook != 0)
  210388. redbook->Release();
  210389. discRecorder->Release();
  210390. discMaster->Release();
  210391. Release();
  210392. }
  210393. HRESULT __stdcall QueryCancel (boolean* pbCancel)
  210394. {
  210395. if (listener != 0 && ! shouldCancel)
  210396. shouldCancel = listener->audioCDBurnProgress (progress);
  210397. *pbCancel = shouldCancel;
  210398. return S_OK;
  210399. }
  210400. HRESULT __stdcall NotifyBlockProgress (long nCompleted, long nTotal)
  210401. {
  210402. progress = nCompleted / (float) nTotal;
  210403. shouldCancel = listener != 0 && listener->audioCDBurnProgress (progress);
  210404. return E_NOTIMPL;
  210405. }
  210406. HRESULT __stdcall NotifyPnPActivity (void) { return E_NOTIMPL; }
  210407. HRESULT __stdcall NotifyAddProgress (long /*nCompletedSteps*/, long /*nTotalSteps*/) { return E_NOTIMPL; }
  210408. HRESULT __stdcall NotifyTrackProgress (long /*nCurrentTrack*/, long /*nTotalTracks*/) { return E_NOTIMPL; }
  210409. HRESULT __stdcall NotifyPreparingBurn (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  210410. HRESULT __stdcall NotifyClosingDisc (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  210411. HRESULT __stdcall NotifyBurnComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  210412. HRESULT __stdcall NotifyEraseComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  210413. class ScopedDiscOpener
  210414. {
  210415. public:
  210416. ScopedDiscOpener (Pimpl& p) : pimpl (p) { pimpl.discRecorder->OpenExclusive(); }
  210417. ~ScopedDiscOpener() { pimpl.discRecorder->Close(); }
  210418. private:
  210419. Pimpl& pimpl;
  210420. ScopedDiscOpener (const ScopedDiscOpener&);
  210421. ScopedDiscOpener& operator= (const ScopedDiscOpener&);
  210422. };
  210423. DiskState getDiskState()
  210424. {
  210425. const ScopedDiscOpener opener (*this);
  210426. long type, flags;
  210427. HRESULT hr = discRecorder->QueryMediaType (&type, &flags);
  210428. if (FAILED (hr))
  210429. return unknown;
  210430. if (type != 0 && (flags & MEDIA_WRITABLE) != 0)
  210431. return writableDiskPresent;
  210432. if (type == 0)
  210433. return noDisc;
  210434. else
  210435. return readOnlyDiskPresent;
  210436. }
  210437. int getIntProperty (const LPOLESTR name, const int defaultReturn) const
  210438. {
  210439. ComSmartPtr<IPropertyStorage> prop;
  210440. if (FAILED (discRecorder->GetRecorderProperties (&prop)))
  210441. return defaultReturn;
  210442. PROPSPEC iPropSpec;
  210443. iPropSpec.ulKind = PRSPEC_LPWSTR;
  210444. iPropSpec.lpwstr = name;
  210445. PROPVARIANT iPropVariant;
  210446. return FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant))
  210447. ? defaultReturn : (int) iPropVariant.lVal;
  210448. }
  210449. bool setIntProperty (const LPOLESTR name, const int value) const
  210450. {
  210451. ComSmartPtr<IPropertyStorage> prop;
  210452. if (FAILED (discRecorder->GetRecorderProperties (&prop)))
  210453. return false;
  210454. PROPSPEC iPropSpec;
  210455. iPropSpec.ulKind = PRSPEC_LPWSTR;
  210456. iPropSpec.lpwstr = name;
  210457. PROPVARIANT iPropVariant;
  210458. if (FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant)))
  210459. return false;
  210460. iPropVariant.lVal = (long) value;
  210461. return SUCCEEDED (prop->WriteMultiple (1, &iPropSpec, &iPropVariant, iPropVariant.vt))
  210462. && SUCCEEDED (discRecorder->SetRecorderProperties (prop));
  210463. }
  210464. void timerCallback()
  210465. {
  210466. const DiskState state = getDiskState();
  210467. if (state != lastState)
  210468. {
  210469. lastState = state;
  210470. owner.sendChangeMessage (&owner);
  210471. }
  210472. }
  210473. AudioCDBurner& owner;
  210474. DiskState lastState;
  210475. IDiscMaster* discMaster;
  210476. IDiscRecorder* discRecorder;
  210477. IRedbookDiscMaster* redbook;
  210478. AudioCDBurner::BurnProgressListener* listener;
  210479. float progress;
  210480. bool shouldCancel;
  210481. };
  210482. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  210483. {
  210484. IDiscMaster* discMaster = 0;
  210485. IDiscRecorder* discRecorder = enumCDBurners (0, deviceIndex, &discMaster);
  210486. if (discRecorder != 0)
  210487. pimpl = new Pimpl (*this, discMaster, discRecorder);
  210488. }
  210489. AudioCDBurner::~AudioCDBurner()
  210490. {
  210491. if (pimpl != 0)
  210492. pimpl.release()->releaseObjects();
  210493. }
  210494. const StringArray AudioCDBurner::findAvailableDevices()
  210495. {
  210496. StringArray devs;
  210497. enumCDBurners (&devs, -1, 0);
  210498. return devs;
  210499. }
  210500. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  210501. {
  210502. ScopedPointer<AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  210503. if (b->pimpl == 0)
  210504. b = 0;
  210505. return b.release();
  210506. }
  210507. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  210508. {
  210509. return pimpl->getDiskState();
  210510. }
  210511. bool AudioCDBurner::isDiskPresent() const
  210512. {
  210513. return getDiskState() == writableDiskPresent;
  210514. }
  210515. bool AudioCDBurner::openTray()
  210516. {
  210517. const Pimpl::ScopedDiscOpener opener (*pimpl);
  210518. return SUCCEEDED (pimpl->discRecorder->Eject());
  210519. }
  210520. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  210521. {
  210522. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  210523. DiskState oldState = getDiskState();
  210524. DiskState newState = oldState;
  210525. while (newState == oldState && Time::currentTimeMillis() < timeout)
  210526. {
  210527. newState = getDiskState();
  210528. Thread::sleep (jmin (250, (int) (timeout - Time::currentTimeMillis())));
  210529. }
  210530. return newState;
  210531. }
  210532. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  210533. {
  210534. Array<int> results;
  210535. const int maxSpeed = pimpl->getIntProperty (L"MaxWriteSpeed", 1);
  210536. const int speeds[] = { 1, 2, 4, 8, 12, 16, 20, 24, 32, 40, 64, 80 };
  210537. for (int i = 0; i < numElementsInArray (speeds); ++i)
  210538. if (speeds[i] <= maxSpeed)
  210539. results.add (speeds[i]);
  210540. results.addIfNotAlreadyThere (maxSpeed);
  210541. return results;
  210542. }
  210543. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  210544. {
  210545. if (pimpl->getIntProperty (L"BufferUnderrunFreeCapable", 0) == 0)
  210546. return false;
  210547. pimpl->setIntProperty (L"EnableBufferUnderrunFree", shouldBeEnabled ? -1 : 0);
  210548. return pimpl->getIntProperty (L"EnableBufferUnderrunFree", 0) != 0;
  210549. }
  210550. int AudioCDBurner::getNumAvailableAudioBlocks() const
  210551. {
  210552. long blocksFree = 0;
  210553. pimpl->redbook->GetAvailableAudioTrackBlocks (&blocksFree);
  210554. return blocksFree;
  210555. }
  210556. const String AudioCDBurner::burn (AudioCDBurner::BurnProgressListener* listener, bool ejectDiscAfterwards,
  210557. bool performFakeBurnForTesting, int writeSpeed)
  210558. {
  210559. pimpl->setIntProperty (L"WriteSpeed", writeSpeed > 0 ? writeSpeed : -1);
  210560. pimpl->listener = listener;
  210561. pimpl->progress = 0;
  210562. pimpl->shouldCancel = false;
  210563. UINT_PTR cookie;
  210564. HRESULT hr = pimpl->discMaster->ProgressAdvise ((AudioCDBurner::Pimpl*) pimpl, &cookie);
  210565. hr = pimpl->discMaster->RecordDisc (performFakeBurnForTesting,
  210566. ejectDiscAfterwards);
  210567. String error;
  210568. if (hr != S_OK)
  210569. {
  210570. const char* e = "Couldn't open or write to the CD device";
  210571. if (hr == IMAPI_E_USERABORT)
  210572. e = "User cancelled the write operation";
  210573. else if (hr == IMAPI_E_MEDIUM_NOTPRESENT || hr == IMAPI_E_TRACKOPEN)
  210574. e = "No Disk present";
  210575. error = e;
  210576. }
  210577. pimpl->discMaster->ProgressUnadvise (cookie);
  210578. pimpl->listener = 0;
  210579. return error;
  210580. }
  210581. bool AudioCDBurner::addAudioTrack (AudioSource* audioSource, int numSamples)
  210582. {
  210583. if (audioSource == 0)
  210584. return false;
  210585. ScopedPointer<AudioSource> source (audioSource);
  210586. long bytesPerBlock;
  210587. HRESULT hr = pimpl->redbook->GetAudioBlockSize (&bytesPerBlock);
  210588. const int samplesPerBlock = bytesPerBlock / 4;
  210589. bool ok = true;
  210590. hr = pimpl->redbook->CreateAudioTrack ((long) numSamples / (bytesPerBlock * 4));
  210591. HeapBlock <byte> buffer (bytesPerBlock);
  210592. AudioSampleBuffer sourceBuffer (2, samplesPerBlock);
  210593. int samplesDone = 0;
  210594. source->prepareToPlay (samplesPerBlock, 44100.0);
  210595. while (ok)
  210596. {
  210597. {
  210598. AudioSourceChannelInfo info;
  210599. info.buffer = &sourceBuffer;
  210600. info.numSamples = samplesPerBlock;
  210601. info.startSample = 0;
  210602. sourceBuffer.clear();
  210603. source->getNextAudioBlock (info);
  210604. }
  210605. zeromem (buffer, bytesPerBlock);
  210606. AudioDataConverters::convertFloatToInt16LE (sourceBuffer.getSampleData (0, 0),
  210607. buffer, samplesPerBlock, 4);
  210608. AudioDataConverters::convertFloatToInt16LE (sourceBuffer.getSampleData (1, 0),
  210609. buffer + 2, samplesPerBlock, 4);
  210610. hr = pimpl->redbook->AddAudioTrackBlocks (buffer, bytesPerBlock);
  210611. if (FAILED (hr))
  210612. ok = false;
  210613. samplesDone += samplesPerBlock;
  210614. if (samplesDone >= numSamples)
  210615. break;
  210616. }
  210617. hr = pimpl->redbook->CloseAudioTrack();
  210618. return ok && hr == S_OK;
  210619. }
  210620. #endif
  210621. #endif
  210622. /*** End of inlined file: juce_win32_AudioCDReader.cpp ***/
  210623. /*** Start of inlined file: juce_win32_Midi.cpp ***/
  210624. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210625. // compiled on its own).
  210626. #if JUCE_INCLUDED_FILE
  210627. using ::free;
  210628. namespace MidiConstants
  210629. {
  210630. static const int midiBufferSize = 1024 * 10;
  210631. static const int numInHeaders = 32;
  210632. static const int inBufferSize = 256;
  210633. }
  210634. class MidiInThread : public Thread
  210635. {
  210636. public:
  210637. MidiInThread (MidiInput* const input_,
  210638. MidiInputCallback* const callback_)
  210639. : Thread ("Juce Midi"),
  210640. hIn (0),
  210641. input (input_),
  210642. callback (callback_),
  210643. isStarted (false),
  210644. startTime (0),
  210645. pendingLength(0)
  210646. {
  210647. for (int i = MidiConstants::numInHeaders; --i >= 0;)
  210648. {
  210649. zeromem (&hdr[i], sizeof (MIDIHDR));
  210650. hdr[i].lpData = inData[i];
  210651. hdr[i].dwBufferLength = MidiConstants::inBufferSize;
  210652. }
  210653. };
  210654. ~MidiInThread()
  210655. {
  210656. stop();
  210657. if (hIn != 0)
  210658. {
  210659. int count = 5;
  210660. while (--count >= 0)
  210661. {
  210662. if (midiInClose (hIn) == MMSYSERR_NOERROR)
  210663. break;
  210664. Sleep (20);
  210665. }
  210666. }
  210667. }
  210668. void handle (const uint32 message, const uint32 timeStamp)
  210669. {
  210670. const int byte = message & 0xff;
  210671. if (byte < 0x80)
  210672. return;
  210673. const int numBytes = MidiMessage::getMessageLengthFromFirstByte ((uint8) byte);
  210674. const double time = timeStampToTime (timeStamp);
  210675. {
  210676. const ScopedLock sl (lock);
  210677. if (pendingLength < MidiConstants::midiBufferSize - 12)
  210678. {
  210679. char* const p = pending + pendingLength;
  210680. *(double*) p = time;
  210681. *(uint32*) (p + 8) = numBytes;
  210682. *(uint32*) (p + 12) = message;
  210683. pendingLength += 12 + numBytes;
  210684. }
  210685. else
  210686. {
  210687. jassertfalse; // midi buffer overflow! You might need to increase the size..
  210688. }
  210689. }
  210690. notify();
  210691. }
  210692. void handleSysEx (MIDIHDR* const hdr, const uint32 timeStamp)
  210693. {
  210694. const int num = hdr->dwBytesRecorded;
  210695. if (num > 0)
  210696. {
  210697. const double time = timeStampToTime (timeStamp);
  210698. {
  210699. const ScopedLock sl (lock);
  210700. if (pendingLength < MidiConstants::midiBufferSize - (8 + num))
  210701. {
  210702. char* const p = pending + pendingLength;
  210703. *(double*) p = time;
  210704. *(uint32*) (p + 8) = num;
  210705. memcpy (p + 12, hdr->lpData, num);
  210706. pendingLength += 12 + num;
  210707. }
  210708. else
  210709. {
  210710. jassertfalse; // midi buffer overflow! You might need to increase the size..
  210711. }
  210712. }
  210713. notify();
  210714. }
  210715. }
  210716. void writeBlock (const int i)
  210717. {
  210718. hdr[i].dwBytesRecorded = 0;
  210719. MMRESULT res = midiInPrepareHeader (hIn, &hdr[i], sizeof (MIDIHDR));
  210720. jassert (res == MMSYSERR_NOERROR);
  210721. res = midiInAddBuffer (hIn, &hdr[i], sizeof (MIDIHDR));
  210722. jassert (res == MMSYSERR_NOERROR);
  210723. }
  210724. void run()
  210725. {
  210726. MemoryBlock pendingCopy (64);
  210727. while (! threadShouldExit())
  210728. {
  210729. for (int i = 0; i < MidiConstants::numInHeaders; ++i)
  210730. {
  210731. if ((hdr[i].dwFlags & WHDR_DONE) != 0)
  210732. {
  210733. MMRESULT res = midiInUnprepareHeader (hIn, &hdr[i], sizeof (MIDIHDR));
  210734. (void) res;
  210735. jassert (res == MMSYSERR_NOERROR);
  210736. writeBlock (i);
  210737. }
  210738. }
  210739. int len;
  210740. {
  210741. const ScopedLock sl (lock);
  210742. len = pendingLength;
  210743. if (len > 0)
  210744. {
  210745. pendingCopy.ensureSize (len);
  210746. pendingCopy.copyFrom (pending, 0, len);
  210747. pendingLength = 0;
  210748. }
  210749. }
  210750. //xxx needs to figure out if blocks are broken up or not
  210751. if (len == 0)
  210752. {
  210753. wait (500);
  210754. }
  210755. else
  210756. {
  210757. const char* p = (const char*) pendingCopy.getData();
  210758. while (len > 0)
  210759. {
  210760. const double time = *(const double*) p;
  210761. const int messageLen = *(const int*) (p + 8);
  210762. const MidiMessage message ((const uint8*) (p + 12), messageLen, time);
  210763. callback->handleIncomingMidiMessage (input, message);
  210764. p += 12 + messageLen;
  210765. len -= 12 + messageLen;
  210766. }
  210767. }
  210768. }
  210769. }
  210770. void start()
  210771. {
  210772. jassert (hIn != 0);
  210773. if (hIn != 0 && ! isStarted)
  210774. {
  210775. stop();
  210776. activeMidiThreads.addIfNotAlreadyThere (this);
  210777. int i;
  210778. for (i = 0; i < MidiConstants::numInHeaders; ++i)
  210779. writeBlock (i);
  210780. startTime = Time::getMillisecondCounter();
  210781. MMRESULT res = midiInStart (hIn);
  210782. jassert (res == MMSYSERR_NOERROR);
  210783. if (res == MMSYSERR_NOERROR)
  210784. {
  210785. isStarted = true;
  210786. pendingLength = 0;
  210787. startThread (6);
  210788. }
  210789. }
  210790. }
  210791. void stop()
  210792. {
  210793. if (isStarted)
  210794. {
  210795. stopThread (5000);
  210796. midiInReset (hIn);
  210797. midiInStop (hIn);
  210798. activeMidiThreads.removeValue (this);
  210799. { const ScopedLock sl (lock); }
  210800. for (int i = MidiConstants::numInHeaders; --i >= 0;)
  210801. {
  210802. if ((hdr[i].dwFlags & WHDR_DONE) != 0)
  210803. {
  210804. int c = 10;
  210805. while (--c >= 0 && midiInUnprepareHeader (hIn, &hdr[i], sizeof (MIDIHDR)) == MIDIERR_STILLPLAYING)
  210806. Sleep (20);
  210807. jassert (c >= 0);
  210808. }
  210809. }
  210810. isStarted = false;
  210811. pendingLength = 0;
  210812. }
  210813. }
  210814. static void CALLBACK midiInCallback (HMIDIIN, UINT uMsg, DWORD_PTR dwInstance, DWORD_PTR midiMessage, DWORD_PTR timeStamp)
  210815. {
  210816. MidiInThread* const thread = reinterpret_cast <MidiInThread*> (dwInstance);
  210817. if (thread != 0 && activeMidiThreads.contains (thread))
  210818. {
  210819. if (uMsg == MIM_DATA)
  210820. thread->handle ((uint32) midiMessage, (uint32) timeStamp);
  210821. else if (uMsg == MIM_LONGDATA)
  210822. thread->handleSysEx ((MIDIHDR*) midiMessage, (uint32) timeStamp);
  210823. }
  210824. }
  210825. juce_UseDebuggingNewOperator
  210826. HMIDIIN hIn;
  210827. private:
  210828. static Array <void*, CriticalSection> activeMidiThreads;
  210829. MidiInput* input;
  210830. MidiInputCallback* callback;
  210831. bool isStarted;
  210832. uint32 startTime;
  210833. CriticalSection lock;
  210834. MIDIHDR hdr [MidiConstants::numInHeaders];
  210835. char inData [MidiConstants::numInHeaders] [MidiConstants::inBufferSize];
  210836. int pendingLength;
  210837. char pending [MidiConstants::midiBufferSize];
  210838. double timeStampToTime (uint32 timeStamp)
  210839. {
  210840. timeStamp += startTime;
  210841. const uint32 now = Time::getMillisecondCounter();
  210842. if (timeStamp > now)
  210843. {
  210844. if (timeStamp > now + 2)
  210845. --startTime;
  210846. timeStamp = now;
  210847. }
  210848. return 0.001 * timeStamp;
  210849. }
  210850. MidiInThread (const MidiInThread&);
  210851. MidiInThread& operator= (const MidiInThread&);
  210852. };
  210853. Array <void*, CriticalSection> MidiInThread::activeMidiThreads;
  210854. const StringArray MidiInput::getDevices()
  210855. {
  210856. StringArray s;
  210857. const int num = midiInGetNumDevs();
  210858. for (int i = 0; i < num; ++i)
  210859. {
  210860. MIDIINCAPS mc;
  210861. zerostruct (mc);
  210862. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  210863. s.add (String (mc.szPname, sizeof (mc.szPname)));
  210864. }
  210865. return s;
  210866. }
  210867. int MidiInput::getDefaultDeviceIndex()
  210868. {
  210869. return 0;
  210870. }
  210871. MidiInput* MidiInput::openDevice (const int index, MidiInputCallback* const callback)
  210872. {
  210873. if (callback == 0)
  210874. return 0;
  210875. UINT deviceId = MIDI_MAPPER;
  210876. int n = 0;
  210877. String name;
  210878. const int num = midiInGetNumDevs();
  210879. for (int i = 0; i < num; ++i)
  210880. {
  210881. MIDIINCAPS mc;
  210882. zerostruct (mc);
  210883. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  210884. {
  210885. if (index == n)
  210886. {
  210887. deviceId = i;
  210888. name = String (mc.szPname, sizeof (mc.szPname));
  210889. break;
  210890. }
  210891. ++n;
  210892. }
  210893. }
  210894. ScopedPointer <MidiInput> in (new MidiInput (name));
  210895. ScopedPointer <MidiInThread> thread (new MidiInThread (in, callback));
  210896. HMIDIIN h;
  210897. HRESULT err = midiInOpen (&h, deviceId,
  210898. (DWORD_PTR) &MidiInThread::midiInCallback,
  210899. (DWORD_PTR) (MidiInThread*) thread,
  210900. CALLBACK_FUNCTION);
  210901. if (err == MMSYSERR_NOERROR)
  210902. {
  210903. thread->hIn = h;
  210904. in->internal = thread.release();
  210905. return in.release();
  210906. }
  210907. return 0;
  210908. }
  210909. MidiInput::MidiInput (const String& name_)
  210910. : name (name_),
  210911. internal (0)
  210912. {
  210913. }
  210914. MidiInput::~MidiInput()
  210915. {
  210916. delete static_cast <MidiInThread*> (internal);
  210917. }
  210918. void MidiInput::start()
  210919. {
  210920. static_cast <MidiInThread*> (internal)->start();
  210921. }
  210922. void MidiInput::stop()
  210923. {
  210924. static_cast <MidiInThread*> (internal)->stop();
  210925. }
  210926. struct MidiOutHandle
  210927. {
  210928. int refCount;
  210929. UINT deviceId;
  210930. HMIDIOUT handle;
  210931. static Array<MidiOutHandle*> activeHandles;
  210932. juce_UseDebuggingNewOperator
  210933. };
  210934. Array<MidiOutHandle*> MidiOutHandle::activeHandles;
  210935. const StringArray MidiOutput::getDevices()
  210936. {
  210937. StringArray s;
  210938. const int num = midiOutGetNumDevs();
  210939. for (int i = 0; i < num; ++i)
  210940. {
  210941. MIDIOUTCAPS mc;
  210942. zerostruct (mc);
  210943. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  210944. s.add (String (mc.szPname, sizeof (mc.szPname)));
  210945. }
  210946. return s;
  210947. }
  210948. int MidiOutput::getDefaultDeviceIndex()
  210949. {
  210950. const int num = midiOutGetNumDevs();
  210951. int n = 0;
  210952. for (int i = 0; i < num; ++i)
  210953. {
  210954. MIDIOUTCAPS mc;
  210955. zerostruct (mc);
  210956. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  210957. {
  210958. if ((mc.wTechnology & MOD_MAPPER) != 0)
  210959. return n;
  210960. ++n;
  210961. }
  210962. }
  210963. return 0;
  210964. }
  210965. MidiOutput* MidiOutput::openDevice (int index)
  210966. {
  210967. UINT deviceId = MIDI_MAPPER;
  210968. const int num = midiOutGetNumDevs();
  210969. int i, n = 0;
  210970. for (i = 0; i < num; ++i)
  210971. {
  210972. MIDIOUTCAPS mc;
  210973. zerostruct (mc);
  210974. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  210975. {
  210976. // use the microsoft sw synth as a default - best not to allow deviceId
  210977. // to be MIDI_MAPPER, or else device sharing breaks
  210978. if (String (mc.szPname, sizeof (mc.szPname)).containsIgnoreCase ("microsoft"))
  210979. deviceId = i;
  210980. if (index == n)
  210981. {
  210982. deviceId = i;
  210983. break;
  210984. }
  210985. ++n;
  210986. }
  210987. }
  210988. for (i = MidiOutHandle::activeHandles.size(); --i >= 0;)
  210989. {
  210990. MidiOutHandle* const han = MidiOutHandle::activeHandles.getUnchecked(i);
  210991. if (han != 0 && han->deviceId == deviceId)
  210992. {
  210993. han->refCount++;
  210994. MidiOutput* const out = new MidiOutput();
  210995. out->internal = han;
  210996. return out;
  210997. }
  210998. }
  210999. for (i = 4; --i >= 0;)
  211000. {
  211001. HMIDIOUT h = 0;
  211002. MMRESULT res = midiOutOpen (&h, deviceId, 0, 0, CALLBACK_NULL);
  211003. if (res == MMSYSERR_NOERROR)
  211004. {
  211005. MidiOutHandle* const han = new MidiOutHandle();
  211006. han->deviceId = deviceId;
  211007. han->refCount = 1;
  211008. han->handle = h;
  211009. MidiOutHandle::activeHandles.add (han);
  211010. MidiOutput* const out = new MidiOutput();
  211011. out->internal = han;
  211012. return out;
  211013. }
  211014. else if (res == MMSYSERR_ALLOCATED)
  211015. {
  211016. Sleep (100);
  211017. }
  211018. else
  211019. {
  211020. break;
  211021. }
  211022. }
  211023. return 0;
  211024. }
  211025. MidiOutput::~MidiOutput()
  211026. {
  211027. MidiOutHandle* const h = static_cast <MidiOutHandle*> (internal);
  211028. if (MidiOutHandle::activeHandles.contains (h) && --(h->refCount) == 0)
  211029. {
  211030. midiOutClose (h->handle);
  211031. MidiOutHandle::activeHandles.removeValue (h);
  211032. delete h;
  211033. }
  211034. }
  211035. void MidiOutput::reset()
  211036. {
  211037. const MidiOutHandle* const h = static_cast <const MidiOutHandle*> (internal);
  211038. midiOutReset (h->handle);
  211039. }
  211040. bool MidiOutput::getVolume (float& leftVol,
  211041. float& rightVol)
  211042. {
  211043. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  211044. DWORD n;
  211045. if (midiOutGetVolume (handle->handle, &n) == MMSYSERR_NOERROR)
  211046. {
  211047. const unsigned short* const nn = (const unsigned short*) &n;
  211048. rightVol = nn[0] / (float) 0xffff;
  211049. leftVol = nn[1] / (float) 0xffff;
  211050. return true;
  211051. }
  211052. else
  211053. {
  211054. rightVol = leftVol = 1.0f;
  211055. return false;
  211056. }
  211057. }
  211058. void MidiOutput::setVolume (float leftVol,
  211059. float rightVol)
  211060. {
  211061. const MidiOutHandle* const handle = static_cast <MidiOutHandle*> (internal);
  211062. DWORD n;
  211063. unsigned short* const nn = (unsigned short*) &n;
  211064. nn[0] = (unsigned short) jlimit (0, 0xffff, (int) (rightVol * 0xffff));
  211065. nn[1] = (unsigned short) jlimit (0, 0xffff, (int) (leftVol * 0xffff));
  211066. midiOutSetVolume (handle->handle, n);
  211067. }
  211068. void MidiOutput::sendMessageNow (const MidiMessage& message)
  211069. {
  211070. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  211071. if (message.getRawDataSize() > 3
  211072. || message.isSysEx())
  211073. {
  211074. MIDIHDR h;
  211075. zerostruct (h);
  211076. h.lpData = (char*) message.getRawData();
  211077. h.dwBufferLength = message.getRawDataSize();
  211078. h.dwBytesRecorded = message.getRawDataSize();
  211079. if (midiOutPrepareHeader (handle->handle, &h, sizeof (MIDIHDR)) == MMSYSERR_NOERROR)
  211080. {
  211081. MMRESULT res = midiOutLongMsg (handle->handle, &h, sizeof (MIDIHDR));
  211082. if (res == MMSYSERR_NOERROR)
  211083. {
  211084. while ((h.dwFlags & MHDR_DONE) == 0)
  211085. Sleep (1);
  211086. int count = 500; // 1 sec timeout
  211087. while (--count >= 0)
  211088. {
  211089. res = midiOutUnprepareHeader (handle->handle, &h, sizeof (MIDIHDR));
  211090. if (res == MIDIERR_STILLPLAYING)
  211091. Sleep (2);
  211092. else
  211093. break;
  211094. }
  211095. }
  211096. }
  211097. }
  211098. else
  211099. {
  211100. midiOutShortMsg (handle->handle,
  211101. *(unsigned int*) message.getRawData());
  211102. }
  211103. }
  211104. #endif
  211105. /*** End of inlined file: juce_win32_Midi.cpp ***/
  211106. /*** Start of inlined file: juce_win32_ASIO.cpp ***/
  211107. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  211108. // compiled on its own).
  211109. #if JUCE_INCLUDED_FILE && JUCE_ASIO
  211110. #undef WINDOWS
  211111. // #define ASIO_DEBUGGING
  211112. #ifdef ASIO_DEBUGGING
  211113. #define log(a) { Logger::writeToLog (a); DBG (a) }
  211114. #else
  211115. #define log(a) {}
  211116. #endif
  211117. #ifdef ASIO_DEBUGGING
  211118. static void logError (const String& context, long error)
  211119. {
  211120. String err ("unknown error");
  211121. if (error == ASE_NotPresent)
  211122. err = "Not Present";
  211123. else if (error == ASE_HWMalfunction)
  211124. err = "Hardware Malfunction";
  211125. else if (error == ASE_InvalidParameter)
  211126. err = "Invalid Parameter";
  211127. else if (error == ASE_InvalidMode)
  211128. err = "Invalid Mode";
  211129. else if (error == ASE_SPNotAdvancing)
  211130. err = "Sample position not advancing";
  211131. else if (error == ASE_NoClock)
  211132. err = "No Clock";
  211133. else if (error == ASE_NoMemory)
  211134. err = "Out of memory";
  211135. log ("!!error: " + context + " - " + err);
  211136. }
  211137. #else
  211138. #define logError(a, b) {}
  211139. #endif
  211140. class ASIOAudioIODevice;
  211141. static ASIOAudioIODevice* volatile currentASIODev[3] = { 0, 0, 0 };
  211142. static const int maxASIOChannels = 160;
  211143. class JUCE_API ASIOAudioIODevice : public AudioIODevice,
  211144. private Timer
  211145. {
  211146. public:
  211147. Component ourWindow;
  211148. ASIOAudioIODevice (const String& name_, const CLSID classId_, const int slotNumber,
  211149. const String& optionalDllForDirectLoading_)
  211150. : AudioIODevice (name_, "ASIO"),
  211151. asioObject (0),
  211152. classId (classId_),
  211153. optionalDllForDirectLoading (optionalDllForDirectLoading_),
  211154. currentBitDepth (16),
  211155. currentSampleRate (0),
  211156. isOpen_ (false),
  211157. isStarted (false),
  211158. postOutput (true),
  211159. insideControlPanelModalLoop (false),
  211160. shouldUsePreferredSize (false)
  211161. {
  211162. name = name_;
  211163. ourWindow.addToDesktop (0);
  211164. windowHandle = ourWindow.getWindowHandle();
  211165. jassert (currentASIODev [slotNumber] == 0);
  211166. currentASIODev [slotNumber] = this;
  211167. openDevice();
  211168. }
  211169. ~ASIOAudioIODevice()
  211170. {
  211171. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  211172. if (currentASIODev[i] == this)
  211173. currentASIODev[i] = 0;
  211174. close();
  211175. log ("ASIO - exiting");
  211176. removeCurrentDriver();
  211177. }
  211178. void updateSampleRates()
  211179. {
  211180. // find a list of sample rates..
  211181. const double possibleSampleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  211182. sampleRates.clear();
  211183. if (asioObject != 0)
  211184. {
  211185. for (int index = 0; index < numElementsInArray (possibleSampleRates); ++index)
  211186. {
  211187. const long err = asioObject->canSampleRate (possibleSampleRates[index]);
  211188. if (err == 0)
  211189. {
  211190. sampleRates.add ((int) possibleSampleRates[index]);
  211191. log ("rate: " + String ((int) possibleSampleRates[index]));
  211192. }
  211193. else if (err != ASE_NoClock)
  211194. {
  211195. logError ("CanSampleRate", err);
  211196. }
  211197. }
  211198. if (sampleRates.size() == 0)
  211199. {
  211200. double cr = 0;
  211201. const long err = asioObject->getSampleRate (&cr);
  211202. log ("No sample rates supported - current rate: " + String ((int) cr));
  211203. if (err == 0)
  211204. sampleRates.add ((int) cr);
  211205. }
  211206. }
  211207. }
  211208. const StringArray getOutputChannelNames()
  211209. {
  211210. return outputChannelNames;
  211211. }
  211212. const StringArray getInputChannelNames()
  211213. {
  211214. return inputChannelNames;
  211215. }
  211216. int getNumSampleRates()
  211217. {
  211218. return sampleRates.size();
  211219. }
  211220. double getSampleRate (int index)
  211221. {
  211222. return sampleRates [index];
  211223. }
  211224. int getNumBufferSizesAvailable()
  211225. {
  211226. return bufferSizes.size();
  211227. }
  211228. int getBufferSizeSamples (int index)
  211229. {
  211230. return bufferSizes [index];
  211231. }
  211232. int getDefaultBufferSize()
  211233. {
  211234. return preferredSize;
  211235. }
  211236. const String open (const BigInteger& inputChannels,
  211237. const BigInteger& outputChannels,
  211238. double sr,
  211239. int bufferSizeSamples)
  211240. {
  211241. close();
  211242. currentCallback = 0;
  211243. if (bufferSizeSamples <= 0)
  211244. shouldUsePreferredSize = true;
  211245. if (asioObject == 0 || ! isASIOOpen)
  211246. {
  211247. log ("Warning: device not open");
  211248. const String err (openDevice());
  211249. if (asioObject == 0 || ! isASIOOpen)
  211250. return err;
  211251. }
  211252. isStarted = false;
  211253. bufferIndex = -1;
  211254. long err = 0;
  211255. long newPreferredSize = 0;
  211256. // if the preferred size has just changed, assume it's a control panel thing and use it as the new value.
  211257. minSize = 0;
  211258. maxSize = 0;
  211259. newPreferredSize = 0;
  211260. granularity = 0;
  211261. if (asioObject->getBufferSize (&minSize, &maxSize, &newPreferredSize, &granularity) == 0)
  211262. {
  211263. if (preferredSize != 0 && newPreferredSize != 0 && newPreferredSize != preferredSize)
  211264. shouldUsePreferredSize = true;
  211265. preferredSize = newPreferredSize;
  211266. }
  211267. // unfortunate workaround for certain manufacturers whose drivers crash horribly if you make
  211268. // dynamic changes to the buffer size...
  211269. shouldUsePreferredSize = shouldUsePreferredSize
  211270. || getName().containsIgnoreCase ("Digidesign");
  211271. if (shouldUsePreferredSize)
  211272. {
  211273. log ("Using preferred size for buffer..");
  211274. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  211275. {
  211276. bufferSizeSamples = preferredSize;
  211277. }
  211278. else
  211279. {
  211280. bufferSizeSamples = 1024;
  211281. logError ("GetBufferSize1", err);
  211282. }
  211283. shouldUsePreferredSize = false;
  211284. }
  211285. int sampleRate = roundDoubleToInt (sr);
  211286. currentSampleRate = sampleRate;
  211287. currentBlockSizeSamples = bufferSizeSamples;
  211288. currentChansOut.clear();
  211289. currentChansIn.clear();
  211290. zeromem (inBuffers, sizeof (inBuffers));
  211291. zeromem (outBuffers, sizeof (outBuffers));
  211292. updateSampleRates();
  211293. if (sampleRate == 0 || (sampleRates.size() > 0 && ! sampleRates.contains (sampleRate)))
  211294. sampleRate = sampleRates[0];
  211295. jassert (sampleRate != 0);
  211296. if (sampleRate == 0)
  211297. sampleRate = 44100;
  211298. long numSources = 32;
  211299. ASIOClockSource clocks[32];
  211300. zeromem (clocks, sizeof (clocks));
  211301. asioObject->getClockSources (clocks, &numSources);
  211302. bool isSourceSet = false;
  211303. // careful not to remove this loop because it does more than just logging!
  211304. int i;
  211305. for (i = 0; i < numSources; ++i)
  211306. {
  211307. String s ("clock: ");
  211308. s += clocks[i].name;
  211309. if (clocks[i].isCurrentSource)
  211310. {
  211311. isSourceSet = true;
  211312. s << " (cur)";
  211313. }
  211314. log (s);
  211315. }
  211316. if (numSources > 1 && ! isSourceSet)
  211317. {
  211318. log ("setting clock source");
  211319. asioObject->setClockSource (clocks[0].index);
  211320. Thread::sleep (20);
  211321. }
  211322. else
  211323. {
  211324. if (numSources == 0)
  211325. {
  211326. log ("ASIO - no clock sources!");
  211327. }
  211328. }
  211329. double cr = 0;
  211330. err = asioObject->getSampleRate (&cr);
  211331. if (err == 0)
  211332. {
  211333. currentSampleRate = cr;
  211334. }
  211335. else
  211336. {
  211337. logError ("GetSampleRate", err);
  211338. currentSampleRate = 0;
  211339. }
  211340. error = String::empty;
  211341. needToReset = false;
  211342. isReSync = false;
  211343. err = 0;
  211344. bool buffersCreated = false;
  211345. if (currentSampleRate != sampleRate)
  211346. {
  211347. log ("ASIO samplerate: " + String (currentSampleRate) + " to " + String (sampleRate));
  211348. err = asioObject->setSampleRate (sampleRate);
  211349. if (err == ASE_NoClock && numSources > 0)
  211350. {
  211351. log ("trying to set a clock source..");
  211352. Thread::sleep (10);
  211353. err = asioObject->setClockSource (clocks[0].index);
  211354. if (err != 0)
  211355. {
  211356. logError ("SetClock", err);
  211357. }
  211358. Thread::sleep (10);
  211359. err = asioObject->setSampleRate (sampleRate);
  211360. }
  211361. }
  211362. if (err == 0)
  211363. {
  211364. currentSampleRate = sampleRate;
  211365. if (needToReset)
  211366. {
  211367. if (isReSync)
  211368. {
  211369. log ("Resync request");
  211370. }
  211371. log ("! Resetting ASIO after sample rate change");
  211372. removeCurrentDriver();
  211373. loadDriver();
  211374. const String error (initDriver());
  211375. if (error.isNotEmpty())
  211376. {
  211377. log ("ASIOInit: " + error);
  211378. }
  211379. needToReset = false;
  211380. isReSync = false;
  211381. }
  211382. numActiveInputChans = 0;
  211383. numActiveOutputChans = 0;
  211384. ASIOBufferInfo* info = bufferInfos;
  211385. int i;
  211386. for (i = 0; i < totalNumInputChans; ++i)
  211387. {
  211388. if (inputChannels[i])
  211389. {
  211390. currentChansIn.setBit (i);
  211391. info->isInput = 1;
  211392. info->channelNum = i;
  211393. info->buffers[0] = info->buffers[1] = 0;
  211394. ++info;
  211395. ++numActiveInputChans;
  211396. }
  211397. }
  211398. for (i = 0; i < totalNumOutputChans; ++i)
  211399. {
  211400. if (outputChannels[i])
  211401. {
  211402. currentChansOut.setBit (i);
  211403. info->isInput = 0;
  211404. info->channelNum = i;
  211405. info->buffers[0] = info->buffers[1] = 0;
  211406. ++info;
  211407. ++numActiveOutputChans;
  211408. }
  211409. }
  211410. const int totalBuffers = numActiveInputChans + numActiveOutputChans;
  211411. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  211412. if (currentASIODev[0] == this)
  211413. {
  211414. callbacks.bufferSwitch = &bufferSwitchCallback0;
  211415. callbacks.asioMessage = &asioMessagesCallback0;
  211416. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  211417. }
  211418. else if (currentASIODev[1] == this)
  211419. {
  211420. callbacks.bufferSwitch = &bufferSwitchCallback1;
  211421. callbacks.asioMessage = &asioMessagesCallback1;
  211422. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  211423. }
  211424. else if (currentASIODev[2] == this)
  211425. {
  211426. callbacks.bufferSwitch = &bufferSwitchCallback2;
  211427. callbacks.asioMessage = &asioMessagesCallback2;
  211428. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  211429. }
  211430. else
  211431. {
  211432. jassertfalse;
  211433. }
  211434. log ("disposing buffers");
  211435. err = asioObject->disposeBuffers();
  211436. log ("creating buffers: " + String (totalBuffers) + ", " + String (currentBlockSizeSamples));
  211437. err = asioObject->createBuffers (bufferInfos,
  211438. totalBuffers,
  211439. currentBlockSizeSamples,
  211440. &callbacks);
  211441. if (err != 0)
  211442. {
  211443. currentBlockSizeSamples = preferredSize;
  211444. logError ("create buffers 2", err);
  211445. asioObject->disposeBuffers();
  211446. err = asioObject->createBuffers (bufferInfos,
  211447. totalBuffers,
  211448. currentBlockSizeSamples,
  211449. &callbacks);
  211450. }
  211451. if (err == 0)
  211452. {
  211453. buffersCreated = true;
  211454. tempBuffer.calloc (totalBuffers * currentBlockSizeSamples + 32);
  211455. int n = 0;
  211456. Array <int> types;
  211457. currentBitDepth = 16;
  211458. for (i = 0; i < jmin ((int) totalNumInputChans, maxASIOChannels); ++i)
  211459. {
  211460. if (inputChannels[i])
  211461. {
  211462. inBuffers[n] = tempBuffer + (currentBlockSizeSamples * n);
  211463. ASIOChannelInfo channelInfo;
  211464. zerostruct (channelInfo);
  211465. channelInfo.channel = i;
  211466. channelInfo.isInput = 1;
  211467. asioObject->getChannelInfo (&channelInfo);
  211468. types.addIfNotAlreadyThere (channelInfo.type);
  211469. typeToFormatParameters (channelInfo.type,
  211470. inputChannelBitDepths[n],
  211471. inputChannelBytesPerSample[n],
  211472. inputChannelIsFloat[n],
  211473. inputChannelLittleEndian[n]);
  211474. currentBitDepth = jmax (currentBitDepth, inputChannelBitDepths[n]);
  211475. ++n;
  211476. }
  211477. }
  211478. jassert (numActiveInputChans == n);
  211479. n = 0;
  211480. for (i = 0; i < jmin ((int) totalNumOutputChans, maxASIOChannels); ++i)
  211481. {
  211482. if (outputChannels[i])
  211483. {
  211484. outBuffers[n] = tempBuffer + (currentBlockSizeSamples * (numActiveInputChans + n));
  211485. ASIOChannelInfo channelInfo;
  211486. zerostruct (channelInfo);
  211487. channelInfo.channel = i;
  211488. channelInfo.isInput = 0;
  211489. asioObject->getChannelInfo (&channelInfo);
  211490. types.addIfNotAlreadyThere (channelInfo.type);
  211491. typeToFormatParameters (channelInfo.type,
  211492. outputChannelBitDepths[n],
  211493. outputChannelBytesPerSample[n],
  211494. outputChannelIsFloat[n],
  211495. outputChannelLittleEndian[n]);
  211496. currentBitDepth = jmax (currentBitDepth, outputChannelBitDepths[n]);
  211497. ++n;
  211498. }
  211499. }
  211500. jassert (numActiveOutputChans == n);
  211501. for (i = types.size(); --i >= 0;)
  211502. {
  211503. log ("channel format: " + String (types[i]));
  211504. }
  211505. jassert (n <= totalBuffers);
  211506. for (i = 0; i < numActiveOutputChans; ++i)
  211507. {
  211508. const int size = currentBlockSizeSamples * (outputChannelBitDepths[i] >> 3);
  211509. if (bufferInfos [numActiveInputChans + i].buffers[0] == 0
  211510. || bufferInfos [numActiveInputChans + i].buffers[1] == 0)
  211511. {
  211512. log ("!! Null buffers");
  211513. }
  211514. else
  211515. {
  211516. zeromem (bufferInfos[numActiveInputChans + i].buffers[0], size);
  211517. zeromem (bufferInfos[numActiveInputChans + i].buffers[1], size);
  211518. }
  211519. }
  211520. inputLatency = outputLatency = 0;
  211521. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  211522. {
  211523. log ("ASIO - no latencies");
  211524. }
  211525. else
  211526. {
  211527. log ("ASIO latencies: " + String ((int) outputLatency) + ", " + String ((int) inputLatency));
  211528. }
  211529. isOpen_ = true;
  211530. log ("starting ASIO");
  211531. calledback = false;
  211532. err = asioObject->start();
  211533. if (err != 0)
  211534. {
  211535. isOpen_ = false;
  211536. log ("ASIO - stop on failure");
  211537. Thread::sleep (10);
  211538. asioObject->stop();
  211539. error = "Can't start device";
  211540. Thread::sleep (10);
  211541. }
  211542. else
  211543. {
  211544. int count = 300;
  211545. while (--count > 0 && ! calledback)
  211546. Thread::sleep (10);
  211547. isStarted = true;
  211548. if (! calledback)
  211549. {
  211550. error = "Device didn't start correctly";
  211551. log ("ASIO didn't callback - stopping..");
  211552. asioObject->stop();
  211553. }
  211554. }
  211555. }
  211556. else
  211557. {
  211558. error = "Can't create i/o buffers";
  211559. }
  211560. }
  211561. else
  211562. {
  211563. error = "Can't set sample rate: ";
  211564. error << sampleRate;
  211565. }
  211566. if (error.isNotEmpty())
  211567. {
  211568. logError (error, err);
  211569. if (asioObject != 0 && buffersCreated)
  211570. asioObject->disposeBuffers();
  211571. Thread::sleep (20);
  211572. isStarted = false;
  211573. isOpen_ = false;
  211574. const String errorCopy (error);
  211575. close(); // (this resets the error string)
  211576. error = errorCopy;
  211577. }
  211578. needToReset = false;
  211579. isReSync = false;
  211580. return error;
  211581. }
  211582. void close()
  211583. {
  211584. error = String::empty;
  211585. stopTimer();
  211586. stop();
  211587. if (isASIOOpen && isOpen_)
  211588. {
  211589. const ScopedLock sl (callbackLock);
  211590. isOpen_ = false;
  211591. isStarted = false;
  211592. needToReset = false;
  211593. isReSync = false;
  211594. log ("ASIO - stopping");
  211595. if (asioObject != 0)
  211596. {
  211597. Thread::sleep (20);
  211598. asioObject->stop();
  211599. Thread::sleep (10);
  211600. asioObject->disposeBuffers();
  211601. }
  211602. Thread::sleep (10);
  211603. }
  211604. }
  211605. bool isOpen()
  211606. {
  211607. return isOpen_ || insideControlPanelModalLoop;
  211608. }
  211609. int getCurrentBufferSizeSamples()
  211610. {
  211611. return currentBlockSizeSamples;
  211612. }
  211613. double getCurrentSampleRate()
  211614. {
  211615. return currentSampleRate;
  211616. }
  211617. const BigInteger getActiveOutputChannels() const
  211618. {
  211619. return currentChansOut;
  211620. }
  211621. const BigInteger getActiveInputChannels() const
  211622. {
  211623. return currentChansIn;
  211624. }
  211625. int getCurrentBitDepth()
  211626. {
  211627. return currentBitDepth;
  211628. }
  211629. int getOutputLatencyInSamples()
  211630. {
  211631. return outputLatency + currentBlockSizeSamples / 4;
  211632. }
  211633. int getInputLatencyInSamples()
  211634. {
  211635. return inputLatency + currentBlockSizeSamples / 4;
  211636. }
  211637. void start (AudioIODeviceCallback* callback)
  211638. {
  211639. if (callback != 0)
  211640. {
  211641. callback->audioDeviceAboutToStart (this);
  211642. const ScopedLock sl (callbackLock);
  211643. currentCallback = callback;
  211644. }
  211645. }
  211646. void stop()
  211647. {
  211648. AudioIODeviceCallback* const lastCallback = currentCallback;
  211649. {
  211650. const ScopedLock sl (callbackLock);
  211651. currentCallback = 0;
  211652. }
  211653. if (lastCallback != 0)
  211654. lastCallback->audioDeviceStopped();
  211655. }
  211656. bool isPlaying()
  211657. {
  211658. return isASIOOpen && (currentCallback != 0);
  211659. }
  211660. const String getLastError()
  211661. {
  211662. return error;
  211663. }
  211664. bool hasControlPanel() const
  211665. {
  211666. return true;
  211667. }
  211668. bool showControlPanel()
  211669. {
  211670. log ("ASIO - showing control panel");
  211671. Component modalWindow (String::empty);
  211672. modalWindow.setOpaque (true);
  211673. modalWindow.addToDesktop (0);
  211674. modalWindow.enterModalState();
  211675. bool done = false;
  211676. JUCE_TRY
  211677. {
  211678. // are there are devices that need to be closed before showing their control panel?
  211679. // close();
  211680. insideControlPanelModalLoop = true;
  211681. const uint32 started = Time::getMillisecondCounter();
  211682. if (asioObject != 0)
  211683. {
  211684. asioObject->controlPanel();
  211685. const int spent = (int) Time::getMillisecondCounter() - (int) started;
  211686. log ("spent: " + String (spent));
  211687. if (spent > 300)
  211688. {
  211689. shouldUsePreferredSize = true;
  211690. done = true;
  211691. }
  211692. }
  211693. }
  211694. JUCE_CATCH_ALL
  211695. insideControlPanelModalLoop = false;
  211696. return done;
  211697. }
  211698. void resetRequest() throw()
  211699. {
  211700. needToReset = true;
  211701. }
  211702. void resyncRequest() throw()
  211703. {
  211704. needToReset = true;
  211705. isReSync = true;
  211706. }
  211707. void timerCallback()
  211708. {
  211709. if (! insideControlPanelModalLoop)
  211710. {
  211711. stopTimer();
  211712. // used to cause a reset
  211713. log ("! ASIO restart request!");
  211714. if (isOpen_)
  211715. {
  211716. AudioIODeviceCallback* const oldCallback = currentCallback;
  211717. close();
  211718. open (BigInteger (currentChansIn), BigInteger (currentChansOut),
  211719. currentSampleRate, currentBlockSizeSamples);
  211720. if (oldCallback != 0)
  211721. start (oldCallback);
  211722. }
  211723. }
  211724. else
  211725. {
  211726. startTimer (100);
  211727. }
  211728. }
  211729. juce_UseDebuggingNewOperator
  211730. private:
  211731. IASIO* volatile asioObject;
  211732. ASIOCallbacks callbacks;
  211733. void* windowHandle;
  211734. CLSID classId;
  211735. const String optionalDllForDirectLoading;
  211736. String error;
  211737. long totalNumInputChans, totalNumOutputChans;
  211738. StringArray inputChannelNames, outputChannelNames;
  211739. Array<int> sampleRates, bufferSizes;
  211740. long inputLatency, outputLatency;
  211741. long minSize, maxSize, preferredSize, granularity;
  211742. int volatile currentBlockSizeSamples;
  211743. int volatile currentBitDepth;
  211744. double volatile currentSampleRate;
  211745. BigInteger currentChansOut, currentChansIn;
  211746. AudioIODeviceCallback* volatile currentCallback;
  211747. CriticalSection callbackLock;
  211748. ASIOBufferInfo bufferInfos [maxASIOChannels];
  211749. float* inBuffers [maxASIOChannels];
  211750. float* outBuffers [maxASIOChannels];
  211751. int inputChannelBitDepths [maxASIOChannels];
  211752. int outputChannelBitDepths [maxASIOChannels];
  211753. int inputChannelBytesPerSample [maxASIOChannels];
  211754. int outputChannelBytesPerSample [maxASIOChannels];
  211755. bool inputChannelIsFloat [maxASIOChannels];
  211756. bool outputChannelIsFloat [maxASIOChannels];
  211757. bool inputChannelLittleEndian [maxASIOChannels];
  211758. bool outputChannelLittleEndian [maxASIOChannels];
  211759. WaitableEvent event1;
  211760. HeapBlock <float> tempBuffer;
  211761. int volatile bufferIndex, numActiveInputChans, numActiveOutputChans;
  211762. bool isOpen_, isStarted;
  211763. bool volatile isASIOOpen;
  211764. bool volatile calledback;
  211765. bool volatile littleEndian, postOutput, needToReset, isReSync;
  211766. bool volatile insideControlPanelModalLoop;
  211767. bool volatile shouldUsePreferredSize;
  211768. void removeCurrentDriver()
  211769. {
  211770. if (asioObject != 0)
  211771. {
  211772. asioObject->Release();
  211773. asioObject = 0;
  211774. }
  211775. }
  211776. bool loadDriver()
  211777. {
  211778. removeCurrentDriver();
  211779. JUCE_TRY
  211780. {
  211781. if (CoCreateInstance (classId, 0, CLSCTX_INPROC_SERVER,
  211782. classId, (void**) &asioObject) == S_OK)
  211783. {
  211784. return true;
  211785. }
  211786. // If a class isn't registered but we have a path for it, we can fallback to
  211787. // doing a direct load of the COM object (only available via the juce_createASIOAudioIODeviceForGUID function).
  211788. if (optionalDllForDirectLoading.isNotEmpty())
  211789. {
  211790. HMODULE h = LoadLibrary (optionalDllForDirectLoading);
  211791. if (h != 0)
  211792. {
  211793. typedef HRESULT (CALLBACK* DllGetClassObjectFunc) (REFCLSID clsid, REFIID iid, LPVOID* ppv);
  211794. DllGetClassObjectFunc dllGetClassObject = (DllGetClassObjectFunc) GetProcAddress (h, "DllGetClassObject");
  211795. if (dllGetClassObject != 0)
  211796. {
  211797. IClassFactory* classFactory = 0;
  211798. HRESULT hr = dllGetClassObject (classId, IID_IClassFactory, (void**) &classFactory);
  211799. if (classFactory != 0)
  211800. {
  211801. hr = classFactory->CreateInstance (0, classId, (void**) &asioObject);
  211802. classFactory->Release();
  211803. }
  211804. return asioObject != 0;
  211805. }
  211806. }
  211807. }
  211808. }
  211809. JUCE_CATCH_ALL
  211810. asioObject = 0;
  211811. return false;
  211812. }
  211813. const String initDriver()
  211814. {
  211815. if (asioObject != 0)
  211816. {
  211817. char buffer [256];
  211818. zeromem (buffer, sizeof (buffer));
  211819. if (! asioObject->init (windowHandle))
  211820. {
  211821. asioObject->getErrorMessage (buffer);
  211822. return String (buffer, sizeof (buffer) - 1);
  211823. }
  211824. // just in case any daft drivers expect this to be called..
  211825. asioObject->getDriverName (buffer);
  211826. return String::empty;
  211827. }
  211828. return "No Driver";
  211829. }
  211830. const String openDevice()
  211831. {
  211832. // use this in case the driver starts opening dialog boxes..
  211833. Component modalWindow (String::empty);
  211834. modalWindow.setOpaque (true);
  211835. modalWindow.addToDesktop (0);
  211836. modalWindow.enterModalState();
  211837. // open the device and get its info..
  211838. log ("opening ASIO device: " + getName());
  211839. needToReset = false;
  211840. isReSync = false;
  211841. outputChannelNames.clear();
  211842. inputChannelNames.clear();
  211843. bufferSizes.clear();
  211844. sampleRates.clear();
  211845. isASIOOpen = false;
  211846. isOpen_ = false;
  211847. totalNumInputChans = 0;
  211848. totalNumOutputChans = 0;
  211849. numActiveInputChans = 0;
  211850. numActiveOutputChans = 0;
  211851. currentCallback = 0;
  211852. error = String::empty;
  211853. if (getName().isEmpty())
  211854. return error;
  211855. long err = 0;
  211856. if (loadDriver())
  211857. {
  211858. if ((error = initDriver()).isEmpty())
  211859. {
  211860. numActiveInputChans = 0;
  211861. numActiveOutputChans = 0;
  211862. totalNumInputChans = 0;
  211863. totalNumOutputChans = 0;
  211864. if (asioObject != 0
  211865. && (err = asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans)) == 0)
  211866. {
  211867. log (String ((int) totalNumInputChans) + " in, " + String ((int) totalNumOutputChans) + " out");
  211868. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  211869. {
  211870. // find a list of buffer sizes..
  211871. log (String ((int) minSize) + " " + String ((int) maxSize) + " " + String ((int) preferredSize) + " " + String ((int) granularity));
  211872. if (granularity >= 0)
  211873. {
  211874. granularity = jmax (1, (int) granularity);
  211875. for (int i = jmax ((int) minSize, (int) granularity); i < jmin (6400, (int) maxSize); i += granularity)
  211876. bufferSizes.addIfNotAlreadyThere (granularity * (i / granularity));
  211877. }
  211878. else if (granularity < 0)
  211879. {
  211880. for (int i = 0; i < 18; ++i)
  211881. {
  211882. const int s = (1 << i);
  211883. if (s >= minSize && s <= maxSize)
  211884. bufferSizes.add (s);
  211885. }
  211886. }
  211887. if (! bufferSizes.contains (preferredSize))
  211888. bufferSizes.insert (0, preferredSize);
  211889. double currentRate = 0;
  211890. asioObject->getSampleRate (&currentRate);
  211891. if (currentRate <= 0.0 || currentRate > 192001.0)
  211892. {
  211893. log ("setting sample rate");
  211894. err = asioObject->setSampleRate (44100.0);
  211895. if (err != 0)
  211896. {
  211897. logError ("setting sample rate", err);
  211898. }
  211899. asioObject->getSampleRate (&currentRate);
  211900. }
  211901. currentSampleRate = currentRate;
  211902. postOutput = (asioObject->outputReady() == 0);
  211903. if (postOutput)
  211904. {
  211905. log ("ASIO outputReady = ok");
  211906. }
  211907. updateSampleRates();
  211908. // ..because cubase does it at this point
  211909. inputLatency = outputLatency = 0;
  211910. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  211911. {
  211912. log ("ASIO - no latencies");
  211913. }
  211914. log ("latencies: " + String ((int) inputLatency) + ", " + String ((int) outputLatency));
  211915. // create some dummy buffers now.. because cubase does..
  211916. numActiveInputChans = 0;
  211917. numActiveOutputChans = 0;
  211918. ASIOBufferInfo* info = bufferInfos;
  211919. int i, numChans = 0;
  211920. for (i = 0; i < jmin (2, (int) totalNumInputChans); ++i)
  211921. {
  211922. info->isInput = 1;
  211923. info->channelNum = i;
  211924. info->buffers[0] = info->buffers[1] = 0;
  211925. ++info;
  211926. ++numChans;
  211927. }
  211928. const int outputBufferIndex = numChans;
  211929. for (i = 0; i < jmin (2, (int) totalNumOutputChans); ++i)
  211930. {
  211931. info->isInput = 0;
  211932. info->channelNum = i;
  211933. info->buffers[0] = info->buffers[1] = 0;
  211934. ++info;
  211935. ++numChans;
  211936. }
  211937. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  211938. if (currentASIODev[0] == this)
  211939. {
  211940. callbacks.bufferSwitch = &bufferSwitchCallback0;
  211941. callbacks.asioMessage = &asioMessagesCallback0;
  211942. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  211943. }
  211944. else if (currentASIODev[1] == this)
  211945. {
  211946. callbacks.bufferSwitch = &bufferSwitchCallback1;
  211947. callbacks.asioMessage = &asioMessagesCallback1;
  211948. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  211949. }
  211950. else if (currentASIODev[2] == this)
  211951. {
  211952. callbacks.bufferSwitch = &bufferSwitchCallback2;
  211953. callbacks.asioMessage = &asioMessagesCallback2;
  211954. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  211955. }
  211956. else
  211957. {
  211958. jassertfalse;
  211959. }
  211960. log ("creating buffers (dummy): " + String (numChans) + ", " + String ((int) preferredSize));
  211961. if (preferredSize > 0)
  211962. {
  211963. err = asioObject->createBuffers (bufferInfos, numChans, preferredSize, &callbacks);
  211964. if (err != 0)
  211965. {
  211966. logError ("dummy buffers", err);
  211967. }
  211968. }
  211969. long newInps = 0, newOuts = 0;
  211970. asioObject->getChannels (&newInps, &newOuts);
  211971. if (totalNumInputChans != newInps || totalNumOutputChans != newOuts)
  211972. {
  211973. totalNumInputChans = newInps;
  211974. totalNumOutputChans = newOuts;
  211975. log (String ((int) totalNumInputChans) + " in; " + String ((int) totalNumOutputChans) + " out");
  211976. }
  211977. updateSampleRates();
  211978. ASIOChannelInfo channelInfo;
  211979. channelInfo.type = 0;
  211980. for (i = 0; i < totalNumInputChans; ++i)
  211981. {
  211982. zerostruct (channelInfo);
  211983. channelInfo.channel = i;
  211984. channelInfo.isInput = 1;
  211985. asioObject->getChannelInfo (&channelInfo);
  211986. inputChannelNames.add (String (channelInfo.name));
  211987. }
  211988. for (i = 0; i < totalNumOutputChans; ++i)
  211989. {
  211990. zerostruct (channelInfo);
  211991. channelInfo.channel = i;
  211992. channelInfo.isInput = 0;
  211993. asioObject->getChannelInfo (&channelInfo);
  211994. outputChannelNames.add (String (channelInfo.name));
  211995. typeToFormatParameters (channelInfo.type,
  211996. outputChannelBitDepths[i],
  211997. outputChannelBytesPerSample[i],
  211998. outputChannelIsFloat[i],
  211999. outputChannelLittleEndian[i]);
  212000. if (i < 2)
  212001. {
  212002. // clear the channels that are used with the dummy stuff
  212003. const int bytesPerBuffer = preferredSize * (outputChannelBitDepths[i] >> 3);
  212004. zeromem (bufferInfos [outputBufferIndex + i].buffers[0], bytesPerBuffer);
  212005. zeromem (bufferInfos [outputBufferIndex + i].buffers[1], bytesPerBuffer);
  212006. }
  212007. }
  212008. outputChannelNames.trim();
  212009. inputChannelNames.trim();
  212010. outputChannelNames.appendNumbersToDuplicates (false, true);
  212011. inputChannelNames.appendNumbersToDuplicates (false, true);
  212012. // start and stop because cubase does it..
  212013. asioObject->getLatencies (&inputLatency, &outputLatency);
  212014. if ((err = asioObject->start()) != 0)
  212015. {
  212016. // ignore an error here, as it might start later after setting other stuff up
  212017. logError ("ASIO start", err);
  212018. }
  212019. Thread::sleep (100);
  212020. asioObject->stop();
  212021. }
  212022. else
  212023. {
  212024. error = "Can't detect buffer sizes";
  212025. }
  212026. }
  212027. else
  212028. {
  212029. error = "Can't detect asio channels";
  212030. }
  212031. }
  212032. }
  212033. else
  212034. {
  212035. error = "No such device";
  212036. }
  212037. if (error.isNotEmpty())
  212038. {
  212039. logError (error, err);
  212040. if (asioObject != 0)
  212041. asioObject->disposeBuffers();
  212042. removeCurrentDriver();
  212043. isASIOOpen = false;
  212044. }
  212045. else
  212046. {
  212047. isASIOOpen = true;
  212048. log ("ASIO device open");
  212049. }
  212050. isOpen_ = false;
  212051. needToReset = false;
  212052. isReSync = false;
  212053. return error;
  212054. }
  212055. void callback (const long index)
  212056. {
  212057. if (isStarted)
  212058. {
  212059. bufferIndex = index;
  212060. processBuffer();
  212061. }
  212062. else
  212063. {
  212064. if (postOutput && (asioObject != 0))
  212065. asioObject->outputReady();
  212066. }
  212067. calledback = true;
  212068. }
  212069. void processBuffer()
  212070. {
  212071. const ASIOBufferInfo* const infos = bufferInfos;
  212072. const int bi = bufferIndex;
  212073. const ScopedLock sl (callbackLock);
  212074. if (needToReset)
  212075. {
  212076. needToReset = false;
  212077. if (isReSync)
  212078. {
  212079. log ("! ASIO resync");
  212080. isReSync = false;
  212081. }
  212082. else
  212083. {
  212084. startTimer (20);
  212085. }
  212086. }
  212087. if (bi >= 0)
  212088. {
  212089. const int samps = currentBlockSizeSamples;
  212090. if (currentCallback != 0)
  212091. {
  212092. int i;
  212093. for (i = 0; i < numActiveInputChans; ++i)
  212094. {
  212095. float* const dst = inBuffers[i];
  212096. jassert (dst != 0);
  212097. const char* const src = (const char*) (infos[i].buffers[bi]);
  212098. if (inputChannelIsFloat[i])
  212099. {
  212100. memcpy (dst, src, samps * sizeof (float));
  212101. }
  212102. else
  212103. {
  212104. jassert (dst == tempBuffer + (samps * i));
  212105. switch (inputChannelBitDepths[i])
  212106. {
  212107. case 16:
  212108. convertInt16ToFloat (src, dst, inputChannelBytesPerSample[i],
  212109. samps, inputChannelLittleEndian[i]);
  212110. break;
  212111. case 24:
  212112. convertInt24ToFloat (src, dst, inputChannelBytesPerSample[i],
  212113. samps, inputChannelLittleEndian[i]);
  212114. break;
  212115. case 32:
  212116. convertInt32ToFloat (src, dst, inputChannelBytesPerSample[i],
  212117. samps, inputChannelLittleEndian[i]);
  212118. break;
  212119. case 64:
  212120. jassertfalse;
  212121. break;
  212122. }
  212123. }
  212124. }
  212125. currentCallback->audioDeviceIOCallback ((const float**) inBuffers,
  212126. numActiveInputChans,
  212127. outBuffers,
  212128. numActiveOutputChans,
  212129. samps);
  212130. for (i = 0; i < numActiveOutputChans; ++i)
  212131. {
  212132. float* const src = outBuffers[i];
  212133. jassert (src != 0);
  212134. char* const dst = (char*) (infos [numActiveInputChans + i].buffers[bi]);
  212135. if (outputChannelIsFloat[i])
  212136. {
  212137. memcpy (dst, src, samps * sizeof (float));
  212138. }
  212139. else
  212140. {
  212141. jassert (src == tempBuffer + (samps * (numActiveInputChans + i)));
  212142. switch (outputChannelBitDepths[i])
  212143. {
  212144. case 16:
  212145. convertFloatToInt16 (src, dst, outputChannelBytesPerSample[i],
  212146. samps, outputChannelLittleEndian[i]);
  212147. break;
  212148. case 24:
  212149. convertFloatToInt24 (src, dst, outputChannelBytesPerSample[i],
  212150. samps, outputChannelLittleEndian[i]);
  212151. break;
  212152. case 32:
  212153. convertFloatToInt32 (src, dst, outputChannelBytesPerSample[i],
  212154. samps, outputChannelLittleEndian[i]);
  212155. break;
  212156. case 64:
  212157. jassertfalse;
  212158. break;
  212159. }
  212160. }
  212161. }
  212162. }
  212163. else
  212164. {
  212165. for (int i = 0; i < numActiveOutputChans; ++i)
  212166. {
  212167. const int bytesPerBuffer = samps * (outputChannelBitDepths[i] >> 3);
  212168. zeromem (infos[numActiveInputChans + i].buffers[bi], bytesPerBuffer);
  212169. }
  212170. }
  212171. }
  212172. if (postOutput)
  212173. asioObject->outputReady();
  212174. }
  212175. static ASIOTime* bufferSwitchTimeInfoCallback0 (ASIOTime*, long index, long)
  212176. {
  212177. if (currentASIODev[0] != 0)
  212178. currentASIODev[0]->callback (index);
  212179. return 0;
  212180. }
  212181. static ASIOTime* bufferSwitchTimeInfoCallback1 (ASIOTime*, long index, long)
  212182. {
  212183. if (currentASIODev[1] != 0)
  212184. currentASIODev[1]->callback (index);
  212185. return 0;
  212186. }
  212187. static ASIOTime* bufferSwitchTimeInfoCallback2 (ASIOTime*, long index, long)
  212188. {
  212189. if (currentASIODev[2] != 0)
  212190. currentASIODev[2]->callback (index);
  212191. return 0;
  212192. }
  212193. static void bufferSwitchCallback0 (long index, long)
  212194. {
  212195. if (currentASIODev[0] != 0)
  212196. currentASIODev[0]->callback (index);
  212197. }
  212198. static void bufferSwitchCallback1 (long index, long)
  212199. {
  212200. if (currentASIODev[1] != 0)
  212201. currentASIODev[1]->callback (index);
  212202. }
  212203. static void bufferSwitchCallback2 (long index, long)
  212204. {
  212205. if (currentASIODev[2] != 0)
  212206. currentASIODev[2]->callback (index);
  212207. }
  212208. static long asioMessagesCallback0 (long selector, long value, void*, double*)
  212209. {
  212210. return asioMessagesCallback (selector, value, 0);
  212211. }
  212212. static long asioMessagesCallback1 (long selector, long value, void*, double*)
  212213. {
  212214. return asioMessagesCallback (selector, value, 1);
  212215. }
  212216. static long asioMessagesCallback2 (long selector, long value, void*, double*)
  212217. {
  212218. return asioMessagesCallback (selector, value, 2);
  212219. }
  212220. static long asioMessagesCallback (long selector, long value, const int deviceIndex)
  212221. {
  212222. switch (selector)
  212223. {
  212224. case kAsioSelectorSupported:
  212225. if (value == kAsioResetRequest
  212226. || value == kAsioEngineVersion
  212227. || value == kAsioResyncRequest
  212228. || value == kAsioLatenciesChanged
  212229. || value == kAsioSupportsInputMonitor)
  212230. return 1;
  212231. break;
  212232. case kAsioBufferSizeChange:
  212233. break;
  212234. case kAsioResetRequest:
  212235. if (currentASIODev[deviceIndex] != 0)
  212236. currentASIODev[deviceIndex]->resetRequest();
  212237. return 1;
  212238. case kAsioResyncRequest:
  212239. if (currentASIODev[deviceIndex] != 0)
  212240. currentASIODev[deviceIndex]->resyncRequest();
  212241. return 1;
  212242. case kAsioLatenciesChanged:
  212243. return 1;
  212244. case kAsioEngineVersion:
  212245. return 2;
  212246. case kAsioSupportsTimeInfo:
  212247. case kAsioSupportsTimeCode:
  212248. return 0;
  212249. }
  212250. return 0;
  212251. }
  212252. static void sampleRateChangedCallback (ASIOSampleRate) throw()
  212253. {
  212254. }
  212255. static void convertInt16ToFloat (const char* src,
  212256. float* dest,
  212257. const int srcStrideBytes,
  212258. int numSamples,
  212259. const bool littleEndian) throw()
  212260. {
  212261. const double g = 1.0 / 32768.0;
  212262. if (littleEndian)
  212263. {
  212264. while (--numSamples >= 0)
  212265. {
  212266. *dest++ = (float) (g * (short) ByteOrder::littleEndianShort (src));
  212267. src += srcStrideBytes;
  212268. }
  212269. }
  212270. else
  212271. {
  212272. while (--numSamples >= 0)
  212273. {
  212274. *dest++ = (float) (g * (short) ByteOrder::bigEndianShort (src));
  212275. src += srcStrideBytes;
  212276. }
  212277. }
  212278. }
  212279. static void convertFloatToInt16 (const float* src,
  212280. char* dest,
  212281. const int dstStrideBytes,
  212282. int numSamples,
  212283. const bool littleEndian) throw()
  212284. {
  212285. const double maxVal = (double) 0x7fff;
  212286. if (littleEndian)
  212287. {
  212288. while (--numSamples >= 0)
  212289. {
  212290. *(uint16*) dest = ByteOrder::swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  212291. dest += dstStrideBytes;
  212292. }
  212293. }
  212294. else
  212295. {
  212296. while (--numSamples >= 0)
  212297. {
  212298. *(uint16*) dest = ByteOrder::swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  212299. dest += dstStrideBytes;
  212300. }
  212301. }
  212302. }
  212303. static void convertInt24ToFloat (const char* src,
  212304. float* dest,
  212305. const int srcStrideBytes,
  212306. int numSamples,
  212307. const bool littleEndian) throw()
  212308. {
  212309. const double g = 1.0 / 0x7fffff;
  212310. if (littleEndian)
  212311. {
  212312. while (--numSamples >= 0)
  212313. {
  212314. *dest++ = (float) (g * ByteOrder::littleEndian24Bit (src));
  212315. src += srcStrideBytes;
  212316. }
  212317. }
  212318. else
  212319. {
  212320. while (--numSamples >= 0)
  212321. {
  212322. *dest++ = (float) (g * ByteOrder::bigEndian24Bit (src));
  212323. src += srcStrideBytes;
  212324. }
  212325. }
  212326. }
  212327. static void convertFloatToInt24 (const float* src,
  212328. char* dest,
  212329. const int dstStrideBytes,
  212330. int numSamples,
  212331. const bool littleEndian) throw()
  212332. {
  212333. const double maxVal = (double) 0x7fffff;
  212334. if (littleEndian)
  212335. {
  212336. while (--numSamples >= 0)
  212337. {
  212338. ByteOrder::littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  212339. dest += dstStrideBytes;
  212340. }
  212341. }
  212342. else
  212343. {
  212344. while (--numSamples >= 0)
  212345. {
  212346. ByteOrder::bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  212347. dest += dstStrideBytes;
  212348. }
  212349. }
  212350. }
  212351. static void convertInt32ToFloat (const char* src,
  212352. float* dest,
  212353. const int srcStrideBytes,
  212354. int numSamples,
  212355. const bool littleEndian) throw()
  212356. {
  212357. const double g = 1.0 / 0x7fffffff;
  212358. if (littleEndian)
  212359. {
  212360. while (--numSamples >= 0)
  212361. {
  212362. *dest++ = (float) (g * (int) ByteOrder::littleEndianInt (src));
  212363. src += srcStrideBytes;
  212364. }
  212365. }
  212366. else
  212367. {
  212368. while (--numSamples >= 0)
  212369. {
  212370. *dest++ = (float) (g * (int) ByteOrder::bigEndianInt (src));
  212371. src += srcStrideBytes;
  212372. }
  212373. }
  212374. }
  212375. static void convertFloatToInt32 (const float* src,
  212376. char* dest,
  212377. const int dstStrideBytes,
  212378. int numSamples,
  212379. const bool littleEndian) throw()
  212380. {
  212381. const double maxVal = (double) 0x7fffffff;
  212382. if (littleEndian)
  212383. {
  212384. while (--numSamples >= 0)
  212385. {
  212386. *(uint32*) dest = ByteOrder::swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  212387. dest += dstStrideBytes;
  212388. }
  212389. }
  212390. else
  212391. {
  212392. while (--numSamples >= 0)
  212393. {
  212394. *(uint32*) dest = ByteOrder::swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  212395. dest += dstStrideBytes;
  212396. }
  212397. }
  212398. }
  212399. static void typeToFormatParameters (const long type,
  212400. int& bitDepth,
  212401. int& byteStride,
  212402. bool& formatIsFloat,
  212403. bool& littleEndian) throw()
  212404. {
  212405. bitDepth = 0;
  212406. littleEndian = false;
  212407. formatIsFloat = false;
  212408. switch (type)
  212409. {
  212410. case ASIOSTInt16MSB:
  212411. case ASIOSTInt16LSB:
  212412. case ASIOSTInt32MSB16:
  212413. case ASIOSTInt32LSB16:
  212414. bitDepth = 16; break;
  212415. case ASIOSTFloat32MSB:
  212416. case ASIOSTFloat32LSB:
  212417. formatIsFloat = true;
  212418. bitDepth = 32; break;
  212419. case ASIOSTInt32MSB:
  212420. case ASIOSTInt32LSB:
  212421. bitDepth = 32; break;
  212422. case ASIOSTInt24MSB:
  212423. case ASIOSTInt24LSB:
  212424. case ASIOSTInt32MSB24:
  212425. case ASIOSTInt32LSB24:
  212426. case ASIOSTInt32MSB18:
  212427. case ASIOSTInt32MSB20:
  212428. case ASIOSTInt32LSB18:
  212429. case ASIOSTInt32LSB20:
  212430. bitDepth = 24; break;
  212431. case ASIOSTFloat64MSB:
  212432. case ASIOSTFloat64LSB:
  212433. default:
  212434. bitDepth = 64;
  212435. break;
  212436. }
  212437. switch (type)
  212438. {
  212439. case ASIOSTInt16MSB:
  212440. case ASIOSTInt32MSB16:
  212441. case ASIOSTFloat32MSB:
  212442. case ASIOSTFloat64MSB:
  212443. case ASIOSTInt32MSB:
  212444. case ASIOSTInt32MSB18:
  212445. case ASIOSTInt32MSB20:
  212446. case ASIOSTInt32MSB24:
  212447. case ASIOSTInt24MSB:
  212448. littleEndian = false; break;
  212449. case ASIOSTInt16LSB:
  212450. case ASIOSTInt32LSB16:
  212451. case ASIOSTFloat32LSB:
  212452. case ASIOSTFloat64LSB:
  212453. case ASIOSTInt32LSB:
  212454. case ASIOSTInt32LSB18:
  212455. case ASIOSTInt32LSB20:
  212456. case ASIOSTInt32LSB24:
  212457. case ASIOSTInt24LSB:
  212458. littleEndian = true; break;
  212459. default:
  212460. break;
  212461. }
  212462. switch (type)
  212463. {
  212464. case ASIOSTInt16LSB:
  212465. case ASIOSTInt16MSB:
  212466. byteStride = 2; break;
  212467. case ASIOSTInt24LSB:
  212468. case ASIOSTInt24MSB:
  212469. byteStride = 3; break;
  212470. case ASIOSTInt32MSB16:
  212471. case ASIOSTInt32LSB16:
  212472. case ASIOSTInt32MSB:
  212473. case ASIOSTInt32MSB18:
  212474. case ASIOSTInt32MSB20:
  212475. case ASIOSTInt32MSB24:
  212476. case ASIOSTInt32LSB:
  212477. case ASIOSTInt32LSB18:
  212478. case ASIOSTInt32LSB20:
  212479. case ASIOSTInt32LSB24:
  212480. case ASIOSTFloat32LSB:
  212481. case ASIOSTFloat32MSB:
  212482. byteStride = 4; break;
  212483. case ASIOSTFloat64MSB:
  212484. case ASIOSTFloat64LSB:
  212485. byteStride = 8; break;
  212486. default:
  212487. break;
  212488. }
  212489. }
  212490. };
  212491. class ASIOAudioIODeviceType : public AudioIODeviceType
  212492. {
  212493. public:
  212494. ASIOAudioIODeviceType()
  212495. : AudioIODeviceType ("ASIO"),
  212496. hasScanned (false)
  212497. {
  212498. CoInitialize (0);
  212499. }
  212500. ~ASIOAudioIODeviceType()
  212501. {
  212502. }
  212503. void scanForDevices()
  212504. {
  212505. hasScanned = true;
  212506. deviceNames.clear();
  212507. classIds.clear();
  212508. HKEY hk = 0;
  212509. int index = 0;
  212510. if (RegOpenKeyA (HKEY_LOCAL_MACHINE, "software\\asio", &hk) == ERROR_SUCCESS)
  212511. {
  212512. for (;;)
  212513. {
  212514. char name [256];
  212515. if (RegEnumKeyA (hk, index++, name, 256) == ERROR_SUCCESS)
  212516. {
  212517. addDriverInfo (name, hk);
  212518. }
  212519. else
  212520. {
  212521. break;
  212522. }
  212523. }
  212524. RegCloseKey (hk);
  212525. }
  212526. }
  212527. const StringArray getDeviceNames (bool /*wantInputNames*/) const
  212528. {
  212529. jassert (hasScanned); // need to call scanForDevices() before doing this
  212530. return deviceNames;
  212531. }
  212532. int getDefaultDeviceIndex (bool) const
  212533. {
  212534. jassert (hasScanned); // need to call scanForDevices() before doing this
  212535. for (int i = deviceNames.size(); --i >= 0;)
  212536. if (deviceNames[i].containsIgnoreCase ("asio4all"))
  212537. return i; // asio4all is a safe choice for a default..
  212538. #if JUCE_DEBUG
  212539. if (deviceNames.size() > 1 && deviceNames[0].containsIgnoreCase ("digidesign"))
  212540. return 1; // (the digi m-box driver crashes the app when you run
  212541. // it in the debugger, which can be a bit annoying)
  212542. #endif
  212543. return 0;
  212544. }
  212545. static int findFreeSlot()
  212546. {
  212547. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  212548. if (currentASIODev[i] == 0)
  212549. return i;
  212550. jassertfalse; // unfortunately you can only have a finite number
  212551. // of ASIO devices open at the same time..
  212552. return -1;
  212553. }
  212554. int getIndexOfDevice (AudioIODevice* d, bool /*asInput*/) const
  212555. {
  212556. jassert (hasScanned); // need to call scanForDevices() before doing this
  212557. return d == 0 ? -1 : deviceNames.indexOf (d->getName());
  212558. }
  212559. bool hasSeparateInputsAndOutputs() const { return false; }
  212560. AudioIODevice* createDevice (const String& outputDeviceName,
  212561. const String& inputDeviceName)
  212562. {
  212563. // ASIO can't open two different devices for input and output - they must be the same one.
  212564. jassert (inputDeviceName == outputDeviceName || outputDeviceName.isEmpty() || inputDeviceName.isEmpty());
  212565. jassert (hasScanned); // need to call scanForDevices() before doing this
  212566. const int index = deviceNames.indexOf (outputDeviceName.isNotEmpty() ? outputDeviceName
  212567. : inputDeviceName);
  212568. if (index >= 0)
  212569. {
  212570. const int freeSlot = findFreeSlot();
  212571. if (freeSlot >= 0)
  212572. return new ASIOAudioIODevice (outputDeviceName, *(classIds [index]), freeSlot, String::empty);
  212573. }
  212574. return 0;
  212575. }
  212576. juce_UseDebuggingNewOperator
  212577. private:
  212578. StringArray deviceNames;
  212579. OwnedArray <CLSID> classIds;
  212580. bool hasScanned;
  212581. static bool checkClassIsOk (const String& classId)
  212582. {
  212583. HKEY hk = 0;
  212584. bool ok = false;
  212585. if (RegOpenKey (HKEY_CLASSES_ROOT, _T("clsid"), &hk) == ERROR_SUCCESS)
  212586. {
  212587. int index = 0;
  212588. for (;;)
  212589. {
  212590. WCHAR buf [512];
  212591. if (RegEnumKey (hk, index++, buf, 512) == ERROR_SUCCESS)
  212592. {
  212593. if (classId.equalsIgnoreCase (buf))
  212594. {
  212595. HKEY subKey, pathKey;
  212596. if (RegOpenKeyEx (hk, buf, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  212597. {
  212598. if (RegOpenKeyEx (subKey, _T("InprocServer32"), 0, KEY_READ, &pathKey) == ERROR_SUCCESS)
  212599. {
  212600. WCHAR pathName [1024];
  212601. DWORD dtype = REG_SZ;
  212602. DWORD dsize = sizeof (pathName);
  212603. if (RegQueryValueEx (pathKey, 0, 0, &dtype, (LPBYTE) pathName, &dsize) == ERROR_SUCCESS)
  212604. ok = File (pathName).exists();
  212605. RegCloseKey (pathKey);
  212606. }
  212607. RegCloseKey (subKey);
  212608. }
  212609. break;
  212610. }
  212611. }
  212612. else
  212613. {
  212614. break;
  212615. }
  212616. }
  212617. RegCloseKey (hk);
  212618. }
  212619. return ok;
  212620. }
  212621. void addDriverInfo (const String& keyName, HKEY hk)
  212622. {
  212623. HKEY subKey;
  212624. if (RegOpenKeyEx (hk, keyName, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  212625. {
  212626. WCHAR buf [256];
  212627. zerostruct (buf);
  212628. DWORD dtype = REG_SZ;
  212629. DWORD dsize = sizeof (buf);
  212630. if (RegQueryValueEx (subKey, _T("clsid"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  212631. {
  212632. if (dsize > 0 && checkClassIsOk (buf))
  212633. {
  212634. CLSID classId;
  212635. if (CLSIDFromString ((LPOLESTR) buf, &classId) == S_OK)
  212636. {
  212637. dtype = REG_SZ;
  212638. dsize = sizeof (buf);
  212639. String deviceName;
  212640. if (RegQueryValueEx (subKey, _T("description"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  212641. deviceName = buf;
  212642. else
  212643. deviceName = keyName;
  212644. log ("found " + deviceName);
  212645. deviceNames.add (deviceName);
  212646. classIds.add (new CLSID (classId));
  212647. }
  212648. }
  212649. RegCloseKey (subKey);
  212650. }
  212651. }
  212652. }
  212653. ASIOAudioIODeviceType (const ASIOAudioIODeviceType&);
  212654. ASIOAudioIODeviceType& operator= (const ASIOAudioIODeviceType&);
  212655. };
  212656. AudioIODeviceType* juce_createAudioIODeviceType_ASIO()
  212657. {
  212658. return new ASIOAudioIODeviceType();
  212659. }
  212660. AudioIODevice* juce_createASIOAudioIODeviceForGUID (const String& name,
  212661. void* guid,
  212662. const String& optionalDllForDirectLoading)
  212663. {
  212664. const int freeSlot = ASIOAudioIODeviceType::findFreeSlot();
  212665. if (freeSlot < 0)
  212666. return 0;
  212667. return new ASIOAudioIODevice (name, *(CLSID*) guid, freeSlot, optionalDllForDirectLoading);
  212668. }
  212669. #undef log
  212670. #endif
  212671. /*** End of inlined file: juce_win32_ASIO.cpp ***/
  212672. /*** Start of inlined file: juce_win32_DirectSound.cpp ***/
  212673. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  212674. // compiled on its own).
  212675. #if JUCE_INCLUDED_FILE && JUCE_DIRECTSOUND
  212676. END_JUCE_NAMESPACE
  212677. extern "C"
  212678. {
  212679. // Declare just the minimum number of interfaces for the DSound objects that we need..
  212680. typedef struct typeDSBUFFERDESC
  212681. {
  212682. DWORD dwSize;
  212683. DWORD dwFlags;
  212684. DWORD dwBufferBytes;
  212685. DWORD dwReserved;
  212686. LPWAVEFORMATEX lpwfxFormat;
  212687. GUID guid3DAlgorithm;
  212688. } DSBUFFERDESC;
  212689. struct IDirectSoundBuffer;
  212690. #undef INTERFACE
  212691. #define INTERFACE IDirectSound
  212692. DECLARE_INTERFACE_(IDirectSound, IUnknown)
  212693. {
  212694. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  212695. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  212696. STDMETHOD_(ULONG,Release) (THIS) PURE;
  212697. STDMETHOD(CreateSoundBuffer) (THIS_ DSBUFFERDESC*, IDirectSoundBuffer**, LPUNKNOWN) PURE;
  212698. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  212699. STDMETHOD(DuplicateSoundBuffer) (THIS_ IDirectSoundBuffer*, IDirectSoundBuffer**) PURE;
  212700. STDMETHOD(SetCooperativeLevel) (THIS_ HWND, DWORD) PURE;
  212701. STDMETHOD(Compact) (THIS) PURE;
  212702. STDMETHOD(GetSpeakerConfig) (THIS_ LPDWORD) PURE;
  212703. STDMETHOD(SetSpeakerConfig) (THIS_ DWORD) PURE;
  212704. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  212705. };
  212706. #undef INTERFACE
  212707. #define INTERFACE IDirectSoundBuffer
  212708. DECLARE_INTERFACE_(IDirectSoundBuffer, IUnknown)
  212709. {
  212710. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  212711. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  212712. STDMETHOD_(ULONG,Release) (THIS) PURE;
  212713. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  212714. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  212715. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  212716. STDMETHOD(GetVolume) (THIS_ LPLONG) PURE;
  212717. STDMETHOD(GetPan) (THIS_ LPLONG) PURE;
  212718. STDMETHOD(GetFrequency) (THIS_ LPDWORD) PURE;
  212719. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  212720. STDMETHOD(Initialize) (THIS_ IDirectSound*, DSBUFFERDESC*) PURE;
  212721. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  212722. STDMETHOD(Play) (THIS_ DWORD, DWORD, DWORD) PURE;
  212723. STDMETHOD(SetCurrentPosition) (THIS_ DWORD) PURE;
  212724. STDMETHOD(SetFormat) (THIS_ const WAVEFORMATEX*) PURE;
  212725. STDMETHOD(SetVolume) (THIS_ LONG) PURE;
  212726. STDMETHOD(SetPan) (THIS_ LONG) PURE;
  212727. STDMETHOD(SetFrequency) (THIS_ DWORD) PURE;
  212728. STDMETHOD(Stop) (THIS) PURE;
  212729. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  212730. STDMETHOD(Restore) (THIS) PURE;
  212731. };
  212732. typedef struct typeDSCBUFFERDESC
  212733. {
  212734. DWORD dwSize;
  212735. DWORD dwFlags;
  212736. DWORD dwBufferBytes;
  212737. DWORD dwReserved;
  212738. LPWAVEFORMATEX lpwfxFormat;
  212739. } DSCBUFFERDESC;
  212740. struct IDirectSoundCaptureBuffer;
  212741. #undef INTERFACE
  212742. #define INTERFACE IDirectSoundCapture
  212743. DECLARE_INTERFACE_(IDirectSoundCapture, IUnknown)
  212744. {
  212745. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  212746. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  212747. STDMETHOD_(ULONG,Release) (THIS) PURE;
  212748. STDMETHOD(CreateCaptureBuffer) (THIS_ DSCBUFFERDESC*, IDirectSoundCaptureBuffer**, LPUNKNOWN) PURE;
  212749. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  212750. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  212751. };
  212752. #undef INTERFACE
  212753. #define INTERFACE IDirectSoundCaptureBuffer
  212754. DECLARE_INTERFACE_(IDirectSoundCaptureBuffer, IUnknown)
  212755. {
  212756. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  212757. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  212758. STDMETHOD_(ULONG,Release) (THIS) PURE;
  212759. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  212760. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  212761. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  212762. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  212763. STDMETHOD(Initialize) (THIS_ IDirectSoundCapture*, DSCBUFFERDESC*) PURE;
  212764. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  212765. STDMETHOD(Start) (THIS_ DWORD) PURE;
  212766. STDMETHOD(Stop) (THIS) PURE;
  212767. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  212768. };
  212769. };
  212770. BEGIN_JUCE_NAMESPACE
  212771. static const String getDSErrorMessage (HRESULT hr)
  212772. {
  212773. const char* result = 0;
  212774. switch (hr)
  212775. {
  212776. case MAKE_HRESULT(1, 0x878, 10): result = "Device already allocated"; break;
  212777. case MAKE_HRESULT(1, 0x878, 30): result = "Control unavailable"; break;
  212778. case E_INVALIDARG: result = "Invalid parameter"; break;
  212779. case MAKE_HRESULT(1, 0x878, 50): result = "Invalid call"; break;
  212780. case E_FAIL: result = "Generic error"; break;
  212781. case MAKE_HRESULT(1, 0x878, 70): result = "Priority level error"; break;
  212782. case E_OUTOFMEMORY: result = "Out of memory"; break;
  212783. case MAKE_HRESULT(1, 0x878, 100): result = "Bad format"; break;
  212784. case E_NOTIMPL: result = "Unsupported function"; break;
  212785. case MAKE_HRESULT(1, 0x878, 120): result = "No driver"; break;
  212786. case MAKE_HRESULT(1, 0x878, 130): result = "Already initialised"; break;
  212787. case CLASS_E_NOAGGREGATION: result = "No aggregation"; break;
  212788. case MAKE_HRESULT(1, 0x878, 150): result = "Buffer lost"; break;
  212789. case MAKE_HRESULT(1, 0x878, 160): result = "Another app has priority"; break;
  212790. case MAKE_HRESULT(1, 0x878, 170): result = "Uninitialised"; break;
  212791. case E_NOINTERFACE: result = "No interface"; break;
  212792. case S_OK: result = "No error"; break;
  212793. default: return "Unknown error: " + String ((int) hr);
  212794. }
  212795. return result;
  212796. }
  212797. #define DS_DEBUGGING 1
  212798. #ifdef DS_DEBUGGING
  212799. #define CATCH JUCE_CATCH_EXCEPTION
  212800. #undef log
  212801. #define log(a) Logger::writeToLog(a);
  212802. #undef logError
  212803. #define logError(a) logDSError(a, __LINE__);
  212804. static void logDSError (HRESULT hr, int lineNum)
  212805. {
  212806. if (hr != S_OK)
  212807. {
  212808. String error ("DS error at line ");
  212809. error << lineNum << " - " << getDSErrorMessage (hr);
  212810. log (error);
  212811. }
  212812. }
  212813. #else
  212814. #define CATCH JUCE_CATCH_ALL
  212815. #define log(a)
  212816. #define logError(a)
  212817. #endif
  212818. #define DSOUND_FUNCTION(functionName, params) \
  212819. typedef HRESULT (WINAPI *type##functionName) params; \
  212820. static type##functionName ds##functionName = 0;
  212821. #define DSOUND_FUNCTION_LOAD(functionName) \
  212822. ds##functionName = (type##functionName) GetProcAddress (h, #functionName); \
  212823. jassert (ds##functionName != 0);
  212824. typedef BOOL (CALLBACK *LPDSENUMCALLBACKW) (LPGUID, LPCWSTR, LPCWSTR, LPVOID);
  212825. typedef BOOL (CALLBACK *LPDSENUMCALLBACKA) (LPGUID, LPCSTR, LPCSTR, LPVOID);
  212826. DSOUND_FUNCTION (DirectSoundCreate, (const GUID*, IDirectSound**, LPUNKNOWN))
  212827. DSOUND_FUNCTION (DirectSoundCaptureCreate, (const GUID*, IDirectSoundCapture**, LPUNKNOWN))
  212828. DSOUND_FUNCTION (DirectSoundEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  212829. DSOUND_FUNCTION (DirectSoundCaptureEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  212830. static void initialiseDSoundFunctions()
  212831. {
  212832. if (dsDirectSoundCreate == 0)
  212833. {
  212834. HMODULE h = LoadLibraryA ("dsound.dll");
  212835. DSOUND_FUNCTION_LOAD (DirectSoundCreate)
  212836. DSOUND_FUNCTION_LOAD (DirectSoundCaptureCreate)
  212837. DSOUND_FUNCTION_LOAD (DirectSoundEnumerateW)
  212838. DSOUND_FUNCTION_LOAD (DirectSoundCaptureEnumerateW)
  212839. }
  212840. }
  212841. class DSoundInternalOutChannel
  212842. {
  212843. String name;
  212844. LPGUID guid;
  212845. int sampleRate, bufferSizeSamples;
  212846. float* leftBuffer;
  212847. float* rightBuffer;
  212848. IDirectSound* pDirectSound;
  212849. IDirectSoundBuffer* pOutputBuffer;
  212850. DWORD writeOffset;
  212851. int totalBytesPerBuffer;
  212852. int bytesPerBuffer;
  212853. unsigned int lastPlayCursor;
  212854. public:
  212855. int bitDepth;
  212856. bool doneFlag;
  212857. DSoundInternalOutChannel (const String& name_,
  212858. LPGUID guid_,
  212859. int rate,
  212860. int bufferSize,
  212861. float* left,
  212862. float* right)
  212863. : name (name_),
  212864. guid (guid_),
  212865. sampleRate (rate),
  212866. bufferSizeSamples (bufferSize),
  212867. leftBuffer (left),
  212868. rightBuffer (right),
  212869. pDirectSound (0),
  212870. pOutputBuffer (0),
  212871. bitDepth (16)
  212872. {
  212873. }
  212874. ~DSoundInternalOutChannel()
  212875. {
  212876. close();
  212877. }
  212878. void close()
  212879. {
  212880. HRESULT hr;
  212881. if (pOutputBuffer != 0)
  212882. {
  212883. JUCE_TRY
  212884. {
  212885. log ("closing dsound out: " + name);
  212886. hr = pOutputBuffer->Stop();
  212887. logError (hr);
  212888. }
  212889. CATCH
  212890. JUCE_TRY
  212891. {
  212892. hr = pOutputBuffer->Release();
  212893. logError (hr);
  212894. }
  212895. CATCH
  212896. pOutputBuffer = 0;
  212897. }
  212898. if (pDirectSound != 0)
  212899. {
  212900. JUCE_TRY
  212901. {
  212902. hr = pDirectSound->Release();
  212903. logError (hr);
  212904. }
  212905. CATCH
  212906. pDirectSound = 0;
  212907. }
  212908. }
  212909. const String open()
  212910. {
  212911. log ("opening dsound out device: " + name + " rate=" + String (sampleRate)
  212912. + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  212913. pDirectSound = 0;
  212914. pOutputBuffer = 0;
  212915. writeOffset = 0;
  212916. String error;
  212917. HRESULT hr = E_NOINTERFACE;
  212918. if (dsDirectSoundCreate != 0)
  212919. hr = dsDirectSoundCreate (guid, &pDirectSound, 0);
  212920. if (hr == S_OK)
  212921. {
  212922. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  212923. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  212924. const int numChannels = 2;
  212925. hr = pDirectSound->SetCooperativeLevel (GetDesktopWindow(), 2 /* DSSCL_PRIORITY */);
  212926. logError (hr);
  212927. if (hr == S_OK)
  212928. {
  212929. IDirectSoundBuffer* pPrimaryBuffer;
  212930. DSBUFFERDESC primaryDesc;
  212931. zerostruct (primaryDesc);
  212932. primaryDesc.dwSize = sizeof (DSBUFFERDESC);
  212933. primaryDesc.dwFlags = 1 /* DSBCAPS_PRIMARYBUFFER */;
  212934. primaryDesc.dwBufferBytes = 0;
  212935. primaryDesc.lpwfxFormat = 0;
  212936. log ("opening dsound out step 2");
  212937. hr = pDirectSound->CreateSoundBuffer (&primaryDesc, &pPrimaryBuffer, 0);
  212938. logError (hr);
  212939. if (hr == S_OK)
  212940. {
  212941. WAVEFORMATEX wfFormat;
  212942. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  212943. wfFormat.nChannels = (unsigned short) numChannels;
  212944. wfFormat.nSamplesPerSec = sampleRate;
  212945. wfFormat.wBitsPerSample = (unsigned short) bitDepth;
  212946. wfFormat.nBlockAlign = (unsigned short) (wfFormat.nChannels * wfFormat.wBitsPerSample / 8);
  212947. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  212948. wfFormat.cbSize = 0;
  212949. hr = pPrimaryBuffer->SetFormat (&wfFormat);
  212950. logError (hr);
  212951. if (hr == S_OK)
  212952. {
  212953. DSBUFFERDESC secondaryDesc;
  212954. zerostruct (secondaryDesc);
  212955. secondaryDesc.dwSize = sizeof (DSBUFFERDESC);
  212956. secondaryDesc.dwFlags = 0x8000 /* DSBCAPS_GLOBALFOCUS */
  212957. | 0x10000 /* DSBCAPS_GETCURRENTPOSITION2 */;
  212958. secondaryDesc.dwBufferBytes = totalBytesPerBuffer;
  212959. secondaryDesc.lpwfxFormat = &wfFormat;
  212960. hr = pDirectSound->CreateSoundBuffer (&secondaryDesc, &pOutputBuffer, 0);
  212961. logError (hr);
  212962. if (hr == S_OK)
  212963. {
  212964. log ("opening dsound out step 3");
  212965. DWORD dwDataLen;
  212966. unsigned char* pDSBuffData;
  212967. hr = pOutputBuffer->Lock (0, totalBytesPerBuffer,
  212968. (LPVOID*) &pDSBuffData, &dwDataLen, 0, 0, 0);
  212969. logError (hr);
  212970. if (hr == S_OK)
  212971. {
  212972. zeromem (pDSBuffData, dwDataLen);
  212973. hr = pOutputBuffer->Unlock (pDSBuffData, dwDataLen, 0, 0);
  212974. if (hr == S_OK)
  212975. {
  212976. hr = pOutputBuffer->SetCurrentPosition (0);
  212977. if (hr == S_OK)
  212978. {
  212979. hr = pOutputBuffer->Play (0, 0, 1 /* DSBPLAY_LOOPING */);
  212980. if (hr == S_OK)
  212981. return String::empty;
  212982. }
  212983. }
  212984. }
  212985. }
  212986. }
  212987. }
  212988. }
  212989. }
  212990. error = getDSErrorMessage (hr);
  212991. close();
  212992. return error;
  212993. }
  212994. void synchronisePosition()
  212995. {
  212996. if (pOutputBuffer != 0)
  212997. {
  212998. DWORD playCursor;
  212999. pOutputBuffer->GetCurrentPosition (&playCursor, &writeOffset);
  213000. }
  213001. }
  213002. bool service()
  213003. {
  213004. if (pOutputBuffer == 0)
  213005. return true;
  213006. DWORD playCursor, writeCursor;
  213007. for (;;)
  213008. {
  213009. HRESULT hr = pOutputBuffer->GetCurrentPosition (&playCursor, &writeCursor);
  213010. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  213011. {
  213012. pOutputBuffer->Restore();
  213013. continue;
  213014. }
  213015. if (hr == S_OK)
  213016. break;
  213017. logError (hr);
  213018. jassertfalse;
  213019. return true;
  213020. }
  213021. int playWriteGap = writeCursor - playCursor;
  213022. if (playWriteGap < 0)
  213023. playWriteGap += totalBytesPerBuffer;
  213024. int bytesEmpty = playCursor - writeOffset;
  213025. if (bytesEmpty < 0)
  213026. bytesEmpty += totalBytesPerBuffer;
  213027. if (bytesEmpty > (totalBytesPerBuffer - playWriteGap))
  213028. {
  213029. writeOffset = writeCursor;
  213030. bytesEmpty = totalBytesPerBuffer - playWriteGap;
  213031. }
  213032. if (bytesEmpty >= bytesPerBuffer)
  213033. {
  213034. LPBYTE lpbuf1 = 0;
  213035. LPBYTE lpbuf2 = 0;
  213036. DWORD dwSize1 = 0;
  213037. DWORD dwSize2 = 0;
  213038. HRESULT hr = pOutputBuffer->Lock (writeOffset,
  213039. bytesPerBuffer,
  213040. (void**) &lpbuf1, &dwSize1,
  213041. (void**) &lpbuf2, &dwSize2, 0);
  213042. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  213043. {
  213044. pOutputBuffer->Restore();
  213045. hr = pOutputBuffer->Lock (writeOffset,
  213046. bytesPerBuffer,
  213047. (void**) &lpbuf1, &dwSize1,
  213048. (void**) &lpbuf2, &dwSize2, 0);
  213049. }
  213050. if (hr == S_OK)
  213051. {
  213052. if (bitDepth == 16)
  213053. {
  213054. const float gainL = 32767.0f;
  213055. const float gainR = 32767.0f;
  213056. int* dest = (int*)lpbuf1;
  213057. const float* left = leftBuffer;
  213058. const float* right = rightBuffer;
  213059. int samples1 = dwSize1 >> 2;
  213060. int samples2 = dwSize2 >> 2;
  213061. if (left == 0)
  213062. {
  213063. while (--samples1 >= 0)
  213064. {
  213065. int r = roundToInt (gainR * *right++);
  213066. if (r < -32768)
  213067. r = -32768;
  213068. else if (r > 32767)
  213069. r = 32767;
  213070. *dest++ = (r << 16);
  213071. }
  213072. dest = (int*)lpbuf2;
  213073. while (--samples2 >= 0)
  213074. {
  213075. int r = roundToInt (gainR * *right++);
  213076. if (r < -32768)
  213077. r = -32768;
  213078. else if (r > 32767)
  213079. r = 32767;
  213080. *dest++ = (r << 16);
  213081. }
  213082. }
  213083. else if (right == 0)
  213084. {
  213085. while (--samples1 >= 0)
  213086. {
  213087. int l = roundToInt (gainL * *left++);
  213088. if (l < -32768)
  213089. l = -32768;
  213090. else if (l > 32767)
  213091. l = 32767;
  213092. l &= 0xffff;
  213093. *dest++ = l;
  213094. }
  213095. dest = (int*)lpbuf2;
  213096. while (--samples2 >= 0)
  213097. {
  213098. int l = roundToInt (gainL * *left++);
  213099. if (l < -32768)
  213100. l = -32768;
  213101. else if (l > 32767)
  213102. l = 32767;
  213103. l &= 0xffff;
  213104. *dest++ = l;
  213105. }
  213106. }
  213107. else
  213108. {
  213109. while (--samples1 >= 0)
  213110. {
  213111. int l = roundToInt (gainL * *left++);
  213112. if (l < -32768)
  213113. l = -32768;
  213114. else if (l > 32767)
  213115. l = 32767;
  213116. l &= 0xffff;
  213117. int r = roundToInt (gainR * *right++);
  213118. if (r < -32768)
  213119. r = -32768;
  213120. else if (r > 32767)
  213121. r = 32767;
  213122. *dest++ = (r << 16) | l;
  213123. }
  213124. dest = (int*)lpbuf2;
  213125. while (--samples2 >= 0)
  213126. {
  213127. int l = roundToInt (gainL * *left++);
  213128. if (l < -32768)
  213129. l = -32768;
  213130. else if (l > 32767)
  213131. l = 32767;
  213132. l &= 0xffff;
  213133. int r = roundToInt (gainR * *right++);
  213134. if (r < -32768)
  213135. r = -32768;
  213136. else if (r > 32767)
  213137. r = 32767;
  213138. *dest++ = (r << 16) | l;
  213139. }
  213140. }
  213141. }
  213142. else
  213143. {
  213144. jassertfalse;
  213145. }
  213146. writeOffset = (writeOffset + dwSize1 + dwSize2) % totalBytesPerBuffer;
  213147. pOutputBuffer->Unlock (lpbuf1, dwSize1, lpbuf2, dwSize2);
  213148. }
  213149. else
  213150. {
  213151. jassertfalse;
  213152. logError (hr);
  213153. }
  213154. bytesEmpty -= bytesPerBuffer;
  213155. return true;
  213156. }
  213157. else
  213158. {
  213159. return false;
  213160. }
  213161. }
  213162. };
  213163. struct DSoundInternalInChannel
  213164. {
  213165. String name;
  213166. LPGUID guid;
  213167. int sampleRate, bufferSizeSamples;
  213168. float* leftBuffer;
  213169. float* rightBuffer;
  213170. IDirectSound* pDirectSound;
  213171. IDirectSoundCapture* pDirectSoundCapture;
  213172. IDirectSoundCaptureBuffer* pInputBuffer;
  213173. public:
  213174. unsigned int readOffset;
  213175. int bytesPerBuffer, totalBytesPerBuffer;
  213176. int bitDepth;
  213177. bool doneFlag;
  213178. DSoundInternalInChannel (const String& name_,
  213179. LPGUID guid_,
  213180. int rate,
  213181. int bufferSize,
  213182. float* left,
  213183. float* right)
  213184. : name (name_),
  213185. guid (guid_),
  213186. sampleRate (rate),
  213187. bufferSizeSamples (bufferSize),
  213188. leftBuffer (left),
  213189. rightBuffer (right),
  213190. pDirectSound (0),
  213191. pDirectSoundCapture (0),
  213192. pInputBuffer (0),
  213193. bitDepth (16)
  213194. {
  213195. }
  213196. ~DSoundInternalInChannel()
  213197. {
  213198. close();
  213199. }
  213200. void close()
  213201. {
  213202. HRESULT hr;
  213203. if (pInputBuffer != 0)
  213204. {
  213205. JUCE_TRY
  213206. {
  213207. log ("closing dsound in: " + name);
  213208. hr = pInputBuffer->Stop();
  213209. logError (hr);
  213210. }
  213211. CATCH
  213212. JUCE_TRY
  213213. {
  213214. hr = pInputBuffer->Release();
  213215. logError (hr);
  213216. }
  213217. CATCH
  213218. pInputBuffer = 0;
  213219. }
  213220. if (pDirectSoundCapture != 0)
  213221. {
  213222. JUCE_TRY
  213223. {
  213224. hr = pDirectSoundCapture->Release();
  213225. logError (hr);
  213226. }
  213227. CATCH
  213228. pDirectSoundCapture = 0;
  213229. }
  213230. if (pDirectSound != 0)
  213231. {
  213232. JUCE_TRY
  213233. {
  213234. hr = pDirectSound->Release();
  213235. logError (hr);
  213236. }
  213237. CATCH
  213238. pDirectSound = 0;
  213239. }
  213240. }
  213241. const String open()
  213242. {
  213243. log ("opening dsound in device: " + name
  213244. + " rate=" + String (sampleRate) + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  213245. pDirectSound = 0;
  213246. pDirectSoundCapture = 0;
  213247. pInputBuffer = 0;
  213248. readOffset = 0;
  213249. totalBytesPerBuffer = 0;
  213250. String error;
  213251. HRESULT hr = E_NOINTERFACE;
  213252. if (dsDirectSoundCaptureCreate != 0)
  213253. hr = dsDirectSoundCaptureCreate (guid, &pDirectSoundCapture, 0);
  213254. logError (hr);
  213255. if (hr == S_OK)
  213256. {
  213257. const int numChannels = 2;
  213258. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  213259. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  213260. WAVEFORMATEX wfFormat;
  213261. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  213262. wfFormat.nChannels = (unsigned short)numChannels;
  213263. wfFormat.nSamplesPerSec = sampleRate;
  213264. wfFormat.wBitsPerSample = (unsigned short)bitDepth;
  213265. wfFormat.nBlockAlign = (unsigned short)(wfFormat.nChannels * (wfFormat.wBitsPerSample / 8));
  213266. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  213267. wfFormat.cbSize = 0;
  213268. DSCBUFFERDESC captureDesc;
  213269. zerostruct (captureDesc);
  213270. captureDesc.dwSize = sizeof (DSCBUFFERDESC);
  213271. captureDesc.dwFlags = 0;
  213272. captureDesc.dwBufferBytes = totalBytesPerBuffer;
  213273. captureDesc.lpwfxFormat = &wfFormat;
  213274. log ("opening dsound in step 2");
  213275. hr = pDirectSoundCapture->CreateCaptureBuffer (&captureDesc, &pInputBuffer, 0);
  213276. logError (hr);
  213277. if (hr == S_OK)
  213278. {
  213279. hr = pInputBuffer->Start (1 /* DSCBSTART_LOOPING */);
  213280. logError (hr);
  213281. if (hr == S_OK)
  213282. return String::empty;
  213283. }
  213284. }
  213285. error = getDSErrorMessage (hr);
  213286. close();
  213287. return error;
  213288. }
  213289. void synchronisePosition()
  213290. {
  213291. if (pInputBuffer != 0)
  213292. {
  213293. DWORD capturePos;
  213294. pInputBuffer->GetCurrentPosition (&capturePos, (DWORD*)&readOffset);
  213295. }
  213296. }
  213297. bool service()
  213298. {
  213299. if (pInputBuffer == 0)
  213300. return true;
  213301. DWORD capturePos, readPos;
  213302. HRESULT hr = pInputBuffer->GetCurrentPosition (&capturePos, &readPos);
  213303. logError (hr);
  213304. if (hr != S_OK)
  213305. return true;
  213306. int bytesFilled = readPos - readOffset;
  213307. if (bytesFilled < 0)
  213308. bytesFilled += totalBytesPerBuffer;
  213309. if (bytesFilled >= bytesPerBuffer)
  213310. {
  213311. LPBYTE lpbuf1 = 0;
  213312. LPBYTE lpbuf2 = 0;
  213313. DWORD dwsize1 = 0;
  213314. DWORD dwsize2 = 0;
  213315. HRESULT hr = pInputBuffer->Lock (readOffset,
  213316. bytesPerBuffer,
  213317. (void**) &lpbuf1, &dwsize1,
  213318. (void**) &lpbuf2, &dwsize2, 0);
  213319. if (hr == S_OK)
  213320. {
  213321. if (bitDepth == 16)
  213322. {
  213323. const float g = 1.0f / 32768.0f;
  213324. float* destL = leftBuffer;
  213325. float* destR = rightBuffer;
  213326. int samples1 = dwsize1 >> 2;
  213327. int samples2 = dwsize2 >> 2;
  213328. const short* src = (const short*)lpbuf1;
  213329. if (destL == 0)
  213330. {
  213331. while (--samples1 >= 0)
  213332. {
  213333. ++src;
  213334. *destR++ = *src++ * g;
  213335. }
  213336. src = (const short*)lpbuf2;
  213337. while (--samples2 >= 0)
  213338. {
  213339. ++src;
  213340. *destR++ = *src++ * g;
  213341. }
  213342. }
  213343. else if (destR == 0)
  213344. {
  213345. while (--samples1 >= 0)
  213346. {
  213347. *destL++ = *src++ * g;
  213348. ++src;
  213349. }
  213350. src = (const short*)lpbuf2;
  213351. while (--samples2 >= 0)
  213352. {
  213353. *destL++ = *src++ * g;
  213354. ++src;
  213355. }
  213356. }
  213357. else
  213358. {
  213359. while (--samples1 >= 0)
  213360. {
  213361. *destL++ = *src++ * g;
  213362. *destR++ = *src++ * g;
  213363. }
  213364. src = (const short*)lpbuf2;
  213365. while (--samples2 >= 0)
  213366. {
  213367. *destL++ = *src++ * g;
  213368. *destR++ = *src++ * g;
  213369. }
  213370. }
  213371. }
  213372. else
  213373. {
  213374. jassertfalse;
  213375. }
  213376. readOffset = (readOffset + dwsize1 + dwsize2) % totalBytesPerBuffer;
  213377. pInputBuffer->Unlock (lpbuf1, dwsize1, lpbuf2, dwsize2);
  213378. }
  213379. else
  213380. {
  213381. logError (hr);
  213382. jassertfalse;
  213383. }
  213384. bytesFilled -= bytesPerBuffer;
  213385. return true;
  213386. }
  213387. else
  213388. {
  213389. return false;
  213390. }
  213391. }
  213392. };
  213393. class DSoundAudioIODevice : public AudioIODevice,
  213394. public Thread
  213395. {
  213396. public:
  213397. DSoundAudioIODevice (const String& deviceName,
  213398. const int outputDeviceIndex_,
  213399. const int inputDeviceIndex_)
  213400. : AudioIODevice (deviceName, "DirectSound"),
  213401. Thread ("Juce DSound"),
  213402. isOpen_ (false),
  213403. isStarted (false),
  213404. outputDeviceIndex (outputDeviceIndex_),
  213405. inputDeviceIndex (inputDeviceIndex_),
  213406. totalSamplesOut (0),
  213407. sampleRate (0.0),
  213408. inputBuffers (1, 1),
  213409. outputBuffers (1, 1),
  213410. callback (0),
  213411. bufferSizeSamples (0)
  213412. {
  213413. if (outputDeviceIndex_ >= 0)
  213414. {
  213415. outChannels.add (TRANS("Left"));
  213416. outChannels.add (TRANS("Right"));
  213417. }
  213418. if (inputDeviceIndex_ >= 0)
  213419. {
  213420. inChannels.add (TRANS("Left"));
  213421. inChannels.add (TRANS("Right"));
  213422. }
  213423. }
  213424. ~DSoundAudioIODevice()
  213425. {
  213426. close();
  213427. }
  213428. const StringArray getOutputChannelNames()
  213429. {
  213430. return outChannels;
  213431. }
  213432. const StringArray getInputChannelNames()
  213433. {
  213434. return inChannels;
  213435. }
  213436. int getNumSampleRates()
  213437. {
  213438. return 4;
  213439. }
  213440. double getSampleRate (int index)
  213441. {
  213442. const double samps[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  213443. return samps [jlimit (0, 3, index)];
  213444. }
  213445. int getNumBufferSizesAvailable()
  213446. {
  213447. return 50;
  213448. }
  213449. int getBufferSizeSamples (int index)
  213450. {
  213451. int n = 64;
  213452. for (int i = 0; i < index; ++i)
  213453. n += (n < 512) ? 32
  213454. : ((n < 1024) ? 64
  213455. : ((n < 2048) ? 128 : 256));
  213456. return n;
  213457. }
  213458. int getDefaultBufferSize()
  213459. {
  213460. return 2560;
  213461. }
  213462. const String open (const BigInteger& inputChannels,
  213463. const BigInteger& outputChannels,
  213464. double sampleRate,
  213465. int bufferSizeSamples)
  213466. {
  213467. lastError = openDevice (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  213468. isOpen_ = lastError.isEmpty();
  213469. return lastError;
  213470. }
  213471. void close()
  213472. {
  213473. stop();
  213474. if (isOpen_)
  213475. {
  213476. closeDevice();
  213477. isOpen_ = false;
  213478. }
  213479. }
  213480. bool isOpen()
  213481. {
  213482. return isOpen_ && isThreadRunning();
  213483. }
  213484. int getCurrentBufferSizeSamples()
  213485. {
  213486. return bufferSizeSamples;
  213487. }
  213488. double getCurrentSampleRate()
  213489. {
  213490. return sampleRate;
  213491. }
  213492. int getCurrentBitDepth()
  213493. {
  213494. int i, bits = 256;
  213495. for (i = inChans.size(); --i >= 0;)
  213496. bits = jmin (bits, inChans[i]->bitDepth);
  213497. for (i = outChans.size(); --i >= 0;)
  213498. bits = jmin (bits, outChans[i]->bitDepth);
  213499. if (bits > 32)
  213500. bits = 16;
  213501. return bits;
  213502. }
  213503. const BigInteger getActiveOutputChannels() const
  213504. {
  213505. return enabledOutputs;
  213506. }
  213507. const BigInteger getActiveInputChannels() const
  213508. {
  213509. return enabledInputs;
  213510. }
  213511. int getOutputLatencyInSamples()
  213512. {
  213513. return (int) (getCurrentBufferSizeSamples() * 1.5);
  213514. }
  213515. int getInputLatencyInSamples()
  213516. {
  213517. return getOutputLatencyInSamples();
  213518. }
  213519. void start (AudioIODeviceCallback* call)
  213520. {
  213521. if (isOpen_ && call != 0 && ! isStarted)
  213522. {
  213523. if (! isThreadRunning())
  213524. {
  213525. // something gone wrong and the thread's stopped..
  213526. isOpen_ = false;
  213527. return;
  213528. }
  213529. call->audioDeviceAboutToStart (this);
  213530. const ScopedLock sl (startStopLock);
  213531. callback = call;
  213532. isStarted = true;
  213533. }
  213534. }
  213535. void stop()
  213536. {
  213537. if (isStarted)
  213538. {
  213539. AudioIODeviceCallback* const callbackLocal = callback;
  213540. {
  213541. const ScopedLock sl (startStopLock);
  213542. isStarted = false;
  213543. }
  213544. if (callbackLocal != 0)
  213545. callbackLocal->audioDeviceStopped();
  213546. }
  213547. }
  213548. bool isPlaying()
  213549. {
  213550. return isStarted && isOpen_ && isThreadRunning();
  213551. }
  213552. const String getLastError()
  213553. {
  213554. return lastError;
  213555. }
  213556. juce_UseDebuggingNewOperator
  213557. StringArray inChannels, outChannels;
  213558. int outputDeviceIndex, inputDeviceIndex;
  213559. private:
  213560. bool isOpen_;
  213561. bool isStarted;
  213562. String lastError;
  213563. OwnedArray <DSoundInternalInChannel> inChans;
  213564. OwnedArray <DSoundInternalOutChannel> outChans;
  213565. WaitableEvent startEvent;
  213566. int bufferSizeSamples;
  213567. int volatile totalSamplesOut;
  213568. int64 volatile lastBlockTime;
  213569. double sampleRate;
  213570. BigInteger enabledInputs, enabledOutputs;
  213571. AudioSampleBuffer inputBuffers, outputBuffers;
  213572. AudioIODeviceCallback* callback;
  213573. CriticalSection startStopLock;
  213574. DSoundAudioIODevice (const DSoundAudioIODevice&);
  213575. DSoundAudioIODevice& operator= (const DSoundAudioIODevice&);
  213576. const String openDevice (const BigInteger& inputChannels,
  213577. const BigInteger& outputChannels,
  213578. double sampleRate_,
  213579. int bufferSizeSamples_);
  213580. void closeDevice()
  213581. {
  213582. isStarted = false;
  213583. stopThread (5000);
  213584. inChans.clear();
  213585. outChans.clear();
  213586. inputBuffers.setSize (1, 1);
  213587. outputBuffers.setSize (1, 1);
  213588. }
  213589. void resync()
  213590. {
  213591. if (! threadShouldExit())
  213592. {
  213593. sleep (5);
  213594. int i;
  213595. for (i = 0; i < outChans.size(); ++i)
  213596. outChans.getUnchecked(i)->synchronisePosition();
  213597. for (i = 0; i < inChans.size(); ++i)
  213598. inChans.getUnchecked(i)->synchronisePosition();
  213599. }
  213600. }
  213601. public:
  213602. void run()
  213603. {
  213604. while (! threadShouldExit())
  213605. {
  213606. if (wait (100))
  213607. break;
  213608. }
  213609. const int latencyMs = (int) (bufferSizeSamples * 1000.0 / sampleRate);
  213610. const int maxTimeMS = jmax (5, 3 * latencyMs);
  213611. while (! threadShouldExit())
  213612. {
  213613. int numToDo = 0;
  213614. uint32 startTime = Time::getMillisecondCounter();
  213615. int i;
  213616. for (i = inChans.size(); --i >= 0;)
  213617. {
  213618. inChans.getUnchecked(i)->doneFlag = false;
  213619. ++numToDo;
  213620. }
  213621. for (i = outChans.size(); --i >= 0;)
  213622. {
  213623. outChans.getUnchecked(i)->doneFlag = false;
  213624. ++numToDo;
  213625. }
  213626. if (numToDo > 0)
  213627. {
  213628. const int maxCount = 3;
  213629. int count = maxCount;
  213630. for (;;)
  213631. {
  213632. for (i = inChans.size(); --i >= 0;)
  213633. {
  213634. DSoundInternalInChannel* const in = inChans.getUnchecked(i);
  213635. if ((! in->doneFlag) && in->service())
  213636. {
  213637. in->doneFlag = true;
  213638. --numToDo;
  213639. }
  213640. }
  213641. for (i = outChans.size(); --i >= 0;)
  213642. {
  213643. DSoundInternalOutChannel* const out = outChans.getUnchecked(i);
  213644. if ((! out->doneFlag) && out->service())
  213645. {
  213646. out->doneFlag = true;
  213647. --numToDo;
  213648. }
  213649. }
  213650. if (numToDo <= 0)
  213651. break;
  213652. if (Time::getMillisecondCounter() > startTime + maxTimeMS)
  213653. {
  213654. resync();
  213655. break;
  213656. }
  213657. if (--count <= 0)
  213658. {
  213659. Sleep (1);
  213660. count = maxCount;
  213661. }
  213662. if (threadShouldExit())
  213663. return;
  213664. }
  213665. }
  213666. else
  213667. {
  213668. sleep (1);
  213669. }
  213670. const ScopedLock sl (startStopLock);
  213671. if (isStarted)
  213672. {
  213673. JUCE_TRY
  213674. {
  213675. callback->audioDeviceIOCallback (const_cast <const float**> (inputBuffers.getArrayOfChannels()),
  213676. inputBuffers.getNumChannels(),
  213677. outputBuffers.getArrayOfChannels(),
  213678. outputBuffers.getNumChannels(),
  213679. bufferSizeSamples);
  213680. }
  213681. JUCE_CATCH_EXCEPTION
  213682. totalSamplesOut += bufferSizeSamples;
  213683. }
  213684. else
  213685. {
  213686. outputBuffers.clear();
  213687. totalSamplesOut = 0;
  213688. sleep (1);
  213689. }
  213690. }
  213691. }
  213692. };
  213693. class DSoundAudioIODeviceType : public AudioIODeviceType
  213694. {
  213695. public:
  213696. DSoundAudioIODeviceType()
  213697. : AudioIODeviceType ("DirectSound"),
  213698. hasScanned (false)
  213699. {
  213700. initialiseDSoundFunctions();
  213701. }
  213702. ~DSoundAudioIODeviceType()
  213703. {
  213704. }
  213705. void scanForDevices()
  213706. {
  213707. hasScanned = true;
  213708. outputDeviceNames.clear();
  213709. outputGuids.clear();
  213710. inputDeviceNames.clear();
  213711. inputGuids.clear();
  213712. if (dsDirectSoundEnumerateW != 0)
  213713. {
  213714. dsDirectSoundEnumerateW (outputEnumProcW, this);
  213715. dsDirectSoundCaptureEnumerateW (inputEnumProcW, this);
  213716. }
  213717. }
  213718. const StringArray getDeviceNames (bool wantInputNames) const
  213719. {
  213720. jassert (hasScanned); // need to call scanForDevices() before doing this
  213721. return wantInputNames ? inputDeviceNames
  213722. : outputDeviceNames;
  213723. }
  213724. int getDefaultDeviceIndex (bool /*forInput*/) const
  213725. {
  213726. jassert (hasScanned); // need to call scanForDevices() before doing this
  213727. return 0;
  213728. }
  213729. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  213730. {
  213731. jassert (hasScanned); // need to call scanForDevices() before doing this
  213732. DSoundAudioIODevice* const d = dynamic_cast <DSoundAudioIODevice*> (device);
  213733. if (d == 0)
  213734. return -1;
  213735. return asInput ? d->inputDeviceIndex
  213736. : d->outputDeviceIndex;
  213737. }
  213738. bool hasSeparateInputsAndOutputs() const { return true; }
  213739. AudioIODevice* createDevice (const String& outputDeviceName,
  213740. const String& inputDeviceName)
  213741. {
  213742. jassert (hasScanned); // need to call scanForDevices() before doing this
  213743. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  213744. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  213745. if (outputIndex >= 0 || inputIndex >= 0)
  213746. return new DSoundAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  213747. : inputDeviceName,
  213748. outputIndex, inputIndex);
  213749. return 0;
  213750. }
  213751. juce_UseDebuggingNewOperator
  213752. StringArray outputDeviceNames;
  213753. OwnedArray <GUID> outputGuids;
  213754. StringArray inputDeviceNames;
  213755. OwnedArray <GUID> inputGuids;
  213756. private:
  213757. bool hasScanned;
  213758. BOOL outputEnumProc (LPGUID lpGUID, String desc)
  213759. {
  213760. desc = desc.trim();
  213761. if (desc.isNotEmpty())
  213762. {
  213763. const String origDesc (desc);
  213764. int n = 2;
  213765. while (outputDeviceNames.contains (desc))
  213766. desc = origDesc + " (" + String (n++) + ")";
  213767. outputDeviceNames.add (desc);
  213768. if (lpGUID != 0)
  213769. outputGuids.add (new GUID (*lpGUID));
  213770. else
  213771. outputGuids.add (0);
  213772. }
  213773. return TRUE;
  213774. }
  213775. static BOOL CALLBACK outputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  213776. {
  213777. return ((DSoundAudioIODeviceType*) object)
  213778. ->outputEnumProc (lpGUID, String (description));
  213779. }
  213780. static BOOL CALLBACK outputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  213781. {
  213782. return ((DSoundAudioIODeviceType*) object)
  213783. ->outputEnumProc (lpGUID, String (description));
  213784. }
  213785. BOOL CALLBACK inputEnumProc (LPGUID lpGUID, String desc)
  213786. {
  213787. desc = desc.trim();
  213788. if (desc.isNotEmpty())
  213789. {
  213790. const String origDesc (desc);
  213791. int n = 2;
  213792. while (inputDeviceNames.contains (desc))
  213793. desc = origDesc + " (" + String (n++) + ")";
  213794. inputDeviceNames.add (desc);
  213795. if (lpGUID != 0)
  213796. inputGuids.add (new GUID (*lpGUID));
  213797. else
  213798. inputGuids.add (0);
  213799. }
  213800. return TRUE;
  213801. }
  213802. static BOOL CALLBACK inputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  213803. {
  213804. return ((DSoundAudioIODeviceType*) object)
  213805. ->inputEnumProc (lpGUID, String (description));
  213806. }
  213807. static BOOL CALLBACK inputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  213808. {
  213809. return ((DSoundAudioIODeviceType*) object)
  213810. ->inputEnumProc (lpGUID, String (description));
  213811. }
  213812. DSoundAudioIODeviceType (const DSoundAudioIODeviceType&);
  213813. DSoundAudioIODeviceType& operator= (const DSoundAudioIODeviceType&);
  213814. };
  213815. const String DSoundAudioIODevice::openDevice (const BigInteger& inputChannels,
  213816. const BigInteger& outputChannels,
  213817. double sampleRate_,
  213818. int bufferSizeSamples_)
  213819. {
  213820. closeDevice();
  213821. totalSamplesOut = 0;
  213822. sampleRate = sampleRate_;
  213823. if (bufferSizeSamples_ <= 0)
  213824. bufferSizeSamples_ = 960; // use as a default size if none is set.
  213825. bufferSizeSamples = bufferSizeSamples_ & ~7;
  213826. DSoundAudioIODeviceType dlh;
  213827. dlh.scanForDevices();
  213828. enabledInputs = inputChannels;
  213829. enabledInputs.setRange (inChannels.size(),
  213830. enabledInputs.getHighestBit() + 1 - inChannels.size(),
  213831. false);
  213832. inputBuffers.setSize (jmax (1, enabledInputs.countNumberOfSetBits()), bufferSizeSamples);
  213833. int i, numIns = 0;
  213834. for (i = 0; i <= enabledInputs.getHighestBit(); i += 2)
  213835. {
  213836. float* left = 0;
  213837. if (enabledInputs[i])
  213838. left = inputBuffers.getSampleData (numIns++);
  213839. float* right = 0;
  213840. if (enabledInputs[i + 1])
  213841. right = inputBuffers.getSampleData (numIns++);
  213842. if (left != 0 || right != 0)
  213843. inChans.add (new DSoundInternalInChannel (dlh.inputDeviceNames [inputDeviceIndex],
  213844. dlh.inputGuids [inputDeviceIndex],
  213845. (int) sampleRate, bufferSizeSamples,
  213846. left, right));
  213847. }
  213848. enabledOutputs = outputChannels;
  213849. enabledOutputs.setRange (outChannels.size(),
  213850. enabledOutputs.getHighestBit() + 1 - outChannels.size(),
  213851. false);
  213852. outputBuffers.setSize (jmax (1, enabledOutputs.countNumberOfSetBits()), bufferSizeSamples);
  213853. int numOuts = 0;
  213854. for (i = 0; i <= enabledOutputs.getHighestBit(); i += 2)
  213855. {
  213856. float* left = 0;
  213857. if (enabledOutputs[i])
  213858. left = outputBuffers.getSampleData (numOuts++);
  213859. float* right = 0;
  213860. if (enabledOutputs[i + 1])
  213861. right = outputBuffers.getSampleData (numOuts++);
  213862. if (left != 0 || right != 0)
  213863. outChans.add (new DSoundInternalOutChannel (dlh.outputDeviceNames[outputDeviceIndex],
  213864. dlh.outputGuids [outputDeviceIndex],
  213865. (int) sampleRate, bufferSizeSamples,
  213866. left, right));
  213867. }
  213868. String error;
  213869. // boost our priority while opening the devices to try to get better sync between them
  213870. const int oldThreadPri = GetThreadPriority (GetCurrentThread());
  213871. const int oldProcPri = GetPriorityClass (GetCurrentProcess());
  213872. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  213873. SetPriorityClass (GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
  213874. for (i = 0; i < outChans.size(); ++i)
  213875. {
  213876. error = outChans[i]->open();
  213877. if (error.isNotEmpty())
  213878. {
  213879. error = "Error opening " + dlh.outputDeviceNames[i] + ": \"" + error + "\"";
  213880. break;
  213881. }
  213882. }
  213883. if (error.isEmpty())
  213884. {
  213885. for (i = 0; i < inChans.size(); ++i)
  213886. {
  213887. error = inChans[i]->open();
  213888. if (error.isNotEmpty())
  213889. {
  213890. error = "Error opening " + dlh.inputDeviceNames[i] + ": \"" + error + "\"";
  213891. break;
  213892. }
  213893. }
  213894. }
  213895. if (error.isEmpty())
  213896. {
  213897. totalSamplesOut = 0;
  213898. for (i = 0; i < outChans.size(); ++i)
  213899. outChans.getUnchecked(i)->synchronisePosition();
  213900. for (i = 0; i < inChans.size(); ++i)
  213901. inChans.getUnchecked(i)->synchronisePosition();
  213902. startThread (9);
  213903. sleep (10);
  213904. notify();
  213905. }
  213906. else
  213907. {
  213908. log (error);
  213909. }
  213910. SetThreadPriority (GetCurrentThread(), oldThreadPri);
  213911. SetPriorityClass (GetCurrentProcess(), oldProcPri);
  213912. return error;
  213913. }
  213914. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound()
  213915. {
  213916. return new DSoundAudioIODeviceType();
  213917. }
  213918. #undef log
  213919. #endif
  213920. /*** End of inlined file: juce_win32_DirectSound.cpp ***/
  213921. /*** Start of inlined file: juce_win32_WASAPI.cpp ***/
  213922. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  213923. // compiled on its own).
  213924. #if JUCE_INCLUDED_FILE && JUCE_WASAPI
  213925. #if 1
  213926. const String getAudioErrorDesc (HRESULT hr)
  213927. {
  213928. const char* e = 0;
  213929. switch (hr)
  213930. {
  213931. case E_POINTER: e = "E_POINTER"; break;
  213932. case E_INVALIDARG: e = "E_INVALIDARG"; break;
  213933. case AUDCLNT_E_NOT_INITIALIZED: e = "AUDCLNT_E_NOT_INITIALIZED"; break;
  213934. case AUDCLNT_E_ALREADY_INITIALIZED: e = "AUDCLNT_E_ALREADY_INITIALIZED"; break;
  213935. case AUDCLNT_E_WRONG_ENDPOINT_TYPE: e = "AUDCLNT_E_WRONG_ENDPOINT_TYPE"; break;
  213936. case AUDCLNT_E_DEVICE_INVALIDATED: e = "AUDCLNT_E_DEVICE_INVALIDATED"; break;
  213937. case AUDCLNT_E_NOT_STOPPED: e = "AUDCLNT_E_NOT_STOPPED"; break;
  213938. case AUDCLNT_E_BUFFER_TOO_LARGE: e = "AUDCLNT_E_BUFFER_TOO_LARGE"; break;
  213939. case AUDCLNT_E_OUT_OF_ORDER: e = "AUDCLNT_E_OUT_OF_ORDER"; break;
  213940. case AUDCLNT_E_UNSUPPORTED_FORMAT: e = "AUDCLNT_E_UNSUPPORTED_FORMAT"; break;
  213941. case AUDCLNT_E_INVALID_SIZE: e = "AUDCLNT_E_INVALID_SIZE"; break;
  213942. case AUDCLNT_E_DEVICE_IN_USE: e = "AUDCLNT_E_DEVICE_IN_USE"; break;
  213943. case AUDCLNT_E_BUFFER_OPERATION_PENDING: e = "AUDCLNT_E_BUFFER_OPERATION_PENDING"; break;
  213944. case AUDCLNT_E_THREAD_NOT_REGISTERED: e = "AUDCLNT_E_THREAD_NOT_REGISTERED"; break;
  213945. case AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED: e = "AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED"; break;
  213946. case AUDCLNT_E_ENDPOINT_CREATE_FAILED: e = "AUDCLNT_E_ENDPOINT_CREATE_FAILED"; break;
  213947. case AUDCLNT_E_SERVICE_NOT_RUNNING: e = "AUDCLNT_E_SERVICE_NOT_RUNNING"; break;
  213948. case AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED: e = "AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED"; break;
  213949. case AUDCLNT_E_EXCLUSIVE_MODE_ONLY: e = "AUDCLNT_E_EXCLUSIVE_MODE_ONLY"; break;
  213950. case AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL: e = "AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL"; break;
  213951. case AUDCLNT_E_EVENTHANDLE_NOT_SET: e = "AUDCLNT_E_EVENTHANDLE_NOT_SET"; break;
  213952. case AUDCLNT_E_INCORRECT_BUFFER_SIZE: e = "AUDCLNT_E_INCORRECT_BUFFER_SIZE"; break;
  213953. case AUDCLNT_E_BUFFER_SIZE_ERROR: e = "AUDCLNT_E_BUFFER_SIZE_ERROR"; break;
  213954. case AUDCLNT_S_BUFFER_EMPTY: e = "AUDCLNT_S_BUFFER_EMPTY"; break;
  213955. case AUDCLNT_S_THREAD_ALREADY_REGISTERED: e = "AUDCLNT_S_THREAD_ALREADY_REGISTERED"; break;
  213956. default: return String::toHexString ((int) hr);
  213957. }
  213958. return e;
  213959. }
  213960. #define logFailure(hr) { if (FAILED (hr)) { DBG ("WASAPI FAIL! " + getAudioErrorDesc (hr)); jassertfalse; } }
  213961. #define OK(a) wasapi_checkResult(a)
  213962. static bool wasapi_checkResult (HRESULT hr)
  213963. {
  213964. logFailure (hr);
  213965. return SUCCEEDED (hr);
  213966. }
  213967. #else
  213968. #define logFailure(hr) {}
  213969. #define OK(a) SUCCEEDED(a)
  213970. #endif
  213971. static const String wasapi_getDeviceID (IMMDevice* const device)
  213972. {
  213973. String s;
  213974. WCHAR* deviceId = 0;
  213975. if (OK (device->GetId (&deviceId)))
  213976. {
  213977. s = String (deviceId);
  213978. CoTaskMemFree (deviceId);
  213979. }
  213980. return s;
  213981. }
  213982. static EDataFlow wasapi_getDataFlow (IMMDevice* const device)
  213983. {
  213984. EDataFlow flow = eRender;
  213985. ComSmartPtr <IMMEndpoint> endPoint;
  213986. if (OK (device->QueryInterface (__uuidof (IMMEndpoint), (void**) &endPoint)))
  213987. (void) OK (endPoint->GetDataFlow (&flow));
  213988. return flow;
  213989. }
  213990. static int wasapi_refTimeToSamples (const REFERENCE_TIME& t, const double sampleRate) throw()
  213991. {
  213992. return roundDoubleToInt (sampleRate * ((double) t) * 0.0000001);
  213993. }
  213994. static void wasapi_copyWavFormat (WAVEFORMATEXTENSIBLE& dest, const WAVEFORMATEX* const src) throw()
  213995. {
  213996. memcpy (&dest, src, src->wFormatTag == WAVE_FORMAT_EXTENSIBLE ? sizeof (WAVEFORMATEXTENSIBLE)
  213997. : sizeof (WAVEFORMATEX));
  213998. }
  213999. class WASAPIDeviceBase
  214000. {
  214001. public:
  214002. WASAPIDeviceBase (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  214003. : device (device_),
  214004. sampleRate (0),
  214005. numChannels (0),
  214006. actualNumChannels (0),
  214007. defaultSampleRate (0),
  214008. minBufferSize (0),
  214009. defaultBufferSize (0),
  214010. latencySamples (0),
  214011. useExclusiveMode (useExclusiveMode_)
  214012. {
  214013. clientEvent = CreateEvent (0, false, false, _T("JuceWASAPI"));
  214014. ComSmartPtr <IAudioClient> tempClient (createClient());
  214015. if (tempClient == 0)
  214016. return;
  214017. REFERENCE_TIME defaultPeriod, minPeriod;
  214018. if (! OK (tempClient->GetDevicePeriod (&defaultPeriod, &minPeriod)))
  214019. return;
  214020. WAVEFORMATEX* mixFormat = 0;
  214021. if (! OK (tempClient->GetMixFormat (&mixFormat)))
  214022. return;
  214023. WAVEFORMATEXTENSIBLE format;
  214024. wasapi_copyWavFormat (format, mixFormat);
  214025. CoTaskMemFree (mixFormat);
  214026. actualNumChannels = numChannels = format.Format.nChannels;
  214027. defaultSampleRate = format.Format.nSamplesPerSec;
  214028. minBufferSize = wasapi_refTimeToSamples (minPeriod, defaultSampleRate);
  214029. defaultBufferSize = wasapi_refTimeToSamples (defaultPeriod, defaultSampleRate);
  214030. rates.addUsingDefaultSort (defaultSampleRate);
  214031. static const double ratesToTest[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  214032. for (int i = 0; i < numElementsInArray (ratesToTest); ++i)
  214033. {
  214034. if (ratesToTest[i] == defaultSampleRate)
  214035. continue;
  214036. format.Format.nSamplesPerSec = roundDoubleToInt (ratesToTest[i]);
  214037. if (SUCCEEDED (tempClient->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  214038. (WAVEFORMATEX*) &format, 0)))
  214039. if (! rates.contains (ratesToTest[i]))
  214040. rates.addUsingDefaultSort (ratesToTest[i]);
  214041. }
  214042. }
  214043. ~WASAPIDeviceBase()
  214044. {
  214045. device = 0;
  214046. CloseHandle (clientEvent);
  214047. }
  214048. bool isOk() const throw() { return defaultBufferSize > 0 && defaultSampleRate > 0; }
  214049. bool openClient (const double newSampleRate, const BigInteger& newChannels)
  214050. {
  214051. sampleRate = newSampleRate;
  214052. channels = newChannels;
  214053. channels.setRange (actualNumChannels, channels.getHighestBit() + 1 - actualNumChannels, false);
  214054. numChannels = channels.getHighestBit() + 1;
  214055. if (numChannels == 0)
  214056. return true;
  214057. client = createClient();
  214058. if (client != 0
  214059. && (tryInitialisingWithFormat (true, 4) || tryInitialisingWithFormat (false, 4)
  214060. || tryInitialisingWithFormat (false, 3) || tryInitialisingWithFormat (false, 2)))
  214061. {
  214062. channelMaps.clear();
  214063. for (int i = 0; i <= channels.getHighestBit(); ++i)
  214064. if (channels[i])
  214065. channelMaps.add (i);
  214066. REFERENCE_TIME latency;
  214067. if (OK (client->GetStreamLatency (&latency)))
  214068. latencySamples = wasapi_refTimeToSamples (latency, sampleRate);
  214069. (void) OK (client->GetBufferSize (&actualBufferSize));
  214070. return OK (client->SetEventHandle (clientEvent));
  214071. }
  214072. return false;
  214073. }
  214074. void closeClient()
  214075. {
  214076. if (client != 0)
  214077. client->Stop();
  214078. client = 0;
  214079. ResetEvent (clientEvent);
  214080. }
  214081. ComSmartPtr <IMMDevice> device;
  214082. ComSmartPtr <IAudioClient> client;
  214083. double sampleRate, defaultSampleRate;
  214084. int numChannels, actualNumChannels;
  214085. int minBufferSize, defaultBufferSize, latencySamples;
  214086. const bool useExclusiveMode;
  214087. Array <double> rates;
  214088. HANDLE clientEvent;
  214089. BigInteger channels;
  214090. AudioDataConverters::DataFormat dataFormat;
  214091. Array <int> channelMaps;
  214092. UINT32 actualBufferSize;
  214093. int bytesPerSample;
  214094. private:
  214095. const ComSmartPtr <IAudioClient> createClient()
  214096. {
  214097. ComSmartPtr <IAudioClient> client;
  214098. if (device != 0)
  214099. {
  214100. HRESULT hr = device->Activate (__uuidof (IAudioClient), CLSCTX_INPROC_SERVER, 0, (void**) &client);
  214101. logFailure (hr);
  214102. }
  214103. return client;
  214104. }
  214105. bool tryInitialisingWithFormat (const bool useFloat, const int bytesPerSampleToTry)
  214106. {
  214107. WAVEFORMATEXTENSIBLE format;
  214108. zerostruct (format);
  214109. if (numChannels <= 2 && bytesPerSampleToTry <= 2)
  214110. {
  214111. format.Format.wFormatTag = WAVE_FORMAT_PCM;
  214112. }
  214113. else
  214114. {
  214115. format.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  214116. format.Format.cbSize = sizeof (WAVEFORMATEXTENSIBLE) - sizeof (WAVEFORMATEX);
  214117. }
  214118. format.Format.nSamplesPerSec = roundDoubleToInt (sampleRate);
  214119. format.Format.nChannels = (WORD) numChannels;
  214120. format.Format.wBitsPerSample = (WORD) (8 * bytesPerSampleToTry);
  214121. format.Format.nAvgBytesPerSec = (DWORD) (format.Format.nSamplesPerSec * numChannels * bytesPerSampleToTry);
  214122. format.Format.nBlockAlign = (WORD) (numChannels * bytesPerSampleToTry);
  214123. format.SubFormat = useFloat ? KSDATAFORMAT_SUBTYPE_IEEE_FLOAT : KSDATAFORMAT_SUBTYPE_PCM;
  214124. format.Samples.wValidBitsPerSample = format.Format.wBitsPerSample;
  214125. switch (numChannels)
  214126. {
  214127. case 1: format.dwChannelMask = SPEAKER_FRONT_CENTER; break;
  214128. case 2: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; break;
  214129. case 4: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  214130. case 6: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  214131. 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;
  214132. default: break;
  214133. }
  214134. WAVEFORMATEXTENSIBLE* nearestFormat = 0;
  214135. HRESULT hr = client->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  214136. (WAVEFORMATEX*) &format, useExclusiveMode ? 0 : (WAVEFORMATEX**) &nearestFormat);
  214137. logFailure (hr);
  214138. if (hr == S_FALSE && format.Format.nSamplesPerSec == nearestFormat->Format.nSamplesPerSec)
  214139. {
  214140. wasapi_copyWavFormat (format, (WAVEFORMATEX*) nearestFormat);
  214141. hr = S_OK;
  214142. }
  214143. CoTaskMemFree (nearestFormat);
  214144. REFERENCE_TIME defaultPeriod = 0, minPeriod = 0;
  214145. if (useExclusiveMode)
  214146. OK (client->GetDevicePeriod (&defaultPeriod, &minPeriod));
  214147. GUID session;
  214148. if (hr == S_OK
  214149. && OK (client->Initialize (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  214150. AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  214151. defaultPeriod, defaultPeriod, (WAVEFORMATEX*) &format, &session)))
  214152. {
  214153. actualNumChannels = format.Format.nChannels;
  214154. const bool isFloat = format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE && format.SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  214155. bytesPerSample = format.Format.wBitsPerSample / 8;
  214156. dataFormat = isFloat ? AudioDataConverters::float32LE
  214157. : (bytesPerSample == 4 ? AudioDataConverters::int32LE
  214158. : ((bytesPerSample == 3 ? AudioDataConverters::int24LE
  214159. : AudioDataConverters::int16LE)));
  214160. return true;
  214161. }
  214162. return false;
  214163. }
  214164. WASAPIDeviceBase (const WASAPIDeviceBase&);
  214165. WASAPIDeviceBase& operator= (const WASAPIDeviceBase&);
  214166. };
  214167. class WASAPIInputDevice : public WASAPIDeviceBase
  214168. {
  214169. public:
  214170. WASAPIInputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  214171. : WASAPIDeviceBase (device_, useExclusiveMode_),
  214172. reservoir (1, 1)
  214173. {
  214174. }
  214175. ~WASAPIInputDevice()
  214176. {
  214177. close();
  214178. }
  214179. bool open (const double newSampleRate, const BigInteger& newChannels)
  214180. {
  214181. reservoirSize = 0;
  214182. reservoirCapacity = 16384;
  214183. reservoir.setSize (actualNumChannels * reservoirCapacity * sizeof (float));
  214184. return openClient (newSampleRate, newChannels)
  214185. && (numChannels == 0 || OK (client->GetService (__uuidof (IAudioCaptureClient), (void**) &captureClient)));
  214186. }
  214187. void close()
  214188. {
  214189. closeClient();
  214190. captureClient = 0;
  214191. reservoir.setSize (0);
  214192. }
  214193. void copyBuffers (float** destBuffers, int numDestBuffers, int bufferSize, Thread& thread)
  214194. {
  214195. if (numChannels <= 0)
  214196. return;
  214197. int offset = 0;
  214198. while (bufferSize > 0)
  214199. {
  214200. if (reservoirSize > 0) // There's stuff in the reservoir, so use that...
  214201. {
  214202. const int samplesToDo = jmin (bufferSize, (int) reservoirSize);
  214203. for (int i = 0; i < numDestBuffers; ++i)
  214204. {
  214205. float* const dest = destBuffers[i] + offset;
  214206. const int srcChan = channelMaps.getUnchecked(i);
  214207. switch (dataFormat)
  214208. {
  214209. case AudioDataConverters::float32LE:
  214210. AudioDataConverters::convertFloat32LEToFloat (((uint8*) reservoir.getData()) + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  214211. break;
  214212. case AudioDataConverters::int32LE:
  214213. AudioDataConverters::convertInt32LEToFloat (((uint8*) reservoir.getData()) + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  214214. break;
  214215. case AudioDataConverters::int24LE:
  214216. AudioDataConverters::convertInt24LEToFloat (((uint8*) reservoir.getData()) + 3 * srcChan, dest, samplesToDo, 3 * actualNumChannels);
  214217. break;
  214218. case AudioDataConverters::int16LE:
  214219. AudioDataConverters::convertInt16LEToFloat (((uint8*) reservoir.getData()) + 2 * srcChan, dest, samplesToDo, 2 * actualNumChannels);
  214220. break;
  214221. default: jassertfalse; break;
  214222. }
  214223. }
  214224. bufferSize -= samplesToDo;
  214225. offset += samplesToDo;
  214226. reservoirSize -= samplesToDo;
  214227. }
  214228. else
  214229. {
  214230. UINT32 packetLength = 0;
  214231. if (! OK (captureClient->GetNextPacketSize (&packetLength)))
  214232. break;
  214233. if (packetLength == 0)
  214234. {
  214235. if (thread.threadShouldExit())
  214236. break;
  214237. Thread::sleep (1);
  214238. continue;
  214239. }
  214240. uint8* inputData = 0;
  214241. UINT32 numSamplesAvailable;
  214242. DWORD flags;
  214243. if (OK (captureClient->GetBuffer (&inputData, &numSamplesAvailable, &flags, 0, 0)))
  214244. {
  214245. const int samplesToDo = jmin (bufferSize, (int) numSamplesAvailable);
  214246. for (int i = 0; i < numDestBuffers; ++i)
  214247. {
  214248. float* const dest = destBuffers[i] + offset;
  214249. const int srcChan = channelMaps.getUnchecked(i);
  214250. switch (dataFormat)
  214251. {
  214252. case AudioDataConverters::float32LE:
  214253. AudioDataConverters::convertFloat32LEToFloat (inputData + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  214254. break;
  214255. case AudioDataConverters::int32LE:
  214256. AudioDataConverters::convertInt32LEToFloat (inputData + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  214257. break;
  214258. case AudioDataConverters::int24LE:
  214259. AudioDataConverters::convertInt24LEToFloat (inputData + 3 * srcChan, dest, samplesToDo, 3 * actualNumChannels);
  214260. break;
  214261. case AudioDataConverters::int16LE:
  214262. AudioDataConverters::convertInt16LEToFloat (inputData + 2 * srcChan, dest, samplesToDo, 2 * actualNumChannels);
  214263. break;
  214264. default: jassertfalse; break;
  214265. }
  214266. }
  214267. bufferSize -= samplesToDo;
  214268. offset += samplesToDo;
  214269. if (samplesToDo < (int) numSamplesAvailable)
  214270. {
  214271. reservoirSize = jmin ((int) (numSamplesAvailable - samplesToDo), reservoirCapacity);
  214272. memcpy ((uint8*) reservoir.getData(), inputData + bytesPerSample * actualNumChannels * samplesToDo,
  214273. bytesPerSample * actualNumChannels * reservoirSize);
  214274. }
  214275. captureClient->ReleaseBuffer (numSamplesAvailable);
  214276. }
  214277. }
  214278. }
  214279. }
  214280. ComSmartPtr <IAudioCaptureClient> captureClient;
  214281. MemoryBlock reservoir;
  214282. int reservoirSize, reservoirCapacity;
  214283. private:
  214284. WASAPIInputDevice (const WASAPIInputDevice&);
  214285. WASAPIInputDevice& operator= (const WASAPIInputDevice&);
  214286. };
  214287. class WASAPIOutputDevice : public WASAPIDeviceBase
  214288. {
  214289. public:
  214290. WASAPIOutputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  214291. : WASAPIDeviceBase (device_, useExclusiveMode_)
  214292. {
  214293. }
  214294. ~WASAPIOutputDevice()
  214295. {
  214296. close();
  214297. }
  214298. bool open (const double newSampleRate, const BigInteger& newChannels)
  214299. {
  214300. return openClient (newSampleRate, newChannels)
  214301. && (numChannels == 0 || OK (client->GetService (__uuidof (IAudioRenderClient), (void**) &renderClient)));
  214302. }
  214303. void close()
  214304. {
  214305. closeClient();
  214306. renderClient = 0;
  214307. }
  214308. void copyBuffers (const float** const srcBuffers, const int numSrcBuffers, int bufferSize, Thread& thread)
  214309. {
  214310. if (numChannels <= 0)
  214311. return;
  214312. int offset = 0;
  214313. while (bufferSize > 0)
  214314. {
  214315. UINT32 padding = 0;
  214316. if (! OK (client->GetCurrentPadding (&padding)))
  214317. return;
  214318. int samplesToDo = useExclusiveMode ? bufferSize
  214319. : jmin ((int) (actualBufferSize - padding), bufferSize);
  214320. if (samplesToDo <= 0)
  214321. {
  214322. if (thread.threadShouldExit())
  214323. break;
  214324. Thread::sleep (0);
  214325. continue;
  214326. }
  214327. uint8* outputData = 0;
  214328. if (OK (renderClient->GetBuffer (samplesToDo, &outputData)))
  214329. {
  214330. for (int i = 0; i < numSrcBuffers; ++i)
  214331. {
  214332. const float* const source = srcBuffers[i] + offset;
  214333. const int destChan = channelMaps.getUnchecked(i);
  214334. switch (dataFormat)
  214335. {
  214336. case AudioDataConverters::float32LE:
  214337. AudioDataConverters::convertFloatToFloat32LE (source, outputData + 4 * destChan, samplesToDo, 4 * actualNumChannels);
  214338. break;
  214339. case AudioDataConverters::int32LE:
  214340. AudioDataConverters::convertFloatToInt32LE (source, outputData + 4 * destChan, samplesToDo, 4 * actualNumChannels);
  214341. break;
  214342. case AudioDataConverters::int24LE:
  214343. AudioDataConverters::convertFloatToInt24LE (source, outputData + 3 * destChan, samplesToDo, 3 * actualNumChannels);
  214344. break;
  214345. case AudioDataConverters::int16LE:
  214346. AudioDataConverters::convertFloatToInt16LE (source, outputData + 2 * destChan, samplesToDo, 2 * actualNumChannels);
  214347. break;
  214348. default: jassertfalse; break;
  214349. }
  214350. }
  214351. renderClient->ReleaseBuffer (samplesToDo, 0);
  214352. offset += samplesToDo;
  214353. bufferSize -= samplesToDo;
  214354. }
  214355. }
  214356. }
  214357. ComSmartPtr <IAudioRenderClient> renderClient;
  214358. private:
  214359. WASAPIOutputDevice (const WASAPIOutputDevice&);
  214360. WASAPIOutputDevice& operator= (const WASAPIOutputDevice&);
  214361. };
  214362. class WASAPIAudioIODevice : public AudioIODevice,
  214363. public Thread
  214364. {
  214365. public:
  214366. WASAPIAudioIODevice (const String& deviceName,
  214367. const String& outputDeviceId_,
  214368. const String& inputDeviceId_,
  214369. const bool useExclusiveMode_)
  214370. : AudioIODevice (deviceName, "Windows Audio"),
  214371. Thread ("Juce WASAPI"),
  214372. isOpen_ (false),
  214373. isStarted (false),
  214374. outputDevice (0),
  214375. outputDeviceId (outputDeviceId_),
  214376. inputDevice (0),
  214377. inputDeviceId (inputDeviceId_),
  214378. useExclusiveMode (useExclusiveMode_),
  214379. currentBufferSizeSamples (0),
  214380. currentSampleRate (0),
  214381. callback (0)
  214382. {
  214383. }
  214384. ~WASAPIAudioIODevice()
  214385. {
  214386. close();
  214387. deleteAndZero (inputDevice);
  214388. deleteAndZero (outputDevice);
  214389. }
  214390. bool initialise()
  214391. {
  214392. double defaultSampleRateIn = 0, defaultSampleRateOut = 0;
  214393. int minBufferSizeIn = 0, defaultBufferSizeIn = 0, minBufferSizeOut = 0, defaultBufferSizeOut = 0;
  214394. latencyIn = latencyOut = 0;
  214395. Array <double> ratesIn, ratesOut;
  214396. if (createDevices())
  214397. {
  214398. jassert (inputDevice != 0 || outputDevice != 0);
  214399. if (inputDevice != 0 && outputDevice != 0)
  214400. {
  214401. defaultSampleRate = jmin (inputDevice->defaultSampleRate, outputDevice->defaultSampleRate);
  214402. minBufferSize = jmin (inputDevice->minBufferSize, outputDevice->minBufferSize);
  214403. defaultBufferSize = jmax (inputDevice->defaultBufferSize, outputDevice->defaultBufferSize);
  214404. sampleRates = inputDevice->rates;
  214405. sampleRates.removeValuesNotIn (outputDevice->rates);
  214406. }
  214407. else
  214408. {
  214409. WASAPIDeviceBase* const d = inputDevice != 0 ? (WASAPIDeviceBase*) inputDevice : (WASAPIDeviceBase*) outputDevice;
  214410. defaultSampleRate = d->defaultSampleRate;
  214411. minBufferSize = d->minBufferSize;
  214412. defaultBufferSize = d->defaultBufferSize;
  214413. sampleRates = d->rates;
  214414. }
  214415. bufferSizes.addUsingDefaultSort (defaultBufferSize);
  214416. if (minBufferSize != defaultBufferSize)
  214417. bufferSizes.addUsingDefaultSort (minBufferSize);
  214418. int n = 64;
  214419. for (int i = 0; i < 40; ++i)
  214420. {
  214421. if (n >= minBufferSize && n <= 2048 && ! bufferSizes.contains (n))
  214422. bufferSizes.addUsingDefaultSort (n);
  214423. n += (n < 512) ? 32 : (n < 1024 ? 64 : 128);
  214424. }
  214425. return true;
  214426. }
  214427. return false;
  214428. }
  214429. const StringArray getOutputChannelNames()
  214430. {
  214431. StringArray outChannels;
  214432. if (outputDevice != 0)
  214433. for (int i = 1; i <= outputDevice->actualNumChannels; ++i)
  214434. outChannels.add ("Output channel " + String (i));
  214435. return outChannels;
  214436. }
  214437. const StringArray getInputChannelNames()
  214438. {
  214439. StringArray inChannels;
  214440. if (inputDevice != 0)
  214441. for (int i = 1; i <= inputDevice->actualNumChannels; ++i)
  214442. inChannels.add ("Input channel " + String (i));
  214443. return inChannels;
  214444. }
  214445. int getNumSampleRates() { return sampleRates.size(); }
  214446. double getSampleRate (int index) { return sampleRates [index]; }
  214447. int getNumBufferSizesAvailable() { return bufferSizes.size(); }
  214448. int getBufferSizeSamples (int index) { return bufferSizes [index]; }
  214449. int getDefaultBufferSize() { return defaultBufferSize; }
  214450. int getCurrentBufferSizeSamples() { return currentBufferSizeSamples; }
  214451. double getCurrentSampleRate() { return currentSampleRate; }
  214452. int getCurrentBitDepth() { return 32; }
  214453. int getOutputLatencyInSamples() { return latencyOut; }
  214454. int getInputLatencyInSamples() { return latencyIn; }
  214455. const BigInteger getActiveOutputChannels() const { return outputDevice != 0 ? outputDevice->channels : BigInteger(); }
  214456. const BigInteger getActiveInputChannels() const { return inputDevice != 0 ? inputDevice->channels : BigInteger(); }
  214457. const String getLastError() { return lastError; }
  214458. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  214459. double sampleRate, int bufferSizeSamples)
  214460. {
  214461. close();
  214462. lastError = String::empty;
  214463. if (sampleRates.size() == 0 && inputDevice != 0 && outputDevice != 0)
  214464. {
  214465. lastError = "The input and output devices don't share a common sample rate!";
  214466. return lastError;
  214467. }
  214468. currentBufferSizeSamples = bufferSizeSamples <= 0 ? defaultBufferSize : jmax (bufferSizeSamples, minBufferSize);
  214469. currentSampleRate = sampleRate > 0 ? sampleRate : defaultSampleRate;
  214470. if (inputDevice != 0 && ! inputDevice->open (currentSampleRate, inputChannels))
  214471. {
  214472. lastError = "Couldn't open the input device!";
  214473. return lastError;
  214474. }
  214475. if (outputDevice != 0 && ! outputDevice->open (currentSampleRate, outputChannels))
  214476. {
  214477. close();
  214478. lastError = "Couldn't open the output device!";
  214479. return lastError;
  214480. }
  214481. if (inputDevice != 0)
  214482. ResetEvent (inputDevice->clientEvent);
  214483. if (outputDevice != 0)
  214484. ResetEvent (outputDevice->clientEvent);
  214485. startThread (8);
  214486. Thread::sleep (5);
  214487. if (inputDevice != 0 && inputDevice->client != 0)
  214488. {
  214489. latencyIn = inputDevice->latencySamples + inputDevice->actualBufferSize + inputDevice->minBufferSize;
  214490. HRESULT hr = inputDevice->client->Start();
  214491. logFailure (hr); //xxx handle this
  214492. }
  214493. if (outputDevice != 0 && outputDevice->client != 0)
  214494. {
  214495. latencyOut = outputDevice->latencySamples + outputDevice->actualBufferSize + outputDevice->minBufferSize;
  214496. HRESULT hr = outputDevice->client->Start();
  214497. logFailure (hr); //xxx handle this
  214498. }
  214499. isOpen_ = true;
  214500. return lastError;
  214501. }
  214502. void close()
  214503. {
  214504. stop();
  214505. if (inputDevice != 0)
  214506. SetEvent (inputDevice->clientEvent);
  214507. if (outputDevice != 0)
  214508. SetEvent (outputDevice->clientEvent);
  214509. stopThread (5000);
  214510. if (inputDevice != 0)
  214511. inputDevice->close();
  214512. if (outputDevice != 0)
  214513. outputDevice->close();
  214514. isOpen_ = false;
  214515. }
  214516. bool isOpen() { return isOpen_ && isThreadRunning(); }
  214517. bool isPlaying() { return isStarted && isOpen_ && isThreadRunning(); }
  214518. void start (AudioIODeviceCallback* call)
  214519. {
  214520. if (isOpen_ && call != 0 && ! isStarted)
  214521. {
  214522. if (! isThreadRunning())
  214523. {
  214524. // something's gone wrong and the thread's stopped..
  214525. isOpen_ = false;
  214526. return;
  214527. }
  214528. call->audioDeviceAboutToStart (this);
  214529. const ScopedLock sl (startStopLock);
  214530. callback = call;
  214531. isStarted = true;
  214532. }
  214533. }
  214534. void stop()
  214535. {
  214536. if (isStarted)
  214537. {
  214538. AudioIODeviceCallback* const callbackLocal = callback;
  214539. {
  214540. const ScopedLock sl (startStopLock);
  214541. isStarted = false;
  214542. }
  214543. if (callbackLocal != 0)
  214544. callbackLocal->audioDeviceStopped();
  214545. }
  214546. }
  214547. void setMMThreadPriority()
  214548. {
  214549. DynamicLibraryLoader dll ("avrt.dll");
  214550. DynamicLibraryImport (AvSetMmThreadCharacteristics, avSetMmThreadCharacteristics, HANDLE, dll, (LPCTSTR, LPDWORD))
  214551. DynamicLibraryImport (AvSetMmThreadPriority, avSetMmThreadPriority, HANDLE, dll, (HANDLE, AVRT_PRIORITY))
  214552. if (avSetMmThreadCharacteristics != 0 && avSetMmThreadPriority != 0)
  214553. {
  214554. DWORD dummy = 0;
  214555. HANDLE h = avSetMmThreadCharacteristics (_T("Pro Audio"), &dummy);
  214556. if (h != 0)
  214557. avSetMmThreadPriority (h, AVRT_PRIORITY_NORMAL);
  214558. }
  214559. }
  214560. void run()
  214561. {
  214562. setMMThreadPriority();
  214563. const int bufferSize = currentBufferSizeSamples;
  214564. HANDLE events[2];
  214565. int numEvents = 0;
  214566. if (inputDevice != 0)
  214567. events [numEvents++] = inputDevice->clientEvent;
  214568. if (outputDevice != 0)
  214569. events [numEvents++] = outputDevice->clientEvent;
  214570. const int numInputBuffers = getActiveInputChannels().countNumberOfSetBits();
  214571. const int numOutputBuffers = getActiveOutputChannels().countNumberOfSetBits();
  214572. AudioSampleBuffer ins (jmax (1, numInputBuffers), bufferSize + 32);
  214573. AudioSampleBuffer outs (jmax (1, numOutputBuffers), bufferSize + 32);
  214574. float** const inputBuffers = ins.getArrayOfChannels();
  214575. float** const outputBuffers = outs.getArrayOfChannels();
  214576. ins.clear();
  214577. while (! threadShouldExit())
  214578. {
  214579. const DWORD result = useExclusiveMode ? WaitForSingleObject (inputDevice->clientEvent, 1000)
  214580. : WaitForMultipleObjects (numEvents, events, true, 1000);
  214581. if (result == WAIT_TIMEOUT)
  214582. continue;
  214583. if (threadShouldExit())
  214584. break;
  214585. if (inputDevice != 0)
  214586. inputDevice->copyBuffers (inputBuffers, numInputBuffers, bufferSize, *this);
  214587. // Make the callback..
  214588. {
  214589. const ScopedLock sl (startStopLock);
  214590. if (isStarted)
  214591. {
  214592. JUCE_TRY
  214593. {
  214594. callback->audioDeviceIOCallback ((const float**) inputBuffers,
  214595. numInputBuffers,
  214596. outputBuffers,
  214597. numOutputBuffers,
  214598. bufferSize);
  214599. }
  214600. JUCE_CATCH_EXCEPTION
  214601. }
  214602. else
  214603. {
  214604. outs.clear();
  214605. }
  214606. }
  214607. if (useExclusiveMode && WaitForSingleObject (outputDevice->clientEvent, 1000) == WAIT_TIMEOUT)
  214608. continue;
  214609. if (outputDevice != 0)
  214610. outputDevice->copyBuffers ((const float**) outputBuffers, numOutputBuffers, bufferSize, *this);
  214611. }
  214612. }
  214613. juce_UseDebuggingNewOperator
  214614. String outputDeviceId, inputDeviceId;
  214615. String lastError;
  214616. private:
  214617. // Device stats...
  214618. WASAPIInputDevice* inputDevice;
  214619. WASAPIOutputDevice* outputDevice;
  214620. const bool useExclusiveMode;
  214621. double defaultSampleRate;
  214622. int minBufferSize, defaultBufferSize;
  214623. int latencyIn, latencyOut;
  214624. Array <double> sampleRates;
  214625. Array <int> bufferSizes;
  214626. // Active state...
  214627. bool isOpen_, isStarted;
  214628. int currentBufferSizeSamples;
  214629. double currentSampleRate;
  214630. AudioIODeviceCallback* callback;
  214631. CriticalSection startStopLock;
  214632. bool createDevices()
  214633. {
  214634. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  214635. if (! OK (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  214636. return false;
  214637. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  214638. if (! OK (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, &deviceCollection)))
  214639. return false;
  214640. UINT32 numDevices = 0;
  214641. if (! OK (deviceCollection->GetCount (&numDevices)))
  214642. return false;
  214643. for (UINT32 i = 0; i < numDevices; ++i)
  214644. {
  214645. ComSmartPtr <IMMDevice> device;
  214646. if (! OK (deviceCollection->Item (i, &device)))
  214647. continue;
  214648. const String deviceId (wasapi_getDeviceID (device));
  214649. if (deviceId.isEmpty())
  214650. continue;
  214651. const EDataFlow flow = wasapi_getDataFlow (device);
  214652. if (deviceId == inputDeviceId && flow == eCapture)
  214653. inputDevice = new WASAPIInputDevice (device, useExclusiveMode);
  214654. else if (deviceId == outputDeviceId && flow == eRender)
  214655. outputDevice = new WASAPIOutputDevice (device, useExclusiveMode);
  214656. }
  214657. return (outputDeviceId.isEmpty() || (outputDevice != 0 && outputDevice->isOk()))
  214658. && (inputDeviceId.isEmpty() || (inputDevice != 0 && inputDevice->isOk()));
  214659. }
  214660. WASAPIAudioIODevice (const WASAPIAudioIODevice&);
  214661. WASAPIAudioIODevice& operator= (const WASAPIAudioIODevice&);
  214662. };
  214663. class WASAPIAudioIODeviceType : public AudioIODeviceType
  214664. {
  214665. public:
  214666. WASAPIAudioIODeviceType()
  214667. : AudioIODeviceType ("Windows Audio"),
  214668. hasScanned (false)
  214669. {
  214670. }
  214671. ~WASAPIAudioIODeviceType()
  214672. {
  214673. }
  214674. void scanForDevices()
  214675. {
  214676. hasScanned = true;
  214677. outputDeviceNames.clear();
  214678. inputDeviceNames.clear();
  214679. outputDeviceIds.clear();
  214680. inputDeviceIds.clear();
  214681. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  214682. if (! OK (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  214683. return;
  214684. const String defaultRenderer = getDefaultEndpoint (enumerator, false);
  214685. const String defaultCapture = getDefaultEndpoint (enumerator, true);
  214686. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  214687. UINT32 numDevices = 0;
  214688. if (! (OK (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, &deviceCollection))
  214689. && OK (deviceCollection->GetCount (&numDevices))))
  214690. return;
  214691. for (UINT32 i = 0; i < numDevices; ++i)
  214692. {
  214693. ComSmartPtr <IMMDevice> device;
  214694. if (! OK (deviceCollection->Item (i, &device)))
  214695. continue;
  214696. const String deviceId (wasapi_getDeviceID (device));
  214697. DWORD state = 0;
  214698. if (! OK (device->GetState (&state)))
  214699. continue;
  214700. if (state != DEVICE_STATE_ACTIVE)
  214701. continue;
  214702. String name;
  214703. {
  214704. ComSmartPtr <IPropertyStore> properties;
  214705. if (! OK (device->OpenPropertyStore (STGM_READ, &properties)))
  214706. continue;
  214707. PROPVARIANT value;
  214708. PropVariantInit (&value);
  214709. if (OK (properties->GetValue (PKEY_Device_FriendlyName, &value)))
  214710. name = value.pwszVal;
  214711. PropVariantClear (&value);
  214712. }
  214713. const EDataFlow flow = wasapi_getDataFlow (device);
  214714. if (flow == eRender)
  214715. {
  214716. const int index = (deviceId == defaultRenderer) ? 0 : -1;
  214717. outputDeviceIds.insert (index, deviceId);
  214718. outputDeviceNames.insert (index, name);
  214719. }
  214720. else if (flow == eCapture)
  214721. {
  214722. const int index = (deviceId == defaultCapture) ? 0 : -1;
  214723. inputDeviceIds.insert (index, deviceId);
  214724. inputDeviceNames.insert (index, name);
  214725. }
  214726. }
  214727. inputDeviceNames.appendNumbersToDuplicates (false, false);
  214728. outputDeviceNames.appendNumbersToDuplicates (false, false);
  214729. }
  214730. const StringArray getDeviceNames (bool wantInputNames) const
  214731. {
  214732. jassert (hasScanned); // need to call scanForDevices() before doing this
  214733. return wantInputNames ? inputDeviceNames
  214734. : outputDeviceNames;
  214735. }
  214736. int getDefaultDeviceIndex (bool /*forInput*/) const
  214737. {
  214738. jassert (hasScanned); // need to call scanForDevices() before doing this
  214739. return 0;
  214740. }
  214741. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  214742. {
  214743. jassert (hasScanned); // need to call scanForDevices() before doing this
  214744. WASAPIAudioIODevice* const d = dynamic_cast <WASAPIAudioIODevice*> (device);
  214745. return d == 0 ? -1 : (asInput ? inputDeviceIds.indexOf (d->inputDeviceId)
  214746. : outputDeviceIds.indexOf (d->outputDeviceId));
  214747. }
  214748. bool hasSeparateInputsAndOutputs() const { return true; }
  214749. AudioIODevice* createDevice (const String& outputDeviceName,
  214750. const String& inputDeviceName)
  214751. {
  214752. jassert (hasScanned); // need to call scanForDevices() before doing this
  214753. const bool useExclusiveMode = false;
  214754. ScopedPointer<WASAPIAudioIODevice> device;
  214755. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  214756. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  214757. if (outputIndex >= 0 || inputIndex >= 0)
  214758. {
  214759. device = new WASAPIAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  214760. : inputDeviceName,
  214761. outputDeviceIds [outputIndex],
  214762. inputDeviceIds [inputIndex],
  214763. useExclusiveMode);
  214764. if (! device->initialise())
  214765. device = 0;
  214766. }
  214767. return device.release();
  214768. }
  214769. juce_UseDebuggingNewOperator
  214770. StringArray outputDeviceNames, outputDeviceIds;
  214771. StringArray inputDeviceNames, inputDeviceIds;
  214772. private:
  214773. bool hasScanned;
  214774. static const String getDefaultEndpoint (IMMDeviceEnumerator* const enumerator, const bool forCapture)
  214775. {
  214776. String s;
  214777. IMMDevice* dev = 0;
  214778. if (OK (enumerator->GetDefaultAudioEndpoint (forCapture ? eCapture : eRender,
  214779. eMultimedia, &dev)))
  214780. {
  214781. WCHAR* deviceId = 0;
  214782. if (OK (dev->GetId (&deviceId)))
  214783. {
  214784. s = String (deviceId);
  214785. CoTaskMemFree (deviceId);
  214786. }
  214787. dev->Release();
  214788. }
  214789. return s;
  214790. }
  214791. WASAPIAudioIODeviceType (const WASAPIAudioIODeviceType&);
  214792. WASAPIAudioIODeviceType& operator= (const WASAPIAudioIODeviceType&);
  214793. };
  214794. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI()
  214795. {
  214796. return new WASAPIAudioIODeviceType();
  214797. }
  214798. #undef logFailure
  214799. #undef OK
  214800. #endif
  214801. /*** End of inlined file: juce_win32_WASAPI.cpp ***/
  214802. /*** Start of inlined file: juce_win32_CameraDevice.cpp ***/
  214803. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  214804. // compiled on its own).
  214805. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  214806. class DShowCameraDeviceInteral : public ChangeBroadcaster
  214807. {
  214808. public:
  214809. DShowCameraDeviceInteral (CameraDevice* const owner_,
  214810. const ComSmartPtr <ICaptureGraphBuilder2>& captureGraphBuilder_,
  214811. const ComSmartPtr <IBaseFilter>& filter_,
  214812. int minWidth, int minHeight,
  214813. int maxWidth, int maxHeight)
  214814. : owner (owner_),
  214815. captureGraphBuilder (captureGraphBuilder_),
  214816. filter (filter_),
  214817. ok (false),
  214818. imageNeedsFlipping (false),
  214819. width (0),
  214820. height (0),
  214821. activeUsers (0),
  214822. recordNextFrameTime (false)
  214823. {
  214824. HRESULT hr = graphBuilder.CoCreateInstance (CLSID_FilterGraph);
  214825. if (FAILED (hr))
  214826. return;
  214827. hr = captureGraphBuilder->SetFiltergraph (graphBuilder);
  214828. if (FAILED (hr))
  214829. return;
  214830. hr = graphBuilder->QueryInterface (IID_IMediaControl, (void**) &mediaControl);
  214831. if (FAILED (hr))
  214832. return;
  214833. {
  214834. ComSmartPtr <IAMStreamConfig> streamConfig;
  214835. hr = captureGraphBuilder->FindInterface (&PIN_CATEGORY_CAPTURE, 0, filter,
  214836. IID_IAMStreamConfig, (void**) &streamConfig);
  214837. if (streamConfig != 0)
  214838. {
  214839. getVideoSizes (streamConfig);
  214840. if (! selectVideoSize (streamConfig, minWidth, minHeight, maxWidth, maxHeight))
  214841. return;
  214842. }
  214843. }
  214844. hr = graphBuilder->AddFilter (filter, _T("Video Capture"));
  214845. if (FAILED (hr))
  214846. return;
  214847. hr = smartTee.CoCreateInstance (CLSID_SmartTee);
  214848. if (FAILED (hr))
  214849. return;
  214850. hr = graphBuilder->AddFilter (smartTee, _T("Smart Tee"));
  214851. if (FAILED (hr))
  214852. return;
  214853. if (! connectFilters (filter, smartTee))
  214854. return;
  214855. ComSmartPtr <IBaseFilter> sampleGrabberBase;
  214856. hr = sampleGrabberBase.CoCreateInstance (CLSID_SampleGrabber);
  214857. if (FAILED (hr))
  214858. return;
  214859. hr = sampleGrabberBase->QueryInterface (IID_ISampleGrabber, (void**) &sampleGrabber);
  214860. if (FAILED (hr))
  214861. return;
  214862. AM_MEDIA_TYPE mt;
  214863. zerostruct (mt);
  214864. mt.majortype = MEDIATYPE_Video;
  214865. mt.subtype = MEDIASUBTYPE_RGB24;
  214866. mt.formattype = FORMAT_VideoInfo;
  214867. sampleGrabber->SetMediaType (&mt);
  214868. callback = new GrabberCallback (*this);
  214869. sampleGrabber->SetCallback (callback, 1);
  214870. hr = graphBuilder->AddFilter (sampleGrabberBase, _T("Sample Grabber"));
  214871. if (FAILED (hr))
  214872. return;
  214873. ComSmartPtr <IPin> grabberInputPin;
  214874. if (! (getPin (smartTee, PINDIR_OUTPUT, &smartTeeCaptureOutputPin, "capture")
  214875. && getPin (smartTee, PINDIR_OUTPUT, &smartTeePreviewOutputPin, "preview")
  214876. && getPin (sampleGrabberBase, PINDIR_INPUT, &grabberInputPin)))
  214877. return;
  214878. hr = graphBuilder->Connect (smartTeePreviewOutputPin, grabberInputPin);
  214879. if (FAILED (hr))
  214880. return;
  214881. zerostruct (mt);
  214882. hr = sampleGrabber->GetConnectedMediaType (&mt);
  214883. VIDEOINFOHEADER* pVih = (VIDEOINFOHEADER*) (mt.pbFormat);
  214884. width = pVih->bmiHeader.biWidth;
  214885. height = pVih->bmiHeader.biHeight;
  214886. ComSmartPtr <IBaseFilter> nullFilter;
  214887. hr = nullFilter.CoCreateInstance (CLSID_NullRenderer);
  214888. hr = graphBuilder->AddFilter (nullFilter, _T("Null Renderer"));
  214889. if (connectFilters (sampleGrabberBase, nullFilter)
  214890. && addGraphToRot())
  214891. {
  214892. activeImage = Image (Image::RGB, width, height, true);
  214893. loadingImage = Image (Image::RGB, width, height, true);
  214894. ok = true;
  214895. }
  214896. }
  214897. ~DShowCameraDeviceInteral()
  214898. {
  214899. if (mediaControl != 0)
  214900. mediaControl->Stop();
  214901. removeGraphFromRot();
  214902. for (int i = viewerComps.size(); --i >= 0;)
  214903. viewerComps.getUnchecked(i)->ownerDeleted();
  214904. callback = 0;
  214905. graphBuilder = 0;
  214906. sampleGrabber = 0;
  214907. mediaControl = 0;
  214908. filter = 0;
  214909. captureGraphBuilder = 0;
  214910. smartTee = 0;
  214911. smartTeePreviewOutputPin = 0;
  214912. smartTeeCaptureOutputPin = 0;
  214913. asfWriter = 0;
  214914. }
  214915. void addUser()
  214916. {
  214917. if (ok && activeUsers++ == 0)
  214918. mediaControl->Run();
  214919. }
  214920. void removeUser()
  214921. {
  214922. if (ok && --activeUsers == 0)
  214923. mediaControl->Stop();
  214924. }
  214925. void handleFrame (double /*time*/, BYTE* buffer, long /*bufferSize*/)
  214926. {
  214927. if (recordNextFrameTime)
  214928. {
  214929. const double defaultCameraLatency = 0.1;
  214930. firstRecordedTime = Time::getCurrentTime() - RelativeTime (defaultCameraLatency);
  214931. recordNextFrameTime = false;
  214932. ComSmartPtr <IPin> pin;
  214933. if (getPin (filter, PINDIR_OUTPUT, &pin))
  214934. {
  214935. ComSmartPtr <IAMPushSource> pushSource;
  214936. HRESULT hr = pin->QueryInterface (IID_IAMPushSource, (void**) &pushSource);
  214937. if (pushSource != 0)
  214938. {
  214939. REFERENCE_TIME latency = 0;
  214940. hr = pushSource->GetLatency (&latency);
  214941. firstRecordedTime = firstRecordedTime - RelativeTime ((double) latency);
  214942. }
  214943. }
  214944. }
  214945. {
  214946. const int lineStride = width * 3;
  214947. const ScopedLock sl (imageSwapLock);
  214948. {
  214949. const Image::BitmapData destData (loadingImage, 0, 0, width, height, true);
  214950. for (int i = 0; i < height; ++i)
  214951. memcpy (destData.getLinePointer ((height - 1) - i),
  214952. buffer + lineStride * i,
  214953. lineStride);
  214954. }
  214955. imageNeedsFlipping = true;
  214956. }
  214957. if (listeners.size() > 0)
  214958. callListeners (loadingImage);
  214959. sendChangeMessage (this);
  214960. }
  214961. void drawCurrentImage (Graphics& g, int x, int y, int w, int h)
  214962. {
  214963. if (imageNeedsFlipping)
  214964. {
  214965. const ScopedLock sl (imageSwapLock);
  214966. swapVariables (loadingImage, activeImage);
  214967. imageNeedsFlipping = false;
  214968. }
  214969. RectanglePlacement rp (RectanglePlacement::centred);
  214970. double dx = 0, dy = 0, dw = width, dh = height;
  214971. rp.applyTo (dx, dy, dw, dh, x, y, w, h);
  214972. const int rx = roundToInt (dx), ry = roundToInt (dy);
  214973. const int rw = roundToInt (dw), rh = roundToInt (dh);
  214974. g.saveState();
  214975. g.excludeClipRegion (Rectangle<int> (rx, ry, rw, rh));
  214976. g.fillAll (Colours::black);
  214977. g.restoreState();
  214978. g.drawImage (activeImage, rx, ry, rw, rh, 0, 0, width, height);
  214979. }
  214980. bool createFileCaptureFilter (const File& file)
  214981. {
  214982. removeFileCaptureFilter();
  214983. file.deleteFile();
  214984. mediaControl->Stop();
  214985. firstRecordedTime = Time();
  214986. recordNextFrameTime = true;
  214987. HRESULT hr = asfWriter.CoCreateInstance (CLSID_WMAsfWriter);
  214988. if (SUCCEEDED (hr))
  214989. {
  214990. ComSmartPtr <IFileSinkFilter> fileSink;
  214991. hr = asfWriter->QueryInterface (IID_IFileSinkFilter, (void**) &fileSink);
  214992. if (SUCCEEDED (hr))
  214993. {
  214994. hr = fileSink->SetFileName (file.getFullPathName(), 0);
  214995. if (SUCCEEDED (hr))
  214996. {
  214997. hr = graphBuilder->AddFilter (asfWriter, _T("AsfWriter"));
  214998. if (SUCCEEDED (hr))
  214999. {
  215000. ComSmartPtr <IConfigAsfWriter> asfConfig;
  215001. hr = asfWriter->QueryInterface (IID_IConfigAsfWriter, (void**) &asfConfig);
  215002. asfConfig->SetIndexMode (true);
  215003. ComSmartPtr <IWMProfileManager> profileManager;
  215004. hr = WMCreateProfileManager (&profileManager);
  215005. // This gibberish is the DirectShow profile for a video-only wmv file.
  215006. String prof ("<profile version=\"589824\" storageformat=\"1\" name=\"Quality\" description=\"Quality type for output.\"><streamconfig "
  215007. "majortype=\"{73646976-0000-0010-8000-00AA00389B71}\" streamnumber=\"1\" streamname=\"Video Stream\" inputname=\"Video409\" bitrate=\"894960\" "
  215008. "bufferwindow=\"0\" reliabletransport=\"1\" decodercomplexity=\"AU\" rfc1766langid=\"en-us\"><videomediaprops maxkeyframespacing=\"50000000\" quality=\"90\"/>"
  215009. "<wmmediatype subtype=\"{33564D57-0000-0010-8000-00AA00389B71}\" bfixedsizesamples=\"0\" btemporalcompression=\"1\" lsamplesize=\"0\"> <videoinfoheader "
  215010. "dwbitrate=\"894960\" dwbiterrorrate=\"0\" avgtimeperframe=\"100000\"><rcsource left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/> <rctarget "
  215011. "left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/> <bitmapinfoheader biwidth=\"$WIDTH\" biheight=\"$HEIGHT\" biplanes=\"1\" bibitcount=\"24\" "
  215012. "bicompression=\"WMV3\" bisizeimage=\"0\" bixpelspermeter=\"0\" biypelspermeter=\"0\" biclrused=\"0\" biclrimportant=\"0\"/> "
  215013. "</videoinfoheader></wmmediatype></streamconfig></profile>");
  215014. prof = prof.replace ("$WIDTH", String (width))
  215015. .replace ("$HEIGHT", String (height));
  215016. ComSmartPtr <IWMProfile> currentProfile;
  215017. hr = profileManager->LoadProfileByData ((const WCHAR*) prof, &currentProfile);
  215018. hr = asfConfig->ConfigureFilterUsingProfile (currentProfile);
  215019. if (SUCCEEDED (hr))
  215020. {
  215021. ComSmartPtr <IPin> asfWriterInputPin;
  215022. if (getPin (asfWriter, PINDIR_INPUT, &asfWriterInputPin, "Video Input 01"))
  215023. {
  215024. hr = graphBuilder->Connect (smartTeeCaptureOutputPin, asfWriterInputPin);
  215025. if (SUCCEEDED (hr)
  215026. && ok && activeUsers > 0
  215027. && SUCCEEDED (mediaControl->Run()))
  215028. {
  215029. return true;
  215030. }
  215031. }
  215032. }
  215033. }
  215034. }
  215035. }
  215036. }
  215037. removeFileCaptureFilter();
  215038. if (ok && activeUsers > 0)
  215039. mediaControl->Run();
  215040. return false;
  215041. }
  215042. void removeFileCaptureFilter()
  215043. {
  215044. mediaControl->Stop();
  215045. if (asfWriter != 0)
  215046. {
  215047. graphBuilder->RemoveFilter (asfWriter);
  215048. asfWriter = 0;
  215049. }
  215050. if (ok && activeUsers > 0)
  215051. mediaControl->Run();
  215052. }
  215053. void addListener (CameraImageListener* listenerToAdd)
  215054. {
  215055. const ScopedLock sl (listenerLock);
  215056. if (listeners.size() == 0)
  215057. addUser();
  215058. listeners.addIfNotAlreadyThere (listenerToAdd);
  215059. }
  215060. void removeListener (CameraImageListener* listenerToRemove)
  215061. {
  215062. const ScopedLock sl (listenerLock);
  215063. listeners.removeValue (listenerToRemove);
  215064. if (listeners.size() == 0)
  215065. removeUser();
  215066. }
  215067. void callListeners (const Image& image)
  215068. {
  215069. const ScopedLock sl (listenerLock);
  215070. for (int i = listeners.size(); --i >= 0;)
  215071. {
  215072. CameraImageListener* const l = listeners[i];
  215073. if (l != 0)
  215074. l->imageReceived (image);
  215075. }
  215076. }
  215077. class DShowCaptureViewerComp : public Component,
  215078. public ChangeListener
  215079. {
  215080. public:
  215081. DShowCaptureViewerComp (DShowCameraDeviceInteral* const owner_)
  215082. : owner (owner_)
  215083. {
  215084. setOpaque (true);
  215085. owner->addChangeListener (this);
  215086. owner->addUser();
  215087. owner->viewerComps.add (this);
  215088. setSize (owner_->width, owner_->height);
  215089. }
  215090. ~DShowCaptureViewerComp()
  215091. {
  215092. if (owner != 0)
  215093. {
  215094. owner->viewerComps.removeValue (this);
  215095. owner->removeUser();
  215096. owner->removeChangeListener (this);
  215097. }
  215098. }
  215099. void ownerDeleted()
  215100. {
  215101. owner = 0;
  215102. }
  215103. void paint (Graphics& g)
  215104. {
  215105. g.setColour (Colours::black);
  215106. g.setImageResamplingQuality (Graphics::lowResamplingQuality);
  215107. if (owner != 0)
  215108. owner->drawCurrentImage (g, 0, 0, getWidth(), getHeight());
  215109. else
  215110. g.fillAll (Colours::black);
  215111. }
  215112. void changeListenerCallback (void*)
  215113. {
  215114. repaint();
  215115. }
  215116. private:
  215117. DShowCameraDeviceInteral* owner;
  215118. };
  215119. bool ok;
  215120. int width, height;
  215121. Time firstRecordedTime;
  215122. Array <DShowCaptureViewerComp*> viewerComps;
  215123. private:
  215124. CameraDevice* const owner;
  215125. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  215126. ComSmartPtr <IBaseFilter> filter;
  215127. ComSmartPtr <IBaseFilter> smartTee;
  215128. ComSmartPtr <IGraphBuilder> graphBuilder;
  215129. ComSmartPtr <ISampleGrabber> sampleGrabber;
  215130. ComSmartPtr <IMediaControl> mediaControl;
  215131. ComSmartPtr <IPin> smartTeePreviewOutputPin;
  215132. ComSmartPtr <IPin> smartTeeCaptureOutputPin;
  215133. ComSmartPtr <IBaseFilter> asfWriter;
  215134. int activeUsers;
  215135. Array <int> widths, heights;
  215136. DWORD graphRegistrationID;
  215137. CriticalSection imageSwapLock;
  215138. bool imageNeedsFlipping;
  215139. Image loadingImage;
  215140. Image activeImage;
  215141. bool recordNextFrameTime;
  215142. void getVideoSizes (IAMStreamConfig* const streamConfig)
  215143. {
  215144. widths.clear();
  215145. heights.clear();
  215146. int count = 0, size = 0;
  215147. streamConfig->GetNumberOfCapabilities (&count, &size);
  215148. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  215149. {
  215150. for (int i = 0; i < count; ++i)
  215151. {
  215152. VIDEO_STREAM_CONFIG_CAPS scc;
  215153. AM_MEDIA_TYPE* config;
  215154. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  215155. if (SUCCEEDED (hr))
  215156. {
  215157. const int w = scc.InputSize.cx;
  215158. const int h = scc.InputSize.cy;
  215159. bool duplicate = false;
  215160. for (int j = widths.size(); --j >= 0;)
  215161. {
  215162. if (w == widths.getUnchecked (j) && h == heights.getUnchecked (j))
  215163. {
  215164. duplicate = true;
  215165. break;
  215166. }
  215167. }
  215168. if (! duplicate)
  215169. {
  215170. DBG ("Camera capture size: " + String (w) + ", " + String (h));
  215171. widths.add (w);
  215172. heights.add (h);
  215173. }
  215174. deleteMediaType (config);
  215175. }
  215176. }
  215177. }
  215178. }
  215179. bool selectVideoSize (IAMStreamConfig* const streamConfig,
  215180. const int minWidth, const int minHeight,
  215181. const int maxWidth, const int maxHeight)
  215182. {
  215183. int count = 0, size = 0, bestArea = 0, bestIndex = -1;
  215184. streamConfig->GetNumberOfCapabilities (&count, &size);
  215185. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  215186. {
  215187. AM_MEDIA_TYPE* config;
  215188. VIDEO_STREAM_CONFIG_CAPS scc;
  215189. for (int i = 0; i < count; ++i)
  215190. {
  215191. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  215192. if (SUCCEEDED (hr))
  215193. {
  215194. if (scc.InputSize.cx >= minWidth
  215195. && scc.InputSize.cy >= minHeight
  215196. && scc.InputSize.cx <= maxWidth
  215197. && scc.InputSize.cy <= maxHeight)
  215198. {
  215199. int area = scc.InputSize.cx * scc.InputSize.cy;
  215200. if (area > bestArea)
  215201. {
  215202. bestIndex = i;
  215203. bestArea = area;
  215204. }
  215205. }
  215206. deleteMediaType (config);
  215207. }
  215208. }
  215209. if (bestIndex >= 0)
  215210. {
  215211. HRESULT hr = streamConfig->GetStreamCaps (bestIndex, &config, (BYTE*) &scc);
  215212. hr = streamConfig->SetFormat (config);
  215213. deleteMediaType (config);
  215214. return SUCCEEDED (hr);
  215215. }
  215216. }
  215217. return false;
  215218. }
  215219. static bool getPin (IBaseFilter* filter, const PIN_DIRECTION wantedDirection, IPin** result, const char* pinName = 0)
  215220. {
  215221. ComSmartPtr <IEnumPins> enumerator;
  215222. ComSmartPtr <IPin> pin;
  215223. filter->EnumPins (&enumerator);
  215224. while (enumerator->Next (1, &pin, 0) == S_OK)
  215225. {
  215226. PIN_DIRECTION dir;
  215227. pin->QueryDirection (&dir);
  215228. if (wantedDirection == dir)
  215229. {
  215230. PIN_INFO info;
  215231. zerostruct (info);
  215232. pin->QueryPinInfo (&info);
  215233. if (pinName == 0 || String (pinName).equalsIgnoreCase (String (info.achName)))
  215234. {
  215235. pin->AddRef();
  215236. *result = pin;
  215237. return true;
  215238. }
  215239. }
  215240. }
  215241. return false;
  215242. }
  215243. bool connectFilters (IBaseFilter* const first, IBaseFilter* const second) const
  215244. {
  215245. ComSmartPtr <IPin> in, out;
  215246. return getPin (first, PINDIR_OUTPUT, &out)
  215247. && getPin (second, PINDIR_INPUT, &in)
  215248. && SUCCEEDED (graphBuilder->Connect (out, in));
  215249. }
  215250. bool addGraphToRot()
  215251. {
  215252. ComSmartPtr <IRunningObjectTable> rot;
  215253. if (FAILED (GetRunningObjectTable (0, &rot)))
  215254. return false;
  215255. ComSmartPtr <IMoniker> moniker;
  215256. WCHAR buffer[128];
  215257. HRESULT hr = CreateItemMoniker (_T("!"), buffer, &moniker);
  215258. if (FAILED (hr))
  215259. return false;
  215260. graphRegistrationID = 0;
  215261. return SUCCEEDED (rot->Register (0, graphBuilder, moniker, &graphRegistrationID));
  215262. }
  215263. void removeGraphFromRot()
  215264. {
  215265. ComSmartPtr <IRunningObjectTable> rot;
  215266. if (SUCCEEDED (GetRunningObjectTable (0, &rot)))
  215267. rot->Revoke (graphRegistrationID);
  215268. }
  215269. static void deleteMediaType (AM_MEDIA_TYPE* const pmt)
  215270. {
  215271. if (pmt->cbFormat != 0)
  215272. CoTaskMemFree ((PVOID) pmt->pbFormat);
  215273. if (pmt->pUnk != 0)
  215274. pmt->pUnk->Release();
  215275. CoTaskMemFree (pmt);
  215276. }
  215277. class GrabberCallback : public ComBaseClassHelper <ISampleGrabberCB>
  215278. {
  215279. public:
  215280. GrabberCallback (DShowCameraDeviceInteral& owner_)
  215281. : owner (owner_)
  215282. {
  215283. }
  215284. STDMETHODIMP SampleCB (double /*SampleTime*/, IMediaSample* /*pSample*/)
  215285. {
  215286. return E_FAIL;
  215287. }
  215288. STDMETHODIMP BufferCB (double time, BYTE* buffer, long bufferSize)
  215289. {
  215290. owner.handleFrame (time, buffer, bufferSize);
  215291. return S_OK;
  215292. }
  215293. private:
  215294. DShowCameraDeviceInteral& owner;
  215295. GrabberCallback (const GrabberCallback&);
  215296. GrabberCallback& operator= (const GrabberCallback&);
  215297. };
  215298. ComSmartPtr <GrabberCallback> callback;
  215299. Array <CameraImageListener*> listeners;
  215300. CriticalSection listenerLock;
  215301. DShowCameraDeviceInteral (const DShowCameraDeviceInteral&);
  215302. DShowCameraDeviceInteral& operator= (const DShowCameraDeviceInteral&);
  215303. };
  215304. CameraDevice::CameraDevice (const String& name_, int /*index*/)
  215305. : name (name_)
  215306. {
  215307. isRecording = false;
  215308. }
  215309. CameraDevice::~CameraDevice()
  215310. {
  215311. stopRecording();
  215312. delete static_cast <DShowCameraDeviceInteral*> (internal);
  215313. internal = 0;
  215314. }
  215315. Component* CameraDevice::createViewerComponent()
  215316. {
  215317. return new DShowCameraDeviceInteral::DShowCaptureViewerComp (static_cast <DShowCameraDeviceInteral*> (internal));
  215318. }
  215319. const String CameraDevice::getFileExtension()
  215320. {
  215321. return ".wmv";
  215322. }
  215323. void CameraDevice::startRecordingToFile (const File& file, int quality)
  215324. {
  215325. stopRecording();
  215326. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215327. d->addUser();
  215328. isRecording = d->createFileCaptureFilter (file);
  215329. }
  215330. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  215331. {
  215332. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215333. return d->firstRecordedTime;
  215334. }
  215335. void CameraDevice::stopRecording()
  215336. {
  215337. if (isRecording)
  215338. {
  215339. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215340. d->removeFileCaptureFilter();
  215341. d->removeUser();
  215342. isRecording = false;
  215343. }
  215344. }
  215345. void CameraDevice::addListener (CameraImageListener* listenerToAdd)
  215346. {
  215347. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215348. if (listenerToAdd != 0)
  215349. d->addListener (listenerToAdd);
  215350. }
  215351. void CameraDevice::removeListener (CameraImageListener* listenerToRemove)
  215352. {
  215353. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215354. if (listenerToRemove != 0)
  215355. d->removeListener (listenerToRemove);
  215356. }
  215357. static ComSmartPtr <IBaseFilter> enumerateCameras (StringArray* const names,
  215358. const int deviceIndexToOpen,
  215359. String& name)
  215360. {
  215361. int index = 0;
  215362. ComSmartPtr <IBaseFilter> result;
  215363. ComSmartPtr <ICreateDevEnum> pDevEnum;
  215364. HRESULT hr = pDevEnum.CoCreateInstance (CLSID_SystemDeviceEnum);
  215365. if (SUCCEEDED (hr))
  215366. {
  215367. ComSmartPtr <IEnumMoniker> enumerator;
  215368. hr = pDevEnum->CreateClassEnumerator (CLSID_VideoInputDeviceCategory, &enumerator, 0);
  215369. if (SUCCEEDED (hr) && enumerator != 0)
  215370. {
  215371. ComSmartPtr <IBaseFilter> captureFilter;
  215372. ComSmartPtr <IMoniker> moniker;
  215373. ULONG fetched;
  215374. while (enumerator->Next (1, &moniker, &fetched) == S_OK)
  215375. {
  215376. hr = moniker->BindToObject (0, 0, IID_IBaseFilter, (void**) &captureFilter);
  215377. if (SUCCEEDED (hr))
  215378. {
  215379. ComSmartPtr <IPropertyBag> propertyBag;
  215380. hr = moniker->BindToStorage (0, 0, IID_IPropertyBag, (void**) &propertyBag);
  215381. if (SUCCEEDED (hr))
  215382. {
  215383. VARIANT var;
  215384. var.vt = VT_BSTR;
  215385. hr = propertyBag->Read (_T("FriendlyName"), &var, 0);
  215386. propertyBag = 0;
  215387. if (SUCCEEDED (hr))
  215388. {
  215389. if (names != 0)
  215390. names->add (var.bstrVal);
  215391. if (index == deviceIndexToOpen)
  215392. {
  215393. name = var.bstrVal;
  215394. result = captureFilter;
  215395. captureFilter = 0;
  215396. break;
  215397. }
  215398. ++index;
  215399. }
  215400. moniker = 0;
  215401. }
  215402. captureFilter = 0;
  215403. }
  215404. }
  215405. }
  215406. }
  215407. return result;
  215408. }
  215409. const StringArray CameraDevice::getAvailableDevices()
  215410. {
  215411. StringArray devs;
  215412. String dummy;
  215413. enumerateCameras (&devs, -1, dummy);
  215414. return devs;
  215415. }
  215416. CameraDevice* CameraDevice::openDevice (int index,
  215417. int minWidth, int minHeight,
  215418. int maxWidth, int maxHeight)
  215419. {
  215420. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  215421. HRESULT hr = captureGraphBuilder.CoCreateInstance (CLSID_CaptureGraphBuilder2);
  215422. if (SUCCEEDED (hr))
  215423. {
  215424. String name;
  215425. const ComSmartPtr <IBaseFilter> filter (enumerateCameras (0, index, name));
  215426. if (filter != 0)
  215427. {
  215428. ScopedPointer <CameraDevice> cam (new CameraDevice (name, index));
  215429. DShowCameraDeviceInteral* const intern
  215430. = new DShowCameraDeviceInteral (cam, captureGraphBuilder, filter,
  215431. minWidth, minHeight, maxWidth, maxHeight);
  215432. cam->internal = intern;
  215433. if (intern->ok)
  215434. return cam.release();
  215435. }
  215436. }
  215437. return 0;
  215438. }
  215439. #endif
  215440. /*** End of inlined file: juce_win32_CameraDevice.cpp ***/
  215441. #endif
  215442. // Auto-link the other win32 libs that are needed by library calls..
  215443. #if (JUCE_AMALGAMATED_TEMPLATE || defined (JUCE_DLL_BUILD)) && JUCE_MSVC && ! DONT_AUTOLINK_TO_WIN32_LIBRARIES
  215444. /*** Start of inlined file: juce_win32_AutoLinkLibraries.h ***/
  215445. // Auto-links to various win32 libs that are needed by library calls..
  215446. #pragma comment(lib, "kernel32.lib")
  215447. #pragma comment(lib, "user32.lib")
  215448. #pragma comment(lib, "shell32.lib")
  215449. #pragma comment(lib, "gdi32.lib")
  215450. #pragma comment(lib, "vfw32.lib")
  215451. #pragma comment(lib, "comdlg32.lib")
  215452. #pragma comment(lib, "winmm.lib")
  215453. #pragma comment(lib, "wininet.lib")
  215454. #pragma comment(lib, "ole32.lib")
  215455. #pragma comment(lib, "oleaut32.lib")
  215456. #pragma comment(lib, "advapi32.lib")
  215457. #pragma comment(lib, "ws2_32.lib")
  215458. #pragma comment(lib, "comsupp.lib")
  215459. #pragma comment(lib, "version.lib")
  215460. #if JUCE_OPENGL
  215461. #pragma comment(lib, "OpenGL32.Lib")
  215462. #pragma comment(lib, "GlU32.Lib")
  215463. #endif
  215464. #if JUCE_QUICKTIME
  215465. #pragma comment (lib, "QTMLClient.lib")
  215466. #endif
  215467. #if JUCE_USE_CAMERA
  215468. #pragma comment (lib, "Strmiids.lib")
  215469. #pragma comment (lib, "wmvcore.lib")
  215470. #endif
  215471. /*** End of inlined file: juce_win32_AutoLinkLibraries.h ***/
  215472. #endif
  215473. END_JUCE_NAMESPACE
  215474. #endif
  215475. /*** End of inlined file: juce_win32_NativeCode.cpp ***/
  215476. #endif
  215477. #if JUCE_LINUX
  215478. /*** Start of inlined file: juce_linux_NativeCode.cpp ***/
  215479. /*
  215480. This file wraps together all the mac-specific code, so that
  215481. we can include all the native headers just once, and compile all our
  215482. platform-specific stuff in one big lump, keeping it out of the way of
  215483. the rest of the codebase.
  215484. */
  215485. #if JUCE_LINUX
  215486. BEGIN_JUCE_NAMESPACE
  215487. #define JUCE_INCLUDED_FILE 1
  215488. // Now include the actual code files..
  215489. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  215490. /*
  215491. This file contains posix routines that are common to both the Linux and Mac builds.
  215492. It gets included directly in the cpp files for these platforms.
  215493. */
  215494. CriticalSection::CriticalSection() throw()
  215495. {
  215496. pthread_mutexattr_t atts;
  215497. pthread_mutexattr_init (&atts);
  215498. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  215499. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  215500. pthread_mutex_init (&internal, &atts);
  215501. }
  215502. CriticalSection::~CriticalSection() throw()
  215503. {
  215504. pthread_mutex_destroy (&internal);
  215505. }
  215506. void CriticalSection::enter() const throw()
  215507. {
  215508. pthread_mutex_lock (&internal);
  215509. }
  215510. bool CriticalSection::tryEnter() const throw()
  215511. {
  215512. return pthread_mutex_trylock (&internal) == 0;
  215513. }
  215514. void CriticalSection::exit() const throw()
  215515. {
  215516. pthread_mutex_unlock (&internal);
  215517. }
  215518. class WaitableEventImpl
  215519. {
  215520. public:
  215521. WaitableEventImpl (const bool manualReset_)
  215522. : triggered (false),
  215523. manualReset (manualReset_)
  215524. {
  215525. pthread_cond_init (&condition, 0);
  215526. pthread_mutexattr_t atts;
  215527. pthread_mutexattr_init (&atts);
  215528. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  215529. pthread_mutex_init (&mutex, &atts);
  215530. }
  215531. ~WaitableEventImpl()
  215532. {
  215533. pthread_cond_destroy (&condition);
  215534. pthread_mutex_destroy (&mutex);
  215535. }
  215536. bool wait (const int timeOutMillisecs) throw()
  215537. {
  215538. pthread_mutex_lock (&mutex);
  215539. if (! triggered)
  215540. {
  215541. if (timeOutMillisecs < 0)
  215542. {
  215543. do
  215544. {
  215545. pthread_cond_wait (&condition, &mutex);
  215546. }
  215547. while (! triggered);
  215548. }
  215549. else
  215550. {
  215551. struct timeval now;
  215552. gettimeofday (&now, 0);
  215553. struct timespec time;
  215554. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  215555. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  215556. if (time.tv_nsec >= 1000000000)
  215557. {
  215558. time.tv_nsec -= 1000000000;
  215559. time.tv_sec++;
  215560. }
  215561. do
  215562. {
  215563. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  215564. {
  215565. pthread_mutex_unlock (&mutex);
  215566. return false;
  215567. }
  215568. }
  215569. while (! triggered);
  215570. }
  215571. }
  215572. if (! manualReset)
  215573. triggered = false;
  215574. pthread_mutex_unlock (&mutex);
  215575. return true;
  215576. }
  215577. void signal() throw()
  215578. {
  215579. pthread_mutex_lock (&mutex);
  215580. triggered = true;
  215581. pthread_cond_broadcast (&condition);
  215582. pthread_mutex_unlock (&mutex);
  215583. }
  215584. void reset() throw()
  215585. {
  215586. pthread_mutex_lock (&mutex);
  215587. triggered = false;
  215588. pthread_mutex_unlock (&mutex);
  215589. }
  215590. private:
  215591. pthread_cond_t condition;
  215592. pthread_mutex_t mutex;
  215593. bool triggered;
  215594. const bool manualReset;
  215595. WaitableEventImpl (const WaitableEventImpl&);
  215596. WaitableEventImpl& operator= (const WaitableEventImpl&);
  215597. };
  215598. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  215599. : internal (new WaitableEventImpl (manualReset))
  215600. {
  215601. }
  215602. WaitableEvent::~WaitableEvent() throw()
  215603. {
  215604. delete static_cast <WaitableEventImpl*> (internal);
  215605. }
  215606. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  215607. {
  215608. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  215609. }
  215610. void WaitableEvent::signal() const throw()
  215611. {
  215612. static_cast <WaitableEventImpl*> (internal)->signal();
  215613. }
  215614. void WaitableEvent::reset() const throw()
  215615. {
  215616. static_cast <WaitableEventImpl*> (internal)->reset();
  215617. }
  215618. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  215619. {
  215620. struct timespec time;
  215621. time.tv_sec = millisecs / 1000;
  215622. time.tv_nsec = (millisecs % 1000) * 1000000;
  215623. nanosleep (&time, 0);
  215624. }
  215625. const juce_wchar File::separator = '/';
  215626. const String File::separatorString ("/");
  215627. const File File::getCurrentWorkingDirectory()
  215628. {
  215629. HeapBlock<char> heapBuffer;
  215630. char localBuffer [1024];
  215631. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  215632. int bufferSize = 4096;
  215633. while (cwd == 0 && errno == ERANGE)
  215634. {
  215635. heapBuffer.malloc (bufferSize);
  215636. cwd = getcwd (heapBuffer, bufferSize - 1);
  215637. bufferSize += 1024;
  215638. }
  215639. return File (String::fromUTF8 (cwd));
  215640. }
  215641. bool File::setAsCurrentWorkingDirectory() const
  215642. {
  215643. return chdir (getFullPathName().toUTF8()) == 0;
  215644. }
  215645. static bool juce_stat (const String& fileName, struct stat& info)
  215646. {
  215647. return fileName.isNotEmpty()
  215648. && (stat (fileName.toUTF8(), &info) == 0);
  215649. }
  215650. bool File::isDirectory() const
  215651. {
  215652. struct stat info;
  215653. return fullPath.isEmpty()
  215654. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  215655. }
  215656. bool File::exists() const
  215657. {
  215658. return fullPath.isNotEmpty()
  215659. && access (fullPath.toUTF8(), F_OK) == 0;
  215660. }
  215661. bool File::existsAsFile() const
  215662. {
  215663. return exists() && ! isDirectory();
  215664. }
  215665. int64 File::getSize() const
  215666. {
  215667. struct stat info;
  215668. return juce_stat (fullPath, info) ? info.st_size : 0;
  215669. }
  215670. bool File::hasWriteAccess() const
  215671. {
  215672. if (exists())
  215673. return access (fullPath.toUTF8(), W_OK) == 0;
  215674. if ((! isDirectory()) && fullPath.containsChar (separator))
  215675. return getParentDirectory().hasWriteAccess();
  215676. return false;
  215677. }
  215678. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  215679. {
  215680. struct stat info;
  215681. const int res = stat (fullPath.toUTF8(), &info);
  215682. if (res != 0)
  215683. return false;
  215684. info.st_mode &= 0777; // Just permissions
  215685. if (shouldBeReadOnly)
  215686. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  215687. else
  215688. // Give everybody write permission?
  215689. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  215690. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  215691. }
  215692. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  215693. {
  215694. modificationTime = 0;
  215695. accessTime = 0;
  215696. creationTime = 0;
  215697. struct stat info;
  215698. const int res = stat (fullPath.toUTF8(), &info);
  215699. if (res == 0)
  215700. {
  215701. modificationTime = (int64) info.st_mtime * 1000;
  215702. accessTime = (int64) info.st_atime * 1000;
  215703. creationTime = (int64) info.st_ctime * 1000;
  215704. }
  215705. }
  215706. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  215707. {
  215708. struct utimbuf times;
  215709. times.actime = (time_t) (accessTime / 1000);
  215710. times.modtime = (time_t) (modificationTime / 1000);
  215711. return utime (fullPath.toUTF8(), &times) == 0;
  215712. }
  215713. bool File::deleteFile() const
  215714. {
  215715. if (! exists())
  215716. return true;
  215717. else if (isDirectory())
  215718. return rmdir (fullPath.toUTF8()) == 0;
  215719. else
  215720. return remove (fullPath.toUTF8()) == 0;
  215721. }
  215722. bool File::moveInternal (const File& dest) const
  215723. {
  215724. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  215725. return true;
  215726. if (hasWriteAccess() && copyInternal (dest))
  215727. {
  215728. if (deleteFile())
  215729. return true;
  215730. dest.deleteFile();
  215731. }
  215732. return false;
  215733. }
  215734. void File::createDirectoryInternal (const String& fileName) const
  215735. {
  215736. mkdir (fileName.toUTF8(), 0777);
  215737. }
  215738. void* juce_fileOpen (const File& file, bool forWriting)
  215739. {
  215740. int flags = O_RDONLY;
  215741. if (forWriting)
  215742. {
  215743. if (file.exists())
  215744. {
  215745. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  215746. if (f != -1)
  215747. lseek (f, 0, SEEK_END);
  215748. return (void*) f;
  215749. }
  215750. else
  215751. {
  215752. flags = O_RDWR + O_CREAT;
  215753. }
  215754. }
  215755. return (void*) open (file.getFullPathName().toUTF8(), flags, 00644);
  215756. }
  215757. void juce_fileClose (void* handle)
  215758. {
  215759. if (handle != 0)
  215760. close ((int) (pointer_sized_int) handle);
  215761. }
  215762. int juce_fileRead (void* handle, void* buffer, int size)
  215763. {
  215764. if (handle != 0)
  215765. return jmax (0, (int) read ((int) (pointer_sized_int) handle, buffer, size));
  215766. return 0;
  215767. }
  215768. int juce_fileWrite (void* handle, const void* buffer, int size)
  215769. {
  215770. if (handle != 0)
  215771. return (int) write ((int) (pointer_sized_int) handle, buffer, size);
  215772. return 0;
  215773. }
  215774. int64 juce_fileSetPosition (void* handle, int64 pos)
  215775. {
  215776. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  215777. return pos;
  215778. return -1;
  215779. }
  215780. int64 FileOutputStream::getPositionInternal() const
  215781. {
  215782. if (fileHandle != 0)
  215783. return lseek ((int) (pointer_sized_int) fileHandle, 0, SEEK_CUR);
  215784. return -1;
  215785. }
  215786. void FileOutputStream::flushInternal()
  215787. {
  215788. if (fileHandle != 0)
  215789. fsync ((int) (pointer_sized_int) fileHandle);
  215790. }
  215791. const File juce_getExecutableFile()
  215792. {
  215793. Dl_info exeInfo;
  215794. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  215795. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  215796. }
  215797. // if this file doesn't exist, find a parent of it that does..
  215798. static bool juce_doStatFS (File f, struct statfs& result)
  215799. {
  215800. for (int i = 5; --i >= 0;)
  215801. {
  215802. if (f.exists())
  215803. break;
  215804. f = f.getParentDirectory();
  215805. }
  215806. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  215807. }
  215808. int64 File::getBytesFreeOnVolume() const
  215809. {
  215810. struct statfs buf;
  215811. if (juce_doStatFS (*this, buf))
  215812. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  215813. return 0;
  215814. }
  215815. int64 File::getVolumeTotalSize() const
  215816. {
  215817. struct statfs buf;
  215818. if (juce_doStatFS (*this, buf))
  215819. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  215820. return 0;
  215821. }
  215822. const String File::getVolumeLabel() const
  215823. {
  215824. #if JUCE_MAC
  215825. struct VolAttrBuf
  215826. {
  215827. u_int32_t length;
  215828. attrreference_t mountPointRef;
  215829. char mountPointSpace [MAXPATHLEN];
  215830. } attrBuf;
  215831. struct attrlist attrList;
  215832. zerostruct (attrList);
  215833. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  215834. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  215835. File f (*this);
  215836. for (;;)
  215837. {
  215838. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  215839. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  215840. (int) attrBuf.mountPointRef.attr_length);
  215841. const File parent (f.getParentDirectory());
  215842. if (f == parent)
  215843. break;
  215844. f = parent;
  215845. }
  215846. #endif
  215847. return String::empty;
  215848. }
  215849. int File::getVolumeSerialNumber() const
  215850. {
  215851. return 0; // xxx
  215852. }
  215853. void juce_runSystemCommand (const String& command)
  215854. {
  215855. int result = system (command.toUTF8());
  215856. (void) result;
  215857. }
  215858. const String juce_getOutputFromCommand (const String& command)
  215859. {
  215860. // slight bodge here, as we just pipe the output into a temp file and read it...
  215861. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  215862. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  215863. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  215864. String result (tempFile.loadFileAsString());
  215865. tempFile.deleteFile();
  215866. return result;
  215867. }
  215868. class InterProcessLock::Pimpl
  215869. {
  215870. public:
  215871. Pimpl (const String& name, const int timeOutMillisecs)
  215872. : handle (0), refCount (1)
  215873. {
  215874. #if JUCE_MAC
  215875. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  215876. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  215877. #else
  215878. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  215879. #endif
  215880. temp.create();
  215881. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  215882. if (handle != 0)
  215883. {
  215884. struct flock fl;
  215885. zerostruct (fl);
  215886. fl.l_whence = SEEK_SET;
  215887. fl.l_type = F_WRLCK;
  215888. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  215889. for (;;)
  215890. {
  215891. const int result = fcntl (handle, F_SETLK, &fl);
  215892. if (result >= 0)
  215893. return;
  215894. if (errno != EINTR)
  215895. {
  215896. if (timeOutMillisecs == 0
  215897. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  215898. break;
  215899. Thread::sleep (10);
  215900. }
  215901. }
  215902. }
  215903. closeFile();
  215904. }
  215905. ~Pimpl()
  215906. {
  215907. closeFile();
  215908. }
  215909. void closeFile()
  215910. {
  215911. if (handle != 0)
  215912. {
  215913. struct flock fl;
  215914. zerostruct (fl);
  215915. fl.l_whence = SEEK_SET;
  215916. fl.l_type = F_UNLCK;
  215917. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  215918. {}
  215919. close (handle);
  215920. handle = 0;
  215921. }
  215922. }
  215923. int handle, refCount;
  215924. };
  215925. InterProcessLock::InterProcessLock (const String& name_)
  215926. : name (name_)
  215927. {
  215928. }
  215929. InterProcessLock::~InterProcessLock()
  215930. {
  215931. }
  215932. bool InterProcessLock::enter (const int timeOutMillisecs)
  215933. {
  215934. const ScopedLock sl (lock);
  215935. if (pimpl == 0)
  215936. {
  215937. pimpl = new Pimpl (name, timeOutMillisecs);
  215938. if (pimpl->handle == 0)
  215939. pimpl = 0;
  215940. }
  215941. else
  215942. {
  215943. pimpl->refCount++;
  215944. }
  215945. return pimpl != 0;
  215946. }
  215947. void InterProcessLock::exit()
  215948. {
  215949. const ScopedLock sl (lock);
  215950. // Trying to release the lock too many times!
  215951. jassert (pimpl != 0);
  215952. if (pimpl != 0 && --(pimpl->refCount) == 0)
  215953. pimpl = 0;
  215954. }
  215955. /*** End of inlined file: juce_posix_SharedCode.h ***/
  215956. /*** Start of inlined file: juce_linux_Files.cpp ***/
  215957. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  215958. // compiled on its own).
  215959. #if JUCE_INCLUDED_FILE
  215960. static const short U_ISOFS_SUPER_MAGIC = 0x9660; // linux/iso_fs.h
  215961. static const short U_MSDOS_SUPER_MAGIC = 0x4d44; // linux/msdos_fs.h
  215962. static const short U_NFS_SUPER_MAGIC = 0x6969; // linux/nfs_fs.h
  215963. static const short U_SMB_SUPER_MAGIC = 0x517B; // linux/smb_fs.h
  215964. bool File::copyInternal (const File& dest) const
  215965. {
  215966. FileInputStream in (*this);
  215967. if (dest.deleteFile())
  215968. {
  215969. {
  215970. FileOutputStream out (dest);
  215971. if (out.failedToOpen())
  215972. return false;
  215973. if (out.writeFromInputStream (in, -1) == getSize())
  215974. return true;
  215975. }
  215976. dest.deleteFile();
  215977. }
  215978. return false;
  215979. }
  215980. void File::findFileSystemRoots (Array<File>& destArray)
  215981. {
  215982. destArray.add (File ("/"));
  215983. }
  215984. bool File::isOnCDRomDrive() const
  215985. {
  215986. struct statfs buf;
  215987. return statfs (getFullPathName().toUTF8(), &buf) == 0
  215988. && buf.f_type == U_ISOFS_SUPER_MAGIC;
  215989. }
  215990. bool File::isOnHardDisk() const
  215991. {
  215992. struct statfs buf;
  215993. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  215994. {
  215995. switch (buf.f_type)
  215996. {
  215997. case U_ISOFS_SUPER_MAGIC: // CD-ROM
  215998. case U_MSDOS_SUPER_MAGIC: // Probably floppy (but could be mounted FAT filesystem)
  215999. case U_NFS_SUPER_MAGIC: // Network NFS
  216000. case U_SMB_SUPER_MAGIC: // Network Samba
  216001. return false;
  216002. default:
  216003. // Assume anything else is a hard-disk (but note it could
  216004. // be a RAM disk. There isn't a good way of determining
  216005. // this for sure)
  216006. return true;
  216007. }
  216008. }
  216009. // Assume so if this fails for some reason
  216010. return true;
  216011. }
  216012. bool File::isOnRemovableDrive() const
  216013. {
  216014. jassertfalse; // xxx not implemented for linux!
  216015. return false;
  216016. }
  216017. bool File::isHidden() const
  216018. {
  216019. return getFileName().startsWithChar ('.');
  216020. }
  216021. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  216022. const File File::getSpecialLocation (const SpecialLocationType type)
  216023. {
  216024. switch (type)
  216025. {
  216026. case userHomeDirectory:
  216027. {
  216028. const char* homeDir = getenv ("HOME");
  216029. if (homeDir == 0)
  216030. {
  216031. struct passwd* const pw = getpwuid (getuid());
  216032. if (pw != 0)
  216033. homeDir = pw->pw_dir;
  216034. }
  216035. return File (String::fromUTF8 (homeDir));
  216036. }
  216037. case userDocumentsDirectory:
  216038. case userMusicDirectory:
  216039. case userMoviesDirectory:
  216040. case userApplicationDataDirectory:
  216041. return File ("~");
  216042. case userDesktopDirectory:
  216043. return File ("~/Desktop");
  216044. case commonApplicationDataDirectory:
  216045. return File ("/var");
  216046. case globalApplicationsDirectory:
  216047. return File ("/usr");
  216048. case tempDirectory:
  216049. {
  216050. File tmp ("/var/tmp");
  216051. if (! tmp.isDirectory())
  216052. {
  216053. tmp = "/tmp";
  216054. if (! tmp.isDirectory())
  216055. tmp = File::getCurrentWorkingDirectory();
  216056. }
  216057. return tmp;
  216058. }
  216059. case invokedExecutableFile:
  216060. if (juce_Argv0 != 0)
  216061. return File (String::fromUTF8 (juce_Argv0));
  216062. // deliberate fall-through...
  216063. case currentExecutableFile:
  216064. case currentApplicationFile:
  216065. return juce_getExecutableFile();
  216066. default:
  216067. jassertfalse; // unknown type?
  216068. break;
  216069. }
  216070. return File::nonexistent;
  216071. }
  216072. const String File::getVersion() const
  216073. {
  216074. return String::empty; // xxx not yet implemented
  216075. }
  216076. const File File::getLinkedTarget() const
  216077. {
  216078. char buffer [4096];
  216079. size_t numChars = readlink (getFullPathName().toUTF8(),
  216080. buffer, sizeof (buffer));
  216081. if (numChars > 0 && numChars <= sizeof (buffer))
  216082. return File (String::fromUTF8 (buffer, (int) numChars));
  216083. return *this;
  216084. }
  216085. bool File::moveToTrash() const
  216086. {
  216087. if (! exists())
  216088. return true;
  216089. File trashCan ("~/.Trash");
  216090. if (! trashCan.isDirectory())
  216091. trashCan = "~/.local/share/Trash/files";
  216092. if (! trashCan.isDirectory())
  216093. return false;
  216094. return moveFileTo (trashCan.getNonexistentChildFile (getFileNameWithoutExtension(),
  216095. getFileExtension()));
  216096. }
  216097. class DirectoryIterator::NativeIterator::Pimpl
  216098. {
  216099. public:
  216100. Pimpl (const File& directory, const String& wildCard_)
  216101. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  216102. wildCard (wildCard_),
  216103. dir (opendir (directory.getFullPathName().toUTF8()))
  216104. {
  216105. if (wildCard == "*.*")
  216106. wildCard = "*";
  216107. wildcardUTF8 = wildCard.toUTF8();
  216108. }
  216109. ~Pimpl()
  216110. {
  216111. if (dir != 0)
  216112. closedir (dir);
  216113. }
  216114. bool next (String& filenameFound,
  216115. bool* const isDir, bool* const isHidden, int64* const fileSize,
  216116. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  216117. {
  216118. if (dir == 0)
  216119. return false;
  216120. for (;;)
  216121. {
  216122. struct dirent* const de = readdir (dir);
  216123. if (de == 0)
  216124. return false;
  216125. if (fnmatch (wildcardUTF8, de->d_name, FNM_CASEFOLD) == 0)
  216126. {
  216127. filenameFound = String::fromUTF8 (de->d_name);
  216128. const String path (parentDir + filenameFound);
  216129. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  216130. {
  216131. struct stat info;
  216132. const bool statOk = juce_stat (path, info);
  216133. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  216134. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  216135. if (modTime != 0) *modTime = statOk ? (int64) info.st_mtime * 1000 : 0;
  216136. if (creationTime != 0) *creationTime = statOk ? (int64) info.st_ctime * 1000 : 0;
  216137. }
  216138. if (isHidden != 0)
  216139. *isHidden = filenameFound.startsWithChar ('.');
  216140. if (isReadOnly != 0)
  216141. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  216142. return true;
  216143. }
  216144. }
  216145. }
  216146. private:
  216147. String parentDir, wildCard;
  216148. const char* wildcardUTF8;
  216149. DIR* dir;
  216150. Pimpl (const Pimpl&);
  216151. Pimpl& operator= (const Pimpl&);
  216152. };
  216153. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  216154. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  216155. {
  216156. }
  216157. DirectoryIterator::NativeIterator::~NativeIterator()
  216158. {
  216159. }
  216160. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  216161. bool* const isDir, bool* const isHidden, int64* const fileSize,
  216162. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  216163. {
  216164. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  216165. }
  216166. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  216167. {
  216168. String cmdString (fileName.replace (" ", "\\ ",false));
  216169. cmdString << " " << parameters;
  216170. if (URL::isProbablyAWebsiteURL (fileName)
  216171. || cmdString.startsWithIgnoreCase ("file:")
  216172. || URL::isProbablyAnEmailAddress (fileName))
  216173. {
  216174. // create a command that tries to launch a bunch of likely browsers
  216175. const char* const browserNames[] = { "xdg-open", "/etc/alternatives/x-www-browser", "firefox", "mozilla", "konqueror", "opera" };
  216176. StringArray cmdLines;
  216177. for (int i = 0; i < numElementsInArray (browserNames); ++i)
  216178. cmdLines.add (String (browserNames[i]) + " " + cmdString.trim().quoted());
  216179. cmdString = cmdLines.joinIntoString (" || ");
  216180. }
  216181. const char* const argv[4] = { "/bin/sh", "-c", cmdString.toUTF8(), 0 };
  216182. const int cpid = fork();
  216183. if (cpid == 0)
  216184. {
  216185. setsid();
  216186. // Child process
  216187. execve (argv[0], (char**) argv, environ);
  216188. exit (0);
  216189. }
  216190. return cpid >= 0;
  216191. }
  216192. void File::revealToUser() const
  216193. {
  216194. if (isDirectory())
  216195. startAsProcess();
  216196. else if (getParentDirectory().exists())
  216197. getParentDirectory().startAsProcess();
  216198. }
  216199. #endif
  216200. /*** End of inlined file: juce_linux_Files.cpp ***/
  216201. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  216202. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  216203. // compiled on its own).
  216204. #if JUCE_INCLUDED_FILE
  216205. struct NamedPipeInternal
  216206. {
  216207. String pipeInName, pipeOutName;
  216208. int pipeIn, pipeOut;
  216209. bool volatile createdPipe, blocked, stopReadOperation;
  216210. static void signalHandler (int) {}
  216211. };
  216212. void NamedPipe::cancelPendingReads()
  216213. {
  216214. while (internal != 0 && ((NamedPipeInternal*) internal)->blocked)
  216215. {
  216216. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  216217. intern->stopReadOperation = true;
  216218. char buffer [1] = { 0 };
  216219. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  216220. (void) bytesWritten;
  216221. int timeout = 2000;
  216222. while (intern->blocked && --timeout >= 0)
  216223. Thread::sleep (2);
  216224. intern->stopReadOperation = false;
  216225. }
  216226. }
  216227. void NamedPipe::close()
  216228. {
  216229. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  216230. if (intern != 0)
  216231. {
  216232. internal = 0;
  216233. if (intern->pipeIn != -1)
  216234. ::close (intern->pipeIn);
  216235. if (intern->pipeOut != -1)
  216236. ::close (intern->pipeOut);
  216237. if (intern->createdPipe)
  216238. {
  216239. unlink (intern->pipeInName.toUTF8());
  216240. unlink (intern->pipeOutName.toUTF8());
  216241. }
  216242. delete intern;
  216243. }
  216244. }
  216245. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  216246. {
  216247. close();
  216248. NamedPipeInternal* const intern = new NamedPipeInternal();
  216249. internal = intern;
  216250. intern->createdPipe = createPipe;
  216251. intern->blocked = false;
  216252. intern->stopReadOperation = false;
  216253. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  216254. siginterrupt (SIGPIPE, 1);
  216255. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  216256. intern->pipeInName = pipePath + "_in";
  216257. intern->pipeOutName = pipePath + "_out";
  216258. intern->pipeIn = -1;
  216259. intern->pipeOut = -1;
  216260. if (createPipe)
  216261. {
  216262. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  216263. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  216264. {
  216265. delete intern;
  216266. internal = 0;
  216267. return false;
  216268. }
  216269. }
  216270. return true;
  216271. }
  216272. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  216273. {
  216274. int bytesRead = -1;
  216275. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  216276. if (intern != 0)
  216277. {
  216278. intern->blocked = true;
  216279. if (intern->pipeIn == -1)
  216280. {
  216281. if (intern->createdPipe)
  216282. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  216283. else
  216284. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  216285. if (intern->pipeIn == -1)
  216286. {
  216287. intern->blocked = false;
  216288. return -1;
  216289. }
  216290. }
  216291. bytesRead = 0;
  216292. char* p = (char*) destBuffer;
  216293. while (bytesRead < maxBytesToRead)
  216294. {
  216295. const int bytesThisTime = maxBytesToRead - bytesRead;
  216296. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  216297. if (numRead <= 0 || intern->stopReadOperation)
  216298. {
  216299. bytesRead = -1;
  216300. break;
  216301. }
  216302. bytesRead += numRead;
  216303. p += bytesRead;
  216304. }
  216305. intern->blocked = false;
  216306. }
  216307. return bytesRead;
  216308. }
  216309. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  216310. {
  216311. int bytesWritten = -1;
  216312. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  216313. if (intern != 0)
  216314. {
  216315. if (intern->pipeOut == -1)
  216316. {
  216317. if (intern->createdPipe)
  216318. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  216319. else
  216320. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  216321. if (intern->pipeOut == -1)
  216322. {
  216323. return -1;
  216324. }
  216325. }
  216326. const char* p = (const char*) sourceBuffer;
  216327. bytesWritten = 0;
  216328. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  216329. while (bytesWritten < numBytesToWrite
  216330. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  216331. {
  216332. const int bytesThisTime = numBytesToWrite - bytesWritten;
  216333. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  216334. if (numWritten <= 0)
  216335. {
  216336. bytesWritten = -1;
  216337. break;
  216338. }
  216339. bytesWritten += numWritten;
  216340. p += bytesWritten;
  216341. }
  216342. }
  216343. return bytesWritten;
  216344. }
  216345. #endif
  216346. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  216347. /*** Start of inlined file: juce_linux_Network.cpp ***/
  216348. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  216349. // compiled on its own).
  216350. #if JUCE_INCLUDED_FILE
  216351. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  216352. {
  216353. int numResults = 0;
  216354. const int s = socket (AF_INET, SOCK_DGRAM, 0);
  216355. if (s != -1)
  216356. {
  216357. char buf [1024];
  216358. struct ifconf ifc;
  216359. ifc.ifc_len = sizeof (buf);
  216360. ifc.ifc_buf = buf;
  216361. ioctl (s, SIOCGIFCONF, &ifc);
  216362. for (unsigned int i = 0; i < ifc.ifc_len / sizeof (struct ifreq); ++i)
  216363. {
  216364. struct ifreq ifr;
  216365. strcpy (ifr.ifr_name, ifc.ifc_req[i].ifr_name);
  216366. if (ioctl (s, SIOCGIFFLAGS, &ifr) == 0
  216367. && (ifr.ifr_flags & IFF_LOOPBACK) == 0
  216368. && ioctl (s, SIOCGIFHWADDR, &ifr) == 0
  216369. && numResults < maxNum)
  216370. {
  216371. int64 a = 0;
  216372. for (int j = 6; --j >= 0;)
  216373. a = (a << 8) | (uint8) ifr.ifr_hwaddr.sa_data [littleEndian ? j : (5 - j)];
  216374. *addresses++ = a;
  216375. ++numResults;
  216376. }
  216377. }
  216378. close (s);
  216379. }
  216380. return numResults;
  216381. }
  216382. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  216383. const String& emailSubject,
  216384. const String& bodyText,
  216385. const StringArray& filesToAttach)
  216386. {
  216387. jassertfalse; // xxx todo
  216388. return false;
  216389. }
  216390. /** A HTTP input stream that uses sockets.
  216391. */
  216392. class JUCE_HTTPSocketStream
  216393. {
  216394. public:
  216395. JUCE_HTTPSocketStream()
  216396. : readPosition (0),
  216397. socketHandle (-1),
  216398. levelsOfRedirection (0),
  216399. timeoutSeconds (15)
  216400. {
  216401. }
  216402. ~JUCE_HTTPSocketStream()
  216403. {
  216404. closeSocket();
  216405. }
  216406. bool open (const String& url,
  216407. const String& headers,
  216408. const MemoryBlock& postData,
  216409. const bool isPost,
  216410. URL::OpenStreamProgressCallback* callback,
  216411. void* callbackContext,
  216412. int timeOutMs)
  216413. {
  216414. closeSocket();
  216415. uint32 timeOutTime = Time::getMillisecondCounter();
  216416. if (timeOutMs == 0)
  216417. timeOutTime += 60000;
  216418. else if (timeOutMs < 0)
  216419. timeOutTime = 0xffffffff;
  216420. else
  216421. timeOutTime += timeOutMs;
  216422. String hostName, hostPath;
  216423. int hostPort;
  216424. if (! decomposeURL (url, hostName, hostPath, hostPort))
  216425. return false;
  216426. const struct hostent* host = 0;
  216427. int port = 0;
  216428. String proxyName, proxyPath;
  216429. int proxyPort = 0;
  216430. String proxyURL (getenv ("http_proxy"));
  216431. if (proxyURL.startsWithIgnoreCase ("http://"))
  216432. {
  216433. if (! decomposeURL (proxyURL, proxyName, proxyPath, proxyPort))
  216434. return false;
  216435. host = gethostbyname (proxyName.toUTF8());
  216436. port = proxyPort;
  216437. }
  216438. else
  216439. {
  216440. host = gethostbyname (hostName.toUTF8());
  216441. port = hostPort;
  216442. }
  216443. if (host == 0)
  216444. return false;
  216445. struct sockaddr_in address;
  216446. zerostruct (address);
  216447. memcpy (&address.sin_addr, host->h_addr, host->h_length);
  216448. address.sin_family = host->h_addrtype;
  216449. address.sin_port = htons (port);
  216450. socketHandle = socket (host->h_addrtype, SOCK_STREAM, 0);
  216451. if (socketHandle == -1)
  216452. return false;
  216453. int receiveBufferSize = 16384;
  216454. setsockopt (socketHandle, SOL_SOCKET, SO_RCVBUF, (char*) &receiveBufferSize, sizeof (receiveBufferSize));
  216455. setsockopt (socketHandle, SOL_SOCKET, SO_KEEPALIVE, 0, 0);
  216456. #if JUCE_MAC
  216457. setsockopt (socketHandle, SOL_SOCKET, SO_NOSIGPIPE, 0, 0);
  216458. #endif
  216459. if (connect (socketHandle, (struct sockaddr*) &address, sizeof (address)) == -1)
  216460. {
  216461. closeSocket();
  216462. return false;
  216463. }
  216464. const MemoryBlock requestHeader (createRequestHeader (hostName, hostPort,
  216465. proxyName, proxyPort,
  216466. hostPath, url,
  216467. headers, postData,
  216468. isPost));
  216469. size_t totalHeaderSent = 0;
  216470. while (totalHeaderSent < requestHeader.getSize())
  216471. {
  216472. if (Time::getMillisecondCounter() > timeOutTime)
  216473. {
  216474. closeSocket();
  216475. return false;
  216476. }
  216477. const int numToSend = jmin (1024, (int) (requestHeader.getSize() - totalHeaderSent));
  216478. if (send (socketHandle,
  216479. ((const char*) requestHeader.getData()) + totalHeaderSent,
  216480. numToSend, 0)
  216481. != numToSend)
  216482. {
  216483. closeSocket();
  216484. return false;
  216485. }
  216486. totalHeaderSent += numToSend;
  216487. if (callback != 0 && ! callback (callbackContext, totalHeaderSent, requestHeader.getSize()))
  216488. {
  216489. closeSocket();
  216490. return false;
  216491. }
  216492. }
  216493. const String responseHeader (readResponse (timeOutTime));
  216494. if (responseHeader.isNotEmpty())
  216495. {
  216496. //DBG (responseHeader);
  216497. headerLines.clear();
  216498. headerLines.addLines (responseHeader);
  216499. const int statusCode = responseHeader.fromFirstOccurrenceOf (" ", false, false)
  216500. .substring (0, 3).getIntValue();
  216501. //int contentLength = findHeaderItem (lines, "Content-Length:").getIntValue();
  216502. //bool isChunked = findHeaderItem (lines, "Transfer-Encoding:").equalsIgnoreCase ("chunked");
  216503. String location (findHeaderItem (headerLines, "Location:"));
  216504. if (statusCode >= 300 && statusCode < 400
  216505. && location.isNotEmpty())
  216506. {
  216507. if (! location.startsWithIgnoreCase ("http://"))
  216508. location = "http://" + location;
  216509. if (levelsOfRedirection++ < 3)
  216510. return open (location, headers, postData, isPost, callback, callbackContext, timeOutMs);
  216511. }
  216512. else
  216513. {
  216514. levelsOfRedirection = 0;
  216515. return true;
  216516. }
  216517. }
  216518. closeSocket();
  216519. return false;
  216520. }
  216521. int read (void* buffer, int bytesToRead)
  216522. {
  216523. fd_set readbits;
  216524. FD_ZERO (&readbits);
  216525. FD_SET (socketHandle, &readbits);
  216526. struct timeval tv;
  216527. tv.tv_sec = timeoutSeconds;
  216528. tv.tv_usec = 0;
  216529. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  216530. return 0; // (timeout)
  216531. const int bytesRead = jmax (0, (int) recv (socketHandle, buffer, bytesToRead, MSG_WAITALL));
  216532. readPosition += bytesRead;
  216533. return bytesRead;
  216534. }
  216535. int readPosition;
  216536. StringArray headerLines;
  216537. juce_UseDebuggingNewOperator
  216538. private:
  216539. int socketHandle, levelsOfRedirection;
  216540. const int timeoutSeconds;
  216541. void closeSocket()
  216542. {
  216543. if (socketHandle >= 0)
  216544. close (socketHandle);
  216545. socketHandle = -1;
  216546. }
  216547. const MemoryBlock createRequestHeader (const String& hostName,
  216548. const int hostPort,
  216549. const String& proxyName,
  216550. const int proxyPort,
  216551. const String& hostPath,
  216552. const String& originalURL,
  216553. const String& headers,
  216554. const MemoryBlock& postData,
  216555. const bool isPost)
  216556. {
  216557. String header (isPost ? "POST " : "GET ");
  216558. if (proxyName.isEmpty())
  216559. {
  216560. header << hostPath << " HTTP/1.0\r\nHost: "
  216561. << hostName << ':' << hostPort;
  216562. }
  216563. else
  216564. {
  216565. header << originalURL << " HTTP/1.0\r\nHost: "
  216566. << proxyName << ':' << proxyPort;
  216567. }
  216568. header << "\r\nUser-Agent: JUCE/"
  216569. << JUCE_MAJOR_VERSION << '.' << JUCE_MINOR_VERSION
  216570. << "\r\nConnection: Close\r\nContent-Length: "
  216571. << postData.getSize() << "\r\n"
  216572. << headers << "\r\n";
  216573. MemoryBlock mb;
  216574. mb.append (header.toUTF8(), (int) strlen (header.toUTF8()));
  216575. mb.append (postData.getData(), postData.getSize());
  216576. return mb;
  216577. }
  216578. const String readResponse (const uint32 timeOutTime)
  216579. {
  216580. int bytesRead = 0, numConsecutiveLFs = 0;
  216581. MemoryBlock buffer (1024, true);
  216582. while (numConsecutiveLFs < 2 && bytesRead < 32768
  216583. && Time::getMillisecondCounter() <= timeOutTime)
  216584. {
  216585. fd_set readbits;
  216586. FD_ZERO (&readbits);
  216587. FD_SET (socketHandle, &readbits);
  216588. struct timeval tv;
  216589. tv.tv_sec = timeoutSeconds;
  216590. tv.tv_usec = 0;
  216591. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  216592. return String::empty; // (timeout)
  216593. buffer.ensureSize (bytesRead + 8, true);
  216594. char* const dest = (char*) buffer.getData() + bytesRead;
  216595. if (recv (socketHandle, dest, 1, 0) == -1)
  216596. return String::empty;
  216597. const char lastByte = *dest;
  216598. ++bytesRead;
  216599. if (lastByte == '\n')
  216600. ++numConsecutiveLFs;
  216601. else if (lastByte != '\r')
  216602. numConsecutiveLFs = 0;
  216603. }
  216604. const String header (String::fromUTF8 ((const char*) buffer.getData()));
  216605. if (header.startsWithIgnoreCase ("HTTP/"))
  216606. return header.trimEnd();
  216607. return String::empty;
  216608. }
  216609. static bool decomposeURL (const String& url,
  216610. String& host, String& path, int& port)
  216611. {
  216612. if (! url.startsWithIgnoreCase ("http://"))
  216613. return false;
  216614. const int nextSlash = url.indexOfChar (7, '/');
  216615. int nextColon = url.indexOfChar (7, ':');
  216616. if (nextColon > nextSlash && nextSlash > 0)
  216617. nextColon = -1;
  216618. if (nextColon >= 0)
  216619. {
  216620. host = url.substring (7, nextColon);
  216621. if (nextSlash >= 0)
  216622. port = url.substring (nextColon + 1, nextSlash).getIntValue();
  216623. else
  216624. port = url.substring (nextColon + 1).getIntValue();
  216625. }
  216626. else
  216627. {
  216628. port = 80;
  216629. if (nextSlash >= 0)
  216630. host = url.substring (7, nextSlash);
  216631. else
  216632. host = url.substring (7);
  216633. }
  216634. if (nextSlash >= 0)
  216635. path = url.substring (nextSlash);
  216636. else
  216637. path = "/";
  216638. return true;
  216639. }
  216640. static const String findHeaderItem (const StringArray& lines, const String& itemName)
  216641. {
  216642. for (int i = 0; i < lines.size(); ++i)
  216643. if (lines[i].startsWithIgnoreCase (itemName))
  216644. return lines[i].substring (itemName.length()).trim();
  216645. return String::empty;
  216646. }
  216647. };
  216648. void* juce_openInternetFile (const String& url,
  216649. const String& headers,
  216650. const MemoryBlock& postData,
  216651. const bool isPost,
  216652. URL::OpenStreamProgressCallback* callback,
  216653. void* callbackContext,
  216654. int timeOutMs)
  216655. {
  216656. ScopedPointer<JUCE_HTTPSocketStream> s (new JUCE_HTTPSocketStream());
  216657. if (s->open (url, headers, postData, isPost, callback, callbackContext, timeOutMs))
  216658. return s.release();
  216659. return 0;
  216660. }
  216661. void juce_closeInternetFile (void* handle)
  216662. {
  216663. delete static_cast <JUCE_HTTPSocketStream*> (handle);
  216664. }
  216665. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  216666. {
  216667. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  216668. return s != 0 ? s->read (buffer, bytesToRead) : 0;
  216669. }
  216670. int64 juce_getInternetFileContentLength (void* handle)
  216671. {
  216672. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  216673. if (s != 0)
  216674. {
  216675. //xxx todo
  216676. jassertfalse
  216677. }
  216678. return -1;
  216679. }
  216680. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  216681. {
  216682. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  216683. if (s != 0)
  216684. {
  216685. for (int i = 0; i < s->headerLines.size(); ++i)
  216686. {
  216687. const String& headersEntry = s->headerLines[i];
  216688. const String key (headersEntry.upToFirstOccurrenceOf (": ", false, false));
  216689. const String value (headersEntry.fromFirstOccurrenceOf (": ", false, false));
  216690. const String previousValue (headers [key]);
  216691. headers.set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  216692. }
  216693. }
  216694. }
  216695. int juce_seekInInternetFile (void* handle, int newPosition)
  216696. {
  216697. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  216698. return s != 0 ? s->readPosition : 0;
  216699. }
  216700. #endif
  216701. /*** End of inlined file: juce_linux_Network.cpp ***/
  216702. /*** Start of inlined file: juce_linux_SystemStats.cpp ***/
  216703. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  216704. // compiled on its own).
  216705. #if JUCE_INCLUDED_FILE
  216706. void Logger::outputDebugString (const String& text)
  216707. {
  216708. std::cerr << text << std::endl;
  216709. }
  216710. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  216711. {
  216712. return Linux;
  216713. }
  216714. const String SystemStats::getOperatingSystemName()
  216715. {
  216716. return "Linux";
  216717. }
  216718. bool SystemStats::isOperatingSystem64Bit()
  216719. {
  216720. #if JUCE_64BIT
  216721. return true;
  216722. #else
  216723. //xxx not sure how to find this out?..
  216724. return false;
  216725. #endif
  216726. }
  216727. static const String juce_getCpuInfo (const char* const key)
  216728. {
  216729. StringArray lines;
  216730. lines.addLines (File ("/proc/cpuinfo").loadFileAsString());
  216731. for (int i = lines.size(); --i >= 0;) // (NB - it's important that this runs in reverse order)
  216732. if (lines[i].startsWithIgnoreCase (key))
  216733. return lines[i].fromFirstOccurrenceOf (":", false, false).trim();
  216734. return String::empty;
  216735. }
  216736. const String SystemStats::getCpuVendor()
  216737. {
  216738. return juce_getCpuInfo ("vendor_id");
  216739. }
  216740. int SystemStats::getCpuSpeedInMegaherz()
  216741. {
  216742. return roundToInt (juce_getCpuInfo ("cpu MHz").getFloatValue());
  216743. }
  216744. int SystemStats::getMemorySizeInMegabytes()
  216745. {
  216746. struct sysinfo sysi;
  216747. if (sysinfo (&sysi) == 0)
  216748. return (sysi.totalram * sysi.mem_unit / (1024 * 1024));
  216749. return 0;
  216750. }
  216751. int SystemStats::getPageSize()
  216752. {
  216753. return sysconf (_SC_PAGESIZE);
  216754. }
  216755. const String SystemStats::getLogonName()
  216756. {
  216757. const char* user = getenv ("USER");
  216758. if (user == 0)
  216759. {
  216760. struct passwd* const pw = getpwuid (getuid());
  216761. if (pw != 0)
  216762. user = pw->pw_name;
  216763. }
  216764. return String::fromUTF8 (user);
  216765. }
  216766. const String SystemStats::getFullUserName()
  216767. {
  216768. return getLogonName();
  216769. }
  216770. void SystemStats::initialiseStats()
  216771. {
  216772. const String flags (juce_getCpuInfo ("flags"));
  216773. cpuFlags.hasMMX = flags.contains ("mmx");
  216774. cpuFlags.hasSSE = flags.contains ("sse");
  216775. cpuFlags.hasSSE2 = flags.contains ("sse2");
  216776. cpuFlags.has3DNow = flags.contains ("3dnow");
  216777. cpuFlags.numCpus = juce_getCpuInfo ("processor").getIntValue() + 1;
  216778. }
  216779. void PlatformUtilities::fpuReset()
  216780. {
  216781. }
  216782. static bool juce_getTimeSinceStartup (timeval* const t) throw()
  216783. {
  216784. if (gettimeofday (t, 0) != 0)
  216785. return false;
  216786. static unsigned int calibrate = 0;
  216787. static bool calibrated = false;
  216788. if (! calibrated)
  216789. {
  216790. calibrated = true;
  216791. struct sysinfo sysi;
  216792. if (sysinfo (&sysi) == 0)
  216793. calibrate = t->tv_sec - sysi.uptime; // Safe to assume system was not brought up earlier than 1970!
  216794. }
  216795. t->tv_sec -= calibrate;
  216796. return true;
  216797. }
  216798. uint32 juce_millisecondsSinceStartup() throw()
  216799. {
  216800. timeval t;
  216801. if (juce_getTimeSinceStartup (&t))
  216802. return (uint32) (t.tv_sec * 1000 + (t.tv_usec / 1000));
  216803. return 0;
  216804. }
  216805. int64 Time::getHighResolutionTicks() throw()
  216806. {
  216807. timeval t;
  216808. if (juce_getTimeSinceStartup (&t))
  216809. return ((int64) t.tv_sec * (int64) 1000000) + (int64) t.tv_usec;
  216810. return 0;
  216811. }
  216812. int64 Time::getHighResolutionTicksPerSecond() throw()
  216813. {
  216814. return 1000000; // (microseconds)
  216815. }
  216816. double Time::getMillisecondCounterHiRes() throw()
  216817. {
  216818. return getHighResolutionTicks() * 0.001;
  216819. }
  216820. bool Time::setSystemTimeToThisTime() const
  216821. {
  216822. timeval t;
  216823. t.tv_sec = millisSinceEpoch % 1000000;
  216824. t.tv_usec = millisSinceEpoch - t.tv_sec;
  216825. return settimeofday (&t, 0) ? false : true;
  216826. }
  216827. #endif
  216828. /*** End of inlined file: juce_linux_SystemStats.cpp ***/
  216829. /*** Start of inlined file: juce_linux_Threads.cpp ***/
  216830. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  216831. // compiled on its own).
  216832. #if JUCE_INCLUDED_FILE
  216833. /*
  216834. Note that a lot of methods that you'd expect to find in this file actually
  216835. live in juce_posix_SharedCode.h!
  216836. */
  216837. void JUCE_API juce_threadEntryPoint (void*);
  216838. void* threadEntryProc (void* value)
  216839. {
  216840. juce_threadEntryPoint (value);
  216841. return 0;
  216842. }
  216843. void* juce_createThread (void* userData)
  216844. {
  216845. pthread_t handle = 0;
  216846. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  216847. {
  216848. pthread_detach (handle);
  216849. return (void*) handle;
  216850. }
  216851. return 0;
  216852. }
  216853. void juce_killThread (void* handle)
  216854. {
  216855. if (handle != 0)
  216856. pthread_cancel ((pthread_t) handle);
  216857. }
  216858. void juce_setCurrentThreadName (const String& /*name*/)
  216859. {
  216860. }
  216861. Thread::ThreadID Thread::getCurrentThreadId()
  216862. {
  216863. return (ThreadID) pthread_self();
  216864. }
  216865. /* This is all a bit non-ideal... the trouble is that on Linux you
  216866. need to call setpriority to affect the dynamic priority for
  216867. non-realtime processes, but this requires the pid, which is not
  216868. accessible from the pthread_t. We could get it by calling getpid
  216869. once each thread has started, but then we would need a list of
  216870. running threads etc etc.
  216871. Also there is no such thing as IDLE priority on Linux.
  216872. For the moment, map idle, low and normal process priorities to
  216873. SCHED_OTHER, with the thread priority ignored for these classes.
  216874. Map high priority processes to the lower half of the SCHED_RR
  216875. range, and realtime to the upper half.
  216876. priority 1 to 10 where 5=normal, 1=low. If the handle is 0, sets the
  216877. priority of the current thread
  216878. */
  216879. bool juce_setThreadPriority (void* handle, int priority)
  216880. {
  216881. struct sched_param param;
  216882. int policy;
  216883. if (handle == 0)
  216884. handle = (void*) pthread_self();
  216885. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) == 0
  216886. && policy != SCHED_OTHER)
  216887. {
  216888. int minp = sched_get_priority_min (policy);
  216889. int maxp = sched_get_priority_max (policy);
  216890. int pri = ((maxp - minp) / 2) * (priority - 1) / 9;
  216891. if (param.sched_priority >= (minp + (maxp - minp) / 2))
  216892. param.sched_priority = minp + ((maxp - minp) / 2) + pri; // (realtime)
  216893. else
  216894. param.sched_priority = minp + pri; // (high)
  216895. param.sched_priority = jlimit (1, 127, 1 + (priority * 126) / 11);
  216896. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  216897. }
  216898. return false;
  216899. }
  216900. /* Remove this macro if you're having problems compiling the cpu affinity
  216901. calls (the API for these has changed about quite a bit in various Linux
  216902. versions, and a lot of distros seem to ship with obsolete versions)
  216903. */
  216904. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  216905. #define SUPPORT_AFFINITIES 1
  216906. #endif
  216907. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  216908. {
  216909. #if SUPPORT_AFFINITIES
  216910. cpu_set_t affinity;
  216911. CPU_ZERO (&affinity);
  216912. for (int i = 0; i < 32; ++i)
  216913. if ((affinityMask & (1 << i)) != 0)
  216914. CPU_SET (i, &affinity);
  216915. /*
  216916. N.B. If this line causes a compile error, then you've probably not got the latest
  216917. version of glibc installed.
  216918. If you don't want to update your copy of glibc and don't care about cpu affinities,
  216919. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  216920. */
  216921. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  216922. sched_yield();
  216923. #else
  216924. /* affinities aren't supported because either the appropriate header files weren't found,
  216925. or the SUPPORT_AFFINITIES macro was turned off
  216926. */
  216927. jassertfalse;
  216928. #endif
  216929. }
  216930. void Thread::yield()
  216931. {
  216932. sched_yield();
  216933. }
  216934. // sets the process to 0=low priority, 1=normal, 2=high, 3=realtime
  216935. void Process::setPriority (ProcessPriority prior)
  216936. {
  216937. struct sched_param param;
  216938. int policy, maxp, minp;
  216939. const int p = (int) prior;
  216940. if (p <= 1)
  216941. policy = SCHED_OTHER;
  216942. else
  216943. policy = SCHED_RR;
  216944. minp = sched_get_priority_min (policy);
  216945. maxp = sched_get_priority_max (policy);
  216946. if (p < 2)
  216947. param.sched_priority = 0;
  216948. else if (p == 2 )
  216949. // Set to middle of lower realtime priority range
  216950. param.sched_priority = minp + (maxp - minp) / 4;
  216951. else
  216952. // Set to middle of higher realtime priority range
  216953. param.sched_priority = minp + (3 * (maxp - minp) / 4);
  216954. pthread_setschedparam (pthread_self(), policy, &param);
  216955. }
  216956. void Process::terminate()
  216957. {
  216958. exit (0);
  216959. }
  216960. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  216961. {
  216962. static char testResult = 0;
  216963. if (testResult == 0)
  216964. {
  216965. testResult = (char) ptrace (PT_TRACE_ME, 0, 0, 0);
  216966. if (testResult >= 0)
  216967. {
  216968. ptrace (PT_DETACH, 0, (caddr_t) 1, 0);
  216969. testResult = 1;
  216970. }
  216971. }
  216972. return testResult < 0;
  216973. }
  216974. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  216975. {
  216976. return juce_isRunningUnderDebugger();
  216977. }
  216978. void Process::raisePrivilege()
  216979. {
  216980. // If running suid root, change effective user
  216981. // to root
  216982. if (geteuid() != 0 && getuid() == 0)
  216983. {
  216984. setreuid (geteuid(), getuid());
  216985. setregid (getegid(), getgid());
  216986. }
  216987. }
  216988. void Process::lowerPrivilege()
  216989. {
  216990. // If runing suid root, change effective user
  216991. // back to real user
  216992. if (geteuid() == 0 && getuid() != 0)
  216993. {
  216994. setreuid (geteuid(), getuid());
  216995. setregid (getegid(), getgid());
  216996. }
  216997. }
  216998. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  216999. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  217000. {
  217001. return dlopen (name.toUTF8(), RTLD_LOCAL | RTLD_NOW);
  217002. }
  217003. void PlatformUtilities::freeDynamicLibrary (void* handle)
  217004. {
  217005. dlclose(handle);
  217006. }
  217007. void* PlatformUtilities::getProcedureEntryPoint (void* libraryHandle, const String& procedureName)
  217008. {
  217009. return dlsym (libraryHandle, procedureName.toCString());
  217010. }
  217011. #endif
  217012. #endif
  217013. /*** End of inlined file: juce_linux_Threads.cpp ***/
  217014. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  217015. /*** Start of inlined file: juce_linux_Clipboard.cpp ***/
  217016. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217017. // compiled on its own).
  217018. #if JUCE_INCLUDED_FILE
  217019. #if JUCE_DEBUG
  217020. #define JUCE_DEBUG_XERRORS 1
  217021. #endif
  217022. extern Display* display;
  217023. extern Window juce_messageWindowHandle;
  217024. namespace ClipboardHelpers
  217025. {
  217026. static String localClipboardContent;
  217027. static Atom atom_UTF8_STRING;
  217028. static Atom atom_CLIPBOARD;
  217029. static Atom atom_TARGETS;
  217030. static void initSelectionAtoms()
  217031. {
  217032. static bool isInitialised = false;
  217033. if (! isInitialised)
  217034. {
  217035. atom_UTF8_STRING = XInternAtom (display, "UTF8_STRING", False);
  217036. atom_CLIPBOARD = XInternAtom (display, "CLIPBOARD", False);
  217037. atom_TARGETS = XInternAtom (display, "TARGETS", False);
  217038. }
  217039. }
  217040. // Read the content of a window property as either a locale-dependent string or an utf8 string
  217041. // works only for strings shorter than 1000000 bytes
  217042. static String readWindowProperty (Window window, Atom prop, Atom fmt)
  217043. {
  217044. String returnData;
  217045. char* clipData;
  217046. Atom actualType;
  217047. int actualFormat;
  217048. unsigned long numItems, bytesLeft;
  217049. if (XGetWindowProperty (display, window, prop,
  217050. 0L /* offset */, 1000000 /* length (max) */, False,
  217051. AnyPropertyType /* format */,
  217052. &actualType, &actualFormat, &numItems, &bytesLeft,
  217053. (unsigned char**) &clipData) == Success)
  217054. {
  217055. if (actualType == atom_UTF8_STRING && actualFormat == 8)
  217056. returnData = String::fromUTF8 (clipData, numItems);
  217057. else if (actualType == XA_STRING && actualFormat == 8)
  217058. returnData = String (clipData, numItems);
  217059. if (clipData != 0)
  217060. XFree (clipData);
  217061. jassert (bytesLeft == 0 || numItems == 1000000);
  217062. }
  217063. XDeleteProperty (display, window, prop);
  217064. return returnData;
  217065. }
  217066. // Send a SelectionRequest to the window owning the selection and waits for its answer (with a timeout) */
  217067. static bool requestSelectionContent (String& selectionContent, Atom selection, Atom requestedFormat)
  217068. {
  217069. Atom property_name = XInternAtom (display, "JUCE_SEL", false);
  217070. // The selection owner will be asked to set the JUCE_SEL property on the
  217071. // juce_messageWindowHandle with the selection content
  217072. XConvertSelection (display, selection, requestedFormat, property_name,
  217073. juce_messageWindowHandle, CurrentTime);
  217074. int count = 50; // will wait at most for 200 ms
  217075. while (--count >= 0)
  217076. {
  217077. XEvent event;
  217078. if (XCheckTypedWindowEvent (display, juce_messageWindowHandle, SelectionNotify, &event))
  217079. {
  217080. if (event.xselection.property == property_name)
  217081. {
  217082. jassert (event.xselection.requestor == juce_messageWindowHandle);
  217083. selectionContent = readWindowProperty (event.xselection.requestor,
  217084. event.xselection.property,
  217085. requestedFormat);
  217086. return true;
  217087. }
  217088. else
  217089. {
  217090. return false; // the format we asked for was denied.. (event.xselection.property == None)
  217091. }
  217092. }
  217093. // not very elegant.. we could do a select() or something like that...
  217094. // however clipboard content requesting is inherently slow on x11, it
  217095. // often takes 50ms or more so...
  217096. Thread::sleep (4);
  217097. }
  217098. return false;
  217099. }
  217100. }
  217101. // Called from the event loop in juce_linux_Messaging in response to SelectionRequest events
  217102. void juce_handleSelectionRequest (XSelectionRequestEvent &evt)
  217103. {
  217104. ClipboardHelpers::initSelectionAtoms();
  217105. // the selection content is sent to the target window as a window property
  217106. XSelectionEvent reply;
  217107. reply.type = SelectionNotify;
  217108. reply.display = evt.display;
  217109. reply.requestor = evt.requestor;
  217110. reply.selection = evt.selection;
  217111. reply.target = evt.target;
  217112. reply.property = None; // == "fail"
  217113. reply.time = evt.time;
  217114. HeapBlock <char> data;
  217115. int propertyFormat = 0, numDataItems = 0;
  217116. if (evt.selection == XA_PRIMARY || evt.selection == ClipboardHelpers::atom_CLIPBOARD)
  217117. {
  217118. if (evt.target == XA_STRING)
  217119. {
  217120. // format data according to system locale
  217121. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsCString() + 1;
  217122. data.calloc (numDataItems + 1);
  217123. ClipboardHelpers::localClipboardContent.copyToCString (data, numDataItems);
  217124. propertyFormat = 8; // bits/item
  217125. }
  217126. else if (evt.target == ClipboardHelpers::atom_UTF8_STRING)
  217127. {
  217128. // translate to utf8
  217129. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsUTF8() + 1;
  217130. data.calloc (numDataItems + 1);
  217131. ClipboardHelpers::localClipboardContent.copyToUTF8 (data, numDataItems);
  217132. propertyFormat = 8; // bits/item
  217133. }
  217134. else if (evt.target == ClipboardHelpers::atom_TARGETS)
  217135. {
  217136. // another application wants to know what we are able to send
  217137. numDataItems = 2;
  217138. propertyFormat = 32; // atoms are 32-bit
  217139. data.calloc (numDataItems * 4);
  217140. Atom* atoms = reinterpret_cast<Atom*> (data.getData());
  217141. atoms[0] = ClipboardHelpers::atom_UTF8_STRING;
  217142. atoms[1] = XA_STRING;
  217143. }
  217144. }
  217145. else
  217146. {
  217147. DBG ("requested unsupported clipboard");
  217148. }
  217149. if (data != 0)
  217150. {
  217151. const int maxReasonableSelectionSize = 1000000;
  217152. // for very big chunks of data, we should use the "INCR" protocol , which is a pain in the *ss
  217153. if (evt.property != None && numDataItems < maxReasonableSelectionSize)
  217154. {
  217155. XChangeProperty (evt.display, evt.requestor,
  217156. evt.property, evt.target,
  217157. propertyFormat /* 8 or 32 */, PropModeReplace,
  217158. reinterpret_cast<const unsigned char*> (data.getData()), numDataItems);
  217159. reply.property = evt.property; // " == success"
  217160. }
  217161. }
  217162. XSendEvent (evt.display, evt.requestor, 0, NoEventMask, (XEvent*) &reply);
  217163. }
  217164. void SystemClipboard::copyTextToClipboard (const String& clipText)
  217165. {
  217166. ClipboardHelpers::initSelectionAtoms();
  217167. ClipboardHelpers::localClipboardContent = clipText;
  217168. XSetSelectionOwner (display, XA_PRIMARY, juce_messageWindowHandle, CurrentTime);
  217169. XSetSelectionOwner (display, ClipboardHelpers::atom_CLIPBOARD, juce_messageWindowHandle, CurrentTime);
  217170. }
  217171. const String SystemClipboard::getTextFromClipboard()
  217172. {
  217173. ClipboardHelpers::initSelectionAtoms();
  217174. /* 1) try to read from the "CLIPBOARD" selection first (the "high
  217175. level" clipboard that is supposed to be filled by ctrl-C
  217176. etc). When a clipboard manager is running, the content of this
  217177. selection is preserved even when the original selection owner
  217178. exits.
  217179. 2) and then try to read from "PRIMARY" selection (the "legacy" selection
  217180. filled by good old x11 apps such as xterm)
  217181. */
  217182. String content;
  217183. Atom selection = XA_PRIMARY;
  217184. Window selectionOwner = None;
  217185. if ((selectionOwner = XGetSelectionOwner (display, selection)) == None)
  217186. {
  217187. selection = ClipboardHelpers::atom_CLIPBOARD;
  217188. selectionOwner = XGetSelectionOwner (display, selection);
  217189. }
  217190. if (selectionOwner != None)
  217191. {
  217192. if (selectionOwner == juce_messageWindowHandle)
  217193. {
  217194. content = ClipboardHelpers::localClipboardContent;
  217195. }
  217196. else
  217197. {
  217198. // first try: we want an utf8 string
  217199. bool ok = ClipboardHelpers::requestSelectionContent (content, selection, ClipboardHelpers::atom_UTF8_STRING);
  217200. if (! ok)
  217201. {
  217202. // second chance, ask for a good old locale-dependent string ..
  217203. ok = ClipboardHelpers::requestSelectionContent (content, selection, XA_STRING);
  217204. }
  217205. }
  217206. }
  217207. return content;
  217208. }
  217209. #endif
  217210. /*** End of inlined file: juce_linux_Clipboard.cpp ***/
  217211. /*** Start of inlined file: juce_linux_Messaging.cpp ***/
  217212. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217213. // compiled on its own).
  217214. #if JUCE_INCLUDED_FILE
  217215. #if JUCE_DEBUG && ! defined (JUCE_DEBUG_XERRORS)
  217216. #define JUCE_DEBUG_XERRORS 1
  217217. #endif
  217218. Display* display = 0;
  217219. Window juce_messageWindowHandle = None;
  217220. XContext windowHandleXContext; // This is referenced from Windowing.cpp
  217221. extern void juce_windowMessageReceive (XEvent* event); // Defined in Windowing.cpp
  217222. extern void juce_handleSelectionRequest (XSelectionRequestEvent &evt); // Defined in Clipboard.cpp
  217223. ScopedXLock::ScopedXLock() { XLockDisplay (display); }
  217224. ScopedXLock::~ScopedXLock() { XUnlockDisplay (display); }
  217225. class InternalMessageQueue
  217226. {
  217227. public:
  217228. InternalMessageQueue()
  217229. : bytesInSocket (0),
  217230. totalEventCount (0)
  217231. {
  217232. int ret = ::socketpair (AF_LOCAL, SOCK_STREAM, 0, fd);
  217233. (void) ret; jassert (ret == 0);
  217234. //setNonBlocking (fd[0]);
  217235. //setNonBlocking (fd[1]);
  217236. }
  217237. ~InternalMessageQueue()
  217238. {
  217239. close (fd[0]);
  217240. close (fd[1]);
  217241. clearSingletonInstance();
  217242. }
  217243. void postMessage (Message* msg)
  217244. {
  217245. const int maxBytesInSocketQueue = 128;
  217246. ScopedLock sl (lock);
  217247. queue.add (msg);
  217248. if (bytesInSocket < maxBytesInSocketQueue)
  217249. {
  217250. ++bytesInSocket;
  217251. ScopedUnlock ul (lock);
  217252. const unsigned char x = 0xff;
  217253. size_t bytesWritten = write (fd[0], &x, 1);
  217254. (void) bytesWritten;
  217255. }
  217256. }
  217257. bool isEmpty() const
  217258. {
  217259. ScopedLock sl (lock);
  217260. return queue.size() == 0;
  217261. }
  217262. bool dispatchNextEvent()
  217263. {
  217264. // This alternates between giving priority to XEvents or internal messages,
  217265. // to keep everything running smoothly..
  217266. if ((++totalEventCount & 1) != 0)
  217267. return dispatchNextXEvent() || dispatchNextInternalMessage();
  217268. else
  217269. return dispatchNextInternalMessage() || dispatchNextXEvent();
  217270. }
  217271. // Wait for an event (either XEvent, or an internal Message)
  217272. bool sleepUntilEvent (const int timeoutMs)
  217273. {
  217274. if (! isEmpty())
  217275. return true;
  217276. if (display != 0)
  217277. {
  217278. ScopedXLock xlock;
  217279. if (XPending (display))
  217280. return true;
  217281. }
  217282. struct timeval tv;
  217283. tv.tv_sec = 0;
  217284. tv.tv_usec = timeoutMs * 1000;
  217285. int fd0 = getWaitHandle();
  217286. int fdmax = fd0;
  217287. fd_set readset;
  217288. FD_ZERO (&readset);
  217289. FD_SET (fd0, &readset);
  217290. if (display != 0)
  217291. {
  217292. ScopedXLock xlock;
  217293. int fd1 = XConnectionNumber (display);
  217294. FD_SET (fd1, &readset);
  217295. fdmax = jmax (fd0, fd1);
  217296. }
  217297. const int ret = select (fdmax + 1, &readset, 0, 0, &tv);
  217298. return (ret > 0); // ret <= 0 if error or timeout
  217299. }
  217300. struct MessageThreadFuncCall
  217301. {
  217302. enum { uniqueID = 0x73774623 };
  217303. MessageCallbackFunction* func;
  217304. void* parameter;
  217305. void* result;
  217306. CriticalSection lock;
  217307. WaitableEvent event;
  217308. };
  217309. juce_DeclareSingleton_SingleThreaded_Minimal (InternalMessageQueue);
  217310. private:
  217311. CriticalSection lock;
  217312. OwnedArray <Message> queue;
  217313. int fd[2];
  217314. int bytesInSocket;
  217315. int totalEventCount;
  217316. int getWaitHandle() const throw() { return fd[1]; }
  217317. static bool setNonBlocking (int handle)
  217318. {
  217319. int socketFlags = fcntl (handle, F_GETFL, 0);
  217320. if (socketFlags == -1)
  217321. return false;
  217322. socketFlags |= O_NONBLOCK;
  217323. return fcntl (handle, F_SETFL, socketFlags) == 0;
  217324. }
  217325. static bool dispatchNextXEvent()
  217326. {
  217327. if (display == 0)
  217328. return false;
  217329. XEvent evt;
  217330. {
  217331. ScopedXLock xlock;
  217332. if (! XPending (display))
  217333. return false;
  217334. XNextEvent (display, &evt);
  217335. }
  217336. if (evt.type == SelectionRequest && evt.xany.window == juce_messageWindowHandle)
  217337. juce_handleSelectionRequest (evt.xselectionrequest);
  217338. else if (evt.xany.window != juce_messageWindowHandle)
  217339. juce_windowMessageReceive (&evt);
  217340. return true;
  217341. }
  217342. Message* popNextMessage()
  217343. {
  217344. ScopedLock sl (lock);
  217345. if (bytesInSocket > 0)
  217346. {
  217347. --bytesInSocket;
  217348. ScopedUnlock ul (lock);
  217349. unsigned char x;
  217350. size_t numBytes = read (fd[1], &x, 1);
  217351. (void) numBytes;
  217352. }
  217353. return queue.removeAndReturn (0);
  217354. }
  217355. bool dispatchNextInternalMessage()
  217356. {
  217357. ScopedPointer <Message> msg (popNextMessage());
  217358. if (msg == 0)
  217359. return false;
  217360. if (msg->intParameter1 == MessageThreadFuncCall::uniqueID)
  217361. {
  217362. // Handle callback message
  217363. MessageThreadFuncCall* const call = (MessageThreadFuncCall*) msg->pointerParameter;
  217364. call->result = (*(call->func)) (call->parameter);
  217365. call->event.signal();
  217366. }
  217367. else
  217368. {
  217369. // Handle "normal" messages
  217370. MessageManager::getInstance()->deliverMessage (msg.release());
  217371. }
  217372. return true;
  217373. }
  217374. };
  217375. juce_ImplementSingleton_SingleThreaded (InternalMessageQueue);
  217376. namespace LinuxErrorHandling
  217377. {
  217378. static bool errorOccurred = false;
  217379. static bool keyboardBreakOccurred = false;
  217380. static XErrorHandler oldErrorHandler = (XErrorHandler) 0;
  217381. static XIOErrorHandler oldIOErrorHandler = (XIOErrorHandler) 0;
  217382. // Usually happens when client-server connection is broken
  217383. static int ioErrorHandler (Display* display)
  217384. {
  217385. DBG ("ERROR: connection to X server broken.. terminating.");
  217386. if (JUCEApplication::getInstance() != 0)
  217387. MessageManager::getInstance()->stopDispatchLoop();
  217388. errorOccurred = true;
  217389. return 0;
  217390. }
  217391. // A protocol error has occurred
  217392. static int juce_XErrorHandler (Display* display, XErrorEvent* event)
  217393. {
  217394. #if JUCE_DEBUG_XERRORS
  217395. char errorStr[64] = { 0 };
  217396. char requestStr[64] = { 0 };
  217397. XGetErrorText (display, event->error_code, errorStr, 64);
  217398. XGetErrorDatabaseText (display, "XRequest", String (event->request_code).toCString(), "Unknown", requestStr, 64);
  217399. DBG ("ERROR: X returned " + String (errorStr) + " for operation " + String (requestStr));
  217400. #endif
  217401. return 0;
  217402. }
  217403. static void installXErrorHandlers()
  217404. {
  217405. oldIOErrorHandler = XSetIOErrorHandler (ioErrorHandler);
  217406. oldErrorHandler = XSetErrorHandler (juce_XErrorHandler);
  217407. }
  217408. static void removeXErrorHandlers()
  217409. {
  217410. XSetIOErrorHandler (oldIOErrorHandler);
  217411. oldIOErrorHandler = 0;
  217412. XSetErrorHandler (oldErrorHandler);
  217413. oldErrorHandler = 0;
  217414. }
  217415. static void keyboardBreakSignalHandler (int sig)
  217416. {
  217417. if (sig == SIGINT)
  217418. keyboardBreakOccurred = true;
  217419. }
  217420. static void installKeyboardBreakHandler()
  217421. {
  217422. struct sigaction saction;
  217423. sigset_t maskSet;
  217424. sigemptyset (&maskSet);
  217425. saction.sa_handler = keyboardBreakSignalHandler;
  217426. saction.sa_mask = maskSet;
  217427. saction.sa_flags = 0;
  217428. sigaction (SIGINT, &saction, 0);
  217429. }
  217430. }
  217431. void MessageManager::doPlatformSpecificInitialisation()
  217432. {
  217433. // Initialise xlib for multiple thread support
  217434. static bool initThreadCalled = false;
  217435. if (! initThreadCalled)
  217436. {
  217437. if (! XInitThreads())
  217438. {
  217439. // This is fatal! Print error and closedown
  217440. Logger::outputDebugString ("Failed to initialise xlib thread support.");
  217441. if (JUCEApplication::getInstance() != 0)
  217442. Process::terminate();
  217443. return;
  217444. }
  217445. initThreadCalled = true;
  217446. }
  217447. LinuxErrorHandling::installXErrorHandlers();
  217448. LinuxErrorHandling::installKeyboardBreakHandler();
  217449. // Create the internal message queue
  217450. InternalMessageQueue::getInstance();
  217451. // Try to connect to a display
  217452. String displayName (getenv ("DISPLAY"));
  217453. if (displayName.isEmpty())
  217454. displayName = ":0.0";
  217455. display = XOpenDisplay (displayName.toCString());
  217456. if (display != 0) // This is not fatal! we can run headless.
  217457. {
  217458. // Create a context to store user data associated with Windows we create in WindowDriver
  217459. windowHandleXContext = XUniqueContext();
  217460. // We're only interested in client messages for this window, which are always sent
  217461. XSetWindowAttributes swa;
  217462. swa.event_mask = NoEventMask;
  217463. // Create our message window (this will never be mapped)
  217464. const int screen = DefaultScreen (display);
  217465. juce_messageWindowHandle = XCreateWindow (display, RootWindow (display, screen),
  217466. 0, 0, 1, 1, 0, 0, InputOnly,
  217467. DefaultVisual (display, screen),
  217468. CWEventMask, &swa);
  217469. }
  217470. }
  217471. void MessageManager::doPlatformSpecificShutdown()
  217472. {
  217473. InternalMessageQueue::deleteInstance();
  217474. if (display != 0 && ! LinuxErrorHandling::errorOccurred)
  217475. {
  217476. XDestroyWindow (display, juce_messageWindowHandle);
  217477. XCloseDisplay (display);
  217478. juce_messageWindowHandle = 0;
  217479. display = 0;
  217480. LinuxErrorHandling::removeXErrorHandlers();
  217481. }
  217482. }
  217483. bool juce_postMessageToSystemQueue (Message* message)
  217484. {
  217485. if (LinuxErrorHandling::errorOccurred)
  217486. return false;
  217487. InternalMessageQueue::getInstanceWithoutCreating()->postMessage (message);
  217488. return true;
  217489. }
  217490. void MessageManager::broadcastMessage (const String& value) throw()
  217491. {
  217492. /* TODO */
  217493. }
  217494. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* func,
  217495. void* parameter)
  217496. {
  217497. if (LinuxErrorHandling::errorOccurred)
  217498. return 0;
  217499. if (isThisTheMessageThread())
  217500. return func (parameter);
  217501. InternalMessageQueue::MessageThreadFuncCall messageCallContext;
  217502. messageCallContext.func = func;
  217503. messageCallContext.parameter = parameter;
  217504. InternalMessageQueue::getInstanceWithoutCreating()
  217505. ->postMessage (new Message (InternalMessageQueue::MessageThreadFuncCall::uniqueID,
  217506. 0, 0, &messageCallContext));
  217507. // Wait for it to complete before continuing
  217508. messageCallContext.event.wait();
  217509. return messageCallContext.result;
  217510. }
  217511. // this function expects that it will NEVER be called simultaneously for two concurrent threads
  217512. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages)
  217513. {
  217514. while (! LinuxErrorHandling::errorOccurred)
  217515. {
  217516. if (LinuxErrorHandling::keyboardBreakOccurred)
  217517. {
  217518. LinuxErrorHandling::errorOccurred = true;
  217519. if (JUCEApplication::getInstance() != 0)
  217520. Process::terminate();
  217521. break;
  217522. }
  217523. if (InternalMessageQueue::getInstanceWithoutCreating()->dispatchNextEvent())
  217524. return true;
  217525. if (returnIfNoPendingMessages)
  217526. break;
  217527. InternalMessageQueue::getInstanceWithoutCreating()->sleepUntilEvent (2000);
  217528. }
  217529. return false;
  217530. }
  217531. #endif
  217532. /*** End of inlined file: juce_linux_Messaging.cpp ***/
  217533. /*** Start of inlined file: juce_linux_Fonts.cpp ***/
  217534. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217535. // compiled on its own).
  217536. #if JUCE_INCLUDED_FILE
  217537. class FreeTypeFontFace
  217538. {
  217539. public:
  217540. enum FontStyle
  217541. {
  217542. Plain = 0,
  217543. Bold = 1,
  217544. Italic = 2
  217545. };
  217546. FreeTypeFontFace (const String& familyName)
  217547. : hasSerif (false),
  217548. monospaced (false)
  217549. {
  217550. family = familyName;
  217551. }
  217552. void setFileName (const String& name, const int faceIndex, FontStyle style)
  217553. {
  217554. if (names [(int) style].fileName.isEmpty())
  217555. {
  217556. names [(int) style].fileName = name;
  217557. names [(int) style].faceIndex = faceIndex;
  217558. }
  217559. }
  217560. const String& getFamilyName() const throw() { return family; }
  217561. const String& getFileName (const int style, int& faceIndex) const throw()
  217562. {
  217563. faceIndex = names[style].faceIndex;
  217564. return names[style].fileName;
  217565. }
  217566. void setMonospaced (bool mono) throw() { monospaced = mono; }
  217567. bool getMonospaced() const throw() { return monospaced; }
  217568. void setSerif (const bool serif) throw() { hasSerif = serif; }
  217569. bool getSerif() const throw() { return hasSerif; }
  217570. private:
  217571. String family;
  217572. struct FontNameIndex
  217573. {
  217574. String fileName;
  217575. int faceIndex;
  217576. };
  217577. FontNameIndex names[4];
  217578. bool hasSerif, monospaced;
  217579. };
  217580. class FreeTypeInterface : public DeletedAtShutdown
  217581. {
  217582. public:
  217583. FreeTypeInterface()
  217584. : ftLib (0),
  217585. lastFace (0),
  217586. lastBold (false),
  217587. lastItalic (false)
  217588. {
  217589. if (FT_Init_FreeType (&ftLib) != 0)
  217590. {
  217591. ftLib = 0;
  217592. DBG ("Failed to initialize FreeType");
  217593. }
  217594. StringArray fontDirs;
  217595. fontDirs.addTokens (String::fromUTF8 (getenv ("JUCE_FONT_PATH")), ";,", String::empty);
  217596. fontDirs.removeEmptyStrings (true);
  217597. if (fontDirs.size() == 0)
  217598. {
  217599. XmlDocument fontsConfig (File ("/etc/fonts/fonts.conf"));
  217600. const ScopedPointer<XmlElement> fontsInfo (fontsConfig.getDocumentElement());
  217601. if (fontsInfo != 0)
  217602. {
  217603. forEachXmlChildElementWithTagName (*fontsInfo, e, "dir")
  217604. {
  217605. fontDirs.add (e->getAllSubText().trim());
  217606. }
  217607. }
  217608. }
  217609. if (fontDirs.size() == 0)
  217610. fontDirs.add ("/usr/X11R6/lib/X11/fonts");
  217611. for (int i = 0; i < fontDirs.size(); ++i)
  217612. enumerateFaces (fontDirs[i]);
  217613. }
  217614. ~FreeTypeInterface()
  217615. {
  217616. if (lastFace != 0)
  217617. FT_Done_Face (lastFace);
  217618. if (ftLib != 0)
  217619. FT_Done_FreeType (ftLib);
  217620. clearSingletonInstance();
  217621. }
  217622. FreeTypeFontFace* findOrCreate (const String& familyName, const bool create = false)
  217623. {
  217624. for (int i = 0; i < faces.size(); i++)
  217625. if (faces[i]->getFamilyName() == familyName)
  217626. return faces[i];
  217627. if (! create)
  217628. return 0;
  217629. FreeTypeFontFace* newFace = new FreeTypeFontFace (familyName);
  217630. faces.add (newFace);
  217631. return newFace;
  217632. }
  217633. // Enumerate all font faces available in a given directory
  217634. void enumerateFaces (const String& path)
  217635. {
  217636. File dirPath (path);
  217637. if (path.isEmpty() || ! dirPath.isDirectory())
  217638. return;
  217639. DirectoryIterator di (dirPath, true);
  217640. while (di.next())
  217641. {
  217642. File possible (di.getFile());
  217643. if (possible.hasFileExtension ("ttf")
  217644. || possible.hasFileExtension ("pfb")
  217645. || possible.hasFileExtension ("pcf"))
  217646. {
  217647. FT_Face face;
  217648. int faceIndex = 0;
  217649. int numFaces = 0;
  217650. do
  217651. {
  217652. if (FT_New_Face (ftLib, possible.getFullPathName().toUTF8(),
  217653. faceIndex, &face) == 0)
  217654. {
  217655. if (faceIndex == 0)
  217656. numFaces = face->num_faces;
  217657. if ((face->face_flags & FT_FACE_FLAG_SCALABLE) != 0)
  217658. {
  217659. FreeTypeFontFace* const newFace = findOrCreate (face->family_name, true);
  217660. int style = (int) FreeTypeFontFace::Plain;
  217661. if ((face->style_flags & FT_STYLE_FLAG_BOLD) != 0)
  217662. style |= (int) FreeTypeFontFace::Bold;
  217663. if ((face->style_flags & FT_STYLE_FLAG_ITALIC) != 0)
  217664. style |= (int) FreeTypeFontFace::Italic;
  217665. newFace->setFileName (possible.getFullPathName(), faceIndex, (FreeTypeFontFace::FontStyle) style);
  217666. newFace->setMonospaced ((face->face_flags & FT_FACE_FLAG_FIXED_WIDTH) != 0);
  217667. // Surely there must be a better way to do this?
  217668. const String name (face->family_name);
  217669. newFace->setSerif (! (name.containsIgnoreCase ("Sans")
  217670. || name.containsIgnoreCase ("Verdana")
  217671. || name.containsIgnoreCase ("Arial")));
  217672. }
  217673. FT_Done_Face (face);
  217674. }
  217675. ++faceIndex;
  217676. }
  217677. while (faceIndex < numFaces);
  217678. }
  217679. }
  217680. }
  217681. // Create a FreeType face object for a given font
  217682. FT_Face createFT_Face (const String& fontName, const bool bold, const bool italic)
  217683. {
  217684. FT_Face face = 0;
  217685. if (fontName == lastFontName && bold == lastBold && italic == lastItalic)
  217686. {
  217687. face = lastFace;
  217688. }
  217689. else
  217690. {
  217691. if (lastFace != 0)
  217692. {
  217693. FT_Done_Face (lastFace);
  217694. lastFace = 0;
  217695. }
  217696. lastFontName = fontName;
  217697. lastBold = bold;
  217698. lastItalic = italic;
  217699. FreeTypeFontFace* const ftFace = findOrCreate (fontName);
  217700. if (ftFace != 0)
  217701. {
  217702. int style = (int) FreeTypeFontFace::Plain;
  217703. if (bold)
  217704. style |= (int) FreeTypeFontFace::Bold;
  217705. if (italic)
  217706. style |= (int) FreeTypeFontFace::Italic;
  217707. int faceIndex;
  217708. String fileName (ftFace->getFileName (style, faceIndex));
  217709. if (fileName.isEmpty())
  217710. {
  217711. style ^= (int) FreeTypeFontFace::Bold;
  217712. fileName = ftFace->getFileName (style, faceIndex);
  217713. if (fileName.isEmpty())
  217714. {
  217715. style ^= (int) FreeTypeFontFace::Bold;
  217716. style ^= (int) FreeTypeFontFace::Italic;
  217717. fileName = ftFace->getFileName (style, faceIndex);
  217718. if (! fileName.length())
  217719. {
  217720. style ^= (int) FreeTypeFontFace::Bold;
  217721. fileName = ftFace->getFileName (style, faceIndex);
  217722. }
  217723. }
  217724. }
  217725. if (! FT_New_Face (ftLib, fileName.toUTF8(), faceIndex, &lastFace))
  217726. {
  217727. face = lastFace;
  217728. // If there isn't a unicode charmap then select the first one.
  217729. if (FT_Select_Charmap (face, ft_encoding_unicode))
  217730. FT_Set_Charmap (face, face->charmaps[0]);
  217731. }
  217732. }
  217733. }
  217734. return face;
  217735. }
  217736. bool addGlyph (FT_Face face, CustomTypeface& dest, uint32 character)
  217737. {
  217738. const unsigned int glyphIndex = FT_Get_Char_Index (face, character);
  217739. const float height = (float) (face->ascender - face->descender);
  217740. const float scaleX = 1.0f / height;
  217741. const float scaleY = -1.0f / height;
  217742. Path destShape;
  217743. if (FT_Load_Glyph (face, glyphIndex, FT_LOAD_NO_SCALE | FT_LOAD_NO_BITMAP | FT_LOAD_IGNORE_TRANSFORM) != 0
  217744. || face->glyph->format != ft_glyph_format_outline)
  217745. {
  217746. return false;
  217747. }
  217748. const FT_Outline* const outline = &face->glyph->outline;
  217749. const short* const contours = outline->contours;
  217750. const char* const tags = outline->tags;
  217751. FT_Vector* const points = outline->points;
  217752. for (int c = 0; c < outline->n_contours; c++)
  217753. {
  217754. const int startPoint = (c == 0) ? 0 : contours [c - 1] + 1;
  217755. const int endPoint = contours[c];
  217756. for (int p = startPoint; p <= endPoint; p++)
  217757. {
  217758. const float x = scaleX * points[p].x;
  217759. const float y = scaleY * points[p].y;
  217760. if (p == startPoint)
  217761. {
  217762. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  217763. {
  217764. float x2 = scaleX * points [endPoint].x;
  217765. float y2 = scaleY * points [endPoint].y;
  217766. if (FT_CURVE_TAG (tags[endPoint]) != FT_Curve_Tag_On)
  217767. {
  217768. x2 = (x + x2) * 0.5f;
  217769. y2 = (y + y2) * 0.5f;
  217770. }
  217771. destShape.startNewSubPath (x2, y2);
  217772. }
  217773. else
  217774. {
  217775. destShape.startNewSubPath (x, y);
  217776. }
  217777. }
  217778. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_On)
  217779. {
  217780. if (p != startPoint)
  217781. destShape.lineTo (x, y);
  217782. }
  217783. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  217784. {
  217785. const int nextIndex = (p == endPoint) ? startPoint : p + 1;
  217786. float x2 = scaleX * points [nextIndex].x;
  217787. float y2 = scaleY * points [nextIndex].y;
  217788. if (FT_CURVE_TAG (tags [nextIndex]) == FT_Curve_Tag_Conic)
  217789. {
  217790. x2 = (x + x2) * 0.5f;
  217791. y2 = (y + y2) * 0.5f;
  217792. }
  217793. else
  217794. {
  217795. ++p;
  217796. }
  217797. destShape.quadraticTo (x, y, x2, y2);
  217798. }
  217799. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Cubic)
  217800. {
  217801. if (p >= endPoint)
  217802. return false;
  217803. const int next1 = p + 1;
  217804. const int next2 = (p == (endPoint - 1)) ? startPoint : p + 2;
  217805. const float x2 = scaleX * points [next1].x;
  217806. const float y2 = scaleY * points [next1].y;
  217807. const float x3 = scaleX * points [next2].x;
  217808. const float y3 = scaleY * points [next2].y;
  217809. if (FT_CURVE_TAG (tags[next1]) != FT_Curve_Tag_Cubic
  217810. || FT_CURVE_TAG (tags[next2]) != FT_Curve_Tag_On)
  217811. return false;
  217812. destShape.cubicTo (x, y, x2, y2, x3, y3);
  217813. p += 2;
  217814. }
  217815. }
  217816. destShape.closeSubPath();
  217817. }
  217818. dest.addGlyph (character, destShape, face->glyph->metrics.horiAdvance / height);
  217819. if ((face->face_flags & FT_FACE_FLAG_KERNING) != 0)
  217820. addKerning (face, dest, character, glyphIndex);
  217821. return true;
  217822. }
  217823. void addKerning (FT_Face face, CustomTypeface& dest, const uint32 character, const uint32 glyphIndex)
  217824. {
  217825. const float height = (float) (face->ascender - face->descender);
  217826. uint32 rightGlyphIndex;
  217827. uint32 rightCharCode = FT_Get_First_Char (face, &rightGlyphIndex);
  217828. while (rightGlyphIndex != 0)
  217829. {
  217830. FT_Vector kerning;
  217831. if (FT_Get_Kerning (face, glyphIndex, rightGlyphIndex, ft_kerning_unscaled, &kerning) == 0)
  217832. {
  217833. if (kerning.x != 0)
  217834. dest.addKerningPair (character, rightCharCode, kerning.x / height);
  217835. }
  217836. rightCharCode = FT_Get_Next_Char (face, rightCharCode, &rightGlyphIndex);
  217837. }
  217838. }
  217839. // Add a glyph to a font
  217840. bool addGlyphToFont (const uint32 character, const String& fontName,
  217841. bool bold, bool italic, CustomTypeface& dest)
  217842. {
  217843. FT_Face face = createFT_Face (fontName, bold, italic);
  217844. return face != 0 && addGlyph (face, dest, character);
  217845. }
  217846. void getFamilyNames (StringArray& familyNames) const
  217847. {
  217848. for (int i = 0; i < faces.size(); i++)
  217849. familyNames.add (faces[i]->getFamilyName());
  217850. }
  217851. void getMonospacedNames (StringArray& monoSpaced) const
  217852. {
  217853. for (int i = 0; i < faces.size(); i++)
  217854. if (faces[i]->getMonospaced())
  217855. monoSpaced.add (faces[i]->getFamilyName());
  217856. }
  217857. void getSerifNames (StringArray& serif) const
  217858. {
  217859. for (int i = 0; i < faces.size(); i++)
  217860. if (faces[i]->getSerif())
  217861. serif.add (faces[i]->getFamilyName());
  217862. }
  217863. void getSansSerifNames (StringArray& sansSerif) const
  217864. {
  217865. for (int i = 0; i < faces.size(); i++)
  217866. if (! faces[i]->getSerif())
  217867. sansSerif.add (faces[i]->getFamilyName());
  217868. }
  217869. juce_DeclareSingleton_SingleThreaded_Minimal (FreeTypeInterface)
  217870. private:
  217871. FT_Library ftLib;
  217872. FT_Face lastFace;
  217873. String lastFontName;
  217874. bool lastBold, lastItalic;
  217875. OwnedArray<FreeTypeFontFace> faces;
  217876. };
  217877. juce_ImplementSingleton_SingleThreaded (FreeTypeInterface)
  217878. class FreetypeTypeface : public CustomTypeface
  217879. {
  217880. public:
  217881. FreetypeTypeface (const Font& font)
  217882. {
  217883. FT_Face face = FreeTypeInterface::getInstance()
  217884. ->createFT_Face (font.getTypefaceName(), font.isBold(), font.isItalic());
  217885. if (face == 0)
  217886. {
  217887. #if JUCE_DEBUG
  217888. String msg ("Failed to create typeface: ");
  217889. msg << font.getTypefaceName() << " " << (font.isBold() ? 'B' : ' ') << (font.isItalic() ? 'I' : ' ');
  217890. DBG (msg);
  217891. #endif
  217892. }
  217893. else
  217894. {
  217895. setCharacteristics (font.getTypefaceName(),
  217896. face->ascender / (float) (face->ascender - face->descender),
  217897. font.isBold(), font.isItalic(),
  217898. L' ');
  217899. }
  217900. }
  217901. bool loadGlyphIfPossible (juce_wchar character)
  217902. {
  217903. return FreeTypeInterface::getInstance()
  217904. ->addGlyphToFont (character, name, isBold, isItalic, *this);
  217905. }
  217906. };
  217907. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  217908. {
  217909. return new FreetypeTypeface (font);
  217910. }
  217911. const StringArray Font::findAllTypefaceNames()
  217912. {
  217913. StringArray s;
  217914. FreeTypeInterface::getInstance()->getFamilyNames (s);
  217915. s.sort (true);
  217916. return s;
  217917. }
  217918. static const String pickBestFont (const StringArray& names,
  217919. const char* const choicesString)
  217920. {
  217921. StringArray choices;
  217922. choices.addTokens (String (choicesString), ",", String::empty);
  217923. choices.trim();
  217924. choices.removeEmptyStrings();
  217925. int i, j;
  217926. for (j = 0; j < choices.size(); ++j)
  217927. if (names.contains (choices[j], true))
  217928. return choices[j];
  217929. for (j = 0; j < choices.size(); ++j)
  217930. for (i = 0; i < names.size(); i++)
  217931. if (names[i].startsWithIgnoreCase (choices[j]))
  217932. return names[i];
  217933. for (j = 0; j < choices.size(); ++j)
  217934. for (i = 0; i < names.size(); i++)
  217935. if (names[i].containsIgnoreCase (choices[j]))
  217936. return names[i];
  217937. return names[0];
  217938. }
  217939. static const String linux_getDefaultSansSerifFontName()
  217940. {
  217941. StringArray allFonts;
  217942. FreeTypeInterface::getInstance()->getSansSerifNames (allFonts);
  217943. return pickBestFont (allFonts, "Verdana, Bitstream Vera Sans, Luxi Sans, Sans");
  217944. }
  217945. static const String linux_getDefaultSerifFontName()
  217946. {
  217947. StringArray allFonts;
  217948. FreeTypeInterface::getInstance()->getSerifNames (allFonts);
  217949. return pickBestFont (allFonts, "Bitstream Vera Serif, Times, Nimbus Roman, Serif");
  217950. }
  217951. static const String linux_getDefaultMonospacedFontName()
  217952. {
  217953. StringArray allFonts;
  217954. FreeTypeInterface::getInstance()->getMonospacedNames (allFonts);
  217955. return pickBestFont (allFonts, "Bitstream Vera Sans Mono, Courier, Sans Mono, Mono");
  217956. }
  217957. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  217958. {
  217959. defaultSans = linux_getDefaultSansSerifFontName();
  217960. defaultSerif = linux_getDefaultSerifFontName();
  217961. defaultFixed = linux_getDefaultMonospacedFontName();
  217962. }
  217963. #endif
  217964. /*** End of inlined file: juce_linux_Fonts.cpp ***/
  217965. /*** Start of inlined file: juce_linux_Windowing.cpp ***/
  217966. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217967. // compiled on its own).
  217968. #if JUCE_INCLUDED_FILE
  217969. // These are defined in juce_linux_Messaging.cpp
  217970. extern Display* display;
  217971. extern XContext windowHandleXContext;
  217972. namespace Atoms
  217973. {
  217974. enum ProtocolItems
  217975. {
  217976. TAKE_FOCUS = 0,
  217977. DELETE_WINDOW = 1,
  217978. PING = 2
  217979. };
  217980. static Atom Protocols, ProtocolList[3], ChangeState, State,
  217981. ActiveWin, Pid, WindowType, WindowState,
  217982. XdndAware, XdndEnter, XdndLeave, XdndPosition, XdndStatus,
  217983. XdndDrop, XdndFinished, XdndSelection, XdndTypeList, XdndActionList,
  217984. XdndActionDescription, XdndActionCopy,
  217985. allowedActions[5],
  217986. allowedMimeTypes[2];
  217987. const unsigned long DndVersion = 3;
  217988. static void initialiseAtoms()
  217989. {
  217990. static bool atomsInitialised = false;
  217991. if (! atomsInitialised)
  217992. {
  217993. atomsInitialised = true;
  217994. Protocols = XInternAtom (display, "WM_PROTOCOLS", True);
  217995. ProtocolList [TAKE_FOCUS] = XInternAtom (display, "WM_TAKE_FOCUS", True);
  217996. ProtocolList [DELETE_WINDOW] = XInternAtom (display, "WM_DELETE_WINDOW", True);
  217997. ProtocolList [PING] = XInternAtom (display, "_NET_WM_PING", True);
  217998. ChangeState = XInternAtom (display, "WM_CHANGE_STATE", True);
  217999. State = XInternAtom (display, "WM_STATE", True);
  218000. ActiveWin = XInternAtom (display, "_NET_ACTIVE_WINDOW", False);
  218001. Pid = XInternAtom (display, "_NET_WM_PID", False);
  218002. WindowType = XInternAtom (display, "_NET_WM_WINDOW_TYPE", True);
  218003. WindowState = XInternAtom (display, "_NET_WM_STATE", True);
  218004. XdndAware = XInternAtom (display, "XdndAware", False);
  218005. XdndEnter = XInternAtom (display, "XdndEnter", False);
  218006. XdndLeave = XInternAtom (display, "XdndLeave", False);
  218007. XdndPosition = XInternAtom (display, "XdndPosition", False);
  218008. XdndStatus = XInternAtom (display, "XdndStatus", False);
  218009. XdndDrop = XInternAtom (display, "XdndDrop", False);
  218010. XdndFinished = XInternAtom (display, "XdndFinished", False);
  218011. XdndSelection = XInternAtom (display, "XdndSelection", False);
  218012. XdndTypeList = XInternAtom (display, "XdndTypeList", False);
  218013. XdndActionList = XInternAtom (display, "XdndActionList", False);
  218014. XdndActionCopy = XInternAtom (display, "XdndActionCopy", False);
  218015. XdndActionDescription = XInternAtom (display, "XdndActionDescription", False);
  218016. allowedMimeTypes[0] = XInternAtom (display, "text/plain", False);
  218017. allowedMimeTypes[1] = XInternAtom (display, "text/uri-list", False);
  218018. allowedActions[0] = XInternAtom (display, "XdndActionMove", False);
  218019. allowedActions[1] = XdndActionCopy;
  218020. allowedActions[2] = XInternAtom (display, "XdndActionLink", False);
  218021. allowedActions[3] = XInternAtom (display, "XdndActionAsk", False);
  218022. allowedActions[4] = XInternAtom (display, "XdndActionPrivate", False);
  218023. }
  218024. }
  218025. }
  218026. namespace Keys
  218027. {
  218028. enum MouseButtons
  218029. {
  218030. NoButton = 0,
  218031. LeftButton = 1,
  218032. MiddleButton = 2,
  218033. RightButton = 3,
  218034. WheelUp = 4,
  218035. WheelDown = 5
  218036. };
  218037. static int AltMask = 0;
  218038. static int NumLockMask = 0;
  218039. static bool numLock = false;
  218040. static bool capsLock = false;
  218041. static char keyStates [32];
  218042. static const int extendedKeyModifier = 0x10000000;
  218043. }
  218044. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  218045. {
  218046. int keysym;
  218047. if (keyCode & Keys::extendedKeyModifier)
  218048. {
  218049. keysym = 0xff00 | (keyCode & 0xff);
  218050. }
  218051. else
  218052. {
  218053. keysym = keyCode;
  218054. if (keysym == (XK_Tab & 0xff)
  218055. || keysym == (XK_Return & 0xff)
  218056. || keysym == (XK_Escape & 0xff)
  218057. || keysym == (XK_BackSpace & 0xff))
  218058. {
  218059. keysym |= 0xff00;
  218060. }
  218061. }
  218062. ScopedXLock xlock;
  218063. const int keycode = XKeysymToKeycode (display, keysym);
  218064. const int keybyte = keycode >> 3;
  218065. const int keybit = (1 << (keycode & 7));
  218066. return (Keys::keyStates [keybyte] & keybit) != 0;
  218067. }
  218068. #if JUCE_USE_XSHM
  218069. namespace XSHMHelpers
  218070. {
  218071. static int trappedErrorCode = 0;
  218072. extern "C" int errorTrapHandler (Display*, XErrorEvent* err)
  218073. {
  218074. trappedErrorCode = err->error_code;
  218075. return 0;
  218076. }
  218077. static bool isShmAvailable() throw()
  218078. {
  218079. static bool isChecked = false;
  218080. static bool isAvailable = false;
  218081. if (! isChecked)
  218082. {
  218083. isChecked = true;
  218084. int major, minor;
  218085. Bool pixmaps;
  218086. ScopedXLock xlock;
  218087. if (XShmQueryVersion (display, &major, &minor, &pixmaps))
  218088. {
  218089. trappedErrorCode = 0;
  218090. XErrorHandler oldHandler = XSetErrorHandler (errorTrapHandler);
  218091. XShmSegmentInfo segmentInfo;
  218092. zerostruct (segmentInfo);
  218093. XImage* xImage = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  218094. 24, ZPixmap, 0, &segmentInfo, 50, 50);
  218095. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  218096. xImage->bytes_per_line * xImage->height,
  218097. IPC_CREAT | 0777)) >= 0)
  218098. {
  218099. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  218100. if (segmentInfo.shmaddr != (void*) -1)
  218101. {
  218102. segmentInfo.readOnly = False;
  218103. xImage->data = segmentInfo.shmaddr;
  218104. XSync (display, False);
  218105. if (XShmAttach (display, &segmentInfo) != 0)
  218106. {
  218107. XSync (display, False);
  218108. XShmDetach (display, &segmentInfo);
  218109. isAvailable = true;
  218110. }
  218111. }
  218112. XFlush (display);
  218113. XDestroyImage (xImage);
  218114. shmdt (segmentInfo.shmaddr);
  218115. }
  218116. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  218117. XSetErrorHandler (oldHandler);
  218118. if (trappedErrorCode != 0)
  218119. isAvailable = false;
  218120. }
  218121. }
  218122. return isAvailable;
  218123. }
  218124. }
  218125. #endif
  218126. #if JUCE_USE_XRENDER
  218127. namespace XRender
  218128. {
  218129. typedef Status (*tXRenderQueryVersion) (Display*, int*, int*);
  218130. typedef XRenderPictFormat* (*tXrenderFindStandardFormat) (Display*, int);
  218131. typedef XRenderPictFormat* (*tXRenderFindFormat) (Display*, unsigned long, XRenderPictFormat*, int);
  218132. typedef XRenderPictFormat* (*tXRenderFindVisualFormat) (Display*, Visual*);
  218133. static tXRenderQueryVersion xRenderQueryVersion = 0;
  218134. static tXrenderFindStandardFormat xRenderFindStandardFormat = 0;
  218135. static tXRenderFindFormat xRenderFindFormat = 0;
  218136. static tXRenderFindVisualFormat xRenderFindVisualFormat = 0;
  218137. static bool isAvailable()
  218138. {
  218139. static bool hasLoaded = false;
  218140. if (! hasLoaded)
  218141. {
  218142. ScopedXLock xlock;
  218143. hasLoaded = true;
  218144. void* h = dlopen ("libXrender.so", RTLD_GLOBAL | RTLD_NOW);
  218145. if (h != 0)
  218146. {
  218147. xRenderQueryVersion = (tXRenderQueryVersion) dlsym (h, "XRenderQueryVersion");
  218148. xRenderFindStandardFormat = (tXrenderFindStandardFormat) dlsym (h, "XrenderFindStandardFormat");
  218149. xRenderFindFormat = (tXRenderFindFormat) dlsym (h, "XRenderFindFormat");
  218150. xRenderFindVisualFormat = (tXRenderFindVisualFormat) dlsym (h, "XRenderFindVisualFormat");
  218151. }
  218152. if (xRenderQueryVersion != 0
  218153. && xRenderFindStandardFormat != 0
  218154. && xRenderFindFormat != 0
  218155. && xRenderFindVisualFormat != 0)
  218156. {
  218157. int major, minor;
  218158. if (xRenderQueryVersion (display, &major, &minor))
  218159. return true;
  218160. }
  218161. xRenderQueryVersion = 0;
  218162. }
  218163. return xRenderQueryVersion != 0;
  218164. }
  218165. static XRenderPictFormat* findPictureFormat()
  218166. {
  218167. ScopedXLock xlock;
  218168. XRenderPictFormat* pictFormat = 0;
  218169. if (isAvailable())
  218170. {
  218171. pictFormat = xRenderFindStandardFormat (display, PictStandardARGB32);
  218172. if (pictFormat == 0)
  218173. {
  218174. XRenderPictFormat desiredFormat;
  218175. desiredFormat.type = PictTypeDirect;
  218176. desiredFormat.depth = 32;
  218177. desiredFormat.direct.alphaMask = 0xff;
  218178. desiredFormat.direct.redMask = 0xff;
  218179. desiredFormat.direct.greenMask = 0xff;
  218180. desiredFormat.direct.blueMask = 0xff;
  218181. desiredFormat.direct.alpha = 24;
  218182. desiredFormat.direct.red = 16;
  218183. desiredFormat.direct.green = 8;
  218184. desiredFormat.direct.blue = 0;
  218185. pictFormat = xRenderFindFormat (display,
  218186. PictFormatType | PictFormatDepth
  218187. | PictFormatRedMask | PictFormatRed
  218188. | PictFormatGreenMask | PictFormatGreen
  218189. | PictFormatBlueMask | PictFormatBlue
  218190. | PictFormatAlphaMask | PictFormatAlpha,
  218191. &desiredFormat,
  218192. 0);
  218193. }
  218194. }
  218195. return pictFormat;
  218196. }
  218197. }
  218198. #endif
  218199. namespace Visuals
  218200. {
  218201. static Visual* findVisualWithDepth (const int desiredDepth) throw()
  218202. {
  218203. ScopedXLock xlock;
  218204. Visual* visual = 0;
  218205. int numVisuals = 0;
  218206. long desiredMask = VisualNoMask;
  218207. XVisualInfo desiredVisual;
  218208. desiredVisual.screen = DefaultScreen (display);
  218209. desiredVisual.depth = desiredDepth;
  218210. desiredMask = VisualScreenMask | VisualDepthMask;
  218211. if (desiredDepth == 32)
  218212. {
  218213. desiredVisual.c_class = TrueColor;
  218214. desiredVisual.red_mask = 0x00FF0000;
  218215. desiredVisual.green_mask = 0x0000FF00;
  218216. desiredVisual.blue_mask = 0x000000FF;
  218217. desiredVisual.bits_per_rgb = 8;
  218218. desiredMask |= VisualClassMask;
  218219. desiredMask |= VisualRedMaskMask;
  218220. desiredMask |= VisualGreenMaskMask;
  218221. desiredMask |= VisualBlueMaskMask;
  218222. desiredMask |= VisualBitsPerRGBMask;
  218223. }
  218224. XVisualInfo* xvinfos = XGetVisualInfo (display,
  218225. desiredMask,
  218226. &desiredVisual,
  218227. &numVisuals);
  218228. if (xvinfos != 0)
  218229. {
  218230. for (int i = 0; i < numVisuals; i++)
  218231. {
  218232. if (xvinfos[i].depth == desiredDepth)
  218233. {
  218234. visual = xvinfos[i].visual;
  218235. break;
  218236. }
  218237. }
  218238. XFree (xvinfos);
  218239. }
  218240. return visual;
  218241. }
  218242. static Visual* findVisualFormat (const int desiredDepth, int& matchedDepth) throw()
  218243. {
  218244. Visual* visual = 0;
  218245. if (desiredDepth == 32)
  218246. {
  218247. #if JUCE_USE_XSHM
  218248. if (XSHMHelpers::isShmAvailable())
  218249. {
  218250. #if JUCE_USE_XRENDER
  218251. if (XRender::isAvailable())
  218252. {
  218253. XRenderPictFormat* pictFormat = XRender::findPictureFormat();
  218254. if (pictFormat != 0)
  218255. {
  218256. int numVisuals = 0;
  218257. XVisualInfo desiredVisual;
  218258. desiredVisual.screen = DefaultScreen (display);
  218259. desiredVisual.depth = 32;
  218260. desiredVisual.bits_per_rgb = 8;
  218261. XVisualInfo* xvinfos = XGetVisualInfo (display,
  218262. VisualScreenMask | VisualDepthMask | VisualBitsPerRGBMask,
  218263. &desiredVisual, &numVisuals);
  218264. if (xvinfos != 0)
  218265. {
  218266. for (int i = 0; i < numVisuals; ++i)
  218267. {
  218268. XRenderPictFormat* pictVisualFormat = XRender::xRenderFindVisualFormat (display, xvinfos[i].visual);
  218269. if (pictVisualFormat != 0
  218270. && pictVisualFormat->type == PictTypeDirect
  218271. && pictVisualFormat->direct.alphaMask)
  218272. {
  218273. visual = xvinfos[i].visual;
  218274. matchedDepth = 32;
  218275. break;
  218276. }
  218277. }
  218278. XFree (xvinfos);
  218279. }
  218280. }
  218281. }
  218282. #endif
  218283. if (visual == 0)
  218284. {
  218285. visual = findVisualWithDepth (32);
  218286. if (visual != 0)
  218287. matchedDepth = 32;
  218288. }
  218289. }
  218290. #endif
  218291. }
  218292. if (visual == 0 && desiredDepth >= 24)
  218293. {
  218294. visual = findVisualWithDepth (24);
  218295. if (visual != 0)
  218296. matchedDepth = 24;
  218297. }
  218298. if (visual == 0 && desiredDepth >= 16)
  218299. {
  218300. visual = findVisualWithDepth (16);
  218301. if (visual != 0)
  218302. matchedDepth = 16;
  218303. }
  218304. return visual;
  218305. }
  218306. }
  218307. class XBitmapImage : public Image::SharedImage
  218308. {
  218309. public:
  218310. XBitmapImage (const Image::PixelFormat format_, const int w, const int h,
  218311. const bool clearImage, const int imageDepth_, Visual* visual)
  218312. : Image::SharedImage (format_, w, h),
  218313. imageDepth (imageDepth_),
  218314. gc (None)
  218315. {
  218316. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  218317. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  218318. lineStride = ((w * pixelStride + 3) & ~3);
  218319. ScopedXLock xlock;
  218320. #if JUCE_USE_XSHM
  218321. usingXShm = false;
  218322. if ((imageDepth > 16) && XSHMHelpers::isShmAvailable())
  218323. {
  218324. zerostruct (segmentInfo);
  218325. segmentInfo.shmid = -1;
  218326. segmentInfo.shmaddr = (char *) -1;
  218327. segmentInfo.readOnly = False;
  218328. xImage = XShmCreateImage (display, visual, imageDepth, ZPixmap, 0, &segmentInfo, w, h);
  218329. if (xImage != 0)
  218330. {
  218331. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  218332. xImage->bytes_per_line * xImage->height,
  218333. IPC_CREAT | 0777)) >= 0)
  218334. {
  218335. if (segmentInfo.shmid != -1)
  218336. {
  218337. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  218338. if (segmentInfo.shmaddr != (void*) -1)
  218339. {
  218340. segmentInfo.readOnly = False;
  218341. xImage->data = segmentInfo.shmaddr;
  218342. imageData = (uint8*) segmentInfo.shmaddr;
  218343. if (XShmAttach (display, &segmentInfo) != 0)
  218344. usingXShm = true;
  218345. else
  218346. jassertfalse;
  218347. }
  218348. else
  218349. {
  218350. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  218351. }
  218352. }
  218353. }
  218354. }
  218355. }
  218356. if (! usingXShm)
  218357. #endif
  218358. {
  218359. imageDataAllocated.malloc (lineStride * h);
  218360. imageData = imageDataAllocated;
  218361. if (format_ == Image::ARGB && clearImage)
  218362. zeromem (imageData, h * lineStride);
  218363. xImage = (XImage*) juce_calloc (sizeof (XImage));
  218364. xImage->width = w;
  218365. xImage->height = h;
  218366. xImage->xoffset = 0;
  218367. xImage->format = ZPixmap;
  218368. xImage->data = (char*) imageData;
  218369. xImage->byte_order = ImageByteOrder (display);
  218370. xImage->bitmap_unit = BitmapUnit (display);
  218371. xImage->bitmap_bit_order = BitmapBitOrder (display);
  218372. xImage->bitmap_pad = 32;
  218373. xImage->depth = pixelStride * 8;
  218374. xImage->bytes_per_line = lineStride;
  218375. xImage->bits_per_pixel = pixelStride * 8;
  218376. xImage->red_mask = 0x00FF0000;
  218377. xImage->green_mask = 0x0000FF00;
  218378. xImage->blue_mask = 0x000000FF;
  218379. if (imageDepth == 16)
  218380. {
  218381. const int pixelStride = 2;
  218382. const int lineStride = ((w * pixelStride + 3) & ~3);
  218383. imageData16Bit.malloc (lineStride * h);
  218384. xImage->data = imageData16Bit;
  218385. xImage->bitmap_pad = 16;
  218386. xImage->depth = pixelStride * 8;
  218387. xImage->bytes_per_line = lineStride;
  218388. xImage->bits_per_pixel = pixelStride * 8;
  218389. xImage->red_mask = visual->red_mask;
  218390. xImage->green_mask = visual->green_mask;
  218391. xImage->blue_mask = visual->blue_mask;
  218392. }
  218393. if (! XInitImage (xImage))
  218394. jassertfalse;
  218395. }
  218396. }
  218397. ~XBitmapImage()
  218398. {
  218399. ScopedXLock xlock;
  218400. if (gc != None)
  218401. XFreeGC (display, gc);
  218402. #if JUCE_USE_XSHM
  218403. if (usingXShm)
  218404. {
  218405. XShmDetach (display, &segmentInfo);
  218406. XFlush (display);
  218407. XDestroyImage (xImage);
  218408. shmdt (segmentInfo.shmaddr);
  218409. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  218410. }
  218411. else
  218412. #endif
  218413. {
  218414. xImage->data = 0;
  218415. XDestroyImage (xImage);
  218416. }
  218417. }
  218418. Image::ImageType getType() const { return Image::NativeImage; }
  218419. LowLevelGraphicsContext* createLowLevelContext()
  218420. {
  218421. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  218422. }
  218423. SharedImage* clone()
  218424. {
  218425. jassertfalse;
  218426. return 0;
  218427. }
  218428. void blitToWindow (Window window, int dx, int dy, int dw, int dh, int sx, int sy)
  218429. {
  218430. ScopedXLock xlock;
  218431. if (gc == None)
  218432. {
  218433. XGCValues gcvalues;
  218434. gcvalues.foreground = None;
  218435. gcvalues.background = None;
  218436. gcvalues.function = GXcopy;
  218437. gcvalues.plane_mask = AllPlanes;
  218438. gcvalues.clip_mask = None;
  218439. gcvalues.graphics_exposures = False;
  218440. gc = XCreateGC (display, window,
  218441. GCBackground | GCForeground | GCFunction | GCPlaneMask | GCClipMask | GCGraphicsExposures,
  218442. &gcvalues);
  218443. }
  218444. if (imageDepth == 16)
  218445. {
  218446. const uint32 rMask = xImage->red_mask;
  218447. const uint32 rShiftL = jmax (0, getShiftNeeded (rMask));
  218448. const uint32 rShiftR = jmax (0, -getShiftNeeded (rMask));
  218449. const uint32 gMask = xImage->green_mask;
  218450. const uint32 gShiftL = jmax (0, getShiftNeeded (gMask));
  218451. const uint32 gShiftR = jmax (0, -getShiftNeeded (gMask));
  218452. const uint32 bMask = xImage->blue_mask;
  218453. const uint32 bShiftL = jmax (0, getShiftNeeded (bMask));
  218454. const uint32 bShiftR = jmax (0, -getShiftNeeded (bMask));
  218455. const Image::BitmapData srcData (Image (this), 0, 0, width, height);
  218456. for (int y = sy; y < sy + dh; ++y)
  218457. {
  218458. const uint8* p = srcData.getPixelPointer (sx, y);
  218459. for (int x = sx; x < sx + dw; ++x)
  218460. {
  218461. const PixelRGB* const pixel = (const PixelRGB*) p;
  218462. p += srcData.pixelStride;
  218463. XPutPixel (xImage, x, y,
  218464. (((((uint32) pixel->getRed()) << rShiftL) >> rShiftR) & rMask)
  218465. | (((((uint32) pixel->getGreen()) << gShiftL) >> gShiftR) & gMask)
  218466. | (((((uint32) pixel->getBlue()) << bShiftL) >> bShiftR) & bMask));
  218467. }
  218468. }
  218469. }
  218470. // blit results to screen.
  218471. #if JUCE_USE_XSHM
  218472. if (usingXShm)
  218473. XShmPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh, True);
  218474. else
  218475. #endif
  218476. XPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh);
  218477. }
  218478. juce_UseDebuggingNewOperator
  218479. private:
  218480. XImage* xImage;
  218481. const int imageDepth;
  218482. HeapBlock <uint8> imageDataAllocated;
  218483. HeapBlock <char> imageData16Bit;
  218484. GC gc;
  218485. #if JUCE_USE_XSHM
  218486. XShmSegmentInfo segmentInfo;
  218487. bool usingXShm;
  218488. #endif
  218489. static int getShiftNeeded (const uint32 mask) throw()
  218490. {
  218491. for (int i = 32; --i >= 0;)
  218492. if (((mask >> i) & 1) != 0)
  218493. return i - 7;
  218494. jassertfalse;
  218495. return 0;
  218496. }
  218497. };
  218498. class LinuxComponentPeer : public ComponentPeer
  218499. {
  218500. public:
  218501. LinuxComponentPeer (Component* const component, const int windowStyleFlags)
  218502. : ComponentPeer (component, windowStyleFlags),
  218503. windowH (0),
  218504. parentWindow (0),
  218505. wx (0),
  218506. wy (0),
  218507. ww (0),
  218508. wh (0),
  218509. fullScreen (false),
  218510. mapped (false),
  218511. visual (0),
  218512. depth (0)
  218513. {
  218514. // it's dangerous to create a window on a thread other than the message thread..
  218515. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  218516. repainter = new LinuxRepaintManager (this);
  218517. createWindow();
  218518. setTitle (component->getName());
  218519. }
  218520. ~LinuxComponentPeer()
  218521. {
  218522. // it's dangerous to delete a window on a thread other than the message thread..
  218523. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  218524. deleteIconPixmaps();
  218525. destroyWindow();
  218526. windowH = 0;
  218527. }
  218528. void* getNativeHandle() const
  218529. {
  218530. return (void*) windowH;
  218531. }
  218532. static LinuxComponentPeer* getPeerFor (Window windowHandle) throw()
  218533. {
  218534. XPointer peer = 0;
  218535. ScopedXLock xlock;
  218536. if (! XFindContext (display, (XID) windowHandle, windowHandleXContext, &peer))
  218537. {
  218538. if (peer != 0 && ! ComponentPeer::isValidPeer ((LinuxComponentPeer*) peer))
  218539. peer = 0;
  218540. }
  218541. return (LinuxComponentPeer*) peer;
  218542. }
  218543. void setVisible (bool shouldBeVisible)
  218544. {
  218545. ScopedXLock xlock;
  218546. if (shouldBeVisible)
  218547. XMapWindow (display, windowH);
  218548. else
  218549. XUnmapWindow (display, windowH);
  218550. }
  218551. void setTitle (const String& title)
  218552. {
  218553. setWindowTitle (windowH, title);
  218554. }
  218555. void setPosition (int x, int y)
  218556. {
  218557. setBounds (x, y, ww, wh, false);
  218558. }
  218559. void setSize (int w, int h)
  218560. {
  218561. setBounds (wx, wy, w, h, false);
  218562. }
  218563. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  218564. {
  218565. fullScreen = isNowFullScreen;
  218566. if (windowH != 0)
  218567. {
  218568. Component::SafePointer<Component> deletionChecker (component);
  218569. wx = x;
  218570. wy = y;
  218571. ww = jmax (1, w);
  218572. wh = jmax (1, h);
  218573. ScopedXLock xlock;
  218574. // Make sure the Window manager does what we want
  218575. XSizeHints* hints = XAllocSizeHints();
  218576. hints->flags = USSize | USPosition;
  218577. hints->width = ww;
  218578. hints->height = wh;
  218579. hints->x = wx;
  218580. hints->y = wy;
  218581. if ((getStyleFlags() & (windowHasTitleBar | windowIsResizable)) == windowHasTitleBar)
  218582. {
  218583. hints->min_width = hints->max_width = hints->width;
  218584. hints->min_height = hints->max_height = hints->height;
  218585. hints->flags |= PMinSize | PMaxSize;
  218586. }
  218587. XSetWMNormalHints (display, windowH, hints);
  218588. XFree (hints);
  218589. XMoveResizeWindow (display, windowH,
  218590. wx - windowBorder.getLeft(),
  218591. wy - windowBorder.getTop(), ww, wh);
  218592. if (deletionChecker != 0)
  218593. {
  218594. updateBorderSize();
  218595. handleMovedOrResized();
  218596. }
  218597. }
  218598. }
  218599. const Rectangle<int> getBounds() const { return Rectangle<int> (wx, wy, ww, wh); }
  218600. const Point<int> getScreenPosition() const { return Point<int> (wx, wy); }
  218601. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  218602. {
  218603. return relativePosition + getScreenPosition();
  218604. }
  218605. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  218606. {
  218607. return screenPosition - getScreenPosition();
  218608. }
  218609. void setMinimised (bool shouldBeMinimised)
  218610. {
  218611. if (shouldBeMinimised)
  218612. {
  218613. Window root = RootWindow (display, DefaultScreen (display));
  218614. XClientMessageEvent clientMsg;
  218615. clientMsg.display = display;
  218616. clientMsg.window = windowH;
  218617. clientMsg.type = ClientMessage;
  218618. clientMsg.format = 32;
  218619. clientMsg.message_type = Atoms::ChangeState;
  218620. clientMsg.data.l[0] = IconicState;
  218621. ScopedXLock xlock;
  218622. XSendEvent (display, root, false, SubstructureRedirectMask | SubstructureNotifyMask, (XEvent*) &clientMsg);
  218623. }
  218624. else
  218625. {
  218626. setVisible (true);
  218627. }
  218628. }
  218629. bool isMinimised() const
  218630. {
  218631. bool minimised = false;
  218632. unsigned char* stateProp;
  218633. unsigned long nitems, bytesLeft;
  218634. Atom actualType;
  218635. int actualFormat;
  218636. ScopedXLock xlock;
  218637. if (XGetWindowProperty (display, windowH, Atoms::State, 0, 64, False,
  218638. Atoms::State, &actualType, &actualFormat, &nitems, &bytesLeft,
  218639. &stateProp) == Success
  218640. && actualType == Atoms::State
  218641. && actualFormat == 32
  218642. && nitems > 0)
  218643. {
  218644. if (((unsigned long*) stateProp)[0] == IconicState)
  218645. minimised = true;
  218646. XFree (stateProp);
  218647. }
  218648. return minimised;
  218649. }
  218650. void setFullScreen (const bool shouldBeFullScreen)
  218651. {
  218652. Rectangle<int> r (lastNonFullscreenBounds); // (get a copy of this before de-minimising)
  218653. setMinimised (false);
  218654. if (fullScreen != shouldBeFullScreen)
  218655. {
  218656. if (shouldBeFullScreen)
  218657. r = Desktop::getInstance().getMainMonitorArea();
  218658. if (! r.isEmpty())
  218659. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  218660. getComponent()->repaint();
  218661. }
  218662. }
  218663. bool isFullScreen() const
  218664. {
  218665. return fullScreen;
  218666. }
  218667. bool isChildWindowOf (Window possibleParent) const
  218668. {
  218669. Window* windowList = 0;
  218670. uint32 windowListSize = 0;
  218671. Window parent, root;
  218672. ScopedXLock xlock;
  218673. if (XQueryTree (display, windowH, &root, &parent, &windowList, &windowListSize) != 0)
  218674. {
  218675. if (windowList != 0)
  218676. XFree (windowList);
  218677. return parent == possibleParent;
  218678. }
  218679. return false;
  218680. }
  218681. bool isFrontWindow() const
  218682. {
  218683. Window* windowList = 0;
  218684. uint32 windowListSize = 0;
  218685. bool result = false;
  218686. ScopedXLock xlock;
  218687. Window parent, root = RootWindow (display, DefaultScreen (display));
  218688. if (XQueryTree (display, root, &root, &parent, &windowList, &windowListSize) != 0)
  218689. {
  218690. for (int i = windowListSize; --i >= 0;)
  218691. {
  218692. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (windowList[i]);
  218693. if (peer != 0)
  218694. {
  218695. result = (peer == this);
  218696. break;
  218697. }
  218698. }
  218699. }
  218700. if (windowList != 0)
  218701. XFree (windowList);
  218702. return result;
  218703. }
  218704. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  218705. {
  218706. int x = position.getX();
  218707. int y = position.getY();
  218708. if (((unsigned int) x) >= (unsigned int) ww
  218709. || ((unsigned int) y) >= (unsigned int) wh)
  218710. return false;
  218711. bool inFront = false;
  218712. for (int i = 0; i < Desktop::getInstance().getNumComponents(); ++i)
  218713. {
  218714. Component* const c = Desktop::getInstance().getComponent (i);
  218715. if (inFront)
  218716. {
  218717. if (c->contains (x + wx - c->getScreenX(),
  218718. y + wy - c->getScreenY()))
  218719. {
  218720. return false;
  218721. }
  218722. }
  218723. else if (c == getComponent())
  218724. {
  218725. inFront = true;
  218726. }
  218727. }
  218728. if (trueIfInAChildWindow)
  218729. return true;
  218730. ::Window root, child;
  218731. unsigned int bw, depth;
  218732. int wx, wy, w, h;
  218733. ScopedXLock xlock;
  218734. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  218735. &wx, &wy, (unsigned int*) &w, (unsigned int*) &h,
  218736. &bw, &depth))
  218737. {
  218738. return false;
  218739. }
  218740. if (! XTranslateCoordinates (display, windowH, windowH, x, y, &wx, &wy, &child))
  218741. return false;
  218742. return child == None;
  218743. }
  218744. const BorderSize getFrameSize() const
  218745. {
  218746. return BorderSize();
  218747. }
  218748. bool setAlwaysOnTop (bool alwaysOnTop)
  218749. {
  218750. return false;
  218751. }
  218752. void toFront (bool makeActive)
  218753. {
  218754. if (makeActive)
  218755. {
  218756. setVisible (true);
  218757. grabFocus();
  218758. }
  218759. XEvent ev;
  218760. ev.xclient.type = ClientMessage;
  218761. ev.xclient.serial = 0;
  218762. ev.xclient.send_event = True;
  218763. ev.xclient.message_type = Atoms::ActiveWin;
  218764. ev.xclient.window = windowH;
  218765. ev.xclient.format = 32;
  218766. ev.xclient.data.l[0] = 2;
  218767. ev.xclient.data.l[1] = CurrentTime;
  218768. ev.xclient.data.l[2] = 0;
  218769. ev.xclient.data.l[3] = 0;
  218770. ev.xclient.data.l[4] = 0;
  218771. {
  218772. ScopedXLock xlock;
  218773. XSendEvent (display, RootWindow (display, DefaultScreen (display)),
  218774. False, SubstructureRedirectMask | SubstructureNotifyMask, &ev);
  218775. XWindowAttributes attr;
  218776. XGetWindowAttributes (display, windowH, &attr);
  218777. if (component->isAlwaysOnTop())
  218778. XRaiseWindow (display, windowH);
  218779. XSync (display, False);
  218780. }
  218781. handleBroughtToFront();
  218782. }
  218783. void toBehind (ComponentPeer* other)
  218784. {
  218785. LinuxComponentPeer* const otherPeer = dynamic_cast <LinuxComponentPeer*> (other);
  218786. jassert (otherPeer != 0); // wrong type of window?
  218787. if (otherPeer != 0)
  218788. {
  218789. setMinimised (false);
  218790. Window newStack[] = { otherPeer->windowH, windowH };
  218791. ScopedXLock xlock;
  218792. XRestackWindows (display, newStack, 2);
  218793. }
  218794. }
  218795. bool isFocused() const
  218796. {
  218797. int revert = 0;
  218798. Window focusedWindow = 0;
  218799. ScopedXLock xlock;
  218800. XGetInputFocus (display, &focusedWindow, &revert);
  218801. return focusedWindow == windowH;
  218802. }
  218803. void grabFocus()
  218804. {
  218805. XWindowAttributes atts;
  218806. ScopedXLock xlock;
  218807. if (windowH != 0
  218808. && XGetWindowAttributes (display, windowH, &atts)
  218809. && atts.map_state == IsViewable
  218810. && ! isFocused())
  218811. {
  218812. XSetInputFocus (display, windowH, RevertToParent, CurrentTime);
  218813. isActiveApplication = true;
  218814. }
  218815. }
  218816. void textInputRequired (const Point<int>&)
  218817. {
  218818. }
  218819. void repaint (const Rectangle<int>& area)
  218820. {
  218821. repainter->repaint (area.getIntersection (getComponent()->getLocalBounds()));
  218822. }
  218823. void performAnyPendingRepaintsNow()
  218824. {
  218825. repainter->performAnyPendingRepaintsNow();
  218826. }
  218827. static Pixmap juce_createColourPixmapFromImage (Display* display, const Image& image)
  218828. {
  218829. ScopedXLock xlock;
  218830. const int width = image.getWidth();
  218831. const int height = image.getHeight();
  218832. HeapBlock <char> colour (width * height);
  218833. int index = 0;
  218834. for (int y = 0; y < height; ++y)
  218835. for (int x = 0; x < width; ++x)
  218836. colour[index++] = static_cast<char> (image.getPixelAt (x, y).getARGB());
  218837. XImage* ximage = XCreateImage (display, CopyFromParent, 24, ZPixmap,
  218838. 0, colour.getData(),
  218839. width, height, 32, 0);
  218840. Pixmap pixmap = XCreatePixmap (display, DefaultRootWindow (display),
  218841. width, height, 24);
  218842. GC gc = XCreateGC (display, pixmap, 0, 0);
  218843. XPutImage (display, pixmap, gc, ximage, 0, 0, 0, 0, width, height);
  218844. XFreeGC (display, gc);
  218845. return pixmap;
  218846. }
  218847. static Pixmap juce_createMaskPixmapFromImage (Display* display, const Image& image)
  218848. {
  218849. ScopedXLock xlock;
  218850. const int width = image.getWidth();
  218851. const int height = image.getHeight();
  218852. const int stride = (width + 7) >> 3;
  218853. HeapBlock <char> mask;
  218854. mask.calloc (stride * height);
  218855. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  218856. for (int y = 0; y < height; ++y)
  218857. {
  218858. for (int x = 0; x < width; ++x)
  218859. {
  218860. const char bit = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  218861. const int offset = y * stride + (x >> 3);
  218862. if (image.getPixelAt (x, y).getAlpha() >= 128)
  218863. mask[offset] |= bit;
  218864. }
  218865. }
  218866. return XCreatePixmapFromBitmapData (display, DefaultRootWindow (display),
  218867. mask.getData(), width, height, 1, 0, 1);
  218868. }
  218869. void setIcon (const Image& newIcon)
  218870. {
  218871. const int dataSize = newIcon.getWidth() * newIcon.getHeight() + 2;
  218872. HeapBlock <unsigned long> data (dataSize);
  218873. int index = 0;
  218874. data[index++] = newIcon.getWidth();
  218875. data[index++] = newIcon.getHeight();
  218876. for (int y = 0; y < newIcon.getHeight(); ++y)
  218877. for (int x = 0; x < newIcon.getWidth(); ++x)
  218878. data[index++] = newIcon.getPixelAt (x, y).getARGB();
  218879. ScopedXLock xlock;
  218880. XChangeProperty (display, windowH,
  218881. XInternAtom (display, "_NET_WM_ICON", False),
  218882. XA_CARDINAL, 32, PropModeReplace,
  218883. reinterpret_cast<unsigned char*> (data.getData()), dataSize);
  218884. deleteIconPixmaps();
  218885. XWMHints* wmHints = XGetWMHints (display, windowH);
  218886. if (wmHints == 0)
  218887. wmHints = XAllocWMHints();
  218888. wmHints->flags |= IconPixmapHint | IconMaskHint;
  218889. wmHints->icon_pixmap = juce_createColourPixmapFromImage (display, newIcon);
  218890. wmHints->icon_mask = juce_createMaskPixmapFromImage (display, newIcon);
  218891. XSetWMHints (display, windowH, wmHints);
  218892. XFree (wmHints);
  218893. XSync (display, False);
  218894. }
  218895. void deleteIconPixmaps()
  218896. {
  218897. ScopedXLock xlock;
  218898. XWMHints* wmHints = XGetWMHints (display, windowH);
  218899. if (wmHints != 0)
  218900. {
  218901. if ((wmHints->flags & IconPixmapHint) != 0)
  218902. {
  218903. wmHints->flags &= ~IconPixmapHint;
  218904. XFreePixmap (display, wmHints->icon_pixmap);
  218905. }
  218906. if ((wmHints->flags & IconMaskHint) != 0)
  218907. {
  218908. wmHints->flags &= ~IconMaskHint;
  218909. XFreePixmap (display, wmHints->icon_mask);
  218910. }
  218911. XSetWMHints (display, windowH, wmHints);
  218912. XFree (wmHints);
  218913. }
  218914. }
  218915. void handleWindowMessage (XEvent* event)
  218916. {
  218917. switch (event->xany.type)
  218918. {
  218919. case 2: // 'KeyPress'
  218920. {
  218921. ScopedXLock xlock;
  218922. XKeyEvent* const keyEvent = (XKeyEvent*) &event->xkey;
  218923. updateKeyStates (keyEvent->keycode, true);
  218924. char utf8 [64];
  218925. zeromem (utf8, sizeof (utf8));
  218926. KeySym sym;
  218927. {
  218928. const char* oldLocale = ::setlocale (LC_ALL, 0);
  218929. ::setlocale (LC_ALL, "");
  218930. XLookupString (keyEvent, utf8, sizeof (utf8), &sym, 0);
  218931. ::setlocale (LC_ALL, oldLocale);
  218932. }
  218933. const juce_wchar unicodeChar = String::fromUTF8 (utf8, sizeof (utf8) - 1) [0];
  218934. int keyCode = (int) unicodeChar;
  218935. if (keyCode < 0x20)
  218936. keyCode = XKeycodeToKeysym (display, keyEvent->keycode, currentModifiers.isShiftDown() ? 1 : 0);
  218937. const ModifierKeys oldMods (currentModifiers);
  218938. bool keyPressed = false;
  218939. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, true);
  218940. if ((sym & 0xff00) == 0xff00)
  218941. {
  218942. // Translate keypad
  218943. if (sym == XK_KP_Divide)
  218944. keyCode = XK_slash;
  218945. else if (sym == XK_KP_Multiply)
  218946. keyCode = XK_asterisk;
  218947. else if (sym == XK_KP_Subtract)
  218948. keyCode = XK_hyphen;
  218949. else if (sym == XK_KP_Add)
  218950. keyCode = XK_plus;
  218951. else if (sym == XK_KP_Enter)
  218952. keyCode = XK_Return;
  218953. else if (sym == XK_KP_Decimal)
  218954. keyCode = Keys::numLock ? XK_period : XK_Delete;
  218955. else if (sym == XK_KP_0)
  218956. keyCode = Keys::numLock ? XK_0 : XK_Insert;
  218957. else if (sym == XK_KP_1)
  218958. keyCode = Keys::numLock ? XK_1 : XK_End;
  218959. else if (sym == XK_KP_2)
  218960. keyCode = Keys::numLock ? XK_2 : XK_Down;
  218961. else if (sym == XK_KP_3)
  218962. keyCode = Keys::numLock ? XK_3 : XK_Page_Down;
  218963. else if (sym == XK_KP_4)
  218964. keyCode = Keys::numLock ? XK_4 : XK_Left;
  218965. else if (sym == XK_KP_5)
  218966. keyCode = XK_5;
  218967. else if (sym == XK_KP_6)
  218968. keyCode = Keys::numLock ? XK_6 : XK_Right;
  218969. else if (sym == XK_KP_7)
  218970. keyCode = Keys::numLock ? XK_7 : XK_Home;
  218971. else if (sym == XK_KP_8)
  218972. keyCode = Keys::numLock ? XK_8 : XK_Up;
  218973. else if (sym == XK_KP_9)
  218974. keyCode = Keys::numLock ? XK_9 : XK_Page_Up;
  218975. switch (sym)
  218976. {
  218977. case XK_Left:
  218978. case XK_Right:
  218979. case XK_Up:
  218980. case XK_Down:
  218981. case XK_Page_Up:
  218982. case XK_Page_Down:
  218983. case XK_End:
  218984. case XK_Home:
  218985. case XK_Delete:
  218986. case XK_Insert:
  218987. keyPressed = true;
  218988. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  218989. break;
  218990. case XK_Tab:
  218991. case XK_Return:
  218992. case XK_Escape:
  218993. case XK_BackSpace:
  218994. keyPressed = true;
  218995. keyCode &= 0xff;
  218996. break;
  218997. default:
  218998. {
  218999. if (sym >= XK_F1 && sym <= XK_F16)
  219000. {
  219001. keyPressed = true;
  219002. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  219003. }
  219004. break;
  219005. }
  219006. }
  219007. }
  219008. if (utf8[0] != 0 || ((sym & 0xff00) == 0 && sym >= 8))
  219009. keyPressed = true;
  219010. if (oldMods != currentModifiers)
  219011. handleModifierKeysChange();
  219012. if (keyDownChange)
  219013. handleKeyUpOrDown (true);
  219014. if (keyPressed)
  219015. handleKeyPress (keyCode, unicodeChar);
  219016. break;
  219017. }
  219018. case KeyRelease:
  219019. {
  219020. const XKeyEvent* const keyEvent = (const XKeyEvent*) &event->xkey;
  219021. updateKeyStates (keyEvent->keycode, false);
  219022. ScopedXLock xlock;
  219023. KeySym sym = XKeycodeToKeysym (display, keyEvent->keycode, 0);
  219024. const ModifierKeys oldMods (currentModifiers);
  219025. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, false);
  219026. if (oldMods != currentModifiers)
  219027. handleModifierKeysChange();
  219028. if (keyDownChange)
  219029. handleKeyUpOrDown (false);
  219030. break;
  219031. }
  219032. case ButtonPress:
  219033. {
  219034. const XButtonPressedEvent* const buttonPressEvent = (const XButtonPressedEvent*) &event->xbutton;
  219035. updateKeyModifiers (buttonPressEvent->state);
  219036. bool buttonMsg = false;
  219037. const int map = pointerMap [buttonPressEvent->button - Button1];
  219038. if (map == Keys::WheelUp || map == Keys::WheelDown)
  219039. {
  219040. handleMouseWheel (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y),
  219041. getEventTime (buttonPressEvent->time), 0, map == Keys::WheelDown ? -84.0f : 84.0f);
  219042. }
  219043. if (map == Keys::LeftButton)
  219044. {
  219045. currentModifiers = currentModifiers.withFlags (ModifierKeys::leftButtonModifier);
  219046. buttonMsg = true;
  219047. }
  219048. else if (map == Keys::RightButton)
  219049. {
  219050. currentModifiers = currentModifiers.withFlags (ModifierKeys::rightButtonModifier);
  219051. buttonMsg = true;
  219052. }
  219053. else if (map == Keys::MiddleButton)
  219054. {
  219055. currentModifiers = currentModifiers.withFlags (ModifierKeys::middleButtonModifier);
  219056. buttonMsg = true;
  219057. }
  219058. if (buttonMsg)
  219059. {
  219060. toFront (true);
  219061. handleMouseEvent (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y), currentModifiers,
  219062. getEventTime (buttonPressEvent->time));
  219063. }
  219064. clearLastMousePos();
  219065. break;
  219066. }
  219067. case ButtonRelease:
  219068. {
  219069. const XButtonReleasedEvent* const buttonRelEvent = (const XButtonReleasedEvent*) &event->xbutton;
  219070. updateKeyModifiers (buttonRelEvent->state);
  219071. const int map = pointerMap [buttonRelEvent->button - Button1];
  219072. if (map == Keys::LeftButton)
  219073. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::leftButtonModifier);
  219074. else if (map == Keys::RightButton)
  219075. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::rightButtonModifier);
  219076. else if (map == Keys::MiddleButton)
  219077. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::middleButtonModifier);
  219078. handleMouseEvent (0, Point<int> (buttonRelEvent->x, buttonRelEvent->y), currentModifiers,
  219079. getEventTime (buttonRelEvent->time));
  219080. clearLastMousePos();
  219081. break;
  219082. }
  219083. case MotionNotify:
  219084. {
  219085. const XPointerMovedEvent* const movedEvent = (const XPointerMovedEvent*) &event->xmotion;
  219086. updateKeyModifiers (movedEvent->state);
  219087. const Point<int> mousePos (Desktop::getMousePosition());
  219088. if (lastMousePos != mousePos)
  219089. {
  219090. lastMousePos = mousePos;
  219091. if (parentWindow != 0 && (styleFlags & windowHasTitleBar) == 0)
  219092. {
  219093. Window wRoot = 0, wParent = 0;
  219094. {
  219095. ScopedXLock xlock;
  219096. unsigned int numChildren;
  219097. Window* wChild = 0;
  219098. XQueryTree (display, windowH, &wRoot, &wParent, &wChild, &numChildren);
  219099. }
  219100. if (wParent != 0
  219101. && wParent != windowH
  219102. && wParent != wRoot)
  219103. {
  219104. parentWindow = wParent;
  219105. updateBounds();
  219106. }
  219107. else
  219108. {
  219109. parentWindow = 0;
  219110. }
  219111. }
  219112. handleMouseEvent (0, mousePos - getScreenPosition(), currentModifiers, getEventTime (movedEvent->time));
  219113. }
  219114. break;
  219115. }
  219116. case EnterNotify:
  219117. {
  219118. clearLastMousePos();
  219119. const XEnterWindowEvent* const enterEvent = (const XEnterWindowEvent*) &event->xcrossing;
  219120. if (! currentModifiers.isAnyMouseButtonDown())
  219121. {
  219122. updateKeyModifiers (enterEvent->state);
  219123. handleMouseEvent (0, Point<int> (enterEvent->x, enterEvent->y), currentModifiers, getEventTime (enterEvent->time));
  219124. }
  219125. break;
  219126. }
  219127. case LeaveNotify:
  219128. {
  219129. const XLeaveWindowEvent* const leaveEvent = (const XLeaveWindowEvent*) &event->xcrossing;
  219130. // Suppress the normal leave if we've got a pointer grab, or if
  219131. // it's a bogus one caused by clicking a mouse button when running
  219132. // in a Window manager
  219133. if (((! currentModifiers.isAnyMouseButtonDown()) && leaveEvent->mode == NotifyNormal)
  219134. || leaveEvent->mode == NotifyUngrab)
  219135. {
  219136. updateKeyModifiers (leaveEvent->state);
  219137. handleMouseEvent (0, Point<int> (leaveEvent->x, leaveEvent->y), currentModifiers, getEventTime (leaveEvent->time));
  219138. }
  219139. break;
  219140. }
  219141. case FocusIn:
  219142. {
  219143. isActiveApplication = true;
  219144. if (isFocused())
  219145. handleFocusGain();
  219146. break;
  219147. }
  219148. case FocusOut:
  219149. {
  219150. isActiveApplication = false;
  219151. if (! isFocused())
  219152. handleFocusLoss();
  219153. break;
  219154. }
  219155. case Expose:
  219156. {
  219157. // Batch together all pending expose events
  219158. XExposeEvent* exposeEvent = (XExposeEvent*) &event->xexpose;
  219159. XEvent nextEvent;
  219160. ScopedXLock xlock;
  219161. if (exposeEvent->window != windowH)
  219162. {
  219163. Window child;
  219164. XTranslateCoordinates (display, exposeEvent->window, windowH,
  219165. exposeEvent->x, exposeEvent->y, &exposeEvent->x, &exposeEvent->y,
  219166. &child);
  219167. }
  219168. repaint (Rectangle<int> (exposeEvent->x, exposeEvent->y,
  219169. exposeEvent->width, exposeEvent->height));
  219170. while (XEventsQueued (display, QueuedAfterFlush) > 0)
  219171. {
  219172. XPeekEvent (display, (XEvent*) &nextEvent);
  219173. if (nextEvent.type != Expose || nextEvent.xany.window != event->xany.window)
  219174. break;
  219175. XNextEvent (display, (XEvent*) &nextEvent);
  219176. XExposeEvent* nextExposeEvent = (XExposeEvent*) &nextEvent.xexpose;
  219177. repaint (Rectangle<int> (nextExposeEvent->x, nextExposeEvent->y,
  219178. nextExposeEvent->width, nextExposeEvent->height));
  219179. }
  219180. break;
  219181. }
  219182. case CirculateNotify:
  219183. case CreateNotify:
  219184. case DestroyNotify:
  219185. // Think we can ignore these
  219186. break;
  219187. case ConfigureNotify:
  219188. {
  219189. updateBounds();
  219190. updateBorderSize();
  219191. handleMovedOrResized();
  219192. // if the native title bar is dragged, need to tell any active menus, etc.
  219193. if ((styleFlags & windowHasTitleBar) != 0
  219194. && component->isCurrentlyBlockedByAnotherModalComponent())
  219195. {
  219196. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  219197. if (currentModalComp != 0)
  219198. currentModalComp->inputAttemptWhenModal();
  219199. }
  219200. XConfigureEvent* const confEvent = (XConfigureEvent*) &event->xconfigure;
  219201. if (confEvent->window == windowH
  219202. && confEvent->above != 0
  219203. && isFrontWindow())
  219204. {
  219205. handleBroughtToFront();
  219206. }
  219207. break;
  219208. }
  219209. case ReparentNotify:
  219210. {
  219211. parentWindow = 0;
  219212. Window wRoot = 0;
  219213. Window* wChild = 0;
  219214. unsigned int numChildren;
  219215. {
  219216. ScopedXLock xlock;
  219217. XQueryTree (display, windowH, &wRoot, &parentWindow, &wChild, &numChildren);
  219218. }
  219219. if (parentWindow == windowH || parentWindow == wRoot)
  219220. parentWindow = 0;
  219221. updateBounds();
  219222. updateBorderSize();
  219223. handleMovedOrResized();
  219224. break;
  219225. }
  219226. case GravityNotify:
  219227. {
  219228. updateBounds();
  219229. updateBorderSize();
  219230. handleMovedOrResized();
  219231. break;
  219232. }
  219233. case MapNotify:
  219234. mapped = true;
  219235. handleBroughtToFront();
  219236. break;
  219237. case UnmapNotify:
  219238. mapped = false;
  219239. break;
  219240. case MappingNotify:
  219241. {
  219242. XMappingEvent* mappingEvent = (XMappingEvent*) &event->xmapping;
  219243. if (mappingEvent->request != MappingPointer)
  219244. {
  219245. // Deal with modifier/keyboard mapping
  219246. ScopedXLock xlock;
  219247. XRefreshKeyboardMapping (mappingEvent);
  219248. updateModifierMappings();
  219249. }
  219250. break;
  219251. }
  219252. case ClientMessage:
  219253. {
  219254. const XClientMessageEvent* const clientMsg = (const XClientMessageEvent*) &event->xclient;
  219255. if (clientMsg->message_type == Atoms::Protocols && clientMsg->format == 32)
  219256. {
  219257. const Atom atom = (Atom) clientMsg->data.l[0];
  219258. if (atom == Atoms::ProtocolList [Atoms::PING])
  219259. {
  219260. Window root = RootWindow (display, DefaultScreen (display));
  219261. event->xclient.window = root;
  219262. XSendEvent (display, root, False, NoEventMask, event);
  219263. XFlush (display);
  219264. }
  219265. else if (atom == Atoms::ProtocolList [Atoms::TAKE_FOCUS])
  219266. {
  219267. XWindowAttributes atts;
  219268. ScopedXLock xlock;
  219269. if (clientMsg->window != 0
  219270. && XGetWindowAttributes (display, clientMsg->window, &atts))
  219271. {
  219272. if (atts.map_state == IsViewable)
  219273. XSetInputFocus (display, clientMsg->window, RevertToParent, clientMsg->data.l[1]);
  219274. }
  219275. }
  219276. else if (atom == Atoms::ProtocolList [Atoms::DELETE_WINDOW])
  219277. {
  219278. handleUserClosingWindow();
  219279. }
  219280. }
  219281. else if (clientMsg->message_type == Atoms::XdndEnter)
  219282. {
  219283. handleDragAndDropEnter (clientMsg);
  219284. }
  219285. else if (clientMsg->message_type == Atoms::XdndLeave)
  219286. {
  219287. resetDragAndDrop();
  219288. }
  219289. else if (clientMsg->message_type == Atoms::XdndPosition)
  219290. {
  219291. handleDragAndDropPosition (clientMsg);
  219292. }
  219293. else if (clientMsg->message_type == Atoms::XdndDrop)
  219294. {
  219295. handleDragAndDropDrop (clientMsg);
  219296. }
  219297. else if (clientMsg->message_type == Atoms::XdndStatus)
  219298. {
  219299. handleDragAndDropStatus (clientMsg);
  219300. }
  219301. else if (clientMsg->message_type == Atoms::XdndFinished)
  219302. {
  219303. resetDragAndDrop();
  219304. }
  219305. break;
  219306. }
  219307. case SelectionNotify:
  219308. handleDragAndDropSelection (event);
  219309. break;
  219310. case SelectionClear:
  219311. case SelectionRequest:
  219312. break;
  219313. default:
  219314. #if JUCE_USE_XSHM
  219315. {
  219316. ScopedXLock xlock;
  219317. if (event->xany.type == XShmGetEventBase (display))
  219318. repainter->notifyPaintCompleted();
  219319. }
  219320. #endif
  219321. break;
  219322. }
  219323. }
  219324. void showMouseCursor (Cursor cursor) throw()
  219325. {
  219326. ScopedXLock xlock;
  219327. XDefineCursor (display, windowH, cursor);
  219328. }
  219329. void setTaskBarIcon (const Image& image)
  219330. {
  219331. ScopedXLock xlock;
  219332. taskbarImage = image;
  219333. Screen* const screen = XDefaultScreenOfDisplay (display);
  219334. const int screenNumber = XScreenNumberOfScreen (screen);
  219335. String screenAtom ("_NET_SYSTEM_TRAY_S");
  219336. screenAtom << screenNumber;
  219337. Atom selectionAtom = XInternAtom (display, screenAtom.toUTF8(), false);
  219338. XGrabServer (display);
  219339. Window managerWin = XGetSelectionOwner (display, selectionAtom);
  219340. if (managerWin != None)
  219341. XSelectInput (display, managerWin, StructureNotifyMask);
  219342. XUngrabServer (display);
  219343. XFlush (display);
  219344. if (managerWin != None)
  219345. {
  219346. XEvent ev;
  219347. zerostruct (ev);
  219348. ev.xclient.type = ClientMessage;
  219349. ev.xclient.window = managerWin;
  219350. ev.xclient.message_type = XInternAtom (display, "_NET_SYSTEM_TRAY_OPCODE", False);
  219351. ev.xclient.format = 32;
  219352. ev.xclient.data.l[0] = CurrentTime;
  219353. ev.xclient.data.l[1] = 0 /*SYSTEM_TRAY_REQUEST_DOCK*/;
  219354. ev.xclient.data.l[2] = windowH;
  219355. ev.xclient.data.l[3] = 0;
  219356. ev.xclient.data.l[4] = 0;
  219357. XSendEvent (display, managerWin, False, NoEventMask, &ev);
  219358. XSync (display, False);
  219359. }
  219360. // For older KDE's ...
  219361. long atomData = 1;
  219362. Atom trayAtom = XInternAtom (display, "KWM_DOCKWINDOW", false);
  219363. XChangeProperty (display, windowH, trayAtom, trayAtom, 32, PropModeReplace, (unsigned char*) &atomData, 1);
  219364. // For more recent KDE's...
  219365. trayAtom = XInternAtom (display, "_KDE_NET_WM_SYSTEM_TRAY_WINDOW_FOR", false);
  219366. XChangeProperty (display, windowH, trayAtom, XA_WINDOW, 32, PropModeReplace, (unsigned char*) &windowH, 1);
  219367. // a minimum size must be specified for GNOME and Xfce, otherwise the icon is displayed with a width of 1
  219368. XSizeHints* hints = XAllocSizeHints();
  219369. hints->flags = PMinSize;
  219370. hints->min_width = 22;
  219371. hints->min_height = 22;
  219372. XSetWMNormalHints (display, windowH, hints);
  219373. XFree (hints);
  219374. }
  219375. const Image& getTaskbarIcon() const throw() { return taskbarImage; }
  219376. juce_UseDebuggingNewOperator
  219377. bool dontRepaint;
  219378. static ModifierKeys currentModifiers;
  219379. static bool isActiveApplication;
  219380. private:
  219381. class LinuxRepaintManager : public Timer
  219382. {
  219383. public:
  219384. LinuxRepaintManager (LinuxComponentPeer* const peer_)
  219385. : peer (peer_),
  219386. lastTimeImageUsed (0)
  219387. {
  219388. #if JUCE_USE_XSHM
  219389. shmCompletedDrawing = true;
  219390. useARGBImagesForRendering = XSHMHelpers::isShmAvailable();
  219391. if (useARGBImagesForRendering)
  219392. {
  219393. ScopedXLock xlock;
  219394. XShmSegmentInfo segmentinfo;
  219395. XImage* const testImage
  219396. = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  219397. 24, ZPixmap, 0, &segmentinfo, 64, 64);
  219398. useARGBImagesForRendering = (testImage->bits_per_pixel == 32);
  219399. XDestroyImage (testImage);
  219400. }
  219401. #endif
  219402. }
  219403. ~LinuxRepaintManager()
  219404. {
  219405. }
  219406. void timerCallback()
  219407. {
  219408. #if JUCE_USE_XSHM
  219409. if (! shmCompletedDrawing)
  219410. return;
  219411. #endif
  219412. if (! regionsNeedingRepaint.isEmpty())
  219413. {
  219414. stopTimer();
  219415. performAnyPendingRepaintsNow();
  219416. }
  219417. else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
  219418. {
  219419. stopTimer();
  219420. image = Image();
  219421. }
  219422. }
  219423. void repaint (const Rectangle<int>& area)
  219424. {
  219425. if (! isTimerRunning())
  219426. startTimer (repaintTimerPeriod);
  219427. regionsNeedingRepaint.add (area);
  219428. }
  219429. void performAnyPendingRepaintsNow()
  219430. {
  219431. #if JUCE_USE_XSHM
  219432. if (! shmCompletedDrawing)
  219433. {
  219434. startTimer (repaintTimerPeriod);
  219435. return;
  219436. }
  219437. #endif
  219438. peer->clearMaskedRegion();
  219439. RectangleList originalRepaintRegion (regionsNeedingRepaint);
  219440. regionsNeedingRepaint.clear();
  219441. const Rectangle<int> totalArea (originalRepaintRegion.getBounds());
  219442. if (! totalArea.isEmpty())
  219443. {
  219444. if (image.isNull() || image.getWidth() < totalArea.getWidth()
  219445. || image.getHeight() < totalArea.getHeight())
  219446. {
  219447. #if JUCE_USE_XSHM
  219448. image = Image (new XBitmapImage (useARGBImagesForRendering ? Image::ARGB
  219449. : Image::RGB,
  219450. #else
  219451. image = Image (new XBitmapImage (Image::RGB,
  219452. #endif
  219453. (totalArea.getWidth() + 31) & ~31,
  219454. (totalArea.getHeight() + 31) & ~31,
  219455. false, peer->depth, peer->visual));
  219456. }
  219457. startTimer (repaintTimerPeriod);
  219458. RectangleList adjustedList (originalRepaintRegion);
  219459. adjustedList.offsetAll (-totalArea.getX(), -totalArea.getY());
  219460. LowLevelGraphicsSoftwareRenderer context (image, -totalArea.getX(), -totalArea.getY(), adjustedList);
  219461. if (peer->depth == 32)
  219462. {
  219463. RectangleList::Iterator i (originalRepaintRegion);
  219464. while (i.next())
  219465. image.clear (*i.getRectangle() - totalArea.getPosition());
  219466. }
  219467. peer->handlePaint (context);
  219468. if (! peer->maskedRegion.isEmpty())
  219469. originalRepaintRegion.subtract (peer->maskedRegion);
  219470. for (RectangleList::Iterator i (originalRepaintRegion); i.next();)
  219471. {
  219472. #if JUCE_USE_XSHM
  219473. shmCompletedDrawing = false;
  219474. #endif
  219475. const Rectangle<int>& r = *i.getRectangle();
  219476. static_cast<XBitmapImage*> (image.getSharedImage())
  219477. ->blitToWindow (peer->windowH,
  219478. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  219479. r.getX() - totalArea.getX(), r.getY() - totalArea.getY());
  219480. }
  219481. }
  219482. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  219483. startTimer (repaintTimerPeriod);
  219484. }
  219485. #if JUCE_USE_XSHM
  219486. void notifyPaintCompleted() { shmCompletedDrawing = true; }
  219487. #endif
  219488. private:
  219489. enum { repaintTimerPeriod = 1000 / 100 };
  219490. LinuxComponentPeer* const peer;
  219491. Image image;
  219492. uint32 lastTimeImageUsed;
  219493. RectangleList regionsNeedingRepaint;
  219494. #if JUCE_USE_XSHM
  219495. bool useARGBImagesForRendering, shmCompletedDrawing;
  219496. #endif
  219497. LinuxRepaintManager (const LinuxRepaintManager&);
  219498. LinuxRepaintManager& operator= (const LinuxRepaintManager&);
  219499. };
  219500. ScopedPointer <LinuxRepaintManager> repainter;
  219501. friend class LinuxRepaintManager;
  219502. Window windowH, parentWindow;
  219503. int wx, wy, ww, wh;
  219504. Image taskbarImage;
  219505. bool fullScreen, mapped;
  219506. Visual* visual;
  219507. int depth;
  219508. BorderSize windowBorder;
  219509. struct MotifWmHints
  219510. {
  219511. unsigned long flags;
  219512. unsigned long functions;
  219513. unsigned long decorations;
  219514. long input_mode;
  219515. unsigned long status;
  219516. };
  219517. static void updateKeyStates (const int keycode, const bool press) throw()
  219518. {
  219519. const int keybyte = keycode >> 3;
  219520. const int keybit = (1 << (keycode & 7));
  219521. if (press)
  219522. Keys::keyStates [keybyte] |= keybit;
  219523. else
  219524. Keys::keyStates [keybyte] &= ~keybit;
  219525. }
  219526. static void updateKeyModifiers (const int status) throw()
  219527. {
  219528. int keyMods = 0;
  219529. if (status & ShiftMask) keyMods |= ModifierKeys::shiftModifier;
  219530. if (status & ControlMask) keyMods |= ModifierKeys::ctrlModifier;
  219531. if (status & Keys::AltMask) keyMods |= ModifierKeys::altModifier;
  219532. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  219533. Keys::numLock = ((status & Keys::NumLockMask) != 0);
  219534. Keys::capsLock = ((status & LockMask) != 0);
  219535. }
  219536. static bool updateKeyModifiersFromSym (KeySym sym, const bool press) throw()
  219537. {
  219538. int modifier = 0;
  219539. bool isModifier = true;
  219540. switch (sym)
  219541. {
  219542. case XK_Shift_L:
  219543. case XK_Shift_R:
  219544. modifier = ModifierKeys::shiftModifier;
  219545. break;
  219546. case XK_Control_L:
  219547. case XK_Control_R:
  219548. modifier = ModifierKeys::ctrlModifier;
  219549. break;
  219550. case XK_Alt_L:
  219551. case XK_Alt_R:
  219552. modifier = ModifierKeys::altModifier;
  219553. break;
  219554. case XK_Num_Lock:
  219555. if (press)
  219556. Keys::numLock = ! Keys::numLock;
  219557. break;
  219558. case XK_Caps_Lock:
  219559. if (press)
  219560. Keys::capsLock = ! Keys::capsLock;
  219561. break;
  219562. case XK_Scroll_Lock:
  219563. break;
  219564. default:
  219565. isModifier = false;
  219566. break;
  219567. }
  219568. if (modifier != 0)
  219569. {
  219570. if (press)
  219571. currentModifiers = currentModifiers.withFlags (modifier);
  219572. else
  219573. currentModifiers = currentModifiers.withoutFlags (modifier);
  219574. }
  219575. return isModifier;
  219576. }
  219577. // Alt and Num lock are not defined by standard X
  219578. // modifier constants: check what they're mapped to
  219579. static void updateModifierMappings() throw()
  219580. {
  219581. ScopedXLock xlock;
  219582. const int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
  219583. const int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
  219584. Keys::AltMask = 0;
  219585. Keys::NumLockMask = 0;
  219586. XModifierKeymap* mapping = XGetModifierMapping (display);
  219587. if (mapping)
  219588. {
  219589. for (int i = 0; i < 8; i++)
  219590. {
  219591. if (mapping->modifiermap [i << 1] == altLeftCode)
  219592. Keys::AltMask = 1 << i;
  219593. else if (mapping->modifiermap [i << 1] == numLockCode)
  219594. Keys::NumLockMask = 1 << i;
  219595. }
  219596. XFreeModifiermap (mapping);
  219597. }
  219598. }
  219599. void removeWindowDecorations (Window wndH)
  219600. {
  219601. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  219602. if (hints != None)
  219603. {
  219604. MotifWmHints motifHints;
  219605. zerostruct (motifHints);
  219606. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  219607. motifHints.decorations = 0;
  219608. ScopedXLock xlock;
  219609. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  219610. (unsigned char*) &motifHints, 4);
  219611. }
  219612. hints = XInternAtom (display, "_WIN_HINTS", True);
  219613. if (hints != None)
  219614. {
  219615. long gnomeHints = 0;
  219616. ScopedXLock xlock;
  219617. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  219618. (unsigned char*) &gnomeHints, 1);
  219619. }
  219620. hints = XInternAtom (display, "KWM_WIN_DECORATION", True);
  219621. if (hints != None)
  219622. {
  219623. long kwmHints = 2; /*KDE_tinyDecoration*/
  219624. ScopedXLock xlock;
  219625. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  219626. (unsigned char*) &kwmHints, 1);
  219627. }
  219628. }
  219629. void addWindowButtons (Window wndH)
  219630. {
  219631. ScopedXLock xlock;
  219632. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  219633. if (hints != None)
  219634. {
  219635. MotifWmHints motifHints;
  219636. zerostruct (motifHints);
  219637. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  219638. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  219639. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  219640. if ((styleFlags & windowHasCloseButton) != 0)
  219641. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  219642. if ((styleFlags & windowHasMinimiseButton) != 0)
  219643. {
  219644. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  219645. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  219646. }
  219647. if ((styleFlags & windowHasMaximiseButton) != 0)
  219648. {
  219649. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  219650. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  219651. }
  219652. if ((styleFlags & windowIsResizable) != 0)
  219653. {
  219654. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  219655. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  219656. }
  219657. XChangeProperty (display, wndH, hints, hints, 32, 0, (unsigned char*) &motifHints, 5);
  219658. }
  219659. hints = XInternAtom (display, "_NET_WM_ALLOWED_ACTIONS", True);
  219660. if (hints != None)
  219661. {
  219662. int netHints [6];
  219663. int num = 0;
  219664. if ((styleFlags & windowIsResizable) != 0)
  219665. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_RESIZE", True);
  219666. if ((styleFlags & windowHasMaximiseButton) != 0)
  219667. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_FULLSCREEN", True);
  219668. if ((styleFlags & windowHasMinimiseButton) != 0)
  219669. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_MINIMIZE", True);
  219670. if ((styleFlags & windowHasCloseButton) != 0)
  219671. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_CLOSE", True);
  219672. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace, (unsigned char*) &netHints, num);
  219673. }
  219674. }
  219675. void setWindowType()
  219676. {
  219677. int netHints [2];
  219678. int numHints = 0;
  219679. if ((styleFlags & windowIsTemporary) != 0
  219680. || ((styleFlags & windowHasDropShadow) == 0 && Desktop::canUseSemiTransparentWindows()))
  219681. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_COMBO", True);
  219682. else
  219683. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_NORMAL", True);
  219684. netHints[numHints++] = XInternAtom (display, "_KDE_NET_WM_WINDOW_TYPE_OVERRIDE", True);
  219685. XChangeProperty (display, windowH, Atoms::WindowType, XA_ATOM, 32, PropModeReplace,
  219686. (unsigned char*) &netHints, numHints);
  219687. numHints = 0;
  219688. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  219689. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_SKIP_TASKBAR", True);
  219690. if (component->isAlwaysOnTop())
  219691. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_ABOVE", True);
  219692. if (numHints > 0)
  219693. XChangeProperty (display, windowH, Atoms::WindowState, XA_ATOM, 32, PropModeReplace,
  219694. (unsigned char*) &netHints, numHints);
  219695. }
  219696. void createWindow()
  219697. {
  219698. ScopedXLock xlock;
  219699. Atoms::initialiseAtoms();
  219700. resetDragAndDrop();
  219701. // Get defaults for various properties
  219702. const int screen = DefaultScreen (display);
  219703. Window root = RootWindow (display, screen);
  219704. // Try to obtain a 32-bit visual or fallback to 24 or 16
  219705. visual = Visuals::findVisualFormat ((styleFlags & windowIsSemiTransparent) ? 32 : 24, depth);
  219706. if (visual == 0)
  219707. {
  219708. Logger::outputDebugString ("ERROR: System doesn't support 32, 24 or 16 bit RGB display.\n");
  219709. Process::terminate();
  219710. }
  219711. // Create and install a colormap suitable fr our visual
  219712. Colormap colormap = XCreateColormap (display, root, visual, AllocNone);
  219713. XInstallColormap (display, colormap);
  219714. // Set up the window attributes
  219715. XSetWindowAttributes swa;
  219716. swa.border_pixel = 0;
  219717. swa.background_pixmap = None;
  219718. swa.colormap = colormap;
  219719. swa.event_mask = getAllEventsMask();
  219720. windowH = XCreateWindow (display, root,
  219721. 0, 0, 1, 1,
  219722. 0, depth, InputOutput, visual,
  219723. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask,
  219724. &swa);
  219725. XGrabButton (display, AnyButton, AnyModifier, windowH, False,
  219726. ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask,
  219727. GrabModeAsync, GrabModeAsync, None, None);
  219728. // Set the window context to identify the window handle object
  219729. if (XSaveContext (display, (XID) windowH, windowHandleXContext, (XPointer) this))
  219730. {
  219731. // Failed
  219732. jassertfalse;
  219733. Logger::outputDebugString ("Failed to create context information for window.\n");
  219734. XDestroyWindow (display, windowH);
  219735. windowH = 0;
  219736. return;
  219737. }
  219738. // Set window manager hints
  219739. XWMHints* wmHints = XAllocWMHints();
  219740. wmHints->flags = InputHint | StateHint;
  219741. wmHints->input = True; // Locally active input model
  219742. wmHints->initial_state = NormalState;
  219743. XSetWMHints (display, windowH, wmHints);
  219744. XFree (wmHints);
  219745. // Set the window type
  219746. setWindowType();
  219747. // Define decoration
  219748. if ((styleFlags & windowHasTitleBar) == 0)
  219749. removeWindowDecorations (windowH);
  219750. else
  219751. addWindowButtons (windowH);
  219752. // Set window name
  219753. setWindowTitle (windowH, getComponent()->getName());
  219754. // Associate the PID, allowing to be shut down when something goes wrong
  219755. unsigned long pid = getpid();
  219756. XChangeProperty (display, windowH, Atoms::Pid, XA_CARDINAL, 32, PropModeReplace,
  219757. (unsigned char*) &pid, 1);
  219758. // Set window manager protocols
  219759. XChangeProperty (display, windowH, Atoms::Protocols, XA_ATOM, 32, PropModeReplace,
  219760. (unsigned char*) Atoms::ProtocolList, 2);
  219761. // Set drag and drop flags
  219762. XChangeProperty (display, windowH, Atoms::XdndTypeList, XA_ATOM, 32, PropModeReplace,
  219763. (const unsigned char*) Atoms::allowedMimeTypes, numElementsInArray (Atoms::allowedMimeTypes));
  219764. XChangeProperty (display, windowH, Atoms::XdndActionList, XA_ATOM, 32, PropModeReplace,
  219765. (const unsigned char*) Atoms::allowedActions, numElementsInArray (Atoms::allowedActions));
  219766. XChangeProperty (display, windowH, Atoms::XdndActionDescription, XA_STRING, 8, PropModeReplace,
  219767. (const unsigned char*) "", 0);
  219768. unsigned long dndVersion = Atoms::DndVersion;
  219769. XChangeProperty (display, windowH, Atoms::XdndAware, XA_ATOM, 32, PropModeReplace,
  219770. (const unsigned char*) &dndVersion, 1);
  219771. // Initialise the pointer and keyboard mapping
  219772. // This is not the same as the logical pointer mapping the X server uses:
  219773. // we don't mess with this.
  219774. static bool mappingInitialised = false;
  219775. if (! mappingInitialised)
  219776. {
  219777. mappingInitialised = true;
  219778. const int numButtons = XGetPointerMapping (display, 0, 0);
  219779. if (numButtons == 2)
  219780. {
  219781. pointerMap[0] = Keys::LeftButton;
  219782. pointerMap[1] = Keys::RightButton;
  219783. pointerMap[2] = pointerMap[3] = pointerMap[4] = Keys::NoButton;
  219784. }
  219785. else if (numButtons >= 3)
  219786. {
  219787. pointerMap[0] = Keys::LeftButton;
  219788. pointerMap[1] = Keys::MiddleButton;
  219789. pointerMap[2] = Keys::RightButton;
  219790. if (numButtons >= 5)
  219791. {
  219792. pointerMap[3] = Keys::WheelUp;
  219793. pointerMap[4] = Keys::WheelDown;
  219794. }
  219795. }
  219796. updateModifierMappings();
  219797. }
  219798. }
  219799. void destroyWindow()
  219800. {
  219801. ScopedXLock xlock;
  219802. XPointer handlePointer;
  219803. if (! XFindContext (display, (XID) windowH, windowHandleXContext, &handlePointer))
  219804. XDeleteContext (display, (XID) windowH, windowHandleXContext);
  219805. XDestroyWindow (display, windowH);
  219806. // Wait for it to complete and then remove any events for this
  219807. // window from the event queue.
  219808. XSync (display, false);
  219809. XEvent event;
  219810. while (XCheckWindowEvent (display, windowH, getAllEventsMask(), &event) == True)
  219811. {}
  219812. }
  219813. static int getAllEventsMask() throw()
  219814. {
  219815. return NoEventMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask
  219816. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  219817. | ExposureMask | StructureNotifyMask | FocusChangeMask;
  219818. }
  219819. static int64 getEventTime (::Time t)
  219820. {
  219821. static int64 eventTimeOffset = 0x12345678;
  219822. const int64 thisMessageTime = t;
  219823. if (eventTimeOffset == 0x12345678)
  219824. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  219825. return eventTimeOffset + thisMessageTime;
  219826. }
  219827. static void setWindowTitle (Window xwin, const String& title)
  219828. {
  219829. XTextProperty nameProperty;
  219830. char* strings[] = { const_cast <char*> (title.toUTF8()) };
  219831. ScopedXLock xlock;
  219832. if (XStringListToTextProperty (strings, 1, &nameProperty))
  219833. {
  219834. XSetWMName (display, xwin, &nameProperty);
  219835. XSetWMIconName (display, xwin, &nameProperty);
  219836. XFree (nameProperty.value);
  219837. }
  219838. }
  219839. void updateBorderSize()
  219840. {
  219841. if ((styleFlags & windowHasTitleBar) == 0)
  219842. {
  219843. windowBorder = BorderSize (0);
  219844. }
  219845. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  219846. {
  219847. ScopedXLock xlock;
  219848. Atom hints = XInternAtom (display, "_NET_FRAME_EXTENTS", True);
  219849. if (hints != None)
  219850. {
  219851. unsigned char* data = 0;
  219852. unsigned long nitems, bytesLeft;
  219853. Atom actualType;
  219854. int actualFormat;
  219855. if (XGetWindowProperty (display, windowH, hints, 0, 4, False,
  219856. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  219857. &data) == Success)
  219858. {
  219859. const unsigned long* const sizes = (const unsigned long*) data;
  219860. if (actualFormat == 32)
  219861. windowBorder = BorderSize ((int) sizes[2], (int) sizes[0],
  219862. (int) sizes[3], (int) sizes[1]);
  219863. XFree (data);
  219864. }
  219865. }
  219866. }
  219867. }
  219868. void updateBounds()
  219869. {
  219870. jassert (windowH != 0);
  219871. if (windowH != 0)
  219872. {
  219873. Window root, child;
  219874. unsigned int bw, depth;
  219875. ScopedXLock xlock;
  219876. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  219877. &wx, &wy, (unsigned int*) &ww, (unsigned int*) &wh,
  219878. &bw, &depth))
  219879. {
  219880. wx = wy = ww = wh = 0;
  219881. }
  219882. else if (! XTranslateCoordinates (display, windowH, root, 0, 0, &wx, &wy, &child))
  219883. {
  219884. wx = wy = 0;
  219885. }
  219886. }
  219887. }
  219888. void resetDragAndDrop()
  219889. {
  219890. dragAndDropFiles.clear();
  219891. lastDropPos = Point<int> (-1, -1);
  219892. dragAndDropCurrentMimeType = 0;
  219893. dragAndDropSourceWindow = 0;
  219894. srcMimeTypeAtomList.clear();
  219895. }
  219896. void sendDragAndDropMessage (XClientMessageEvent& msg)
  219897. {
  219898. msg.type = ClientMessage;
  219899. msg.display = display;
  219900. msg.window = dragAndDropSourceWindow;
  219901. msg.format = 32;
  219902. msg.data.l[0] = windowH;
  219903. ScopedXLock xlock;
  219904. XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
  219905. }
  219906. void sendDragAndDropStatus (const bool acceptDrop, Atom dropAction)
  219907. {
  219908. XClientMessageEvent msg;
  219909. zerostruct (msg);
  219910. msg.message_type = Atoms::XdndStatus;
  219911. msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
  219912. msg.data.l[4] = dropAction;
  219913. sendDragAndDropMessage (msg);
  219914. }
  219915. void sendDragAndDropLeave()
  219916. {
  219917. XClientMessageEvent msg;
  219918. zerostruct (msg);
  219919. msg.message_type = Atoms::XdndLeave;
  219920. sendDragAndDropMessage (msg);
  219921. }
  219922. void sendDragAndDropFinish()
  219923. {
  219924. XClientMessageEvent msg;
  219925. zerostruct (msg);
  219926. msg.message_type = Atoms::XdndFinished;
  219927. sendDragAndDropMessage (msg);
  219928. }
  219929. void handleDragAndDropStatus (const XClientMessageEvent* const clientMsg)
  219930. {
  219931. if ((clientMsg->data.l[1] & 1) == 0)
  219932. {
  219933. sendDragAndDropLeave();
  219934. if (dragAndDropFiles.size() > 0)
  219935. handleFileDragExit (dragAndDropFiles);
  219936. dragAndDropFiles.clear();
  219937. }
  219938. }
  219939. void handleDragAndDropPosition (const XClientMessageEvent* const clientMsg)
  219940. {
  219941. if (dragAndDropSourceWindow == 0)
  219942. return;
  219943. dragAndDropSourceWindow = clientMsg->data.l[0];
  219944. Point<int> dropPos ((int) clientMsg->data.l[2] >> 16,
  219945. (int) clientMsg->data.l[2] & 0xffff);
  219946. dropPos -= getScreenPosition();
  219947. if (lastDropPos != dropPos)
  219948. {
  219949. lastDropPos = dropPos;
  219950. dragAndDropTimestamp = clientMsg->data.l[3];
  219951. Atom targetAction = Atoms::XdndActionCopy;
  219952. for (int i = numElementsInArray (Atoms::allowedActions); --i >= 0;)
  219953. {
  219954. if ((Atom) clientMsg->data.l[4] == Atoms::allowedActions[i])
  219955. {
  219956. targetAction = Atoms::allowedActions[i];
  219957. break;
  219958. }
  219959. }
  219960. sendDragAndDropStatus (true, targetAction);
  219961. if (dragAndDropFiles.size() == 0)
  219962. updateDraggedFileList (clientMsg);
  219963. if (dragAndDropFiles.size() > 0)
  219964. handleFileDragMove (dragAndDropFiles, dropPos);
  219965. }
  219966. }
  219967. void handleDragAndDropDrop (const XClientMessageEvent* const clientMsg)
  219968. {
  219969. if (dragAndDropFiles.size() == 0)
  219970. updateDraggedFileList (clientMsg);
  219971. const StringArray files (dragAndDropFiles);
  219972. const Point<int> lastPos (lastDropPos);
  219973. sendDragAndDropFinish();
  219974. resetDragAndDrop();
  219975. if (files.size() > 0)
  219976. handleFileDragDrop (files, lastPos);
  219977. }
  219978. void handleDragAndDropEnter (const XClientMessageEvent* const clientMsg)
  219979. {
  219980. dragAndDropFiles.clear();
  219981. srcMimeTypeAtomList.clear();
  219982. dragAndDropCurrentMimeType = 0;
  219983. const unsigned long dndCurrentVersion = static_cast <unsigned long> (clientMsg->data.l[1] & 0xff000000) >> 24;
  219984. if (dndCurrentVersion < 3 || dndCurrentVersion > Atoms::DndVersion)
  219985. {
  219986. dragAndDropSourceWindow = 0;
  219987. return;
  219988. }
  219989. dragAndDropSourceWindow = clientMsg->data.l[0];
  219990. if ((clientMsg->data.l[1] & 1) != 0)
  219991. {
  219992. Atom actual;
  219993. int format;
  219994. unsigned long count = 0, remaining = 0;
  219995. unsigned char* data = 0;
  219996. ScopedXLock xlock;
  219997. XGetWindowProperty (display, dragAndDropSourceWindow, Atoms::XdndTypeList,
  219998. 0, 0x8000000L, False, XA_ATOM, &actual, &format,
  219999. &count, &remaining, &data);
  220000. if (data != 0)
  220001. {
  220002. if (actual == XA_ATOM && format == 32 && count != 0)
  220003. {
  220004. const unsigned long* const types = (const unsigned long*) data;
  220005. for (unsigned int i = 0; i < count; ++i)
  220006. if (types[i] != None)
  220007. srcMimeTypeAtomList.add (types[i]);
  220008. }
  220009. XFree (data);
  220010. }
  220011. }
  220012. if (srcMimeTypeAtomList.size() == 0)
  220013. {
  220014. for (int i = 2; i < 5; ++i)
  220015. if (clientMsg->data.l[i] != None)
  220016. srcMimeTypeAtomList.add (clientMsg->data.l[i]);
  220017. if (srcMimeTypeAtomList.size() == 0)
  220018. {
  220019. dragAndDropSourceWindow = 0;
  220020. return;
  220021. }
  220022. }
  220023. for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
  220024. for (int j = 0; j < numElementsInArray (Atoms::allowedMimeTypes); ++j)
  220025. if (srcMimeTypeAtomList[i] == Atoms::allowedMimeTypes[j])
  220026. dragAndDropCurrentMimeType = Atoms::allowedMimeTypes[j];
  220027. handleDragAndDropPosition (clientMsg);
  220028. }
  220029. void handleDragAndDropSelection (const XEvent* const evt)
  220030. {
  220031. dragAndDropFiles.clear();
  220032. if (evt->xselection.property != 0)
  220033. {
  220034. StringArray lines;
  220035. {
  220036. MemoryBlock dropData;
  220037. for (;;)
  220038. {
  220039. Atom actual;
  220040. uint8* data = 0;
  220041. unsigned long count = 0, remaining = 0;
  220042. int format = 0;
  220043. ScopedXLock xlock;
  220044. if (XGetWindowProperty (display, evt->xany.window, evt->xselection.property,
  220045. dropData.getSize() / 4, 65536, 1, AnyPropertyType, &actual,
  220046. &format, &count, &remaining, &data) == Success)
  220047. {
  220048. dropData.append (data, count * format / 8);
  220049. XFree (data);
  220050. if (remaining == 0)
  220051. break;
  220052. }
  220053. else
  220054. {
  220055. XFree (data);
  220056. break;
  220057. }
  220058. }
  220059. lines.addLines (dropData.toString());
  220060. }
  220061. for (int i = 0; i < lines.size(); ++i)
  220062. dragAndDropFiles.add (URL::removeEscapeChars (lines[i].fromFirstOccurrenceOf ("file://", false, true)));
  220063. dragAndDropFiles.trim();
  220064. dragAndDropFiles.removeEmptyStrings();
  220065. }
  220066. }
  220067. void updateDraggedFileList (const XClientMessageEvent* const clientMsg)
  220068. {
  220069. dragAndDropFiles.clear();
  220070. if (dragAndDropSourceWindow != None
  220071. && dragAndDropCurrentMimeType != 0)
  220072. {
  220073. dragAndDropTimestamp = clientMsg->data.l[2];
  220074. ScopedXLock xlock;
  220075. XConvertSelection (display,
  220076. Atoms::XdndSelection,
  220077. dragAndDropCurrentMimeType,
  220078. XInternAtom (display, "JXSelectionWindowProperty", 0),
  220079. windowH,
  220080. dragAndDropTimestamp);
  220081. }
  220082. }
  220083. StringArray dragAndDropFiles;
  220084. int dragAndDropTimestamp;
  220085. Point<int> lastDropPos;
  220086. Atom dragAndDropCurrentMimeType;
  220087. Window dragAndDropSourceWindow;
  220088. Array <Atom> srcMimeTypeAtomList;
  220089. static int pointerMap[5];
  220090. static Point<int> lastMousePos;
  220091. static void clearLastMousePos() throw()
  220092. {
  220093. lastMousePos = Point<int> (0x100000, 0x100000);
  220094. }
  220095. };
  220096. ModifierKeys LinuxComponentPeer::currentModifiers;
  220097. bool LinuxComponentPeer::isActiveApplication = false;
  220098. int LinuxComponentPeer::pointerMap[5];
  220099. Point<int> LinuxComponentPeer::lastMousePos;
  220100. bool Process::isForegroundProcess()
  220101. {
  220102. return LinuxComponentPeer::isActiveApplication;
  220103. }
  220104. void ModifierKeys::updateCurrentModifiers() throw()
  220105. {
  220106. currentModifiers = LinuxComponentPeer::currentModifiers;
  220107. }
  220108. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  220109. {
  220110. Window root, child;
  220111. int x, y, winx, winy;
  220112. unsigned int mask;
  220113. int mouseMods = 0;
  220114. ScopedXLock xlock;
  220115. if (XQueryPointer (display, RootWindow (display, DefaultScreen (display)),
  220116. &root, &child, &x, &y, &winx, &winy, &mask) != False)
  220117. {
  220118. if ((mask & Button1Mask) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  220119. if ((mask & Button2Mask) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  220120. if ((mask & Button3Mask) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  220121. }
  220122. LinuxComponentPeer::currentModifiers = LinuxComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  220123. return LinuxComponentPeer::currentModifiers;
  220124. }
  220125. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  220126. {
  220127. if (enableOrDisable)
  220128. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  220129. }
  220130. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  220131. {
  220132. return new LinuxComponentPeer (this, styleFlags);
  220133. }
  220134. // (this callback is hooked up in the messaging code)
  220135. void juce_windowMessageReceive (XEvent* event)
  220136. {
  220137. if (event->xany.window != None)
  220138. {
  220139. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (event->xany.window);
  220140. if (ComponentPeer::isValidPeer (peer))
  220141. peer->handleWindowMessage (event);
  220142. }
  220143. else
  220144. {
  220145. switch (event->xany.type)
  220146. {
  220147. case KeymapNotify:
  220148. {
  220149. const XKeymapEvent* const keymapEvent = (const XKeymapEvent*) &event->xkeymap;
  220150. memcpy (Keys::keyStates, keymapEvent->key_vector, 32);
  220151. break;
  220152. }
  220153. default:
  220154. break;
  220155. }
  220156. }
  220157. }
  220158. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool /*clipToWorkArea*/)
  220159. {
  220160. if (display == 0)
  220161. return;
  220162. #if JUCE_USE_XINERAMA
  220163. int major_opcode, first_event, first_error;
  220164. ScopedXLock xlock;
  220165. if (XQueryExtension (display, "XINERAMA", &major_opcode, &first_event, &first_error))
  220166. {
  220167. typedef Bool (*tXineramaIsActive) (Display*);
  220168. typedef XineramaScreenInfo* (*tXineramaQueryScreens) (Display*, int*);
  220169. static tXineramaIsActive xXineramaIsActive = 0;
  220170. static tXineramaQueryScreens xXineramaQueryScreens = 0;
  220171. if (xXineramaIsActive == 0 || xXineramaQueryScreens == 0)
  220172. {
  220173. void* h = dlopen ("libXinerama.so", RTLD_GLOBAL | RTLD_NOW);
  220174. if (h == 0)
  220175. h = dlopen ("libXinerama.so.1", RTLD_GLOBAL | RTLD_NOW);
  220176. if (h != 0)
  220177. {
  220178. xXineramaIsActive = (tXineramaIsActive) dlsym (h, "XineramaIsActive");
  220179. xXineramaQueryScreens = (tXineramaQueryScreens) dlsym (h, "XineramaQueryScreens");
  220180. }
  220181. }
  220182. if (xXineramaIsActive != 0
  220183. && xXineramaQueryScreens != 0
  220184. && xXineramaIsActive (display))
  220185. {
  220186. int numMonitors = 0;
  220187. XineramaScreenInfo* const screens = xXineramaQueryScreens (display, &numMonitors);
  220188. if (screens != 0)
  220189. {
  220190. for (int i = numMonitors; --i >= 0;)
  220191. {
  220192. int index = screens[i].screen_number;
  220193. if (index >= 0)
  220194. {
  220195. while (monitorCoords.size() < index)
  220196. monitorCoords.add (Rectangle<int>());
  220197. monitorCoords.set (index, Rectangle<int> (screens[i].x_org,
  220198. screens[i].y_org,
  220199. screens[i].width,
  220200. screens[i].height));
  220201. }
  220202. }
  220203. XFree (screens);
  220204. }
  220205. }
  220206. }
  220207. if (monitorCoords.size() == 0)
  220208. #endif
  220209. {
  220210. Atom hints = XInternAtom (display, "_NET_WORKAREA", True);
  220211. if (hints != None)
  220212. {
  220213. const int numMonitors = ScreenCount (display);
  220214. for (int i = 0; i < numMonitors; ++i)
  220215. {
  220216. Window root = RootWindow (display, i);
  220217. unsigned long nitems, bytesLeft;
  220218. Atom actualType;
  220219. int actualFormat;
  220220. unsigned char* data = 0;
  220221. if (XGetWindowProperty (display, root, hints, 0, 4, False,
  220222. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  220223. &data) == Success)
  220224. {
  220225. const long* const position = (const long*) data;
  220226. if (actualType == XA_CARDINAL && actualFormat == 32 && nitems == 4)
  220227. monitorCoords.add (Rectangle<int> (position[0], position[1],
  220228. position[2], position[3]));
  220229. XFree (data);
  220230. }
  220231. }
  220232. }
  220233. if (monitorCoords.size() == 0)
  220234. {
  220235. monitorCoords.add (Rectangle<int> (0, 0,
  220236. DisplayWidth (display, DefaultScreen (display)),
  220237. DisplayHeight (display, DefaultScreen (display))));
  220238. }
  220239. }
  220240. }
  220241. void Desktop::createMouseInputSources()
  220242. {
  220243. mouseSources.add (new MouseInputSource (0, true));
  220244. }
  220245. bool Desktop::canUseSemiTransparentWindows() throw()
  220246. {
  220247. int matchedDepth = 0;
  220248. const int desiredDepth = 32;
  220249. return Visuals::findVisualFormat (desiredDepth, matchedDepth) != 0
  220250. && (matchedDepth == desiredDepth);
  220251. }
  220252. const Point<int> Desktop::getMousePosition()
  220253. {
  220254. Window root, child;
  220255. int x, y, winx, winy;
  220256. unsigned int mask;
  220257. ScopedXLock xlock;
  220258. if (XQueryPointer (display,
  220259. RootWindow (display, DefaultScreen (display)),
  220260. &root, &child,
  220261. &x, &y, &winx, &winy, &mask) == False)
  220262. {
  220263. // Pointer not on the default screen
  220264. x = y = -1;
  220265. }
  220266. return Point<int> (x, y);
  220267. }
  220268. void Desktop::setMousePosition (const Point<int>& newPosition)
  220269. {
  220270. ScopedXLock xlock;
  220271. Window root = RootWindow (display, DefaultScreen (display));
  220272. XWarpPointer (display, None, root, 0, 0, 0, 0, newPosition.getX(), newPosition.getY());
  220273. }
  220274. static bool screenSaverAllowed = true;
  220275. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  220276. {
  220277. if (screenSaverAllowed != isEnabled)
  220278. {
  220279. screenSaverAllowed = isEnabled;
  220280. typedef void (*tXScreenSaverSuspend) (Display*, Bool);
  220281. static tXScreenSaverSuspend xScreenSaverSuspend = 0;
  220282. if (xScreenSaverSuspend == 0)
  220283. {
  220284. void* h = dlopen ("libXss.so", RTLD_GLOBAL | RTLD_NOW);
  220285. if (h != 0)
  220286. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  220287. }
  220288. ScopedXLock xlock;
  220289. if (xScreenSaverSuspend != 0)
  220290. xScreenSaverSuspend (display, ! isEnabled);
  220291. }
  220292. }
  220293. bool Desktop::isScreenSaverEnabled()
  220294. {
  220295. return screenSaverAllowed;
  220296. }
  220297. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  220298. {
  220299. ScopedXLock xlock;
  220300. const unsigned int imageW = image.getWidth();
  220301. const unsigned int imageH = image.getHeight();
  220302. #if JUCE_USE_XCURSOR
  220303. {
  220304. typedef XcursorBool (*tXcursorSupportsARGB) (Display*);
  220305. typedef XcursorImage* (*tXcursorImageCreate) (int, int);
  220306. typedef void (*tXcursorImageDestroy) (XcursorImage*);
  220307. typedef Cursor (*tXcursorImageLoadCursor) (Display*, const XcursorImage*);
  220308. static tXcursorSupportsARGB xXcursorSupportsARGB = 0;
  220309. static tXcursorImageCreate xXcursorImageCreate = 0;
  220310. static tXcursorImageDestroy xXcursorImageDestroy = 0;
  220311. static tXcursorImageLoadCursor xXcursorImageLoadCursor = 0;
  220312. static bool hasBeenLoaded = false;
  220313. if (! hasBeenLoaded)
  220314. {
  220315. hasBeenLoaded = true;
  220316. void* h = dlopen ("libXcursor.so", RTLD_GLOBAL | RTLD_NOW);
  220317. if (h != 0)
  220318. {
  220319. xXcursorSupportsARGB = (tXcursorSupportsARGB) dlsym (h, "XcursorSupportsARGB");
  220320. xXcursorImageCreate = (tXcursorImageCreate) dlsym (h, "XcursorImageCreate");
  220321. xXcursorImageLoadCursor = (tXcursorImageLoadCursor) dlsym (h, "XcursorImageLoadCursor");
  220322. xXcursorImageDestroy = (tXcursorImageDestroy) dlsym (h, "XcursorImageDestroy");
  220323. if (xXcursorSupportsARGB == 0 || xXcursorImageCreate == 0
  220324. || xXcursorImageLoadCursor == 0 || xXcursorImageDestroy == 0
  220325. || ! xXcursorSupportsARGB (display))
  220326. xXcursorSupportsARGB = 0;
  220327. }
  220328. }
  220329. if (xXcursorSupportsARGB != 0)
  220330. {
  220331. XcursorImage* xcImage = xXcursorImageCreate (imageW, imageH);
  220332. if (xcImage != 0)
  220333. {
  220334. xcImage->xhot = hotspotX;
  220335. xcImage->yhot = hotspotY;
  220336. XcursorPixel* dest = xcImage->pixels;
  220337. for (int y = 0; y < (int) imageH; ++y)
  220338. for (int x = 0; x < (int) imageW; ++x)
  220339. *dest++ = image.getPixelAt (x, y).getARGB();
  220340. void* result = (void*) xXcursorImageLoadCursor (display, xcImage);
  220341. xXcursorImageDestroy (xcImage);
  220342. if (result != 0)
  220343. return result;
  220344. }
  220345. }
  220346. }
  220347. #endif
  220348. Window root = RootWindow (display, DefaultScreen (display));
  220349. unsigned int cursorW, cursorH;
  220350. if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  220351. return 0;
  220352. Image im (Image::ARGB, cursorW, cursorH, true);
  220353. {
  220354. Graphics g (im);
  220355. if (imageW > cursorW || imageH > cursorH)
  220356. {
  220357. hotspotX = (hotspotX * cursorW) / imageW;
  220358. hotspotY = (hotspotY * cursorH) / imageH;
  220359. g.drawImageWithin (image, 0, 0, imageW, imageH,
  220360. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  220361. false);
  220362. }
  220363. else
  220364. {
  220365. g.drawImageAt (image, 0, 0);
  220366. }
  220367. }
  220368. const int stride = (cursorW + 7) >> 3;
  220369. HeapBlock <char> maskPlane, sourcePlane;
  220370. maskPlane.calloc (stride * cursorH);
  220371. sourcePlane.calloc (stride * cursorH);
  220372. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  220373. for (int y = cursorH; --y >= 0;)
  220374. {
  220375. for (int x = cursorW; --x >= 0;)
  220376. {
  220377. const char mask = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  220378. const int offset = y * stride + (x >> 3);
  220379. const Colour c (im.getPixelAt (x, y));
  220380. if (c.getAlpha() >= 128)
  220381. maskPlane[offset] |= mask;
  220382. if (c.getBrightness() >= 0.5f)
  220383. sourcePlane[offset] |= mask;
  220384. }
  220385. }
  220386. Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, sourcePlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  220387. Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, maskPlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  220388. XColor white, black;
  220389. black.red = black.green = black.blue = 0;
  220390. white.red = white.green = white.blue = 0xffff;
  220391. void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black, hotspotX, hotspotY);
  220392. XFreePixmap (display, sourcePixmap);
  220393. XFreePixmap (display, maskPixmap);
  220394. return result;
  220395. }
  220396. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool)
  220397. {
  220398. ScopedXLock xlock;
  220399. if (cursorHandle != 0)
  220400. XFreeCursor (display, (Cursor) cursorHandle);
  220401. }
  220402. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  220403. {
  220404. unsigned int shape;
  220405. switch (type)
  220406. {
  220407. case NormalCursor: return None; // Use parent cursor
  220408. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 16, 16, true), 0, 0);
  220409. case WaitCursor: shape = XC_watch; break;
  220410. case IBeamCursor: shape = XC_xterm; break;
  220411. case PointingHandCursor: shape = XC_hand2; break;
  220412. case LeftRightResizeCursor: shape = XC_sb_h_double_arrow; break;
  220413. case UpDownResizeCursor: shape = XC_sb_v_double_arrow; break;
  220414. case UpDownLeftRightResizeCursor: shape = XC_fleur; break;
  220415. case TopEdgeResizeCursor: shape = XC_top_side; break;
  220416. case BottomEdgeResizeCursor: shape = XC_bottom_side; break;
  220417. case LeftEdgeResizeCursor: shape = XC_left_side; break;
  220418. case RightEdgeResizeCursor: shape = XC_right_side; break;
  220419. case TopLeftCornerResizeCursor: shape = XC_top_left_corner; break;
  220420. case TopRightCornerResizeCursor: shape = XC_top_right_corner; break;
  220421. case BottomLeftCornerResizeCursor: shape = XC_bottom_left_corner; break;
  220422. case BottomRightCornerResizeCursor: shape = XC_bottom_right_corner; break;
  220423. case CrosshairCursor: shape = XC_crosshair; break;
  220424. case DraggingHandCursor:
  220425. {
  220426. static unsigned char dragHandData[] = { 71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,
  220427. 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,
  220428. 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 };
  220429. const int dragHandDataSize = 99;
  220430. return createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, dragHandDataSize), 8, 7);
  220431. }
  220432. case CopyingCursor:
  220433. {
  220434. static unsigned char copyCursorData[] = { 71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  220435. 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,
  220436. 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,
  220437. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  220438. const int copyCursorSize = 119;
  220439. return createMouseCursorFromImage (ImageFileFormat::loadFrom (copyCursorData, copyCursorSize), 1, 3);
  220440. }
  220441. default:
  220442. jassertfalse;
  220443. return None;
  220444. }
  220445. ScopedXLock xlock;
  220446. return (void*) XCreateFontCursor (display, shape);
  220447. }
  220448. void MouseCursor::showInWindow (ComponentPeer* peer) const
  220449. {
  220450. LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (peer);
  220451. if (lp != 0)
  220452. lp->showMouseCursor ((Cursor) getHandle());
  220453. }
  220454. void MouseCursor::showInAllWindows() const
  220455. {
  220456. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  220457. showInWindow (ComponentPeer::getPeer (i));
  220458. }
  220459. const Image juce_createIconForFile (const File& file)
  220460. {
  220461. return Image();
  220462. }
  220463. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  220464. {
  220465. return createSoftwareImage (format, width, height, clearImage);
  220466. }
  220467. #if JUCE_OPENGL
  220468. class WindowedGLContext : public OpenGLContext
  220469. {
  220470. public:
  220471. WindowedGLContext (Component* const component,
  220472. const OpenGLPixelFormat& pixelFormat_,
  220473. GLXContext sharedContext)
  220474. : renderContext (0),
  220475. embeddedWindow (0),
  220476. pixelFormat (pixelFormat_),
  220477. swapInterval (0)
  220478. {
  220479. jassert (component != 0);
  220480. LinuxComponentPeer* const peer = dynamic_cast <LinuxComponentPeer*> (component->getTopLevelComponent()->getPeer());
  220481. if (peer == 0)
  220482. return;
  220483. ScopedXLock xlock;
  220484. XSync (display, False);
  220485. GLint attribs [64];
  220486. int n = 0;
  220487. attribs[n++] = GLX_RGBA;
  220488. attribs[n++] = GLX_DOUBLEBUFFER;
  220489. attribs[n++] = GLX_RED_SIZE;
  220490. attribs[n++] = pixelFormat.redBits;
  220491. attribs[n++] = GLX_GREEN_SIZE;
  220492. attribs[n++] = pixelFormat.greenBits;
  220493. attribs[n++] = GLX_BLUE_SIZE;
  220494. attribs[n++] = pixelFormat.blueBits;
  220495. attribs[n++] = GLX_ALPHA_SIZE;
  220496. attribs[n++] = pixelFormat.alphaBits;
  220497. attribs[n++] = GLX_DEPTH_SIZE;
  220498. attribs[n++] = pixelFormat.depthBufferBits;
  220499. attribs[n++] = GLX_STENCIL_SIZE;
  220500. attribs[n++] = pixelFormat.stencilBufferBits;
  220501. attribs[n++] = GLX_ACCUM_RED_SIZE;
  220502. attribs[n++] = pixelFormat.accumulationBufferRedBits;
  220503. attribs[n++] = GLX_ACCUM_GREEN_SIZE;
  220504. attribs[n++] = pixelFormat.accumulationBufferGreenBits;
  220505. attribs[n++] = GLX_ACCUM_BLUE_SIZE;
  220506. attribs[n++] = pixelFormat.accumulationBufferBlueBits;
  220507. attribs[n++] = GLX_ACCUM_ALPHA_SIZE;
  220508. attribs[n++] = pixelFormat.accumulationBufferAlphaBits;
  220509. // xxx not sure how to do fullSceneAntiAliasingNumSamples on linux..
  220510. attribs[n++] = None;
  220511. XVisualInfo* const bestVisual = glXChooseVisual (display, DefaultScreen (display), attribs);
  220512. if (bestVisual == 0)
  220513. return;
  220514. renderContext = glXCreateContext (display, bestVisual, sharedContext, GL_TRUE);
  220515. Window windowH = (Window) peer->getNativeHandle();
  220516. Colormap colourMap = XCreateColormap (display, windowH, bestVisual->visual, AllocNone);
  220517. XSetWindowAttributes swa;
  220518. swa.colormap = colourMap;
  220519. swa.border_pixel = 0;
  220520. swa.event_mask = ExposureMask | StructureNotifyMask;
  220521. embeddedWindow = XCreateWindow (display, windowH,
  220522. 0, 0, 1, 1, 0,
  220523. bestVisual->depth,
  220524. InputOutput,
  220525. bestVisual->visual,
  220526. CWBorderPixel | CWColormap | CWEventMask,
  220527. &swa);
  220528. XSaveContext (display, (XID) embeddedWindow, windowHandleXContext, (XPointer) peer);
  220529. XMapWindow (display, embeddedWindow);
  220530. XFreeColormap (display, colourMap);
  220531. XFree (bestVisual);
  220532. XSync (display, False);
  220533. }
  220534. ~WindowedGLContext()
  220535. {
  220536. makeInactive();
  220537. ScopedXLock xlock;
  220538. glXDestroyContext (display, renderContext);
  220539. XUnmapWindow (display, embeddedWindow);
  220540. XDestroyWindow (display, embeddedWindow);
  220541. }
  220542. bool makeActive() const throw()
  220543. {
  220544. jassert (renderContext != 0);
  220545. ScopedXLock xlock;
  220546. return glXMakeCurrent (display, embeddedWindow, renderContext)
  220547. && XSync (display, False);
  220548. }
  220549. bool makeInactive() const throw()
  220550. {
  220551. ScopedXLock xlock;
  220552. return (! isActive()) || glXMakeCurrent (display, None, 0);
  220553. }
  220554. bool isActive() const throw()
  220555. {
  220556. ScopedXLock xlock;
  220557. return glXGetCurrentContext() == renderContext;
  220558. }
  220559. const OpenGLPixelFormat getPixelFormat() const
  220560. {
  220561. return pixelFormat;
  220562. }
  220563. void* getRawContext() const throw()
  220564. {
  220565. return renderContext;
  220566. }
  220567. void updateWindowPosition (int x, int y, int w, int h, int)
  220568. {
  220569. ScopedXLock xlock;
  220570. XMoveResizeWindow (display, embeddedWindow,
  220571. x, y, jmax (1, w), jmax (1, h));
  220572. }
  220573. void swapBuffers()
  220574. {
  220575. ScopedXLock xlock;
  220576. glXSwapBuffers (display, embeddedWindow);
  220577. }
  220578. bool setSwapInterval (const int numFramesPerSwap)
  220579. {
  220580. static PFNGLXSWAPINTERVALSGIPROC GLXSwapIntervalSGI = (PFNGLXSWAPINTERVALSGIPROC) glXGetProcAddress ((const GLubyte*) "glXSwapIntervalSGI");
  220581. if (GLXSwapIntervalSGI != 0)
  220582. {
  220583. swapInterval = numFramesPerSwap;
  220584. GLXSwapIntervalSGI (numFramesPerSwap);
  220585. return true;
  220586. }
  220587. return false;
  220588. }
  220589. int getSwapInterval() const
  220590. {
  220591. return swapInterval;
  220592. }
  220593. void repaint()
  220594. {
  220595. }
  220596. juce_UseDebuggingNewOperator
  220597. GLXContext renderContext;
  220598. private:
  220599. Window embeddedWindow;
  220600. OpenGLPixelFormat pixelFormat;
  220601. int swapInterval;
  220602. WindowedGLContext (const WindowedGLContext&);
  220603. WindowedGLContext& operator= (const WindowedGLContext&);
  220604. };
  220605. OpenGLContext* OpenGLComponent::createContext()
  220606. {
  220607. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  220608. contextToShareListsWith != 0 ? (GLXContext) contextToShareListsWith->getRawContext() : 0));
  220609. return (c->renderContext != 0) ? c.release() : 0;
  220610. }
  220611. void juce_glViewport (const int w, const int h)
  220612. {
  220613. glViewport (0, 0, w, h);
  220614. }
  220615. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  220616. OwnedArray <OpenGLPixelFormat>& results)
  220617. {
  220618. results.add (new OpenGLPixelFormat()); // xxx
  220619. }
  220620. #endif
  220621. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  220622. {
  220623. jassertfalse; // not implemented!
  220624. return false;
  220625. }
  220626. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  220627. {
  220628. jassertfalse; // not implemented!
  220629. return false;
  220630. }
  220631. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  220632. {
  220633. if (! isOnDesktop ())
  220634. addToDesktop (0);
  220635. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  220636. if (wp != 0)
  220637. {
  220638. wp->setTaskBarIcon (newImage);
  220639. setVisible (true);
  220640. toFront (false);
  220641. repaint();
  220642. }
  220643. }
  220644. void SystemTrayIconComponent::paint (Graphics& g)
  220645. {
  220646. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  220647. if (wp != 0)
  220648. {
  220649. g.drawImageWithin (wp->getTaskbarIcon(), 0, 0, getWidth(), getHeight(),
  220650. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  220651. false);
  220652. }
  220653. }
  220654. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  220655. {
  220656. // xxx not yet implemented!
  220657. }
  220658. void PlatformUtilities::beep()
  220659. {
  220660. std::cout << "\a" << std::flush;
  220661. }
  220662. bool AlertWindow::showNativeDialogBox (const String& title,
  220663. const String& bodyText,
  220664. bool isOkCancel)
  220665. {
  220666. // use a non-native one for the time being..
  220667. if (isOkCancel)
  220668. return AlertWindow::showOkCancelBox (AlertWindow::NoIcon, title, bodyText);
  220669. else
  220670. AlertWindow::showMessageBox (AlertWindow::NoIcon, title, bodyText);
  220671. return true;
  220672. }
  220673. const int KeyPress::spaceKey = XK_space & 0xff;
  220674. const int KeyPress::returnKey = XK_Return & 0xff;
  220675. const int KeyPress::escapeKey = XK_Escape & 0xff;
  220676. const int KeyPress::backspaceKey = XK_BackSpace & 0xff;
  220677. const int KeyPress::leftKey = (XK_Left & 0xff) | Keys::extendedKeyModifier;
  220678. const int KeyPress::rightKey = (XK_Right & 0xff) | Keys::extendedKeyModifier;
  220679. const int KeyPress::upKey = (XK_Up & 0xff) | Keys::extendedKeyModifier;
  220680. const int KeyPress::downKey = (XK_Down & 0xff) | Keys::extendedKeyModifier;
  220681. const int KeyPress::pageUpKey = (XK_Page_Up & 0xff) | Keys::extendedKeyModifier;
  220682. const int KeyPress::pageDownKey = (XK_Page_Down & 0xff) | Keys::extendedKeyModifier;
  220683. const int KeyPress::endKey = (XK_End & 0xff) | Keys::extendedKeyModifier;
  220684. const int KeyPress::homeKey = (XK_Home & 0xff) | Keys::extendedKeyModifier;
  220685. const int KeyPress::insertKey = (XK_Insert & 0xff) | Keys::extendedKeyModifier;
  220686. const int KeyPress::deleteKey = (XK_Delete & 0xff) | Keys::extendedKeyModifier;
  220687. const int KeyPress::tabKey = XK_Tab & 0xff;
  220688. const int KeyPress::F1Key = (XK_F1 & 0xff) | Keys::extendedKeyModifier;
  220689. const int KeyPress::F2Key = (XK_F2 & 0xff) | Keys::extendedKeyModifier;
  220690. const int KeyPress::F3Key = (XK_F3 & 0xff) | Keys::extendedKeyModifier;
  220691. const int KeyPress::F4Key = (XK_F4 & 0xff) | Keys::extendedKeyModifier;
  220692. const int KeyPress::F5Key = (XK_F5 & 0xff) | Keys::extendedKeyModifier;
  220693. const int KeyPress::F6Key = (XK_F6 & 0xff) | Keys::extendedKeyModifier;
  220694. const int KeyPress::F7Key = (XK_F7 & 0xff) | Keys::extendedKeyModifier;
  220695. const int KeyPress::F8Key = (XK_F8 & 0xff) | Keys::extendedKeyModifier;
  220696. const int KeyPress::F9Key = (XK_F9 & 0xff) | Keys::extendedKeyModifier;
  220697. const int KeyPress::F10Key = (XK_F10 & 0xff) | Keys::extendedKeyModifier;
  220698. const int KeyPress::F11Key = (XK_F11 & 0xff) | Keys::extendedKeyModifier;
  220699. const int KeyPress::F12Key = (XK_F12 & 0xff) | Keys::extendedKeyModifier;
  220700. const int KeyPress::F13Key = (XK_F13 & 0xff) | Keys::extendedKeyModifier;
  220701. const int KeyPress::F14Key = (XK_F14 & 0xff) | Keys::extendedKeyModifier;
  220702. const int KeyPress::F15Key = (XK_F15 & 0xff) | Keys::extendedKeyModifier;
  220703. const int KeyPress::F16Key = (XK_F16 & 0xff) | Keys::extendedKeyModifier;
  220704. const int KeyPress::numberPad0 = (XK_KP_0 & 0xff) | Keys::extendedKeyModifier;
  220705. const int KeyPress::numberPad1 = (XK_KP_1 & 0xff) | Keys::extendedKeyModifier;
  220706. const int KeyPress::numberPad2 = (XK_KP_2 & 0xff) | Keys::extendedKeyModifier;
  220707. const int KeyPress::numberPad3 = (XK_KP_3 & 0xff) | Keys::extendedKeyModifier;
  220708. const int KeyPress::numberPad4 = (XK_KP_4 & 0xff) | Keys::extendedKeyModifier;
  220709. const int KeyPress::numberPad5 = (XK_KP_5 & 0xff) | Keys::extendedKeyModifier;
  220710. const int KeyPress::numberPad6 = (XK_KP_6 & 0xff) | Keys::extendedKeyModifier;
  220711. const int KeyPress::numberPad7 = (XK_KP_7 & 0xff)| Keys::extendedKeyModifier;
  220712. const int KeyPress::numberPad8 = (XK_KP_8 & 0xff)| Keys::extendedKeyModifier;
  220713. const int KeyPress::numberPad9 = (XK_KP_9 & 0xff)| Keys::extendedKeyModifier;
  220714. const int KeyPress::numberPadAdd = (XK_KP_Add & 0xff)| Keys::extendedKeyModifier;
  220715. const int KeyPress::numberPadSubtract = (XK_KP_Subtract & 0xff)| Keys::extendedKeyModifier;
  220716. const int KeyPress::numberPadMultiply = (XK_KP_Multiply & 0xff)| Keys::extendedKeyModifier;
  220717. const int KeyPress::numberPadDivide = (XK_KP_Divide & 0xff)| Keys::extendedKeyModifier;
  220718. const int KeyPress::numberPadSeparator = (XK_KP_Separator & 0xff)| Keys::extendedKeyModifier;
  220719. const int KeyPress::numberPadDecimalPoint = (XK_KP_Decimal & 0xff)| Keys::extendedKeyModifier;
  220720. const int KeyPress::numberPadEquals = (XK_KP_Equal & 0xff)| Keys::extendedKeyModifier;
  220721. const int KeyPress::numberPadDelete = (XK_KP_Delete & 0xff)| Keys::extendedKeyModifier;
  220722. const int KeyPress::playKey = (0xffeeff00) | Keys::extendedKeyModifier;
  220723. const int KeyPress::stopKey = (0xffeeff01) | Keys::extendedKeyModifier;
  220724. const int KeyPress::fastForwardKey = (0xffeeff02) | Keys::extendedKeyModifier;
  220725. const int KeyPress::rewindKey = (0xffeeff03) | Keys::extendedKeyModifier;
  220726. #endif
  220727. /*** End of inlined file: juce_linux_Windowing.cpp ***/
  220728. /*** Start of inlined file: juce_linux_Audio.cpp ***/
  220729. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  220730. // compiled on its own).
  220731. #if JUCE_INCLUDED_FILE && JUCE_ALSA
  220732. static const int maxNumChans = 64;
  220733. static void getDeviceSampleRates (snd_pcm_t* handle, Array <int>& rates)
  220734. {
  220735. const int ratesToTry[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  220736. snd_pcm_hw_params_t* hwParams;
  220737. snd_pcm_hw_params_alloca (&hwParams);
  220738. for (int i = 0; ratesToTry[i] != 0; ++i)
  220739. {
  220740. if (snd_pcm_hw_params_any (handle, hwParams) >= 0
  220741. && snd_pcm_hw_params_test_rate (handle, hwParams, ratesToTry[i], 0) == 0)
  220742. {
  220743. rates.addIfNotAlreadyThere (ratesToTry[i]);
  220744. }
  220745. }
  220746. }
  220747. static void getDeviceNumChannels (snd_pcm_t* handle, unsigned int* minChans, unsigned int* maxChans)
  220748. {
  220749. snd_pcm_hw_params_t *params;
  220750. snd_pcm_hw_params_alloca (&params);
  220751. if (snd_pcm_hw_params_any (handle, params) >= 0)
  220752. {
  220753. snd_pcm_hw_params_get_channels_min (params, minChans);
  220754. snd_pcm_hw_params_get_channels_max (params, maxChans);
  220755. }
  220756. }
  220757. static void getDeviceProperties (const String& deviceID,
  220758. unsigned int& minChansOut,
  220759. unsigned int& maxChansOut,
  220760. unsigned int& minChansIn,
  220761. unsigned int& maxChansIn,
  220762. Array <int>& rates)
  220763. {
  220764. if (deviceID.isEmpty())
  220765. return;
  220766. snd_ctl_t* handle;
  220767. if (snd_ctl_open (&handle, deviceID.upToLastOccurrenceOf (",", false, false).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  220768. {
  220769. snd_pcm_info_t* info;
  220770. snd_pcm_info_alloca (&info);
  220771. snd_pcm_info_set_stream (info, SND_PCM_STREAM_PLAYBACK);
  220772. snd_pcm_info_set_device (info, deviceID.fromLastOccurrenceOf (",", false, false).getIntValue());
  220773. snd_pcm_info_set_subdevice (info, 0);
  220774. if (snd_ctl_pcm_info (handle, info) >= 0)
  220775. {
  220776. snd_pcm_t* pcmHandle;
  220777. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_PLAYBACK, SND_PCM_ASYNC | SND_PCM_NONBLOCK ) >= 0)
  220778. {
  220779. getDeviceNumChannels (pcmHandle, &minChansOut, &maxChansOut);
  220780. getDeviceSampleRates (pcmHandle, rates);
  220781. snd_pcm_close (pcmHandle);
  220782. }
  220783. }
  220784. snd_pcm_info_set_stream (info, SND_PCM_STREAM_CAPTURE);
  220785. if (snd_ctl_pcm_info (handle, info) >= 0)
  220786. {
  220787. snd_pcm_t* pcmHandle;
  220788. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_CAPTURE, SND_PCM_ASYNC | SND_PCM_NONBLOCK ) >= 0)
  220789. {
  220790. getDeviceNumChannels (pcmHandle, &minChansIn, &maxChansIn);
  220791. if (rates.size() == 0)
  220792. getDeviceSampleRates (pcmHandle, rates);
  220793. snd_pcm_close (pcmHandle);
  220794. }
  220795. }
  220796. snd_ctl_close (handle);
  220797. }
  220798. }
  220799. class ALSADevice
  220800. {
  220801. public:
  220802. ALSADevice (const String& deviceID,
  220803. const bool forInput)
  220804. : handle (0),
  220805. bitDepth (16),
  220806. numChannelsRunning (0),
  220807. isInput (forInput),
  220808. sampleFormat (AudioDataConverters::int16LE)
  220809. {
  220810. failed (snd_pcm_open (&handle, deviceID.toUTF8(),
  220811. forInput ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
  220812. SND_PCM_ASYNC));
  220813. }
  220814. ~ALSADevice()
  220815. {
  220816. if (handle != 0)
  220817. snd_pcm_close (handle);
  220818. }
  220819. bool setParameters (unsigned int sampleRate, int numChannels, int bufferSize)
  220820. {
  220821. if (handle == 0)
  220822. return false;
  220823. snd_pcm_hw_params_t* hwParams;
  220824. snd_pcm_hw_params_alloca (&hwParams);
  220825. if (failed (snd_pcm_hw_params_any (handle, hwParams)))
  220826. return false;
  220827. if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_NONINTERLEAVED) >= 0)
  220828. isInterleaved = false;
  220829. else if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_INTERLEAVED) >= 0)
  220830. isInterleaved = true;
  220831. else
  220832. {
  220833. jassertfalse;
  220834. return false;
  220835. }
  220836. const int formatsToTry[] = { SND_PCM_FORMAT_FLOAT_LE, 32, AudioDataConverters::float32LE,
  220837. SND_PCM_FORMAT_FLOAT_BE, 32, AudioDataConverters::float32BE,
  220838. SND_PCM_FORMAT_S32_LE, 32, AudioDataConverters::int32LE,
  220839. SND_PCM_FORMAT_S32_BE, 32, AudioDataConverters::int32BE,
  220840. SND_PCM_FORMAT_S24_3LE, 24, AudioDataConverters::int24LE,
  220841. SND_PCM_FORMAT_S24_3BE, 24, AudioDataConverters::int24BE,
  220842. SND_PCM_FORMAT_S16_LE, 16, AudioDataConverters::int16LE,
  220843. SND_PCM_FORMAT_S16_BE, 16, AudioDataConverters::int16BE };
  220844. bitDepth = 0;
  220845. for (int i = 0; i < numElementsInArray (formatsToTry); i += 3)
  220846. {
  220847. if (snd_pcm_hw_params_set_format (handle, hwParams, (_snd_pcm_format) formatsToTry [i]) >= 0)
  220848. {
  220849. bitDepth = formatsToTry [i + 1];
  220850. sampleFormat = (AudioDataConverters::DataFormat) formatsToTry [i + 2];
  220851. break;
  220852. }
  220853. }
  220854. if (bitDepth == 0)
  220855. {
  220856. error = "device doesn't support a compatible PCM format";
  220857. DBG ("ALSA error: " + error + "\n");
  220858. return false;
  220859. }
  220860. int dir = 0;
  220861. unsigned int periods = 4;
  220862. snd_pcm_uframes_t samplesPerPeriod = bufferSize;
  220863. if (failed (snd_pcm_hw_params_set_rate_near (handle, hwParams, &sampleRate, 0))
  220864. || failed (snd_pcm_hw_params_set_channels (handle, hwParams, numChannels))
  220865. || failed (snd_pcm_hw_params_set_periods_near (handle, hwParams, &periods, &dir))
  220866. || failed (snd_pcm_hw_params_set_period_size_near (handle, hwParams, &samplesPerPeriod, &dir))
  220867. || failed (snd_pcm_hw_params (handle, hwParams)))
  220868. {
  220869. return false;
  220870. }
  220871. snd_pcm_sw_params_t* swParams;
  220872. snd_pcm_sw_params_alloca (&swParams);
  220873. snd_pcm_uframes_t boundary;
  220874. if (failed (snd_pcm_sw_params_current (handle, swParams))
  220875. || failed (snd_pcm_sw_params_get_boundary (swParams, &boundary))
  220876. || failed (snd_pcm_sw_params_set_silence_threshold (handle, swParams, 0))
  220877. || failed (snd_pcm_sw_params_set_silence_size (handle, swParams, boundary))
  220878. || failed (snd_pcm_sw_params_set_start_threshold (handle, swParams, samplesPerPeriod))
  220879. || failed (snd_pcm_sw_params_set_stop_threshold (handle, swParams, boundary))
  220880. || failed (snd_pcm_sw_params (handle, swParams)))
  220881. {
  220882. return false;
  220883. }
  220884. /*
  220885. #if JUCE_DEBUG
  220886. // enable this to dump the config of the devices that get opened
  220887. snd_output_t* out;
  220888. snd_output_stdio_attach (&out, stderr, 0);
  220889. snd_pcm_hw_params_dump (hwParams, out);
  220890. snd_pcm_sw_params_dump (swParams, out);
  220891. #endif
  220892. */
  220893. numChannelsRunning = numChannels;
  220894. return true;
  220895. }
  220896. bool write (AudioSampleBuffer& outputChannelBuffer, const int numSamples)
  220897. {
  220898. jassert (numChannelsRunning <= outputChannelBuffer.getNumChannels());
  220899. float** const data = outputChannelBuffer.getArrayOfChannels();
  220900. if (isInterleaved)
  220901. {
  220902. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  220903. float* interleaved = static_cast <float*> (scratch.getData());
  220904. AudioDataConverters::interleaveSamples ((const float**) data, interleaved, numSamples, numChannelsRunning);
  220905. AudioDataConverters::convertFloatToFormat (sampleFormat, interleaved, interleaved, numSamples * numChannelsRunning);
  220906. snd_pcm_sframes_t num = snd_pcm_writei (handle, interleaved, numSamples);
  220907. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  220908. return false;
  220909. }
  220910. else
  220911. {
  220912. for (int i = 0; i < numChannelsRunning; ++i)
  220913. if (data[i] != 0)
  220914. AudioDataConverters::convertFloatToFormat (sampleFormat, data[i], data[i], numSamples);
  220915. snd_pcm_sframes_t num = snd_pcm_writen (handle, (void**) data, numSamples);
  220916. if (failed (num))
  220917. {
  220918. if (num == -EPIPE)
  220919. {
  220920. if (failed (snd_pcm_prepare (handle)))
  220921. return false;
  220922. }
  220923. else if (num != -ESTRPIPE)
  220924. return false;
  220925. }
  220926. }
  220927. return true;
  220928. }
  220929. bool read (AudioSampleBuffer& inputChannelBuffer, const int numSamples)
  220930. {
  220931. jassert (numChannelsRunning <= inputChannelBuffer.getNumChannels());
  220932. float** const data = inputChannelBuffer.getArrayOfChannels();
  220933. if (isInterleaved)
  220934. {
  220935. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  220936. float* interleaved = static_cast <float*> (scratch.getData());
  220937. snd_pcm_sframes_t num = snd_pcm_readi (handle, interleaved, numSamples);
  220938. if (failed (num))
  220939. {
  220940. if (num == -EPIPE)
  220941. {
  220942. if (failed (snd_pcm_prepare (handle)))
  220943. return false;
  220944. }
  220945. else if (num != -ESTRPIPE)
  220946. return false;
  220947. }
  220948. AudioDataConverters::convertFormatToFloat (sampleFormat, interleaved, interleaved, numSamples * numChannelsRunning);
  220949. AudioDataConverters::deinterleaveSamples (interleaved, data, numSamples, numChannelsRunning);
  220950. }
  220951. else
  220952. {
  220953. snd_pcm_sframes_t num = snd_pcm_readn (handle, (void**) data, numSamples);
  220954. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  220955. return false;
  220956. for (int i = 0; i < numChannelsRunning; ++i)
  220957. if (data[i] != 0)
  220958. AudioDataConverters::convertFormatToFloat (sampleFormat, data[i], data[i], numSamples);
  220959. }
  220960. return true;
  220961. }
  220962. juce_UseDebuggingNewOperator
  220963. snd_pcm_t* handle;
  220964. String error;
  220965. int bitDepth, numChannelsRunning;
  220966. private:
  220967. const bool isInput;
  220968. bool isInterleaved;
  220969. MemoryBlock scratch;
  220970. AudioDataConverters::DataFormat sampleFormat;
  220971. bool failed (const int errorNum)
  220972. {
  220973. if (errorNum >= 0)
  220974. return false;
  220975. error = snd_strerror (errorNum);
  220976. DBG ("ALSA error: " + error + "\n");
  220977. return true;
  220978. }
  220979. };
  220980. class ALSAThread : public Thread
  220981. {
  220982. public:
  220983. ALSAThread (const String& inputId_,
  220984. const String& outputId_)
  220985. : Thread ("Juce ALSA"),
  220986. sampleRate (0),
  220987. bufferSize (0),
  220988. callback (0),
  220989. inputId (inputId_),
  220990. outputId (outputId_),
  220991. outputDevice (0),
  220992. inputDevice (0),
  220993. numCallbacks (0),
  220994. inputChannelBuffer (1, 1),
  220995. outputChannelBuffer (1, 1)
  220996. {
  220997. initialiseRatesAndChannels();
  220998. }
  220999. ~ALSAThread()
  221000. {
  221001. close();
  221002. }
  221003. void open (BigInteger inputChannels,
  221004. BigInteger outputChannels,
  221005. const double sampleRate_,
  221006. const int bufferSize_)
  221007. {
  221008. close();
  221009. error = String::empty;
  221010. sampleRate = sampleRate_;
  221011. bufferSize = bufferSize_;
  221012. inputChannelBuffer.setSize (jmax ((int) minChansIn, inputChannels.getHighestBit()) + 1, bufferSize);
  221013. inputChannelBuffer.clear();
  221014. inputChannelDataForCallback.clear();
  221015. currentInputChans.clear();
  221016. if (inputChannels.getHighestBit() >= 0)
  221017. {
  221018. for (int i = 0; i <= jmax (inputChannels.getHighestBit(), (int) minChansIn); ++i)
  221019. {
  221020. if (inputChannels[i])
  221021. {
  221022. inputChannelDataForCallback.add (inputChannelBuffer.getSampleData (i));
  221023. currentInputChans.setBit (i);
  221024. }
  221025. }
  221026. }
  221027. outputChannelBuffer.setSize (jmax ((int) minChansOut, outputChannels.getHighestBit()) + 1, bufferSize);
  221028. outputChannelBuffer.clear();
  221029. outputChannelDataForCallback.clear();
  221030. currentOutputChans.clear();
  221031. if (outputChannels.getHighestBit() >= 0)
  221032. {
  221033. for (int i = 0; i <= jmax (outputChannels.getHighestBit(), (int) minChansOut); ++i)
  221034. {
  221035. if (outputChannels[i])
  221036. {
  221037. outputChannelDataForCallback.add (outputChannelBuffer.getSampleData (i));
  221038. currentOutputChans.setBit (i);
  221039. }
  221040. }
  221041. }
  221042. if (outputChannelDataForCallback.size() > 0 && outputId.isNotEmpty())
  221043. {
  221044. outputDevice = new ALSADevice (outputId, false);
  221045. if (outputDevice->error.isNotEmpty())
  221046. {
  221047. error = outputDevice->error;
  221048. deleteAndZero (outputDevice);
  221049. return;
  221050. }
  221051. currentOutputChans.setRange (0, minChansOut, true);
  221052. if (! outputDevice->setParameters ((unsigned int) sampleRate,
  221053. jlimit ((int) minChansOut, (int) maxChansOut, currentOutputChans.getHighestBit() + 1),
  221054. bufferSize))
  221055. {
  221056. error = outputDevice->error;
  221057. deleteAndZero (outputDevice);
  221058. return;
  221059. }
  221060. }
  221061. if (inputChannelDataForCallback.size() > 0 && inputId.isNotEmpty())
  221062. {
  221063. inputDevice = new ALSADevice (inputId, true);
  221064. if (inputDevice->error.isNotEmpty())
  221065. {
  221066. error = inputDevice->error;
  221067. deleteAndZero (inputDevice);
  221068. return;
  221069. }
  221070. currentInputChans.setRange (0, minChansIn, true);
  221071. if (! inputDevice->setParameters ((unsigned int) sampleRate,
  221072. jlimit ((int) minChansIn, (int) maxChansIn, currentInputChans.getHighestBit() + 1),
  221073. bufferSize))
  221074. {
  221075. error = inputDevice->error;
  221076. deleteAndZero (inputDevice);
  221077. return;
  221078. }
  221079. }
  221080. if (outputDevice == 0 && inputDevice == 0)
  221081. {
  221082. error = "no channels";
  221083. return;
  221084. }
  221085. if (outputDevice != 0 && inputDevice != 0)
  221086. {
  221087. snd_pcm_link (outputDevice->handle, inputDevice->handle);
  221088. }
  221089. if (inputDevice != 0 && failed (snd_pcm_prepare (inputDevice->handle)))
  221090. return;
  221091. if (outputDevice != 0 && failed (snd_pcm_prepare (outputDevice->handle)))
  221092. return;
  221093. startThread (9);
  221094. int count = 1000;
  221095. while (numCallbacks == 0)
  221096. {
  221097. sleep (5);
  221098. if (--count < 0 || ! isThreadRunning())
  221099. {
  221100. error = "device didn't start";
  221101. break;
  221102. }
  221103. }
  221104. }
  221105. void close()
  221106. {
  221107. stopThread (6000);
  221108. deleteAndZero (inputDevice);
  221109. deleteAndZero (outputDevice);
  221110. inputChannelBuffer.setSize (1, 1);
  221111. outputChannelBuffer.setSize (1, 1);
  221112. numCallbacks = 0;
  221113. }
  221114. void setCallback (AudioIODeviceCallback* const newCallback) throw()
  221115. {
  221116. const ScopedLock sl (callbackLock);
  221117. callback = newCallback;
  221118. }
  221119. void run()
  221120. {
  221121. while (! threadShouldExit())
  221122. {
  221123. if (inputDevice != 0)
  221124. {
  221125. if (! inputDevice->read (inputChannelBuffer, bufferSize))
  221126. {
  221127. DBG ("ALSA: read failure");
  221128. break;
  221129. }
  221130. }
  221131. if (threadShouldExit())
  221132. break;
  221133. {
  221134. const ScopedLock sl (callbackLock);
  221135. ++numCallbacks;
  221136. if (callback != 0)
  221137. {
  221138. callback->audioDeviceIOCallback ((const float**) inputChannelDataForCallback.getRawDataPointer(),
  221139. inputChannelDataForCallback.size(),
  221140. outputChannelDataForCallback.getRawDataPointer(),
  221141. outputChannelDataForCallback.size(),
  221142. bufferSize);
  221143. }
  221144. else
  221145. {
  221146. for (int i = 0; i < outputChannelDataForCallback.size(); ++i)
  221147. zeromem (outputChannelDataForCallback[i], sizeof (float) * bufferSize);
  221148. }
  221149. }
  221150. if (outputDevice != 0)
  221151. {
  221152. failed (snd_pcm_wait (outputDevice->handle, 2000));
  221153. if (threadShouldExit())
  221154. break;
  221155. failed (snd_pcm_avail_update (outputDevice->handle));
  221156. if (! outputDevice->write (outputChannelBuffer, bufferSize))
  221157. {
  221158. DBG ("ALSA: write failure");
  221159. break;
  221160. }
  221161. }
  221162. }
  221163. }
  221164. int getBitDepth() const throw()
  221165. {
  221166. if (outputDevice != 0)
  221167. return outputDevice->bitDepth;
  221168. if (inputDevice != 0)
  221169. return inputDevice->bitDepth;
  221170. return 16;
  221171. }
  221172. juce_UseDebuggingNewOperator
  221173. String error;
  221174. double sampleRate;
  221175. int bufferSize;
  221176. BigInteger currentInputChans, currentOutputChans;
  221177. Array <int> sampleRates;
  221178. StringArray channelNamesOut, channelNamesIn;
  221179. AudioIODeviceCallback* callback;
  221180. private:
  221181. const String inputId, outputId;
  221182. ALSADevice* outputDevice;
  221183. ALSADevice* inputDevice;
  221184. int numCallbacks;
  221185. CriticalSection callbackLock;
  221186. AudioSampleBuffer inputChannelBuffer, outputChannelBuffer;
  221187. Array<float*> inputChannelDataForCallback, outputChannelDataForCallback;
  221188. unsigned int minChansOut, maxChansOut;
  221189. unsigned int minChansIn, maxChansIn;
  221190. bool failed (const int errorNum)
  221191. {
  221192. if (errorNum >= 0)
  221193. return false;
  221194. error = snd_strerror (errorNum);
  221195. DBG ("ALSA error: " + error + "\n");
  221196. return true;
  221197. }
  221198. void initialiseRatesAndChannels()
  221199. {
  221200. sampleRates.clear();
  221201. channelNamesOut.clear();
  221202. channelNamesIn.clear();
  221203. minChansOut = 0;
  221204. maxChansOut = 0;
  221205. minChansIn = 0;
  221206. maxChansIn = 0;
  221207. unsigned int dummy = 0;
  221208. getDeviceProperties (inputId, dummy, dummy, minChansIn, maxChansIn, sampleRates);
  221209. getDeviceProperties (outputId, minChansOut, maxChansOut, dummy, dummy, sampleRates);
  221210. unsigned int i;
  221211. for (i = 0; i < maxChansOut; ++i)
  221212. channelNamesOut.add ("channel " + String ((int) i + 1));
  221213. for (i = 0; i < maxChansIn; ++i)
  221214. channelNamesIn.add ("channel " + String ((int) i + 1));
  221215. }
  221216. };
  221217. class ALSAAudioIODevice : public AudioIODevice
  221218. {
  221219. public:
  221220. ALSAAudioIODevice (const String& deviceName,
  221221. const String& inputId_,
  221222. const String& outputId_)
  221223. : AudioIODevice (deviceName, "ALSA"),
  221224. inputId (inputId_),
  221225. outputId (outputId_),
  221226. isOpen_ (false),
  221227. isStarted (false),
  221228. internal (new ALSAThread (inputId_, outputId_))
  221229. {
  221230. }
  221231. ~ALSAAudioIODevice()
  221232. {
  221233. }
  221234. const StringArray getOutputChannelNames()
  221235. {
  221236. return internal->channelNamesOut;
  221237. }
  221238. const StringArray getInputChannelNames()
  221239. {
  221240. return internal->channelNamesIn;
  221241. }
  221242. int getNumSampleRates()
  221243. {
  221244. return internal->sampleRates.size();
  221245. }
  221246. double getSampleRate (int index)
  221247. {
  221248. return internal->sampleRates [index];
  221249. }
  221250. int getNumBufferSizesAvailable()
  221251. {
  221252. return 50;
  221253. }
  221254. int getBufferSizeSamples (int index)
  221255. {
  221256. int n = 16;
  221257. for (int i = 0; i < index; ++i)
  221258. n += n < 64 ? 16
  221259. : (n < 512 ? 32
  221260. : (n < 1024 ? 64
  221261. : (n < 2048 ? 128 : 256)));
  221262. return n;
  221263. }
  221264. int getDefaultBufferSize()
  221265. {
  221266. return 512;
  221267. }
  221268. const String open (const BigInteger& inputChannels,
  221269. const BigInteger& outputChannels,
  221270. double sampleRate,
  221271. int bufferSizeSamples)
  221272. {
  221273. close();
  221274. if (bufferSizeSamples <= 0)
  221275. bufferSizeSamples = getDefaultBufferSize();
  221276. if (sampleRate <= 0)
  221277. {
  221278. for (int i = 0; i < getNumSampleRates(); ++i)
  221279. {
  221280. if (getSampleRate (i) >= 44100)
  221281. {
  221282. sampleRate = getSampleRate (i);
  221283. break;
  221284. }
  221285. }
  221286. }
  221287. internal->open (inputChannels, outputChannels,
  221288. sampleRate, bufferSizeSamples);
  221289. isOpen_ = internal->error.isEmpty();
  221290. return internal->error;
  221291. }
  221292. void close()
  221293. {
  221294. stop();
  221295. internal->close();
  221296. isOpen_ = false;
  221297. }
  221298. bool isOpen()
  221299. {
  221300. return isOpen_;
  221301. }
  221302. int getCurrentBufferSizeSamples()
  221303. {
  221304. return internal->bufferSize;
  221305. }
  221306. double getCurrentSampleRate()
  221307. {
  221308. return internal->sampleRate;
  221309. }
  221310. int getCurrentBitDepth()
  221311. {
  221312. return internal->getBitDepth();
  221313. }
  221314. const BigInteger getActiveOutputChannels() const
  221315. {
  221316. return internal->currentOutputChans;
  221317. }
  221318. const BigInteger getActiveInputChannels() const
  221319. {
  221320. return internal->currentInputChans;
  221321. }
  221322. int getOutputLatencyInSamples()
  221323. {
  221324. return 0;
  221325. }
  221326. int getInputLatencyInSamples()
  221327. {
  221328. return 0;
  221329. }
  221330. void start (AudioIODeviceCallback* callback)
  221331. {
  221332. if (! isOpen_)
  221333. callback = 0;
  221334. internal->setCallback (callback);
  221335. if (callback != 0)
  221336. callback->audioDeviceAboutToStart (this);
  221337. isStarted = (callback != 0);
  221338. }
  221339. void stop()
  221340. {
  221341. AudioIODeviceCallback* const oldCallback = internal->callback;
  221342. start (0);
  221343. if (oldCallback != 0)
  221344. oldCallback->audioDeviceStopped();
  221345. }
  221346. bool isPlaying()
  221347. {
  221348. return isStarted && internal->error.isEmpty();
  221349. }
  221350. const String getLastError()
  221351. {
  221352. return internal->error;
  221353. }
  221354. String inputId, outputId;
  221355. private:
  221356. bool isOpen_, isStarted;
  221357. ScopedPointer<ALSAThread> internal;
  221358. };
  221359. class ALSAAudioIODeviceType : public AudioIODeviceType
  221360. {
  221361. public:
  221362. ALSAAudioIODeviceType()
  221363. : AudioIODeviceType ("ALSA"),
  221364. hasScanned (false)
  221365. {
  221366. }
  221367. ~ALSAAudioIODeviceType()
  221368. {
  221369. }
  221370. void scanForDevices()
  221371. {
  221372. if (hasScanned)
  221373. return;
  221374. hasScanned = true;
  221375. inputNames.clear();
  221376. inputIds.clear();
  221377. outputNames.clear();
  221378. outputIds.clear();
  221379. snd_ctl_t* handle;
  221380. snd_ctl_card_info_t* info;
  221381. snd_ctl_card_info_alloca (&info);
  221382. int cardNum = -1;
  221383. while (outputIds.size() + inputIds.size() <= 32)
  221384. {
  221385. snd_card_next (&cardNum);
  221386. if (cardNum < 0)
  221387. break;
  221388. if (snd_ctl_open (&handle, ("hw:" + String (cardNum)).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  221389. {
  221390. if (snd_ctl_card_info (handle, info) >= 0)
  221391. {
  221392. String cardId (snd_ctl_card_info_get_id (info));
  221393. if (cardId.removeCharacters ("0123456789").isEmpty())
  221394. cardId = String (cardNum);
  221395. int device = -1;
  221396. for (;;)
  221397. {
  221398. if (snd_ctl_pcm_next_device (handle, &device) < 0 || device < 0)
  221399. break;
  221400. String id, name;
  221401. id << "hw:" << cardId << ',' << device;
  221402. bool isInput, isOutput;
  221403. if (testDevice (id, isInput, isOutput))
  221404. {
  221405. name << snd_ctl_card_info_get_name (info);
  221406. if (name.isEmpty())
  221407. name = id;
  221408. if (isInput)
  221409. {
  221410. inputNames.add (name);
  221411. inputIds.add (id);
  221412. }
  221413. if (isOutput)
  221414. {
  221415. outputNames.add (name);
  221416. outputIds.add (id);
  221417. }
  221418. }
  221419. }
  221420. }
  221421. snd_ctl_close (handle);
  221422. }
  221423. }
  221424. inputNames.appendNumbersToDuplicates (false, true);
  221425. outputNames.appendNumbersToDuplicates (false, true);
  221426. }
  221427. const StringArray getDeviceNames (bool wantInputNames) const
  221428. {
  221429. jassert (hasScanned); // need to call scanForDevices() before doing this
  221430. return wantInputNames ? inputNames : outputNames;
  221431. }
  221432. int getDefaultDeviceIndex (bool forInput) const
  221433. {
  221434. jassert (hasScanned); // need to call scanForDevices() before doing this
  221435. return 0;
  221436. }
  221437. bool hasSeparateInputsAndOutputs() const { return true; }
  221438. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  221439. {
  221440. jassert (hasScanned); // need to call scanForDevices() before doing this
  221441. ALSAAudioIODevice* d = dynamic_cast <ALSAAudioIODevice*> (device);
  221442. if (d == 0)
  221443. return -1;
  221444. return asInput ? inputIds.indexOf (d->inputId)
  221445. : outputIds.indexOf (d->outputId);
  221446. }
  221447. AudioIODevice* createDevice (const String& outputDeviceName,
  221448. const String& inputDeviceName)
  221449. {
  221450. jassert (hasScanned); // need to call scanForDevices() before doing this
  221451. const int inputIndex = inputNames.indexOf (inputDeviceName);
  221452. const int outputIndex = outputNames.indexOf (outputDeviceName);
  221453. String deviceName (outputIndex >= 0 ? outputDeviceName
  221454. : inputDeviceName);
  221455. if (inputIndex >= 0 || outputIndex >= 0)
  221456. return new ALSAAudioIODevice (deviceName,
  221457. inputIds [inputIndex],
  221458. outputIds [outputIndex]);
  221459. return 0;
  221460. }
  221461. juce_UseDebuggingNewOperator
  221462. private:
  221463. StringArray inputNames, outputNames, inputIds, outputIds;
  221464. bool hasScanned;
  221465. static bool testDevice (const String& id, bool& isInput, bool& isOutput)
  221466. {
  221467. unsigned int minChansOut = 0, maxChansOut = 0;
  221468. unsigned int minChansIn = 0, maxChansIn = 0;
  221469. Array <int> rates;
  221470. getDeviceProperties (id, minChansOut, maxChansOut, minChansIn, maxChansIn, rates);
  221471. DBG ("ALSA device: " + id
  221472. + " outs=" + String ((int) minChansOut) + "-" + String ((int) maxChansOut)
  221473. + " ins=" + String ((int) minChansIn) + "-" + String ((int) maxChansIn)
  221474. + " rates=" + String (rates.size()));
  221475. isInput = maxChansIn > 0;
  221476. isOutput = maxChansOut > 0;
  221477. return (isInput || isOutput) && rates.size() > 0;
  221478. }
  221479. ALSAAudioIODeviceType (const ALSAAudioIODeviceType&);
  221480. ALSAAudioIODeviceType& operator= (const ALSAAudioIODeviceType&);
  221481. };
  221482. AudioIODeviceType* juce_createAudioIODeviceType_ALSA()
  221483. {
  221484. return new ALSAAudioIODeviceType();
  221485. }
  221486. #endif
  221487. /*** End of inlined file: juce_linux_Audio.cpp ***/
  221488. /*** Start of inlined file: juce_linux_JackAudio.cpp ***/
  221489. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  221490. // compiled on its own).
  221491. #ifdef JUCE_INCLUDED_FILE
  221492. #if JUCE_JACK
  221493. static void* juce_libjack_handle = 0;
  221494. void* juce_load_jack_function (const char* const name)
  221495. {
  221496. if (juce_libjack_handle == 0)
  221497. return 0;
  221498. return dlsym (juce_libjack_handle, name);
  221499. }
  221500. #define JUCE_DECL_JACK_FUNCTION(return_type, fn_name, argument_types, arguments) \
  221501. typedef return_type (*fn_name##_ptr_t)argument_types; \
  221502. return_type fn_name argument_types { \
  221503. static fn_name##_ptr_t fn = 0; \
  221504. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  221505. if (fn) return (*fn)arguments; \
  221506. else return 0; \
  221507. }
  221508. #define JUCE_DECL_VOID_JACK_FUNCTION(fn_name, argument_types, arguments) \
  221509. typedef void (*fn_name##_ptr_t)argument_types; \
  221510. void fn_name argument_types { \
  221511. static fn_name##_ptr_t fn = 0; \
  221512. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  221513. if (fn) (*fn)arguments; \
  221514. }
  221515. 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));
  221516. JUCE_DECL_JACK_FUNCTION (int, jack_client_close, (jack_client_t *client), (client));
  221517. JUCE_DECL_JACK_FUNCTION (int, jack_activate, (jack_client_t* client), (client));
  221518. JUCE_DECL_JACK_FUNCTION (int, jack_deactivate, (jack_client_t* client), (client));
  221519. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_buffer_size, (jack_client_t* client), (client));
  221520. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_sample_rate, (jack_client_t* client), (client));
  221521. JUCE_DECL_VOID_JACK_FUNCTION (jack_on_shutdown, (jack_client_t* client, void (*function)(void* arg), void* arg), (client, function, arg));
  221522. JUCE_DECL_JACK_FUNCTION (void* , jack_port_get_buffer, (jack_port_t* port, jack_nframes_t nframes), (port, nframes));
  221523. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_port_get_total_latency, (jack_client_t* client, jack_port_t* port), (client, port));
  221524. 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));
  221525. JUCE_DECL_VOID_JACK_FUNCTION (jack_set_error_function, (void (*func)(const char*)), (func));
  221526. JUCE_DECL_JACK_FUNCTION (int, jack_set_process_callback, (jack_client_t* client, JackProcessCallback process_callback, void* arg), (client, process_callback, arg));
  221527. 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));
  221528. JUCE_DECL_JACK_FUNCTION (int, jack_connect, (jack_client_t* client, const char* source_port, const char* destination_port), (client, source_port, destination_port));
  221529. JUCE_DECL_JACK_FUNCTION (const char*, jack_port_name, (const jack_port_t* port), (port));
  221530. JUCE_DECL_JACK_FUNCTION (int, jack_set_port_connect_callback, (jack_client_t* client, JackPortConnectCallback connect_callback, void* arg), (client, connect_callback, arg));
  221531. JUCE_DECL_JACK_FUNCTION (jack_port_t* , jack_port_by_id, (jack_client_t* client, jack_port_id_t port_id), (client, port_id));
  221532. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected, (const jack_port_t* port), (port));
  221533. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected_to, (const jack_port_t* port, const char* port_name), (port, port_name));
  221534. #if JUCE_DEBUG
  221535. #define JACK_LOGGING_ENABLED 1
  221536. #endif
  221537. #if JACK_LOGGING_ENABLED
  221538. static void jack_Log (const String& s)
  221539. {
  221540. std::cerr << s << std::endl;
  221541. }
  221542. static void dumpJackErrorMessage (const jack_status_t status)
  221543. {
  221544. if (status & JackServerFailed || status & JackServerError)
  221545. jack_Log ("Unable to connect to JACK server");
  221546. if (status & JackVersionError)
  221547. jack_Log ("Client's protocol version does not match");
  221548. if (status & JackInvalidOption)
  221549. jack_Log ("The operation contained an invalid or unsupported option");
  221550. if (status & JackNameNotUnique)
  221551. jack_Log ("The desired client name was not unique");
  221552. if (status & JackNoSuchClient)
  221553. jack_Log ("Requested client does not exist");
  221554. if (status & JackInitFailure)
  221555. jack_Log ("Unable to initialize client");
  221556. }
  221557. #else
  221558. #define dumpJackErrorMessage(a) {}
  221559. #define jack_Log(...) {}
  221560. #endif
  221561. #ifndef JUCE_JACK_CLIENT_NAME
  221562. #define JUCE_JACK_CLIENT_NAME "JuceJack"
  221563. #endif
  221564. class JackAudioIODevice : public AudioIODevice
  221565. {
  221566. public:
  221567. JackAudioIODevice (const String& deviceName,
  221568. const String& inputId_,
  221569. const String& outputId_)
  221570. : AudioIODevice (deviceName, "JACK"),
  221571. inputId (inputId_),
  221572. outputId (outputId_),
  221573. isOpen_ (false),
  221574. callback (0),
  221575. totalNumberOfInputChannels (0),
  221576. totalNumberOfOutputChannels (0)
  221577. {
  221578. jassert (deviceName.isNotEmpty());
  221579. jack_status_t status;
  221580. client = JUCE_NAMESPACE::jack_client_open (JUCE_JACK_CLIENT_NAME, JackNoStartServer, &status);
  221581. if (client == 0)
  221582. {
  221583. dumpJackErrorMessage (status);
  221584. }
  221585. else
  221586. {
  221587. JUCE_NAMESPACE::jack_set_error_function (errorCallback);
  221588. // open input ports
  221589. const StringArray inputChannels (getInputChannelNames());
  221590. for (int i = 0; i < inputChannels.size(); i++)
  221591. {
  221592. String inputName;
  221593. inputName << "in_" << ++totalNumberOfInputChannels;
  221594. inputPorts.add (JUCE_NAMESPACE::jack_port_register (client, inputName.toUTF8(),
  221595. JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0));
  221596. }
  221597. // open output ports
  221598. const StringArray outputChannels (getOutputChannelNames());
  221599. for (int i = 0; i < outputChannels.size (); i++)
  221600. {
  221601. String outputName;
  221602. outputName << "out_" << ++totalNumberOfOutputChannels;
  221603. outputPorts.add (JUCE_NAMESPACE::jack_port_register (client, outputName.toUTF8(),
  221604. JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0));
  221605. }
  221606. inChans.calloc (totalNumberOfInputChannels + 2);
  221607. outChans.calloc (totalNumberOfOutputChannels + 2);
  221608. }
  221609. }
  221610. ~JackAudioIODevice()
  221611. {
  221612. close();
  221613. if (client != 0)
  221614. {
  221615. JUCE_NAMESPACE::jack_client_close (client);
  221616. client = 0;
  221617. }
  221618. }
  221619. const StringArray getChannelNames (bool forInput) const
  221620. {
  221621. StringArray names;
  221622. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */
  221623. forInput ? JackPortIsInput : JackPortIsOutput);
  221624. if (ports != 0)
  221625. {
  221626. int j = 0;
  221627. while (ports[j] != 0)
  221628. {
  221629. const String portName (ports [j++]);
  221630. if (portName.upToFirstOccurrenceOf (":", false, false) == getName())
  221631. names.add (portName.fromFirstOccurrenceOf (":", false, false));
  221632. }
  221633. free (ports);
  221634. }
  221635. return names;
  221636. }
  221637. const StringArray getOutputChannelNames() { return getChannelNames (false); }
  221638. const StringArray getInputChannelNames() { return getChannelNames (true); }
  221639. int getNumSampleRates() { return client != 0 ? 1 : 0; }
  221640. double getSampleRate (int index) { return client != 0 ? JUCE_NAMESPACE::jack_get_sample_rate (client) : 0; }
  221641. int getNumBufferSizesAvailable() { return client != 0 ? 1 : 0; }
  221642. int getBufferSizeSamples (int index) { return getDefaultBufferSize(); }
  221643. int getDefaultBufferSize() { return client != 0 ? JUCE_NAMESPACE::jack_get_buffer_size (client) : 0; }
  221644. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  221645. double sampleRate, int bufferSizeSamples)
  221646. {
  221647. if (client == 0)
  221648. {
  221649. lastError = "No JACK client running";
  221650. return lastError;
  221651. }
  221652. lastError = String::empty;
  221653. close();
  221654. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, this);
  221655. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, this);
  221656. JUCE_NAMESPACE::jack_activate (client);
  221657. isOpen_ = true;
  221658. if (! inputChannels.isZero())
  221659. {
  221660. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  221661. if (ports != 0)
  221662. {
  221663. const int numInputChannels = inputChannels.getHighestBit() + 1;
  221664. for (int i = 0; i < numInputChannels; ++i)
  221665. {
  221666. const String portName (ports[i]);
  221667. if (inputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  221668. {
  221669. int error = JUCE_NAMESPACE::jack_connect (client, ports[i], JUCE_NAMESPACE::jack_port_name ((jack_port_t*) inputPorts[i]));
  221670. if (error != 0)
  221671. jack_Log ("Cannot connect input port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  221672. }
  221673. }
  221674. free (ports);
  221675. }
  221676. }
  221677. if (! outputChannels.isZero())
  221678. {
  221679. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  221680. if (ports != 0)
  221681. {
  221682. const int numOutputChannels = outputChannels.getHighestBit() + 1;
  221683. for (int i = 0; i < numOutputChannels; ++i)
  221684. {
  221685. const String portName (ports[i]);
  221686. if (outputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  221687. {
  221688. int error = JUCE_NAMESPACE::jack_connect (client, JUCE_NAMESPACE::jack_port_name ((jack_port_t*) outputPorts[i]), ports[i]);
  221689. if (error != 0)
  221690. jack_Log ("Cannot connect output port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  221691. }
  221692. }
  221693. free (ports);
  221694. }
  221695. }
  221696. return lastError;
  221697. }
  221698. void close()
  221699. {
  221700. stop();
  221701. if (client != 0)
  221702. {
  221703. JUCE_NAMESPACE::jack_deactivate (client);
  221704. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, 0);
  221705. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, 0);
  221706. }
  221707. isOpen_ = false;
  221708. }
  221709. void start (AudioIODeviceCallback* newCallback)
  221710. {
  221711. if (isOpen_ && newCallback != callback)
  221712. {
  221713. if (newCallback != 0)
  221714. newCallback->audioDeviceAboutToStart (this);
  221715. AudioIODeviceCallback* const oldCallback = callback;
  221716. {
  221717. const ScopedLock sl (callbackLock);
  221718. callback = newCallback;
  221719. }
  221720. if (oldCallback != 0)
  221721. oldCallback->audioDeviceStopped();
  221722. }
  221723. }
  221724. void stop()
  221725. {
  221726. start (0);
  221727. }
  221728. bool isOpen() { return isOpen_; }
  221729. bool isPlaying() { return callback != 0; }
  221730. int getCurrentBufferSizeSamples() { return getBufferSizeSamples (0); }
  221731. double getCurrentSampleRate() { return getSampleRate (0); }
  221732. int getCurrentBitDepth() { return 32; }
  221733. const String getLastError() { return lastError; }
  221734. const BigInteger getActiveOutputChannels() const
  221735. {
  221736. BigInteger outputBits;
  221737. for (int i = 0; i < outputPorts.size(); i++)
  221738. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) outputPorts [i]))
  221739. outputBits.setBit (i);
  221740. return outputBits;
  221741. }
  221742. const BigInteger getActiveInputChannels() const
  221743. {
  221744. BigInteger inputBits;
  221745. for (int i = 0; i < inputPorts.size(); i++)
  221746. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) inputPorts [i]))
  221747. inputBits.setBit (i);
  221748. return inputBits;
  221749. }
  221750. int getOutputLatencyInSamples()
  221751. {
  221752. int latency = 0;
  221753. for (int i = 0; i < outputPorts.size(); i++)
  221754. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) outputPorts [i]));
  221755. return latency;
  221756. }
  221757. int getInputLatencyInSamples()
  221758. {
  221759. int latency = 0;
  221760. for (int i = 0; i < inputPorts.size(); i++)
  221761. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) inputPorts [i]));
  221762. return latency;
  221763. }
  221764. String inputId, outputId;
  221765. private:
  221766. void process (const int numSamples)
  221767. {
  221768. int i, numActiveInChans = 0, numActiveOutChans = 0;
  221769. for (i = 0; i < totalNumberOfInputChannels; ++i)
  221770. {
  221771. jack_default_audio_sample_t* in
  221772. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) inputPorts.getUnchecked(i), numSamples);
  221773. if (in != 0)
  221774. inChans [numActiveInChans++] = (float*) in;
  221775. }
  221776. for (i = 0; i < totalNumberOfOutputChannels; ++i)
  221777. {
  221778. jack_default_audio_sample_t* out
  221779. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) outputPorts.getUnchecked(i), numSamples);
  221780. if (out != 0)
  221781. outChans [numActiveOutChans++] = (float*) out;
  221782. }
  221783. const ScopedLock sl (callbackLock);
  221784. if (callback != 0)
  221785. {
  221786. callback->audioDeviceIOCallback (const_cast<const float**> (inChans.getData()), numActiveInChans,
  221787. outChans, numActiveOutChans, numSamples);
  221788. }
  221789. else
  221790. {
  221791. for (i = 0; i < numActiveOutChans; ++i)
  221792. zeromem (outChans[i], sizeof (float) * numSamples);
  221793. }
  221794. }
  221795. static int processCallback (jack_nframes_t nframes, void* callbackArgument)
  221796. {
  221797. if (callbackArgument != 0)
  221798. ((JackAudioIODevice*) callbackArgument)->process (nframes);
  221799. return 0;
  221800. }
  221801. static void threadInitCallback (void* callbackArgument)
  221802. {
  221803. jack_Log ("JackAudioIODevice::initialise");
  221804. }
  221805. static void shutdownCallback (void* callbackArgument)
  221806. {
  221807. jack_Log ("JackAudioIODevice::shutdown");
  221808. JackAudioIODevice* device = (JackAudioIODevice*) callbackArgument;
  221809. if (device != 0)
  221810. {
  221811. device->client = 0;
  221812. device->close();
  221813. }
  221814. }
  221815. static void errorCallback (const char* msg)
  221816. {
  221817. jack_Log ("JackAudioIODevice::errorCallback " + String (msg));
  221818. }
  221819. bool isOpen_;
  221820. jack_client_t* client;
  221821. String lastError;
  221822. AudioIODeviceCallback* callback;
  221823. CriticalSection callbackLock;
  221824. HeapBlock <float*> inChans, outChans;
  221825. int totalNumberOfInputChannels;
  221826. int totalNumberOfOutputChannels;
  221827. Array<void*> inputPorts, outputPorts;
  221828. };
  221829. class JackAudioIODeviceType : public AudioIODeviceType
  221830. {
  221831. public:
  221832. JackAudioIODeviceType()
  221833. : AudioIODeviceType ("JACK"),
  221834. hasScanned (false)
  221835. {
  221836. }
  221837. ~JackAudioIODeviceType()
  221838. {
  221839. }
  221840. void scanForDevices()
  221841. {
  221842. hasScanned = true;
  221843. inputNames.clear();
  221844. inputIds.clear();
  221845. outputNames.clear();
  221846. outputIds.clear();
  221847. if (juce_libjack_handle == 0)
  221848. {
  221849. juce_libjack_handle = dlopen ("libjack.so", RTLD_LAZY);
  221850. if (juce_libjack_handle == 0)
  221851. return;
  221852. }
  221853. // open a dummy client
  221854. jack_status_t status;
  221855. jack_client_t* client = JUCE_NAMESPACE::jack_client_open ("JuceJackDummy", JackNoStartServer, &status);
  221856. if (client == 0)
  221857. {
  221858. dumpJackErrorMessage (status);
  221859. }
  221860. else
  221861. {
  221862. // scan for output devices
  221863. const char** ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  221864. if (ports != 0)
  221865. {
  221866. int j = 0;
  221867. while (ports[j] != 0)
  221868. {
  221869. String clientName (ports[j]);
  221870. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  221871. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  221872. && ! inputNames.contains (clientName))
  221873. {
  221874. inputNames.add (clientName);
  221875. inputIds.add (ports [j]);
  221876. }
  221877. ++j;
  221878. }
  221879. free (ports);
  221880. }
  221881. // scan for input devices
  221882. ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  221883. if (ports != 0)
  221884. {
  221885. int j = 0;
  221886. while (ports[j] != 0)
  221887. {
  221888. String clientName (ports[j]);
  221889. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  221890. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  221891. && ! outputNames.contains (clientName))
  221892. {
  221893. outputNames.add (clientName);
  221894. outputIds.add (ports [j]);
  221895. }
  221896. ++j;
  221897. }
  221898. free (ports);
  221899. }
  221900. JUCE_NAMESPACE::jack_client_close (client);
  221901. }
  221902. }
  221903. const StringArray getDeviceNames (bool wantInputNames) const
  221904. {
  221905. jassert (hasScanned); // need to call scanForDevices() before doing this
  221906. return wantInputNames ? inputNames : outputNames;
  221907. }
  221908. int getDefaultDeviceIndex (bool forInput) const
  221909. {
  221910. jassert (hasScanned); // need to call scanForDevices() before doing this
  221911. return 0;
  221912. }
  221913. bool hasSeparateInputsAndOutputs() const { return true; }
  221914. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  221915. {
  221916. jassert (hasScanned); // need to call scanForDevices() before doing this
  221917. JackAudioIODevice* d = dynamic_cast <JackAudioIODevice*> (device);
  221918. if (d == 0)
  221919. return -1;
  221920. return asInput ? inputIds.indexOf (d->inputId)
  221921. : outputIds.indexOf (d->outputId);
  221922. }
  221923. AudioIODevice* createDevice (const String& outputDeviceName,
  221924. const String& inputDeviceName)
  221925. {
  221926. jassert (hasScanned); // need to call scanForDevices() before doing this
  221927. const int inputIndex = inputNames.indexOf (inputDeviceName);
  221928. const int outputIndex = outputNames.indexOf (outputDeviceName);
  221929. if (inputIndex >= 0 || outputIndex >= 0)
  221930. return new JackAudioIODevice (outputIndex >= 0 ? outputDeviceName
  221931. : inputDeviceName,
  221932. inputIds [inputIndex],
  221933. outputIds [outputIndex]);
  221934. return 0;
  221935. }
  221936. juce_UseDebuggingNewOperator
  221937. private:
  221938. StringArray inputNames, outputNames, inputIds, outputIds;
  221939. bool hasScanned;
  221940. JackAudioIODeviceType (const JackAudioIODeviceType&);
  221941. JackAudioIODeviceType& operator= (const JackAudioIODeviceType&);
  221942. };
  221943. AudioIODeviceType* juce_createAudioIODeviceType_JACK()
  221944. {
  221945. return new JackAudioIODeviceType();
  221946. }
  221947. #else // if JACK is turned off..
  221948. AudioIODeviceType* juce_createAudioIODeviceType_JACK() { return 0; }
  221949. #endif
  221950. #endif
  221951. /*** End of inlined file: juce_linux_JackAudio.cpp ***/
  221952. /*** Start of inlined file: juce_linux_Midi.cpp ***/
  221953. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  221954. // compiled on its own).
  221955. #if JUCE_INCLUDED_FILE
  221956. #if JUCE_ALSA
  221957. static snd_seq_t* iterateDevices (const bool forInput,
  221958. StringArray& deviceNamesFound,
  221959. const int deviceIndexToOpen)
  221960. {
  221961. snd_seq_t* returnedHandle = 0;
  221962. snd_seq_t* seqHandle;
  221963. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  221964. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  221965. {
  221966. snd_seq_system_info_t* systemInfo;
  221967. snd_seq_client_info_t* clientInfo;
  221968. if (snd_seq_system_info_malloc (&systemInfo) == 0)
  221969. {
  221970. if (snd_seq_system_info (seqHandle, systemInfo) == 0
  221971. && snd_seq_client_info_malloc (&clientInfo) == 0)
  221972. {
  221973. int numClients = snd_seq_system_info_get_cur_clients (systemInfo);
  221974. while (--numClients >= 0 && returnedHandle == 0)
  221975. {
  221976. if (snd_seq_query_next_client (seqHandle, clientInfo) == 0)
  221977. {
  221978. snd_seq_port_info_t* portInfo;
  221979. if (snd_seq_port_info_malloc (&portInfo) == 0)
  221980. {
  221981. int numPorts = snd_seq_client_info_get_num_ports (clientInfo);
  221982. const int client = snd_seq_client_info_get_client (clientInfo);
  221983. snd_seq_port_info_set_client (portInfo, client);
  221984. snd_seq_port_info_set_port (portInfo, -1);
  221985. while (--numPorts >= 0)
  221986. {
  221987. if (snd_seq_query_next_port (seqHandle, portInfo) == 0
  221988. && (snd_seq_port_info_get_capability (portInfo)
  221989. & (forInput ? SND_SEQ_PORT_CAP_READ
  221990. : SND_SEQ_PORT_CAP_WRITE)) != 0)
  221991. {
  221992. deviceNamesFound.add (snd_seq_client_info_get_name (clientInfo));
  221993. if (deviceNamesFound.size() == deviceIndexToOpen + 1)
  221994. {
  221995. const int sourcePort = snd_seq_port_info_get_port (portInfo);
  221996. const int sourceClient = snd_seq_client_info_get_client (clientInfo);
  221997. if (sourcePort != -1)
  221998. {
  221999. snd_seq_set_client_name (seqHandle,
  222000. forInput ? "Juce Midi Input"
  222001. : "Juce Midi Output");
  222002. const int portId
  222003. = snd_seq_create_simple_port (seqHandle,
  222004. forInput ? "Juce Midi In Port"
  222005. : "Juce Midi Out Port",
  222006. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  222007. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  222008. SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  222009. snd_seq_connect_from (seqHandle, portId, sourceClient, sourcePort);
  222010. returnedHandle = seqHandle;
  222011. }
  222012. }
  222013. }
  222014. }
  222015. snd_seq_port_info_free (portInfo);
  222016. }
  222017. }
  222018. }
  222019. snd_seq_client_info_free (clientInfo);
  222020. }
  222021. snd_seq_system_info_free (systemInfo);
  222022. }
  222023. if (returnedHandle == 0)
  222024. snd_seq_close (seqHandle);
  222025. }
  222026. deviceNamesFound.appendNumbersToDuplicates (true, true);
  222027. return returnedHandle;
  222028. }
  222029. static snd_seq_t* createDevice (const bool forInput,
  222030. const String& deviceNameToOpen)
  222031. {
  222032. snd_seq_t* seqHandle = 0;
  222033. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  222034. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  222035. {
  222036. snd_seq_set_client_name (seqHandle,
  222037. (deviceNameToOpen + (forInput ? " Input" : " Output")).toCString());
  222038. const int portId
  222039. = snd_seq_create_simple_port (seqHandle,
  222040. forInput ? "in"
  222041. : "out",
  222042. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  222043. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  222044. forInput ? SND_SEQ_PORT_TYPE_APPLICATION
  222045. : SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  222046. if (portId < 0)
  222047. {
  222048. snd_seq_close (seqHandle);
  222049. seqHandle = 0;
  222050. }
  222051. }
  222052. return seqHandle;
  222053. }
  222054. class MidiOutputDevice
  222055. {
  222056. public:
  222057. MidiOutputDevice (MidiOutput* const midiOutput_,
  222058. snd_seq_t* const seqHandle_)
  222059. :
  222060. midiOutput (midiOutput_),
  222061. seqHandle (seqHandle_),
  222062. maxEventSize (16 * 1024)
  222063. {
  222064. jassert (seqHandle != 0 && midiOutput != 0);
  222065. snd_midi_event_new (maxEventSize, &midiParser);
  222066. }
  222067. ~MidiOutputDevice()
  222068. {
  222069. snd_midi_event_free (midiParser);
  222070. snd_seq_close (seqHandle);
  222071. }
  222072. void sendMessageNow (const MidiMessage& message)
  222073. {
  222074. if (message.getRawDataSize() > maxEventSize)
  222075. {
  222076. maxEventSize = message.getRawDataSize();
  222077. snd_midi_event_free (midiParser);
  222078. snd_midi_event_new (maxEventSize, &midiParser);
  222079. }
  222080. snd_seq_event_t event;
  222081. snd_seq_ev_clear (&event);
  222082. snd_midi_event_encode (midiParser,
  222083. message.getRawData(),
  222084. message.getRawDataSize(),
  222085. &event);
  222086. snd_midi_event_reset_encode (midiParser);
  222087. snd_seq_ev_set_source (&event, 0);
  222088. snd_seq_ev_set_subs (&event);
  222089. snd_seq_ev_set_direct (&event);
  222090. snd_seq_event_output (seqHandle, &event);
  222091. snd_seq_drain_output (seqHandle);
  222092. }
  222093. juce_UseDebuggingNewOperator
  222094. private:
  222095. MidiOutput* const midiOutput;
  222096. snd_seq_t* const seqHandle;
  222097. snd_midi_event_t* midiParser;
  222098. int maxEventSize;
  222099. };
  222100. const StringArray MidiOutput::getDevices()
  222101. {
  222102. StringArray devices;
  222103. iterateDevices (false, devices, -1);
  222104. return devices;
  222105. }
  222106. int MidiOutput::getDefaultDeviceIndex()
  222107. {
  222108. return 0;
  222109. }
  222110. MidiOutput* MidiOutput::openDevice (int deviceIndex)
  222111. {
  222112. MidiOutput* newDevice = 0;
  222113. StringArray devices;
  222114. snd_seq_t* const handle = iterateDevices (false, devices, deviceIndex);
  222115. if (handle != 0)
  222116. {
  222117. newDevice = new MidiOutput();
  222118. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  222119. }
  222120. return newDevice;
  222121. }
  222122. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  222123. {
  222124. MidiOutput* newDevice = 0;
  222125. snd_seq_t* const handle = createDevice (false, deviceName);
  222126. if (handle != 0)
  222127. {
  222128. newDevice = new MidiOutput();
  222129. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  222130. }
  222131. return newDevice;
  222132. }
  222133. MidiOutput::~MidiOutput()
  222134. {
  222135. MidiOutputDevice* const device = (MidiOutputDevice*) internal;
  222136. delete device;
  222137. }
  222138. void MidiOutput::reset()
  222139. {
  222140. }
  222141. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  222142. {
  222143. return false;
  222144. }
  222145. void MidiOutput::setVolume (float leftVol, float rightVol)
  222146. {
  222147. }
  222148. void MidiOutput::sendMessageNow (const MidiMessage& message)
  222149. {
  222150. ((MidiOutputDevice*) internal)->sendMessageNow (message);
  222151. }
  222152. class MidiInputThread : public Thread
  222153. {
  222154. public:
  222155. MidiInputThread (MidiInput* const midiInput_,
  222156. snd_seq_t* const seqHandle_,
  222157. MidiInputCallback* const callback_)
  222158. : Thread ("Juce MIDI Input"),
  222159. midiInput (midiInput_),
  222160. seqHandle (seqHandle_),
  222161. callback (callback_)
  222162. {
  222163. jassert (seqHandle != 0 && callback != 0 && midiInput != 0);
  222164. }
  222165. ~MidiInputThread()
  222166. {
  222167. snd_seq_close (seqHandle);
  222168. }
  222169. void run()
  222170. {
  222171. const int maxEventSize = 16 * 1024;
  222172. snd_midi_event_t* midiParser;
  222173. if (snd_midi_event_new (maxEventSize, &midiParser) >= 0)
  222174. {
  222175. HeapBlock <uint8> buffer (maxEventSize);
  222176. const int numPfds = snd_seq_poll_descriptors_count (seqHandle, POLLIN);
  222177. struct pollfd* const pfd = (struct pollfd*) alloca (numPfds * sizeof (struct pollfd));
  222178. snd_seq_poll_descriptors (seqHandle, pfd, numPfds, POLLIN);
  222179. while (! threadShouldExit())
  222180. {
  222181. if (poll (pfd, numPfds, 500) > 0)
  222182. {
  222183. snd_seq_event_t* inputEvent = 0;
  222184. snd_seq_nonblock (seqHandle, 1);
  222185. do
  222186. {
  222187. if (snd_seq_event_input (seqHandle, &inputEvent) >= 0)
  222188. {
  222189. // xxx what about SYSEXes that are too big for the buffer?
  222190. const int numBytes = snd_midi_event_decode (midiParser, buffer, maxEventSize, inputEvent);
  222191. snd_midi_event_reset_decode (midiParser);
  222192. if (numBytes > 0)
  222193. {
  222194. const MidiMessage message ((const uint8*) buffer,
  222195. numBytes,
  222196. Time::getMillisecondCounter() * 0.001);
  222197. callback->handleIncomingMidiMessage (midiInput, message);
  222198. }
  222199. snd_seq_free_event (inputEvent);
  222200. }
  222201. }
  222202. while (snd_seq_event_input_pending (seqHandle, 0) > 0);
  222203. snd_seq_free_event (inputEvent);
  222204. }
  222205. }
  222206. snd_midi_event_free (midiParser);
  222207. }
  222208. };
  222209. juce_UseDebuggingNewOperator
  222210. private:
  222211. MidiInput* const midiInput;
  222212. snd_seq_t* const seqHandle;
  222213. MidiInputCallback* const callback;
  222214. };
  222215. MidiInput::MidiInput (const String& name_)
  222216. : name (name_),
  222217. internal (0)
  222218. {
  222219. }
  222220. MidiInput::~MidiInput()
  222221. {
  222222. stop();
  222223. MidiInputThread* const thread = (MidiInputThread*) internal;
  222224. delete thread;
  222225. }
  222226. void MidiInput::start()
  222227. {
  222228. ((MidiInputThread*) internal)->startThread();
  222229. }
  222230. void MidiInput::stop()
  222231. {
  222232. ((MidiInputThread*) internal)->stopThread (3000);
  222233. }
  222234. int MidiInput::getDefaultDeviceIndex()
  222235. {
  222236. return 0;
  222237. }
  222238. const StringArray MidiInput::getDevices()
  222239. {
  222240. StringArray devices;
  222241. iterateDevices (true, devices, -1);
  222242. return devices;
  222243. }
  222244. MidiInput* MidiInput::openDevice (int deviceIndex, MidiInputCallback* callback)
  222245. {
  222246. MidiInput* newDevice = 0;
  222247. StringArray devices;
  222248. snd_seq_t* const handle = iterateDevices (true, devices, deviceIndex);
  222249. if (handle != 0)
  222250. {
  222251. newDevice = new MidiInput (devices [deviceIndex]);
  222252. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  222253. }
  222254. return newDevice;
  222255. }
  222256. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  222257. {
  222258. MidiInput* newDevice = 0;
  222259. snd_seq_t* const handle = createDevice (true, deviceName);
  222260. if (handle != 0)
  222261. {
  222262. newDevice = new MidiInput (deviceName);
  222263. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  222264. }
  222265. return newDevice;
  222266. }
  222267. #else
  222268. // (These are just stub functions if ALSA is unavailable...)
  222269. const StringArray MidiOutput::getDevices() { return StringArray(); }
  222270. int MidiOutput::getDefaultDeviceIndex() { return 0; }
  222271. MidiOutput* MidiOutput::openDevice (int) { return 0; }
  222272. MidiOutput* MidiOutput::createNewDevice (const String&) { return 0; }
  222273. MidiOutput::~MidiOutput() {}
  222274. void MidiOutput::reset() {}
  222275. bool MidiOutput::getVolume (float&, float&) { return false; }
  222276. void MidiOutput::setVolume (float, float) {}
  222277. void MidiOutput::sendMessageNow (const MidiMessage&) {}
  222278. MidiInput::MidiInput (const String& name_) : name (name_), internal (0) {}
  222279. MidiInput::~MidiInput() {}
  222280. void MidiInput::start() {}
  222281. void MidiInput::stop() {}
  222282. int MidiInput::getDefaultDeviceIndex() { return 0; }
  222283. const StringArray MidiInput::getDevices() { return StringArray(); }
  222284. MidiInput* MidiInput::openDevice (int, MidiInputCallback*) { return 0; }
  222285. MidiInput* MidiInput::createNewDevice (const String&, MidiInputCallback*) { return 0; }
  222286. #endif
  222287. #endif
  222288. /*** End of inlined file: juce_linux_Midi.cpp ***/
  222289. /*** Start of inlined file: juce_linux_AudioCDReader.cpp ***/
  222290. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222291. // compiled on its own).
  222292. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  222293. AudioCDReader::AudioCDReader()
  222294. : AudioFormatReader (0, "CD Audio")
  222295. {
  222296. }
  222297. const StringArray AudioCDReader::getAvailableCDNames()
  222298. {
  222299. StringArray names;
  222300. return names;
  222301. }
  222302. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  222303. {
  222304. return 0;
  222305. }
  222306. AudioCDReader::~AudioCDReader()
  222307. {
  222308. }
  222309. void AudioCDReader::refreshTrackLengths()
  222310. {
  222311. }
  222312. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  222313. int64 startSampleInFile, int numSamples)
  222314. {
  222315. return false;
  222316. }
  222317. bool AudioCDReader::isCDStillPresent() const
  222318. {
  222319. return false;
  222320. }
  222321. int AudioCDReader::getNumTracks() const
  222322. {
  222323. return 0;
  222324. }
  222325. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  222326. {
  222327. return 0;
  222328. }
  222329. bool AudioCDReader::isTrackAudio (int trackNum) const
  222330. {
  222331. return false;
  222332. }
  222333. void AudioCDReader::enableIndexScanning (bool b)
  222334. {
  222335. }
  222336. int AudioCDReader::getLastIndex() const
  222337. {
  222338. return 0;
  222339. }
  222340. const Array<int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  222341. {
  222342. return Array<int>();
  222343. }
  222344. int AudioCDReader::getCDDBId()
  222345. {
  222346. return 0;
  222347. }
  222348. #endif
  222349. /*** End of inlined file: juce_linux_AudioCDReader.cpp ***/
  222350. /*** Start of inlined file: juce_linux_FileChooser.cpp ***/
  222351. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222352. // compiled on its own).
  222353. #if JUCE_INCLUDED_FILE
  222354. void FileChooser::showPlatformDialog (Array<File>& results,
  222355. const String& title,
  222356. const File& file,
  222357. const String& filters,
  222358. bool isDirectory,
  222359. bool selectsFiles,
  222360. bool isSave,
  222361. bool warnAboutOverwritingExistingFiles,
  222362. bool selectMultipleFiles,
  222363. FilePreviewComponent* previewComponent)
  222364. {
  222365. const String separator (":");
  222366. String command ("zenity --file-selection");
  222367. if (title.isNotEmpty())
  222368. command << " --title=\"" << title << "\"";
  222369. if (file != File::nonexistent)
  222370. command << " --filename=\"" << file.getFullPathName () << "\"";
  222371. if (isDirectory)
  222372. command << " --directory";
  222373. if (isSave)
  222374. command << " --save";
  222375. if (selectMultipleFiles)
  222376. command << " --multiple --separator=\"" << separator << "\"";
  222377. command << " 2>&1";
  222378. MemoryOutputStream result;
  222379. int status = -1;
  222380. FILE* stream = popen (command.toUTF8(), "r");
  222381. if (stream != 0)
  222382. {
  222383. for (;;)
  222384. {
  222385. char buffer [1024];
  222386. const int bytesRead = fread (buffer, 1, sizeof (buffer), stream);
  222387. if (bytesRead <= 0)
  222388. break;
  222389. result.write (buffer, bytesRead);
  222390. }
  222391. status = pclose (stream);
  222392. }
  222393. if (status == 0)
  222394. {
  222395. StringArray tokens;
  222396. if (selectMultipleFiles)
  222397. tokens.addTokens (result.toUTF8(), separator, String::empty);
  222398. else
  222399. tokens.add (result.toUTF8());
  222400. for (int i = 0; i < tokens.size(); i++)
  222401. results.add (File (tokens[i]));
  222402. return;
  222403. }
  222404. //xxx ain't got one!
  222405. jassertfalse;
  222406. }
  222407. #endif
  222408. /*** End of inlined file: juce_linux_FileChooser.cpp ***/
  222409. /*** Start of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  222410. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222411. // compiled on its own).
  222412. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  222413. /*
  222414. Sorry.. This class isn't implemented on Linux!
  222415. */
  222416. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  222417. : browser (0),
  222418. blankPageShown (false),
  222419. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  222420. {
  222421. setOpaque (true);
  222422. }
  222423. WebBrowserComponent::~WebBrowserComponent()
  222424. {
  222425. }
  222426. void WebBrowserComponent::goToURL (const String& url,
  222427. const StringArray* headers,
  222428. const MemoryBlock* postData)
  222429. {
  222430. lastURL = url;
  222431. lastHeaders.clear();
  222432. if (headers != 0)
  222433. lastHeaders = *headers;
  222434. lastPostData.setSize (0);
  222435. if (postData != 0)
  222436. lastPostData = *postData;
  222437. blankPageShown = false;
  222438. }
  222439. void WebBrowserComponent::stop()
  222440. {
  222441. }
  222442. void WebBrowserComponent::goBack()
  222443. {
  222444. lastURL = String::empty;
  222445. blankPageShown = false;
  222446. }
  222447. void WebBrowserComponent::goForward()
  222448. {
  222449. lastURL = String::empty;
  222450. }
  222451. void WebBrowserComponent::refresh()
  222452. {
  222453. }
  222454. void WebBrowserComponent::paint (Graphics& g)
  222455. {
  222456. g.fillAll (Colours::white);
  222457. }
  222458. void WebBrowserComponent::checkWindowAssociation()
  222459. {
  222460. }
  222461. void WebBrowserComponent::reloadLastURL()
  222462. {
  222463. if (lastURL.isNotEmpty())
  222464. {
  222465. goToURL (lastURL, &lastHeaders, &lastPostData);
  222466. lastURL = String::empty;
  222467. }
  222468. }
  222469. void WebBrowserComponent::parentHierarchyChanged()
  222470. {
  222471. checkWindowAssociation();
  222472. }
  222473. void WebBrowserComponent::resized()
  222474. {
  222475. }
  222476. void WebBrowserComponent::visibilityChanged()
  222477. {
  222478. checkWindowAssociation();
  222479. }
  222480. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  222481. {
  222482. return true;
  222483. }
  222484. #endif
  222485. /*** End of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  222486. #endif
  222487. END_JUCE_NAMESPACE
  222488. #endif
  222489. /*** End of inlined file: juce_linux_NativeCode.cpp ***/
  222490. #endif
  222491. #if JUCE_MAC || JUCE_IPHONE
  222492. /*** Start of inlined file: juce_mac_NativeCode.mm ***/
  222493. /*
  222494. This file wraps together all the mac-specific code, so that
  222495. we can include all the native headers just once, and compile all our
  222496. platform-specific stuff in one big lump, keeping it out of the way of
  222497. the rest of the codebase.
  222498. */
  222499. #if JUCE_MAC || JUCE_IPHONE
  222500. BEGIN_JUCE_NAMESPACE
  222501. #undef Point
  222502. #define JUCE_INCLUDED_FILE 1
  222503. // Now include the actual code files..
  222504. /*** Start of inlined file: juce_mac_ObjCSuffix.h ***/
  222505. /** This suffix is used for naming all Obj-C classes that are used inside juce.
  222506. Because of the flat naming structure used by Obj-C, you can get horrible situations where
  222507. two DLLs are loaded into a host, each of which uses classes with the same names, and these get
  222508. cross-linked so that when you make a call to a class that you thought was private, it ends up
  222509. actually calling into a similarly named class in the other module's address space.
  222510. By changing this macro to a unique value, you ensure that all the obj-C classes in your app
  222511. have unique names, and should avoid this problem.
  222512. If you're using the amalgamated version, you can just set this macro to something unique before
  222513. you include juce_amalgamated.cpp.
  222514. */
  222515. #ifndef JUCE_ObjCExtraSuffix
  222516. #define JUCE_ObjCExtraSuffix 3
  222517. #endif
  222518. #define appendMacro1(a, b, c, d, e) a ## _ ## b ## _ ## c ## _ ## d ## _ ## e
  222519. #define appendMacro2(a, b, c, d, e) appendMacro1(a, b, c, d, e)
  222520. #define MakeObjCClassName(rootName) appendMacro2 (rootName, JUCE_MAJOR_VERSION, JUCE_MINOR_VERSION, JUCE_BUILDNUMBER, JUCE_ObjCExtraSuffix)
  222521. /*** End of inlined file: juce_mac_ObjCSuffix.h ***/
  222522. /*** Start of inlined file: juce_mac_Strings.mm ***/
  222523. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222524. // compiled on its own).
  222525. #if JUCE_INCLUDED_FILE
  222526. static const String nsStringToJuce (NSString* s)
  222527. {
  222528. return String::fromUTF8 ([s UTF8String]);
  222529. }
  222530. static NSString* juceStringToNS (const String& s)
  222531. {
  222532. return [NSString stringWithUTF8String: s.toUTF8()];
  222533. }
  222534. static const String convertUTF16ToString (const UniChar* utf16)
  222535. {
  222536. String s;
  222537. while (*utf16 != 0)
  222538. s += (juce_wchar) *utf16++;
  222539. return s;
  222540. }
  222541. const String PlatformUtilities::cfStringToJuceString (CFStringRef cfString)
  222542. {
  222543. String result;
  222544. if (cfString != 0)
  222545. {
  222546. CFRange range = { 0, CFStringGetLength (cfString) };
  222547. HeapBlock <UniChar> u (range.length + 1);
  222548. CFStringGetCharacters (cfString, range, u);
  222549. u[range.length] = 0;
  222550. result = convertUTF16ToString (u);
  222551. }
  222552. return result;
  222553. }
  222554. CFStringRef PlatformUtilities::juceStringToCFString (const String& s)
  222555. {
  222556. const int len = s.length();
  222557. HeapBlock <UniChar> temp (len + 2);
  222558. for (int i = 0; i <= len; ++i)
  222559. temp[i] = s[i];
  222560. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  222561. }
  222562. const String PlatformUtilities::convertToPrecomposedUnicode (const String& s)
  222563. {
  222564. #if JUCE_IPHONE
  222565. const ScopedAutoReleasePool pool;
  222566. return nsStringToJuce ([juceStringToNS (s) precomposedStringWithCanonicalMapping]);
  222567. #else
  222568. UnicodeMapping map;
  222569. map.unicodeEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  222570. kUnicodeNoSubset,
  222571. kTextEncodingDefaultFormat);
  222572. map.otherEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  222573. kUnicodeCanonicalCompVariant,
  222574. kTextEncodingDefaultFormat);
  222575. map.mappingVersion = kUnicodeUseLatestMapping;
  222576. UnicodeToTextInfo conversionInfo = 0;
  222577. String result;
  222578. if (CreateUnicodeToTextInfo (&map, &conversionInfo) == noErr)
  222579. {
  222580. const int len = s.length();
  222581. HeapBlock <UniChar> tempIn, tempOut;
  222582. tempIn.calloc (len + 2);
  222583. tempOut.calloc (len + 2);
  222584. for (int i = 0; i <= len; ++i)
  222585. tempIn[i] = s[i];
  222586. ByteCount bytesRead = 0;
  222587. ByteCount outputBufferSize = 0;
  222588. if (ConvertFromUnicodeToText (conversionInfo,
  222589. len * sizeof (UniChar), tempIn,
  222590. kUnicodeDefaultDirectionMask,
  222591. 0, 0, 0, 0,
  222592. len * sizeof (UniChar), &bytesRead,
  222593. &outputBufferSize, tempOut) == noErr)
  222594. {
  222595. result.preallocateStorage (bytesRead / sizeof (UniChar) + 2);
  222596. juce_wchar* t = result;
  222597. unsigned int i;
  222598. for (i = 0; i < bytesRead / sizeof (UniChar); ++i)
  222599. t[i] = (juce_wchar) tempOut[i];
  222600. t[i] = 0;
  222601. }
  222602. DisposeUnicodeToTextInfo (&conversionInfo);
  222603. }
  222604. return result;
  222605. #endif
  222606. }
  222607. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  222608. void SystemClipboard::copyTextToClipboard (const String& text)
  222609. {
  222610. #if JUCE_IPHONE
  222611. [[UIPasteboard generalPasteboard] setValue: juceStringToNS (text)
  222612. forPasteboardType: @"public.text"];
  222613. #else
  222614. [[NSPasteboard generalPasteboard] declareTypes: [NSArray arrayWithObject: NSStringPboardType]
  222615. owner: nil];
  222616. [[NSPasteboard generalPasteboard] setString: juceStringToNS (text)
  222617. forType: NSStringPboardType];
  222618. #endif
  222619. }
  222620. const String SystemClipboard::getTextFromClipboard()
  222621. {
  222622. #if JUCE_IPHONE
  222623. NSString* text = [[UIPasteboard generalPasteboard] valueForPasteboardType: @"public.text"];
  222624. #else
  222625. NSString* text = [[NSPasteboard generalPasteboard] stringForType: NSStringPboardType];
  222626. #endif
  222627. return text == 0 ? String::empty
  222628. : nsStringToJuce (text);
  222629. }
  222630. #endif
  222631. #endif
  222632. /*** End of inlined file: juce_mac_Strings.mm ***/
  222633. /*** Start of inlined file: juce_mac_SystemStats.mm ***/
  222634. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222635. // compiled on its own).
  222636. #if JUCE_INCLUDED_FILE
  222637. namespace SystemStatsHelpers
  222638. {
  222639. static int64 highResTimerFrequency = 0;
  222640. static double highResTimerToMillisecRatio = 0;
  222641. #if JUCE_INTEL
  222642. static void juce_getCpuVendor (char* const v) throw()
  222643. {
  222644. int vendor[4];
  222645. zerostruct (vendor);
  222646. int dummy = 0;
  222647. asm ("mov %%ebx, %%esi \n\t"
  222648. "cpuid \n\t"
  222649. "xchg %%esi, %%ebx"
  222650. : "=a" (dummy), "=S" (vendor[0]), "=c" (vendor[2]), "=d" (vendor[1]) : "a" (0));
  222651. memcpy (v, vendor, 16);
  222652. }
  222653. static unsigned int getCPUIDWord (unsigned int& familyModel, unsigned int& extFeatures)
  222654. {
  222655. unsigned int cpu = 0;
  222656. unsigned int ext = 0;
  222657. unsigned int family = 0;
  222658. unsigned int dummy = 0;
  222659. asm ("mov %%ebx, %%esi \n\t"
  222660. "cpuid \n\t"
  222661. "xchg %%esi, %%ebx"
  222662. : "=a" (family), "=S" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  222663. familyModel = family;
  222664. extFeatures = ext;
  222665. return cpu;
  222666. }
  222667. #endif
  222668. }
  222669. void SystemStats::initialiseStats()
  222670. {
  222671. using namespace SystemStatsHelpers;
  222672. static bool initialised = false;
  222673. if (! initialised)
  222674. {
  222675. initialised = true;
  222676. #if JUCE_MAC
  222677. // extremely annoying: adding this line stops the apple menu items from working. Of
  222678. // course, not adding it means that carbon windows (e.g. in plugins) won't get
  222679. // any events.
  222680. //NSApplicationLoad();
  222681. [NSApplication sharedApplication];
  222682. #endif
  222683. #if JUCE_INTEL
  222684. unsigned int familyModel, extFeatures;
  222685. const unsigned int features = getCPUIDWord (familyModel, extFeatures);
  222686. cpuFlags.hasMMX = ((features & (1 << 23)) != 0);
  222687. cpuFlags.hasSSE = ((features & (1 << 25)) != 0);
  222688. cpuFlags.hasSSE2 = ((features & (1 << 26)) != 0);
  222689. cpuFlags.has3DNow = ((extFeatures & (1 << 31)) != 0);
  222690. #else
  222691. cpuFlags.hasMMX = false;
  222692. cpuFlags.hasSSE = false;
  222693. cpuFlags.hasSSE2 = false;
  222694. cpuFlags.has3DNow = false;
  222695. #endif
  222696. #if JUCE_IPHONE || (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5)
  222697. cpuFlags.numCpus = (int) [[NSProcessInfo processInfo] activeProcessorCount];
  222698. #else
  222699. cpuFlags.numCpus = (int) MPProcessors();
  222700. #endif
  222701. mach_timebase_info_data_t timebase;
  222702. (void) mach_timebase_info (&timebase);
  222703. highResTimerFrequency = (int64) (1.0e9 * timebase.denom / timebase.numer);
  222704. highResTimerToMillisecRatio = timebase.numer / (1.0e6 * timebase.denom);
  222705. String s (SystemStats::getJUCEVersion());
  222706. rlimit lim;
  222707. getrlimit (RLIMIT_NOFILE, &lim);
  222708. lim.rlim_cur = lim.rlim_max = RLIM_INFINITY;
  222709. setrlimit (RLIMIT_NOFILE, &lim);
  222710. }
  222711. }
  222712. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  222713. {
  222714. return MacOSX;
  222715. }
  222716. const String SystemStats::getOperatingSystemName()
  222717. {
  222718. return "Mac OS X";
  222719. }
  222720. bool SystemStats::isOperatingSystem64Bit()
  222721. {
  222722. #if JUCE_64BIT
  222723. return true;
  222724. #else
  222725. //xxx not sure how to find this out?..
  222726. return false;
  222727. #endif
  222728. }
  222729. int SystemStats::getMemorySizeInMegabytes()
  222730. {
  222731. uint64 mem = 0;
  222732. size_t memSize = sizeof (mem);
  222733. int mib[] = { CTL_HW, HW_MEMSIZE };
  222734. sysctl (mib, 2, &mem, &memSize, 0, 0);
  222735. return (int) (mem / (1024 * 1024));
  222736. }
  222737. const String SystemStats::getCpuVendor()
  222738. {
  222739. #if JUCE_INTEL
  222740. char v [16];
  222741. SystemStatsHelpers::juce_getCpuVendor (v);
  222742. return String (v, 16);
  222743. #else
  222744. return String::empty;
  222745. #endif
  222746. }
  222747. int SystemStats::getCpuSpeedInMegaherz()
  222748. {
  222749. uint64 speedHz = 0;
  222750. size_t speedSize = sizeof (speedHz);
  222751. int mib[] = { CTL_HW, HW_CPU_FREQ };
  222752. sysctl (mib, 2, &speedHz, &speedSize, 0, 0);
  222753. #if JUCE_BIG_ENDIAN
  222754. if (speedSize == 4)
  222755. speedHz >>= 32;
  222756. #endif
  222757. return (int) (speedHz / 1000000);
  222758. }
  222759. const String SystemStats::getLogonName()
  222760. {
  222761. return nsStringToJuce (NSUserName());
  222762. }
  222763. const String SystemStats::getFullUserName()
  222764. {
  222765. return nsStringToJuce (NSFullUserName());
  222766. }
  222767. uint32 juce_millisecondsSinceStartup() throw()
  222768. {
  222769. return (uint32) (mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio);
  222770. }
  222771. double Time::getMillisecondCounterHiRes() throw()
  222772. {
  222773. return mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio;
  222774. }
  222775. int64 Time::getHighResolutionTicks() throw()
  222776. {
  222777. return (int64) mach_absolute_time();
  222778. }
  222779. int64 Time::getHighResolutionTicksPerSecond() throw()
  222780. {
  222781. return SystemStatsHelpers::highResTimerFrequency;
  222782. }
  222783. bool Time::setSystemTimeToThisTime() const
  222784. {
  222785. jassertfalse;
  222786. return false;
  222787. }
  222788. int SystemStats::getPageSize()
  222789. {
  222790. return (int) NSPageSize();
  222791. }
  222792. void PlatformUtilities::fpuReset()
  222793. {
  222794. }
  222795. #endif
  222796. /*** End of inlined file: juce_mac_SystemStats.mm ***/
  222797. /*** Start of inlined file: juce_mac_Network.mm ***/
  222798. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222799. // compiled on its own).
  222800. #if JUCE_INCLUDED_FILE
  222801. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  222802. {
  222803. #ifndef IFT_ETHER
  222804. #define IFT_ETHER 6
  222805. #endif
  222806. ifaddrs* addrs = 0;
  222807. int numResults = 0;
  222808. if (getifaddrs (&addrs) == 0)
  222809. {
  222810. const ifaddrs* cursor = addrs;
  222811. while (cursor != 0 && numResults < maxNum)
  222812. {
  222813. sockaddr_storage* sto = (sockaddr_storage*) cursor->ifa_addr;
  222814. if (sto->ss_family == AF_LINK)
  222815. {
  222816. const sockaddr_dl* const sadd = (const sockaddr_dl*) cursor->ifa_addr;
  222817. if (sadd->sdl_type == IFT_ETHER)
  222818. {
  222819. const uint8* const addr = ((const uint8*) sadd->sdl_data) + sadd->sdl_nlen;
  222820. uint64 a = 0;
  222821. for (int i = 6; --i >= 0;)
  222822. a = (a << 8) | addr [littleEndian ? i : (5 - i)];
  222823. *addresses++ = (int64) a;
  222824. ++numResults;
  222825. }
  222826. }
  222827. cursor = cursor->ifa_next;
  222828. }
  222829. freeifaddrs (addrs);
  222830. }
  222831. return numResults;
  222832. }
  222833. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  222834. const String& emailSubject,
  222835. const String& bodyText,
  222836. const StringArray& filesToAttach)
  222837. {
  222838. #if JUCE_IPHONE
  222839. //xxx probably need to use MFMailComposeViewController
  222840. jassertfalse;
  222841. return false;
  222842. #else
  222843. const ScopedAutoReleasePool pool;
  222844. String script;
  222845. script << "tell application \"Mail\"\r\n"
  222846. "set newMessage to make new outgoing message with properties {subject:\""
  222847. << emailSubject.replace ("\"", "\\\"")
  222848. << "\", content:\""
  222849. << bodyText.replace ("\"", "\\\"")
  222850. << "\" & return & return}\r\n"
  222851. "tell newMessage\r\n"
  222852. "set visible to true\r\n"
  222853. "set sender to \"sdfsdfsdfewf\"\r\n"
  222854. "make new to recipient at end of to recipients with properties {address:\""
  222855. << targetEmailAddress
  222856. << "\"}\r\n";
  222857. for (int i = 0; i < filesToAttach.size(); ++i)
  222858. {
  222859. script << "tell content\r\n"
  222860. "make new attachment with properties {file name:\""
  222861. << filesToAttach[i].replace ("\"", "\\\"")
  222862. << "\"} at after the last paragraph\r\n"
  222863. "end tell\r\n";
  222864. }
  222865. script << "end tell\r\n"
  222866. "end tell\r\n";
  222867. NSAppleScript* s = [[NSAppleScript alloc]
  222868. initWithSource: juceStringToNS (script)];
  222869. NSDictionary* error = 0;
  222870. const bool ok = [s executeAndReturnError: &error] != nil;
  222871. [s release];
  222872. return ok;
  222873. #endif
  222874. }
  222875. END_JUCE_NAMESPACE
  222876. using namespace JUCE_NAMESPACE;
  222877. #define JuceURLConnection MakeObjCClassName(JuceURLConnection)
  222878. @interface JuceURLConnection : NSObject
  222879. {
  222880. @public
  222881. NSURLRequest* request;
  222882. NSURLConnection* connection;
  222883. NSMutableData* data;
  222884. Thread* runLoopThread;
  222885. bool initialised, hasFailed, hasFinished;
  222886. int position;
  222887. int64 contentLength;
  222888. NSDictionary* headers;
  222889. NSLock* dataLock;
  222890. }
  222891. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req withCallback: (URL::OpenStreamProgressCallback*) callback withContext: (void*) context;
  222892. - (void) dealloc;
  222893. - (void) connection: (NSURLConnection*) connection didReceiveResponse: (NSURLResponse*) response;
  222894. - (void) connection: (NSURLConnection*) connection didFailWithError: (NSError*) error;
  222895. - (void) connection: (NSURLConnection*) connection didReceiveData: (NSData*) data;
  222896. - (void) connectionDidFinishLoading: (NSURLConnection*) connection;
  222897. - (BOOL) isOpen;
  222898. - (int) read: (char*) dest numBytes: (int) num;
  222899. - (int) readPosition;
  222900. - (void) stop;
  222901. - (void) createConnection;
  222902. @end
  222903. class JuceURLConnectionMessageThread : public Thread
  222904. {
  222905. JuceURLConnection* owner;
  222906. public:
  222907. JuceURLConnectionMessageThread (JuceURLConnection* owner_)
  222908. : Thread ("http connection"),
  222909. owner (owner_)
  222910. {
  222911. }
  222912. ~JuceURLConnectionMessageThread()
  222913. {
  222914. stopThread (10000);
  222915. }
  222916. void run()
  222917. {
  222918. [owner createConnection];
  222919. while (! threadShouldExit())
  222920. {
  222921. const ScopedAutoReleasePool pool;
  222922. [[NSRunLoop currentRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  222923. }
  222924. }
  222925. };
  222926. @implementation JuceURLConnection
  222927. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req
  222928. withCallback: (URL::OpenStreamProgressCallback*) callback
  222929. withContext: (void*) context;
  222930. {
  222931. [super init];
  222932. request = req;
  222933. [request retain];
  222934. data = [[NSMutableData data] retain];
  222935. dataLock = [[NSLock alloc] init];
  222936. connection = 0;
  222937. initialised = false;
  222938. hasFailed = false;
  222939. hasFinished = false;
  222940. contentLength = -1;
  222941. headers = 0;
  222942. runLoopThread = new JuceURLConnectionMessageThread (self);
  222943. runLoopThread->startThread();
  222944. while (runLoopThread->isThreadRunning() && ! initialised)
  222945. {
  222946. if (callback != 0)
  222947. callback (context, -1, (int) [[request HTTPBody] length]);
  222948. Thread::sleep (1);
  222949. }
  222950. return self;
  222951. }
  222952. - (void) dealloc
  222953. {
  222954. [self stop];
  222955. deleteAndZero (runLoopThread);
  222956. [connection release];
  222957. [data release];
  222958. [dataLock release];
  222959. [request release];
  222960. [headers release];
  222961. [super dealloc];
  222962. }
  222963. - (void) createConnection
  222964. {
  222965. NSInteger oldRetainCount = [self retainCount];
  222966. connection = [[NSURLConnection alloc] initWithRequest: request
  222967. delegate: self];
  222968. if (oldRetainCount == [self retainCount])
  222969. [self retain]; // newer SDK should already retain this, but there were problems in older versions..
  222970. if (connection == nil)
  222971. runLoopThread->signalThreadShouldExit();
  222972. }
  222973. - (void) connection: (NSURLConnection*) conn didReceiveResponse: (NSURLResponse*) response
  222974. {
  222975. (void) conn;
  222976. [dataLock lock];
  222977. [data setLength: 0];
  222978. [dataLock unlock];
  222979. initialised = true;
  222980. contentLength = [response expectedContentLength];
  222981. [headers release];
  222982. headers = 0;
  222983. if ([response isKindOfClass: [NSHTTPURLResponse class]])
  222984. headers = [[((NSHTTPURLResponse*) response) allHeaderFields] retain];
  222985. }
  222986. - (void) connection: (NSURLConnection*) conn didFailWithError: (NSError*) error
  222987. {
  222988. (void) conn;
  222989. DBG (nsStringToJuce ([error description]));
  222990. hasFailed = true;
  222991. initialised = true;
  222992. if (runLoopThread != 0)
  222993. runLoopThread->signalThreadShouldExit();
  222994. }
  222995. - (void) connection: (NSURLConnection*) conn didReceiveData: (NSData*) newData
  222996. {
  222997. (void) conn;
  222998. [dataLock lock];
  222999. [data appendData: newData];
  223000. [dataLock unlock];
  223001. initialised = true;
  223002. }
  223003. - (void) connectionDidFinishLoading: (NSURLConnection*) conn
  223004. {
  223005. (void) conn;
  223006. hasFinished = true;
  223007. initialised = true;
  223008. if (runLoopThread != 0)
  223009. runLoopThread->signalThreadShouldExit();
  223010. }
  223011. - (BOOL) isOpen
  223012. {
  223013. return connection != 0 && ! hasFailed;
  223014. }
  223015. - (int) readPosition
  223016. {
  223017. return position;
  223018. }
  223019. - (int) read: (char*) dest numBytes: (int) numNeeded
  223020. {
  223021. int numDone = 0;
  223022. while (numNeeded > 0)
  223023. {
  223024. int available = jmin (numNeeded, (int) [data length]);
  223025. if (available > 0)
  223026. {
  223027. [dataLock lock];
  223028. [data getBytes: dest length: available];
  223029. [data replaceBytesInRange: NSMakeRange (0, available) withBytes: nil length: 0];
  223030. [dataLock unlock];
  223031. numDone += available;
  223032. numNeeded -= available;
  223033. dest += available;
  223034. }
  223035. else
  223036. {
  223037. if (hasFailed || hasFinished)
  223038. break;
  223039. Thread::sleep (1);
  223040. }
  223041. }
  223042. position += numDone;
  223043. return numDone;
  223044. }
  223045. - (void) stop
  223046. {
  223047. [connection cancel];
  223048. if (runLoopThread != 0)
  223049. runLoopThread->stopThread (10000);
  223050. }
  223051. @end
  223052. BEGIN_JUCE_NAMESPACE
  223053. void* juce_openInternetFile (const String& url,
  223054. const String& headers,
  223055. const MemoryBlock& postData,
  223056. const bool isPost,
  223057. URL::OpenStreamProgressCallback* callback,
  223058. void* callbackContext,
  223059. int timeOutMs)
  223060. {
  223061. const ScopedAutoReleasePool pool;
  223062. NSMutableURLRequest* req = [NSMutableURLRequest
  223063. requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  223064. cachePolicy: NSURLRequestUseProtocolCachePolicy
  223065. timeoutInterval: timeOutMs <= 0 ? 60.0 : (timeOutMs / 1000.0)];
  223066. if (req == nil)
  223067. return 0;
  223068. [req setHTTPMethod: isPost ? @"POST" : @"GET"];
  223069. //[req setCachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData];
  223070. StringArray headerLines;
  223071. headerLines.addLines (headers);
  223072. headerLines.removeEmptyStrings (true);
  223073. for (int i = 0; i < headerLines.size(); ++i)
  223074. {
  223075. const String key (headerLines[i].upToFirstOccurrenceOf (":", false, false).trim());
  223076. const String value (headerLines[i].fromFirstOccurrenceOf (":", false, false).trim());
  223077. if (key.isNotEmpty() && value.isNotEmpty())
  223078. [req addValue: juceStringToNS (value) forHTTPHeaderField: juceStringToNS (key)];
  223079. }
  223080. if (isPost && postData.getSize() > 0)
  223081. {
  223082. [req setHTTPBody: [NSData dataWithBytes: postData.getData()
  223083. length: postData.getSize()]];
  223084. }
  223085. JuceURLConnection* const s = [[JuceURLConnection alloc] initWithRequest: req
  223086. withCallback: callback
  223087. withContext: callbackContext];
  223088. if ([s isOpen])
  223089. return s;
  223090. [s release];
  223091. return 0;
  223092. }
  223093. void juce_closeInternetFile (void* handle)
  223094. {
  223095. JuceURLConnection* const s = (JuceURLConnection*) handle;
  223096. if (s != 0)
  223097. {
  223098. const ScopedAutoReleasePool pool;
  223099. [s stop];
  223100. [s release];
  223101. }
  223102. }
  223103. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  223104. {
  223105. JuceURLConnection* const s = (JuceURLConnection*) handle;
  223106. if (s != 0)
  223107. {
  223108. const ScopedAutoReleasePool pool;
  223109. return [s read: (char*) buffer numBytes: bytesToRead];
  223110. }
  223111. return 0;
  223112. }
  223113. int64 juce_getInternetFileContentLength (void* handle)
  223114. {
  223115. JuceURLConnection* const s = (JuceURLConnection*) handle;
  223116. if (s != 0)
  223117. return s->contentLength;
  223118. return -1;
  223119. }
  223120. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  223121. {
  223122. JuceURLConnection* const s = (JuceURLConnection*) handle;
  223123. if (s != 0 && s->headers != 0)
  223124. {
  223125. NSEnumerator* enumerator = [s->headers keyEnumerator];
  223126. NSString* key;
  223127. while ((key = [enumerator nextObject]) != nil)
  223128. headers.set (nsStringToJuce (key),
  223129. nsStringToJuce ((NSString*) [s->headers objectForKey: key]));
  223130. }
  223131. }
  223132. int juce_seekInInternetFile (void* handle, int /*newPosition*/)
  223133. {
  223134. JuceURLConnection* const s = (JuceURLConnection*) handle;
  223135. if (s != 0)
  223136. return [s readPosition];
  223137. return 0;
  223138. }
  223139. #endif
  223140. /*** End of inlined file: juce_mac_Network.mm ***/
  223141. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  223142. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223143. // compiled on its own).
  223144. #if JUCE_INCLUDED_FILE
  223145. struct NamedPipeInternal
  223146. {
  223147. String pipeInName, pipeOutName;
  223148. int pipeIn, pipeOut;
  223149. bool volatile createdPipe, blocked, stopReadOperation;
  223150. static void signalHandler (int) {}
  223151. };
  223152. void NamedPipe::cancelPendingReads()
  223153. {
  223154. while (internal != 0 && ((NamedPipeInternal*) internal)->blocked)
  223155. {
  223156. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  223157. intern->stopReadOperation = true;
  223158. char buffer [1] = { 0 };
  223159. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  223160. (void) bytesWritten;
  223161. int timeout = 2000;
  223162. while (intern->blocked && --timeout >= 0)
  223163. Thread::sleep (2);
  223164. intern->stopReadOperation = false;
  223165. }
  223166. }
  223167. void NamedPipe::close()
  223168. {
  223169. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  223170. if (intern != 0)
  223171. {
  223172. internal = 0;
  223173. if (intern->pipeIn != -1)
  223174. ::close (intern->pipeIn);
  223175. if (intern->pipeOut != -1)
  223176. ::close (intern->pipeOut);
  223177. if (intern->createdPipe)
  223178. {
  223179. unlink (intern->pipeInName.toUTF8());
  223180. unlink (intern->pipeOutName.toUTF8());
  223181. }
  223182. delete intern;
  223183. }
  223184. }
  223185. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  223186. {
  223187. close();
  223188. NamedPipeInternal* const intern = new NamedPipeInternal();
  223189. internal = intern;
  223190. intern->createdPipe = createPipe;
  223191. intern->blocked = false;
  223192. intern->stopReadOperation = false;
  223193. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  223194. siginterrupt (SIGPIPE, 1);
  223195. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  223196. intern->pipeInName = pipePath + "_in";
  223197. intern->pipeOutName = pipePath + "_out";
  223198. intern->pipeIn = -1;
  223199. intern->pipeOut = -1;
  223200. if (createPipe)
  223201. {
  223202. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  223203. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  223204. {
  223205. delete intern;
  223206. internal = 0;
  223207. return false;
  223208. }
  223209. }
  223210. return true;
  223211. }
  223212. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  223213. {
  223214. int bytesRead = -1;
  223215. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  223216. if (intern != 0)
  223217. {
  223218. intern->blocked = true;
  223219. if (intern->pipeIn == -1)
  223220. {
  223221. if (intern->createdPipe)
  223222. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  223223. else
  223224. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  223225. if (intern->pipeIn == -1)
  223226. {
  223227. intern->blocked = false;
  223228. return -1;
  223229. }
  223230. }
  223231. bytesRead = 0;
  223232. char* p = (char*) destBuffer;
  223233. while (bytesRead < maxBytesToRead)
  223234. {
  223235. const int bytesThisTime = maxBytesToRead - bytesRead;
  223236. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  223237. if (numRead <= 0 || intern->stopReadOperation)
  223238. {
  223239. bytesRead = -1;
  223240. break;
  223241. }
  223242. bytesRead += numRead;
  223243. p += bytesRead;
  223244. }
  223245. intern->blocked = false;
  223246. }
  223247. return bytesRead;
  223248. }
  223249. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  223250. {
  223251. int bytesWritten = -1;
  223252. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  223253. if (intern != 0)
  223254. {
  223255. if (intern->pipeOut == -1)
  223256. {
  223257. if (intern->createdPipe)
  223258. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  223259. else
  223260. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  223261. if (intern->pipeOut == -1)
  223262. {
  223263. return -1;
  223264. }
  223265. }
  223266. const char* p = (const char*) sourceBuffer;
  223267. bytesWritten = 0;
  223268. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  223269. while (bytesWritten < numBytesToWrite
  223270. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  223271. {
  223272. const int bytesThisTime = numBytesToWrite - bytesWritten;
  223273. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  223274. if (numWritten <= 0)
  223275. {
  223276. bytesWritten = -1;
  223277. break;
  223278. }
  223279. bytesWritten += numWritten;
  223280. p += bytesWritten;
  223281. }
  223282. }
  223283. return bytesWritten;
  223284. }
  223285. #endif
  223286. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  223287. /*** Start of inlined file: juce_mac_Threads.mm ***/
  223288. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223289. // compiled on its own).
  223290. #if JUCE_INCLUDED_FILE
  223291. /*
  223292. Note that a lot of methods that you'd expect to find in this file actually
  223293. live in juce_posix_SharedCode.h!
  223294. */
  223295. void JUCE_API juce_threadEntryPoint (void*);
  223296. void* threadEntryProc (void* userData)
  223297. {
  223298. const ScopedAutoReleasePool pool;
  223299. juce_threadEntryPoint (userData);
  223300. return 0;
  223301. }
  223302. void* juce_createThread (void* userData)
  223303. {
  223304. pthread_t handle = 0;
  223305. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  223306. {
  223307. pthread_detach (handle);
  223308. return (void*) handle;
  223309. }
  223310. return 0;
  223311. }
  223312. void juce_killThread (void* handle)
  223313. {
  223314. if (handle != 0)
  223315. pthread_cancel ((pthread_t) handle);
  223316. }
  223317. void juce_setCurrentThreadName (const String& /*name*/)
  223318. {
  223319. }
  223320. bool juce_setThreadPriority (void* handle, int priority)
  223321. {
  223322. if (handle == 0)
  223323. handle = (void*) pthread_self();
  223324. struct sched_param param;
  223325. int policy;
  223326. pthread_getschedparam ((pthread_t) handle, &policy, &param);
  223327. param.sched_priority = jlimit (1, 127, 1 + (priority * 126) / 11);
  223328. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  223329. }
  223330. Thread::ThreadID Thread::getCurrentThreadId()
  223331. {
  223332. return static_cast <ThreadID> (pthread_self());
  223333. }
  223334. void Thread::yield()
  223335. {
  223336. sched_yield();
  223337. }
  223338. void Thread::setCurrentThreadAffinityMask (const uint32 /*affinityMask*/)
  223339. {
  223340. // xxx
  223341. jassertfalse;
  223342. }
  223343. bool Process::isForegroundProcess()
  223344. {
  223345. #if JUCE_MAC
  223346. return [NSApp isActive];
  223347. #else
  223348. return true; // xxx change this if more than one app is ever possible on the iPhone!
  223349. #endif
  223350. }
  223351. void Process::raisePrivilege()
  223352. {
  223353. jassertfalse;
  223354. }
  223355. void Process::lowerPrivilege()
  223356. {
  223357. jassertfalse;
  223358. }
  223359. void Process::terminate()
  223360. {
  223361. exit (0);
  223362. }
  223363. void Process::setPriority (ProcessPriority)
  223364. {
  223365. // xxx
  223366. }
  223367. #endif
  223368. /*** End of inlined file: juce_mac_Threads.mm ***/
  223369. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  223370. /*
  223371. This file contains posix routines that are common to both the Linux and Mac builds.
  223372. It gets included directly in the cpp files for these platforms.
  223373. */
  223374. CriticalSection::CriticalSection() throw()
  223375. {
  223376. pthread_mutexattr_t atts;
  223377. pthread_mutexattr_init (&atts);
  223378. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  223379. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  223380. pthread_mutex_init (&internal, &atts);
  223381. }
  223382. CriticalSection::~CriticalSection() throw()
  223383. {
  223384. pthread_mutex_destroy (&internal);
  223385. }
  223386. void CriticalSection::enter() const throw()
  223387. {
  223388. pthread_mutex_lock (&internal);
  223389. }
  223390. bool CriticalSection::tryEnter() const throw()
  223391. {
  223392. return pthread_mutex_trylock (&internal) == 0;
  223393. }
  223394. void CriticalSection::exit() const throw()
  223395. {
  223396. pthread_mutex_unlock (&internal);
  223397. }
  223398. class WaitableEventImpl
  223399. {
  223400. public:
  223401. WaitableEventImpl (const bool manualReset_)
  223402. : triggered (false),
  223403. manualReset (manualReset_)
  223404. {
  223405. pthread_cond_init (&condition, 0);
  223406. pthread_mutexattr_t atts;
  223407. pthread_mutexattr_init (&atts);
  223408. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  223409. pthread_mutex_init (&mutex, &atts);
  223410. }
  223411. ~WaitableEventImpl()
  223412. {
  223413. pthread_cond_destroy (&condition);
  223414. pthread_mutex_destroy (&mutex);
  223415. }
  223416. bool wait (const int timeOutMillisecs) throw()
  223417. {
  223418. pthread_mutex_lock (&mutex);
  223419. if (! triggered)
  223420. {
  223421. if (timeOutMillisecs < 0)
  223422. {
  223423. do
  223424. {
  223425. pthread_cond_wait (&condition, &mutex);
  223426. }
  223427. while (! triggered);
  223428. }
  223429. else
  223430. {
  223431. struct timeval now;
  223432. gettimeofday (&now, 0);
  223433. struct timespec time;
  223434. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  223435. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  223436. if (time.tv_nsec >= 1000000000)
  223437. {
  223438. time.tv_nsec -= 1000000000;
  223439. time.tv_sec++;
  223440. }
  223441. do
  223442. {
  223443. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  223444. {
  223445. pthread_mutex_unlock (&mutex);
  223446. return false;
  223447. }
  223448. }
  223449. while (! triggered);
  223450. }
  223451. }
  223452. if (! manualReset)
  223453. triggered = false;
  223454. pthread_mutex_unlock (&mutex);
  223455. return true;
  223456. }
  223457. void signal() throw()
  223458. {
  223459. pthread_mutex_lock (&mutex);
  223460. triggered = true;
  223461. pthread_cond_broadcast (&condition);
  223462. pthread_mutex_unlock (&mutex);
  223463. }
  223464. void reset() throw()
  223465. {
  223466. pthread_mutex_lock (&mutex);
  223467. triggered = false;
  223468. pthread_mutex_unlock (&mutex);
  223469. }
  223470. private:
  223471. pthread_cond_t condition;
  223472. pthread_mutex_t mutex;
  223473. bool triggered;
  223474. const bool manualReset;
  223475. WaitableEventImpl (const WaitableEventImpl&);
  223476. WaitableEventImpl& operator= (const WaitableEventImpl&);
  223477. };
  223478. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  223479. : internal (new WaitableEventImpl (manualReset))
  223480. {
  223481. }
  223482. WaitableEvent::~WaitableEvent() throw()
  223483. {
  223484. delete static_cast <WaitableEventImpl*> (internal);
  223485. }
  223486. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  223487. {
  223488. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  223489. }
  223490. void WaitableEvent::signal() const throw()
  223491. {
  223492. static_cast <WaitableEventImpl*> (internal)->signal();
  223493. }
  223494. void WaitableEvent::reset() const throw()
  223495. {
  223496. static_cast <WaitableEventImpl*> (internal)->reset();
  223497. }
  223498. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  223499. {
  223500. struct timespec time;
  223501. time.tv_sec = millisecs / 1000;
  223502. time.tv_nsec = (millisecs % 1000) * 1000000;
  223503. nanosleep (&time, 0);
  223504. }
  223505. const juce_wchar File::separator = '/';
  223506. const String File::separatorString ("/");
  223507. const File File::getCurrentWorkingDirectory()
  223508. {
  223509. HeapBlock<char> heapBuffer;
  223510. char localBuffer [1024];
  223511. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  223512. int bufferSize = 4096;
  223513. while (cwd == 0 && errno == ERANGE)
  223514. {
  223515. heapBuffer.malloc (bufferSize);
  223516. cwd = getcwd (heapBuffer, bufferSize - 1);
  223517. bufferSize += 1024;
  223518. }
  223519. return File (String::fromUTF8 (cwd));
  223520. }
  223521. bool File::setAsCurrentWorkingDirectory() const
  223522. {
  223523. return chdir (getFullPathName().toUTF8()) == 0;
  223524. }
  223525. static bool juce_stat (const String& fileName, struct stat& info)
  223526. {
  223527. return fileName.isNotEmpty()
  223528. && (stat (fileName.toUTF8(), &info) == 0);
  223529. }
  223530. bool File::isDirectory() const
  223531. {
  223532. struct stat info;
  223533. return fullPath.isEmpty()
  223534. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  223535. }
  223536. bool File::exists() const
  223537. {
  223538. return fullPath.isNotEmpty()
  223539. && access (fullPath.toUTF8(), F_OK) == 0;
  223540. }
  223541. bool File::existsAsFile() const
  223542. {
  223543. return exists() && ! isDirectory();
  223544. }
  223545. int64 File::getSize() const
  223546. {
  223547. struct stat info;
  223548. return juce_stat (fullPath, info) ? info.st_size : 0;
  223549. }
  223550. bool File::hasWriteAccess() const
  223551. {
  223552. if (exists())
  223553. return access (fullPath.toUTF8(), W_OK) == 0;
  223554. if ((! isDirectory()) && fullPath.containsChar (separator))
  223555. return getParentDirectory().hasWriteAccess();
  223556. return false;
  223557. }
  223558. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  223559. {
  223560. struct stat info;
  223561. const int res = stat (fullPath.toUTF8(), &info);
  223562. if (res != 0)
  223563. return false;
  223564. info.st_mode &= 0777; // Just permissions
  223565. if (shouldBeReadOnly)
  223566. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  223567. else
  223568. // Give everybody write permission?
  223569. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  223570. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  223571. }
  223572. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  223573. {
  223574. modificationTime = 0;
  223575. accessTime = 0;
  223576. creationTime = 0;
  223577. struct stat info;
  223578. const int res = stat (fullPath.toUTF8(), &info);
  223579. if (res == 0)
  223580. {
  223581. modificationTime = (int64) info.st_mtime * 1000;
  223582. accessTime = (int64) info.st_atime * 1000;
  223583. creationTime = (int64) info.st_ctime * 1000;
  223584. }
  223585. }
  223586. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  223587. {
  223588. struct utimbuf times;
  223589. times.actime = (time_t) (accessTime / 1000);
  223590. times.modtime = (time_t) (modificationTime / 1000);
  223591. return utime (fullPath.toUTF8(), &times) == 0;
  223592. }
  223593. bool File::deleteFile() const
  223594. {
  223595. if (! exists())
  223596. return true;
  223597. else if (isDirectory())
  223598. return rmdir (fullPath.toUTF8()) == 0;
  223599. else
  223600. return remove (fullPath.toUTF8()) == 0;
  223601. }
  223602. bool File::moveInternal (const File& dest) const
  223603. {
  223604. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  223605. return true;
  223606. if (hasWriteAccess() && copyInternal (dest))
  223607. {
  223608. if (deleteFile())
  223609. return true;
  223610. dest.deleteFile();
  223611. }
  223612. return false;
  223613. }
  223614. void File::createDirectoryInternal (const String& fileName) const
  223615. {
  223616. mkdir (fileName.toUTF8(), 0777);
  223617. }
  223618. void* juce_fileOpen (const File& file, bool forWriting)
  223619. {
  223620. int flags = O_RDONLY;
  223621. if (forWriting)
  223622. {
  223623. if (file.exists())
  223624. {
  223625. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  223626. if (f != -1)
  223627. lseek (f, 0, SEEK_END);
  223628. return (void*) f;
  223629. }
  223630. else
  223631. {
  223632. flags = O_RDWR + O_CREAT;
  223633. }
  223634. }
  223635. return (void*) open (file.getFullPathName().toUTF8(), flags, 00644);
  223636. }
  223637. void juce_fileClose (void* handle)
  223638. {
  223639. if (handle != 0)
  223640. close ((int) (pointer_sized_int) handle);
  223641. }
  223642. int juce_fileRead (void* handle, void* buffer, int size)
  223643. {
  223644. if (handle != 0)
  223645. return jmax (0, (int) read ((int) (pointer_sized_int) handle, buffer, size));
  223646. return 0;
  223647. }
  223648. int juce_fileWrite (void* handle, const void* buffer, int size)
  223649. {
  223650. if (handle != 0)
  223651. return (int) write ((int) (pointer_sized_int) handle, buffer, size);
  223652. return 0;
  223653. }
  223654. int64 juce_fileSetPosition (void* handle, int64 pos)
  223655. {
  223656. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  223657. return pos;
  223658. return -1;
  223659. }
  223660. int64 FileOutputStream::getPositionInternal() const
  223661. {
  223662. if (fileHandle != 0)
  223663. return lseek ((int) (pointer_sized_int) fileHandle, 0, SEEK_CUR);
  223664. return -1;
  223665. }
  223666. void FileOutputStream::flushInternal()
  223667. {
  223668. if (fileHandle != 0)
  223669. fsync ((int) (pointer_sized_int) fileHandle);
  223670. }
  223671. const File juce_getExecutableFile()
  223672. {
  223673. Dl_info exeInfo;
  223674. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  223675. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  223676. }
  223677. // if this file doesn't exist, find a parent of it that does..
  223678. static bool juce_doStatFS (File f, struct statfs& result)
  223679. {
  223680. for (int i = 5; --i >= 0;)
  223681. {
  223682. if (f.exists())
  223683. break;
  223684. f = f.getParentDirectory();
  223685. }
  223686. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  223687. }
  223688. int64 File::getBytesFreeOnVolume() const
  223689. {
  223690. struct statfs buf;
  223691. if (juce_doStatFS (*this, buf))
  223692. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  223693. return 0;
  223694. }
  223695. int64 File::getVolumeTotalSize() const
  223696. {
  223697. struct statfs buf;
  223698. if (juce_doStatFS (*this, buf))
  223699. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  223700. return 0;
  223701. }
  223702. const String File::getVolumeLabel() const
  223703. {
  223704. #if JUCE_MAC
  223705. struct VolAttrBuf
  223706. {
  223707. u_int32_t length;
  223708. attrreference_t mountPointRef;
  223709. char mountPointSpace [MAXPATHLEN];
  223710. } attrBuf;
  223711. struct attrlist attrList;
  223712. zerostruct (attrList);
  223713. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  223714. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  223715. File f (*this);
  223716. for (;;)
  223717. {
  223718. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  223719. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  223720. (int) attrBuf.mountPointRef.attr_length);
  223721. const File parent (f.getParentDirectory());
  223722. if (f == parent)
  223723. break;
  223724. f = parent;
  223725. }
  223726. #endif
  223727. return String::empty;
  223728. }
  223729. int File::getVolumeSerialNumber() const
  223730. {
  223731. return 0; // xxx
  223732. }
  223733. void juce_runSystemCommand (const String& command)
  223734. {
  223735. int result = system (command.toUTF8());
  223736. (void) result;
  223737. }
  223738. const String juce_getOutputFromCommand (const String& command)
  223739. {
  223740. // slight bodge here, as we just pipe the output into a temp file and read it...
  223741. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  223742. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  223743. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  223744. String result (tempFile.loadFileAsString());
  223745. tempFile.deleteFile();
  223746. return result;
  223747. }
  223748. class InterProcessLock::Pimpl
  223749. {
  223750. public:
  223751. Pimpl (const String& name, const int timeOutMillisecs)
  223752. : handle (0), refCount (1)
  223753. {
  223754. #if JUCE_MAC
  223755. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  223756. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  223757. #else
  223758. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  223759. #endif
  223760. temp.create();
  223761. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  223762. if (handle != 0)
  223763. {
  223764. struct flock fl;
  223765. zerostruct (fl);
  223766. fl.l_whence = SEEK_SET;
  223767. fl.l_type = F_WRLCK;
  223768. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  223769. for (;;)
  223770. {
  223771. const int result = fcntl (handle, F_SETLK, &fl);
  223772. if (result >= 0)
  223773. return;
  223774. if (errno != EINTR)
  223775. {
  223776. if (timeOutMillisecs == 0
  223777. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  223778. break;
  223779. Thread::sleep (10);
  223780. }
  223781. }
  223782. }
  223783. closeFile();
  223784. }
  223785. ~Pimpl()
  223786. {
  223787. closeFile();
  223788. }
  223789. void closeFile()
  223790. {
  223791. if (handle != 0)
  223792. {
  223793. struct flock fl;
  223794. zerostruct (fl);
  223795. fl.l_whence = SEEK_SET;
  223796. fl.l_type = F_UNLCK;
  223797. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  223798. {}
  223799. close (handle);
  223800. handle = 0;
  223801. }
  223802. }
  223803. int handle, refCount;
  223804. };
  223805. InterProcessLock::InterProcessLock (const String& name_)
  223806. : name (name_)
  223807. {
  223808. }
  223809. InterProcessLock::~InterProcessLock()
  223810. {
  223811. }
  223812. bool InterProcessLock::enter (const int timeOutMillisecs)
  223813. {
  223814. const ScopedLock sl (lock);
  223815. if (pimpl == 0)
  223816. {
  223817. pimpl = new Pimpl (name, timeOutMillisecs);
  223818. if (pimpl->handle == 0)
  223819. pimpl = 0;
  223820. }
  223821. else
  223822. {
  223823. pimpl->refCount++;
  223824. }
  223825. return pimpl != 0;
  223826. }
  223827. void InterProcessLock::exit()
  223828. {
  223829. const ScopedLock sl (lock);
  223830. // Trying to release the lock too many times!
  223831. jassert (pimpl != 0);
  223832. if (pimpl != 0 && --(pimpl->refCount) == 0)
  223833. pimpl = 0;
  223834. }
  223835. /*** End of inlined file: juce_posix_SharedCode.h ***/
  223836. /*** Start of inlined file: juce_mac_Files.mm ***/
  223837. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223838. // compiled on its own).
  223839. #if JUCE_INCLUDED_FILE
  223840. /*
  223841. Note that a lot of methods that you'd expect to find in this file actually
  223842. live in juce_posix_SharedCode.h!
  223843. */
  223844. bool File::copyInternal (const File& dest) const
  223845. {
  223846. const ScopedAutoReleasePool pool;
  223847. NSFileManager* fm = [NSFileManager defaultManager];
  223848. return [fm fileExistsAtPath: juceStringToNS (fullPath)]
  223849. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  223850. && [fm copyItemAtPath: juceStringToNS (fullPath)
  223851. toPath: juceStringToNS (dest.getFullPathName())
  223852. error: nil];
  223853. #else
  223854. && [fm copyPath: juceStringToNS (fullPath)
  223855. toPath: juceStringToNS (dest.getFullPathName())
  223856. handler: nil];
  223857. #endif
  223858. }
  223859. void File::findFileSystemRoots (Array<File>& destArray)
  223860. {
  223861. destArray.add (File ("/"));
  223862. }
  223863. static bool isFileOnDriveType (const File& f, const char* const* types)
  223864. {
  223865. struct statfs buf;
  223866. if (juce_doStatFS (f, buf))
  223867. {
  223868. const String type (buf.f_fstypename);
  223869. while (*types != 0)
  223870. if (type.equalsIgnoreCase (*types++))
  223871. return true;
  223872. }
  223873. return false;
  223874. }
  223875. bool File::isOnCDRomDrive() const
  223876. {
  223877. const char* const cdTypes[] = { "cd9660", "cdfs", "cddafs", "udf", 0 };
  223878. return isFileOnDriveType (*this, cdTypes);
  223879. }
  223880. bool File::isOnHardDisk() const
  223881. {
  223882. const char* const nonHDTypes[] = { "nfs", "smbfs", "ramfs", 0 };
  223883. return ! (isOnCDRomDrive() || isFileOnDriveType (*this, nonHDTypes));
  223884. }
  223885. bool File::isOnRemovableDrive() const
  223886. {
  223887. #if JUCE_IPHONE
  223888. return false; // xxx is this possible?
  223889. #else
  223890. const ScopedAutoReleasePool pool;
  223891. BOOL removable = false;
  223892. [[NSWorkspace sharedWorkspace]
  223893. getFileSystemInfoForPath: juceStringToNS (getFullPathName())
  223894. isRemovable: &removable
  223895. isWritable: nil
  223896. isUnmountable: nil
  223897. description: nil
  223898. type: nil];
  223899. return removable;
  223900. #endif
  223901. }
  223902. static bool juce_isHiddenFile (const String& path)
  223903. {
  223904. #if JUCE_IPHONE
  223905. return File (path).getFileName().startsWithChar ('.');
  223906. #else
  223907. FSRef ref;
  223908. if (! PlatformUtilities::makeFSRefFromPath (&ref, path))
  223909. return false;
  223910. FSCatalogInfo info;
  223911. FSGetCatalogInfo (&ref, kFSCatInfoNodeFlags | kFSCatInfoFinderInfo, &info, 0, 0, 0);
  223912. if ((info.nodeFlags & kFSNodeIsDirectoryBit) != 0)
  223913. return (((FolderInfo*) &info.finderInfo)->finderFlags & kIsInvisible) != 0;
  223914. return (((FileInfo*) &info.finderInfo)->finderFlags & kIsInvisible) != 0;
  223915. #endif
  223916. }
  223917. bool File::isHidden() const
  223918. {
  223919. return juce_isHiddenFile (getFullPathName());
  223920. }
  223921. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  223922. const File File::getSpecialLocation (const SpecialLocationType type)
  223923. {
  223924. const ScopedAutoReleasePool pool;
  223925. String resultPath;
  223926. switch (type)
  223927. {
  223928. case userHomeDirectory:
  223929. resultPath = nsStringToJuce (NSHomeDirectory());
  223930. break;
  223931. case userDocumentsDirectory:
  223932. resultPath = "~/Documents";
  223933. break;
  223934. case userDesktopDirectory:
  223935. resultPath = "~/Desktop";
  223936. break;
  223937. case userApplicationDataDirectory:
  223938. resultPath = "~/Library";
  223939. break;
  223940. case commonApplicationDataDirectory:
  223941. resultPath = "/Library";
  223942. break;
  223943. case globalApplicationsDirectory:
  223944. resultPath = "/Applications";
  223945. break;
  223946. case userMusicDirectory:
  223947. resultPath = "~/Music";
  223948. break;
  223949. case userMoviesDirectory:
  223950. resultPath = "~/Movies";
  223951. break;
  223952. case tempDirectory:
  223953. {
  223954. File tmp ("~/Library/Caches/" + juce_getExecutableFile().getFileNameWithoutExtension());
  223955. tmp.createDirectory();
  223956. return tmp.getFullPathName();
  223957. }
  223958. case invokedExecutableFile:
  223959. if (juce_Argv0 != 0)
  223960. return File (String::fromUTF8 (juce_Argv0));
  223961. // deliberate fall-through...
  223962. case currentExecutableFile:
  223963. return juce_getExecutableFile();
  223964. case currentApplicationFile:
  223965. {
  223966. const File exe (juce_getExecutableFile());
  223967. const File parent (exe.getParentDirectory());
  223968. return parent.getFullPathName().endsWithIgnoreCase ("Contents/MacOS")
  223969. ? parent.getParentDirectory().getParentDirectory()
  223970. : exe;
  223971. }
  223972. default:
  223973. jassertfalse; // unknown type?
  223974. break;
  223975. }
  223976. if (resultPath.isNotEmpty())
  223977. return File (PlatformUtilities::convertToPrecomposedUnicode (resultPath));
  223978. return File::nonexistent;
  223979. }
  223980. const String File::getVersion() const
  223981. {
  223982. const ScopedAutoReleasePool pool;
  223983. String result;
  223984. NSBundle* bundle = [NSBundle bundleWithPath: juceStringToNS (getFullPathName())];
  223985. if (bundle != 0)
  223986. {
  223987. NSDictionary* info = [bundle infoDictionary];
  223988. if (info != 0)
  223989. {
  223990. NSString* name = [info valueForKey: @"CFBundleShortVersionString"];
  223991. if (name != nil)
  223992. result = nsStringToJuce (name);
  223993. }
  223994. }
  223995. return result;
  223996. }
  223997. const File File::getLinkedTarget() const
  223998. {
  223999. #if JUCE_IPHONE || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
  224000. NSString* dest = [[NSFileManager defaultManager] destinationOfSymbolicLinkAtPath: juceStringToNS (getFullPathName()) error: nil];
  224001. #else
  224002. NSString* dest = [[NSFileManager defaultManager] pathContentOfSymbolicLinkAtPath: juceStringToNS (getFullPathName())];
  224003. #endif
  224004. if (dest != nil)
  224005. return File (nsStringToJuce (dest));
  224006. return *this;
  224007. }
  224008. bool File::moveToTrash() const
  224009. {
  224010. if (! exists())
  224011. return true;
  224012. #if JUCE_IPHONE
  224013. return deleteFile(); //xxx is there a trashcan on the iPhone?
  224014. #else
  224015. const ScopedAutoReleasePool pool;
  224016. NSString* p = juceStringToNS (getFullPathName());
  224017. return [[NSWorkspace sharedWorkspace]
  224018. performFileOperation: NSWorkspaceRecycleOperation
  224019. source: [p stringByDeletingLastPathComponent]
  224020. destination: @""
  224021. files: [NSArray arrayWithObject: [p lastPathComponent]]
  224022. tag: nil ];
  224023. #endif
  224024. }
  224025. class DirectoryIterator::NativeIterator::Pimpl
  224026. {
  224027. public:
  224028. Pimpl (const File& directory, const String& wildCard_)
  224029. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  224030. wildCard (wildCard_),
  224031. enumerator (0)
  224032. {
  224033. ScopedAutoReleasePool pool;
  224034. enumerator = [[[NSFileManager defaultManager] enumeratorAtPath: juceStringToNS (directory.getFullPathName())] retain];
  224035. wildcardUTF8 = wildCard.toUTF8();
  224036. }
  224037. ~Pimpl()
  224038. {
  224039. [enumerator release];
  224040. }
  224041. bool next (String& filenameFound,
  224042. bool* const isDir, bool* const isHidden, int64* const fileSize,
  224043. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  224044. {
  224045. ScopedAutoReleasePool pool;
  224046. for (;;)
  224047. {
  224048. NSString* file;
  224049. if (enumerator == 0 || (file = [enumerator nextObject]) == 0)
  224050. return false;
  224051. [enumerator skipDescendents];
  224052. filenameFound = nsStringToJuce (file);
  224053. if (fnmatch (wildcardUTF8, filenameFound.toUTF8(), FNM_CASEFOLD) != 0)
  224054. continue;
  224055. const String path (parentDir + filenameFound);
  224056. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  224057. {
  224058. struct stat info;
  224059. const bool statOk = juce_stat (path, info);
  224060. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  224061. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  224062. if (modTime != 0) *modTime = statOk ? (int64) info.st_mtime * 1000 : 0;
  224063. if (creationTime != 0) *creationTime = statOk ? (int64) info.st_ctime * 1000 : 0;
  224064. }
  224065. if (isHidden != 0)
  224066. *isHidden = juce_isHiddenFile (path);
  224067. if (isReadOnly != 0)
  224068. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  224069. return true;
  224070. }
  224071. }
  224072. private:
  224073. String parentDir, wildCard;
  224074. const char* wildcardUTF8;
  224075. NSDirectoryEnumerator* enumerator;
  224076. Pimpl (const Pimpl&);
  224077. Pimpl& operator= (const Pimpl&);
  224078. };
  224079. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  224080. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  224081. {
  224082. }
  224083. DirectoryIterator::NativeIterator::~NativeIterator()
  224084. {
  224085. }
  224086. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  224087. bool* const isDir, bool* const isHidden, int64* const fileSize,
  224088. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  224089. {
  224090. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  224091. }
  224092. bool juce_launchExecutable (const String& pathAndArguments)
  224093. {
  224094. const char* const argv[4] = { "/bin/sh", "-c", pathAndArguments.toUTF8(), 0 };
  224095. const int cpid = fork();
  224096. if (cpid == 0)
  224097. {
  224098. // Child process
  224099. if (execve (argv[0], (char**) argv, 0) < 0)
  224100. exit (0);
  224101. }
  224102. else
  224103. {
  224104. if (cpid < 0)
  224105. return false;
  224106. }
  224107. return true;
  224108. }
  224109. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  224110. {
  224111. #if JUCE_IPHONE
  224112. return [[UIApplication sharedApplication] openURL: [NSURL fileURLWithPath: juceStringToNS (fileName)]];
  224113. #else
  224114. const ScopedAutoReleasePool pool;
  224115. if (parameters.isEmpty())
  224116. {
  224117. return [[NSWorkspace sharedWorkspace] openFile: juceStringToNS (fileName)]
  224118. || [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: juceStringToNS (fileName)]];
  224119. }
  224120. bool ok = false;
  224121. FSRef ref;
  224122. if (PlatformUtilities::makeFSRefFromPath (&ref, fileName))
  224123. {
  224124. if (PlatformUtilities::isBundle (fileName))
  224125. {
  224126. NSMutableArray* urls = [NSMutableArray array];
  224127. StringArray docs;
  224128. docs.addTokens (parameters, true);
  224129. for (int i = 0; i < docs.size(); ++i)
  224130. [urls addObject: juceStringToNS (docs[i])];
  224131. ok = [[NSWorkspace sharedWorkspace] openURLs: urls
  224132. withAppBundleIdentifier: [[NSBundle bundleWithPath: juceStringToNS (fileName)] bundleIdentifier]
  224133. options: 0
  224134. additionalEventParamDescriptor: nil
  224135. launchIdentifiers: nil];
  224136. }
  224137. else
  224138. {
  224139. ok = juce_launchExecutable ("\"" + fileName + "\" " + parameters);
  224140. }
  224141. }
  224142. return ok;
  224143. #endif
  224144. }
  224145. void File::revealToUser() const
  224146. {
  224147. #if ! JUCE_IPHONE
  224148. if (exists())
  224149. [[NSWorkspace sharedWorkspace] selectFile: juceStringToNS (getFullPathName()) inFileViewerRootedAtPath: @""];
  224150. else if (getParentDirectory().exists())
  224151. getParentDirectory().revealToUser();
  224152. #endif
  224153. }
  224154. #if ! JUCE_IPHONE
  224155. bool PlatformUtilities::makeFSRefFromPath (FSRef* destFSRef, const String& path)
  224156. {
  224157. return FSPathMakeRef ((const UInt8*) path.toUTF8(), destFSRef, 0) == noErr;
  224158. }
  224159. const String PlatformUtilities::makePathFromFSRef (FSRef* file)
  224160. {
  224161. char path [2048];
  224162. zerostruct (path);
  224163. if (FSRefMakePath (file, (UInt8*) path, sizeof (path) - 1) == noErr)
  224164. return PlatformUtilities::convertToPrecomposedUnicode (String::fromUTF8 (path));
  224165. return String::empty;
  224166. }
  224167. #endif
  224168. OSType PlatformUtilities::getTypeOfFile (const String& filename)
  224169. {
  224170. const ScopedAutoReleasePool pool;
  224171. #if JUCE_IPHONE || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
  224172. NSDictionary* fileDict = [[NSFileManager defaultManager] attributesOfItemAtPath: juceStringToNS (filename) error: nil];
  224173. #else
  224174. NSDictionary* fileDict = [[NSFileManager defaultManager] fileAttributesAtPath: juceStringToNS (filename) traverseLink: NO];
  224175. #endif
  224176. //return (OSType) [fileDict objectForKey: NSFileHFSTypeCode];
  224177. return [fileDict fileHFSTypeCode];
  224178. }
  224179. bool PlatformUtilities::isBundle (const String& filename)
  224180. {
  224181. #if JUCE_IPHONE
  224182. return false; // xxx can't find a sensible way to do this without trying to open the bundle..
  224183. #else
  224184. const ScopedAutoReleasePool pool;
  224185. return [[NSWorkspace sharedWorkspace] isFilePackageAtPath: juceStringToNS (filename)];
  224186. #endif
  224187. }
  224188. #endif
  224189. /*** End of inlined file: juce_mac_Files.mm ***/
  224190. #if JUCE_IPHONE
  224191. /*** Start of inlined file: juce_iphone_MiscUtilities.mm ***/
  224192. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224193. // compiled on its own).
  224194. #if JUCE_INCLUDED_FILE
  224195. static JUCEApplication* juce_intialisingApp;
  224196. END_JUCE_NAMESPACE
  224197. @interface JuceAppStartupDelegate : NSObject <UIApplicationDelegate>
  224198. {
  224199. }
  224200. - (void) applicationDidFinishLaunching: (UIApplication*) application;
  224201. - (void) applicationWillResignActive: (UIApplication*) application;
  224202. @end
  224203. @implementation JuceAppStartupDelegate
  224204. - (void) applicationDidFinishLaunching: (UIApplication*) application
  224205. {
  224206. String dummy;
  224207. if (! juce_intialisingApp->initialiseApp (dummy))
  224208. exit (0);
  224209. }
  224210. - (void) applicationWillResignActive: (UIApplication*) application
  224211. {
  224212. JUCEApplication::shutdownAppAndClearUp();
  224213. }
  224214. @end
  224215. BEGIN_JUCE_NAMESPACE
  224216. int juce_IPhoneMain (int argc, const char* argv[], JUCEApplication* app)
  224217. {
  224218. juce_intialisingApp = app;
  224219. return UIApplicationMain (argc, const_cast<char**> (argv), nil, @"JuceAppStartupDelegate");
  224220. }
  224221. ScopedAutoReleasePool::ScopedAutoReleasePool()
  224222. {
  224223. pool = [[NSAutoreleasePool alloc] init];
  224224. }
  224225. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  224226. {
  224227. [((NSAutoreleasePool*) pool) release];
  224228. }
  224229. void PlatformUtilities::beep()
  224230. {
  224231. //xxx
  224232. //AudioServicesPlaySystemSound ();
  224233. }
  224234. void PlatformUtilities::addItemToDock (const File& file)
  224235. {
  224236. }
  224237. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  224238. END_JUCE_NAMESPACE
  224239. @interface JuceAlertBoxDelegate : NSObject
  224240. {
  224241. @public
  224242. bool clickedOk;
  224243. }
  224244. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex;
  224245. @end
  224246. @implementation JuceAlertBoxDelegate
  224247. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex
  224248. {
  224249. clickedOk = (buttonIndex == 0);
  224250. alertView.hidden = true;
  224251. }
  224252. @end
  224253. BEGIN_JUCE_NAMESPACE
  224254. // (This function is used directly by other bits of code)
  224255. bool juce_iPhoneShowModalAlert (const String& title,
  224256. const String& bodyText,
  224257. NSString* okButtonText,
  224258. NSString* cancelButtonText)
  224259. {
  224260. const ScopedAutoReleasePool pool;
  224261. JuceAlertBoxDelegate* callback = [[JuceAlertBoxDelegate alloc] init];
  224262. UIAlertView* alert = [[UIAlertView alloc] initWithTitle: juceStringToNS (title)
  224263. message: juceStringToNS (bodyText)
  224264. delegate: callback
  224265. cancelButtonTitle: okButtonText
  224266. otherButtonTitles: cancelButtonText, nil];
  224267. [alert retain];
  224268. [alert show];
  224269. while (! alert.hidden && alert.superview != nil)
  224270. [[NSRunLoop mainRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  224271. const bool result = callback->clickedOk;
  224272. [alert release];
  224273. [callback release];
  224274. return result;
  224275. }
  224276. bool AlertWindow::showNativeDialogBox (const String& title,
  224277. const String& bodyText,
  224278. bool isOkCancel)
  224279. {
  224280. return juce_iPhoneShowModalAlert (title, bodyText,
  224281. @"OK",
  224282. isOkCancel ? @"Cancel" : nil);
  224283. }
  224284. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  224285. {
  224286. jassertfalse; // no such thing on the iphone!
  224287. return false;
  224288. }
  224289. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  224290. {
  224291. jassertfalse; // no such thing on the iphone!
  224292. return false;
  224293. }
  224294. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  224295. {
  224296. [[UIApplication sharedApplication] setIdleTimerDisabled: ! isEnabled];
  224297. }
  224298. bool Desktop::isScreenSaverEnabled()
  224299. {
  224300. return ! [[UIApplication sharedApplication] isIdleTimerDisabled];
  224301. }
  224302. void juce_updateMultiMonitorInfo (Array <Rectangle <int> >& monitorCoords, const bool clipToWorkArea)
  224303. {
  224304. const ScopedAutoReleasePool pool;
  224305. monitorCoords.clear();
  224306. CGRect r = clipToWorkArea ? [[UIScreen mainScreen] applicationFrame]
  224307. : [[UIScreen mainScreen] bounds];
  224308. monitorCoords.add (Rectangle<int> ((int) r.origin.x,
  224309. (int) r.origin.y,
  224310. (int) r.size.width,
  224311. (int) r.size.height));
  224312. }
  224313. #endif
  224314. #endif
  224315. /*** End of inlined file: juce_iphone_MiscUtilities.mm ***/
  224316. #else
  224317. /*** Start of inlined file: juce_mac_MiscUtilities.mm ***/
  224318. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224319. // compiled on its own).
  224320. #if JUCE_INCLUDED_FILE
  224321. ScopedAutoReleasePool::ScopedAutoReleasePool()
  224322. {
  224323. pool = [[NSAutoreleasePool alloc] init];
  224324. }
  224325. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  224326. {
  224327. [((NSAutoreleasePool*) pool) release];
  224328. }
  224329. void PlatformUtilities::beep()
  224330. {
  224331. NSBeep();
  224332. }
  224333. void PlatformUtilities::addItemToDock (const File& file)
  224334. {
  224335. // check that it's not already there...
  224336. if (! juce_getOutputFromCommand ("defaults read com.apple.dock persistent-apps")
  224337. .containsIgnoreCase (file.getFullPathName()))
  224338. {
  224339. 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>"
  224340. + file.getFullPathName() + "</string><key>_CFURLStringType</key><integer>0</integer></dict></dict></dict>\"");
  224341. juce_runSystemCommand ("osascript -e \"tell application \\\"Dock\\\" to quit\"");
  224342. }
  224343. }
  224344. int PlatformUtilities::getOSXMinorVersionNumber()
  224345. {
  224346. SInt32 versionMinor = 0;
  224347. OSErr err = Gestalt (gestaltSystemVersionMinor, &versionMinor);
  224348. (void) err;
  224349. jassert (err == noErr);
  224350. return (int) versionMinor;
  224351. }
  224352. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  224353. bool AlertWindow::showNativeDialogBox (const String& title,
  224354. const String& bodyText,
  224355. bool isOkCancel)
  224356. {
  224357. const ScopedAutoReleasePool pool;
  224358. return NSRunAlertPanel (juceStringToNS (title),
  224359. juceStringToNS (bodyText),
  224360. @"Ok",
  224361. isOkCancel ? @"Cancel" : nil,
  224362. nil) == NSAlertDefaultReturn;
  224363. }
  224364. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool /*canMoveFiles*/)
  224365. {
  224366. if (files.size() == 0)
  224367. return false;
  224368. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource(0);
  224369. if (draggingSource == 0)
  224370. {
  224371. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  224372. return false;
  224373. }
  224374. Component* sourceComp = draggingSource->getComponentUnderMouse();
  224375. if (sourceComp == 0)
  224376. {
  224377. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  224378. return false;
  224379. }
  224380. const ScopedAutoReleasePool pool;
  224381. NSView* view = (NSView*) sourceComp->getWindowHandle();
  224382. if (view == 0)
  224383. return false;
  224384. NSPasteboard* pboard = [NSPasteboard pasteboardWithName: NSDragPboard];
  224385. [pboard declareTypes: [NSArray arrayWithObject: NSFilenamesPboardType]
  224386. owner: nil];
  224387. NSMutableArray* filesArray = [NSMutableArray arrayWithCapacity: 4];
  224388. for (int i = 0; i < files.size(); ++i)
  224389. [filesArray addObject: juceStringToNS (files[i])];
  224390. [pboard setPropertyList: filesArray
  224391. forType: NSFilenamesPboardType];
  224392. NSPoint dragPosition = [view convertPoint: [[[view window] currentEvent] locationInWindow]
  224393. fromView: nil];
  224394. dragPosition.x -= 16;
  224395. dragPosition.y -= 16;
  224396. [view dragImage: [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (files[0])]
  224397. at: dragPosition
  224398. offset: NSMakeSize (0, 0)
  224399. event: [[view window] currentEvent]
  224400. pasteboard: pboard
  224401. source: view
  224402. slideBack: YES];
  224403. return true;
  224404. }
  224405. bool DragAndDropContainer::performExternalDragDropOfText (const String& /*text*/)
  224406. {
  224407. jassertfalse; // not implemented!
  224408. return false;
  224409. }
  224410. bool Desktop::canUseSemiTransparentWindows() throw()
  224411. {
  224412. return true;
  224413. }
  224414. const Point<int> Desktop::getMousePosition()
  224415. {
  224416. const ScopedAutoReleasePool pool;
  224417. const NSPoint p ([NSEvent mouseLocation]);
  224418. return Point<int> (roundToInt (p.x), roundToInt ([[[NSScreen screens] objectAtIndex: 0] frame].size.height - p.y));
  224419. }
  224420. void Desktop::setMousePosition (const Point<int>& newPosition)
  224421. {
  224422. // this rubbish needs to be done around the warp call, to avoid causing a
  224423. // bizarre glitch..
  224424. CGAssociateMouseAndMouseCursorPosition (false);
  224425. CGWarpMouseCursorPosition (CGPointMake (newPosition.getX(), newPosition.getY()));
  224426. CGAssociateMouseAndMouseCursorPosition (true);
  224427. }
  224428. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  224429. class ScreenSaverDefeater : public Timer,
  224430. public DeletedAtShutdown
  224431. {
  224432. public:
  224433. ScreenSaverDefeater()
  224434. {
  224435. startTimer (10000);
  224436. timerCallback();
  224437. }
  224438. ~ScreenSaverDefeater() {}
  224439. void timerCallback()
  224440. {
  224441. if (Process::isForegroundProcess())
  224442. UpdateSystemActivity (UsrActivity);
  224443. }
  224444. };
  224445. static ScreenSaverDefeater* screenSaverDefeater = 0;
  224446. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  224447. {
  224448. if (isEnabled)
  224449. deleteAndZero (screenSaverDefeater);
  224450. else if (screenSaverDefeater == 0)
  224451. screenSaverDefeater = new ScreenSaverDefeater();
  224452. }
  224453. bool Desktop::isScreenSaverEnabled()
  224454. {
  224455. return screenSaverDefeater == 0;
  224456. }
  224457. #else
  224458. static IOPMAssertionID screenSaverDisablerID = 0;
  224459. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  224460. {
  224461. if (isEnabled)
  224462. {
  224463. if (screenSaverDisablerID != 0)
  224464. {
  224465. IOPMAssertionRelease (screenSaverDisablerID);
  224466. screenSaverDisablerID = 0;
  224467. }
  224468. }
  224469. else
  224470. {
  224471. if (screenSaverDisablerID == 0)
  224472. {
  224473. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  224474. IOPMAssertionCreateWithName (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  224475. CFSTR ("Juce"), &screenSaverDisablerID);
  224476. #else
  224477. IOPMAssertionCreate (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  224478. &screenSaverDisablerID);
  224479. #endif
  224480. }
  224481. }
  224482. }
  224483. bool Desktop::isScreenSaverEnabled()
  224484. {
  224485. return screenSaverDisablerID == 0;
  224486. }
  224487. #endif
  224488. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  224489. {
  224490. const ScopedAutoReleasePool pool;
  224491. monitorCoords.clear();
  224492. NSArray* screens = [NSScreen screens];
  224493. const CGFloat mainScreenBottom = [[[NSScreen screens] objectAtIndex: 0] frame].size.height;
  224494. for (unsigned int i = 0; i < [screens count]; ++i)
  224495. {
  224496. NSScreen* s = (NSScreen*) [screens objectAtIndex: i];
  224497. NSRect r = clipToWorkArea ? [s visibleFrame]
  224498. : [s frame];
  224499. monitorCoords.add (Rectangle<int> ((int) r.origin.x,
  224500. (int) (mainScreenBottom - (r.origin.y + r.size.height)),
  224501. (int) r.size.width,
  224502. (int) r.size.height));
  224503. }
  224504. jassert (monitorCoords.size() > 0);
  224505. }
  224506. #endif
  224507. #endif
  224508. /*** End of inlined file: juce_mac_MiscUtilities.mm ***/
  224509. #endif
  224510. /*** Start of inlined file: juce_mac_Debugging.mm ***/
  224511. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224512. // compiled on its own).
  224513. #if JUCE_INCLUDED_FILE
  224514. void Logger::outputDebugString (const String& text)
  224515. {
  224516. std::cerr << text << std::endl;
  224517. }
  224518. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  224519. {
  224520. static char testResult = 0;
  224521. if (testResult == 0)
  224522. {
  224523. struct kinfo_proc info;
  224524. int m[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid() };
  224525. size_t sz = sizeof (info);
  224526. sysctl (m, 4, &info, &sz, 0, 0);
  224527. testResult = ((info.kp_proc.p_flag & P_TRACED) != 0) ? 1 : -1;
  224528. }
  224529. return testResult > 0;
  224530. }
  224531. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  224532. {
  224533. return juce_isRunningUnderDebugger();
  224534. }
  224535. #endif
  224536. /*** End of inlined file: juce_mac_Debugging.mm ***/
  224537. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  224538. #if JUCE_IPHONE
  224539. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  224540. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224541. // compiled on its own).
  224542. #if JUCE_INCLUDED_FILE
  224543. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  224544. #define SUPPORT_10_4_FONTS 1
  224545. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  224546. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  224547. #define SUPPORT_ONLY_10_4_FONTS 1
  224548. #endif
  224549. END_JUCE_NAMESPACE
  224550. @interface NSFont (PrivateHack)
  224551. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  224552. @end
  224553. BEGIN_JUCE_NAMESPACE
  224554. #endif
  224555. class MacTypeface : public Typeface
  224556. {
  224557. public:
  224558. MacTypeface (const Font& font)
  224559. : Typeface (font.getTypefaceName())
  224560. {
  224561. const ScopedAutoReleasePool pool;
  224562. renderingTransform = CGAffineTransformIdentity;
  224563. bool needsItalicTransform = false;
  224564. #if JUCE_IPHONE
  224565. NSString* fontName = juceStringToNS (font.getTypefaceName());
  224566. if (font.isItalic() || font.isBold())
  224567. {
  224568. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  224569. for (NSString* i in familyFonts)
  224570. {
  224571. const String fn (nsStringToJuce (i));
  224572. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  224573. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  224574. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  224575. || afterDash.containsIgnoreCase ("italic")
  224576. || fn.endsWithIgnoreCase ("oblique")
  224577. || fn.endsWithIgnoreCase ("italic");
  224578. if (probablyBold == font.isBold()
  224579. && probablyItalic == font.isItalic())
  224580. {
  224581. fontName = i;
  224582. needsItalicTransform = false;
  224583. break;
  224584. }
  224585. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  224586. {
  224587. fontName = i;
  224588. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  224589. }
  224590. }
  224591. if (needsItalicTransform)
  224592. renderingTransform.c = 0.15f;
  224593. }
  224594. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  224595. const int ascender = abs (CGFontGetAscent (fontRef));
  224596. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  224597. ascent = ascender / totalHeight;
  224598. unitsToHeightScaleFactor = 1.0f / totalHeight;
  224599. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  224600. #else
  224601. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  224602. if (font.isItalic())
  224603. {
  224604. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  224605. toHaveTrait: NSItalicFontMask];
  224606. if (newFont == nsFont)
  224607. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  224608. nsFont = newFont;
  224609. }
  224610. if (font.isBold())
  224611. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  224612. [nsFont retain];
  224613. ascent = std::abs ((float) [nsFont ascender]);
  224614. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  224615. ascent /= totalSize;
  224616. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  224617. if (needsItalicTransform)
  224618. {
  224619. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  224620. renderingTransform.c = 0.15f;
  224621. }
  224622. #if SUPPORT_ONLY_10_4_FONTS
  224623. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  224624. if (atsFont == 0)
  224625. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  224626. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  224627. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  224628. unitsToHeightScaleFactor = 1.0f / totalHeight;
  224629. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  224630. #else
  224631. #if SUPPORT_10_4_FONTS
  224632. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  224633. {
  224634. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  224635. if (atsFont == 0)
  224636. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  224637. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  224638. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  224639. unitsToHeightScaleFactor = 1.0f / totalHeight;
  224640. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  224641. }
  224642. else
  224643. #endif
  224644. {
  224645. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  224646. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  224647. unitsToHeightScaleFactor = 1.0f / totalHeight;
  224648. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  224649. }
  224650. #endif
  224651. #endif
  224652. }
  224653. ~MacTypeface()
  224654. {
  224655. #if ! JUCE_IPHONE
  224656. [nsFont release];
  224657. #endif
  224658. if (fontRef != 0)
  224659. CGFontRelease (fontRef);
  224660. }
  224661. float getAscent() const
  224662. {
  224663. return ascent;
  224664. }
  224665. float getDescent() const
  224666. {
  224667. return 1.0f - ascent;
  224668. }
  224669. float getStringWidth (const String& text)
  224670. {
  224671. if (fontRef == 0 || text.isEmpty())
  224672. return 0;
  224673. const int length = text.length();
  224674. HeapBlock <CGGlyph> glyphs;
  224675. createGlyphsForString (text, length, glyphs);
  224676. float x = 0;
  224677. #if SUPPORT_ONLY_10_4_FONTS
  224678. HeapBlock <NSSize> advances (length);
  224679. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  224680. for (int i = 0; i < length; ++i)
  224681. x += advances[i].width;
  224682. #else
  224683. #if SUPPORT_10_4_FONTS
  224684. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  224685. {
  224686. HeapBlock <NSSize> advances (length);
  224687. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  224688. for (int i = 0; i < length; ++i)
  224689. x += advances[i].width;
  224690. }
  224691. else
  224692. #endif
  224693. {
  224694. HeapBlock <int> advances (length);
  224695. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  224696. for (int i = 0; i < length; ++i)
  224697. x += advances[i];
  224698. }
  224699. #endif
  224700. return x * unitsToHeightScaleFactor;
  224701. }
  224702. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  224703. {
  224704. xOffsets.add (0);
  224705. if (fontRef == 0 || text.isEmpty())
  224706. return;
  224707. const int length = text.length();
  224708. HeapBlock <CGGlyph> glyphs;
  224709. createGlyphsForString (text, length, glyphs);
  224710. #if SUPPORT_ONLY_10_4_FONTS
  224711. HeapBlock <NSSize> advances (length);
  224712. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  224713. int x = 0;
  224714. for (int i = 0; i < length; ++i)
  224715. {
  224716. x += advances[i].width;
  224717. xOffsets.add (x * unitsToHeightScaleFactor);
  224718. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  224719. }
  224720. #else
  224721. #if SUPPORT_10_4_FONTS
  224722. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  224723. {
  224724. HeapBlock <NSSize> advances (length);
  224725. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  224726. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  224727. float x = 0;
  224728. for (int i = 0; i < length; ++i)
  224729. {
  224730. x += advances[i].width;
  224731. xOffsets.add (x * unitsToHeightScaleFactor);
  224732. resultGlyphs.add (nsGlyphs[i]);
  224733. }
  224734. }
  224735. else
  224736. #endif
  224737. {
  224738. HeapBlock <int> advances (length);
  224739. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  224740. {
  224741. int x = 0;
  224742. for (int i = 0; i < length; ++i)
  224743. {
  224744. x += advances [i];
  224745. xOffsets.add (x * unitsToHeightScaleFactor);
  224746. resultGlyphs.add (glyphs[i]);
  224747. }
  224748. }
  224749. }
  224750. #endif
  224751. }
  224752. bool getOutlineForGlyph (int glyphNumber, Path& path)
  224753. {
  224754. #if JUCE_IPHONE
  224755. return false;
  224756. #else
  224757. if (nsFont == 0)
  224758. return false;
  224759. // we might need to apply a transform to the path, so it mustn't have anything else in it
  224760. jassert (path.isEmpty());
  224761. const ScopedAutoReleasePool pool;
  224762. NSBezierPath* bez = [NSBezierPath bezierPath];
  224763. [bez moveToPoint: NSMakePoint (0, 0)];
  224764. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  224765. inFont: nsFont];
  224766. for (int i = 0; i < [bez elementCount]; ++i)
  224767. {
  224768. NSPoint p[3];
  224769. switch ([bez elementAtIndex: i associatedPoints: p])
  224770. {
  224771. case NSMoveToBezierPathElement:
  224772. path.startNewSubPath ((float) p[0].x, (float) -p[0].y);
  224773. break;
  224774. case NSLineToBezierPathElement:
  224775. path.lineTo ((float) p[0].x, (float) -p[0].y);
  224776. break;
  224777. case NSCurveToBezierPathElement:
  224778. 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);
  224779. break;
  224780. case NSClosePathBezierPathElement:
  224781. path.closeSubPath();
  224782. break;
  224783. default:
  224784. jassertfalse;
  224785. break;
  224786. }
  224787. }
  224788. path.applyTransform (pathTransform);
  224789. return true;
  224790. #endif
  224791. }
  224792. juce_UseDebuggingNewOperator
  224793. CGFontRef fontRef;
  224794. float fontHeightToCGSizeFactor;
  224795. CGAffineTransform renderingTransform;
  224796. private:
  224797. float ascent, unitsToHeightScaleFactor;
  224798. #if JUCE_IPHONE
  224799. #else
  224800. NSFont* nsFont;
  224801. AffineTransform pathTransform;
  224802. #endif
  224803. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  224804. {
  224805. #if SUPPORT_10_4_FONTS
  224806. #if ! SUPPORT_ONLY_10_4_FONTS
  224807. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  224808. #endif
  224809. {
  224810. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  224811. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  224812. for (int i = 0; i < length; ++i)
  224813. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  224814. return;
  224815. }
  224816. #endif
  224817. #if ! SUPPORT_ONLY_10_4_FONTS
  224818. if (charToGlyphMapper == 0)
  224819. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  224820. glyphs.malloc (length);
  224821. for (int i = 0; i < length; ++i)
  224822. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  224823. #endif
  224824. }
  224825. #if ! SUPPORT_ONLY_10_4_FONTS
  224826. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  224827. class CharToGlyphMapper
  224828. {
  224829. public:
  224830. CharToGlyphMapper (CGFontRef fontRef)
  224831. : segCount (0), endCode (0), startCode (0), idDelta (0),
  224832. idRangeOffset (0), glyphIndexes (0)
  224833. {
  224834. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  224835. if (cmapTable != 0)
  224836. {
  224837. const int numSubtables = getValue16 (cmapTable, 2);
  224838. for (int i = 0; i < numSubtables; ++i)
  224839. {
  224840. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  224841. {
  224842. const int offset = getValue32 (cmapTable, i * 8 + 8);
  224843. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  224844. {
  224845. const int length = getValue16 (cmapTable, offset + 2);
  224846. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  224847. segCount = segCountX2 / 2;
  224848. const int endCodeOffset = offset + 14;
  224849. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  224850. const int idDeltaOffset = startCodeOffset + segCountX2;
  224851. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  224852. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  224853. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  224854. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  224855. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  224856. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  224857. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  224858. }
  224859. break;
  224860. }
  224861. }
  224862. CFRelease (cmapTable);
  224863. }
  224864. }
  224865. ~CharToGlyphMapper()
  224866. {
  224867. if (endCode != 0)
  224868. {
  224869. CFRelease (endCode);
  224870. CFRelease (startCode);
  224871. CFRelease (idDelta);
  224872. CFRelease (idRangeOffset);
  224873. CFRelease (glyphIndexes);
  224874. }
  224875. }
  224876. int getGlyphForCharacter (const juce_wchar c) const
  224877. {
  224878. for (int i = 0; i < segCount; ++i)
  224879. {
  224880. if (getValue16 (endCode, i * 2) >= c)
  224881. {
  224882. const int start = getValue16 (startCode, i * 2);
  224883. if (start > c)
  224884. break;
  224885. const int delta = getValue16 (idDelta, i * 2);
  224886. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  224887. if (rangeOffset == 0)
  224888. return delta + c;
  224889. else
  224890. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  224891. }
  224892. }
  224893. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  224894. return jmax (-1, c - 29);
  224895. }
  224896. private:
  224897. int segCount;
  224898. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  224899. static uint16 getValue16 (CFDataRef data, const int index)
  224900. {
  224901. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  224902. }
  224903. static uint32 getValue32 (CFDataRef data, const int index)
  224904. {
  224905. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  224906. }
  224907. };
  224908. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  224909. #endif
  224910. MacTypeface (const MacTypeface&);
  224911. MacTypeface& operator= (const MacTypeface&);
  224912. };
  224913. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  224914. {
  224915. return new MacTypeface (font);
  224916. }
  224917. const StringArray Font::findAllTypefaceNames()
  224918. {
  224919. StringArray names;
  224920. const ScopedAutoReleasePool pool;
  224921. #if JUCE_IPHONE
  224922. NSArray* fonts = [UIFont familyNames];
  224923. #else
  224924. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  224925. #endif
  224926. for (unsigned int i = 0; i < [fonts count]; ++i)
  224927. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  224928. names.sort (true);
  224929. return names;
  224930. }
  224931. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  224932. {
  224933. #if JUCE_IPHONE
  224934. defaultSans = "Helvetica";
  224935. defaultSerif = "Times New Roman";
  224936. defaultFixed = "Courier New";
  224937. #else
  224938. defaultSans = "Lucida Grande";
  224939. defaultSerif = "Times New Roman";
  224940. defaultFixed = "Monaco";
  224941. #endif
  224942. }
  224943. #endif
  224944. /*** End of inlined file: juce_mac_Fonts.mm ***/
  224945. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  224946. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224947. // compiled on its own).
  224948. #if JUCE_INCLUDED_FILE
  224949. class CoreGraphicsImage : public Image::SharedImage
  224950. {
  224951. public:
  224952. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  224953. : Image::SharedImage (format_, width_, height_)
  224954. {
  224955. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  224956. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  224957. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  224958. imageData = imageDataAllocated;
  224959. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  224960. : CGColorSpaceCreateDeviceRGB();
  224961. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  224962. colourSpace, getCGImageFlags (format_));
  224963. CGColorSpaceRelease (colourSpace);
  224964. }
  224965. ~CoreGraphicsImage()
  224966. {
  224967. CGContextRelease (context);
  224968. }
  224969. Image::ImageType getType() const { return Image::NativeImage; }
  224970. LowLevelGraphicsContext* createLowLevelContext();
  224971. SharedImage* clone()
  224972. {
  224973. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  224974. memcpy (im->imageData, imageData, lineStride * height);
  224975. return im;
  224976. }
  224977. static CGImageRef createImage (const Image& juceImage, const bool forAlpha, CGColorSpaceRef colourSpace)
  224978. {
  224979. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  224980. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  224981. {
  224982. return CGBitmapContextCreateImage (nativeImage->context);
  224983. }
  224984. else
  224985. {
  224986. const Image::BitmapData srcData (juceImage, 0, 0, juceImage.getWidth(), juceImage.getHeight());
  224987. CGDataProviderRef provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  224988. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  224989. 8, srcData.pixelStride * 8, srcData.lineStride,
  224990. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  224991. 0, true, kCGRenderingIntentDefault);
  224992. CGDataProviderRelease (provider);
  224993. return imageRef;
  224994. }
  224995. }
  224996. #if JUCE_MAC
  224997. static NSImage* createNSImage (const Image& image)
  224998. {
  224999. const ScopedAutoReleasePool pool;
  225000. NSImage* im = [[NSImage alloc] init];
  225001. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  225002. [im lockFocus];
  225003. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  225004. CGImageRef imageRef = createImage (image, false, colourSpace);
  225005. CGColorSpaceRelease (colourSpace);
  225006. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  225007. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  225008. CGImageRelease (imageRef);
  225009. [im unlockFocus];
  225010. return im;
  225011. }
  225012. #endif
  225013. CGContextRef context;
  225014. HeapBlock<uint8> imageDataAllocated;
  225015. private:
  225016. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  225017. {
  225018. #if JUCE_BIG_ENDIAN
  225019. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  225020. #else
  225021. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  225022. #endif
  225023. }
  225024. };
  225025. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  225026. {
  225027. #if USE_COREGRAPHICS_RENDERING
  225028. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  225029. #else
  225030. return createSoftwareImage (format, width, height, clearImage);
  225031. #endif
  225032. }
  225033. class CoreGraphicsContext : public LowLevelGraphicsContext
  225034. {
  225035. public:
  225036. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  225037. : context (context_),
  225038. flipHeight (flipHeight_),
  225039. state (new SavedState()),
  225040. numGradientLookupEntries (0),
  225041. lastClipRectIsValid (false)
  225042. {
  225043. CGContextRetain (context);
  225044. CGContextSaveGState(context);
  225045. CGContextSetShouldSmoothFonts (context, true);
  225046. CGContextSetShouldAntialias (context, true);
  225047. CGContextSetBlendMode (context, kCGBlendModeNormal);
  225048. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  225049. greyColourSpace = CGColorSpaceCreateDeviceGray();
  225050. gradientCallbacks.version = 0;
  225051. gradientCallbacks.evaluate = gradientCallback;
  225052. gradientCallbacks.releaseInfo = 0;
  225053. setFont (Font());
  225054. }
  225055. ~CoreGraphicsContext()
  225056. {
  225057. CGContextRestoreGState (context);
  225058. CGContextRelease (context);
  225059. CGColorSpaceRelease (rgbColourSpace);
  225060. CGColorSpaceRelease (greyColourSpace);
  225061. }
  225062. bool isVectorDevice() const { return false; }
  225063. void setOrigin (int x, int y)
  225064. {
  225065. CGContextTranslateCTM (context, x, -y);
  225066. if (lastClipRectIsValid)
  225067. lastClipRect.translate (-x, -y);
  225068. }
  225069. bool clipToRectangle (const Rectangle<int>& r)
  225070. {
  225071. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  225072. if (lastClipRectIsValid)
  225073. {
  225074. lastClipRect = lastClipRect.getIntersection (r);
  225075. return ! lastClipRect.isEmpty();
  225076. }
  225077. return ! isClipEmpty();
  225078. }
  225079. bool clipToRectangleList (const RectangleList& clipRegion)
  225080. {
  225081. if (clipRegion.isEmpty())
  225082. {
  225083. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  225084. lastClipRectIsValid = true;
  225085. lastClipRect = Rectangle<int>();
  225086. return false;
  225087. }
  225088. else
  225089. {
  225090. const int numRects = clipRegion.getNumRectangles();
  225091. HeapBlock <CGRect> rects (numRects);
  225092. for (int i = 0; i < numRects; ++i)
  225093. {
  225094. const Rectangle<int>& r = clipRegion.getRectangle(i);
  225095. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  225096. }
  225097. CGContextClipToRects (context, rects, numRects);
  225098. lastClipRectIsValid = false;
  225099. return ! isClipEmpty();
  225100. }
  225101. }
  225102. void excludeClipRectangle (const Rectangle<int>& r)
  225103. {
  225104. RectangleList remaining (getClipBounds());
  225105. remaining.subtract (r);
  225106. clipToRectangleList (remaining);
  225107. lastClipRectIsValid = false;
  225108. }
  225109. void clipToPath (const Path& path, const AffineTransform& transform)
  225110. {
  225111. createPath (path, transform);
  225112. CGContextClip (context);
  225113. lastClipRectIsValid = false;
  225114. }
  225115. void clipToImageAlpha (const Image& sourceImage, const Rectangle<int>& srcClip, const AffineTransform& transform)
  225116. {
  225117. if (! transform.isSingularity())
  225118. {
  225119. Image singleChannelImage (sourceImage);
  225120. if (sourceImage.getFormat() != Image::SingleChannel)
  225121. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  225122. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace);
  225123. if (srcClip != sourceImage.getBounds())
  225124. {
  225125. CGImageRef fullImage = image;
  225126. image = CGImageCreateWithImageInRect (fullImage, CGRectMake (srcClip.getX(), srcClip.getY(),
  225127. srcClip.getWidth(), srcClip.getHeight()));
  225128. CGImageRelease (fullImage);
  225129. }
  225130. flip();
  225131. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, srcClip.getHeight()).followedBy (transform));
  225132. applyTransform (t);
  225133. CGRect r = CGRectMake (0, 0, srcClip.getWidth(), srcClip.getHeight());
  225134. CGContextClipToMask (context, r, image);
  225135. applyTransform (t.inverted());
  225136. flip();
  225137. CGImageRelease (image);
  225138. lastClipRectIsValid = false;
  225139. }
  225140. }
  225141. bool clipRegionIntersects (const Rectangle<int>& r)
  225142. {
  225143. return getClipBounds().intersects (r);
  225144. }
  225145. const Rectangle<int> getClipBounds() const
  225146. {
  225147. if (! lastClipRectIsValid)
  225148. {
  225149. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  225150. lastClipRectIsValid = true;
  225151. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  225152. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  225153. roundToInt (bounds.size.width),
  225154. roundToInt (bounds.size.height));
  225155. }
  225156. return lastClipRect;
  225157. }
  225158. bool isClipEmpty() const
  225159. {
  225160. return getClipBounds().isEmpty();
  225161. }
  225162. void saveState()
  225163. {
  225164. CGContextSaveGState (context);
  225165. stateStack.add (new SavedState (*state));
  225166. }
  225167. void restoreState()
  225168. {
  225169. CGContextRestoreGState (context);
  225170. SavedState* const top = stateStack.getLast();
  225171. if (top != 0)
  225172. {
  225173. state = top;
  225174. stateStack.removeLast (1, false);
  225175. lastClipRectIsValid = false;
  225176. }
  225177. else
  225178. {
  225179. jassertfalse; // trying to pop with an empty stack!
  225180. }
  225181. }
  225182. void setFill (const FillType& fillType)
  225183. {
  225184. state->fillType = fillType;
  225185. if (fillType.isColour())
  225186. {
  225187. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  225188. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  225189. CGContextSetAlpha (context, 1.0f);
  225190. }
  225191. }
  225192. void setOpacity (float newOpacity)
  225193. {
  225194. state->fillType.setOpacity (newOpacity);
  225195. setFill (state->fillType);
  225196. }
  225197. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  225198. {
  225199. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  225200. ? kCGInterpolationLow
  225201. : kCGInterpolationHigh);
  225202. }
  225203. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  225204. {
  225205. CGRect cgRect = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  225206. if (replaceExistingContents)
  225207. {
  225208. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  225209. CGContextClearRect (context, cgRect);
  225210. #else
  225211. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  225212. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  225213. CGContextClearRect (context, cgRect);
  225214. else
  225215. #endif
  225216. CGContextSetBlendMode (context, kCGBlendModeCopy);
  225217. #endif
  225218. fillRect (r, false);
  225219. CGContextSetBlendMode (context, kCGBlendModeNormal);
  225220. }
  225221. else
  225222. {
  225223. if (state->fillType.isColour())
  225224. {
  225225. CGContextFillRect (context, cgRect);
  225226. }
  225227. else if (state->fillType.isGradient())
  225228. {
  225229. CGContextSaveGState (context);
  225230. CGContextClipToRect (context, cgRect);
  225231. drawGradient();
  225232. CGContextRestoreGState (context);
  225233. }
  225234. else
  225235. {
  225236. CGContextSaveGState (context);
  225237. CGContextClipToRect (context, cgRect);
  225238. drawImage (state->fillType.image, state->fillType.image.getBounds(), state->fillType.transform, true);
  225239. CGContextRestoreGState (context);
  225240. }
  225241. }
  225242. }
  225243. void fillPath (const Path& path, const AffineTransform& transform)
  225244. {
  225245. CGContextSaveGState (context);
  225246. if (state->fillType.isColour())
  225247. {
  225248. flip();
  225249. applyTransform (transform);
  225250. createPath (path);
  225251. if (path.isUsingNonZeroWinding())
  225252. CGContextFillPath (context);
  225253. else
  225254. CGContextEOFillPath (context);
  225255. }
  225256. else
  225257. {
  225258. createPath (path, transform);
  225259. if (path.isUsingNonZeroWinding())
  225260. CGContextClip (context);
  225261. else
  225262. CGContextEOClip (context);
  225263. if (state->fillType.isGradient())
  225264. drawGradient();
  225265. else
  225266. drawImage (state->fillType.image, state->fillType.image.getBounds(), state->fillType.transform, true);
  225267. }
  225268. CGContextRestoreGState (context);
  225269. }
  225270. void drawImage (const Image& sourceImage, const Rectangle<int>& srcClip,
  225271. const AffineTransform& transform, const bool fillEntireClipAsTiles)
  225272. {
  225273. jassert (sourceImage.getBounds().contains (srcClip));
  225274. CGImageRef fullImage = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace);
  225275. CGImageRef image = fullImage;
  225276. if (srcClip != sourceImage.getBounds())
  225277. {
  225278. image = CGImageCreateWithImageInRect (fullImage, CGRectMake (srcClip.getX(), srcClip.getY(),
  225279. srcClip.getWidth(), srcClip.getHeight()));
  225280. CGImageRelease (fullImage);
  225281. }
  225282. CGContextSaveGState (context);
  225283. CGContextSetAlpha (context, state->fillType.getOpacity());
  225284. flip();
  225285. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, srcClip.getHeight()).followedBy (transform));
  225286. CGRect imageRect = CGRectMake (0, 0, srcClip.getWidth(), srcClip.getHeight());
  225287. if (fillEntireClipAsTiles)
  225288. {
  225289. #if JUCE_IPHONE
  225290. CGContextDrawTiledImage (context, imageRect, image);
  225291. #else
  225292. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  225293. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  225294. // if it's doing a transformation - it's quicker to just draw lots of images manually
  225295. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  225296. CGContextDrawTiledImage (context, imageRect, image);
  225297. else
  225298. #endif
  225299. {
  225300. // Fallback to manually doing a tiled fill on 10.4
  225301. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  225302. const int iw = srcClip.getWidth();
  225303. const int ih = srcClip.getHeight();
  225304. int x = 0, y = 0;
  225305. while (x > clip.origin.x) x -= iw;
  225306. while (y > clip.origin.y) y -= ih;
  225307. const int right = (int) (clip.origin.x + clip.size.width);
  225308. const int bottom = (int) (clip.origin.y + clip.size.height);
  225309. while (y < bottom)
  225310. {
  225311. for (int x2 = x; x2 < right; x2 += iw)
  225312. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  225313. y += ih;
  225314. }
  225315. }
  225316. #endif
  225317. }
  225318. else
  225319. {
  225320. CGContextDrawImage (context, imageRect, image);
  225321. }
  225322. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  225323. CGContextRestoreGState (context);
  225324. }
  225325. void drawLine (const Line<float>& line)
  225326. {
  225327. CGContextSetLineCap (context, kCGLineCapSquare);
  225328. CGContextSetLineWidth (context, 1.0f);
  225329. CGContextSetRGBStrokeColor (context,
  225330. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  225331. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  225332. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  225333. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  225334. CGContextStrokeLineSegments (context, cgLine, 1);
  225335. }
  225336. void drawVerticalLine (const int x, float top, float bottom)
  225337. {
  225338. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  225339. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  225340. #else
  225341. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  225342. // the x co-ord slightly to trick it..
  225343. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  225344. #endif
  225345. }
  225346. void drawHorizontalLine (const int y, float left, float right)
  225347. {
  225348. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  225349. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  225350. #else
  225351. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  225352. // the x co-ord slightly to trick it..
  225353. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  225354. #endif
  225355. }
  225356. void setFont (const Font& newFont)
  225357. {
  225358. if (state->font != newFont)
  225359. {
  225360. state->fontRef = 0;
  225361. state->font = newFont;
  225362. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  225363. if (mf != 0)
  225364. {
  225365. state->fontRef = mf->fontRef;
  225366. CGContextSetFont (context, state->fontRef);
  225367. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  225368. state->fontTransform = mf->renderingTransform;
  225369. state->fontTransform.a *= state->font.getHorizontalScale();
  225370. CGContextSetTextMatrix (context, state->fontTransform);
  225371. }
  225372. }
  225373. }
  225374. const Font getFont()
  225375. {
  225376. return state->font;
  225377. }
  225378. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  225379. {
  225380. if (state->fontRef != 0 && state->fillType.isColour())
  225381. {
  225382. if (transform.isOnlyTranslation())
  225383. {
  225384. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  225385. CGGlyph g = glyphNumber;
  225386. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  225387. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  225388. }
  225389. else
  225390. {
  225391. CGContextSaveGState (context);
  225392. flip();
  225393. applyTransform (transform);
  225394. CGAffineTransform t = state->fontTransform;
  225395. t.d = -t.d;
  225396. CGContextSetTextMatrix (context, t);
  225397. CGGlyph g = glyphNumber;
  225398. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  225399. CGContextRestoreGState (context);
  225400. }
  225401. }
  225402. else
  225403. {
  225404. Path p;
  225405. Font& f = state->font;
  225406. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  225407. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  225408. .followedBy (transform));
  225409. }
  225410. }
  225411. private:
  225412. CGContextRef context;
  225413. const CGFloat flipHeight;
  225414. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  225415. CGFunctionCallbacks gradientCallbacks;
  225416. mutable Rectangle<int> lastClipRect;
  225417. mutable bool lastClipRectIsValid;
  225418. struct SavedState
  225419. {
  225420. SavedState()
  225421. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  225422. {
  225423. }
  225424. SavedState (const SavedState& other)
  225425. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  225426. fontTransform (other.fontTransform)
  225427. {
  225428. }
  225429. ~SavedState()
  225430. {
  225431. }
  225432. FillType fillType;
  225433. Font font;
  225434. CGFontRef fontRef;
  225435. CGAffineTransform fontTransform;
  225436. };
  225437. ScopedPointer <SavedState> state;
  225438. OwnedArray <SavedState> stateStack;
  225439. HeapBlock <PixelARGB> gradientLookupTable;
  225440. int numGradientLookupEntries;
  225441. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  225442. {
  225443. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  225444. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  225445. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  225446. colour.unpremultiply();
  225447. outData[0] = colour.getRed() / 255.0f;
  225448. outData[1] = colour.getGreen() / 255.0f;
  225449. outData[2] = colour.getBlue() / 255.0f;
  225450. outData[3] = colour.getAlpha() / 255.0f;
  225451. }
  225452. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  225453. {
  225454. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable);
  225455. --numGradientLookupEntries;
  225456. CGShadingRef result = 0;
  225457. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  225458. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  225459. if (gradient.isRadial)
  225460. {
  225461. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  225462. p1, gradient.point1.getDistanceFrom (gradient.point2),
  225463. function, true, true);
  225464. }
  225465. else
  225466. {
  225467. result = CGShadingCreateAxial (rgbColourSpace, p1,
  225468. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  225469. function, true, true);
  225470. }
  225471. CGFunctionRelease (function);
  225472. return result;
  225473. }
  225474. void drawGradient()
  225475. {
  225476. flip();
  225477. applyTransform (state->fillType.transform);
  225478. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  225479. // you draw a gradient with high quality interp enabled).
  225480. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  225481. CGContextSetAlpha (context, state->fillType.getOpacity());
  225482. CGContextDrawShading (context, shading);
  225483. CGShadingRelease (shading);
  225484. }
  225485. void createPath (const Path& path) const
  225486. {
  225487. CGContextBeginPath (context);
  225488. Path::Iterator i (path);
  225489. while (i.next())
  225490. {
  225491. switch (i.elementType)
  225492. {
  225493. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  225494. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  225495. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  225496. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  225497. case Path::Iterator::closePath: CGContextClosePath (context); break;
  225498. default: jassertfalse; break;
  225499. }
  225500. }
  225501. }
  225502. void createPath (const Path& path, const AffineTransform& transform) const
  225503. {
  225504. CGContextBeginPath (context);
  225505. Path::Iterator i (path);
  225506. while (i.next())
  225507. {
  225508. switch (i.elementType)
  225509. {
  225510. case Path::Iterator::startNewSubPath:
  225511. transform.transformPoint (i.x1, i.y1);
  225512. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  225513. break;
  225514. case Path::Iterator::lineTo:
  225515. transform.transformPoint (i.x1, i.y1);
  225516. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  225517. break;
  225518. case Path::Iterator::quadraticTo:
  225519. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  225520. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  225521. break;
  225522. case Path::Iterator::cubicTo:
  225523. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  225524. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  225525. break;
  225526. case Path::Iterator::closePath:
  225527. CGContextClosePath (context); break;
  225528. default:
  225529. jassertfalse;
  225530. break;
  225531. }
  225532. }
  225533. }
  225534. void flip() const
  225535. {
  225536. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  225537. }
  225538. void applyTransform (const AffineTransform& transform) const
  225539. {
  225540. CGAffineTransform t;
  225541. t.a = transform.mat00;
  225542. t.b = transform.mat10;
  225543. t.c = transform.mat01;
  225544. t.d = transform.mat11;
  225545. t.tx = transform.mat02;
  225546. t.ty = transform.mat12;
  225547. CGContextConcatCTM (context, t);
  225548. }
  225549. CoreGraphicsContext (const CoreGraphicsContext&);
  225550. CoreGraphicsContext& operator= (const CoreGraphicsContext&);
  225551. };
  225552. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  225553. {
  225554. return new CoreGraphicsContext (context, height);
  225555. }
  225556. #endif
  225557. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  225558. /*** Start of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  225559. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225560. // compiled on its own).
  225561. #if JUCE_INCLUDED_FILE
  225562. class UIViewComponentPeer;
  225563. END_JUCE_NAMESPACE
  225564. #define JuceUIView MakeObjCClassName(JuceUIView)
  225565. @interface JuceUIView : UIView <UITextFieldDelegate>
  225566. {
  225567. @public
  225568. UIViewComponentPeer* owner;
  225569. UITextField *hiddenTextField;
  225570. }
  225571. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner withFrame: (CGRect) frame;
  225572. - (void) dealloc;
  225573. - (void) drawRect: (CGRect) r;
  225574. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event;
  225575. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event;
  225576. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event;
  225577. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event;
  225578. - (BOOL) becomeFirstResponder;
  225579. - (BOOL) resignFirstResponder;
  225580. - (BOOL) canBecomeFirstResponder;
  225581. - (void) asyncRepaint: (id) rect;
  225582. - (BOOL) textField: (UITextField*) textField shouldChangeCharactersInRange: (NSRange) range replacementString: (NSString*) string;
  225583. - (BOOL) textFieldShouldClear: (UITextField*) textField;
  225584. - (BOOL) textFieldShouldReturn: (UITextField*) textField;
  225585. @end
  225586. #define JuceUIWindow MakeObjCClassName(JuceUIWindow)
  225587. @interface JuceUIWindow : UIWindow
  225588. {
  225589. @private
  225590. UIViewComponentPeer* owner;
  225591. bool isZooming;
  225592. }
  225593. - (void) setOwner: (UIViewComponentPeer*) owner;
  225594. - (void) becomeKeyWindow;
  225595. @end
  225596. BEGIN_JUCE_NAMESPACE
  225597. class UIViewComponentPeer : public ComponentPeer,
  225598. public FocusChangeListener
  225599. {
  225600. public:
  225601. UIViewComponentPeer (Component* const component,
  225602. const int windowStyleFlags,
  225603. UIView* viewToAttachTo);
  225604. ~UIViewComponentPeer();
  225605. void* getNativeHandle() const;
  225606. void setVisible (bool shouldBeVisible);
  225607. void setTitle (const String& title);
  225608. void setPosition (int x, int y);
  225609. void setSize (int w, int h);
  225610. void setBounds (int x, int y, int w, int h, bool isNowFullScreen);
  225611. const Rectangle<int> getBounds() const;
  225612. const Rectangle<int> getBounds (const bool global) const;
  225613. const Point<int> getScreenPosition() const;
  225614. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition);
  225615. const Point<int> globalPositionToRelative (const Point<int>& screenPosition);
  225616. void setMinimised (bool shouldBeMinimised);
  225617. bool isMinimised() const;
  225618. void setFullScreen (bool shouldBeFullScreen);
  225619. bool isFullScreen() const;
  225620. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  225621. const BorderSize getFrameSize() const;
  225622. bool setAlwaysOnTop (bool alwaysOnTop);
  225623. void toFront (bool makeActiveWindow);
  225624. void toBehind (ComponentPeer* other);
  225625. void setIcon (const Image& newIcon);
  225626. virtual void drawRect (CGRect r);
  225627. virtual bool canBecomeKeyWindow();
  225628. virtual bool windowShouldClose();
  225629. virtual void redirectMovedOrResized();
  225630. virtual CGRect constrainRect (CGRect r);
  225631. virtual void viewFocusGain();
  225632. virtual void viewFocusLoss();
  225633. bool isFocused() const;
  225634. void grabFocus();
  225635. void textInputRequired (const Point<int>& position);
  225636. virtual BOOL textFieldReplaceCharacters (const Range<int>& range, const String& text);
  225637. virtual BOOL textFieldShouldClear();
  225638. virtual BOOL textFieldShouldReturn();
  225639. void updateHiddenTextContent (TextInputTarget* target);
  225640. void globalFocusChanged (Component*);
  225641. void handleTouches (UIEvent* e, bool isDown, bool isUp, bool isCancel);
  225642. void repaint (const Rectangle<int>& area);
  225643. void performAnyPendingRepaintsNow();
  225644. juce_UseDebuggingNewOperator
  225645. UIWindow* window;
  225646. JuceUIView* view;
  225647. bool isSharedWindow, fullScreen, insideDrawRect;
  225648. static ModifierKeys currentModifiers;
  225649. static int64 getMouseTime (UIEvent* e)
  225650. {
  225651. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  225652. + (int64) ([e timestamp] * 1000.0);
  225653. }
  225654. Array <UITouch*> currentTouches;
  225655. };
  225656. END_JUCE_NAMESPACE
  225657. @implementation JuceUIView
  225658. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner_
  225659. withFrame: (CGRect) frame
  225660. {
  225661. [super initWithFrame: frame];
  225662. owner = owner_;
  225663. hiddenTextField = [[UITextField alloc] initWithFrame: CGRectMake (0, 0, 0, 0)];
  225664. [self addSubview: hiddenTextField];
  225665. hiddenTextField.delegate = self;
  225666. return self;
  225667. }
  225668. - (void) dealloc
  225669. {
  225670. [hiddenTextField removeFromSuperview];
  225671. [hiddenTextField release];
  225672. [super dealloc];
  225673. }
  225674. - (void) drawRect: (CGRect) r
  225675. {
  225676. if (owner != 0)
  225677. owner->drawRect (r);
  225678. }
  225679. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  225680. {
  225681. return false;
  225682. }
  225683. ModifierKeys UIViewComponentPeer::currentModifiers;
  225684. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  225685. {
  225686. return UIViewComponentPeer::currentModifiers;
  225687. }
  225688. void ModifierKeys::updateCurrentModifiers() throw()
  225689. {
  225690. currentModifiers = UIViewComponentPeer::currentModifiers;
  225691. }
  225692. JUCE_NAMESPACE::Point<int> juce_lastMousePos;
  225693. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event
  225694. {
  225695. if (owner != 0)
  225696. owner->handleTouches (event, true, false, false);
  225697. }
  225698. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event
  225699. {
  225700. if (owner != 0)
  225701. owner->handleTouches (event, false, false, false);
  225702. }
  225703. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event
  225704. {
  225705. if (owner != 0)
  225706. owner->handleTouches (event, false, true, false);
  225707. }
  225708. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event
  225709. {
  225710. if (owner != 0)
  225711. owner->handleTouches (event, false, true, true);
  225712. [self touchesEnded: touches withEvent: event];
  225713. }
  225714. - (BOOL) becomeFirstResponder
  225715. {
  225716. if (owner != 0)
  225717. owner->viewFocusGain();
  225718. return true;
  225719. }
  225720. - (BOOL) resignFirstResponder
  225721. {
  225722. if (owner != 0)
  225723. owner->viewFocusLoss();
  225724. return true;
  225725. }
  225726. - (BOOL) canBecomeFirstResponder
  225727. {
  225728. return owner != 0 && owner->canBecomeKeyWindow();
  225729. }
  225730. - (void) asyncRepaint: (id) rect
  225731. {
  225732. CGRect* r = (CGRect*) [((NSData*) rect) bytes];
  225733. [self setNeedsDisplayInRect: *r];
  225734. }
  225735. - (BOOL) textField: (UITextField*) textField shouldChangeCharactersInRange: (NSRange) range replacementString: (NSString*) text
  225736. {
  225737. return owner->textFieldReplaceCharacters (Range<int> (range.location, range.location + range.length),
  225738. nsStringToJuce (text));
  225739. }
  225740. - (BOOL) textFieldShouldClear: (UITextField*) textField
  225741. {
  225742. return owner->textFieldShouldClear();
  225743. }
  225744. - (BOOL) textFieldShouldReturn: (UITextField*) textField
  225745. {
  225746. return owner->textFieldShouldReturn();
  225747. }
  225748. @end
  225749. @implementation JuceUIWindow
  225750. - (void) setOwner: (UIViewComponentPeer*) owner_
  225751. {
  225752. owner = owner_;
  225753. isZooming = false;
  225754. }
  225755. - (void) becomeKeyWindow
  225756. {
  225757. [super becomeKeyWindow];
  225758. if (owner != 0)
  225759. owner->grabFocus();
  225760. }
  225761. @end
  225762. BEGIN_JUCE_NAMESPACE
  225763. UIViewComponentPeer::UIViewComponentPeer (Component* const component,
  225764. const int windowStyleFlags,
  225765. UIView* viewToAttachTo)
  225766. : ComponentPeer (component, windowStyleFlags),
  225767. window (0),
  225768. view (0),
  225769. isSharedWindow (viewToAttachTo != 0),
  225770. fullScreen (false),
  225771. insideDrawRect (false)
  225772. {
  225773. CGRect r = CGRectMake (0, 0, (float) component->getWidth(), (float) component->getHeight());
  225774. view = [[JuceUIView alloc] initWithOwner: this withFrame: r];
  225775. if (isSharedWindow)
  225776. {
  225777. window = [viewToAttachTo window];
  225778. [viewToAttachTo addSubview: view];
  225779. setVisible (component->isVisible());
  225780. }
  225781. else
  225782. {
  225783. r.origin.x = (float) component->getX();
  225784. r.origin.y = (float) component->getY();
  225785. r.origin.y = [[UIScreen mainScreen] bounds].size.height - (r.origin.y + r.size.height);
  225786. window = [[JuceUIWindow alloc] init];
  225787. window.frame = r;
  225788. window.opaque = component->isOpaque();
  225789. view.opaque = component->isOpaque();
  225790. window.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  225791. view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  225792. [((JuceUIWindow*) window) setOwner: this];
  225793. if (component->isAlwaysOnTop())
  225794. window.windowLevel = UIWindowLevelAlert;
  225795. [window addSubview: view];
  225796. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  225797. view.hidden = ! component->isVisible();
  225798. window.hidden = ! component->isVisible();
  225799. view.multipleTouchEnabled = YES;
  225800. }
  225801. setTitle (component->getName());
  225802. Desktop::getInstance().addFocusChangeListener (this);
  225803. }
  225804. UIViewComponentPeer::~UIViewComponentPeer()
  225805. {
  225806. Desktop::getInstance().removeFocusChangeListener (this);
  225807. view->owner = 0;
  225808. [view removeFromSuperview];
  225809. [view release];
  225810. if (! isSharedWindow)
  225811. {
  225812. [((JuceUIWindow*) window) setOwner: 0];
  225813. [window release];
  225814. }
  225815. }
  225816. void* UIViewComponentPeer::getNativeHandle() const
  225817. {
  225818. return view;
  225819. }
  225820. void UIViewComponentPeer::setVisible (bool shouldBeVisible)
  225821. {
  225822. view.hidden = ! shouldBeVisible;
  225823. if (! isSharedWindow)
  225824. window.hidden = ! shouldBeVisible;
  225825. }
  225826. void UIViewComponentPeer::setTitle (const String& title)
  225827. {
  225828. // xxx is this possible?
  225829. }
  225830. void UIViewComponentPeer::setPosition (int x, int y)
  225831. {
  225832. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  225833. }
  225834. void UIViewComponentPeer::setSize (int w, int h)
  225835. {
  225836. setBounds (component->getX(), component->getY(), w, h, false);
  225837. }
  225838. void UIViewComponentPeer::setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  225839. {
  225840. fullScreen = isNowFullScreen;
  225841. w = jmax (0, w);
  225842. h = jmax (0, h);
  225843. CGRect r;
  225844. r.origin.x = (float) x;
  225845. r.origin.y = (float) y;
  225846. r.size.width = (float) w;
  225847. r.size.height = (float) h;
  225848. if (isSharedWindow)
  225849. {
  225850. //r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  225851. if ([view frame].size.width != r.size.width
  225852. || [view frame].size.height != r.size.height)
  225853. [view setNeedsDisplay];
  225854. view.frame = r;
  225855. }
  225856. else
  225857. {
  225858. window.frame = r;
  225859. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  225860. }
  225861. }
  225862. const Rectangle<int> UIViewComponentPeer::getBounds (const bool global) const
  225863. {
  225864. CGRect r = [view frame];
  225865. if (global && [view window] != 0)
  225866. {
  225867. r = [view convertRect: r toView: nil];
  225868. CGRect wr = [[view window] frame];
  225869. r.origin.x += wr.origin.x;
  225870. r.origin.y += wr.origin.y;
  225871. }
  225872. return Rectangle<int> ((int) r.origin.x, (int) r.origin.y,
  225873. (int) r.size.width, (int) r.size.height);
  225874. }
  225875. const Rectangle<int> UIViewComponentPeer::getBounds() const
  225876. {
  225877. return getBounds (! isSharedWindow);
  225878. }
  225879. const Point<int> UIViewComponentPeer::getScreenPosition() const
  225880. {
  225881. return getBounds (true).getPosition();
  225882. }
  225883. const Point<int> UIViewComponentPeer::relativePositionToGlobal (const Point<int>& relativePosition)
  225884. {
  225885. return relativePosition + getScreenPosition();
  225886. }
  225887. const Point<int> UIViewComponentPeer::globalPositionToRelative (const Point<int>& screenPosition)
  225888. {
  225889. return screenPosition - getScreenPosition();
  225890. }
  225891. CGRect UIViewComponentPeer::constrainRect (CGRect r)
  225892. {
  225893. if (constrainer != 0)
  225894. {
  225895. CGRect current = [window frame];
  225896. current.origin.y = [[UIScreen mainScreen] bounds].size.height - current.origin.y - current.size.height;
  225897. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.origin.y - r.size.height;
  225898. Rectangle<int> pos ((int) r.origin.x, (int) r.origin.y,
  225899. (int) r.size.width, (int) r.size.height);
  225900. Rectangle<int> original ((int) current.origin.x, (int) current.origin.y,
  225901. (int) current.size.width, (int) current.size.height);
  225902. constrainer->checkBounds (pos, original,
  225903. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  225904. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  225905. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  225906. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  225907. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  225908. r.origin.x = pos.getX();
  225909. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.size.height - pos.getY();
  225910. r.size.width = pos.getWidth();
  225911. r.size.height = pos.getHeight();
  225912. }
  225913. return r;
  225914. }
  225915. void UIViewComponentPeer::setMinimised (bool shouldBeMinimised)
  225916. {
  225917. // xxx
  225918. }
  225919. bool UIViewComponentPeer::isMinimised() const
  225920. {
  225921. return false;
  225922. }
  225923. void UIViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  225924. {
  225925. if (! isSharedWindow)
  225926. {
  225927. Rectangle<int> r (lastNonFullscreenBounds);
  225928. setMinimised (false);
  225929. if (fullScreen != shouldBeFullScreen)
  225930. {
  225931. if (shouldBeFullScreen)
  225932. r = Desktop::getInstance().getMainMonitorArea();
  225933. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  225934. if (r != getComponent()->getBounds() && ! r.isEmpty())
  225935. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  225936. }
  225937. }
  225938. }
  225939. bool UIViewComponentPeer::isFullScreen() const
  225940. {
  225941. return fullScreen;
  225942. }
  225943. bool UIViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  225944. {
  225945. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  225946. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  225947. return false;
  225948. CGPoint p;
  225949. p.x = (float) position.getX();
  225950. p.y = (float) position.getY();
  225951. UIView* v = [view hitTest: p withEvent: nil];
  225952. if (trueIfInAChildWindow)
  225953. return v != nil;
  225954. return v == view;
  225955. }
  225956. const BorderSize UIViewComponentPeer::getFrameSize() const
  225957. {
  225958. BorderSize b;
  225959. if (! isSharedWindow)
  225960. {
  225961. CGRect v = [view convertRect: [view frame] toView: nil];
  225962. CGRect w = [window frame];
  225963. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  225964. b.setBottom ((int) v.origin.y);
  225965. b.setLeft ((int) v.origin.x);
  225966. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  225967. }
  225968. return b;
  225969. }
  225970. bool UIViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  225971. {
  225972. if (! isSharedWindow)
  225973. window.windowLevel = alwaysOnTop ? UIWindowLevelAlert : UIWindowLevelNormal;
  225974. return true;
  225975. }
  225976. void UIViewComponentPeer::toFront (bool makeActiveWindow)
  225977. {
  225978. if (isSharedWindow)
  225979. [[view superview] bringSubviewToFront: view];
  225980. if (window != 0 && component->isVisible())
  225981. [window makeKeyAndVisible];
  225982. }
  225983. void UIViewComponentPeer::toBehind (ComponentPeer* other)
  225984. {
  225985. UIViewComponentPeer* const otherPeer = dynamic_cast <UIViewComponentPeer*> (other);
  225986. jassert (otherPeer != 0); // wrong type of window?
  225987. if (otherPeer != 0)
  225988. {
  225989. if (isSharedWindow)
  225990. {
  225991. [[view superview] insertSubview: view belowSubview: otherPeer->view];
  225992. }
  225993. else
  225994. {
  225995. jassertfalse; // don't know how to do this
  225996. }
  225997. }
  225998. }
  225999. void UIViewComponentPeer::setIcon (const Image& /*newIcon*/)
  226000. {
  226001. // to do..
  226002. }
  226003. void UIViewComponentPeer::handleTouches (UIEvent* event, const bool isDown, const bool isUp, bool isCancel)
  226004. {
  226005. NSArray* touches = [[event touchesForView: view] allObjects];
  226006. for (unsigned int i = 0; i < [touches count]; ++i)
  226007. {
  226008. UITouch* touch = [touches objectAtIndex: i];
  226009. CGPoint p = [touch locationInView: view];
  226010. const Point<int> pos ((int) p.x, (int) p.y);
  226011. juce_lastMousePos = pos + getScreenPosition();
  226012. const int64 time = getMouseTime (event);
  226013. int touchIndex = currentTouches.indexOf (touch);
  226014. if (touchIndex < 0)
  226015. {
  226016. touchIndex = currentTouches.size();
  226017. currentTouches.add (touch);
  226018. }
  226019. if (isDown)
  226020. {
  226021. currentModifiers = currentModifiers.withoutMouseButtons();
  226022. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  226023. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  226024. }
  226025. else if (isUp)
  226026. {
  226027. currentModifiers = currentModifiers.withoutMouseButtons();
  226028. currentTouches.remove (touchIndex);
  226029. }
  226030. if (isCancel)
  226031. currentTouches.clear();
  226032. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  226033. }
  226034. }
  226035. static UIViewComponentPeer* currentlyFocusedPeer = 0;
  226036. void UIViewComponentPeer::viewFocusGain()
  226037. {
  226038. if (currentlyFocusedPeer != this)
  226039. {
  226040. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  226041. currentlyFocusedPeer->handleFocusLoss();
  226042. currentlyFocusedPeer = this;
  226043. handleFocusGain();
  226044. }
  226045. }
  226046. void UIViewComponentPeer::viewFocusLoss()
  226047. {
  226048. if (currentlyFocusedPeer == this)
  226049. {
  226050. currentlyFocusedPeer = 0;
  226051. handleFocusLoss();
  226052. }
  226053. }
  226054. void juce_HandleProcessFocusChange()
  226055. {
  226056. if (UIViewComponentPeer::isValidPeer (currentlyFocusedPeer))
  226057. {
  226058. if (Process::isForegroundProcess())
  226059. {
  226060. currentlyFocusedPeer->handleFocusGain();
  226061. ComponentPeer::bringModalComponentToFront();
  226062. }
  226063. else
  226064. {
  226065. currentlyFocusedPeer->handleFocusLoss();
  226066. // turn kiosk mode off if we lose focus..
  226067. Desktop::getInstance().setKioskModeComponent (0);
  226068. }
  226069. }
  226070. }
  226071. bool UIViewComponentPeer::isFocused() const
  226072. {
  226073. return isSharedWindow ? this == currentlyFocusedPeer
  226074. : (window != 0 && [window isKeyWindow]);
  226075. }
  226076. void UIViewComponentPeer::grabFocus()
  226077. {
  226078. if (window != 0)
  226079. {
  226080. [window makeKeyWindow];
  226081. viewFocusGain();
  226082. }
  226083. }
  226084. void UIViewComponentPeer::textInputRequired (const Point<int>&)
  226085. {
  226086. }
  226087. void UIViewComponentPeer::updateHiddenTextContent (TextInputTarget* target)
  226088. {
  226089. view->hiddenTextField.text = juceStringToNS (target->getTextInRange (Range<int> (0, target->getHighlightedRegion().getStart())));
  226090. }
  226091. BOOL UIViewComponentPeer::textFieldReplaceCharacters (const Range<int>& range, const String& text)
  226092. {
  226093. TextInputTarget* const target = findCurrentTextInputTarget();
  226094. if (target != 0)
  226095. {
  226096. const Range<int> currentSelection (target->getHighlightedRegion());
  226097. if (range.getLength() == 1 && text.isEmpty()) // (detect backspace)
  226098. if (currentSelection.isEmpty())
  226099. target->setHighlightedRegion (currentSelection.withStart (currentSelection.getStart() - 1));
  226100. target->insertTextAtCaret (text);
  226101. updateHiddenTextContent (target);
  226102. }
  226103. return NO;
  226104. }
  226105. BOOL UIViewComponentPeer::textFieldShouldClear()
  226106. {
  226107. TextInputTarget* const target = findCurrentTextInputTarget();
  226108. if (target != 0)
  226109. {
  226110. target->setHighlightedRegion (Range<int> (0, std::numeric_limits<int>::max()));
  226111. target->insertTextAtCaret (String::empty);
  226112. updateHiddenTextContent (target);
  226113. }
  226114. return YES;
  226115. }
  226116. BOOL UIViewComponentPeer::textFieldShouldReturn()
  226117. {
  226118. TextInputTarget* const target = findCurrentTextInputTarget();
  226119. if (target != 0)
  226120. {
  226121. target->insertTextAtCaret ("\n");
  226122. updateHiddenTextContent (target);
  226123. }
  226124. return YES;
  226125. }
  226126. void UIViewComponentPeer::globalFocusChanged (Component*)
  226127. {
  226128. TextInputTarget* const target = findCurrentTextInputTarget();
  226129. if (target != 0)
  226130. {
  226131. Component* comp = dynamic_cast<Component*> (target);
  226132. Point<int> pos (comp->relativePositionToOtherComponent (component, Point<int>()));
  226133. view->hiddenTextField.frame = CGRectMake (pos.getX(), pos.getY(), 0, 0);
  226134. updateHiddenTextContent (target);
  226135. [view->hiddenTextField becomeFirstResponder];
  226136. }
  226137. else
  226138. {
  226139. [view->hiddenTextField resignFirstResponder];
  226140. }
  226141. }
  226142. void UIViewComponentPeer::drawRect (CGRect r)
  226143. {
  226144. if (r.size.width < 1.0f || r.size.height < 1.0f)
  226145. return;
  226146. CGContextRef cg = UIGraphicsGetCurrentContext();
  226147. if (! component->isOpaque())
  226148. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  226149. CGContextConcatCTM (cg, CGAffineTransformMake (1, 0, 0, -1, 0, view.bounds.size.height));
  226150. CoreGraphicsContext g (cg, view.bounds.size.height);
  226151. insideDrawRect = true;
  226152. handlePaint (g);
  226153. insideDrawRect = false;
  226154. }
  226155. bool UIViewComponentPeer::canBecomeKeyWindow()
  226156. {
  226157. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  226158. }
  226159. bool UIViewComponentPeer::windowShouldClose()
  226160. {
  226161. if (! isValidPeer (this))
  226162. return YES;
  226163. handleUserClosingWindow();
  226164. return NO;
  226165. }
  226166. void UIViewComponentPeer::redirectMovedOrResized()
  226167. {
  226168. handleMovedOrResized();
  226169. }
  226170. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  226171. {
  226172. }
  226173. class AsyncRepaintMessage : public CallbackMessage
  226174. {
  226175. public:
  226176. UIViewComponentPeer* const peer;
  226177. const Rectangle<int> rect;
  226178. AsyncRepaintMessage (UIViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  226179. : peer (peer_), rect (rect_)
  226180. {
  226181. }
  226182. void messageCallback()
  226183. {
  226184. if (ComponentPeer::isValidPeer (peer))
  226185. peer->repaint (rect);
  226186. }
  226187. };
  226188. void UIViewComponentPeer::repaint (const Rectangle<int>& area)
  226189. {
  226190. if (insideDrawRect || ! MessageManager::getInstance()->isThisTheMessageThread())
  226191. {
  226192. (new AsyncRepaintMessage (this, area))->post();
  226193. }
  226194. else
  226195. {
  226196. [view setNeedsDisplayInRect: CGRectMake ((float) area.getX(), (float) area.getY(),
  226197. (float) area.getWidth(), (float) area.getHeight())];
  226198. }
  226199. }
  226200. void UIViewComponentPeer::performAnyPendingRepaintsNow()
  226201. {
  226202. }
  226203. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  226204. {
  226205. return new UIViewComponentPeer (this, styleFlags, (UIView*) windowToAttachTo);
  226206. }
  226207. const Image juce_createIconForFile (const File& file)
  226208. {
  226209. return Image();
  226210. }
  226211. void Desktop::createMouseInputSources()
  226212. {
  226213. for (int i = 0; i < 10; ++i)
  226214. mouseSources.add (new MouseInputSource (i, false));
  226215. }
  226216. bool Desktop::canUseSemiTransparentWindows() throw()
  226217. {
  226218. return true;
  226219. }
  226220. const Point<int> Desktop::getMousePosition()
  226221. {
  226222. return juce_lastMousePos;
  226223. }
  226224. void Desktop::setMousePosition (const Point<int>&)
  226225. {
  226226. }
  226227. const int KeyPress::spaceKey = ' ';
  226228. const int KeyPress::returnKey = 0x0d;
  226229. const int KeyPress::escapeKey = 0x1b;
  226230. const int KeyPress::backspaceKey = 0x7f;
  226231. const int KeyPress::leftKey = 0x1000;
  226232. const int KeyPress::rightKey = 0x1001;
  226233. const int KeyPress::upKey = 0x1002;
  226234. const int KeyPress::downKey = 0x1003;
  226235. const int KeyPress::pageUpKey = 0x1004;
  226236. const int KeyPress::pageDownKey = 0x1005;
  226237. const int KeyPress::endKey = 0x1006;
  226238. const int KeyPress::homeKey = 0x1007;
  226239. const int KeyPress::deleteKey = 0x1008;
  226240. const int KeyPress::insertKey = -1;
  226241. const int KeyPress::tabKey = 9;
  226242. const int KeyPress::F1Key = 0x2001;
  226243. const int KeyPress::F2Key = 0x2002;
  226244. const int KeyPress::F3Key = 0x2003;
  226245. const int KeyPress::F4Key = 0x2004;
  226246. const int KeyPress::F5Key = 0x2005;
  226247. const int KeyPress::F6Key = 0x2006;
  226248. const int KeyPress::F7Key = 0x2007;
  226249. const int KeyPress::F8Key = 0x2008;
  226250. const int KeyPress::F9Key = 0x2009;
  226251. const int KeyPress::F10Key = 0x200a;
  226252. const int KeyPress::F11Key = 0x200b;
  226253. const int KeyPress::F12Key = 0x200c;
  226254. const int KeyPress::F13Key = 0x200d;
  226255. const int KeyPress::F14Key = 0x200e;
  226256. const int KeyPress::F15Key = 0x200f;
  226257. const int KeyPress::F16Key = 0x2010;
  226258. const int KeyPress::numberPad0 = 0x30020;
  226259. const int KeyPress::numberPad1 = 0x30021;
  226260. const int KeyPress::numberPad2 = 0x30022;
  226261. const int KeyPress::numberPad3 = 0x30023;
  226262. const int KeyPress::numberPad4 = 0x30024;
  226263. const int KeyPress::numberPad5 = 0x30025;
  226264. const int KeyPress::numberPad6 = 0x30026;
  226265. const int KeyPress::numberPad7 = 0x30027;
  226266. const int KeyPress::numberPad8 = 0x30028;
  226267. const int KeyPress::numberPad9 = 0x30029;
  226268. const int KeyPress::numberPadAdd = 0x3002a;
  226269. const int KeyPress::numberPadSubtract = 0x3002b;
  226270. const int KeyPress::numberPadMultiply = 0x3002c;
  226271. const int KeyPress::numberPadDivide = 0x3002d;
  226272. const int KeyPress::numberPadSeparator = 0x3002e;
  226273. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  226274. const int KeyPress::numberPadEquals = 0x30030;
  226275. const int KeyPress::numberPadDelete = 0x30031;
  226276. const int KeyPress::playKey = 0x30000;
  226277. const int KeyPress::stopKey = 0x30001;
  226278. const int KeyPress::fastForwardKey = 0x30002;
  226279. const int KeyPress::rewindKey = 0x30003;
  226280. #endif
  226281. /*** End of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  226282. /*** Start of inlined file: juce_iphone_MessageManager.mm ***/
  226283. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226284. // compiled on its own).
  226285. #if JUCE_INCLUDED_FILE
  226286. struct CallbackMessagePayload
  226287. {
  226288. MessageCallbackFunction* function;
  226289. void* parameter;
  226290. void* volatile result;
  226291. bool volatile hasBeenExecuted;
  226292. };
  226293. END_JUCE_NAMESPACE
  226294. @interface JuceCustomMessageHandler : NSObject
  226295. {
  226296. }
  226297. - (void) performCallback: (id) info;
  226298. @end
  226299. @implementation JuceCustomMessageHandler
  226300. - (void) performCallback: (id) info
  226301. {
  226302. if ([info isKindOfClass: [NSData class]])
  226303. {
  226304. JUCE_NAMESPACE::CallbackMessagePayload* pl = (JUCE_NAMESPACE::CallbackMessagePayload*) [((NSData*) info) bytes];
  226305. if (pl != 0)
  226306. {
  226307. pl->result = (*pl->function) (pl->parameter);
  226308. pl->hasBeenExecuted = true;
  226309. }
  226310. }
  226311. else
  226312. {
  226313. jassertfalse; // should never get here!
  226314. }
  226315. }
  226316. @end
  226317. BEGIN_JUCE_NAMESPACE
  226318. void MessageManager::runDispatchLoop()
  226319. {
  226320. jassert (isThisTheMessageThread()); // must only be called by the message thread
  226321. runDispatchLoopUntil (-1);
  226322. }
  226323. void MessageManager::stopDispatchLoop()
  226324. {
  226325. exit (0); // iPhone apps get no mercy..
  226326. }
  226327. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  226328. {
  226329. const ScopedAutoReleasePool pool;
  226330. jassert (isThisTheMessageThread()); // must only be called by the message thread
  226331. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  226332. NSDate* endDate = [NSDate dateWithTimeIntervalSinceNow: millisecondsToRunFor * 0.001];
  226333. while (! quitMessagePosted)
  226334. {
  226335. const ScopedAutoReleasePool pool;
  226336. [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
  226337. beforeDate: endDate];
  226338. if (millisecondsToRunFor >= 0 && Time::getMillisecondCounter() >= endTime)
  226339. break;
  226340. }
  226341. return ! quitMessagePosted;
  226342. }
  226343. static CFRunLoopRef runLoop = 0;
  226344. static CFRunLoopSourceRef runLoopSource = 0;
  226345. static OwnedArray <Message, CriticalSection>* pendingMessages = 0;
  226346. static JuceCustomMessageHandler* juceCustomMessageHandler = 0;
  226347. static void runLoopSourceCallback (void*)
  226348. {
  226349. if (pendingMessages != 0)
  226350. {
  226351. int numDispatched = 0;
  226352. do
  226353. {
  226354. Message* const nextMessage = pendingMessages->removeAndReturn (0);
  226355. if (nextMessage == 0)
  226356. return;
  226357. const ScopedAutoReleasePool pool;
  226358. MessageManager::getInstance()->deliverMessage (nextMessage);
  226359. } while (++numDispatched <= 4);
  226360. CFRunLoopSourceSignal (runLoopSource);
  226361. CFRunLoopWakeUp (runLoop);
  226362. }
  226363. }
  226364. void MessageManager::doPlatformSpecificInitialisation()
  226365. {
  226366. pendingMessages = new OwnedArray <Message, CriticalSection>();
  226367. runLoop = CFRunLoopGetCurrent();
  226368. CFRunLoopSourceContext sourceContext;
  226369. zerostruct (sourceContext);
  226370. sourceContext.perform = runLoopSourceCallback;
  226371. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  226372. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  226373. if (juceCustomMessageHandler == 0)
  226374. juceCustomMessageHandler = [[JuceCustomMessageHandler alloc] init];
  226375. }
  226376. void MessageManager::doPlatformSpecificShutdown()
  226377. {
  226378. CFRunLoopSourceInvalidate (runLoopSource);
  226379. CFRelease (runLoopSource);
  226380. runLoopSource = 0;
  226381. deleteAndZero (pendingMessages);
  226382. if (juceCustomMessageHandler != 0)
  226383. {
  226384. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceCustomMessageHandler];
  226385. [juceCustomMessageHandler release];
  226386. juceCustomMessageHandler = 0;
  226387. }
  226388. }
  226389. bool juce_postMessageToSystemQueue (Message* message)
  226390. {
  226391. if (pendingMessages != 0)
  226392. {
  226393. pendingMessages->add (message);
  226394. CFRunLoopSourceSignal (runLoopSource);
  226395. CFRunLoopWakeUp (runLoop);
  226396. }
  226397. return true;
  226398. }
  226399. void MessageManager::broadcastMessage (const String& value) throw()
  226400. {
  226401. }
  226402. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  226403. void* data)
  226404. {
  226405. if (isThisTheMessageThread())
  226406. {
  226407. return (*callback) (data);
  226408. }
  226409. else
  226410. {
  226411. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  226412. // deadlock because the message manager is blocked from running, so can never
  226413. // call your function..
  226414. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  226415. const ScopedAutoReleasePool pool;
  226416. CallbackMessagePayload cmp;
  226417. cmp.function = callback;
  226418. cmp.parameter = data;
  226419. cmp.result = 0;
  226420. cmp.hasBeenExecuted = false;
  226421. [juceCustomMessageHandler performSelectorOnMainThread: @selector (performCallback:)
  226422. withObject: [NSData dataWithBytesNoCopy: &cmp
  226423. length: sizeof (cmp)
  226424. freeWhenDone: NO]
  226425. waitUntilDone: YES];
  226426. return cmp.result;
  226427. }
  226428. }
  226429. #endif
  226430. /*** End of inlined file: juce_iphone_MessageManager.mm ***/
  226431. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  226432. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226433. // compiled on its own).
  226434. #if JUCE_INCLUDED_FILE
  226435. #if JUCE_MAC
  226436. END_JUCE_NAMESPACE
  226437. using namespace JUCE_NAMESPACE;
  226438. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  226439. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  226440. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  226441. #else
  226442. @interface JuceFileChooserDelegate : NSObject
  226443. #endif
  226444. {
  226445. StringArray* filters;
  226446. }
  226447. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  226448. - (void) dealloc;
  226449. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  226450. @end
  226451. @implementation JuceFileChooserDelegate
  226452. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  226453. {
  226454. [super init];
  226455. filters = filters_;
  226456. return self;
  226457. }
  226458. - (void) dealloc
  226459. {
  226460. delete filters;
  226461. [super dealloc];
  226462. }
  226463. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  226464. {
  226465. (void) sender;
  226466. const File f (nsStringToJuce (filename));
  226467. for (int i = filters->size(); --i >= 0;)
  226468. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  226469. return true;
  226470. return f.isDirectory();
  226471. }
  226472. @end
  226473. BEGIN_JUCE_NAMESPACE
  226474. void FileChooser::showPlatformDialog (Array<File>& results,
  226475. const String& title,
  226476. const File& currentFileOrDirectory,
  226477. const String& filter,
  226478. bool selectsDirectory,
  226479. bool selectsFiles,
  226480. bool isSaveDialogue,
  226481. bool warnAboutOverwritingExistingFiles,
  226482. bool selectMultipleFiles,
  226483. FilePreviewComponent* extraInfoComponent)
  226484. {
  226485. const ScopedAutoReleasePool pool;
  226486. StringArray* filters = new StringArray();
  226487. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  226488. filters->trim();
  226489. filters->removeEmptyStrings();
  226490. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  226491. [delegate autorelease];
  226492. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  226493. : [NSOpenPanel openPanel];
  226494. [panel setTitle: juceStringToNS (title)];
  226495. if (! isSaveDialogue)
  226496. {
  226497. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  226498. [openPanel setCanChooseDirectories: selectsDirectory];
  226499. [openPanel setCanChooseFiles: selectsFiles];
  226500. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  226501. }
  226502. [panel setDelegate: delegate];
  226503. if (isSaveDialogue || selectsDirectory)
  226504. [panel setCanCreateDirectories: YES];
  226505. String directory, filename;
  226506. if (currentFileOrDirectory.isDirectory())
  226507. {
  226508. directory = currentFileOrDirectory.getFullPathName();
  226509. }
  226510. else
  226511. {
  226512. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  226513. filename = currentFileOrDirectory.getFileName();
  226514. }
  226515. if ([panel runModalForDirectory: juceStringToNS (directory)
  226516. file: juceStringToNS (filename)]
  226517. == NSOKButton)
  226518. {
  226519. if (isSaveDialogue)
  226520. {
  226521. results.add (File (nsStringToJuce ([panel filename])));
  226522. }
  226523. else
  226524. {
  226525. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  226526. NSArray* urls = [openPanel filenames];
  226527. for (unsigned int i = 0; i < [urls count]; ++i)
  226528. {
  226529. NSString* f = [urls objectAtIndex: i];
  226530. results.add (File (nsStringToJuce (f)));
  226531. }
  226532. }
  226533. }
  226534. [panel setDelegate: nil];
  226535. }
  226536. #else
  226537. void FileChooser::showPlatformDialog (Array<File>& results,
  226538. const String& title,
  226539. const File& currentFileOrDirectory,
  226540. const String& filter,
  226541. bool selectsDirectory,
  226542. bool selectsFiles,
  226543. bool isSaveDialogue,
  226544. bool warnAboutOverwritingExistingFiles,
  226545. bool selectMultipleFiles,
  226546. FilePreviewComponent* extraInfoComponent)
  226547. {
  226548. const ScopedAutoReleasePool pool;
  226549. jassertfalse; //xxx to do
  226550. }
  226551. #endif
  226552. #endif
  226553. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  226554. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  226555. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226556. // compiled on its own).
  226557. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  226558. #if JUCE_MAC
  226559. END_JUCE_NAMESPACE
  226560. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  226561. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  226562. {
  226563. CriticalSection* contextLock;
  226564. bool needsUpdate;
  226565. }
  226566. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  226567. - (bool) makeActive;
  226568. - (void) makeInactive;
  226569. - (void) reshape;
  226570. @end
  226571. @implementation ThreadSafeNSOpenGLView
  226572. - (id) initWithFrame: (NSRect) frameRect
  226573. pixelFormat: (NSOpenGLPixelFormat*) format
  226574. {
  226575. contextLock = new CriticalSection();
  226576. self = [super initWithFrame: frameRect pixelFormat: format];
  226577. if (self != nil)
  226578. [[NSNotificationCenter defaultCenter] addObserver: self
  226579. selector: @selector (_surfaceNeedsUpdate:)
  226580. name: NSViewGlobalFrameDidChangeNotification
  226581. object: self];
  226582. return self;
  226583. }
  226584. - (void) dealloc
  226585. {
  226586. [[NSNotificationCenter defaultCenter] removeObserver: self];
  226587. delete contextLock;
  226588. [super dealloc];
  226589. }
  226590. - (bool) makeActive
  226591. {
  226592. const ScopedLock sl (*contextLock);
  226593. if ([self openGLContext] == 0)
  226594. return false;
  226595. [[self openGLContext] makeCurrentContext];
  226596. if (needsUpdate)
  226597. {
  226598. [super update];
  226599. needsUpdate = false;
  226600. }
  226601. return true;
  226602. }
  226603. - (void) makeInactive
  226604. {
  226605. const ScopedLock sl (*contextLock);
  226606. [NSOpenGLContext clearCurrentContext];
  226607. }
  226608. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  226609. {
  226610. const ScopedLock sl (*contextLock);
  226611. needsUpdate = true;
  226612. }
  226613. - (void) update
  226614. {
  226615. const ScopedLock sl (*contextLock);
  226616. needsUpdate = true;
  226617. }
  226618. - (void) reshape
  226619. {
  226620. const ScopedLock sl (*contextLock);
  226621. needsUpdate = true;
  226622. }
  226623. @end
  226624. BEGIN_JUCE_NAMESPACE
  226625. class WindowedGLContext : public OpenGLContext
  226626. {
  226627. public:
  226628. WindowedGLContext (Component* const component,
  226629. const OpenGLPixelFormat& pixelFormat_,
  226630. NSOpenGLContext* sharedContext)
  226631. : renderContext (0),
  226632. pixelFormat (pixelFormat_)
  226633. {
  226634. jassert (component != 0);
  226635. NSOpenGLPixelFormatAttribute attribs [64];
  226636. int n = 0;
  226637. attribs[n++] = NSOpenGLPFADoubleBuffer;
  226638. attribs[n++] = NSOpenGLPFAAccelerated;
  226639. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  226640. attribs[n++] = NSOpenGLPFAColorSize;
  226641. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  226642. pixelFormat.greenBits,
  226643. pixelFormat.blueBits);
  226644. attribs[n++] = NSOpenGLPFAAlphaSize;
  226645. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  226646. attribs[n++] = NSOpenGLPFADepthSize;
  226647. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  226648. attribs[n++] = NSOpenGLPFAStencilSize;
  226649. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  226650. attribs[n++] = NSOpenGLPFAAccumSize;
  226651. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  226652. pixelFormat.accumulationBufferGreenBits,
  226653. pixelFormat.accumulationBufferBlueBits,
  226654. pixelFormat.accumulationBufferAlphaBits);
  226655. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  226656. attribs[n++] = NSOpenGLPFASampleBuffers;
  226657. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  226658. attribs[n++] = NSOpenGLPFAClosestPolicy;
  226659. attribs[n++] = NSOpenGLPFANoRecovery;
  226660. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  226661. NSOpenGLPixelFormat* format
  226662. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  226663. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  226664. pixelFormat: format];
  226665. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  226666. shareContext: sharedContext] autorelease];
  226667. const GLint swapInterval = 1;
  226668. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  226669. [view setOpenGLContext: renderContext];
  226670. [renderContext setView: view];
  226671. [format release];
  226672. viewHolder = new NSViewComponentInternal (view, component);
  226673. }
  226674. ~WindowedGLContext()
  226675. {
  226676. makeInactive();
  226677. [renderContext clearDrawable];
  226678. viewHolder = 0;
  226679. }
  226680. bool makeActive() const throw()
  226681. {
  226682. jassert (renderContext != 0);
  226683. [view makeActive];
  226684. return isActive();
  226685. }
  226686. bool makeInactive() const throw()
  226687. {
  226688. [view makeInactive];
  226689. return true;
  226690. }
  226691. bool isActive() const throw()
  226692. {
  226693. return [NSOpenGLContext currentContext] == renderContext;
  226694. }
  226695. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  226696. void* getRawContext() const throw() { return renderContext; }
  226697. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  226698. {
  226699. }
  226700. void swapBuffers()
  226701. {
  226702. [renderContext flushBuffer];
  226703. }
  226704. bool setSwapInterval (const int numFramesPerSwap)
  226705. {
  226706. [renderContext setValues: (const GLint*) &numFramesPerSwap
  226707. forParameter: NSOpenGLCPSwapInterval];
  226708. return true;
  226709. }
  226710. int getSwapInterval() const
  226711. {
  226712. GLint numFrames = 0;
  226713. [renderContext getValues: &numFrames
  226714. forParameter: NSOpenGLCPSwapInterval];
  226715. return numFrames;
  226716. }
  226717. void repaint()
  226718. {
  226719. // we need to invalidate the juce view that holds this gl view, to make it
  226720. // cause a repaint callback
  226721. NSView* v = (NSView*) viewHolder->view;
  226722. NSRect r = [v frame];
  226723. // bit of a bodge here.. if we only invalidate the area of the gl component,
  226724. // it's completely covered by the NSOpenGLView, so the OS throws away the
  226725. // repaint message, thus never causing our paint() callback, and never repainting
  226726. // the comp. So invalidating just a little bit around the edge helps..
  226727. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  226728. }
  226729. void* getNativeWindowHandle() const { return viewHolder->view; }
  226730. juce_UseDebuggingNewOperator
  226731. NSOpenGLContext* renderContext;
  226732. ThreadSafeNSOpenGLView* view;
  226733. private:
  226734. OpenGLPixelFormat pixelFormat;
  226735. ScopedPointer <NSViewComponentInternal> viewHolder;
  226736. WindowedGLContext (const WindowedGLContext&);
  226737. WindowedGLContext& operator= (const WindowedGLContext&);
  226738. };
  226739. OpenGLContext* OpenGLComponent::createContext()
  226740. {
  226741. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  226742. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  226743. return (c->renderContext != 0) ? c.release() : 0;
  226744. }
  226745. void* OpenGLComponent::getNativeWindowHandle() const
  226746. {
  226747. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  226748. : 0;
  226749. }
  226750. void juce_glViewport (const int w, const int h)
  226751. {
  226752. glViewport (0, 0, w, h);
  226753. }
  226754. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  226755. OwnedArray <OpenGLPixelFormat>& results)
  226756. {
  226757. /* GLint attribs [64];
  226758. int n = 0;
  226759. attribs[n++] = AGL_RGBA;
  226760. attribs[n++] = AGL_DOUBLEBUFFER;
  226761. attribs[n++] = AGL_ACCELERATED;
  226762. attribs[n++] = AGL_NO_RECOVERY;
  226763. attribs[n++] = AGL_NONE;
  226764. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  226765. while (p != 0)
  226766. {
  226767. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  226768. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  226769. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  226770. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  226771. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  226772. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  226773. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  226774. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  226775. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  226776. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  226777. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  226778. results.add (pf);
  226779. p = aglNextPixelFormat (p);
  226780. }*/
  226781. //jassertfalse //xxx can't see how you do this in cocoa!
  226782. }
  226783. #else
  226784. END_JUCE_NAMESPACE
  226785. @interface JuceGLView : UIView
  226786. {
  226787. }
  226788. + (Class) layerClass;
  226789. @end
  226790. @implementation JuceGLView
  226791. + (Class) layerClass
  226792. {
  226793. return [CAEAGLLayer class];
  226794. }
  226795. @end
  226796. BEGIN_JUCE_NAMESPACE
  226797. class GLESContext : public OpenGLContext
  226798. {
  226799. public:
  226800. GLESContext (UIViewComponentPeer* peer,
  226801. Component* const component_,
  226802. const OpenGLPixelFormat& pixelFormat_,
  226803. const GLESContext* const sharedContext,
  226804. NSUInteger apiType)
  226805. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  226806. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  226807. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  226808. {
  226809. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  226810. view.opaque = YES;
  226811. view.hidden = NO;
  226812. view.backgroundColor = [UIColor blackColor];
  226813. view.userInteractionEnabled = NO;
  226814. glLayer = (CAEAGLLayer*) [view layer];
  226815. [peer->view addSubview: view];
  226816. if (sharedContext != 0)
  226817. context = [[EAGLContext alloc] initWithAPI: apiType
  226818. sharegroup: [sharedContext->context sharegroup]];
  226819. else
  226820. context = [[EAGLContext alloc] initWithAPI: apiType];
  226821. createGLBuffers();
  226822. }
  226823. ~GLESContext()
  226824. {
  226825. makeInactive();
  226826. [context release];
  226827. [view removeFromSuperview];
  226828. [view release];
  226829. freeGLBuffers();
  226830. }
  226831. bool makeActive() const throw()
  226832. {
  226833. jassert (context != 0);
  226834. [EAGLContext setCurrentContext: context];
  226835. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  226836. return true;
  226837. }
  226838. void swapBuffers()
  226839. {
  226840. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  226841. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  226842. }
  226843. bool makeInactive() const throw()
  226844. {
  226845. return [EAGLContext setCurrentContext: nil];
  226846. }
  226847. bool isActive() const throw()
  226848. {
  226849. return [EAGLContext currentContext] == context;
  226850. }
  226851. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  226852. void* getRawContext() const throw() { return glLayer; }
  226853. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  226854. {
  226855. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  226856. if (lastWidth != w || lastHeight != h)
  226857. {
  226858. lastWidth = w;
  226859. lastHeight = h;
  226860. freeGLBuffers();
  226861. createGLBuffers();
  226862. }
  226863. }
  226864. bool setSwapInterval (const int numFramesPerSwap)
  226865. {
  226866. numFrames = numFramesPerSwap;
  226867. return true;
  226868. }
  226869. int getSwapInterval() const
  226870. {
  226871. return numFrames;
  226872. }
  226873. void repaint()
  226874. {
  226875. }
  226876. void createGLBuffers()
  226877. {
  226878. makeActive();
  226879. glGenFramebuffersOES (1, &frameBufferHandle);
  226880. glGenRenderbuffersOES (1, &colorBufferHandle);
  226881. glGenRenderbuffersOES (1, &depthBufferHandle);
  226882. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  226883. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  226884. GLint width, height;
  226885. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  226886. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  226887. if (useDepthBuffer)
  226888. {
  226889. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  226890. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  226891. }
  226892. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  226893. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  226894. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  226895. if (useDepthBuffer)
  226896. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  226897. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  226898. }
  226899. void freeGLBuffers()
  226900. {
  226901. if (frameBufferHandle != 0)
  226902. {
  226903. glDeleteFramebuffersOES (1, &frameBufferHandle);
  226904. frameBufferHandle = 0;
  226905. }
  226906. if (colorBufferHandle != 0)
  226907. {
  226908. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  226909. colorBufferHandle = 0;
  226910. }
  226911. if (depthBufferHandle != 0)
  226912. {
  226913. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  226914. depthBufferHandle = 0;
  226915. }
  226916. }
  226917. juce_UseDebuggingNewOperator
  226918. private:
  226919. Component::SafePointer<Component> component;
  226920. OpenGLPixelFormat pixelFormat;
  226921. JuceGLView* view;
  226922. CAEAGLLayer* glLayer;
  226923. EAGLContext* context;
  226924. bool useDepthBuffer;
  226925. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  226926. int numFrames;
  226927. int lastWidth, lastHeight;
  226928. GLESContext (const GLESContext&);
  226929. GLESContext& operator= (const GLESContext&);
  226930. };
  226931. OpenGLContext* OpenGLComponent::createContext()
  226932. {
  226933. ScopedAutoReleasePool pool;
  226934. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  226935. if (peer != 0)
  226936. return new GLESContext (peer, this, preferredPixelFormat,
  226937. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  226938. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  226939. return 0;
  226940. }
  226941. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  226942. OwnedArray <OpenGLPixelFormat>& /*results*/)
  226943. {
  226944. }
  226945. void juce_glViewport (const int w, const int h)
  226946. {
  226947. glViewport (0, 0, w, h);
  226948. }
  226949. #endif
  226950. #endif
  226951. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  226952. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  226953. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226954. // compiled on its own).
  226955. #if JUCE_INCLUDED_FILE
  226956. #if JUCE_MAC
  226957. namespace MouseCursorHelpers
  226958. {
  226959. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  226960. {
  226961. NSImage* im = CoreGraphicsImage::createNSImage (image);
  226962. NSCursor* c = [[NSCursor alloc] initWithImage: im
  226963. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  226964. [im release];
  226965. return c;
  226966. }
  226967. static void* fromWebKitFile (const char* filename, float hx, float hy)
  226968. {
  226969. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  226970. BufferedInputStream buf (&fileStream, 4096, false);
  226971. PNGImageFormat pngFormat;
  226972. Image im (pngFormat.decodeImage (buf));
  226973. if (im.isValid())
  226974. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  226975. jassertfalse;
  226976. return 0;
  226977. }
  226978. }
  226979. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  226980. {
  226981. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  226982. }
  226983. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  226984. {
  226985. const ScopedAutoReleasePool pool;
  226986. NSCursor* c = 0;
  226987. switch (type)
  226988. {
  226989. case NormalCursor: c = [NSCursor arrowCursor]; break;
  226990. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  226991. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  226992. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  226993. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  226994. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  226995. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  226996. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  226997. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  226998. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  226999. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  227000. case UpDownResizeCursor:
  227001. case TopEdgeResizeCursor:
  227002. case BottomEdgeResizeCursor:
  227003. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  227004. case TopLeftCornerResizeCursor:
  227005. case BottomRightCornerResizeCursor:
  227006. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  227007. case TopRightCornerResizeCursor:
  227008. case BottomLeftCornerResizeCursor:
  227009. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  227010. case UpDownLeftRightResizeCursor:
  227011. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  227012. default:
  227013. jassertfalse;
  227014. break;
  227015. }
  227016. [c retain];
  227017. return c;
  227018. }
  227019. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  227020. {
  227021. [((NSCursor*) cursorHandle) release];
  227022. }
  227023. void MouseCursor::showInAllWindows() const
  227024. {
  227025. showInWindow (0);
  227026. }
  227027. void MouseCursor::showInWindow (ComponentPeer*) const
  227028. {
  227029. [((NSCursor*) getHandle()) set];
  227030. }
  227031. #else
  227032. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  227033. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  227034. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  227035. void MouseCursor::showInAllWindows() const {}
  227036. void MouseCursor::showInWindow (ComponentPeer*) const {}
  227037. #endif
  227038. #endif
  227039. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  227040. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  227041. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227042. // compiled on its own).
  227043. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  227044. #if JUCE_MAC
  227045. END_JUCE_NAMESPACE
  227046. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  227047. @interface DownloadClickDetector : NSObject
  227048. {
  227049. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  227050. }
  227051. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  227052. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  227053. request: (NSURLRequest*) request
  227054. frame: (WebFrame*) frame
  227055. decisionListener: (id<WebPolicyDecisionListener>) listener;
  227056. @end
  227057. @implementation DownloadClickDetector
  227058. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  227059. {
  227060. [super init];
  227061. ownerComponent = ownerComponent_;
  227062. return self;
  227063. }
  227064. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  227065. request: (NSURLRequest*) request
  227066. frame: (WebFrame*) frame
  227067. decisionListener: (id <WebPolicyDecisionListener>) listener
  227068. {
  227069. (void) sender;
  227070. (void) request;
  227071. (void) frame;
  227072. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  227073. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  227074. [listener use];
  227075. else
  227076. [listener ignore];
  227077. }
  227078. @end
  227079. BEGIN_JUCE_NAMESPACE
  227080. class WebBrowserComponentInternal : public NSViewComponent
  227081. {
  227082. public:
  227083. WebBrowserComponentInternal (WebBrowserComponent* owner)
  227084. {
  227085. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  227086. frameName: @""
  227087. groupName: @""];
  227088. setView (webView);
  227089. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  227090. [webView setPolicyDelegate: clickListener];
  227091. }
  227092. ~WebBrowserComponentInternal()
  227093. {
  227094. [webView setPolicyDelegate: nil];
  227095. [clickListener release];
  227096. setView (0);
  227097. }
  227098. void goToURL (const String& url,
  227099. const StringArray* headers,
  227100. const MemoryBlock* postData)
  227101. {
  227102. NSMutableURLRequest* r
  227103. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  227104. cachePolicy: NSURLRequestUseProtocolCachePolicy
  227105. timeoutInterval: 30.0];
  227106. if (postData != 0 && postData->getSize() > 0)
  227107. {
  227108. [r setHTTPMethod: @"POST"];
  227109. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  227110. length: postData->getSize()]];
  227111. }
  227112. if (headers != 0)
  227113. {
  227114. for (int i = 0; i < headers->size(); ++i)
  227115. {
  227116. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  227117. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  227118. [r setValue: juceStringToNS (headerValue)
  227119. forHTTPHeaderField: juceStringToNS (headerName)];
  227120. }
  227121. }
  227122. stop();
  227123. [[webView mainFrame] loadRequest: r];
  227124. }
  227125. void goBack()
  227126. {
  227127. [webView goBack];
  227128. }
  227129. void goForward()
  227130. {
  227131. [webView goForward];
  227132. }
  227133. void stop()
  227134. {
  227135. [webView stopLoading: nil];
  227136. }
  227137. void refresh()
  227138. {
  227139. [webView reload: nil];
  227140. }
  227141. private:
  227142. WebView* webView;
  227143. DownloadClickDetector* clickListener;
  227144. };
  227145. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  227146. : browser (0),
  227147. blankPageShown (false),
  227148. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  227149. {
  227150. setOpaque (true);
  227151. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  227152. }
  227153. WebBrowserComponent::~WebBrowserComponent()
  227154. {
  227155. deleteAndZero (browser);
  227156. }
  227157. void WebBrowserComponent::goToURL (const String& url,
  227158. const StringArray* headers,
  227159. const MemoryBlock* postData)
  227160. {
  227161. lastURL = url;
  227162. lastHeaders.clear();
  227163. if (headers != 0)
  227164. lastHeaders = *headers;
  227165. lastPostData.setSize (0);
  227166. if (postData != 0)
  227167. lastPostData = *postData;
  227168. blankPageShown = false;
  227169. browser->goToURL (url, headers, postData);
  227170. }
  227171. void WebBrowserComponent::stop()
  227172. {
  227173. browser->stop();
  227174. }
  227175. void WebBrowserComponent::goBack()
  227176. {
  227177. lastURL = String::empty;
  227178. blankPageShown = false;
  227179. browser->goBack();
  227180. }
  227181. void WebBrowserComponent::goForward()
  227182. {
  227183. lastURL = String::empty;
  227184. browser->goForward();
  227185. }
  227186. void WebBrowserComponent::refresh()
  227187. {
  227188. browser->refresh();
  227189. }
  227190. void WebBrowserComponent::paint (Graphics&)
  227191. {
  227192. }
  227193. void WebBrowserComponent::checkWindowAssociation()
  227194. {
  227195. if (isShowing())
  227196. {
  227197. if (blankPageShown)
  227198. goBack();
  227199. }
  227200. else
  227201. {
  227202. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  227203. {
  227204. // when the component becomes invisible, some stuff like flash
  227205. // carries on playing audio, so we need to force it onto a blank
  227206. // page to avoid this, (and send it back when it's made visible again).
  227207. blankPageShown = true;
  227208. browser->goToURL ("about:blank", 0, 0);
  227209. }
  227210. }
  227211. }
  227212. void WebBrowserComponent::reloadLastURL()
  227213. {
  227214. if (lastURL.isNotEmpty())
  227215. {
  227216. goToURL (lastURL, &lastHeaders, &lastPostData);
  227217. lastURL = String::empty;
  227218. }
  227219. }
  227220. void WebBrowserComponent::parentHierarchyChanged()
  227221. {
  227222. checkWindowAssociation();
  227223. }
  227224. void WebBrowserComponent::resized()
  227225. {
  227226. browser->setSize (getWidth(), getHeight());
  227227. }
  227228. void WebBrowserComponent::visibilityChanged()
  227229. {
  227230. checkWindowAssociation();
  227231. }
  227232. bool WebBrowserComponent::pageAboutToLoad (const String&)
  227233. {
  227234. return true;
  227235. }
  227236. #else
  227237. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  227238. {
  227239. }
  227240. WebBrowserComponent::~WebBrowserComponent()
  227241. {
  227242. }
  227243. void WebBrowserComponent::goToURL (const String& url,
  227244. const StringArray* headers,
  227245. const MemoryBlock* postData)
  227246. {
  227247. }
  227248. void WebBrowserComponent::stop()
  227249. {
  227250. }
  227251. void WebBrowserComponent::goBack()
  227252. {
  227253. }
  227254. void WebBrowserComponent::goForward()
  227255. {
  227256. }
  227257. void WebBrowserComponent::refresh()
  227258. {
  227259. }
  227260. void WebBrowserComponent::paint (Graphics& g)
  227261. {
  227262. }
  227263. void WebBrowserComponent::checkWindowAssociation()
  227264. {
  227265. }
  227266. void WebBrowserComponent::reloadLastURL()
  227267. {
  227268. }
  227269. void WebBrowserComponent::parentHierarchyChanged()
  227270. {
  227271. }
  227272. void WebBrowserComponent::resized()
  227273. {
  227274. }
  227275. void WebBrowserComponent::visibilityChanged()
  227276. {
  227277. }
  227278. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  227279. {
  227280. return true;
  227281. }
  227282. #endif
  227283. #endif
  227284. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  227285. /*** Start of inlined file: juce_iphone_Audio.cpp ***/
  227286. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227287. // compiled on its own).
  227288. #if JUCE_INCLUDED_FILE
  227289. class IPhoneAudioIODevice : public AudioIODevice
  227290. {
  227291. public:
  227292. IPhoneAudioIODevice (const String& deviceName)
  227293. : AudioIODevice (deviceName, "Audio"),
  227294. audioUnit (0),
  227295. isRunning (false),
  227296. callback (0),
  227297. actualBufferSize (0),
  227298. floatData (1, 2)
  227299. {
  227300. numInputChannels = 2;
  227301. numOutputChannels = 2;
  227302. preferredBufferSize = 0;
  227303. AudioSessionInitialize (0, 0, interruptionListenerStatic, this);
  227304. updateDeviceInfo();
  227305. }
  227306. ~IPhoneAudioIODevice()
  227307. {
  227308. close();
  227309. }
  227310. const StringArray getOutputChannelNames()
  227311. {
  227312. StringArray s;
  227313. s.add ("Left");
  227314. s.add ("Right");
  227315. return s;
  227316. }
  227317. const StringArray getInputChannelNames()
  227318. {
  227319. StringArray s;
  227320. if (audioInputIsAvailable)
  227321. {
  227322. s.add ("Left");
  227323. s.add ("Right");
  227324. }
  227325. return s;
  227326. }
  227327. int getNumSampleRates()
  227328. {
  227329. return 1;
  227330. }
  227331. double getSampleRate (int index)
  227332. {
  227333. return sampleRate;
  227334. }
  227335. int getNumBufferSizesAvailable()
  227336. {
  227337. return 1;
  227338. }
  227339. int getBufferSizeSamples (int index)
  227340. {
  227341. return getDefaultBufferSize();
  227342. }
  227343. int getDefaultBufferSize()
  227344. {
  227345. return 1024;
  227346. }
  227347. const String open (const BigInteger& inputChannels,
  227348. const BigInteger& outputChannels,
  227349. double sampleRate,
  227350. int bufferSize)
  227351. {
  227352. close();
  227353. lastError = String::empty;
  227354. preferredBufferSize = (bufferSize <= 0) ? getDefaultBufferSize() : bufferSize;
  227355. // xxx set up channel mapping
  227356. activeOutputChans = outputChannels;
  227357. activeOutputChans.setRange (2, activeOutputChans.getHighestBit(), false);
  227358. numOutputChannels = activeOutputChans.countNumberOfSetBits();
  227359. monoOutputChannelNumber = activeOutputChans.findNextSetBit (0);
  227360. activeInputChans = inputChannels;
  227361. activeInputChans.setRange (2, activeInputChans.getHighestBit(), false);
  227362. numInputChannels = activeInputChans.countNumberOfSetBits();
  227363. monoInputChannelNumber = activeInputChans.findNextSetBit (0);
  227364. AudioSessionSetActive (true);
  227365. UInt32 audioCategory = kAudioSessionCategory_PlayAndRecord;
  227366. AudioSessionSetProperty (kAudioSessionProperty_AudioCategory, sizeof (audioCategory), &audioCategory);
  227367. AudioSessionAddPropertyListener (kAudioSessionProperty_AudioRouteChange, propertyChangedStatic, this);
  227368. fixAudioRouteIfSetToReceiver();
  227369. updateDeviceInfo();
  227370. Float32 bufferDuration = preferredBufferSize / sampleRate;
  227371. AudioSessionSetProperty (kAudioSessionProperty_PreferredHardwareIOBufferDuration, sizeof (bufferDuration), &bufferDuration);
  227372. actualBufferSize = preferredBufferSize;
  227373. prepareFloatBuffers();
  227374. isRunning = true;
  227375. propertyChanged (0, 0, 0); // creates and starts the AU
  227376. lastError = audioUnit != 0 ? "" : "Couldn't open the device";
  227377. return lastError;
  227378. }
  227379. void close()
  227380. {
  227381. if (isRunning)
  227382. {
  227383. isRunning = false;
  227384. AudioSessionSetActive (false);
  227385. if (audioUnit != 0)
  227386. {
  227387. AudioComponentInstanceDispose (audioUnit);
  227388. audioUnit = 0;
  227389. }
  227390. }
  227391. }
  227392. bool isOpen()
  227393. {
  227394. return isRunning;
  227395. }
  227396. int getCurrentBufferSizeSamples()
  227397. {
  227398. return actualBufferSize;
  227399. }
  227400. double getCurrentSampleRate()
  227401. {
  227402. return sampleRate;
  227403. }
  227404. int getCurrentBitDepth()
  227405. {
  227406. return 16;
  227407. }
  227408. const BigInteger getActiveOutputChannels() const
  227409. {
  227410. return activeOutputChans;
  227411. }
  227412. const BigInteger getActiveInputChannels() const
  227413. {
  227414. return activeInputChans;
  227415. }
  227416. int getOutputLatencyInSamples()
  227417. {
  227418. return 0; //xxx
  227419. }
  227420. int getInputLatencyInSamples()
  227421. {
  227422. return 0; //xxx
  227423. }
  227424. void start (AudioIODeviceCallback* callback_)
  227425. {
  227426. if (isRunning && callback != callback_)
  227427. {
  227428. if (callback_ != 0)
  227429. callback_->audioDeviceAboutToStart (this);
  227430. const ScopedLock sl (callbackLock);
  227431. callback = callback_;
  227432. }
  227433. }
  227434. void stop()
  227435. {
  227436. if (isRunning)
  227437. {
  227438. AudioIODeviceCallback* lastCallback;
  227439. {
  227440. const ScopedLock sl (callbackLock);
  227441. lastCallback = callback;
  227442. callback = 0;
  227443. }
  227444. if (lastCallback != 0)
  227445. lastCallback->audioDeviceStopped();
  227446. }
  227447. }
  227448. bool isPlaying()
  227449. {
  227450. return isRunning && callback != 0;
  227451. }
  227452. const String getLastError()
  227453. {
  227454. return lastError;
  227455. }
  227456. private:
  227457. CriticalSection callbackLock;
  227458. Float64 sampleRate;
  227459. int numInputChannels, numOutputChannels;
  227460. int preferredBufferSize;
  227461. int actualBufferSize;
  227462. bool isRunning;
  227463. String lastError;
  227464. AudioStreamBasicDescription format;
  227465. AudioUnit audioUnit;
  227466. UInt32 audioInputIsAvailable;
  227467. AudioIODeviceCallback* callback;
  227468. BigInteger activeOutputChans, activeInputChans;
  227469. AudioSampleBuffer floatData;
  227470. float* inputChannels[3];
  227471. float* outputChannels[3];
  227472. bool monoInputChannelNumber, monoOutputChannelNumber;
  227473. void prepareFloatBuffers()
  227474. {
  227475. floatData.setSize (numInputChannels + numOutputChannels, actualBufferSize);
  227476. zerostruct (inputChannels);
  227477. zerostruct (outputChannels);
  227478. for (int i = 0; i < numInputChannels; ++i)
  227479. inputChannels[i] = floatData.getSampleData (i);
  227480. for (int i = 0; i < numOutputChannels; ++i)
  227481. outputChannels[i] = floatData.getSampleData (i + numInputChannels);
  227482. }
  227483. OSStatus process (AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  227484. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  227485. {
  227486. OSStatus err = noErr;
  227487. if (audioInputIsAvailable)
  227488. err = AudioUnitRender (audioUnit, ioActionFlags, inTimeStamp, 1, inNumberFrames, ioData);
  227489. const ScopedLock sl (callbackLock);
  227490. if (callback != 0)
  227491. {
  227492. if (audioInputIsAvailable && numInputChannels > 0)
  227493. {
  227494. short* shortData = (short*) ioData->mBuffers[0].mData;
  227495. if (numInputChannels >= 2)
  227496. {
  227497. for (UInt32 i = 0; i < inNumberFrames; ++i)
  227498. {
  227499. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  227500. inputChannels[1][i] = *shortData++ * (1.0f / 32768.0f);
  227501. }
  227502. }
  227503. else
  227504. {
  227505. if (monoInputChannelNumber > 0)
  227506. ++shortData;
  227507. for (UInt32 i = 0; i < inNumberFrames; ++i)
  227508. {
  227509. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  227510. ++shortData;
  227511. }
  227512. }
  227513. }
  227514. else
  227515. {
  227516. for (int i = numInputChannels; --i >= 0;)
  227517. zeromem (inputChannels[i], sizeof (float) * inNumberFrames);
  227518. }
  227519. callback->audioDeviceIOCallback ((const float**) inputChannels, numInputChannels,
  227520. outputChannels, numOutputChannels,
  227521. (int) inNumberFrames);
  227522. short* shortData = (short*) ioData->mBuffers[0].mData;
  227523. int n = 0;
  227524. if (numOutputChannels >= 2)
  227525. {
  227526. for (UInt32 i = 0; i < inNumberFrames; ++i)
  227527. {
  227528. shortData [n++] = (short) (outputChannels[0][i] * 32767.0f);
  227529. shortData [n++] = (short) (outputChannels[1][i] * 32767.0f);
  227530. }
  227531. }
  227532. else if (numOutputChannels == 1)
  227533. {
  227534. for (UInt32 i = 0; i < inNumberFrames; ++i)
  227535. {
  227536. const short s = (short) (outputChannels[monoOutputChannelNumber][i] * 32767.0f);
  227537. shortData [n++] = s;
  227538. shortData [n++] = s;
  227539. }
  227540. }
  227541. else
  227542. {
  227543. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  227544. }
  227545. }
  227546. else
  227547. {
  227548. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  227549. }
  227550. return err;
  227551. }
  227552. void updateDeviceInfo()
  227553. {
  227554. UInt32 size = sizeof (sampleRate);
  227555. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareSampleRate, &size, &sampleRate);
  227556. size = sizeof (audioInputIsAvailable);
  227557. AudioSessionGetProperty (kAudioSessionProperty_AudioInputAvailable, &size, &audioInputIsAvailable);
  227558. }
  227559. void propertyChanged (AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  227560. {
  227561. if (! isRunning)
  227562. return;
  227563. if (inPropertyValue != 0)
  227564. {
  227565. CFDictionaryRef routeChangeDictionary = (CFDictionaryRef) inPropertyValue;
  227566. CFNumberRef routeChangeReasonRef = (CFNumberRef) CFDictionaryGetValue (routeChangeDictionary,
  227567. CFSTR (kAudioSession_AudioRouteChangeKey_Reason));
  227568. SInt32 routeChangeReason;
  227569. CFNumberGetValue (routeChangeReasonRef, kCFNumberSInt32Type, &routeChangeReason);
  227570. if (routeChangeReason == kAudioSessionRouteChangeReason_OldDeviceUnavailable)
  227571. fixAudioRouteIfSetToReceiver();
  227572. }
  227573. updateDeviceInfo();
  227574. createAudioUnit();
  227575. AudioSessionSetActive (true);
  227576. if (audioUnit != 0)
  227577. {
  227578. UInt32 formatSize = sizeof (format);
  227579. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, &formatSize);
  227580. Float32 bufferDuration = preferredBufferSize / sampleRate;
  227581. UInt32 bufferDurationSize = sizeof (bufferDuration);
  227582. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareIOBufferDuration, &bufferDurationSize, &bufferDurationSize);
  227583. actualBufferSize = (int) (sampleRate * bufferDuration + 0.5);
  227584. AudioOutputUnitStart (audioUnit);
  227585. }
  227586. }
  227587. void interruptionListener (UInt32 inInterruption)
  227588. {
  227589. /*if (inInterruption == kAudioSessionBeginInterruption)
  227590. {
  227591. isRunning = false;
  227592. AudioOutputUnitStop (audioUnit);
  227593. if (juce_iPhoneShowModalAlert ("Audio Interrupted",
  227594. "This could have been interrupted by another application or by unplugging a headset",
  227595. @"Resume",
  227596. @"Cancel"))
  227597. {
  227598. isRunning = true;
  227599. propertyChanged (0, 0, 0);
  227600. }
  227601. }*/
  227602. if (inInterruption == kAudioSessionEndInterruption)
  227603. {
  227604. isRunning = true;
  227605. AudioSessionSetActive (true);
  227606. AudioOutputUnitStart (audioUnit);
  227607. }
  227608. }
  227609. static OSStatus processStatic (void* inRefCon, AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  227610. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  227611. {
  227612. return ((IPhoneAudioIODevice*) inRefCon)->process (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  227613. }
  227614. static void propertyChangedStatic (void* inClientData, AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  227615. {
  227616. ((IPhoneAudioIODevice*) inClientData)->propertyChanged (inID, inDataSize, inPropertyValue);
  227617. }
  227618. static void interruptionListenerStatic (void* inClientData, UInt32 inInterruption)
  227619. {
  227620. ((IPhoneAudioIODevice*) inClientData)->interruptionListener (inInterruption);
  227621. }
  227622. void resetFormat (const int numChannels)
  227623. {
  227624. memset (&format, 0, sizeof (format));
  227625. format.mFormatID = kAudioFormatLinearPCM;
  227626. format.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked;
  227627. format.mBitsPerChannel = 8 * sizeof (short);
  227628. format.mChannelsPerFrame = 2;
  227629. format.mFramesPerPacket = 1;
  227630. format.mBytesPerFrame = format.mBytesPerPacket = 2 * sizeof (short);
  227631. }
  227632. bool createAudioUnit()
  227633. {
  227634. if (audioUnit != 0)
  227635. {
  227636. AudioComponentInstanceDispose (audioUnit);
  227637. audioUnit = 0;
  227638. }
  227639. resetFormat (2);
  227640. AudioComponentDescription desc;
  227641. desc.componentType = kAudioUnitType_Output;
  227642. desc.componentSubType = kAudioUnitSubType_RemoteIO;
  227643. desc.componentManufacturer = kAudioUnitManufacturer_Apple;
  227644. desc.componentFlags = 0;
  227645. desc.componentFlagsMask = 0;
  227646. AudioComponent comp = AudioComponentFindNext (0, &desc);
  227647. AudioComponentInstanceNew (comp, &audioUnit);
  227648. if (audioUnit == 0)
  227649. return false;
  227650. const UInt32 one = 1;
  227651. AudioUnitSetProperty (audioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &one, sizeof (one));
  227652. AudioChannelLayout layout;
  227653. layout.mChannelBitmap = 0;
  227654. layout.mNumberChannelDescriptions = 0;
  227655. layout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  227656. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Input, 0, &layout, sizeof (layout));
  227657. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Output, 0, &layout, sizeof (layout));
  227658. AURenderCallbackStruct inputProc;
  227659. inputProc.inputProc = processStatic;
  227660. inputProc.inputProcRefCon = this;
  227661. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &inputProc, sizeof (inputProc));
  227662. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &format, sizeof (format));
  227663. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, sizeof (format));
  227664. AudioUnitInitialize (audioUnit);
  227665. return true;
  227666. }
  227667. // If the routing is set to go through the receiver (i.e. the speaker, but quiet), this re-routes it
  227668. // to make it loud. Needed because by default when using an input + output, the output is kept quiet.
  227669. static void fixAudioRouteIfSetToReceiver()
  227670. {
  227671. CFStringRef audioRoute = 0;
  227672. UInt32 propertySize = sizeof (audioRoute);
  227673. if (AudioSessionGetProperty (kAudioSessionProperty_AudioRoute, &propertySize, &audioRoute) == noErr)
  227674. {
  227675. NSString* route = (NSString*) audioRoute;
  227676. //DBG ("audio route: " + nsStringToJuce (route));
  227677. if ([route hasPrefix: @"Receiver"])
  227678. {
  227679. UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
  227680. AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute, sizeof (audioRouteOverride), &audioRouteOverride);
  227681. }
  227682. CFRelease (audioRoute);
  227683. }
  227684. }
  227685. IPhoneAudioIODevice (const IPhoneAudioIODevice&);
  227686. IPhoneAudioIODevice& operator= (const IPhoneAudioIODevice&);
  227687. };
  227688. class IPhoneAudioIODeviceType : public AudioIODeviceType
  227689. {
  227690. public:
  227691. IPhoneAudioIODeviceType()
  227692. : AudioIODeviceType ("iPhone Audio")
  227693. {
  227694. }
  227695. ~IPhoneAudioIODeviceType()
  227696. {
  227697. }
  227698. void scanForDevices()
  227699. {
  227700. }
  227701. const StringArray getDeviceNames (bool wantInputNames) const
  227702. {
  227703. StringArray s;
  227704. s.add ("iPhone Audio");
  227705. return s;
  227706. }
  227707. int getDefaultDeviceIndex (bool forInput) const
  227708. {
  227709. return 0;
  227710. }
  227711. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  227712. {
  227713. return device != 0 ? 0 : -1;
  227714. }
  227715. bool hasSeparateInputsAndOutputs() const { return false; }
  227716. AudioIODevice* createDevice (const String& outputDeviceName,
  227717. const String& inputDeviceName)
  227718. {
  227719. if (outputDeviceName.isNotEmpty() || inputDeviceName.isNotEmpty())
  227720. {
  227721. return new IPhoneAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  227722. : inputDeviceName);
  227723. }
  227724. return 0;
  227725. }
  227726. juce_UseDebuggingNewOperator
  227727. private:
  227728. IPhoneAudioIODeviceType (const IPhoneAudioIODeviceType&);
  227729. IPhoneAudioIODeviceType& operator= (const IPhoneAudioIODeviceType&);
  227730. };
  227731. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio()
  227732. {
  227733. return new IPhoneAudioIODeviceType();
  227734. }
  227735. #endif
  227736. /*** End of inlined file: juce_iphone_Audio.cpp ***/
  227737. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  227738. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227739. // compiled on its own).
  227740. #if JUCE_INCLUDED_FILE
  227741. #if JUCE_MAC
  227742. #undef log
  227743. #define log(a) Logger::writeToLog(a)
  227744. static bool logAnyErrorsMidi (const OSStatus err, const int lineNum)
  227745. {
  227746. if (err == noErr)
  227747. return true;
  227748. log ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  227749. jassertfalse;
  227750. return false;
  227751. }
  227752. #undef OK
  227753. #define OK(a) logAnyErrorsMidi(a, __LINE__)
  227754. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  227755. {
  227756. String result;
  227757. CFStringRef str = 0;
  227758. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  227759. if (str != 0)
  227760. {
  227761. result = PlatformUtilities::cfStringToJuceString (str);
  227762. CFRelease (str);
  227763. str = 0;
  227764. }
  227765. MIDIEntityRef entity = 0;
  227766. MIDIEndpointGetEntity (endpoint, &entity);
  227767. if (entity == 0)
  227768. return result; // probably virtual
  227769. if (result.isEmpty())
  227770. {
  227771. // endpoint name has zero length - try the entity
  227772. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  227773. if (str != 0)
  227774. {
  227775. result += PlatformUtilities::cfStringToJuceString (str);
  227776. CFRelease (str);
  227777. str = 0;
  227778. }
  227779. }
  227780. // now consider the device's name
  227781. MIDIDeviceRef device = 0;
  227782. MIDIEntityGetDevice (entity, &device);
  227783. if (device == 0)
  227784. return result;
  227785. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  227786. if (str != 0)
  227787. {
  227788. const String s (PlatformUtilities::cfStringToJuceString (str));
  227789. CFRelease (str);
  227790. // if an external device has only one entity, throw away
  227791. // the endpoint name and just use the device name
  227792. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  227793. {
  227794. result = s;
  227795. }
  227796. else if (! result.startsWithIgnoreCase (s))
  227797. {
  227798. // prepend the device name to the entity name
  227799. result = (s + " " + result).trimEnd();
  227800. }
  227801. }
  227802. return result;
  227803. }
  227804. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  227805. {
  227806. String result;
  227807. // Does the endpoint have connections?
  227808. CFDataRef connections = 0;
  227809. int numConnections = 0;
  227810. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  227811. if (connections != 0)
  227812. {
  227813. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  227814. if (numConnections > 0)
  227815. {
  227816. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  227817. for (int i = 0; i < numConnections; ++i, ++pid)
  227818. {
  227819. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  227820. MIDIObjectRef connObject;
  227821. MIDIObjectType connObjectType;
  227822. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  227823. if (err == noErr)
  227824. {
  227825. String s;
  227826. if (connObjectType == kMIDIObjectType_ExternalSource
  227827. || connObjectType == kMIDIObjectType_ExternalDestination)
  227828. {
  227829. // Connected to an external device's endpoint (10.3 and later).
  227830. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  227831. }
  227832. else
  227833. {
  227834. // Connected to an external device (10.2) (or something else, catch-all)
  227835. CFStringRef str = 0;
  227836. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  227837. if (str != 0)
  227838. {
  227839. s = PlatformUtilities::cfStringToJuceString (str);
  227840. CFRelease (str);
  227841. }
  227842. }
  227843. if (s.isNotEmpty())
  227844. {
  227845. if (result.isNotEmpty())
  227846. result += ", ";
  227847. result += s;
  227848. }
  227849. }
  227850. }
  227851. }
  227852. CFRelease (connections);
  227853. }
  227854. if (result.isNotEmpty())
  227855. return result;
  227856. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  227857. return getEndpointName (endpoint, false);
  227858. }
  227859. const StringArray MidiOutput::getDevices()
  227860. {
  227861. StringArray s;
  227862. const ItemCount num = MIDIGetNumberOfDestinations();
  227863. for (ItemCount i = 0; i < num; ++i)
  227864. {
  227865. MIDIEndpointRef dest = MIDIGetDestination (i);
  227866. if (dest != 0)
  227867. {
  227868. String name (getConnectedEndpointName (dest));
  227869. if (name.isEmpty())
  227870. name = "<error>";
  227871. s.add (name);
  227872. }
  227873. else
  227874. {
  227875. s.add ("<error>");
  227876. }
  227877. }
  227878. return s;
  227879. }
  227880. int MidiOutput::getDefaultDeviceIndex()
  227881. {
  227882. return 0;
  227883. }
  227884. static MIDIClientRef globalMidiClient;
  227885. static bool hasGlobalClientBeenCreated = false;
  227886. static bool makeSureClientExists()
  227887. {
  227888. if (! hasGlobalClientBeenCreated)
  227889. {
  227890. String name ("JUCE");
  227891. if (JUCEApplication::getInstance() != 0)
  227892. name = JUCEApplication::getInstance()->getApplicationName();
  227893. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  227894. hasGlobalClientBeenCreated = OK (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  227895. CFRelease (appName);
  227896. }
  227897. return hasGlobalClientBeenCreated;
  227898. }
  227899. class MidiPortAndEndpoint
  227900. {
  227901. public:
  227902. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  227903. : port (port_), endPoint (endPoint_)
  227904. {
  227905. }
  227906. ~MidiPortAndEndpoint()
  227907. {
  227908. if (port != 0)
  227909. MIDIPortDispose (port);
  227910. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  227911. MIDIEndpointDispose (endPoint);
  227912. }
  227913. MIDIPortRef port;
  227914. MIDIEndpointRef endPoint;
  227915. };
  227916. MidiOutput* MidiOutput::openDevice (int index)
  227917. {
  227918. MidiOutput* mo = 0;
  227919. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  227920. {
  227921. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  227922. CFStringRef pname;
  227923. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  227924. {
  227925. log ("CoreMidi - opening out: " + PlatformUtilities::cfStringToJuceString (pname));
  227926. if (makeSureClientExists())
  227927. {
  227928. MIDIPortRef port;
  227929. if (OK (MIDIOutputPortCreate (globalMidiClient, pname, &port)))
  227930. {
  227931. mo = new MidiOutput();
  227932. mo->internal = new MidiPortAndEndpoint (port, endPoint);
  227933. }
  227934. }
  227935. CFRelease (pname);
  227936. }
  227937. }
  227938. return mo;
  227939. }
  227940. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  227941. {
  227942. MidiOutput* mo = 0;
  227943. if (makeSureClientExists())
  227944. {
  227945. MIDIEndpointRef endPoint;
  227946. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  227947. if (OK (MIDISourceCreate (globalMidiClient, name, &endPoint)))
  227948. {
  227949. mo = new MidiOutput();
  227950. mo->internal = new MidiPortAndEndpoint (0, endPoint);
  227951. }
  227952. CFRelease (name);
  227953. }
  227954. return mo;
  227955. }
  227956. MidiOutput::~MidiOutput()
  227957. {
  227958. delete (MidiPortAndEndpoint*) internal;
  227959. }
  227960. void MidiOutput::reset()
  227961. {
  227962. }
  227963. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  227964. {
  227965. return false;
  227966. }
  227967. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  227968. {
  227969. }
  227970. void MidiOutput::sendMessageNow (const MidiMessage& message)
  227971. {
  227972. MidiPortAndEndpoint* const mpe = (MidiPortAndEndpoint*) internal;
  227973. if (message.isSysEx())
  227974. {
  227975. const int maxPacketSize = 256;
  227976. int pos = 0, bytesLeft = message.getRawDataSize();
  227977. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  227978. HeapBlock <MIDIPacketList> packets;
  227979. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  227980. packets->numPackets = numPackets;
  227981. MIDIPacket* p = packets->packet;
  227982. for (int i = 0; i < numPackets; ++i)
  227983. {
  227984. p->timeStamp = 0;
  227985. p->length = jmin (maxPacketSize, bytesLeft);
  227986. memcpy (p->data, message.getRawData() + pos, p->length);
  227987. pos += p->length;
  227988. bytesLeft -= p->length;
  227989. p = MIDIPacketNext (p);
  227990. }
  227991. if (mpe->port != 0)
  227992. MIDISend (mpe->port, mpe->endPoint, packets);
  227993. else
  227994. MIDIReceived (mpe->endPoint, packets);
  227995. }
  227996. else
  227997. {
  227998. MIDIPacketList packets;
  227999. packets.numPackets = 1;
  228000. packets.packet[0].timeStamp = 0;
  228001. packets.packet[0].length = message.getRawDataSize();
  228002. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  228003. if (mpe->port != 0)
  228004. MIDISend (mpe->port, mpe->endPoint, &packets);
  228005. else
  228006. MIDIReceived (mpe->endPoint, &packets);
  228007. }
  228008. }
  228009. const StringArray MidiInput::getDevices()
  228010. {
  228011. StringArray s;
  228012. const ItemCount num = MIDIGetNumberOfSources();
  228013. for (ItemCount i = 0; i < num; ++i)
  228014. {
  228015. MIDIEndpointRef source = MIDIGetSource (i);
  228016. if (source != 0)
  228017. {
  228018. String name (getConnectedEndpointName (source));
  228019. if (name.isEmpty())
  228020. name = "<error>";
  228021. s.add (name);
  228022. }
  228023. else
  228024. {
  228025. s.add ("<error>");
  228026. }
  228027. }
  228028. return s;
  228029. }
  228030. int MidiInput::getDefaultDeviceIndex()
  228031. {
  228032. return 0;
  228033. }
  228034. struct MidiPortAndCallback
  228035. {
  228036. MidiInput* input;
  228037. MidiPortAndEndpoint* portAndEndpoint;
  228038. MidiInputCallback* callback;
  228039. MemoryBlock pendingData;
  228040. int pendingBytes;
  228041. double pendingDataTime;
  228042. bool active;
  228043. void processSysex (const uint8*& d, int& size, const double time)
  228044. {
  228045. if (*d == 0xf0)
  228046. {
  228047. pendingBytes = 0;
  228048. pendingDataTime = time;
  228049. }
  228050. pendingData.ensureSize (pendingBytes + size, false);
  228051. uint8* totalMessage = (uint8*) pendingData.getData();
  228052. uint8* dest = totalMessage + pendingBytes;
  228053. while (size > 0)
  228054. {
  228055. if (pendingBytes > 0 && *d >= 0x80)
  228056. {
  228057. if (*d >= 0xfa || *d == 0xf8)
  228058. {
  228059. callback->handleIncomingMidiMessage (input, MidiMessage (*d, time));
  228060. ++d;
  228061. --size;
  228062. }
  228063. else
  228064. {
  228065. if (*d == 0xf7)
  228066. {
  228067. *dest++ = *d++;
  228068. pendingBytes++;
  228069. --size;
  228070. }
  228071. break;
  228072. }
  228073. }
  228074. else
  228075. {
  228076. *dest++ = *d++;
  228077. pendingBytes++;
  228078. --size;
  228079. }
  228080. }
  228081. if (totalMessage [pendingBytes - 1] == 0xf7)
  228082. {
  228083. callback->handleIncomingMidiMessage (input, MidiMessage (totalMessage, pendingBytes, pendingDataTime));
  228084. pendingBytes = 0;
  228085. }
  228086. else
  228087. {
  228088. callback->handlePartialSysexMessage (input, totalMessage, pendingBytes, pendingDataTime);
  228089. }
  228090. }
  228091. };
  228092. namespace CoreMidiCallbacks
  228093. {
  228094. static CriticalSection callbackLock;
  228095. static Array<void*> activeCallbacks;
  228096. }
  228097. static void midiInputProc (const MIDIPacketList* pktlist,
  228098. void* readProcRefCon,
  228099. void* /*srcConnRefCon*/)
  228100. {
  228101. double time = Time::getMillisecondCounterHiRes() * 0.001;
  228102. const double originalTime = time;
  228103. MidiPortAndCallback* const mpc = (MidiPortAndCallback*) readProcRefCon;
  228104. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  228105. if (CoreMidiCallbacks::activeCallbacks.contains (mpc) && mpc->active)
  228106. {
  228107. const MIDIPacket* packet = &pktlist->packet[0];
  228108. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  228109. {
  228110. const uint8* d = (const uint8*) (packet->data);
  228111. int size = packet->length;
  228112. while (size > 0)
  228113. {
  228114. time = originalTime;
  228115. if (mpc->pendingBytes > 0 || d[0] == 0xf0)
  228116. {
  228117. mpc->processSysex (d, size, time);
  228118. }
  228119. else
  228120. {
  228121. int used = 0;
  228122. const MidiMessage m (d, size, used, 0, time);
  228123. if (used <= 0)
  228124. {
  228125. jassertfalse; // malformed midi message
  228126. break;
  228127. }
  228128. else
  228129. {
  228130. mpc->callback->handleIncomingMidiMessage (mpc->input, m);
  228131. }
  228132. size -= used;
  228133. d += used;
  228134. }
  228135. }
  228136. packet = MIDIPacketNext (packet);
  228137. }
  228138. }
  228139. }
  228140. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  228141. {
  228142. MidiInput* mi = 0;
  228143. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  228144. {
  228145. MIDIEndpointRef endPoint = MIDIGetSource (index);
  228146. if (endPoint != 0)
  228147. {
  228148. CFStringRef pname;
  228149. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  228150. {
  228151. log ("CoreMidi - opening inp: " + PlatformUtilities::cfStringToJuceString (pname));
  228152. if (makeSureClientExists())
  228153. {
  228154. MIDIPortRef port;
  228155. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  228156. mpc->active = false;
  228157. if (OK (MIDIInputPortCreate (globalMidiClient, pname, midiInputProc, mpc, &port)))
  228158. {
  228159. if (OK (MIDIPortConnectSource (port, endPoint, 0)))
  228160. {
  228161. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  228162. mpc->callback = callback;
  228163. mpc->pendingBytes = 0;
  228164. mpc->pendingData.ensureSize (128);
  228165. mi = new MidiInput (getDevices() [index]);
  228166. mpc->input = mi;
  228167. mi->internal = mpc;
  228168. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  228169. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  228170. }
  228171. else
  228172. {
  228173. OK (MIDIPortDispose (port));
  228174. }
  228175. }
  228176. }
  228177. }
  228178. CFRelease (pname);
  228179. }
  228180. }
  228181. return mi;
  228182. }
  228183. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  228184. {
  228185. MidiInput* mi = 0;
  228186. if (makeSureClientExists())
  228187. {
  228188. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  228189. mpc->active = false;
  228190. MIDIEndpointRef endPoint;
  228191. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  228192. if (OK (MIDIDestinationCreate (globalMidiClient, name, midiInputProc, mpc, &endPoint)))
  228193. {
  228194. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  228195. mpc->callback = callback;
  228196. mpc->pendingBytes = 0;
  228197. mpc->pendingData.ensureSize (128);
  228198. mi = new MidiInput (deviceName);
  228199. mpc->input = mi;
  228200. mi->internal = mpc;
  228201. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  228202. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  228203. }
  228204. CFRelease (name);
  228205. }
  228206. return mi;
  228207. }
  228208. MidiInput::MidiInput (const String& name_)
  228209. : name (name_)
  228210. {
  228211. }
  228212. MidiInput::~MidiInput()
  228213. {
  228214. MidiPortAndCallback* const mpc = (MidiPortAndCallback*) internal;
  228215. mpc->active = false;
  228216. {
  228217. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  228218. CoreMidiCallbacks::activeCallbacks.removeValue (mpc);
  228219. }
  228220. if (mpc->portAndEndpoint->port != 0)
  228221. OK (MIDIPortDisconnectSource (mpc->portAndEndpoint->port, mpc->portAndEndpoint->endPoint));
  228222. delete mpc->portAndEndpoint;
  228223. delete mpc;
  228224. }
  228225. void MidiInput::start()
  228226. {
  228227. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  228228. ((MidiPortAndCallback*) internal)->active = true;
  228229. }
  228230. void MidiInput::stop()
  228231. {
  228232. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  228233. ((MidiPortAndCallback*) internal)->active = false;
  228234. }
  228235. #undef log
  228236. #else
  228237. MidiOutput::~MidiOutput()
  228238. {
  228239. }
  228240. void MidiOutput::reset()
  228241. {
  228242. }
  228243. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  228244. {
  228245. return false;
  228246. }
  228247. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  228248. {
  228249. }
  228250. void MidiOutput::sendMessageNow (const MidiMessage& message)
  228251. {
  228252. }
  228253. const StringArray MidiOutput::getDevices()
  228254. {
  228255. return StringArray();
  228256. }
  228257. MidiOutput* MidiOutput::openDevice (int index)
  228258. {
  228259. return 0;
  228260. }
  228261. const StringArray MidiInput::getDevices()
  228262. {
  228263. return StringArray();
  228264. }
  228265. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  228266. {
  228267. return 0;
  228268. }
  228269. #endif
  228270. #endif
  228271. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  228272. #else
  228273. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  228274. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228275. // compiled on its own).
  228276. #if JUCE_INCLUDED_FILE
  228277. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  228278. #define SUPPORT_10_4_FONTS 1
  228279. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  228280. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  228281. #define SUPPORT_ONLY_10_4_FONTS 1
  228282. #endif
  228283. END_JUCE_NAMESPACE
  228284. @interface NSFont (PrivateHack)
  228285. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  228286. @end
  228287. BEGIN_JUCE_NAMESPACE
  228288. #endif
  228289. class MacTypeface : public Typeface
  228290. {
  228291. public:
  228292. MacTypeface (const Font& font)
  228293. : Typeface (font.getTypefaceName())
  228294. {
  228295. const ScopedAutoReleasePool pool;
  228296. renderingTransform = CGAffineTransformIdentity;
  228297. bool needsItalicTransform = false;
  228298. #if JUCE_IPHONE
  228299. NSString* fontName = juceStringToNS (font.getTypefaceName());
  228300. if (font.isItalic() || font.isBold())
  228301. {
  228302. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  228303. for (NSString* i in familyFonts)
  228304. {
  228305. const String fn (nsStringToJuce (i));
  228306. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  228307. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  228308. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  228309. || afterDash.containsIgnoreCase ("italic")
  228310. || fn.endsWithIgnoreCase ("oblique")
  228311. || fn.endsWithIgnoreCase ("italic");
  228312. if (probablyBold == font.isBold()
  228313. && probablyItalic == font.isItalic())
  228314. {
  228315. fontName = i;
  228316. needsItalicTransform = false;
  228317. break;
  228318. }
  228319. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  228320. {
  228321. fontName = i;
  228322. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  228323. }
  228324. }
  228325. if (needsItalicTransform)
  228326. renderingTransform.c = 0.15f;
  228327. }
  228328. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  228329. const int ascender = abs (CGFontGetAscent (fontRef));
  228330. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  228331. ascent = ascender / totalHeight;
  228332. unitsToHeightScaleFactor = 1.0f / totalHeight;
  228333. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  228334. #else
  228335. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  228336. if (font.isItalic())
  228337. {
  228338. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  228339. toHaveTrait: NSItalicFontMask];
  228340. if (newFont == nsFont)
  228341. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  228342. nsFont = newFont;
  228343. }
  228344. if (font.isBold())
  228345. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  228346. [nsFont retain];
  228347. ascent = std::abs ((float) [nsFont ascender]);
  228348. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  228349. ascent /= totalSize;
  228350. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  228351. if (needsItalicTransform)
  228352. {
  228353. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  228354. renderingTransform.c = 0.15f;
  228355. }
  228356. #if SUPPORT_ONLY_10_4_FONTS
  228357. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  228358. if (atsFont == 0)
  228359. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  228360. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  228361. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  228362. unitsToHeightScaleFactor = 1.0f / totalHeight;
  228363. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  228364. #else
  228365. #if SUPPORT_10_4_FONTS
  228366. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  228367. {
  228368. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  228369. if (atsFont == 0)
  228370. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  228371. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  228372. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  228373. unitsToHeightScaleFactor = 1.0f / totalHeight;
  228374. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  228375. }
  228376. else
  228377. #endif
  228378. {
  228379. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  228380. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  228381. unitsToHeightScaleFactor = 1.0f / totalHeight;
  228382. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  228383. }
  228384. #endif
  228385. #endif
  228386. }
  228387. ~MacTypeface()
  228388. {
  228389. #if ! JUCE_IPHONE
  228390. [nsFont release];
  228391. #endif
  228392. if (fontRef != 0)
  228393. CGFontRelease (fontRef);
  228394. }
  228395. float getAscent() const
  228396. {
  228397. return ascent;
  228398. }
  228399. float getDescent() const
  228400. {
  228401. return 1.0f - ascent;
  228402. }
  228403. float getStringWidth (const String& text)
  228404. {
  228405. if (fontRef == 0 || text.isEmpty())
  228406. return 0;
  228407. const int length = text.length();
  228408. HeapBlock <CGGlyph> glyphs;
  228409. createGlyphsForString (text, length, glyphs);
  228410. float x = 0;
  228411. #if SUPPORT_ONLY_10_4_FONTS
  228412. HeapBlock <NSSize> advances (length);
  228413. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  228414. for (int i = 0; i < length; ++i)
  228415. x += advances[i].width;
  228416. #else
  228417. #if SUPPORT_10_4_FONTS
  228418. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  228419. {
  228420. HeapBlock <NSSize> advances (length);
  228421. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  228422. for (int i = 0; i < length; ++i)
  228423. x += advances[i].width;
  228424. }
  228425. else
  228426. #endif
  228427. {
  228428. HeapBlock <int> advances (length);
  228429. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  228430. for (int i = 0; i < length; ++i)
  228431. x += advances[i];
  228432. }
  228433. #endif
  228434. return x * unitsToHeightScaleFactor;
  228435. }
  228436. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  228437. {
  228438. xOffsets.add (0);
  228439. if (fontRef == 0 || text.isEmpty())
  228440. return;
  228441. const int length = text.length();
  228442. HeapBlock <CGGlyph> glyphs;
  228443. createGlyphsForString (text, length, glyphs);
  228444. #if SUPPORT_ONLY_10_4_FONTS
  228445. HeapBlock <NSSize> advances (length);
  228446. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  228447. int x = 0;
  228448. for (int i = 0; i < length; ++i)
  228449. {
  228450. x += advances[i].width;
  228451. xOffsets.add (x * unitsToHeightScaleFactor);
  228452. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  228453. }
  228454. #else
  228455. #if SUPPORT_10_4_FONTS
  228456. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  228457. {
  228458. HeapBlock <NSSize> advances (length);
  228459. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  228460. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  228461. float x = 0;
  228462. for (int i = 0; i < length; ++i)
  228463. {
  228464. x += advances[i].width;
  228465. xOffsets.add (x * unitsToHeightScaleFactor);
  228466. resultGlyphs.add (nsGlyphs[i]);
  228467. }
  228468. }
  228469. else
  228470. #endif
  228471. {
  228472. HeapBlock <int> advances (length);
  228473. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  228474. {
  228475. int x = 0;
  228476. for (int i = 0; i < length; ++i)
  228477. {
  228478. x += advances [i];
  228479. xOffsets.add (x * unitsToHeightScaleFactor);
  228480. resultGlyphs.add (glyphs[i]);
  228481. }
  228482. }
  228483. }
  228484. #endif
  228485. }
  228486. bool getOutlineForGlyph (int glyphNumber, Path& path)
  228487. {
  228488. #if JUCE_IPHONE
  228489. return false;
  228490. #else
  228491. if (nsFont == 0)
  228492. return false;
  228493. // we might need to apply a transform to the path, so it mustn't have anything else in it
  228494. jassert (path.isEmpty());
  228495. const ScopedAutoReleasePool pool;
  228496. NSBezierPath* bez = [NSBezierPath bezierPath];
  228497. [bez moveToPoint: NSMakePoint (0, 0)];
  228498. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  228499. inFont: nsFont];
  228500. for (int i = 0; i < [bez elementCount]; ++i)
  228501. {
  228502. NSPoint p[3];
  228503. switch ([bez elementAtIndex: i associatedPoints: p])
  228504. {
  228505. case NSMoveToBezierPathElement:
  228506. path.startNewSubPath ((float) p[0].x, (float) -p[0].y);
  228507. break;
  228508. case NSLineToBezierPathElement:
  228509. path.lineTo ((float) p[0].x, (float) -p[0].y);
  228510. break;
  228511. case NSCurveToBezierPathElement:
  228512. 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);
  228513. break;
  228514. case NSClosePathBezierPathElement:
  228515. path.closeSubPath();
  228516. break;
  228517. default:
  228518. jassertfalse;
  228519. break;
  228520. }
  228521. }
  228522. path.applyTransform (pathTransform);
  228523. return true;
  228524. #endif
  228525. }
  228526. juce_UseDebuggingNewOperator
  228527. CGFontRef fontRef;
  228528. float fontHeightToCGSizeFactor;
  228529. CGAffineTransform renderingTransform;
  228530. private:
  228531. float ascent, unitsToHeightScaleFactor;
  228532. #if JUCE_IPHONE
  228533. #else
  228534. NSFont* nsFont;
  228535. AffineTransform pathTransform;
  228536. #endif
  228537. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  228538. {
  228539. #if SUPPORT_10_4_FONTS
  228540. #if ! SUPPORT_ONLY_10_4_FONTS
  228541. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  228542. #endif
  228543. {
  228544. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  228545. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  228546. for (int i = 0; i < length; ++i)
  228547. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  228548. return;
  228549. }
  228550. #endif
  228551. #if ! SUPPORT_ONLY_10_4_FONTS
  228552. if (charToGlyphMapper == 0)
  228553. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  228554. glyphs.malloc (length);
  228555. for (int i = 0; i < length; ++i)
  228556. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  228557. #endif
  228558. }
  228559. #if ! SUPPORT_ONLY_10_4_FONTS
  228560. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  228561. class CharToGlyphMapper
  228562. {
  228563. public:
  228564. CharToGlyphMapper (CGFontRef fontRef)
  228565. : segCount (0), endCode (0), startCode (0), idDelta (0),
  228566. idRangeOffset (0), glyphIndexes (0)
  228567. {
  228568. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  228569. if (cmapTable != 0)
  228570. {
  228571. const int numSubtables = getValue16 (cmapTable, 2);
  228572. for (int i = 0; i < numSubtables; ++i)
  228573. {
  228574. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  228575. {
  228576. const int offset = getValue32 (cmapTable, i * 8 + 8);
  228577. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  228578. {
  228579. const int length = getValue16 (cmapTable, offset + 2);
  228580. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  228581. segCount = segCountX2 / 2;
  228582. const int endCodeOffset = offset + 14;
  228583. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  228584. const int idDeltaOffset = startCodeOffset + segCountX2;
  228585. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  228586. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  228587. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  228588. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  228589. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  228590. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  228591. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  228592. }
  228593. break;
  228594. }
  228595. }
  228596. CFRelease (cmapTable);
  228597. }
  228598. }
  228599. ~CharToGlyphMapper()
  228600. {
  228601. if (endCode != 0)
  228602. {
  228603. CFRelease (endCode);
  228604. CFRelease (startCode);
  228605. CFRelease (idDelta);
  228606. CFRelease (idRangeOffset);
  228607. CFRelease (glyphIndexes);
  228608. }
  228609. }
  228610. int getGlyphForCharacter (const juce_wchar c) const
  228611. {
  228612. for (int i = 0; i < segCount; ++i)
  228613. {
  228614. if (getValue16 (endCode, i * 2) >= c)
  228615. {
  228616. const int start = getValue16 (startCode, i * 2);
  228617. if (start > c)
  228618. break;
  228619. const int delta = getValue16 (idDelta, i * 2);
  228620. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  228621. if (rangeOffset == 0)
  228622. return delta + c;
  228623. else
  228624. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  228625. }
  228626. }
  228627. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  228628. return jmax (-1, c - 29);
  228629. }
  228630. private:
  228631. int segCount;
  228632. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  228633. static uint16 getValue16 (CFDataRef data, const int index)
  228634. {
  228635. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  228636. }
  228637. static uint32 getValue32 (CFDataRef data, const int index)
  228638. {
  228639. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  228640. }
  228641. };
  228642. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  228643. #endif
  228644. MacTypeface (const MacTypeface&);
  228645. MacTypeface& operator= (const MacTypeface&);
  228646. };
  228647. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  228648. {
  228649. return new MacTypeface (font);
  228650. }
  228651. const StringArray Font::findAllTypefaceNames()
  228652. {
  228653. StringArray names;
  228654. const ScopedAutoReleasePool pool;
  228655. #if JUCE_IPHONE
  228656. NSArray* fonts = [UIFont familyNames];
  228657. #else
  228658. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  228659. #endif
  228660. for (unsigned int i = 0; i < [fonts count]; ++i)
  228661. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  228662. names.sort (true);
  228663. return names;
  228664. }
  228665. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  228666. {
  228667. #if JUCE_IPHONE
  228668. defaultSans = "Helvetica";
  228669. defaultSerif = "Times New Roman";
  228670. defaultFixed = "Courier New";
  228671. #else
  228672. defaultSans = "Lucida Grande";
  228673. defaultSerif = "Times New Roman";
  228674. defaultFixed = "Monaco";
  228675. #endif
  228676. }
  228677. #endif
  228678. /*** End of inlined file: juce_mac_Fonts.mm ***/
  228679. // (must go before juce_mac_CoreGraphicsContext.mm)
  228680. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  228681. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228682. // compiled on its own).
  228683. #if JUCE_INCLUDED_FILE
  228684. class CoreGraphicsImage : public Image::SharedImage
  228685. {
  228686. public:
  228687. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  228688. : Image::SharedImage (format_, width_, height_)
  228689. {
  228690. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  228691. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  228692. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  228693. imageData = imageDataAllocated;
  228694. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  228695. : CGColorSpaceCreateDeviceRGB();
  228696. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  228697. colourSpace, getCGImageFlags (format_));
  228698. CGColorSpaceRelease (colourSpace);
  228699. }
  228700. ~CoreGraphicsImage()
  228701. {
  228702. CGContextRelease (context);
  228703. }
  228704. Image::ImageType getType() const { return Image::NativeImage; }
  228705. LowLevelGraphicsContext* createLowLevelContext();
  228706. SharedImage* clone()
  228707. {
  228708. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  228709. memcpy (im->imageData, imageData, lineStride * height);
  228710. return im;
  228711. }
  228712. static CGImageRef createImage (const Image& juceImage, const bool forAlpha, CGColorSpaceRef colourSpace)
  228713. {
  228714. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  228715. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  228716. {
  228717. return CGBitmapContextCreateImage (nativeImage->context);
  228718. }
  228719. else
  228720. {
  228721. const Image::BitmapData srcData (juceImage, 0, 0, juceImage.getWidth(), juceImage.getHeight());
  228722. CGDataProviderRef provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  228723. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  228724. 8, srcData.pixelStride * 8, srcData.lineStride,
  228725. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  228726. 0, true, kCGRenderingIntentDefault);
  228727. CGDataProviderRelease (provider);
  228728. return imageRef;
  228729. }
  228730. }
  228731. #if JUCE_MAC
  228732. static NSImage* createNSImage (const Image& image)
  228733. {
  228734. const ScopedAutoReleasePool pool;
  228735. NSImage* im = [[NSImage alloc] init];
  228736. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  228737. [im lockFocus];
  228738. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  228739. CGImageRef imageRef = createImage (image, false, colourSpace);
  228740. CGColorSpaceRelease (colourSpace);
  228741. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  228742. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  228743. CGImageRelease (imageRef);
  228744. [im unlockFocus];
  228745. return im;
  228746. }
  228747. #endif
  228748. CGContextRef context;
  228749. HeapBlock<uint8> imageDataAllocated;
  228750. private:
  228751. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  228752. {
  228753. #if JUCE_BIG_ENDIAN
  228754. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  228755. #else
  228756. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  228757. #endif
  228758. }
  228759. };
  228760. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  228761. {
  228762. #if USE_COREGRAPHICS_RENDERING
  228763. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  228764. #else
  228765. return createSoftwareImage (format, width, height, clearImage);
  228766. #endif
  228767. }
  228768. class CoreGraphicsContext : public LowLevelGraphicsContext
  228769. {
  228770. public:
  228771. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  228772. : context (context_),
  228773. flipHeight (flipHeight_),
  228774. state (new SavedState()),
  228775. numGradientLookupEntries (0),
  228776. lastClipRectIsValid (false)
  228777. {
  228778. CGContextRetain (context);
  228779. CGContextSaveGState(context);
  228780. CGContextSetShouldSmoothFonts (context, true);
  228781. CGContextSetShouldAntialias (context, true);
  228782. CGContextSetBlendMode (context, kCGBlendModeNormal);
  228783. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  228784. greyColourSpace = CGColorSpaceCreateDeviceGray();
  228785. gradientCallbacks.version = 0;
  228786. gradientCallbacks.evaluate = gradientCallback;
  228787. gradientCallbacks.releaseInfo = 0;
  228788. setFont (Font());
  228789. }
  228790. ~CoreGraphicsContext()
  228791. {
  228792. CGContextRestoreGState (context);
  228793. CGContextRelease (context);
  228794. CGColorSpaceRelease (rgbColourSpace);
  228795. CGColorSpaceRelease (greyColourSpace);
  228796. }
  228797. bool isVectorDevice() const { return false; }
  228798. void setOrigin (int x, int y)
  228799. {
  228800. CGContextTranslateCTM (context, x, -y);
  228801. if (lastClipRectIsValid)
  228802. lastClipRect.translate (-x, -y);
  228803. }
  228804. bool clipToRectangle (const Rectangle<int>& r)
  228805. {
  228806. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  228807. if (lastClipRectIsValid)
  228808. {
  228809. lastClipRect = lastClipRect.getIntersection (r);
  228810. return ! lastClipRect.isEmpty();
  228811. }
  228812. return ! isClipEmpty();
  228813. }
  228814. bool clipToRectangleList (const RectangleList& clipRegion)
  228815. {
  228816. if (clipRegion.isEmpty())
  228817. {
  228818. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  228819. lastClipRectIsValid = true;
  228820. lastClipRect = Rectangle<int>();
  228821. return false;
  228822. }
  228823. else
  228824. {
  228825. const int numRects = clipRegion.getNumRectangles();
  228826. HeapBlock <CGRect> rects (numRects);
  228827. for (int i = 0; i < numRects; ++i)
  228828. {
  228829. const Rectangle<int>& r = clipRegion.getRectangle(i);
  228830. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  228831. }
  228832. CGContextClipToRects (context, rects, numRects);
  228833. lastClipRectIsValid = false;
  228834. return ! isClipEmpty();
  228835. }
  228836. }
  228837. void excludeClipRectangle (const Rectangle<int>& r)
  228838. {
  228839. RectangleList remaining (getClipBounds());
  228840. remaining.subtract (r);
  228841. clipToRectangleList (remaining);
  228842. lastClipRectIsValid = false;
  228843. }
  228844. void clipToPath (const Path& path, const AffineTransform& transform)
  228845. {
  228846. createPath (path, transform);
  228847. CGContextClip (context);
  228848. lastClipRectIsValid = false;
  228849. }
  228850. void clipToImageAlpha (const Image& sourceImage, const Rectangle<int>& srcClip, const AffineTransform& transform)
  228851. {
  228852. if (! transform.isSingularity())
  228853. {
  228854. Image singleChannelImage (sourceImage);
  228855. if (sourceImage.getFormat() != Image::SingleChannel)
  228856. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  228857. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace);
  228858. if (srcClip != sourceImage.getBounds())
  228859. {
  228860. CGImageRef fullImage = image;
  228861. image = CGImageCreateWithImageInRect (fullImage, CGRectMake (srcClip.getX(), srcClip.getY(),
  228862. srcClip.getWidth(), srcClip.getHeight()));
  228863. CGImageRelease (fullImage);
  228864. }
  228865. flip();
  228866. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, srcClip.getHeight()).followedBy (transform));
  228867. applyTransform (t);
  228868. CGRect r = CGRectMake (0, 0, srcClip.getWidth(), srcClip.getHeight());
  228869. CGContextClipToMask (context, r, image);
  228870. applyTransform (t.inverted());
  228871. flip();
  228872. CGImageRelease (image);
  228873. lastClipRectIsValid = false;
  228874. }
  228875. }
  228876. bool clipRegionIntersects (const Rectangle<int>& r)
  228877. {
  228878. return getClipBounds().intersects (r);
  228879. }
  228880. const Rectangle<int> getClipBounds() const
  228881. {
  228882. if (! lastClipRectIsValid)
  228883. {
  228884. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  228885. lastClipRectIsValid = true;
  228886. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  228887. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  228888. roundToInt (bounds.size.width),
  228889. roundToInt (bounds.size.height));
  228890. }
  228891. return lastClipRect;
  228892. }
  228893. bool isClipEmpty() const
  228894. {
  228895. return getClipBounds().isEmpty();
  228896. }
  228897. void saveState()
  228898. {
  228899. CGContextSaveGState (context);
  228900. stateStack.add (new SavedState (*state));
  228901. }
  228902. void restoreState()
  228903. {
  228904. CGContextRestoreGState (context);
  228905. SavedState* const top = stateStack.getLast();
  228906. if (top != 0)
  228907. {
  228908. state = top;
  228909. stateStack.removeLast (1, false);
  228910. lastClipRectIsValid = false;
  228911. }
  228912. else
  228913. {
  228914. jassertfalse; // trying to pop with an empty stack!
  228915. }
  228916. }
  228917. void setFill (const FillType& fillType)
  228918. {
  228919. state->fillType = fillType;
  228920. if (fillType.isColour())
  228921. {
  228922. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  228923. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  228924. CGContextSetAlpha (context, 1.0f);
  228925. }
  228926. }
  228927. void setOpacity (float newOpacity)
  228928. {
  228929. state->fillType.setOpacity (newOpacity);
  228930. setFill (state->fillType);
  228931. }
  228932. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  228933. {
  228934. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  228935. ? kCGInterpolationLow
  228936. : kCGInterpolationHigh);
  228937. }
  228938. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  228939. {
  228940. CGRect cgRect = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  228941. if (replaceExistingContents)
  228942. {
  228943. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  228944. CGContextClearRect (context, cgRect);
  228945. #else
  228946. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  228947. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  228948. CGContextClearRect (context, cgRect);
  228949. else
  228950. #endif
  228951. CGContextSetBlendMode (context, kCGBlendModeCopy);
  228952. #endif
  228953. fillRect (r, false);
  228954. CGContextSetBlendMode (context, kCGBlendModeNormal);
  228955. }
  228956. else
  228957. {
  228958. if (state->fillType.isColour())
  228959. {
  228960. CGContextFillRect (context, cgRect);
  228961. }
  228962. else if (state->fillType.isGradient())
  228963. {
  228964. CGContextSaveGState (context);
  228965. CGContextClipToRect (context, cgRect);
  228966. drawGradient();
  228967. CGContextRestoreGState (context);
  228968. }
  228969. else
  228970. {
  228971. CGContextSaveGState (context);
  228972. CGContextClipToRect (context, cgRect);
  228973. drawImage (state->fillType.image, state->fillType.image.getBounds(), state->fillType.transform, true);
  228974. CGContextRestoreGState (context);
  228975. }
  228976. }
  228977. }
  228978. void fillPath (const Path& path, const AffineTransform& transform)
  228979. {
  228980. CGContextSaveGState (context);
  228981. if (state->fillType.isColour())
  228982. {
  228983. flip();
  228984. applyTransform (transform);
  228985. createPath (path);
  228986. if (path.isUsingNonZeroWinding())
  228987. CGContextFillPath (context);
  228988. else
  228989. CGContextEOFillPath (context);
  228990. }
  228991. else
  228992. {
  228993. createPath (path, transform);
  228994. if (path.isUsingNonZeroWinding())
  228995. CGContextClip (context);
  228996. else
  228997. CGContextEOClip (context);
  228998. if (state->fillType.isGradient())
  228999. drawGradient();
  229000. else
  229001. drawImage (state->fillType.image, state->fillType.image.getBounds(), state->fillType.transform, true);
  229002. }
  229003. CGContextRestoreGState (context);
  229004. }
  229005. void drawImage (const Image& sourceImage, const Rectangle<int>& srcClip,
  229006. const AffineTransform& transform, const bool fillEntireClipAsTiles)
  229007. {
  229008. jassert (sourceImage.getBounds().contains (srcClip));
  229009. CGImageRef fullImage = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace);
  229010. CGImageRef image = fullImage;
  229011. if (srcClip != sourceImage.getBounds())
  229012. {
  229013. image = CGImageCreateWithImageInRect (fullImage, CGRectMake (srcClip.getX(), srcClip.getY(),
  229014. srcClip.getWidth(), srcClip.getHeight()));
  229015. CGImageRelease (fullImage);
  229016. }
  229017. CGContextSaveGState (context);
  229018. CGContextSetAlpha (context, state->fillType.getOpacity());
  229019. flip();
  229020. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, srcClip.getHeight()).followedBy (transform));
  229021. CGRect imageRect = CGRectMake (0, 0, srcClip.getWidth(), srcClip.getHeight());
  229022. if (fillEntireClipAsTiles)
  229023. {
  229024. #if JUCE_IPHONE
  229025. CGContextDrawTiledImage (context, imageRect, image);
  229026. #else
  229027. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  229028. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  229029. // if it's doing a transformation - it's quicker to just draw lots of images manually
  229030. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  229031. CGContextDrawTiledImage (context, imageRect, image);
  229032. else
  229033. #endif
  229034. {
  229035. // Fallback to manually doing a tiled fill on 10.4
  229036. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  229037. const int iw = srcClip.getWidth();
  229038. const int ih = srcClip.getHeight();
  229039. int x = 0, y = 0;
  229040. while (x > clip.origin.x) x -= iw;
  229041. while (y > clip.origin.y) y -= ih;
  229042. const int right = (int) (clip.origin.x + clip.size.width);
  229043. const int bottom = (int) (clip.origin.y + clip.size.height);
  229044. while (y < bottom)
  229045. {
  229046. for (int x2 = x; x2 < right; x2 += iw)
  229047. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  229048. y += ih;
  229049. }
  229050. }
  229051. #endif
  229052. }
  229053. else
  229054. {
  229055. CGContextDrawImage (context, imageRect, image);
  229056. }
  229057. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  229058. CGContextRestoreGState (context);
  229059. }
  229060. void drawLine (const Line<float>& line)
  229061. {
  229062. CGContextSetLineCap (context, kCGLineCapSquare);
  229063. CGContextSetLineWidth (context, 1.0f);
  229064. CGContextSetRGBStrokeColor (context,
  229065. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  229066. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  229067. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  229068. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  229069. CGContextStrokeLineSegments (context, cgLine, 1);
  229070. }
  229071. void drawVerticalLine (const int x, float top, float bottom)
  229072. {
  229073. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  229074. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  229075. #else
  229076. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  229077. // the x co-ord slightly to trick it..
  229078. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  229079. #endif
  229080. }
  229081. void drawHorizontalLine (const int y, float left, float right)
  229082. {
  229083. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  229084. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  229085. #else
  229086. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  229087. // the x co-ord slightly to trick it..
  229088. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  229089. #endif
  229090. }
  229091. void setFont (const Font& newFont)
  229092. {
  229093. if (state->font != newFont)
  229094. {
  229095. state->fontRef = 0;
  229096. state->font = newFont;
  229097. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  229098. if (mf != 0)
  229099. {
  229100. state->fontRef = mf->fontRef;
  229101. CGContextSetFont (context, state->fontRef);
  229102. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  229103. state->fontTransform = mf->renderingTransform;
  229104. state->fontTransform.a *= state->font.getHorizontalScale();
  229105. CGContextSetTextMatrix (context, state->fontTransform);
  229106. }
  229107. }
  229108. }
  229109. const Font getFont()
  229110. {
  229111. return state->font;
  229112. }
  229113. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  229114. {
  229115. if (state->fontRef != 0 && state->fillType.isColour())
  229116. {
  229117. if (transform.isOnlyTranslation())
  229118. {
  229119. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  229120. CGGlyph g = glyphNumber;
  229121. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  229122. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  229123. }
  229124. else
  229125. {
  229126. CGContextSaveGState (context);
  229127. flip();
  229128. applyTransform (transform);
  229129. CGAffineTransform t = state->fontTransform;
  229130. t.d = -t.d;
  229131. CGContextSetTextMatrix (context, t);
  229132. CGGlyph g = glyphNumber;
  229133. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  229134. CGContextRestoreGState (context);
  229135. }
  229136. }
  229137. else
  229138. {
  229139. Path p;
  229140. Font& f = state->font;
  229141. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  229142. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  229143. .followedBy (transform));
  229144. }
  229145. }
  229146. private:
  229147. CGContextRef context;
  229148. const CGFloat flipHeight;
  229149. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  229150. CGFunctionCallbacks gradientCallbacks;
  229151. mutable Rectangle<int> lastClipRect;
  229152. mutable bool lastClipRectIsValid;
  229153. struct SavedState
  229154. {
  229155. SavedState()
  229156. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  229157. {
  229158. }
  229159. SavedState (const SavedState& other)
  229160. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  229161. fontTransform (other.fontTransform)
  229162. {
  229163. }
  229164. ~SavedState()
  229165. {
  229166. }
  229167. FillType fillType;
  229168. Font font;
  229169. CGFontRef fontRef;
  229170. CGAffineTransform fontTransform;
  229171. };
  229172. ScopedPointer <SavedState> state;
  229173. OwnedArray <SavedState> stateStack;
  229174. HeapBlock <PixelARGB> gradientLookupTable;
  229175. int numGradientLookupEntries;
  229176. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  229177. {
  229178. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  229179. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  229180. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  229181. colour.unpremultiply();
  229182. outData[0] = colour.getRed() / 255.0f;
  229183. outData[1] = colour.getGreen() / 255.0f;
  229184. outData[2] = colour.getBlue() / 255.0f;
  229185. outData[3] = colour.getAlpha() / 255.0f;
  229186. }
  229187. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  229188. {
  229189. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable);
  229190. --numGradientLookupEntries;
  229191. CGShadingRef result = 0;
  229192. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  229193. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  229194. if (gradient.isRadial)
  229195. {
  229196. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  229197. p1, gradient.point1.getDistanceFrom (gradient.point2),
  229198. function, true, true);
  229199. }
  229200. else
  229201. {
  229202. result = CGShadingCreateAxial (rgbColourSpace, p1,
  229203. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  229204. function, true, true);
  229205. }
  229206. CGFunctionRelease (function);
  229207. return result;
  229208. }
  229209. void drawGradient()
  229210. {
  229211. flip();
  229212. applyTransform (state->fillType.transform);
  229213. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  229214. // you draw a gradient with high quality interp enabled).
  229215. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  229216. CGContextSetAlpha (context, state->fillType.getOpacity());
  229217. CGContextDrawShading (context, shading);
  229218. CGShadingRelease (shading);
  229219. }
  229220. void createPath (const Path& path) const
  229221. {
  229222. CGContextBeginPath (context);
  229223. Path::Iterator i (path);
  229224. while (i.next())
  229225. {
  229226. switch (i.elementType)
  229227. {
  229228. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  229229. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  229230. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  229231. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  229232. case Path::Iterator::closePath: CGContextClosePath (context); break;
  229233. default: jassertfalse; break;
  229234. }
  229235. }
  229236. }
  229237. void createPath (const Path& path, const AffineTransform& transform) const
  229238. {
  229239. CGContextBeginPath (context);
  229240. Path::Iterator i (path);
  229241. while (i.next())
  229242. {
  229243. switch (i.elementType)
  229244. {
  229245. case Path::Iterator::startNewSubPath:
  229246. transform.transformPoint (i.x1, i.y1);
  229247. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  229248. break;
  229249. case Path::Iterator::lineTo:
  229250. transform.transformPoint (i.x1, i.y1);
  229251. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  229252. break;
  229253. case Path::Iterator::quadraticTo:
  229254. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  229255. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  229256. break;
  229257. case Path::Iterator::cubicTo:
  229258. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  229259. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  229260. break;
  229261. case Path::Iterator::closePath:
  229262. CGContextClosePath (context); break;
  229263. default:
  229264. jassertfalse;
  229265. break;
  229266. }
  229267. }
  229268. }
  229269. void flip() const
  229270. {
  229271. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  229272. }
  229273. void applyTransform (const AffineTransform& transform) const
  229274. {
  229275. CGAffineTransform t;
  229276. t.a = transform.mat00;
  229277. t.b = transform.mat10;
  229278. t.c = transform.mat01;
  229279. t.d = transform.mat11;
  229280. t.tx = transform.mat02;
  229281. t.ty = transform.mat12;
  229282. CGContextConcatCTM (context, t);
  229283. }
  229284. CoreGraphicsContext (const CoreGraphicsContext&);
  229285. CoreGraphicsContext& operator= (const CoreGraphicsContext&);
  229286. };
  229287. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  229288. {
  229289. return new CoreGraphicsContext (context, height);
  229290. }
  229291. #endif
  229292. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  229293. /*** Start of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  229294. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229295. // compiled on its own).
  229296. #if JUCE_INCLUDED_FILE
  229297. class NSViewComponentPeer;
  229298. END_JUCE_NAMESPACE
  229299. @interface NSEvent (JuceDeviceDelta)
  229300. - (float) deviceDeltaX;
  229301. - (float) deviceDeltaY;
  229302. @end
  229303. #define JuceNSView MakeObjCClassName(JuceNSView)
  229304. @interface JuceNSView : NSView<NSTextInput>
  229305. {
  229306. @public
  229307. NSViewComponentPeer* owner;
  229308. NSNotificationCenter* notificationCenter;
  229309. String* stringBeingComposed;
  229310. bool textWasInserted;
  229311. }
  229312. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner withFrame: (NSRect) frame;
  229313. - (void) dealloc;
  229314. - (BOOL) isOpaque;
  229315. - (void) drawRect: (NSRect) r;
  229316. - (void) mouseDown: (NSEvent*) ev;
  229317. - (void) asyncMouseDown: (NSEvent*) ev;
  229318. - (void) mouseUp: (NSEvent*) ev;
  229319. - (void) asyncMouseUp: (NSEvent*) ev;
  229320. - (void) mouseDragged: (NSEvent*) ev;
  229321. - (void) mouseMoved: (NSEvent*) ev;
  229322. - (void) mouseEntered: (NSEvent*) ev;
  229323. - (void) mouseExited: (NSEvent*) ev;
  229324. - (void) rightMouseDown: (NSEvent*) ev;
  229325. - (void) rightMouseDragged: (NSEvent*) ev;
  229326. - (void) rightMouseUp: (NSEvent*) ev;
  229327. - (void) otherMouseDown: (NSEvent*) ev;
  229328. - (void) otherMouseDragged: (NSEvent*) ev;
  229329. - (void) otherMouseUp: (NSEvent*) ev;
  229330. - (void) scrollWheel: (NSEvent*) ev;
  229331. - (BOOL) acceptsFirstMouse: (NSEvent*) ev;
  229332. - (void) frameChanged: (NSNotification*) n;
  229333. - (void) viewDidMoveToWindow;
  229334. - (void) keyDown: (NSEvent*) ev;
  229335. - (void) keyUp: (NSEvent*) ev;
  229336. // NSTextInput Methods
  229337. - (void) insertText: (id) aString;
  229338. - (void) doCommandBySelector: (SEL) aSelector;
  229339. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selRange;
  229340. - (void) unmarkText;
  229341. - (BOOL) hasMarkedText;
  229342. - (long) conversationIdentifier;
  229343. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange;
  229344. - (NSRange) markedRange;
  229345. - (NSRange) selectedRange;
  229346. - (NSRect) firstRectForCharacterRange: (NSRange) theRange;
  229347. - (unsigned int) characterIndexForPoint: (NSPoint) thePoint;
  229348. - (NSArray*) validAttributesForMarkedText;
  229349. - (void) flagsChanged: (NSEvent*) ev;
  229350. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  229351. - (BOOL) performKeyEquivalent: (NSEvent*) ev;
  229352. #endif
  229353. - (BOOL) becomeFirstResponder;
  229354. - (BOOL) resignFirstResponder;
  229355. - (BOOL) acceptsFirstResponder;
  229356. - (void) asyncRepaint: (id) rect;
  229357. - (NSArray*) getSupportedDragTypes;
  229358. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender;
  229359. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender;
  229360. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender;
  229361. - (void) draggingEnded: (id <NSDraggingInfo>) sender;
  229362. - (void) draggingExited: (id <NSDraggingInfo>) sender;
  229363. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender;
  229364. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender;
  229365. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender;
  229366. @end
  229367. #define JuceNSWindow MakeObjCClassName(JuceNSWindow)
  229368. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  229369. @interface JuceNSWindow : NSWindow <NSWindowDelegate>
  229370. #else
  229371. @interface JuceNSWindow : NSWindow
  229372. #endif
  229373. {
  229374. @private
  229375. NSViewComponentPeer* owner;
  229376. bool isZooming;
  229377. }
  229378. - (void) setOwner: (NSViewComponentPeer*) owner;
  229379. - (BOOL) canBecomeKeyWindow;
  229380. - (void) becomeKeyWindow;
  229381. - (BOOL) windowShouldClose: (id) window;
  229382. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen;
  229383. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize;
  229384. - (void) zoom: (id) sender;
  229385. @end
  229386. BEGIN_JUCE_NAMESPACE
  229387. class NSViewComponentPeer : public ComponentPeer
  229388. {
  229389. public:
  229390. NSViewComponentPeer (Component* const component,
  229391. const int windowStyleFlags,
  229392. NSView* viewToAttachTo);
  229393. ~NSViewComponentPeer();
  229394. void* getNativeHandle() const;
  229395. void setVisible (bool shouldBeVisible);
  229396. void setTitle (const String& title);
  229397. void setPosition (int x, int y);
  229398. void setSize (int w, int h);
  229399. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen);
  229400. const Rectangle<int> getBounds (const bool global) const;
  229401. const Rectangle<int> getBounds() const;
  229402. const Point<int> getScreenPosition() const;
  229403. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition);
  229404. const Point<int> globalPositionToRelative (const Point<int>& screenPosition);
  229405. void setMinimised (bool shouldBeMinimised);
  229406. bool isMinimised() const;
  229407. void setFullScreen (bool shouldBeFullScreen);
  229408. bool isFullScreen() const;
  229409. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  229410. const BorderSize getFrameSize() const;
  229411. bool setAlwaysOnTop (bool alwaysOnTop);
  229412. void toFront (bool makeActiveWindow);
  229413. void toBehind (ComponentPeer* other);
  229414. void setIcon (const Image& newIcon);
  229415. const StringArray getAvailableRenderingEngines() throw();
  229416. int getCurrentRenderingEngine() throw();
  229417. void setCurrentRenderingEngine (int index) throw();
  229418. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  229419. for example having more than one juce plugin loaded into a host, then when a
  229420. method is called, the actual code that runs might actually be in a different module
  229421. than the one you expect... So any calls to library functions or statics that are
  229422. made inside obj-c methods will probably end up getting executed in a different DLL's
  229423. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  229424. To work around this insanity, I'm only allowing obj-c methods to make calls to
  229425. virtual methods of an object that's known to live inside the right module's space.
  229426. */
  229427. virtual void redirectMouseDown (NSEvent* ev);
  229428. virtual void redirectMouseUp (NSEvent* ev);
  229429. virtual void redirectMouseDrag (NSEvent* ev);
  229430. virtual void redirectMouseMove (NSEvent* ev);
  229431. virtual void redirectMouseEnter (NSEvent* ev);
  229432. virtual void redirectMouseExit (NSEvent* ev);
  229433. virtual void redirectMouseWheel (NSEvent* ev);
  229434. void sendMouseEvent (NSEvent* ev);
  229435. bool handleKeyEvent (NSEvent* ev, bool isKeyDown);
  229436. virtual bool redirectKeyDown (NSEvent* ev);
  229437. virtual bool redirectKeyUp (NSEvent* ev);
  229438. virtual void redirectModKeyChange (NSEvent* ev);
  229439. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  229440. virtual bool redirectPerformKeyEquivalent (NSEvent* ev);
  229441. #endif
  229442. virtual BOOL sendDragCallback (int type, id <NSDraggingInfo> sender);
  229443. virtual bool isOpaque();
  229444. virtual void drawRect (NSRect r);
  229445. virtual bool canBecomeKeyWindow();
  229446. virtual bool windowShouldClose();
  229447. virtual void redirectMovedOrResized();
  229448. virtual void viewMovedToWindow();
  229449. virtual NSRect constrainRect (NSRect r);
  229450. static void showArrowCursorIfNeeded();
  229451. static void updateModifiers (NSEvent* e);
  229452. static void updateKeysDown (NSEvent* ev, bool isKeyDown);
  229453. static int getKeyCodeFromEvent (NSEvent* ev)
  229454. {
  229455. const String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  229456. int keyCode = unmodified[0];
  229457. if (keyCode == 0x19) // (backwards-tab)
  229458. keyCode = '\t';
  229459. else if (keyCode == 0x03) // (enter)
  229460. keyCode = '\r';
  229461. return keyCode;
  229462. }
  229463. static int64 getMouseTime (NSEvent* e)
  229464. {
  229465. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  229466. + (int64) ([e timestamp] * 1000.0);
  229467. }
  229468. static const Point<int> getMousePos (NSEvent* e, NSView* view)
  229469. {
  229470. NSPoint p = [view convertPoint: [e locationInWindow] fromView: nil];
  229471. return Point<int> (roundToInt (p.x), roundToInt ([view frame].size.height - p.y));
  229472. }
  229473. static int getModifierForButtonNumber (const NSInteger num)
  229474. {
  229475. return num == 0 ? ModifierKeys::leftButtonModifier
  229476. : (num == 1 ? ModifierKeys::rightButtonModifier
  229477. : (num == 2 ? ModifierKeys::middleButtonModifier : 0));
  229478. }
  229479. virtual void viewFocusGain();
  229480. virtual void viewFocusLoss();
  229481. bool isFocused() const;
  229482. void grabFocus();
  229483. void textInputRequired (const Point<int>& position);
  229484. void repaint (const Rectangle<int>& area);
  229485. void performAnyPendingRepaintsNow();
  229486. juce_UseDebuggingNewOperator
  229487. NSWindow* window;
  229488. JuceNSView* view;
  229489. bool isSharedWindow, fullScreen, insideDrawRect, usingCoreGraphics, recursiveToFrontCall;
  229490. static ModifierKeys currentModifiers;
  229491. static ComponentPeer* currentlyFocusedPeer;
  229492. static Array<int> keysCurrentlyDown;
  229493. };
  229494. END_JUCE_NAMESPACE
  229495. @implementation JuceNSView
  229496. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner_
  229497. withFrame: (NSRect) frame
  229498. {
  229499. [super initWithFrame: frame];
  229500. owner = owner_;
  229501. stringBeingComposed = 0;
  229502. textWasInserted = false;
  229503. notificationCenter = [NSNotificationCenter defaultCenter];
  229504. [notificationCenter addObserver: self
  229505. selector: @selector (frameChanged:)
  229506. name: NSViewFrameDidChangeNotification
  229507. object: self];
  229508. if (! owner_->isSharedWindow)
  229509. {
  229510. [notificationCenter addObserver: self
  229511. selector: @selector (frameChanged:)
  229512. name: NSWindowDidMoveNotification
  229513. object: owner_->window];
  229514. }
  229515. [self registerForDraggedTypes: [self getSupportedDragTypes]];
  229516. return self;
  229517. }
  229518. - (void) dealloc
  229519. {
  229520. [notificationCenter removeObserver: self];
  229521. delete stringBeingComposed;
  229522. [super dealloc];
  229523. }
  229524. - (void) drawRect: (NSRect) r
  229525. {
  229526. if (owner != 0)
  229527. owner->drawRect (r);
  229528. }
  229529. - (BOOL) isOpaque
  229530. {
  229531. return owner == 0 || owner->isOpaque();
  229532. }
  229533. - (void) mouseDown: (NSEvent*) ev
  229534. {
  229535. // In some host situations, the host will stop modal loops from working
  229536. // correctly if they're called from a mouse event, so we'll trigger
  229537. // the event asynchronously..
  229538. if (JUCEApplication::getInstance() == 0)
  229539. [self performSelectorOnMainThread: @selector (asyncMouseDown:)
  229540. withObject: ev
  229541. waitUntilDone: NO];
  229542. else
  229543. [self asyncMouseDown: ev];
  229544. }
  229545. - (void) asyncMouseDown: (NSEvent*) ev
  229546. {
  229547. if (owner != 0)
  229548. owner->redirectMouseDown (ev);
  229549. }
  229550. - (void) mouseUp: (NSEvent*) ev
  229551. {
  229552. // In some host situations, the host will stop modal loops from working
  229553. // correctly if they're called from a mouse event, so we'll trigger
  229554. // the event asynchronously..
  229555. if (JUCEApplication::getInstance() == 0)
  229556. [self performSelectorOnMainThread: @selector (asyncMouseUp:)
  229557. withObject: ev
  229558. waitUntilDone: NO];
  229559. else
  229560. [self asyncMouseUp: ev];
  229561. }
  229562. - (void) asyncMouseUp: (NSEvent*) ev
  229563. {
  229564. if (owner != 0)
  229565. owner->redirectMouseUp (ev);
  229566. }
  229567. - (void) mouseDragged: (NSEvent*) ev
  229568. {
  229569. if (owner != 0)
  229570. owner->redirectMouseDrag (ev);
  229571. }
  229572. - (void) mouseMoved: (NSEvent*) ev
  229573. {
  229574. if (owner != 0)
  229575. owner->redirectMouseMove (ev);
  229576. }
  229577. - (void) mouseEntered: (NSEvent*) ev
  229578. {
  229579. if (owner != 0)
  229580. owner->redirectMouseEnter (ev);
  229581. }
  229582. - (void) mouseExited: (NSEvent*) ev
  229583. {
  229584. if (owner != 0)
  229585. owner->redirectMouseExit (ev);
  229586. }
  229587. - (void) rightMouseDown: (NSEvent*) ev
  229588. {
  229589. [self mouseDown: ev];
  229590. }
  229591. - (void) rightMouseDragged: (NSEvent*) ev
  229592. {
  229593. [self mouseDragged: ev];
  229594. }
  229595. - (void) rightMouseUp: (NSEvent*) ev
  229596. {
  229597. [self mouseUp: ev];
  229598. }
  229599. - (void) otherMouseDown: (NSEvent*) ev
  229600. {
  229601. [self mouseDown: ev];
  229602. }
  229603. - (void) otherMouseDragged: (NSEvent*) ev
  229604. {
  229605. [self mouseDragged: ev];
  229606. }
  229607. - (void) otherMouseUp: (NSEvent*) ev
  229608. {
  229609. [self mouseUp: ev];
  229610. }
  229611. - (void) scrollWheel: (NSEvent*) ev
  229612. {
  229613. if (owner != 0)
  229614. owner->redirectMouseWheel (ev);
  229615. }
  229616. - (BOOL) acceptsFirstMouse: (NSEvent*) ev
  229617. {
  229618. (void) ev;
  229619. return YES;
  229620. }
  229621. - (void) frameChanged: (NSNotification*) n
  229622. {
  229623. (void) n;
  229624. if (owner != 0)
  229625. owner->redirectMovedOrResized();
  229626. }
  229627. - (void) viewDidMoveToWindow
  229628. {
  229629. if (owner != 0)
  229630. owner->viewMovedToWindow();
  229631. }
  229632. - (void) asyncRepaint: (id) rect
  229633. {
  229634. NSRect* r = (NSRect*) [((NSData*) rect) bytes];
  229635. [self setNeedsDisplayInRect: *r];
  229636. }
  229637. - (void) keyDown: (NSEvent*) ev
  229638. {
  229639. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  229640. textWasInserted = false;
  229641. if (target != 0)
  229642. [self interpretKeyEvents: [NSArray arrayWithObject: ev]];
  229643. else
  229644. deleteAndZero (stringBeingComposed);
  229645. if ((! textWasInserted) && (owner == 0 || ! owner->redirectKeyDown (ev)))
  229646. [super keyDown: ev];
  229647. }
  229648. - (void) keyUp: (NSEvent*) ev
  229649. {
  229650. if (owner == 0 || ! owner->redirectKeyUp (ev))
  229651. [super keyUp: ev];
  229652. }
  229653. - (void) insertText: (id) aString
  229654. {
  229655. // This commits multi-byte text when return is pressed, or after every keypress for western keyboards
  229656. if ([aString length] > 0)
  229657. {
  229658. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  229659. if (target != 0)
  229660. {
  229661. target->insertTextAtCaret (nsStringToJuce ([aString isKindOfClass: [NSAttributedString class]] ? [aString string] : aString));
  229662. textWasInserted = true;
  229663. }
  229664. }
  229665. deleteAndZero (stringBeingComposed);
  229666. }
  229667. - (void) doCommandBySelector: (SEL) aSelector
  229668. {
  229669. (void) aSelector;
  229670. }
  229671. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selectionRange
  229672. {
  229673. (void) selectionRange;
  229674. if (stringBeingComposed == 0)
  229675. stringBeingComposed = new String();
  229676. *stringBeingComposed = nsStringToJuce ([aString isKindOfClass:[NSAttributedString class]] ? [aString string] : aString);
  229677. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  229678. if (target != 0)
  229679. {
  229680. const Range<int> currentHighlight (target->getHighlightedRegion());
  229681. target->insertTextAtCaret (*stringBeingComposed);
  229682. target->setHighlightedRegion (currentHighlight.withLength (stringBeingComposed->length()));
  229683. textWasInserted = true;
  229684. }
  229685. }
  229686. - (void) unmarkText
  229687. {
  229688. if (stringBeingComposed != 0)
  229689. {
  229690. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  229691. if (target != 0)
  229692. {
  229693. target->insertTextAtCaret (*stringBeingComposed);
  229694. textWasInserted = true;
  229695. }
  229696. }
  229697. deleteAndZero (stringBeingComposed);
  229698. }
  229699. - (BOOL) hasMarkedText
  229700. {
  229701. return stringBeingComposed != 0;
  229702. }
  229703. - (long) conversationIdentifier
  229704. {
  229705. return (long) (pointer_sized_int) self;
  229706. }
  229707. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange
  229708. {
  229709. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  229710. if (target != 0)
  229711. {
  229712. const Range<int> r ((int) theRange.location,
  229713. (int) (theRange.location + theRange.length));
  229714. return [[[NSAttributedString alloc] initWithString: juceStringToNS (target->getTextInRange (r))] autorelease];
  229715. }
  229716. return nil;
  229717. }
  229718. - (NSRange) markedRange
  229719. {
  229720. return stringBeingComposed != 0 ? NSMakeRange (0, stringBeingComposed->length())
  229721. : NSMakeRange (NSNotFound, 0);
  229722. }
  229723. - (NSRange) selectedRange
  229724. {
  229725. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  229726. if (target != 0)
  229727. {
  229728. const Range<int> highlight (target->getHighlightedRegion());
  229729. if (! highlight.isEmpty())
  229730. return NSMakeRange (highlight.getStart(), highlight.getLength());
  229731. }
  229732. return NSMakeRange (NSNotFound, 0);
  229733. }
  229734. - (NSRect) firstRectForCharacterRange: (NSRange) theRange
  229735. {
  229736. (void) theRange;
  229737. JUCE_NAMESPACE::Component* const comp = dynamic_cast <JUCE_NAMESPACE::Component*> (owner->findCurrentTextInputTarget());
  229738. if (comp == 0)
  229739. return NSMakeRect (0, 0, 0, 0);
  229740. const Rectangle<int> bounds (comp->getScreenBounds());
  229741. return NSMakeRect (bounds.getX(),
  229742. [[[NSScreen screens] objectAtIndex: 0] frame].size.height - bounds.getY(),
  229743. bounds.getWidth(),
  229744. bounds.getHeight());
  229745. }
  229746. - (unsigned int) characterIndexForPoint: (NSPoint) thePoint
  229747. {
  229748. (void) thePoint;
  229749. return NSNotFound;
  229750. }
  229751. - (NSArray*) validAttributesForMarkedText
  229752. {
  229753. return [NSArray array];
  229754. }
  229755. - (void) flagsChanged: (NSEvent*) ev
  229756. {
  229757. if (owner != 0)
  229758. owner->redirectModKeyChange (ev);
  229759. }
  229760. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  229761. - (BOOL) performKeyEquivalent: (NSEvent*) ev
  229762. {
  229763. if (owner != 0 && owner->redirectPerformKeyEquivalent (ev))
  229764. return true;
  229765. return [super performKeyEquivalent: ev];
  229766. }
  229767. #endif
  229768. - (BOOL) becomeFirstResponder
  229769. {
  229770. if (owner != 0)
  229771. owner->viewFocusGain();
  229772. return true;
  229773. }
  229774. - (BOOL) resignFirstResponder
  229775. {
  229776. if (owner != 0)
  229777. owner->viewFocusLoss();
  229778. return true;
  229779. }
  229780. - (BOOL) acceptsFirstResponder
  229781. {
  229782. return owner != 0 && owner->canBecomeKeyWindow();
  229783. }
  229784. - (NSArray*) getSupportedDragTypes
  229785. {
  229786. return [NSArray arrayWithObjects: NSFilenamesPboardType, /*NSFilesPromisePboardType, NSStringPboardType,*/ nil];
  229787. }
  229788. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender
  229789. {
  229790. return owner != 0 && owner->sendDragCallback (type, sender);
  229791. }
  229792. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
  229793. {
  229794. if ([self sendDragCallback: 0 sender: sender])
  229795. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  229796. else
  229797. return NSDragOperationNone;
  229798. }
  229799. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender
  229800. {
  229801. if ([self sendDragCallback: 0 sender: sender])
  229802. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  229803. else
  229804. return NSDragOperationNone;
  229805. }
  229806. - (void) draggingEnded: (id <NSDraggingInfo>) sender
  229807. {
  229808. [self sendDragCallback: 1 sender: sender];
  229809. }
  229810. - (void) draggingExited: (id <NSDraggingInfo>) sender
  229811. {
  229812. [self sendDragCallback: 1 sender: sender];
  229813. }
  229814. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender
  229815. {
  229816. (void) sender;
  229817. return YES;
  229818. }
  229819. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender
  229820. {
  229821. return [self sendDragCallback: 2 sender: sender];
  229822. }
  229823. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender
  229824. {
  229825. (void) sender;
  229826. }
  229827. @end
  229828. @implementation JuceNSWindow
  229829. - (void) setOwner: (NSViewComponentPeer*) owner_
  229830. {
  229831. owner = owner_;
  229832. isZooming = false;
  229833. }
  229834. - (BOOL) canBecomeKeyWindow
  229835. {
  229836. return owner != 0 && owner->canBecomeKeyWindow();
  229837. }
  229838. - (void) becomeKeyWindow
  229839. {
  229840. [super becomeKeyWindow];
  229841. if (owner != 0)
  229842. owner->grabFocus();
  229843. }
  229844. - (BOOL) windowShouldClose: (id) window
  229845. {
  229846. (void) window;
  229847. return owner == 0 || owner->windowShouldClose();
  229848. }
  229849. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen
  229850. {
  229851. (void) screen;
  229852. if (owner != 0)
  229853. frameRect = owner->constrainRect (frameRect);
  229854. return frameRect;
  229855. }
  229856. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize
  229857. {
  229858. (void) window;
  229859. if (isZooming)
  229860. return proposedFrameSize;
  229861. NSRect frameRect = [self frame];
  229862. frameRect.origin.y -= proposedFrameSize.height - frameRect.size.height;
  229863. frameRect.size = proposedFrameSize;
  229864. if (owner != 0)
  229865. frameRect = owner->constrainRect (frameRect);
  229866. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  229867. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  229868. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  229869. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  229870. return frameRect.size;
  229871. }
  229872. - (void) zoom: (id) sender
  229873. {
  229874. isZooming = true;
  229875. [super zoom: sender];
  229876. isZooming = false;
  229877. }
  229878. - (void) windowWillMove: (NSNotification*) notification
  229879. {
  229880. (void) notification;
  229881. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  229882. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  229883. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  229884. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  229885. }
  229886. @end
  229887. BEGIN_JUCE_NAMESPACE
  229888. ModifierKeys NSViewComponentPeer::currentModifiers;
  229889. ComponentPeer* NSViewComponentPeer::currentlyFocusedPeer = 0;
  229890. Array<int> NSViewComponentPeer::keysCurrentlyDown;
  229891. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  229892. {
  229893. if (NSViewComponentPeer::keysCurrentlyDown.contains (keyCode))
  229894. return true;
  229895. if (keyCode >= 'A' && keyCode <= 'Z'
  229896. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toLowerCase ((juce_wchar) keyCode)))
  229897. return true;
  229898. if (keyCode >= 'a' && keyCode <= 'z'
  229899. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode)))
  229900. return true;
  229901. return false;
  229902. }
  229903. void NSViewComponentPeer::updateModifiers (NSEvent* e)
  229904. {
  229905. int m = 0;
  229906. if (([e modifierFlags] & NSShiftKeyMask) != 0) m |= ModifierKeys::shiftModifier;
  229907. if (([e modifierFlags] & NSControlKeyMask) != 0) m |= ModifierKeys::ctrlModifier;
  229908. if (([e modifierFlags] & NSAlternateKeyMask) != 0) m |= ModifierKeys::altModifier;
  229909. if (([e modifierFlags] & NSCommandKeyMask) != 0) m |= ModifierKeys::commandModifier;
  229910. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (m);
  229911. }
  229912. void NSViewComponentPeer::updateKeysDown (NSEvent* ev, bool isKeyDown)
  229913. {
  229914. updateModifiers (ev);
  229915. int keyCode = getKeyCodeFromEvent (ev);
  229916. if (keyCode != 0)
  229917. {
  229918. if (isKeyDown)
  229919. keysCurrentlyDown.addIfNotAlreadyThere (keyCode);
  229920. else
  229921. keysCurrentlyDown.removeValue (keyCode);
  229922. }
  229923. }
  229924. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  229925. {
  229926. return NSViewComponentPeer::currentModifiers;
  229927. }
  229928. void ModifierKeys::updateCurrentModifiers() throw()
  229929. {
  229930. currentModifiers = NSViewComponentPeer::currentModifiers;
  229931. }
  229932. NSViewComponentPeer::NSViewComponentPeer (Component* const component_,
  229933. const int windowStyleFlags,
  229934. NSView* viewToAttachTo)
  229935. : ComponentPeer (component_, windowStyleFlags),
  229936. window (0),
  229937. view (0),
  229938. isSharedWindow (viewToAttachTo != 0),
  229939. fullScreen (false),
  229940. insideDrawRect (false),
  229941. #if USE_COREGRAPHICS_RENDERING
  229942. usingCoreGraphics (true),
  229943. #else
  229944. usingCoreGraphics (false),
  229945. #endif
  229946. recursiveToFrontCall (false)
  229947. {
  229948. NSRect r;
  229949. r.origin.x = 0;
  229950. r.origin.y = 0;
  229951. r.size.width = (float) component->getWidth();
  229952. r.size.height = (float) component->getHeight();
  229953. view = [[JuceNSView alloc] initWithOwner: this withFrame: r];
  229954. [view setPostsFrameChangedNotifications: YES];
  229955. if (isSharedWindow)
  229956. {
  229957. window = [viewToAttachTo window];
  229958. [viewToAttachTo addSubview: view];
  229959. setVisible (component->isVisible());
  229960. }
  229961. else
  229962. {
  229963. r.origin.x = (float) component->getX();
  229964. r.origin.y = (float) component->getY();
  229965. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  229966. unsigned int style = 0;
  229967. if ((windowStyleFlags & windowHasTitleBar) == 0)
  229968. style = NSBorderlessWindowMask;
  229969. else
  229970. style = NSTitledWindowMask;
  229971. if ((windowStyleFlags & windowHasMinimiseButton) != 0)
  229972. style |= NSMiniaturizableWindowMask;
  229973. if ((windowStyleFlags & windowHasCloseButton) != 0)
  229974. style |= NSClosableWindowMask;
  229975. if ((windowStyleFlags & windowIsResizable) != 0)
  229976. style |= NSResizableWindowMask;
  229977. window = [[JuceNSWindow alloc] initWithContentRect: r
  229978. styleMask: style
  229979. backing: NSBackingStoreBuffered
  229980. defer: YES];
  229981. [((JuceNSWindow*) window) setOwner: this];
  229982. [window orderOut: nil];
  229983. [window setDelegate: (JuceNSWindow*) window];
  229984. [window setOpaque: component->isOpaque()];
  229985. [window setHasShadow: ((windowStyleFlags & windowHasDropShadow) != 0)];
  229986. if (component->isAlwaysOnTop())
  229987. [window setLevel: NSFloatingWindowLevel];
  229988. [window setContentView: view];
  229989. [window setAutodisplay: YES];
  229990. [window setAcceptsMouseMovedEvents: YES];
  229991. // We'll both retain and also release this on closing because plugin hosts can unexpectedly
  229992. // close the window for us, and also tend to get cause trouble if setReleasedWhenClosed is NO.
  229993. [window setReleasedWhenClosed: YES];
  229994. [window retain];
  229995. [window setExcludedFromWindowsMenu: (windowStyleFlags & windowIsTemporary) != 0];
  229996. [window setIgnoresMouseEvents: (windowStyleFlags & windowIgnoresMouseClicks) != 0];
  229997. }
  229998. setTitle (component->getName());
  229999. }
  230000. NSViewComponentPeer::~NSViewComponentPeer()
  230001. {
  230002. view->owner = 0;
  230003. [view removeFromSuperview];
  230004. [view release];
  230005. if (! isSharedWindow)
  230006. {
  230007. [((JuceNSWindow*) window) setOwner: 0];
  230008. [window close];
  230009. [window release];
  230010. }
  230011. }
  230012. void* NSViewComponentPeer::getNativeHandle() const
  230013. {
  230014. return view;
  230015. }
  230016. void NSViewComponentPeer::setVisible (bool shouldBeVisible)
  230017. {
  230018. if (isSharedWindow)
  230019. {
  230020. [view setHidden: ! shouldBeVisible];
  230021. }
  230022. else
  230023. {
  230024. if (shouldBeVisible)
  230025. {
  230026. [window orderFront: nil];
  230027. handleBroughtToFront();
  230028. }
  230029. else
  230030. {
  230031. [window orderOut: nil];
  230032. }
  230033. }
  230034. }
  230035. void NSViewComponentPeer::setTitle (const String& title)
  230036. {
  230037. const ScopedAutoReleasePool pool;
  230038. if (! isSharedWindow)
  230039. [window setTitle: juceStringToNS (title)];
  230040. }
  230041. void NSViewComponentPeer::setPosition (int x, int y)
  230042. {
  230043. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  230044. }
  230045. void NSViewComponentPeer::setSize (int w, int h)
  230046. {
  230047. setBounds (component->getX(), component->getY(), w, h, false);
  230048. }
  230049. void NSViewComponentPeer::setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  230050. {
  230051. fullScreen = isNowFullScreen;
  230052. w = jmax (0, w);
  230053. h = jmax (0, h);
  230054. NSRect r;
  230055. r.origin.x = (float) x;
  230056. r.origin.y = (float) y;
  230057. r.size.width = (float) w;
  230058. r.size.height = (float) h;
  230059. if (isSharedWindow)
  230060. {
  230061. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  230062. if ([view frame].size.width != r.size.width
  230063. || [view frame].size.height != r.size.height)
  230064. [view setNeedsDisplay: true];
  230065. [view setFrame: r];
  230066. }
  230067. else
  230068. {
  230069. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  230070. [window setFrame: [window frameRectForContentRect: r]
  230071. display: true];
  230072. }
  230073. }
  230074. const Rectangle<int> NSViewComponentPeer::getBounds (const bool global) const
  230075. {
  230076. NSRect r = [view frame];
  230077. if (global && [view window] != 0)
  230078. {
  230079. r = [view convertRect: r toView: nil];
  230080. NSRect wr = [[view window] frame];
  230081. r.origin.x += wr.origin.x;
  230082. r.origin.y += wr.origin.y;
  230083. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  230084. }
  230085. else
  230086. {
  230087. r.origin.y = [[view superview] frame].size.height - r.origin.y - r.size.height;
  230088. }
  230089. return Rectangle<int> ((int) r.origin.x, (int) r.origin.y, (int) r.size.width, (int) r.size.height);
  230090. }
  230091. const Rectangle<int> NSViewComponentPeer::getBounds() const
  230092. {
  230093. return getBounds (! isSharedWindow);
  230094. }
  230095. const Point<int> NSViewComponentPeer::getScreenPosition() const
  230096. {
  230097. return getBounds (true).getPosition();
  230098. }
  230099. const Point<int> NSViewComponentPeer::relativePositionToGlobal (const Point<int>& relativePosition)
  230100. {
  230101. return relativePosition + getScreenPosition();
  230102. }
  230103. const Point<int> NSViewComponentPeer::globalPositionToRelative (const Point<int>& screenPosition)
  230104. {
  230105. return screenPosition - getScreenPosition();
  230106. }
  230107. NSRect NSViewComponentPeer::constrainRect (NSRect r)
  230108. {
  230109. if (constrainer != 0)
  230110. {
  230111. NSRect current = [window frame];
  230112. current.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - current.origin.y - current.size.height;
  230113. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  230114. Rectangle<int> pos ((int) r.origin.x, (int) r.origin.y,
  230115. (int) r.size.width, (int) r.size.height);
  230116. Rectangle<int> original ((int) current.origin.x, (int) current.origin.y,
  230117. (int) current.size.width, (int) current.size.height);
  230118. constrainer->checkBounds (pos, original,
  230119. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  230120. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  230121. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  230122. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  230123. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  230124. r.origin.x = pos.getX();
  230125. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.size.height - pos.getY();
  230126. r.size.width = pos.getWidth();
  230127. r.size.height = pos.getHeight();
  230128. }
  230129. return r;
  230130. }
  230131. void NSViewComponentPeer::setMinimised (bool shouldBeMinimised)
  230132. {
  230133. if (! isSharedWindow)
  230134. {
  230135. if (shouldBeMinimised)
  230136. [window miniaturize: nil];
  230137. else
  230138. [window deminiaturize: nil];
  230139. }
  230140. }
  230141. bool NSViewComponentPeer::isMinimised() const
  230142. {
  230143. return window != 0 && [window isMiniaturized];
  230144. }
  230145. void NSViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  230146. {
  230147. if (! isSharedWindow)
  230148. {
  230149. Rectangle<int> r (lastNonFullscreenBounds);
  230150. setMinimised (false);
  230151. if (fullScreen != shouldBeFullScreen)
  230152. {
  230153. if (shouldBeFullScreen && (getStyleFlags() & windowHasTitleBar) != 0)
  230154. {
  230155. fullScreen = true;
  230156. [window performZoom: nil];
  230157. }
  230158. else
  230159. {
  230160. if (shouldBeFullScreen)
  230161. r = Desktop::getInstance().getMainMonitorArea();
  230162. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  230163. if (r != getComponent()->getBounds() && ! r.isEmpty())
  230164. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  230165. }
  230166. }
  230167. }
  230168. }
  230169. bool NSViewComponentPeer::isFullScreen() const
  230170. {
  230171. return fullScreen;
  230172. }
  230173. bool NSViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  230174. {
  230175. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  230176. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  230177. return false;
  230178. NSPoint p;
  230179. p.x = (float) position.getX();
  230180. p.y = (float) position.getY();
  230181. NSView* v = [view hitTest: p];
  230182. if (trueIfInAChildWindow)
  230183. return v != nil;
  230184. return v == view;
  230185. }
  230186. const BorderSize NSViewComponentPeer::getFrameSize() const
  230187. {
  230188. BorderSize b;
  230189. if (! isSharedWindow)
  230190. {
  230191. NSRect v = [view convertRect: [view frame] toView: nil];
  230192. NSRect w = [window frame];
  230193. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  230194. b.setBottom ((int) v.origin.y);
  230195. b.setLeft ((int) v.origin.x);
  230196. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  230197. }
  230198. return b;
  230199. }
  230200. bool NSViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  230201. {
  230202. if (! isSharedWindow)
  230203. {
  230204. [window setLevel: alwaysOnTop ? NSFloatingWindowLevel
  230205. : NSNormalWindowLevel];
  230206. }
  230207. return true;
  230208. }
  230209. void NSViewComponentPeer::toFront (bool makeActiveWindow)
  230210. {
  230211. if (isSharedWindow)
  230212. {
  230213. [[view superview] addSubview: view
  230214. positioned: NSWindowAbove
  230215. relativeTo: nil];
  230216. }
  230217. if (window != 0 && component->isVisible())
  230218. {
  230219. if (makeActiveWindow)
  230220. [window makeKeyAndOrderFront: nil];
  230221. else
  230222. [window orderFront: nil];
  230223. if (! recursiveToFrontCall)
  230224. {
  230225. recursiveToFrontCall = true;
  230226. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  230227. handleBroughtToFront();
  230228. recursiveToFrontCall = false;
  230229. }
  230230. }
  230231. }
  230232. void NSViewComponentPeer::toBehind (ComponentPeer* other)
  230233. {
  230234. NSViewComponentPeer* const otherPeer = dynamic_cast <NSViewComponentPeer*> (other);
  230235. jassert (otherPeer != 0); // wrong type of window?
  230236. if (otherPeer != 0)
  230237. {
  230238. if (isSharedWindow)
  230239. {
  230240. [[view superview] addSubview: view
  230241. positioned: NSWindowBelow
  230242. relativeTo: otherPeer->view];
  230243. }
  230244. else
  230245. {
  230246. [window orderWindow: NSWindowBelow
  230247. relativeTo: otherPeer->window != 0 ? [otherPeer->window windowNumber]
  230248. : nil ];
  230249. }
  230250. }
  230251. }
  230252. void NSViewComponentPeer::setIcon (const Image& /*newIcon*/)
  230253. {
  230254. // to do..
  230255. }
  230256. void NSViewComponentPeer::viewFocusGain()
  230257. {
  230258. if (currentlyFocusedPeer != this)
  230259. {
  230260. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  230261. currentlyFocusedPeer->handleFocusLoss();
  230262. currentlyFocusedPeer = this;
  230263. handleFocusGain();
  230264. }
  230265. }
  230266. void NSViewComponentPeer::viewFocusLoss()
  230267. {
  230268. if (currentlyFocusedPeer == this)
  230269. {
  230270. currentlyFocusedPeer = 0;
  230271. handleFocusLoss();
  230272. }
  230273. }
  230274. void juce_HandleProcessFocusChange()
  230275. {
  230276. NSViewComponentPeer::keysCurrentlyDown.clear();
  230277. if (NSViewComponentPeer::isValidPeer (NSViewComponentPeer::currentlyFocusedPeer))
  230278. {
  230279. if (Process::isForegroundProcess())
  230280. {
  230281. NSViewComponentPeer::currentlyFocusedPeer->handleFocusGain();
  230282. ComponentPeer::bringModalComponentToFront();
  230283. }
  230284. else
  230285. {
  230286. NSViewComponentPeer::currentlyFocusedPeer->handleFocusLoss();
  230287. // turn kiosk mode off if we lose focus..
  230288. Desktop::getInstance().setKioskModeComponent (0);
  230289. }
  230290. }
  230291. }
  230292. bool NSViewComponentPeer::isFocused() const
  230293. {
  230294. return isSharedWindow ? this == currentlyFocusedPeer
  230295. : (window != 0 && [window isKeyWindow]);
  230296. }
  230297. void NSViewComponentPeer::grabFocus()
  230298. {
  230299. if (window != 0)
  230300. {
  230301. [window makeKeyWindow];
  230302. [window makeFirstResponder: view];
  230303. viewFocusGain();
  230304. }
  230305. }
  230306. void NSViewComponentPeer::textInputRequired (const Point<int>&)
  230307. {
  230308. }
  230309. bool NSViewComponentPeer::handleKeyEvent (NSEvent* ev, bool isKeyDown)
  230310. {
  230311. String unicode (nsStringToJuce ([ev characters]));
  230312. String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  230313. int keyCode = getKeyCodeFromEvent (ev);
  230314. //DBG ("unicode: " + unicode + " " + String::toHexString ((int) unicode[0]));
  230315. //DBG ("unmodified: " + unmodified + " " + String::toHexString ((int) unmodified[0]));
  230316. if (unicode.isNotEmpty() || keyCode != 0)
  230317. {
  230318. if (isKeyDown)
  230319. {
  230320. bool used = false;
  230321. while (unicode.length() > 0)
  230322. {
  230323. juce_wchar textCharacter = unicode[0];
  230324. unicode = unicode.substring (1);
  230325. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  230326. textCharacter = 0;
  230327. used = handleKeyUpOrDown (true) || used;
  230328. used = handleKeyPress (keyCode, textCharacter) || used;
  230329. }
  230330. return used;
  230331. }
  230332. else
  230333. {
  230334. if (handleKeyUpOrDown (false))
  230335. return true;
  230336. }
  230337. }
  230338. return false;
  230339. }
  230340. bool NSViewComponentPeer::redirectKeyDown (NSEvent* ev)
  230341. {
  230342. updateKeysDown (ev, true);
  230343. bool used = handleKeyEvent (ev, true);
  230344. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  230345. {
  230346. // for command keys, the key-up event is thrown away, so simulate one..
  230347. updateKeysDown (ev, false);
  230348. used = (isValidPeer (this) && handleKeyEvent (ev, false)) || used;
  230349. }
  230350. // (If we're running modally, don't allow unused keystrokes to be passed
  230351. // along to other blocked views..)
  230352. if (Component::getCurrentlyModalComponent() != 0)
  230353. used = true;
  230354. return used;
  230355. }
  230356. bool NSViewComponentPeer::redirectKeyUp (NSEvent* ev)
  230357. {
  230358. updateKeysDown (ev, false);
  230359. return handleKeyEvent (ev, false)
  230360. || Component::getCurrentlyModalComponent() != 0;
  230361. }
  230362. void NSViewComponentPeer::redirectModKeyChange (NSEvent* ev)
  230363. {
  230364. keysCurrentlyDown.clear();
  230365. handleKeyUpOrDown (true);
  230366. updateModifiers (ev);
  230367. handleModifierKeysChange();
  230368. }
  230369. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230370. bool NSViewComponentPeer::redirectPerformKeyEquivalent (NSEvent* ev)
  230371. {
  230372. if ([ev type] == NSKeyDown)
  230373. return redirectKeyDown (ev);
  230374. else if ([ev type] == NSKeyUp)
  230375. return redirectKeyUp (ev);
  230376. return false;
  230377. }
  230378. #endif
  230379. void NSViewComponentPeer::sendMouseEvent (NSEvent* ev)
  230380. {
  230381. updateModifiers (ev);
  230382. handleMouseEvent (0, getMousePos (ev, view), currentModifiers, getMouseTime (ev));
  230383. }
  230384. void NSViewComponentPeer::redirectMouseDown (NSEvent* ev)
  230385. {
  230386. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  230387. sendMouseEvent (ev);
  230388. }
  230389. void NSViewComponentPeer::redirectMouseUp (NSEvent* ev)
  230390. {
  230391. currentModifiers = currentModifiers.withoutFlags (getModifierForButtonNumber ([ev buttonNumber]));
  230392. sendMouseEvent (ev);
  230393. showArrowCursorIfNeeded();
  230394. }
  230395. void NSViewComponentPeer::redirectMouseDrag (NSEvent* ev)
  230396. {
  230397. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  230398. sendMouseEvent (ev);
  230399. }
  230400. void NSViewComponentPeer::redirectMouseMove (NSEvent* ev)
  230401. {
  230402. currentModifiers = currentModifiers.withoutMouseButtons();
  230403. sendMouseEvent (ev);
  230404. showArrowCursorIfNeeded();
  230405. }
  230406. void NSViewComponentPeer::redirectMouseEnter (NSEvent* ev)
  230407. {
  230408. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  230409. currentModifiers = currentModifiers.withoutMouseButtons();
  230410. sendMouseEvent (ev);
  230411. }
  230412. void NSViewComponentPeer::redirectMouseExit (NSEvent* ev)
  230413. {
  230414. currentModifiers = currentModifiers.withoutMouseButtons();
  230415. sendMouseEvent (ev);
  230416. }
  230417. void NSViewComponentPeer::redirectMouseWheel (NSEvent* ev)
  230418. {
  230419. updateModifiers (ev);
  230420. float x = 0, y = 0;
  230421. @try
  230422. {
  230423. x = [ev deviceDeltaX] * 0.5f;
  230424. y = [ev deviceDeltaY] * 0.5f;
  230425. }
  230426. @catch (...)
  230427. {
  230428. x = [ev deltaX] * 10.0f;
  230429. y = [ev deltaY] * 10.0f;
  230430. }
  230431. handleMouseWheel (0, getMousePos (ev, view), getMouseTime (ev), x, y);
  230432. }
  230433. void NSViewComponentPeer::showArrowCursorIfNeeded()
  230434. {
  230435. MouseInputSource& mouse = Desktop::getInstance().getMainMouseSource();
  230436. if (mouse.getComponentUnderMouse() == 0
  230437. && Desktop::getInstance().findComponentAt (mouse.getScreenPosition()) == 0)
  230438. {
  230439. [[NSCursor arrowCursor] set];
  230440. }
  230441. }
  230442. BOOL NSViewComponentPeer::sendDragCallback (int type, id <NSDraggingInfo> sender)
  230443. {
  230444. NSString* bestType
  230445. = [[sender draggingPasteboard] availableTypeFromArray: [view getSupportedDragTypes]];
  230446. if (bestType == nil)
  230447. return false;
  230448. NSPoint p = [view convertPoint: [sender draggingLocation] fromView: nil];
  230449. const Point<int> pos ((int) p.x, (int) ([view frame].size.height - p.y));
  230450. StringArray files;
  230451. id list = [[sender draggingPasteboard] propertyListForType: bestType];
  230452. if (list == nil)
  230453. return false;
  230454. if ([list isKindOfClass: [NSArray class]])
  230455. {
  230456. NSArray* items = (NSArray*) list;
  230457. for (unsigned int i = 0; i < [items count]; ++i)
  230458. files.add (nsStringToJuce ((NSString*) [items objectAtIndex: i]));
  230459. }
  230460. if (files.size() == 0)
  230461. return false;
  230462. if (type == 0)
  230463. handleFileDragMove (files, pos);
  230464. else if (type == 1)
  230465. handleFileDragExit (files);
  230466. else if (type == 2)
  230467. handleFileDragDrop (files, pos);
  230468. return true;
  230469. }
  230470. bool NSViewComponentPeer::isOpaque()
  230471. {
  230472. return component == 0 || component->isOpaque();
  230473. }
  230474. void NSViewComponentPeer::drawRect (NSRect r)
  230475. {
  230476. if (r.size.width < 1.0f || r.size.height < 1.0f)
  230477. return;
  230478. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  230479. if (! component->isOpaque())
  230480. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  230481. #if USE_COREGRAPHICS_RENDERING
  230482. if (usingCoreGraphics)
  230483. {
  230484. CoreGraphicsContext context (cg, (float) [view frame].size.height);
  230485. insideDrawRect = true;
  230486. handlePaint (context);
  230487. insideDrawRect = false;
  230488. }
  230489. else
  230490. #endif
  230491. {
  230492. Image temp (getComponent()->isOpaque() ? Image::RGB : Image::ARGB,
  230493. (int) (r.size.width + 0.5f),
  230494. (int) (r.size.height + 0.5f),
  230495. ! getComponent()->isOpaque());
  230496. const int xOffset = -roundToInt (r.origin.x);
  230497. const int yOffset = -roundToInt ([view frame].size.height - (r.origin.y + r.size.height));
  230498. const NSRect* rects = 0;
  230499. NSInteger numRects = 0;
  230500. [view getRectsBeingDrawn: &rects count: &numRects];
  230501. const Rectangle<int> clipBounds (temp.getBounds());
  230502. RectangleList clip;
  230503. for (int i = 0; i < numRects; ++i)
  230504. {
  230505. clip.addWithoutMerging (clipBounds.getIntersection (Rectangle<int> (roundToInt (rects[i].origin.x) + xOffset,
  230506. roundToInt ([view frame].size.height - (rects[i].origin.y + rects[i].size.height)) + yOffset,
  230507. roundToInt (rects[i].size.width),
  230508. roundToInt (rects[i].size.height))));
  230509. }
  230510. if (! clip.isEmpty())
  230511. {
  230512. LowLevelGraphicsSoftwareRenderer context (temp, xOffset, yOffset, clip);
  230513. insideDrawRect = true;
  230514. handlePaint (context);
  230515. insideDrawRect = false;
  230516. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  230517. CGImageRef image = CoreGraphicsImage::createImage (temp, false, colourSpace);
  230518. CGColorSpaceRelease (colourSpace);
  230519. CGContextDrawImage (cg, CGRectMake (r.origin.x, r.origin.y, temp.getWidth(), temp.getHeight()), image);
  230520. CGImageRelease (image);
  230521. }
  230522. }
  230523. }
  230524. const StringArray NSViewComponentPeer::getAvailableRenderingEngines() throw()
  230525. {
  230526. StringArray s;
  230527. s.add ("Software Renderer");
  230528. #if USE_COREGRAPHICS_RENDERING
  230529. s.add ("CoreGraphics Renderer");
  230530. #endif
  230531. return s;
  230532. }
  230533. int NSViewComponentPeer::getCurrentRenderingEngine() throw()
  230534. {
  230535. return usingCoreGraphics ? 1 : 0;
  230536. }
  230537. void NSViewComponentPeer::setCurrentRenderingEngine (int index) throw()
  230538. {
  230539. #if USE_COREGRAPHICS_RENDERING
  230540. if (usingCoreGraphics != (index > 0))
  230541. {
  230542. usingCoreGraphics = index > 0;
  230543. [view setNeedsDisplay: true];
  230544. }
  230545. #endif
  230546. }
  230547. bool NSViewComponentPeer::canBecomeKeyWindow()
  230548. {
  230549. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  230550. }
  230551. bool NSViewComponentPeer::windowShouldClose()
  230552. {
  230553. if (! isValidPeer (this))
  230554. return YES;
  230555. handleUserClosingWindow();
  230556. return NO;
  230557. }
  230558. void NSViewComponentPeer::redirectMovedOrResized()
  230559. {
  230560. handleMovedOrResized();
  230561. }
  230562. void NSViewComponentPeer::viewMovedToWindow()
  230563. {
  230564. if (isSharedWindow)
  230565. window = [view window];
  230566. }
  230567. void Desktop::createMouseInputSources()
  230568. {
  230569. mouseSources.add (new MouseInputSource (0, true));
  230570. }
  230571. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  230572. {
  230573. // Very annoyingly, this function has to use the old SetSystemUIMode function,
  230574. // which is in Carbon.framework. But, because there's no Cocoa equivalent, it
  230575. // is apparently still available in 64-bit apps..
  230576. if (enableOrDisable)
  230577. {
  230578. SetSystemUIMode (kUIModeAllSuppressed, allowMenusAndBars ? kUIOptionAutoShowMenuBar : 0);
  230579. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  230580. }
  230581. else
  230582. {
  230583. SetSystemUIMode (kUIModeNormal, 0);
  230584. }
  230585. }
  230586. class AsyncRepaintMessage : public CallbackMessage
  230587. {
  230588. public:
  230589. NSViewComponentPeer* const peer;
  230590. const Rectangle<int> rect;
  230591. AsyncRepaintMessage (NSViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  230592. : peer (peer_), rect (rect_)
  230593. {
  230594. }
  230595. void messageCallback()
  230596. {
  230597. if (ComponentPeer::isValidPeer (peer))
  230598. peer->repaint (rect);
  230599. }
  230600. };
  230601. void NSViewComponentPeer::repaint (const Rectangle<int>& area)
  230602. {
  230603. if (insideDrawRect)
  230604. {
  230605. (new AsyncRepaintMessage (this, area))->post();
  230606. }
  230607. else
  230608. {
  230609. [view setNeedsDisplayInRect: NSMakeRect ((float) area.getX(), [view frame].size.height - (float) area.getBottom(),
  230610. (float) area.getWidth(), (float) area.getHeight())];
  230611. }
  230612. }
  230613. void NSViewComponentPeer::performAnyPendingRepaintsNow()
  230614. {
  230615. [view displayIfNeeded];
  230616. }
  230617. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  230618. {
  230619. return new NSViewComponentPeer (this, styleFlags, (NSView*) windowToAttachTo);
  230620. }
  230621. const Image juce_createIconForFile (const File& file)
  230622. {
  230623. const ScopedAutoReleasePool pool;
  230624. NSImage* image = [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (file.getFullPathName())];
  230625. CoreGraphicsImage* result = new CoreGraphicsImage (Image::ARGB, (int) [image size].width, (int) [image size].height, true);
  230626. [NSGraphicsContext saveGraphicsState];
  230627. [NSGraphicsContext setCurrentContext: [NSGraphicsContext graphicsContextWithGraphicsPort: result->context flipped: false]];
  230628. [image drawAtPoint: NSMakePoint (0, 0)
  230629. fromRect: NSMakeRect (0, 0, [image size].width, [image size].height)
  230630. operation: NSCompositeSourceOver fraction: 1.0f];
  230631. [[NSGraphicsContext currentContext] flushGraphics];
  230632. [NSGraphicsContext restoreGraphicsState];
  230633. return Image (result);
  230634. }
  230635. const int KeyPress::spaceKey = ' ';
  230636. const int KeyPress::returnKey = 0x0d;
  230637. const int KeyPress::escapeKey = 0x1b;
  230638. const int KeyPress::backspaceKey = 0x7f;
  230639. const int KeyPress::leftKey = NSLeftArrowFunctionKey;
  230640. const int KeyPress::rightKey = NSRightArrowFunctionKey;
  230641. const int KeyPress::upKey = NSUpArrowFunctionKey;
  230642. const int KeyPress::downKey = NSDownArrowFunctionKey;
  230643. const int KeyPress::pageUpKey = NSPageUpFunctionKey;
  230644. const int KeyPress::pageDownKey = NSPageDownFunctionKey;
  230645. const int KeyPress::endKey = NSEndFunctionKey;
  230646. const int KeyPress::homeKey = NSHomeFunctionKey;
  230647. const int KeyPress::deleteKey = NSDeleteFunctionKey;
  230648. const int KeyPress::insertKey = -1;
  230649. const int KeyPress::tabKey = 9;
  230650. const int KeyPress::F1Key = NSF1FunctionKey;
  230651. const int KeyPress::F2Key = NSF2FunctionKey;
  230652. const int KeyPress::F3Key = NSF3FunctionKey;
  230653. const int KeyPress::F4Key = NSF4FunctionKey;
  230654. const int KeyPress::F5Key = NSF5FunctionKey;
  230655. const int KeyPress::F6Key = NSF6FunctionKey;
  230656. const int KeyPress::F7Key = NSF7FunctionKey;
  230657. const int KeyPress::F8Key = NSF8FunctionKey;
  230658. const int KeyPress::F9Key = NSF9FunctionKey;
  230659. const int KeyPress::F10Key = NSF10FunctionKey;
  230660. const int KeyPress::F11Key = NSF1FunctionKey;
  230661. const int KeyPress::F12Key = NSF12FunctionKey;
  230662. const int KeyPress::F13Key = NSF13FunctionKey;
  230663. const int KeyPress::F14Key = NSF14FunctionKey;
  230664. const int KeyPress::F15Key = NSF15FunctionKey;
  230665. const int KeyPress::F16Key = NSF16FunctionKey;
  230666. const int KeyPress::numberPad0 = 0x30020;
  230667. const int KeyPress::numberPad1 = 0x30021;
  230668. const int KeyPress::numberPad2 = 0x30022;
  230669. const int KeyPress::numberPad3 = 0x30023;
  230670. const int KeyPress::numberPad4 = 0x30024;
  230671. const int KeyPress::numberPad5 = 0x30025;
  230672. const int KeyPress::numberPad6 = 0x30026;
  230673. const int KeyPress::numberPad7 = 0x30027;
  230674. const int KeyPress::numberPad8 = 0x30028;
  230675. const int KeyPress::numberPad9 = 0x30029;
  230676. const int KeyPress::numberPadAdd = 0x3002a;
  230677. const int KeyPress::numberPadSubtract = 0x3002b;
  230678. const int KeyPress::numberPadMultiply = 0x3002c;
  230679. const int KeyPress::numberPadDivide = 0x3002d;
  230680. const int KeyPress::numberPadSeparator = 0x3002e;
  230681. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  230682. const int KeyPress::numberPadEquals = 0x30030;
  230683. const int KeyPress::numberPadDelete = 0x30031;
  230684. const int KeyPress::playKey = 0x30000;
  230685. const int KeyPress::stopKey = 0x30001;
  230686. const int KeyPress::fastForwardKey = 0x30002;
  230687. const int KeyPress::rewindKey = 0x30003;
  230688. #endif
  230689. /*** End of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  230690. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  230691. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230692. // compiled on its own).
  230693. #if JUCE_INCLUDED_FILE
  230694. #if JUCE_MAC
  230695. namespace MouseCursorHelpers
  230696. {
  230697. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  230698. {
  230699. NSImage* im = CoreGraphicsImage::createNSImage (image);
  230700. NSCursor* c = [[NSCursor alloc] initWithImage: im
  230701. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  230702. [im release];
  230703. return c;
  230704. }
  230705. static void* fromWebKitFile (const char* filename, float hx, float hy)
  230706. {
  230707. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  230708. BufferedInputStream buf (&fileStream, 4096, false);
  230709. PNGImageFormat pngFormat;
  230710. Image im (pngFormat.decodeImage (buf));
  230711. if (im.isValid())
  230712. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  230713. jassertfalse;
  230714. return 0;
  230715. }
  230716. }
  230717. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  230718. {
  230719. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  230720. }
  230721. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  230722. {
  230723. const ScopedAutoReleasePool pool;
  230724. NSCursor* c = 0;
  230725. switch (type)
  230726. {
  230727. case NormalCursor: c = [NSCursor arrowCursor]; break;
  230728. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  230729. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  230730. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  230731. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  230732. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  230733. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  230734. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  230735. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  230736. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  230737. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  230738. case UpDownResizeCursor:
  230739. case TopEdgeResizeCursor:
  230740. case BottomEdgeResizeCursor:
  230741. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  230742. case TopLeftCornerResizeCursor:
  230743. case BottomRightCornerResizeCursor:
  230744. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  230745. case TopRightCornerResizeCursor:
  230746. case BottomLeftCornerResizeCursor:
  230747. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  230748. case UpDownLeftRightResizeCursor:
  230749. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  230750. default:
  230751. jassertfalse;
  230752. break;
  230753. }
  230754. [c retain];
  230755. return c;
  230756. }
  230757. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  230758. {
  230759. [((NSCursor*) cursorHandle) release];
  230760. }
  230761. void MouseCursor::showInAllWindows() const
  230762. {
  230763. showInWindow (0);
  230764. }
  230765. void MouseCursor::showInWindow (ComponentPeer*) const
  230766. {
  230767. [((NSCursor*) getHandle()) set];
  230768. }
  230769. #else
  230770. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  230771. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  230772. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  230773. void MouseCursor::showInAllWindows() const {}
  230774. void MouseCursor::showInWindow (ComponentPeer*) const {}
  230775. #endif
  230776. #endif
  230777. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  230778. /*** Start of inlined file: juce_mac_NSViewComponent.mm ***/
  230779. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230780. // compiled on its own).
  230781. #if JUCE_INCLUDED_FILE
  230782. class NSViewComponentInternal : public ComponentMovementWatcher
  230783. {
  230784. Component* const owner;
  230785. NSViewComponentPeer* currentPeer;
  230786. bool wasShowing;
  230787. public:
  230788. NSView* const view;
  230789. NSViewComponentInternal (NSView* const view_, Component* const owner_)
  230790. : ComponentMovementWatcher (owner_),
  230791. owner (owner_),
  230792. currentPeer (0),
  230793. wasShowing (false),
  230794. view (view_)
  230795. {
  230796. [view_ retain];
  230797. if (owner_->isShowing())
  230798. componentPeerChanged();
  230799. }
  230800. ~NSViewComponentInternal()
  230801. {
  230802. [view removeFromSuperview];
  230803. [view release];
  230804. }
  230805. void componentMovedOrResized (Component& comp, bool wasMoved, bool wasResized)
  230806. {
  230807. ComponentMovementWatcher::componentMovedOrResized (comp, wasMoved, wasResized);
  230808. // The ComponentMovementWatcher version of this method avoids calling
  230809. // us when the top-level comp is resized, but for an NSView we need to know this
  230810. // because with inverted co-ords, we need to update the position even if the
  230811. // top-left pos hasn't changed
  230812. if (comp.isOnDesktop() && wasResized)
  230813. componentMovedOrResized (wasMoved, wasResized);
  230814. }
  230815. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  230816. {
  230817. Component* const topComp = owner->getTopLevelComponent();
  230818. if (topComp->getPeer() != 0)
  230819. {
  230820. const Point<int> pos (owner->relativePositionToOtherComponent (topComp, Point<int>()));
  230821. NSRect r;
  230822. r.origin.x = (float) pos.getX();
  230823. r.origin.y = (float) pos.getY();
  230824. r.size.width = (float) owner->getWidth();
  230825. r.size.height = (float) owner->getHeight();
  230826. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  230827. [view setFrame: r];
  230828. }
  230829. }
  230830. void componentPeerChanged()
  230831. {
  230832. NSViewComponentPeer* const peer = dynamic_cast <NSViewComponentPeer*> (owner->getPeer());
  230833. if (currentPeer != peer)
  230834. {
  230835. [view removeFromSuperview];
  230836. currentPeer = peer;
  230837. if (peer != 0)
  230838. {
  230839. [peer->view addSubview: view];
  230840. componentMovedOrResized (false, false);
  230841. }
  230842. }
  230843. [view setHidden: ! owner->isShowing()];
  230844. }
  230845. void componentVisibilityChanged (Component&)
  230846. {
  230847. componentPeerChanged();
  230848. }
  230849. juce_UseDebuggingNewOperator
  230850. private:
  230851. NSViewComponentInternal (const NSViewComponentInternal&);
  230852. NSViewComponentInternal& operator= (const NSViewComponentInternal&);
  230853. };
  230854. NSViewComponent::NSViewComponent()
  230855. {
  230856. }
  230857. NSViewComponent::~NSViewComponent()
  230858. {
  230859. }
  230860. void NSViewComponent::setView (void* view)
  230861. {
  230862. if (view != getView())
  230863. {
  230864. if (view != 0)
  230865. info = new NSViewComponentInternal ((NSView*) view, this);
  230866. else
  230867. info = 0;
  230868. }
  230869. }
  230870. void* NSViewComponent::getView() const
  230871. {
  230872. return info == 0 ? 0 : info->view;
  230873. }
  230874. void NSViewComponent::paint (Graphics&)
  230875. {
  230876. }
  230877. #endif
  230878. /*** End of inlined file: juce_mac_NSViewComponent.mm ***/
  230879. /*** Start of inlined file: juce_mac_AppleRemote.mm ***/
  230880. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230881. // compiled on its own).
  230882. #if JUCE_INCLUDED_FILE
  230883. AppleRemoteDevice::AppleRemoteDevice()
  230884. : device (0),
  230885. queue (0),
  230886. remoteId (0)
  230887. {
  230888. }
  230889. AppleRemoteDevice::~AppleRemoteDevice()
  230890. {
  230891. stop();
  230892. }
  230893. static io_object_t getAppleRemoteDevice()
  230894. {
  230895. CFMutableDictionaryRef dict = IOServiceMatching ("AppleIRController");
  230896. io_iterator_t iter = 0;
  230897. io_object_t iod = 0;
  230898. if (IOServiceGetMatchingServices (kIOMasterPortDefault, dict, &iter) == kIOReturnSuccess
  230899. && iter != 0)
  230900. {
  230901. iod = IOIteratorNext (iter);
  230902. }
  230903. IOObjectRelease (iter);
  230904. return iod;
  230905. }
  230906. static bool createAppleRemoteInterface (io_object_t iod, void** device)
  230907. {
  230908. jassert (*device == 0);
  230909. io_name_t classname;
  230910. if (IOObjectGetClass (iod, classname) == kIOReturnSuccess)
  230911. {
  230912. IOCFPlugInInterface** cfPlugInInterface = 0;
  230913. SInt32 score = 0;
  230914. if (IOCreatePlugInInterfaceForService (iod,
  230915. kIOHIDDeviceUserClientTypeID,
  230916. kIOCFPlugInInterfaceID,
  230917. &cfPlugInInterface,
  230918. &score) == kIOReturnSuccess)
  230919. {
  230920. HRESULT hr = (*cfPlugInInterface)->QueryInterface (cfPlugInInterface,
  230921. CFUUIDGetUUIDBytes (kIOHIDDeviceInterfaceID),
  230922. device);
  230923. (void) hr;
  230924. (*cfPlugInInterface)->Release (cfPlugInInterface);
  230925. }
  230926. }
  230927. return *device != 0;
  230928. }
  230929. bool AppleRemoteDevice::start (const bool inExclusiveMode)
  230930. {
  230931. if (queue != 0)
  230932. return true;
  230933. stop();
  230934. bool result = false;
  230935. io_object_t iod = getAppleRemoteDevice();
  230936. if (iod != 0)
  230937. {
  230938. if (createAppleRemoteInterface (iod, &device) && open (inExclusiveMode))
  230939. result = true;
  230940. else
  230941. stop();
  230942. IOObjectRelease (iod);
  230943. }
  230944. return result;
  230945. }
  230946. void AppleRemoteDevice::stop()
  230947. {
  230948. if (queue != 0)
  230949. {
  230950. (*(IOHIDQueueInterface**) queue)->stop ((IOHIDQueueInterface**) queue);
  230951. (*(IOHIDQueueInterface**) queue)->dispose ((IOHIDQueueInterface**) queue);
  230952. (*(IOHIDQueueInterface**) queue)->Release ((IOHIDQueueInterface**) queue);
  230953. queue = 0;
  230954. }
  230955. if (device != 0)
  230956. {
  230957. (*(IOHIDDeviceInterface**) device)->close ((IOHIDDeviceInterface**) device);
  230958. (*(IOHIDDeviceInterface**) device)->Release ((IOHIDDeviceInterface**) device);
  230959. device = 0;
  230960. }
  230961. }
  230962. bool AppleRemoteDevice::isActive() const
  230963. {
  230964. return queue != 0;
  230965. }
  230966. static void appleRemoteQueueCallback (void* const target, const IOReturn result, void*, void*)
  230967. {
  230968. if (result == kIOReturnSuccess)
  230969. ((AppleRemoteDevice*) target)->handleCallbackInternal();
  230970. }
  230971. bool AppleRemoteDevice::open (const bool openInExclusiveMode)
  230972. {
  230973. Array <int> cookies;
  230974. CFArrayRef elements;
  230975. IOHIDDeviceInterface122** const device122 = (IOHIDDeviceInterface122**) device;
  230976. if ((*device122)->copyMatchingElements (device122, 0, &elements) != kIOReturnSuccess)
  230977. return false;
  230978. for (int i = 0; i < CFArrayGetCount (elements); ++i)
  230979. {
  230980. CFDictionaryRef element = (CFDictionaryRef) CFArrayGetValueAtIndex (elements, i);
  230981. // get the cookie
  230982. CFTypeRef object = CFDictionaryGetValue (element, CFSTR (kIOHIDElementCookieKey));
  230983. if (object == 0 || CFGetTypeID (object) != CFNumberGetTypeID())
  230984. continue;
  230985. long number;
  230986. if (! CFNumberGetValue ((CFNumberRef) object, kCFNumberLongType, &number))
  230987. continue;
  230988. cookies.add ((int) number);
  230989. }
  230990. CFRelease (elements);
  230991. if ((*(IOHIDDeviceInterface**) device)
  230992. ->open ((IOHIDDeviceInterface**) device,
  230993. openInExclusiveMode ? kIOHIDOptionsTypeSeizeDevice
  230994. : kIOHIDOptionsTypeNone) == KERN_SUCCESS)
  230995. {
  230996. queue = (*(IOHIDDeviceInterface**) device)->allocQueue ((IOHIDDeviceInterface**) device);
  230997. if (queue != 0)
  230998. {
  230999. (*(IOHIDQueueInterface**) queue)->create ((IOHIDQueueInterface**) queue, 0, 12);
  231000. for (int i = 0; i < cookies.size(); ++i)
  231001. {
  231002. IOHIDElementCookie cookie = (IOHIDElementCookie) cookies.getUnchecked(i);
  231003. (*(IOHIDQueueInterface**) queue)->addElement ((IOHIDQueueInterface**) queue, cookie, 0);
  231004. }
  231005. CFRunLoopSourceRef eventSource;
  231006. if ((*(IOHIDQueueInterface**) queue)
  231007. ->createAsyncEventSource ((IOHIDQueueInterface**) queue, &eventSource) == KERN_SUCCESS)
  231008. {
  231009. if ((*(IOHIDQueueInterface**) queue)->setEventCallout ((IOHIDQueueInterface**) queue,
  231010. appleRemoteQueueCallback, this, 0) == KERN_SUCCESS)
  231011. {
  231012. CFRunLoopAddSource (CFRunLoopGetCurrent(), eventSource, kCFRunLoopDefaultMode);
  231013. (*(IOHIDQueueInterface**) queue)->start ((IOHIDQueueInterface**) queue);
  231014. return true;
  231015. }
  231016. }
  231017. }
  231018. }
  231019. return false;
  231020. }
  231021. void AppleRemoteDevice::handleCallbackInternal()
  231022. {
  231023. int totalValues = 0;
  231024. AbsoluteTime nullTime = { 0, 0 };
  231025. char cookies [12];
  231026. int numCookies = 0;
  231027. while (numCookies < numElementsInArray (cookies))
  231028. {
  231029. IOHIDEventStruct e;
  231030. if ((*(IOHIDQueueInterface**) queue)->getNextEvent ((IOHIDQueueInterface**) queue, &e, nullTime, 0) != kIOReturnSuccess)
  231031. break;
  231032. if ((int) e.elementCookie == 19)
  231033. {
  231034. remoteId = e.value;
  231035. buttonPressed (switched, false);
  231036. }
  231037. else
  231038. {
  231039. totalValues += e.value;
  231040. cookies [numCookies++] = (char) (pointer_sized_int) e.elementCookie;
  231041. }
  231042. }
  231043. cookies [numCookies++] = 0;
  231044. //DBG (String::toHexString ((uint8*) cookies, numCookies, 1) + " " + String (totalValues));
  231045. static const char buttonPatterns[] =
  231046. {
  231047. 0x1f, 0x14, 0x12, 0x1f, 0x14, 0x12, 0,
  231048. 0x1f, 0x15, 0x12, 0x1f, 0x15, 0x12, 0,
  231049. 0x1f, 0x1d, 0x1c, 0x12, 0,
  231050. 0x1f, 0x1e, 0x1c, 0x12, 0,
  231051. 0x1f, 0x16, 0x12, 0x1f, 0x16, 0x12, 0,
  231052. 0x1f, 0x17, 0x12, 0x1f, 0x17, 0x12, 0,
  231053. 0x1f, 0x12, 0x04, 0x02, 0,
  231054. 0x1f, 0x12, 0x03, 0x02, 0,
  231055. 0x1f, 0x12, 0x1f, 0x12, 0,
  231056. 0x23, 0x1f, 0x12, 0x23, 0x1f, 0x12, 0,
  231057. 19, 0
  231058. };
  231059. int buttonNum = (int) menuButton;
  231060. int i = 0;
  231061. while (i < numElementsInArray (buttonPatterns))
  231062. {
  231063. if (strcmp (cookies, buttonPatterns + i) == 0)
  231064. {
  231065. buttonPressed ((ButtonType) buttonNum, totalValues > 0);
  231066. break;
  231067. }
  231068. i += (int) strlen (buttonPatterns + i) + 1;
  231069. ++buttonNum;
  231070. }
  231071. }
  231072. #endif
  231073. /*** End of inlined file: juce_mac_AppleRemote.mm ***/
  231074. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  231075. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231076. // compiled on its own).
  231077. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  231078. #if JUCE_MAC
  231079. END_JUCE_NAMESPACE
  231080. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  231081. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  231082. {
  231083. CriticalSection* contextLock;
  231084. bool needsUpdate;
  231085. }
  231086. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  231087. - (bool) makeActive;
  231088. - (void) makeInactive;
  231089. - (void) reshape;
  231090. @end
  231091. @implementation ThreadSafeNSOpenGLView
  231092. - (id) initWithFrame: (NSRect) frameRect
  231093. pixelFormat: (NSOpenGLPixelFormat*) format
  231094. {
  231095. contextLock = new CriticalSection();
  231096. self = [super initWithFrame: frameRect pixelFormat: format];
  231097. if (self != nil)
  231098. [[NSNotificationCenter defaultCenter] addObserver: self
  231099. selector: @selector (_surfaceNeedsUpdate:)
  231100. name: NSViewGlobalFrameDidChangeNotification
  231101. object: self];
  231102. return self;
  231103. }
  231104. - (void) dealloc
  231105. {
  231106. [[NSNotificationCenter defaultCenter] removeObserver: self];
  231107. delete contextLock;
  231108. [super dealloc];
  231109. }
  231110. - (bool) makeActive
  231111. {
  231112. const ScopedLock sl (*contextLock);
  231113. if ([self openGLContext] == 0)
  231114. return false;
  231115. [[self openGLContext] makeCurrentContext];
  231116. if (needsUpdate)
  231117. {
  231118. [super update];
  231119. needsUpdate = false;
  231120. }
  231121. return true;
  231122. }
  231123. - (void) makeInactive
  231124. {
  231125. const ScopedLock sl (*contextLock);
  231126. [NSOpenGLContext clearCurrentContext];
  231127. }
  231128. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  231129. {
  231130. const ScopedLock sl (*contextLock);
  231131. needsUpdate = true;
  231132. }
  231133. - (void) update
  231134. {
  231135. const ScopedLock sl (*contextLock);
  231136. needsUpdate = true;
  231137. }
  231138. - (void) reshape
  231139. {
  231140. const ScopedLock sl (*contextLock);
  231141. needsUpdate = true;
  231142. }
  231143. @end
  231144. BEGIN_JUCE_NAMESPACE
  231145. class WindowedGLContext : public OpenGLContext
  231146. {
  231147. public:
  231148. WindowedGLContext (Component* const component,
  231149. const OpenGLPixelFormat& pixelFormat_,
  231150. NSOpenGLContext* sharedContext)
  231151. : renderContext (0),
  231152. pixelFormat (pixelFormat_)
  231153. {
  231154. jassert (component != 0);
  231155. NSOpenGLPixelFormatAttribute attribs [64];
  231156. int n = 0;
  231157. attribs[n++] = NSOpenGLPFADoubleBuffer;
  231158. attribs[n++] = NSOpenGLPFAAccelerated;
  231159. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  231160. attribs[n++] = NSOpenGLPFAColorSize;
  231161. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  231162. pixelFormat.greenBits,
  231163. pixelFormat.blueBits);
  231164. attribs[n++] = NSOpenGLPFAAlphaSize;
  231165. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  231166. attribs[n++] = NSOpenGLPFADepthSize;
  231167. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  231168. attribs[n++] = NSOpenGLPFAStencilSize;
  231169. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  231170. attribs[n++] = NSOpenGLPFAAccumSize;
  231171. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  231172. pixelFormat.accumulationBufferGreenBits,
  231173. pixelFormat.accumulationBufferBlueBits,
  231174. pixelFormat.accumulationBufferAlphaBits);
  231175. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  231176. attribs[n++] = NSOpenGLPFASampleBuffers;
  231177. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  231178. attribs[n++] = NSOpenGLPFAClosestPolicy;
  231179. attribs[n++] = NSOpenGLPFANoRecovery;
  231180. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  231181. NSOpenGLPixelFormat* format
  231182. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  231183. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  231184. pixelFormat: format];
  231185. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  231186. shareContext: sharedContext] autorelease];
  231187. const GLint swapInterval = 1;
  231188. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  231189. [view setOpenGLContext: renderContext];
  231190. [renderContext setView: view];
  231191. [format release];
  231192. viewHolder = new NSViewComponentInternal (view, component);
  231193. }
  231194. ~WindowedGLContext()
  231195. {
  231196. makeInactive();
  231197. [renderContext clearDrawable];
  231198. viewHolder = 0;
  231199. }
  231200. bool makeActive() const throw()
  231201. {
  231202. jassert (renderContext != 0);
  231203. [view makeActive];
  231204. return isActive();
  231205. }
  231206. bool makeInactive() const throw()
  231207. {
  231208. [view makeInactive];
  231209. return true;
  231210. }
  231211. bool isActive() const throw()
  231212. {
  231213. return [NSOpenGLContext currentContext] == renderContext;
  231214. }
  231215. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  231216. void* getRawContext() const throw() { return renderContext; }
  231217. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  231218. {
  231219. }
  231220. void swapBuffers()
  231221. {
  231222. [renderContext flushBuffer];
  231223. }
  231224. bool setSwapInterval (const int numFramesPerSwap)
  231225. {
  231226. [renderContext setValues: (const GLint*) &numFramesPerSwap
  231227. forParameter: NSOpenGLCPSwapInterval];
  231228. return true;
  231229. }
  231230. int getSwapInterval() const
  231231. {
  231232. GLint numFrames = 0;
  231233. [renderContext getValues: &numFrames
  231234. forParameter: NSOpenGLCPSwapInterval];
  231235. return numFrames;
  231236. }
  231237. void repaint()
  231238. {
  231239. // we need to invalidate the juce view that holds this gl view, to make it
  231240. // cause a repaint callback
  231241. NSView* v = (NSView*) viewHolder->view;
  231242. NSRect r = [v frame];
  231243. // bit of a bodge here.. if we only invalidate the area of the gl component,
  231244. // it's completely covered by the NSOpenGLView, so the OS throws away the
  231245. // repaint message, thus never causing our paint() callback, and never repainting
  231246. // the comp. So invalidating just a little bit around the edge helps..
  231247. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  231248. }
  231249. void* getNativeWindowHandle() const { return viewHolder->view; }
  231250. juce_UseDebuggingNewOperator
  231251. NSOpenGLContext* renderContext;
  231252. ThreadSafeNSOpenGLView* view;
  231253. private:
  231254. OpenGLPixelFormat pixelFormat;
  231255. ScopedPointer <NSViewComponentInternal> viewHolder;
  231256. WindowedGLContext (const WindowedGLContext&);
  231257. WindowedGLContext& operator= (const WindowedGLContext&);
  231258. };
  231259. OpenGLContext* OpenGLComponent::createContext()
  231260. {
  231261. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  231262. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  231263. return (c->renderContext != 0) ? c.release() : 0;
  231264. }
  231265. void* OpenGLComponent::getNativeWindowHandle() const
  231266. {
  231267. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  231268. : 0;
  231269. }
  231270. void juce_glViewport (const int w, const int h)
  231271. {
  231272. glViewport (0, 0, w, h);
  231273. }
  231274. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  231275. OwnedArray <OpenGLPixelFormat>& results)
  231276. {
  231277. /* GLint attribs [64];
  231278. int n = 0;
  231279. attribs[n++] = AGL_RGBA;
  231280. attribs[n++] = AGL_DOUBLEBUFFER;
  231281. attribs[n++] = AGL_ACCELERATED;
  231282. attribs[n++] = AGL_NO_RECOVERY;
  231283. attribs[n++] = AGL_NONE;
  231284. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  231285. while (p != 0)
  231286. {
  231287. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  231288. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  231289. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  231290. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  231291. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  231292. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  231293. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  231294. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  231295. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  231296. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  231297. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  231298. results.add (pf);
  231299. p = aglNextPixelFormat (p);
  231300. }*/
  231301. //jassertfalse //xxx can't see how you do this in cocoa!
  231302. }
  231303. #else
  231304. END_JUCE_NAMESPACE
  231305. @interface JuceGLView : UIView
  231306. {
  231307. }
  231308. + (Class) layerClass;
  231309. @end
  231310. @implementation JuceGLView
  231311. + (Class) layerClass
  231312. {
  231313. return [CAEAGLLayer class];
  231314. }
  231315. @end
  231316. BEGIN_JUCE_NAMESPACE
  231317. class GLESContext : public OpenGLContext
  231318. {
  231319. public:
  231320. GLESContext (UIViewComponentPeer* peer,
  231321. Component* const component_,
  231322. const OpenGLPixelFormat& pixelFormat_,
  231323. const GLESContext* const sharedContext,
  231324. NSUInteger apiType)
  231325. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  231326. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  231327. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  231328. {
  231329. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  231330. view.opaque = YES;
  231331. view.hidden = NO;
  231332. view.backgroundColor = [UIColor blackColor];
  231333. view.userInteractionEnabled = NO;
  231334. glLayer = (CAEAGLLayer*) [view layer];
  231335. [peer->view addSubview: view];
  231336. if (sharedContext != 0)
  231337. context = [[EAGLContext alloc] initWithAPI: apiType
  231338. sharegroup: [sharedContext->context sharegroup]];
  231339. else
  231340. context = [[EAGLContext alloc] initWithAPI: apiType];
  231341. createGLBuffers();
  231342. }
  231343. ~GLESContext()
  231344. {
  231345. makeInactive();
  231346. [context release];
  231347. [view removeFromSuperview];
  231348. [view release];
  231349. freeGLBuffers();
  231350. }
  231351. bool makeActive() const throw()
  231352. {
  231353. jassert (context != 0);
  231354. [EAGLContext setCurrentContext: context];
  231355. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  231356. return true;
  231357. }
  231358. void swapBuffers()
  231359. {
  231360. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  231361. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  231362. }
  231363. bool makeInactive() const throw()
  231364. {
  231365. return [EAGLContext setCurrentContext: nil];
  231366. }
  231367. bool isActive() const throw()
  231368. {
  231369. return [EAGLContext currentContext] == context;
  231370. }
  231371. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  231372. void* getRawContext() const throw() { return glLayer; }
  231373. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  231374. {
  231375. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  231376. if (lastWidth != w || lastHeight != h)
  231377. {
  231378. lastWidth = w;
  231379. lastHeight = h;
  231380. freeGLBuffers();
  231381. createGLBuffers();
  231382. }
  231383. }
  231384. bool setSwapInterval (const int numFramesPerSwap)
  231385. {
  231386. numFrames = numFramesPerSwap;
  231387. return true;
  231388. }
  231389. int getSwapInterval() const
  231390. {
  231391. return numFrames;
  231392. }
  231393. void repaint()
  231394. {
  231395. }
  231396. void createGLBuffers()
  231397. {
  231398. makeActive();
  231399. glGenFramebuffersOES (1, &frameBufferHandle);
  231400. glGenRenderbuffersOES (1, &colorBufferHandle);
  231401. glGenRenderbuffersOES (1, &depthBufferHandle);
  231402. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  231403. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  231404. GLint width, height;
  231405. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  231406. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  231407. if (useDepthBuffer)
  231408. {
  231409. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  231410. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  231411. }
  231412. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  231413. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  231414. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  231415. if (useDepthBuffer)
  231416. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  231417. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  231418. }
  231419. void freeGLBuffers()
  231420. {
  231421. if (frameBufferHandle != 0)
  231422. {
  231423. glDeleteFramebuffersOES (1, &frameBufferHandle);
  231424. frameBufferHandle = 0;
  231425. }
  231426. if (colorBufferHandle != 0)
  231427. {
  231428. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  231429. colorBufferHandle = 0;
  231430. }
  231431. if (depthBufferHandle != 0)
  231432. {
  231433. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  231434. depthBufferHandle = 0;
  231435. }
  231436. }
  231437. juce_UseDebuggingNewOperator
  231438. private:
  231439. Component::SafePointer<Component> component;
  231440. OpenGLPixelFormat pixelFormat;
  231441. JuceGLView* view;
  231442. CAEAGLLayer* glLayer;
  231443. EAGLContext* context;
  231444. bool useDepthBuffer;
  231445. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  231446. int numFrames;
  231447. int lastWidth, lastHeight;
  231448. GLESContext (const GLESContext&);
  231449. GLESContext& operator= (const GLESContext&);
  231450. };
  231451. OpenGLContext* OpenGLComponent::createContext()
  231452. {
  231453. ScopedAutoReleasePool pool;
  231454. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  231455. if (peer != 0)
  231456. return new GLESContext (peer, this, preferredPixelFormat,
  231457. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  231458. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  231459. return 0;
  231460. }
  231461. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  231462. OwnedArray <OpenGLPixelFormat>& /*results*/)
  231463. {
  231464. }
  231465. void juce_glViewport (const int w, const int h)
  231466. {
  231467. glViewport (0, 0, w, h);
  231468. }
  231469. #endif
  231470. #endif
  231471. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  231472. /*** Start of inlined file: juce_mac_MainMenu.mm ***/
  231473. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231474. // compiled on its own).
  231475. #if JUCE_INCLUDED_FILE
  231476. class JuceMainMenuHandler;
  231477. END_JUCE_NAMESPACE
  231478. using namespace JUCE_NAMESPACE;
  231479. #define JuceMenuCallback MakeObjCClassName(JuceMenuCallback)
  231480. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  231481. @interface JuceMenuCallback : NSObject <NSMenuDelegate>
  231482. #else
  231483. @interface JuceMenuCallback : NSObject
  231484. #endif
  231485. {
  231486. JuceMainMenuHandler* owner;
  231487. }
  231488. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_;
  231489. - (void) dealloc;
  231490. - (void) menuItemInvoked: (id) menu;
  231491. - (void) menuNeedsUpdate: (NSMenu*) menu;
  231492. @end
  231493. BEGIN_JUCE_NAMESPACE
  231494. class JuceMainMenuHandler : private MenuBarModelListener,
  231495. private DeletedAtShutdown
  231496. {
  231497. public:
  231498. static JuceMainMenuHandler* instance;
  231499. JuceMainMenuHandler()
  231500. : currentModel (0),
  231501. lastUpdateTime (0)
  231502. {
  231503. callback = [[JuceMenuCallback alloc] initWithOwner: this];
  231504. }
  231505. ~JuceMainMenuHandler()
  231506. {
  231507. setMenu (0);
  231508. jassert (instance == this);
  231509. instance = 0;
  231510. [callback release];
  231511. }
  231512. void setMenu (MenuBarModel* const newMenuBarModel)
  231513. {
  231514. if (currentModel != newMenuBarModel)
  231515. {
  231516. if (currentModel != 0)
  231517. currentModel->removeListener (this);
  231518. currentModel = newMenuBarModel;
  231519. if (currentModel != 0)
  231520. currentModel->addListener (this);
  231521. menuBarItemsChanged (0);
  231522. }
  231523. }
  231524. void addSubMenu (NSMenu* parent, const PopupMenu& child,
  231525. const String& name, const int menuId, const int tag)
  231526. {
  231527. NSMenuItem* item = [parent addItemWithTitle: juceStringToNS (name)
  231528. action: nil
  231529. keyEquivalent: @""];
  231530. [item setTag: tag];
  231531. NSMenu* sub = createMenu (child, name, menuId, tag);
  231532. [parent setSubmenu: sub forItem: item];
  231533. [sub setAutoenablesItems: false];
  231534. [sub release];
  231535. }
  231536. void updateSubMenu (NSMenuItem* parentItem, const PopupMenu& menuToCopy,
  231537. const String& name, const int menuId, const int tag)
  231538. {
  231539. [parentItem setTag: tag];
  231540. NSMenu* menu = [parentItem submenu];
  231541. [menu setTitle: juceStringToNS (name)];
  231542. while ([menu numberOfItems] > 0)
  231543. [menu removeItemAtIndex: 0];
  231544. PopupMenu::MenuItemIterator iter (menuToCopy);
  231545. while (iter.next())
  231546. addMenuItem (iter, menu, menuId, tag);
  231547. [menu setAutoenablesItems: false];
  231548. [menu update];
  231549. }
  231550. void menuBarItemsChanged (MenuBarModel*)
  231551. {
  231552. lastUpdateTime = Time::getMillisecondCounter();
  231553. StringArray menuNames;
  231554. if (currentModel != 0)
  231555. menuNames = currentModel->getMenuBarNames();
  231556. NSMenu* menuBar = [NSApp mainMenu];
  231557. while ([menuBar numberOfItems] > 1 + menuNames.size())
  231558. [menuBar removeItemAtIndex: [menuBar numberOfItems] - 1];
  231559. int menuId = 1;
  231560. for (int i = 0; i < menuNames.size(); ++i)
  231561. {
  231562. const PopupMenu menu (currentModel->getMenuForIndex (i, menuNames [i]));
  231563. if (i >= [menuBar numberOfItems] - 1)
  231564. addSubMenu (menuBar, menu, menuNames[i], menuId, i);
  231565. else
  231566. updateSubMenu ([menuBar itemAtIndex: 1 + i], menu, menuNames[i], menuId, i);
  231567. }
  231568. }
  231569. static void flashMenuBar (NSMenu* menu)
  231570. {
  231571. if ([[menu title] isEqualToString: @"Apple"])
  231572. return;
  231573. [menu retain];
  231574. const unichar f35Key = NSF35FunctionKey;
  231575. NSString* f35String = [NSString stringWithCharacters: &f35Key length: 1];
  231576. NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: @"x"
  231577. action: nil
  231578. keyEquivalent: f35String];
  231579. [item setTarget: nil];
  231580. [menu insertItem: item atIndex: [menu numberOfItems]];
  231581. [item release];
  231582. if ([menu indexOfItem: item] >= 0)
  231583. {
  231584. NSEvent* f35Event = [NSEvent keyEventWithType: NSKeyDown
  231585. location: NSZeroPoint
  231586. modifierFlags: NSCommandKeyMask
  231587. timestamp: 0
  231588. windowNumber: 0
  231589. context: [NSGraphicsContext currentContext]
  231590. characters: f35String
  231591. charactersIgnoringModifiers: f35String
  231592. isARepeat: NO
  231593. keyCode: 0];
  231594. [menu performKeyEquivalent: f35Event];
  231595. if ([menu indexOfItem: item] >= 0)
  231596. [menu removeItem: item]; // (this throws if the item isn't actually in the menu)
  231597. }
  231598. [menu release];
  231599. }
  231600. static NSMenuItem* findMenuItem (NSMenu* const menu, const ApplicationCommandTarget::InvocationInfo& info)
  231601. {
  231602. for (NSInteger i = [menu numberOfItems]; --i >= 0;)
  231603. {
  231604. NSMenuItem* m = [menu itemAtIndex: i];
  231605. if ([m tag] == info.commandID)
  231606. return m;
  231607. if ([m submenu] != 0)
  231608. {
  231609. NSMenuItem* found = findMenuItem ([m submenu], info);
  231610. if (found != 0)
  231611. return found;
  231612. }
  231613. }
  231614. return 0;
  231615. }
  231616. void menuCommandInvoked (MenuBarModel*, const ApplicationCommandTarget::InvocationInfo& info)
  231617. {
  231618. NSMenuItem* item = findMenuItem ([NSApp mainMenu], info);
  231619. if (item != 0)
  231620. flashMenuBar ([item menu]);
  231621. }
  231622. void updateMenus()
  231623. {
  231624. if (Time::getMillisecondCounter() > lastUpdateTime + 500)
  231625. menuBarItemsChanged (0);
  231626. }
  231627. void invoke (const int commandId, ApplicationCommandManager* const commandManager, const int topLevelIndex) const
  231628. {
  231629. if (currentModel != 0)
  231630. {
  231631. if (commandManager != 0)
  231632. {
  231633. ApplicationCommandTarget::InvocationInfo info (commandId);
  231634. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  231635. commandManager->invoke (info, true);
  231636. }
  231637. currentModel->menuItemSelected (commandId, topLevelIndex);
  231638. }
  231639. }
  231640. MenuBarModel* currentModel;
  231641. uint32 lastUpdateTime;
  231642. void addMenuItem (PopupMenu::MenuItemIterator& iter, NSMenu* menuToAddTo,
  231643. const int topLevelMenuId, const int topLevelIndex)
  231644. {
  231645. NSString* text = juceStringToNS (iter.itemName.upToFirstOccurrenceOf ("<end>", false, true));
  231646. if (text == 0)
  231647. text = @"";
  231648. if (iter.isSeparator)
  231649. {
  231650. [menuToAddTo addItem: [NSMenuItem separatorItem]];
  231651. }
  231652. else if (iter.isSectionHeader)
  231653. {
  231654. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  231655. action: nil
  231656. keyEquivalent: @""];
  231657. [item setEnabled: false];
  231658. }
  231659. else if (iter.subMenu != 0)
  231660. {
  231661. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  231662. action: nil
  231663. keyEquivalent: @""];
  231664. [item setTag: iter.itemId];
  231665. [item setEnabled: iter.isEnabled];
  231666. NSMenu* sub = createMenu (*iter.subMenu, iter.itemName, topLevelMenuId, topLevelIndex);
  231667. [sub setDelegate: nil];
  231668. [menuToAddTo setSubmenu: sub forItem: item];
  231669. [sub release];
  231670. }
  231671. else
  231672. {
  231673. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  231674. action: @selector (menuItemInvoked:)
  231675. keyEquivalent: @""];
  231676. [item setTag: iter.itemId];
  231677. [item setEnabled: iter.isEnabled];
  231678. [item setState: iter.isTicked ? NSOnState : NSOffState];
  231679. [item setTarget: (id) callback];
  231680. NSMutableArray* info = [NSMutableArray arrayWithObject: [NSNumber numberWithUnsignedLongLong: (pointer_sized_int) (void*) iter.commandManager]];
  231681. [info addObject: [NSNumber numberWithInt: topLevelIndex]];
  231682. [item setRepresentedObject: info];
  231683. if (iter.commandManager != 0)
  231684. {
  231685. const Array <KeyPress> keyPresses (iter.commandManager->getKeyMappings()
  231686. ->getKeyPressesAssignedToCommand (iter.itemId));
  231687. if (keyPresses.size() > 0)
  231688. {
  231689. const KeyPress& kp = keyPresses.getReference(0);
  231690. if (kp.getKeyCode() != KeyPress::backspaceKey
  231691. && kp.getKeyCode() != KeyPress::deleteKey) // (adding these is annoying because it flashes the menu bar
  231692. // every time you press the key while editing text)
  231693. {
  231694. juce_wchar key = kp.getTextCharacter();
  231695. if (kp.getKeyCode() == KeyPress::backspaceKey)
  231696. key = NSBackspaceCharacter;
  231697. else if (kp.getKeyCode() == KeyPress::deleteKey)
  231698. key = NSDeleteCharacter;
  231699. else if (key == 0)
  231700. key = (juce_wchar) kp.getKeyCode();
  231701. unsigned int mods = 0;
  231702. if (kp.getModifiers().isShiftDown())
  231703. mods |= NSShiftKeyMask;
  231704. if (kp.getModifiers().isCtrlDown())
  231705. mods |= NSControlKeyMask;
  231706. if (kp.getModifiers().isAltDown())
  231707. mods |= NSAlternateKeyMask;
  231708. if (kp.getModifiers().isCommandDown())
  231709. mods |= NSCommandKeyMask;
  231710. [item setKeyEquivalent: juceStringToNS (String::charToString (key))];
  231711. [item setKeyEquivalentModifierMask: mods];
  231712. }
  231713. }
  231714. }
  231715. }
  231716. }
  231717. JuceMenuCallback* callback;
  231718. private:
  231719. NSMenu* createMenu (const PopupMenu menu,
  231720. const String& menuName,
  231721. const int topLevelMenuId,
  231722. const int topLevelIndex)
  231723. {
  231724. NSMenu* m = [[NSMenu alloc] initWithTitle: juceStringToNS (menuName)];
  231725. [m setAutoenablesItems: false];
  231726. [m setDelegate: callback];
  231727. PopupMenu::MenuItemIterator iter (menu);
  231728. while (iter.next())
  231729. addMenuItem (iter, m, topLevelMenuId, topLevelIndex);
  231730. [m update];
  231731. return m;
  231732. }
  231733. };
  231734. JuceMainMenuHandler* JuceMainMenuHandler::instance = 0;
  231735. END_JUCE_NAMESPACE
  231736. @implementation JuceMenuCallback
  231737. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_
  231738. {
  231739. [super init];
  231740. owner = owner_;
  231741. return self;
  231742. }
  231743. - (void) dealloc
  231744. {
  231745. [super dealloc];
  231746. }
  231747. - (void) menuItemInvoked: (id) menu
  231748. {
  231749. NSMenuItem* item = (NSMenuItem*) menu;
  231750. if ([[item representedObject] isKindOfClass: [NSArray class]])
  231751. {
  231752. // 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
  231753. // our own components, which may have wanted to intercept it. So, rather than dispatching directly, we'll feed it back
  231754. // into the focused component and let it trigger the menu item indirectly.
  231755. NSEvent* e = [NSApp currentEvent];
  231756. if ([e type] == NSKeyDown || [e type] == NSKeyUp)
  231757. {
  231758. if (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent() != 0)
  231759. {
  231760. JUCE_NAMESPACE::NSViewComponentPeer* peer = dynamic_cast <JUCE_NAMESPACE::NSViewComponentPeer*> (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent()->getPeer());
  231761. if (peer != 0)
  231762. {
  231763. if ([e type] == NSKeyDown)
  231764. peer->redirectKeyDown (e);
  231765. else
  231766. peer->redirectKeyUp (e);
  231767. return;
  231768. }
  231769. }
  231770. }
  231771. NSArray* info = (NSArray*) [item representedObject];
  231772. owner->invoke ((int) [item tag],
  231773. (ApplicationCommandManager*) (pointer_sized_int)
  231774. [((NSNumber*) [info objectAtIndex: 0]) unsignedLongLongValue],
  231775. (int) [((NSNumber*) [info objectAtIndex: 1]) intValue]);
  231776. }
  231777. }
  231778. - (void) menuNeedsUpdate: (NSMenu*) menu;
  231779. {
  231780. (void) menu;
  231781. if (JuceMainMenuHandler::instance != 0)
  231782. JuceMainMenuHandler::instance->updateMenus();
  231783. }
  231784. @end
  231785. BEGIN_JUCE_NAMESPACE
  231786. static NSMenu* createStandardAppMenu (NSMenu* menu, const String& appName,
  231787. const PopupMenu* extraItems)
  231788. {
  231789. if (extraItems != 0 && JuceMainMenuHandler::instance != 0 && extraItems->getNumItems() > 0)
  231790. {
  231791. PopupMenu::MenuItemIterator iter (*extraItems);
  231792. while (iter.next())
  231793. JuceMainMenuHandler::instance->addMenuItem (iter, menu, 0, -1);
  231794. [menu addItem: [NSMenuItem separatorItem]];
  231795. }
  231796. NSMenuItem* item;
  231797. // Services...
  231798. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Services", nil)
  231799. action: nil keyEquivalent: @""];
  231800. [menu addItem: item];
  231801. [item release];
  231802. NSMenu* servicesMenu = [[NSMenu alloc] initWithTitle: @"Services"];
  231803. [menu setSubmenu: servicesMenu forItem: item];
  231804. [NSApp setServicesMenu: servicesMenu];
  231805. [servicesMenu release];
  231806. [menu addItem: [NSMenuItem separatorItem]];
  231807. // Hide + Show stuff...
  231808. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Hide " + appName)
  231809. action: @selector (hide:) keyEquivalent: @"h"];
  231810. [item setTarget: NSApp];
  231811. [menu addItem: item];
  231812. [item release];
  231813. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Hide Others", nil)
  231814. action: @selector (hideOtherApplications:) keyEquivalent: @"h"];
  231815. [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
  231816. [item setTarget: NSApp];
  231817. [menu addItem: item];
  231818. [item release];
  231819. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Show All", nil)
  231820. action: @selector (unhideAllApplications:) keyEquivalent: @""];
  231821. [item setTarget: NSApp];
  231822. [menu addItem: item];
  231823. [item release];
  231824. [menu addItem: [NSMenuItem separatorItem]];
  231825. // Quit item....
  231826. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Quit " + appName)
  231827. action: @selector (terminate:) keyEquivalent: @"q"];
  231828. [item setTarget: NSApp];
  231829. [menu addItem: item];
  231830. [item release];
  231831. return menu;
  231832. }
  231833. // Since our app has no NIB, this initialises a standard app menu...
  231834. static void rebuildMainMenu (const PopupMenu* extraItems)
  231835. {
  231836. // this can't be used in a plugin!
  231837. jassert (JUCEApplication::getInstance() != 0);
  231838. if (JUCEApplication::getInstance() != 0)
  231839. {
  231840. const ScopedAutoReleasePool pool;
  231841. NSMenu* mainMenu = [[NSMenu alloc] initWithTitle: @"MainMenu"];
  231842. NSMenuItem* item = [mainMenu addItemWithTitle: @"Apple" action: nil keyEquivalent: @""];
  231843. NSMenu* appMenu = [[NSMenu alloc] initWithTitle: @"Apple"];
  231844. [NSApp performSelector: @selector (setAppleMenu:) withObject: appMenu];
  231845. [mainMenu setSubmenu: appMenu forItem: item];
  231846. [NSApp setMainMenu: mainMenu];
  231847. createStandardAppMenu (appMenu, JUCEApplication::getInstance()->getApplicationName(), extraItems);
  231848. [appMenu release];
  231849. [mainMenu release];
  231850. }
  231851. }
  231852. void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel,
  231853. const PopupMenu* extraAppleMenuItems)
  231854. {
  231855. if (getMacMainMenu() != newMenuBarModel)
  231856. {
  231857. const ScopedAutoReleasePool pool;
  231858. if (newMenuBarModel == 0)
  231859. {
  231860. delete JuceMainMenuHandler::instance;
  231861. jassert (JuceMainMenuHandler::instance == 0); // should be zeroed in the destructor
  231862. jassert (extraAppleMenuItems == 0); // you can't specify some extra items without also supplying a model
  231863. extraAppleMenuItems = 0;
  231864. }
  231865. else
  231866. {
  231867. if (JuceMainMenuHandler::instance == 0)
  231868. JuceMainMenuHandler::instance = new JuceMainMenuHandler();
  231869. JuceMainMenuHandler::instance->setMenu (newMenuBarModel);
  231870. }
  231871. }
  231872. rebuildMainMenu (extraAppleMenuItems);
  231873. if (newMenuBarModel != 0)
  231874. newMenuBarModel->menuItemsChanged();
  231875. }
  231876. MenuBarModel* MenuBarModel::getMacMainMenu()
  231877. {
  231878. return JuceMainMenuHandler::instance != 0
  231879. ? JuceMainMenuHandler::instance->currentModel : 0;
  231880. }
  231881. void initialiseMainMenu()
  231882. {
  231883. if (JUCEApplication::getInstance() != 0) // only needed in an app
  231884. rebuildMainMenu (0);
  231885. }
  231886. #endif
  231887. /*** End of inlined file: juce_mac_MainMenu.mm ***/
  231888. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  231889. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231890. // compiled on its own).
  231891. #if JUCE_INCLUDED_FILE
  231892. #if JUCE_MAC
  231893. END_JUCE_NAMESPACE
  231894. using namespace JUCE_NAMESPACE;
  231895. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  231896. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  231897. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  231898. #else
  231899. @interface JuceFileChooserDelegate : NSObject
  231900. #endif
  231901. {
  231902. StringArray* filters;
  231903. }
  231904. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  231905. - (void) dealloc;
  231906. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  231907. @end
  231908. @implementation JuceFileChooserDelegate
  231909. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  231910. {
  231911. [super init];
  231912. filters = filters_;
  231913. return self;
  231914. }
  231915. - (void) dealloc
  231916. {
  231917. delete filters;
  231918. [super dealloc];
  231919. }
  231920. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  231921. {
  231922. (void) sender;
  231923. const File f (nsStringToJuce (filename));
  231924. for (int i = filters->size(); --i >= 0;)
  231925. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  231926. return true;
  231927. return f.isDirectory();
  231928. }
  231929. @end
  231930. BEGIN_JUCE_NAMESPACE
  231931. void FileChooser::showPlatformDialog (Array<File>& results,
  231932. const String& title,
  231933. const File& currentFileOrDirectory,
  231934. const String& filter,
  231935. bool selectsDirectory,
  231936. bool selectsFiles,
  231937. bool isSaveDialogue,
  231938. bool warnAboutOverwritingExistingFiles,
  231939. bool selectMultipleFiles,
  231940. FilePreviewComponent* extraInfoComponent)
  231941. {
  231942. const ScopedAutoReleasePool pool;
  231943. StringArray* filters = new StringArray();
  231944. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  231945. filters->trim();
  231946. filters->removeEmptyStrings();
  231947. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  231948. [delegate autorelease];
  231949. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  231950. : [NSOpenPanel openPanel];
  231951. [panel setTitle: juceStringToNS (title)];
  231952. if (! isSaveDialogue)
  231953. {
  231954. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  231955. [openPanel setCanChooseDirectories: selectsDirectory];
  231956. [openPanel setCanChooseFiles: selectsFiles];
  231957. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  231958. }
  231959. [panel setDelegate: delegate];
  231960. if (isSaveDialogue || selectsDirectory)
  231961. [panel setCanCreateDirectories: YES];
  231962. String directory, filename;
  231963. if (currentFileOrDirectory.isDirectory())
  231964. {
  231965. directory = currentFileOrDirectory.getFullPathName();
  231966. }
  231967. else
  231968. {
  231969. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  231970. filename = currentFileOrDirectory.getFileName();
  231971. }
  231972. if ([panel runModalForDirectory: juceStringToNS (directory)
  231973. file: juceStringToNS (filename)]
  231974. == NSOKButton)
  231975. {
  231976. if (isSaveDialogue)
  231977. {
  231978. results.add (File (nsStringToJuce ([panel filename])));
  231979. }
  231980. else
  231981. {
  231982. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  231983. NSArray* urls = [openPanel filenames];
  231984. for (unsigned int i = 0; i < [urls count]; ++i)
  231985. {
  231986. NSString* f = [urls objectAtIndex: i];
  231987. results.add (File (nsStringToJuce (f)));
  231988. }
  231989. }
  231990. }
  231991. [panel setDelegate: nil];
  231992. }
  231993. #else
  231994. void FileChooser::showPlatformDialog (Array<File>& results,
  231995. const String& title,
  231996. const File& currentFileOrDirectory,
  231997. const String& filter,
  231998. bool selectsDirectory,
  231999. bool selectsFiles,
  232000. bool isSaveDialogue,
  232001. bool warnAboutOverwritingExistingFiles,
  232002. bool selectMultipleFiles,
  232003. FilePreviewComponent* extraInfoComponent)
  232004. {
  232005. const ScopedAutoReleasePool pool;
  232006. jassertfalse; //xxx to do
  232007. }
  232008. #endif
  232009. #endif
  232010. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  232011. /*** Start of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  232012. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232013. // compiled on its own).
  232014. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  232015. END_JUCE_NAMESPACE
  232016. #define NonInterceptingQTMovieView MakeObjCClassName(NonInterceptingQTMovieView)
  232017. @interface NonInterceptingQTMovieView : QTMovieView
  232018. {
  232019. }
  232020. - (id) initWithFrame: (NSRect) frame;
  232021. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent;
  232022. - (NSView*) hitTest: (NSPoint) p;
  232023. @end
  232024. @implementation NonInterceptingQTMovieView
  232025. - (id) initWithFrame: (NSRect) frame
  232026. {
  232027. self = [super initWithFrame: frame];
  232028. [self setNextResponder: [self superview]];
  232029. return self;
  232030. }
  232031. - (void) dealloc
  232032. {
  232033. [super dealloc];
  232034. }
  232035. - (NSView*) hitTest: (NSPoint) point
  232036. {
  232037. return [self isControllerVisible] ? [super hitTest: point] : nil;
  232038. }
  232039. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent
  232040. {
  232041. return YES;
  232042. }
  232043. @end
  232044. BEGIN_JUCE_NAMESPACE
  232045. #define theMovie (static_cast <QTMovie*> (movie))
  232046. QuickTimeMovieComponent::QuickTimeMovieComponent()
  232047. : movie (0)
  232048. {
  232049. setOpaque (true);
  232050. setVisible (true);
  232051. QTMovieView* view = [[NonInterceptingQTMovieView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)];
  232052. setView (view);
  232053. [view release];
  232054. }
  232055. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  232056. {
  232057. closeMovie();
  232058. setView (0);
  232059. }
  232060. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  232061. {
  232062. return true;
  232063. }
  232064. static QTMovie* openMovieFromStream (InputStream* movieStream, File& movieFile)
  232065. {
  232066. // unfortunately, QTMovie objects can only be created on the main thread..
  232067. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  232068. QTMovie* movie = 0;
  232069. FileInputStream* const fin = dynamic_cast <FileInputStream*> (movieStream);
  232070. if (fin != 0)
  232071. {
  232072. movieFile = fin->getFile();
  232073. movie = [QTMovie movieWithFile: juceStringToNS (movieFile.getFullPathName())
  232074. error: nil];
  232075. }
  232076. else
  232077. {
  232078. MemoryBlock temp;
  232079. movieStream->readIntoMemoryBlock (temp);
  232080. const char* const suffixesToTry[] = { ".mov", ".mp3", ".avi", ".m4a" };
  232081. for (int i = 0; i < numElementsInArray (suffixesToTry); ++i)
  232082. {
  232083. movie = [QTMovie movieWithDataReference: [QTDataReference dataReferenceWithReferenceToData: [NSData dataWithBytes: temp.getData()
  232084. length: temp.getSize()]
  232085. name: [NSString stringWithUTF8String: suffixesToTry[i]]
  232086. MIMEType: @""]
  232087. error: nil];
  232088. if (movie != 0)
  232089. break;
  232090. }
  232091. }
  232092. return movie;
  232093. }
  232094. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  232095. const bool isControllerVisible_)
  232096. {
  232097. return loadMovie ((InputStream*) movieFile_.createInputStream(), isControllerVisible_);
  232098. }
  232099. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  232100. const bool controllerVisible_)
  232101. {
  232102. closeMovie();
  232103. if (getPeer() == 0)
  232104. {
  232105. // To open a movie, this component must be visible inside a functioning window, so that
  232106. // the QT control can be assigned to the window.
  232107. jassertfalse;
  232108. return false;
  232109. }
  232110. movie = openMovieFromStream (movieStream, movieFile);
  232111. [theMovie retain];
  232112. QTMovieView* view = (QTMovieView*) getView();
  232113. [view setMovie: theMovie];
  232114. [view setControllerVisible: controllerVisible_];
  232115. setLooping (looping);
  232116. return movie != nil;
  232117. }
  232118. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  232119. const bool isControllerVisible_)
  232120. {
  232121. // unfortunately, QTMovie objects can only be created on the main thread..
  232122. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  232123. closeMovie();
  232124. if (getPeer() == 0)
  232125. {
  232126. // To open a movie, this component must be visible inside a functioning window, so that
  232127. // the QT control can be assigned to the window.
  232128. jassertfalse;
  232129. return false;
  232130. }
  232131. NSURL* url = [NSURL URLWithString: juceStringToNS (movieURL.toString (true))];
  232132. NSError* err;
  232133. if ([QTMovie canInitWithURL: url])
  232134. movie = [QTMovie movieWithURL: url error: &err];
  232135. [theMovie retain];
  232136. QTMovieView* view = (QTMovieView*) getView();
  232137. [view setMovie: theMovie];
  232138. [view setControllerVisible: controllerVisible];
  232139. setLooping (looping);
  232140. return movie != nil;
  232141. }
  232142. void QuickTimeMovieComponent::closeMovie()
  232143. {
  232144. stop();
  232145. QTMovieView* view = (QTMovieView*) getView();
  232146. [view setMovie: nil];
  232147. [theMovie release];
  232148. movie = 0;
  232149. movieFile = File::nonexistent;
  232150. }
  232151. bool QuickTimeMovieComponent::isMovieOpen() const
  232152. {
  232153. return movie != nil;
  232154. }
  232155. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  232156. {
  232157. return movieFile;
  232158. }
  232159. void QuickTimeMovieComponent::play()
  232160. {
  232161. [theMovie play];
  232162. }
  232163. void QuickTimeMovieComponent::stop()
  232164. {
  232165. [theMovie stop];
  232166. }
  232167. bool QuickTimeMovieComponent::isPlaying() const
  232168. {
  232169. return movie != 0 && [theMovie rate] != 0;
  232170. }
  232171. void QuickTimeMovieComponent::setPosition (const double seconds)
  232172. {
  232173. if (movie != 0)
  232174. {
  232175. QTTime t;
  232176. t.timeValue = (uint64) (100000.0 * seconds);
  232177. t.timeScale = 100000;
  232178. t.flags = 0;
  232179. [theMovie setCurrentTime: t];
  232180. }
  232181. }
  232182. double QuickTimeMovieComponent::getPosition() const
  232183. {
  232184. if (movie == 0)
  232185. return 0.0;
  232186. QTTime t = [theMovie currentTime];
  232187. return t.timeValue / (double) t.timeScale;
  232188. }
  232189. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  232190. {
  232191. [theMovie setRate: newSpeed];
  232192. }
  232193. double QuickTimeMovieComponent::getMovieDuration() const
  232194. {
  232195. if (movie == 0)
  232196. return 0.0;
  232197. QTTime t = [theMovie duration];
  232198. return t.timeValue / (double) t.timeScale;
  232199. }
  232200. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  232201. {
  232202. looping = shouldLoop;
  232203. [theMovie setAttribute: [NSNumber numberWithBool: shouldLoop]
  232204. forKey: QTMovieLoopsAttribute];
  232205. }
  232206. bool QuickTimeMovieComponent::isLooping() const
  232207. {
  232208. return looping;
  232209. }
  232210. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  232211. {
  232212. [theMovie setVolume: newVolume];
  232213. }
  232214. float QuickTimeMovieComponent::getMovieVolume() const
  232215. {
  232216. return movie != 0 ? [theMovie volume] : 0.0f;
  232217. }
  232218. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  232219. {
  232220. width = 0;
  232221. height = 0;
  232222. if (movie != 0)
  232223. {
  232224. NSSize s = [[theMovie attributeForKey: QTMovieNaturalSizeAttribute] sizeValue];
  232225. width = (int) s.width;
  232226. height = (int) s.height;
  232227. }
  232228. }
  232229. void QuickTimeMovieComponent::paint (Graphics& g)
  232230. {
  232231. if (movie == 0)
  232232. g.fillAll (Colours::black);
  232233. }
  232234. bool QuickTimeMovieComponent::isControllerVisible() const
  232235. {
  232236. return controllerVisible;
  232237. }
  232238. void QuickTimeMovieComponent::goToStart()
  232239. {
  232240. setPosition (0.0);
  232241. }
  232242. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  232243. const RectanglePlacement& placement)
  232244. {
  232245. int normalWidth, normalHeight;
  232246. getMovieNormalSize (normalWidth, normalHeight);
  232247. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  232248. {
  232249. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  232250. placement.applyTo (x, y, w, h,
  232251. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  232252. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  232253. if (w > 0 && h > 0)
  232254. {
  232255. setBounds (roundToInt (x), roundToInt (y),
  232256. roundToInt (w), roundToInt (h));
  232257. }
  232258. }
  232259. else
  232260. {
  232261. setBounds (spaceToFitWithin);
  232262. }
  232263. }
  232264. #if ! (JUCE_MAC && JUCE_64BIT)
  232265. bool juce_OpenQuickTimeMovieFromStream (InputStream* movieStream, Movie& result, Handle& dataHandle)
  232266. {
  232267. if (movieStream == 0)
  232268. return false;
  232269. File file;
  232270. QTMovie* movie = openMovieFromStream (movieStream, file);
  232271. if (movie != nil)
  232272. result = [movie quickTimeMovie];
  232273. return movie != nil;
  232274. }
  232275. #endif
  232276. #endif
  232277. /*** End of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  232278. /*** Start of inlined file: juce_mac_AudioCDBurner.mm ***/
  232279. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232280. // compiled on its own).
  232281. #if JUCE_INCLUDED_FILE && JUCE_USE_CDBURNER
  232282. const int kilobytesPerSecond1x = 176;
  232283. END_JUCE_NAMESPACE
  232284. #define OpenDiskDevice MakeObjCClassName(OpenDiskDevice)
  232285. @interface OpenDiskDevice : NSObject
  232286. {
  232287. @public
  232288. DRDevice* device;
  232289. NSMutableArray* tracks;
  232290. bool underrunProtection;
  232291. }
  232292. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device;
  232293. - (void) dealloc;
  232294. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) numSamples_;
  232295. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  232296. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed;
  232297. @end
  232298. #define AudioTrackProducer MakeObjCClassName(AudioTrackProducer)
  232299. @interface AudioTrackProducer : NSObject
  232300. {
  232301. JUCE_NAMESPACE::AudioSource* source;
  232302. int readPosition, lengthInFrames;
  232303. }
  232304. - (AudioTrackProducer*) init: (int) lengthInFrames;
  232305. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) lengthInSamples;
  232306. - (void) dealloc;
  232307. - (void) setupTrackProperties: (DRTrack*) track;
  232308. - (void) cleanupTrackAfterBurn: (DRTrack*) track;
  232309. - (BOOL) cleanupTrackAfterVerification:(DRTrack*)track;
  232310. - (uint64_t) estimateLengthOfTrack:(DRTrack*)track;
  232311. - (BOOL) prepareTrack:(DRTrack*)track forBurn:(DRBurn*)burn
  232312. toMedia:(NSDictionary*)mediaInfo;
  232313. - (BOOL) prepareTrackForVerification:(DRTrack*)track;
  232314. - (uint32_t) produceDataForTrack:(DRTrack*)track intoBuffer:(char*)buffer
  232315. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  232316. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  232317. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  232318. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  232319. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  232320. ioFlags:(uint32_t*)flags;
  232321. - (BOOL) verifyDataForTrack:(DRTrack*)track inBuffer:(const char*)buffer
  232322. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  232323. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  232324. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  232325. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  232326. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  232327. ioFlags:(uint32_t*)flags;
  232328. @end
  232329. @implementation OpenDiskDevice
  232330. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device_
  232331. {
  232332. [super init];
  232333. device = device_;
  232334. tracks = [[NSMutableArray alloc] init];
  232335. underrunProtection = true;
  232336. return self;
  232337. }
  232338. - (void) dealloc
  232339. {
  232340. [tracks release];
  232341. [super dealloc];
  232342. }
  232343. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) numSamples_
  232344. {
  232345. AudioTrackProducer* p = [[AudioTrackProducer alloc] initWithAudioSource: source_ numSamples: numSamples_];
  232346. DRTrack* t = [[DRTrack alloc] initWithProducer: p];
  232347. [p setupTrackProperties: t];
  232348. [tracks addObject: t];
  232349. [t release];
  232350. [p release];
  232351. }
  232352. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  232353. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed
  232354. {
  232355. DRBurn* burn = [DRBurn burnForDevice: device];
  232356. if (! [device acquireExclusiveAccess])
  232357. {
  232358. *error = "Couldn't open or write to the CD device";
  232359. return;
  232360. }
  232361. [device acquireMediaReservation];
  232362. NSMutableDictionary* d = [[burn properties] mutableCopy];
  232363. [d autorelease];
  232364. [d setObject: [NSNumber numberWithBool: peformFakeBurnForTesting] forKey: DRBurnTestingKey];
  232365. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnVerifyDiscKey];
  232366. [d setObject: (shouldEject ? DRBurnCompletionActionEject : DRBurnCompletionActionMount) forKey: DRBurnCompletionActionKey];
  232367. if (burnSpeed > 0)
  232368. [d setObject: [NSNumber numberWithFloat: burnSpeed * JUCE_NAMESPACE::kilobytesPerSecond1x] forKey: DRBurnRequestedSpeedKey];
  232369. if (! underrunProtection)
  232370. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnUnderrunProtectionKey];
  232371. [burn setProperties: d];
  232372. [burn writeLayout: tracks];
  232373. for (;;)
  232374. {
  232375. JUCE_NAMESPACE::Thread::sleep (300);
  232376. float progress = [[[burn status] objectForKey: DRStatusPercentCompleteKey] floatValue];
  232377. if (listener != 0 && listener->audioCDBurnProgress (progress))
  232378. {
  232379. [burn abort];
  232380. *error = "User cancelled the write operation";
  232381. break;
  232382. }
  232383. if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateFailed])
  232384. {
  232385. *error = "Write operation failed";
  232386. break;
  232387. }
  232388. else if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateDone])
  232389. {
  232390. break;
  232391. }
  232392. NSString* err = (NSString*) [[[burn status] objectForKey: DRErrorStatusKey]
  232393. objectForKey: DRErrorStatusErrorStringKey];
  232394. if ([err length] > 0)
  232395. {
  232396. *error = JUCE_NAMESPACE::String::fromUTF8 ([err UTF8String]);
  232397. break;
  232398. }
  232399. }
  232400. [device releaseMediaReservation];
  232401. [device releaseExclusiveAccess];
  232402. }
  232403. @end
  232404. @implementation AudioTrackProducer
  232405. - (AudioTrackProducer*) init: (int) lengthInFrames_
  232406. {
  232407. lengthInFrames = lengthInFrames_;
  232408. readPosition = 0;
  232409. return self;
  232410. }
  232411. - (void) setupTrackProperties: (DRTrack*) track
  232412. {
  232413. NSMutableDictionary* p = [[track properties] mutableCopy];
  232414. [p setObject:[DRMSF msfWithFrames: lengthInFrames] forKey: DRTrackLengthKey];
  232415. [p setObject:[NSNumber numberWithUnsignedShort:2352] forKey: DRBlockSizeKey];
  232416. [p setObject:[NSNumber numberWithInt:0] forKey: DRDataFormKey];
  232417. [p setObject:[NSNumber numberWithInt:0] forKey: DRBlockTypeKey];
  232418. [p setObject:[NSNumber numberWithInt:0] forKey: DRTrackModeKey];
  232419. [p setObject:[NSNumber numberWithInt:0] forKey: DRSessionFormatKey];
  232420. [track setProperties: p];
  232421. [p release];
  232422. }
  232423. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) lengthInSamples
  232424. {
  232425. AudioTrackProducer* s = [self init: (lengthInSamples + 587) / 588];
  232426. if (s != nil)
  232427. s->source = source_;
  232428. return s;
  232429. }
  232430. - (void) dealloc
  232431. {
  232432. if (source != 0)
  232433. {
  232434. source->releaseResources();
  232435. delete source;
  232436. }
  232437. [super dealloc];
  232438. }
  232439. - (void) cleanupTrackAfterBurn: (DRTrack*) track
  232440. {
  232441. }
  232442. - (BOOL) cleanupTrackAfterVerification: (DRTrack*) track
  232443. {
  232444. return true;
  232445. }
  232446. - (uint64_t) estimateLengthOfTrack: (DRTrack*) track
  232447. {
  232448. return lengthInFrames;
  232449. }
  232450. - (BOOL) prepareTrack: (DRTrack*) track forBurn: (DRBurn*) burn
  232451. toMedia: (NSDictionary*) mediaInfo
  232452. {
  232453. if (source != 0)
  232454. source->prepareToPlay (44100 / 75, 44100);
  232455. readPosition = 0;
  232456. return true;
  232457. }
  232458. - (BOOL) prepareTrackForVerification: (DRTrack*) track
  232459. {
  232460. if (source != 0)
  232461. source->prepareToPlay (44100 / 75, 44100);
  232462. return true;
  232463. }
  232464. - (uint32_t) produceDataForTrack: (DRTrack*) track intoBuffer: (char*) buffer
  232465. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  232466. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  232467. {
  232468. if (source != 0)
  232469. {
  232470. const int numSamples = JUCE_NAMESPACE::jmin ((int) bufferLength / 4, (lengthInFrames * (44100 / 75)) - readPosition);
  232471. if (numSamples > 0)
  232472. {
  232473. JUCE_NAMESPACE::AudioSampleBuffer tempBuffer (2, numSamples);
  232474. JUCE_NAMESPACE::AudioSourceChannelInfo info;
  232475. info.buffer = &tempBuffer;
  232476. info.startSample = 0;
  232477. info.numSamples = numSamples;
  232478. source->getNextAudioBlock (info);
  232479. JUCE_NAMESPACE::AudioDataConverters::convertFloatToInt16LE (tempBuffer.getSampleData (0),
  232480. buffer, numSamples, 4);
  232481. JUCE_NAMESPACE::AudioDataConverters::convertFloatToInt16LE (tempBuffer.getSampleData (1),
  232482. buffer + 2, numSamples, 4);
  232483. readPosition += numSamples;
  232484. }
  232485. return numSamples * 4;
  232486. }
  232487. return 0;
  232488. }
  232489. - (uint32_t) producePreGapForTrack: (DRTrack*) track
  232490. intoBuffer: (char*) buffer length: (uint32_t) bufferLength
  232491. atAddress: (uint64_t) address blockSize: (uint32_t) blockSize
  232492. ioFlags: (uint32_t*) flags
  232493. {
  232494. zeromem (buffer, bufferLength);
  232495. return bufferLength;
  232496. }
  232497. - (BOOL) verifyDataForTrack: (DRTrack*) track inBuffer: (const char*) buffer
  232498. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  232499. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  232500. {
  232501. return true;
  232502. }
  232503. @end
  232504. BEGIN_JUCE_NAMESPACE
  232505. class AudioCDBurner::Pimpl : public Timer
  232506. {
  232507. public:
  232508. Pimpl (AudioCDBurner& owner_, const int deviceIndex)
  232509. : device (0), owner (owner_)
  232510. {
  232511. DRDevice* dev = [[DRDevice devices] objectAtIndex: deviceIndex];
  232512. if (dev != 0)
  232513. {
  232514. device = [[OpenDiskDevice alloc] initWithDRDevice: dev];
  232515. lastState = getDiskState();
  232516. startTimer (1000);
  232517. }
  232518. }
  232519. ~Pimpl()
  232520. {
  232521. stopTimer();
  232522. [device release];
  232523. }
  232524. void timerCallback()
  232525. {
  232526. const DiskState state = getDiskState();
  232527. if (state != lastState)
  232528. {
  232529. lastState = state;
  232530. owner.sendChangeMessage (&owner);
  232531. }
  232532. }
  232533. DiskState getDiskState() const
  232534. {
  232535. if ([device->device isValid])
  232536. {
  232537. NSDictionary* status = [device->device status];
  232538. NSString* state = [status objectForKey: DRDeviceMediaStateKey];
  232539. if ([state isEqualTo: DRDeviceMediaStateNone])
  232540. {
  232541. if ([[status objectForKey: DRDeviceIsTrayOpenKey] boolValue])
  232542. return trayOpen;
  232543. return noDisc;
  232544. }
  232545. if ([state isEqualTo: DRDeviceMediaStateMediaPresent])
  232546. {
  232547. if ([[[status objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceMediaBlocksFreeKey] intValue] > 0)
  232548. return writableDiskPresent;
  232549. else
  232550. return readOnlyDiskPresent;
  232551. }
  232552. }
  232553. return unknown;
  232554. }
  232555. bool openTray() { return [device->device isValid] && [device->device ejectMedia]; }
  232556. const Array<int> getAvailableWriteSpeeds() const
  232557. {
  232558. Array<int> results;
  232559. if ([device->device isValid])
  232560. {
  232561. NSArray* speeds = [[[device->device status] objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceBurnSpeedsKey];
  232562. for (unsigned int i = 0; i < [speeds count]; ++i)
  232563. {
  232564. const int kbPerSec = [[speeds objectAtIndex: i] intValue];
  232565. results.add (kbPerSec / kilobytesPerSecond1x);
  232566. }
  232567. }
  232568. return results;
  232569. }
  232570. bool setBufferUnderrunProtection (const bool shouldBeEnabled)
  232571. {
  232572. if ([device->device isValid])
  232573. {
  232574. device->underrunProtection = shouldBeEnabled;
  232575. return shouldBeEnabled && [[[device->device status] objectForKey: DRDeviceCanUnderrunProtectCDKey] boolValue];
  232576. }
  232577. return false;
  232578. }
  232579. int getNumAvailableAudioBlocks() const
  232580. {
  232581. return [[[[device->device status] objectForKey: DRDeviceMediaInfoKey]
  232582. objectForKey: DRDeviceMediaBlocksFreeKey] intValue];
  232583. }
  232584. OpenDiskDevice* device;
  232585. private:
  232586. DiskState lastState;
  232587. AudioCDBurner& owner;
  232588. };
  232589. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  232590. {
  232591. pimpl = new Pimpl (*this, deviceIndex);
  232592. }
  232593. AudioCDBurner::~AudioCDBurner()
  232594. {
  232595. }
  232596. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  232597. {
  232598. ScopedPointer <AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  232599. if (b->pimpl->device == 0)
  232600. b = 0;
  232601. return b.release();
  232602. }
  232603. static NSArray* findDiskBurnerDevices()
  232604. {
  232605. NSMutableArray* results = [NSMutableArray array];
  232606. NSArray* devs = [DRDevice devices];
  232607. if (devs != 0)
  232608. {
  232609. int num = [devs count];
  232610. int i;
  232611. for (i = 0; i < num; ++i)
  232612. {
  232613. NSDictionary* dic = [[devs objectAtIndex: i] info];
  232614. NSString* name = [dic valueForKey: DRDeviceProductNameKey];
  232615. if (name != nil)
  232616. [results addObject: name];
  232617. }
  232618. }
  232619. return results;
  232620. }
  232621. const StringArray AudioCDBurner::findAvailableDevices()
  232622. {
  232623. NSArray* names = findDiskBurnerDevices();
  232624. StringArray s;
  232625. for (unsigned int i = 0; i < [names count]; ++i)
  232626. s.add (String::fromUTF8 ([[names objectAtIndex: i] UTF8String]));
  232627. return s;
  232628. }
  232629. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  232630. {
  232631. return pimpl->getDiskState();
  232632. }
  232633. bool AudioCDBurner::isDiskPresent() const
  232634. {
  232635. return getDiskState() == writableDiskPresent;
  232636. }
  232637. bool AudioCDBurner::openTray()
  232638. {
  232639. return pimpl->openTray();
  232640. }
  232641. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  232642. {
  232643. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  232644. DiskState oldState = getDiskState();
  232645. DiskState newState = oldState;
  232646. while (newState == oldState && Time::currentTimeMillis() < timeout)
  232647. {
  232648. newState = getDiskState();
  232649. Thread::sleep (100);
  232650. }
  232651. return newState;
  232652. }
  232653. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  232654. {
  232655. return pimpl->getAvailableWriteSpeeds();
  232656. }
  232657. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  232658. {
  232659. return pimpl->setBufferUnderrunProtection (shouldBeEnabled);
  232660. }
  232661. int AudioCDBurner::getNumAvailableAudioBlocks() const
  232662. {
  232663. return pimpl->getNumAvailableAudioBlocks();
  232664. }
  232665. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamps)
  232666. {
  232667. if ([pimpl->device->device isValid])
  232668. {
  232669. [pimpl->device addSourceTrack: source numSamples: numSamps];
  232670. return true;
  232671. }
  232672. return false;
  232673. }
  232674. const String AudioCDBurner::burn (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener* listener,
  232675. bool ejectDiscAfterwards,
  232676. bool performFakeBurnForTesting,
  232677. int writeSpeed)
  232678. {
  232679. String error ("Couldn't open or write to the CD device");
  232680. if ([pimpl->device->device isValid])
  232681. {
  232682. error = String::empty;
  232683. [pimpl->device burn: listener
  232684. errorString: &error
  232685. ejectAfterwards: ejectDiscAfterwards
  232686. isFake: performFakeBurnForTesting
  232687. speed: writeSpeed];
  232688. }
  232689. return error;
  232690. }
  232691. #endif
  232692. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  232693. void AudioCDReader::ejectDisk()
  232694. {
  232695. const ScopedAutoReleasePool p;
  232696. [[NSWorkspace sharedWorkspace] unmountAndEjectDeviceAtPath: juceStringToNS (volumeDir.getFullPathName())];
  232697. }
  232698. #endif
  232699. /*** End of inlined file: juce_mac_AudioCDBurner.mm ***/
  232700. /*** Start of inlined file: juce_mac_AudioCDReader.mm ***/
  232701. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232702. // compiled on its own).
  232703. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  232704. static void juce_findCDs (Array<File>& cds)
  232705. {
  232706. File volumes ("/Volumes");
  232707. volumes.findChildFiles (cds, File::findDirectories, false);
  232708. for (int i = cds.size(); --i >= 0;)
  232709. if (! cds.getReference(i).getChildFile (".TOC.plist").exists())
  232710. cds.remove (i);
  232711. }
  232712. const StringArray AudioCDReader::getAvailableCDNames()
  232713. {
  232714. Array<File> cds;
  232715. juce_findCDs (cds);
  232716. StringArray names;
  232717. for (int i = 0; i < cds.size(); ++i)
  232718. names.add (cds.getReference(i).getFileName());
  232719. return names;
  232720. }
  232721. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  232722. {
  232723. Array<File> cds;
  232724. juce_findCDs (cds);
  232725. if (cds[index].exists())
  232726. return new AudioCDReader (cds[index]);
  232727. return 0;
  232728. }
  232729. AudioCDReader::AudioCDReader (const File& volume)
  232730. : AudioFormatReader (0, "CD Audio"),
  232731. volumeDir (volume),
  232732. currentReaderTrack (-1),
  232733. reader (0)
  232734. {
  232735. sampleRate = 44100.0;
  232736. bitsPerSample = 16;
  232737. numChannels = 2;
  232738. usesFloatingPointData = false;
  232739. refreshTrackLengths();
  232740. }
  232741. AudioCDReader::~AudioCDReader()
  232742. {
  232743. }
  232744. static int juce_getCDTrackNumber (const File& file)
  232745. {
  232746. return file.getFileName()
  232747. .initialSectionContainingOnly ("0123456789")
  232748. .getIntValue();
  232749. }
  232750. int AudioCDReader::compareElements (const File& first, const File& second)
  232751. {
  232752. const int firstTrack = juce_getCDTrackNumber (first);
  232753. const int secondTrack = juce_getCDTrackNumber (second);
  232754. jassert (firstTrack > 0 && secondTrack > 0);
  232755. return firstTrack - secondTrack;
  232756. }
  232757. void AudioCDReader::refreshTrackLengths()
  232758. {
  232759. tracks.clear();
  232760. trackStartSamples.clear();
  232761. volumeDir.findChildFiles (tracks, File::findFiles | File::ignoreHiddenFiles, false, "*.aiff");
  232762. tracks.sort (*this);
  232763. AiffAudioFormat format;
  232764. int sample = 0;
  232765. for (int i = 0; i < tracks.size(); ++i)
  232766. {
  232767. trackStartSamples.add (sample);
  232768. FileInputStream* const in = tracks.getReference(i).createInputStream();
  232769. if (in != 0)
  232770. {
  232771. ScopedPointer <AudioFormatReader> r (format.createReaderFor (in, true));
  232772. if (r != 0)
  232773. sample += (int) r->lengthInSamples;
  232774. }
  232775. }
  232776. trackStartSamples.add (sample);
  232777. lengthInSamples = sample;
  232778. }
  232779. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  232780. int64 startSampleInFile, int numSamples)
  232781. {
  232782. while (numSamples > 0)
  232783. {
  232784. int track = -1;
  232785. for (int i = 0; i < trackStartSamples.size() - 1; ++i)
  232786. {
  232787. if (startSampleInFile < trackStartSamples.getUnchecked (i + 1))
  232788. {
  232789. track = i;
  232790. break;
  232791. }
  232792. }
  232793. if (track < 0)
  232794. return false;
  232795. if (track != currentReaderTrack)
  232796. {
  232797. reader = 0;
  232798. FileInputStream* const in = tracks [track].createInputStream();
  232799. if (in != 0)
  232800. {
  232801. BufferedInputStream* const bin = new BufferedInputStream (in, 65536, true);
  232802. AiffAudioFormat format;
  232803. reader = format.createReaderFor (bin, true);
  232804. if (reader == 0)
  232805. currentReaderTrack = -1;
  232806. else
  232807. currentReaderTrack = track;
  232808. }
  232809. }
  232810. if (reader == 0)
  232811. return false;
  232812. const int startPos = (int) (startSampleInFile - trackStartSamples.getUnchecked (track));
  232813. const int numAvailable = (int) jmin ((int64) numSamples, reader->lengthInSamples - startPos);
  232814. reader->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer, startPos, numAvailable);
  232815. numSamples -= numAvailable;
  232816. startSampleInFile += numAvailable;
  232817. }
  232818. return true;
  232819. }
  232820. bool AudioCDReader::isCDStillPresent() const
  232821. {
  232822. return volumeDir.exists();
  232823. }
  232824. int AudioCDReader::getNumTracks() const
  232825. {
  232826. return tracks.size();
  232827. }
  232828. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  232829. {
  232830. return trackStartSamples [trackNum];
  232831. }
  232832. bool AudioCDReader::isTrackAudio (int trackNum) const
  232833. {
  232834. return tracks [trackNum] != File::nonexistent;
  232835. }
  232836. void AudioCDReader::enableIndexScanning (bool b)
  232837. {
  232838. // any way to do this on a Mac??
  232839. }
  232840. int AudioCDReader::getLastIndex() const
  232841. {
  232842. return 0;
  232843. }
  232844. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  232845. {
  232846. return Array <int>();
  232847. }
  232848. int AudioCDReader::getCDDBId()
  232849. {
  232850. return 0; //xxx
  232851. }
  232852. #endif
  232853. /*** End of inlined file: juce_mac_AudioCDReader.mm ***/
  232854. /*** Start of inlined file: juce_mac_MessageManager.mm ***/
  232855. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232856. // compiled on its own).
  232857. #if JUCE_INCLUDED_FILE
  232858. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  232859. for example having more than one juce plugin loaded into a host, then when a
  232860. method is called, the actual code that runs might actually be in a different module
  232861. than the one you expect... So any calls to library functions or statics that are
  232862. made inside obj-c methods will probably end up getting executed in a different DLL's
  232863. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  232864. To work around this insanity, I'm only allowing obj-c methods to make calls to
  232865. virtual methods of an object that's known to live inside the right module's space.
  232866. */
  232867. class AppDelegateRedirector
  232868. {
  232869. public:
  232870. AppDelegateRedirector()
  232871. {
  232872. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4
  232873. runLoop = CFRunLoopGetMain();
  232874. #else
  232875. runLoop = CFRunLoopGetCurrent();
  232876. #endif
  232877. CFRunLoopSourceContext sourceContext;
  232878. zerostruct (sourceContext);
  232879. sourceContext.info = this;
  232880. sourceContext.perform = runLoopSourceCallback;
  232881. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  232882. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  232883. }
  232884. virtual ~AppDelegateRedirector()
  232885. {
  232886. CFRunLoopRemoveSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  232887. CFRunLoopSourceInvalidate (runLoopSource);
  232888. CFRelease (runLoopSource);
  232889. }
  232890. virtual NSApplicationTerminateReply shouldTerminate()
  232891. {
  232892. if (JUCEApplication::getInstance() != 0)
  232893. {
  232894. JUCEApplication::getInstance()->systemRequestedQuit();
  232895. return NSTerminateCancel;
  232896. }
  232897. return NSTerminateNow;
  232898. }
  232899. virtual BOOL openFile (const NSString* filename)
  232900. {
  232901. if (JUCEApplication::getInstance() != 0)
  232902. {
  232903. JUCEApplication::getInstance()->anotherInstanceStarted (nsStringToJuce (filename));
  232904. return YES;
  232905. }
  232906. return NO;
  232907. }
  232908. virtual void openFiles (NSArray* filenames)
  232909. {
  232910. StringArray files;
  232911. for (unsigned int i = 0; i < [filenames count]; ++i)
  232912. {
  232913. String filename (nsStringToJuce ((NSString*) [filenames objectAtIndex: i]));
  232914. if (filename.containsChar (' '))
  232915. filename = filename.quoted('"');
  232916. files.add (filename);
  232917. }
  232918. if (files.size() > 0 && JUCEApplication::getInstance() != 0)
  232919. {
  232920. JUCEApplication::getInstance()->anotherInstanceStarted (files.joinIntoString (" "));
  232921. }
  232922. }
  232923. virtual void focusChanged()
  232924. {
  232925. juce_HandleProcessFocusChange();
  232926. }
  232927. struct CallbackMessagePayload
  232928. {
  232929. MessageCallbackFunction* function;
  232930. void* parameter;
  232931. void* volatile result;
  232932. bool volatile hasBeenExecuted;
  232933. };
  232934. virtual void performCallback (CallbackMessagePayload* pl)
  232935. {
  232936. pl->result = (*pl->function) (pl->parameter);
  232937. pl->hasBeenExecuted = true;
  232938. }
  232939. virtual void deleteSelf()
  232940. {
  232941. delete this;
  232942. }
  232943. void postMessage (Message* const m)
  232944. {
  232945. messages.add (m);
  232946. CFRunLoopSourceSignal (runLoopSource);
  232947. CFRunLoopWakeUp (runLoop);
  232948. }
  232949. private:
  232950. CFRunLoopRef runLoop;
  232951. CFRunLoopSourceRef runLoopSource;
  232952. OwnedArray <Message, CriticalSection> messages;
  232953. void runLoopCallback()
  232954. {
  232955. int numDispatched = 0;
  232956. do
  232957. {
  232958. Message* const nextMessage = messages.removeAndReturn (0);
  232959. if (nextMessage == 0)
  232960. return;
  232961. const ScopedAutoReleasePool pool;
  232962. MessageManager::getInstance()->deliverMessage (nextMessage);
  232963. } while (++numDispatched <= 4);
  232964. CFRunLoopSourceSignal (runLoopSource);
  232965. CFRunLoopWakeUp (runLoop);
  232966. }
  232967. static void runLoopSourceCallback (void* info)
  232968. {
  232969. static_cast <AppDelegateRedirector*> (info)->runLoopCallback();
  232970. }
  232971. };
  232972. END_JUCE_NAMESPACE
  232973. using namespace JUCE_NAMESPACE;
  232974. #define JuceAppDelegate MakeObjCClassName(JuceAppDelegate)
  232975. @interface JuceAppDelegate : NSObject
  232976. {
  232977. @private
  232978. id oldDelegate;
  232979. @public
  232980. AppDelegateRedirector* redirector;
  232981. }
  232982. - (JuceAppDelegate*) init;
  232983. - (void) dealloc;
  232984. - (BOOL) application: (NSApplication*) theApplication openFile: (NSString*) filename;
  232985. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames;
  232986. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app;
  232987. - (void) applicationDidBecomeActive: (NSNotification*) aNotification;
  232988. - (void) applicationDidResignActive: (NSNotification*) aNotification;
  232989. - (void) applicationWillUnhide: (NSNotification*) aNotification;
  232990. - (void) performCallback: (id) info;
  232991. - (void) dummyMethod;
  232992. @end
  232993. @implementation JuceAppDelegate
  232994. - (JuceAppDelegate*) init
  232995. {
  232996. [super init];
  232997. redirector = new AppDelegateRedirector();
  232998. NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
  232999. if (JUCEApplication::getInstance() != 0)
  233000. {
  233001. oldDelegate = [NSApp delegate];
  233002. [NSApp setDelegate: self];
  233003. }
  233004. else
  233005. {
  233006. oldDelegate = 0;
  233007. [center addObserver: self selector: @selector (applicationDidResignActive:)
  233008. name: NSApplicationDidResignActiveNotification object: NSApp];
  233009. [center addObserver: self selector: @selector (applicationDidBecomeActive:)
  233010. name: NSApplicationDidBecomeActiveNotification object: NSApp];
  233011. [center addObserver: self selector: @selector (applicationWillUnhide:)
  233012. name: NSApplicationWillUnhideNotification object: NSApp];
  233013. }
  233014. return self;
  233015. }
  233016. - (void) dealloc
  233017. {
  233018. if (oldDelegate != 0)
  233019. [NSApp setDelegate: oldDelegate];
  233020. redirector->deleteSelf();
  233021. [super dealloc];
  233022. }
  233023. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app
  233024. {
  233025. (void) app;
  233026. return redirector->shouldTerminate();
  233027. }
  233028. - (BOOL) application: (NSApplication*) app openFile: (NSString*) filename
  233029. {
  233030. (void) app;
  233031. return redirector->openFile (filename);
  233032. }
  233033. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames
  233034. {
  233035. (void) sender;
  233036. return redirector->openFiles (filenames);
  233037. }
  233038. - (void) applicationDidBecomeActive: (NSNotification*) notification
  233039. {
  233040. (void) notification;
  233041. redirector->focusChanged();
  233042. }
  233043. - (void) applicationDidResignActive: (NSNotification*) notification
  233044. {
  233045. (void) notification;
  233046. redirector->focusChanged();
  233047. }
  233048. - (void) applicationWillUnhide: (NSNotification*) notification
  233049. {
  233050. (void) notification;
  233051. redirector->focusChanged();
  233052. }
  233053. - (void) performCallback: (id) info
  233054. {
  233055. if ([info isKindOfClass: [NSData class]])
  233056. {
  233057. AppDelegateRedirector::CallbackMessagePayload* pl
  233058. = (AppDelegateRedirector::CallbackMessagePayload*) [((NSData*) info) bytes];
  233059. if (pl != 0)
  233060. redirector->performCallback (pl);
  233061. }
  233062. else
  233063. {
  233064. jassertfalse; // should never get here!
  233065. }
  233066. }
  233067. - (void) dummyMethod {} // (used as a way of running a dummy thread)
  233068. @end
  233069. BEGIN_JUCE_NAMESPACE
  233070. static JuceAppDelegate* juceAppDelegate = 0;
  233071. void MessageManager::runDispatchLoop()
  233072. {
  233073. if (! quitMessagePosted) // check that the quit message wasn't already posted..
  233074. {
  233075. const ScopedAutoReleasePool pool;
  233076. // must only be called by the message thread!
  233077. jassert (isThisTheMessageThread());
  233078. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  233079. @try
  233080. {
  233081. [NSApp run];
  233082. }
  233083. @catch (NSException* e)
  233084. {
  233085. // An AppKit exception will kill the app, but at least this provides a chance to log it.,
  233086. std::runtime_error ex (std::string ("NSException: ") + [[e name] UTF8String] + ", Reason:" + [[e reason] UTF8String]);
  233087. JUCEApplication::sendUnhandledException (&ex, __FILE__, __LINE__);
  233088. }
  233089. @finally
  233090. {
  233091. }
  233092. #else
  233093. [NSApp run];
  233094. #endif
  233095. }
  233096. }
  233097. void MessageManager::stopDispatchLoop()
  233098. {
  233099. quitMessagePosted = true;
  233100. [NSApp stop: nil];
  233101. [NSApp activateIgnoringOtherApps: YES]; // (if the app is inactive, it sits there and ignores the quit request until the next time it gets activated)
  233102. [NSEvent startPeriodicEventsAfterDelay: 0 withPeriod: 0.1];
  233103. }
  233104. static bool isEventBlockedByModalComps (NSEvent* e)
  233105. {
  233106. if (Component::getNumCurrentlyModalComponents() == 0)
  233107. return false;
  233108. NSWindow* const w = [e window];
  233109. if (w == 0 || [w worksWhenModal])
  233110. return false;
  233111. bool isKey = false, isInputAttempt = false;
  233112. switch ([e type])
  233113. {
  233114. case NSKeyDown:
  233115. case NSKeyUp:
  233116. isKey = isInputAttempt = true;
  233117. break;
  233118. case NSLeftMouseDown:
  233119. case NSRightMouseDown:
  233120. case NSOtherMouseDown:
  233121. isInputAttempt = true;
  233122. break;
  233123. case NSLeftMouseDragged:
  233124. case NSRightMouseDragged:
  233125. case NSLeftMouseUp:
  233126. case NSRightMouseUp:
  233127. case NSOtherMouseUp:
  233128. case NSOtherMouseDragged:
  233129. if (Desktop::getInstance().getDraggingMouseSource(0) != 0)
  233130. return false;
  233131. break;
  233132. case NSMouseMoved:
  233133. case NSMouseEntered:
  233134. case NSMouseExited:
  233135. case NSCursorUpdate:
  233136. case NSScrollWheel:
  233137. case NSTabletPoint:
  233138. case NSTabletProximity:
  233139. break;
  233140. default:
  233141. return false;
  233142. }
  233143. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  233144. {
  233145. ComponentPeer* const peer = ComponentPeer::getPeer (i);
  233146. NSView* const compView = (NSView*) peer->getNativeHandle();
  233147. if ([compView window] == w)
  233148. {
  233149. if (isKey)
  233150. {
  233151. if (compView == [w firstResponder])
  233152. return false;
  233153. }
  233154. else
  233155. {
  233156. if (NSPointInRect ([compView convertPoint: [e locationInWindow] fromView: nil],
  233157. [compView bounds]))
  233158. return false;
  233159. }
  233160. }
  233161. }
  233162. if (isInputAttempt)
  233163. {
  233164. if (! [NSApp isActive])
  233165. [NSApp activateIgnoringOtherApps: YES];
  233166. Component* const modal = Component::getCurrentlyModalComponent (0);
  233167. if (modal != 0)
  233168. modal->inputAttemptWhenModal();
  233169. }
  233170. return true;
  233171. }
  233172. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  233173. {
  233174. const ScopedAutoReleasePool pool;
  233175. jassert (isThisTheMessageThread()); // must only be called by the message thread
  233176. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  233177. while (! quitMessagePosted)
  233178. {
  233179. const ScopedAutoReleasePool pool2;
  233180. CFRunLoopRunInMode (kCFRunLoopDefaultMode, 0.001, true);
  233181. NSEvent* e = [NSApp nextEventMatchingMask: NSAnyEventMask
  233182. untilDate: [NSDate dateWithTimeIntervalSinceNow: 0.001]
  233183. inMode: NSDefaultRunLoopMode
  233184. dequeue: YES];
  233185. if (e != 0 && ! isEventBlockedByModalComps (e))
  233186. [NSApp sendEvent: e];
  233187. if (Time::getMillisecondCounter() >= endTime)
  233188. break;
  233189. }
  233190. return ! quitMessagePosted;
  233191. }
  233192. void MessageManager::doPlatformSpecificInitialisation()
  233193. {
  233194. if (juceAppDelegate == 0)
  233195. juceAppDelegate = [[JuceAppDelegate alloc] init];
  233196. // This launches a dummy thread, which forces Cocoa to initialise NSThreads
  233197. // correctly (needed prior to 10.5)
  233198. if (! [NSThread isMultiThreaded])
  233199. [NSThread detachNewThreadSelector: @selector (dummyMethod)
  233200. toTarget: juceAppDelegate
  233201. withObject: nil];
  233202. initialiseMainMenu();
  233203. }
  233204. void MessageManager::doPlatformSpecificShutdown()
  233205. {
  233206. if (juceAppDelegate != 0)
  233207. {
  233208. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceAppDelegate];
  233209. [[NSNotificationCenter defaultCenter] removeObserver: juceAppDelegate];
  233210. [juceAppDelegate release];
  233211. juceAppDelegate = 0;
  233212. }
  233213. }
  233214. bool juce_postMessageToSystemQueue (Message* message)
  233215. {
  233216. juceAppDelegate->redirector->postMessage (message);
  233217. return true;
  233218. }
  233219. void MessageManager::broadcastMessage (const String& value) throw()
  233220. {
  233221. }
  233222. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  233223. void* data)
  233224. {
  233225. if (isThisTheMessageThread())
  233226. {
  233227. return (*callback) (data);
  233228. }
  233229. else
  233230. {
  233231. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  233232. // deadlock because the message manager is blocked from running, so can never
  233233. // call your function..
  233234. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  233235. const ScopedAutoReleasePool pool;
  233236. AppDelegateRedirector::CallbackMessagePayload cmp;
  233237. cmp.function = callback;
  233238. cmp.parameter = data;
  233239. cmp.result = 0;
  233240. cmp.hasBeenExecuted = false;
  233241. [juceAppDelegate performSelectorOnMainThread: @selector (performCallback:)
  233242. withObject: [NSData dataWithBytesNoCopy: &cmp
  233243. length: sizeof (cmp)
  233244. freeWhenDone: NO]
  233245. waitUntilDone: YES];
  233246. return cmp.result;
  233247. }
  233248. }
  233249. #endif
  233250. /*** End of inlined file: juce_mac_MessageManager.mm ***/
  233251. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  233252. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233253. // compiled on its own).
  233254. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  233255. #if JUCE_MAC
  233256. END_JUCE_NAMESPACE
  233257. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  233258. @interface DownloadClickDetector : NSObject
  233259. {
  233260. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  233261. }
  233262. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  233263. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  233264. request: (NSURLRequest*) request
  233265. frame: (WebFrame*) frame
  233266. decisionListener: (id<WebPolicyDecisionListener>) listener;
  233267. @end
  233268. @implementation DownloadClickDetector
  233269. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  233270. {
  233271. [super init];
  233272. ownerComponent = ownerComponent_;
  233273. return self;
  233274. }
  233275. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  233276. request: (NSURLRequest*) request
  233277. frame: (WebFrame*) frame
  233278. decisionListener: (id <WebPolicyDecisionListener>) listener
  233279. {
  233280. (void) sender;
  233281. (void) request;
  233282. (void) frame;
  233283. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  233284. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  233285. [listener use];
  233286. else
  233287. [listener ignore];
  233288. }
  233289. @end
  233290. BEGIN_JUCE_NAMESPACE
  233291. class WebBrowserComponentInternal : public NSViewComponent
  233292. {
  233293. public:
  233294. WebBrowserComponentInternal (WebBrowserComponent* owner)
  233295. {
  233296. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  233297. frameName: @""
  233298. groupName: @""];
  233299. setView (webView);
  233300. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  233301. [webView setPolicyDelegate: clickListener];
  233302. }
  233303. ~WebBrowserComponentInternal()
  233304. {
  233305. [webView setPolicyDelegate: nil];
  233306. [clickListener release];
  233307. setView (0);
  233308. }
  233309. void goToURL (const String& url,
  233310. const StringArray* headers,
  233311. const MemoryBlock* postData)
  233312. {
  233313. NSMutableURLRequest* r
  233314. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  233315. cachePolicy: NSURLRequestUseProtocolCachePolicy
  233316. timeoutInterval: 30.0];
  233317. if (postData != 0 && postData->getSize() > 0)
  233318. {
  233319. [r setHTTPMethod: @"POST"];
  233320. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  233321. length: postData->getSize()]];
  233322. }
  233323. if (headers != 0)
  233324. {
  233325. for (int i = 0; i < headers->size(); ++i)
  233326. {
  233327. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  233328. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  233329. [r setValue: juceStringToNS (headerValue)
  233330. forHTTPHeaderField: juceStringToNS (headerName)];
  233331. }
  233332. }
  233333. stop();
  233334. [[webView mainFrame] loadRequest: r];
  233335. }
  233336. void goBack()
  233337. {
  233338. [webView goBack];
  233339. }
  233340. void goForward()
  233341. {
  233342. [webView goForward];
  233343. }
  233344. void stop()
  233345. {
  233346. [webView stopLoading: nil];
  233347. }
  233348. void refresh()
  233349. {
  233350. [webView reload: nil];
  233351. }
  233352. private:
  233353. WebView* webView;
  233354. DownloadClickDetector* clickListener;
  233355. };
  233356. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  233357. : browser (0),
  233358. blankPageShown (false),
  233359. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  233360. {
  233361. setOpaque (true);
  233362. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  233363. }
  233364. WebBrowserComponent::~WebBrowserComponent()
  233365. {
  233366. deleteAndZero (browser);
  233367. }
  233368. void WebBrowserComponent::goToURL (const String& url,
  233369. const StringArray* headers,
  233370. const MemoryBlock* postData)
  233371. {
  233372. lastURL = url;
  233373. lastHeaders.clear();
  233374. if (headers != 0)
  233375. lastHeaders = *headers;
  233376. lastPostData.setSize (0);
  233377. if (postData != 0)
  233378. lastPostData = *postData;
  233379. blankPageShown = false;
  233380. browser->goToURL (url, headers, postData);
  233381. }
  233382. void WebBrowserComponent::stop()
  233383. {
  233384. browser->stop();
  233385. }
  233386. void WebBrowserComponent::goBack()
  233387. {
  233388. lastURL = String::empty;
  233389. blankPageShown = false;
  233390. browser->goBack();
  233391. }
  233392. void WebBrowserComponent::goForward()
  233393. {
  233394. lastURL = String::empty;
  233395. browser->goForward();
  233396. }
  233397. void WebBrowserComponent::refresh()
  233398. {
  233399. browser->refresh();
  233400. }
  233401. void WebBrowserComponent::paint (Graphics&)
  233402. {
  233403. }
  233404. void WebBrowserComponent::checkWindowAssociation()
  233405. {
  233406. if (isShowing())
  233407. {
  233408. if (blankPageShown)
  233409. goBack();
  233410. }
  233411. else
  233412. {
  233413. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  233414. {
  233415. // when the component becomes invisible, some stuff like flash
  233416. // carries on playing audio, so we need to force it onto a blank
  233417. // page to avoid this, (and send it back when it's made visible again).
  233418. blankPageShown = true;
  233419. browser->goToURL ("about:blank", 0, 0);
  233420. }
  233421. }
  233422. }
  233423. void WebBrowserComponent::reloadLastURL()
  233424. {
  233425. if (lastURL.isNotEmpty())
  233426. {
  233427. goToURL (lastURL, &lastHeaders, &lastPostData);
  233428. lastURL = String::empty;
  233429. }
  233430. }
  233431. void WebBrowserComponent::parentHierarchyChanged()
  233432. {
  233433. checkWindowAssociation();
  233434. }
  233435. void WebBrowserComponent::resized()
  233436. {
  233437. browser->setSize (getWidth(), getHeight());
  233438. }
  233439. void WebBrowserComponent::visibilityChanged()
  233440. {
  233441. checkWindowAssociation();
  233442. }
  233443. bool WebBrowserComponent::pageAboutToLoad (const String&)
  233444. {
  233445. return true;
  233446. }
  233447. #else
  233448. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  233449. {
  233450. }
  233451. WebBrowserComponent::~WebBrowserComponent()
  233452. {
  233453. }
  233454. void WebBrowserComponent::goToURL (const String& url,
  233455. const StringArray* headers,
  233456. const MemoryBlock* postData)
  233457. {
  233458. }
  233459. void WebBrowserComponent::stop()
  233460. {
  233461. }
  233462. void WebBrowserComponent::goBack()
  233463. {
  233464. }
  233465. void WebBrowserComponent::goForward()
  233466. {
  233467. }
  233468. void WebBrowserComponent::refresh()
  233469. {
  233470. }
  233471. void WebBrowserComponent::paint (Graphics& g)
  233472. {
  233473. }
  233474. void WebBrowserComponent::checkWindowAssociation()
  233475. {
  233476. }
  233477. void WebBrowserComponent::reloadLastURL()
  233478. {
  233479. }
  233480. void WebBrowserComponent::parentHierarchyChanged()
  233481. {
  233482. }
  233483. void WebBrowserComponent::resized()
  233484. {
  233485. }
  233486. void WebBrowserComponent::visibilityChanged()
  233487. {
  233488. }
  233489. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  233490. {
  233491. return true;
  233492. }
  233493. #endif
  233494. #endif
  233495. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  233496. /*** Start of inlined file: juce_mac_CoreAudio.cpp ***/
  233497. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233498. // compiled on its own).
  233499. #if JUCE_INCLUDED_FILE
  233500. #ifndef JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  233501. #define JUCE_COREAUDIO_ERROR_LOGGING_ENABLED 1
  233502. #endif
  233503. #undef log
  233504. #if JUCE_COREAUDIO_LOGGING_ENABLED
  233505. #define log(a) Logger::writeToLog (a)
  233506. #else
  233507. #define log(a)
  233508. #endif
  233509. #undef OK
  233510. #if JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  233511. static bool logAnyErrors_CoreAudio (const OSStatus err, const int lineNum)
  233512. {
  233513. if (err == noErr)
  233514. return true;
  233515. Logger::writeToLog ("CoreAudio error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  233516. jassertfalse;
  233517. return false;
  233518. }
  233519. #define OK(a) logAnyErrors_CoreAudio (a, __LINE__)
  233520. #else
  233521. #define OK(a) (a == noErr)
  233522. #endif
  233523. class CoreAudioInternal : public Timer
  233524. {
  233525. public:
  233526. CoreAudioInternal (AudioDeviceID id)
  233527. : inputLatency (0),
  233528. outputLatency (0),
  233529. callback (0),
  233530. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  233531. audioProcID (0),
  233532. #endif
  233533. isSlaveDevice (false),
  233534. deviceID (id),
  233535. started (false),
  233536. sampleRate (0),
  233537. bufferSize (512),
  233538. numInputChans (0),
  233539. numOutputChans (0),
  233540. callbacksAllowed (true),
  233541. numInputChannelInfos (0),
  233542. numOutputChannelInfos (0)
  233543. {
  233544. jassert (deviceID != 0);
  233545. updateDetailsFromDevice();
  233546. AudioObjectPropertyAddress pa;
  233547. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  233548. pa.mScope = kAudioObjectPropertyScopeWildcard;
  233549. pa.mElement = kAudioObjectPropertyElementWildcard;
  233550. AudioObjectAddPropertyListener (deviceID, &pa, deviceListenerProc, this);
  233551. }
  233552. ~CoreAudioInternal()
  233553. {
  233554. AudioObjectPropertyAddress pa;
  233555. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  233556. pa.mScope = kAudioObjectPropertyScopeWildcard;
  233557. pa.mElement = kAudioObjectPropertyElementWildcard;
  233558. AudioObjectRemovePropertyListener (deviceID, &pa, deviceListenerProc, this);
  233559. stop (false);
  233560. }
  233561. void allocateTempBuffers()
  233562. {
  233563. const int tempBufSize = bufferSize + 4;
  233564. audioBuffer.calloc ((numInputChans + numOutputChans) * tempBufSize);
  233565. tempInputBuffers.calloc (numInputChans + 2);
  233566. tempOutputBuffers.calloc (numOutputChans + 2);
  233567. int i, count = 0;
  233568. for (i = 0; i < numInputChans; ++i)
  233569. tempInputBuffers[i] = audioBuffer + count++ * tempBufSize;
  233570. for (i = 0; i < numOutputChans; ++i)
  233571. tempOutputBuffers[i] = audioBuffer + count++ * tempBufSize;
  233572. }
  233573. // returns the number of actual available channels
  233574. void fillInChannelInfo (const bool input)
  233575. {
  233576. int chanNum = 0;
  233577. UInt32 size;
  233578. AudioObjectPropertyAddress pa;
  233579. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  233580. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  233581. pa.mElement = kAudioObjectPropertyElementMaster;
  233582. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  233583. {
  233584. HeapBlock <AudioBufferList> bufList;
  233585. bufList.calloc (size, 1);
  233586. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  233587. {
  233588. const int numStreams = bufList->mNumberBuffers;
  233589. for (int i = 0; i < numStreams; ++i)
  233590. {
  233591. const AudioBuffer& b = bufList->mBuffers[i];
  233592. for (unsigned int j = 0; j < b.mNumberChannels; ++j)
  233593. {
  233594. String name;
  233595. {
  233596. char channelName [256];
  233597. zerostruct (channelName);
  233598. UInt32 nameSize = sizeof (channelName);
  233599. UInt32 channelNum = chanNum + 1;
  233600. pa.mSelector = kAudioDevicePropertyChannelName;
  233601. if (AudioObjectGetPropertyData (deviceID, &pa, sizeof (channelNum), &channelNum, &nameSize, channelName) == noErr)
  233602. name = String::fromUTF8 (channelName, nameSize);
  233603. }
  233604. if (input)
  233605. {
  233606. if (activeInputChans[chanNum])
  233607. {
  233608. inputChannelInfo [numInputChannelInfos].streamNum = i;
  233609. inputChannelInfo [numInputChannelInfos].dataOffsetSamples = j;
  233610. inputChannelInfo [numInputChannelInfos].dataStrideSamples = b.mNumberChannels;
  233611. ++numInputChannelInfos;
  233612. }
  233613. if (name.isEmpty())
  233614. name << "Input " << (chanNum + 1);
  233615. inChanNames.add (name);
  233616. }
  233617. else
  233618. {
  233619. if (activeOutputChans[chanNum])
  233620. {
  233621. outputChannelInfo [numOutputChannelInfos].streamNum = i;
  233622. outputChannelInfo [numOutputChannelInfos].dataOffsetSamples = j;
  233623. outputChannelInfo [numOutputChannelInfos].dataStrideSamples = b.mNumberChannels;
  233624. ++numOutputChannelInfos;
  233625. }
  233626. if (name.isEmpty())
  233627. name << "Output " << (chanNum + 1);
  233628. outChanNames.add (name);
  233629. }
  233630. ++chanNum;
  233631. }
  233632. }
  233633. }
  233634. }
  233635. }
  233636. void updateDetailsFromDevice()
  233637. {
  233638. stopTimer();
  233639. if (deviceID == 0)
  233640. return;
  233641. const ScopedLock sl (callbackLock);
  233642. Float64 sr;
  233643. UInt32 size = sizeof (Float64);
  233644. AudioObjectPropertyAddress pa;
  233645. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  233646. pa.mScope = kAudioObjectPropertyScopeWildcard;
  233647. pa.mElement = kAudioObjectPropertyElementMaster;
  233648. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &sr)))
  233649. sampleRate = sr;
  233650. UInt32 framesPerBuf;
  233651. size = sizeof (framesPerBuf);
  233652. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  233653. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &framesPerBuf)))
  233654. {
  233655. bufferSize = framesPerBuf;
  233656. allocateTempBuffers();
  233657. }
  233658. bufferSizes.clear();
  233659. pa.mSelector = kAudioDevicePropertyBufferFrameSizeRange;
  233660. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  233661. {
  233662. HeapBlock <AudioValueRange> ranges;
  233663. ranges.calloc (size, 1);
  233664. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  233665. {
  233666. bufferSizes.add ((int) ranges[0].mMinimum);
  233667. for (int i = 32; i < 2048; i += 32)
  233668. {
  233669. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  233670. {
  233671. if (i >= ranges[j].mMinimum && i <= ranges[j].mMaximum)
  233672. {
  233673. bufferSizes.addIfNotAlreadyThere (i);
  233674. break;
  233675. }
  233676. }
  233677. }
  233678. if (bufferSize > 0)
  233679. bufferSizes.addIfNotAlreadyThere (bufferSize);
  233680. }
  233681. }
  233682. if (bufferSizes.size() == 0 && bufferSize > 0)
  233683. bufferSizes.add (bufferSize);
  233684. sampleRates.clear();
  233685. const double possibleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  233686. String rates;
  233687. pa.mSelector = kAudioDevicePropertyAvailableNominalSampleRates;
  233688. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  233689. {
  233690. HeapBlock <AudioValueRange> ranges;
  233691. ranges.calloc (size, 1);
  233692. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  233693. {
  233694. for (int i = 0; i < numElementsInArray (possibleRates); ++i)
  233695. {
  233696. bool ok = false;
  233697. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  233698. if (possibleRates[i] >= ranges[j].mMinimum - 2 && possibleRates[i] <= ranges[j].mMaximum + 2)
  233699. ok = true;
  233700. if (ok)
  233701. {
  233702. sampleRates.add (possibleRates[i]);
  233703. rates << possibleRates[i] << ' ';
  233704. }
  233705. }
  233706. }
  233707. }
  233708. if (sampleRates.size() == 0 && sampleRate > 0)
  233709. {
  233710. sampleRates.add (sampleRate);
  233711. rates << sampleRate;
  233712. }
  233713. log ("sr: " + rates);
  233714. inputLatency = 0;
  233715. outputLatency = 0;
  233716. UInt32 lat;
  233717. size = sizeof (lat);
  233718. pa.mSelector = kAudioDevicePropertyLatency;
  233719. pa.mScope = kAudioDevicePropertyScopeInput;
  233720. //if (AudioDeviceGetProperty (deviceID, 0, true, kAudioDevicePropertyLatency, &size, &lat) == noErr)
  233721. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  233722. inputLatency = (int) lat;
  233723. pa.mScope = kAudioDevicePropertyScopeOutput;
  233724. size = sizeof (lat);
  233725. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  233726. outputLatency = (int) lat;
  233727. log ("lat: " + String (inputLatency) + " " + String (outputLatency));
  233728. inChanNames.clear();
  233729. outChanNames.clear();
  233730. inputChannelInfo.calloc (numInputChans + 2);
  233731. numInputChannelInfos = 0;
  233732. outputChannelInfo.calloc (numOutputChans + 2);
  233733. numOutputChannelInfos = 0;
  233734. fillInChannelInfo (true);
  233735. fillInChannelInfo (false);
  233736. }
  233737. const StringArray getSources (bool input)
  233738. {
  233739. StringArray s;
  233740. HeapBlock <OSType> types;
  233741. const int num = getAllDataSourcesForDevice (deviceID, types);
  233742. for (int i = 0; i < num; ++i)
  233743. {
  233744. AudioValueTranslation avt;
  233745. char buffer[256];
  233746. avt.mInputData = &(types[i]);
  233747. avt.mInputDataSize = sizeof (UInt32);
  233748. avt.mOutputData = buffer;
  233749. avt.mOutputDataSize = 256;
  233750. UInt32 transSize = sizeof (avt);
  233751. AudioObjectPropertyAddress pa;
  233752. pa.mSelector = kAudioDevicePropertyDataSourceNameForID;
  233753. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  233754. pa.mElement = kAudioObjectPropertyElementMaster;
  233755. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &transSize, &avt)))
  233756. {
  233757. DBG (buffer);
  233758. s.add (buffer);
  233759. }
  233760. }
  233761. return s;
  233762. }
  233763. int getCurrentSourceIndex (bool input) const
  233764. {
  233765. OSType currentSourceID = 0;
  233766. UInt32 size = sizeof (currentSourceID);
  233767. int result = -1;
  233768. AudioObjectPropertyAddress pa;
  233769. pa.mSelector = kAudioDevicePropertyDataSource;
  233770. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  233771. pa.mElement = kAudioObjectPropertyElementMaster;
  233772. if (deviceID != 0)
  233773. {
  233774. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &currentSourceID)))
  233775. {
  233776. HeapBlock <OSType> types;
  233777. const int num = getAllDataSourcesForDevice (deviceID, types);
  233778. for (int i = 0; i < num; ++i)
  233779. {
  233780. if (types[num] == currentSourceID)
  233781. {
  233782. result = i;
  233783. break;
  233784. }
  233785. }
  233786. }
  233787. }
  233788. return result;
  233789. }
  233790. void setCurrentSourceIndex (int index, bool input)
  233791. {
  233792. if (deviceID != 0)
  233793. {
  233794. HeapBlock <OSType> types;
  233795. const int num = getAllDataSourcesForDevice (deviceID, types);
  233796. if (((unsigned int) index) < (unsigned int) num)
  233797. {
  233798. AudioObjectPropertyAddress pa;
  233799. pa.mSelector = kAudioDevicePropertyDataSource;
  233800. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  233801. pa.mElement = kAudioObjectPropertyElementMaster;
  233802. OSType typeId = types[index];
  233803. OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (typeId), &typeId));
  233804. }
  233805. }
  233806. }
  233807. const String reopen (const BigInteger& inputChannels,
  233808. const BigInteger& outputChannels,
  233809. double newSampleRate,
  233810. int bufferSizeSamples)
  233811. {
  233812. String error;
  233813. log ("CoreAudio reopen");
  233814. callbacksAllowed = false;
  233815. stopTimer();
  233816. stop (false);
  233817. activeInputChans = inputChannels;
  233818. activeInputChans.setRange (inChanNames.size(),
  233819. activeInputChans.getHighestBit() + 1 - inChanNames.size(),
  233820. false);
  233821. activeOutputChans = outputChannels;
  233822. activeOutputChans.setRange (outChanNames.size(),
  233823. activeOutputChans.getHighestBit() + 1 - outChanNames.size(),
  233824. false);
  233825. numInputChans = activeInputChans.countNumberOfSetBits();
  233826. numOutputChans = activeOutputChans.countNumberOfSetBits();
  233827. // set sample rate
  233828. AudioObjectPropertyAddress pa;
  233829. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  233830. pa.mScope = kAudioObjectPropertyScopeWildcard;
  233831. pa.mElement = kAudioObjectPropertyElementMaster;
  233832. Float64 sr = newSampleRate;
  233833. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (sr), &sr)))
  233834. {
  233835. error = "Couldn't change sample rate";
  233836. }
  233837. else
  233838. {
  233839. // change buffer size
  233840. UInt32 framesPerBuf = bufferSizeSamples;
  233841. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  233842. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (framesPerBuf), &framesPerBuf)))
  233843. {
  233844. error = "Couldn't change buffer size";
  233845. }
  233846. else
  233847. {
  233848. // Annoyingly, after changing the rate and buffer size, some devices fail to
  233849. // correctly report their new settings until some random time in the future, so
  233850. // after calling updateDetailsFromDevice, we need to manually bodge these values
  233851. // to make sure we're using the correct numbers..
  233852. updateDetailsFromDevice();
  233853. sampleRate = newSampleRate;
  233854. bufferSize = bufferSizeSamples;
  233855. if (sampleRates.size() == 0)
  233856. error = "Device has no available sample-rates";
  233857. else if (bufferSizes.size() == 0)
  233858. error = "Device has no available buffer-sizes";
  233859. else if (inputDevice != 0)
  233860. error = inputDevice->reopen (inputChannels,
  233861. outputChannels,
  233862. newSampleRate,
  233863. bufferSizeSamples);
  233864. }
  233865. }
  233866. callbacksAllowed = true;
  233867. return error;
  233868. }
  233869. bool start (AudioIODeviceCallback* cb)
  233870. {
  233871. if (! started)
  233872. {
  233873. callback = 0;
  233874. if (deviceID != 0)
  233875. {
  233876. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  233877. if (OK (AudioDeviceAddIOProc (deviceID, audioIOProc, this)))
  233878. #else
  233879. if (OK (AudioDeviceCreateIOProcID (deviceID, audioIOProc, this, &audioProcID)))
  233880. #endif
  233881. {
  233882. if (OK (AudioDeviceStart (deviceID, audioIOProc)))
  233883. {
  233884. started = true;
  233885. }
  233886. else
  233887. {
  233888. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  233889. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  233890. #else
  233891. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  233892. audioProcID = 0;
  233893. #endif
  233894. }
  233895. }
  233896. }
  233897. }
  233898. if (started)
  233899. {
  233900. const ScopedLock sl (callbackLock);
  233901. callback = cb;
  233902. }
  233903. if (inputDevice != 0)
  233904. return started && inputDevice->start (cb);
  233905. else
  233906. return started;
  233907. }
  233908. void stop (bool leaveInterruptRunning)
  233909. {
  233910. {
  233911. const ScopedLock sl (callbackLock);
  233912. callback = 0;
  233913. }
  233914. if (started
  233915. && (deviceID != 0)
  233916. && ! leaveInterruptRunning)
  233917. {
  233918. OK (AudioDeviceStop (deviceID, audioIOProc));
  233919. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  233920. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  233921. #else
  233922. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  233923. audioProcID = 0;
  233924. #endif
  233925. started = false;
  233926. { const ScopedLock sl (callbackLock); }
  233927. // wait until it's definately stopped calling back..
  233928. for (int i = 40; --i >= 0;)
  233929. {
  233930. Thread::sleep (50);
  233931. UInt32 running = 0;
  233932. UInt32 size = sizeof (running);
  233933. AudioObjectPropertyAddress pa;
  233934. pa.mSelector = kAudioDevicePropertyDeviceIsRunning;
  233935. pa.mScope = kAudioObjectPropertyScopeWildcard;
  233936. pa.mElement = kAudioObjectPropertyElementMaster;
  233937. OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &running));
  233938. if (running == 0)
  233939. break;
  233940. }
  233941. const ScopedLock sl (callbackLock);
  233942. }
  233943. if (inputDevice != 0)
  233944. inputDevice->stop (leaveInterruptRunning);
  233945. }
  233946. double getSampleRate() const
  233947. {
  233948. return sampleRate;
  233949. }
  233950. int getBufferSize() const
  233951. {
  233952. return bufferSize;
  233953. }
  233954. void audioCallback (const AudioBufferList* inInputData,
  233955. AudioBufferList* outOutputData)
  233956. {
  233957. int i;
  233958. const ScopedLock sl (callbackLock);
  233959. if (callback != 0)
  233960. {
  233961. if (inputDevice == 0)
  233962. {
  233963. for (i = numInputChans; --i >= 0;)
  233964. {
  233965. const CallbackDetailsForChannel& info = inputChannelInfo[i];
  233966. float* dest = tempInputBuffers [i];
  233967. const float* src = ((const float*) inInputData->mBuffers[info.streamNum].mData)
  233968. + info.dataOffsetSamples;
  233969. const int stride = info.dataStrideSamples;
  233970. if (stride != 0) // if this is zero, info is invalid
  233971. {
  233972. for (int j = bufferSize; --j >= 0;)
  233973. {
  233974. *dest++ = *src;
  233975. src += stride;
  233976. }
  233977. }
  233978. }
  233979. }
  233980. if (! isSlaveDevice)
  233981. {
  233982. if (inputDevice == 0)
  233983. {
  233984. callback->audioDeviceIOCallback (const_cast<const float**> (tempInputBuffers.getData()),
  233985. numInputChans,
  233986. tempOutputBuffers,
  233987. numOutputChans,
  233988. bufferSize);
  233989. }
  233990. else
  233991. {
  233992. jassert (inputDevice->bufferSize == bufferSize);
  233993. // Sometimes the two linked devices seem to get their callbacks in
  233994. // parallel, so we need to lock both devices to stop the input data being
  233995. // changed while inside our callback..
  233996. const ScopedLock sl2 (inputDevice->callbackLock);
  233997. callback->audioDeviceIOCallback (const_cast<const float**> (inputDevice->tempInputBuffers.getData()),
  233998. inputDevice->numInputChans,
  233999. tempOutputBuffers,
  234000. numOutputChans,
  234001. bufferSize);
  234002. }
  234003. for (i = numOutputChans; --i >= 0;)
  234004. {
  234005. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  234006. const float* src = tempOutputBuffers [i];
  234007. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  234008. + info.dataOffsetSamples;
  234009. const int stride = info.dataStrideSamples;
  234010. if (stride != 0) // if this is zero, info is invalid
  234011. {
  234012. for (int j = bufferSize; --j >= 0;)
  234013. {
  234014. *dest = *src++;
  234015. dest += stride;
  234016. }
  234017. }
  234018. }
  234019. }
  234020. }
  234021. else
  234022. {
  234023. for (i = jmin (numOutputChans, numOutputChannelInfos); --i >= 0;)
  234024. {
  234025. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  234026. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  234027. + info.dataOffsetSamples;
  234028. const int stride = info.dataStrideSamples;
  234029. if (stride != 0) // if this is zero, info is invalid
  234030. {
  234031. for (int j = bufferSize; --j >= 0;)
  234032. {
  234033. *dest = 0.0f;
  234034. dest += stride;
  234035. }
  234036. }
  234037. }
  234038. }
  234039. }
  234040. // called by callbacks
  234041. void deviceDetailsChanged()
  234042. {
  234043. if (callbacksAllowed)
  234044. startTimer (100);
  234045. }
  234046. void timerCallback()
  234047. {
  234048. stopTimer();
  234049. log ("CoreAudio device changed callback");
  234050. const double oldSampleRate = sampleRate;
  234051. const int oldBufferSize = bufferSize;
  234052. updateDetailsFromDevice();
  234053. if (oldBufferSize != bufferSize || oldSampleRate != sampleRate)
  234054. {
  234055. callbacksAllowed = false;
  234056. stop (false);
  234057. updateDetailsFromDevice();
  234058. callbacksAllowed = true;
  234059. }
  234060. }
  234061. CoreAudioInternal* getRelatedDevice() const
  234062. {
  234063. UInt32 size = 0;
  234064. ScopedPointer <CoreAudioInternal> result;
  234065. AudioObjectPropertyAddress pa;
  234066. pa.mSelector = kAudioDevicePropertyRelatedDevices;
  234067. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234068. pa.mElement = kAudioObjectPropertyElementMaster;
  234069. if (deviceID != 0
  234070. && AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size) == noErr
  234071. && size > 0)
  234072. {
  234073. HeapBlock <AudioDeviceID> devs;
  234074. devs.calloc (size, 1);
  234075. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, devs)))
  234076. {
  234077. for (unsigned int i = 0; i < size / sizeof (AudioDeviceID); ++i)
  234078. {
  234079. if (devs[i] != deviceID && devs[i] != 0)
  234080. {
  234081. result = new CoreAudioInternal (devs[i]);
  234082. const bool thisIsInput = inChanNames.size() > 0 && outChanNames.size() == 0;
  234083. const bool otherIsInput = result->inChanNames.size() > 0 && result->outChanNames.size() == 0;
  234084. if (thisIsInput != otherIsInput
  234085. || (inChanNames.size() + outChanNames.size() == 0)
  234086. || (result->inChanNames.size() + result->outChanNames.size()) == 0)
  234087. break;
  234088. result = 0;
  234089. }
  234090. }
  234091. }
  234092. }
  234093. return result.release();
  234094. }
  234095. juce_UseDebuggingNewOperator
  234096. int inputLatency, outputLatency;
  234097. BigInteger activeInputChans, activeOutputChans;
  234098. StringArray inChanNames, outChanNames;
  234099. Array <double> sampleRates;
  234100. Array <int> bufferSizes;
  234101. AudioIODeviceCallback* callback;
  234102. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  234103. AudioDeviceIOProcID audioProcID;
  234104. #endif
  234105. ScopedPointer<CoreAudioInternal> inputDevice;
  234106. bool isSlaveDevice;
  234107. private:
  234108. CriticalSection callbackLock;
  234109. AudioDeviceID deviceID;
  234110. bool started;
  234111. double sampleRate;
  234112. int bufferSize;
  234113. HeapBlock <float> audioBuffer;
  234114. int numInputChans, numOutputChans;
  234115. bool callbacksAllowed;
  234116. struct CallbackDetailsForChannel
  234117. {
  234118. int streamNum;
  234119. int dataOffsetSamples;
  234120. int dataStrideSamples;
  234121. };
  234122. int numInputChannelInfos, numOutputChannelInfos;
  234123. HeapBlock <CallbackDetailsForChannel> inputChannelInfo, outputChannelInfo;
  234124. HeapBlock <float*> tempInputBuffers, tempOutputBuffers;
  234125. CoreAudioInternal (const CoreAudioInternal&);
  234126. CoreAudioInternal& operator= (const CoreAudioInternal&);
  234127. static OSStatus audioIOProc (AudioDeviceID /*inDevice*/,
  234128. const AudioTimeStamp* /*inNow*/,
  234129. const AudioBufferList* inInputData,
  234130. const AudioTimeStamp* /*inInputTime*/,
  234131. AudioBufferList* outOutputData,
  234132. const AudioTimeStamp* /*inOutputTime*/,
  234133. void* device)
  234134. {
  234135. static_cast <CoreAudioInternal*> (device)->audioCallback (inInputData, outOutputData);
  234136. return noErr;
  234137. }
  234138. static OSStatus deviceListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  234139. {
  234140. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  234141. switch (pa->mSelector)
  234142. {
  234143. case kAudioDevicePropertyBufferSize:
  234144. case kAudioDevicePropertyBufferFrameSize:
  234145. case kAudioDevicePropertyNominalSampleRate:
  234146. case kAudioDevicePropertyStreamFormat:
  234147. case kAudioDevicePropertyDeviceIsAlive:
  234148. intern->deviceDetailsChanged();
  234149. break;
  234150. case kAudioDevicePropertyBufferSizeRange:
  234151. case kAudioDevicePropertyVolumeScalar:
  234152. case kAudioDevicePropertyMute:
  234153. case kAudioDevicePropertyPlayThru:
  234154. case kAudioDevicePropertyDataSource:
  234155. case kAudioDevicePropertyDeviceIsRunning:
  234156. break;
  234157. }
  234158. return noErr;
  234159. }
  234160. static int getAllDataSourcesForDevice (AudioDeviceID deviceID, HeapBlock <OSType>& types)
  234161. {
  234162. AudioObjectPropertyAddress pa;
  234163. pa.mSelector = kAudioDevicePropertyDataSources;
  234164. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234165. pa.mElement = kAudioObjectPropertyElementMaster;
  234166. UInt32 size = 0;
  234167. if (deviceID != 0
  234168. && OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  234169. {
  234170. types.calloc (size, 1);
  234171. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, types)))
  234172. return size / (int) sizeof (OSType);
  234173. }
  234174. return 0;
  234175. }
  234176. };
  234177. class CoreAudioIODevice : public AudioIODevice
  234178. {
  234179. public:
  234180. CoreAudioIODevice (const String& deviceName,
  234181. AudioDeviceID inputDeviceId,
  234182. const int inputIndex_,
  234183. AudioDeviceID outputDeviceId,
  234184. const int outputIndex_)
  234185. : AudioIODevice (deviceName, "CoreAudio"),
  234186. inputIndex (inputIndex_),
  234187. outputIndex (outputIndex_),
  234188. isOpen_ (false),
  234189. isStarted (false)
  234190. {
  234191. CoreAudioInternal* device = 0;
  234192. if (outputDeviceId == 0 || outputDeviceId == inputDeviceId)
  234193. {
  234194. jassert (inputDeviceId != 0);
  234195. device = new CoreAudioInternal (inputDeviceId);
  234196. }
  234197. else
  234198. {
  234199. device = new CoreAudioInternal (outputDeviceId);
  234200. if (inputDeviceId != 0)
  234201. {
  234202. CoreAudioInternal* secondDevice = new CoreAudioInternal (inputDeviceId);
  234203. device->inputDevice = secondDevice;
  234204. secondDevice->isSlaveDevice = true;
  234205. }
  234206. }
  234207. internal = device;
  234208. AudioObjectPropertyAddress pa;
  234209. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  234210. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234211. pa.mElement = kAudioObjectPropertyElementWildcard;
  234212. AudioObjectAddPropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  234213. }
  234214. ~CoreAudioIODevice()
  234215. {
  234216. AudioObjectPropertyAddress pa;
  234217. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  234218. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234219. pa.mElement = kAudioObjectPropertyElementWildcard;
  234220. AudioObjectRemovePropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  234221. }
  234222. const StringArray getOutputChannelNames()
  234223. {
  234224. return internal->outChanNames;
  234225. }
  234226. const StringArray getInputChannelNames()
  234227. {
  234228. if (internal->inputDevice != 0)
  234229. return internal->inputDevice->inChanNames;
  234230. else
  234231. return internal->inChanNames;
  234232. }
  234233. int getNumSampleRates()
  234234. {
  234235. return internal->sampleRates.size();
  234236. }
  234237. double getSampleRate (int index)
  234238. {
  234239. return internal->sampleRates [index];
  234240. }
  234241. int getNumBufferSizesAvailable()
  234242. {
  234243. return internal->bufferSizes.size();
  234244. }
  234245. int getBufferSizeSamples (int index)
  234246. {
  234247. return internal->bufferSizes [index];
  234248. }
  234249. int getDefaultBufferSize()
  234250. {
  234251. for (int i = 0; i < getNumBufferSizesAvailable(); ++i)
  234252. if (getBufferSizeSamples(i) >= 512)
  234253. return getBufferSizeSamples(i);
  234254. return 512;
  234255. }
  234256. const String open (const BigInteger& inputChannels,
  234257. const BigInteger& outputChannels,
  234258. double sampleRate,
  234259. int bufferSizeSamples)
  234260. {
  234261. isOpen_ = true;
  234262. if (bufferSizeSamples <= 0)
  234263. bufferSizeSamples = getDefaultBufferSize();
  234264. lastError = internal->reopen (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  234265. isOpen_ = lastError.isEmpty();
  234266. return lastError;
  234267. }
  234268. void close()
  234269. {
  234270. isOpen_ = false;
  234271. internal->stop (false);
  234272. }
  234273. bool isOpen()
  234274. {
  234275. return isOpen_;
  234276. }
  234277. int getCurrentBufferSizeSamples()
  234278. {
  234279. return internal != 0 ? internal->getBufferSize() : 512;
  234280. }
  234281. double getCurrentSampleRate()
  234282. {
  234283. return internal != 0 ? internal->getSampleRate() : 0;
  234284. }
  234285. int getCurrentBitDepth()
  234286. {
  234287. return 32; // no way to find out, so just assume it's high..
  234288. }
  234289. const BigInteger getActiveOutputChannels() const
  234290. {
  234291. return internal != 0 ? internal->activeOutputChans : BigInteger();
  234292. }
  234293. const BigInteger getActiveInputChannels() const
  234294. {
  234295. BigInteger chans;
  234296. if (internal != 0)
  234297. {
  234298. chans = internal->activeInputChans;
  234299. if (internal->inputDevice != 0)
  234300. chans |= internal->inputDevice->activeInputChans;
  234301. }
  234302. return chans;
  234303. }
  234304. int getOutputLatencyInSamples()
  234305. {
  234306. if (internal == 0)
  234307. return 0;
  234308. // this seems like a good guess at getting the latency right - comparing
  234309. // this with a round-trip measurement, it gets it to within a few millisecs
  234310. // for the built-in mac soundcard
  234311. return internal->outputLatency + internal->getBufferSize() * 2;
  234312. }
  234313. int getInputLatencyInSamples()
  234314. {
  234315. if (internal == 0)
  234316. return 0;
  234317. return internal->inputLatency + internal->getBufferSize() * 2;
  234318. }
  234319. void start (AudioIODeviceCallback* callback)
  234320. {
  234321. if (internal != 0 && ! isStarted)
  234322. {
  234323. if (callback != 0)
  234324. callback->audioDeviceAboutToStart (this);
  234325. isStarted = true;
  234326. internal->start (callback);
  234327. }
  234328. }
  234329. void stop()
  234330. {
  234331. if (isStarted && internal != 0)
  234332. {
  234333. AudioIODeviceCallback* const lastCallback = internal->callback;
  234334. isStarted = false;
  234335. internal->stop (true);
  234336. if (lastCallback != 0)
  234337. lastCallback->audioDeviceStopped();
  234338. }
  234339. }
  234340. bool isPlaying()
  234341. {
  234342. if (internal->callback == 0)
  234343. isStarted = false;
  234344. return isStarted;
  234345. }
  234346. const String getLastError()
  234347. {
  234348. return lastError;
  234349. }
  234350. int inputIndex, outputIndex;
  234351. juce_UseDebuggingNewOperator
  234352. private:
  234353. ScopedPointer<CoreAudioInternal> internal;
  234354. bool isOpen_, isStarted;
  234355. String lastError;
  234356. static OSStatus hardwareListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  234357. {
  234358. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  234359. switch (pa->mSelector)
  234360. {
  234361. case kAudioHardwarePropertyDevices:
  234362. intern->deviceDetailsChanged();
  234363. break;
  234364. case kAudioHardwarePropertyDefaultOutputDevice:
  234365. case kAudioHardwarePropertyDefaultInputDevice:
  234366. case kAudioHardwarePropertyDefaultSystemOutputDevice:
  234367. break;
  234368. }
  234369. return noErr;
  234370. }
  234371. CoreAudioIODevice (const CoreAudioIODevice&);
  234372. CoreAudioIODevice& operator= (const CoreAudioIODevice&);
  234373. };
  234374. class CoreAudioIODeviceType : public AudioIODeviceType
  234375. {
  234376. public:
  234377. CoreAudioIODeviceType()
  234378. : AudioIODeviceType ("CoreAudio"),
  234379. hasScanned (false)
  234380. {
  234381. }
  234382. ~CoreAudioIODeviceType()
  234383. {
  234384. }
  234385. void scanForDevices()
  234386. {
  234387. hasScanned = true;
  234388. inputDeviceNames.clear();
  234389. outputDeviceNames.clear();
  234390. inputIds.clear();
  234391. outputIds.clear();
  234392. UInt32 size;
  234393. AudioObjectPropertyAddress pa;
  234394. pa.mSelector = kAudioHardwarePropertyDevices;
  234395. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234396. pa.mElement = kAudioObjectPropertyElementMaster;
  234397. if (OK (AudioObjectGetPropertyDataSize (kAudioObjectSystemObject, &pa, 0, 0, &size)))
  234398. {
  234399. HeapBlock <AudioDeviceID> devs;
  234400. devs.calloc (size, 1);
  234401. if (OK (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, devs)))
  234402. {
  234403. static bool alreadyLogged = false;
  234404. const int num = size / (int) sizeof (AudioDeviceID);
  234405. for (int i = 0; i < num; ++i)
  234406. {
  234407. char name [1024];
  234408. size = sizeof (name);
  234409. pa.mSelector = kAudioDevicePropertyDeviceName;
  234410. if (OK (AudioObjectGetPropertyData (devs[i], &pa, 0, 0, &size, name)))
  234411. {
  234412. const String nameString (String::fromUTF8 (name, (int) strlen (name)));
  234413. if (! alreadyLogged)
  234414. log ("CoreAudio device: " + nameString);
  234415. const int numIns = getNumChannels (devs[i], true);
  234416. const int numOuts = getNumChannels (devs[i], false);
  234417. if (numIns > 0)
  234418. {
  234419. inputDeviceNames.add (nameString);
  234420. inputIds.add (devs[i]);
  234421. }
  234422. if (numOuts > 0)
  234423. {
  234424. outputDeviceNames.add (nameString);
  234425. outputIds.add (devs[i]);
  234426. }
  234427. }
  234428. }
  234429. alreadyLogged = true;
  234430. }
  234431. }
  234432. inputDeviceNames.appendNumbersToDuplicates (false, true);
  234433. outputDeviceNames.appendNumbersToDuplicates (false, true);
  234434. }
  234435. const StringArray getDeviceNames (bool wantInputNames) const
  234436. {
  234437. jassert (hasScanned); // need to call scanForDevices() before doing this
  234438. if (wantInputNames)
  234439. return inputDeviceNames;
  234440. else
  234441. return outputDeviceNames;
  234442. }
  234443. int getDefaultDeviceIndex (bool forInput) const
  234444. {
  234445. jassert (hasScanned); // need to call scanForDevices() before doing this
  234446. AudioDeviceID deviceID;
  234447. UInt32 size = sizeof (deviceID);
  234448. // if they're asking for any input channels at all, use the default input, so we
  234449. // get the built-in mic rather than the built-in output with no inputs..
  234450. AudioObjectPropertyAddress pa;
  234451. pa.mSelector = forInput ? kAudioHardwarePropertyDefaultInputDevice : kAudioHardwarePropertyDefaultOutputDevice;
  234452. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234453. pa.mElement = kAudioObjectPropertyElementMaster;
  234454. if (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, &deviceID) == noErr)
  234455. {
  234456. if (forInput)
  234457. {
  234458. for (int i = inputIds.size(); --i >= 0;)
  234459. if (inputIds[i] == deviceID)
  234460. return i;
  234461. }
  234462. else
  234463. {
  234464. for (int i = outputIds.size(); --i >= 0;)
  234465. if (outputIds[i] == deviceID)
  234466. return i;
  234467. }
  234468. }
  234469. return 0;
  234470. }
  234471. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  234472. {
  234473. jassert (hasScanned); // need to call scanForDevices() before doing this
  234474. CoreAudioIODevice* const d = dynamic_cast <CoreAudioIODevice*> (device);
  234475. if (d == 0)
  234476. return -1;
  234477. return asInput ? d->inputIndex
  234478. : d->outputIndex;
  234479. }
  234480. bool hasSeparateInputsAndOutputs() const { return true; }
  234481. AudioIODevice* createDevice (const String& outputDeviceName,
  234482. const String& inputDeviceName)
  234483. {
  234484. jassert (hasScanned); // need to call scanForDevices() before doing this
  234485. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  234486. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  234487. String deviceName (outputDeviceName);
  234488. if (deviceName.isEmpty())
  234489. deviceName = inputDeviceName;
  234490. if (index >= 0)
  234491. return new CoreAudioIODevice (deviceName,
  234492. inputIds [inputIndex],
  234493. inputIndex,
  234494. outputIds [outputIndex],
  234495. outputIndex);
  234496. return 0;
  234497. }
  234498. juce_UseDebuggingNewOperator
  234499. private:
  234500. StringArray inputDeviceNames, outputDeviceNames;
  234501. Array <AudioDeviceID> inputIds, outputIds;
  234502. bool hasScanned;
  234503. static int getNumChannels (AudioDeviceID deviceID, bool input)
  234504. {
  234505. int total = 0;
  234506. UInt32 size;
  234507. AudioObjectPropertyAddress pa;
  234508. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  234509. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  234510. pa.mElement = kAudioObjectPropertyElementMaster;
  234511. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  234512. {
  234513. HeapBlock <AudioBufferList> bufList;
  234514. bufList.calloc (size, 1);
  234515. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  234516. {
  234517. const int numStreams = bufList->mNumberBuffers;
  234518. for (int i = 0; i < numStreams; ++i)
  234519. {
  234520. const AudioBuffer& b = bufList->mBuffers[i];
  234521. total += b.mNumberChannels;
  234522. }
  234523. }
  234524. }
  234525. return total;
  234526. }
  234527. CoreAudioIODeviceType (const CoreAudioIODeviceType&);
  234528. CoreAudioIODeviceType& operator= (const CoreAudioIODeviceType&);
  234529. };
  234530. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio()
  234531. {
  234532. return new CoreAudioIODeviceType();
  234533. }
  234534. #undef log
  234535. #endif
  234536. /*** End of inlined file: juce_mac_CoreAudio.cpp ***/
  234537. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  234538. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234539. // compiled on its own).
  234540. #if JUCE_INCLUDED_FILE
  234541. #if JUCE_MAC
  234542. #undef log
  234543. #define log(a) Logger::writeToLog(a)
  234544. static bool logAnyErrorsMidi (const OSStatus err, const int lineNum)
  234545. {
  234546. if (err == noErr)
  234547. return true;
  234548. log ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  234549. jassertfalse;
  234550. return false;
  234551. }
  234552. #undef OK
  234553. #define OK(a) logAnyErrorsMidi(a, __LINE__)
  234554. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  234555. {
  234556. String result;
  234557. CFStringRef str = 0;
  234558. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  234559. if (str != 0)
  234560. {
  234561. result = PlatformUtilities::cfStringToJuceString (str);
  234562. CFRelease (str);
  234563. str = 0;
  234564. }
  234565. MIDIEntityRef entity = 0;
  234566. MIDIEndpointGetEntity (endpoint, &entity);
  234567. if (entity == 0)
  234568. return result; // probably virtual
  234569. if (result.isEmpty())
  234570. {
  234571. // endpoint name has zero length - try the entity
  234572. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  234573. if (str != 0)
  234574. {
  234575. result += PlatformUtilities::cfStringToJuceString (str);
  234576. CFRelease (str);
  234577. str = 0;
  234578. }
  234579. }
  234580. // now consider the device's name
  234581. MIDIDeviceRef device = 0;
  234582. MIDIEntityGetDevice (entity, &device);
  234583. if (device == 0)
  234584. return result;
  234585. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  234586. if (str != 0)
  234587. {
  234588. const String s (PlatformUtilities::cfStringToJuceString (str));
  234589. CFRelease (str);
  234590. // if an external device has only one entity, throw away
  234591. // the endpoint name and just use the device name
  234592. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  234593. {
  234594. result = s;
  234595. }
  234596. else if (! result.startsWithIgnoreCase (s))
  234597. {
  234598. // prepend the device name to the entity name
  234599. result = (s + " " + result).trimEnd();
  234600. }
  234601. }
  234602. return result;
  234603. }
  234604. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  234605. {
  234606. String result;
  234607. // Does the endpoint have connections?
  234608. CFDataRef connections = 0;
  234609. int numConnections = 0;
  234610. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  234611. if (connections != 0)
  234612. {
  234613. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  234614. if (numConnections > 0)
  234615. {
  234616. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  234617. for (int i = 0; i < numConnections; ++i, ++pid)
  234618. {
  234619. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  234620. MIDIObjectRef connObject;
  234621. MIDIObjectType connObjectType;
  234622. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  234623. if (err == noErr)
  234624. {
  234625. String s;
  234626. if (connObjectType == kMIDIObjectType_ExternalSource
  234627. || connObjectType == kMIDIObjectType_ExternalDestination)
  234628. {
  234629. // Connected to an external device's endpoint (10.3 and later).
  234630. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  234631. }
  234632. else
  234633. {
  234634. // Connected to an external device (10.2) (or something else, catch-all)
  234635. CFStringRef str = 0;
  234636. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  234637. if (str != 0)
  234638. {
  234639. s = PlatformUtilities::cfStringToJuceString (str);
  234640. CFRelease (str);
  234641. }
  234642. }
  234643. if (s.isNotEmpty())
  234644. {
  234645. if (result.isNotEmpty())
  234646. result += ", ";
  234647. result += s;
  234648. }
  234649. }
  234650. }
  234651. }
  234652. CFRelease (connections);
  234653. }
  234654. if (result.isNotEmpty())
  234655. return result;
  234656. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  234657. return getEndpointName (endpoint, false);
  234658. }
  234659. const StringArray MidiOutput::getDevices()
  234660. {
  234661. StringArray s;
  234662. const ItemCount num = MIDIGetNumberOfDestinations();
  234663. for (ItemCount i = 0; i < num; ++i)
  234664. {
  234665. MIDIEndpointRef dest = MIDIGetDestination (i);
  234666. if (dest != 0)
  234667. {
  234668. String name (getConnectedEndpointName (dest));
  234669. if (name.isEmpty())
  234670. name = "<error>";
  234671. s.add (name);
  234672. }
  234673. else
  234674. {
  234675. s.add ("<error>");
  234676. }
  234677. }
  234678. return s;
  234679. }
  234680. int MidiOutput::getDefaultDeviceIndex()
  234681. {
  234682. return 0;
  234683. }
  234684. static MIDIClientRef globalMidiClient;
  234685. static bool hasGlobalClientBeenCreated = false;
  234686. static bool makeSureClientExists()
  234687. {
  234688. if (! hasGlobalClientBeenCreated)
  234689. {
  234690. String name ("JUCE");
  234691. if (JUCEApplication::getInstance() != 0)
  234692. name = JUCEApplication::getInstance()->getApplicationName();
  234693. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  234694. hasGlobalClientBeenCreated = OK (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  234695. CFRelease (appName);
  234696. }
  234697. return hasGlobalClientBeenCreated;
  234698. }
  234699. class MidiPortAndEndpoint
  234700. {
  234701. public:
  234702. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  234703. : port (port_), endPoint (endPoint_)
  234704. {
  234705. }
  234706. ~MidiPortAndEndpoint()
  234707. {
  234708. if (port != 0)
  234709. MIDIPortDispose (port);
  234710. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  234711. MIDIEndpointDispose (endPoint);
  234712. }
  234713. MIDIPortRef port;
  234714. MIDIEndpointRef endPoint;
  234715. };
  234716. MidiOutput* MidiOutput::openDevice (int index)
  234717. {
  234718. MidiOutput* mo = 0;
  234719. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  234720. {
  234721. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  234722. CFStringRef pname;
  234723. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  234724. {
  234725. log ("CoreMidi - opening out: " + PlatformUtilities::cfStringToJuceString (pname));
  234726. if (makeSureClientExists())
  234727. {
  234728. MIDIPortRef port;
  234729. if (OK (MIDIOutputPortCreate (globalMidiClient, pname, &port)))
  234730. {
  234731. mo = new MidiOutput();
  234732. mo->internal = new MidiPortAndEndpoint (port, endPoint);
  234733. }
  234734. }
  234735. CFRelease (pname);
  234736. }
  234737. }
  234738. return mo;
  234739. }
  234740. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  234741. {
  234742. MidiOutput* mo = 0;
  234743. if (makeSureClientExists())
  234744. {
  234745. MIDIEndpointRef endPoint;
  234746. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  234747. if (OK (MIDISourceCreate (globalMidiClient, name, &endPoint)))
  234748. {
  234749. mo = new MidiOutput();
  234750. mo->internal = new MidiPortAndEndpoint (0, endPoint);
  234751. }
  234752. CFRelease (name);
  234753. }
  234754. return mo;
  234755. }
  234756. MidiOutput::~MidiOutput()
  234757. {
  234758. delete (MidiPortAndEndpoint*) internal;
  234759. }
  234760. void MidiOutput::reset()
  234761. {
  234762. }
  234763. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  234764. {
  234765. return false;
  234766. }
  234767. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  234768. {
  234769. }
  234770. void MidiOutput::sendMessageNow (const MidiMessage& message)
  234771. {
  234772. MidiPortAndEndpoint* const mpe = (MidiPortAndEndpoint*) internal;
  234773. if (message.isSysEx())
  234774. {
  234775. const int maxPacketSize = 256;
  234776. int pos = 0, bytesLeft = message.getRawDataSize();
  234777. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  234778. HeapBlock <MIDIPacketList> packets;
  234779. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  234780. packets->numPackets = numPackets;
  234781. MIDIPacket* p = packets->packet;
  234782. for (int i = 0; i < numPackets; ++i)
  234783. {
  234784. p->timeStamp = 0;
  234785. p->length = jmin (maxPacketSize, bytesLeft);
  234786. memcpy (p->data, message.getRawData() + pos, p->length);
  234787. pos += p->length;
  234788. bytesLeft -= p->length;
  234789. p = MIDIPacketNext (p);
  234790. }
  234791. if (mpe->port != 0)
  234792. MIDISend (mpe->port, mpe->endPoint, packets);
  234793. else
  234794. MIDIReceived (mpe->endPoint, packets);
  234795. }
  234796. else
  234797. {
  234798. MIDIPacketList packets;
  234799. packets.numPackets = 1;
  234800. packets.packet[0].timeStamp = 0;
  234801. packets.packet[0].length = message.getRawDataSize();
  234802. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  234803. if (mpe->port != 0)
  234804. MIDISend (mpe->port, mpe->endPoint, &packets);
  234805. else
  234806. MIDIReceived (mpe->endPoint, &packets);
  234807. }
  234808. }
  234809. const StringArray MidiInput::getDevices()
  234810. {
  234811. StringArray s;
  234812. const ItemCount num = MIDIGetNumberOfSources();
  234813. for (ItemCount i = 0; i < num; ++i)
  234814. {
  234815. MIDIEndpointRef source = MIDIGetSource (i);
  234816. if (source != 0)
  234817. {
  234818. String name (getConnectedEndpointName (source));
  234819. if (name.isEmpty())
  234820. name = "<error>";
  234821. s.add (name);
  234822. }
  234823. else
  234824. {
  234825. s.add ("<error>");
  234826. }
  234827. }
  234828. return s;
  234829. }
  234830. int MidiInput::getDefaultDeviceIndex()
  234831. {
  234832. return 0;
  234833. }
  234834. struct MidiPortAndCallback
  234835. {
  234836. MidiInput* input;
  234837. MidiPortAndEndpoint* portAndEndpoint;
  234838. MidiInputCallback* callback;
  234839. MemoryBlock pendingData;
  234840. int pendingBytes;
  234841. double pendingDataTime;
  234842. bool active;
  234843. void processSysex (const uint8*& d, int& size, const double time)
  234844. {
  234845. if (*d == 0xf0)
  234846. {
  234847. pendingBytes = 0;
  234848. pendingDataTime = time;
  234849. }
  234850. pendingData.ensureSize (pendingBytes + size, false);
  234851. uint8* totalMessage = (uint8*) pendingData.getData();
  234852. uint8* dest = totalMessage + pendingBytes;
  234853. while (size > 0)
  234854. {
  234855. if (pendingBytes > 0 && *d >= 0x80)
  234856. {
  234857. if (*d >= 0xfa || *d == 0xf8)
  234858. {
  234859. callback->handleIncomingMidiMessage (input, MidiMessage (*d, time));
  234860. ++d;
  234861. --size;
  234862. }
  234863. else
  234864. {
  234865. if (*d == 0xf7)
  234866. {
  234867. *dest++ = *d++;
  234868. pendingBytes++;
  234869. --size;
  234870. }
  234871. break;
  234872. }
  234873. }
  234874. else
  234875. {
  234876. *dest++ = *d++;
  234877. pendingBytes++;
  234878. --size;
  234879. }
  234880. }
  234881. if (totalMessage [pendingBytes - 1] == 0xf7)
  234882. {
  234883. callback->handleIncomingMidiMessage (input, MidiMessage (totalMessage, pendingBytes, pendingDataTime));
  234884. pendingBytes = 0;
  234885. }
  234886. else
  234887. {
  234888. callback->handlePartialSysexMessage (input, totalMessage, pendingBytes, pendingDataTime);
  234889. }
  234890. }
  234891. };
  234892. namespace CoreMidiCallbacks
  234893. {
  234894. static CriticalSection callbackLock;
  234895. static Array<void*> activeCallbacks;
  234896. }
  234897. static void midiInputProc (const MIDIPacketList* pktlist,
  234898. void* readProcRefCon,
  234899. void* /*srcConnRefCon*/)
  234900. {
  234901. double time = Time::getMillisecondCounterHiRes() * 0.001;
  234902. const double originalTime = time;
  234903. MidiPortAndCallback* const mpc = (MidiPortAndCallback*) readProcRefCon;
  234904. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  234905. if (CoreMidiCallbacks::activeCallbacks.contains (mpc) && mpc->active)
  234906. {
  234907. const MIDIPacket* packet = &pktlist->packet[0];
  234908. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  234909. {
  234910. const uint8* d = (const uint8*) (packet->data);
  234911. int size = packet->length;
  234912. while (size > 0)
  234913. {
  234914. time = originalTime;
  234915. if (mpc->pendingBytes > 0 || d[0] == 0xf0)
  234916. {
  234917. mpc->processSysex (d, size, time);
  234918. }
  234919. else
  234920. {
  234921. int used = 0;
  234922. const MidiMessage m (d, size, used, 0, time);
  234923. if (used <= 0)
  234924. {
  234925. jassertfalse; // malformed midi message
  234926. break;
  234927. }
  234928. else
  234929. {
  234930. mpc->callback->handleIncomingMidiMessage (mpc->input, m);
  234931. }
  234932. size -= used;
  234933. d += used;
  234934. }
  234935. }
  234936. packet = MIDIPacketNext (packet);
  234937. }
  234938. }
  234939. }
  234940. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  234941. {
  234942. MidiInput* mi = 0;
  234943. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  234944. {
  234945. MIDIEndpointRef endPoint = MIDIGetSource (index);
  234946. if (endPoint != 0)
  234947. {
  234948. CFStringRef pname;
  234949. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  234950. {
  234951. log ("CoreMidi - opening inp: " + PlatformUtilities::cfStringToJuceString (pname));
  234952. if (makeSureClientExists())
  234953. {
  234954. MIDIPortRef port;
  234955. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  234956. mpc->active = false;
  234957. if (OK (MIDIInputPortCreate (globalMidiClient, pname, midiInputProc, mpc, &port)))
  234958. {
  234959. if (OK (MIDIPortConnectSource (port, endPoint, 0)))
  234960. {
  234961. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  234962. mpc->callback = callback;
  234963. mpc->pendingBytes = 0;
  234964. mpc->pendingData.ensureSize (128);
  234965. mi = new MidiInput (getDevices() [index]);
  234966. mpc->input = mi;
  234967. mi->internal = mpc;
  234968. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  234969. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  234970. }
  234971. else
  234972. {
  234973. OK (MIDIPortDispose (port));
  234974. }
  234975. }
  234976. }
  234977. }
  234978. CFRelease (pname);
  234979. }
  234980. }
  234981. return mi;
  234982. }
  234983. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  234984. {
  234985. MidiInput* mi = 0;
  234986. if (makeSureClientExists())
  234987. {
  234988. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  234989. mpc->active = false;
  234990. MIDIEndpointRef endPoint;
  234991. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  234992. if (OK (MIDIDestinationCreate (globalMidiClient, name, midiInputProc, mpc, &endPoint)))
  234993. {
  234994. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  234995. mpc->callback = callback;
  234996. mpc->pendingBytes = 0;
  234997. mpc->pendingData.ensureSize (128);
  234998. mi = new MidiInput (deviceName);
  234999. mpc->input = mi;
  235000. mi->internal = mpc;
  235001. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  235002. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  235003. }
  235004. CFRelease (name);
  235005. }
  235006. return mi;
  235007. }
  235008. MidiInput::MidiInput (const String& name_)
  235009. : name (name_)
  235010. {
  235011. }
  235012. MidiInput::~MidiInput()
  235013. {
  235014. MidiPortAndCallback* const mpc = (MidiPortAndCallback*) internal;
  235015. mpc->active = false;
  235016. {
  235017. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  235018. CoreMidiCallbacks::activeCallbacks.removeValue (mpc);
  235019. }
  235020. if (mpc->portAndEndpoint->port != 0)
  235021. OK (MIDIPortDisconnectSource (mpc->portAndEndpoint->port, mpc->portAndEndpoint->endPoint));
  235022. delete mpc->portAndEndpoint;
  235023. delete mpc;
  235024. }
  235025. void MidiInput::start()
  235026. {
  235027. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  235028. ((MidiPortAndCallback*) internal)->active = true;
  235029. }
  235030. void MidiInput::stop()
  235031. {
  235032. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  235033. ((MidiPortAndCallback*) internal)->active = false;
  235034. }
  235035. #undef log
  235036. #else
  235037. MidiOutput::~MidiOutput()
  235038. {
  235039. }
  235040. void MidiOutput::reset()
  235041. {
  235042. }
  235043. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  235044. {
  235045. return false;
  235046. }
  235047. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  235048. {
  235049. }
  235050. void MidiOutput::sendMessageNow (const MidiMessage& message)
  235051. {
  235052. }
  235053. const StringArray MidiOutput::getDevices()
  235054. {
  235055. return StringArray();
  235056. }
  235057. MidiOutput* MidiOutput::openDevice (int index)
  235058. {
  235059. return 0;
  235060. }
  235061. const StringArray MidiInput::getDevices()
  235062. {
  235063. return StringArray();
  235064. }
  235065. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  235066. {
  235067. return 0;
  235068. }
  235069. #endif
  235070. #endif
  235071. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  235072. /*** Start of inlined file: juce_mac_CameraDevice.mm ***/
  235073. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  235074. // compiled on its own).
  235075. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  235076. #if ! JUCE_QUICKTIME
  235077. #error "On the Mac, cameras use Quicktime, so if you turn on JUCE_USE_CAMERA, you also need to enable JUCE_QUICKTIME"
  235078. #endif
  235079. #define QTCaptureCallbackDelegate MakeObjCClassName(QTCaptureCallbackDelegate)
  235080. class QTCameraDeviceInteral;
  235081. END_JUCE_NAMESPACE
  235082. @interface QTCaptureCallbackDelegate : NSObject
  235083. {
  235084. @public
  235085. CameraDevice* owner;
  235086. QTCameraDeviceInteral* internal;
  235087. int64 firstPresentationTime;
  235088. int64 averageTimeOffset;
  235089. }
  235090. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner internalDev: (QTCameraDeviceInteral*) d;
  235091. - (void) dealloc;
  235092. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  235093. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  235094. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  235095. fromConnection: (QTCaptureConnection*) connection;
  235096. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  235097. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  235098. fromConnection: (QTCaptureConnection*) connection;
  235099. @end
  235100. BEGIN_JUCE_NAMESPACE
  235101. class QTCameraDeviceInteral
  235102. {
  235103. public:
  235104. QTCameraDeviceInteral (CameraDevice* owner, int index)
  235105. {
  235106. const ScopedAutoReleasePool pool;
  235107. session = [[QTCaptureSession alloc] init];
  235108. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  235109. device = (QTCaptureDevice*) [devs objectAtIndex: index];
  235110. input = 0;
  235111. audioInput = 0;
  235112. audioDevice = 0;
  235113. fileOutput = 0;
  235114. imageOutput = 0;
  235115. callbackDelegate = [[QTCaptureCallbackDelegate alloc] initWithOwner: owner
  235116. internalDev: this];
  235117. NSError* err = 0;
  235118. [device retain];
  235119. [device open: &err];
  235120. if (err == 0)
  235121. {
  235122. input = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  235123. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  235124. [session addInput: input error: &err];
  235125. if (err == 0)
  235126. {
  235127. resetFile();
  235128. imageOutput = [[QTCaptureDecompressedVideoOutput alloc] init];
  235129. [imageOutput setDelegate: callbackDelegate];
  235130. if (err == 0)
  235131. {
  235132. [session startRunning];
  235133. return;
  235134. }
  235135. }
  235136. }
  235137. openingError = nsStringToJuce ([err description]);
  235138. DBG (openingError);
  235139. }
  235140. ~QTCameraDeviceInteral()
  235141. {
  235142. [session stopRunning];
  235143. [session removeOutput: imageOutput];
  235144. [session release];
  235145. [input release];
  235146. [device release];
  235147. [audioDevice release];
  235148. [audioInput release];
  235149. [fileOutput release];
  235150. [imageOutput release];
  235151. [callbackDelegate release];
  235152. }
  235153. void resetFile()
  235154. {
  235155. [fileOutput recordToOutputFileURL: nil];
  235156. [session removeOutput: fileOutput];
  235157. [fileOutput release];
  235158. fileOutput = [[QTCaptureMovieFileOutput alloc] init];
  235159. [session removeInput: audioInput];
  235160. [audioInput release];
  235161. audioInput = 0;
  235162. [audioDevice release];
  235163. audioDevice = 0;
  235164. [fileOutput setDelegate: callbackDelegate];
  235165. }
  235166. void addDefaultAudioInput()
  235167. {
  235168. NSError* err = nil;
  235169. audioDevice = [QTCaptureDevice defaultInputDeviceWithMediaType: QTMediaTypeSound];
  235170. if ([audioDevice open: &err])
  235171. [audioDevice retain];
  235172. else
  235173. audioDevice = nil;
  235174. if (audioDevice != 0)
  235175. {
  235176. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: audioDevice];
  235177. [session addInput: audioInput error: &err];
  235178. }
  235179. }
  235180. void addListener (CameraImageListener* listenerToAdd)
  235181. {
  235182. const ScopedLock sl (listenerLock);
  235183. if (listeners.size() == 0)
  235184. [session addOutput: imageOutput error: nil];
  235185. listeners.addIfNotAlreadyThere (listenerToAdd);
  235186. }
  235187. void removeListener (CameraImageListener* listenerToRemove)
  235188. {
  235189. const ScopedLock sl (listenerLock);
  235190. listeners.removeValue (listenerToRemove);
  235191. if (listeners.size() == 0)
  235192. [session removeOutput: imageOutput];
  235193. }
  235194. void callListeners (CIImage* frame, int w, int h)
  235195. {
  235196. CoreGraphicsImage* cgImage = new CoreGraphicsImage (Image::ARGB, w, h, false);
  235197. Image image (cgImage);
  235198. CIContext* cic = [CIContext contextWithCGContext: cgImage->context options: nil];
  235199. [cic drawImage: frame inRect: CGRectMake (0, 0, w, h) fromRect: CGRectMake (0, 0, w, h)];
  235200. CGContextFlush (cgImage->context);
  235201. const ScopedLock sl (listenerLock);
  235202. for (int i = listeners.size(); --i >= 0;)
  235203. {
  235204. CameraImageListener* const l = listeners[i];
  235205. if (l != 0)
  235206. l->imageReceived (image);
  235207. }
  235208. }
  235209. QTCaptureDevice* device;
  235210. QTCaptureDeviceInput* input;
  235211. QTCaptureDevice* audioDevice;
  235212. QTCaptureDeviceInput* audioInput;
  235213. QTCaptureSession* session;
  235214. QTCaptureMovieFileOutput* fileOutput;
  235215. QTCaptureDecompressedVideoOutput* imageOutput;
  235216. QTCaptureCallbackDelegate* callbackDelegate;
  235217. String openingError;
  235218. Array<CameraImageListener*> listeners;
  235219. CriticalSection listenerLock;
  235220. };
  235221. END_JUCE_NAMESPACE
  235222. @implementation QTCaptureCallbackDelegate
  235223. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner_
  235224. internalDev: (QTCameraDeviceInteral*) d
  235225. {
  235226. [super init];
  235227. owner = owner_;
  235228. internal = d;
  235229. firstPresentationTime = 0;
  235230. averageTimeOffset = 0;
  235231. return self;
  235232. }
  235233. - (void) dealloc
  235234. {
  235235. [super dealloc];
  235236. }
  235237. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  235238. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  235239. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  235240. fromConnection: (QTCaptureConnection*) connection
  235241. {
  235242. if (internal->listeners.size() > 0)
  235243. {
  235244. const ScopedAutoReleasePool pool;
  235245. internal->callListeners ([CIImage imageWithCVImageBuffer: videoFrame],
  235246. CVPixelBufferGetWidth (videoFrame),
  235247. CVPixelBufferGetHeight (videoFrame));
  235248. }
  235249. }
  235250. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  235251. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  235252. fromConnection: (QTCaptureConnection*) connection
  235253. {
  235254. const Time now (Time::getCurrentTime());
  235255. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  235256. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: QTSampleBufferHostTimeAttribute];
  235257. #else
  235258. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: @"hostTime"];
  235259. #endif
  235260. int64 presentationTime = (hosttime != nil)
  235261. ? ((int64) AudioConvertHostTimeToNanos ([hosttime unsignedLongLongValue]) / 1000000 + 40)
  235262. : (([sampleBuffer presentationTime].timeValue * 1000) / [sampleBuffer presentationTime].timeScale + 50);
  235263. const int64 timeDiff = now.toMilliseconds() - presentationTime;
  235264. if (firstPresentationTime == 0)
  235265. {
  235266. firstPresentationTime = presentationTime;
  235267. averageTimeOffset = timeDiff;
  235268. }
  235269. else
  235270. {
  235271. averageTimeOffset = (averageTimeOffset * 120 + timeDiff * 8) / 128;
  235272. }
  235273. }
  235274. @end
  235275. BEGIN_JUCE_NAMESPACE
  235276. class QTCaptureViewerComp : public NSViewComponent
  235277. {
  235278. public:
  235279. QTCaptureViewerComp (CameraDevice* const cameraDevice, QTCameraDeviceInteral* const internal)
  235280. {
  235281. const ScopedAutoReleasePool pool;
  235282. captureView = [[QTCaptureView alloc] init];
  235283. [captureView setCaptureSession: internal->session];
  235284. setSize (640, 480); // xxx need to somehow get the movie size - how?
  235285. setView (captureView);
  235286. }
  235287. ~QTCaptureViewerComp()
  235288. {
  235289. setView (0);
  235290. [captureView setCaptureSession: nil];
  235291. [captureView release];
  235292. }
  235293. QTCaptureView* captureView;
  235294. };
  235295. CameraDevice::CameraDevice (const String& name_, int index)
  235296. : name (name_)
  235297. {
  235298. isRecording = false;
  235299. internal = new QTCameraDeviceInteral (this, index);
  235300. }
  235301. CameraDevice::~CameraDevice()
  235302. {
  235303. stopRecording();
  235304. delete static_cast <QTCameraDeviceInteral*> (internal);
  235305. internal = 0;
  235306. }
  235307. Component* CameraDevice::createViewerComponent()
  235308. {
  235309. return new QTCaptureViewerComp (this, static_cast <QTCameraDeviceInteral*> (internal));
  235310. }
  235311. const String CameraDevice::getFileExtension()
  235312. {
  235313. return ".mov";
  235314. }
  235315. void CameraDevice::startRecordingToFile (const File& file, int quality)
  235316. {
  235317. stopRecording();
  235318. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  235319. d->callbackDelegate->firstPresentationTime = 0;
  235320. file.deleteFile();
  235321. // In some versions of QT (e.g. on 10.5), if you record video without audio, the speed comes
  235322. // out wrong, so we'll put some audio in there too..,
  235323. d->addDefaultAudioInput();
  235324. [d->session addOutput: d->fileOutput error: nil];
  235325. NSEnumerator* connectionEnumerator = [[d->fileOutput connections] objectEnumerator];
  235326. for (;;)
  235327. {
  235328. QTCaptureConnection* connection = [connectionEnumerator nextObject];
  235329. if (connection == 0)
  235330. break;
  235331. QTCompressionOptions* options = 0;
  235332. NSString* mediaType = [connection mediaType];
  235333. if ([mediaType isEqualToString: QTMediaTypeVideo])
  235334. options = [QTCompressionOptions compressionOptionsWithIdentifier:
  235335. quality >= 1 ? @"QTCompressionOptionsSD480SizeH264Video"
  235336. : @"QTCompressionOptions240SizeH264Video"];
  235337. else if ([mediaType isEqualToString: QTMediaTypeSound])
  235338. options = [QTCompressionOptions compressionOptionsWithIdentifier: @"QTCompressionOptionsHighQualityAACAudio"];
  235339. [d->fileOutput setCompressionOptions: options forConnection: connection];
  235340. }
  235341. [d->fileOutput recordToOutputFileURL: [NSURL fileURLWithPath: juceStringToNS (file.getFullPathName())]];
  235342. isRecording = true;
  235343. }
  235344. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  235345. {
  235346. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  235347. if (d->callbackDelegate->firstPresentationTime != 0)
  235348. return Time (d->callbackDelegate->firstPresentationTime + d->callbackDelegate->averageTimeOffset);
  235349. return Time();
  235350. }
  235351. void CameraDevice::stopRecording()
  235352. {
  235353. if (isRecording)
  235354. {
  235355. static_cast <QTCameraDeviceInteral*> (internal)->resetFile();
  235356. isRecording = false;
  235357. }
  235358. }
  235359. void CameraDevice::addListener (CameraImageListener* listenerToAdd)
  235360. {
  235361. if (listenerToAdd != 0)
  235362. static_cast <QTCameraDeviceInteral*> (internal)->addListener (listenerToAdd);
  235363. }
  235364. void CameraDevice::removeListener (CameraImageListener* listenerToRemove)
  235365. {
  235366. if (listenerToRemove != 0)
  235367. static_cast <QTCameraDeviceInteral*> (internal)->removeListener (listenerToRemove);
  235368. }
  235369. const StringArray CameraDevice::getAvailableDevices()
  235370. {
  235371. const ScopedAutoReleasePool pool;
  235372. StringArray results;
  235373. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  235374. for (int i = 0; i < (int) [devs count]; ++i)
  235375. {
  235376. QTCaptureDevice* dev = (QTCaptureDevice*) [devs objectAtIndex: i];
  235377. results.add (nsStringToJuce ([dev localizedDisplayName]));
  235378. }
  235379. return results;
  235380. }
  235381. CameraDevice* CameraDevice::openDevice (int index,
  235382. int minWidth, int minHeight,
  235383. int maxWidth, int maxHeight)
  235384. {
  235385. ScopedPointer <CameraDevice> d (new CameraDevice (getAvailableDevices() [index], index));
  235386. if (static_cast <QTCameraDeviceInteral*> (d->internal)->openingError.isEmpty())
  235387. return d.release();
  235388. return 0;
  235389. }
  235390. #endif
  235391. /*** End of inlined file: juce_mac_CameraDevice.mm ***/
  235392. #endif
  235393. #endif
  235394. END_JUCE_NAMESPACE
  235395. #endif
  235396. /*** End of inlined file: juce_mac_NativeCode.mm ***/
  235397. #endif
  235398. #endif